text
stringlengths
180
608k
[Question] [ A [repdigit](https://en.wikipedia.org/wiki/Repdigit) is a natural number that can be written solely by repeating the same digit. For example, `777` is a repdigit, since it's solely composed of the digit `7` repeated three times. This isn't limited to simply decimal (base 10) numbers, however: * Every Mersenne number (of the form *Mn = 2n-1*) is a repdigit when written in binary (base 2). * Every number is trivially a repdigit when written in unary (base 1). * Every number `n` can also trivially be written as the repdigit `11` in base `n-1` (for example, `17` when written in hexadecimal (base 16) is `11`, and `3` when written in binary (base 2) is also `11`). The challenge here is to find *other* bases where the input number may be a repdigit. ### Input A positive integer `x > 3`, in any convenient format. ### Output A positive integer `b` with `(x-1) > b > 1` where the representation of `x` in base `b` is a repdigit. * If no such `b` exists, output `0` or some [falsey](http://meta.codegolf.stackexchange.com/a/2194/42963) value. * If multiple such `b` exist, you can output any or all of them. ### Rules * The `(x-1) > b > 1` restriction is to prevent the trivial conversions to unary or the "subtract one" base. The *output* number can be written in unary or any convenient base, but the *base itself* must not be one of the trivial conversions. * Input/output can be via any [suitable method](http://meta.codegolf.stackexchange.com/q/2447/42963). * [Standard loophole](http://meta.codegolf.stackexchange.com/q/1061/42963) restrictions apply. ### Examples ``` In --> Out 11 --> 0 (or other falsey value) 23 --> 0 (or other falsey value) 55 --> 10 (since 55 is 55 in base 10) 90 --> 14 (since 90 is 66 in base 14 ... 17, 29, 44 also allowed) 91 --> 9 (since 91 is 111 in base 9 ... 12 also allowed) ``` [Answer] # Jelly, ~~11~~ 9 bytes ``` bRI¬¨P‚ǨT·∏ä·πñ ``` Returns a list of bases, which is empty (falsy) if there is none. [Try it online!](http://jelly.tryitonline.net/#code=YlJJwqxQ4oKsVOG4iuG5lg&input=&args=OTA) ### How it works ``` bRI¬¨P‚ǨT·∏ä·πñ Main link. Argument: x (number) R Range; yield [1, ..., x]. b Base; convert x to base n, for each n in the range. I Compute the increment (differences of successive values) of each array of base-n digits. This yields only 0's for a repdigit. ¬¨ Apply logical NOT to each increment. P‚Ǩ Compute the product of all lists of increments. T Get the indices of all truthy products. ·∏ä Discard the first index (1). ·πñ Discard the last index (x - 1). ``` [Answer] # Pyth, ~~11~~ 10 ``` fqjQT)r2tQ ``` Apparently Pyth's unary `q` checks for a list that has all unique values as of about 10 days ago. Apparently investigating Pyth bugs improves golf scores. Filters the list `[2..input-1)` on if the unique set of digits of the input in that base is length 1. [Test Suite](http://pyth.herokuapp.com/?code=fqjQT%29r2tQ&test_suite=1&test_suite_input=11%0A23%0A55%0A90%0A91&debug=0) ### Explanation: ``` r2tQ ## generate the python range from 2 to the input (Q) - 1 ## python range meaning inclusive lower and exclusive upper bounds f ## filter that list with lambda T: jQT ## convert the input to base T q ) ## true if the resulting list digits has all equal elements ``` [Answer] ## Ruby, ~~87~~ ~~69~~ 63 bytes ``` ->x{(2..x-2).find{|b|y=x;a=y%b;a=0if a!=y%b while(y/=b)>0;a>0}} ``` I had to implement base conversion by hand, since Ruby's builtins only go up to base 36... Returns `nil` for not found. ``` ->x{ # anonymous lambda that takes one argument (2..x-2) # range of the possible bases to search over .find{ # return the first element that satisfies the block, or nil if none |b| # b represents the base currently being tested y=x; # a temporary value to avoid mutating the original value of x a=y%b; # the first (well, last) digit in base b, which will be compared to y/=b # divide the number by the base if a!=y%b # if this digit does not match (is different)... a=0 # set a to a value representing "failure" while( )>0; # keep doing this until we get zero (no digits left) a>0 # return whether a has maintained its original value (no digit change) }} # find then returns the first element for which this is true (or nil) ``` [Answer] ## Python, 71 72 78 bytes ``` lambda x:{b for b in range(2,x-1)for d in range(x)if x*~-b==x%b*~-b**d} ``` No recursion, just tries all bases and outputs a set of those that work. It's tempting to encode `b` and `d` in a single number, but it takes too many parenthesized expressions to extract them. 77 bytes: ``` lambda x:{k/x for k in range(2*x,x*x-x))if x*~-(k/x)==x%(k/x)*~-(k/x)**(k%x)} ``` --- **72 bytes:** ``` f=lambda x,b=2:b*any(x*~-b==x%b*~-b**d for d in range(x))or f(x,b+1)%~-x ``` Outputs the first `b` that works, or `0` if none do. A rep-unit `x` of `d` digits of `c` in base `b` has value `x==c*(b**d-1)/(b-1)`. Equivalently, `x*(b-1)==c*(b**d-1)`. The value `c` must be `x%b`, the last digit. I don't see a way though to determine `d` arithmetically, so the code tries all possibilities to see if any of them work. Saved 5 bytes by copying [Dennis's trick](https://codegolf.stackexchange.com/a/75664/20260) of giving a falsey output when `b` reaches `x-1` by taking the output modulo `x-1`. Another byte saved from Dennis reminding me that exponentiation inexplicably has higher precedence that `~`. An equal-length solution with `in` instead of `any`. ``` f=lambda x,b=2:b*(x*~-b in[x%b*~-b**d for d in range(x)])or f(x,b+1)%~-x ``` [Answer] # Ruby, 50 bytes ``` ->n{(2..n-2).find{|b,i=n|i%b==(i/=b)%b ?redo:i<1}} ``` I would really like to remove that annoying space but as a newcomer to ruby, I'm still quite unfamiliar with its syntactic quirks. [Answer] # [Emojicode](http://www.emojicode.org/), 214 bytes (77 characters): ``` üêáüêπüçáüêáüêñüèÅ‚û°üöÇüçáüç¶büç∫üî≤üóûüî∑üî°üòØüî§üî§üöÇüçÆi 2üçÆn 0üîÅ‚óÄi‚ûñb 1üçáüç¶vüî∑üî°üöÇb iüçä‚ñ∂üêîüî´vüî™v 0 1üìèvüçáüçÆn iüçâüç´iüçâüòÄüî∑üî°üöÇn 9üçé0üçâüçâ ``` Prints results in base 9. I've been meaning to do a code golf with emojicode for a couple weeks now, but the language has only recently become stable enough to actually work with üòâ. As a bonus, this question makes use of the one piece of functionality emojicode is actually really good at: representing integers in other bases. Ungolfed (üë¥ is a line comment in emojicode) ``` üêáüêπüçá üë¥ define main class "üêπ" üêáüêñüèÅ‚û°üöÇüçá üë¥ define main method üë¥ read an integer from stdin, store it in frozen variable "b" üç¶ b üç∫ üî≤ üóû üî∑üî°üòØüî§üî§ üöÇ üçÆ i 2 üë¥ i = 2 üçÆ n 0 üë¥ n = 0 üîÅ‚óÄi‚ûñb 1üçá üë¥ while i < b - 1 üç¶ v üî∑üî°üöÇb i üë¥ v = the string representation of b in base i üë¥ Split v on every instance of the first character of v. üë¥ If the length of that list is greater than the actual length of v, üë¥ n = i üçä‚ñ∂üêîüî´vüî™v 0 1üìèvüçá üçÆ n i üçâ üç´ i üë¥ increment i üçâ üòÄ üî∑üî°üöÇ n 9 üë¥ represent n in base 9 instead of 10, to save a byte üòú üçé 0 üë¥ return error code 0 üçâ üçâ ``` [Answer] # Python 2, 79 bytes ``` f=lambda x,b=2:~-b*x in[i%b*~-b**(i/b)for i in range(b*x)]and b or f(x,-~b)%~-x ``` Try it on [Ideone](http://ideone.com/1GgtGC). ### Idea Any repdigit **x** of base **b > 1** and digit **d < b** satisfies the following. ![condition](https://i.stack.imgur.com/d834e.png) Since **d < b**, the map **(b, d) ↦ cb + d** is injective. Also, since **b, x > 1**, we have **c < x**, so **cb + d < cb + b = (c + 1)b ≤ xb**. This means that, to find suitable values for **c** and **d** for a given base **b**, we can iterate through all **i** in **[0, …, bx)** and check whether **(b - 1)x == (i % b)(bi / b - 1)**. ### Code The named lambda **f** test whether **(b - 1)x** is in the set **{(i % b)(bi / b - 1) | 0 ≤ i < bx}**, beginning with the value **b = 2**. * If the test was successful, we return **b**. * Else, we call **f** again, with the same **x** and **b** incremented by **1**. Since **b** may eventually reach **x - 1**, we take the final result modulo **x - 1** to return **0** in this case. Note that this will not happen if **b = 2** satisfies the condition, since it is returned without recursing. However, the question guarantees that **b = 2 < x - 1** in this case. [Answer] # Perl 6, ~~45~~ ~~43~~ 42 bytes ``` {grep 2..$^x-2: {[==] $x.polymod($_ xx*)}} ``` **Explained (sort of)** For reference, a variable `$^x` in `{ ... }` is the same as doing `-> $x { ... }` ``` {grep 2..$^x-2: {[==] $x.polymod($_ xx*)}} { # Anonymous function taking $x grep # Return the all values in 2..$^x-2: { # Range from 2 to $x - 2 satisfying: [==] # Reduce with ==: $x.polymod( # (See below for polymod) $_ xx* # An infinite list containing # the current value )}} ``` Polymod (TL;DR): `$n.polymod($b xx *)` gives you a reversed list of digits/'digits' for `$n` in base `$b` Polymod (For real): The polymod method is almost like a more powerful version of python's `divmod` function. `$n.polymod(*@args)` divides $n by each value in \*@args, adding the remainder (`$n mod $x`) to the list it returns, and using the quotient for the next division. I feel I explained it poorly so here's some examples (written in perl 6, but clean enough to be understood by most I hope): ``` 12.polymod(7) # returns (5, 1) # Roughly equivalent to: (12 mod 7, 12 div 7) 86400.polymod(60,60,24) # returns (0, 0, 0, 1) # Roughly equivalent to (this will give you an array rather than a list): my $n = 86400; my @remainders; # Here lies the end result for (60, 60, 24) -> $divisor { @remainders.push( $n mod $divisor ); $n div= $divisor; } @remainders.push($n) # This is essentially the base conversion algorithm everyone # knows and loves rolled into a method. # Given an infinite list of divisors, polymod keeps going until # the remainder given is 0. 0xDEADBEEF.polymod(16 xx *) # returns (15 14 14 11 13 10 14 13) # Roughly equivalent to (but gives an array rather than a list): my $n = 0xDEADBEEF; my @remainders; # Here lies the end result while $n > 0 { @remainders.push( $n mod 16 ); $n div= 16; } ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 28 bytes ``` {b/‚箂çµ{1=‚â¢‚à™‚çµ‚ä•‚ç£¬Ø1‚䢂ç∫}¬®b‚Üê1+‚ç≥‚çµ-3} ``` `{`‚Ķ`‚çµ`‚Ķ`}` anonymous function to be applied to `x` (represented by `‚çµ`) `b‚Üê1+‚ç≥‚çµ-3` integers from 2 ‚Äì ‚çµ-2 stored as `b` `‚çµ{`‚Ķ`}¬®` for each element in b (`‚çµ`), apply the function `{`‚Ķ`}` with x as left argument `‚ç∫` `‚終䕂磬Ø1‚䢂ç∫` convert x to that base `1=‚⢂à™` is 1 equal to the tally of unique digit? `b/‚ç®` elements of b where true (that there is only one unique digit). [Example cases](http://tryapl.org/?a=%7Bb/%u2368%u2375%7B1%3D%u2262%u222A%u2375%u22A5%u2363%AF1%u22A2%u237A%7D%A8b%u21901+%u2373%u2375-3%7D%A811%2023%2055%2090%2091&run) If no base exists, the output is empty (which is falsey), as can be demonstrated by this program: ``` WhatIsEmpty ‚Üí''/TRUE ‚çù goto (‚Üí) TRUE: if (/) emptystring ('') 'False' ‚ÜíEND TRUE: 'True' END: ``` This prints 'False' [Answer] # Pyth, ~~26~~ 19 bytes ``` hMfql{eT1m,djQdr2tQ ``` [Try it here!](http://pyth.herokuapp.com/?code=hMfql%7BeT1m%2CdjQdr2tQ&input=91&test_suite=1&test_suite_input=11%0A23%0A55%0A90%0A91&debug=0) ~~Will add an explanation after I golfed this.~~ Look at [this answer](https://codegolf.stackexchange.com/a/75629/49110) for a shorter implementation and explanation. [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~15~~ 14 bytes ``` 3-:Q"G@:YAd~?@ ``` This works with [current version (14.0.0)](https://github.com/lmendo/MATL/releases/tag/14.0.0) of the language/compiler. If no base exists, the output is empty (which is falsey). [**Try it online!**](http://matl.tryitonline.net/#code=My06USJHQDpZQWR-P0A&input=OTE) ``` 3-:Q % take input x implicitly. Generate range of possible bases: [2,3,...,x-2] " % for each base b G % push input again @: % generate vector of (1-based) digits in base b: [1,2,...,b] YA % convert to that base d~ % differences between consecutive digits; negate ? % if all values are true (that is, if all digits were equal) @ % push that base % end if implicitly % end for each implicitly % display implicitly ``` [Answer] # Mathematica, 55 bytes ``` Cases[4~Range~#-2,a_/;Equal@@#~IntegerDigits~a]/.{}->0& ``` Anonymous function, not too complicated. Just filters out bases based on repdigit-ness. [Answer] # Python 2, 75 bytes ``` n=input() b=1 while b<n-2: i=n;b+=1 while i%b==i/b%b:i/=b if i<b:print b ``` A port of my ruby answer. Prints all valid bases if any exists. [Answer] # Julia, 45 bytes ``` n->filter(b->endof(‚à™(digits(n,b)))<2,2:n-2) ``` This is an anonymous function that accepts an integer and returns an integer array. To call it, assign it to a variable. It will return all applicable bases or an empty array. There are no issues with large bases. First we generate the inclusive range [2, *n* - 2], where *n* is the input. We then `filter` the list to only integers *b* for which *n* in base *b* has fewer than 2 unique digits. To do this, for each integer *b* in the range, we get the digits of *n* in base *b* as an array using `digits`, get unique items using `‚à™`, and get the index of the last element (i.e. the length) using `endof`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes ``` >>.‚Ñï‚ÇÇ‚âú&·∏É‚Üô.=‚àß ``` [Try it online!](https://tio.run/##AVwAo/9icmFjaHlsb2cy/3t3IiAtLT4gInc/e@KGsOKCg3ziiKciZmFsc2UuIn3huol94bWQ/z4@LuKEleKCguKJnCbhuIPihpkuPeKIp///WzExLDIzLDU1LDkwLDkxXQ "Brachylog ‚Äì Try It Online") [(as a generator!)](https://tio.run/##AVEArv9icmFjaHlsb2cy/3t3IiAtLT4gInc/4oaw4oKC4bag4bqJfeG1kP8@Pi7ihJXigoLiiZwm4biD4oaZLj3iiKf//1sxMSwyMyw1NSw5MCw5MV0) Takes input through the input variable and outputs a base through the output variable in the case that this is possible, failing otherwise. At the same time, it also works as a [generator](https://codegolf.meta.stackexchange.com/a/10753/85334) which outputs a list of all bases, where that list can be empty. Ideally this could look something like `·∏É‚Üô.=&>>`, possibly sacrificing generator functionality in that form or a similar one (since it would eventually hit unary), but as of now 12 bytes is the shortest I know how to get it. ``` ‚âú Assign an integer value to . the output variable ‚Ñï‚ÇÇ which is greater than or equal to 2 > and less than a number > which is less than the input. & The input ·∏É‚Üô. in base-(the output) = is a repdigit. ‚àß (which is not necessarily the output) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~46~~ 43 bytes Uses the [Integer#digits](https://ruby-doc.org/core-2.4.0/Integer.html#method-i-digits) function introduced in Ruby 2.4 to avoid needing to manually divide. -3 bytes thanks to @Jordan. ``` ->n{(2..n-2).find{|i|!n.digits(i).uniq[1]}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNITy9P10hTLy0zL6W6JrNGMU8vJTM9s6RYI1NTrzQvszDaMLa29n@BQlq0SrxeSX58Zmx5RmZOqkJ6aknxf0NDLiNjLlNTLksDLktDAA "Ruby ‚Äì Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` √çL¬¶ í–≤√ôg ``` Outputs all possible values, or an empty list as falsey value (although technically valid outputs are falsey as well, since only `1` is truthy in 05AB1E, and everything else is falsey). [Try it online](https://tio.run/##yy9OTMpM/f//cK/PoWWnJl3YdHhm@v//lgYA) or [verify all test cases](https://tio.run/##ATgAx/9vc2FiaWX/dnnDkFU/IiDihpIgIj//w41MwqbKklhz0LLDmWf/fSz/WzExLDIzLDU1LDkwLDkxXQ). **Explanation:** ``` √ç # Decrease the (implicit) input-integer by 2 L # Create a list in the range [1, input-2] ¬¶ # Remove the first value to make the range [2, input-2]  í # Filter this list by: –≤ # Convert the (implicit) input to the base of the number we're filtering √ô # Uniquify it, leaving only distinct digits g # Get the length of this, which is truthy (1) if all digits were the same # (and then output the filtered list implicitly as result) ``` [Answer] # [Perl 5](https://www.perl.org/) `-Minteger -na`, 63 bytes ``` map{$r=$,=($c="@F")%$_;$r*=$c%$_==$,while$c/=$_;$r&&say}2..$_-2 ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saBapchWRcdWQyXZVsnBTUlTVSXeWqVIy1YlGciyBUqVZ2TmpKok69uCJdTUihMra4309FTidY3@/7c0AMJ/@QUlmfl5xf91fU31DAwNgHRmXklqemrRf928RAA "Perl 5 ‚Äì Try It Online") Outputs all possible answers or nothing if no solution exists. ]
[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/26855/edit). Closed 7 years ago. [Improve this question](/posts/26855/edit) This challenge is simple. Write code that shows what looks exactly like a complete reboot of the computer. It must not show anything on-screen that shows it is not a full reboot and should end at the log-in screen you would get after rebooting. **Rules** 1. You can choose any OS you like to imitate. For example you can reboot into Linux from Windows, Mac from Linux, or any other combination you choose. 2. The code should display the full reboot full-screen with no signs that it isn't real. 3. This is a popularity contest so the cooler it looks, the better it is. 4. The code must be completely harmless, perform no actual rebooting, and be easy to quit at any point. 5. If you need to use external images to make the reboot look more realistic, then your code should automatically grab them from the web. 6. Your code should be self-contained, only relying on standard freely available libraries or tools, and must be easily executable by reading the instructions you provide. As it is a popularity contest, I will award the win to the answer with the highest number of votes on June 1, 2014. --- Following a request to narrow the question, here is an additional rule, the system should imitate any version of Windows or the Mint, Ubuntu, Debian, Fedora, Archlinux or Mageia distributions of Linux or OS X. For extra coolness, you should shut down in one and open in the other. Interested people may want to look at [Pitch dark (Earth Hour remembrance)](https://codegolf.stackexchange.com/questions/26697/pitch-dark-earth-hour-remembrance) where a number of ways are suggested for using the full screen even when starting in an xterm. [Answer] # zsh + coreutils + unclutter + amixer + xterm (Arch Linux) I took the answer by @TheDoctor and ran with it. This version has many improvements, and is 99% convincing to an experienced user (me) on my Arch Linux system. I use Zsh since it has good array and floating-point number support. Dependencies: **feh, unclutter, amixer, zsh, xterm** **Improvements:** 1) Use the number printed in the first column by dmesg, which is the time since boot, (e.g. [ 0.000000] ) to determine the time to sleep. Without this it looks very unrealistic on my machine. These times are parsed before the loop (in an early call to sleep) since parsing inside the loop is too slow. 2) Don't print lines where time since boot is larger than 16 seconds. This specific number is machine-dependent, but the point is to avoid printing later dmesg-stuff that comes from inserting/removing usb sticks, etc. and is unrelated to booting. 3) Do all this in a fullscreen terminal window with black background and white text. Kudos to Mechanical Snail for this trick used in: [Make a PNG image with "Hello World!" with programming APIs, in the shortest code possible](https://codegolf.stackexchange.com/questions/19801/make-a-png-image-with-hello-world-with-programming-apis-in-the-shortest-code/19893#19893) 4) Mute the audio on shutdown, restore volume when script finishes. 5) Hide the mouse cursor, restore when script finishes. 6) Show BIOS and Syslinux splash screens. **Run with:** xterm -fu -fg white -bg black -e '/usr/bin/zsh fake-reboot.sh' **Code:** ``` #!/usr/bin/zsh # Remove (undisplay) the mouse pointer unclutter -idle 0 -jitter 255 & # Since there is no easily-accessible (i.e. without being root) shutdown log, we # fake these messages. echo "The system is going down for maintenance NOW." sleep 2.0 echo "[21656.404742] systemd[1]: Shutting down." echo "[21656.404742] systemd[1]: Stopping Session 1 of user `id -u -n`." echo "[21656.404742] systemd[1]: Stopped Session 1 of user `id -u -n`." echo "[21656.404742] systemd[1]: Stopping Sound Card." # For added effect, store volume and then mute sound volume=`amixer -- sget Master | awk -F'[][]' 'END{print $2}'` amixer -- sset Master 0% &> /dev/null echo "[21656.404742] systemd[1]: Stopped target Sound Card." sleep 0.5 echo "[21656.919792] systemd[1]: Stopping system-systemd\x2dfsck.slice." echo "[21656.919792] systemd[1]: Removed slice system-systemd\x2dfsck.slice." echo "[21656.919792] systemd[1]: Stopping system-netctl\x2difplugd.slice." echo "[21656.919793] systemd[1]: Removed slice system-netctl\x2difplugd.slice." echo "[21656.919793] systemd[1]: Stopping User Manager for UID `id -u`..." sleep 0.7 echo "[21657.624741] systemd[1]: Stopping Graphical Interface." echo "[21657.624742] systemd[1]: Stopped target Graphical Interface." echo "[21657.624745] systemd[1]: Stopping Multi-User System." sleep 0.9 echo "[21658.606561] systemd[1]: Stopped target Multi-User System." echo "[21658.606562] systemd[1]: Stopping Paths." echo "[21658.606562] systemd[1]: Stopped D-Bus System Message Bus." echo "[21658.606562] systemd[1]: Stopped target Paths." echo "[21658.606568] systemd[1]: Stopping Timers." echo "[21658.606568] systemd[1]: Stopped target Timers." echo "[21658.606568] systemd[1]: Stopping Sockets." echo "[21658.606568] systemd[1]: Stopped target Sockets." echo "[21658.606568] systemd[1]: Starting Shutdown." echo "[21658.606571] systemd[1]: Reached target Shutdown." echo "[21658.606571] systemd[1]: Starting Exit the Session..." echo "[21658.606571] systemd[1]: Received SIGRTMIN+26 from PID 10988 (kill)." echo "[21658.606571] systemd[1]: Deactivated swap." sleep 0.4 echo "[21659.001741] systemd[1]: Starting Unmount All Filesystems." echo "[21659.001742] systemd[1]: Unmounted /home." echo "[21659.001742] systemd[1]: Reached target Unmount All Filesystems." echo "[21659.001742] systemd[1]: Stopping Remount Root and Kernel File Systems..." echo "[21659.001742] systemd[1]: Stopped Remount Root and Kernel File Systems." echo "[21659.001743] systemd[1]: Reached target Shutdown." echo "[21659.001743] systemd[1]: Starting Final Step." echo "[21659.001743] systemd[1]: Reached target Final Step." echo "[21659.001754] systemd[1]: Shutting down." sleep 0.3 echo "[21659.304341] systemd-journal[250]: Journal stopped" sleep 0.2 echo "System halted." sleep 2 clear sleep 1 # Get the BIOS splash screen and display it wget http://pvv.ntnu.no/~asmunder/bios.jpg &> /dev/null feh -Z -x -F -N --force-aliasing bios.jpg & pid=$! # Store PID of Feh, so we can kill it later # While showing the BIOS splash, use the time to parse dmesg output into arrays tim=`dmesg | awk '{print $2}' | sed 's/]//' | grep "[0-9][0-9][0-9][0-9][0-9]"` tim=($=tim) dmsg=("${(@f)$(dmesg)}") sleep 2.5 kill $pid sleep 0.5 # Get the Syslinux splash and display it wget http://pvv.ntnu.no/~asmunder/syslinux.png &> /dev/null feh -Z -x -F -N --force-aliasing syslinux.png & pid=$! sleep 1.3 kill $pid # Loop through the arrays we created. Calculate the time we have to wait before # displaying this line. If the wait time is less than 0.1 sec, we skip waiting. T1=0.0 T2=0.0 n=0 for d in $dmsg; do T1=$T2 T2=${tim[$n]} ((dT = $T2-$T1)) if (( $dT > 0.1));then sleep $dT fi echo $d if (( $T2 > 16.0 )); then break fi ((n=$n+1)) done sleep 1 clear # It's normally agetty that parses /etc/issue and handles escape codes in a # special way. Thus we skip the first line of /etc/issue and do that manually. echo "Arch Linux "`uname -r`" (tty1)" tail -n +2 /etc/issue echo `hostname`" login:" sleep 10 # Reset the mouse pointer so it is visible again unclutter -idle 5 -jitter 0 & # Reset the audio volume amixer -- sset Master $volume &> /dev/null ``` [Answer] ## Commodore 64 ``` 1?CHR$(147) 2?" **** COMMODORE 64 BASIC V2 ****" 3? 4?" 64K RAM SYSTEM 38911 BASIC BYTES FREE" ``` The BASIC intepreter will display the `READY.` prompt automatically. [Answer] # TI-Basic ``` AxesOff GridOff LabelOff CoordOff ClrDraw DispGraph ClrHome ``` [Answer] # Bash + Coreutils (Linux) ``` echo "The system is going down for maintenance NOW." clear sleep 5 dmesg|while read i; do echo "$i"; sleep 0.1; done cat /etc/issue login ``` [Answer] # Windows 8 Shoddy attempt, I can't figure out how to auto full screen. I tried. ``` <!DOCTYPE html> <html> <body> <iframe width="1600" height="900" src="http://www.youtube.com/embed/VgQ87b7muWs?start=510&end=524&autoplay=1" frameborder="0" allowfullscreen></iframe> </body> </html> ``` [Answer] # Python / Pygame OSX ``` import pygame, time, os, urllib # Import Modules pygame.init() # Initalise Pygame pygame.mouse.set_visible(0) # Hide the Cursor stdscr = pygame.display.set_mode((1280,800),pygame.FULLSCREEN) # Set up the display stdscr.fill((255,255,255)) # Fill the screen white urllib.urlretrieve("http://harrybeadle.github.io/FakeRestart/apple.bmp", "apple.bmp") # Get Apple Logo urllib.urlretrieve("http://harrybeadle.github.io/FakeRestart/startup.wav", "startup.wav") # Get Startup Sound time.sleep(1) # Wait for 1 second, screen still black applelogo = pygame.image.load('apple.bmp').convert() # Load the Logo pygame.mixer.music.load('startup.wav') # Load the Bung stdscr.blit(applelogo,(580, 340)) # Blit the logo pygame.mixer.music.play(1) # Play the sound pygame.display.flip() # Flip the buffers time.sleep(5) # Wait 5 seconds pygame.quit() # Quit the pygame window os.remove('apple.bmp') # Delete logo os.remove('startup.wav') # Delete bung os.system('/System/Library/CoreServices/"Menu Extras"/User.menu/Contents/Resources/CGSession -suspend') # Lock the Mac ``` Now Updated! Features: * Blank Screen * White Screen w/ Apple Logo **and Bung Sound** * Assets downloaded from GitHub using `urlib` * Locks the user's Mac preserving any work using a terminal command and `os.system()` [Answer] This one does linux with parameters "quiet" and "init=/bin/sh" ``` #!/bin/sh echo shutting down sleep 1 clear echo Press F12 to enter setup. #everyone forgets the BIOS sleep 1 clear ``` ]
[Question] [ You will be given as input an infinite stream of positive integers. Your task is to write a program which outputs an infinite sequence of lists with two requirements: * All lists in the output are finite sub-lists of the input stream. * Every sub-list must be output *eventually* by your program. Sub-lists are not necessarily contiguous, so `[1,1]` *is* a sub-list of `[0,1,0,1,0,...`, and should be included in your output if your input was `[0,1,0,1,0,...`. The empty list `[]` is a sub-list of every possible input, so it should always be output at some point. Aside from this, you can do what you want. You can output them in whatever order suits you, you can output any sub-list any (positive) number of times. It's up to you to figure out what's best. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being the goal. ## IO Outputting an infinite sequence is done as per the defaults of [the sequence tag wiki](https://codegolf.stackexchange.com/tags/sequence/info). Input of an infinite sequence is basically the dual of those rules. You may: * Take the input as a [black-box function](https://codegolf.meta.stackexchange.com/a/13706) which takes \$n\$ and outputs the \$n\$th term * Take the input as a [black-box function](https://codegolf.meta.stackexchange.com/a/13706) which takes \$n\$ and outputs all terms up to the \$n\$th term * Take the input as a lazy list, generator or stream. * Take the input by repeatedly querying STDIN each time receiving the next term of the sequence. [Answer] # [Haskell](https://www.haskell.org/), ~~31~~ 27 bytes -4 bytes thanks to Wheat Wizard! Takes an infinite list as input and returns each finite sublist an infinite number of times. ``` f(a:l)=[]:do x<-f l;[a:x,x] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00j0SpH0zY61iolX6HCRjdNIcc6OtGqQqci9n9uYmaegq1CbmKBb7xCQVFmXomCikKaQrShnl7sfwA "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte ``` æ ``` [Try it online!](https://tio.run/##yy9OTMpM/f@oY97/w8v@/wcA "05AB1E – Try It Online") # [05AB1E](https://github.com/Adriandmen/05AB1E) no builtin, 5 bytes ``` [DNÏ, ``` [Try it online!](https://tio.run/##yy9OTMpM/f@oY97/aBe/w/06//8DAA "05AB1E – Try It Online") Takes the input as an 05AB1E infinite lazy list ``` [ infinite loop D create a copy of the infinite list N iteration index (starting from 0) Ï elements of the list for which the corresponding element of the index is 1 , print ``` [Answer] # [Python](https://www.python.org), 43 bytes ``` lambda s,n:[s(b)for b in range(n)if n>>b&1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3tXMSc5NSEhWKdfKsoos1kjTT8osUkhQy8xSKEvPSUzXyNDPTFPLs7JLUDGNhWkBK8hBKDA0MDDStCooy80o00jSMFPTi4wvyy-PjdfI0NSFaFiyA0AA) Outputs the `n`th sublist. # [Python](https://www.python.org), 55 bytes ``` n=0 while[print([s(b)for b in range(n)if n>>b&1])]:n+=1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwZpiWyMFvfj4gvzy-PilpSVpuhY3zfNsDbjKMzJzUqMLijLzSjSiizWSNNPyixSSFDLzFIoS89JTNfI0M9MU8uzsktQMYzVjrfK0bQ0h2hdAKSgNAA) Takes input using a black-box function [predefined under the name](https://codegolf.meta.stackexchange.com/a/13707) `s`, which takes a number and outputs the corresponding 0-indexed value of the sequence. Shown in the ATO link using the powers of 2 `[1, 2, 4, 8, ...`. Outputs infinitely to STDOUT. Uses the binary representation of each non-negative integer `n` to produce a sub-list; `1`s in the binary representation correspond to indices where the list's value is included in the output. A bug fix for -12 bytes (!): By using `n` itself rather than the bit length of `n` to determine how many bits to select, we also get, pretty much for free, the ability to sometimes output sublists which don't include the first item. Because `n` is always greater than or equal to its bit length (besides for `0`), we will effectively select some `0` bits which form part of its "padding", but which allow us to skip some of the first few elements. When `n` is `0`, this is the only number with no `1`s in its binary. As a result, by initialising `n` to `0`, we output an empty list at the start, satisfying that requirement at no byte cost. --- # [Python](https://www.python.org), ~~63~~ 62 bytes ``` def f(s,*e): yield e for x in f(s,next(s)):yield from{x,e+x} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Nc5BDoIwEAXQfU8xyxbRBFeKwbugTGESmJK2xBLjSdyw0Tt5G6ngJH_1k__m-e5H3xieptfg9fbwOVeoQUuXJqhyASNhWwEK0MZCAOJfxxi8dErlS62t6e4hxU14rCsX6npjPbjRiTk7h97idbCODLfUkZfHeEpErZZcZBG7NdQiZOsqnzgp9iLC5QLXciZ7S-xlqRbp__cX) This is a version based on [@ovs' clever Haskell answer](https://codegolf.stackexchange.com/a/241144), but with some changes to make it work in Python where we don't have infinite lists. It might be improvable. -1 thanks to Command Master Thanks to loopy walt, this version now outputs every sub-list exactly once, for the same byte count. [Answer] # Scala, 89 bytes ``` _.scanLeft(Seq[Int]())(_:+_)flatMap(l=>l.indices.toSet.subsets.map(_.toSeq.sorted map l)) ``` [Try it online!](https://scastie.scala-lang.org/N2jvydukSDqBPxhNLz2Byg) Welp, this turned out much longer than I expected. Time to reconsider this approach. Input is a `LazyList[Int]`. It outputs all the sublists up to the current integer for every integer. ``` _ //The input (infinite list) .scanLeft //Scan left over the sequence, (Seq[Int]())(_:+_) //building an infinite list of subsequences flatMap(l=> //Map each of those subsequences l to its sublists l.indices.toSet.subsets //Get all subsets of the indices .map( _.toSeq.sorted //Sort the indices to ensure sublists are in order map l) //Map the index to the corresponding element in l ) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 30 bytes ``` a=>n=>a(n).filter(_=>(n/=2)&1) ``` [Try it online!](https://tio.run/##LYxBCsJADAC/0pMkVLdV8FSz4EtKqLsSWZOSFsHXr3vwMHObefGHt8Vl3U9qj1QzVaaoFBkUQ5ayJ4eZIuhAFzycsWbzDoTGSW7Xpr7HbjHdrKRQ7AkZWnx35@9/UGDE8OYVQI@CFAURGlP9AQ "JavaScript (Node.js) – Try It Online") Input array as a function which output first n elements. Output n-th element. [Answer] # [R](https://www.r-project.org/), ~~73~~ 68 bytes Or **[R](https://www.r-project.org/)>=4.1, 61 bytes** by replacing the word `function` with a `\`. *Edit: -5 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).* ``` function(g)while(T<-T+1)for(i in 1:2^T)show(g(T)[!i%/%2^(T:1-1)%%2]) ``` [Try it online!](https://tio.run/?fbclid=IwAR3OZreuoZF254JJXfYmeB1949ewhQQ32LJmGGPom2Ia6XkZdRp2jj3JAgA##PczRCoIwFADQ5/YVN2JwL01i6yESP2NvopFj06FsMBWL6NsXvXg@4KTsoCoguzWYxceAPW2DnyzqqtBnSS4m9OADyFK1muYhbtijpvro@YWrFnUpC0mcq4ZyNz3N@Oji61/uY6CPwauQQombuMPhBO@4Jpj8vMBgk2WMalmGhn2Zw72g/AM "R – Try It Online") Explanation: 1. Take a black-box function `g` as an argument. 2. Increment `T` in each iteration - how many numbers to read from `g`. 3. In the loop, calculate all the sub-sequences of the current vector (and some more): * take all numbers from `1` to `2^T`, * convert to binary, * use as logical indices, which numbers from `g(T)` to print. [Answer] # [Ruby], ~~64 56~~ 48 bytes ``` ->g{1.step{|n|n.times{p *g[n].combination(_1)}}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3DXTt0qsN9YpLUguqa_Jq8vRKMnNTi6sLFLTSo_Ni9ZLzc5My8xJLMvPzNOINNWtrayH69hYUZeaVKKRF69rlQbXrpWUWFZdo5GnWxkLULFgAoQE) * saved 8 Bucks thanks to @ovs takes a black box function returning first *n* elements. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` WS«E⌕A⮌⍘Lυ²1§υκD⎚D⊞υι ``` [Try it online!](https://tio.run/##VYrLCsIwEEXXna8IXU1AwdYnuKqKUFAo@gWhHZpgjCVNqiB@e0zBjZvDuZdTS2Hrh9AhPKXSxLA0nXdXZ5VpkXP2hqSK7vAsOjwq0xRa44UGsj3hTvT0S09kWifR8wnLeUSapZGFK01DL/QTduOcbyE5@HuHo@w1CYt/V@V7OaYqjk8IM8gghzksYAkrWMMGwnTQXw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` WS« ``` Repeatedly input the next integer as a string. (This will actually stop on a blank line, which is what I use to allow the linked example to halt, but for positive integers it will keep prompting for input.) ``` E⌕A⮌⍘Lυ²1§υκ ``` Convert the length of the predefined empty list to binary and find the positions of the `1`s counting the least significant bit as `0`. Output the elements of the predefined empty list with matching positions. ``` D⎚D ``` Output the canvas double-spaced. (Charcoal's default output format lists one element per line, so it's not easy to distinguish consecutive lists otherwise, although if you were running it interactively then the `Enter input:` prompt would do the trick.) ``` ⊞υι ``` Append the next term of the input stream to the predefined empty list. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 35 bytes ``` g->i->[g(j)|j<-[0..i],bittest(i,j)] ``` [Try it online!](https://tio.run/##DckxDoAgDAXQ3VM4tgklGFfhIoRBE2k@gxJk9O7oW1/dG0TryLMfKgESolLht2wSnbVI5kDv59MJpnAaSmCPKd@N4J1ZF1Mbrk6ZlP9iHh8 "Pari/GP – Try It Online") Take the input as a black-box function which takes \$n\$ (0-indexed) and outputs the \$n\$th term. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte (non-competing) ``` ṗ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLDnuKIniIsIuG5lyIsIiIsIiJd) Non-competing as this builtin and many others were [recently given infinite list support](https://github.com/Vyxal/Vyxal/issues/586) because of this challenge. [Answer] # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 2 bytes ``` sS ``` I just finished adding builtins having to do with subsequences to hgl. `sS` gets all the subsequences of the input and works just fine on infinite lists. It outputs subsequences in order of the index of their last element last element. That is first it outputs the empty list, then it outputs all sequences that end in the 0th element, then all sequences that end in the 1st element, then all sequences that end in the 2nd etc. # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 21 bytes ``` jn<<mM(ap[i,p]<p)<+cg ``` Since it's no fun to just post a built-in here's one that solves the task without `sS` or related functions. First we make `jn<<mM(ap[i,p]<p)`. This takes a *finite* list and outputs all subsequences. To do this it uses `mM`, (`mapM` or `traverse` if you are a Haskell user) which is a little complicated, but it's equivalent to `sQ<m` (`sequence.map` if your a Haskell user) so I'll explain it like that. First `m(ap[i,p]<p)` will replace every element with a list of a singleton containing itself and an empty list: ``` >>> m(ap[i,p]<p)[1,2,3] [[[],[1]],[[],[2]],[[],[3]]] ``` Then `sQ` basically does the generalized cartesian product. It takes n lists as input and gives all the ways to take 1 item from each list. Since we have two possibilities in each list, the integer singleton or any empty list, this gives us basically binary numbers of n digits with 0 being the empty list and 1 being the value. ``` >>> mM(ap[i,p]<p)[1,2,3] [[[],[],[]],[[],[],[3]],[[],[2],[]],[[],[2],[3]],[[1],[],[]],[[1],[],[3]],[[1],[2],[]],[[1],[2],[3]]] ``` Now we want to get rid of the singletons so we use `m jn` ``` >>> jn<<mM(ap[i,p]<p)$[1,2,3] [[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]] ``` Now we have all the subsequences of the input! However this stalls out on infinite lists. Our fix here is to use `cg`. `cg` gives all the *contiguous* subsequences of the input, possibly infinite. So we first run `cg` and then run this finite subsequence on every result. Unlike the first solution this ## Reflections Nice to see that we used no 3 byte functions anywhere. Still * `ap[i,p]<p` is a little long for my liking `(<p)<ap` could probably be it's own function. I think it would have use beyond this challenge. [Answer] # [Julia 1.0](http://julialang.org/), ~~45~~ 31 bytes ``` f\n=[f(i) for i=0:n if n&2^i>0] ``` [Try it online!](https://tio.run/##HcpBCoAgEAXQvaf4q9CdtVOwi2RCUAMT8Yso6PYWvfVb702n9qlVMtMgVh1kP6HJR0IFbLqivR@rWDokdIXmD1DCxxCCwec4lddGK1mdWTjXFw "Julia 1.0 – Try It Online") Port of [pxeger's answer](https://codegolf.stackexchange.com/a/241143). Outputs the n-th sublist ## [Julia 1.0](http://julialang.org/), 45 bytes ``` !(x,a=[[]])=for i=x a=[@show a;vcat.(a,i)]end ``` [Try it online!](https://tio.run/##HcpBCoAgEADAr2w3DYnqGkLX3hAeljLaKBdMy9@bdByYI56EXcq5EkmhnmdjpN7YA@kExeO98ws4PAuGRqAiaaxby@5rgv8BOZiC9RjY383C0YXN8yVaKfMH "Julia 1.0 – Try It Online") Input is an iterator. Output has a bit of unnecessary stuff but hopefully it's acceptable [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, 18 bytes ``` lPBlW1P*lAL:_AEqMl ``` Reads values from stdin, outputs sublists to stdout. Each sublist will be printed infinitely many times. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7IKlpSVpuhabcgKccsINA7RyHH2s4h1dC31zIBJQ-QW7DbmMuUy5zLksuQwNuQyNuQxNuQzNuQwtuYwMIUoA) ### Explanation We track every sublist of the inputs-thus-far in `l`. At each iteration, we read a new input, append it to each of the existing sublists, append that list to the list of existing sublists, and output the whole thing. ``` lPBlW1P*lAL:_AEqMl l Variable preset to empty list PBl Push the empty list to l; l is now [[]] W1 While 1 (loop forever): Ml Map this function to each sublist in l: q Read a line of stdin _AE and append it to the sublist lAL: Append those results to l in-place P* Print each sublist in l ``` ]
[Question] [ The [Kempner series](https://en.wikipedia.org/wiki/Kempner_series) is a series that sums the inverse of all positive integers that don't contain a "9" in their base-10 representations (i.e., \$\frac{1}{1} + \frac{1}{2} + \frac{1}{3} + .. + \frac{1}{8} + \frac{1}{10} + ...\$). It can be shown that, unlike the Harmonic series, the Kempner series converges (to a value of about 22.92067661926415034816). **Your task is to find the partial sums of the Kempner series.** These are the ways you can do it: * Take a number \$n\$, and return the sum of the inverse of the first \$n\$ numbers that don't have a "9" in them, which is the \$n\$th partial sum of the series. * Take a number \$n\$, and return the first \$n\$ partial sums of the series. * Don't take any input and output the partial sums infinitely. You can choose if your input is 0-indexed or 1-indexed. ~~Your algorithm result's distance from the correct value may not be over \$10^{-4}\$, for all possible values of \$n\$.~~ While your algorithm should work theoretically for all values for N, you may ignore inaccuracies coming from floating-point errors. Test cases, in case of returning the \$n\$th partial sum, 0-indexed: ``` 0 -> 1.0 1 -> 1.5 9 -> 2.908766... 999 -> 6.8253... ``` Standard loopholes are disallowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes ``` Rb9ḌİS ``` [Try it online!](https://tio.run/##y0rNyan8/z8oyfLhjp4jG4L/P2qYcbj9/39LS0sA "Jelly – Try It Online") *-1 byte thanks to @Razetime* Takes input 1-indexed as an argument (footer on TIO converts to 0-indexed like in test cases) Returns the nth partial sum ### How it Works Let's look at the denominators in base 10: \$[1, 2, 3, 4, 5, 6, 7, 8, 10,11,12,13,...]\$ (base 10) Since these consist of the nine base-9 digits, we can interpret them as base 9 strings: \$[1\_9, 2\_9, 3\_9, 4\_9, 5\_9, 6\_9, 7\_9, 8\_9, 10\_9, 11\_9, 12\_9, 13\_9, ...]\$ \$=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]\$ (base 10) So all of the denominators can be generated as natural numbers, converted to base 9, then interpreted as base 10. ``` Rb9ḌİS - main link, taking n (1-indexed) R - convert to list [1..n] b9 - convert each natural number to base 9 Ḍ - interpret each base-9 string as base 10 (decimal) İ - reciprocal S - sum ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 52 39 36 bytes *-13 bytes thanks to Dingus!* *-3 bytes thanks to Sisyphus* ``` x=0;"#$."[?9]||p(x+=1r/$.)while$.+=1 ``` [Try it online!](https://tio.run/##KypNqvz/v8LWwFpJWUVPKdreMrampkCjQtvWsEhfRU@zPCMzJ1VFD8j9/x8A "Ruby – Try It Online") Prints all values. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 5 bytes -4(!) bytes thanks to [Command Master](https://codegolf.stackexchange.com/users/92727/command-master)! Outputs one value 1-indexed ``` L9BzO ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fx9Kpyv//f0MDAwMA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##yy9OTMpM/V/jYndu638fS6cq//@1h3cc2v3fgMuQy5LL0tISAA "05AB1E – Try It Online") ``` L # push the range [1..n] 9B # convert each number to base 9 # this yields the first n natural numbers that don't contain a 9 z # take reciprocal of each number O # sum the list ``` [Answer] # Scala, 56 bytes ``` Stream from 1 filterNot(_+""toSet 57)take _ map 1.0./sum ``` [Try it online!](https://scastie.scala-lang.org/TzCD41TkQwS4jKxnJLLQAg) 1-indexed. Returns the sum of the inverses of the first \$n\$ numbers. ``` Stream from 1 //Infinite list of integers, starting at 1 filterNot( //Remove the ones with a 9 _ + "" //Convert to string toSet //A Set is also a predicate. Check if it contains 57) //57, '9' as an integer take _ //Take the first n numbers map 1.0./ //Divide 1 by each sum //Sum them ``` ## Just for completeness, 58 bytes ``` (Stream.from(1)filterNot(_+""toSet 57)scanLeft.0)(_+1.0/_) ``` [Try it online!](https://scastie.scala-lang.org/kXgXdHMESPeSJsR3OCsBGw) This is an infinite stream of partial sums, but also a function that gives the \$n\$th partial sum (1-indexed). You can also use `take` on it to get the first \$n\$ partial sums. Unfortunately, it's a little longer than the version above. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` 1w9¬$#İS ``` [Try it online!](https://tio.run/##y0rNyan8/9@w3PLQGhXlIxuCgWwDAwMA "Jelly – Try It Online") 1-indexed, takes input from STDIN, returns the \$n\$th partial sum My last Jelly answer of the year, and it just so happens to outgolf Husk! ## How it works ``` 1w9¬$#İS - Main link. Takes no arguments 1 $# - Find the first n numbers that meet the following criterion: w9 - The index of 9 in the number’s digits... ¬ - ...is 0 (i.e. 9 is not in the digits) İ - Invert each number S - Sum ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12~~ 10 bytes Saved 2 bytes on both solutions thanks to [@Razetime](https://codegolf.stackexchange.com/users/80214/razetime)! ``` ṁ\↑fȯ¬#9dN ``` [Try it online!](https://tio.run/##yygtzv7//@HOxphHbRPTTqw/tEbZMsXv////hgYGBgA "Husk – Try It Online") It's been a while since my last Husk answer. This one outputs the \$n\$th number. It outputs a fraction, but I've [checked](https://scastie.scala-lang.org/Cbn3xUlsQVCVdKDdoWslJw) and it seems to be correct. Explanation ``` ṁ\↑fȯ¬#9dN N Infinite list of natural numbers f Filter by predicate: d Digits in base 10 #9 Number of occurrences of digit 9 ¬ Negate that ↑ Take the first n elements (implicit input) ṁ\ Map each to its reciprocal ṁ And sum ``` ### Infinite sequence, also ~~12~~ 10 bytes ``` ∫m\fȯ¬#9dN ``` [Try it online!](https://tio.run/##yygtzv7//1HH6tyYtBPrD61Rtkzx@/8fAA "Husk – Try It Online") [Answer] # [J](http://jsoftware.com/), 20 bytes ``` 1#.10%@#.9#.inv>:@i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1DA1UHZT1LJX1MvPK7KwcMvX@a3JxpSZn5CukKRjCGEZwEQMEy8CA6z8A "J – Try It Online") I just wanted to see if I could golf [fireflame's excellent Jelly answer](https://codegolf.stackexchange.com/a/217099/15469) in J. 1 based indexing. * `>:@i.` Integers 1..argument * `9#.inv` Each as a list of digits in base 9 * `10#.` Back to single number in base 10 * `%@` Reciprocal of each * `1#.` Sum [Answer] # [Husk](https://github.com/barbuz/Husk), ~~8~~ 7 bytes ``` ṁȯ\dB9ḣ ``` [Try it online!](https://tio.run/##yygtzv7//@HOxhPrY1KcLB/uWPz//39DAwMDAA "Husk – Try It Online") Outputs the \$n^{th}\$ partial sum. I tried using `İ\` from [here](https://github.com/barbuz/Husk/wiki/Sequences), but it's longer. Uses fireflame's idea. -1 byte from user. ## Explanation ``` ∫mȯ\dB9N N the list of natural numbers mȯ map to: B9 base 9 digits d represented as base 10 number \ take reciprocal ∫ take the cumulative sum ``` [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes ``` f=lambda k,n=1,b=0:k<2or b/n+f(k-b,n+1,1.-('9'in`~n`)) ``` [Try it online!](https://tio.run/##DcuxDoIwEIDhWZ7iNgocSEkcSuyTGBOoQrwA16atA4uvXjv82/@5M34sD4kOZ32EcIYi14Ul@uX19YEs73RQFLKv61uVVr3Ph3nPsCFriUb343YfrAdz5WYVW2uQG4mya0WpSuLpx1OVWT4YiOHRo0SFSqnnWFycJ47ACKvIqkp/ "Python 2 – Try It Online") One-indexed. Avoids repeating the `'9'in`n+1`` by passing it as an optional argument `b` to the next iteration of the function where the actual calculation is done. **58 bytes** ``` f=lambda k,n=1.:k and f(k-1+('9'in`n`),n+1)-~-('9'in`n`)/n ``` [Try it online!](https://tio.run/##RYyxDoMgFADn@hVvExSsNOmAiV/SNNFWSV@QBwE6uPTXqZ063HLJXdjzy9OloAs@Zkh7qg66tOa4Pt8xoacNHWam@qa58mLGbXaPZQYraFTdYGGmBQyzUrWs1jXSRBMX1CouP/JvzlSMj0CABLdeKKGF1vo@VKcQkTKQOCa/qnwB "Python 2 – Try It Online") **59 bytes** ``` f=lambda k,n=1:'9'in`n`and f(k,n+1)or k and 1./n+f(k-1,n+1) ``` [Try it online!](https://tio.run/##HczNDoIwEATgszzF3viryJpwKAlPYkyoQuMGum3aeuDpa@Uwl28m4474sXxPZJz1EcIRipwurNGv768PZHknQ7HCvmmGOulpV@a1KNgETziWsiSeeVa8gK6ytVhbDxv8Absbt1mveHrSuWEghkcvUEghpXyOxcV54ggs8sE5@wE "Python 2 – Try It Online") **62 bytes** ``` lambda k:sum([1./n for n in range(1,k*k+1)if~-('9'in`n`)][:k]) ``` [Try it online!](https://tio.run/##PcuxDsIgFEDR2X7F2woVazFxoIlfgiStWvSF8miADl38dezkcLdzly1/Al0K@iXEDGlL1V6bphyn5xoTBprRY2aya5orr@ztXubRP14juD6tnmnZnglsiECABHGk98SkcI07So72e2K1qpEGGrjRvTO8/K3uhBRKKKVMXx2WiJSBBFhG@1p@ "Python 2 – Try It Online") The `k*k+1` can be `2**k`, saving a byte but making the code really slow. **64 bytes** ``` s=0 n=1 exec"while'9'in`n`:n+=1\ns+=1./n;n+=1\n"*input() print s ``` [Try it online!](https://tio.run/##JYzBCoMwEAXv@YriRY1gTaGHtORPehBkwQV9CdmV1q@PgR5mYC6TTl0jHoX3FLPe5BRTGYU003Jk4YiNd9bOTdY@@yJhMgjO0I@W5rvyRq1vGTPmF4bgPpDq8Y73vxrLSId2vUmZUf@leO8v "Python 2 – Try It Online") --- # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 53 bytes ``` f=lambda k,n=1:k and(b:=max(str(n))<'9')/n+f(k-b,n+1) ``` [Try it online!](https://tio.run/##FctBDoIwEEDRtZxidkyhKo0xscSexLgoArGBTptpTeT0FRd/937c8jvQ5Ra5OB8DZ0hbqvZOaco8vT6cXKDVeZdRdU1zFWU2q/XDaGGRZFS/gKURh954@8WUGUmIe61rcaZ2xuU4SGrVfgUGAkfw6KSSWmqtn311iOwoA5KEGf9OlB8 "Python 3.8 (pre-release) – Try It Online") *Saved one byte thanks to @dingledooper.* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes ``` IΣ∕¹IEN⍘⊕ι⁹ ``` [Try it online!](https://tio.run/##JYtBDkAwEAC/4rgSkjqKGy4OROIFqzY00ZJ26/urYY4zGX2g1xeeIrM3jqHDwLBEC715zEZQFdmnRrxhcHfkKdqVPORF1mKghdO1p6I9WXJMG5iU6vynEamUUlI@5ws "Charcoal – Try It Online") Link is to verbose version of code. 1-indexed. Explanation: ``` N Input number E Map over implicit range ι Current index ⊕ Incremented ⍘ ⁹ Convert to base 9 as a string I Vectorised cast to integer ∕¹ Vectorised reciprocal Σ Sum I Cast to string Implicitly print ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~78~~ 77 bytes ``` def f(n,i=.0,s=0): while n: i+=1 while"9"in`i`:i+=1 s+=1/i;n-=1 return s ``` [Try it online!](https://tio.run/##JYzBCoMwEETP7lcsnhJq2423RvIvHprggqwhiYhfH4PCMPAezMSzLJuMtf59wKBkYPehITvSFvBYePUoFjp@OQPdzf2vZ5l5to/Lrb88ybsBJl/2JJjrszTtIyaWooJiiXtRWutqYARDLURwAQ "Python 2 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 30 bytes ``` f=n=>n&&1/n.toString(9)+f(n-1) ``` [Try it online!](https://tio.run/##FcyxCoMwEADQ3a@4QSRHNU26FYmbX9CxFAypsRa5KzG4hHx72g5vfW972N2F9RM74udcijdkBmoafSYZ@RbDSou44skL6jSW/q5buLSg1Z9SD@k5jNa9BIEZIFUAjmnnbZYbL2Kyok6UEQzU6VdgnrCvMpYv "JavaScript (Node.js) – Try It Online") Convert \$n\$ to base 9, and read the converted result as base 10. Then inverse it. You will get the \$n\$th item. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-mx`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) 1-indexed ``` 1/°Us9 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW14&code=MS%2bwVXM5&input=MTA) [Answer] # [Haskell](https://www.haskell.org/), 45 44 42 bytes ``` f=scanl(+)0[1/x|x<-[1..],all(<'9')$show x] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P822ODkxL0dDW9Mg2lC/oqbCRjfaUE8vVicxJ0fDRt1SXVOlOCO/XKEi9n9uYmaegpWVgqe/goYmF5hnq1BQlJlXoqCikKagqKhgaGBg8B8A "Haskell – Try It Online") Infinite list. 44 byte thanks to ovs, who suggested `all(<'9')` to replace `not$elem '9'`. 42 bytes thanks to Donat, who suggested `1` to replace `1.0`. [Answer] # [Perl 5](https://www.perl.org/), 26 bytes ``` /9/||say$a+=1/$_ while++$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/1/fUr@mpjixUiVR29ZQXyVeoTwjMydVW1sl/v//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online") [Answer] # AWK, 37 bytes ``` {for(;++i<=$1;)i~9?$1++:n+=1/i;$1=n}1 ``` [Try it online!](https://tio.run/##SyzP/v@/Oi2/SMNaWzvTxlbF0Fozs87SXsVQW9sqT9vWUD/TWsXQNq/W8P9/QwMDAwA "AWK – Try It Online") ``` { for(;++i<=$1;) #loops while i<= the input. # also increments the variable 1 every loop. i~9? # if there is a 9 in _i_ $1++: # skips this _i_, adding 1 to $1 n+=1/i; # otherwise, adds 1/i to _n_ $1=n # in the end, assigns _n_ to $1 } 1 # prints $1 ``` ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes ``` Tr[1/FromDigits/@Range@#~IntegerDigits~9]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6Qo2lDfrSg/1yUzPbOkWN8hKDEvPdVBuc4zryQ1PbUIIlxnGav2P6AoM68kWlnXLs1BOVatLjg5Ma@umstQh8tIh8vQAIQNDLhq/wMA "Wolfram Language (Mathematica) – Try It Online") [Answer] # JavaScript (ES6), 46 bytes 1-indexed. ``` f=(n,i=1)=>n&&(/9/.test(i)?0:n/n--/i)+f(n,i+1) ``` [Try it online!](https://tio.run/##Fcy9CoMwFEDh3ae4g0gu5rdbK7FTn6IUDKm2EbkpKl1Cnj2tw9k@zuy@bvNr@OyC4nMsZbKMeLAGbU9Nw9RZyX3cdhbwqi@kSAgVsJ0O1Bos3d1wOHEw@kjrh5zienP@zQhsD6kC8JG2uIxyiS82OFYnyggW6vSfYB6wqzKWHw "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://cran.r-project.org/), ~~94 93 92 64~~ 59 bytes Thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) for suggesting a [grepl](https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/grep) shortcut! ``` n=scan()+2;while(n<-n-1){F=F+1/T;while(grepl(9,T<-T+1))0};F ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0NT28i6PCMzJ1Ujz0Y3T9dQs9rN1k3bUD8EKppelFqQo2GpE2KjG6JtqKlpUGvt9t8SDP4DAA "R – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~45~~ 43 bytes *Edit: -2 bytes thanks to Giuseppe* ``` x=scan();y=1:x^2;sum(1/y[!grepl(9,y)][1:x]) ``` [Try it online!](https://tio.run/##K/r/v8K2ODkxT0PTutLW0Koizsi6uDRXw1C/MloxvSi1IEfDUqdSMzYaKBWr@d/QwMDgPwA "R – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 10 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ∞╒gÉ9╧┌<∩Σ ``` Outputs the \$n^{th}\$ value with 1-based input \$n\$. [Try it online.](https://tio.run/##y00syUjPz0n7//9Rx7xHUyelH@60fDR1@aMpPTaPOlaeW/z/vyGXEZehARAZGAAA) **Explanation:** ``` ∞ # Double the (implicit) input-integer ╒ # Pop and push a list in the range [1,2*input] g # Filter this list by, É # using the following 3 characters as inner codeblock: 9╧ # Check that the integer contains a digit 9 ┌ # And invert the boolean < # Only keep the first (implicit) input amount of values of the filtered list ∩ # Map all values to 1/n Σ # And sum those together # (after which the entire stack joined together is output implicitly as result) ``` MathGolf unfortunately doesn't contain base-conversion builtins, except for binary and hexadecimal. So I use a manual filter instead. The double at the start is to ensure we have enough values left after the filter for which we can keep the first input amount of values. After which we'll map them to \$\frac{1}{n}\$, and sum them together. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes ``` +/1%10/9\1+!: ``` [Try it online!](https://ngn.bitbucket.io/k#eJwlyUsKgzAUQNF5VpFCCy1CfJ8kJnlL0YBOAkWhIA6UomuvxcnlwC2pqvGBUMcOq1tSaknfe7sdcypa61X6zyjPvgzvSVbZZH7lXS0tChrIJ+iE+wNByEQIjffEfNXSdQDEm0COQxMtx0DE1rv8A9WOHuo=) A similar approach to many other answers, modeled after [@fireflame241's Jelly answer](https://codegolf.stackexchange.com/a/217099/98547). Uses 1-based indices. * `1+!:` generate `1..n` * `10/9\` convert to base-9, then back to base-10 * `+/1%` take the sum of the inverses [Answer] # [Raku](http://raku.org/), 25 bytes ``` [\+] 1 X/grep {!/9/},1..* ``` [Try it online!](https://tio.run/##K0gtyjH7n1up4FCcWqhg@z86RjtWwVAhQj@9KLVAoVpR31K/VsdQT0/rv7WCXnFipUJafhFYbXSckUHsfwA "Perl 6 – Try It Online") This is an expression for an infinite sequence of the partial sums. * `grep { !/9/ }, 1..*` is the infinite sequence of all natural numbers with no 9 digit in its decimal representation. * `1 X/` produces the reciprocals of that sequence. (`X` is the cross-product metaoperator, combined here with the `/` division operator.) * `[\+]` produces the partial sums of that sequence. [Answer] # SmileBASIC 4, 139 bytes Zero-indexed. Returns the nth partial sum of the series. ``` 1 DEF F(X)REPEAT INC U,X MOD 9*POW(10,I)X=X DIV 9INC I UNTIL!X RETURN U END 2 DIM O[1]@0 UNSHIFT O,O[0]+1INC S,1/F(O[0])IF N+2>LEN(0)GOTO@0 3 ?S ``` --- Newline chars on lines 1 & 2 are included in byte count. The program iterates through integers 0-N, converts each value to base 9, and adds the base-10 interpreted inverse of the value to a sum. Finally, it prints the sum. [Answer] # [Perl 5](https://www.perl.org/), 39 bytes ``` sub f{my$r;$r+=!/9//$_ for 1..$_[0];$r} ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhrTq3UqXIWqVI21ZR31JfXyVeIS2/SMFQT08lPtogFihR@7@gKDOvRCFNQyVeU0cpJk8JrELDUMdIx0LHUsfQQMfQEEgaGGj@BwA "Perl 5 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~87~~ 84 bytes Saved 3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` m;float i,s;float f(n){for(i=s=0;m=n--;s+=1/i)for(;m;)for(m=++i;~m%10*m;m/=10);i=s;} ``` [Try it online!](https://tio.run/##bVFBboMwELznFSskJEiAGAgE5LiXqq9ocqBgWquxiTAH1Ih@ndqxg9KqSDZmZnZ2Gdfhe13PM8ftuasGYIG0p9YT/rXteo8RSRDmRIQhlhsSb5mvYczx7c3JZsPwN3djtOaYb0mMfKxq8DQzMQCvmPD81XUF6tHAQOUgX09A4BoHkAQQI70QmvBNY7rT8ULrgTZWGGlNlCl9VKJin@dJmpp9F0AeFUmWFvtyl5ZFkqSZdao/qn6tdlp/0t4YOcfxJTmO5bNamRPA43fq/J7gItm5E6oqpmFmma4HT/8EEw0dFYWwPR5Asi/atd59cH9rgfWCYFBJabUPJo57JLqJieVGn/DCmlGk4vV1/MWpwpeg/i9t6HmodHn1Jj0Z0gePS696t57jNhA@gduCK49CZSICkMESmzE43OM4WYNpNc0/ "C (gcc) – Try It Online") Inputs a \$1\$-indexed \$n\$ and returns the \$n^{\text{th}}\$ partial sum of the series. [Answer] # x86 Machine Code (x87 FPU), 35 bytes ``` D9 EE 31 F6 8D 7E 0A 46 89 F0 99 F7 F7 83 FA 09 74 F5 85 C0 75 F4 89 33 DB 03 D9 E8 DE F1 DE C1 E2 E5 C3 ``` The above bytes define a function that computes the *n*th partial sum of the Kempner series. The function defines a custom calling convention, whereby it accepts two arguments: * The value *n* is passed in the `ecx` register (this is an unsigned 32-bit integer value). * The address of a "scratch" memory buffer is passed in the `ebx` register (the buffer's size must be at least 4 bytes in length). The function returns a single result, the *n*th partial sum, at the top of the x87 FPU stack (`st(0)`). **[Try it online!](https://tio.run/##lVbbbts4EH33VwxYZCHBsivbufhSp8AmfdqHLZICLZAEBkNSNluJVCUqVRLk19c7lCxHtuQUFSCJoDWHZ2bOzJjFcW/J2HodhJoa@EdEsRKJk6lULpXgoDzYru@zIBCJ23nuAF6lQSLSLDSzYmexoGm0WDikL5UR4SJ9VIbmoHSciEDmpFN8VV3kVt2aIORPBA5d799Damhi4Jc0K4hxJWkIaRbBfA5@3wcHGRgdgw4gH5@5TfxcJ3YtUunZB2ng4yYgVtMyFLSw5Gh5Y7/qwsC/IzVLbi0HfsOrzyXP6yw6mk9JE1kqtuFE2n0uTkPopmmkHwpTmh9yB@M9tz81WF2sBPtxKZfStLNi/OfhRFjoJ5FodDoHR@kkomH46IFNrEiA2DDjT559kJY0cPmwCeYhl3k@tdyLsLaQi@LSHo@YkBb7RERUKo5cUBmTj02E76JY13NDdoX2Q8YgA@A2RPCLpkBh0sQxIjXbDNC8mYGfmTZSKPzIarSNiXqy63o@dpmEWhdMIp2Ikk6KIgdmDToHNXH59d@rS/j85QrVep/fVfooSsgCWVFhWWpIWUINW0Ek8IDHTVG3VKYMeRO2pv84S1fwQMNMQJDoqB3XEn8t0Nb6H7xZ/8UpAyz13wGhxJIYfXUGrmdfvrsbVUZDloXUiAKtKLIWFMo5Ku0wCmUsi0qYejtyyjYIElXzm45UZPctIXLBUM1WQYLZYkMiVHFgWmHnwGBbAKmWViFKq54ty4Yq@tSYqv2WzfdW7dT8FMjckIq3eyj6OjNxZqyrNBIG0ykVXH/BqOxhMXQBmb7ZP6RqQH26@FYH8oDcW6C/NoPmD4D@/rbHqFThjs9uOaUSYbJEbQfXy/odNuQw4wI@sBQ7lT7v1HYialb1DYknUiyo804Hqwls13Gqibg3KGdlWjBx2DJeB@qGzc0dNupnGHgw9HCK2Nv34WVWsyknrO02eSyYEbyy6dvP@ydo2p/447PT0@FoVD6PPTjtj4cno/HZ5Hg0GQ@Ho5MKNMAm/TrYi7E3w9cH1DmfTlP5JJzqIHcG3a4ss/y8jWHJimZYihu9z7d/GNSNxJ6zSdxsaxInGKXAIUcceudwFMBRikr0OntZLaz3N8szGtuOU/Cl92lVdb3XAMk7Fx0a@KJ37MJHLIX80/A2n1zgPSJWF7WNE@JumL7UheFbTfzHgpAu03UvGg3XPTxwzrrdIf0f "C++ (gcc) – Try It Online")** In ungolfed assembly language mnemonics: ``` ; Computes the nth partial sum of the Kempner series. ; Input(s): ; ecx = n ; ebx = address of DWORD scratch buffer ; Output(s): ; st(0) = nth partial sum ; Clobber(s): ; eax, [ebx], ecx, edx, esi, edi, st, flags Kempner: D9 EE fldz ; start with partial sum == 0.0 (at top of x87) 31 F6 xor esi, esi ; esi = 0 8D 7E 0A lea edi, [esi + 10] ; edi = 10 PartialSum: 46 inc esi ; esi += 1 89 F0 mov eax, esi ; eax = esi CheckDigit: 99 cdq ; zero edx (normally, prefer xor edx, edx) F7 F7 div edi ; edx:eax / edi 83 FA 09 cmp edx, 9 ; remainder == 9? 74 F5 je PartialSum ; skip if digit was a 9 85 C0 test eax, eax ; quotient == 0? 75 F4 jnz CheckDigit ; loop if more digits to check 89 33 mov DWORD PTR [ebx], esi ; store esi into scratch memory buffer DB 03 fild DWORD PTR [ebx] ; push value from scratch memory buffer to top of x87 D9 E8 fld1 ; push 1.0 to top of x87 DE F1 fdivrp st(1), st(0) ; calculate 1.0 / esi DE C1 faddp st(1), st(0) ; accumulate partial sum (result is at top of x87) E2 E3 loop PartialSum ; decrement ecx (n), and continue looping if non-zero C3 ret ``` --- # [BONUS:] x86 Machine Code (AVX), 44 bytes ``` 31 F6 46 0F 57 C0 8D 7E 09 F3 0F 2A D6 4E 46 89 F0 99 F7 F7 83 FA 09 74 F5 85 C0 75 F4 C5 F2 2A CE C5 EA 5E C9 C5 FA 58 C1 E2 E3 C3 ``` In ungolfed assembly language mnemonics: ``` ; Computes the nth partial sum of the Kempner series. ; Input(s): ; ecx = n ; Output(s): ; xmm0 = nth partial sum ; Clobber(s): ; eax, ecx, edx, esi, edi, xmm0, xmm1, xmm2, flags Kempner: 31 F6 xor esi, esi ; \ set ESI to 1 46 inc esi ; / 0F 57 C0 xorps xmm0, xmm0 ; zero XMM0 8D 7E 09 lea edi, [esi + 9] ; set EDI to 10 F3 0F 2A D6 cvtsi2ss xmm2, esi ; set XMM2 to 1 (from ESI) 4E dec esi ; set ESI back to 0 PartialSum: 46 inc esi 89 F0 mov eax, esi CheckDigit: 99 cdq F7 F7 div edi 83 FA 09 cmp edx, 9 74 F5 je PartialSum 85 C0 test eax, eax 75 F4 jne CheckDigit C5 F2 2A CE vcvtsi2ss xmm1, xmm1, esi C5 EA 5E C9 vdivss xmm1, xmm2, xmm1 C5 FA 58 C1 vaddss xmm0, xmm0, xmm1 E2 E3 loop PartialSum C3 ret ``` This is larger, since the AVX instructions require more bytes to encode than the x87 instructions. It is essentially the direct translation of the above function targeting the x87 FPU, except that I had to be a bit clever when loading "1.0" in the AVX (`xmm2`) register. Basically, I eagerly set `esi` to 1, load it into `xmm2` using the convert-from-integer instruction, and then set `esi` back to 0. Since `inc` and `dec` are 1-byte instructions, this is the cheapest way that I could find. [Answer] # [Zsh](https://www.zsh.org/) `-o forcefloat`, ~~41~~ 40 bytes ``` for ((;++n;))((n[(I)9]))||echo $[a+=1/n] ``` [Try it online!](https://tio.run/##qyrO@F@cWpJfUKKQll@UnBqflpOfWMJV/R/IU9DQsNbWzrPW1NTQyIvW8NS0jNXUrKlJTc7IV1CJTtS2NdTPi/1fW5ORmpiioGto9N/QCAA "Zsh – Try It Online") Outputs infinitely. Explanation: ``` for ((;++n;))((n[(I)9]))||echo $[a+=1/n] implicitly intitialise $n and $a to 0 for ((; ;)) loop while ++n increment $n (always truthy) || if not n[(I)9] the index of "9" in $n (( )) is not zero, $[a+= ] then increase $a by 1/n the reciprocal of $n echo and print $a ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 39 bits1, 4.875 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md) ``` 9c¬)ȯĖ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJz4biLPSIsIiIsIjljwqwpyK/EliIsIiIsIjEwIl0=) 1-indexed. ## Explained ``` 9c¬)ȯĖ )ȯ # First #input numbers which: c¬ # don't contain 9 # the number 9 Ė # reciprocals # summed by the s flag ``` ]
[Question] [ ## Challenge Given an arbitrary list of 2-tuples, and a single element in one of those tuples, output its "partner", i.e. given `a` and `[(i,j),...,(a,b),...,(l,m)]`, output `b`. You can assume all tuples are unique, and that all elements in tuples are strings. Further assume you do not have both `(x,y)` and `(y,x)`. ### Test cases ``` Input Output [("(", ")"), ("{", "}"), ("[", "]")], "}" "{" [("I'm", "So"), ("Meta", "Even"), ("This", "Acronym")], "Even" "Meta" [("I", "S"), ("M", "E"), ("T", "A")], "A" "T" [("test", "cases"), ("are", "fun")], "test" "cases" [("sad", "beep"), ("boop", "boop")], "boop" "boop" ``` Fewest bytes wins! [Answer] # Japt, 6 bytes Works with strings or integers. ``` æøV kV ``` [Test it](http://ethproductions.github.io/japt/?v=2.0a0&code=5vhWIGtW&input=W1sxLDJdLFszLDRdLFs1LDZdXQo0) --- ## Explanation Implicit input of array `U` and string/integer `V`. ``` æ ``` Get the first element (subarray) in `U` that ... ``` øV ``` Contains `V`. ``` kV ``` Remove `V` and implicitly return the resulting single-element array. [Answer] # [Haskell](https://www.haskell.org/), 33 bytes ``` x!((a,b):c)|x==a=b|x==b=a|1<2=x!c ``` [Try it online!](https://tio.run/##lcuxCsIwFEbh3af4A8JNIIuO0vsk4nBvkmJpraIdMvTd00gXRzOds3x3@YxpmkrJxlrx6i7BrZlZWL9RlvXUnTmbUB4yzGDE5wF4vYd5wREkBIOrrfWk5Dwshbpx31S3J3f7FdosQrOIzSI1i/4/UTY "Haskell – Try It Online") Defines a binary operator `!`, which takes as its left argument a value `x` of type τ and as its right argument a list of tuples (τ, τ). The definition pattern matches on the head `(a,b)` and tail `c` of the given list; if `x==a` then `b` is returned; if `x==b` then `a` is returned, and otherwise we go on looking in the rest of the list by recursing. ``` 'f' ! [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')] ≡ 'f' ! [('c', 'd'), ('e', 'f'), ('g', 'h')] ≡ 'f' ! [('e', 'f'), ('g', 'h')] ≡ 'e' ``` (If there’s no “partner” in the list, this will crash, because we didn’t define what `x![]` should be.) [Answer] ## JavaScript (ES6), 39 bytes ``` e=>g=([[b,c],...a])=>e==b?c:e==c?b:g(a) ``` Takes the entry and array of arrays as curried arguments. Best non-recursive version I could do was 44 bytes: ``` e=>a=>a.find(a=>a.includes(e)).find(b=>b!=e) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~4~~ ~~14~~ ~~5~~ 6 bytes ``` yY=P)u ``` [Try it online!](https://tio.run/##y00syfn/vzLSNkCz9P//6Gr1RHVr9aQk9VqdavWUzAIgJyW/AMxzK0rNS84AySaml6aWlKSCRQvySxJL8oGixfmlQHWxXDB1AA "MATL – Try It Online") Input is an array as `[{a;b},{c;d}]`. Bytecount fluctuates heavily while the OP figures out what's actually allowed. ``` y % Implicitly input tuples T and 'lonely element' E, duplicate from below to get [T E T] on the stack Y= % String comparison, element wise, between T and E. Yields a boolean array with a 1 at the correct location. P % Flip this array vertically, to put the 1 at the 'partner' of E. ) % Select this partner from the bottom T. ``` I started off with a 4-byte version that could only handle single-character strings, which was the only testcase in the original challenge. When this turned out to be invalid, I made a very long 14-byte version, which was nice and hacky (check the revision history!), made me discover a bug, and then turned out to be completely unnecessary as `Y=`, with suitable input, worked just as well as my original 4-byte `y=P)`. [Answer] # [Python 2](https://docs.python.org/2/), 37 bytes ``` lambda x,y:dict(x+map(reversed,x))[y] ``` [Try it online!](https://tio.run/##JchBCoAgEADAr3jbXdpTx6CXmAdLIyFLTEKJ3m5Ft2FCScu@tXXuh7pqPxotMpfOuClhbrwOGO1p42ENZyJZVA3RbQlnlAgIDATEAuF6ef@ULxWQYvEN1Qc "Python 2 – Try It Online") # [Proton](https://github.com/alexander-liao/proton), 31 bytes ``` a,b=>dict(a+map(reversed,a))[b] ``` [Try it online!](https://tio.run/##JcgxDoAgDADAr7C1jf0CfoQwFIGEQSBIXIxvrxq3y/XRZquarQoHu8ayTZRll44jnWkcKbIQueC1j1InZnQICAwExAbhenn/dC89kGfzDekD "Proton – Try It Online") (These two answers are so similar that I'm posting them together to avoid repfarming) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ċÞṪ⁻ÞṪ ``` A dyadic link taking the list partners on the left and the lost-partner on the right and returning the partner. **[Try it online!](https://tio.run/##y0rNyan8//9I9@F5D3euetS4G0z///8/WkPJUz1XSUdBKThfSVNHQUPJN7UkEcR3LUvNg4iEZGQWg0Qck4vy8ypzlTRj/0NkAQ "Jelly – Try It Online")** ### How? ``` ċÞṪ⁻ÞṪ - Link: list, partners; item, lost-partner Þ - sort (the tuples) by: ċ - count occurrence of lost-partner Ṫ - tail (gets the tuple containing the lost-partner) Þ - sort (that tuple's items) by: ⁻ - not equals (non-vectorising version) Ṫ - tail (get the other one, or the rightmost one if they were equla) ``` [Answer] # [Perl 5](https://www.perl.org/), 30 + 1 (-p) = 31 bytes ``` $_={@f=eval$_,reverse@f}->{<>} ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3rbaIc02tSwxRyVepyi1LLWoONUhrVbXrtrGrvb/fw11DXUddU11TR0FDfVqILMWwowGMmPVNbli/@UXlGTm5xX/1/U11TMwNPivWwAA "Perl 5 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~59~~ ~~45~~ 42 bytes *-14 bytes thanks to Emigna. -3 bytes thanks to Maltysen.* ``` lambda l,v:sum(l,())[sum(l,()).index(v)^1] ``` [Try it online!](https://tio.run/##TZAxC8IwEIX3/orDJYkUQUfBwcGhg1PdaoW0TTHQJiFJi0X87dVLqpglj3fvexdiJn/Xaje3h@vc8b5qOHTpuHdDT7uUMlb81EaqRjzoyG7bcvbCeQcHKBL4HFpQQkkKhBGWAiVP1K@oC9QlYeVifYFVRvrVx8t1zJ2F5xg9jUJF53KXDp1jbbWa@lixjH9rM0zkS0XgFziQkTn@A/hynNXcCRez3Ap02kHFfIj8IY43OK@EMBGotDbBwTsgQQFLyiRptQUJUkH4o31oMVYqDy1dSza/AQ "Python 2 – Try It Online") Still wanna use currying though. ;-; [Answer] ## C++, 179 bytes ``` #include<vector> #include<string> #define S std::string S f(std::vector<std::pair<S,S>>s,S t){for(auto&a:s){if(a.first==t)return a.second;if(a.second==t)return a.first;}return"";} ``` ## C++ w/ map data type, 162 bytes ``` #include<map> #include<string> #define S std::string S f(std::map<S,S>s,S t){for(auto&a:s){if(a.first==t)return a.second;if(a.second==t)return a.first;}return"";} ``` With MSVC, the code compiles even if the last `return` statement ( `return"";` ) is omitted. It makes the code 9 bytes lighter, **BUT** exiting by the function end ( i.e. not exiting by a `return` statement in the loop ) with no return statements will cause **undefined behavior**, and not work if the tuple array does not contains the "key" element [Answer] # PowerShell, 36 Bytes ``` param($a,$c)$a|?{$c-in$_}|%{$_-ne$c} ``` finds the element containing the intput, then gets the 'other' element by excluding the input from it, PowerShell doesn't have the most amazing array management but there might be a built-in for this i'm not aware of. ``` .\Partner.ps1 (("I'm","So"),("Meta","Even"),("This","Acronym")) "Even" Meta ``` [Answer] # [Röda](https://github.com/fergusq/roda), 30 bytes ``` f a{[(_+"")[1-indexOf(a,_1)]]} ``` [Try it online!](https://tio.run/##fcyxDoIwFAXQWb@i6WIbceATHBwcjINuTUMeUCIDLaHVaJBvr7wW2GTq7c19pzMleF8R6AXL9pRykR5qXar3tWKQZCmXcvAN1Jr0240QVNCEUEllQgTtMQ8xz70kX1KxseVjKIwuwDGMbVdrxzIekPOuwfnNxNuLcoD/00vp2NwftcXmWHRGf5qFDYtVObgTG8wJDNriHFcRp6zDfQFW2XgPncKmeurFCKs1xkKJN7lSbURyY9rQ4Dsz4fOPGfwP "Röda – Try It Online") Explanation: ``` f a{[(_+"")[1-indexOf(a,_1)]]} f a{ } /* Function f(a) */ /* For each pair _1 in the stream: */ indexOf(a,_1) /* Index of a in _1 or -1 if not found */ 1- /* Subtract from 1 to get the index of the other value in the pair or 2 if a is not in the pair */ (_+"") /* Append "" to _1 */ [ ] /* Get element the other element or "" */ [ ] /* Push it to the straem */ /* All values in the stream are printed */ ``` [Answer] ## Mathematica ~~27~~ 24 Bytes `Cases` picks out elements of a list that match a pattern. When used with an arrow, elements matching patterns can be transformed. ``` Cases[{#,x_}|{x_,#}:>x]& ``` Usage: ``` %[3][{{1, 2}, {3, 4}}] ``` Explanation: In this example, after encountering the first argument, 3, the function becomes `Cases[{3,x_}|{x_,3}:>x]` which is an operator form of `Cases` that is then applied to the 2nd argument, `{{1, 2}, {3, 4}}`, thus selecting the companion of 3, whether it be in the abscissa or ordinate position. Notably, this function will list out all of the companions if in fact the 1st argument appears more than once within the 2nd argument, in other words, this goes a little beyond the assumptions of the stated question. Enclosing glyphs must be squiggly braces. Saved 3 bytes with "Currying" suggestion from @Notatree [Answer] # [R](https://www.r-project.org/), 47 ~~42~~ bytes ``` function(v,a)a[(i=min(which(v==a)))+(i%%2*2-1)] ``` [Try it online!](https://tio.run/##fYsxDsIwDEX3nqKKVNkGM5A9J6k6pKFRPTSpSilIiLMHw1AxMb0vvf@WEl2JtxRWyQk39uRbFDdJwvsoYcTNOU9ER5SmsQd7OlNXIkKf8ww8@XWRBwY0V38xXJt@GOYvVe8ktkSVRu1PAQgMBFzDU8frM1RDB/tb5b8bVeUN "R – Try It Online") Works on either a matrix or a straight vector. v = the search value, a = tuple array. [Answer] # Pyth - ~~11~~ ~~9~~ 8 bytes ``` h-hf}QTE ``` [Try it online here](http://pyth.herokuapp.com/?code=h-hf%7DQTE&input=%27%5D%27%0A%5B%28%27%28%27%2C%27%29%27%29%2C+%28%27%7B%27%2C%27%7D%27%29%2C+%28%27%5B%27%2C%27%5D%27%29%5D&debug=0). [Answer] # [Haskell](https://www.haskell.org/), ~~65~~ 62 bytes ``` c#(a,b)|a==c=b|1>0=a x%l=x#(snd(span(\(a,b)->a/=x&&b/=x)l)!!0) ``` [Try it online!](https://tio.run/##JYpBDoIwEADvvgKCsLtJVXjAcvLoD5DDFk1sLLWhPZCIb6@NXiaTyTwkPO/WJjP71xKLs0Q5XkyIaapQlKZNmCfWW9e3LLu1trxWGNwNgxeH199z6OXEa9PoTLJUli2lWYxjvxgX9/CGekBAUEBAqsAcFHz@OmQdgcb0BQ "Haskell – Try It Online") ## Explanation This uses span to find the first instance where `x` is contained by the tuple. It then grabs the first element of the tuple if its not equal and the second otherwise. # Haskell Lambdabot, ~~59~~ 56 bytes ``` c#Just(a,b)|a==c=b|1>0=a x%l=x#find(\(a,b)->a==x||b==x)l ``` [Try it online!](https://tio.run/##JYlBCsIwEADvvqLQlt1AFH3A9uRJ/EHtYVMVF9NYmhQCxrfHoJdhmHmwf96szTLNryVURw68O4sPeaxPqw/I2qjERCOZdOj2xJvYWor1XdwVL7@97cqPKZlCZfPE4mhexIUG3tD2CAgaFChdYQkaPn/tiw6ghvwF "Haskell – Try It Online") ## Explanation This uses `Data.List`s `first` function to cut down on the bytes used by `(!!0).snd.span`, however because `first` returns a `Maybe` we need to add `Just` to our pattern match in `#`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` .åÏ`¹K` Ï # keep only pairs that contain the first input ` # flatten ¹K # remove the first input ` # flatten ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f7/DSw/0Jh3Z6J/z/r8EVHa2uoa6jrqkeqxOtXg1k1YJZ0UBWrHpsLAA "05AB1E – Try It Online") **Alternative 7 byte solution** ``` ˜DIkX~è ˜ # deep flatten D # duplicate Ik # get the index of the second input in this list X^ # XOR with 1 è # get the element at this index ``` [Try it online!](https://tio.run/##MzBNTDJM/f//9BwXz@yIuMMr/v@PjlbXUNdR11SP1YlWrwayasGsaCArVj02lksDAA "05AB1E – Try It Online") [Answer] # Common Lisp, 74 bytes ``` (lambda(a x)(or(cdr(assoc x a :test'equal))(car(rassoc x a :test'equal)))) ``` [Try it online!](https://tio.run/##dck7CoAwEEXRrQzT@F7jAtyKWIzRQoi/SQRBXHtEe7vDvSFOaSvYfFqyoCDa3A8Gk5NYHWFwWEprkFNMmjymXI37YZFEMIf/TLJUgEJrUSoFer28P7YvOyW/wPIA) [Answer] # Java 8, 78 bytes A lambda (curried) from `Stream<List<String>>` to a lambda from `String` to `String` (although implicit typing happens to allow this to work for arbitrary lists). The language has no dedicated tuple classes, and I'm not aware of any in the standard library, so input pairs are represented as lists. Can be assigned to `Function<Stream<List<String>>, Function<String, String>>`. ``` l->s->l.filter(p->p.contains(s)).map(p->p.get(1-p.indexOf(s))).findAny().get() ``` [Try It Online](https://tio.run/##fVDLasMwEDwnXyF8qQS2oNc8DDm0UGhoIb2VHlRbSZXKayGt3Rrjb3fXUUpCDz1JmtkZ7cxRtSqrnYZj@Tm65t2aghVWhcC2ygDr5zPnTatQs4AKiTySQDZorNw3UKCpQd6fL6sLF9BrVcnd6bjCH03AFaEGDnme/msWp1L2O80OGp@VR9CerUeb5SHLSWcsas9dljtZ1IC0dOBBCFkpF1GS8dvMSQOl/n7aT6QgGZQb6Lg40WKcLeeUNMY/B21rU7KK/Hjc4PWNKX8IYupk9gsRSC2tGegvdoX1ffJwUyUpS3Z1MqSsT7Ya1fS@azVE5OXDhAnZFL6GrkqGYTkZdwF1JesGJRUPaIFfckvlnO34pbWN96oL57a5gRj7L79YqDAVT7mjQdxGCPpwmA/jDw) I'll credit the saving of the last 6 bytes to anyone who can convince me that returning an `Optional` is valid. I haven't been able to convince myself. One of the interesting parts of this solution for me was determining the cheapest way to get the output from the stream. I considered `reduce`, `findFirst`, and `min`/`max`, but none was shorter than the intuitive `findAny`. [Answer] # JavaScript (ES6), 45 bytes Came up with this last night then noticed Neil had beaten me to a better JS solution; figured I may as well post it anyway. Works with strings and integers. ``` a=>n=>a.reduce((x,y)=>y[1-y.indexOf(n)]||x,0) ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 43 bytes ``` f([[A,B]|T],X,R):-A=X,R=B;B=X,R=A;f(T,X,R). ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P00jOtpRxym2JiRWJ0InSNNK19EWSNs6WTuBaUfrNI0QsIweRLGShpKOgpKmUqxOtFI1iFkLZCpEK0WD2LFKsbE6IOEITT0A "Prolog (SWI) – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~101~~ 100 + 18 bytes thank you to Grzegorz Puławski helping reducing a couple of bytes. ``` x=>y=>x.Where(z=>z.Item1==y).FirstOrDefault()?.Item2??x.Where(z=>z.Item2==y).FirstOrDefault()?.Item1 ``` [Try it online!](https://tio.run/##fY9Pa8MwDMXP86cQPtmQGdpraufQUShs7LBBDyEHkymdIXU629mahnz2LH/GWFuYdBD6vQfSy/19Xjnsa2/sHl4aH/AQk7@beDT2IyZ5qb2HY0vABx1MDpva5qvX@ljiygc3@COYp0qzaBLhiqtC9iepGqlOYveODtlZqrPYDkcWUjZcbIzz4dk9YKHrMjCeTNoySW78y3/8iz4mPz9@VuYNnrSxbH4hzUC7veekJXfryvqqRLFzJuCQEVnBLH7BRaTfRO2ExdqhDsgooxFQTnl0idsRdzc4HXFGecfZqPKYdEPDXIT03w "C# (.NET Core) – Try It Online") # C# (.NET Core), ~~122~~ ~~121~~ 120 bytes ``` x=>y=>{for(int i=0;i<x.Length;i++){if(x[i].Item1==y){return x[i].Item2;}if(x[i].Item2==y){return x[i].Item1;}}return"";} ``` [Try it online!](https://tio.run/##bY9Ba4QwEIXPza8YckpYK929ZuNloVDYnlroQTwEO9qAGyWJrRLy262uIN22c5nhe2/gvdLdl63FqXfa1PAyOo8XQYy6oOtUieACKRvlHHSBgPPK6xIee1MeX/uuwaPzdv5LYN1ZXiRXEX7xrJLTILNRZqFqLdPGg5YPQh@H9Iym9h9C73Y86IoNuS7SpznEXsqRB4u@twY2ehDxp@nwr2kvYlwZpSJOYgv@2ep3eFbasDVXXoCyteMkkLtTa1zbYPpmtcezNsgqZvALbnpuNcMVpyeLyiOjjCZAOeXJLQ4Ljn9wvuCC8sjZonJBIoF15itO3w "C# (.NET Core) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` →ḟo=⁰←S+m↔ ``` [Try it online!](https://tio.run/##yygtzv7//1HbpIc75ufbPmrc8KhtQrB27qO2Kf///1dKys8vUPofraFUnJiipKOUlJpaoKSpowER14FQmrEA "Husk – Try It Online") ### Ungolfed/Explanation ``` -- example input: 4 [(1,2),(3,4)] S+ -- concatenate list with - m↔ -- itself but all pairs flipped - [(1,2),(3,4),(2,1),(4,3)] ḟo -- find first occurence where - =⁰← -- the left element is equal to input - (4,3) → -- get the right element - 3 ``` **Note**: The above example works on integers just for the sake of readability, the type itself doesn't matter (as long as you can compare it). [Answer] # [Swift 4](http://swift.sandbox.bluemix.net/#/repl/59c7ce136032437898077606), 43 bytes ``` {a,m in a.flatMap{$0==m ?$1:$1==m ?$0:nil}} ``` The output is an array, which is either empty (no partner found), or has a single element (the partner). [Test cases:](http://swift.sandbox.bluemix.net/#/repl/59c7ce136032437898077606) ``` let testcases: [(pairs: [(String, String)], match: String, expected: String)] = [ ( pairs: [("(", ")"), ("{", "}"), ("[", "]")], match: "}", expected: "{" ), ( pairs: [("I'm", "So"), ("Meta", "Even"), ("This", "Acronym")], match: "Even", expected: "Meta" ), ( pairs: [("I", "S"), ("M", "E"), ("T", "A")], match: "A", expected: "T" ), ( pairs: [("test", "cases"), ("are", "fun")], match: "test", expected: "cases" ), ( pairs: [("sad", "beep"), ("boop", "boop")], match: "boop", expected: "boop" ), ] for (caseNumber, testcase) in testcases.enumerated() { let actual = f(testcase.pairs, testcase.match).first assert(actual == testcase.expected, "Testcase #\(caseNumber) \((testcase.pairs, testcase.match)) failed. Got \(String(reflecting: actual)), but expected \(testcase.expected)!") print("Testcase #\(caseNumber) passed!") } ``` [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 30 bytes ``` {_?~A=G|_X]_?~A=;|Z=B]~B=C|Z=A ``` QBIC isn't strong on lists and tuples. The above code takes `a` as a command line parameter, then asks for user input in pairs for the tuples. When an empty element is given, it outputs `b`. # Sample run ``` Command line: Even I'm So Meta Even This Acronym Meta ``` # Explanation ``` { DO infinitely _? Ask for part 1 of tuple, A$ ~A=G| ] IF A$ is empty (equal to G$, which is undefined and therefore "") THEN _X Quit _? Ask for part 2 of tuple, B$ ~A=;| IF part 1 of the tuple equals teh cmd line param (loaded in as C$) THEN Z=B] set Z$ to part 2 of the tuple (Z$ gets printed when QBIC quits) ~B=C|Z=A IF part 2 of the tuple matches input, set Z$ to part 1 The final IF and the DO loop are closed implicitly ``` ## Alternative version, 22 bytes ``` {_?_?~A=;|_XB]~B=C|_XA ``` This basically does the same as the longer version, but immediately quits when it finds a match. I've listed this as the alternative, because you can't input all tuples into this program given that it quits early. [Answer] # [Arturo](https://arturo-lang.io), 32 bytes ``` $[a,s][--select.n:1a=>[in? s&]s] ``` [Try it](http://arturo-lang.io/playground?Lq5Mzm) [Answer] # Mathematica, 50 bytes ``` (t={#2};Select[Complement[#,t]&/@#,Length@#==1&])& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfo8S2Wtmo1jo4NSc1uSTaOT@3ICc1NzWvJFpZpyRWTd9BWccnNS@9JMNB2dbWUC1WU@1/QFFmXomCQ1p0dbVSopKOglKSUq2OQrVSMoidAmGngthpSrW1YCr2PwA "Mathics – Try It Online") [Answer] # Ruby, 31 bytes ``` ->a,e{e=*e;a.find{|p|p!=p-e}-e} ``` Returns a singleton array. [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 21 bytes ``` [:$revmap,KeyArray\#] ``` [Try it online!](https://tio.run/##TZAxa8MwEIV3/YoHKZwUQoaOTluSoUMondrN8aA4Z5y2toykBEzpb3dPtlMqENLdfe@ddCHa8pNPw5Bnd56vje1WL9zvvLf9YVEM26xSSi/ReY6xR@QQUV3aMp5di6VR@WKFDOv1GhUOEIfOQzxA2Mj@cOdW0mN2JfHj0y3pLrHANkt@amwwOpc2cNjAVYg1o3K@AQW2vqwJOl66LzapqdIKoB/CvLQmTSBDBpq@KZXSLZdbQcYk@PnKLd3gPVEjtTc3Yq8cLc1Eit/rc5B4V3rX9s2s3/1vtk/iSZuEkypJZnj8Bs1w@hjdcom0niWWIc700bnu72nBnqR4ZO5GdqpNh9DK4H7xgDzNO/kWaGXYwy8 "Stacked – Try It Online") This takes input from the the stack and leaves output on the stack. Expanded, this looks like: ``` [ : $rev map , KeyArray \ # ] ``` ## Explanation Let's take `(('sad' 'beep') ('boop' 'boop'))` and `'boop'` as the input. Then, an array like so is constructed by `:$revmap,`: ``` (( 'sad' 'beep') ('boop' 'boop') ('beep' 'sad') ('boop' 'boop')) ``` That is, a copy of the array is map, each member is reversed, and the two are concatenated together. `KeyArray` in turn makes a hash out of the values given, like so: ``` KeyArray [ sad => beep, boop => boop, beep => sad, boop => boop ] ``` Then, `\` brings the search string to the top of the stack, and obtains the key from the KeyArray that matches with `#`. This returns only one value, so the duplicate key in the KeyArray does not need to be worried about. ## Other approaches 32 bytes: (input from stack, output to STDOUT) `[@x:$revmap,uniq[...x=$out*]map]` 36 bytes: `{%x[y index#+]YES 0# :y neq keep 0#}` 38 bytes: `[@x:$revmap#,[KeyArray x#]map:keep 0#]` 46 bytes: `[@x:KeyArray\$revmap KeyArray,[x#]map:keep 0#]` [Answer] # Excel, 18 Bytes Anonymous Excel Workbook Formula that takes input as `<Lookup Value>` from range `A1`, `<Key Array>` from range `B:B` and `<Def Array>` from range `C:C`, and outputs the value of the definition associated with the lookup value to the calling cell ``` =VLOOKUP(A1,B:C,2) ``` Sample I/O shall be included when possible ]
[Question] [ You will be given a String that only contains letters of the English Alphabet, both lowercase and uppercase (ASCII 65-90 and 97-122). Your task is to output the Fizz-Buzzified version of the String. ### How to Fizz-Buzzify a String? * Each letter that has an even index in the English alphabet (the alphabet **must** be 1-indexed: `a->1,b->2,...,z->26`) will be turned into `fizz` if it is lowercase and `FIZZ` if it is uppercase (`f -> fizz, F -> FIZZ`). * Each letter that has an odd index in the English alphabet will be turned into `buzz` if it is lowercase, and `BUZZ` if it is uppercase (`e -> buzz, E -> BUZZ`). * Let's have an example, to illustrate the algorithm, using the string `CodeGolf` (spaces added for clarity): ``` "C o d e G o l f" -> "BUZZ buzz fizz buzz BUZZ buzz fizz fizz" ^ ^ ^ ^ ^ ^ ^ ^ 1 1 0 1 1 1 0 0 (1 is odd index, 0 is even index) ``` * If it is more convenient for your language, you may also leave *single spaces* between the groups (`fizz, buzz, FIZZ, BUZZ`). Hence, a result like `fizzBUZZbuzzbuzz` can also be returned as `fizz BUZZ buzz buzz`. Other separators are not allowed. --- # Test Cases: ``` Input -> Output "egg" -> "buzzbuzzbuzz" "CodeGolf" -> "BUZZbuzzfizzbuzzBUZZbuzzfizzfizz" "Reset" -> "FIZZbuzzbuzzbuzzfizz" "ATOM" -> "BUZZFIZZBUZZBUZZ" "yOuArEgReAt" -> "buzzBUZZbuzzBUZZfizzBUZZbuzzFIZZbuzzBUZZfizz" ``` --- * [Any standard method for I/O](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) can be used. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * You are only allowed to take input in your language's native String type. The same applies for output. * You can assume that the input will not be empty. * Shortest code in bytes in every language wins. Good Luck and Fizz-Buzz! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~26~~ 24 bytes ``` FθF⎇﹪℅ι²buzz¦fizz⎇№αι↥κκ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nmXndgCJR33t73euetTSem7noU1JpVVVh5alZVZVAYUftUw7t/HczkdtS8/tOrfr/383oLATUAEA "Charcoal – Try It Online") Originally inspired by @CarlosAlejo. Edit: Saved 2 bytes by looping over the letters of fizz/buzz instead of assigning to a temporary. Explanation: ``` Fθ Loop over the input (i = loop variable) F Choose and loop over the word (k = loop variable) ⎇ Ternary ﹪℅ι² If i has an odd ASCII code buzz fizz Print (implicit) ⎇ Ternary №αι If i is an uppercase letter ↥κ Uppercase(k) κ k ``` [Answer] # C#, 92 bytes ``` using System.Linq;a=>string.Concat(a.Select(x=>x%2<1?x<97?"FIZZ":"fizz":x<97?"BUZZ":"buzz")) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~73~~ 69 bytes 4 bytes thanks to ovs. ``` lambda s:"".join("fbFBiuIUzzZZzzZZ"[(c<"a")*2+ord(c)%2::4]for c in s) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYSklJLys/M09DKS3JzSmz1DO0qioqCoSVojWSbZQSlTS1jLTzi1I0kjVVjaysTGLT8osUkhUy8xSKNf8XFGXmlWikaSilpqcraWpywfnO@Smp7vk5aSiCQanFqSUoIo4h/r4oApX@pY5FrulBqY4ghf8B "Python 3 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 75 bytes ``` f(char*s){for(;*s;++s)printf(*s>90?*s%2?"buzz":"fizz":*s%2?"BUZZ":"FIZZ");} ``` [Try it online!](https://tio.run/##VYxBC4IwHMXP7VPIQNimgnirgWJR0SEEqUs3W5sJpeJUSPGz/zP10rs83o/HTzipEACKiGdSMU17VVSEM80tS9OyyvJaEab9tRswbXoBvjddhzdYZb@a0fZ6u43ocBqL8gHeSZYTYbd0UrKW9wgZY2azZbWc9mi1uLHpudpwfAPbrKV8Ok5n8jfLptYE44UMCA0AMk1hVzzksXgpiKWWNYSX6AyfqAmrfRrLsP4C "C (gcc) – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~105~~ ~~100~~ ~~94~~ ~~91~~ 90 bytes ``` s->{for(int i:s.getBytes())System.out.print(i%2<1?i>90?"fizz":"FIZZ":i>90?"buzz":"BUZZ");} ``` [Try it online!](https://tio.run/##lY4xa8MwEIV3/4rDUJCHiKZbndTBCW3pEAJJu6R0UGxJyLElY50CTvBvd4VjKHTzLQffe@/eFezCZqbmusjPfe1OpcogK5m1sGVKwy0AGKlFhn5djMqh8ho5YKO0/P4B1kgbDVaAwt@jDlVJhdMZKqPpxmjrKt4s74EExEtvZ8lNmIYojaBiSyXHdYvckig6tBZ5RY1DWns/EvXwtJyvVPL8uAqFul7DOHz7OB7D@I5ObkDrL4@iRdfDMItgeEdQlmW8RhJyKb08wP8NpSaj8mffmJy/m1JMyey55TglkH7utlP87c6lzavc83Ss6YKu/wU "Java (OpenJDK 8) – Try It Online") Much golfable, very bytes, so Java! Very golfed by @KevinCruijssen by 9 bytes! [Answer] # [Plain English](https://github.com/Folds/english), ~~820~~ ~~632~~ 610 bytes [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487) suggested eliminating an unneeded error trap, which saved 22 bytes. ``` A fizzy string is a string. To convert a s string to a z fizzy string: Clear the z. Slap a r rider on the s. Loop. If the r's source's first is greater than the r's source's last, exit. Put the r's source's first's target in a b byte. If the b is not any letter, bump the r; repeat. Put "FIZZ" in a t string. If the b is d, put "BUZZ" in the t. If the b is _, lowercase the t. Append the t to the z. Bump the r. Repeat. To decide if a b byte is d: Put the b in a n number. If the n is odd, say yes. Say no. To decide if a b byte is _: Put the b in a c byte. Lowercase the c. If the c is the b, say yes. Say no. ``` Ungolfed code: ``` A fizzy string is a string. To convert a string to a fizzy string: Clear the fizzy string. Slap a rider on the string. Loop. If the rider's source's first is greater than the rider's source's last, exit. Put the rider's source's first's target in a byte. If the byte is not any letter, bump the rider; repeat. Put "FIZZ" in another string. If the byte is odd, put "BUZZ" in the other string. If the byte is lower case, lowercase the other string. Append the other string to the fizzy string. Bump the rider. Repeat. To decide if a byte is odd: Put the byte in a number. If the number is odd, say yes. Say no. To decide if a byte is lower case: Privatize the byte. Lowercase the byte. If the byte is the original byte, say yes. Say no. ``` The Plain English IDE is available at [github.com/Folds/english](https://github.com/Folds/english). The IDE runs on Windows. It compiles to 32-bit x86 code. [Answer] ## JavaScript (ES6), ~~79~~ 77 bytes ``` s=>s.replace(/./g,c=>['BUZZ','buzz','FIZZ','fizz'][parseInt(c,36)%2*2|c>'Z']) ``` ### Test cases ``` let f = s=>s.replace(/./g,c=>['BUZZ','buzz','FIZZ','fizz'][parseInt(c,36)%2*2|c>'Z']) console.log(f("egg" )) // "buzzbuzzbuzz" console.log(f("CodeGolf" )) // "BUZZbuzzfizzbuzzBUZZbuzzfizzfizz" console.log(f("Reset" )) // "FIZZbuzzbuzzbuzzfizz" console.log(f("ATOM" )) // "BUZZFIZZBUZZBUZZ" console.log(f("yOuArEgReAt")) // "buzzBUZZbuzzBUZZfizzBUZZbuzzFIZZbuzzBUZZfizz" ``` [Answer] # C#, 97 bytes ``` using System.Linq;s=>string.Concat(s.Select(c=>"fizzbuzzFIZZBUZZ".Substring(c%2*4+(c>96?0:8),2))) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes ``` “=%“Ƈ×»ẋ13Œu;$ɓØWiЀị ``` [Try it online!](https://tio.run/##ATMAzP9qZWxsef//4oCcPSXigJzGh8OXwrvhuosxM8WSdTskyZPDmFdpw5Digqzhu4v///9lZ2c "Jelly – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~23~~ 21 bytes ``` smr<d\a@c"fizzbuzz"4C ``` [Test suite](http://pyth.herokuapp.com/?code=smr%3Cd%5Ca%40c%22fizzbuzz%224C&test_suite=1&test_suite_input=%22egg%22%0A%22CodeGolf%22%0A%22Reset%22%0A%22ATOM%22%0A%22yOuArEgReAt%22&debug=0). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 40 36 bytes ``` Fθ¿№αι¿﹪⌕αι²FIZZ¦BUZZ¿﹪⌕βι²fizz¦buzz ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nmXndhza/6hl2rmN53Ye2v9@56pHPVPB7E1unlFRh5Y5hQJJmPgmkHhaZlXVoWVJpVVV//8756ekuufnpAEA "Charcoal – Try It Online") Explanation: ``` Fθ for every char i in the input: ¿№αι if i is found in the uppercase alphabet ¿﹪⌕αι² if i is an even uppercase char FIZZ¦BUZZ print "FIZZ" or else "BUZZ" ¿﹪⌕βι² if i is an even lowercase char fizz¦buzz print "fizz" or else "buzz" ``` An alternative with the same byte count: ``` AfizzφAbuzzχFθ¿№αι¿﹪⌕αι²↥φ↥χ¿﹪⌕βι²φχ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9noVpmVVV59uAjKRSIKP9/Z5l53Yc2v@oZdq5jed2Htr/fueqRz1TwexNj9qWnm8DEe1w8U0g8fNt59v//3fOT0l1z89JAwA "Charcoal – Try It Online") ([Verbose version](https://tio.run/##Zc69DsIgEMDxvU9x6cQldHHtZJroZOLiA1DglIRwFcShL49I/Eoc@d3dP@iLipqVL2WbkjsH0ZNb114C4di9ac6NdCXiCOKKHYAjEBPncBNKOsT2PrDJnsXOBdNUburgGF1dOi2LjVolKwhx/ENd8RX9jczPCHwr9DmtnyllYmP37KkM9zIk/wA)) * 4 bytes saved thanks to Neil! [Answer] ## [><>](https://esolangs.org/wiki/Fish), 68 bytes ``` <vv?("^"$%2:;?(0:i v\?\"zzif" v \\"zzub" v \ "ZZIF" v \"ZZUB" \oooo ``` [Try it online](https://tio.run/##S8sszvj/36aszF5DKU5JRdXIytpew8Aqk6ssxj5GqaoqM02Jq0whBsQsTQIzFZSiojzdQEyFGCAz1EmJKyYfCP7/D0vNKUstcUrNyan0ScwrSS3KK85ILMoGAA "><> – Try It Online"), or watch it at the [fish playground](https://fishlanguage.com/playground)! (But look at [Aaron's answer](https://codegolf.stackexchange.com/a/128653/66104) which is 13 bytes shorter!) If you're not familiar with ><>, there's a fish that swims through the code in 2D, and the edges wrap. The symbols `>`, `<`, `^` and `v` set the direction of the fish, `/` and `\` are mirrors that reflect it, and `?` means "do the next instruction if the top thing on the stack is non-zero, otherwise jump over the next instruction". In the first line, the fish takes a character of input (`i`); if it's -1 for EOF, it halts (`:0(?;`); it gets the charcode mod 2 (`:2%$`); and it pushes a 1 or 0 on the stack depending on whether the charcode is less than or greater than the charcode of "^" (`"^"(`). The next three lines redirect the fish to the right fizz/buzz string, then the last line prints it (one `o` for each character) and sends the fish back to the start. [Answer] # [><>](https://esolangs.org/wiki/Fish), 55 bytes Based on Not a tree's [answer](https://codegolf.stackexchange.com/a/128636/41881). ``` <v%2$)"^":;?(0:i \?v"ZZIF" ~v >"ZZUB"! ^>{:}" "*+ol1=? ``` Instead of representing the 4 possible output in the code, I only represent their capitalized versions and add 32 to the character code to get the small case equivalents. [Try it online !](https://tio.run/##S8sszvj/36ZM1UhFUylOycraXsPAKpNLIca@TCkqytNNiauuTMEOyAx1UlLkirOrtqpVUlDS0s7PMbS1///fOT8l1T0/Jw0A) Modified code for the [online interpreter](https://fishlanguage.com/playground), which pads its codespace with empty cells : ``` <v%2$)"^":;?(0:i \?v"ZZIF" ~v >"ZZUB" ! ^>{:}" "*+o l1=? ``` [Answer] # [Perl5](http://www.perl.org/), 50+1 bytes ``` perl -nE'say+((FIZZ,BUZZ)x48,(fizz,buzz)x16)[unpack"C*",$_]' ``` Creates a 128-item list that maps ASCII chars to the proper code word. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes ``` v‘FIZZÒÖ‘#yÇÉèAyåil}J? ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/7FHDDDfPqKjDkw5PAzKVKw@3H@48vMKx8vDSzJxaL/v//yv9Sx2LXNODUh1LAA "05AB1E – Try It Online") **Explanation** ``` v # for each char y of input string ‘FIZZÒÖ‘# # push the list ['FIZZ','BUZZ'] yÇÉ # check if y has an odd character code è # use this to index into the list Ayåi # if y is a member of the lowercase alphabet l} # convert to lowercase J? # unwrap from list and print ``` **Alternative 22 byte solution** ``` ÇÉAISå·+‘FIZZÒÖ‘#Dl«èJ ``` [Answer] # [PHP](https://php.net/), 67 bytes ``` for(;$c=$argn[$i++];)echo[FIZZ,BUZZ,fizz,buzz][ord($c)%2+2*($c>Z)]; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6vknJ@S6p6fk6Zk/T8tv0jDWiXZFiwTrZKprR1rrZmanJEf7eYZFaXjFAok0jKrqnSSSquqYqPzi1I0VJI1VY20jbSADLsozVjr//8B "PHP – Try It Online") [Answer] # [F#](http://fsharp.org/), ~~154~~ ~~153~~ 145 bytes saved ~~1~~ 9 bytes thanks to [@Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) ``` let g s= Seq.map(fun c->match int c with |x when x>64&&x<91->if x%2=0 then"FIZZ"else"BUZZ" |x->if x%2=0 then"fizz"else"buzz")s |>String.concat"" ``` [Try it online!](https://tio.run/##XYvBCoJAFEX3fsXlgWELpSKCIAWDglZB0sadDTPjgI7WPMnCfzepXbtzuOcqF9aNbcaxkgwNF3vI5D2qizZQnYUIEw91waKEsQyBp@HSA4Yez1Ja9MlmPZv1u@0yTIxC76/iBXha6HjKc5KVk7S/ToTv6T9S5v3@RbduornzMCQZP4zVkWisKBhEYzs5KwvyHSHQoNe5Sx8HfZEp03z8AA "F# (Mono) – Try It Online") [Answer] # Mathematica, 134 bytes ``` ""<>{(s=Max@ToCharacterCode@#;If[96<s<123,If[EvenQ@s,c="fizz",c="buzz"]];If[64<s<91,If[EvenQ@s,c="FIZZ",c="BUZZ"]];c)&/@Characters@#}& ``` [Answer] # Java 8, 89 bytes ``` s->s.chars().mapToObj(i->i%2<1?i>90?"fizz":"FIZZ":i>90?"buzz":"BUZZ").collect(joining()); ``` It assumes `import static java.util.stream.Collectors.*;` [Answer] # q/kdb+, 48 bytes **Solution:** ``` raze{@[($)`fizz`buzz x mod 2;(&)x<91;upper]}"i"$ ``` **Examples:** ``` q)raze{@[($)`fizz`buzz x mod 2;(&)x<91;upper]}"i"$"egg" "buzzbuzzbuzz" q)raze{@[($)`fizz`buzz x mod 2;(&)x<91;upper]}"i"$"CodeGolf" "BUZZbuzzfizzbuzzBUZZbuzzfizzfizz" q)raze{@[($)`fizz`buzz x mod 2;(&)x<91;upper]}"i"$"Reset" "FIZZbuzzbuzzbuzzfizz" q)raze{@[($)`fizz`buzz x mod 2;(&)x<91;upper]}"i"$"ATOM" "BUZZFIZZBUZZBUZZ" q)raze{@[($)`fizz`buzz x mod 2;(&)x<91;upper]}"i"$"yOuArEgReAt" "buzzBUZZbuzzBUZZfizzBUZZbuzzFIZZbuzzBUZZfizz" ``` **Explanation:** Fairly straightforward, take the input string, cast into ASCII values, create a list of 1 or 0 depending whether it is odd or even (hint A=65=odd), then use this list to index into a list of `fizz` and `buzz`. Cast this to a string, and then for cases where the input is <91 (lower than a Z) we apply the `upper` function to get a `FIZZ` or a `BUZZ`. q is interpreted right to left: ``` raze{@[string `fizz`buzz x mod 2;where x < 91;upper]}"i"$ / ungolfed version "i"$ / cast input to ascii values { } / anonymous lambda @[ ; ; ] / apply upper / upper-case where x < 91 / indices where input is less than 91 (ie uppercase) x mod 2 / returns 0 if even and 1 if odd `fizz`buzz / 2 item list, which we are indexing into string / cast symbols to strings `buzz -> "buzz" raze / raze (merge) list into a single string ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 61+1 = 62 bytes Uses the `-p` flag. ``` gsub(/./){k=$&.ord%2*4;$&<?_?"FIZZBUZZ"[k,4]:"fizzbuzz"[k,4]} ``` [Try it online!](https://tio.run/##KypNqvyvrFgEpBR0C/6nF5cmaejr6WtWZ9uqqOnlF6WoGmmZWKuo2djH2yu5eUZFOYVGRSlFZ@uYxFoppWVWVSWVVlVB@LX//zvnp6S65@ekAQA "Ruby – Try It Online") [Answer] # [Swift 4](https://swift.org/blog/swift-4-0-release-process/), ~~144~~ 135 bytes ``` func f(s:String){print(s.map{let d=Int(UnicodeScalar("\($0)")!.value);return d%2<1 ?d>90 ?"fizz":"FIZZ":d>90 ?"buzz":"BUZZ"}.joined())} ``` Un-golfed: ``` func f(s:String){ print( s.map{ let d=Int(UnicodeScalar("\($0)")!.value) return d%2 < 1 ? d > 90 ? "fizz" : "FIZZ" : d > 90 ? "buzz" : "BUZZ" }.joined() ) } ``` What I am doing is looping over each character in the string. I convert each to its ASCII value, then check to see if it is even or odd, and then check to see if it is upper or lowercase and output the matching value from the loop. I then join all the elements of the resulting array into a single string and print it. This solution uses Swift 4, so there is no way to easily test it online yet. Thanks to @Mr.Xcoder for saving me 9 bytes! [Answer] ## R, ~~150~~ ~~123~~ 108 bytes ``` i=ifelse cat(i(sapply(el(strsplit(scan(,''),'')),utf8ToInt)>91,i(x%%2,'buzz','fizz'),i(x%%2,'BUZZ','FIZZ'))) ``` ~~Has to be shorter using ASCII?~~ It was shorter. See edit history for old answer, which used `letters`. Checks each letter for (1) whether it's capital or not (`>91`) and whether it's a `fizz` or a `buzz`. ]
[Question] [ # Problem Inspired by a [previous challenge](https://codegolf.stackexchange.com/questions/125383/draw-a-big-slash-x) doing something similar Given positive integer input `n` output a shape that follows this pattern: input `n=1`: ``` * * * * * ``` input `n=2`: ``` ** ** **** ** **** ** ** ``` input `n=3`: ``` *** *** *** *** ***** *** ***** *** *** *** *** ``` and so on... It has these properties: `n*2+1` lines tall the "arms" are `n` wide except when they merge the center line is `n` wide if `n` is even the lines above and below the center are `n*2` wide if `n` is odd the lines above and below the center are `n*2-1` wide # Rules * Trailing newlines accepted * Standard loopholes apply * **Shortest bytes win** * Output may be print out or a string or array of strings # Edits * `n=0` doesn't need to be handled * Trailing spaces allowed [Answer] # [MATL](https://github.com/lmendo/MATL), 16 bytes ``` EQXyG:Y+tP+g42*c ``` [**Try it online!**](https://tio.run/##y00syfn/3zUwotLdKlK7JEA73cRIK/n/f3MA) ### Explanation Consider input `2` as an example. Stack contents are shown with more recent ones below. ``` EQ % Implicitly input n. Push 2*n+1 % STACK: 5 Xy % Identity matrix of that size % STACK: [1 0 0 0 0; 0 1 0 0 0; 0 0 1 0 0; 0 0 0 1 0; 0 0 0 0 1] G: % Push [1 2 ... n] % STACK: [1 0 0 0 0; 0 1 0 0 0; 0 0 1 0 0; 0 0 0 1 0; 0 0 0 0 1], [1 2] Y+ % 2D convolution, extending size % STACK: [1 2 0 0 0 0; 0 1 2 0 0 0; 0 0 1 2 0 0; 0 0 0 1 2 0; 0 0 0 0 1 2] tP+ % Duplicate, flip vertically, add % STACK: [1 2 0 0 2 1; 0 1 2 1 2 0; 0 0 1 4 0 0; 0 1 2 1 2 0; 1 2 0 0 1 2] g % Convert to logical % STACK: [1 1 0 0 1 1; 0 1 1 1 1 0; 0 0 1 1 0 0; 0 1 1 1 1 0; 1 1 0 0 1 1] 42* % Multiply by 42. % STACK: [42 42 0 0 42 42; 0 42 42 42 42 0; 0 0 42 42 0 0; 0 42 42 42 42 0; 42 42 0 0 42 42] c % Convert to char. Char 42 is '*'. Char 0 is displayed as space % STACK: ['** **'; ' **** '; ' ** '; ' **** '; '** **'] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~13~~ 12 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page) Thanks to @ErikTheOutgolfer for a byte ``` FN«PX⁺*×*Iθ→ ``` [Try it online!](https://tio.run/##ASgA1/9jaGFyY29hbP//77ym77yuwqvvvLBY4oG6KsOXKu@8qc644oaS//8y "Charcoal – Try It Online") This is my first ever Charcoal answer, and I'm pretty sure it's not golfed as well as it could be, but I figured I'd start somewhere. ``` FN« # For input() (i in range(0,input())) P # Print X # In an 'X' shape ⁺*×*Iθ # '*'+'*'*int(first_input) → # Move the cursor right one ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` Ḥ‘Ḷ⁶ẋ;€”*ẋ$»Ṛ$Y ``` [Try it online!](https://tio.run/##AS0A0v9qZWxsef//4bik4oCY4bi24oG24bqLO@KCrOKAnSrhuoskwrvhuZokWf///zM "Jelly – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` Å4bS{I·ƒDÂ~„ *èJ,À ``` [Try it online!](https://tio.run/##ASUA2v8wNWFiMWX//8OFNGJTe0nCt8aSRMOCfuKAniAqw6hKLMOA//8z "05AB1E – Try It Online") **Explanation** Example for `n=2` ``` Å4 # push a list of 4s with length as the input # STACK: [4,4] b # convert each to binary # STACK: [100, 100] S{ # split into digit list and sort # STACK: [0, 0, 0, 0, 1, 1] I·ƒ # input*2+1 times do D # duplicate top of stack # 1st iteration: [0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1] # 2nd iteration: [0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0] # 3rd iteration: [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0] Â~ # or each item in the duplicate with its reverse # 1st iteration: [0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 1, 1] # 2nd iteration: [0, 0, 0, 1, 1, 0], [0, 1, 1, 1, 1, 0] # 3rd iteration: [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0] „ *èJ # use the resulting binary list to index into the string " *" # 1st iteration: [0, 0, 0, 0, 1, 1], "** **" # 2nd iteration: [0, 0, 0, 1, 1, 0], " **** " # 3rd iteration: [0, 0, 1, 1, 0, 0], " ** " , # print À # rotate list left ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~18~~ 17 bytes Saved a byte thanks to @DJMcMayhem's input trick. ``` Àé*ÄJÀälÀñ2ÙÀl2x> ``` [Try it online!](https://tio.run/##K/v//3DD4ZVah1u8gPSSHCCx0ejwzMMNOUYVdv///7cEAA "V – Try It Online") Explanation ``` Àé*ÄJÀäl ``` This inserts `[n]*'*'+[n]*' '+[n]*'*'` ``` Àñ ' [arg] times 2Ù ' Duplicate the current line down twice Àl ' Move right [arg] times 2x ' Delete two characters > ' Indent this line one space ``` Each iteration of the loop the buffer goes from ``` |** *** ``` To ``` *** *** |** *** *** *** ``` Where `|` is the cursor with a `*` under it [Answer] # [V](https://github.com/DJMcMayhem/V), 23 bytes ``` Àé*ÄJÀälÀñÙãlxx>ñyHæGVp ``` [Try it online!](https://tio.run/##K/v//3DD4ZVah1u8gPSSHCCx8fDMw4tzKirsDm@s9Di8zD2s4P///xYA "V – Try It Online") Hexdump: ``` 00000000: c0e9 2ac4 4ac0 e46c c0f1 d9e3 6c78 783e ..*.J..l....lxx> 00000010: f179 48e6 4756 70 .yH.GVp ``` For whatever reason, this challenge is significantly harder in V than the last one. Since our general approach of *n times, grow an 'x'* won't work here, we'll instead construct the top of the X, copy it and flip it, then attaching the two parts together. Explanation: ``` Àé*ÄJÀäl " Insert ('*' * n) + (' ' * n) + ('*' * n) " The obvious way would be 'Àé*ÀÁ ÀÁ*', but this " non-obvious way saves us a byte Àñ ñ " 'n' times: Ù " Duplicate this line (below us) ãl " Move to the center of this line xx " Delete two characters > " And indent this line with one space. ``` Doing the indent at the *end* of the loop, allows us to [take advantage of implicit endings](https://codegolf.stackexchange.com/a/124600/31716). This also conveniently creates *n+1* lines, which is exactly the top half of the 'X'. Let's say the input was 4. Then at this point, the buffer looks like this: ``` **** **** **** **** ******** ****** **** ``` And we're on the last line. So then we: ``` yH " Copy the whole buffer and move to the first line æG " Reverse every line Vp " And paste what we just copied *over* the current " line, deleting it in the process ``` [Answer] # C#, 139 130 115 bytes -1 byte by creating a string and calling `WriteLine`, thus saving the check for the new line. -6 bytes thanks to Kevin and his master golfing techniques! -2 bytes by replacing `n*3-n` with `n*2`. -15 bytes after Kevin kindly pointed me in the right direction: I can just return the string instead of printing it, thus saving the call to `System.Console.WriteLine()`. And some other tips also... ``` n=>{var s="";for(int i,j=0;j<=n*2;j++,s+='\n')for(i=0;i<n*3;)s+=i>=j&i<j+n|i<=n*3-j-1&i++>=n*2-j?'*':' ';return s;} ``` [Try it online!](https://tio.run/##jc5NS8NAEAbge37FkEPzsUmxDYK42XgQvIggeuhBPSzbTZilnYXdbaHU/PaYaE@CmPc487zDKF8q6/SgdtJ7eHa2c3IP5wjG@CADKjha3MKTREp9cEjd2wdI1/nsoqa8nnzQ@@XDgVSNFIof2EALAgYSzfkoHXgRx7y1Lh0FYGHEFTe1oHzNDWOFZyJ@pzj7BuMKa8orno1jbIRZYG0YfeLkq9KUqwUy1kzl0twleXKbQMKdDgdH4Hk/8Oj3b/eWvN3p5cZh0GmbrrKM/2fWM0w1w1zPMDeT@Qu9aLl91Kf0cqaP@uEL) Ungolfed: ``` class Program { static void Main(string[] args) { System.Func<int, string> g = n => { var s = ""; for (int i, j = 0; j <= n*2; j++, s += '\n') for (i = 0; i < n*3;) s += i >= j & i < j+n | i <= n*3-j-1 & i++ >= n*2-j ? '*' : ' '; return s; }; System.Console.Write(f(1)); System.Console.Write(f(2)); System.Console.Write(f(3)); System.Console.Write(f(5)); System.Console.Write(f(8)); System.Console.ReadKey(); } } ``` It just iterates along the rows and columns of the space needed to print the big X and prints either a `'*'` or a `' '` depending on the condition. [Answer] # [Haskell](https://www.haskell.org/), 88 87 86 bytes -1 thanks to @Laikoni ``` (!)=replicate x n=[zipWith max(reverse m)m|m<-[i!' '++n!'*'++(n*2-i)!' '|i<-[0..n*2]]] ``` [Try it online!](https://tio.run/##FcmxCsMgEIDhvU9xTmpCQmnX@gbplKFDkCLlIEc9EWODlLy7tdMP37@67Y3e16qENgmjp5fLeCoQzPKl@KC8AruiEu6YNgTWfPBtWEhIkH0fhOxaVOguA@m/HdTueRybWGsrOwqGXbw/IX7ynNMUQBW46voD "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ ~~23~~ 16 bytes ``` Ḥ‘Ḷ⁸+þṬ+Ṛ$a”*o⁶Y ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//4bik4oCY4bi24oG4K8O@4bmsK@G5miRh4oCdKm/igbZZ////Mw "Jelly – Try It Online") [Answer] # MATLAB, 153 126 bytes (17.6%↓) Thanks to @LuisMendo's comment, function `disp()` can output chars without single quotes, thus I could prevent using `fprintf` with `formats` and omit a few bytes. Besides, his comment reminds me that I need use `char(32)` to present a space rather than `char(0)` (null). ``` n=input('') r=2*n+1 c=3*n a=0 for i=0:n-1 a=a+[zeros(r,i),diag(1:r),zeros(r,c-r-i)]; end a((a+flipud(a))>0)=10 disp([a+32 '']) ``` [Try it online!](https://www.jdoodle.com/a/3Np) ### MATLAB, 153 bytes ``` n=input('') r=2*n+1 c=3*n a=0 for i=0:n-1 a=a+[zeros(r,i),diag(1:r),zeros(r,c-r-i)]; end a((a+flipud(a))>0)=42 fprintf([repmat('%c',1,c),'\n'],char(a)') ``` Result example: n=10 ``` ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ******************** ****************** **************** ************** ************ ********** ************ ************** **************** ****************** ******************** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~93~~ ~~90~~ ~~89~~ 83 bytes -3 bytes thanks to Leaky Nun -1 byte thanks to Zachary T -6 bytes thanks to xnor ``` n=input() x=n*'*'+n*' ' exec"print`map(max,x,x[::-1])`[2::5];x=' '+x[:-1];"*(n-~n) ``` [Try it online!][TIO-j3xwsktf] Starts with a string like `'*** '` for `n=3`, applying `map/max` to pick the `*` over the spaces for each position, then append a space and remove the last character from the string and do this all again. [Answer] # [Haskell](https://www.haskell.org/), 70 bytes ``` f n=[[last$' ':['*'|y<-[1..n],(c-n-y)^2==r^2]|c<-[1..3*n]]|r<-[-n..n]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6OiexuERFXUHdKlpdS72m0kY32lBPLy9WRyNZN0@3UjPOyNa2KM4otiYZImOslRcbW1ME5OjmgdTF/s9NzMxTsFXITSzwVSgoLQkuKfLJU1BRSFMw/Q8A "Haskell – Try It Online") Outputs a list of strings. For each position of row `r`, column `c`, uses a formula to determine whether it falls in one of the two diagonal bands and so is `*`. [Answer] # Javascript (ES2017), ~~155~~ 157 bytes ``` n=>[...e=[...Array(n+1)].map((a,i)=>[...d=((b=''.padEnd(n))[c='slice'](i)+'*'.repeat(n)+b[c](0,i))[c](n/2)].reverse().join``+d[c](n%1)),...e.reverse()[c](1)] ``` Returns an array of strings. I perform operations on arrays then mirror it. This could probably be optimized with matrices like the other answers, but I wanted to be unique. Edit: As pointed out by Neil, for even values of `n`, the center line was not `n` wide, so I added a modulus to detect even/odd when slicing the column. ``` n=5 ['***** *****', ' ***** ***** ', ' ***** ***** ', ' ********* ', ' ******* ', ' ***** ', ' ******* ', ' ********* ', ' ***** ***** ', ' ***** ***** ', '***** *****'] ``` **Ungolfed** ``` n => { e = [...Array(n+1)].map((a, i) => { // Create and iterate over array with n+1 elements b = ''.padEnd(n) // String of n spaces d = (b.slice(i) + '*'.repeat(n) + b.slice(0, i)).slice(n/2) // Create row string return [...d].reverse().join`` + d.slice(1) // Mirror and combine row horizontally }) return [...e,...e.reverse().slice(1)] // Mirror and combine vertically } ``` **Quadrant** ``` n=5 ***** ***** ***** ***** **** *** ``` **Mirrored Horizontally** ``` n=5 ***** ***** ***** ***** ***** ***** ********* ******* ***** ``` **Mirrored Vertically** ``` n=5 ***** ***** ***** ***** ***** ***** ********* ******* ***** ******* ********* ***** ***** ***** ***** ***** ***** ``` [Answer] # Java 10, ~~119~~ ~~118~~ 111 bytes ``` n->{var r="";for(int i=0,j;i<n-~n;i++,r+="\n")for(j=0;j<n*3;r+=j>=i&j<i+n|j<n*3-i&++j>n*2-i?"*":" ");return r;} ``` Port from [*@CarlosAlejo*'s amazing C# answer](https://codegolf.stackexchange.com/a/126277/52210), after I helped him golf a few things. **So make sure to upvote him as well!** -4 bytes thanks to *@ceilingcat*. [Try it here.](https://tio.run/##RY/BasMwDIbvewrhQ4njJnQb7DDF6RO0lx23Hbw0HfJSpThOYHTZq2dqUhjIAv@S4Pu8G1zmD19T1biug50jvtwBEMc6HF1Vw/76BXiJgfgTqkQmwBolHOVJddFFqmAPDBYmzsrL4AIEqxQe2zDvk92sPVLB2S8jGbMOxqo3Vvq64O0GfcHpI0rqS0srX5DhnznLaGWMLzl9yGirUvWsQGkMdewDQ8BxwgXi3H80AnFjGVo6wElUkgX79R2cXjz@ke4RqHiSZoyeRyL53cX6lLd9zM9yFxtOOBdlffMdpz8) [Answer] # Mathematica, 148 bytes ``` T=Table;(a=Join[T[T["*",i],{i,(n=#)+2,2n,2}],T[Join[t=T["*",n],T[" ",y],t],{y,1,n,2}]];Column[Row/@Join[Reverse@a,{T["*",n]},a],Alignment->Center])& ``` [Answer] ## R, 102 bytes Code: ``` n=scan();x=matrix(" ",M<-3*n,N<-2*n+1);for(i in 1:N)x[c(i-1+1:n,M+2-i-1:n),i]="*";cat(x,sep="",fill=M) ``` Test: ``` > n=scan();x=matrix(" ",M<-3*n,N<-2*n+1);for(i in 1:N)x[c(i-1+1:n,M+2-i-1:n),i]="*";cat(x,sep="",fill=M) 1: 10 2: Read 1 item ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ******************** ****************** **************** ************** ************ ********** ************ ************** **************** ****************** ******************** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ``` [Answer] ## CJam, 24 bytes ``` {:T2*){S*T'**+}%_W%..e>} ``` This is a block that takes a number from the stack and outputs a list of lines to the stack. ### Explanation: ``` { e# Stack: | 2 :T e# Store in T: | 2, T=2 2* e# Multiply by 2: | 4 ) e# Increment: | 5 { e# Map over range: | [0 S e# Push space: | [0 " " * e# Repeat string: | ["" T e# Push T: | ["" 2 '* e# Push char '*': | ["" 2 '* * e# Repeat char: | ["" "**" + e# Concatenate: | ["**" }% e# End: | ["**" " **" " **" " **" " **"] _ e# Duplicate: | ["**" " **" " **" " **" " **"] ["**" " **" " **" " **" " **"] W% e# Reverse: | ["**" " **" " **" " **" " **"] [" **" " **" " **" " **" "**"] ..e> e# Overlay: | ["** **" " ****" " **" " ****" "** **"] } e# End ``` [Answer] # **Python 2**, 110 bytes ``` x=a=0 n=c=input() while x<2*n+1: print ' '*a+'*'*n+' '*c+'*'*(2*n-2*a-c) x+=1 a=n-abs(n-x) c=max(0, n-2*a) ``` This program breaks each line into 4 parts, first spaces, first stars, second spaces and then second stars. For each horizontal line of the X it calculates how many stars or spaces are needed for each of the 4 sections of the line, then constructs and prints that string. [Answer] # [Retina](https://github.com/m-ender/retina), 144 bytes ``` .+ $&$* $&$* $& $`#$'¶ ¶\d+$ ( *)#( *)(\d+) $1$3$**$2#$3$* #$2$3$**$1 ( +)(\*+)( *)(# +#)\3\2\3 + $3$2$1$4$1$2$3 +` (# +#) $1 +` #... # ## ``` [Try it online!](https://tio.run/##NYwxCgMxDAT7fYVgl@RsgeHsPMfFBZIiTYqQt90D7mOOzJFCIwZG@jy/r/d9jOIwXZT/gEEbdT12HHt/uIDFcuLEEp6gVU05q3Juo@rpa4QeTQ7MmOZMvfXamzmiqXF5i4kevtkZxDubxlIKCBJjtB8 "Retina – Try It Online") Explanation: ``` .+ $&$* $&$* $& ``` Add 2n+1 spaces before the input value (one for each output line). ``` $`#$'¶ ``` Replace each space with a `#` and collect the results. This gives a diagonal line of `#`s, space padded on both sides, with the input value suffixed. ``` ¶\d+$ ``` Delete the original input value, as we now have a copy on each line. ``` ( *)#( *)(\d+) $1$3$**$2#$3$* #$2$3$**$1 ``` Build up two diagonal lines of n `*`s, with a separator column of `n` spaces wrapped in a pair of `#`s. ``` ( +)(\*+)( *)(# +#)\3\2\3 + $3$2$1$4$1$2$3 ``` On those lines where the `*`s are nearer the middle, swap the two halves around. This gives an appearance resembling `> | | <`. ``` +` (# +#) $1 ``` Move the `| |`s as far left as they will go, giving a sort of `>> > <` appearance. ``` +` #... # ``` For each space between the `#`s, delete the three following characters. This joins the `> <` into an `X`. ``` ## ``` Delete the now unnecessary `#`s. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ENI>1})¦'*…×82SΛ ``` [Try it online.](https://tio.run/##yy9OTMpM/f/f1c/TzrBW89Ayda1HDcsOT7cwCj43@/9/YwA) **Explanation:** ``` E # Loop N in the range [1, (implicit) input]: N # Push loop-index N I> # Push the input, and increase it by 1 1 # Push 1 }) # After the loop: wrap all values on the stack into a list ¦ # And remove the very first 1 '* '# Push "*" …×82S # Push "×82" as list: ["×",8,2] Λ # Use the Canvas builtin with these three arguments # (after which it is output implicitly) ``` *Canvas explanation:* The Canvas builtin takes three arguments: 1. The lengths of the lines to 'draw', which in this case is the list we generate at the start with the loop. For an input \$n=3\$, the list will look like this: \$[4,1,2,4,1,3,4,1]\$ (or more in general: for sequence \$x\_n\$ in \$[2,n]\$, the list will be \$[n+1,1,x\_1,n+1,1,x\_2,n+1,1,x\_3,...]\$). 2. The string to 'draw', which in this case is `"*"`. 3. The directions, which in this case is `["×",8,2]`. These will be the directions `[cross, reset-to-origin, →]`. With these arguments, it will draw as follows (let's take the \$n=3\$ as example again): ``` Draw an X-shaped cross of character "*" with arms of length 4: * * * * * * * * * * * * * Reset back to the origin (8), and draw 2-1 characters "*" in direction 2 (→): (NOTE: The origin is the center of this first cross.) * * * * * * ** * * * * * * Draw an X-shaped cross of character "*" with arms of length 4 again: ** ** ** ** **** ** **** ** ** ** ** Reset back to the origin (8), and draw 3-1 characters "*" in direction 2 (→): ** ** ** ** **** *** **** ** ** ** ** Draw an X-shaped cross of character "*" with arms of length 4 again: *** *** *** *** ***** *** ***** *** *** *** *** ``` [See this 05AB1E tip of mine for a more in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210) ]
[Question] [ We often see music videos on Youtube. Many Youtube channels that host music videos are "powered by VEVO". Those can be easily identified by both embedding VEVO at their video thumbnails and appending VEVO to their channel name. Now write some code to test whether a string given by user is a VEVO user account or not. Requirements for valid VEVO user account strings: * Must only contain uppercase, lowercase, and digit characters. (no whitespace or punctuation) * Must not exceed 80 characters length. * Must have "VEVO" substring at the end of string Test cases: Valid inputs: ``` AdeleVEVO ConnieTalbotVEVO SHMVEVO justimberlakeVEVO DJMartinJensenVEVO test123VEVO ``` Invalid inputs: ``` syam kapuk jypentertainment Noche de Brujas testVEVO123 ``` Of course, because this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), I'm looking for the shortest code using any programming language. [Answer] # [Python 2](https://docs.python.org/2/), 45 bytes *-3 bytes thanks to Rod. -2 bytes thanks to ovs.* ``` lambda s:len(s)<81*s.isalnum()<'VEVO'==s[-4:] ``` [Try it online!](https://tio.run/##VY89b4NADEB3foU3oGoqJelQoTAkbaUoUtqhVZYkgwlGObjzofMx8Osp0CJRT/bzx5Pr1t8tr7oivXQaTZYjSKKJI4k3L8sHeVKCmhsTxZvw9H76DNNUzovn5Np5Ei@QwjmAPkJp0UCFdVOFj7@kbGtiT86jYtNnE/@wtztBTrBzTYky4eHeYFiu1hPa5qRptP6BV8us6Bt1Zv2cf@2P87JsxCuTkdNY/dt/OxzRecUHYiGedwZ7bx5RcA2CwjpQoBjGN5NxqHaKPRSRirsf "Python 2 – Try It Online") A regex solution turns out to be longer. ``` lambda s:re.match('^[^\W_]{0,76}VEVO$',s) import re ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/) v2.0a0, ~~20~~ 16 bytes Returns `1` for valid or `0` for invalid. `[\l\d]` would also work in place of `[^\W_]` for the same byte count. ``` è/^\w{0,76}VEVO$ ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=6C9eXHd7MCw3Nn1WRVZPJA==&input=InRlc3QxMjNWRVZPIg==) | [Check all test cases](https://ethproductions.github.io/japt/?v=2.0a0&code=y+gvXlx3ezAsNzZ9VkVWTyQ=&input=WyJzeWFtIGthcHVrIiwianlwZW50ZXJ0YWlubWVudCIsIk5vY2hlIGRlIEJydWphcyIsInRlc3RWRVZPMTIzIiwiQWRlbGVWRVZPIiwiQ29ubmllVGFsYm90VkVWTyIsIlNITVZFVk8iLCJqdXN0aW1iZXJsYWtlVkVWTyIsIkRKTWFydGluSmVuc2VuVkVWTyIsInRlc3QxMjNWRVZPIl0KLVE=) **Explanation**: `è` counts the number of matches of the RegEx in the input. In Japt, the `\w` RegEx class doesn't include underscore. [Answer] # JavaScript (ES6), ~~27~~ ~~36~~ ~~34~~ 31 bytes *Saved 2 bytes thanks to @Neil and 3 bytes thanks to @Shaggy* ``` s=>/^[^\W_]{0,76}VEVO$/.test(s) ``` ### Test cases ``` let f = s=>/^[^\W_]{0,76}VEVO$/.test(s) console.log(f('syam kapuk')) // (INVALID) console.log(f('jypentertainment')) // (INVALID) console.log(f('Noche de Brujas')) // (INVALID) console.log(f('testVEVO123')) // (INVALID) console.log(f('AdeleVEVO')) // (VALID) console.log(f('ConnieTalbotVEVO')) // (VALID) console.log(f('SHMVEVO')) // (VALID) console.log(f('justimberlakeVEVO')) // (VALID) console.log(f('DJMartinJensenVEVO')) // (VALID) ``` [Answer] # [PHP](https://php.net/), 51 bytes -10 bytes thanks to @Ismael Miguel for using `<?=` instead of `<?php echo`! and removing the closing tag ``` <?=preg_match("/^[^\W_]{0,76}VEVO$/",fgets(STDIN)); ``` [Try it online!](https://tio.run/##K8go@P/fxt62oCg1PT43sSQ5Q0NJPy46LiY8PrbaQMfcrDbMNcxfRV9JJy09taRYIzjExdNPU9P6///0NJAMAA "PHP – Try It Online") Thanks for the other answers so I didn't have to write the regex! [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 25 bytes ``` ≢'^[^_\W]{0,76}VEVO$'⎕S 3 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HnIvW46Lj4mPDYagMdc7PaMNcwfxX1R31TgxWM//9Pe9Q2Aa8SrnSgimp1IHjUu@pR71YgCWRbKUC4U9OAQrVcXEC1QGXqnn5hjj6eLgolqcUlxeowUXUurnT14srEXIXsxILSbHUgL6uyIDWvJLWoJDEzLxfIAon55SdnpCqkpCo4FZVmJRaDhEDmgBxjaGSszoUwDspwTEnJLMnMz0vMUcBjMcgcA6ABJqZm5haWVGCBHITFNTgd4JiSmpMK0ZSu7pyfl5eZGpKYk5RfAhML9vCFMbNKi0syc5NSi3ISs@F6XLx8E4tKMvO8UvOKU/NgoiCbgA7C4RqksMHpMJhJ1AwdsJkA "APL (Dyalog Unicode) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 83 bytes ``` c,i;f(char*s){for(c=i=0;s[i];c+=!isalnum(s[i++]));c=i<81*!c*!strcmp("VEVO",s+i-4);} ``` [Try it online!](https://tio.run/##fY8/a8MwFMT3fApZUJBsB5q2Q0H10H9QAmmHhixtBkV@bp5tSUaSCyHks7tKh061t@Pux713av6l1DCoHEXF1F661PNjZR1TBRaXwn/gVqisSNDL1vSaRSPLtpyLmN/dLtJEpYkPTumO0c3z5o3mPsP5DRenAU0gWqJh3xZLTo4zQjoXzYrRi/LT0JxE5Q9Sk0Z2fUNj6b9IfejABHAhdumoRsFXq/ZASiAPrq@lH@UC@HD@dXF1Pcrcl9DC76Ax4tEag7CW7c6GSfD9ZTWZ170PqHfgWtlMn3xarqQLaJZgPJhJ9Lwx7vtjTrPhBw "C (gcc) – Try It Online") [Answer] # [Dyalog APL](https://www.dyalog.com/), 47 bytes ``` {0::0⋄(∧/(1(819⌶)t)∊⎕A,⎕D)∧77>≢t←,∘'VEVO'⍣¯1⊢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqAysrg0fdLRqPOpbraxhqWBhaPurZplmi@aij61HfVEcdIOEC5Cw3N7d71LmoBKhF51HHDPUw1zB/9Ue9iw@tN3zUtehR79ZaoHnqaYnZqQpgKa409eLKxFyF7MSC0mwQLyM1Jyc/vjy/KCcFpiCrsiA1ryS1qCQxMy8XyAKJ@eUnZ6QqpKQqOBWVZiUWg4RKUotLQFoMjYxB3LLUsnxq4XyIU4B@BPrL0EBfXRdkg2NKak4qzJFgd8M4zvl5eZmpIYk5SfklMLFgD1@4h0qLSzJzk1KLcoDhABN08fJNLCrJzPNKzStOzYOJUtMXMDNBAQUMJDAXAA "APL (Dyalog Unicode) – Try It Online") A pure regex solution is [32 bytes](https://tio.run/##SyzI0U2pTMzJT///P@1R2wR19UedCzXU4zQ07BXjNWPKNasNdMzNasNcw/xV1B/1TS1SV9cEqlRPS8xOVQCJqnOlqRdXJuYqZCcWlGaDeBmpOTn58eX5RTkpMAVZlQWpeSWpRSWJmXm5QBZIzC8/OSNVISVVwamoNCuxGCRUklpcAtJiaGQM4palluVTC@dDnAL0AdCThgb66rogGxxTUnNSYY4EuxvGcc7Py8tMDUnMScovgYkFe/jCPVRaXJKZm5RalAMMB5igi5dvYlFJZp5Xal5xah5MlJq@gJkJCihgIIG5AA), but also is much more boring than this approach. ``` {0::0⋄(∧/(1(819⌶)t)∊⎕A,⎕D)∧77>≢t←,∘'VEVO'⍣¯1⊢⍵} a dfn with right arg '⍵' 0::0⋄ on error, return 0 ,∘'VEVO' a train that appends VEVO ⍣¯1 apply it -1 times ⍵ on '⍵' and error if impossible (which returns 0) t← save on variable 't' ≢ get the length of that 77> if that's smaller than 77 ∧ and (1(819I)t) [for each of] 't' uppercased ∊⎕A,⎕D is it in the uppercase alphabet concatenated with the digits ∧/ reduced by and ``` [Answer] # [Grime](https://github.com/iatorm/grime), 13 bytes ``` e`n{-76"VEVO" ``` [Try it online!](https://tio.run/##Sy/KzE39/z81Ia9a19xMKcw1zF/p/38zE9OstKCwdA9vU5AIAA "Grime – Try It Online") Nothing fancy here. Match the `e`ntire input against the pattern: at most 76 alpha`n`umeric characters, followed by the string `VEVO`. Prints `1` for match and `0` for no match. I remembered that the last quote could be removed at end of line, but apparently it just causes a parse error. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/learn/what-is-dotnet), 87 + 18 = 105 bytes [Try it online!](https://tio.run/##lY/BTsMwDIbveYqoB5RILBI3pK67jCEhFQ0BWs9patrQNoHYRZvQnr2kG5M4TAJ8sn/7828bnBkfYBzQupo/7ZCgT9nPSuXWvaeMmU4j8gf2yXgMJE3W8A9vK36vrRPyIB@bU9wOzsyRQlx0yUvvuwV/iRLPOBt1ttCqaCCA2GYL0@ig7jAHIgjrcGNrS2IrpVr6wZGQWaZVDq6m5uKUzK@vYr5yFRaWGpFsVpt1Isd45cl@6R36DlQRLEH8AMTkLhLc6Z63@m1oEynTX8dfByTblxA63cLR5a/U7L9U1J2FZ92VniZomj0LPoKuDpz8fnjP9uMX) ``` a=>a.Where(x=>char.IsLetterOrDigit(x)).Count()==a.Length&a.Length<81&a.EndsWith("VEVO") ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~147~~ 125 bytes ``` !\i:0(?^1[::::::"/9@Z`z"! ;>{(?;{(?v{(?;{(?v{(?;{(?v ~l1-?!v > > !|!: !< ;v ]/~l99*-0(?!;4["OVEV"{-?;{-?;{-?;{-?;1n ``` [Try it online!](https://tio.run/##S8sszvj/XzEm08pAwz7OMNoKDJT0LR2iEqqUFLms7ao17K2BuAyd5lKoyzHUtVcsU7BTgAA7BcUaRSsFRRsu6zIQP1a/LsfSUksXaLKitUm0kn@Ya5hStS5QOxI2zPv/vyS1uMTQyBgo7Q8A "><> – Try It Online") # [><>](https://esolangs.org/wiki/Fish), 147 bytes [Try it online!](https://tio.run/##S8sszvj/XzEm08pAwz7OMFopMSk5JTUtPSMzKzsnNy@/oLCouKS0rLyissrRydnF1c3dw9PL28fXzz8gMCg4JDQsPCIyytDI2MTUzNzC0kBJkStH39621qraWtFe15Crzi7HUNdesYzLukwBBPSBApaWWrpAyxStTaKV/MNcw5Sqde2tkbFhHpdC7P//R1cfbTuy@kjv0d6UI5OB6vwB "><> – Try It Online") This prints 1 if the input string is valid and nothing for an invalid input. Edit 1: Changed the Alphanumeric checks to use ranges rather than comparing against every character. (saving 22 bytes) [Answer] # Bash, ~~53~~ ~~26~~ 30 bytes ``` [[ $1 =~ ^[^\W_]{0,76}VEVO$ ]] ``` Exit code 0 for VALID results and 1 for INVALID results. ~~Still working on 80 characters or less.~~ -27 bytes from removing output, thanks to @KeyWeeUsr +4 bytes, fixed regex (same as everyone else) [Try it online!](https://tio.run/##S0oszvivrKiflJmnnwRiR0crqBgq2NYpxEXHxYTHx1Yb6Jib1Ya5hvmrKMTG/v//vyS1uMTQyNgEJAQA "Try it online!") [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~101~~ ~~89~~ ~~83~~ ~~81~~ 94 bytes Edit: ~~Switched to checking for non-alphanumeric characters rather than for alphanumeric.~~ Switched back cause I forget to check between Z and a. Thanks @Emigna. Rip those lost bytes though Edit 2: Also, I can totally just get rid of those }}}}. Thanks [Teal pelican](https://codegolf.stackexchange.com/users/62009/teal-pelican) for that and finding the problem with TIO Edit 3: replaced a ~~~ with a p ``` !\i::0(?v:::"/")$":"(*$:"`")$"{"(*+$:"@")$"["(*+? 0/?("S"l/ l/"VEVO"[4pn?$0(6 !\{-?vl? 1/;n0/n ``` ~~I don't know why this won't work on TIO, but it works fine [here](https://fishlanguage.com/playground).~~ The problem was that the {} commands in TIO don't work for an empty list. [Try It Here](https://tio.run/##S8sszvj/XzEm08rKQMO@zMrKSklfSVNFyUpJQ0vFSikBxK4GsrWBHAcQJxrEsecy0LfXUApWytHnytFXCnMN81eKNinIs1cx0DDjUoyp1rUvy7HnMtS3zjPQz/v/vyS1uASkyNDIGAA) ### How It Works ``` !\i::0(?v:::"/")$":"(*$:"`")$"{"(*+$:"@")$"["(*+? 0/....../ ......... Checks each input is alphanumeric ... If any isn't, print 0 and exit with an error ... ... 0/?("S"l/ Checks if there are more than 80 characters ... If so, print 0 and exit with an error ... ... ... ... l/"VEVO"[4pn?$0(6 Check if the input is less than 4 characters ... If so, print 0 and exit with an error ... ... ... ./"VEVO"[4pn?$0(6 Take the last 4 characters of the input into a new stack (first time I've actually used [) ... Add "VEVO" to the stack to compare ... ... 0/....../n ........V !\{-?vl? Check if the last 4 characters are VEVO 1/;n0/n Print 1 and exit with an error if so, else print 0 and exit ``` For consistency, replacing the ; in the last line with an invalid instruction makes *every* output an error. [Answer] ## C++, ~~129~~ ~~105~~ 102 bytes Thanks to other answers that showed me that i can count the number of characters -2 bytes thanks to Zacharý ``` #include<regex> int v(std::string s){return std::regex_match(s, std::regex("[a-zA-Z0-9]{0,76}VEVO"));} ``` [TIO LINK](https://tio.run/##TZBvS8MwEMZft5/iqCAtrDAVFNc6mTqR4RTc3Av/IFl3btnatCSX6Rz97DOJYn0T7nmS@12ey6oqnmfZbo@LLNczhJSXiiSyovvnpRLn@Nn1Fc06HVeDDINnFn/14qd2fPq6bbdOjutJf3IfRAkXBOvQvTUgLuagoq1E0lJAQ3grGGWLULVklNQ721MwLsIItr7HNJVAqAjOrPSC3gxzdPiWlZelEBzHLJ@W1Lijm2EjlloRL6Yoc7b613k1GDJJXAxQKBSNb4cdHB41htqwAlas0qtf3qZCQSjJfLIw1Y97V2YLBLO0C6mXTDUsCzK8wPfqxPe991JCaFPtM@i4ZC6n59aRlZogTSEY28QfnBYQWM2cCQBxbA6JSuekzEbcZbgOWQTnpunhsf8iAoMNrnu3I1tHiRnr17tv) [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 21 bytes ``` ['^\i{0,76}VEVO'-''=] ``` [Try it online!](https://tio.run/##Ky5JTM5OTfn/P1o9Liaz2kDH3Kw2zDXMX11XXd029r@DVRqXhnpJanEJWFABzDQCsY3BXKhoZX6pQnFBamK2Qk5marG6pkJ0mkJ@aUmsQm5iwX8A "Stacked – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes ``` žKÃQsg81‹IR4£"OVEV"QP ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6D7vw82BxekWho8adnoGmRxarOQf5hqmFBjw/39JanGJoZExkOsPAA "05AB1E – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 37 36 bytes Pretty simple answer using some lovely regex. Quite possibly the shortest Java answer I've ever done. -1 bytes thanks to Neil on the Javascript answer ``` w->w.matches("((?!_)\\w){0,76}VEVO") ``` [Try it online!](https://tio.run/##NYwxq8IwFIXn5Ffc55TAszjpUNTpjU8HwUVFbmusqWlSmluDlP72GEGnA@ec76vxgVPXKltf7rE06D38o7YDZ9qS6q5YKtgMHBgrnDMKLVRiR522FQSZczZyztq@MLoET0gpHk5foEmOz@9wApTJx74YLAEPs1P@rp6eVJO5nrI2jWSssFklgvyqP84N2ETFMF2FrEEqb8qLiRDrn7M8HoMcZr@L@bj/228nMrKcjzHWvSfdFKozeFfv5QU "Java (OpenJDK 8) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 18 bytes ``` A`\W|_|.{81} VEVO$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3zEhJrwmvkav2sKwlivMNcxf5f//4srEXIXsxILSbK6syoLUvJLUopLEzLxcIIvLLz85I1UhJVXBqag0K7GYqyS1uASkzdDImMsxJTUnFcThcs7Py8tMDUnMScoHy3IFe/iC6azS4pLM3KTUopzEbIhSFy/fxCKge7xS84pT88BCIDOB5oHYAA "Retina – Try It Online") or ``` ^[^\W_]{0,76}VEVO$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPy46LiY8PrbaQMfcrDbMNcxf5f//4srEXIXsxILSbK6syoLUvJLUopLEzLxcIIvLLz85I1UhJVXBqag0K7GYqyS1uASkzdDImMsxJTUnFcThcs7Py8tMDUnMScoHy3IFe/iC6azS4pLM3KTUopzEbIhSFy/fxCKge7xS84pT88BCIDOB5oHYAA "Retina – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 75 bytes *-2 bytes thanks to user28667.* ``` import Data.Char f s|l<-length s=all isAlphaNum s&&l<81&&drop(l-4)s=="VEVO" ``` [Try it online!](https://tio.run/##VY69asNQDIX3PIXwYBJoAmk7dIiHNCmUgNOhJUvpoNRK77V1f7iSh0Df3XUMNVjT0XeQzjEoDTF3nXUxJIU9Kq52BtPsAvLLmyWT/1EDUiAzWNlyNHhsHUie8@ZpnedVCnHOy8eFFEV2ejm9ZZ1D66EAh7GEeUzWK6zgsphBP5@QyRUdNBjbJhvQHWT1NZJXStpful6NxjF8G4KK4Dm1NcrIlURvYev7h5FtK2IaGvyTXfDe0gfyOejEeH8tJ3vdilp3psTYTF/sDyUmtf5AXshPrFuHPn9g8NX9AQ "Haskell – Try It Online") [Answer] # [Deorst](https://github.com/cairdcoinheringaahing/Deorst), 22 bytes ``` '^[^\W_]{0,76}VEVO$'gm ``` [Try it online!](https://tio.run/##S0nNLyou@f9fPS46LiY8PrbaQMfcrDbMNcxfRT099////yWpxSWGRsYgEQA "Deorst – Try It Online") Just uses the regex found by Shaggy [Answer] # [V](https://github.com/DJMcMayhem/V), 17 bytes ``` ø^¨áüä©û,76}VEVO$ ``` [Try it online!](https://tio.run/##K/v///COuEMrDi88vOfwkkMrD@/WMTerDXMN81f5/985Py8vMzUkMScpvwQkBAA "V – Try It Online") Hexdump: ``` 00000000: f85e a8e1 fce4 a9fb 2c37 367d 5645 564f .^......,76}VEVO 00000010: 24 $ ``` Compressed regexes for the win! ``` ø " Count the number of matches of ^ " The beginning of the line ¨áüä© " A letter or number... û,76} " From 0 to 76 times... VEVO " Followed by "VEVO" $ " At the end of the line ``` [Answer] # [Ruby](https://www.ruby-lang.org/) -n, 22+1 = 23 bytes ``` p~/^[^\W_]{0,76}VEVO$/ ``` Output `0` if true, `nil` if false [Try it online!](https://tio.run/##KypNqvz/v6BOPy46LiY8PrbaQMfcrDbMNcxfRf///8SkZEMjYxCPC8YsgzLj4aIKEAUVVAYYdv/LLyjJzM8r/q@bBwA "Ruby – Try It Online") Using the same boring regex as everybody else. [Answer] # [Swift 4](https://developer.apple.com/swift/), 113 bytes ``` import Foundation;var f={(s:String)->Bool in s.range(of:"^[^\\W_]{0,76}VEVO$",options:.regularExpression) != nil} ``` [Try it online!](https://tio.run/##VdDdS8MwEADw9/4VZ/GhhTr8QmFSwelEBtOHyXzYh2T2Wm9LLyW56sbY317bjcLMU/LL5e5y7pdSua4qygtjBZ5NyYkSMnz3oyyk8TZw3ZFY4iw8u@8Zo4EYXMcqzjAwadefT@bT6cfnbHse3d7sxv3x26kfmaJJ4bodi1mple2vC4vO1RbCSQxMeldpFBB04iCGiQf18t1G5bBSRbnyo4MsNwWyoBVFnNe71l/N1zdCgtCz5VK5lpt8TQsXl1ctPSSosbEWHg0z4bvSCyPHPnoZHh@XpRPKF2i1Wv17/zQYKivEA2SHfHzTVK8r78mbeV5qLFAzr8M3t/uoop6lBGlAYejtqj8 "Swift 4 – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 23 bytes ``` $0~/^[^\W_]{0,76}VEVO$/ ``` [Try it online!](https://tio.run/##SyzP/v9fxaBOPy46LiY8PrbaQMfcrDbMNcxfRf///5LU4hJDI2MQFwA "AWK – Try It Online") Outputs the account name if valid, and outputs nothing if it isn't valid [Answer] # [Clean](https://clean.cs.ru.nl), 61 bytes ``` import StdEnv ?['VEVO']=True ?[_:l]=length l<80&& ?l ?_=False ``` [Try it online!](https://tio.run/##JY2xCsIwFAD3fkWmZio4ihgyaAWh4NDSpZTy2sYaeHmRJhX8eZ9BxxvubkIDxM7PGxrhwBJb9/RrFHWcS3plupNt2d5kr5p1MwmHA/YKDS3xIfC43@W50JjpQV0Ag@E6QpKV0KKTJ09kTQM4@viP8Ge6IyyBi5GLa8XnN4GzU/hBOlZ2/AI "Clean – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), ~~35~~ 29+1(-a) = 30 bytes *-6 bytes thanks to ETHproductions* *Added 4 bytes. Didn't see that underscore wasn't allowed.* This is my first golf, so here's hoping I did it right. Returns 1 if valid, 0 if not. ``` print/^[^\W_]{0,76}VEVO$/?1:0 ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRD8uOi4mPD622kDH3Kw2zDXMX0Xf3tDK4P//kNTiEkMjY5DQv/yCksz8vOL/uokA "Perl 5 – Try It Online") [Answer] # Google Sheets, 33 Bytes Anonymous worksheet function that takes input from range `A1` and outputs to the calling cell ``` =RegexMatch(A1,"^[^\W_]{0,76}VEVO ``` [Answer] # [Clojure](https://clojure.org/), 146 bytes ``` (fn[u](let[c count](and(<(c u)81)(=(c(filter #(let[i(int %)](or(< 47 i 58)(< 64 i 91)(< 96 i 123)))u))(c u))(clojure.string/ends-with? u"VEVO")))) ``` [Try it online!](https://tio.run/##JY1NC4JQEEX/ymAEM4sKy0zBaFMbIdq5ERfyfNaEjPA@6Oe/Xra5HLiHe9U0v73RIeAore9w0q5VoGYvrsNeBqxQgaciJTyjwpEnpw2sFo@RxcGaOpwNVpCdgOFYUMQ8i1imPyzziOn@QESeaBmL@X/dWmdYnjstg9182L0u4JPm1jySaFMIIbnW9944llqL1bJUXw "Clojure – Try It Online") This would be much shorter using a regex, but I figured doing it manually would be more interesting. ``` (defn vevo? [username] (and (< (count username) 81) ; Filter out the illegal characters, then check if the length is the same as the original string (= (count (filter #(let [i (int %)] ; Make sure the char code is in the valid ranges (or (< 47 i 58) (< 64 i 91) (< 96 i 123))) username)) (count username)) (clojure.string/ends-with? username "VEVO"))) ``` ]
[Question] [ In this challenge, you will be given a square matrix `A`, a vector `v`, and a scalar `λ`. You will be required to determine if `(λ, v)` is an eigenpair corresponding to `A`; that is, whether or not `Av = λv`. # Dot Product The dot product of two vectors is the sum of element-wise multiplication. For example, the dot product of the following two vectors is: ``` (1, 2, 3) * (4, 5, 6) = 1*4 + 2*5 + 3*6 = 32 ``` Note that the dot product is only defined between two vectors of the same length. # Matrix-Vector Multiplication A matrix is a 2D grid of values. An `m` x `n` matrix has `m` rows and `n` columns. We can imagine an `m` x `n` matrix as `m` vectors of length `n` (if we take the rows). Matrix-Vector multiplication is defined between an `m` x `n` matrix and a size-`n` vector. If we multiply an `m` x `n` matrix and a size-`n` vector, we obtain a size-`m` vector. The `i`-th value in the result vector is the dot product of the `i`-th row of the matrix and the original vector. ### Example ``` 1 2 3 4 5 Let A = 3 4 5 6 7 5 6 7 8 9 1 3 Let v = 5 7 9 ``` If we multiply the matrix and the vector `Av = x`, we get the following: x1 = AT1 \* v `/* AT1 means the first row of A; A1 would be the first column */` = (1,2,3,4,5) \* (1,3,5,7,9) = 1\*1 + 2\*3 + 3\*5 + 4\*7 + 5\*9 = 1+6+15+28+45 = 95 x2 = AT2 \* v = (3,4,5,6,7) \* (1,3,5,7,9) = 3\*1 + 4\*3 + 5\*5 + 6\*7 + 7\*9 = 3+12+25+42+63 = 145 x3 = AT3 \* v = (5,6,7,8,9) \* (1,3,5,7,9) = 5\*1 + 6\*3 + 7\*5 + 8\*7 + 9\*9 = 5+18+35+56+81 = 195 So, we get `Av = x = (95, 145, 195)`. # Scalar Multiplication Multiplication of a scalar (a single number) and a vector is simply element-wise multiplication. For example, `3 * (1, 2, 3) = (3, 6, 9)`. It's fairly straightforward. # Eigenvalues and Eigenvectors Given the matrix `A`, we say that `λ` is an eigenvalue corresponding to `v` and `v` is an eigenvector corresponding to `λ` **if and only if** `Av = λv`. (Where `Av` is matrix-vector multiplication and `λv` is scalar multiplication). `(λ, v)` is an eigenpair. # Challenge Specifications ### Input Input will consist of a matrix, a vector, and a scalar. These can be taken in any order in any reasonable format. ### Output Output will be a truthy/falsy value; truthy if and only if the scalar and the vector are an eigenpair with the matrix specified. # Rules * Standard loopholes apply * If a built-in for verifying an eigenpair exists in your language, you may not use it. * You may assume that all numbers are integers # Test Cases ``` MATRIX VECTOR EIGENVALUE 2 -3 -1 3 1 -2 -1 1 1 -> TRUE 1 -3 0 0 2 -3 -1 1 1 -2 -1 1 -2 -> TRUE 1 -3 0 1 1 6 3 1 0 -2 0 0 4 -> TRUE 3 6 1 1 1 0 -1 2 -1 1 1 1 7 -> FALSE 1 0 0 0 -4 3 1 2 1 2 2 -> TRUE 2 1 2 -> TRUE ``` I will add a 4x4 later. [Unreadable Test Cases that are easier for testing](https://hastebin.com/niqinazizu.lua) [Answer] ## Mathematica, 10 bytes ``` #2.#==#3#& ``` Takes input like `{vector, matrix, scalar}` and returns a boolean. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` æ.⁵⁼× ``` This is a triadic, full program. [Try it online!](https://tio.run/nexus/jelly#@394md6jxq2PGvccnv7///9oQx0FEIr9r2v0PzpawUhHQdcYiA1jdbgUokFSukaoXKCsgkFsLAA "Jelly – TIO Nexus") ### How it works ``` æ.⁵⁼× Main link Left argument: v (eigenvector) Right argument: λ (eigenvalue) Third argument: A (matrix) ⁵ Third; yield A. æ. Take the dot product of v and A, yielding Av. × Multiply v and λ component by component, yielding λv. ⁼ Test the results to the left and to the right for equality. ``` [Answer] # MATL, 7 bytes ``` *i2GY*= ``` Inputs in order: `l`,`v`,`A`. Explanation: ``` * % implicitly get l and v, multiply. i % get A 2G % get second input, i.e., v again Y* % perform matrix multiplication = % test equality of both multiplications ``` Surprisingly long answer, if you ask me, mostly because I needed a way to get all the input correctly. I do not think that less than 5 bytes is possible, but it would be cool if someone found a 5 or 6 byte solution. Basically, this calculates `l*v==A*v`. [Answer] # [CJam](https://sourceforge.net/p/cjam), 15 bytes ``` q~W$f.*::+@@f*= ``` Takes input in the form `vector scalar matrix`. [Try it online!](https://tio.run/nexus/cjam#@19YF66SpqdlZaXt4JCmZfv/f7ShAhDGKugaKURHGynoGivoGsYCBYF8KMNYQcEgNhYA "CJam – TIO Nexus") **Explanation** ``` q~ e# Read and eval the input W$ e# Copy the bottom most value (the vector) f.*::+ e# Perform element-wise multiplication with each row of the matrix, then e# sum the results of each (ie dot product with each row) @@ e# Move the resulting vector to the bottom of the stack f* e# Element-wise multiplication of the scalar and the vector = e# Check if the two vectors are equal ``` [Answer] # MATLAB, 16 bytes ``` @(A,v,l)A*v==v*l ``` Rather trivial answer. Defines an anonymous function taking the inputs, and calculates element-wise equality of the resulting vectors. A single zero in a logical array makes an array falsey in MATLAB. [Answer] # MATLAB, 38 bytes ``` function r=f(m,v,s);r=isequal(m*v,s*v) ``` Returns 1 or 0. # MATLAB, 30 bytes ``` function r=f(m,v,s);r=m*v==s*v ``` Returns ``` 1 1 1 ``` as a truthy value. A falsy value is a similar vector with any or all values 0 instead of 1. [Answer] # C++, ~~225~~ 203 bytes *Thanks to @Cort Ammon and @Julian Wolf for saving 22 bytes!* ``` #import<vector> #define F(v,i)for(i=0;i<v.size();++i) using V=std::vector<float>;int f(std::vector<V>m,V v,float s){V p;int i,j;F(m,i){p.push_back(0);F(v,j)p[i]+=v[j]*m[i][j];}F(v,i)v[i]*=s;return v==p;} ``` [Try it online!](https://tio.run/nexus/cpp-gcc#jY/BbsIwDIbvfYoILgkE1Ba0SaTtkUfohaGpK@kWRtOqSXNY1GdnTlo2bhDJsuP8/vznOhd123Q6MbzUTZcF8xOvhORojw0VpGo6LNKQicSslfjhmLDlUpCgV0J@ojxV@rTbjaNJdWkKnTEhNarw/UOe1TRHhnoBUsTmqPUyQc9sj2vYY9t126uv94@i/MYhYW77mbQHcVym5nA@LmooIbNh9GXgukgV67juO4lMmrZsuM6FLC/9iaNENEp3vKizwO2pCyExCWyA4HhnZdNrlCRg1NqYotUGIhqojSDHdzX0w2GgyEIRuRoScYOzNznzuP/zHG7iRZ4HfRA8AIIOvUBsABKOQGfEWfL96AYMR@D2CV44mVq5i4/RoXuYHMZ/P359AFxtJ3du5GYmhvzoZ/Eo9koWDNdf) [Answer] # Julia, 17 bytes ``` (a,b,c)->a*b==b*c ``` [Try it online!](https://tio.run/nexus/julia5#S7P9r5Gok6STrKlrl6iVZGubpJX8v6AoM69EI00j2khB11hB19BawVBB1wjGMFYwiNWJNgayrUEsQ03N/wA "Julia 0.5 – TIO Nexus") [Answer] # Python 2.7, 33 bytes ``` f=lambda m,s,e:all(m.dot(s)==e*s) ``` input: m=matrix, s=scalar, e=eigenvalue. M and s are numpy arrays [Answer] # [Python 3](https://docs.python.org/3/), ~~96~~ 70 bytes No builtins for matrix-vector or scalar-vector multiplication! ``` lambda A,L,v:all(L*y==sum(i*j for i,j in zip(x,v))for x,y in zip(A,v)) ``` [Try it online!](https://tio.run/nexus/python3#jZC9DoIwFEZneIo7FvM1ocVoQsLgzhs0DKiQ1CAaQQO@PN6Wn9mJ5uTklH5TnTXl/Xwt6YQcn7RsGpHvxizr3ndhdzeqHy@yuJFt6WufYsAnihwbMK7s5NjUV11/Kbuqo4xMGAhjNGQCqQoYBam3U4K4KEAmgeITSEX4R1esMyKpF1/hgISd2Nkc4uCBjdmNvbvf1HjuyaXiydzVy28cF1fufVVvKc2f9U49M0/CInRDuOcjj9wY2wRpGDxftu1FLfysPM8P "Python 3 – TIO Nexus") -26 bytes by using `zip` thanks to @LeakyNun! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` vy²*O})²³*Q ``` [Try it online!](https://tio.run/nexus/05ab1e#@19WeWiTln@t5qFNhzZrBf7/Hx1tpKNrrKNrGKsTbaijawRnGesYxMZyRRvrGAIZXIYA "05AB1E – TIO Nexus") ``` vy²*O}) # Vectorized product-sum. ²³* # Vector * scalar. Q # Equivalence. ``` [Answer] # R, ~~30~~ 25 bytes ``` s=pryr::f(all(a%*%v==λ*v)) ``` Anonymous function, fairly straightforward. Returns `TRUE` or `FALSE`. [Answer] # oK, 12 bytes ``` {y~z%+/y*+x} ``` This is a function, it takes in `[matrix;vector;scalar]`. This does not work in k for the same reasons that `3.0~3` gives `0` as a result. --- The following works in **k**, with **14 bytes**: ``` {(y*z)~+/y*+x} ``` [Answer] # Axiom, 27 bytes ``` f(a,b,c)==(a*b=c*b)@Boolean ``` exercises ``` (17) -> m:=matrix[[2,-3,-1],[1,-2,-1],[1,-3,0] ]; v:=matrix[[3],[1],[0]]; (18) -> f(m,v,1) (18) true (19) -> m:=matrix[[2,-3,-1],[1,-2,-1],[1,-3,0] ]; v:=matrix[[1],[1],[1]]; (20) -> f(m,v,-2) (20) true (21) -> m:=matrix[[1,6,3],[0,-2,0],[3,6,1] ]; v:=matrix[[1],[0],[1]]; (22) -> f(m,v,4) (22) true (23) -> m:=matrix[[1,0,-1],[-1,1,1],[1,0,0] ]; v:=matrix[[2],[1],[0]]; (24) -> f(m,v,7) (24) false (25) -> m:=matrix[[-4,3],[2,1] ]; v:=matrix[[1],[2]]; (26) -> f(m,v,2) (26) true (27) -> f(2,1,2) (27) true ``` [Answer] # Python, 26 bytes ``` lambda a,b,c:c*b==a.dot(b) ``` `a` and `b` are numpy arrays, `c` is an integer. [Try it online!](https://tio.run/nexus/python2#jZBBCoMwEEXXeopZJmUiSRQLgiexLhKtIDQq0S48vR1jbbvs7s/8x2OY3k2jX2B4ummNOyjhtj2Ms60BgxabornYsjRJOy7M8q0bPTCHM9459AOwOIpYVWkUKQpVY6VQ6E9KUdaUUlQUUHH8h1ZE00boE1eYY0qF3GEZfDkRAZU7mn1JedjEWxI2waqPG64nKrLg1KdI16h5HPGC6sn3wwIdCy9JjPdmZY7j7zhzesD2Ag "Python 2 – TIO Nexus") [Answer] ## Clojure, 60 bytes ``` #(=(set(map(fn[a v](apply -(* v %3)(map * a %2)))% %2))#{0}) ``` This checks that all deltas are zero, thus collapsing into the set of zero. Calling example: ``` (def f #(=(set(map(fn[a v](apply -(* v %3)(map * a %2)))% %2))#{0})) (f [[1 6 3][0 -2 0][3 6 1]] [1 0 1] 4) ``` ]
[Question] [ You are given a multi-dimensional array of integers. Each dimension has a fixed size (so that it would be always rectangular if it is 2D). Your program should calculate the sums in each dimension and append the sums as the new last items in that dimension. Assume the input and output arrays are A and B, and the size of dimension *i* of A is ni. B would have the same number of dimensions as A and the size of dimension *i* would be ni+1. Bj1,j2,...,jm is the sum of Ak1,k2,...,km where: * ki = ji if ji <= ni * 0 < ki <= ni if ji = ni+1 For the input: ``` [[1 2 3] [4 5 6]] ``` Your program (or function) should output: ``` [[1 2 3 6] [4 5 6 15] [5 7 9 21]] ``` The input contains only the array. The total number of dimensions and the size of each dimension are **not** given in the input. (But you can get them from the array by your own code.) You can use any convenient list formats in your language, as long as it doesn't specify the number of dimensions or dimension sizes directly. The input has at least 1 dimension, and has at least 1 item in the array. This is code-golf. Shortest code wins. ## Test cases ``` Input: [5 2 3] Output: [5 2 3 10] Input: [[1 2 3] [4 5 6]] Outputs: [[1 2 3 6] [4 5 6 15] [5 7 9 21]] Input: [[[1] [1] [1] [0]]] Output: [[[1 1] [1 1] [1 1] [0 0] [3 3]] [[1 1] [1 1] [1 1] [0 0] [3 3]]] Input: [[[[-1]]]] Output: [[[[-1 -1] [-1 -1]] [[-1 -1] [-1 -1]]] [[[-1 -1] [-1 -1]] [[-1 -1] [-1 -1]]]] ``` [Answer] # Mathematica, ~~32~~ 20 bytes ``` #/.List->({##,+##}&)& ``` ### Example: ``` In[1]:= #/.List->({##,+##}&)&[{{1, 2, 3}, {4, 5, 6}}] Out[1]= {{1, 2, 3, 6}, {4, 5, 6, 15}, {5, 7, 9, 21}} ``` ### Explanation: The full form of `{{1, 2, 3}, {4, 5, 6}}` is `List[List[1, 2, 3], List[4, 5, 6]]`. Then replace all the `List`s in the expression with the function `({##,+##}&)`. [Answer] ## Python 2, 95 bytes ``` from numpy import* a=copy(input()) for d in r_[:a.ndim]:a=r_[`d`,a,sum(a,d,keepdims=1)] print a ``` This iterates over each dimension, concatenating its sums using NumPy. I stumbled across NumPy's [`r_`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html#numpy-r), which is pretty awesome for golfing. `r_[:n]` is shorter than `range(n)` and much more powerful (e.g. `r_[:4, 7, 8, 10:100:10]`). It can also do other things like concatenation along an arbitrary axis. Example usage: ``` $ python sum.py [[1, 2, 3], [4, 5, 6]] [[ 1 2 3 6] [ 4 5 6 15] [ 5 7 9 21]] ``` [Answer] # J, 14 bytes ``` #@$(0|:],+/^:) ``` Usage: ``` ]a=.i.2 3 0 1 2 3 4 5 (#@$(0|:],+/^:)) a NB. parens are optional 0 1 2 3 3 4 5 12 3 5 7 15 ``` The function is equivalent to the following `(0|:],+/)^:(#@$)` but uses a user-defined adverb to save parens. Explanation for the latter code from right to left: * `^:(#@$)`repeat `^:` for the number `#` of dimensions `$`: + `],+/` concatenate `,` to the argument `]` with the sum of it on the last dimension `+/` + `0|:` rotate dimensions `|:` by putting the first one `0` to the end of the dimension-list * After doing the above procedure we get back the original input with sums on all dimensions. *For my older solution check revision history.* [Try it online here.](http://tryj.tk/) [Answer] # APL, ~~16~~ 15 bytes ``` {×≡⍵:∇¨⍵,+/⍵⋄⍵} ``` *Thanks to @user23013 for golfing off 3 bytes and figuring out the proper input format.* Verify the test cases online with [TryAPL](http://tryapl.org/?a=sum%u2190%7B%D7%u2261%u2375%3A%u2207%A8%u2375%2C+/%u2375%u22C4%u2375%7D%20%u22C4%20sum%205%202%203%20%u22C4%20sum%20%281%202%203%29%284%205%206%29%20%u22C4%20sum%20%2C%u2282%28%2C1%29%28%2C1%29%28%2C1%29%28%2C0%29%20%u22C4%20sum%20%u2282%u2282%u2282%2C%AF1&run). ### Idea The general idea is the same as in my CJam submission, for which APL allows a much shorter implementation. It consists of only two steps: 1. Sum the array across its outmost dimension. 2. Repeat step 1 for each subarray. ### Code ``` { } ⍝ Define a monadic function with argument ⍵ and reference ∇. ×≡⍵: ⍝ If the depth of ⍵ is positive: ∇ ⍝ Apply this function... ¨ ⍝ to each element of... ⍵, ⍝ the concatenation of ⍵... +/⍵ ⍝ and the sum across ⍵. ⋄⍵ ⍝ Else, return ⍵. ``` [Answer] # [Pip](http://github.com/dloscutoff/pip), ~~18~~ 15 bytes ``` {a-a?fMaAE$+aa} ``` This is an anonymous function, which takes the array as an argument and returns the result. Sample invocation, using the `-p` flag to obtain readable output: ``` C:\> pip.py -pe "( {a-a?fMaAE$+aa} [[1 2 3] [4 5 6]] )" [[1;2;3;6];[4;5;6;15];[5;7;9;21]] ``` The idea is basically the same as [Dennis's APL](https://codegolf.stackexchange.com/a/50654/16766), though independently derived. More specifically: ``` { } Define a lambda function with parameter a a-a? Shortest way I could find to test whether the argument is a list or scalar: subtracting a number from itself gives 0 (falsy); subtracting a list from itself gives a list of zeros (truthy!) fM If truthy, it's a list, so map the same function (f) recursively to: aAE Argument, with appended element... $+a ...sum of argument (fold on +) a If falsy, it's a scalar, so just return it ``` This method works because `+` (along with many other operators) functions item-wise on lists in Pip--a feature inspired by array-programming languages like APL. So when you `$+` a list like `[[1 2 3] [4 5 6]]`, the result is `[5 7 9]` as desired. Also used in the list-or-scalar test: `[1 2 3] - [1 2 3]` gives `[0 0 0]`, which is truthy (as are all lists except the empty list). Previous 18-byte version: ``` {Ja=a?a(fMaAE$+a)} ``` Changes: 1. Saved a byte on the scalar-or-list test--previous method was to join the argument (on empty string) and test whether equal to its un-joined self (works because `[1 2 3] != 123`); 2. Eliminated the parentheses. They're necessary in the original because `M` is lower precedence than `?` (though I'm probably going to change that, especially now): without them, the code would parse as `(Ja=a?af)M(aAE$+a)`, leading to bizarre error messages. However, the middle argument of a ternary operator can be *any* expression of whatever precedence, no parentheses needed. So by making the list the truthy case, I can save those two bytes. [Answer] # APL (25) ``` {N⊣{N,[⍵]←+/[⍵]N}¨⍳⍴⍴N←⍵} ``` APL's arrays have dimensions built-in, so this is a function that takes an *n*-dimensional array and then sums along each dimension. ``` {N⊣{N,[⍵]←+/[⍵]N}¨⍳⍴⍴N←⍵} ↑(1 2 3)(4 5 6) 1 2 3 6 4 5 6 15 5 7 9 21 ``` Explanation: * `N←⍵`: store the array in `N`. * `⍴⍴N`: get the amount of dimensions `N` has. (`⍴` gives the dimensions, i.e. `⍴↑(1 2 3)(4 5 6)` gives `2 3`, so `⍴⍴` gives the dimensions of the dimensions.) * `{`...`}¨⍳`: for each number from 1 to `⍴⍴N`: + `+/[⍵]N`: sum `N` along dimension `⍵` + `N,[⍵]←`: join the result to `N` in that dimension * `N`: finally, return `N`. [Answer] # CJam, 36 bytes ``` {_`{'[<}#:D{_":"D'.e]'++~a+{S}%}&}:S ``` This is a recursive named function that pops an array from the stack and leaves one in return. Try the test cases in the [CJam interpreter](http://cjam.aditsu.net/#code=%7B_%60%7B'%5B%3C%7D%23%3AD%7B_%22%3A%22D'.e%5D'%2B%2B~a%2B%7BS%7D%25%7D%26%7D%3AS%20e%23%20Define%20S.%0A%0A%20qN%2F%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Read%20from%20STDIN%20and%20split%20at%20linefeeds.%0A%7B~Sp%7D%2F%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Evaluate%20each%20line%2C%20execute%20S%20and%20print.%0A%3B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Clear%20the%20stack.&input=%5B5%202%203%5D%0A%5B%5B1%202%203%5D%20%5B4%205%206%5D%5D%0A%5B%5B%5B1%5D%20%5B1%5D%20%5B1%5D%20%5B0%5D%5D%5D%0A%5B%5B%5B%5B-1%5D%5D%5D%5D). ### Idea Sadly, CJam does not have some automagical operator that allows to add arbitrarily nested arrays, so we have to implement it ourselves. Luckily, it does that two infix operators, `:` (reduce) and `.` (vectorize), that will prove helpful for this task. Step one is calculating the number of dimensions. This is easy: Convert the array into its string representation and count the number of leading **[**'s. Now, to reduce an array of one dimension, you usually just execute `:+`: ``` [1 2] :+ e# Pushes 3. ``` For an array of two dimensions, `+` would perform concatenation instead of addition, so we have to vectorize it: ``` [[1 2][3 4]] :.+ Pushes [4 6]. ``` Now, for an array of three dimensions, `.+` would operate on arrays of two dimensions and perform, once again, concatenation. This time, we have to vectorize `.+`: ``` [[[1 2][3 4]][[5 6][7 8]]] :..+ e# Pushes [[[6 8] [10 12]]]. ``` For the general case, an array of dimension **D**, we have to chain one `:`, **D - 1** `.`'s and one `+`. Of course, this only sums the array only across its outmost dimension. We can solve this by defining a function **S** that computes the dimension (and does nothing if it's zero), performs the sum as indicated above and, finally, applies itself to the array's elements. ### Code ``` { }:S e# Define S: _` e# Push a string representation of a the array. {'[<}# e# Find the index of the first non-bracket. :D e# Save it in D. { }& e# If D is positive: _ e# Push a copy of the array. ":"D'.e] e# Pad ":" with "."s to a string of length D. '++~ e# Add a "+" to the string and evaluate. a+ e# Wrap the result in a array and concatenate. {S}% e# Apply S to the elements of the array. ``` [Answer] ## Ruby (~~181~~ ~~139~~ ~~119~~ 108 bytes) ``` def d a;a.push a[0].to_s['[']?a.map{|x|d x}.transpose.map{|x|x.reduce:+}:a.reduce(:+)end p d eval ARGF.read ``` Assumes input is passed as JSON. [Answer] # Java, 669 bytes not gonna lie, I'm quite proud of myself for this one :p ``` import java.lang.reflect.Array;enum S{D;<A>A s(A a){int l=Array.getLength(a),x=0;Class t=a.getClass();Class c=t.getComponentType();A r=(A)Array.newInstance(c,l+1);System.arraycopy(a,0,r,0,l);if(t==int[].class)for(;x<l;)((int[])r)[l]=((int[])r)[l]+((int[])r)[x++];else{for(;x<l;)Array.set(r,x,S.this.s(Array.get(r,x++)));Object o=Array.get(r,0);for(;--x>0;)o=s(o,Array.get(r,x));Array.set(r,l,o);}return r;}<A>A s(A a,A b){int l=Array.getLength(a),x=0;Class t=a.getClass();A r=(A)Array.newInstance(t.getComponentType(),l);if(int[].class==t)for(;x<l;)((int[])r)[x]=((int[])a)[x]+((int[])b)[x++];else for(;x<l;)Array.set(r,x,s(Array.get(a,x),Array.get(b,x++)));return r;}} ``` expanded with testing: ``` import java.lang.reflect.Array; import java.util.Arrays; public enum SumOf{ Dimensions; <A>A sum(A array){ //call this method to solve the challenge int length=Array.getLength(array),x=0; Class arrayType=array.getClass(); Class componentType=arrayType.getComponentType(); //grow the array to include the sum element A result=(A)Array.newInstance(componentType,length+1); System.arraycopy(array,0,result,0,length); if(arrayType==int[].class) //one-dimensional array needs to be handled separately for(;x<length;) //find the sum ((int[])result)[length]=((int[])result)[length]+((int[])result)[x++]; else{ //multi-dimensional array for(;x<length;) //find the sum for each element in this dimension's array Array.set(result,x,sum(Array.get(result,x++))); //find the total sum for this dimension's array Object s=Array.get(result,0); for(;--x>0;) s=_sum(s,Array.get(result,x)); //add the 2 elements together Array.set(result,length,s); } return result; } <A>A _sum(A arrayA,A arrayB){ //this method is used by the previous method int length=Array.getLength(arrayA),x=0; Class arrayType=arrayA.getClass(); A result=(A)Array.newInstance(arrayType.getComponentType(),length); if(int[].class==arrayType) //one-dimensional array needs to be handled separately for(;x<length;) //find the sum of both arrays ((int[])result)[x]=((int[])arrayA)[x]+((int[])arrayB)[x++]; else for(;x<length;) //find the sum of both arrays Array.set(result,x,sum(Array.get(arrayA,x),Array.get(arrayB,x++))); return result; } static int[] intArray( int firstElement, int...array ) { if( array == null ) array = new int[0]; array = Arrays.copyOf( array, array.length + 1 ); System.arraycopy( array, 0, array, 1, array.length - 1 ); array[0] = firstElement; return array; } static <E> E[] arrayArray( E firstElement, E...array ) { if( array == null ) array = (E[]) Array.newInstance( firstElement.getClass(), 0 ); array = Arrays.copyOf( array, array.length + 1 ); System.arraycopy( array, 0, array, 1, array.length - 1 ); array[0] = firstElement; return array; } static void printIntArray( int[]array ){ System.out.print("[ "); for( int x = 0; x < array.length; x++ ) System.out.print( array[x] + " " ); System.out.print("] "); } static < A > void printArray( A array ) { if( array.getClass() == int[].class ){ printIntArray( (int[]) array ); } else { System.out.print("[ "); int length = Array.getLength( array ); for( int x = 0; x < length; x++ ) printArray( Array.get( array, x ) ); System.out.print("] "); } } public static void main(String[]s){ int[] test01 = intArray( 5, 2, 3 ); System.out.print("Input: "); printArray( test01 ); System.out.print("\nOutput: "); printArray( SumOf.Dimensions.sum( test01 ) ); System.out.println(); int[][] test02 = arrayArray( intArray( 1, 2, 3 ), intArray( 4, 5, 6 ) ); System.out.print("\nInput: "); printArray( test02 ); System.out.print("\nOutput: "); printArray( SumOf.Dimensions.sum( test02 ) ); System.out.println(); int[][][] test03 = arrayArray( arrayArray( intArray( 1 ), intArray( 1 ), intArray( 1 ), intArray( 0 ) ) ); System.out.print("\nInput: "); printArray( test03 ); System.out.print("\nOutput: "); printArray( SumOf.Dimensions.sum( test03 ) ); System.out.println(); int[][][][] test04 = arrayArray( arrayArray( arrayArray( intArray( -1 ) ) ) ); System.out.print("\nInput: "); printArray( test04 ); System.out.print("\nOutput: "); printArray( SumOf.Dimensions.sum( test04 ) ); System.out.println(); int[][][] test05 = arrayArray( arrayArray( intArray( 1, 2, 3 ), intArray( 4, 5, 6 ), intArray( 7, 8, 9 ) ), arrayArray( intArray( 11, 12, 13 ), intArray( 14, 15, 16 ), intArray( 17, 18, 19 ) ), arrayArray( intArray( 21, 22, 23 ), intArray( 24, 25, 26 ), intArray( 27, 28, 29 ) ) ); System.out.print("\nInput: "); printArray( test05 ); System.out.print("\nOutput: "); printArray( SumOf.Dimensions.sum( test05 ) ); System.out.println(); } } ``` running the expanded testing version prints this: ``` Input: [ 5 2 3 ] Output: [ 5 2 3 10 ] Input: [ [ 1 2 3 ] [ 4 5 6 ] ] Output: [ [ 1 2 3 6 ] [ 4 5 6 15 ] [ 5 7 9 21 ] ] Input: [ [ [ 1 ] [ 1 ] [ 1 ] [ 0 ] ] ] Output: [ [ [ 1 1 ] [ 1 1 ] [ 1 1 ] [ 0 0 ] [ 3 3 ] ] [ [ 1 1 ] [ 1 1 ] [ 1 1 ] [ 0 0 ] [ 3 3 ] ] ] Input: [ [ [ [ -1 ] ] ] ] Output: [ [ [ [ -1 -1 ] [ -1 -1 ] ] [ [ -1 -1 ] [ -1 -1 ] ] ] [ [ [ -1 -1 ] [ -1 -1 ] ] [ [ -1 -1 ] [ -1 -1 ] ] ] ] Input: [ [ [ 1 2 3 ] [ 4 5 6 ] [ 7 8 9 ] ] [ [ 11 12 13 ] [ 14 15 16 ] [ 17 18 19 ] ] [ [ 21 22 23 ] [ 24 25 26 ] [ 27 28 29 ] ] ] Output: [ [ [ 1 2 3 6 ] [ 4 5 6 15 ] [ 7 8 9 24 ] [ 12 15 18 45 ] ] [ [ 11 12 13 36 ] [ 14 15 16 45 ] [ 17 18 19 54 ] [ 42 45 48 135 ] ] [ [ 21 22 23 66 ] [ 24 25 26 75 ] [ 27 28 29 84 ] [ 72 75 78 225 ] ] [ [ 33 36 39 108 ] [ 42 45 48 135 ] [ 51 54 57 162 ] [ 126 135 144 405 ] ] ] ``` ]
[Question] [ You are given a square \$n \times n\$ matrix \$A\$, and a list (or vector) \$u\$ of length \$n\$ containing the numbers \$1\$ through \$n\$ (or \$0\$ through \$n-1\$). Your task is to reorder the columns **and** rows of the matrix \$A\$ according to the order specified in \$u\$. That is, you will construct a matrix \$B\$ where the \$(i,j)\$-th element is the \$(u(i),u(j))\$-th element of \$A\$. You should also output the inverse of this action; that is, the (i,j)-th element of \$A\$ will end up at position \$(u(i),u(j))\$ in a new matrix \$C\$. For example, given $$A = \begin{bmatrix} 11 &12& 13 \\ 21& 22& 23 \\ 31& 32& 33 \end{bmatrix},\quad u=\begin{bmatrix}3 & 1 & 2\end{bmatrix}$$ the output should be $$B = \begin{bmatrix}33 & 31 & 32 \\ 13 & 11 & 12 \\ 23 & 21 & 22 \end{bmatrix},\quad C= \begin{bmatrix}22 & 23 & 21 \\32 & 33 & 31 \\ 12 & 13 & 11 \end{bmatrix}$$ You may take input and output through any of the default I/O methods. You do not have to specify which matrix is \$B\$ or \$C\$, as long as you output both. You may assume \$A\$ only contains positive integers, and you may use 1- or 0-based indexing for \$u\$. You must support matrices up to at least size \$64 \times 64\$. ## Example ``` ===== Input ===== A = 35 1 6 26 19 24 3 32 7 21 23 25 31 9 2 22 27 20 8 28 33 17 10 15 30 5 34 12 14 16 4 36 29 13 18 11 u= 3 5 6 1 4 2 ==== Output ===== B = 2 27 20 31 22 9 34 14 16 30 12 5 29 18 11 4 13 36 6 19 24 35 26 1 33 10 15 8 17 28 7 23 25 3 21 32 C = 17 15 8 10 28 33 13 11 4 18 36 29 26 24 35 19 1 6 12 16 30 14 5 34 21 25 3 23 32 7 22 20 31 27 9 2 ``` [Answer] # [R](https://www.r-project.org/), 42 bytes ``` function(A,o)list(A[o,o],A[I<-order(o),I]) ``` [Try it online!](https://tio.run/##DcoxCoAwDAXQqzgm8B2SrDp09AziINVCQQ3UCt6@urzplZa6oe9aeq5Ys18U4Hzku1KYHb4gzNPQe9n2Qs6YFm6JwniuteSXIolABSYQhSpMIQY1mDF@GT5GMvyLuX0 "R – Try It Online") Takes `A` as a `matrix` and 1-based indexes `o`. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~15~~ 13 bytes ``` t3$)&Gw&St3$) ``` Inputs `u`, then `A`. Outputs `B`, then `C` without a separator, as there is no ambiguity. [Try it online!](https://tio.run/##FYwxCsMwEAT7vGKKYEinvZNlGz0gD0hpXKRPOkOer6zhOJbZZb7v8zPGmffH9PxNryuMsSczDVGJ47bn7NgIk42onSSDhRCRxGwg3BA@49JZiZVMtKCCrkmxMysK5N@65WnphjxbkY4/) ### Explanation ``` t % Take input u implicitly. Duplicate u 3$) % Take input A implicitly. Index A with u as row and column indices &G % Push the two inputs again: u, A w % Swap &S % Push indices that would make u sorted. Call that v t % Duplicate v 3$) % Index A with v as row as column indices. Display implcitly ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 33 bytes ``` @(A,u){A(u,u) A([~,v]=sort(u),v)} ``` [Try it online!](https://tio.run/##TU7NCoNgDLt/T5GjQhHT@suHMJ9DPIwxr8KmXsb26q56GIPS0iRNM9@W63bfpy7Lsv2S9LKmrz5ZfaBPho9sY/ecH0uyprKl771Hh4EUqtCiUlRFLRrFVMzGGNZDYeKML2E6HUM476wEUUErsIUWEQZT1FBCDVo6QDgD9XI4j2igDczAGszBQ5KjhBWggt6riALmpi3osgbkL4QL/ZXzf1H2Lw "Octave – Try It Online") Thanks to [Luis](https://codegolf.stackexchange.com/users/36398/luis-mendo) for correcting an error and saving several bytes! Basic indexing works here for both tasks, by defining a vector \$ v \$ equal to the permutation that undoes \$ u \$. That is, if \$ u = ( 3, 1, 2 ) \$ then the first element of \$ v \$ is 2, since 1 is in the second position of \$ u \$. This is accomplished with Octave's [sort](https://octave.sourceforge.io/octave/function/sort.html) function. [Answer] # [Python 3](https://docs.python.org/3/) with numpy, ~~51~~ 45 bytes ``` lambda m,p:[m[x][:,x]for x in(p,p.argsort())] ``` [Try it online!](https://tio.run/##bVDRboQgEHznKza@qA01B3i2vcQvUdPQnN6ZFNwgTfTrLSx3Ty0Pk8kwM8uCu78vVh2zwcV5sD8Gd9ArWGRT2x/f2nxdNRiOl85029Bd@DZMi4MNZlsgx0q72xqSRVkOh9H@c/UOWsiyrGfqDPEIwiaCJBQfxGsGoCJTkhxvpJJbki7PDFRKUwLIJxMm9yl0vBMjVJQTdCdOhLGDGNBrVE0qdYjEm9BBTKU30iyRmqhViJ6FhRiOzjz3U6GuCavVIDPGwuJBtFhNbjHBMdtb8fgMDuuIbQ45h6vfcWxn68vKjetd41g0HJqSiv/kn9P@LYBXEAyDzxcvUxzFIfrLh7m3vc3L4xc "Python 3 – Try It Online") *-6 bytes thanks to @xnor* The function takes two arguments: a `numpy` matrix and a permutation vector having values from \$0\$ to \$n-1\$. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes ``` ii[[#,#]]&/@{#,Ordering@#}& ``` [Try it online!](https://tio.run/##PY6/joJAEMZ7nmLjJlQfkZkBhMJkG2vtCQVRPCn0LoRugw/hG/iEPgI36@E1k5l8f@Z3bcdLd23H/tjO5@3cvx7Pvq4tbNPEa@ct9sOpG/rbl7NTPB90G9fO3g9D99PdTvdVkiQrNZ5r29SWm9i53fHy7WwIR957IhCDZEJkjGcCM3i5hCAMkSmcXqBiWDUlOQzBFOACVIGzv4CREDAbhB4B5/89poLhd7eK6eIuwaXWgzagFPRxpzA5JHtz6SwWdwbRf5WygkoQfahyKAOywBZN8y8 "Wolfram Language (Mathematica) – Try It Online") Input as `f[A][u]`. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~78~~ ~~73~~ 71 bytes ``` ($A,$u=$args)|%{$A[$u]|%{''+$_[$u]} $u=1..$u.count|%{$u.indexof($_-1)}} ``` [Try it online](https://tio.run/##RVDBbsIwDL3nK3wwkGhZhZOW0QOHfsc0VWgr2yREJ1i0SSXfXp6hiIPT9579bNc//V93PH11@/3IO9rQMFpuPKcNb4@fJ3eeDdy8cnoDWCyeuFWcDfJSFJyK9z4dfrUoFd@Hj@6/31lun8XlPGZjrLUiniQgovOGyAbwAB4mHsEjeIzOeaQ9LVEMrOZYAXuiFSLgkRrGcjJCU@OL5rQphFA9mtaqa@gwFIXlLbdWba0D0Q@66Ly7D7jSvuW0tH5Xt1ypOnYItf4MAj1E7kuXVyPs8bo9nWk2wIVTEieclVuwOeHE3EAxebwA). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` ŒJṁ⁸ịⱮ⁹,Ụ¤œị⁸ ``` [Try it online!](https://tio.run/##JU6xDcMwDHtFB2iIrDhtX@gLhscsRR7o6Llb@0LmAt0SZCuQQ@xHVCoFTEiiSNG3cZruZvvzWtfSylK3R/u8W1m5bvN33l9OlMXMUtLIJEwDUwDkgtpnpqRMGphOmLEOGEM8eEwuwnP4vnP@jAZQCAWkdMDfgA4Z2oOAQ7wOvkCjHotr4i64RXI2j47HjxAFUcg/ "Jelly – Try It Online") [Answer] # [J](http://jsoftware.com/), 19 bytes ``` (]/:~"1/:)"_ 1],:/: ``` [Try it online!](https://tio.run/##DYqxCoNAEAX7@4rhCBhB79zdbsEqYJUqvQSRiNjkD/Lrl@UxMDDvarl0B7PTMTDhwVh4vJ5Lu6/Vf1mq9/mNrINXb31K21yw2A0RRBEDFVTRMBNMMUvps59fNo64Rm1/ "J – Try It Online") * Main verb `]/:~"1/:` + The right most `/:` sorts the left arg (matrix) according to the order that would sort the right arg (specified order). This sorts rows. + Now that result get sorted `/:~"1` again according to the order specified `]`. But this time we're sorting with rank 1, ie, we're sorting each row, which has the effect of sorting columns. * `],:/:` We apply the above using both the order specified `]` and the *grade up* of the order specified `/:`. This gives us the 2 results we want. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~77~~ ~~70~~ 68 bytes ``` a=>g=(u,v=[])=>[u.map((i,x)=>u.map(j=>a[i][j],v[i]=x)),v&&g(v,0)[0]] ``` [Try it online!](https://tio.run/##bVPBjoIwFLzzFc0eDCRdpS0qhtTbfsEemx6qVoNxRUGI2Z93sVM21MjlZfKm03nzytF0ptnW5eX2ea529rGXDyPXBxm3tJNKJ3Kt2umPucRxSe89AjjKtVGlVkdNu77Ke5LQbjI5xB1NE5Vq/TBNY@ubrO21LWsbfwB/JEVkpIoUEXNKnh9DWbjCUdgKKNO0ZxLhkOBgLtHDOY4enzum8GI4TnCA@@LPpdDMgVAEVBgoLEXxmkAEdkWGHjSZRwtoAgk/CkwwL42LGNORLqJWqqe5nt@r9vo9h@mCzGbk19YVKc87e7e7aOOCIi/@cQkbz0ZWsJqFrsBMx44JhhrMDa7Qy8aOhR/qZSPozcfb6r2720WYHnr5OFmeQ3MZ7g5MMd6r4C6orUtg2EsomYYbdMpD2uFAebgXJLB4M5Cf8v9NQpO/izMLXwU02buBXl4vmPzdMpfh60UC1bmpTnZ6qg7xPjZJ3CbPX8j9TNOdtZfvW11ub1/X1pwGAiVqQ7c6KR5/ "JavaScript (Node.js) – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 [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") Full program. Prompts for \$u\$ and then \$A\$. Prints \$C\$ next to \$B\$, separated by two spaces ``` ⌷∘⎕¨⍋¨⍛⍮⍨⍮⍨⎕ ``` [Try it online!](https://tio.run/##RY49DoJAEIV7TvFKKUiYmeXvOCQQG6IUFnoBJVFILEhMvACVrb1HmYvgLJK4xcvu2/m@TNk2UXUqm/02qo@HelfV1azdpZ319tbuocP4mbS/@nhq/9J@WnMY/dyM5bSBgMCBnu8bIhCDJMSGrWOwvwpBGCJh8CcSpEa5lZPEHinYugLsPOORDN4i4ORnsb9Fan1sTQ7OTQvKQDFoGYrNLG7ZwjK1ykHMXNhWoBxE4Rc "APL (Dyalog Extended) – Try It Online") `⎕` prompt for \$u\$; `[3,1,2]` `⍮⍨` juxtaposition-selfie; `[[3,1,2],[3,1,2]]` `⍋¨` permutation-inversion of each; `[[2,3,1],[2,3,1]]` `⍛` then `⍮⍨` juxtapose with itself `[[[2,3,1],[2,3,1]],[[3,1,2],[3,1,2]]]` `⌷` reorder `∘` the value of `⎕` \$A\$ as inputted `¨` using each pair as a set of orders, one order per axis [Answer] # [J](http://jsoftware.com/), ~~17 16 15~~ 14 bytes -1 thanks to @Jonah ``` ([{"1{)~(,:/:) ``` [Try it online!](https://tio.run/##NZCxasNAEET7/YrBGGwR27ndlU6nA1WBVKnSpgjGxIQ0rlwZ8uvKrC8WQoi7Zd68/VlWh815rptdQk37w8v72@uy/bit9Nb9bnf1uXZLJ8e5ZuS1D1BkWIZOsB5wuGGEKcxhAw8UvIHx5XECCqzAHTpCEzRGEgZ4DzUovxno4QydoBwrUJXrXD/1yTlHEq9Nvk7fFxxxxlXaf7SVPR8RPGCEE4xJIv0eTRYxGCTSIzpgxHgWPCQoRSGoRMtWsURdKxJq/17h6CYSHm0iNTOJ1i23NA9hXMslgP2RJVxbGy4t7CVW1nLvO8QosbPmMNIBlO6WPw "J – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` E⟦ηEη⌕ηκ⟧Eθ⪫Eθ§§θ§ιμ§ιξ ``` [Try it online!](https://tio.run/##VZDNCsIwEITvPsXiKYEIblL/8ORFUBC8hxyKChZr1VKkbx83nQjay9fZnZmkPV3L9vQo6xiPbdV06lA@lb8aShRsq@aceNM6YPgytH9Ujcrvm27XnC@9@vJnVBm6a/2ne50GYxoL9TpG70ee3MxQehiYD7AAr6CKYMRJblDOwrnADjmLnZ0NTpfLECcEbEbOTdG5hAIcWhgWngK5E4pwXVdgh07Oao5OKJc/BZfgXI2DmMNI/qiXuJilUsrFwCHEybv@AA "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Note: Trailing space. Explanation: ``` η Input `u` E Map over elements ⌕ Index of κ Current index in η Input `u` η Input `u` E⟦ ⟧ Map over `u` and its inverse θ Input `A` E Map over elements θ Input `A` E Map over elements θ Input `A` § Indexed by ι Current vector § Indexed by μ Row index § Indexed by ι Current vector § Indexed by ξ Column index ⪫ Join with spaces for readability Implicitly print ``` [Answer] # [Kotlin](https://kotlinlang.org), 213 bytes ``` {a:List<List<Int>>,u:List<Int>->val s=u.size for(l in List(s){r->List(s){c->a[u[r]][u[c]]}})println(l.joinToString(" ")) for(l in List(s){r->List(s){c->a[u.indexOf(r)][u.indexOf(c)]}})println(l.joinToString(" "))} ``` [Try it online!](https://tio.run/##rVjbbtw4En33V1SMBaYFtNuW5PvGBhzv7CJABgEmARaLTD/Qana3YjXVESlfJuP3fd6X@aD5k/mR7KkiKcmXycTYNWy3RB7W9RRZ7MvaVaX5sr1Nr826dcdkarcszYLmdUNuqWmm56qtHDltHRXKarsBMCYNYaG2VM/xaNeq0GT1WjXK6RmVxumFbgQbJa2Ua8qbMa2r1pKS1YPFjHy8HguVI9Voak35qdV0od211obRP@umJmVmVENQpa2ADZnJBs@eN1okee2lpaKeaVrU1ZyKpaoqbRb6mIFL59b2eHub53l6Yp0qLvUNUIBMinq1/Wk7PcqzvV2G/6jrZqYbOBD9cdclfBel/6pbMXZRXmkDiP3U8qv57Vcj834JnY3Fbo4BgjqChVe6cHWTUIuIMJDNc0vEpqiNU6XhjHAMTbu64LCkeGvqdrFksBERO3GIzO///k@aTNga@K7sJcF9VzO0CdazrKKu2pWxYkpTX0smMT60k1RRYIFor2WRX27XuijnpZ4xuDTUToif3nOySjumW8ThuqwqNt@6pi1cFy96xcjrpUZcWOCoHH9MtuCrrvRKGye28ng7KpMxY9vRx@QeAnaeiXdkl3VbIZCVFe/q1oHDsrw0V4iT9j5BpCpcWZu/Cp/EaFj5pHoW7m3XRtxr1wSv1rUtWUKwS2xizxUZfT0I2bln39@REH2jVutKjwMbZPyMTugDP6QpZSnlqTxnlGWUZ/KcU5ZTnk@96wzP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kGXfIMAnszpjS5Gsa8z0gxrQPMfhLj/C5@1gSa4C0A28dK8z2eiPytF/AAryZGaN3etQhXg/ZUqg56BekbOJQGN5hU747FodT/tx/bBGGczYa@jgGKSSn8PRx1CBjVyRCbh6jIZsp@iHftXEP9uW/ "Kotlin – Try It Online") [Answer] # APL+WIN, 21 bytes Prompts for input of u followed by a. Outputs b immediately over the top of c with no separator: ``` (a←⎕)[u;u←⎕]⋄a[⍋u;⍋u] ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##JY4xCsJAEEX7nOKXWgiZmWRNyBX0BCHFokSEgIKksBcVQsTGm3iivUj8G5vP7OfNm/XnbrW/@u50WO06f7kcd1N4fbabcH9bEp6Pdlp4zuyWdV/1/7EJw83XYRz6KkYzEZzaxCBQpoXxKwJRiEHZKZStwBRmSQRzOMIZcQdH3HI@HZRtCc1gkV3Py1TkcZn9bGKbooAWdEHWkBRCIKXTsvko09Ft9JXxC1JA5Ac "APL (Dyalog Classic) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 79 bytes ``` sub{$[=1;($A,$u)=@_;@$v[@$u]=(1..@$u);map{$x=$_;[map[@$_[@$x]],@$A[@$x]]}$u,$v} ``` [Try it online!](https://tio.run/##dc3BCsIwDIDhe59ilBw2iMO0eAqVzkfYtZah4EDQOaYdg7Fnr53i0UPgI/kh/WW47SK0Jj7DeQZniHOoEEJhbMMWRmcheJNTWSYUfD/1M0wGGnaJ6dikmbxHC9VXCwSEcYksbG2g3exz54iQFJL26BShUqhWakKtUGu/GtPeFyxEP1y7VyYrIyR/LNOTYyez9jFkdobabf3Cv@zwP6M1i28 "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12 11~~ 13 [bytes](https://github.com/DennisMitchell/jelly) +2 :( to fix cases when B = C ``` ṭþ`œị¥@Ƭị@2,0 ``` A dyadic Link accepting a list of lists, `A` (`n` by `n`), on the left and a list of the first `n` integers on the right, `u`, which yields a list of lists of lists, `[B, C]`. **[Try it online!](https://tio.run/##JY69DQIxDIV7pvAAKWL77oDu9ogi0dCgW4AZKJmBDgZASBQg2OMmCZ@P4un5531xDvtpOrY232/v5@5znh@n12X8XvHRUm6tleJ9ElE0JDGkW7yrq1TEk7ixWTMhYfTWx8YjT07YWigSeWE2VMjJKlPN6M9QCbe8YwKj4cPCUHlc50UNDl611lZoIOJTKUJWfw "Jelly – Try It Online")** ### How? ``` ṭþ`œị¥@Ƭị@2,0 - Link: A, u Ƭ - collect up while the results are no longer unique, applying: ¥@ - last two links as a dyad with swapped arguments: ` - use left (u) as both arguments of: þ - outer product with: ṭ - tack œị - multi-dimensional index into last result (starting with A) ...at the end of the Ƭ-loop we have [A,B,...,C] or [A] if A=B=C or [A,B] if B=C but A!=B 2,0 - literal pair [2,0] @ - with swapped arguments: ị - index into (1-based & modular) -> [B,C] or [A,A]=[B,C] if A=B=C or [B,B]=[B,C] if B=C ``` [Answer] # q, 26 bytes ``` {Y:iasc y;(x[y;y];x[Y;Y])} ``` `iasc` returns indexes to sort it's argument. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 91 bytes ``` import StdEnv $a u=map(\l={{a.[i,j]\\j<-l}\\i<-l})[u,[k\\i<-[0..]&_<-u,j<-u&k<-[0..]|j==i]] ``` [Try it online!](https://tio.run/##PZBfS8MwFMWf209xwTEU2tI029SxPAz0YeDbHpMgoauaru3G1ihS89WNWW9mIDmc3HN/@VM2lepce9iZpoJW6c7p9ng49bDtd8/dZzxRYFirjreiYcOgMq6TWgpRr9LGCqEvcsdNwvej4XmWyenrKjWJT5jpPmz91IxpKd22Vx69XAIfhk3XWytj3GIwgTWY@OujOlVxtAYWR9FwMy50nsBlEJTFKAUKeUQ3s8mYBTp6WmD2HqvYWWCtmIcsDUBEALYUQUJnfuU@oEehSCIYIjnKPxc94LXpDKvIJcEtrlz0NDwKr0ICHg8jxPqon8b/EvcY3@LR/hAfI9L9lm@Nej@7dPPinr471ery/Ac "Clean – Try It Online") Defines `$ :: {{a}} [Int] -> [{{a}}]` (used with `a = Int`) taking an array of arrays and a list of zero-based indices, returning a list of arrays of arrays containing B and C. [Answer] # [Python 3](https://docs.python.org/3/), 91 bytes ``` lambda a,u:[[[a[y][x]for x in t]for y in t]for t in[u,[u.index(i)for i in range(len(u))]]] ``` [Try it online!](https://tio.run/##TVJda4MwFH33V2S@qOMwTGLVFhz0YYPBHgZ9zHxwbdyEzkobof313U1i60BCOPfc8xEcLubn0MtrW31e983v165hDcaVUqpRl1qd6/ZwZGfW9cy462W@GrqqEWp86vqdPsddYtHOEo5N/63jve7jMUnqug6uO90yo08m7vphNCcwfR701uhdsgoYa7ZmbPasYm386AkJocOx600cfqw3m5B17Z1V3ZeZ3p80C1/Xb@/hvHGziKrnaEajtVtfRZiE7GhWfZhVbaL71ssNjP5lJkLg2sRKyQU4cogcfAmR1QiUhBQoIDiEhFg4iIOmEPTRILVQCVFCSvACPAX3tBQLyAxcgNOZWyyDJPklOFFLcF4TGCiBjKgpCKwTCyg1aYO8yGfp9DKvAxImTedhpawOCZCkdB5TeFAZW8StSh8LpU0oSosVvhCZUjcpfBJlCzha6htZpg3rHEqf3hnnkwV50ZM5mriFy1xxR@OThX9GB4lbr8I@I/1RyfUP "Python 3 – Try It Online") Takes parameters as a 2D and 1D list and returns a list containing two 2D lists B and C. I'm not sure if there's a cleaner way to do all the for-loops. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~148~~ 142 bytes ``` #import<queue> #define q[o[i/z]*z+o[i%z]] using V=std::vector<int>;int f(V m,V o,V&r,V&R,int z){int i=z*z;for(r=R=V(i);i--;r[i]=m q)R q=m[i];} ``` [Try it online!](https://tio.run/##lZTfjppAFMbv5ylOdtMGdMwyA6Iu4EX7AE288MY1jVHczGb54whtg/HZ7TeAFbXbpCQDwznfnPM7ZxjWeT54Xa9Pp0eV5Jkuwl0Zl/GUPW7irUpj2i2yhXqqlr2qj8mnarlk5V6lrzSP9sXm@flHvC4yHaq0mAa40daaU8LnlPH5Z40x48Za2QfzUFHVq4Jtpi0dzaK5pexADQaBXqhllNDOntEuSvASHE@3wSlZFVr9IoroQCQ4SU4uJ48zur6GnHxOI07jO9eEC4cLwYW8dQmXC4@LIRf@MbjxsTuUTG9iTdFBcizjDlawe1EiG1QXQMD1iUtwiQme19AucVcSH8FhykJRctgVuIL4BEb4zTA65yrAGBYMF4EE6hYOmUq6EWAZQuDBgRDCPMHTjQGTaxCBh16QGGMIU9hdXaUpC1E8blrt1LsgCNKnHotw0beyyMuCovqFfYEc7MCWjikFNUyozgwckAAEeMAaNlYQiDFyg0i45PoNpG8aJz00kyTmbQDX1CqGaIBA@HFjJUxdtBB9lYLQ2cbKvgIEskbuGDnWs2bz23ww@QagAfHbhMgsANBI5RnYAzAqaKSizeeafKPWKM8Vj1CxZL0nfCWPKl2/l5uYQpXtCx2vkumVLVmlKp@2JyxdJfE@X61jwiZgK8wJyjXu3xOLcMqIU322yD4wwqEiq35XKNShAM8QvoD6fVUrOpK3VvL2R/JGtqFeZ9i5MKR9XPy0XNtMkwWpXkV9iJfm/YEezAlhF/HDS2pMR3bsMmaGMfsfxk7IDEm76a5TtXmSlUotmw6sbQpitz8J/BfIRseul7VckDUHuFXdfeGazwK2tc6xWjGs3IPcxAzDON28B5fE2rj@6rksakFe0sHN1YGra8Dhwvf2L/7yrAAl1GVD539M539IZxax@oPVcVHqlBzT39Nv "C++ (gcc) – Try It Online") Thanks to @ceilingcat suggestion to use #import <queue> instead of <vector> which mysteriously brings std::vector ]
[Question] [ Given a decimal number `k`, find the smallest integer `n` such that the square root of `n` is within `k` of an integer. However, the distance should be nonzero - `n` cannot be a perfect square. Given `k`, a decimal number or a fraction (whichever is easier for you), such that `0 < k < 1`, output the smallest positive integer `n` such that the difference between the square root of `n` and the closest integer to the square root of `n` is less than or equal to `k` but nonzero. If `i` is the closest integer to the square root of `n`, you are looking for the first `n` where `0 < |i - sqrt(n)| <= k`. # Rules * You cannot use a language's insufficient implementation of non-integer numbers to trivialize the problem. * Otherwise, you can assume that `k` will not cause problems with, for example, floating point rounding. # Test Cases ``` .9 > 2 .5 > 2 .4 > 3 .3 > 3 .25 > 5 .2 > 8 .1 > 26 .05 > 101 .03 > 288 .01 > 2501 .005 > 10001 .003 > 27888 .001 > 250001 .0005 > 1000001 .0003 > 2778888 .0001 > 25000001 .0314159 > 255 .00314159 > 25599 .000314159 > 2534463 ``` Comma separated test case inputs: ``` 0.9, 0.5, 0.4, 0.3, 0.25, 0.2, 0.1, 0.05, 0.03, 0.01, 0.005, 0.003, 0.001, 0.0005, 0.0003, 0.0001, 0.0314159, 0.00314159, 0.000314159 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes ``` Min[⌈.5/#+{-#,#}/2⌉^2+{1,-1}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfNzMv@lFPh56pvrJ2ta6yjnKtvtGjns44I@1qQx1dw9pYtf8BRZl5JdHKCrp2CmnRyrGxCmoK@g4K1QZ6ljoKBnqmIMIERBiDCCMw3whEGIIIAzDfACxnABGBCkHFYIIwUZgwVNzY0MTQ1BKqAYkN5dT@BwA "Wolfram Language (Mathematica) – Try It Online") ### Explanation The result must be of the form \$m^2 \pm 1\$ for some \$m \in \mathbb{N}\$. Solving the inequations \$\sqrt{m^2+1} - m \le k\$ and \$m - \sqrt{m^2-1} \le k\$, we get \$m \ge \frac{1-k^2}{2k}\$ and \$m \ge \frac{1+k^2}{2k}\$ respectively. So the result is \$\operatorname{min}\left({\left\lceil \frac{1-k^2}{2k} \right\rceil}^2+1, {\left\lceil \frac{1+k^2}{2k} \right\rceil}^2-1\right)\$. [Answer] # [Python](https://docs.python.org/2/), 42 bytes ``` lambda k:((k-1/k)//2)**2+1-2*(k<1/k%2<2-k) ``` [Try it online!](https://tio.run/##Tc7RDoIgFMbx63qKc@MGFAJHvdDZk1QXtsZyp9A5b3x6EoKtm//4foyNeVtfk0NvLzf/Hj6P5wDUMUbSKOJKIRcCT0aiYNTvVGCPkri30wIEo4OrLtsz6LIJqUOqEIwbQ0yIjlvHO/2TRMkyZs2cvDK1adr04O@cxr07HuZldCtYtv/uCw "Python 2 – Try It Online") Based on [alephalpha's formula](https://codegolf.stackexchange.com/a/180415/20260), explicitly checking if we're in the \$m^2-1\$ or \$m^2+1\$ case via the condition `k<1/k%2<2-k`. Python 3.8 can save a byte with an inline assignment. **[Python 3.8](https://docs.python.org/3.8/), 41 bytes** ``` lambda k:((a:=k-1/k)//2)**2-1+2*(a/2%1<k) ``` [Try it online!](https://tio.run/##TcvRCsIgFMbx63oKbwJdbepxgybtSaoLI6RxlhPZTU9vaArd/PH7HfSf7bU6dfYh2ukWF/N@PA1BTanRE7aSI@McWNNAK4/QUMPhIC/Iol0DQTI7chXdeCKiG1L6FJUCeUOKTBF5i3wTPylUrGLVysWV7OUwlg9/7zLuer/zYXYbtRQZi18 "Python 3.8 (pre-release) – Try It Online") These beat my recursive solution: **50 bytes** ``` f=lambda k,x=1:k>.5-abs(x**.5%1-.5)>0 or-~f(k,x+1) ``` [Try it online!](https://tio.run/##TY7BCoMwDIbP8ylyGWjV0qo9KOiLjB10U1bUVtoO9LJXd62rsEM@8n9JIMtmXlJkO58XqQzoTQe2sO6N6h9vpbkUE5@5CSlBiEX7UE/t3D1bGJO1ptXYYJa2nQ5XhDC70hSzqCEgVfoZQrsSU3siFYzABdwILhMgmDkUDrlDduTMgTqQI5NjRn7GK@9OedpTe5/TgrLSH/z1Ptyr4LIoLgzYD6P9Cw "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` nD(‚>I·/înTS·<-ß ``` Port of [*@alephalpha*'s Mathematica answer](https://codegolf.stackexchange.com/a/180415/52210), with inspiration from [*@Sok*'s Pyth answer](https://codegolf.stackexchange.com/a/180424/52210), so make sure to upvote both of them! [Try it online](https://tio.run/##yy9OTMpM/f8/z0XjUcMsO89D2/UPr8sLCT603Ub38Pz//w30DEwB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/PBeNRw2z7CoPbdc/vC4vJPjQdhvdw/P/6/yPNtCz1FEw0DMFESYgwhhEGIH5RiDCEEQYgPkGYDkDiAhUCCoGE4SJwoSh4saGJoamllANSGwoJxYA). **Explanation:** ``` n # Take the square of the (implicit) input # i.e. 0.05 → 0.0025 D(‚ # Pair it with its negative # i.e. 0.0025 → [0.0025,-0.0025] > # Increment both by 1 # i.e. [0.0025,-0.0025] → [1.0025,0.9975] I· # Push the input doubled # i.e. 0.05 → 0.1 / # Divide both numbers with this doubled input # i.e. [1.0025,0.9975] / 0.1 → [10.025,9.975] î # Round both up # i.e. [10.025,9.975] → [11.0,10.0] n # Take the square of those # i.e. [11.0,10.0] → [121.0,100.0] TS # Push [1,0] · # Double both to [2,0] < # Decrease both by 1 to [1,-1] - # Decrease the earlier numbers by this # i.e. [121.0,100.0] - [1,-1] → [120.0,101.0] ß # Pop and push the minimum of the two # i.e. [120.0,101.0] → 101.0 # (which is output implicitly) ``` [Answer] # JavaScript (ES7), ~~51~~ 50 bytes ``` f=(k,n)=>!(d=(s=n**.5)+~(s-.5))|d*d>k*k?f(k,-~n):n ``` [Try it online!](https://tio.run/##fc7RDoIgGAXg@57C7oASQf2btmHP4kRa4aBF66r56uRqbhRObrj4DudwbZ@t6@6X2yM1VvbeK4H03mDRbJEUyAlDCAW8G5FLpxu/JJGNJvqkplg6Gnw0vrPG2aGngz0jhRitk8/BOMmyJN/8M6xzGXIRcbHOOQQMMYevq4j5z9cOkbOwnTMeB4qwoIoXGA8DsFTxHZk32OIKLznUcwn4Nw "JavaScript (Node.js) – Try It Online") (fails for the test cases that require too much recursion) --- # Non-recursive version, ~~57~~ 56 bytes ``` k=>{for(n=1;!(d=(s=++n**.5)+~(s-.5))|d*d>k*k;);return n} ``` [Try it online!](https://tio.run/##hc9JDoMgAIXhfU9hd6BRQcRqDN7FODStBhq13XS4up0citDIhs2X98MxvaRt1hxOnc1FXvQl6yuWXEvRAM5wvAU5Ay2zLG6aDoXWA7T264a33MyTyqxiGDdFd264we99Jngr6sKpxR6UADmRMRwIDdc1vM0S0DXgy4AogKwBj0qAqkBeCBWAF48MFIHkBkZYJUQeCdUOwjKhupkxNZaQFhFpaBfqamNuqumnhuDc@8OIVHwndc0h@tPUzhHsYxrNjur@@DUTiSLtsz5qRMT3A9I/AQ "JavaScript (Node.js) – Try It Online") Or for **55 bytes**: ``` k=>eval(`for(n=1;!(d=(s=++n**.5)+~(s-.5))|d*d>k*k;);n`) ``` [Try it online!](https://tio.run/##hc/PDoIgAMfxe09hN9CpIGI6h8@iE22lg6bNU@vV7Z9mCE0uXD77feFcDEVfdqfL1RWSV2PNxoZl1VC0IK9lBwTD6R5wBnrmOMK2PQqdO@jd5w1v3OZZYzcpTEUOx1KKXraV18ojqAHyEms6EFq@bwW7NaBbIFQB0QDZAgFVANWBuhBrAK8eGWkCqQ2MsE6IOhLrHYRVQk0zc2ouISMiytAhNtXm3LdmnpqCS@8PI0rxlTQ1p@hP0zhHcIhpsjhq@uPHfEmSGJ/1VjMiYRiR8QE "JavaScript (Node.js) – Try It Online") (but this one is significantly slower) [Answer] # [J](http://jsoftware.com/), ~~39~~ 29 bytes ``` [:<./_1 1++:*:@>.@%~1+(,-)@*: ``` NB. This shorter version simply uses @alephalpha's formula. [Try it online!](https://tio.run/##hdC9CsIwEMDxvU9xCFLtR8w1TU2DlYLg5OTq4CAWcfENfPWqmEvJBTGQ5fhx/7T3cSbSAToLKRQgwb5vKWB3POzHk92I1RkB89xmtt@Kfv7EfFGUyz6z4zJJrpfbAyrwp4MBpGinwQ@huVBc1H@F4kJzUWkmTCSilzZMIBcoMRSSVypjmFBcaL/ECYwqkmZOTBm3Y22oQ0JFFVpCAuOKG5LwGap8MiYQKq58l3iBTGj@P7BG3Qaibdm3ECGh6rpR4TscSVwsGV8 "J – Try It Online") ## 39 bytes, original, brute force ``` 2(>:@])^:((<+.0=])(<.-.)@(-<.)@%:)^:_~] ``` [Try it online!](https://tio.run/##hdBBC4IwFMDxu5/iEYSTcmxus21oBEGnTt2tQyTRpW/QV19Ge4pvRIIenj/ef/oIC5730HrIYQ0C/HCXHPan4yFUbOt3XXH2jDUrLtquYA0vebFjZTM8l354dXl1ociy2/X@hArGq4UeBHfT4IcwVCgq9F@hqDBUVIYIm4jkpDURkgop5FwIWqmsJUJRYcYlUcikInAWxZSJOzYWOyhUUsElKGRaiUMUYwYrn4ydCZVWvktGIYkw9H9ILY2bCefItyBBobSu1fwckWThDQ "J – Try It Online") Handles all test cases [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~18~~ 16 bytes -2 bytes from [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) ``` _=¬u1)©U>½-½aZ}a ``` [Try it online!](https://tio.run/##y0osKPn/P9720JpSQ81DK0PtDu3VPbQ3Mao28f//aD1LHT1THT0THT1jHT0jIMtIR89QR88AyDIAihiA2GAOmAfhQvgQAbCIsaGJoaklWBGcBWXGcunmAgA "Japt – Try It Online") [Answer] # Pyth, ~~22~~ 21 bytes ``` hSm-^.Ech*d^Q2yQ2d_B1 ``` Try it online [here](https://pyth.herokuapp.com/?code=hSm-%5E.Ech%2ad%5EQ2yQ2d_B1&input=0.12345&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=hSm-%5E.Ech%2ad%5EQ2yQ2d_B1&test_suite=1&test_suite_input=0.9%0A0.5%0A0.4%0A0.3%0A0.25%0A0.2%0A0.1%0A0.05%0A0.03%0A0.01%0A0.005%0A0.003%0A0.001%0A0.0005%0A0.0003%0A0.0001%0A0.0314159%0A0.00314159%0A0.000314159&debug=0). Another port of [alephalpha's excellent answer](https://codegolf.stackexchange.com/a/180415/41020), make sure to give them an upvote! ``` hSm-^.Ech*d^Q2yQ2d_B1 Implicit: Q=eval(input()) _B1 [1,-1] m Map each element of the above, as d, using: ^Q2 Q^2 *d Multiply by d h Increment c yQ Divide by (2 * Q) .E Round up ^ 2 Square - d Subtract d S Sort h Take first element, implicit print ``` *Edit: Saved a byte, thanks to Kevin Cruijssen* [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~34~~ ~~33~~ 29 bytes *-1 byte thanks to Grimy* ``` {+(1...$_>*.sqrt*(1|-1)%1>0)} ``` [Try it online!](https://tio.run/##VYxRC4IwFEaf268YUuGMLrvOmXtof0QkghQCy9IgZPnbl5nl3Ns59zu75XUZ20tL1wXdW7PxEQCWBx1Ac68fgY@vLbIVas46W1Q19cvzNW@0hmdVnxpGDVk0x5Z6pvAh5RnrqIE0zDqPdBYU/T1NQwJyjpGDgoCYYygnlD0614QAul/FBLizRo69EM4g6QuOjpDD5B99Gv5VYhrtkqETGKFUYyeHzWgGodQb "Perl 6 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 27 [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") ``` ⌊/0~⍨¯1 1+2*⍨∘⌈+⍨÷⍨1(+,-)×⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FPl75B3aPeFYfWGyoYahtpAZmPOmY86unQBrIObwcShhraOrqah6cDmf/THrVNeNTb96hvqqf/o67mQ@uNH7VNBPKCg5yBZIiHZ/D/R72r0g6tMNCz1FEw0DMFESYgwhhEGIH5RiDCEEQYgPkGYDkDiAhUCCoGE4SJwoSh4saGJoamllANSGwoBwA "APL (Dyalog Unicode) – Try It Online") Monadic train taking one argument. This is a port of [alephalpha's answer](https://codegolf.stackexchange.com/a/180415/74163). ### How: ``` ⌊/0~⍨¯1 1+2*⍨∘⌈+⍨÷⍨1(+,-)×⍨ ⍝ Monadic train ×⍨ ⍝ Square of the argument 1(+,-) ⍝ 1 ± that (returns 1+k^2, 1-k^2) ÷⍨ ⍝ divided by +⍨ ⍝ twice the argument ∘⌈ ⍝ Ceiling 2*⍨ ⍝ Squared ¯1 1+ ⍝ -1 to the first, +1 to the second 0~⍨ ⍝ Removing the zeroes ⌊/ ⍝ Return the smallest ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~89~~ ~~85~~ 71 bytes ``` k=>{double n=2,p;for(;!((p=Math.Sqrt(n)%1)>0&p<k|1-p<k);n++);return n;} ``` [Try it online!](https://tio.run/##hY/BS8MwFMbv@StiUZew9tF062Fk7U1hoDjcwIuX2KasbLzWNPUy97fXrBFREPYOye/73sfjvaKLiq4e7nsslmXTvx106L@8yoZ9lh@9opglYSurxjB5xVibPSq7g827sQz5jeB5fNsu958ici@XOJ1yabTtDVKUp0GSF1Nb/VCjZsEK297S/@qpt64V8D/x6EKd424trYod@1CGKlojXSE8a1VumzssGYdNe6gtm7zihPNfs6@DowojkZ7cmRXzh8JamU4zxXnoGm74AAsCKYE5gRmBxFFCQBCIHcXOic88ilF56bU3Rmcm5iJdjKEf@sYv "C# (Visual C# Interactive Compiler) – Try It Online") -4 bytes thanks to Kevin Cruijssen! [Answer] # [Java (JDK)](http://jdk.java.net/), ~~73~~ 70 bytes ``` k->{double i=1,j;for(;(j=Math.sqrt(++i)%1)==0|j>=k&1-j>=k;);return i;} ``` [Try it online!](https://tio.run/##fZA9b8MgEIZn@1ewtAIlRjgfQ4IcqUPHqEPGqgO1aYK/C@dIkevf7oJNqkxleI/3uTt0Ry6uIsqzYlRV22hAufW0A1XSF63FzfAwbLvPUqUoLYUx6ChUjfow8NCAABuujcpQZVP4BFrV5/cPJPTZEFcZZI2tlRaBNJAKIw1KUM/obokY3TrZOFk7WU1@5SR2wibPphybiUee3eGd3rHn63gTb3e@4eHuzcDtfPOi1ICWosJ/QxJaiRaPRXTo5w2QSuJlzr8ajTnOk6OACzXfGvBiochTTJKE/eSHpHiOIxc44VpCp2uk@DAGAfr3EGrffRXp5U1nUssMn24GZEWbDvb71v4plDWx0w7hMP4C "Java (JDK) – Try It Online") `-3 bytes` thanks to @ceilingcat [Answer] # Java 8, 85 bytes ``` n->{double i=1,p;for(;Math.abs(Math.round(p=Math.sqrt(i))-p)>n|p%1==0;i++);return i;} ``` [Port of *EmbodimentOfIgnorance*'s C# .NET answer.](https://codegolf.stackexchange.com/a/180417/52210) [Try it online.](https://tio.run/##TZA7b8MgFIX3/IqrSJVAjhHOY0iQs3ROloxRBmKTltTBFHCqKvVvd4HgqsvRPR@Pc@DK7zy/1h9D1XBrYcelekwApHLCXHglYB8sQN1250ZAhdKgMPO8n3ixjjtZwR4UlIPKt4@0RZbFTLNLaxDbcfdO@NmiOJi2UzXSZTT20zgkMc413qof/VKUJWUyyzAzwnVGgWT9wEKO9rf6nBR3b2UNN18XHZyR6u14Ao6fXUNk6uCEda/cCtiAEl/pFcfTg5L1DChZBVkGWQSZRz8PUgSh0dO4Rp8kocRGONIRJ74olsVqnQ78m5PpcawLcPi2TtxI2zmi/Vtco9BYPJtuYJopUv0RnH6@H34B) The `Math.round` can alternatively be this, but unfortunately it's the same byte-count: ``` n->{double i=1,p;for(;Math.abs((int)((p=Math.sqrt(i))+.5)-p)>n|p%1==0;i++);return i;} ``` [Try it online.](https://tio.run/##TZDBb8IgFMbv/hUvJksgtYSqPSipl5314tF4wBY3XKUMqMvS9W/voNJlly/v/YD3fY8bf/D0Vn0MZc2thT2XqpsBSOWEufJSwCG0AFXTXmoBJYqFwszzfubFOu5kCQdQUAwq3XXxiiyyhWbXxiC25@6d8ItFyA/GCOliJPbTOCQxTkiOU4136ke/ZEVBmUwSzIxwrVEgWT@w4KP9VO8T7R6NrODu46KjM1K9nc7A8TNrsIwZnLDulVsBW1DiK25xOneUbBZASR5kHWQVZDn2yyBZEDr2dDyjTxJRZBOc6IQjX2XrLN/EB//q2PR4jAtw/LZO3EnTOqL9Lq5WaAqezLcwTxQp/wiOP98Pvw) [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 16 bytes ``` ²_b*α)½╠ü²1bαm,╓ ``` [Try it online!](https://tio.run/##y00syUjPz0n7///QpvgkrXMbNQ/tfTR1weE9hzYZJp3bmKvzaOrk///1LLn0TLn0TLj0jLn0jIAsIy49Qy49AwMDY0MTQ1PL/wA "MathGolf – Try It Online") Not a huge fan of this solution. It is a port of the 05AB1E solution, which is based on the same formula most answers are using. ## Explanation ``` ² pop a : push(a*a) _ duplicate TOS b push -1 * pop a, b : push(a*b) α wrap last two elements in array ) increment ½ halve ╠ pop a, b, push b/a ü ceiling with implicit map ² pop a : push(a*a) 1 push 1 b push -1 α wrap last two elements in array m explicit map , pop a, b, push b-a ╓ min of list ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 76 bytes ``` : f 1 begin 1+ dup s>f fsqrt fdup fround f- fabs fdup f0> fover f< * until ; ``` [Try it online!](https://tio.run/##VY3LDoIwEEX3fsUNSw3NlMeiYvgXEQZJTMEW/H0saW3j6uTeMw@ezfrMRz6w71cwJLphnDTkBf22wLYMtm@zgo/IZt50D87B986Gjlrw/BkM@IYzNr1OLzTu2OK9JCh3loXpF4gMyFtk7pPAw6A5kVCDGyVRe1QepUcR2sJDelBoKUzRr48imqSSSzLaUlayVnH5L6W4fwE "Forth (gforth) – Try It Online") ### Explanation Starts a counter at 1 and Increments it in a loop. Each iteration it checks if the absolute value of the counter's square root - the closest integer is less than k ### Code Explanation ``` : f \ start a new word definition 1 \ place a counter on the stack, start it at 1 begin \ start and indefinite loop 1+ \ add 1 to the counter dup s>f \ convert a copy of the counter to a float fsqrt \ get the square root of the counter fdup fround f- \ get the difference between the square root and the next closes integer fabs fdup \ get the absolute value of the result and duplicate f0> \ check if the result is greater than 0 (not perfect square) fover f< \ bring k to the top of the float stack and check if the sqrt is less than k * \ multiply the two results (shorter "and" in this case) until \ end loop if result ("and" of both conditions) is true ; \ end word definition ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) I have not managed to get anything terser than the same approach as alephalpha - go upvote his [Mathematica answer](https://codegolf.stackexchange.com/a/180415/53748)! ``` ²;N$‘÷ḤĊ²_Ø+Ṃ ``` **[Try it online!](https://tio.run/##y0rNyan8///QJms/lUcNMw5vf7hjyZGuQ5viD8/Qfriz6f/RPYfbHzWtcf//30DPUkfBQM8URJiACGMQYQTmG4EIQxBhAOYbgOUMICJQIagYTBAmChOGihsbmhiaWkI1ILGhHAA "Jelly – Try It Online")** ### How? ``` ²;N$‘÷ḤĊ²_Ø+Ṃ - Link: number, n (in (0,1)) ² - square n -> n² $ - last two links as a monad: N - negate -> -(n²) ; - concatenate -> [n², -(n²)] ‘ - increment -> [1+n², 1-(n²)] Ḥ - double n -> 2n ÷ - divide -> [(1+n²)/n/2, (1-(n²))/n/2] Ċ - ceiling -> [⌈(1+n²)/n/2⌉, ⌈(1-(n²))/n/2⌉] ² - square -> [⌈(1+n²)/n/2⌉², ⌈(1-(n²))/n/2⌉²] Ø+ - literal -> [1,-1] _ - subtract -> [⌈(1+n²)/n/2⌉²-1, ⌈(1-(n²))/n/2⌉²+1] Ṃ - minimum -> min(⌈(1+n²)/n/2⌉²-1, ⌈(1-(n²))/n/2⌉²+1) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` _=¬aZ¬r¹©U¨Z}a ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Xz2sYVqscrmpVahafWE&input=LjI) ``` _=¬aZ¬r¹©U¨Z}a :Implicit input of integer U _ :Function taking an integer Z as an argument = : Reassign to Z ¬ : Square root of Z a : Absolute difference with Z¬ : Square root of Z r : Round to the nearest integer ¹ : End reassignment © : Logical AND with U¨Z : U greater than or equal to Z } :End function a :Return the first integer that returns true when passed through that function ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 42 bytes ``` $t=sqrt++$\while($p=abs$t-int$t)>$_||!$p}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/1@lxLa4sKhEW1slpjwjMydVQ6XANjGpWKVENzOvRKVE004lvqZGUaWgtvr/fz3Df/kFJZn5ecX/dQsA "Perl 5 – Try It Online") ]
[Question] [ ### Background [Jelly](https://github.com/DennisMitchell/jelly)'s arithmetic atoms vectorize automatically. In fact, **x + y** is well-defined whenever **x** and **y** are numbers or ragged arrays of numbers. Jelly's source code implements this behavior using a generic vectorizer, but for this challenge, we'll only consider addition of integers and nested integer arrays. ### Definitions Define the depth of **x** as **0** if **x** is an integer, as **1** if it is a (possibly empty) flat array of integers, and as **n + 1** if it contains at least one element of depth **n** and no elements of depth **k > n**. This way, **1** has depth **0**, **[]** and **[1]** and **[1, 1]** have depth **1**, **[[], []]** and **[[1], [1]]** and **[[1]]** and **[1, []]** have depth **2**, **[1, [1, [1]]]** has depth **3**, etc. The operation **x + y** is defined as follows. 1. If **x** and **y** have depth **0**, return their sum. 2. If **x** and **y** have equal but positive depths, recursively apply **+** to all items of **x** and the corresponding items of **y**. If **x** and **y** have different lengths, append the tail of the longer array to the array of sums. Return the result. 3. If **x**'s depth is strictly smaller than **y's** depth, recursively apply **+** to **x** and all items of **y**, and return the result. Do the opposite if **y**'s depth is strictly smaller than **x**'s. For example, consider the operation **[1, [2, 3], [4]] + [[[10, 20], [30], 40, 50], 60]**. * The depth of the left argument is **2**, while the depth of the right argument is **3**, so we compute **[1, [2, 3], [4]] + [[10, 20], [30], 40, 50]** and **[1, [2, 3], [4]] + 60**. + **[1, [2, 3], [4]]** and **[[10, 20], [30], 40, 50]** both have depth **2**, so we compute **1 + [10, 20]**, **[2, 3] + [30]** and **[4] + 40**. - **1 + [10, 20] = [1 + 10, 1 + 20] = [11, 21]** - **[2, 3] + [30] = [2 + 30, 3] = [32, 3]** Note that **3** remains untouched, since it doesn't have a matching element. - **[4] + 40 = [4 + 40] = [44]**​ **50** doesn't have a matching element, so the result is **[[[11, 21], [32, 3], [44], 50]]**. + **[1, [2, 3], [4]] + 60 = [1 + 60, [2, 3] + 60, [4] + 60] = [61, [2 + 60, 3 + 60], [4 + 60]]**, resulting in **[61, [62, 63], [64]]**. * The final result is **[[[11, 21], [32, 3], [44], 50], [61, [62, 63], [64]]]**. ### Task Write a program or a function that takes two integers, two nested arrays of integers or a combination thereof as input and returns their sum, as defined above. If your language has multiple array-like types (lists, tuples, vectors, etc.) you may choose any of them for your answer. The return type must match the argument type. To prevent boring and unbeatable solutions, if a language has this *exact* operation as a built-in, you may not use that language. All built-ins of all other languages are allowed. If your language of choice permits this, you may overload and/or redefine the built-in addition. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ### Test cases ``` 0 + 0 = 0 [-1, 0, -1] + [1] = [0, 0, -1] [] + [0] = [0] [] + 0 = [] [] + [] = [] [[], 0] + [] = [[], []] [1, 2, 3] + 10 = [11, 12, 13] [1, 2, 3] + [10] = [11, 2, 3] [1, 2, 3] + [10, [20]] = [[11, 12, 13], [21, 2, 3]] [1, 2, 3, []] + [10, [20]] = [11, [22], 3, []] [1, [2, [3, [4]]]] + [10, [20]] = [[11, [21]], [[12, [22]], [13, [24]]]] ``` To generate more test cases, you can use [this Jelly program](http://jelly.tryitonline.net/#code=K8WS4bmY&input=&args=WzEsIFsyLCAzXSwgWzRdXQ+W1tbMTAsIDIwXSwgWzMwXSwgNDAsIDUwXSwgNjBd). [Answer] # APL, 44 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) ``` {1=≡⍺⍵:⍺+⍵⋄=/∆←|≡¨⍺⍵:⊃∇¨/↓↑⍺⍵⋄</∆:⍺∘∇¨⍵⋄⍵∇⍺} ``` APL's `+` distributes over arrays as well, but in a different enough manner that this can't really be used. However, there is a built-in depth function (`≡`). Explanation: * `1=≡⍺⍵:⍺+⍵`: if the depths of `⍺` `⍵` are both zero (and therefore the depth of `⍺ ⍵` is 1), add them. * `∆←|≡¨⍺⍵`: take the absolute of the depth of both `⍺` and `⍵` and store them in `∆`. (`≡` gives a negative value if not all elements have the same depth.) * `=/∆`: if they have the same depth: + `↓↑⍺⍵`: pad the shortest array with zeroes to match the longer array + `⊃∇¨/`: distribute the function over both arrays * `</∆`: if the depth of `⍺` is less than that of `⍵`: + `⍺∘∇¨⍵`: bind `⍺` and then map over `⍵` * `⍵∇⍺`: if nothing else (so `⍵` is deeper than `⍺`), swap the arguments and try again. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 22 bytes ``` ß"+ŒḊ?çⱮç€</ɼ?,ŒḊ€©Eɗ? ``` [Try it online!](https://tio.run/##y0rNyan8///wfCXto5Me7uiyP7z80cZ1QKJpjY3@yT32OmBRIO/QSteT0@3///8fbaijEG2ko2AcC6RNYmP/R0dHGxroKBgZgASMQaQJkGsKYpgZxAIA) or [see all test cases](https://tio.run/##fZKxTsMwEIb3PIUFLKiuYjupl1Jl6sQTIMsjC@oLsDIyspSNsaqEkLoViYmIoY8BL2L@O8dJIE0zXGzf9/93ufjudrW6D/Uu1C9nk6@n7/1jVW9@dm8ID69X@eGjknyK3ed2eVhXYZLLepOL@fJCIPP@jMzlNcJNCC5zTkvhjBSFx7v0FHGmpDCK1gXFEtsZLawi4FwsGILSaIZafekb0lnytUhYzlhY@8zBiLLjD3krdDWFHPCU/bUfaLgHlRgIiFN@3DsKGvJkD0wmyxOOHZgsx@g4sAjEiTcD00cbYZymq4Hp4q8E/@ZIlVbC1H8B/WGo@rLYUq8IMUnUM2g@amjSVnTG@AR218kV8ToNxF1h1IvXjTogF0ZJZ1iY@V8 "Jelly – Try It Online") This technically violates > > To prevent boring and unbeatable solutions, if a language has this exact operation as a built-in, you may not use that language. > > > However, this is by no means a boring or unbeatable solution. The only time `+` is used here is to add two flat integers. The rest of it is recursion to get to that point. This is a full program which takes the two lists are arguments, and outputs the result. ## How it works ``` ß"+ŒḊ?çⱮç€</ɼ?,ŒḊ€©Eɗ? - Main link f(A, B). Takes A on the left and B on the right ? - If: ɗ - Condition: , - [A, B] ŒḊ€ - Depth of each © - (Save in register, R) E - Both depths are equal? Then: ? - If: ŒḊ - Condition: depth of A is non-zero ß" - Then: Run f(A, B) on each subarray in A, B + - Else: Return A+B Else: ? - If: </ɼ - Condition: depth of A is less than that of B çⱮ - Then: Over each element b of B, yield f(A, b) ç€ - Else: Over each element a of A, yield f(a, B) ``` We (ab)use `ç` in order to get `Ɱ` to work, as `ßⱮ` will error due to a bug in setting the arity of `ß` during execution. `ç` technically calls the link above explicitly as a dyad, but in a full program with only one link, this wraps around to call the same link. [Answer] ## Mathematica, 122 bytes ``` d=Depth x_~f~y_/;d@x>d@y:=y~f~x x_~f~y_/;d@x<d@y:=x~f~#&/@y x_List~f~y_:=MapThread[f,{x,y}~PadRight~Automatic] x_~f~y_=x+y ``` Defines a recursive function `f` which computes the sum. Making use of Mathematica's pattern matching, this function is made up of four separate definitions: ``` x_~f~y_/;d@x>d@y:=y~f~x ``` If the depth of `x` is greater than that of `y`, swap the arguments so that we only have to handle distribution in one direction (which we can do, since addition is commutative). ``` x_~f~y_/;d@x<d@y:=x~f~#&/@y ``` If the depth of `x` is less thann that of `y`, replace each value `#` in `y` with `f[x,#]`, which takes care of the distribution for arguments of unequal depth. ``` x_List~f~y_:=MapThread[f,{x,y}~PadRight~Automatic] ``` Otherwise, if one argument is a list (which implies that the other also is a list, since we know they have the same depth), we put both arguments in a list, pad them to the same length with `PadRight[..., Automatic]` (which simply fills up a ragged array with zeros to make it rectangular), and then use `MapThread` to apply `f` to corresponding pairs from the two lists. And finally, the base case: ``` x_~f~y_=x+y ``` If none of the other patterns match, we must be trying to add two numbers, so we just do that. [Answer] # Haskell, 150 bytes ``` data L=S Int|V{v::[L]} d(V z)=1+maximum(d<$>S 0:z);d _=0 S x!S y=S$x+y x!y|d x<d y=V$(x!)<$>v y|d x>d y=y!x|1<2=V$v x#v y (x:a)#(y:b)=x!y:a#b;a#b=a++b ``` ## Explanation The first line defines an algebraic data type `L`, which is either a `S`calar (containing an `Int`) or a `V`ector (containing a list of `L`s, accessed using a record getter `v`, which is a partial function `L → [L]`.) The second line defines the **depth** function: the depth of a `V`ector is one plus its maximum depth. I prepend `S 0` to the values in the vector, so that `depth [] == 1 + maximum [depth (S 0)] == 1`. The depth of “anything else” (a scalar) is `0`. The third line defines the base case for `!` (the addition function): the sum of scalars is simply a scalar. The fifth line defines a variant of `zipWith (!)` that just picks elements from the longest list when one of them is empty. The fourth line is split in three cases: ``` x!y | d x<d y = V$(x!)<$>v y | d x>d y = y!x | True = V$v x#v y ``` * If the depth of `x` is strictly less than the depth of `y`, map `(x!)` over the elements of `y`. (The use of `v` is guaranteed to be valid, as `d(y) ≥ 1`.) * If the depth of `x` is strictly greater, flip the arguments and restart. * If their depths are equal, zip the arguments together with `(!)`. (The use of `v` is guaranteed to be valid, as the case `d(x) = d(y) = 0` was handled as a base case.) ## Test cases ``` instance Show L where show (S x) = show x show (V x) = show x lArg = V [S 1, V [S 2, V [S 3, V [S 4]]]] rArg = V [S 10, V [S 20]] ``` Then `show (lArg ! rArg) == "[[11,[21]],[[12,[22]],[13,[24]]]]"`. [Answer] # Java, ~~802~~ ~~794~~ ~~754~~ 746 bytes I decided to take up @Dennis♦ for the challenge to operate on strings "as a last resort" because it was probably "too complicated". Also, in the worst language to golf on. Arrays in the input are comma-separated, surrounded with square brackets, and without whitespace. [Full program with functions wrapped into a class and with test cases](https://repl.it/CYdx/5) ``` import java.util.*; List<String>p(String s){List r=new ArrayList<String>();String p="";int l=0;for(char c:s.substring(1,s.length()-1).toCharArray()){l+=c=='['?1:c==']'?-1:0;if(c==','&&l<1){r.add(p);p="";}else p+=c;}if(p!="")r.add(p);return r;} int d(String s){int l=0;if(s.contains("[")){for(String c:p(s))l=d(c)>l?d(c):l;l++;}return l;} String f(String x,String y){int i=0;String r="";if(d(x)<1&&d(y)<1)r+=Integer.valueOf(x)+Integer.valueOf(y);else{r="[";if(d(x)<d(y))for(String k:p(y))r+=(i++<1?"":",")+f(x,k);else if(d(x)>d(y))for(String k:p(x))r+=(i++<1?"":",")+f(k,y);else for(;i<p(x).size()||i<p(y).size();i++)r+=(i<1?"":",")+(i<p(x).size()&&i<p(y).size()?f(p(x).get(i),p(y).get(i)):i<p(x).size()?p(x).get(i):p(y).get(i));r+="]";}return r;} ``` I might port this to C++ later since it's the other language I know that doesn't support ragged arrays, since I'm ~~pretty sure~~ almost certain it'll be shorter than this answer. This was mostly a proof of concept but any golfing tips would still be appreciated! *-31 bytes from @user902383 suggesting using a foreach over a converted character array, and then I saved a little more from rearranging the if blocks in the final part.* [Answer] # [C (GCC)](https://gcc.gnu.org), ~~377~~ 354 bytes *-23 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` d(w,r,i,x)S w;{for(r=i=0;w.v&&i<w.n;r=x>r?x:r)x=d(w.v[i++]);return!!w.v+r;}s(S*z,S x,S y){int e=d(x),f=d(y);if(e-f){S X=e<f?x:y,Y=e<f?y:x;for(z->v=calloc(e=z->n=Y.n,16);e--;)s(z->v+e,X,Y.v[e]);}else if(e+f){z->v=malloc(x.n+y.n<<4);for(e=0;e<x.n|e<y.n;++e)e>=x.n|e>=y.n?z->v[e]=(e<x.n?x:y).v[e],0:s(z->v+e,x.v[e],y.v[e]);z->n=e;}else z->n=x.n+y.n,z->v=0;} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jVVLktpIEI1ZOeAU2US4rUICS9DTMUEh-gLesXEHJiZ6UMlWDC0ISdAqejjJbHrjQ80cwydwZlZJSBh_FiBVfl6-fJVV-vfz6s-Pq9XLf16htypSMeRFtlsVMH_udpK0gFR2O5UJ-nvZPcJcft4V8eCP_3_7K3KevMxLvFLM4Uk-x5vMycIk9OXTcH99nUyfhqnMwnKW3ZWTTJQhxg_3i8R1l0Jmqthl6dUVWtxMHnNn3j94cyjxp8Uz1VYYXwovxocWMokdNYjF8xzeh2oaI6L27vlNT0pJpQ-D2T5cPazXm5WjQlyl4f0w9YJbIdVgIEXOEa7y3nv3SEMhiaNa5woI2kVoBng0AOUwdfUwnU5vBIMr7EpN0fqPmqJduq4SahayYRai5Y6yETR0OIz4Ca7i-ZO6cmks2pZnjsqy4IUt6zEVXx6t1K--oPq5YUbS5MlBCcA9IjOEYEmTGfrs3cTOXAjaPUTCCB9fjeSQ4y52u_tNEkGapEnhEIgHvN0MiikppqSt7Cpl_4splm0qOJUitxn-O6tNmvMw5YJmLAbHJGAR0e1UHDk2dnqvo54HBI4wZiIz28x2V6w-PWTOm8UbahP3CFgaGj9IppQjwXUTptfJwA0tAa4n0CFb9thJ4CrkWjCAAO4AK_dgAr0eRR4bFZdc0TJFBBi1e1yn511a3oZALpr0P6TnaEGNFqlt8ekXFSNNOMfq8xNBeOso1tQgRCsJGdEzQ6Q7eplAZPq3haKaIs9DvnukaTh4UPMsG--ayzGxsq6GpxoiXS811aW-KATZw_U1u6lBJmvGFEuUtDsuaDMQVe9Mr4kQUdVOx7b5Dgtx4izkTGyLlxNeEczbtzzK628DtQksbeC-IvKOy7O8Vm8jOCnNENhCMtW15ujvkFJ8DyTcCD_1SfdW_imrb3ME1uk75YV4_YP4Bn5Lq9NebWkbSpiS4igMqSIbft32axID_bUQemv34nze2NEYuFb3W5NoqR3rYXp8SFIHpxzPh70A7MeHrrQJvI4-pHQfNO63Lm0eTdYi8GAx8mC8xOfNcin5cixPN1Egat44oGNambliTX0PmgFkQsDRKcrahA3-jiewyA2YkUVuBo8qmBu-C-ylUdYLbJyPBrK3PVcHp2qZTs9isQiIik8tj-n_Bpe_08utv-T-9cX-teVvV00uxmRtl5ptuaqAwP9hBCnpX0YP2uq0XBX6uIneCBhRw5ddY9Lh5NK21K3f1Fv_VG9t9Kb77UxIHmecZBzkJuShjh-dJzgH5Et3Y7-dMeKUisbmbyzP30zz6X95Mc-v) (footer contains main, non-golfed functions, and other useful functions) Assumes that ragged arrays are represented with the following struct: ``` typedef struct S{ int n; struct S *v; } S; ``` where * if `x` is an integer, `x.n` is its value, and `x.v` is set to `NULL`; * if `x` is a ragged array, `x.n` is its length, and `x.v` is the array containing the sub-elements. Possible improvement: write a function that computes the sum in-place instead of allocating a new ragged array. --- Thanks to [@zoomlogo](https://codegolf.stackexchange.com/users/103854/zoomlogo) for pointing to this old interesting challenge in this [bounty](https://codegolf.meta.stackexchange.com/a/24189/73593) [Answer] # Pyth, 42 bytes ``` L?sIb0heSyM+b0M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ ``` [Test suite](https://pyth.herokuapp.com/?code=L%3FsIb0heSyM%2Bb0M%3FqFyMJ%2CGH%3FyGgM.tJ0%2BGHgLFyDJgF.Q&test_suite=1&test_suite_input=0%0A0%0A%5B-1%2C+0%2C+-1%5D%0A%5B1%5D%0A%5B%5D%0A%5B0%5D%0A%5B%5D%0A0%0A%5B%5D%0A%5B%5D%0A%5B%5B%5D%2C+0%5D%0A%5B%5D%0A%5B1%2C+2%2C+3%5D%0A10%0A%5B1%2C+2%2C+3%5D%0A%5B10%5D%0A%5B1%2C+2%2C+3%5D%0A%5B10%2C+%5B20%5D%5D%0A%5B1%2C+2%2C+3%2C+%5B%5D%5D%0A%5B10%2C+%5B20%5D%5D%0A%5B1%2C+%5B2%2C+%5B3%2C+%5B4%5D%5D%5D%5D%0A%5B10%2C+%5B20%5D%5D%0A%5B1%2C+%5B2%2C+3%5D%2C+%5B4%5D%5D%0A%5B%5B%5B10%2C+20%5D%2C+%5B30%5D%2C+40%2C+50%5D%2C+60%5D&debug=0&input_size=2) The last 4 bytes simply run the function on the input. ``` L?sIb0heSyM+b0M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ L?sIb0heSyM+b0 Define y(b), a helper function to calculate the depth. ? Ternary: sIb If b is invariant under the s function, which is only the case if s is an int. 0 The depth is 0. +b0 Add a 0 on to b. This handles the edge case where b is []. yM Map each to their depth eS Take the max. h Add one. M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ M Define g(G, H), which calculates the Jelly +. ? Ternary: ,GH Form [G, H]. J Save it to J. yM Map each to its depth. qF Check if they are equal. ?yG If so, check if the depth is nonzero. .tJ0 If so, transpose J, pairing each element of each argument with the corresponding element of the other. Pad with zeroes. gM Map each to its Jelly +. +GH If the depths are zero, return the normal sum. yDJ If the depths are different, order J by depth. gLF Apply the function which left-maps the Jelly + function to the two values. The first is treated as a constant, while the second varies over elements over the second values. ``` [Answer] # Python 2.7, ~~261~~ ~~209~~ ~~202~~ ~~198~~ ~~191~~ ~~185~~ ~~197~~ 181 bytes FGITW trivial solution EDIT: Of course @Dennis beats it Thanks to @LeakyNun for saving 57 bytes with tips on lambda expressions, and 2 bytes from unneeded brackets. Thanks to @Adnan for 4 bytes due to suggestion to use `type` instead of `isinstance` Thanks to @Lynn for 7 bytes with `-~` and `map` Thanks to @FryAmTheEggman for `z>=[]` instead of `type` +12 bytes to convert lambda to if else and fix a major bug -16 bytes thanks to @Kevin Lau - not Kenny [Try it online](https://repl.it/CYLV/1) ``` d=lambda z:z==[]or z>[]and-~max(map(d,z)) p=lambda x,y:p(y,x)if d(x)>d(y)else(x+y if d(x)<1 else[p(a,b)for a,b in zip(x,y)]+x[len(y):]+y[len(x):])if d(x)==d(y)else[p(a,x)for a in y] ``` [Answer] # Python 2, ~~145~~ 136 bytes ``` d=lambda t:t>{}and-~max(map(d,t+[0])) s=lambda x,y:s(y,x)if d(y)<d(x)else map(s,(x,[x]*len(y))[d(x)<d(y)],y)if d(y)else(x or 0)+(y or 0) ``` Test it on [Ideone](http://ideone.com/qynvcd). ### How it works In Python 2, all integers are less than all dictionaries, but all lists are greater. **d** recursively computes the depth of **t** by returning **0** for integers or the incremented maximum of the depths of its elements and **0**. `t+[0]` avoids special-casing the empty list. **s** recursively computes the Jelly sum of **x** and **y**. If **y**'s depth exceeds **x**'s, `s(y,x)` calls **s** with swapped arguments, making sure that **d(x) ≤ d(y)**. If **y** has positive depth, `map(s,(x,[x]*len(y))[d(x)<d(y)],y)` does the following. * If the **x**'s and **y**'s depths match, it executes `map(s,x,y)`, mapping **s** over all elements of **x** and the corresponding elements of **y**. In the case of lists of different lengths, **map** will pass **None** as left or right argument for missing elements in the shorter list. * If **x**'s depth is lower than **y**'s, it executes `map(s,[x]*len(y),y)`, mapping **s(x, · )** over **y**. If **y** (and, therefore, **x**) has depth **0**, `(x or 0)+(y or 0)` replaces falsy arguments (**None** or **0**) with zeroes and returns the sum of the resulting integers. [Answer] # [Scala 3](https://www.scala-lang.org/), 496 bytes Port of [@Value Ink's Ruby anwer](https://codegolf.stackexchange.com/a/81245/110802) in Scala. --- Golfed version. [Attmept this online!](https://ato.pxeger.com/run?1=fVJBTsMwEBTXvMJHr5pGLXBAEY7EgQMSqBKIU1VFTuK0htSExCC7VV6ChHqBGw-CV_AENnFaCQT44HHWM7OTTZ5e65QX_GDzdpfciFSTCy4VWb886Hx49LH3-cgLkoUnyrLoTGm2TnktSBFeiftpPGPReFAES17SDBDMpNTyTgVzoSfVaVELOoKOH7No1HiZyElOTWvm23aHzpdm1ICfUQuw5DpdrL1WQ7mfgMwJP05YZANen6lac5WKST51zWddYzT0Y4Dvmgg15j9N7Nte02ZDC_uttwnxXTEj7oBOA7stOxe8cQe89HBAXV9G0WERLKWiJqjlSvi2A_BdnZsfdWilZMVMoPktZodgJUtqt0_QRaU5iSHQD2UhMvBWgwGVee_DWAJOeynnC02TIQeBQyeYjQI4qt1R7d_U3SBM07gP__5M2q-1xH-B8mpeh-SkqridXulKqvkMQnKtpCaMrD2Cq8SqLhQO9lzWmo590uF-jwc9HgKu_jwebUmjtvqbzRB9kDXeSRyv8RrPpdxsHH4B) 496 bytes, it can be golfed much more. ``` val d:Any=>Int={case l:Seq[_]=>1+l.map(d).maxOption.getOrElse(0)case _=>0} def f(x:Any,y:Any):Any=(d(x),d(y))match{ case(a,b)if a<b=>y.asInstanceOf[Seq[_]].map(f(x,_)) case(a,b)if a>b=>x.asInstanceOf[Seq[_]].map(f(_,y)) case _=>(x,y)match{ case(x:Int,y:Int)=>x+y case(x:Seq[_],y:Seq[_])=> val(a,b)=(math.min(x.size,y.size),math.max(x.size,y.size)) val z=x.take(a).zip(y.take(a)).map((f _).tupled) z++(if(x.size==b)x.takeRight(b-a)else Seq())++(if(y.size==b)y.takeRight(b-a)else Seq()) case _=>x}} ``` Ungolfed version. [Attmpt this online!](https://ato.pxeger.com/run?1=lVRNi9swEL30lF8xRw1JTNLtoSxNoIcWAltSWgpdQgiqLSdqba2xlSJtyS_pZS_tj-qv6Uge7zpZNrA5ZOTRmzdPTx-__zapLOTF3d2fvc3Hr_-9eH_z7btKLXyQ2sCvAcBPWUCmKru7hLfGw2wOC2NhFucAUtkocJdwpRu72qzD9BSG4JJSViKWIQ3dsrL6xiRbZZf1u6JRYoIP5ZtQNaHvw4D-MpVDvjdpKBAuNh2BjxFZArTMwuGolSY8IpTSpru-LJE5mvcIOofMwRsah04-kc3CNFaaVC3zFStfR8WqUKUKy5v3NIyA04hPks-Z3D2TnHO0Qjx1JDT2x8vqepMti1gUI8bG5Lo_BXH7CORxADOs3dtSmytlyFRqtEvoS7ik0beKimLEY7R0fbR0Z9G3uvoo63BaXGLlDyXaZpjQhPBHKYwWic4Y2GBi91WhsmPGWpV0MLXZBt6vRKxzVgCzGatD7vZJb3dWsOIxLxRpM8md4IY4Q33dUvtH1P651J0Hw-Gp-NPMdX_74hFwMXPoX42AF7LeNnQX6lr61WdbU_2a7sYXox8uZkVZW5h7Q0WUNR218l5yvOD4CunH4-mkA01C9gzbmOgIPL2vbOGHwWHQPif8qnSvy38) ``` object Main { val depth: Any => Int = { case x: List[_] => 1 + x.map(depth).maxOption.getOrElse(0) case _ => 0 } def function(x: Any, y: Any): Any = (depth(x), depth(y)) match { case (dx, dy) if dx < dy => y.asInstanceOf[List[_]].map(element => function(x, element)) case (dx, dy) if dx > dy => x.asInstanceOf[List[_]].map(element => function(element, y)) case _ => (x, y) match { case (x: Int, y: Int) => x + y case (x: List[_], y: List[_]) => val minLen = math.min(x.size, y.size) val maxLen = math.max(x.size, y.size) val zipPart = x.take(minLen).zip(y.take(minLen)).map((function _).tupled) val remainingPartX = if(x.size == maxLen) x.takeRight(maxLen - minLen) else List() val remainingPartY = if(y.size == maxLen) y.takeRight(maxLen - minLen) else List() zipPart ++ remainingPartX ++ remainingPartY case _ => x } } def main(args: Array[String]): Unit = { println(function(List(1, List(2, List(3, List(4)))), List(10, List(20)))) println(function(List(-1, 0, 1), List(1))) } } ``` [Answer] ## JavaScript (ES6), 152 bytes ``` f=(a,b,g=a=>a.map?1+Math.max(0,...a.map(g)):0)=>g(a)<g(b)?f(b,a):g(b)<g(a)?a.map(e=>f(e,b)):g(a)?a.length<b.length?f(b,a):a.map((e,i)=>f(e,b[i]||0)):a+b ;t=(x,y,z)=>o.textContent+=` ${JSON.stringify(x)} ${JSON.stringify(y)} ${JSON.stringify(z)} ${JSON.stringify(f(x,y))} `;` 0 + 0 = 0 [-1, 0, -1] + [1] = [0, 0, -1] [] + [0] = [0] [] + 0 = [] [] + [] = [] [[], 0] + [] = [[], []] [1, 2, 3] + 10 = [11, 12, 13] [1, 2, 3] + [10] = [11, 2, 3] [1, 2, 3] + [10, [20]] = [[11, 12, 13], [21, 2, 3]] [1, 2, 3, []] + [10, [20]] = [11, [22], 3, []] [1, [2, [3, [4]]]] + [10, [20]] = [[11, [21]], [[12, [22]], [13, [24]]]]`.slice(1).split` `.map(l=>t(...l.split(/ [+=] /).map(a=>JSON.parse(a)))); ``` ``` <pre id=o></pre> ``` [Answer] # Julia, 113 bytes ``` ~=endof;!t=0t!=0&&1+maximum(!,[t;0]) x::Array+y::Array=(!x,~x)>(!y,~y)?y+x:!x<!y?map(t->x+t,y):~x<~y?[x;0]+y:x.+y ``` [Try it online!](http://julia.tryitonline.net/#code=fj1lbmRvZjshdD0wdCE9MCYmMSttYXhpbXVtKCEsW3Q7MF0pCng6OkFycmF5K3k6OkFycmF5PSgheCx-eCk-KCF5LH55KT95K3g6IXg8IXk_bWFwKHQtPngrdCx5KTp-eDx-eT9beDswXSt5OnguK3kKCmZvciByZXN1bHQgaW4gKAogICAgMCArIDAsCiAgICBBbnlbLTEsIDAsIC0xXSArIEFueVsxXSwKICAgIEFueVtdICsgQW55WzBdLAogICAgQW55W10gKyAwLAogICAgQW55W10gKyBBbnlbXSwKICAgIEFueVtBbnlbXSwgMF0gKyBBbnlbXSwKICAgIEFueVsxLCAyLCAzXSArIDEwLAogICAgQW55WzEsIDIsIDNdICsgQW55WzEwXSwKICAgIEFueVsxLCAyLCAzXSArIEFueVsxMCwgQW55WzIwXV0sCiAgICBBbnlbMSwgMiwgMywgQW55W11dICsgQW55WzEwLCBBbnlbMjBdXSwKICAgIEFueVsxLCBBbnlbMiwgQW55WzMsIEFueVs0XV1dXSArIEFueVsxMCwgQW55WzIwXV0KKQogICAgcHJpbnRsbihyZXN1bHQpCmVuZA&input=) ### How it works ``` ~=endof ``` creates a 1-byte alias for **endof**, which returns the length of an array. ``` !t=0t!=0&&1+maximum(!,[t;0]) ``` defines a depth function. The depth of **t** is zero if and only if **0t == 0**. If not, **t** is an array, and its depth is calculated as the incremented maximum of the depths of its elements and **0**. `[t;0]` appends a **0** to the array **t**, thus avoiding the need to special-case the empty array. Julia's built-in sum **+** already behaves like Jelly's sum if either (or both) of its arguments is an integer. However, the sum of two arrays (**+**) requires arrays of the same shape, and even the vectorized sum (**.+**) required arrays that can be broadcast to a common shape. We redefine **+** for a pair of arrays via ``` x::Array+y::Array=(!x,~x)>(!y,~y)?y+x:!x<!y?map(t->x+t,y):~x<~y?[x;0]+y:x.+y ``` This does not affect the definition of **+** for integer/integer, array/integer or integer/array arguments. `(!x,~x)>(!y,~y)` lexicographically compares the pairs of depths and lengths of both **x** and **y**. If **x**'s depth exceeds **y**'s, or if their depth match and **x**'s length exceeds **y**'s, `y+x` recursively calls **+** with swapped arguments. Otherwise, `!x<!y` tests if **x**'s depth is lower than **y**'s. If it is, `map(t->x+t,y)` maps **x + ·** over **y**. If the depths match, `~x<~y` tests if **x** is shorter than **y**. If it is, `[x;0]+y` recursively calls **+** after appending a **0** to the left argument. Finally, if both depths and lengths are identical, `x.+y` maps **+** over all elements of **x** and the corresponding elements of **y**. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~143~~ ~~145~~ ~~148~~ ~~149~~ 147 bytes Ruby has all these little quirks in how `zip` works with different-length arrays and `map` with multi-argument functions, making this pretty fun to golf down. The function has to be explicitly declared as a `proc` because `->` declares a `lambda`, which has strict argument checking that won't splat arguments passed in through `Array#map`. ``` d=->a{-~(a.map(&d).max||0)rescue 0} f=proc{|x,y|d[x]<d[y]?y.map{f[x,_1]}:d[x]>d[y]?x.map{f[_1,y]}:d[x]<1?x+(y||0):[*x.zip(y).map(&f),*y[x.size..]]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fZJBToNAFIajS07xFsZAO9AZdGGa0l7AG7xMSC2DklQl0CpTwEu4dNOFHkpP4xsK0WIrC8jkff__vUl4e8_WN3q7_VivYvfq8zUK3Om8dF_suXc_T-3zyKFvUVXcyVS-WCvgtRUHafa4KKuC6SrCQk4i1HKmTaCMsWChkPXYDKbNoGgHoWC6HUzErBja2tSOcVB4myS1tbMzxg4baCy8PNkoz5Oyble7fr5Llgpu1Sq3gNRMQQBnoZeny2Rlj3AYyFFTUaqn-RJCUVuQEWI20tKCFDIGWRAoSz1Eu87t1-kJhyFwOP4EwC10BQPOwBWSaKR3n0HeARY2DO8ze3BL_eMlqqs62tRCKMl9nCTIECgJpWv4DC4MLA7ICRWECGLExT6O4u-NWrxB-jAJfS7lHvy73My7xE-4WfNAQWtC35cd1WSQQmjOl1L2g52QPNLo0JhNgzkIE_Kb1O5X-AY) ]
[Question] [ You will be given as input a non-empty list of positive integers. For example: ``` [1,2,2,2,1] ``` You want to produce a ragged list as output which has this as its "depth map". This list should have the same elements in the same order but each element `n` should be at the depth equal to its value. ``` [1,[2,2,2],1] ``` This is a list where the `1`s are at the first level, the `2`s are nested in there, the threes would be nested in that etc. There are multiple outputs that fit this description: ``` [1,[2],[2],[2],1] [1,[],[2,[],2,2],1] [1,[2,2,2],1,[[[]]]] ``` We want the simplest one, that is the one with the fewest lists total. So in this case ``` [1,[2,2,2],1] ``` only has 2 lists whereas all the other examples had more. ## Task Take a depth map and produce the simplest ragged list that it could represent as outlined above. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as scored in bytes. ## Test cases ``` [1] -> [1] [2] -> [[2]] [3] -> [[[3]]] [10] -> [[[[[[[[[[10]]]]]]]]]] [1,2] -> [1,[2]] [2,2] -> [[2,2]] [2,1,2] -> [[2],1,[2]] [1,2,3,2] -> [1,[2,[3],2]] [1,2,3,3,3,2,1] -> [1,[2,[3,3,3],2],1] [1,2,1,2,1,3,3,1] -> [1,[2],1,[2],1,[[3,3]],1] ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~23~~ 21 bytes Input are comma-separated integers, output is in the same format as the test cases. ``` \d+ *[$&$&*] +`],\[ , ``` [Try it online!](https://tio.run/##K0otycxLNPz/PyZFm0srWkVNRU0rlks7IVYnJppL5/9/Qx0jMDTkMuQy4jLmMjTgAgpxGYExiAVSYAynQRCsWAcsC8QgEUMA "Retina – Try It Online") Wraps each number on its own, then repeatedly replaces `],[` with `,`. [Answer] # JavaScript (ES6), ~~ 80 79 ~~ 74 bytes *Saved 5 bytes thanks to @tsh* This builds a weird and dirty string internally but eventually returns a clean ragged list. ``` a=>eval('_='+[...a,'_'].map(g=v=>d^v?d++<v?"["+g(v):"],"+g(v,d-=2):v,d=0)) ``` [Try it online!](https://tio.run/##bY@7boMwFIb3PIXFgi1OnEC2tCZTlg7t0BG5kcWtVARHEFnq01MfQyBFHMsX/d9/Lv5RRnVpW93u20ZneV@IXok4N6qm/kX4QcI5V@BffMmv6kZLYUScfZlTFgSv5uQlXlBSw46eBPeCbCsidrS32DPWvyQbQpJQAvkXux2KiKI1ZFUHD6vQygMO9ws@4DEsncK5YdHLDQGPXtEaduqIF/njnDBXsAY4PJseDQA/Yk1kduGyJdH75EIZnRBOBYeNJJTzxDCdmCRdgtzwQrdnlX5TRURMUt10us55rUv69vnxzrt7WzVlVfzSgipmo/8D "JavaScript (Node.js) – Try It Online") ### How? Starting with \$d=0\$, for each entry \$v\$ in the original array followed by an extra `"_"`: * if the current depth \$d\$ is less than \$v\$: we append the string `"["` repeated \$v-d\$ times before \$v\$ and update \$d\$ to \$v\$ * if \$d\$ is greater than \$v\$: we append the string `"],"` repeated \$d-v\$ times before \$v\$ and update \$d\$ to \$v\$. (NB: The trailing `"_"` triggers this case and closes all pending brackets.) * if \$d=v\$: we just leave \$v\$ unchanged We then prepend `"_="`, which implicitly joins everything with commas, and we evaluate the resulting string. For instance, `[1,2,3,3,3,2,1]` is turned into: ``` "_=[1,[2,[3,3,3,],2,],1,],_" ``` which is evaluated to: ``` [1,[2,[3,3,3],2],1] ``` [Answer] # [Python 3](https://docs.python.org/3/), 75 bytes ``` f=lambda x,l=0:x and"],"*(l-x[0])+"["*(x[0]-l)+"%s,"%x+f(x[1:],x[0])or"]"*l ``` [Try it online!](https://tio.run/##VU3NisMgEL77FCIUtJ2E2twC6YsED5YkrGBUVJb06bNOY3e7iM73O4Zn/vKu2/dlsHp9TJpuYIdrv1HtJqaAnblttvGqxIWNhSBsbCGnBOy0XZaiyF7BK@IjU@xsd7MGHzNNz0TI4iO11DhkbcqTcW2c9WSNmxMXPaEG/LDqwOdvbcG2KViTOWvuTAhCQzQucwNo8oUbIcCLfZSKNndaBhlvByyzkK6SApBKqK6Ew7/BbxyqIP8kBe9cEaH7LEPZiA369vCU8r8EipgCWVccF/WPYP0FX6wojP8A "Python 3 – Try It Online") Python's `%` formatter coming in clutch. Output is a list in string format that can be evaluated by Python to the correct answer. Simple recursive function that walks down the input list. `l` just stores the value of the last element. # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 71 bytes ``` lambda x,i=0:",".join((j-i)*"["+(i-(i:=j))*"],"+str(j)for j in x)+i*"]" ``` [Try it online!](https://tio.run/##VY3RboQgEEXf/QrC01BHU9eXxsT9EesDjZqOQSBANrtfb5nottsQmLn33Bn8I3072374sC/952709jVpcUfq3zuJsl4dWYC1IvUmB1kCVUBdv6osR5RlTAFWtbggVkFW3FVJGcidNu9CEvERi4KpYZpVHdNEtg6zngzZOYLqCkHo@k17mG/aoKmjN5RAVlepVCF8IJuAkCEsQEqhU/vQjKK6ilyK4XK0uWbRniI3LBs8aYMHv@BvHE@j@bNGfOayie3rMOaNPCGejE8e/pdgk1PYnCuOy/5L8PyFXx4ZOf4D "Python 3.8 (pre-release) – Try It Online") Using the walrus operator removes the need for recursion, and the trailing comma can be added by `str.join`. Suggested by @loopywalt. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 28 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {⟨0⟩:0;1+𝕊¨{⊐+`»⊸∨¬×𝕩}⊸⊔𝕩-1} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge+KfqDDin6k6MDsxK/CdlYrCqHviipArYMK74oq44oiowqzDl/Cdlal94oq44oqU8J2VqS0xfQoKPuKLiOKfnEbCqCDin6gK4ouIMQrii4gyCuKLiDMK4ouIMTAKMeKAvzIKMuKAvzIKMuKAvzHigL8yCjHigL8y4oC/M+KAvzIKMeKAvzLigL8z4oC/M+KAvzPigL8y4oC/MQox4oC/MuKAvzHigL8y4oC/MeKAvzPigL8z4oC/MQrin6kK) A single recursive function that builds the output as a nested list. `⟨0⟩:0` Base case: If the argument is a list containing a single 0, return 0 as a scalar value. `𝕩-1` Decrement each value. `{⊐+`»⊸∨¬×𝕩}⊸⊔` Group adjacent positive integers, and put each 0 in its own group. `𝕊¨` recursively call the function on each group. `1+` Add 1 to each number. [Answer] # [J](http://jsoftware.com/), 63 59 37 bytes ``` <:<@([:>:L:0$:^:(0<{.));.1~1,2~:/\=&1 ``` [Try it online!](https://tio.run/##XY3BCsIwEETv@YpBpE2grklzW5NSFDwVD14VEaRFvPgBQn89pohNKMPCzgxv9xVWVA7wjBIVNDjOhnA4d8fg2LXywg13rNd8Y6ndh5TakRlNVY@8vfrCBCVOe8LgyTEQgUSou2xYtSR10ZPCAhT94/nGAIM6yuZ27qwQc/5f6lQmZC7zNcunq3ZpJ2XPzA@JMxUmfAE "J – Try It Online") -22 thanks to approach suggested by ovs! It's similar or the same as his BQN answer's. ## [J](http://jsoftware.com/), original approach 63 59 bytes ``` g=.((,$:/@,&.>/@]^:[~[:(1=*+.1<<.)/,&L.){.),}.@] [:g/<^:]"+ ``` [Try it online!](https://tio.run/##y/r/P91WT0NDR8VK30FHTc9O3yE2ziq6LtpKw9BWS1vP0MZGT1NfR81HT7NaT1OnVs8hlivNVi/aKl3fJs4qVkn7f2pyRr5CmoKhghEQGoMhiGXIxQWTgTGMYAxjLoQmuCQyE0ncEGwqGhdiiSGyIASDJAz/AwA "J – Try It Online") This is *ridiculous*. Someone please find a better approach that still uses boxes and let me know what it is... The basic approach is: * Individually wrap each element to its depth. * Recursively meld together neighboring elements using a fold. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` ≔⁰ηFA«F⁻ηι]→F⁻ιη[Iι≔ιη»Fη]UB, ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DQEchQ9OaKy2/SEHDM6@gtERDU1OhmosTLOCbmVdarJGho5AJFAwoyswr0VCKVQIq5/TNL0vVsArKTM8oAXGRVGeCDISrjgarhnCcE4tLNIAmAQWglmdCLK@FWJ@BakdwaolTYnJ2elF@aV6KhpIOUOz//@hoQx0jHQg2BkLD2Nj/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁰η ``` Start with a depth of 0. ``` FA« ``` Loop through the depths. ``` F⁻ηι] ``` Add `]`s as necessary to reduce the depth to the current depth. ``` → ``` Leave a space between values. ``` F⁻ιη[ ``` Add `]`s as necessary to increase the depth to the current depth. ``` Iι ``` Output the current depth. ``` ≔ιη ``` Save the current depth as the previous depth. ``` »Fη] ``` Output the necessary closing `]`s at the end. ``` UB, ``` Replace all the interior spaces with commas. (The leading space simply gets skipped, since it wasn't actually printed.) Actually creating the list in memory takes 44 bytes: ``` ⊞υ⟦⟧FA«W‹Lυι«≔⟦⟧θ⊞§υ±¹θ⊞υθ»≔…υιυ⊞§υ±¹ι»⭆¹§υ⁰ ``` [Try it online!](https://tio.run/##fYw9C8IwEIbn9FdkvIMIVsdOpZOgUnAsHUqNSSCktUn8QPrbY2oVdJHj7jje555WNkPbNTqE0lsJntGqxiw5dQOFjem9A0T6SMhVKs0pbLm1cRjhIouMqjklubVKGKhqRs/xnZCXLXcbc@S3ybrnonEcUsQfwr@vMfkoinureSG7fspUpP2U/9OpCIxJOSjj4ODiErumh5TRL36JiFkIVZWyFZt7HSut67C46Cc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υ⟦⟧ ``` Start with an empty list. ``` FA« ``` Loop over the depths. ``` W‹Lυι« ``` While the next depth is larger than the current depth, ... ``` ≔⟦⟧θ⊞§υ±¹θ⊞υθ ``` ... nest a list. ``` »≔…υιυ ``` Truncate the current depth to the next depth. ``` ⊞§υ±¹ι ``` Append the next depth value to its list. ``` »⭆¹§υ⁰ ``` Pretty-print the final list. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εDG…[ÿ]]',ý…[ÿ]…],[',: ``` Input as list, output as string. It kinda feels like cheating, but I saw multiple other answers do the same.. And I guess we could technically add an eval. [Try it online](https://tio.run/##yy9OTMpM/f//3FYX90cNy6IP74@NVdc5vBfKBlKxOtHqOlb//0cb6hjpQLAxEBrGAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1td3B81LIs@vD@2tlZd5/BeKAdIxepEq@tY/df5Hx1tGKujEG0EIoxBhKEBmNQBixjBKCgfSOkYIzNBECgLE4BgkKBhbCwA). A port of [*@xigoi*'s Jelly answer](https://codegolf.stackexchange.com/a/241653/52210) is 22 bytes as well: ``` 0.ø¥Ý€{.±…,[]sèJI.ιJ¦¨ ``` [Try it online](https://tio.run/##yy9OTMpM/f/fQO/wjkNLD8991LSmWu/QxkcNy3SiY4sPr/Dy1Du30@vQskMr/v@PNtQx0oFgYyA0jAUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/A73DOw4tPTz3UdOaar1DGx81LNOJji0@vMKrUu/cTq9Dyw6t@K/zPzraMFZHIdoIRBiDCEMDMKkDFjGCUVA@kNIxRmaCIFAWJgDBIEHD2FgA). **Explanation:** ``` ε # Map over each integer in the (implicit) input-list: D # Duplicate the integer G # Pop and loop the integer-1 amount of times: …[ÿ] # Wrap it in block-quotes as string ] # Close both the inner loop and outer map ',ý '# Join the strings with "," delimiter …[ÿ] # Wrap the entire string into block-quotes as well …],[',: '# Replace all "],[" with "," # (after which the resulting string is output implicitly) 0.ø # Surround the (implicit) input-list with leading/trailing 0 ¥ # Get the deltas/forward-differences of this list Ý # Transform each value to a list in the range [0,value] €{ # Sort each inner list .± # Convert each to its sign (-1 if <0; 0 if 0; 1 if >0) …,[]sè # Modular 0-based index each into ",[]" J # Join each inner list of characters to a string I.ι # Interleave it with the input-list J # Join it together again ¦¨ # Remove the leading/trailing "," # (after which the resulting string is output implicitly) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` Ø0jIr0Ṣ€Ṡị“[],”ż⁸FḊṖ ``` [Try it online!](https://tio.run/##y0rNyan8///wDIMszyKDhzsXPWpa83Dngoe7ux81zImO1XnUMPfonkeNO9we7uh6uHPa////ow11jHQg2BgIDXVMYgE "Jelly – Try It Online") A string-based approach. ## Explanation ``` Ø0jIr0Ṣ€Ṡị“[],”ż⁸FḊṖ Ø0j Surround with zeroes I Increments r0 Raplace each element x with the range x..0 Ṣ€ Sort each range Ṡ Replace each number with its sign ị“[],” Perform the mapping: 1 -> "[", -1 -> "]", 0 -> "," ż⁸ Zip with the original input F Flatten ḊṖ Remove the leading and trailing commas ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~59~~ ~~41~~ 40 bytes ``` f@{a:0..}=a f@l_:=f/@SplitBy[l-1,Sign]+1 ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/NoTrRykBPr9Y2kSvNISfeyjZN3yG4ICezxKkyOkfXUCc4Mz0vVtvwf0BRZl5JtLKuXZqDcqxaXXByYl5dNVe1Ya0OV7URiDAGEYYGYFIHLGIEo6B8IKVjjMwEQaAsTACCQYKGtVy1/wE "Wolfram Language (Mathematica) – Try It Online") [Answer] # Python3, 112 bytes: ``` from itertools import* f=lambda x,n=1:[j for a,b in groupby(x,key=lambda x:x==n)for j in(b if a else[f(b,n+1)])] ``` [Try it online!](https://tio.run/##VZHRboQgEEWf61dMfBHa6aasL40J/RFrGky1dYtAxDb69XYm4naLQZjLuTNhCOv86V35HKZt6yc/wjB30@y9jTCMwU/zfdZra8b23cCCTquqvkDvJzDYwuDgY/LfoV3Fgl/degWrRWsnGbsQJIjswUBnY1f3okX3oGQjm22vACbOWQSd53mtGnh8AVqy@rxvaaWgTAFtOFRPR5wGCddBx5jMCnf7Ga/ZMAnqT2rw4EjE8taMVJAdcJzxR@Z/BItMoUop9sn6DZiq8J8tDeN05Yy7NHAr4ykGO8yieHWFrLI77rCG0QRBDTpZfhhj37ofYxGGg@X0hZREx0gPB70wUut2@wU) [Answer] # [Perl 5](https://www.perl.org/) -p, 86 bytes ``` s/\d+,?|$/"]"x($d=$l-$&).","."["x-$d.($l=$&)/ge;s/(\[),|,(])|,(,)/$1$2$3/g;s/^.|..$//g ``` [Try it online!](https://tio.run/##TYlBCsIwEEX3HmMYJMFJxqS4kuJB0rhqCUKwpXXRRc9unNAuZHiP@f9Pw5xvpSzc9Rd6bMgQYVXYt5gNnrUFAgsBVoO9VZhb6TgN94VVFzRtpKIWkWZ06LHhJNPTbtYicyoluHgKXmgEd62iGv3hPYmp@fvqyXbkndq5@B2nz2t8L8VM@Qc "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 54 bytes ``` f=->a,d=1{a.chunk{_1>d}.flat_map{_1 ? [f[_2,d+1]]:_2}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVDbasMwDKWv_gqRp7VTQpXCGIVmH-IZ4zU1DUuz0CWDUfIle-nD9lHt10zCTi8ytnSOzpFBP7_7_u37ePzrO58-n578Ki0clis6uGy97Zv3g6WiHDJfu87uXMsQXkB7bXMsH8mYpc2HIbjPk5n_2EMFVQOJJgNpAZyUzkPJmcEiAi4E0nzEMZi4BLcxmgmDPcfLNIwEXSmDo45JXNyakT8UB4w9OWy-UwgpKqQ4Ilzhb4TxF3nFYkSeZJ9tXXUPyWuTTDPZ1ObL1WAp8HpuBtWC15VRm6ZUKqxsXPw_) -16 from AZTECCO. [Answer] # [R](https://www.r-project.org/), 84 bytes Or **[R](https://www.r-project.org/)>=4.1, 77 bytes** by replacing the word `function` with a `\`. ``` f=function(v,s=1)"if"(all(v<s),v,{y[]=cumsum(c(T,y<-v==s)|y);Map(f,split(v,y),s+1)}) ``` [Try it online!](https://tio.run/?fbclid=IwAR1LuUT8zKk_OaDLtmpg4YS-vE-DQlpYLwWbKDUBVzGBeBuScasDenpyqkI##jZBNCoMwEIX3PYW4ytARHF1qeoPuutMsRAgImkqjAWl7dptQKfhDdUJmk/e9eZPHOEoue1V21V0xg5oT@JX0WVHXzKQa0OBzyAQv@0b3DSvZDYc0MJxreA2QXIuWSdRtXXWWHgD1meANo7RKAkjKomO@F1y8jESugmXlKlc@nJw6mqmzSOzo47k@i8UeQeECmYpC8asdB5ynJNzPGeFyMzzA0IoSeGSa5TDeSIn2f9xc7wjujo2wZeLenBHSgSDf65i117SO685V/HUcPw "R – Try It Online") Outputs the actual list structure. [Answer] # [Vyxal 2.4.1](https://github.com/Vyxal/Vyxal/releases/tag/v2.4.1) `D`, 20 bytes ``` Ġƛh‹(w);S`⟩|⟨`\|øVḢṪ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%C4%A0%C6%9Bh%E2%80%B9%28w%29%3BS%60%E2%9F%A9%7C%E2%9F%A8%60%5C%7C%C3%B8V%E1%B8%A2%E1%B9%AA&inputs=%5B1%2C2%2C3%2C5%2C2%2C3%2C1%2C2%2C2%2C1%2C1%2C1%2C3%2C2%2C1%2C3%2C2%5D&header=&footer=) A big mess. We're using v2.4.1 because v2.6+ prettyprint lists with spacing. ``` Ġ # Group consecutive identical elements ƛ ; # Map... h‹( ) # item-1 times... w # wrap in a list S # Stringify `⟩|⟨`\|øV # Replace `⟩|⟨` with `|` ḢṪ # Remove the first and last characters. ``` ]
[Question] [ Given a strictly positive integer **n**, follow these steps: 1. Create an array **A** with **n** **1**s. 2. If **A** only has one element, terminate. Otherwise, starting from the first element, replace each pair of **A** with its sum, leaving the last element as is if **A**'s length is odd, and repeat this step. The output should contain **A**'s state after each step in order from the first step to the last. Usage of [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/41024) is forbidden. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the solution with the fewest bytes in each language wins. ## Test cases Each line in the output of these examples is a state. You can output via any reasonable format. Input: `1` ``` [1] ``` Input: `4` ``` [1, 1, 1, 1] [2, 2] [4] ``` Input: `13` ``` [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] [2, 2, 2, 2, 2, 2, 1] [4, 4, 4, 1] [8, 5] [13] ``` Input: `15` ``` [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] [2, 2, 2, 2, 2, 2, 2, 1] [4, 4, 4, 3] [8, 7] [15] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` Å1Δ=2ôO ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cKvhuSm2Roe3@P//b2gKAA "05AB1E – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` :g`t2estnq ``` [Try it online!](https://tio.run/##y00syfn/3yo9ocQotbgkr/D/f0NjAA "MATL – Try It Online\"t Online\"") ### How it works ``` : % Input n (implicit). Range [1 2 ... n] g % Convert to logical. Gives [1 1 ... 1] ` % Do...while t % Duplicate 2 % Push 2 e % Reshape as 2-column matrix, in column-major order, padding with 0 if needed s % Sum of each column t % Duplicate n % Number of elements q % Subtract 1. This will be used as loop condition % End (implicit). If top of the stack is not zero run new iteration % Display stack, bottom to top (implicit) ``` [Answer] # [Python 3](https://docs.python.org/3/), 57 bytes ``` def f(i,j=1):print(i//j*[j]+[i%j][:i%j]);i>j and f(i,j*2) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1Mny9ZQ06qgKDOvRCNTXz9LKzorVjs6UzUrNtoKRGpaZ9plKSTmpUAUaxlp/k/TMNTkStMwARGGxmDSVPM/AA "Python 3 – Try It Online") # [Python 2](https://docs.python.org/2/), 51 bytes ``` def f(i,j=1):print i/j*[j]+[i%j][:i%j];i>j>f(i,j*2) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI1Mny9ZQ06qgKDOvRCFTP0srOitWOzpTNSs22gpEWmfaZdmBlWkZaf5P0zDU5ErTMAERhsZg0lTzPwA "Python 2 – Try It Online") *-6 bytes total thanks to tsh* Recursive function. For each step, it constructs a list of powers of `2`, such that the sum is smaller than or equal to the given integer. It then appends the remainder, if it is larger than `0`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` L€+2/Ƭ ``` **[Try it online!](https://tio.run/##y0rNyan8/9/nUdMabSP9Y2v@//9vaAoA "Jelly – Try It Online")** [Answer] # JavaScript, 55 bytes ``` f=(n,t=1,r=n)=>r>t?t+[,f(n,t,r-t)]:n>t?r+` `+f(n,t+t):r ``` [Try it online!](https://tio.run/##NchLCoAgEADQvSdx0BZFtAisg0RglIJFk4xD0OntAy3fW6dzSjOFyEWKYXG0H7i5K2dvJGo2pSaDYDrquGc1aP@upoJhbPE5UlZY9a1iaClHCsjSy7oCED/KBiDf "JavaScript (SpiderMonkey) – Try It Online") This is basically the golfed version of following codes: ``` function f(n) { var output = ''; t = 1; for (t = 1; ; t *= 2) { for (r = n; r > t; r -= t) { output += t + ','; } output += r; if (n <= t) break; output += '\n'; } return output; } ``` [Answer] # [R](https://www.r-project.org/), 65 bytes -1 byte thanks to Giuseppe. ``` n=scan();while(T<2*n){cat(rep(+T,n%/%T),if(n%%T)n%%T,"\n");T=2*T} ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTujwjMydVI8TGSCtPszo5sUSjKLVAQztEJ09VXzVEUyczTSNPFcgAETpKMXlKmtYhtkZaIbX/DU3/AwA "R – Try It Online") Avoids recursion. In R, `%/%` is integer division and `%%` is the modulo. For each power of 2 `k=2^i`, we need to print `n%/%k` times the value `k`, and then `n%%k` if that value is non zero. Do this for all powers of 2 smaller than \$2n-1\$. Here I am using `T` instead of `k`, since it is initialized as `TRUE` which is converted to 1. I still need to print `+T` instead of `T` to avoid a vector of `TRUE`s in the output. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` .u+McN2m1 ``` [Try it online!](https://tio.run/##K6gsyfj/X69U2zfZz0gr1vD/f0NjAA "Pyth – Try It Online") ``` .u # Apply until a result is repeated, return all intermediate steps: lambda N,Y: +M # map by + (reduce list on +): cN2 # chop N (current value) into chunks of 2, last one is shorter if needed m1Q # map(1, range(Q)) (implicit Q = input) ``` -1 byte thanks to FryAmTheEggman [Answer] # [JavaScript (V8)](https://v8.dev/), 109 bytes ``` f=n=>g(Array(n).fill(1));g=(a,i=1)=>{console.log(a);if(a[i]){for(;a[i];)a.splice(i-1,2,a[i-1]+a[i++]);g(a);}} ``` [Try it online!](https://tio.run/##FYzBCsMgEETv/RF3iQnYU4sYyHcED1sbZYvEoCVQQr7dmsNjhgczH9qpuMzbt98ftXqzmjHAlDP9YMXBc4ygEHUwQJKNQjMeLq0lxWWIKQChZg80s8XDpwz6qhppKFtktwD3St5lk72yXYuus@3smp1n9fBEfQswCxJSvBqu8W4swmL9Aw "JavaScript (V8) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~55~~ 54 bytes ``` Last@Reap[1~Table~#//.a_:>Tr/@Sow@a~Partition~UpTo@2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yexuMQhKDWxINqwLiQxKSe1TllfXy8x3soupEjfITi/3CGxLiCxqCSzJDM/ry60ICTfwShW7X9AUWZeSbSyrl2ag3Ksmr5DNZehDpeJDpehMRCbctX@BwA "Wolfram Language (Mathematica) – Try It Online") ~~Finally, `Sow`/`Reap` beats an alternative!~~ Returns a singleton list containing a list of the steps. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~15~~ 17 bytes ``` {{+/'0N 2#x}\x#1} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qulpbX93AT8FIuaI2pkLZsPZ/moKh8X8A "K (oK) – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~20~~ 17 bytes ``` _2+/\&.>^:a:<@#&1 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/44209WPU9OzirBKtbByU1Qz/a3JxpSZn5CukKZhAGOrqMAFDYwwR0/8A "J – Try It Online") *-5 bytes thanks to Bubbler* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes -1 byte thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer). ``` 1x+2/Ƭ ``` [Try it online!](https://tio.run/##y0rNyan8/9@wQttI/9ia/0CWKQA "Jelly – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` _ò mx}hUõÎü)â ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=X/IgbXh9aFX1zvwp4g&input=MTU) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes ``` ;1j₍ẹẉ₂{ġ₂+ᵐ}ⁱ.ẉȮ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6kUFCUn1KanFpspfRwV6f9o7YNj5qaHnUsf7hjG5Bf@3DrhP/WhlmPmnof7toJFABKVh9ZCCS1gTK1jxo36gEFT6z7/z/aUMdEx9BYx9A0FgA "Brachylog – Try It Online") As horribly long as this is, I still feel a bit clever for using `.ẉȮ`: the obvious way to print something, then check if its length is 1 would be `ẉ₂l1`, `ẉ₂~g`, or `ẉ₂≡Ȯ`, where the `≡` in the last one is necessary because `ẉ₂` unifies its input and output *before* it prints them, and `Ȯ` is pre-constrained to be a list of length 1, so the unification fails if the input is not a list of length 1. At the end of a predicate, this feature of `ẉ₂` can be circumvented, however, by using the output variable instead of subscripting `ẉ`: `.ẉȮ` first unifies its input with the output variable, then prints the output variable, and only afterwards unifies the output variable with `Ȯ`. [Answer] # [Haskell](https://www.haskell.org/), 75 bytes ``` g.pure g x|x!!0<2=[x]|1>0=(g$(\z->filter(0/=)[-div(-z)2,div z 2])=<<x)++[x] ``` [Try it online!](https://tio.run/##DcyxDoMgFEDRvV/xTBwglhZJuvH8EXUgFigpGoK2IcRvL2W7y7kvtb@198UAwlTsLXyivlhIZ2oaLgWOaT77gSOxLZkyG4zzh46E35GO7Om@hGUqrjUgg5gpSplo11VVVuW2Og3RbQe0YKB/lN9ivLJ7YUsIfw "Haskell – Try It Online") Works backwards from the list `[n]` until it reaches a list of just ones. Going forwards, I could get 80 bytes using `chunksof` from `Data.List.Split`: ``` import Data.List.Split f x=g$1<$[1..x] g[n]=[[n]] g x=x:(g$map sum$chunksOf 2 x) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuEQvuCAns4QrTaHCNl3F0EYl2lBPryKWKz06L9Y2GkgAmUCpCiuNdJXcxAKF4tJcleSM0rzsYv80BSOFCs3/uYmZeQq2CgVFmXklCioKaQqGpv8B "Haskell – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Çë⌐ⁿ┤5π»Å╡ ``` [Run and debug it](https://staxlang.xyz/#p=8089a9fcb435e3af8fb5&i=1%0A4%0A13%0A15&a=1&m=2) ## Procedure: 1. Generate 0-based range. 2. Repeatedly halve each element until all items are zero. 3. Calculate run-lengths for each unique array. ## Annotated Source: ``` r main:[0 .. 5] {{hmgu main:[[0 .. 5], [0, 0, 1, 1, 2, 2], [0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0]] m:GJ main:"1 1 1 1 1 1" ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` NθIE↨⊖⊗θ²E⪪Eθ¹X²κLλ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMM3sUDDKbE4VcMlNbkoNTc1ryQ1RcMlvzQpB0gXamrqKBgBMUhVcEFOJkR9oY6CIVAwIL8caJ6RjkI2SJlPal56SYZGjiYYWP//b2j8X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Uses Charcoal's default output format, which is one number per line, with subarrays double-spaced from each other. Explanation: ``` Nθ Input `n` into a variable θ `n` ⊗ Doubled ⊖ Decremented ↨ ² Converted to base 2 (i.e. ceil(log2(input))) E Map Eθ¹ List of `1`s of length `n` ⪪ Split into sublists of length ² Literal `2` X To power κ Loop index E Map over each sublist Lλ Take the length I Cast to string for implicit print ``` [Answer] # [Perl 5](https://www.perl.org/), 46 bytes ``` say$_="1 "x<>;say while s/(\d+) (\d+)/$1+$2/ge ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIl3lbJUEGpwsbOGshTKM/IzElVKNbXiEnR1lQAk/oqhtoqRvrpqf//G5r@yy8oyczPK/6v62uqZ2BoAAA "Perl 5 – Try It Online") Output is space separated. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 38 bytes ``` {1 xx$_,*.rotor(2,:partial)>>.sum...1} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2lChokIlXkdLryi/JL9Iw0jHqiCxqCQzMUfTzk6vuDRXT0/PsPZ/cWKlQpqGiaY1F4RlqvkfAA "Perl 6 – Try It Online") There's some shortcut to partial rotoring that I'm not remembering right now... ### Explanation: ``` { } # Anonymous code block ... # Return a sequence 1 xx$_, # Starting with a list of 1s with input length * # Where each element is .rotor(2,:partial) # The previous list split into chunks of 2 or less >>.sum # And each chunk summed 1 # Until the list is length 1 ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 30 bytes ``` (|1){!1>|^(:. ,")^ ,(!2/|+")}. ``` [Try it online!](https://tio.run/##y05N//9fo8ZQs1rR0K4mTsNKT0FHSTOOS0dD0Ui/RltJs1bv/39DUwA "Keg – Try It Online") I've actually been meaning to complete this challenge for a while (I mean, I emailed myself the link to it so I would remember), but I've never gotten around to doing so until now! [Answer] # APL, 28 chars ``` {1≢≢⎕←⍵:∇+/(⌈.5×≢⍵)2⍴⍵,0}⍴∘1 ``` vector of 1s ``` ⍴∘1 ``` output the argument and check if length is different than 1: if so, go on ``` 1≢≢⎕←⍵: ``` get half of the length and round up ``` ⌈.5×≢⍵ ``` reshape into a nx2 matrix adding a trailing 0 if needed ``` (⌈.5×≢⍵)2⍴⍵,0 ``` sum of row by row ``` +/ ``` recurse ``` ∇ ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 24 bytes A horribly long answer... golfed out 1 byte by using a hard-to-read output format ``` ~[1]*{..2/{{+}*}%\,(}do; ``` [Try it online!](https://tio.run/##HcyxCsIwFIXhPU9xoAhSS4o6ugsuOjpohxBjE6xJSG8tEuKrx@hZ/4/Tu@E@ymA85fy5rLs6cr5pY1ylOi2uzTLd3C5XOLoGB4gnrCNQeBvbgxykVoKgVVCcc9ahwjkID9IKIwn5gLFFCQxmJBYZyjyKOk3kJ8JsSJdq1TwYq1hqf23vghJSw71U@D8ZW2zefgE "GolfScript – Try It Online") ## Explanation ``` ~ // Dump the contents of the input string [1]* // Create a 1-list with the length of the input string { }do // do ... while \,( // the length of the array is larger than 1 . // Extra evolution step that we need to keep . // Create a copy of the input 2/ // That splits into parts of 2 items { }% // For each over the splitted array: {+}* // Reduce the item with addition // e.g. [1] -> [1], [1 2] -> [3], etc. ; // Discard the abundant copy ``` [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 93 bytes ``` :s/1\n/a D@"i1 <esc> qqYplllA]<esc>0i[<esc>:s/\(\d\+\) \(\d\+\) /\1+\2,/g C<c-r>=<c-r>" <Esc><c-o>V}J0i <esc>@qq@qdd:s/ i1/1 ``` [Try it online!](https://tio.run/##K/v/36pY3zAmTz@Ry8VBKdNQwSa1ONmOq7AwsiAnJ8cxFsw1yIwG00ClMRoxKTHaMZoKcIZ@jKF2jJGOfjqXs02ybpGdLZhU4rJxBeoAsvPtwmq9DDIhBjsUFjoUpqQADVLINNQ35Pr/39Tsv24ZAA "V (vim) – Try It Online") Special casing 1 for `<c-o>` was a bit annoying, but the rest plays out smoothly. Possible byte saves can be in the large regex, and maybe removing the 1 special case. Outputs as space separated lists. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` 1ẋ≬2ẇṠ↔ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIx4bqL4omsMuG6h+G5oOKGlCIsIiIsIjEzIl0=) ``` 1ẋ # n 1s ↔ # Collect while unique: ≬--- # Next three as function ẇ # Cut into chunks of length 2 # 2 Ṡ # Sum each chunk ``` [Answer] # [Ohm v2](https://github.com/nickbclifford/Ohm), 8 bytes ``` @Dv·Ω2σΣ ``` [Try it online!](https://tio.run/##y8/INfr/38Gl7ND2cyuNzjefW/z/v6EpAA "Ohm v2 – Try It Online") If output in scientific notation is allowed, otherwise: # [Ohm v2](https://github.com/nickbclifford/Ohm), 9 bytes ``` @Dv·Ω2σΣì ``` [Try it online!](https://tio.run/##y8/INfr/38Gl7ND2cyuNzjefW3x4zf//hqYA "Ohm v2 – Try It Online") [Answer] # [Gaia](https://github.com/splcurran/Gaia), 12 bytes ``` ċ)¦⟨:q2/Σ¦⟩ª ``` [Try it online!](https://tio.run/##S0/MTPz//0i35qFlj@avsCo00j@3GMRceWjV//@GpgA "Gaia – Try It Online") ``` ċ)¦ | generate array of n 1's (really, generate array of n 0's and increment each) ⟨ ⟩ª | do the following until you get to a fixed point: :q | dup and print with a newline 2/ | split into groups of 2, with last group possibly being smaller Σ¦ | take the sum ``` ]
[Question] [ Challenge Taken with permission from my University Code Challenge Contest --- For some years now, the number of students in my school has been growing steadily. First the number of students was increased by classroom, but then it was necessary to convert some spaces for some groups to give classes there, such as the gym stands or, this last course, up to the broom room. Last year the academic authorities got the budget to build a new building and started the works. At last they have finished and the new building can be used already, so we can move (the old building will be rehabilitated and will be used for another function), but it has caught us halfway through the course. The director wants to know if the move will be possible without splitting or joining groups, or that some students have to change groups. **Challenge** Given the amount of students of the current groups and the new classrooms (capacity), output a truthy value if it is possible to assign a different classroom, with sufficient capacity, to each of the current groups, or a falsey value otherwise. **Test Cases** ``` Input: groups of students => [10, 20, 30], classrooms capacity => [31, 12, 20] Output: True Input: groups of students => [10, 20, 30], classrooms capacity => [100, 200] Output: False Input: groups of students => [20, 10, 30], classrooms capacity => [20, 20, 50, 40] Output: True Input: groups => [30, 10, 30, 5, 100, 99], classrooms => [40, 20, 50, 40, 99, 99] Output: False Input: groups => [], classrooms => [10, 10, 10] Output: True Input: groups => [10, 10, 10], classrooms => [] Output: False Input: groups => [], classrooms => [] Output: True Input: groups => [10, 1], classrooms => [100] Output: False Input: groups => [10], classrooms => [100, 100] Output: True Input: groups => [1,2,3], classrooms => [1,1,2,3] Output: True ``` **Notes** * You can take the input in any reasonable format * You can output any Truthy/Falsey value (`1/0`, `True/False`, etc...) * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes It's always nice to see a challenge and know brachylog is gonna beat everyone. Takes current classes as input and new classrooms as output; It will output true if it finds a way to fit the students, false otherwise ``` p≤ᵐ⊆ ``` ## Explanation The code has 3 parts of which the order actually doesn't matter ``` ≤ᵐ --> projects each value to a value bigger/equal then input ⊆ --> input is a ordered subsequence of output p --> permutes the list so it becomes a unordered subsequence ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v@BR55KHWyc86mr7/z/aUMdIxzgWRENYAA "Brachylog – Try It Online") [Answer] # Pyth, 11 bytes ``` .AgM.t_DMQ0 ``` Takes input as a list of lists, classroom sizes first, group sizes second. Try it online [here](https://pyth.herokuapp.com/?code=.AgM.t_DMQ0&input=%5B%5B31%2C%202%2C%2021%2C%201%5D%2C%5B10%2C%2020%2C%2030%5D%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=.AgM.t_DMQ0&test_suite=1&test_suite_input=%5B%5B31%2C%2012%2C%2020%5D%2C%5B10%2C%2020%2C%2030%5D%5D%0A%5B%5B100%2C%20200%5D%2C%5B10%2C%2020%2C%2030%5D%5D%0A%5B%5B20%2C%2020%2C%2050%2C%2040%5D%2C%5B20%2C%2010%2C%2030%5D%5D%0A%5B%5B40%2C%2020%2C%2050%2C%2040%2C%2099%2C%2099%5D%2C%5B30%2C%2010%2C%2030%2C%205%2C%20100%2C%2099%5D%5D%0A%5B%5B10%2C%2010%2C%2010%5D%2C%5B%5D%5D%0A%5B%5B%5D%2C%5B10%2C%2010%2C%2010%5D%5D%0A%5B%5B%5D%2C%5B%5D%5D%0A%5B%5B100%5D%2C%5B10%2C%201%5D%5D%0A%5B%5B100%2C%20100%5D%2C%5B10%5D%5D%0A%5B%5B1%2C1%2C2%2C3%5D%2C%5B1%2C2%2C3%5D%5D&debug=0). ``` .AgM.t_DMQ0 Implicit: Q=eval(input()) _DMQ Sort each element of Q in reverse .t 0 Transpose, padding the shorter with zeroes gM Element wise test if first number >= second number .A Are all elements truthy? Implicit print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes Takes the classrooms as first argument and the groups as second argument. ``` Œ!~+Ṡ‘ḌẠ¬ ``` [Try it online!](https://tio.run/##y0rNyan8///oJMU67Yc7FzxqmPFwR8/DXQsOrfn//3@0oY6hjpGOcSyIBaIB "Jelly – Try It Online") ### Commented *NB: This `Ṡ‘ḌẠ¬` is far too long. But I suspect that this is not the right approach anyway.* ``` Œ!~+Ṡ‘ḌẠ¬ - main link taking the classrooms and the groups e.g. [1,1,2,3], [1,2,3] Œ! - computes all permutations of the classrooms --> [..., [1,2,3,1], ...] ~ - bitwise NOT --> [..., [-2,-3,-4,-2], ...] + - add the groups to each list; the groups fits --> [..., [-1,-1,-1,-2], ...] in a given permutation if all resulting values are negative Ṡ - take the signs --> [..., [-1,-1,-1,-1], ...] ‘ - increment --> [..., [0,0,0,0], ...] Ḍ - convert from decimal to integer --> [..., 0, ...] Ạ - all truthy? --> 0 ¬ - logical NOT --> 1 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes ``` ñÍí§Vñn)e ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8c3tp1bxbill&input=WzEsMiwzXQpbMSwxLDIsM10=) or [run all test cases on TIO](https://tio.run/##y0osKPnvl35oQwgXmPx/eOPh3sNrDy0PO7wxTzP1/39DA65oQwMdIwMdY4NYnWhjQx1DIyAvFkXU0ADEBgkCRQyhgkZgeVMDHROQhDFUQsdUB6Ta0hKowgShAigAEuOKBpumA0YQOyBMnWiIHFQMYieYA7UeytUx0jEGiehAWFy6uUEA) ``` ñÍí§Vñn)e :Implicit input of arrays U=students, V=classrooms ñ :Sort U by Í : Subtracting each integer from 2 í :Interleave with Vñn : V sorted by negating each integer § : Reduce each pair by checking if the first is <= the second ) :End interleaving e :All true? ``` --- ``` ñÍeȧVn o ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8c1lyKdWbiBv&input=WzEsMiwzXQpbMSwxLDIsM10=) or [run all test cases on TIO](https://tio.run/##y0osKPnvl35oQwgXmPx/eOPh3tTDHYeWh@Up5P//b2jAFW1ooGNkoGNsEKsTbWyoY2gE5MWiiBoagNggQaCIIVTQCCxvaqBjApIwhkromOqAVFtaAlWYIFQABUBiXNFg03TACGIHhKkTDZGDikHsBHOg1kO5OkY6xiARHQiLSzc3CAA) ``` ñÍeȧVn o :Implicit input of arrays U=students, V=classrooms ñ :Sort U by Í : Subtracting each integer from 2 e :Does every element return true È :When passed through the following function § : Less than or equal to Vn : Sort V o : Pop the last element ``` [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes Outputs by exit code, fails for falsy input. ``` g,r=map(sorted,input()) while g:g.pop()>r.pop()>y ``` [Try it online!](https://tio.run/##XY4xj4MwDIX3/AqLCaToREJvKFK7lfWWbqgDRy2K2pLIDbry67k4pKh3g/Xi9z3HtpO7mEHPrTkj7CBJkrmTtLs3Nn0YcniW/WBHl2aZ@Ln0N4Su7D6ssWm2p6jT7KciPdKIpQBwNLEA4BNb4M9DZ6kfXAgJRi1aB4ev6kBkaMl/EzbXNxikN0P5Nl81twfOtcolaF9FfpJQF0qC0uycxD@k8tAyYFOtQMfYp68N42LF3uSn1@2Wo5s/UXYDEfWyYBlTr92x8SgmXn48J7TradGQWhbBk8vzFw "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` yn&Y@>~!Aa ``` [Try it online!](https://tio.run/##y00syfn/vzJPLdLBrk7RMfH//2gjAx0FQyA2NojlAnNA2BSITQxiAQ) Or [verify all test cases](https://tio.run/##y00syfmf8L8yTy3Swa5O0THxv0vI/2hDAx0FIyA2NojlijY21FEwNAIJADkoMoYGYB6ICRIzhIkbQRWZArEJ2Ai4LFAQxATSlpZACRMUlSBBqATUKghG58ARWATiEDAJcxOUr2OkYwymISwA). ### Explanation Consider inputs `[20, 10, 30]`, `[20, 20, 50, 40]` as an example. Stack is shown bottom to top. ``` y % Implicit inputs. Duplicate from below % STACK: [20 10 30] [20 20 50 40] [20 10 30] n % Number of elements % STACK: [20 10 30] [20 20 50 40] 3 &Y@ % Variations. Gives a matrix, each row is a variation % STACK: [20 10 30] [20 10 30 20 20 40 20 20 40 ··· 50 40 20] >~ % Less than? Element-wise with broadcast % STACK: [1 1 1 1 1 1 1 1 1 ··· 1 1 0] ! % Transpose % STACK: [1 1 1 ··· 0 1 1 1 ··· 1 1 1 1 ··· 1] A % All. True for columns that only contain nonzeros % STACK: [1 1 1 ··· 0] a % Any. True if the row vector contains at least a nonzero. Implicit display % STACK: 1 ``` [Answer] # [Haskell](https://www.haskell.org/), 40 bytes ``` c%l=[1|x<-l,x>=c] s#g=and[c%s<=c%g|c<-s] ``` [Try it online!](https://tio.run/##dY/BCoMwEETvfsWCFVpYIYl6UIyH3voNIQeJxUpTLdWDB/89TVQQqoUcJjNvNtlH2T/vWhujAs0FncY81DgWXEmv92tetpVQQZ9zFdSTysNemrN/gSwDcWsHCWGxiWvXae9VNi1wqDoP3p@mHeAEriAoQUYwIhJERJEye5P/EUqc3hE2pivBZjghGO@oaKUwQTcnTS0eb7g1nPdTmh/F@Rz8a/EttW8d0csG@2Td7ChDhpGLcVHmCw "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ ~~12~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` €{í0ζÆdP ``` Port of [*@Sok*'s Pyth answer](https://codegolf.stackexchange.com/a/179562/52210), so make sure to upvote him as well! Takes the input as a list of lists, with the classroom-list as first item and group-list as second item. [Try it online](https://tio.run/##yy9OTMpM/f//UdOa6sNrDc5tO9yWEvD/f3S0oY6hjpGOcaxONISOBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/R01rqg@vNTi37XBbSsB/nf/R0dHGhjoKhkY6CkYGsTrRhgYgho6CsUFsrI5CNJAPFjAAcdDljKB8UyA2AasA8QyRVJigqNBRsLQEYaA1xnCFQEkQEywJsxIiZwg2EiIGsx4qDheDOxKuAMnZcGGomI6hjpGOMVgIzIiNBQA). **Explanation:** ``` €{ # Sort each inner list í # Reverse each inner list 0ζ # Zip/transpose; swapping rows/columns, with 0 as filler Æ # For each pair: subtract the group from the classroom d # Check if its non-negative (1 if truthy; 0 if falsey) P # Check if all are truthy by taking the product # (and output implicitly) ``` --- **Old 12-byte answer:** ``` æε{I{0ζÆdP}à ``` Takes the classroom-list first, and then the group-list. [Try it online](https://tio.run/##yy9OTMpM/f//8LJzW6s9qw3ObTvclhJQe3jB///RhjqGOkY6xrFc0RAaAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9o4ObpYq@kkJiXoqBk73l4QiiQ86htEpBT/P/wsnNbqyOqDc5tO9yWElB7eMF/nf/RxoY6CoZGOgpGBrFc0YYGIIaOgjGEA@ZhiBtBOaZAbAITMITJmqDI6ihYWoIwUMIYrgooCWIaQCUMoRKGIO0QhFUI5hBDmNtgQiBCx1DHSMcYzALRAA). **Explanation:** ``` æ # Take the powerset of the (implicit) classroom-list, # resulting in a list of all possible sublists of the classrooms ε # Map each classroom sublist to: { # Sort the sublist I{ # Take the group-list input, and sort it as well 0ζ # Transpose/zip; swapping rows/columns, with 0 as filler Æ # For each pair: subtract the group from the classroom d # Check for everything if it's non-negative (1 if truthy; 0 if falsey) P # Check if all are truthy by taking the product }à # After the map: check if any are truthy by getting the maximum # (and output the result implicitly) ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~77~~ 74 bytes ``` a=>b=>a.Count==a.OrderBy(x=>-x).Zip(b.OrderBy(x=>-x),(x,y)=>x>y?0:1).Sum() ``` [Try it online!](https://tio.run/##jZJRa4MwEMff/RR5TCCVRLuHrk0KGwwGgw32tuJDdMqEVUcSN6Xss7tLLaKW1aIhuf/d/xc8LzGLxOTtQ1Ukm8en3NhNXlhJp3Fclp9SZqJVQsZCKv@@rAorhPKf9Xuq7xpcC7moif@Wf@F4IlJc04YIWctmy2458V@rPSbt2vOAvYvcg2xqrEECFekP6tWDNwgHwYEzigJYIfulAznkFPHApUAeZq5yc3bUL3udj597gxPyBtbyMiHsCVDujrCvViPackRz6VPJ/9TJl3RX8Pk@9GUj1JX3zNOnDZ5xnP@PWQ90Cno5NoKtl90Lk5aVOlXJB/5W@jhrUNrNHPEQetFgxBl2wo5FpDvwiJB1@wc "C# (Visual C# Interactive Compiler) – Try It Online") Commented code: ``` // a: student group counts // b: classroom capacities a=>b=> // compare the number of student // groups to... a.Count== // sort student groups descending a.OrderBy(x=>-x) // combine with classroom // capacities sorted descending .Zip( b.OrderBy(x=>-x), // the result selector 1 when // the classroom has enough // capacity, 0 when it doesn't (x,y)=>x<y?0:1 ) // add up the 1's to get the number // of student groups who can fit // in a classroom .Sum() ``` [Answer] ## Haskell, 66 bytes ``` import Data.List q=sortOn(0-) x#y=and$zipWith(<=)(q x)$q y++(0<$x) ``` [Try it online!](https://tio.run/##dY89C4MwEIZ3f8WBDgm9lsToIJitY6FjB3EIWDDUbzNo/7yNH1CoFm64e9/nvnLVv55FMU26bOrOwFUZdbnp3jit7K1wrwg7U2dwR6mqzHvr5qFNTmJJSQsD9VoYTyfCYm@gU6l0BRKy2oGm05UBD4hLIeEMfYaCpZAIjty3Vfof4WzOd4S1@Ub4CxwyDHaU2CgMcZ4TRRYPvrgVZu2naVmKSxzcteqW2ncd0esHe2f77MhDH8Vs45pNHw "Haskell – Try It Online") [Answer] # Bash + GNU tools, 68 bytes ``` (sort -nr<<<$2|paste -d- - <(sort -nr<<<$1)|bc|grep -- -)&>/dev/null ``` 69 bytes ``` (paste -d- <(sort -nr<<<$2) <(sort -nr<<<$1)|bc|grep -- -)&>/dev/null ``` [TIO](https://tio.run/##VY1JCoMwGIX3/ykeRbQuQgZ1IZX2It3YJtSCqCQdFrVnt4mWDhCS7w28HGrXTPfm3BpYU2s4xPFCdgPdkzMXMIZV9HCcg0fJvkueq6Dtj6Zp7Xrrm52tqipS41C7iwHTDAzVXybT8XAcT9YMYZel8ZZrc@PdtW0nc2x6RDvSfWdokgJKIBOUSUjlmT6OFIEEeSVnQ81JIZD7@ttEgdArS8q/qZfBCVPz@QItZtgmuXwxIxQyfy/vCw) takes student rooms as first and second argument as string numbers delimited by newline returns exit status 1 for true or 0 for false [Answer] # [Perl 5](https://www.perl.org/) `-pal`, ~~67~~ 62 bytes *@NahuelFouilleul saved 5 bytes with a rearrangement and a grep* ``` $_=!grep$_>0,map$_-(sort{$b-$a}@F)[$x++],sort{$b-$a}<>=~/\d+/g ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lYxvSi1QCXezkAnNxFI62oU5xeVVKsk6aok1jq4aUarVGhrx@ogCdrY2dbpx6Ro66f//29ooGBkoGBswGVsoGBopGBo8C@/oCQzP6/4v66vqZ6BocF/3YLEHAA "Perl 5 – Try It Online") [67 bytes version](https://tio.run/##K0gtyjH9/9@hyDY3saBaozi/qKRaJUlXJbHWwU0zWltbRbkkVlclvhZJwsbOtk4/JkVbP91aJd5WyaFISbFOX1f//39DAwUjAwVjAy5jAwVDIwVDg3/5BSWZ@XnF/3V9TfUMDA3@6xYk5gAA "Perl 5 – Try It Online") Takes the space separated list of class sizes on the first line and the space separated list of room sizes on the next. [Answer] # Common Lisp, 74 bytes `(defun c(s r)(or(not(sort s'>))(and(sort r'>)(<=(pop s)(pop r))(c s r))))` ## Non-minified ``` (defun can-students-relocate (students rooms) (or (not (sort students #'>)) (and (sort rooms #'>) (<= (pop students) (pop rooms)) (can-students-relocate students rooms)))) ``` [Test it](https://rextester.com/NMOUG17878) Note that sort permanently mutates the list, and pop rebinds the variable to the next element. In effect this just recursively checks that the largest student group can fit in the largest room. There are 3 base-cases: 1. No students - return T 2. Students, but no rooms - return NIL 3. Students and rooms, but largest student group larger than largest room - return NIL [Answer] # [Python 2](https://docs.python.org/2/), ~~71~~ ~~67~~ 64 bytes ``` lambda g,c:s(g)==s(map(min,zip(s(g)[::-1],s(c)[::-1]))) s=sorted ``` [Try it online!](https://tio.run/##dZA5DoMwEEV7TmEpjS1NJMaQAiS3OUE6QkHYgsQmTIrk8sQGQxbhYuRZ3v/2uH@O967lUyGuU500tywhJaShpCUTQtIm6WlTtfCqeqp7URgeMQZJU5MyxhwpZDeMeTb1Q9WOpKARukC4Cs@NgUQeAkGuOzEjB3IZHrnjWFh053Ihz0ktv1GN4YZyIzyp8HetvY1XlE7VGQRa6/9odXee7F26vGoxQusGZqpYq4lVavbeFeLnV1bk3wI4eDMES7oy0xs "Python 2 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 50 bytes ``` \d+ $* %O^`1+ %`$ , ^((1*,)(?=.*¶((?>\3?)1*\2)))*¶ ``` [Try it online!](https://tio.run/##RY5NCgIxDIX3OccU0k6QpJ1ZDEV7BBduy1BBF25cyJzNA3ixmhZ/4EG@vBeSPK7b7X6uBk8l1nwZYXBgjmuREUwZgGBFFEcW037nXk/EdMghWXHZW2vVqVWYPFPgGITEK8PPEW7EoJ10w/dkZpoYwsekmdrcssTpn2qrAt1AXfCFCLFz263QT3QkTyHqB62@AQ "Retina 0.8.2 – Try It Online") Link includes test suite. Takes two lists of groups and rooms (test suite uses `;` as list separator). Explanation: ``` \d+ $* ``` Convert to unary. ``` %O^`1+ ``` Reverse sort each list separately. ``` %`$ , ``` Append a comma to each list. ``` ^((1*,)(?=.*¶((?>\3?)1*\2)))*¶ ``` Check that each of the numbers in the first list can be matched to the appropriate number in the second list. Each time `\3` contains the previously matched rooms and the next group `\2` therefore needs to be able to fit into the next room. The `(?>\3?)` handles the case of the first room when there are no previous rooms yet. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` W∧⌊講⌈§θ¹⌈§θ⁰UMθΦκ⁻ν⌕κ⌈κ¬⊟θ ``` [Try it online!](https://tio.run/##bY47C8MwDIT3/gqPMrjg9DF1CoWWDinZgweTGGLiR@I6bf69K3vpUsEt3@lO6kcZei9NSp9RG0WgdgM02mm7WlgoI08f4R6UjCpAI7fC6/hwg9pgYaSiuPOHc1oGrfnqrZXYivSmTe6ZMKLd@gKXEVrTr2MqucuuDdpFyNdbP@MnyFLquu7AGck6o05cMFJIhTpyIUTav80X "Charcoal – Try It Online") Link is to verbose version of code. Takes a list of lists of rooms and groups and outputs `-` if the rooms can accommodate the groups. Explanation: ``` W∧⌊講⌈§θ¹⌈§θ⁰ ``` Repeat while a group can be assigned to a room. ``` UMθΦκ⁻ν⌕κ⌈κ ``` Remove the largest room and group from their lists. ``` ¬⊟θ ``` Check that there are no unallocated groups remaining. [Answer] # JavaScript, 56 bytes ``` s=>c=>s.sort(g=(x,y)=>y-x).every((x,y)=>c.sort(g)[y]>=x) ``` [Try it](https://tio.run/##ZZBBDoIwEEX3nMJlm4y1BVy4KEtP4K42kWAhGqSGIqGnxxaoRkm6mP7/5nc697zPTdHent220Vc1lnw0PCt4ZojRbYcqjgawmGd2O2CietVatCjFQmBhZcYHPBa6MbpWpNYVElEkBKMQU0ioBJEwYLG7SQmb3W5zal/qF2DU18E/5rXxgHPZAsQTu6eQ/oUkCwN78CGHg4PTL@wEr00tIXZ6D6YzG995ZhHEqmEFzkP/cix85eOEBogh8R7MlQxWJMkjfyIk3FKl22qJBowsxuSub83l3Fzw@AY) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 34 bytes ``` {none [Z>] $_>>.sort(-*)>>[^.[0]]} ``` [Try it online!](https://tio.run/##rZBRa4MwFIWf56@4FFm1pGq0G3Rgyh42GAz6MvYw60Z0OgpqxOiDtP3tzmQyKnWrjD1cEsg53zk3eVQk101aw2UMLjS7jGUReC/EB/WNEIOzotTmM50Q79XwLN8/NDErQEu2WcR1mBNQKQI1aCd0JxPYKRec1rCKNZUaIUsDzdx4xmy18c2WYdw93z7qCKbCOEV7Neg0T0UV7e9pwiNTVw7NQ5ZX5Q18FKzKObAYeFm9R1nJwSXgYQuB3Y5j@QjChHJeMJZyCGlOw21ZS5GDEWBbCH1lXZWSJ1IU5R/g2JKqI7Tsfo4tuPgc2@4KXLWzOFNeLvoNbT3i2p7LZT9A6BY9rtBI3e8bCOMpCneReES9I@0J50/hIyOHWlsjAod6yj/t2X@MRjZyBgDo66Hn/wQ "Perl 6 – Try It Online") Takes input as a list of two lists, the groups and the classrooms, and returns a None Junction that can be boolified to true/false. ### Explanation: ``` { } # Anonymous code block $_>>.sort(-*) # Sort both lists from largest to smallest >>[^.[0]] # Pad both lists to the length of the first list none # Are none of [Z>] # The groups larger than the assigned classroom ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` ->c,r{r.permutation.any?{|p|c.zip(p).all?{|a,b|b&&a<=b}}} ``` [Try it online!](https://tio.run/##ZZBBCoMwEEX3nsJVaWEaTGIXQm0PErKIolSwNogurPHsdhJTtXQxzMz7f8gnbZ8Nc5nO51sO7dgSXbTPvlNd9WqIaob7aLTJybvSR30iqq4RKMhMdjioa5pN0zSLQAgaQciweCQhFJxCSJklUsKfSiO3es1yumrMOy9YsXfw1YHcjtiTxLrjH7elTnFXy0vLJd3l8Duqm2@n@oBfsubdGDDgDsMyykCSQuWP0eAHGh2WAruc5g8 "Ruby – Try It Online") Takes `c` for classes, `r` for rooms. Checks all permutations of rooms instead of using sort, because reverse sorting costs too many bytes. Still looks rather long though... [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~105~~ ~~93~~ ~~91~~ ~~82~~ ~~81~~ ~~79~~ ~~77~~ ~~76~~ 74 bytes Now matches dana's score! ``` n=>m=>{n.Sort();m.Sort();int i=m.Count-n.Count;i/=n.Any(b=>m[i++]<b)?0:1;} ``` Throws an error if false, nothing if true. -12 bytes thanks to @Destrogio! [Try it online!](https://tio.run/##pZBNi4MwEIbv/gqPSq012h7amJRS2FNve9jDsoc2KB2oI@hIKZLfbpN@sq0syB6GGeZ9M89MVD1WNXQfDap0AzWlgCSDlSIo8dmQMhcdClkI2WL4WVbk@by4F8bhgijCddkgjfGaOUwEhis8eTvz7htGo5905y@jBeO64w5Vp9bJPcyO7oPSsihwYxNJpP0XKWGBy2Ira587XxVQtgHMPKqazDS0o7ak9u1TyLeH2ih6MIlFF62X8wfmwnnFWATrx8S3DWYmphY2gNWHSh4oM9OWJs/nb9jpL6y1XG38v6f2/KPdYtDk7gw "C# (Visual C# Interactive Compiler) – Try It Online") # Explanation ``` //Function taking in a list, and returning another function //that takes in a list and doesn't return n=>m=>{ //Sort the student groups from smallest to largest n.Sort(); //Sort the classrooms fom smallest capacity to largest m.Sort(); //Initialize a variable that will function as a sort of index int i=m.Count-n.Count; //And divide that by... i/= //0 if any of the student groups... n.Any(b=> //Don't fit into the corresponding classroom and incrementing i in the process /*(In the case that a the amount of classrooms are less than the amount of student groups, an IndexOutOfRangeException is thrown)*/ m[i++]<b)?0 //Else divide by 1 :1; } ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 183 bytes ``` a->{int b=a[0].length;Arrays.sort(a[0]);Arrays.sort(a[1]);if(b>a[1].length){return false;}for(int i=0;i<b;i++){if(a[0][i]>a[1][i]){return false;}}return true;} ``` [Try it online!](https://tio.run/##tVBNa8MwDL33V@gYUzc4/TgUr4X9gPXSY8jBaZ3OXWoHx@koxr89k7PAoNDt0oFB0pPfe5LO4ipmppH6fPzo1aUx1sEZsbRzqk5frRW3lk8OtWhbeBNK@wmA0k7aShwk7HxpTC2FBpsgmhd5AYLwgJ9aJ5w6wA70Bnox23rsQ7kROSvSWuqTe@ff6mmLnknEyR2SIaKqpNzGdCQRb6XrrIZK1K3koTKDM6gN4@ql5Go6JR5JUS9XxUDFeE8LY@lsh1XPceCmK2sceJz7atQRLrhwsndW6VNeCBJ3B9jfWicvqelc2mDH1TrRqU20/ITxBN5njM4ZXbBAPcZsThdZCITwRwKPO79JZyzm7B@U50O6YnT5NPUF3iGq0xWNc6/XaLP8sUEgYk8yG45Dh/e3ZJiE/gs "Java (OpenJDK 8) – Try It Online") With a little helpful advice from [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen/%22Kevin%20Cruijssen%22) and simply another glance over my code myself, I can decrease my score by a whole 9% just by replacing three English words! # [Java (OpenJDK 8)](http://openjdk.java.net/), 166 bytes ``` a->{int b=a[0].length;Arrays.sort(a[0]);Arrays.sort(a[1]);if(b>a[1].length){return 0;}for(int i=0;i<b;){if(a[0][i]>a[1][i++]){return 0;}}return 1;} ``` [Try it online!](https://tio.run/##tVDLasMwELznK/ZoNYqQ8zgENYF@QHPJ0fggJ0oq15GNLKcEoW93V8bQUkh7SUFIw@zuzKxKeZWzulGmPL73@tLU1kGJHOucrtiTmBwq2bbwKrXxEwBtnLIneVCw84jBJnhneZaDJCJgQ@uk0wfYgdlAL2fboavYyIznrFLm7N7Ei7Xy1rIWrZLIkx9Miow@JcU2wnGIeKtcZw1wEU714Ap6w4V@LgTx2B2FMp0PM5meTvPvE2GEqQi9wJBNV1QYcsx6rfURLrhgsndWm3OWSxJ3BdjfWqcurO4ca7DiKpMYZhOjPmBc2/uU0zmnCx6oxzed00UaAiHinsD9ym/SKY@Y/4PyfIArTpcPU1/gP0R1uqIx93qNNssvGyQi9yCz4XPocP6WDJPQfwI "Java (OpenJDK 8) – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 80 bytes ``` param($s,$c)!($s|sort -d|?{$_-gt($r=$c|?{$_-notin$o}|sort|select -l 1);$o+=,$r}) ``` [Try it online!](https://tio.run/##dZJda4MwFIbv/RVZORsJi2C0u@iGzKv9gt0X0XQbpMYlkQ2qv90d48faYgMhOec875vPWv9IYz@lUj0cSEpOfZ2b/EjBcijYHY6t1caRsGxfT7APPxwFk0IxRpV2XxXozjOtlUoWiCoi2Avox5SD6VjfBUFGA4KN04yKiJMYexIxTjKaCE5EPKQwBGcayW6hIvKxB99yZc/IgRL/ZDwJn7BvPf9@YZwsODLDFMfdzku3F9IhPZWul5y2NBqJlUUuap5ftbghnE@8IhNn1zERVwY85snI8Hk@IYy05J6cPArWNaWsnMVqoXJrjdbHIZC/Nb6jLPE7wH5EjbSNcph4wF@yCM91ntsAndBQfi8@7Hk22ARd/wc "PowerShell – Try It Online") Less golfed test script: ``` $f = { param($students,$classrooms) $x=$students|sort -Descending|where{ $freeRoomWithMaxCapacity = $classrooms|where{$_ -notin $occupied}|sort|select -Last 1 $occupied += ,$freeRoomWithMaxCapacity # append to the array $_ -gt $freeRoomWithMaxCapacity # -gt means 'greater than'. It's a predicate for the 'where' } # $x contains student groups not assigned to a relevant classroom !$x # this function returns a true if $x is empty } @( ,(@(10, 20, 30), @(31, 12, 20), $true) ,(@(10, 20, 30), @(100, 200), $False) ,(@(20, 10, 30), @(20, 20, 50, 40), $True) ,(@(30, 10, 30, 5, 100, 99), @(40, 20, 50, 40, 99, 99), $False) ,(@(), @(10, 10, 10), $True) ,(@(10, 10, 10), @(), $False) ,(@(), @(), $True) ,(@(10, 1), @(100), $False) ,(@(10), @(100, 100), $True) ,(@(1,2,3), @(1,1,2,3), $True) ) | % { $students, $classrooms, $expected = $_ $result = &$f $students $classrooms "$($result-eq$expected): $result" } ``` [Answer] # [R](https://www.r-project.org/), 65 bytes ``` function(g,r)isTRUE(all(Map(`-`,sort(-g),sort(-r)[seq(a=g)])>=0)) ``` [Try it online!](https://tio.run/##bVC9DoIwEN59ChKXu@RM2oIDAyYOOuniz2RMIAQaEgJa8PmR0gKCDJd@ve@nd1VNGjTpp4jrrCxAksKsul3uB4jyHM7RC8JNSFWpathItEDho0reEAUSn7gLGGKTQgyckSPachlSDC4nhwvdQXTWjs5c/as4665Gc9yfrkakBXwQCWvZtuXN4txB2fIatqfva5c3celux/w@lBV1IhMFZhITxBfmtX0a9MshE3oaYHedrcnHP@jJ0UaC3I4mA3u2@QI "R – Try It Online") ]
[Question] [ In chess, a knight can only move to the positions marked with X relative to its current position, marked with ♞: [![where a knight can move](https://i.stack.imgur.com/uYFbI.png)](https://i.stack.imgur.com/uYFbI.png) --- A [Knight's Graph](https://en.wikipedia.org/wiki/Knight%27s_graph) is a graph that represents all legal moves of the knight chess piece on a chessboard. Each vertex of this graph represents a square of the chessboard, and each edge connects two squares that are a knight's move apart from each other. The graph looks like this for a standard 8-by-8 board. [![enter image description here](https://i.stack.imgur.com/QX6H9.png)](https://i.stack.imgur.com/QX6H9.png) --- ### Challenge: Given an integer **N**, where **3 ≤ N ≤ 8**, output an **N-by-N** matrix representing a board, where the number of possible moves from each position is shown. For **N = 8**, the output will be a matrix showing the values of each vertex in the graph above. The output format is flexible. List of lists or even a flattened list etc. are accepted formats. --- ### Complete set of test cases: ``` --- N = 3 --- 2 2 2 2 0 2 2 2 2 --- N = 4 --- 2 3 3 2 3 4 4 3 3 4 4 3 2 3 3 2 --- N = 5 --- 2 3 4 3 2 3 4 6 4 3 4 6 8 6 4 3 4 6 4 3 2 3 4 3 2 --- N = 6 --- 2 3 4 4 3 2 3 4 6 6 4 3 4 6 8 8 6 4 4 6 8 8 6 4 3 4 6 6 4 3 2 3 4 4 3 2 --- N = 7 --- 2 3 4 4 4 3 2 3 4 6 6 6 4 3 4 6 8 8 8 6 4 4 6 8 8 8 6 4 4 6 8 8 8 6 4 3 4 6 6 6 4 3 2 3 4 4 4 3 2 --- N = 8 --- 2 3 4 4 4 4 3 2 3 4 6 6 6 6 4 3 4 6 8 8 8 8 6 4 4 6 8 8 8 8 6 4 4 6 8 8 8 8 6 4 4 6 8 8 8 8 6 4 3 4 6 6 6 6 4 3 2 3 4 4 4 4 3 2 ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution in each language wins. **Explanations are encouraged!** [Answer] # [MATL](https://github.com/lmendo/MATL), ~~17~~ 16 bytes ``` t&l[2K0]B2:&ZvZ+ ``` [Try it online!](https://tio.run/##y00syfn/v0QtJ9rI2yDWychKLaosSvv/f1MA "MATL – Try It Online") *(-1 byte thanks to @Luis Mendo.)* The main part of the code is creating a matrix \$ K \$ for convolution: $$ \mathbf{K} = \begin{pmatrix}0&1&0&1&0\\1&0&0&0&1\\0&0&0&0&0\\1&0&0&0&1\\0&1&0&1&0\end{pmatrix} $$ (Relative to the centre of the matrix, each 1 is a valid knight's move.) `t&l` - Form a nxn matrix of all 1s (where n is the input). Let this be M. `[2K0]` - Push an array containing [2, 4, 0] on stack `B` - Convert all to binary, padding with 0s as needed ``` 0 1 0 1 0 0 0 0 0 ``` `2:&Zv` - Mirror that on both dimensions, without repeating the final row/column ("symmetric range indexing"). This gives us the required matrix K. ``` 0 1 0 1 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 1 0 1 0 ``` `Z+` - Perform 2D convolution of K over the earlier matrix M (`conv2(M, K, 'same')`), summing up the 1s at legal knight move targets for each position Result matrix is displayed implicitly. [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` lambda n:[sum(2==abs((i/n-k/n)*(i%n-k%n))for k in range(n*n))for i in range(n*n)] ``` [Try it online!](https://tio.run/##VYtBCoMwFETXeoq/EX5ii9RuSiAnsS4i1Taoo0Sl9PRpgoW2qxnevJlf62NC6Tt99YMZm5shqGrZRi61Ns3CbAsc@wJCss1CyyBENznqyYKcwb1lyA@z/6z2EeILzwe6CJUmrl22YSVNHUOkSbTc9Pw5RymZncVKu1uFXUJxiPwkJOp0n/0b "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 88 bytes Returns a string. ``` n=>(g=k=>--k?[n>3?'-2344-6-6'[(h=k=>k*2<n?~k:k-n)(k%n)*h(k/n|0)]||8:k-4&&2]+g(k):2)(n*n) ``` [Try it online!](https://tio.run/##XYxLDoJAEAX3nqIX6nQzGTBAjEEHbuAFxETCVwd7jBo3gFdH2LqqpF7l3bJP9sqf18dbsS3KsdIj6xhrbXSslElOHAeJUH4QhmqrtuKEzTwZxz9w8jWRUUxoVkxOg8bjfkPnvt9NOlyv/bOs0VDkE7LDNFb2iQwagj0wHDTsJkpJ0C0Acssv25Zua2sUxykSIKdKgogE7f@CCpnce/bOGyw/WYsXD9O0oG7Z8TB49YXIvdkro0hZ0PwxczGMPw "JavaScript (Node.js) – Try It Online") ## How? ### Special case: \$n=3\$ We fill each cell with \$2\$, except the center one which is set to \$0\$: $$\pmatrix{2 & 2 & 2\\ 2 & 0 & 2\\ 2 & 2 & 2}$$ ### Other cases: \$3<n\le 8\$ For each cell \$(x,y)\$ with \$0\le x<n\$ and \$0\le y<n\$, we compute a lookup index \$i\_{x,y}\$ defined as: $$i\_{x,y}=\min(x+1,n-x)\times \min(y+1,n-y)$$ For \$n=8\$, this gives: $$\pmatrix{1 & 2 & 3 & 4 & 4 & 3 & 2 & 1\\ 2 & 4 & 6 & 8 & 8 & 6 & 4 & 2\\ 3 & 6 & 9 & 12 & 12 & 9 & 6 & 3\\ 4 & 8 & 12 & 16 & 16 & 12 & 8 & 4\\ 4 & 8 & 12 & 16 & 16 & 12 & 8 & 4\\ 3 & 6 & 9 & 12 & 12 & 9 & 6 & 3\\ 2 & 4 & 6 & 8 & 8 & 6 & 4 & 2\\ 1 & 2 & 3 & 4 & 4 & 3 & 2 & 1}$$ The lookup table \$T\$ is defined as: $$T = [0,2,3,4,4,0,6,0,6]$$ where \$0\$ represents an unused slot. We set each cell \$(x,y)\$ to: $$\begin{cases}T(i\_{x,y})&\text{if }i\_{x,y} \le 8\\8&\text{otherwise}\end{cases}$$ --- # JavaScript (ES7), 107 bytes A naive implementation which actually tries all moves. ``` n=>[...10**n-1+''].map((_,y,a)=>a.map((k,x)=>~[...b=i='01344310'].map(v=>k-=!a[x-v+2]|!a[y-b[i++&7]+2])+k)) ``` [Try it online!](https://tio.run/##XY1LbsJAEET3nKKzoadpz8iOkUBA@wi5gGNFA8GRMfQgE1mgfK7ujBNWWdVHr1QH3/vLrmvO71bD636oZVApSudcls5majNGrNzJn415SW6JJyn8X2yTawzfI7qVRjDN8vk8z9I73kvRWnnw5dX2/Fh9Rnez27Jhni6qWBC3REMdOqMgkK9BYSOwjMpM8DEB2AW9hOPeHcObwacIIXCkGHCFtP4H1Ebp97cDKaBzh9CoQUCiu31WpHE76uRr@AE "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23 22 14~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ²ḶdðạP€ċ2) ``` A monadic link yielding a flat list - uses the idea first used by KSab in [their Python answer](https://codegolf.stackexchange.com/a/170489/53748) - knight's moves have "sides" 1 and 2, the only factors of 2. **[Try it online!](https://tio.run/##ASUA2v9qZWxsef//wrLhuLZkw7DhuqFQ4oKsxIsyKf/Dh3PigbhH//84 "Jelly – Try It Online")** (footer calls the program's only Link and then formats the result as a grid) Alternatively, also for 10 bytes, `²Ḷdðạ²§ċ5)` (knight's moves are all of the possible moves with distance \$\sqrt{5}\$) ### How? ``` ²ḶdðạP€ċ2) - Link: integer, n (any non-negative) e.g. 8 ² - square n 64 Ḷ - lowered range [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63] d - divmod (vectorises) i.e. x->[x//n,x%n] [[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[1,0],[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[2,0],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[3,0],[3,1],[3,2],[3,3],[3,4],[3,5],[3,6],[3,7],[4,0],[4,1],[4,2],[4,3],[4,4],[4,5],[4,6],[4,7],[5,0],[5,1],[5,2],[5,3],[5,4],[5,5],[5,6],[5,7],[6,0],[6,1],[6,2],[6,3],[6,4],[6,5],[6,6],[6,7],[7,0],[7,1],[7,2],[7,3],[7,4],[7,5],[7,6],[7,7]] ð ) - new dyadic chain for each - call that L ( & e.g. R = [1,2] representing the "2nd row, 3rd column" ...-^ ) ạ - absolute difference (vectorises) [[1,2],[1,1],[1,0],[1,1],[1,2],[1,3],[1,4],[1,5],[0,2],[0,1],[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[1,2],[1,1],[1,0],[1,1],[1,2],[1,3],[1,4],[1,5],[2,2],[2,1],[2,0],[2,1],[2,2],[2,3],[2,4],[2,5],[3,2],[3,1],[3,0],[3,1],[3,2],[3,3],[3,4],[3,5],[4,2],[4,1],[4,0],[4,1],[4,2],[4,3],[4,4],[4,5],[5,2],[5,1],[5,0],[5,1],[5,2],[5,3],[5,4],[5,5],[6,2],[6,1],[6,0],[6,1],[6,2],[6,3],[6,4],[6,5]] P€ - product of €ach [2, 1, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 1, 2, 3, 4, 5, 4, 2, 0, 2, 4, 6, 8, 10, 6, 3, 0, 3, 6, 9, 12, 15, 8, 4, 0, 4, 8, 12, 16, 20, 10, 5, 0, 5, 10, 15, 20, 25, 12, 6, 0, 6, 12, 18, 24, 30] ċ2 - count 2s 6: ^-...1 ^-...2 ^-...3 ^-...4 ^-...5 ^-...6 - ) v-...that goes here - -> -> [2, 3, 4, 4, 4, 4, 3, 2, 3, 4, 6, 6, 6, 6, 4, 3, 4, 6, 8, 8, 8, 8, 6, 4, 4, 6, 8, 8, 8, 8, 6, 4, 4, 6, 8, 8, 8, 8, 6, 4, 4, 6, 8, 8, 8, 8, 6, 4, 3, 4, 6, 6, 6, 6, 4, 3, 2, 3, 4, 4, 4, 4, 3, 2] ``` --- **Previous 22 byter** ``` 2RżN$Œp;U$+,ḟ€³R¤Ẉ¬Sðþ ``` A full program (due to `³`). **[Try it online!](https://tio.run/##ATEAzv9qZWxsef//MlLFvE4kxZJwO1UkKyzhuJ/igqzCs1LCpOG6iMKsU8Oww77/w4dH//84 "Jelly – Try It Online")** (footer calls the program's only Link and then formats the result as a grid) Finds all moves and counts those which land on the board ~~probably~~ *definitely* beatable by calculating (maybe beatable by changing the "land on the board" logic). [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 18 bytes ``` +/+/2=×/¨|∘.-⍨⍳2⍴⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/5r62vrG9kenq5/aEXNo44ZerqPelc86t1s9Kh3C1Dlf6Ca/2lcxlxpXCZAbArEZkBsDsQWAA "APL (Dyalog Classic) – Try It Online") `⎕` evaluated input N `2⍴⎕` two copies of N `⍳2⍴⎕` the indices of an N×N matrix - a matrix of length-2 vectors `∘.-⍨` subtract each pair of indices from each other pair, get an N×N×N×N array `|` absolute value `×/¨` product each `2=` where are the 2s? return a boolean (0/1) matrix Note that a knight moves ±1 on one axis and ±2 on the other, so the absolute value of the product of those steps is 2. As 2 can't be factored in any other way, this is valid only for knight moves. `+/+/` sum along the last dimension, twice [Answer] # [RAD](https://bitbucket.org/zacharyjtaylor/rad), ~~51~~ ~~46~~ 39 bytes ``` {+/(⍵∘+¨(⊖,⊢)(⊢,-)(⍳2)(1¯2))∊,W}¨¨W←⍳⍵⍵ ``` [Try it online!](https://tio.run/##K0pM@f@/Wltf41Hv1kcdM7QPrdB41DVN51HXIk0gY5GOLpDq3WykqWF4aL2Rpuajji6d8NpDKw6tCH/UNgEoA9LWu/X///8WAA "RAD – Try It Online") ## How? Counts the number of valid knight moves for each square by seeing which knight moves would land on the board: ``` {+/(⍵∘+¨(⊖,⊢)(⊢,-)(⍳2)(1¯2))∊,W}¨¨W←⍳⍵⍵ +/ - The number of ... ∊,W - ... in-bounds ... (⊖,⊢)(⊢,-)(⍳2)(1¯2) - ... knight movements ... (⍵∘+¨ ) - ... from ... { }¨¨W←⍳⍵⍵ - ... each square ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 65 40 33 bytes This breaks down for N bigger then 9. So I'm happy N can be only go to 8 =) ``` ⟦₅⟨∋≡∋⟩ᶠ;?z{{hQ&t⟦₅↰₁;Qz-ᵐ×ȧ2}ᶜ}ᵐ ``` * -25 bytes by switching to KSab's formula * -7 bytes by flattening the array thanks to sundar [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZY@aWh/NX/Goo/tR50IQOX/lw20LrO2rqqszAtVKoAraNjxqarQOrNJ9uHXC4eknlhvVPtw2pxbI@f/f9H8UAA "Brachylog – Try It Online") --- # [Brachylog](https://github.com/JCumin/Brachylog), 44 36 bytes This one also works for number higher then 9 ``` gP&⟦₅⟨∋≡∋⟩ᶠ;z{{hQ&t⟦₅↰₁;Qz-ᵐ×ȧ2}ᶜ}ᵐ ``` * -8 bytes by flattening the array thanks to sundar [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/Pz1A7dH8ZY@aWh/NX/Goo/tR50IQOX/lw20LrAOqqqszAtVKoAraNjxqarQOrNJ9uHXC4eknlhvVPtw2pxbI@f/f0PR/FAA "Brachylog – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 161 bytes ``` .+ * L$`_ $= (?<=(¶)_+¶_+)?(?=(?<=(¶)_*¶_*)__)?(?<=(¶)__+)?(?=(?<=(¶)_*)___)?_(?=(?<=___)_*(¶))?(?=__+(¶))?(?=(?<=__)_*¶_*(¶))?(?=_+¶_+(¶))? $.($1$2$3$4$5$6$7$8) ``` [Try it online!](https://tio.run/##ZY07DsIwEET7Occg@SNF2nwgBZZLGu6woaCgoUCcLQfIxRw7sUJBt/Pmafbz/L7eD0knc5tS4@Fw56RggInXYJbZql9m9TaaGA7kMnJWtdCK/pSMcq@VlaCuNJuW9ePe6zr6M7a3ewQbQ2HLjj0HnnnhaFMSoAU6oAcGYAREVg "Retina – Try It Online") Link includes test cases. Explanation: ``` .+ * ``` Convert to unary. ``` L$`_ $= ``` List the value once for each `_` in the value, i.e. create a square. ``` (?<=(¶)_+¶_+)? (?=(?<=(¶)_*¶_*)__)? (?<=(¶)__+)? (?=(?<=(¶)_*)___)? _ (?=(?<=___)_*(¶))? (?=__+(¶))? (?=(?<=__)_*¶_*(¶))? (?=_+¶_+(¶))? ``` Starting at the `_` in the middle of the regex, try to match enough context to determine whether each of the eight knight's moves is possible. Each pattern captures a single character if the match succeeds. I tried using named groups so that the number of captures directly equals the desired result but that cost 15 bytes. ``` $.($1$2$3$4$5$6$7$8) ``` Concatenate all the successful captures and take the length. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes Yet another Mathematica built-in. ``` VertexDegree@KnightTourGraph[#,#]& ``` Returns a flattened list. [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z8stagktcIlNb0oNdXBOy8zPaMkJL@0yL0osSAjWllHOVbtv0t@dEBRZl5JdJ6Crp1CWnRebKyOQnWejoKxjoJFbex/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~114~~ ~~103~~ 92 bytes ``` lambda n:[sum((d*c>d)+(d*c>c)for d in(y%n,n-y%n-1)for c in(y/n,n-y/n-1))for y in range(n*n)] ``` [Try it online!](https://tio.run/##RcgxDsIwEETRnlNsg7QbEkVARSS4CFAYG8NKZBKZUPj0JtkCmvmjN@bpOWBX4vFSXq6/BUfozu9PzxwqfwqysXqJQ6JACs5r1GjmbbaG3rA1bBc0zbNScnjcGRXkWhbUP@5rOki3IhqTYiL9vcgq5Qs "Python 2 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 133 125 bytes This solution should work on any size board. ``` #define T(x,y)(x<3?x:2)*(y<3?y:2)/2+ a,b;f(i){for(a=i--;a--;)for(b=i+1;b--;)printf("%i ",T(a,b)T(i-a,b)T(a,i-b)T(i-a,i-b)0);} ``` [Try it online!](https://tio.run/##ZU7NCsIwDD7bpwgTIbUt6naRdcWX2NFLN53kYJXhYWPs2WuKDg8Gknxf8uWnNbe2jXF9uXYUrlDjoEeJQ1WchjKXWxwZjYx2uRJeN7ZDklP36NE7MsZ6dplo40gdbJPos6fw6jDbEGS6Rp6SNZL5ZK/JLDyhvbRzZD3cPQWUMAlg442AqUqusECVO3JUamkn@10p@QyQtGKVnrN/inPIvtVZzPEN "C (gcc) – Try It Online") ]
[Question] [ Quick musical refresher: The piano keyboard consists of 88 notes. On each octave, there are 12 notes, `C, C♯/D♭, D, D♯/E♭, E, F, F♯/G♭, G, G♯/A♭, A, A♯/B♭` and `B`. Each time you hit a 'C', the pattern repeats an octave higher. [![enter image description here](https://i.stack.imgur.com/Pu3t5.png)](https://i.stack.imgur.com/Pu3t5.png) A note is uniquely identified by 1) the letter, including any sharps or flats, and 2) the octave, which is a number from 0 to 8. The first three notes of the keyboard, are `A0, A♯/B♭` and `B0`. After this comes the full chromatic scale on octave 1. `C1, C♯1/D♭1, D1, D♯1/E♭1, E1, F1, F♯1/G♭1, G1, G♯1/A♭1, A1, A♯1/B♭1` and `B1`. After this comes a full chromatic scale on octaves 2, 3, 4, 5, 6, and 7. Then, the last note is a `C8`. Each note corresponds to a frequency in the 20-4100 Hz range. With `A0` starting at exactly 27.500 hertz, each corresponding note is the previous note times the twelfth root of two, or roughly 1.059463. A more general formula is: [![enter image description here](https://i.stack.imgur.com/rwSEC.png)](https://i.stack.imgur.com/rwSEC.png) where n is the number of the note, with A0 being 1. (More information [here](https://en.wikipedia.org/wiki/Piano_key_frequencies)) # The Challenge Write a program or function that takes in a string representing a note, and prints or returns the frequency of that note. We will use a pound sign `#` for the sharp symbol (or hashtag for you youngins) and a lowercase `b` for the flat symbol. All inputs will look like `(uppercase letter) + (optional sharp or flat) + (number)` with no whitespace. If the input is outside of the range of the keyboard (lower than A0, or higher than C8), or there are invalid, missing or extra characters, this is an invalid input, and you do not have to handle it. You can also safely assume you will not get any weird inputs such as E#, or Cb. # Precision Since infinite precision isn't really possible, we'll say that anything within [one cent](https://en.wikipedia.org/wiki/Cent_(music)) of the true value is acceptable. Without going into excess detail, a cent is the 1200th root of two, or 1.0005777895. Let's use a concrete example to make it more clear. Let's say your input was A4. The ***exact*** value of this note is 440 Hz. Once cent flat is `440 / 1.0005777895 = 439.7459`. Once cent sharp is `440 * 1.0005777895 = 440.2542` Therefore, any number greater than 439.7459 but smaller than 440.2542 is precise enough to count. # Test cases ``` A0 --> 27.500 C4 --> 261.626 F#3 --> 184.997 Bb6 --> 1864.66 A#6 --> 1864.66 A4 --> 440 D9 --> Too high, invalid input. G0 --> Too low, invalid input. Fb5 --> Invalid input. E --> Missing octave, invalid input b2 --> Lowercase, invalid input H#4 --> H is not a real note, invalid input. ``` Keep in mind that you don't have to handle the invalid inputs. If your program pretends they are real inputs and prints out a value, that is acceptable. If your program crashes, that it also acceptable. Anything can happen when you get one. For the full list of inputs and outputs, see [this page](http://www.sengpielaudio.com/calculator-notenames.htm) As usual, this is code-golf, so standard loopholes apply, and shortest answer in bytes wins. [Answer] # Japt, ~~41~~ ~~37~~ ~~35~~ 34 bytes I finally have a chance to put `¾` to good use! :-) ``` 55*2pU¬®-1¾ª"C#D EF G A B"bZ /C} x ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=NTUqMnBVrK4tMb6qIkMjRCBFRiBHIEEgQiJiWiAvQ30geA==&input=IkE0Ig==) ### How it works ``` // Implicit: U = input string, C = 12 U¬® } // Take U, split into chars, and map each item Z by this function: -1¾ // Subtract 1.75 from Z. This produces NaN for non-digits. ª"..."bZ // If the result is falsy (NaN), instead return the index of Z in this string. // C produces 0, D -> 2, E -> 4, F -> 5, G -> 7, A -> 9, B -> 11. // # -> 1, and b -> -1, so we don't need to calculate them separately. /C // Divide the index by 12. x // Sum. 2p // Take 2 to the power of the result. 55* // Multiply by 55. ``` ## Test cases All the valid test cases come through fine. It's the invalid ones where it gets weird... ``` input --> output (program's reasoning) A0 --> 27.5 (Yep, I can do that for you!) C4 --> 261.625565... (Yep, I can do that for you!) F#3 --> 184.997211... (Yep, I can do that for you!) Bb6 --> 1864.6550... (Yep, I can do that for you!) A#6 --> 1864.6550... (Yep, I can do that for you!) A4 --> 440 (Yep, I can do that for you!) D9 --> 9397.27257... (Who says that's too high?) G0 --> 24.49971... (I've heard that note before.) Fb5 --> 659.25511... (Wait, Fb isn't supposed to be a note?) E --> 69.295657... (I'm gonna guess that the missing octave is 1¾.) b2 --> 61.735412... (I assume that b means Cb...) H#4 --> 261.625565... (H# is C!) ``` [Answer] # Pyth, ~~46~~ ~~44~~ ~~43~~ ~~42~~ ~~39~~ 35 bytes ``` *55^2tsm.xsdc-x"C D EF GbA#B"d9 12z ``` [Try it online.](https://pyth.herokuapp.com/?code=*55%5E2%2Btsezc%2B-x%22C%20D%20EF%20G%20A%20B%22hz9-%7D%5C%23z%7D%5Cbz12&input=C4&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=*55%5E2%2Btsezc%2B-x%22C%20D%20EF%20G%20A%20B%22hz9-%7D%5C%23z%7D%5Cbz12&test_suite=1&test_suite_input=A0%0AC4%0AF%233%0ABb6%0AA%236%0AA4&debug=0) The code now uses a similar algorithm to [ETHproductions's Japt answer](https://codegolf.stackexchange.com/a/69761/30164), so credit to him for that. ### Explanation ``` implicit: z = input m z for each character in input: sd try parsing as number .x if that fails: "C D EF GbA#B" string "C D EF GbA#B" x d find index of character in that - 9 subtract 9 c 12 divide by 12 s sum results t decrement ^2 get the correct power of 2 *55 multiply by 55 (frequency of A1) ``` ## Old version (42 bytes, 39 w/ packed string) ``` *55^2+tsezc+-x"C D EF G A B"hz9-}\#z}\bz12 ``` ### Explanation ``` <pre> implicit: z = input GET OFFSET BY NOTE: ."…" string "C@D@EF@G@A@B" packed x hz get index of first char in input - 9 subtract 9 PARSE #/b: + }\#z add 1 if input contains "#" - }\bz subtract 1 if input contains "b" CONVERT OFFSET TO OCTAVES: c 12 divide by 12 FIND OCTAVE IN INPUT: ez last char of input s convert to number GET FINAL RESULT: t decrement the octave + add the octave and the note offset ^2 get the correct power of 2 *55 multiply by 55 (frequency of A1) </pre> ``` [Answer] # Mathematica, 77 bytes ``` 2^((Import[".mid"~Export~Sound@SoundNote@#,"RawData"][[1,3,3,1]]-69)/12)440.& ``` --- **Explanation**: The main idea of this function is to convert the string of note to its relative pitch, and then calculate its frequency. The method I use is export the sound to midi and import the raw data, but I suspect that there is a more elegant way. --- **Test cases**: ``` f=%; (* assign the function above to f *) f["A4"] (* 440. *) f["A5"] (* 880. *) f["C#-1"] (* 8.66196 *) f["Fb4"] (* 329.628 *) f["E4"] (* 329.628 *) f["E"] (* 329.628 *) ``` [Answer] # JavaScript ES7, ~~73~~ ~~70~~ 69 bytes ``` x=>[...x].map(c=>t+=c-1.75||"C#D EF G A B".search(c)/12,t=0)&&2**t*55 ``` Uses the same technique as my [Japt answer](https://codegolf.stackexchange.com/a/69761/42545). [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~56~~ ~~53~~ ~~50~~ 49 48 bytes ``` Hj1)'C D EF G A B'=f22-'#b'"G@m]-s+ 12/G0)U+^55* ``` Uses [current release (10.1.0)](https://github.com/lmendo/MATL/releases/tag/10.1.0), which is earlier than this challenge. [**Try it online**!](http://matl.tryitonline.net/#code=SGoxKSdDIEQgRUYgRyBBIEInPWYyMi0nI2InIkdAbV0tcysgMTIvRzApVSteNTUq&input=QmI2) ### Explanation ``` H % push 2 j1) % get input string. Take first character (note) 'C D EF G A B'=f % find index of note: 1 for C, 3 for D... 22- % subtract 22. This number comes from three parts: % 9; 1 for 0-based indexing; 12 to subtract 1 octave '#b'"G@m]-s % For loop. Gives 1 if input contains '#', -1 if 'b', 0 otherwise + % add to previous number. Space needed to separate from next literal 12/ % divide by 12 G0) % push input and get last character (octave) U+ % convert to number and add to previous number ^ % raise 2 (that was initially pushed) to accumulated number 55* % multiply by 55 (=27.5*2). Implicitly display ``` [Answer] # Ruby, ~~69~~ 65 ``` ->n{2**((n.ord*13/8%12-n.size+(n=~/#/?7:5))/12.0+n[-1].to_i)*55/4} ``` **Ungolfed in test program** ``` f=->n{ 2**( #raise 2 to the power of the following expression: ( n.ord*13/8%12- #note name C..B maps to number 0..11 calculated from the ascii code of n[0] n.size+(n=~/#/?7:5) #Correction for flat: length of n is 1 more for flat (or sharp) than for natural. Then apply correction for sharp #now we have a number 3..14 for C..B (so 12 for A, will be a whole number when divided) )/12.0+ #divide by 12 to convert into a fraction of an octave n[-1].to_i #add the octave number, last character in n )* #end of power expression, now we have A0=2,A1=4,A2=4 etc 55/4 #multiply to get correct frequency, this is shorter than 13.75 or 440/32 } #complete octave test case puts %w{A0 A#0 Bb0 B0 C1 C#1 Db1 D1 D#1 Eb1 E1 F1 F#1 Gb1 G1 G#1 Ab1 A1 A#1}.map{|e|[e,f[e]]} #test case per OP puts %w{A0 C4 F#3 Bb6 A#6}.map{|e|[e,f[e]]} ``` **Output** ``` A0 27.5 A#0 29.13523509488062 Bb0 29.13523509488062 B0 30.867706328507758 C1 32.70319566257483 C#1 34.64782887210901 Db1 34.64782887210901 D1 36.70809598967595 D#1 38.890872965260115 Eb1 38.890872965260115 E1 41.20344461410875 F1 43.653528929125486 F#1 46.2493028389543 Gb1 46.2493028389543 G1 48.999429497718666 G#1 51.91308719749314 Ab1 51.91308719749314 A1 55.0 A#1 58.27047018976123 A0 27.5 C4 261.6255653005986 F#3 184.9972113558172 Bb6 1864.6550460723593 A#6 1864.6550460723593 ``` [Answer] # ES7, 82 bytes ``` s=>55*2**(+s.slice(-1)+("C D EF G A B".search(s[0])+(s[1]<'0')-(s[1]>'9')-21)/12) ``` Returns 130.8127826502993 on input of "B#2" as expected. Edit: Saved 3 bytes thanks to @user81655. [Answer] # C, 123 bytes ``` float d(char*s){int n=*s++,m=(n*12+(n<67?90:6))/7,o=*s++,a=o^35?o^98?0:-1:1;return exp((m+(a?*s++:o)*12+a)/17.3123-37.12);} ``` Usage: ``` #include <stdio.h> #include <math.h> float d(char*s){int n=*s++,m=(n*12+(n<67?90:6))/7,o=*s++,a=o^35?o^98?0:-1:1;return exp((m+(a?*s++:o)*12+a)/17.3123-37.12);} int main() { printf("%f\n", d("A4")); } ``` The calculated value is always about 0.8 cents less than the exact value, because I cut as many digits as possible from the floating-point numbers. Overview of the code: ``` float d(char*s){ int n=*s++, // read the letter m=(n*12+ // multiply by 12/7 to convert from A...G to 0...11 (n<67?90:6) // if A or B, add 1 octave; also add some fix-up rounding value )/7, o=*s++, // read next char: the octave digit or accidental a=o^35?o^98?0:-1:1; // if accidental, convert it into +1 or -1; else 0 return exp((m+ // I adjusted the factors to use exp instead of pow (a?*s++:o) // if was accidental, now read the octave digit *12+a)/ 17.3123- // a more exact value is 17.3123404447 37.12); // a more exact value is 37.1193996632 } ``` [Answer] # R, ~~157~~ ~~150~~ ~~141~~ 136 bytes ``` f=function(x){y=strsplit(x,"")[[1]];55*2^(as.double(y[nchar(x)])-1+(c(10,12,1,3,5,6,8)[LETTERS==y[1]]-switch(y[2],"#"=9,"b"=11,10))/12)} ``` With indent and newlines: ``` f=function(x){ y=strsplit(x,"")[[1]] 55 * 2^(as.double(y[nchar(x)]) - 1 + (c(10,12,1,3,5,6,8)[LETTERS==y[1]] - switch(y[2],"#"=9,"b"=11,10))/12) } ``` Usage: ``` > f("A0") [1] 27.5 > f("C8") [1] 4186.009 > sapply(c("C4","Bb6","A#6","A4"),f) C4 Bb6 A#6 A4 261.6256 1864.6550 1864.6550 440.0000 ``` [Answer] # Python, ~~97~~ 95 bytes ``` def f(n):a,*b,c=n;return 2**(int(c)+('C@D@EF@G@A@B'.find(a)-(21,(22,20)['#'in b])[b>[]])/12)*55 ``` Based on Pietu1998's (and others') old approach of looking for the index of the note in the string `'C@D@EF@G@A@B'` for some blank char or another. I use iterable unpacking to parse the note string without conditionals. I did a little bit of algebra at the end to simplify the conversion expression. Don't know if I can get it shorter without changing my approach. [Answer] # Wolfram Language (Mathematica), 69 bytes ``` ToExpression@("Music`"<>StringReplace[#,{"b"->"flat","#"->"sharp"}])& ``` Using the [music package](http://reference.wolfram.com/language/Music/guide/MusicPackage.html), with which simply entering a note as an expression evaluates to its frequency, like this: ``` In[1]:= Eflat3 Out[1]:= 155.563 ``` To save bytes by avoiding to import the package with `<<Music`, I'm using the fully qualified names: `Music`Eflat3`. However, I still have to replace `b` with `flat` and `#` with `sharp` to match the input format of the question, which I do with a simple `StringReplace`. ]
[Question] [ *This is the cops' thread of a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. The robbers' thread can be found [here](https://codegolf.stackexchange.com/questions/251451/polyglot-quiz-robbers-thread)* In this challenge as a cop you will choose two programming languages **A** and **B**, as well as a non-empty string **S**. You are then going to write 4 programs: 1. A program which outputs exactly **S** when run in both **A** and **B**. 2. A program which outputs **S** in **A** but not in **B**. 3. A program which outputs **S** in **B** but not in **A**. 4. A program which doesn't output **S** in either **A** or **B**. You will then reveal all 4 programs (including which number each program is) and **S**, but keep the languages hidden. Robbers will try to figure out a pair of languages such that they print the correct results for the 4 programs, and cops will try to make posts that are hard to figure out while remaining as short as possible. **Warning: There is a slight difference in the rules from "normal" [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'")** Cops' posts here can have 4 different states: 1. Vulnerable 2. Cracked 3. Safe 4. Revealed All cops' posts start as *vulnerable*. If a robber finds and posts a solution to a *vulnerable* post they will receive 1 point and the post will become *cracked*. If a post lasts 10 days in *vulnerable* without being solved it automatically becomes *safe*. A cop with a *safe* post may choose to reveal **A** and **B** and their *safe* post will become *revealed*. A robber can still solve a *safe* post, if they do they receive a point and the post becomes *revealed*. Only *revealed* posts are eligible for scoring. Robbers are only permitted to solve *vulnerable* and *safe* posts. ## Scoring Cops will be scored on the sum size of all four programs as measured in bytes, with the goal being to have an answer with as low a score as possible. Answers that are not *revealed* effectively have infinite score by this measure until they become *revealed*. ## Languages and Output In the interest of fairness, we are going to require that languages are free and reasonably cross platform. Both languages you choose must be freely available on Linux and FreeBSD (the two largest foss operating systems). This includes languages which are free and open source. Your selected languages must predate this challenge. Since this challenge requires that **A** and **B** produce different outputs for the same program, there is no requirement for what "counts" as a different language, the fact that they produce different outputs is enough. Programs do not have to compile, run without error or "work" in the cases where they do not need to output **S**. As long as **S** is not the output it is valid. Programs here should be complete programs not functions, expressions or snippets. Running a program is assumed to be done with no input. All four programs must be deterministic, within an environment. It is fine for example if as a part of an error the program outputs the name of the file or your host name, this is not considered non-determinism since it is determined by the environment running the program. However if it is included in the output please indicate what the file is named etc. [Answer] # A = [HQ9+](https://esolangs.org/wiki/HQ9%2B), B = [Python 3](https://docs.python.org/3/), 291 bytes, [Cracked](https://codegolf.stackexchange.com/a/251464/107310) **S** is `Hello, world!` 1. Both **A** and **B** work ``` #console.log("Hello, world!")/* print("hello, world!".capitalize()) #*/ ``` 2. **A** only ``` console.log("Hello, world!")/* print("hello, world!") */ ``` 3. **B** only ``` #console.log("Hello, world!")/* print("Hello, world!") #*/ ``` 4. Neither work ``` console.log(String.fromCharCode(49-1)+"ello, world!")/* print(String.fromCharCode(49-1)+"ello, world!") */ ``` GG [Answer] # [A] and [B], 64 Bytes, [Cracked](https://codegolf.stackexchange.com/a/251462/92689) by @Steffan S = "Cop" Both *A* and *B* works ``` main=print"Cop" ``` Works only *A* ``` main=print "Cop" ``` Works only *B* ``` main= print"Cop" ``` None works ``` main=print "Cop" ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) and [yup](https://github.com/ConorOBrien-Foxx/yup/wiki), 8 bytes, [Cracked by *@FryAmTheEggman*](https://codegolf.stackexchange.com/a/251649/52210) \$S\$: `0` 1. Works in \$A\$=05AB1E and \$B\$=yup: ``` 0#? ``` 2. Works in just \$A\$=05AB1E: ``` 0? ``` 3. Works in just \$B\$=yup: ``` 0# ``` 4. Works in neither \$A\$=05AB1E nor \$B\$=yup: ``` 0 ``` --- **Explanation now that it's cracked:** ``` 0#? # 05AB1E: Push 0; pop and split on spaces (no-op that just pops); print # without newline, which implicitly uses the last value that was on the now # empty stack, which is the 0 # yup: Push 0; pop and print it without newline; no-op character '?' 0? # 05AB1E: Push 0; pop and print it without newline # yup: Push 0; no-op character '?', so don't print anything 0# # 05AB1E: Push 0; no-op pop; implicitly output 0 with trailing newline # yup: Push 0; pop and print it without newline 0 # 05AB1E: Push 0; implicitly output 0 with trailing newline # yup: Push 0; don't print anything ``` [Answer] # Hexagony and Labyrinth, 44 bytes, [Cracked](https://codegolf.stackexchange.com/a/251469/78410) by Aiden Chow **S** = `1234` 1. Works in both A and B ``` "123_1234!@ ``` 2. Works in A, but not in B ``` 123+1 234!@ ``` 3. Works in B, but not A ``` 1234@ ;!;!; ``` 4. Does not work in A or B ``` ;!;!; 1234@ ``` [Answer] # ??? and ???, 69 bytes, vulnerable S = `A` 1. Both A and B work: ``` :-%~! v put(97) .% >`a ``` 2. Works in A, but not B: ``` :-%~v! put(a) .% >97 ``` 3. Works in B, but not A: ``` :-%~!< put a. .%^97C ``` 4. Works in neither A or B: ``` put(97) ``` [Answer] # [Glypho](https://web.archive.org/web/20060621185740/http://www4.ncsu.edu/%7Ebcthomp2/glypho.txt) and [Somme](https://github.com/ConorOBrien-Foxx/Somme), 747 bytes, revealed ## Explanation For this approach, I thought it would make sense to choose two languages which cared very little about the actual content of their source codes, and instead cared about some properties the code has. Glypho is a language who cares about the distinct permutations formed by chunks of 4 bytes. It has 15 commands, and is a stack-based language. For example, the string `UU{u` corresponds to the `push` command, since it is equivalent to `aabc` (in terms of uniqueness). Somme is a language which is usually a fairly innocuous stack-based language, but once multiple lines are involved, the columns are summed and converted into a corresponding command. (Addition is performed by treating space, 32, as 0, `!` as 1, etc., then taking the result mod 95.) Hence, the programs consist almost entirely of red herrings. Recall that **S** = `owo!owo!owo!owo!owo!owo!owo!owo!` a string chosen because I thought it was funny. ## Both **[Glypho](https://tio.run/##VY9NSwNBDIbv8yv6theV0g74cXE7mVI8eQjTcRlQbPekHixpDxKKP37N7AoiuQQenrxv3j/Pxw/p@7b9/mJWARGEbVQlb/O2UW0KChvzUqQE1QAHVzk8vANc0qRsAwIt5ot5ZZEi/bqoTEqR0XUYXHh1KOZqGl2iIVfU/XeV/3IHV@G9t7UkPaXKa64IGxONRLHRYK6VVussBUGDji5bZw@Xc04mWyse/wUHBHKzdTfZrJ7v3s6bl7bL@fB0Gy8PXbh@nax2/LC7n9oJTK9ulqfH/cW@738A)** and **[Somme](https://tio.run/##VY9BSwNBDIXv8yv62otKaQfUXtxOphRPHsJ0XAYU273obQlFShB//JrZFURyCXx8eS@f0vfvw9C23xdmFRBB2EZV8iEfGtWmoLAxL0VKUA1wcJXDwzvAJU3KNiDQarlaVhYp0q@LyqQUmVyH0YVXh2KupsklGnNF3X9X@S93dBXee1tL0nOqvOaKsDHRSBQbDeZaabXOUhA06OSydfZwOedksrXi6V9wQCC32HWz/fZl8/G1f227nPvn@3jdd@H2bbY98uPxYW4nML@5W5@fTlenYfgB)** work: ``` UU{uOOwo!??!oOoOowwoSRSR<ww<W!WOOOw0oWoW>ww>! ! owwo!0!0 !! QwQwOwOw!?!?.,.,owwo@?@?<ww<W!W!OwOwoWWo>ww>! !owwo!!0w !W QwwQOwOw!???oOoOoow @?@?<ww<W!W!OwwOoWoW>ww>! !owww!000 !WQwqQOwwO!?!?ooO!owow@??@<w><W!!WOww0ooW!>w>w! !owOo!00! SSSQQwqOwoO!??!oO!O>!>? #A` C=Z6fyC[U`SSmT5@)m`>3] =^OE^;"owO!"*4/qK_(_ ``` This corresponds to the [Glypho (shorthand) program](https://tio.run/##S8@pLMjI1y3OyC8qyUjMS/n/39BQOwUIow1TwHQKEIApbSAw1NVOyU@Bymjn54P4QJ6uthaYBPFjo1MRIPb/fwA) (`[eeeeeeeeeee]` is a loop that never runs): ``` 11+d+d+[1d+d+d+dddd+d+dd++++1-+dod1d+d+d++oo1-+d1d+-+*1d+-+o1-+][eeeeeeeeeee] 11+ stack: 2 d+d+ stack: 8 (loop counter) [ 1-+] loop 8 times 1d+d+d+ stack: LC, 8 dddd stack: LC, 8, 8, 8, 8, 8 +d+dd++++ stack: LC, 8, 112 1-+ stack: LC, 8, 111 do output and keep 'o' d1d+d+d++ stack: LC, 8, 111, 119 oo output 'wo' 1-+ stack: LC, 7 d1d+-+* stack: LC, 35 1d+-+ stack: LC, 33 o output '!' 1-+ stack: LC-1 ``` In Somme, this corresponds to the following program after the columns are summed: ``` F1+7*1-::8+\3B*m,m,m,m,m,m,m,m,0;!fw'@9AH ` F stack: 15 1+ stack: 16 7*1- stack: 111 :: stack: 111, 111, 111 8+\ stack: 111, 119, 111 3B* stack: 111, 119, 111, 33 m, map output (,) over stack m,m,m,m,m,m,m, ...eight times in total 0; exit with exit code 0 !fw'@9AH ` (never executed) ``` ## Only **[Glypho](https://tio.run/##Pc0xDgIxDETRPqew444GFy62WOEj5ABRaiiQDNWI0wcrLGuXo6d/f35ej5izdxvO@are0FCiRBAFIoqSxhjWVdF25h0CcRHPEd2s/5xrA1pJllARBUqkw/7O0wk85XJb35yZ3XNcvQxSUPbSKaUbCmj2OJ24C5YDjt7hRG6nU4rDIXsOSK2CGkBUu9j1PdbN@QU)** works: ``` [[4]?!?!?00?OwOw o oo owoo 0 0o]]4[00wO<!!<w#w#?##?owow[44[?!?!?0?0OwwO oooo 0wo w0 0]44[00wO<!?<w##w?#?#owow[8[8?!!!??0wOwOw oo o o woow0 0 ]44]0ww0<!!!w###??#wowow[ww[?!?!?00wOwOw ##>o o woow00 o]44]0www<!??ww#""#w"owwo"4*4/q]]]]]] ``` This corresponds to the following [Glypho (shorthand) program](https://tio.run/##HYlBCoBADAPfsteGPeQ96kEI2INsRb34@lqWITBkjvO7PPrjcb@@D2VSkGALCWH6yg6rSQrOD4hpVoCIVnVrI/MH): ``` 1d+dd+*[11+d+d+dd+\1-+*1-+dddo1d+d+d++oo1d+d*d*d+1+o!1-+]!n 1d+dd+* stack: 8 [ 1-+] loop 8 times 11+d+d+dd+ stack: LC, 8, 16 \1-+*1-+dd stack: LC, 8, 111, 111, 111 do output and keep 'o' 1d+d+d++ stack: LC, 8, 111, 111, 119 oo output 'wo' 1d+d*d*d+1+ stack: LC, 8, 111, 33 o output '!' ! discard 111 1-+ stack: LC-1 !n discard; no-op ``` And also to the (gibberish) [Somme program](https://tio.run/##Pc0xDgMxCETR3qcA06UJBcUWq3AEH8BymXKFohRzfAc5TqAcPf13XNdzzt5tOOerekNDiRJBFIgoShpjWFdFO5lPCMRFPEd0s/51rg1oJVlCRRQokQ77OU8n8JTLHf1wZnbPcfUySEHZS6eUbiig2eN04i5YDti97UQef6cU2yF7DkitghpAVLvZ/TXWzfkB): ``` u>B-t$?@+@@v)IUnX'PFK;~{k**bj2Q1J02is?F}zRC/)mmU-U-w ``` This errors out immediately because `u` is not a command that exists. ## Only **[Somme](https://tio.run/##K87PzU39/z8zTaGgKDOvREMpv9xfSVOhJCM1z0pBOYxLASbuX56vpMmVmpfCpZxqYK1V52qXklTo6FtVq@1elGhbaRWQmcqVlFpSnpqap5CamJyhkF9aUlBaopCcmJOjo5CSb4UwShFoAQjkRcc4mOVUWykYgM0tSi1ITSxRKCnPTE7liojWSjcycFDKDteoNvHRLQrOVinXM6nVrNOy9ga6FwA)** works: ``` if print("owO") then: #V print("Owo") end #e0;*~E>dbqAMz}+Gra=y:Pie between each output call, do: print("!") n[\@6l{: 0 end repeat twice X[*g20@"kW({4L-rSk$w.4})~*;Ke ``` This corresponds to the following Somme program: ``` F1+7*1-::8+\3B*r`,{`FF+2+*0; F1+7*1-::8+\3B* same as previous r reverse stack `,{` push this string FF+2+ push 32 * execute that string 32 times (once for each character) 0; exit with exit code 0 ``` And to the (gibberish) [Glypho (shorthand) program](https://tio.run/##S8@pLMjI1y3OyC8qyUjMS/n/PxUMtFLhQFcRiFMNgTA6D8SPjYXJ/P8PAA): ``` eeeeee*eeeeeeeeee-!ee-e1e1e[neeee]]eeeeeeee ``` This errors out immediately due to `e` (execute) having no parameters. ## Neither **[A]** nor **[B]** work: Didn't need to spend too much time here, since the answer was probably fine without it. ``` print("owo!"*8) #&7("owo!"-1) ``` Thanks for reading! [Answer] # [Python](https://www.python.org/) and [PARI/GP](https://pari.math.u-bordeaux.fr/), 48 bytes, [Cracked](https://codegolf.stackexchange.com/a/251466/9288) by @Steffan An easy one. **S** is `Cop` 1. Both **A** and **B** work ``` print("Cop") ``` 2. **A** only ``` print('Cop') ``` 3. **B** only ``` print('Cop)' ``` 4. Neither work ``` print("Cop)" ``` [Answer] # ??? and ???, 54 bytes String: `8356830650` Works in A and B (hex): ``` 00000000: 300b 3366 b87e 0b00 247e e239 2a83 2a3b 0.3f.~..$~.9*.*; 00000010: 0fd6 30 ..0 ``` Works in A (hex): ``` 00000000: a4ac b3bb 762b 3a74 d6 ....v+:t. ``` Works in B (hex): ``` 00000000: 300b 01f9 3033 1f0b 3131 5ee2 8891 5ebb 0...03..11^...^. 00000010: 2d88 7661 8976 0bce 0000 0b2b -.va.v.....+ ``` Works in neither: ``` We're no strangers to love You know the rules and so do I (do I) A full commitment's what I'm thinking of You wouldn't get this from any other guy I just wanna tell you how I'm feeling Gotta make you understand Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you We've known each other for so long Your heart's been aching, but you're too shy to say it (say it) Inside, we both know what's been going on (going on) We know the game and we're gonna play it And if you ask me how I'm feeling Don't tell me you're too blind to see Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you (Ooh, give you up) (Ooh, give you up) (Ooh) Never gonna give, never gonna give (give you up) (Ooh) Never gonna give, never gonna give (give you up) We've known each other for so long Your heart's been aching, but you're too shy to say it (to say it) Inside, we both know what's been going on (going on) We know the game and we're gonna play it I just wanna tell you how I'm feeling Gotta make you understand Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you ``` Or the empty program. [Answer] # [A] and [B], 46 bytes, Cracked by @mousetail **S** is `0` 1. Both **A** and **B**, 14 bytes ``` print('0') out ``` 2. **A** but not **B**, 15 bytes ``` print('0') out# ``` 3. **B** but not **A**, 17 bytes ``` print('0',) out # ``` 4. Neither **B** nor **A**, 0 bytes Yeah, I'm not wasting any bytes here `:-)` [Answer] # ??? and ???, 300 bytes S = `A\n` (as in, `A` with a trailing newline) 1. Works in *A* and *B* ``` puts A n = A[ exit ] n = 8 m = n - 1 p = m - n n = 3 * 10 p /= 2 t = p * p ``` 2. Works in *A* but not *B* ``` puts 'A' n = A[ exit ] n = 8 m = n - 1 p = m - n n = 3 * 10 p /= 2 t = p * p ``` 3. Works in *B* but not *A*. ``` puts A n = A[exit] n = 8 m = n - 1 p = m - n n = 3 * 10 p /= 2 t = p * p ``` 4. Works in neither *A* nor *B* ``` n = A[ exit ] puts A n = 8 m = n - 1 p = m - n n = 3 * 10 p /= 2 t = p * p ``` [Answer] # [A] and [B], ACTUALLY 3 BYTES!!!, [Cracked](https://codegolf.stackexchange.com/questions/251451/polyglot-quiz-robbers-thread/251487#251487) **S** is `0` * Both, 0 bytes: * Only **A**, 1 byte: ``` ! ``` * Only **B**, 1 byte: ``` r ``` * Neither, 1 byte: ``` " ``` [Answer] # [Lightlang](https://esolangs.org/wiki/Lightlang) and [PDAsephone](https://esolangs.org/wiki/PDAsephone), 141 bytes, revealed ## Explanation My thought process for this approach was to choose two obscure esolangs with interpreters not on TIO. Since there are no interpreters online available, I recommend you download [`lightlang.py`](https://github.com/bangyen/esolangs/blob/master/register-based/lightlang.py) and [`PDASephone.java`](https://esolangs.org/wiki/Talk:PDAsephone). My strategy with this one was further devious. If you were hurriedly scanning through esolangs, and found this language, the program will not complete immediately. The `_` command in Lightlang sleeps for one second, meaning the program takes about 13 seconds to complete. Lightlang is a curious language which only has 1 bit of memory, whose implementation clocks in at 35 sloc. My solutions use the "interesting" parts of the language, bouncing, jumping, and conditional skipping, to produce varied output. The program otherwise is just a garden path through toggling a bit on and off and printing it occasionally. PDAsephone is a language with a PDA (push-down automaton) datatype. Unfortunately, I didn't want to spend bytes (or mental energy) getting a non-trivial PDA functional in the language, especially when the other language is so simple that it would be hard to replicate any meaningfully complex behavior implemented in PDAsephone. Hence, I use it just for its stack-based capabilities, and most of the work done is to make it play nice with Lightlang. **S** = `0110100` Both **Lightlang** and **PDAsephone** work: ``` __@;"1_&^"0^!^!.$$:.__/!^#&!^&$$:."0:v..^:..___ ``` Only **Lightlang** works: ``` [*)`!$]^|>,=+!+/#(]+|!!-+)$'%)}|^!]>*].==`^{;"| ``` Only **PDAsephone** works: ``` '**"0-'})'"1=/:+?.`/:~'{++:.>.'+*/(:./:-./::'.. ``` Neither **Lightlang** nor **PDAsephone** work: (the empty program) Thanks for reading! [Answer] # ??? and ???, 43 bytes, safe output: `2147483647` | | | | --- | --- | | both | `-print /*"\r"%S #*/|2**31-1` | | only A | `-print %S` | | only B | `2**31-1` | | neither | | hint: none of the languages are esoteric or recreational, both are practical and one of them is even quite popular, the other one is free open source but not available on any service like TIO, it's a script for a domain-specific tool [Answer] # ??? and ???, 406 bytes, [cracked by Conor O'Brian](https://codegolf.stackexchange.com/a/251507/91213) S=`2` Both A and B: ``` # print("22222222222") // !\print("22222222222")# 2 \\ ("11111111111")<<n ;;;;;;;;;;;;;;;;;;;;;;;;; ``` ## A but not B: ``` # print("11111111110") // !\print("11111111110")# 2 \\ ("11111111110")<<n ;;;;;;;;;;;;;;;;;;;;;;;;; ``` ## B but not A: ``` print("22222222222") // !\print("22222222222")# 2 \\ ("11111111111")<<n ;;;;;;;;;;;;;;;;;;;;;;;;; ``` ## Neither A nor B: ``` # print("11111111111") // !\print("11111111111")# 1 \\\ ("11111111111")>>n ;;;;;;;;;;;;;;;;;;;;;;;;; ``` [Answer] # Pyth and V, 11 bytes, [Cracked](https://codegolf.stackexchange.com/questions/251451/polyglot-quiz-robbers-thread/251500#251500) by @Steffan S = `3` Both: ``` l"aa3 ``` Only A: ``` 3 ``` Only B: ``` dl3P1é3 ``` None: (empty) ]
[Question] [ In this challenge you will be given a list of positive integers which represents some range of integers which has been truncated for display. Your job is to find the missing bits and insert ellipses to show that that part has been truncated. The input will always be strictly ascending and if two consecutive values differ by more than 1 then we know some data has been removed in between them. For example if the input is: ``` 1,2,3,4,20,21,22 ``` Then since `4` and `20` differ by more than 1 we insert an ellipsis between them: ``` 1,2,3,4,...,20,21,22 ``` However if the consecutive values differ by *exactly two*, then we just reinsert the missing value (their mean), since an ellipsis doesn't actually save any space when it's just covering 1 value. So for example if the input is: ``` 1,2,3,5,6 ``` Then `3` and `5` differ by more than 1 so data has been removed between them, but they differ by 2 so we just insert the missing `4`. ``` 1,2,3,4,5,6 ``` Additionally if the first value is greater than `1` we know that something has been truncated off the front. So we add an ellipsis, or if the first value is `2`, a `1` as the first value. We can't know that something has been truncated off the end so we never add anything there. ## Task Given a list of positive strictly-ascending integers as input output the list with the proper insertions. You can represent ellipses in the output as any constant value other than a positive integer. For the convenience of strongly typed programming, you may also output a list of optional values with the null value representing ellipses. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes. ## Test cases ``` [1,2,3,4,20,21,22] -> [1,2,3,4,...,20,21,22] [1,2,3,5,6] -> [1,2,3,4,5,6] [2,3,4,9] -> [1,2,3,4,...,9] [3,5,7,8,10] -> [...,3,4,5,6,7,8,9,10] [1,20,23] -> [1,...,20,...,23] ``` [Answer] # JavaScript (ES10), ~~45~~ 43 bytes Uses `undefined` for ellipses. ``` a=>a.map(p=v=>[[[],v-1][v+~p],p=v]).flat(2) ``` [Try it online!](https://tio.run/##bY3LDsIgEEX3fgnEKSlTnwv6I5NZTGoxGizENiz9dcS4ZXdzz308Jcs6vR9p65Z4m4t3Rdwo5iVJJZfdSEQMubNMef9JDNVkbXyQTaEuU1zWGGYT4l15RRYQBjgA9oBVI2u9a0aOcGqwf/naIL/GGS5g@/Zk/RsqKV8 "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array, e.g. [ 1, 3, 6 ] a.map(p = // initialize p to a zero'ish value v => // for each value v in a[]: [ // build an array: [ // according to v - p - 1, append: [], // an empty array if it's 0 v - 1 // v - 1 if it's 1 // implicitly: undefined for anything else ][v + ~p], // p = v // append v and update p to v ] // end of array ) // end of map(); this gives: // [ [ [], 1 ], [ 2, 3 ], [ undefined, 6 ] ] .flat(2) // apply .flat() at depth 2 to clean this up: // [ 1, 2, 3, undefined, 6 ] ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 24 bytes ``` ,/0{((0;();x-1)x-y),x}': ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs9LRN6jW0DCw1tC0rtA11KzQrdTUqahVt+LiSlMwVDBSMFYwUTAyUDACso3gQqYKZkA2RNISyAKJmCtYKBgaQJQA1RsDAHV1EeY=) Uses `0N` for ellipses. ## Explanation * `0{...}':` pairwise map with placeholder 0 (*y* is prev elem, *x* is next elem)... + `(0;();x-1)x-y` get elem of list `(0;();x-1)` at index *x* - *y* + `,x` append *x* * `,/` flatten [Answer] # [R](https://www.r-project.org), ~~69~~ 68 bytes *Edit: -1 byte thanks to pajonk* ``` \(x){F[i<-cumsum(2-!(j=diff(c(0,x))-1))]=x;F[-i]=(x*(j<2))[j>0]-1;F} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHaxJSUkozUpJzEvOxi26WlJWm6FjddYjQqNKvdojNtdJNLc4tLczWMdBU1smxTMtPSNJI1DHQqNDV1DTU1Y20rrN2idTNjbTUqtDSybIw0NaOz7AxidQ2t3WohZt1iZES2AajbUMdIx1jHRMfIQMcIyAbqUVBW0LVTiIZJ6OnpwSVjubDqNtUxw9AGFMNQDZGxxGqFJYZqkLnmOhY6hgZwDSCFUMPBUpZASWxuAjrXGMkWqBfAlHEsJCQWLIDQAA) Uses `-1` as the ellipsis character. **How?** ``` j=diff(c(0,x))-1 # get the differences between adjacent elements -1 !j # zero for consecutive integers, 1 otherwise i=cumsum(2-!j) # indices of original elements, leaving gaps for ellipses or new elements-in-gaps F[i]=x # fill-in the elements into vector F F[-i]= # fill-in the gaps with... (x...)[j>0]-1 # one less than the subsequent original value... *(j<2) # ...adjusted to zero if the gap was >2 F # finally, return F ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ ~~19~~ ~~17~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0šüŸε¦¤®s‚‚éн}˜ ``` Uses `-1` for ellipsis, but could alternatively use another 1-byte alternative (e.g. `0`, `""`, `" "`, `"\n"`, `"abcdefghijklmnopqrstuvwxyz"`, etc.) by replacing the `®`. -3 bytes porting [*@MamaFunRoll*'s K (ngn/k) answer](https://codegolf.stackexchange.com/a/249628/52210) -2 bytes porting [*@DominicVanEssen*'s Husk answer](https://codegolf.stackexchange.com/a/249636/52210) -2 bytes thanks to *@CommandMaster* with yet another different approach [Try it online](https://tio.run/##yy9OTMpM/f/f4OjCw3uO7ji39dCyQ0sOrSt@1DALiA6vvLC39vSc//@jjXSMdUx1LHUMjWMB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/g6MLD@85uuPc1kPLDi05tK74UcMsIDq88sLe2tNz/uv8j4421DHSMdYx0TEy0DECso1idaBCpjpmQDZE0hLIAomY61joGBpAlADVG0MVmOpY6hiCOEC5WAA). **Explanation:** ``` # Example input: [2,3,5,9,13] 0š # Prepend a 0 to the (implicit) input-list # STACK: [0,2,3,5,9,13] ü # For each overlapping pair {a,b}: Ÿ # Push a list in the range [a,b] # STACK: [[0,1,2],[2,3],[3,4,5],[5,6,7,8,9],[9,10,11,12,13]] ε # Map over each inner list: # STACK1: [0,1,2] ; STACK2: [5,6,7,8,9] ¦ # Remove the first item # STACK1: [1,2] ; STACK2: [6,7,8,9] ¤ # Push the last item (without popping the list) # STACK1: [1,2],2 ; STACK2: [6,7,8,9],9 ® # Push -1, the ellipsis value # STACK1: [1,2],2,-1 ; STACK2: [6,7,8,9],9,-1 s # Swap the top two values on the stack # STACK1: [1,2],-1,2 ; STACK2: [6,7,8,9],-1,9 ‚ # Pair them together # STACK1: [1,2],[-1,2] ; STACK2: [6,7,8,9],[-1,9] ‚ # Pair the two lists together # STACK1: [[1,2],[-1,2]] ; STACK2: [[6,7,8,9],[-1,9]] é # Sort by length (shortest to longest) # STACK1: [[1,2],[-1,2]] ; STACK2: [[-1,9],[6,7,8,9]] н # Pop and leave the first inner list # STACK1: [1,2] ; STACK2: [-1,9] } # After the map # STACK: [[1,2],[3],[4,5],[-1,9],[-1,13]] ˜ # Flatten the resulting list of lists # STACK: [1,2,3,4,5,-1,9,-1,13] # (after which the result is output implicitly) ``` [Answer] # [Python 3](https://docs.python.org/3/), 62 bytes ``` lambda a:sum([[~-i*(i-2in[0]+a),i][i-1in[0]+a:]for i in a],[]) ``` [Try it online!](https://tio.run/##bY7PDoIwDMbvPsUSL5t2BDb/QeKTzB5mDLGJDIJ48OKrT4YLKPHU9vt@/drm2V1rp315PPmbrc4Xy2xxf1TcmJekFSepyJkU11YAoSGZxbHAsm4ZMXLMIhgUvmnJdbzkJgMFGjagUlB9r1AItmSjnCTJZC1mW1vYzfCgTNRHy/9E5l9UyNnDAbI0ggGIYYORB@vndv@QHlPji0PR6N8 "Python 3 – Try It Online") Use `0` for ellipses. For each value `i` in input: * If `i - 1` is already included in input, or `i - 1` is `0`, we need insert nothing before it; * Otherwise, if `i - 2` is already included in input, or `i - 2` is `0`, we need insert `i - 1` before it; * Otherwise, we insert `...` before it. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes ``` ##&[Pick[#>p+2||++p,p<#],p=#]&/@(p=0;#)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lZLTogMzk7WtmuQNuopkZbu0CnwEY5VqfAVjlWTd9Bo8DWwFpZU@1/QFFmXkm0sq5dmgNQoi44OTGvrpqr2lDHSMdYx0THyEDHCMg2qtWBiZnqmIE4EGlLEBMkZq5joWNoAFUF1GNcy1X7HwA "Wolfram Language (Mathematica) – Try It Online") Represents ellipses by `True`. ``` ##&[Pick[#>p+2||++p,p<#],p=#]&/@(p=0;#)& p=0 starting from 0, /@( ;#) for each element: #>p+2 True if current-previous>2, ||++p otherwise previous+1, Pick[ ,p<#] but omit if =current ##&[ ,p=#] prepend and update previous ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 bytes ``` ŻṖ‘ż¹FQµIỊa ``` [Try it online!](https://tio.run/##y0rNyan8///o7oc7pz1qmHF0z6GdboGHtno@3N2V@P9w@9FJD3fO0Iz8/z/aUMdIx1jHRMfIQMcIyDaK1YEKmeqYAdkQSUsgCyRirmOhY2gAUQJUbxwLAA "Jelly – Try It Online") `0` for ellipses. ``` Ż Prepend a 0, Ṗ trim the last element, ‘ increment, ż¹F flat-interleave with the original input, Q and uniquify. µ a Zero out any elements of the result which I have a difference with the next element Ị greater than 1. ``` [Answer] # [Haskell](https://www.haskell.org), 69 bytes ``` g x y|x+1==y=[y]|x+2==y=[x+1,y]|True=[0,y] f a=concat$zipWith g(0:a)a ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZBNbsIwEIXVRTc-xSxYEDFIjmkhQfKSExSJRZSFlZLEgvwocQSpehM2bFDPVE7DJKnbdOX3vXl-Gs3lK1X1YX88Xq-3xsRz73uTwBnaz_PMlbKVQRuSFL0kCwm3VbOXASfJYlAyKvJImcmHLnfapJBM-Vo5aii7Pz0bkBAwAJgGLgpc4AsKjoK0CBF-Pf7nOjiOv-JynOvQBgbH_1_jj_9T5WIY9_092nFXvUIPXd4luG3vPb9znZAxTdtnqoS4NmBY8UN1_k7EKjsEzVimdE5cNubNVDCBOi1O9FBGQjFcw574AQ) [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 50 bytes ``` a->b=0;concat([if(c-b<3,[b+1..b=c],[x,b=c])|c<-a]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY1dCsIwEISvEvqU4KY0qT8Vm14kBNkEUgqlhlJBwZv4UhDxTN7GhNanmfl2h3l-Ao7duQ3zyxP1vk6eV1-JvLGqOLnL4HCiuvPUcVuXoO1G5LlVzoC-QVL2cDVHw9ZmiyH0d4qENySM3TBFm6WQEU-RMSBaC5BQwhZkATJ6aSJc2A72KSznY7KJHaACUaxfsVOa_9w8L_oD) Use `x` for ellipses. [Answer] # [Perl 5](https://www.perl.org/) + `-p -M5.10.0`, 35 bytes If using a `0` is acceptable this would be 31 bytes, but that feels a bit cheaty... ``` $;=$_*say$--1?"...":$_-1if$-=$_-1-$ ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJDs9JF8qc2F5JC0tMT9cIi4uLlwiOiRfLTFpZiQtPSRfLTEtJCIsImFyZ3MiOiItcFxuLU01LjEwLjAiLCJpbnB1dCI6IjNcbjVcbjdcbjlcbjEwIn0=) [Answer] # [Python 2](https://docs.python.org/2/), 57 bytes ``` p=1 for n in input(): if p<n:print-~p/n*p print n;p=n+1 ``` [Try it online!](https://tio.run/##RYzLCsIwEEX3@YpLVz5GbFKf0X6JdCUpDZTpUCLqxl@PSRWFGZhzHyPP0A1s4r3zvYO27uGuRVFEqbVqhxEMn0duYTa3Cr6FnNnK6DmsXrLmhShMBD5JzUsdJ1L5x0UTDKEibNJRps2CadTf2BJ2iX@pY4KPvCccCLr8pnO7at4 "Python 2 – Try It Online") A program that takes in a list on STDIN and prints the output values on separate lines. [Answer] # [J](http://jsoftware.com/), 34 31 bytes ``` 0(}.(+_*_1>])2-/\])@~.@,<:,@,.] ``` [Try it online!](https://tio.run/##Vcw9DsIwDAXgvaewWJrAq0lSfqNSRSAxIQZmog6ICrFwgvbqIS0UlcGS/fzZzzDhtKadpZRAimysjOlwOR2DEg2LWTWtdOmlyeZXL13LDoWFA/sgk/OeSTXWNeyE6KguvFRoTdb@dKSllQ6@118VTcOyZxpjmCT32@NFNWkY5FjAKJjYm/98idUQfNh2GLvdGhtoNbqIP/LwBg "J – Try It Online") This was surprisingly difficult to golf in J and the K approach ended up being longer than either of these. ## Idea We take a two pass strategy: * First we insert the numbers below each number. * Then we check if there are any gaps greater than 1. If so, we replace those gaps with infinity `_`. ## How Consider `2 3 4 9`: * `<:...,.]` Decrement zipped with original input: ``` 1 2 2 3 3 4 8 9 ``` * `0...~.@,...,@` Flatten, prepend 0, and take the unique: ``` 0 1 2 3 4 8 9 ``` * `}.(...)2-/\]` On the left hand side, kill the 0, on the right hand side take consecutive deltas: ``` 1 2 3 4 8 9 (...) _1 _1 _1 _1 _4 _1 ``` * `_*_1>]` Turn every entry less than \_1 on the right into infinity: ``` 0 0 0 0 _ 0 ``` * `+` And add that to the left side: ``` 1 2 3 4 _ 9 ``` ## [J](http://jsoftware.com/), first approach, 34 bytes ``` [:;]<@~.@,~"+]+_3>.@%@+3<.2-~/\0,] ``` [Try it online!](https://tio.run/##bY1LCsIwEED3nmIoaBMzjenEb40SFFyJC7c1RBCLuPEGvXpMLYUWXAzze/PmHRKZVrArIAUEBUWMTMLxej6Fstg6Y2tpsU6EE17vpR1boY2krJ7dFLrAR5eDBMdEQ5U8@Qf9EHNnJup4TNZzK5nP@0zrGT7MIkJM@ClNDLedbPR8vD5QQY6EGudICinWNJwvcNkNWmzTtc1uhWvMVe8iOnT4Ag "J – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes ``` Gɾ‡?cḊƛḢ[h?c∧;f ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBUCIsIiIsIkfJvuKAoT9j4biKxpvhuKJbaD9j4oinO2YiLCIiLCJbMSwyLDMsNCwyMCwyMSwyMl1cblsxLDIsMyw1LDZdXG5bMiwzLDQsOV1cblszLDUsNyw4LDEwXVxuWzEsMjAsMjNdIl0=) Uses `0` for ellpisis. [Answer] # [Brainfuck](https://github.com/TryItOnline/brainfuck), 71 bytes ``` ,[[->+>+<<]>>[-<<+>>]<<<[->-<]+>-[-[<<.>-]<[>>-.+<<-<]>]<[-<]>>[-]>.>,] ``` [Ungolfed program](https://ato.pxeger.com/run?1=ZZExbsMwDEXRlaf4YwJFNuKpA6GLGB7cREaMNrIhyajTubfokqVDr9TTlLbspEUBQRLFx0-K_Ph68nXrmuHwfL1-DrHRj98P77QjKonyPEeItY8BnUM8WTj7isOp9uLWRhnFXJExYjArYypi5smj5ZkMEZe6UvMuFPRYEtoGR7QBrovYEyEh80FYoT9Ugc09QnaPYisIcya4VNj71kW8Wd_Jq6yRdcWE0vzSKeRudKYY-S1iRP8yBJHciOQF59ZN1jYpcCXfokne22Ajoj334V-1QtCSb0q3ZtsT-jqExZmkpggy2b3gi5i71GPrjnOHb90VlNIwlpmss_kB) (a port of my Haskell solution) [Script to test it](https://ato.pxeger.com/run?1=lVJLTsQwDJXYkVMYhmVauUm_A-qGY6BZdPphKkRThVaaBcdgx2YWcClOg5O0DIgpEl448Xt-tmPl9W1bPO0Oh_dxaLz04-xlBXcBF1zykAvkgu5iA15-RH3fPzLsKz3i8c88AxjaRdnvIpmljTLhKQ_QZRhmkls8M8zUhrrKuc40hj3khrFGaWi7fhzIAwYoUGIoUARCzGGEMTgcM7BxgikWRFOevIZKsfO63Cm4coWeYb-vwNPg9XS_2eqi7ZqxfPDabqh1r2vy-Xe81-peF4-5U7JKdTWj0W-V1nU5gBoHKrsGgnCytZ3NDBMSJhDsvCfNNwYXl0tq87pls2p_sTMt5H9aRAm0xwgwxgRojbTRYlF7ojU9FY2TfzQ2cvBXzH3O6Y_Of_UT) [Answer] # [Rust](https://www.rust-lang.org), ~~135~~ 130 bytes *-5 bytes thanks to @alpehalpha* ``` |v:Vec<i8>|v.iter().scan(0,|c,&a|Some((match a-*c{1=>vec![a],2=>vec![a-1,a],_=>vec![-1,a]},*c=a).0)).flatten().collect::<Vec<_>>() ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVFLTsMwEBXbnmLaBbKraZSkfNq0CYdAYoOiyDJOieQ6VeJGSEk2XINNkeAC3AZOg5OUUGhnYc_4vTdvbL-8Zdtc7z5iBWuWKEKhlELDCvz3rY4ns8_nqvDuBF8ms6AqrESLjFAr50wRGyuO56y6TdeCkDXT_BHYZMxLxw8KwYf3LET3J504aMpoX7ZVjWPuM2rZlFqxZFoLY2_xVErBtectG9coCAjtJvk6e10MBmAiTjMgWuQ64iwXCOJpYxTiISqY3AoKiYLWpSU3QdrSQReneIGuja7J3RAQ_gBmqh6jeFJ9iVdHsubsiN5B81Me82N20_gaZ-jYvcAQ981bZN5gp4YyA08PXLo7NOs0pC07hLJXbbJEaamGZFR6N_UIYfX7jhaXqRKEUrro-SzPRaaH5IBGwff_v3gnqAd191O7Xbd_Aw) [Answer] # [Husk](https://github.com/barbuz/Husk), ~~16~~ 14 bytes *Edit: -2 bytes by stealing [Kevin Cruijssen's improvements](https://codegolf.stackexchange.com/a/249629/95126) in his port of this!* ``` ΣẊö◄LSeoe0→t…Θ ``` [Try it online!](https://tio.run/##ATIAzf9odXNr///Oo@G6isO24peETFNlb2Uw4oaSdOKAps6Y////WzIsMyw0LDE4LDE5LDIwXQ "Husk – Try It Online") Uses `0` for ellipsis; could use any other integer by exchanging the `0` at position 10 in the code. ``` Θ # add a zero at the start of the list; Ẋȯ # now, for every pair of elements: … # fill gaps with numeric ranges, t # and discard the first element, Se # then make a 2-element list of this and oe0→ # just the last element preceded by zero, ◄L # and select the element with minimum length; Σ # finally, flatten the resulting list-of-lists. ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~76~~ 71 bytes ``` p;f(*a,n){for(p=0;n--;)printf("%d %d "+(++p==*a)*3,p+1<*a?0:p,p=*a++);} ``` [Try it online!](https://tio.run/##hVTRbqMwEHzvV1hIlTAYldjQXuJyfaj6FSU6IWJ6qI2DAtJFF/HrRx1sbMe1riiJzc7s7uxu7DqpPyr@Nk0dbcKoQhyem8Mx7IqU8iShsDu2fGjC4HYHxCeIwzjuiiKqYERQF68eo@op3XSoE6Y4hnScBB3sq5aHEJxvgHguhoH1w6/V6xYU4LxCGBGUIZwiLPZ4pIaCbUqO7m2MSEw6r20kk8jF4wH9QKvUBnMdUuQjI100RTPcS1TqQ0qEWolaM7XmxlkauHTu27/s0IQyBrxTr5F6R8DGsYNjBycOThw8c/DMwXMHz6Elmp06Vg9s504idWehifiaaCaiGcQNtXYZajrpEmGe0dpMSRP1pGY97rQWmiSZUpCl1toTa59Z@9zXj@tBmtimmZZNN9zk9fCwh0c8POLhZR5e5uHlHp4eeH3g/QDq39UxEr@sfmdHWWVQnl5weVo/i28eIGC/k0B5izsAhJcetXzHTsItpWr76Mr4KgJSEMczG87B5D1gzp0IJ8/ezNlSGwZcoWIoPriftWiT0ak0Cn18Tg815/L0caFvsv52J8punwIQbAKxG17bLTQhFx5IfoLAsosThgCH9LoYJvLqv6ZP8N4ieGpaspX8RZE211k9BfYgAfeeIrXy7wLs/@P8pT3M356Sl3zJM96M07@6@aje@in58wk "C (clang) – Try It Online") *Saved 5 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!!* Inputs a pointer to an array of positive integers and its length (because pointers in C carry no length info). Prints out the filled in array using \$0\$ for ellipses. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~50~~ 45 bytes ``` ->l{a=0;l.map{|x|p x-a<2?a:0if x>a+=1;p a=x}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOtHWwDpHLzexoLqmoqZAoUI30cbIPtHKIDNNocIuUdvW0LpAIdG2orb2P1dadLShjpGOsY6pjpmOZWwsV4GCujpI1AiJbRwb@x8A "Ruby – Try It Online") Thanks Jonah for -2 bytes and a different approach which saved 3 more bytes. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 44 bytes ``` {d=$0-a;if(d>1)print d==2?$0-1:0;print a=$0} ``` [Try it online!](https://tio.run/##SyzP/v@/OsVWxUA30TozTSPFzlCzoCgzr0QhxdbWyB4obGhlYA0RSQSqqv3/35jLlMuMy5LL0IDL0IjL0JjLyOBffkFJZn5e8X/dskRbAwA "AWK – Try It Online") *Thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) for pointing out that 5 bytes needed to initialize the variable `a` on TIO aren't needed on GNU awk, and so shouldn't count in the score.* Outputs 0 for `...`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 17 bytes *Inspired by Arnauld's [JavaScript answer](https://codegolf.stackexchange.com/a/249624/65425)* ``` .n,Le<[YtdG)aZ=Zd ``` [Try it online!](https://tio.run/##K6gsyfj/Xy9PxyfVJjqyJMVdMzHKNirl//9oQx0jHRMdIwMdIyDLKBYA "Pyth – Try It Online") or [Try all test cases](https://tio.run/##K6gsyfivbBtl8F8vT8cn1SY6siTFXTMxyjYqJVDB1vX//2hDHSMdYx0THSMDHSMg2yiWCypkqmMGZEMkLYEskIi5joWOoQFECVC9cSwA "Pyth – Try It Online") Uses the lowercase alphabet as the ellipsis (could alternatively use `0` or empty string). ``` .n,Le<[YtdG)aZ=Zd Implicitly initialize Z to 0 L Left map over the input with variable d [ ) 3-element list of... Y ... the empty list td ... (d - 1) G ... the lowercase alphabet < Keep the first N elements of that list, where... aZd ... N = the absolute difference of Z and d =Zd (Set Z to d) e Take the last element of the resulting list , Create a two-element list of (result, current element) .n Flatten ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 73 bytes ``` \d+ $* ^ , (^|\b1+),(?=11\1\b) $&1$1, (^|\b1+),(?=11\1) $&..., ^, 1+ $.& ``` [Try it online!](https://tio.run/##Zcw9DoMwFAPg3edIUSBWhAP9G6qOXCKKKCoDS4eqY@@eJmLs9uzPeu/1s70e@WCnOceng@mQQNj0jYtcS3u/SVFxaWEaGf1TBe89kQiofPBNzmLgwJGhZyh3wF4cecIOV9R05oXqK5bd8AM "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+ $* ``` Convert to unary. ``` ^ , ``` Prefix `0` (in unary). ``` (^|\b1+),(?=11\1\b) $&1$1, ``` Where two consecutive integers differ by `2`, insert the missing integer. ``` (^|\b1+),(?=11\1) $&..., ``` Where two consecutive integers differ by more than `1`, insert an ellipsis. ``` ^, ``` Remove the leading `0`. ``` 1+ $.& ``` Convert to decimal. [Answer] # [R](https://www.r-project.org), 75 bytes ``` \(x,y=c(0,x))for(i in x-1){if(!i%in%y)show(`if`((i-1)%in%y,i,0));show(i+1)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3vWM0KnQqbZM1DHQqNDXT8os0MhUy8xQqdA01qzPTNBQzVTPzVCs1izPyyzUSMtMSNDQygVJgQZ1MHQNNTWuwVKa2oWYt1MjvaRrJGoY6RjrGOiY6RgY6RkC2EVBhcmKJhlJMnpKmsoKunUI0TIWenh5cVSwXQq-pjhluTUBJiFoI1xK_8ZYQtSAzzXUsdAwNMJWDlEENBquxBKqCuwboOmNsNkCdDqaMYyHeX7AAQgMA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` IE⊕Φ⌈θ№⁺θ⊖θ⊕ι∧№⊞O⁺θ⊕θ¹ιι ``` [Try it online!](https://tio.run/##TYzNCsIwEIRfpccNrGARUfAkFcGD2HvpIaQLDeSn3STi28dYRDswl5n5Ro2SlZcm55a1i9DIEOEuJ7g5xWTJRRrgqk0kLvFL22RhFlg1PpV1a1KAGasL/cezKPWa1kJ8orMb4EulMD4mYhk9/y7WxHJRF@vFRaecu26HezzgEett3@fN07wB "Charcoal – Try It Online") Link is to verbose version of code. Uses `0` to represent an ellipsis. Explanation: ``` θ Input array ⌈ Maximum Φ Filter on implicit 0-indexed range θ Input array ⁺ Concatenated with θ Input array ⊖ Vectorised decrement № Contains ι 0-indexed value ⊕ Incremented (i.e. 1-indexed) ⊕ Incremented (back to 1-indexed values) E Map over values θ Input array ⁺ Concatenated with θ Input array ⊕ Vectorised increment ⊞O Concatenated with ¹ Literal integer `1` № Contains ι Current value ∧ Logical And ι Current value I Cast to string Implicitly print ``` ]
[Question] [ Create a function which given a number of lines `n`, makes a `bigA`. * The horizontal bar of `bigA` must be at the middle row, or the lower of the two if `n` is even * Assume a monospace font for output Output should be a string (or similar, eg character array) with clear linebreaks to break up the lines, and with correct whitespace for left-padding (you can assume \t to be 4 spaces). There can be any whitespace on the right. ## Examples ### n = 1 `A` ### n = 2 ``` A AAA ``` ### n = 3 ``` A AAA A A ``` ### n = 4 ``` A A A AAAAA A A ``` ### n = 5 ``` A A A AAAAA A A A A ``` This is inspired by [Create an "H" from smaller "H"s](https://codegolf.stackexchange.com/questions/157664/create-an-h-from-smaller-hs) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ### Code: ``` Ð;î¹)'A1376SΛ ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//8ATrw@sO7dRUdzQ0NjcLPjf7/39zAA "05AB1E – Try It Online") ### Explanation: ``` Ð # Triplicate the input. ;î # Compute ceiling(n / 2). ¹ # Push the first input again. ) # Wrap into an array. For input 7, this would result in: [7, 7, 4, 7]. 'A # Push the character 'A' 1376S # Push the array [1, 3, 7, 6]. These are the directions of the canvas. This essentially translates to [↗, ↘, ↖, ←]. Λ # Write to canvas using the previous three parameters. ``` ### Canvas I should probably document the canvas a little bit more (and a lot of other functions), but this basically sums it up. The canvas has different 'modes' based on the parameter types given. The canvas command has three parameters: **<length> <string> <direction>**. Since the length and direction parameters are lists, it 'zips' these lists to create a set of instructions to be executed. The string parameter is just the letter **A**, so this is the fill character used by all instructions. The canvas interprets this as the following set of instructions (for input 7): * Draw a line of length **7** with the string **A** in direction **↗** * Draw a line of length **7** with the string **A** in direction **↘** * Draw a line of length **4** with the string **A** in direction **↖** * Draw a line of length **7** with the string **A** in direction **←** The directions are translated in the following manner: ``` 7 0 1 ↖ ↑ ↗ 6 ← X → 2 ↙ ↓ ↘ 5 4 3 ``` If nothing has been outputted, 05AB1E automatically outputs the canvas result. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~17~~ 15 bytes ``` NθP×θAM⊘θ↗P^×θA ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05rLtzSnJLOgKDOvRCMkMze1WKNQR0HJUUkTJJVflqrhkZhTlpoCVKqjYBVaEJSZnlGCqssqTkcBTef//yb/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` P×θA ``` Print the horizontal bar of the big `A`. (For even numbers, the `n+1`th overlaps the right side anyway.) ``` M⊘θ↗ ``` Move to the top of the big `A`. ``` P^×θA ``` Print both sides of the big `A`. [Answer] # [Python 2](https://docs.python.org/2/), 80 bytes ``` lambda n:'\n'.join(' '*(n+~i)+('A'+' A'[i==n/2]*n*2)[:i*2]+'A'for i in range(n)) ``` [Try it online!](https://tio.run/##XcoxDsIwDEbhq3iznSCgGSNl6DnaDkEQMII/VdSFhauHzqzve@tne1SEXtLcX/l9uWZC5Bl8fFaDMLET@K@pFx7ZM408WUo4hcXBBZ2iubD43UptZGSglnG/CVT7XxoOw1nj2gybFLF9@AE "Python 2 – Try It Online") Divide the desired output into the left whitespace, left `A` plus middle whitespace or `A`s, and the right `A`. Compute the middle part using slicing on a fixed string. This allows to use the same way to generate the first line. [Answer] # [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ┴3╬*ôP^x'┌_╓J²♫ ``` [Run and debug it](https://staxlang.xyz/#p=c133ce2a93505e7827da5fd64afd0e&i=1%0A2%0A4%0A5&a=1&m=2) Unpacked, ungolfed, and commented, the program looks like this. ``` m map over [1 .. input] using rest of the program, output each result 'A "A" literal xhi= is the iteration index equal to (integer) half the input? 65* multiply by 65 (character code of "A") ]i* repeat that character (" " or "A") i times + concat to initial "A" x) left pad to the original input |p palindromize (concatenate the reverse minus the last character) ``` [Run this one](https://staxlang.xyz/#c=m+++%09map+over+[1+..+input]+using+rest+of+the+program,+output+each+result%0A%27A++%09%22A%22+literal%0Axhi%3D%09is+the+iteration+index+equal+to+%28integer%29+half+the+input%3F%0A65*+%09multiply+by+65+%28character+code+of+%22A%22%29%0A]i*+%09repeat+that+character+%28%22+%22+or++%22A%22%29+i+times%0A%2B+++%09concat+to+initial+%22A%22%0Ax%29++%09left+pad+to+the+original+input%0A%7Cp++%09palindromize+%28concatenate+the+reverse+minus+the+last+character%29&i=1%0A2%0A4%0A5&a=1&m=2) [Answer] # JavaScript (ES6), 77 bytes This source code has a [rectangle shape](https://codegolf.stackexchange.com/q/160034/58563)! Oh wait ... wrong challenge :-/ ``` f=(n,k=n>>1,p='A')=>--n?f(n,k,' '+p)+` ${p}${(k-n?' ':'A').repeat(n*2-1)}A`:p ``` [Try it online!](https://tio.run/##bcqxCoMwFEDR3a/oICSvSYTYdhGS4n90MNiktMrLQ6WL@O2pjoWs596P@7q5n960KIxPn1IwHOVg0FotybCWgbFK4T0cLNmJCQLRFeVKW7nyYS@7NcdXTZ68Wziea6Vha7uGUh9xjqOvxvjigWsQ7IEMin@u83zJ8zXPN4D0Aw "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3.6](https://docs.python.org/3/), 79 bytes or 73 bytes Using **f-strings** to align horizontal parts of the letter: ``` lambda n:'\n'.join(f"{'A'+' A'[i==n//2]*2*i:>{n+i}}"[:-1]+'A'for i in range(n)) ``` With `\b` used to delete one `A` (possibly cheating): ``` lambda n:'\n'.join(f"{'A'+' A'[i==n//2]*2*i:>{n+i}}\bA"for i in range(n)) ``` [Answer] # [J](http://jsoftware.com/), 65 bytes ``` f=:3 :''' A''{~1(([:(<@;]+i.@+:)<.@-:)y)}([:(}:@|."1,.])=/~@i.)y' ``` [Try it online!](https://tio.run/##y/r/P83WyljBSl1dXcFRXb26zlBDI9pKw8bBOlY7U89B20rTRs9B10qzUrMWJF5r5VCjp2Sooxeraatf55Cpp1mp/j81OSNfIU3BiAvKMIUxDA3@AwA "J – Try It Online") It can be reduced by approx. 12 bytes by simply making the verb tacit, but I have problems doing it. ## Explanation: `3 : '...'` denotes an explicit one-liner verb `y` is the argument `=/~@i.` creates an identity matrix with size the argument ``` =/~@i. 4 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 ``` `([:(}:@|."1,.])` prepends the identity matrix with its mirror copy with last elements of each row dropped. ``` ]a =. ([:(}:@|."1,.])=/~@i.) 4 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 1 0 1 0 0 0 0 0 1 ``` `1(...)}(...)` changes to 1 the positions in its right argument, selected by the left one `([:(<@;]+i.@+:)<.@-:)` - prepares the selection by doing the following: ``` <.@-: - halves the argument and finds the floor (finds the row number) <@; - box the row, followed by a list of columns: ]+i.@+: - a list form the argumnt to the doubled row number ([:(<@;]+i.@+:)<.@-:) 4 ┌───────────┐ │┌─┬───────┐│ ││2│2 3 4 5││ │└─┴───────┘│ └───────────┘ 1(([:(<@;]+i.@+:)<.@-:) 4)}a 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 0 1 0 0 0 0 0 1 ``` `' A'{~` renders a space in the places of 0 and 'A' where there is 1 ``` ' A'{~1(([:(<@;]+i.@+:)<.@-:) 4)}a A A A AAAAA A A ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~17~~ 13 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` A×/╶½A×╶»╵:╋│ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=QSVENyV1RkYwRiV1MjU3NiVCREElRDcldTI1NzYlQkIldTI1NzUldUZGMUEldTI1NEIldTI1MDI_,i=MTQ_) *-4 bytes thanks to [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima)!* [Answer] # [Java (JDK)](http://jdk.java.net/), 121 bytes ``` n->{var a=new char[n][n+n-1];for(int c=n*n,r,q;c-->0;a[r=c%n][q=c/n]=a[r][n+n-q-2]+=r==n/2&q>=r|r==n+~q?65:32);return a;} ``` [Try it online!](https://tio.run/##bVBNT4NAEL3zKyYkNVAK/TB66HYxxsTEg6cekcO6hboVBphdamqtf71uC40HPUzezL73dj42YivCzer9qMq6IgMbW0etUUU0ZM6ft7xFaVSF/5LaUCbKE@XIQmgNz0Ih7B2Aun0tlARthLGwrdQKSst5S0MK10kKgtbaP0sBntA89m0W8k1QkiZpDDnwI4bxfisIBMfsA84cpgkGGE5TllfkKTQgOQ5xRKOGyTCMJ0wkxOXA6houx5hyW3eeJpylASfOcTy7amJOX6c8@G7ubm/m1zOfUWZaQhDscGTnyS4tFHCYMgsLixObBMFleIDLyECZbgtjpXkk6rrYecpnvabbG7Ql74nETve38zqPH5Wi7o8zn9td/UhWRZFJ4z10WJGONpVCK/DcF3T936932mRlVLUmqq3f5J67VJ/ZHAarAQ60DXRHagS6dxycUxxO6fEH "Java (JDK) – Try It Online") ## Credits * -3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) [Answer] # [Ruby](https://www.ruby-lang.org/), 66 bytes ``` ->n{(0...n).map{|i|(s=(i==n/2??A:?\s)*2*i+?A)[0]=?A;?\s*(n+~i)+s}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNAT08vT1MvN7GguiazRqPYViPT1jZP38je3tHKPqZYU8tIK1Pb3lEz2iDW1t7RGiikpZGnXZepqV1cW/tfxc7GJi3aJFbLPibvPwA "Ruby – Try It Online") Returns as array of lines [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 12 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` A*:╚╥≤.»I:ž ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIwQSolM0EldTI1NUEldTI1NjUldTIyNjQuJUJCSSUzQSV1MDE3RQ__,inputs=NA__,v=0.12) Explanation: ``` A* repeat "A" input times : duplicate it ╚ create a "/" diagonal of one of the copies of As ╥ palindromize it horizontally ≤ get the other copy of the "A"s on top .»I: push floor(input/2)+1 twice ž and at those coordinates in the palindromized diagonals place in the row of As ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) `-R`, ~~20~~ 19 bytes ``` Çç" A"gZ¶Uz¹i'A êÃû ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=x+ciIEEiZ1q2VXq5aSdBIOrD+w==&input=OAotUg==) --- ## Explanation ``` :Implicit input of integer U Ç :Create the range [0,U) and pass each Z through a function Uz : Floor divide U by 2 Z¶ : Test for equality with Z (true=1, false=0) " A"g : Get the character in the string " A" at that index ç : Repeat Z times ¹ : (Closes a few nested methods) i'A : Prepend an "A" ê : Palindromise à :End function û :Centre pad each element to the length of the longest element :Implicitly join with newlines and output ``` --- ## Alternative (In the hope that it might help me spot some savings!) ``` Æ'AúXÄ" A"gX¶Uz¹êÃû ``` [Answer] # Javascript, 124 bytes A fairly naive solution, gave it a shot to practice js skills. `for(i=-1,p=" ".repeat(n-1)+"A ";++i<n;console.log(i-~~(n/2)?p:p.slice(0,i)+"A".repeat(n)),p=p.slice(1,n)+" "+p.slice(n-1)){}` Unpacked ``` for( //create the first line i=-1, p=" ".repeat(n-1)+"A "; ++i<n; console.log( //if we are not at the bar i-~~(n/2)? //otherwise, use the modified previous line p //slice the start of the previous line and add As :p.slice(0,i)+"A".repeat(n)), //add a space in between the previous line and remove padding on each side p=p.slice(1,n)+" "+p.slice(n-1)){} ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 73 bytes ``` ->n{(0...n).map{|i|(?A.ljust(i*2,i==n/2??A:' ')+(i>0??A:'')).center n*2}} ``` [Try it online!](https://tio.run/##HcfdCkAwFADgV9ndfnBo5UZty3PgAlFHnDRzITz7lO/u8@dwxdnEzNItCgAgCVu/3w8@wtWwLucRBCqdojGUa@fqijMuE4G2@MOlhHGiMHlGSr9v3D1SYHNTdsq1FD8 "Ruby – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ ~~20~~ ~~19~~ 18 bytes ``` =þ`o\L‘HĊƲ¦UŒBị⁾A ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//PcO@YG9cTOKAmEjEisaywqZVxZJC4buL4oG@QSD/w4dZ//80MA "Jelly – Try It Online") `=þ`` creates an identity matrix of size `n`. `L‘HĊƲ` finds the row index of the horizontal bar with `¦` picking that row out and applying `o\` to it which creates the bar. `U` reverses each row so we don't have an upside down "A" and `ŒB` (palindromize; vectorizes) makes the second half of the "A". `ị⁾A` (with a space that is getting trimmed in the formatting) replaces `0`s with spaces and `1`s with `A`s. [Answer] # [T-SQL](https://www.microsoft.com/sql-server), ~~182~~ 177 bytes ``` DECLARE @n INT=5DECLARE @ INT=0a:DECLARE @s VARCHAR(9)=STR(POWER(10,@),@n)PRINT REPLACE(REPLACE(@s+REVERSE(LEFT(@s,@n-1)),'1','A'),'0',IIF(@=@n/2,'A',' '))SET @+=1IF @<@n GOTO a ``` First version (with 182 bytes): ``` DECLARE @n INT=5DECLARE @ INT=0WHILE @<@n BEGIN DECLARE @s VARCHAR(9)=STR(POWER(10,@),@n)PRINT REPLACE(REPLACE(@s+REVERSE(LEFT(@s,@n-1)),'1','A'),'0',IIF(@=@n/2,'A',' '))SET @+=1 END ``` The version above works up to @n=9. Here is another version, which works up to @n=23, but has 2 extra bytes: ``` DECLARE @n INT=5DECLARE @ INT=0WHILE @<@n BEGIN DECLARE @s VARCHAR(23)=STR(POWER(10.,@),@n)PRINT REPLACE(REPLACE(@s+REVERSE(LEFT(@s,@n-1)),'1','A'),'0',IIF(@=@n/2,'A',' '))SET @+=1 END ``` Ungolfed: ``` DECLARE @n INT=5 DECLARE @i INT=0 WHILE @i<@n BEGIN DECLARE @s VARCHAR(9)=STR(POWER(10,@i),@n) PRINT REPLACE(REPLACE(@s+REVERSE(LEFT(@s,@n-1)),'1','A'),'0',IIF(@i=@n/2,'A',' ')) SET @i+=1 END ``` [Answer] # [Haskell](https://www.haskell.org/), ~~98~~ ~~97~~ 95 bytes and 109 bytes Two very different approaches. First (95 bytes): ``` c!n=([1..n]>>c)++"A" f n=unlines[" "!(n-x)++drop 3([" "!(abs$n`div`2-x+1)!!0]!(2*x))|x<-[1..n]] ``` and second (109 bytes): ``` m True='A' m _=' ' g n=unlines[[m(abs(n-j)==l||l==q&&elem j[q+1..q+n])|j<-[1..2*n]]|l<-[0..n-1],q<-[n`div`2]] ``` ~~[Try them here!](http://rextester.com/PDHKH9517)~~; ~~[Try modified version here!](http://rextester.com/TBXH98462)~~ [Try third version here!](http://rextester.com/SLVQ22299) [Answer] # [Python 2](https://docs.python.org/2/), 70 bytes or 65 bytes List of strings is acceptable result, as @Budd stated in comments. ``` lambda n:['%*sA\n'%(n+i,('A'+i*2*' A'[i==n/2])[:-1])for i in range(n)] ``` [Try it online!](https://tio.run/##Xc29DsIgEADgWZ/iluY4ipoyOJAwsPcNKAPGvzN6NNjFp6edXb/lm3/Ls4hto5/aO38u1wziInb6GybBTknPRmHAnrXVCAEjey8nmyi6w5DoXiowsEDN8rgpodT@aDBncvvdXFkWQDy@CosaFRMZwO1oKw "Python 2 – Try It Online") --- Seemingly cheaty solution, using `\b`. It looks funky in TIO, in console it does the job. ``` lambda n:['%*s\bA\n'%(n+i,'A'+i*2*' A'[i==n/2])for i in range(n)] ``` [Try it online!](https://tio.run/##Xcy9DsIgFAbQWZ/iLs0FSjQyODRhYO8blA40/l1TPxrs0qenzq5nOMu2vjJc7X2sc/pMt0ToBm7MN04hghuFViwHbsU4wxR4EO9xdqN@5EJCAioJz7uCHusfXexVd8fDUgQrMZ/eWaB6JVpb4l9edw "Python 2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-n`, 57 bytes ``` #!/usr/bin/perl -n say$"x-$_.uc(A x($n+$_&-2?1:$n*2)|$"x2x$n++.A)for 1-$_..0 ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJFqUJXJV6vNFnDUaFCQyVPWyVeTdfI3tBKJU/LSLMGKG1UARTV1nPUTMsvUjAEKdYz@P/f8l9@QUlmfl7xf928/7q@pnqGBnoGAA "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 93, 88 bytes ``` lambda n:'\n'.join(f"{'A'+(x>0)*('A '[x!=n//2]*(x*2-1)+'A'):^{n*2-1}}"for x in range(n)) ``` [Try it online!](https://tio.run/##FYvBCoJAFADP9RUvQd5b3TK1LoKB36EGG7pl1FsxD7uI3256nGGmd@PLcLrovFo@6vtoFHCGFePpbTom7U1YYEj2dhYBYQFY2kPOUZTUAdkgOcYiXAOR3SfeaJ49bQaw0DEMip8tsRDLptymylhCIiGVcJFwrbP9rh86Hgn9pmL/hz45qcmJ9fkD "Python 3 – Try It Online") -3 by @ovs using f-string ]
[Question] [ Haskell has tuples that can be written as ``` (a,b,c) ``` However this is just syntactic sugar for ``` (,,)a b c ``` In general an **n** tuple can be formed with **n-1** `,`s between `(`...`)` followed by its elements separated by spaces. For example the 7-tuple, `(1,2,3,4,5,6,7)` can be formed by ``` (,,,,,,)1 2 3 4 5 6 7 ``` Since Haskell does not have 1-tuples they cannot be formed. You will also not be held responsible for empty tuples. Nested tuples can be formed using parens to override the order of operations. ``` ((1,2),3) == (,)((,)1 2)3 ``` As part of [our pursuit to remove all syntactic sugar from Haskell](https://codegolf.stackexchange.com/questions/126410/sugar-free-syntax) I am going to ask you to write a program that removes syntactic sugar from Haskell's tuples as well. Your program should take a tuple, an array, or a string representing a sugary tuple and should output a string representing a "sugar-free" tuple. Input tuples will only ever contain positive integers or other tuples. Since we are golfing here your output should be short. It should not contain unnecessary * Spaces. Spaces should be used only to separate arguments of a tuple functions and should not appear after a `)` or before a `(` * Parentheses. Parentheses should be used only when forming tuple functions or when nesting tuples. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes with fewer bytes being better. ## Test cases ``` (1,2) -> (,)1 2 (1,2,3) -> (,,)1 2 3 ((1,2),3) -> (,)((,)1 2)3 (1,2,3,4) -> (,,,)1 2 3 4 (1,(2,3)) -> (,)1((,)2 3) (10,1) -> (,)10 1 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~169~~ 148 bytes ``` init.tail.fst.([]%) p:k="(," l%('(':r)|(y,x:s)<-[]%r,m<-y:l=last$m%(p:s):[(p:p:(l>>k)++x:foldl(\r x->x++[' '|x>k,r>k]++r)[x]m,s)|x<','] l%r=lex r!!0 ``` [Try it online!](https://tio.run/##TY5NboMwEIX3PsUEBTEWNoKQlQWcoF11SVhYaWgRhlqGSo5Kr17KX1BmM09vvpk3n7Krb0qNZXoZq7bqg15WKii7PsC8cCnRok4dZA5RLnroCUMHvDMrOprwCTCsSfhdqFTJrj82LuppIvKpaYEqy2rq@1aUX@pd4cWA5Zn1/dwDb7BZzUxWF75vaG6LhnV0sInHvGKKMqm6WTCHQzg2smohhUbqV0D93b/15qWFAEoKR8gdjNiJOmzpLF7UYm16cdl50zgjqw5Z9AzPSEHIDyeLAXPxDJDRCE5kO/7wFhNisidtKK44jcmeuy1sG3Am@xeP8/PSNKJk/ekpOISI8N/x71oq@dGN/Kr1Pw "Haskell – Try It Online") Takes the tuple as a string. `init.tail.fst.([]%)` is the anonymous main function. Bind it to e.g. `f` and use like `f "(3,(14,1),4,7)"`, which yields `"(,,,)3((,)14 1)4 7"`. Why is the input not provided as a Haskell tuple, you ask? Because Haskell is strongly typed, a tuple `(1,2)` has type `(Int,Int)`1 and a tuple `(1,(2,3))` has type `(Int,(Int,Int))`. Thus a function which accepts the first kind of tuple can not be applied to the second kind, and especially there can be no function which takes an arbitrary tuple2. ### Explanation: * `p:k="(,"` is a short way to assign `p` to `'('` and `k` to `","`. * `(%)` is the recursive parsing and converting function. The first argument is a list of already parsed tuple entries, the second argument is the remainder of the original string. Each call returns a tuple of the current converted tuple (as a string and enclosed in brackets) and the remainder of the string. + `l%('(':r)` If the string starts with an opening bracket, we need to parse a new tuple entry. `(y,x:s)<-[]%r` We recursively apply `%` and get a tuple entry `y` and the remaining string splitted into the next character `x` and the rest of the string `s`. `m<-y:l` We add the new entry `y` to the current list of already found entries `l` and call the result `m`. + The next character `x` is now either a comma `,` or a closing bracket `)`. The `last$ <B> :[ <A> |x<',']` is just a shorter way of writing `if x == ')' then <A> else <B>`. + So if a `,` is next, we need to recursively parse the next entry: `m%(p:s)` We prepend an opening bracket in order to end up in the right case and pass the list of already found entries `m`. + If otherwise `x == ')'`, we finished the current tuple and need to do the required transformation: `(p:p:(l>>k)++x:foldl(\r x->x++[' '|x>k,r>k]++r)[x]m,s)` - `p:p:(l>>k)++x:` If we have found *n* entries, then `m` has *n* elements and `y`, the list before adding the most recently found element, has *n-1* entries. This comes in handy as we need *n-1* `,` for an `n` element tuple and `l>>k` works on lists as *"concatenate the list `k` with itself as many times as `y` has elements"*. Thus this first part yields some string like `"((,,,)"`. - `foldl(\r x->x++[' '|x>k,r>k]++r)[x]m` concatenates the elements of `m` (in reverse order, because by adding new entries to the front `m` itself was constructed in reverse order) while adding only spaces in between two elements if they are both numbers: `[' '|x>k,r>k]` we check if the current entries `x` and `r` are numbers by lexicographically comparing them to `","` - if they are not numbers, they are already a tuple representation enclosed in brackets, and `'(' < ','` holds. + If the pattern match `l%('(':r)` right at the beginning fails, then we end up on the last line: `l%r=lex r!!0`. This means we need to parse a number and return the number and the remainder of the string. Luckily there is the `lex` function which does exactly that (It parses the next valid Haskell token, not just numbers). However the resulting tuple is wrapped into a list, so we use `!!0` to get the first element of the list. * `init.tail.fst.([]%)` is the main function which takes a string and applies `%` with an empty list to it. E.g. for an input `"(1,2)"`, , applying `([]%)` yields `("((,)1 2)","")`, so the outer tuple and brackets need to be removed. `fst` gets the first element of the tuple, `tail` removes the closing bracket and `init` the opening one. **Edit:** Many thanks to [@Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen) for golfing a total of **21 bytes**! --- 1 Actually, the type is *(Num t1, Num t) => (t, t1)*, but that's a diferent story. 2 Ignoring polymorphic functions like *id*, which cannot actually work with their input. [Answer] ## Haskell, ~~141 bytes~~ 138 bytes(Thanks to Ørjan Johansen) ``` import Language.Haskell.TH f(TupE l)='(':tail(","<*l)++')':""%l q%(LitE(IntegerL i):l)=q++show i++" "%l _%(e:l)='(':f e++')':""%l _%[]=[] ``` `f` has type `Exp -> String`. * Input: a [Template Haskell `Exp`](http://hackage.haskell.org/package/template-haskell-2.12.0.0/docs/Language-Haskell-TH.html#t:Exp)ression (i.e., the standard AST representation of arbitrary-type Haskell values – basically, parsed Haskell code before type checking); must represent a tuple containing only nonnegative integer numbers and other such tuples. * Output: a string containing the desugared syntax for that tuple expression. Demo: ``` $ ghci TupDesugar.hs GHCi, version 8.3.20170711: http://www.haskell.org/ghc/ :? for help Loaded GHCi configuration from /home/sagemuej/.ghc/ghci.conf Loaded GHCi configuration from /home/sagemuej/.ghci [1 of 1] Compiling Main ( TupDesugar.hs, interpreted ) Ok, 1 module loaded. *Main> :set -XTemplateHaskell -XQuasiQuotes *Main> f <$> runQ [|(1,2)|] "(,)1 2" *Main> f <$> runQ [|(1,2,3)|] "(,,)1 2 3" *Main> f <$> runQ [|((1,2),3)|] "(,)((,)1 2)3" *Main> f <$> runQ [|(1,2,3,4)|] "(,,,)1 2 3 4" *Main> f <$> runQ [|(1,(2,3))|] "(,)1((,)2 3)" *Main> f <$> runQ [|(10,1)|] "(,)10 1" ``` [Answer] # [Haskell](https://www.haskell.org/), 119 bytes ``` data T=I Int|U[T] f(U t)="(("++init(t>>",")++')':foldr(\x y->f x++[' '|f x>",",y>","]++y)")"t f(I n)=show n init.tail.f ``` [Try it online!](https://tio.run/##bU5Na4NAEL3vr3hIwR12FVc9FfQutKfGk/UgpCZSY0KypZGmv93uaqoWujDDzvua2VeX97e2HYZtpStskgxZp295sSlZzXNoShzOHSGartFcp6kjHRLCJfexPrbbM3@9ovfSGlchChfuzfysRva2l0L05JCjTVaGjpLL/viJju0SG@frqmn9ejhUTYcEh@r0DH760C/6/NTBx47wgIIhLzIomSEs5WowFU3Aip@xlchUvIC2T94ZC8yo/osanQwlY18e40qGhOl5KbgkhXBEZUQLOsKIGB/1EzXJ@WSh6G6S8cz9uhBbjtvExaes0ZBkuEAq@nNCADWvsoH3G@ZdJtH7Hn4A "Haskell – Try It Online") This uses a custom data type `T` to represent tuples, that is a tuple `((1,2),3)` is represented as `U[U[I 1,I 2],I 3]`. Example usage: `init.tail.f $ U[U[I 1,I 2],I 3]` yields `(,)((,)1 2)3`. [Answer] # [Python 2](https://docs.python.org/2/), 110 bytes ``` def f(t): s='('+','*~-len(t)+')';c=0 for i in t: try:s+=' '*c+`+i`;c=1 except:s+='(%s)'%f(i);c=0 return s ``` [Try it online!](https://tio.run/##JY1BCsMgEEXX8RSzCTMTLTTpzuJdAqlSoRjRCTSbXt1Ku/3vPX4@5bmnpbWHDxBI2CqoDgk1Gpw@l5dPfdTIeN/cVUHYC0SICcSqQcppq3YIOG161XHtzqwG/958lh@hsTKOgSL/8@LlKAlqyyUm6Ycx5UOIudFsgBYDN@Yv "Python 2 – Try It Online") Takes a `tuple`. [Answer] # GNU sed, ~~149~~ 82 + 2 = 84 bytes +2 bytes for `-r` flag. ``` y/(),/<>'/ : s/([^<>']+)'/,\1 / t s/ ?<(,+)([^>]+)>/((\1)\2)/ t s/^.|(\)) |.$/\1/g ``` [Try it online!](https://tio.run/##JYmxDsIwDET3fEUGpNqqW@PChKr0QzCdQIiFItIFqd@OccJy9@5evl3NPgxIPKaGwylkhvPsfGmxYVKJHFY/4zQCteguuUkMoII64N/O/QaKGLd@xyp8NwOhAUNJOnjXWak@dKwERRbak@B3ea2P5Zmte/8A "sed 4.2.2 – Try It Online") ## Explanation ``` y/(),/<>'/ # Replace parens and commas with brackets and apostrophes : s/([^<>']+)'/,\1 /. # Remove each apostrophe and insert comma after < t # Branch to : if substitution was made s/ ?<(,+)([^>]+)>/((\1)\2)/ # Change <,,,...> to ((,,,)...) t # Branch to : if substitution was made s/^.|(\)) |.$/\1/g # Remove outermost ()s and extra spaces ``` [Answer] # JavaScript, 75 bytes ``` f=a=>`(${t=a.map(x=>'')})${a.map(v=>t=1/v?1/t?' '+v:v:`(${f(v)})`).join``}` ``` Input array of number|array, output string. Thanks to Neil, save 2 bytes [Answer] # Mathematica, 94 bytes ``` {"(",","&/@Most@#,")",c=1>0;(xIf[j=ListQ@x,c=j;"("<>#0@x<>")",If[c,c=j;x," "<>x]])/@#}<>""& ``` Contains an unprintable `U+F4A1`, a builtin `Function` function. Takes a `List` of integer `String`s. If this is not allowed, this can be fixed by adding 10 more bytes (this version takes a `List` of `List`s/`Integer`s): ``` {"(",","&/@Most@#,")",c=1>0;(xIf[j=ListQ@x,c=j;"("<>#0@x<>")",If[c,c=j;""," "]<>ToString@x])/@#}<>""& ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 45 bytes ``` {Y"()"b:yJ',X#a-1Fcab.:c>0?s.cyJ(fc)bR") "')} ``` This is a function that takes a list as an argument. [Try it online!](https://tio.run/##K8gs@J9m9b86UklDUynJqtJLXSdCOVHX0C05MUnPKtnOwL5YL7nSSyMtWTMpSElTQUlds/Z/gEaaQrShgpGCsYJJrCYXmBttaKBgaBirYGgEEzFUiAaqiEVWAhEBCilEmyqYxQIlSv8DAA "Pip – Try It Online") ### Commented version ``` ; Define an anonymous function (the argument is available inside as the variable a) { ; Yank the string "()" into y variable Y "()" ; Create a string of len(a)-1 commas, join y on it, and assign to b b: y J ',X#a-1 ; For each item c in a F c a ; Concatenate to b the following expression b .: ; Is c integer or list? ; (If c is a positive integer, c>0 is true; but if c is a list, c>0 is false) c>0 ? ; If c is integer, concatenate space followed by c s.c ; If c is list, call function recursively on c and use the result to join y yJ(fc) ; Replace ") " with ")" in b and return the resulting string b R ") " ') } ``` [Answer] ## JavaScript (ES6), ~~88~~ 84 bytes ``` f=a=>a.reduce((s,e)=>s+=e[0]?`(${f(e)})`:/\)$/.test(s)?e:' '+e,`(${[...a].fill``})`) ``` Takes an array of integers and arrays. Edit: Saved 1 byte by using `s+=` instead of two separate uses of `s+`. Saved a further 3 bytes now that I can simplify the inner ternary. If I steal @tsh's ideas then I can get it down to 76 bytes: ``` f=a=>a.reduce((s,e)=>s+=t=1/e?1/t?' '+e:e:`(${f(e)})`,`(${t=a.map(_=>``)})`) ``` [Answer] # R, 316 bytes? (Have to head out and not sure the proper way to count bytes... plus it's not a great solution but wanted to post it since I spent the time making it...) ``` p=function(x){ x=eval(parse(text=gsub("\\(","list(",x))) f=function(j,r=T){ p=paste s=if(r){"("}else{"(("} o=paste0(s,p(rep(",",length(j)-1),collapse=""),")") n=lengths(j) for(i in seq_along(n)){ v=j[[i]] if(n[i]>1){v=f(v,F)} o=p(o,v)} if(!r){o=p(o,")")} o=gsub(" *([()]) *","\\1",o) return(o)} f(x) } ``` Test cases: ``` > p("(1,2)") [1] "(,)1 2" > p("(1,2,3)") [1] "(,,)1 2 3" > p("((1,2),3)") [1] "(,)((,)1 2)3" > p("(1,2,3,4)") [1] "(,,,)1 2 3 4" > p("(1,(2,3))") [1] "(,)1((,)2 3)" > p("(10,1)") [1] "(,)10 1" ``` [Answer] ## JavaScript (ES6), 72 bytes ``` f=(a,b="",c="")=>a.map?b+"("+a.map(x=>'')+")"+a.map(x=>f(x,"(",")"))+c:a ``` Input: Array containing numbers and/or arrays Output:string Usage: f([...]) Completes all test cases, improvements welcome [Answer] # C, 308 or 339 bytes ``` #include <ctype.h> #define p putchar f(s,e,c,i,l)char*s,*e,*c;{i=1,l=40;if(*s++==l){p(l);for(c=s;i;i+=*c==l,i-=*c==41,i+*c==45&&p(44),c++);p(41);}for(;s<e;s=c){for(i=0;isdigit(*s);s+=*s==44)for(i&&p(32),i=1;isdigit(*s);s++)p(*s);*s==l&&p(l);for(c=s,i=1;++c,c<=e&&i;i+=*c==l)i-=*c==41;f(s,c-1);*s==l&&p(41);}} #define g(x) f(x, x+strlen(x)) ``` 308 or 339 bytes, depending on whether or not passing a pointer to the end of the input string is allowed; the last line is only there to allow passing a string literal directly without having to calculate its length. ## Explanation A pretty simple algorithm. It counts the number of commas at the current depth, prints them as a tuple constructor, then follows up with the tuple's arguments, escaped (spaces between numbers, nested tuples between parenthesis), recursively. ``` #include <stdio.h> #include <ctype.h> typedef enum { false, true } bool; void tup2ptsfree(char *s, char *e) { int depth; char *c; if (*s++ == '(') { /* If we are at the start of a tuple, write tuple function `(,,,)` (Otherwise, we are at a closing bracket or a comma) */ putchar('('); /* do the search for comma's */ c=s; /* probe without moving the original pointer */ for (depth=1; depth != 0; c++) { if (*c == '(') depth++; if (*c == ')') depth--; if (*c == ',' && depth == 1) putchar(','); /* We have found a comma at the right depth, print it */ } putchar(')'); } while (s < e) { /* The last character is always ')', we can ignore it and save a character. */ bool wroteNumber; for (wroteNumber=false; isdigit(*s); wroteNumber = true) { if (wroteNumber) p(' '); /* If this is not the first number we are writing, add a space */ while (isdigit(*s)) putchar(*s++); /* Prints the entire number */ if (*s == ',') s++; /* We found a ',' instead of a ')', so there might be more numbers following */ } /* Add escaping parenthesis if we are expanding a tuple (Using a small if statement instead of a large branch to prevent doing the same thing twice, since the rest of the code is essentially the same for both cases). */ if (*s == '(') putchar('('); /* Find a matching ')'... */ c=s+1; for (depth=1; c <= e && depth != 0; c++) { if (*c == '(') depth++; if (*c == ')') depth--; } /* Found one */ /* Note how we are looking for a matching paren twice, with slightly different parameters. */ /* I couldn't find a way to golf this duplication away, though it might be possible. */ /* Expand the rest of the tuple */ tup2ptsfree(s, c-1); /* idem */ if (*s == '(') putchar(')'); /* Make the end of the last expansion the new start pointer. */ s=c; } } #define h(x) tup2ptsfree(x, x+strlen(x)) ``` ## Test cases and application ``` #include <stdio.h> #define ARRAYSIZE(arr) (sizeof(arr)/sizeof(*arr)) static char *examples[] = { "(1,2)", "(10,1)", "(1,2,3)", "(1,2,3,4)", "((1,2),3)", "(1,(2,3))", "(1,(2,3),4)", "((1,2),(3,4))", "((1,(2,3)),4,(5,6))", "((1,((2,3), 4)),5,(6,7))", "(42,48)", "(1,2,3,4,5,6,7)" }; int main(void) { int i; for (i=0; i < ARRAYSIZE(examples); i++) { printf("%-32s | \"", examples[i]); g(examples[i]); /* Test with golfed version */ printf("\"\n"); printf("%-32s | \"", examples[i]); h(examples[i]); /* Test with original version */ printf("\"\n"); } } ``` ]
[Question] [ I recently stumbled across [this image](https://commons.wikimedia.org/wiki/File:Tesseract_Hasse_diagram_with_nibble_shorthands.svg) on wikimedia commons. It's a little bit of an information overload at first, but after examining it a bit it shows an interesting number system for writing nibbles. [![Tesseract Hasse diagram with nibble shorthands](https://i.stack.imgur.com/Urze2.png)](https://i.stack.imgur.com/Urze2.png) *Image created by user [Watchduck](https://commons.wikimedia.org/wiki/User:Watchduck).* First off a "nibble" is a 4 bit number which is really a number ranging from 0 to 15, with a particular emphasis on binary. This diagram shows a shorthand for writing such numbers with each number being one symbol. Ok, who cares? Plenty of people make up new symbols for numbers all the time. Well the interesting thing about these numbers is their symmetry. If you take one of the symbols and mirror it horizontally you get the symbol of the number with the same bits in reverse order. For example the symbol that sort of looks like a 3 represents the bits 0011, it's horizontal mirror represents the bits 1100. Numbers which are symmetric along this mirror represent nibbles which are palindromes. Similarly if you take a symbol and rotate it a half turn (180 degrees) you get the symbol for the bitwise compliment of that number, for example if you take the symbol that looks like a 7, it represents 0111, if you rotate it a half turn you get a symbol representing 1000. ## Task You will write a program or function which takes as input a nibble and outputs an image of a symbol. Your symbols are not required to be anything in specific but they are required to have the symmetry properties. 1. Distinct nibbles should give distinct symbols 2. The symbol for a nibble \$r\$ should be the mirror image of the symbol for the reverse of \$r\$. 3. The symbol for a nibble \$r\$ should be the symbol for the bitwise compliment of \$r\$ rotated 180 degrees. You may take input in any reasonable format and output in any image or graphical format. There are no additional requirements on resolution, aside from those implied by the rules. You can make your symbols as small as you wish as long as you satisfy the rules. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the goal is to minimize the size of your source code as measured in bytes. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12~~ 7 bytes ``` t~Pv1YG ``` Input is a 4-digit binary vector. **Example outputs** (or try it at [**MATL Online**](https://matl.io/?code=t%7EPv1YG&inputs=%5B0+1+0+0%5D&version=22.7.4)!): * Input `[0 1 0 0]`: [![enter image description here](https://i.stack.imgur.com/PN9ypm.png)](https://i.stack.imgur.com/PN9ypm.png) * Input `[1 0 1 1]`: [![enter image description here](https://i.stack.imgur.com/ODR4Jm.png)](https://i.stack.imgur.com/ODR4Jm.png) * Input `[1 1 0 1]`: [![enter image description here](https://i.stack.imgur.com/hdivwm.png)](https://i.stack.imgur.com/hdivwm.png) * Input `[1 0 0 1]`: [![enter image description here](https://i.stack.imgur.com/Q2kQdm.png)](https://i.stack.imgur.com/Q2kQdm.png) * Input `[0 1 1 0]`: [![enter image description here](https://i.stack.imgur.com/aNQ6Tm.png)](https://i.stack.imgur.com/aNQ6Tm.png) ### How it works The output is a 2-row, 4-column image where the first row corresponds to the input binary digits, and the second row is the first element-wise negated and reversed. ``` t % Implicit input. Duplicate % STACK: [0 1 0 0], [0 1 0 0] ~ % Negate, element-wise % STACK: [0 1 0 0], [1 0 1 1] P % Reverse % STACK: [0 1 0 0], [1 1 0 1] v % Vertically concatenate % STACK: [0 1 0 0; 1 1 0 1] 1YG % Display image with scaled colors. 0 is shown as black, 1 as white ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 106 bytes Takes an integer as input and returns a PBM image. ``` ->i{t="'/%[g|eS  s m R\rzrt" "P1 5 3 "+("%08b"%t[t.index(i.chr)+1].ord).gsub(/./,'\&0')[1..]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3s3TtMqtLbJUYxBnVmfSZVVmiWdPZathTOYI55bmKuXN5gmKKqviK-EuUuJQCDLlMFYy5lLQ1lFQNLJKUVEuiS_Qy81JSKzQy9ZIzijS1DWP18otSNPXSi0uTNPT19HXUY9QM1DWjDfX0YmuhNsZoGOjpGZpq6qUmJmcopOQr1OTVcCkoZOYmpqcq2CqkRefFArkFpSXFCkrWCqnJGfkKMUrK1WD52hglBTsF5Wqg_SZA-_Nq9QqScpWgyrlS81IgdixYAKEB) The code has unprintable characters that make it copy-and-paste-unfriendly; expand the below snippet for an xxd dump if you want to try it on your own machine. ``` 00000000: 2d3e 697b 743d 2200 1701 2702 2f03 2504 ->i{t="...'./.%. 00000010: 5b05 6706 7c07 6508 5309 1f0a 730b 6d0c [.g.|.e.S...s.m. 00000020: 525c 727a 0e72 0f74 220a 2250 310a 3520 R\rz.r.t"."P1.5 00000030: 330a 222b 2822 2530 3862 2225 745b 742e 3."+("%08b"%t[t. 00000040: 696e 6465 7828 692e 6368 7229 2b31 5d2e index(i.chr)+1]. 00000050: 6f72 6429 2e67 7375 6228 2f2e 2f2c 2726 ord).gsub(/./,'& 00000060: 3027 295b 312e 2e5d 7d0a 0')[1..]}. ``` ## The shorthand [![](https://i.stack.imgur.com/f9HxX.png)](https://i.stack.imgur.com/f9HxX.png) ## How it works The images are 5×3 but there are only 7 "real" pixels, in a hex pattern: ``` 1 1 1 1 1 1 1 ``` This makes each image's data fit in a byte. `t` is a lookup table where the ASCII character corresponding to each nibble is followed by the character corresponding to its image representation. The code looks up the image data in the table, formats it as a string of `1`s and `0`s, interleaves the extra `0`s, and returns it in PBM format. ## Ungolfed ``` ->input{ table = "\x00\x17\x01\x27\x02\x2f\x03\x25\x04\x5b\x05\x67\x06\x7c\x07\x65\x08\x53\x09\x1f\x0a\x73\x0b\x6d\x0c\x52\x0d\x7a\x0e\x72\x0f\x74" image_byte = table[table.index(input.chr) + 1].ord image_data = ("%08b" % image_byte).gsub(/./,'\&0')[1..] "P1 5 3 " + image_data } ``` [Answer] # [Python 3](https://docs.python.org/3) + [NumPy](https://numpy.org/) and [Pillow](https://pillow.readthedocs.io/en/stable/), ~~101~~ ~~92~~ ~~91~~ ~~82~~ 77 bytes ``` import numpy as n,PIL.Image as p lambda x:p.fromarray(n.array([x,1-x[::-1]])) ``` Takes in a NumPy array of ones and zeros and returns the resulting 4x2 image. Basically a copy of [Luis Mendo's answer](https://codegolf.stackexchange.com/a/252262/114332) in Python. Ungolfed: ``` import numpy as np from PIL import Image def represent(nibble: np.array) -> None: representation = np.array([nibble, 1 - nibble[::-1]) image = Image.fromarray(representation) return image ``` Thanks to Louis Mendo, who figured this out (and then saved me 9 bytes)! Examples: * `[1, 0, 0, 1]` [![first example](https://i.stack.imgur.com/zBQlW.png)](https://i.stack.imgur.com/zBQlW.png) * `[1, 1, 1, 1]` [![second example](https://i.stack.imgur.com/uY4Zn.png)](https://i.stack.imgur.com/uY4Zn.png) * `[0, 1, 1, 0]` [![third example](https://i.stack.imgur.com/TAIU7.png)](https://i.stack.imgur.com/TAIU7.png) I have no idea where the blurring comes from. However, it still satisfies the criteria. Note that in these images, the colors are RGB (0, 0, 0) and (255, 255, 255), for human readability. However, in the image generated by the program, the colors are (0, 0, 0) and (1, 1, 1), which, while distinct, cannot be told appart using a human eye. * -9 thanks to Luis Mendo * -1 thanks to Jonathan Allen * -9 because I figured out I could return the image instead of displaying it, and not assign this to a variable * -5 again thanks to Jonathan Allen [Answer] ## JavaScript (browser), ~~187~~ 182 bytes ``` f= (n,c)=>c.getContext`2d`.putImageData(new ImageData(new Uint8ClampedArray(Int32Array.from([...s=n.toString(2).padStart(4,0),...[...s].reverse()],(c,i)=>-1<<(c^i/4)*24).buffer),4),0,0) ``` ``` canvas{width:256px;height:128px;image-rendering:pixelated;} ``` ``` <input type=number size=2 min=0 max=15 oninput=f(+this.value,c)><div><canvas id=c height=2 width=4> ``` Uses @LuisMendo's method. Draws the output on a `2×4` canvas passed as the second parameter, but the snippet scales the output up 64 times for convenience. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes A port of [@Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/252262/9288). ``` Image@{#,Reverse[1-#]}& ``` [![enter image description here](https://i.stack.imgur.com/LcOk9.png)](https://i.stack.imgur.com/LcOk9.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 142D;Ṛ;¬K”P; ``` A full program that outputs a PBM file on STD OUT. **[Try it online!](https://tio.run/##AUAAv/9qZWxsef//MTQyRDvhuZo7wqxL4oCdUDv/MuG4tuG5lzTCtcOH4oG@IiJqLEDFkuG5mGrigJwgLT4g4oCdKVn/ "Jelly – Try It Online")** ### How? Jelly cannot produce images on screen, so this places an image file content on STD OUT ready to be directed to a file. The PBM format idea came from [Jordan](https://codegolf.stackexchange.com/users/11261/jordan)'s [Goruby](https://codegolf.stackexchange.com/a/252279/53748) and [Ruby](https://codegolf.stackexchange.com/a/252278/53748) posts. Go upvote! The method is similar to [Luis Meno](https://codegolf.stackexchange.com/users/36398/luis-mendo)'s [MATL](https://codegolf.stackexchange.com/a/252262/53748) post, because there is nothing simpler. Go upvote! The only difference is that rather than the number on top of the reversed negated number we have the reverse of the number on top of the negated number. ``` 142D;Ṛ;¬K”P; - Main Link: list of four bits, N e.g. [0,0,1,0] 142 - 142 D - to decimal digits -> [1, 4, 2] Ṛ - reverse (N) [0,1,0,0] ; - concatenate [1,4,2,0,1,0,0] ¬ - logical NOT (N) [1,1,0,1] ; - concatenate [1,4,2,0,1,0,0,1,1,0,1] K - join with spaces [1,' ',4,' ',2,' ',0,' ',1,' ',0,' ',0,' ',1,' ',1,' ',0,' ',1] ”P - 'P' ; - concatenate ['P',1,' ',4,' ',2,' ',0,' ',1,' ',0,' ',0,' ',1,' ',1,' ',0,' ',1] - implicit, smashing print P1 4 2 0 1 0 0 1 1 0 1 i.e. the pixels: 0100 1101 ``` [Answer] ## HTML + Javascript 70 + ~~159~~ ~~154~~ 151 = 221 bytes The output is topologically like [Jordan's](https://codegolf.stackexchange.com/a/252258/252278), with the output rotated by 90° and lines instead of dots. This achieves a classical seven part display. The symbols also loosely resemble those used by Watchduck in his original grafic in shape and order. The order of the elements is ``` 0 M1,1h3 1 2 M1,1v3 M4,1v3 3 M1,4h3 4 5 M1,4v3 M4,4v3 6 M1,7h3 ``` After experimenting with multiple other variants, I find it interesting that this intuitive ordering still gives the shortest path production. The Bigint holds the shown elements for each symbol as bits ordered right to left. Since the symbol for 1111, the last symbol, has no shown elements in the lower half, the last (leftmost) hex digit is 0, and the number can be written in hex with 27 digits instead of the expected 16\*7/4 = 28. *-5 bytes thanks to Steffan.* *-3 bytes for bitwise operation on `BigInt` and symbol reordering.* ``` f=n=>{for(d='',i=0;i<7;i++)0xe5cfdb4f4dbf24fdb2f2dbf3a70n>>BigInt(n*7+i)&1n?d+=`M${(i+1)%3?1:4},${(i/3&3)*3+1}${i%3?'v':'h'}3`:0;p.setAttribute('d',d)} ``` ``` <input oninput=f(value)><svg viewBox=0,0,5,8><path id=p stroke=#000 /> ``` ### Ungolfed and a bit more pretty ``` f = n => { t = 0xe5cfdb4f4dbf24fdb2f2dbf3a70n for (d='',i=0; i<7; i++) { if (t>>BigInt(n*7+i)&1n) { d += `M${(i+1)%3?1:4},${(i/3&3)*3+1}${i%3?'v':'h'}3` } } p.setAttribute('d', d) } f(0) ``` ``` <input type=number size=2 value=0 min=0 max=15 oninput=f(value)> <div> <svg viewBox=0,0,5,8 width=80> <path id=p stroke=#000 /> </svg> </div> ``` [Answer] # [Goruby](https://codegolf.stackexchange.com/questions/363/tips-for-golfing-in-ruby/9289#9289), 37 bytes Takes an array of `0`s and `1`s and returns a PBM image. Same technique as [Luis Mendo's answer](https://codegolf.stackexchange.com/a/252262/11261). ``` ->a{"P1 4 2 #{a+a.rv.m{_1>0?0:1}}"} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=pVbdbts2FL73U5w4aSw5imJvHTAEddN2SLfdrEML7GKGJ1ASbbOVKJWk3NiS8iK7ycX2AHuc7Wl2SEryT92iw3IR0uf_5zuH-v0PUYTrh39670_h-0zfIRc0KeJelBAp4VX4lkaqB_Ds2SJL5sGSyCVMoKx7SFtREWaSenD2y-3rF6_e3CKnvXrAWYIyMZ1DStUyi4OUScn4AlIPhsSD8xDZAAqVdoxPYYp8SZO5byKYwQyqagIpUdEStQNrTDqpOx3NjAU2RyPn52DtAQSBpDwOAkdpRy6U1ZCIhawaNkDoh4zHaMynK5I4_VxkUVmZEIybmChSwdk9RrZPhLrv-hFJEufs3tV-z-53jBqGceU21NqcNJG0ISi4OQhP18GFa5BFToUV53Gv_b9T2KbYvbamh_WQKDMYeJDiqSMhYUJbpo1HIOfqt9NS-ioL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pKfs_j3uP4asebs0L4ouVn5bB-OnoZnQ9rut-bUX_Mpt1Pp2OvLE38kazmaU_PNjzXw) [Answer] # [Desmos](https://www.desmos.com/calculator), 44 bytes ``` L=[0...3] f(l)=join((L[l>0],1),(3-L[l=0],0)) ``` I have no idea what this question is asking about; I'm just porting most of the other answers here. [Try It On Desmos!](https://www.desmos.com/calculator/4ojzplhamn) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/yvcbqz6yus) [Answer] # [Fig](https://github.com/Seggan/Fig), \$16\log\_{256}(96)\approx\$ 13.17 bytes ``` J/Pj/ JJf142$xe! ``` [Try it online!](https://fig.fly.dev/#WyJKL1BqLyBKSmYxNDIkeGUhIiwiWzAsMCwxLDBdIl0=) Outputs as a PBM image. Port of Jelly, so go upvote that (and the posts that inspired it)! [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~35~~ 33 bytes ``` {`0:"P1\n4 2\n",*',/$x,"\n",$|~x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6pOMLBSCjCMyTNRMIrJU9LRUtfRV6nQUQKxVWrqKmq5uNKiDRUMFAwVDGPBTDAnFioKZYKlFQxiAS1AEuY=) Took me quite some time, but I finally got it. Output PBM image data, as that seems to be what everyone's doing. Forgive me if the explanation doesn't make sense. Neither do I understand it well. Explanation: ``` {`0:"P1\n4 2\n",*',/$x,"\n",$|~x} Main program. Takes x as input x x itself |~ Not, then reverse $ Convert each number to string "\n", Concat with newline , Concat with $x x, with each number converted to string ,/ Joined everything together *' Get the first element of each string. This is to remove the sub-arrays of the negate-then-reverse x , Concat the entire result with "P1\n4 2\n" PBM hardcoded image data. Defined an image of 2x4 pixels `0: Print everything to stdout ``` ]
[Question] [ ## Definition Given a matrix \$M\$ of non-negative integers and a non-negative integer \$k\$, we define \$F\_k\$ as the "chop-off" function that removes all rows and all columns in \$M\$ that contain \$k\$. *Example:* $$\begin{align}M=\pmatrix{\color{red}6&\color{red}1&\color{white}{\bbox[red,1pt]{5}}\\1&2&\color{red}8\\\color{red}9&\color{red}8&\color{white}{\bbox[red,1pt]{5}}\\6&0&\color{red}4}\\\\F\_5(M)=\pmatrix{1&2\\6&0}\end{align}$$ ## Your task Given \$M\$ and a target sum \$S\$, your task is to find all possible values of \$k\$ such that the sum of the remaining elements in \$F\_k(M)\$ is equal to \$S\$. *Example:* Given the above matrix \$M\$ and \$S=9\$: * \$k=5\$ is a solution, because \$F\_5(M)=\pmatrix{1&2\\6&0}\$ and \$1+2+6+0=9\$ * \$k=1\$ is the only other possible solution: \$F\_1(M)=\pmatrix{5\\4}\$ and \$5+4=9\$ So the expected output would be \$\{1,5\}\$. ## Clarifications and rules * The input is guaranteed to admit at least one solution. * The sum of the elements in the original matrix is guaranteed to be greater than \$S\$. * You may assume \$S>0\$. It means that an empty matrix will never lead to a solution. * The values of \$k\$ may be printed or returned in any order and in any reasonable, unambiguous format. * You are allowed not to deduplicate the output (e.g. \$[1,1,5,5]\$ or \$[1,5,1,5]\$ are considered valid answers for the above example). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). ## Test cases ``` M = [[6,1,5],[1,2,8],[9,8,5],[6,0,4]] S = 9 Solution = {1,5} M = [[7,2],[1,4]] S = 7 Solution = {4} M = [[12,5,2,3],[17,11,18,8]] S = 43 Solution = {5} M = [[7,12],[10,5],[0,13]] S = 17 Solution = {0,13} M = [[1,1,0,1],[2,0,0,2],[2,0,1,0]] S = 1 Solution = {2} M = [[57,8,33,84],[84,78,19,14],[43,14,81,30]] S = 236 Solution = {19,43,57} M = [[2,5,8],[3,5,8],[10,8,5],[10,6,7],[10,6,4]] S = 49 Solution = {2,3,4,7} M = [[5,4,0],[3,0,4],[8,2,2]] S = 8 Solution = {0,2,3,4,5,8} ``` [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 39 bytes ``` {a@&y=x{+//x*(&/'b)&\:&/b:~x=y}/:a:,/x} ``` [Try it online!](https://tio.run/##PU/LboJQFNz7FbNoLLRauDzkck9N/Qh3lkRsxBoNWMQUYvDX6SCmm/OYzMw5c5jmu7zrMnNNF@NmXl9fHad@scbO88Yef5qxszG3et60jknNxKnbbmcyIbtcvJfmY7eqpUlaOPgt09NpWyK75F/VvshRFTgXZTW95PsfVN9blNvz5ViNlub6tGpupcnwhlrWxUGsdZbuj0IrKe2kHS1XljWDQigKHrTE0JxncBHYEttEw@ROiuBxIRjZMgkGTHkIqfJFRVAKSkPbEvgk/IsUVS4dXSjiiuJ@esh5l5t4rC7t@06ENDp4AyeM@JDvQweiA0QaKoYKeIQVWsEn3fNn1MQgGEaDrH9Mi3@vvN9nYpshGhpjBAzH10HTxyWOLiVMLpqpPFt0/@1AolHS/QE "K (ngn/k) – Try It Online") *thanks @Adám for this explanation*: `{`…`}` function, `x` is *M* and `y` is *S*  `,/x` flatten *M* (these are the *k* candidates)  `a:` assign to `a`  `x{`…`}/:` apply the following function to each while using *M* as fixed left argument (`x`):   `x=y` Boolean matrix indicating where elements of *M* equal the current *k* candidate   `~` negate that   `b:` assign that to `b`   `&/` AND reduction (finds columns without that *k*)   `(`…`)&\:` AND that with each of the following:    `&/'b` AND reduction of each (finds rows without that *k*)   `x*` multiply *M* by that   `+//` grand sum  `y=` list of Booleans indicating where *S* equals those sums  `&` indices of Trues  `a@` use that to index into the elements (the *k* candidates) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~35~~ ~~33~~ 28 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") -7 thanks to ngn. Anonymous infix lambda. Takes *S* as left argument and *M* as right argument. ``` {⍵[⍸⍺=(+/∘,⍵×∧/∘.∧∧⌿)¨⍵≠⊂⍵]} ``` [Try it online!](https://tio.run/##bVA9SwNBEO39FemiOOrNzt7tXmFlYywMeHbHFQGJTUBbERuFEIMXtBAt7bSzEsQmEP/J/JHz7UabnHDcm483b2bf4Hy0dXIxGJ2dNs2l1h@l1p9af@2ub@7o5JlQ@X7SyWtItoHhu5tvLN7Q0NsXnV4jqK6aoY7vtZ7p7LHX1@nN4l10/ICsONrD/3i/VzR5Z9hZFg@K/mG3LDNiSisqmQx5YE4@5hklZKuqu@ZWJxyZyI9dK6ttNpRCSwLHETOxhzCo/I8SR6kkbkyIJfJaijgRTVAMMInrQ4Rq4BvJVidSh1eIkLegekvOE@fEIbMCJM8kcdi2DAnnByPkF3Hd0hEEGbm/IL7etxaTxVFhOLiH3XDCgPkD "APL (Dyalog Unicode) – Try It Online") `{`…`}` "dfn", `⍺` and `⍵` are left and right arguments (*S* and *M*) respectively:  `⍵[`…`]` index *M* with the following coordinates:   `⊂⍵` enclose *M* to treat it as a single element   `⍵=` compare each element (i.e. *k* candidate) of *M* to that entire *M*   `(`…`)¨` apply the following tacit function to each:    `∧⌿` vertical AND reduction (finds columns without that *k* candidate) …`∘.∧` Cartesian Boolean product with:     `∧/` horizontal AND reduction (finds rows without that *k* candidate)    `⍵×` multiply *M* with that mask    `+/∘,` sum the flattened matrix   `⍺=` Boolean indicating where *S* equals those sums   `⍸` indices where that's true [Answer] # [R](https://www.r-project.org/), ~~78~~ 73 bytes ``` function(m,s)m[Map(function(y)sum(m[(w=-which(m==y,T))[,1],w[,2]]),m)==s] ``` [Try it online!](https://tio.run/##XZBBisMwDEX3cxIL/oBlO7Gz8BG66y5k0QmEZuF2SFoyOX1GTqGtiy0LxH@y9KdtiNtwv/S38XpRCTOl9nD6Vc/SSvM9qdSqJX4v57E/qxTjiiNRC@6wtDBdR0gU49xtg0qn2zT@qV7VYFQSBgGNRIUaGo7g8LNO1yUeCQ19vRFetJwV5qXwhYKNtDGwYA9mcEAo1M5@NBSAtTAabEm4p5I/GsvHeh9WyzF7lkqJFETlZSdrEVy@PoAbsJMJ8hsYtoSNrQs8LyL8/sqE2R5JNfwjiQnV21qlT5VYqIUVNwWUYYufAm3/ "R – Try It Online") Does not sort or deduplicate the output. Credit to J.Doe & Giuseppe for -5 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ ~~19~~ ~~17~~ ~~15~~ 14 bytes ``` pZnⱮFȦ€€ḋFẹƓịF ``` This is a monadic link that takes **M** as argument and reads **S** from STDIN. [Try it online!](https://tio.run/##TVAxTgMxEOz3FX6Ai9tbX3z3geMPsVzSoAilTUtDkZI/UCGkdIGUkRDfuHzEzO7ZgGRpx7Mz61k/3O92h1L228fb6X3@fr09veEs5@O8fH58vSyX41yuz6DuykSRghBHYuplQ2GisaSUNt6xd0P2LqH23o0KJ9TKQtB5F3L25FKK0FRtoximwaxiHUgYbR511q@LV1tXp6KytAEWQRnt9Aa7@s5603YVD9GiiaAEVYzBuwiGkZmNCaIIfdik@daQtpz8Qc3TFlWMZeM/3FaEPGiE1WzfoS/b0n3OlH8A "Jelly – Try It Online") ### How it works ``` pZnⱮFȦ€€ḋFẹƓịF Main link. Argument: M Z Zip; transpose the rows and columns of M. p Take the Cartesian product of M and its transpose, yielding all pairs (r, c) of rows and columns of M. F Flatten; yield the elements of M. nⱮ Not equal map; for each element e of M, compare the elements of the pairs (r, c) with e. Ȧ€€ All each each; for each array of Booleans corresponding to an (r, c) pair, test if all of them are true. F Flatten; yield the elements of M. ḋ Take the dot product of each list of resulting Booleans and the elements of M. Ɠ Read an integer S from STDIN. ẹ Find all indices of S in the dot products. F Flatten; yield the elements of M. ị Retrieve the elements of the right at the indices from the left. ``` [Answer] # [Haskell](https://www.haskell.org/), ~~88~~ ~~86~~ ~~84~~ 77 bytes * -2 bytes thanks to [BWO](https://codegolf.stackexchange.com/questions/171550/get-me-out-of-here/171698?noredirect=1#comment414551_171698) * -7 bytes thanks to [Tesseract](https://codegolf.stackexchange.com/users/82692/tesseract) ``` m!s=[k|k<-m>>=id,s==sum[x|r<-m,all(/=k)r,(i,x)<-zip[0..]r,all((/=k).(!!i))m]] ``` [Verify all testcases](https://tio.run/##XZFRasMwDIbfewoH9hDDny6OndiFpjfYCTwzAhvMJC4haaGM3j2T3Q6W@EWy9OmXLH93c/81DMsSsrm1/b0/FuF0av0n5radr8He7hOF0A1D/tr2fELucePH4sePttzv3ZRSKbfPs8xzHpxb/Hm8XmbWMrtjz5Nb20CgdrACFQzZA0y6NyihnAM7cPznNapEp5xe50SFmmRkBDSEgDCkSZySWxGRVMrUqoSQkRJbORqNckRUZMvUOHoUTfiarjVNLiWMIswoaANxgIg3JcnCCMhUWMlmXRrHjm@XT0tzPZZATgP956Qnq80@aigaJ9bGfVFnWkAVQcMT5na70PkzrT1049sHy9/zADZzVpzYOPnzhb2wwLIYeXzQ8gs "Haskell – Try It Online"). ## Explanation ``` m ! s = -- function !, taking m and s as input [k | -- the list of all k's such that k <- m >>= id, -- * k is an entry of m s == sum -- * s equals the sum of [x | -- the list of x's such that r <- m, -- * r is a row of m all (/= k) r, -- * r does not contain k (i, x) <- zip [0 ..] r, -- * i is a valid column index; also let x = r[i] all ((/= k) . (!! i)) m -- * none of the rows contain k at index i ] ] ``` [Answer] # [Pyth](https://pyth.readthedocs.io), ~~27 23 22 21~~ 20 bytes ``` fqvzss.DRsxLTQ-I#TQs ``` **[Test suite!](https://pyth.herokuapp.com/?code=fqvzss.DRsxLTQ-I%23TQs&input=%5B%5B6%2C1%2C5%5D%2C%5B1%2C2%2C8%5D%2C%5B9%2C8%2C5%5D%2C%5B6%2C0%2C4%5D%5D%0A9&test_suite=1&test_suite_input=%5B%5B6%2C+1%2C+5%5D%2C+%5B1%2C+2%2C+8%5D%2C+%5B9%2C+8%2C+5%5D%2C+%5B6%2C+0%2C+4%5D%5D%0A9%0A%0A%5B%5B7%2C+2%5D%2C+%5B1%2C+4%5D%5D%0A7%0A%0A%5B%5B12%2C+5%2C+2%2C+3%5D%2C+%5B17%2C+11%2C+18%2C+8%5D%5D%0A43%0A%0A%5B%5B7%2C+12%5D%2C+%5B10%2C+5%5D%2C+%5B0%2C+13%5D%5D%0A17%0A%0A%5B%5B1%2C+1%2C+0%2C+1%5D%2C+%5B2%2C+0%2C+0%2C+2%5D%2C+%5B2%2C+0%2C+1%2C+0%5D%5D%0A1%0A%0A%5B%5B57%2C+8%2C+33%2C+84%5D%2C+%5B84%2C+78%2C+19%2C+14%5D%2C+%5B43%2C+14%2C+81%2C+30%5D%5D%0A236%0A%0A%5B%5B2%2C+5%2C+8%5D%2C+%5B3%2C+5%2C+8%5D%2C+%5B10%2C+8%2C+5%5D%2C+%5B10%2C+6%2C+7%5D%2C+%5B10%2C+6%2C+4%5D%5D%0A49%0A%0A%5B%5B5%2C+4%2C+0%5D%2C+%5B3%2C+0%2C+4%5D%2C+%5B8%2C+2%2C+2%5D%5D%0A8%0A&debug=0&input_size=3)** Does not deduplicate. ### How it works? ``` fqvzss.DRsxLTQ-I#TQs Full program. f s Flatten M and keep only those elements T which satisfy: qvzss.DRsxLTQ-I#TQ The filtering function. Breakdown: -I#TQ Discard the rows that contain T. More elaborate explanation: # Q |-> In M, keep only those elements that are... I |-> Invariant under (equal to themselves after...) - T |-> Removing T. Let's call the result of this expression CR (chopped rows). xLTQ Map over the rows M and retrieve all indices of T. s Collect indices in 1D list (flatten). Call this I. .DR For each row left in CR, remove the elements at indices in I. ss Sum all the elements of this matrix flattened. qvz And then finally check whether they equal S. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~114~~ 108 bytes ``` lambda m,s:{a for a in sum(m,[])if s==sum(v for l in m for i,v in enumerate(l)if{a}-set(l)-set(zip(*m)[i]))} ``` [Try it online!](https://tio.run/##XVDLaoRAELzvVwzkoqECzkNnDPglxoMhSgTHFXUXEvHbTU@7IZhTv6qqu2v8Wj6vg9rb4m3va//@UQuP@XWtRXudRC26Qcw3H3mUVdy1Yi6KUN552oep57TDPRTNcPPNVC9N1BN6rbeXuVko5/DdjdGzj8uuiuNtH6duWEQblWUGibRCKaHgKOZwXGdIYKoKIo8vT2Il0Ha5/NEsFJMYYhliTgCpkJKkDigLKSEd6RPYaEb/l5Osl/DuBFIHqDyEQ3nWppupSUhFMeFTQkZdpjFLnSippb@0hjOEdQbWQeaQoTKaIpyEZrbS2fFxDpqk9iQTngou6Uekgw@7KMlgfxN2xRzOkQegfedrqJOwTDCZDiKnVOC4x8MHiXZs@w8 "Python 2 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~80~~ 74 bytes ``` ->\m,\s{grep {s==sum m[m.$_;[[Z](m).$_]]}o{*.grep(:k,!*.grep($_))},m[*;*]} ``` [Try it online!](https://tio.run/##NU/LboMwELz3K1wpqgBNItY22BTRD6ljRT2EHlorEaiHiPDtdG3gtOt57Hju1@G3XsJDvPWiW44f54DzOH0P17uYxq4b/4IILpwOl9a5T5@FnFfv59tUnKIoe//B67YeLnk@I7iiLfy8jF8P0WdPBkV/G14y52oQKg9HkLA8G9j0rlFCew/R5Ig6A5lUCTMrRhIV21QkDIhAlm8wr9VuouQq08kSpCJLu52jGWNG8ixTQNwYTbJVVRn@kVKwmmmrYSyoAcWXVjxhCSoZpKpXS/xW7KK2yflrKV5qmH1JVfTWr4Lm2OiJvTmJi8kosMy3yz8 "Perl 6 – Try It Online") ### Explanation ``` ->\m,\s{...} # Anonymous block taking arguments m and s grep {...}o{...},m[*;*] # Filter matrix elements # with combination of two functions *.grep(:k,!*.grep($_)) # (1) Whatever code returning matching rows s==sum m[ # (2) s equals sum of elements m.$_; # in matched rows [ # (array supporting multiple iterations) [Z](m).$_ # and matched columns (matched rows # of m transposed with [Z]) ] ] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes ``` ²˜ʒQεZ+}øεZ<~}ø_*OO¹Q ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0KbTc05NCjy3NUq79vAOIGVTB6Tjtfz9D@0M/P/fkis62kzHUMc0VifaUMdIxwJIW@pYgPlmOgY6JrGxAA "05AB1E – Try It Online") Only after I've written this answer have I seen [Kevin's](https://codegolf.stackexchange.com/a/171762/59487). I believe this is substantially different, so I am posting it separately. My intuition says that the optimal byte count is around 18, so I'll have to revisit this and see what else I can do. With the current code, it is impossible to write a test suite but I have verified all test cases myself and the results are correct. ### Cropping Algorithm To better illustrate the technique used, let's grab an example, with the element to crop \$k=5\$: $$M=\left(\begin{matrix}6&1&\bbox[green,1pt]{\color{white}{5}}\\1&2&8\\9&8&\bbox[green,1pt]{\color{white}{5}}\\6&0&4\end{matrix}\right)$$ It first generates the matrix of equality with \$k\$: $$\left(\begin{matrix}0&0&1\\0&0&0\\0&0&1\\0&0&0\end{matrix}\right)$$ Then, it goes through \$M\$ and for each row \$R\$, it adds \$\max(R)\$ to each element in \$R\$, highlighting the necessary rows while still preserving the uniqueness of the horizontal positions of the searched element: $$\left(\begin{matrix}\color{green}{1}&\color{green}{1}&\bbox[green,1pt]{\color{white}{2}}\\0&0&0\\\color{green}{1}&\color{green}{1}&\bbox[green,1pt]{\color{white}{2}}\\0&0&0\end{matrix}\right)$$ Then, it goes through the transpose of \$M\$ and for each column \$C\$, it performs the operation \$(\max(C)-1)\space ||\space c\space\forall\space c\in C\:\$ (where \$||\$ is 05AB1E's bitwise OR – addition should work too, so replace `~` with `+` if you want to test that too), which results in: $$\left(\begin{matrix}\color{green}{1}&\color{green}{1}&\bbox[green,1pt]{\color{white}{3}}\\0&0&\color{green}{1}\\\color{green}{1}&\color{green}{1}&\bbox[green,1pt]{\color{white}{3}}\\0&0&\color{green}{1}\end{matrix}\right)$$ Finally, it maps \$0\$ to \$1\$ and all other integers to \$0\$ and performs element-wise multiplication with \$M\$: $$\left(\begin{matrix}\color{green}{0}&\color{green}{0}&\color{green}{0}\\1&1&\color{green}{0}\\\color{green}{0}&\color{green}{0}&\color{green}{0}\\1&1&\color{green}{0}\end{matrix}\right)\:\longrightarrow\:\left(\begin{matrix}\color{green}{0}&\color{green}{0}&\color{green}{0}\\1&2&\color{green}{0}\\\color{green}{0}&\color{green}{0}&\color{green}{0}\\6&0&\color{green}{0}\end{matrix}\right)$$ After which the sum of the resulting matrix is computed. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~27~~ 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ˜ʒ©¹ε®å_}¹ζʒ®å_}ζ‚ζ€€OPOIQ ``` Does not sort nor uniquify the result. Only works in the legacy (for now), because sum-each seems to be doing some odd things when part of the inner lists are integers and other are lists.. [Try it online](https://tio.run/##MzBNTDJM/f//9JxTkw6tPLTz3NZD6w4vja8FsrYBRcDsc9seNcwCEk1rgMg/wN8z8P//6GhDHUMdAx3DWJ1oIyBtoGMEZQFFY2O5DAE) or [verify all test cases](https://tio.run/##NU@7TgMxEOzvK6zUU3j9OPto0kRIqQIF6CLrhIKgzR9EQnwCJaKlQELpkg8IHUj3EfzIMWtAsrwzu7M7uzZubuV@yufLxdXy2vTzmdls78xsviYyZ4Zo@nr5fDq99ePhtP94vdn145G8wvH4/fDM7/Gdb3WxWl9OO0yltBDEAUXgkBk75MpbWIRhaLqmlARXFcoTuThEyr0mE0Qgmb1DE3wVS1XbOsZCPCtS22hFzqxjtHWoImZVQkVMdPceObCUA1KGdBBlwTMiC7yKnW8p1zV0Z/8X6fm7PEGL9A907aB3RARaqV5vowOPcCzmHw). **Explanation:** ``` ˜ # Flatten the (implicit) matrix-input # i.e. [[6,1,5],[1,2,8],[9,8,5],[6,0,4]] → [6,1,5,1,2,8,9,8,5,6,0,4] ʒ # Filter this list by: © # Store the current value in a register-variable ¹ # Take the matrix-input ε } # Map it to: ®å_ # 0 if the current number is in this row, 1 if not # i.e. [[6,1,5],[1,2,8],[9,8,5],[6,0,4]] and 6 → [0,1,1,0] ¹ # Take the matrix-input again ζ # Swap its rows and columns # i.e. [[6,1,5],[1,2,8],[9,8,5],[6,0,4]] → [[6,1,9,6],[1,2,8,0],[5,8,5,4]] ʒ } # Filter it by: ®å_ # Only keep the inner lists that does not contain the current number # i.e. [[6,1,9,6],[1,2,8,0],[5,8,5,4]] and 6 → [[1,2,8,0],[5,8,5,4]] # i.e. [[1,2,2],[1,0,0],[0,0,1],[1,2,0]] and 1 → [] ζ # After filtering, swap it's rows and columns back again # i.e. [[1,2,8,0],[5,8,5,4]] → [[1,5],[2,8],[8,5],[0,4]] ‚ζ # Pair both lists together and zip them # i.e. [0,1,1,0] and [[1,5],[2,8],[8,5],[0,4]] # → [[0,[1,5]],[1,[2,8]],[1,[8,5]],[0,[0,4]]] # i.e. [0,1,0] and [] → [[0,' '],[1,' '],[0,' ']] € # Map each inner list / value to: €O # Sum each # i.e. [[0,[1,5]],[1,[2,8]],[1,[8,5]],[0,[0,4]]] # → [[0,6],[1,10],[1,13],[0,4]] # i.e. [[0,' '],[1,' '],[0,' ']] # → [[0,0],[1,0],[0,0]] # (NOTE: For most test cases just `O` instead of `€€O` would be enough, # but not if we removed ALL zipped inner lists for a number, like the # second example above with input [[1,1,0,1],[2,0,0,2],[2,0,1,0]] and 1) P # Now take the product of each inner list # i.e. [[0,6],[1,10],[1,13],[0,4]] → [0,10,13,0] O # Then take the sum of those # i.e. [0,10,13,0] → 23 IQ # And only keep those that are equal to the number-input # i.e. 23 and 9 → 0 (falsey), so it's removed from the flattened input ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` =+Ṁ$€Z$⁺’¬×⁸FS F³ç=⁹ƲƇ ``` [Try it online!](https://tio.run/##y0rNyan8/99W@@HOBpVHTWuiVB417nrUMPPQmsPTHzXucAvmcju0@fBy20eNO49tOtb@////aDMdQx3TWJ1oQx0jHQsgbaljAeab6RjomMT@twQA "Jelly – Try It Online") -6 bytes using the general approach from Mr. Xcoder's 05AB1E answer. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` FθFι⊞υκIΦυ⁼ηΣEθ∧¬№λιΣEλ∧¬№Eθ§πξιν ``` [Try it online!](https://tio.run/##XYwxD4IwEIV3f8WN1@RMgJXJEE0cNCSODUMDGBprC6U1/PtaEKLxlnf33veu7oStjVAh3I0FHBgsKle9GoeF8dqhJ3gwxqD0Y/c58l1pZUwKMTo8SeVaOwfHwQs1Ykdw80@8iB4HgoNufn4pAsnYF1D/wNZyZ920E/YE08wvJc22yUPgnKeUUkJpRTyLmlC2btGtquiH/Uu9AQ "Charcoal – Try It Online") Link is to verbose version of code and includes deduplication. Explanation: ``` FθFι⊞υκ ``` Flatten the first input array `q` into the predefined list `u`. ``` υ Flattened array Φ Filter elements θ Input array E Map over rows ι Current element λ Current row № Count matching elements ¬ Logical Not ∧ Logical And λ Current row E Map over columns θ Input array E Map over rows π Inner row ξ Column index § Inner element ι Current element № Count matching elements ¬ Logical Not ∧ Logical And ν Current element Σ Sum Σ Sum η Second input ⁼ Equals I Cast to string Implicitly print each result on its own line ``` For each element of the list, sum the array, but if the row contains the element then use `0` instead of its sum, and when summing rows that don't contain the element, if the column contains the element then use `0` instead of the column's value. This is very slightly golfier than filtering the elements out as Charcoal can't sum an empty list. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 92 bytes ``` import StdEnv $m s=[c\\r<-m,c<-r|sum[b\\a<-m|all((<>)c)a,b<-a&x<-[0..]|all(\u=u!!x<>c)m]==s] ``` [Try it online!](https://tio.run/##RY1NawIxEIbv@ysiSnFhIioqCoknPRR685jkMMZVAklW8iEr@NubBlvoaXhmnvcdbTv0xfWXbDvi0Phi3L0PiZzS5egfzcSRyIWWMjDqQDMaXjE7cZYS6@KF1k6nbN/qFuHMKH4MjIr5bKbeF5l5Ho0GttetU5xHVU4JQ2rG9VMKZiCcCLGBBawViAUsYVvnDrZv3sAcVkpVuWZuXaryrsI1e51M7ytOGv6Pf42/bvnWV4u3WOjnVzk8PTqj4w8 "Clean – Try It Online") Explained: ``` $ m s // the function $ of `m` and `s` = [ // is equal to c // the value `c` \\ r <- m // for every row `r` in `m` , c <- r // for every value `c` in `r` | sum [ // where the sum of b // the value `b` \\ a <- m // for every row `a` in `m` | all ((<>)c) a // where `c` isn't in `a` , b <- a // for every value `b` in `a` & x <- [0..] // with every column index `x` from zero | all (\u = u!!x <> c) m // where `c` isn't in column `x` ] == s // equals `s` ] ``` [Answer] ## MATLAB - 80 bytes (*Corrected and*) Compacted: ``` function f(M,s);for k=M(:)';if sum(sum(M(~sum(M==k,2),~sum(M==k))))==s;k,end;end ``` And in a fully developped version: ``` function getthesum(M,s) for k=M(:)' % For each element of M x = M==k ; % Index elements equal to "k" N = M( ~sum(x,2) , ~sum(x) ) ; % New matrix with only the appropriate rows/columns if sum(sum(N))==s % sum rows and columns and compare to "s" k % display "k" in console if "k" is valid end end ``` --- Thanks to the comments to highlight my initial mistake. Note that this version does not de-duplicate the output. It is possible to deduplicate the output with 5 more bytes: ``` % This will only cycle through the unique elements of 'M' (85 bytes): function f(M,s);for k=unique(M)';if sum(sum(M(~sum(M==k,2),~sum(M==k))))==s;k,end;end ``` ]
[Question] [ [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle) is generated by starting with `1` and having each row formed from successive additions. Here, instead, we're going to form a triangle by alternating multiplication and addition. We start row `1` with just a solitary `1`. Thereafter, addition is done on the odd rows, and multiplication is done on the even rows (1-indexed). When performing the addition step, assume the spaces outside of the triangle are filled with `0`s. When performing the multiplication step, assume that the outside is filled with `1`s. Here's the full triangle down to 7 rows. The `*` or `+` on the left shows what step was performed to generate that row. ``` 1 1 2 * 1 1 3 + 1 2 1 4 * 1 2 2 1 5 + 1 3 4 3 1 6 * 1 3 12 12 3 1 7 + 1 4 15 24 15 4 1 ``` ## Challenge Given input `n`, output the `n`th row of this triangle. ## Rules * You may choose to 0-index instead, but then please realize that the addition and multiplication rows must flip-flop, so that the exact same triangle is generated as above. Please state in your submission if you choose to do this. * The input and output can be assumed to fit in your language's native integer type. * The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an online testing environment so other 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 Showing two possible examples of output out of many: a list, or a space separated string. ``` 4 [1, 2, 2, 1] 8 "1 4 60 360 360 60 4 1" ``` [Answer] # [Pascal](https://www.freepascal.org/), ~~249~~ ~~247~~ 233 bytes *Well, this is **Pascal's** alternating triangle.* *1 byte saved thanks to @Mr.Xcoder* ``` function f(n,k:integer):integer;begin if((k<1)or(k>n)or(n=1))then f:=n mod 2 else if n mod 2=0then f:=f(n-1,k-1)*f(n-1,k)else f:=f(n-1,k-1)+f(n-1,k)end; procedure g(n:integer);var k:integer;begin for k:=1to n do write(f(n,k),' ')end; ``` [Try it online!](https://tio.run/##XY/NUsMgFIX3eYqzK2jiiCsniO8SE0AkvWQobR8/3tCmM7qBc3/Ox2EZTuMwd24Z1yUnn4cjltrSqzvTWEIiOEFt7AMV622Wu9Bf1gdCcELEDyVTFvGTtouMkrJ8Wzb2hnBME95g55PlXdxr87ovMLxTbeyUfLpLWXf/jJ4fI5p0w0FHO52zhRf0yKUvQ0b8l86lrWdUSfzylHDNoVhRPyTbAw4VuLKzAUKLnx67v6kAbm@IgN5AgSnvG@XG9iJIfSPOJFjWcHy8rL8) [Answer] # [Python 2](https://docs.python.org/2/), ~~97~~ ~~93~~ ~~86~~ ~~81~~ 78 bytes *-4 bytes thanks to Rod. -10 bytes thanks to Halvard Hummel.* ``` f=lambda n:n and[[i+j,i*j][n%2]for i,j in zip([n%2]+f(n-1),f(n-1)+[n%2])]or[1] ``` 0-indexed. [Try it online!](https://tio.run/##JYtBCsMgFAX3OcXbFLTaRdJFIZCTfFwYUumX9ivGTXp5S@xqYIbJR30lmVoLy9t/1s1DZoGXjYhNtHyNjuQyuZAK2Eaw4MtZdWeCktuo7R@mO@1SodG1@tzrjgV0t3i4Yej/efcwIxeWiqBYtx8 "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 12 bytes ``` µ×+LḂ$?Ḋ1;µ¡ ``` This is a full program (or niladic link) that takes input from STDIN. [Try it online!](https://tio.run/##AR4A4f9qZWxsef//wrXDlytM4biCJD/huIoxO8K1wqH//zc "Jelly – Try It Online") ### How it works ``` µ×+LḂ$?Ḋ1;µ¡ Main link. No arguments. Implicit argument: 0 µ¡ Start a monadic chain and apply the ntimes quick to the previous one. This reads an integer n from STDIN and executes the previous chain n times, with initial argument 0, returning the last result. µ Start a monadic chain. Argument: A (array or 0) Ḋ Dequeue; yield A without its first element. LḂ$? If the length of A is odd: × Multiply A and dequeued A. Else: + Add A and dequeued A. 1; Prepend a 1 to the result. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~96 89~~ 87 bytes * 2 bytes Thanks to Mr. Xcoder: `s=[1]` * A bit different than [totallyhuman's answer](https://codegolf.stackexchange.com/a/138230/59523) ``` s=a=[1] for i in range(1,input()):a=s+[[k+l,k*l][i%2]for k,l in zip(a[1:],a)]+s print a ``` [Try it online!](https://tio.run/##Fco7DoAgDADQ3VOwmICw4GJiwkmaDh38NJBKAAe9PMY3v/y085K59xoogMdhv4pixaIKybFp71jy3bQxK4VqAaJNLk4JgccZ/xxd@vvLWRP4FR0ZtHXIhaUp6n35AA "Python 2 – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 25 bytes ``` {1a\{2%!_2$+\{.*}{.+}?}/} ``` 0-indexed. [Try it online!](https://tio.run/##S85KzP1fWPe/2jAxptpIVTHeSEU7plpPq7ZaT7vWvla/9n9dwX8zAA "CJam – Try It Online") ### Explanation This is an anonymous block that takes the number from the stack and leaves the result on the stack. ``` 1a Push [1]. \ Bring the number to the top. { }/ For reach number 0 .. arg-1, do: 2%! Push 0 if even, 1 if odd. _ Copy that. 2$+ Copy the list so far and prepend the 0 or 1 to it. \ Bring the 0 or 1 back to the top. {.*}{.+}? If 1, element-wise multiplication. If 0, element-wise addition. ``` [Answer] # Mathematica, 92 bytes ``` (s={i=1};While[i<#,s=Flatten@{1,{Tr/@#,Times@@@#}[[i~Mod~2+1]]&@Partition[s,2,1],1};i++];s)& ``` [Try it online!](https://tio.run/##DcyxCsMgEADQXykIocWDYqZCKtyUrZAh0EEcpDXkwCjkbpPk123fB7wtyEofbottV7aVrDmG90opOnoqYDumIBIzVgN1LhLSHRXMtEVGRHU4R@erfM9eG@87nMIuJFSyY@jBePhvpLUf@Na1aacsF1zcw7cf "Mathics – Try It Online") (in order to work on mathics "Tr" is replaced with "Total") [Answer] # [Haskell](https://www.haskell.org/), ~~76~~ 72 bytes 0-indexed solution: ``` (p!!) p=[1]:[zipWith o(e:l)l++[1]|(l,(o,e))<-zip p$cycle[((*),1),((+),0)]] ``` [Try it online!](https://tio.run/##DcmxDoIwEIDh3ac4Eoc7KUYmE9JOvACbJsjQ4AENZ2mgi8ZntzL8y/dPdptZJA3mkTBkGR2Cacuuaj8u3FycYEGuhCTPd/2iKFwUE@li/xCO/bsXbhFPpEpSiDmpC3VdelnnwUBYnY9whmFvZfsEozWMHOvFR/ZxS9dfP4gdt1Tc66b5Aw "Haskell – Try It Online") ### Explanation `p` recursively defines the alternating triangle, the base case/first element of it is `[1]` ``` p=[1]:[ ] ``` It then builds the triangle by taking the previous line (`l`). To know what to do with it we need to keep track of the correct operator (`o`) and the corresponding neutral element (`e`): ``` |(l,(o,e))<-zip p$cycle[((*),1),((+),0)] ``` From this build the new line by duplicating the line and for one copy we prepend the neutral element, zip them with the operator and append a 1: ``` zipWith o(e:l)l++[1] ``` [Answer] # [R](https://www.r-project.org/), ~~108~~ 98 bytes *-10 bytes by replacing the actual multiply sign with a plus sign. Please forgive me.* ``` f=function(n){if(n<3)return(rep(1,n))else{v=f(n-1)};if(n%%2)`*`=`+`;return(c(1,v[3:n-2]*v[-1],1))} ``` [Try it online!](https://tio.run/##LcpNCoMwEEDhvfcQZqxZTNI/anMSEQKSAaFMS6rZiGePDrj5Nu@lUtjzIuM8fQUE14lB3g5TnJckkOIPqBXE@PnHNfsjGsKt06uuLYYm@HAJ3bmPx5x79xJjhyb3hoaWELfCQFgxWMUpV@Wm3JWH8sSq7A "R – Try It Online") Quite pleased with the general method (first time I've aliased a primitive) but I'm sure there's golfing to be done on it yet, especially with the awkward handling of cases where n<3 which leads to a lot of boilerplate. [Answer] ## [Husk](https://github.com/barbuz/Husk), ~~17~~ 16 bytes ``` !G₅;1¢e*+ :1Sż⁰t ``` [Try it online!](https://tio.run/##ASgA1/9odXNr/yBt4oKB4bijMTD/IUfigoU7McKiZSorCjoxU8W84oGwdP// "Husk – Try It Online") A 1-indexed solution. ## Explanation The first line is the main function, which calls the helper function on the second line. The helper function is usually called with `₁`, but in this case I'm using the *overflowing labels* feature of Husk: if you refer to a line **N** in a program with **M < N** lines, you get line **N mod M** with modifier function **M / N** applied to it. The second modifier function is `flip`, so I'm using `₅` to flip the arguments of the helper function with no additional byte cost. Here is the helper function. ``` :1Sż⁰t Takes a function f and a list x. ż Zip preserving elements of longer list ⁰ using function f S t x and its tail, :1 then prepend 1. ``` Here is the main function. ``` !G₅;1¢e*+ Takes a number n. e*+ 2-element list of the functions * and + ¢ repeated infinitely. G Left scan this list ₅ using the flipped helper function ;1 with initial value [1]. ! Get n'th element. ``` [Answer] # [Python 2](https://docs.python.org/2/), 83 bytes Give some love to `exec` 0-indexed ``` l=[1];exec"l[1:]=[[a+b,a*b][len(l)%2]for a,b in zip(l,l[1:])]+[1];"*input() print l ``` [Try it online!](https://tio.run/##HctBCoAgEADAe6@QIND0opeg6CXLHjSMhGWTMKg@b9R9Jt9l29nVSjNYnOIVl5bAjjgDeB2M7wMCRZakOofrfghvgkgsnpQlmZ8q1N9t@8T5LFI1@UhcBNU6vA) [Answer] # [Pyth](https://pyth.herokuapp.com), 22 bytes Saved tons of byte thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman)! The initial solution is below. ``` u++1@,+VGtG*VGtGlG1Q[1 ``` **[Full Test Suite (0-indexed).](https://pyth.herokuapp.com/?code=u%2B%2B1%40%2C%2BVGtG%2aVGtGlG1Q%5B1&input=7&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7&debug=0)** # [Pyth](https://pyth.readathedocs.io), ~~40 38 36~~ 35 bytes This feels ~~waaaaaaaay too~~ reasonably long. Suggestions are welcome. ``` K]1VStQ=K++]1m@,sd*hded%N2C,KtK]1;K ``` **[Test Suite](https://pyth.herokuapp.com/?code=K%5D1VStQ%3DK%2B%2B%5D1m%40%2Csd%2ahded%25N2C%2CKtK%5D1%3BK&input=5&test_suite=1&test_suite_input=1%0A%0A2%0A%0A3%0A%0A4%0A%0A5%0A%0A6%0A%0A7%0A&debug=0&input_size=2)** or **[Try it online!](http://pyth.herokuapp.com/?code=K%5D1VStQ%3DK%2B%2B%5D1m%40%2Csd%2ahded%25N2C%2CKtK%5D1%3BK&input=5&test_suite_input=1%0A%0A2%0A%0A3%0A%0A4%0A%0A5%0A%0A6%0A%0A7%0A&debug=0&input_size=2)** [Answer] # [J](http://jsoftware.com/), 32 bytes ``` [:(1,]{::(}.@,-.)(*;+)[)~/2|]-i. ``` [Try it online!](https://tio.run/##y/r/P03B1koh2krDUCe22spKo1bPQUdXT1NDy1pbM1qzTt@oJlY3U4@LKzU5I19BycohTclAwc5KIVNPwfz/fwA "J – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 111 + 2 (-na) = 113 bytes ``` sub t{($r,$c)=@_;!--$r||!$c||$c>=$r?1:eval"t($r,$c)".($r%2?"*":"+")."t($r,$c-1)"}say map{t($F[0],$_).$"}0..$_-1 ``` [Try it online!](https://tio.run/##NYpBCsIwEAC/0i4rGO2GRChIpdaTN18gEmLooVDbkERBmn7d2IPehpmxrevLlPzznoVpja5Aw@qTOuRE6GLM0cSI5lija2TVvnQP4XcBX2C1a2ADFWyB8X8hyWD2@p09tJ0Wd76KW4GKcYRZcI6KZEr7z2hDNw4@0aXkQopEg/4C "Perl 5 – Try It Online") [Answer] # Mathematica, 70 bytes ``` Fold[#2@@@Partition[#,2,1,{-1,1},{}]&,{1},PadRight[{},#,{1##&,Plus}]]& ``` Try it at the [Wolfram sandbox](https://sandbox.open.wolframcloud.com/)! It doesn't work in Mathics, unfortunately. It's 0-indexed. Explanation: `Partition[#,2,1,{-1,1},{}]` takes a list and returns all the two-element sublists, plus 1-element lists for the start and end — e.g., `{1,2,3,4}` becomes `{{1}, {1,2}, {2,3}, {3,4}, {4}}`. `PadRight[{},#,{1##&,Plus}]` makes an alternating list of `1##&` (effectively `Times`) and `Plus`, whose length is the input number. Then `Fold` repeatedly applies the partition function with the `Plus`es and `Times`es applied to it, to make the rows of the triangle. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~143~~ ~~134~~ 128 bytes *-4 bytes thanks to [Phaeze](https://codegolf.stackexchange.com/users/19547/phaeze)* *-5 bytes thanks to [Zac Faragher](https://codegolf.stackexchange.com/users/56606/zac-faragher)* ``` n=>{int[]b={1},c;for(int i=0,j;++i<n;b=c)for(c=new int[i+1],c[0]=c[i]=1,j=0;++j<i;)c[j]=i%2<1?b[j-1]+b[j]:b[j-1]*b[j];return b;} ``` [Try it online!](https://tio.run/##ZVBdS8MwFH3Pr7gOhMZ2ZZ3fppmIuKcJooIPpQ9tlrlbunQmqVNGf3vth0yK5yE5Offcj1xhxqLQsi4Nqnd4@TZWbvwFqg9GiEo20mwTIX91sifQQOSJMXDX8V5pYWxiUcBngUt4TFA59BD6M7WYl0qEqKwHzRHFM1gBrxWf7btnyvdB5Qm2KrTTCIB84mXMdTFULOWCtrrgSu66bHSD2BPRJOYiwpgHXsYnjTkLkVERZTHH42kY3KZRNg5it7nim56ftJxpaUutIGVVzQYzGqvbdaDalnYY2a0xl@A4XQg43BfKFLn0n2WybNYmHUrhiIMq85wOEodLaLFqP@g/JdrIvhyl/muxQGMd6s8L/ZCItfMFfHZo8qbRykZyYQQjStm/kgNjP87QVJEhq0hVB2RKTskZOScX5JJckWsSTH4A "C# (.NET Core) – Try It Online") Explanation: ``` n => { int[] b = { 1 }, c; // Create first layer for(int i = 0, j; ++i < n; b = c) // Iterate for every layer, replace last layer with a new one for(c = new int[i+1], // Create new layer c[0] = c[i] = 1, // First and last elements are always 1 j = 0; ++j < i; ) // Replace every element (besides 1st and last)... c[j] = i % 2 == 0 ? b[j - 1] + b[j] : // ... with addition... b[j - 1] * b[j]; // ... or multiplication of two from previous layers return b; // Return latest layer }; ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~83~~ 82 bytes ``` ->n{a=[1];p=0;n.times{a=[p=1-p,*a,p].each_cons(2).map{|x|x.reduce([:+,:*][p])}};a} ``` [Try it online!](https://tio.run/##HcvRCoMgFADQ977CR2110T0m9iMiw6kxoexSCxrptzu21wNnO56fOqnaj@mySgsjUXGZ4B2XsP8Eleixa22HBoJ1r4db007vDBaLVz7zCVvwhwtUD7duaI1Gw0qRtlTKAQRn/0X8SnLMDSFIJnB2nklsQvL1Cw "Ruby – Try It Online") This is 0-indexed. [Answer] # [Racket](https://racket-lang.org/), 116 bytes ``` (define(t n[i 1][r'(1)])(if(= n 1)r(t(- n 1)(- 1 i)(cons 1(append(map(if(> i 0)* +)(cdr r)(reverse(cdr r)))'(1)))))) ``` [Try it online!](https://tio.run/##Lc3NDsIwCADgu09B4kHQmIi/J32RZYdmZaZRsWGNr187lMMHBAIWhoeUunwGvYP9GowyJhUsoF0C7jtbIVNPmEa8ggKTYcGtVy0xJMLhrRMwhpxFI75CnpdvkGBHa9i0eTQwQpOP2CT/lmg@7FHbN6ZFc@8e3KN7cs/uheoX "Racket – Try It Online") [Answer] # TI-Basic (TI-84 Plus CE), 100 bytes ``` Prompt X {1→M For(A,2,X LM→L A→dim(M For(B,2,A–1 If A/2=int(A/2 Then LL(B–1)LL(B→LM(B Else LL(B–1)+LL(B→LM(B End End 1→LM(dim(LM End LM ``` 1-indexed, prompts user for input and prints a list containing the `n`th row of Pascal's Alternating Triangle. While looping: LM is the current row, and LL is the previous row. TI-Basic is a [tokenized language](http://tibasicdev.wikidot.com/one-byte-tokens). All tokens used here are one-byte tokens. I think I can golf this further by modifying M in-place from the end. Explanation: ``` Prompt X # 3 bytes; get user input, store in X {1→M # 5 bytes, store the first row into LM For(A,2,X # 7 bytes, Loop X-1 times, with A as the counter, starting at 2 LM→L # 5 bytes, copy list M into list L A→dim(M # 5 bytes, extend M by one For(B,2,A–1 # 9 bytes, for each index B that isn't the first or last... If A/2=int(A/2 # 10 bytes, if A is even... Then # 2 bytes, then... LL(B–1)LL(B→LM(B # 17 bytes, the Bth item in this row is the Bth times the (B-1)th of the previous row Else # 2 bytes, else... LL(B–1)+LL(B→LM(B # 18 bytes, the Bth item in this row is the Bth plus the (B-1)th of the previous row End # 2 bytes, endif End # 2 bytes, endfor 1→LM(dim(LM # 9 bytes, the last item is always 1 End # 2 bytes, endfor LM # 2 bytes, Implicitly print the final row ``` [Answer] # JavaScript (ES6), ~~71~~ ~~69~~ 66 bytes ``` f=n=>n?(p=f(n-1),[...p.map((v,i)=>i--?n%2?v*p[i]:v+p[i]:1),1]):[1] ``` [Try it online!](https://tio.run/##HcoxDsIgFADQvaf4i8lHChHHVspBCAOpxXxTgVDDYjw7Eqe3vKev/lgL5beI6b61FnTUSzSYdcAoFButlDLLl8@IdSSmFxLCxNPV1HO25KbK//SpHJusci2kAlh9AQINl7lzA9XlnBh8BoA1xSPtm9zTAwMSY/PwbT8 "JavaScript (Node.js) – Try It Online") 0-indexed. **-3 bytes** by @Arnauld ``` f=n=>n?(p=f(n-1),[...p.map((v,i)=>i--?n%2?v*p[i]:v+p[i]:1),1]):[1] for (var i = 0; i < 10; ++i) { console.log(JSON.stringify(f(i))); } ``` ]
[Question] [ The task is the following. Given an integer `x` (such that `x` modulo `100000000003` is not equal to `0`) presented to your code in any way you find convenient, output another integer `y < 100000000003` so that `(x * y) mod 100000000003 = 1`. You code must take less than 30 minutes to run on a standard desktop machine for *any* input `x` such that `|x| < 2^40`. **Test cases** Input: 400000001. Output: 65991902837 Input: 4000000001. Output: 68181818185 Input: 2. Output: 50000000002 Input: 50000000002. Output: 2. Input: 1000000. Output: 33333300001 **Restrictions** You may not use any libraries or builtin functions that perform modulo arithmetic (or this inverse operation). This means you can't even do `a % b` without implementing `%` yourself. You can use all other non-modulo arithmetic builtin functions however. **Similar question** This is similar to [this question](https://codegolf.stackexchange.com/questions/215/compute-modular-inverse?rq=1) although hopefully different enough to still be of interest. [Answer] # Pyth, 24 bytes ``` L-b*/bJ+3^T11Jy*uy^GT11Q ``` [Test suite](https://pyth.herokuapp.com/?code=L-b%2a%2FbJ%2B3%5ET11Jy%2auy%5EGT11Q&test_suite=1&test_suite_input=2%0A3%0A1000000%0A50000000002&debug=0) This uses the fact that a^(p-2) mod p = a^-1 mod p. First, I manually reimplement modulus, for the specific case of mod 100000000003. I use the formula `a mod b = a - (a/b)*b`, where `/` is floored division. I generate the modulus with `10^11 + 3`, using the code `+3^T11`, then save it in `J`, then use this and the above formula to calculate b mod 100000000003 with `-b*/bJ+3^T11J`. This function is defined as `y` with `L`. Next, I start with the input, then take it to the tenth power and reduce mod 100000000003, and repeat this 11 times. `y^GT` is the code executed in each step, and `uy^GT11Q` runs it 11 times starting with the input. Now I have `Q^(10^11) mod 10^11 + 3`, and I want `Q^(10^11 + 1) mod 10^11 + 3`, so I multiply by the input with `*`, reduce it mod 100000000003 with `y` one last time, and output. [Answer] # [Haskell](https://www.haskell.org/), 118 113 105 101 bytes Inspired from [this solution](https://codegolf.stackexchange.com/a/129721/31975). *-12 from Ørjan Johansen* ``` p=10^11+3 k b=((p-2)?b)b 1 r x=x-div x p*p (e?b)s a|e==0=a|1<2=(div e 2?b$r$s*s)$last$a:[r$a*s|odd e] ``` [Try it online!](https://tio.run/##HclLDoIwFAXQOau4gw5ahITWmfHJClwBonkNTSRAbVpiGLD3@jnT8@Q0uXnOOZBu7lofjsUES1KG2qjWKgtdRGy01cP4xoZQhkK6byTw7oga4l2fDclfO5jWiihSmZSYOa2CT10UXKb9NQxwfV549CAsHK4PyJtHfUGIo18hfYUJXil0ptLNX58/ "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 48 bytes A rewrite of [this solution](https://codegolf.stackexchange.com/a/129731/31975). While fast enough for the test vector, this solution is too slow for other inputs. ``` s x=until(\t->t-t`div`x*x==0)(+(10^11+3))1`div`x ``` [Try it online!](https://tio.run/##NclBCsIwEEbhq/zLiU0gU3GZ3sATWGsDCgbToTSj5PbpovhWH7x3LJ9Xzq0V1PAVTZlGdYM6nZ/pN9dTDcEb6oj9xNydjeFjtCUmQcAS1@sDNArcgHVLoiCxKBBjcOvtxf/rLR@4tx0 "Haskell – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 22 bytes ``` ∧10^₁₁+₃;İ≜N&;.×-₁~×N∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HHckODuEdNjUCk/aip2frIhkedc/zUrPUOT9cFitUdnu4HVPP/v9H/KAA "Brachylog – Try It Online") This took about 10 minutes for `1000000` with a slightly different (and longer) version of the code which was exactly two times faster (checked only positive values of `İ` instead of both positive and negatives). Therefore this should take about 20 minutes to complete for that input. ### Explanation We simply describe that `Input × Output - 1 = 100000000003 × an integer`, and let constraint arithmetic find `Output` for us. ``` ∧10^₁₁+₃ 100000000003 ;İ≜N N = [100000000003, an integer (0, then 1, then -1, then 2, etc.)] &;.× Input × Output… -₁ … - 1… ~×N∧ … = the product of the elements of N ``` We technically do not need the explicit labeling `≜`, however if we do not use it, `~×` will not check the case `N = [100000000003,1]` (because it's often useless), meaning that this will be very slow for input `2` for example because it will need to find the second smallest integer instead of the first. [Answer] # Python, ~~53~~ ~~51~~ ~~49~~ ~~58~~ ~~53~~ 49 bytes -2 bytes thanks to orlp -2 bytes thanks to officialaimm -4 bytes thanks to Felipe Nardi Batist ``` x=input() t=1 while t-t/x*x:t+=3+10**11 print t/x ``` [Try it Online!](https://tio.run/##K6gsycjPM/r/v8I2M6@gtERDk6vE1pCrPCMzJ1WhRLdEv0KrwqpE29ZY29BAS8vQkKugKDOvRAEo/v@/oQEIQCkA) It took me ~30 minutes to figure this one out. My solution is to start with the first number that will mod to 1. This number is 1. If its divisible by x, then y is that number divided by x. If not, add 10000000003 to this number to find the second number which mod 1000000003 will equal 1 and repeat. [Answer] ## JavaScript (ES6), ~~153~~ ~~143~~ 141 bytes Inspired by [this answer from math.stackexchange.com](https://math.stackexchange.com/a/67199). A recursive function based on the Euclidean algorithm. ``` f=(n,d=(F=Math.floor,m=1e11+3,a=1,c=n,b=F(m/n),k=m-b*n,n>1))=>k>1&d?(e=F(c/k),a+=e*b,c-=e*k,f(n,c>1&&(e=F(k/c),k-=e*c,b+=e*a,1))):a+d*(m-a-b) ``` Modulo is implemented by computing: ``` quotient = Math.floor(a / b); remainder = a - b * quotient; ``` Because the quotient is also needed, doing it that way does actually make some sense. ### Test cases ``` let f = f=(n,d=(F=Math.floor,m=1e11+3,a=1,c=n,b=F(m/n),k=m-b*n,n>1))=>k>1&d?(e=F(c/k),a+=e*b,c-=e*k,f(n,c>1&&(e=F(k/c),k-=e*c,b+=e*a,1))):a+d*(m-a-b) console.log(f(2)) console.log(f(50000000002)) console.log(f(1000000)) ``` [Answer] # C++11 (GCC/Clang, Linux), ~~104~~ 102 bytes ``` using T=__int128_t;T m=1e11+3;T f(T a,T r=1,T n=m-2){return n?f(a*a-a*a/m*m,n&1?r*a-r*a/m*m:r,n/2):r;} ``` <https://ideone.com/gp41rW> Ungolfed, based on Euler's theorem and binary exponentation. ``` using T=__int128_t; T m=1e11+3; T f(T a,T r=1,T n=m-2){ if(n){ if(n & 1){ return f(a * a - a * a / m * m, r * a - r * a / m * m, n / 2); } return f(a * a - a * a / m * m, r, n / 2); } return r; } ``` [Answer] # Mathematica, 49 bytes ``` x/.FindInstance[x#==k(10^11+3)+1,{x,k},Integers]& ``` [Answer] # PHP, 71 bytes ``` for(;($r=bcdiv(bcadd(bcmul(++$i,1e11+3),1),$argn,9))!=$o=$r^0;);echo$o; ``` [Testcases](http://sandbox.onlinephpfunctions.com/code/9e543565d82bcc273c4e6ae6ded5a91db9e290fd) [Answer] # [Ruby](https://www.ruby-lang.org/), 58 bytes Uses isaacg's application of Fermat's little theorem for now while I finish timing the brute-force solution. ``` ->n,x=10**11+3{i=n;11.times{i**=10;i-=i/x*x};i*=n;i-i/x*x} ``` Current brute force version, which is 47 bytes but ~~might be~~ *is* too slow: ``` ->n,x=10**11+3{(1..x).find{|i|i*=n;i-i/x*x==1}} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cuT6fC1tBAS8vQUNu4OtM2z9rQUK8kMze1uDpTSwsoY52pa5upX6FVUWudqQWUztSF8P4XKKRFp6eWFOuV5Mdnxv43NAADQwA "Ruby – Try It Online") ]
[Question] [ Given a list with number, output the ranges like this: Input: `[0, 5, 0]` would become `[0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]`. This is mapping a range through the array, so we first have to create the range `[0, 5]`, which is `[0, 1, 2, 3, 4, 5]`. After that, we use the `5` to create the range `[5, 0]`. Appended at our previous range, this gives us: ``` [0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0] ``` Let's observe a test case with two same digits next to each other: ``` [3, 5, 5, 3], ranges: [3, 5] = 3, 4, 5 [5, 5] = 5 (actually [5, 5] due to overlapping) [5, 3] = 5, 4, 3 ``` So this would give us `[3, 4, 5, 5, 4, 3]`. Some other test cases: ``` [1, 9] > [1, 2, 3, 4, 5, 6, 7, 8, 9] [10, -10] > [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10] [3, 0, 0, -3] > [3, 2, 1, 0, 0, -1, -2, -3] [1, 3, 5, 7, 5, 3, 1, -1, -3] > [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3] ``` Input will always have at least 2 integers. Shortest answer wins! [Answer] # 05AB1E, 1 byte ``` Ÿ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=xbg&input=WzMsIDAsIDAsIC0zXQ) ### How it works It's a built-in. [Answer] # Javascript, ~~99~~ ~~95~~ 93 bytes ~~4~~ 6 bytes off thanks [@Neil](https://codegolf.stackexchange.com/users/17602/neil). ``` a=>a.reduce((x,y)=>x.concat(b.map?b=y:[...Array(y<b?b-y:y-b||1)].map(_=>b+=y<b?-1:y>b)),b=[]) ``` ``` f= a=>a.reduce( (x,y)=> x.concat( b.map?b=y :[...Array(y<b?b-y:y-b||1)] .map(_=>b+=y<b?-1:y>b) ) ,b=[]) G.addEventListener('click',_=>O.innerHTML=f(JSON.parse(I.value))); ``` ``` <input id=I value="[3,5,5,3]"><button id=G>Go</button><pre id=O> ``` [Answer] # JavaScript (SpiderMonkey 30+), ~~81~~ 76 bytes ``` ([n,...a])=>[n,...[for(i of a)for(j of Array(i<n?n-i:i-n||1))n+=i<n?-1:i>n]] ``` Tested in Firefox 44. Uses ES6's awesome argument destructuring capabilities and ES7's array comprehensions (which have sadly been removed from the ES7 spec). [Answer] # JavaScript (ES6) 66 ~~72~~ A recursive function that repeatedly adds values inside the array to fill the gaps between near numbers ``` f=l=>l.some((x,i)=>(z=l[i-1]-x)*z>1&&l.splice(i,0,x+z/2|0))?f(l):l ``` **Test** ``` f=l=>l.some((x,i)=>(z=l[i-1]-x)*z>1&&l.splice(i,0,x+z/2|0))?f(l):l console.log=x=>O.textContent+=x+'\n' ;[[1,9],[10,-10],[3,0,0,-3],[1, 3, 5, 7, 5, 3, 1, -1, -3]] .forEach(t=>console.log(t+' -> ' +f(t))) ``` ``` <pre id=O></pre> ``` [Answer] # C, 120 + 12 = 132 bytes ``` i,j,k;f(a,n)int*a;{a[0]--;for(i=0;i<n-1;i++)for(k=0,j=a[i]-a[i+1]?a[i]:a[i]-1;j-a[i+1];)printf("%i ",j+=a[i+1]>j?1:-1);} ``` Example call: ``` f(a,sizeof(a)/4); // I've added 12 bytes because of ",sizeof(a)/4" ``` Test live on [**ideone**](http://ideone.com/bViLqb). [Answer] ## Python 2, 77 bytes ``` lambda n:n[0:1]+sum([range(x,y,2*(y>x)-1)[1:]+[y]for(x,y)in zip(n,n[1:])],[]) ``` [Try it online](http://ideone.com/fork/Wl6sRo) Thanks to Neil, DenkerAffe, and Erwan for pointing out improvements that I missed [Answer] # Perl, 47 bytes Includes +3 for `-p` (code contains `$'` so space and `-` count too) Give the list of numbers on STDIN: ``` fluctuating.pl <<< "3 5 5 3" ``` `fluctuating.pl`: ``` #!/usr/bin/perl -p ($n=$&+($'<=>$&))-$'&&s/\G/$n / while/\S+ /g ``` The temporary variable and all these parenthesis feel suboptimal... [Answer] ## Haskell, ~~63~~ 55 bytes ``` g(a:b:r)=[a|a==b]++[a..b-1]++[a,a-1..b+1]++g(b:r) g x=x ``` Usage example: `g [3,5,5,3]` -> `[3,4,5,5,4,3]`. It's a modification of [my answer](https://codegolf.stackexchange.com/a/73640/34531) to a [related challenge](https://codegolf.stackexchange.com/q/73636/34531). Again, the main work is done by concatenating the list from `a` upwards to `b-1` and from `a` downwards to `b+1` (where one list will be empty) and a recursive call. To handle the `a==b` case where both lists are empty, we prepend `[a|a==b]` which evaluates to `[a]` if `a==b` and `[]` otherwise. [Answer] # R, ~~86~~ ~~82~~ 75 bytes ``` function(x)rep((y<-rle(unlist(Map(seq,head(x,-1),x[-1]))))$v,pmax(1,y$l-1)) ``` saved 4 bytes using rep not rep.int (code golf not performance!) saved another 7 bytes by using built-in partial matching when using `$` (and collapsing function definition to 1 line [Answer] # Ruby, ~~116~~ 82 bytes ``` ->n{o,*m=n;o=[o];m.zip(n).map{|t,u|o+=[[u],[*u+1..t],[*t..u-1].reverse][t<=>u]};o} ``` My first ever golf. Edit: Thanks manatwork for the awesome suggestions. [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 bytes Saved 16 bytes thanks to [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)! ``` ä!õ ËsE©DÊ>1 ``` [Test it online](https://ethproductions.github.io/japt/?v=1.4.5&code=5CH1IMtzRalEyj4x&input=WzEsIDMsIDUsIDcsIDUsIDMsIDEsIC0xLCAtM10=) [Answer] # Perl 6, 94 bytes I'm not super happy with this right now, I'll probably take another shot later ``` {reduce {|@^a[0..*-2],|@^b},map {@_[0]!= @_[1]??(@_[0]...@_[1])!!(@_[0],@_[1])},.rotor(2=>-1)} ``` [Answer] # PHP 5.4, 86 bytes This is meant to be used as an included file, that returns the result. The values are passed as commandline parameters. ``` <?for($i=1;$i<$argc-1;$R=array_merge($R?:[],range($argv[$i++],$argv[$i++])));return$R; ``` Not exactly pretty or anything, but does the job. [Answer] # [Python 3](https://docs.python.org/3/), 76 bytes First attempt at a Python answer. The basic idea is to repeatedly identify pairs in the sequence where the difference is larger than a step and insert one (and only one) additional element to complete the sequence in the right direction. Repeat until all differences between consecutive elements are between +1 and -1. ``` d=diff while any(d(x)**2>1):i=argmax(d(x)**2);x[:i+1]+=[x[i]+sign(d(x)[i])] ``` [Try it online!](https://tio.run/##Ncm9DsIgFEDhnae4IxQGqyxi8EUIQxOkvY38hGKEp0dj4ni@k3vdUrwMX1KA@Aq5A4acSoWJkKaNFFKcxFVISzpoMHY47dB78t7w@YAldupoY9N0vs9MoV7KGpb2N3ZrRiGfLdemGbT8wDX@5jeYJcOnAjtghKYI5IKx0p2N8QE "Python 3 – Try It Online") [Answer] ## Lua, 156 Bytes A function that takes an array in parameter and return the extended array. ``` function f(t)r={}for i=2,#t do x,y=t[i-1],t[i]r[#r+1]=x==y and x or nil z=x>y and-1or 1 x=x==r[#r]and x+z or x for j=x,y,z do r[#r+1]=j end end return r end ``` ### Ungolfed and explanations ``` function f(t) r={} -- Initialise an empty array for i=2,#t -- Iterate over the parameter array do x,y=t[i-1],t[i] -- x and y are shorter names than t[i-1] r[#r+1]= -- when there's a range like [5,5] x==y and x or nil -- put this number once in the array z=x>y and-1or 1 -- determine the step value x= x==r[#r] -- prevent repeating the last value of r and x+z or x -- by incrementing/decrementing x for j=x,y,z -- iterate from t[i-1] to t[i] by step z (-1 or 1) do r[#r+1]=j -- put j into the array r end end return r -- return the extended array end ``` For ease of use, you can use the following function to print the array returned by `f()`. ``` function printArray(t) print("["..table.concat(t,",").."]") end ``` When testing this submission, you can call it like: ``` printArray(f( {0,5,0,3,4,4,7,3,-3} )) > [0,1,2,3,4,5,4,3,2,1,0,1,2,3,4,4,5,6,7,6,5,4,3,2,1,0,-1,-2,-3] ``` [Answer] # Mathcad, 62 "bytes" [![enter image description here](https://i.stack.imgur.com/nGDGu.jpg)](https://i.stack.imgur.com/nGDGu.jpg) As Mathcad uses a 2D "whiteboard" and special operators (eg, summation operator, integral operator), and saves in an XML format, an actual worksheet may contain several hundred (or more) characters. For the purposes of Code Golf, I've taken a Mathcad "byte count" to be the number of characters or operators that the user must enter to create the worksheet. Converting the function definition to a straight program, and replacing the variable lst with a single character name, gives a total of 62 "bytes". With the function, using a single character rather than the full name, this increases to 65 "bytes" for the definition and a further 4 "bytes" for each call (assuming that creation of the list itself isn't included in the overall byte count (Using Mathcad's built-in tables is another way of inputting the list). [Answer] ## PHP, 144 bytes ``` function f($r){$m=[];for($i=0;++$i<count($r);){$d=array_pop($m);$n=$r[$i];$p=$r[$i-1];$m=array_merge($m,$p==$n?[$p,$n]:range($p,$n));}return$m;} ``` **Exploded view** ``` function f($r) { $m = []; for ($i=0; ++$i < count($r); ) { $d = array_pop($m); $n = $r[$i]; $p = $r[$i-1]; $m = array_merge($m, $p==$n ? [$p,$n] : range($p,$n)); } return $m; } ``` **Input / function call** ``` f([ bound1, bound2, bound3, ... ]); ``` **Output** ``` [int, int, int, int, ...] ``` It's messy and chunky, and I'll try to optimize it later. It creates a `range()` from each pair of adjacent value pairs, then stitches them together (after `pop`ing off the end of the previous cumulative `Array`). [Answer] **Perl6, 21** .join is short for $\_.join ``` say EVAL .join: "..." ``` **Test (rakudo)** ``` perl6 -MMONKEY-SEE-NO-EVAL -e'say EVAL @*ARGS.join: "..."' 1 3 5 7 5 3 1 -1 -3 ``` **Output** ``` (1 2 3 4 5 6 7 6 5 4 3 2 1 0 -1 -2 -3) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ,r⁼?2\Ṗ;¥/ ``` [Try it online!](https://tio.run/##y0rNyan8/1@n6FHjHnujmIc7p1kfWqr//3D70UkPd874/z/aUEfBWEfBVEfBHEwC2UARXRA2jgUA "Jelly – Try It Online") [Answer] # [R](https://www.r-project.org/), 74 bytes Another R solution ``` function(x){b=x[1];z=c();for(a in x[-1]){z=c(z,c(b:(a-sign(a-b))));b=a};z} ``` [Try it online!](https://tio.run/##Fcg9CoAwDEDh3VN0TKCCQidLTiIObaDSpYI/UCOePda3fPB2TaTpKnzmrUDFJ1Kdx8ULMaBP2w7B5GLq3I8LPv8VyxAnCP2R19KI2PKRwuvl1duQYXDW2cE67IQS3NhxOEFQ9QM "R – Try It Online") ]
[Question] [ **Disclaimer: the content of this post *is not medical information* and should not be used for any medical purpose, as it is deliberately oversimplified for the purpose of the challenge.** There are several different strains of [*Neisseria meningitidis*](https://en.wikipedia.org/wiki/Neisseria_meningitidis), the bacterium that causes meningococcal meningitis. Vaccines are available for strains A, B, C, W, and Y. They are available in three combinations. The first is the quadrivalent meningococcal ACWY vaccine. As the name implies, this protects against strains A, C, W, and Y, but not B. The second is the meningococcal B vaccine, which protects only against strain B. The third is the pentavalent meningococcal ABCWY vaccine, which combines ACWY and B to protect against all five strains. Receiving the ABCWY vaccine is equivalent to receiving ACWY and B simultaneously. However, while only one dose of ACWY is needed for full vaccination (we're ignoring boosters), two doses of B are needed. ABCWY counts as one dose of ACWY and one dose of B. Write a program or function that accepts either an array of strings, or several strings delimited by a string of your choice. (The empty string is an acceptable delimiter; i.e., you may accept the strings run together.) These strings will be from the set `ACWY`, `B`, and `ABCWY`. Return or print `ACWY` if at least one dose of ACWY has been given but zero or one doses of B have been given, `B` if at least two doses of B but no doses of ACWY have been given, and `ABCWY` if at least one dose of ACWY and at least two doses of B have been given. If neither vaccine has been fully received, output the empty string. "Overvaccination" is allowed; `ABCWY ABCWY ACWY` should become `ABCWY`. You do not have to support invalid inputs. | Input | Output | | --- | --- | | `ABCWY B` | `ABCWY` | | `ABCWY` | `ACWY` | | `B` | [empty string] | | `B B` | `B` | | `ACWY B B` | `ABCWY` | | `ACWY B` | `ACWY` | [Answer] # [Perl 5](https://www.perl.org/) `-p`, 28 bytes ``` $_=A x/A/.B x/B.*B/.CWY x/A/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tZRoULfUV/PCUg56Wk56es5h0eChf7/d3QCsZ24wDSXE5cTiA0WgjP@5ReUZObnFf/X9TXVMzA0@K9bkAMA "Perl 5 – Try It Online") [Answer] # Google Sheets, 64 bytes ``` =join(,ifna(filter({"A","B","CWY"},search({"A","B*B","A"},A1)))) ``` Put the input in cell `A1` and the formula in cell `B1`. Uses the `search()` with `*` wildcard method of [JvdV's Excel answer](https://codegolf.stackexchange.com/a/268657/119296). The same can be done without arrays using simple string concatenation and regexes (**81 bytes**): ``` =let(a,regexmatch(A1,"A"),if(a,"A",)&if(regexmatch(A1,"B.*B"),"B",)&if(a,"CWY",) ``` Implementation of the same in JavaScript (**62 bytes**): ``` t=>(a=/A/.test(t)?'A':'')+(/B.*B/.test(t)?'B':'')+(a?'CWY':'') ``` (-4 bytes thanks to [noodle man](https://codegolf.stackexchange.com/users/108687/noodle-man)) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` œ-”BQṢ ``` [Try it online!](https://tio.run/##y0rNyan8///oZN1HDXOdAh/uXPT/4e4th9sfNa2J/P/f0ck5PNKJC0xxOXE5AZkgASgFAA "Jelly – Try It Online") A monadic link taking a string with no delimiter and returning a string. ## Explanation ``` œ-”B | Set difference with "B" Q | Uniquify Ṣ | Sort ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 54 bytes ``` lambda s:"A"*(x:="C"in s)+"B"*(s.count("B")>1)+"CWY"*x ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPqfpmAb8z8nMTcpJVGh2ErJUUlLo8LKVslZKTNPoVhTW8kJKFCsl5xfmleiAeRo2hkCBZ3DI5W0Kv4XFGUCRdM0lBydgCIKQFlNLlQxFBFUeSd09WAjsAoChf4DAA "Python 3.8 (pre-release) – Try It Online") # [Python 3](https://docs.python.org/3/), 59 bytes ``` def f(s):x="C"in s;return"A"*x+"B"*(s.count("B")>1)+"CWY"*x ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNo1jTqsJWyVkpM0@h2LootaS0KE/JUUmrQlvJSUlLo1gvOb80r0QDyNG0M9TUVnIOjwRK/i8oygSKpmkoOToBRRSAsppcqGIoIqjyTujqwUZgFQQK/QcA "Python 3 – Try It Online") [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 6 bytes ``` "B"∕uo ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FiuUnJQedUwtzV9SnJRcDBVccFNLydHJOTzSSYkLwgDSILYTWAAkAWcoQbQAAA) A port of [@Nick Kennedy's Jelly answer](https://codegolf.stackexchange.com/a/268624/9288). ``` "B"∕uo "B"∕ Set difference with "B" u Uniquify o Sort ``` [Answer] # JavaScript (ES6), 55 / 48 / 41 bytes Expects a space-separated string. ``` s=>[...new Set(s.replace("B",""))].sort().join``.trim() ``` [Try it online!](https://tio.run/##fc7BCoJAEMbxe08xzGkXanwCg7ZH6BAhgmKjKLq77C5FT7@ZWQRKx2F@8P278lb6yrU27LS5cqzT6NN9RkSa73DiIDw5tn1ZsUCFW0Qpc/LGBSGpM60uCgquHYSMldHe9Ey9aUQt8KCO5wsoBCkhSWA6N2sGAT5mhajXG74k48GGB/hxUzf5AsPM31gt9qakEf1rmrN/muIT "JavaScript (Node.js) – Try It Online") Or **[48 bytes](https://tio.run/##fc5BCsIwEIXhvacIs0pApyeoYDyCiyKl0FKnpSVmQhIUTx9t60JocXYDH7x/bB5NaP3g4sHyjVKXp5AfS0S09BQXijKgJ2ealiRo2AMoVWFgH6XCkQdb16llG9gQGu5lJ@Gkz8VVf5zIMjE/uy0B4is2gAYx3QJKurv4EiH6wfbVii52oXq1NKX8b5ljf1rSGw)** if we take a string with no delimiter. Or **[41 bytes](https://tio.run/##fc5BCsIwEIXhvacIs0pApyeoYDyCC5HSRYjTUqlJyATF00fbuBBanN3AB@@/mYdhG4eQds5fKXd15nrfIKKjpzhRkoyRwmgsSdCwBVCqRfYxSZWtd@xHwtH3spNw0MfzRX@AqCoxP5s1AeIrVoAGMV0BDd1DeglOcXB9u6DFFqoXS1PK/5Y59qclvwE)** if we return an array. ## Method Given the input string, e.g. `"ABCWY ACWY B"`: * remove the first "B" → `"ACWY ACWY B"` * turn the string into a set → `Set { 'A','C','W','Y',' ','B' }` * turn the set into an array → `[ 'A','C','W','Y',' ','B' ]` * sort it in lexicographical order → `[ ' ','A','B','C','W','Y' ]` * turn it back into a string → `" ABCWY"` * remove the leading space, if any → `"ABCWY"` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 16 bytes ``` \W 1`B O`. D`. ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyaci8swwYmLyz9Bj8slQe//f0cn5/BIBScuMM3lxOUEYoOF4AwA "Retina 0.8.2 – Try It Online") Link includes test cases. Accepts any non-`\w` characters as a delimiter. Explanation: ``` \W ``` Join the words together. ``` 1`B ``` Delete the first `B`, if any. ``` O`. ``` Sort the letters. ``` D`. ``` Deduplicate the letters. [Answer] # [Bash](https://www.gnu.org/software/bash/) + [core utilities](https://www.gnu.org/software/coreutils/), 37 bytes ``` sed s/B//|grep -o .|sort -u|tr -d \\n ``` ### Explanation ``` sed s/B// | # remove the first occurrence of B grep -o . | # insert a newline after every character sort -u | # sort lines and remove duplicates tr -d \\n | # remove newlines inserted for sorting ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 8 ~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Note while I did eventually think of using `œ-` to avoid a byte, I now see that [Nick Kennedy actually got there first](https://codegolf.stackexchange.com/a/268624/53748)! ``` Fœ-”BQṢ ``` A monadic Link that accepts a list of lists of characters (the vaccines) and yields a list of characters (the fully vaccinated). **[Try it online!](https://tio.run/##y0rNyan8/9/t6GTdRw1znQIf7lz0////aCVH5/BIJR0FJSelWAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/t6GTdRw1znQIf7lz0/@HuLYe26jzcselwu0qWw6OmNY8a9ykpabr//@/o5BweqeDEBaa5nLicQGywEJwBkVOAkiBljjAWAA "Jelly – Try It Online"). ### How? ``` Fœ-”BQṢ - Link: list of strings (from "B", "ACWY", "ABCWY"), Vaccinations F - flatten œ-”B - multiset difference with 'B' Q - deduplicate Ṣ - sort ``` --- Alternative [TIO](https://tio.run/##y0rNyan8///oZN1HDXOdDs9wTPv/cPeWQ1t1DrdnOTxqWvOocZ@Skqb7//@OTs7hkQpOXGCay4nLCcQGC8EZEDkFKAlS5ghjAQA "Jelly – Try It Online"): Taking a non `[A-Z]` separating string (like `" "` or `", "`, etc): ``` œ-”BØAf œ-”B - multiset difference with 'B' ØAf - "ABC...XYZ" filter keep ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 'Bõ.;ê ``` Port of [*@NickKennedy*'s Jelly answer](https://codegolf.stackexchange.com/a/268624/52210). [Try it online](https://tio.run/##yy9OTMpM/f9f3enwVj3rw6v@/3d0Do90cgIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf3Wnw1v1rA@v@q/z39HJOTzSiQtMcTlxOQGZIAEoBQA). **Explanation:** ``` .; # In the (implicit) input-string, replace the first 'B '# "B" õ # with an empty string "" ê # Then sort and uniquify the characters of the string # (which is output implicitly) ``` [Answer] # Excel ms365, ~~64~~63 bytes New: ``` =CONCAT(IFERROR(MID(A1,SEARCH({"A","B*B","C"},A1),{1,1,3}),"")) ``` Old: ``` =CONCAT(REPT({"A","B","CWY"},COUNTIF(A1,{"*A*","*B*B*","*A*"}))) ``` [Answer] # Python, 50 bytes ``` lambda s:''.join(sorted(set(s.replace('B','',1)))) ``` Another port of [@NickKennedy's answer](https://codegolf.stackexchange.com/a/268624/52210), approximately. Python doesn't have a built-in multiset or corresponding set-difference operator; it does have `collections.Counter`, but that takes way too much setup. Instead, I just remove up to one `B` from the input before uniquifying and sorting (and producing a string from the resulting list). This works in both Python 2 and Python 3. The `count` argument for the `replace` method of strings is not commonly discussed, but it's clearly documented. [Answer] # [Ruby](https://www.ruby-lang.org/), 26 bytes ``` ->s{s.sub(?B,'').chars|[]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664ulivuDRJw95JR11dUy85I7GouCY6tvZ/gUJatJKjk3N4pIKTkl46SI2SgpKOkpJmLKeyAidYhguhCJsSuApsBkSn5haUVCoUlxRl5qXHQtVhtcoJag3YKQQdg9PBQIn/AA "Ruby – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 44 bytes ``` s=>s.sort().filter(x=>!~(s[x]=~-s[x]),s.B=1) ``` [Try it online!](https://tio.run/##hY9BCsIwEADvvmLNKQG7xQekYHyESMih1LRUalOyQeqlX49Ei3po8bQszLCz1/JeUuXbIWS9u9hYy0iyICTnAxdYt12wno@y2E6c9GjklKUhdoRK7kWsXE@us9i5htdcIyI7qOPprBgYISDP4bVu1jgG8AFXOJUY@HLa3obwAAq@7RuzaMzKLKjF6ylSsb@R719@G@MT "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 49 bytes ``` s=>[...'ABCWY'].filter(x=>s.split(x)[x=='B'?2:1]) ``` [Try it online!](https://tio.run/##fc5BC8IgFMDxe5/i4UU95Khj4CL7EBGyw1huGKZDJezTWzgWwUbHx/s93v/ePtvQeT3GrXU3lXueA68lYwyfxPlyxQ3rtYnKk8TrwMJodCSJysQ5Fvi4P@wamjtngzOKGTeQnqByCAIQUApVBWXerCIEMKMVI8oevkaqxxhfEKLXdmiWevaTFouXU9ZH/eua23@68hs "JavaScript (Node.js) – Try It Online") +4 bytes if a trailing delimited is not allowed. Worse than Arnauld's solution (41, if it use no delimit and output array) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` Φα›№θι⁼κ¹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMtM6cktUgjUUfBvSg1EcR0zi8FihfqKGRq6ii4FpYm5hRrZOsoGGoCgfX//45OzuGR/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Accepts any character that's not an uppercase letter as a delimiter (some characters may need extra quoting). Explanation: ``` α Predefined variable uppercase alphabet Φ Filtered where № Count of ι Current letter θ In input string › Is greater than κ Current index ⁼ Equals ¹ Literal integer `1` Implicitly print ``` [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), ~~17~~15 bytes [SBCS](https://github.com/abrudz/SBCS) ``` ⎕A∩⊢(/⍨)≠⍲'B'=⊢ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9Q31fFRx8pHXYs09B/1rtB81LngUe8mdSd1W6AQAA&f=K0ktLil@1DZB3dHJOTxSwUldAcJSV9B41LtGR91JXVNB3QkiDlaAxFTnKgHp1ok21DONTTu0AswDAA&i=AwA&r=tryapl&l=apl-dyalog-extended&m=train&n=f) A tacit function which takes a string on the right using no delimiter or any delimiter that is not a capital letter. The test cases use spaces. (The test case `B` is written as `(⍬,'B')` because single characters in quotes are not treated as strings in APL) ``` ⎕A∩⊢(/⍨)≠⍲'B'=⊢­⁡​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌­ 'B'=⊢ # ‎⁡Boolean mask for all Bs ⍲ # ‎⁢NAND ≠ # ‎⁣Boolean mask for all first instances ⊢(/⍨) # ‎⁤apply Boolean mask (removes first B) ∩ # ‎⁢⁡intersection ⎕A # ‎⁢⁢capital letter alphabet 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). Taking the intersection with the alphabet helpfully removes any delimiters and sorts alphabetically. This solution doesn't work on any of the APL versions on TIO, as @att describes. [Answer] # [Uiua 0.8.0](https://www.uiua.org/), 13 bytes [SBCS](http://tinyurl.com/SBCSUiua "SBCS for Uiua 0.8.0") ``` ⊏⍏.⊝▽≠⇡⧻,⊗@B. ``` [Try on Uiua Pad!](https://uiua.org/pad?src=0_7_1__ZiDihpAg4oqP4o2PLuKKneKWveKJoOKHoeKnuyziipdAQi4KZiJCIgpmIkJCIgpmIkJCQiIKZiJBQ1dZIgpmIkFDV1lCIgpmIkFDV1lCQiIKZiJBQkNXWSIKZiJBQkNXWUIiCmYiQUNXWUFDV1kiCg==) [Answer] # [Scala](https://www.scala-lang.org/), 115 bytes A Port of [@spooky\_simon's Python answer](https://codegolf.stackexchange.com/a/268625/110802) in Scala. --- Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=fY6xTsMwEIb3PMXpltqgIioWlMpIcWcmhBCqKmSCHQWZM7JdCKr6GEwsXWDhifo2XJqOEV7u7O-7__z1k2rjzcXvEqcU3k0kXO3n4fHZ1hmuTUuwKQCerIMXvggTm1RCFaP5WN7k2FKzkiXcUptBscnq9zq76eU-9SON6EodgreGpGqd6OQMrE8WzoseO5HKIUSqzZvx0Kl0VgfKvCkJXKCcY4UnnCJPUfdNj9eUxYNSEz2RVzMGi7v7wdkeV38Cn1eOzZ6EE1hpVkCjlMUYGXkfc_V4wiH6HzSAbXH83G431D8) ``` def g(x:Boolean)=if(x)1 else 0 def f(s:String)={val x=s.contains("C");"A"*g(x)+"B"*g(s.count(_=='B')>1)+"CWY"*g(x)} ``` Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=fZHBasJAEIbxmqf42Ut2Ky2VXkSIkM25p1KKiMiaZjWSbkp2LYjkSbx40buv49O4zSZBSuxtdv5vv2GY_UnHIhMvh8NxY-Tj8NI754t1Ehu8ilRh5wGficSXfVBRLPUIYVGI7fTNFKlaztgI7yo1CCrSsZJayuWsKVoA-BEZVkJHtqWf4lwZq9aURITdAIso3yhTI7aicwQBfO4zjDHwapKSkOABNJWgv0qGAZJMJ3hmDP0W4i3ktHew6GNy11ZBpZv7bRcymaLSjuf2Ezipgb9JR7-L5d2GSv1P5ILSK93l6gM2h7wC) ``` object Main { def main(args: Array[String]): Unit = { def f(s: String): String = { val hasC = s.contains("C") val bCount = s.count(_ == 'B') > 1 ("A" * (if (hasC) 1 else 0)) + ("B" * (if (bCount) 1 else 0)) + ("CWY" * (if (hasC) 1 else 0)) } println(f("ABCWY B")) println(f("ABCWY")) println(f("B")) println(f("B B")) println(f("ACWY B B")) println(f("ACWY B")) } } ``` ]
[Question] [ Totally not inspired by Lyxal repeatedly mentioning elevators in chat :P ## Challenge In short: simulate some people filling up an elevator and then leaving it. The elevator is simplified as a grid, where each person can occupy one cell of the grid. The height and width of the grid is the input parameter. The width is always odd, and it has an opening of 1 unit width at the center of the top side. The following diagram shows an elevator of width 5 and height 4, initially empty: ``` +------ ------+ | ? ? ? ? ? | | ? ? ? ? ? | | ? ? ? ? ? | | ? ? ? ? ? | +---------------+ ``` Now, 20 people, numbered 1 to 20 in the order of boarding, start filling up the elevator. People tend to stick to the front, but cannot block other people boarding when some spots are still empty. As a simplification, let's simply assume that people fill the spots in the left-right-left-right fashion from the frontmost row, leaving the middle column empty (which is then filled by the last few people): ``` +------ ------+ | 1 3 20 4 2 | | 5 7 19 8 6 | | 9 11 18 12 10 | | 13 15 17 16 14 | +----------------+ ``` When people leave the elevator, they do row-by-row, starting with the center column and then alternating left and right sides. So the order of leaving is as follows: ``` 20, 3, 4, 1, 2, 19, 7, 8, 5, 6, 18, 11, 12, 9, 10, 17, 15, 16, 13, 14 ``` The challenge is to **produce this sequence** for given width and height of the elevator (again, the width is guaranteed to be odd). You can use 0-based numbering instead of 1-based. [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") I/O applies. The I/O format can be in one of three ways: * Take width and height, and output the full sequence * Take width, height, and index (0- or 1-based), and output the n-th number (index is guaranteed to be valid) * Take width, height, and n (at most the number of cells), and output the first n numbers The standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## More test cases ``` width = 1, height = 1 output = 1 width = 1, height = 10 output = 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 width = 9, height = 1 output = 9, 7, 8, 5, 6, 3, 4, 1, 2 width = 7, height = 5 output = 35, 5, 6, 3, 4, 1, 2, 34, 11, 12, 9, 10, 7, 8, 33, 17, 18, 15, 16, 13, 14, 32, 23, 24, 21, 22, 19, 20, 31, 29, 30, 27, 28, 25, 26 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` p1Ṛ;@pỤɓḊU^1 ``` [Try it online!](https://tio.run/##y0rNyan8/7/A8OHOWdYOBQ93Lzk5@eGOrtA4w/@Hl@sfnfRw5wzNyP//ow11FAxjdRSiDQ1gDB0FSxBtqqNgDqJNdBRMYwE "Jelly – Try It Online") Takes (height, width) arguments and returns the sequence. Unrelated String saved two bytes. Thank you! ## Explanation for (width, height) = (7, 5) `ḊU^1` is `[width..2]` each XORed with `1`: `[6,7,4,5,2,3]`. We take the Cartesian `p`roduct of `[1..height]` and that. The result is a list of `6×5` pairs: ``` [[1,6], [1,7], [1,4], [1,5], [1,2], [1,3], [2,6], [2,7], [2,4], [2,5], [2,2], [2,3], [3,6], [3,7], [3,4], [3,5], [3,2], [3,3], [4,6], [4,7], [4,4], [4,5], [4,2], [4,3], [5,6], [5,7], [5,4], [5,5], [5,2], [5,3]] ``` Then, `p1Ṛ;@` appends `[[5,1],[4,1],[3,1],[2,1],[1,1]]` to this list, for a total of `7×5` pairs. ``` [[1,6], [1,7], [1,4], [1,5], [1,2], [1,3], [2,6], [2,7], [2,4], [2,5], [2,2], [2,3], [3,6], [3,7], [3,4], [3,5], [3,2], [3,3], [4,6], [4,7], [4,4], [4,5], [4,2], [4,3], [5,6], [5,7], [5,4], [5,5], [5,2], [5,3], [5,1], [4,1], [3,1], [2,1], [1,1]] ``` Wow, this all seems like it's getting us nowhere! But: * The lexicographically smallest element `[1,1]` is found at index `35`, * and the second smallest element `[1,2]` is at index `5`, * and the third smallest element `[1,3]` is at index `6`, * ... * and the largest element `[5,7]` is at index `26`. so in other words, the "grade" `Ụ` is an elevator sequence, and we're done. [Answer] # [Python 2](https://docs.python.org/2/), ~~75~~ ~~69~~ ~~50~~ ~~48~~ 45 bytes ``` lambda w,h,i:[w*h+~i/w,1^~i%w+i/w*~-w][i%w>0] ``` [Try it online!](https://tio.run/##hVHda8IwEH/vX3F0DKyezKT1Exz4MhjsYeBj14EfiQ1oK5rR7cV/vbtLZt30YaGEy/2@Ls3@y@ZlIWs9fau3i91yvYAKczSTtGrnnZN5qFC8n8x91aGyfepWWUqHx15W34He2QmUWgdWHe0RppAGQKslEOhLRRbhpdHjDm1jhBHCEGGA0EdIEGIESYSGPfbysWONHGvgWIkDZEP08lT2fqO0XykFVYJHkC6dhxCEC0IFw6QVSWM6dLI07t8GU53cWPmkOP4xHV0bE0ZkyZekWrLPz4xubj5THVMtSS9JL0kvB1kUZMH5HxdBoMsDVGZtc4RcmU1uEdTnXq2sWoMpwD3BxF1hU1p@C936SzcRsIdh9mFRbJTH2x6OMqdtLMlgBV0QTrNizRnyRKN9zrTp@3Be@4Mp7FU6hK@z@TyMfMr2qP6jP82eX5AzQrdTZ/lhm7Dwcvuo/gY "Python 2 – Try It Online") *-6 bytes thanks to a suggestion from @dingledooper to persue a single for loop* *-2 bytes from following a lead from @Arnauld* *-3 bytes from @dingledooper* Outputs the sequence as 0-based instead of 1-based. Given a (0-based) index i, this returns the i-th entry of the sequence as per [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") tag [defaults](https://codegolf.stackexchange.com/tags/sequence/info). > > Format: The answers can use one of the following input/output methods: > ∘ Given some index n it can return the n-th entry of the list. > ∘ ... > > > Notes: `~y == -y - 1`, `~-w == w-1` (avoids parentheses), and two-argument bitwise operators have very low [precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence), so `w-i%w-1^1 = (w-i%w-1)^1`. [Answer] # JavaScript (ES6), 39 bytes Expects `(w, h, n)` and returns the n-th term. Everything is 0-indexed. ``` (w,h,n,y=n/w)=>n%w?-n%w-~y*~-w^1:w*h+~y ``` [Try it online!](https://tio.run/##TcvRCoIwGAXge5/ivwn/2Vx5EVExo4ueYqwYpk2xTWY0vPHVlwZCNwc@zjmN@qi@cHX3To19lKHiAT3V1NCBm40nPDcrf06nSMchGVN/y44@0etxCCcRAQjIKEAGki7ItgsO/81@wg5kJCNWWXdVhUYU4ClokAR4DoU1vW1L1tonCsbYxTk1oIcENJHspTrEOwXz21Y4H2cR1tjaYEwhJoSELw "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 bytes ``` ×µð_ḶœsḂ_$Þ€ż@_ⱮF ``` [Try it online!](https://tio.run/##y0rNyan8///w9ENbD2@If7hj29HJxQ93NMWrHJ73qGnN0T0O8Y82rnP7f3i5/qOGGd6akf//RxvqKBjG6iiAaQMQwxIqYK6jYAqiTXUUTGIB "Jelly – Try It Online") *-1 byte trading one dyad-identity-dyad chain for another* Width on the left, height on the right. 0-indexed. Still feels a bit golfable. Ties the similar, arguments-reversed `_ḶœsḂ_$Þ€ż@_ⱮFð@×`. (Speaking of tying, take a peek at the edit history for a good laugh.) ``` × Let the product of the arguments µð be the left argument to the following dyadic chain: _Ḷ [0 .. product-height-1] œs split into as many slices as the height. Þ€ Sort the elements of each ascending by Ḃ_$ (x % 2) - x. ż@ Interleave the slices after each _Ɱ product - each [1 .. height], F and flatten to obtain the sequence. ``` [Answer] # [J](http://jsoftware.com/), 37 36 bytes ``` ,@(_2|.\|.)"1@i.@(,<:),@,.~[{.i.@-@* ``` [Try it online!](https://tio.run/##ZVBNS8QwFLz7K4a9tNXX0Jc0221QKAiePIk3F0SWLurFQ725@NfrpAm7sntImJf5eEM@55Up9rgLKCBoEHhqg/unx4dZhvLVHsz2YKqVDh9mKOU2VDKI@X35MZzr4Xqursbd@xda7OETLJ7H6Ru7t2mcivRSSmgq1AFKleY32wicoBWowPLuBZ1gI/CCNWciJaXkSCnlSl7JaqTp1Tan3qT9yNFR2y9R3RLllzUurTlatPnX5mz5qdhJTnWf1c5fConbi8Yp07ncfXPenxzFNlYjtjEnf8XyPXEmdsSWfku/pd@uj608W3XzHw "J – Try It Online") Returns the full sequence. Zips the last "height" elements, reversed, with the remaining elements taken in rows of "width - 1", with each row re-arranged by reversing it, and then taking chunks of 2 and reversing each of those. The resulting matrix is flattened. [Answer] # JavaScript (ES6), 67 bytes ``` w=>h=>(g=c=>[c?w*r-r-c^1:w*h-r,...++c-w?g(c):r++-h?g(0):[]])(0,r=1) ``` [Try it online!](https://tio.run/##bczBCoMwEATQe78ka0xIoKVU2fghYkG2mrSIkbU0n5/mWirMYXgM8xo/40783N5qjY8pz5gTuoBOeCR0PXWpYsWK7rZJVVBca62lJJU6LwgallKFUg00/TCAMDWjhUxx3eMy6SV6MYsLiDNAe/pVCyWHav75dji@QvmGNn8B "JavaScript (Node.js) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~26~~ ~~24~~ 23 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Ugly as all hell and almost certainly golfable but it does the job without need for a mathematical formula. Takes height as the first input, width as the second and outputs the full sequence. ``` N×õ oNg)íUòVÉ mò mw)c f ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Ttf1Cm9OZyntVfJWySBt8iBtdyljIGY&input=NSw3) ``` N×õ\noNg)íUòVÉ mò mw)c f :Implicit input of integers U=height & V=width N :The array of all inputs (i.e [U,V]) × :Reduce by multiplication õ :Range [0,N×] \n :Reassign to U o :Remove and return the last Ng : First element of N (i.e., original U) elements ) :End remove í :Interleave Uò : Partitions of the remaining elements of U of length VÉ : V-1 m : Map ò : Partitions of length 2 m : Map w : Reverse ) :End interleave c :Flatten f :Filter ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes ``` R}Uð×RœṖ@’בɗœsL}¹;"U}¥ʋ/s€2Ṛ€FðỊ? ``` [Try it online!](https://tio.run/##AUcAuP9qZWxsef//Un1Vw7DDl1LFk@G5lkDigJnDl@KAmMmXxZNzTH3CuTsiVX3CpcqLL3Pigqwy4bma4oKsRsOw4buKP////zX/Nw "Jelly – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` NθNηFηIEθ⎇κ⁺⁻×⊖θ⊕ικ⊗¬﹪κ²⁻×θηι ``` [Try it online!](https://tio.run/##TY0xDoMwDEX3niKjI9GlEurAWBYGEAMXCOAqESEBJ6nU06fOVAZbft/W86IVLV7ZnDt3pDikfUaCUza3K2vmtyfBgxjJuAgvFSL06oCzEhOSU/SFrRKjTQF647hPZscALS6EO7qIK1sr0bk/G8nBxtX6NFsOBs9Ovybri@shZTm42viZ5siUjWxyfoo63z/2Bw "Charcoal – Try It Online") Link is to verbose version of code. Outputs the 1-indexed list. Explanation: ``` NθNηFη ``` Input the width and height and loop over each row of the lift. ``` IEθ⎇κ ``` Loop over each column of the lift; ... ``` ⁺⁻×⊖θ⊕ικ⊗¬﹪κ² ``` ... the columns leave in swapped pairs, ... ``` ⁻×θηι ``` ... but the centre column of the row leaves first. Example for the 3rd (0-indexed row `i=2`) row of the `7×5` lift: the 0-indexed column variable `k` loops from `0` to `6`; `0` gets mapped to the centre column, which is `7×5-i=33`, while the columns `1` to `6` get mapped first to `6×3-k` or `17, 16, 15, 14, 13, 12`, but 2 is then added to alternate terms, yielding the desired result `17, 18, 15, 16, 13, 14`. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `R`, 13 bytes ``` ɽ›Ṙ1꘍Ẋ⁰1v"ṘJ⇧ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=R&code=%C9%BD%E2%80%BA%E1%B9%981%EA%98%8D%E1%BA%8A%E2%81%B01v%22%E1%B9%98J%E2%87%A7&inputs=7%0A5&header=&footer=) Returns 0-indexed. A port of Lynn's excellent Jelly answer - go upvote that, and have a look at their explanation, which is much better than this. Returns 0-indexed. ``` ɽ›Ṙ # Width...2 1꘍ # xor 1 Ẋ # Cartesian product with 1...height ⁰ # 1...height 1v" # Each paired with 1 Ṙ # Reverse J # Append that to the previous ⇧ # Grade ``` ]
[Question] [ Let's build an advent Calendar for this Christmas! Many Advent calendars for children take the form of a large rectangular card with numbered windows for each day of December starting from 1 ( although advent time begins on Advent Sunday, which is the fourth Sunday before Christmas day and often happens to be on November) and leading up to and including Christmas Eve (24) or in some cases Christmas day (25). Windows are distributed across the calendar at a random position. Every day children open the corresponding calendar window to reveal a small gift(usually a chocolate) # Task The task is to display an advent calendar up to date following these rules: * Include Christmas day : 1 to 25 * For days that have passed put an opened empty window `[ ]` ( no different characters allowed ), so if i run the same code the next day there must be a new window opened. * At the current day put an opened window with a gift in it `[@]` ( instead of `@` you can use every printable character excep for `space`, `[` , `]` and `digits` ). * For the remaining days put only the day number. * At Christmas all the windows will be open, the next day they are all closed ( a new calendar ). * Windows must open only on December, windows must stay closed on every month except for December. * It should work the same way the next year, and every year, that is for example on December 2099 Windows start opening. * Windows are laid down in random order on a 5 rows x 5 columns grid. * The grid has not to be accurate, just consider that every windows must have at least one character space separating them on every side: left, top, right and bottom hence numbers must have left and right spaces of at least two characters. # Example Today (15 December) : ``` 23 21 [ ] 18 [ ] [ ] [ ] [ ] [ ] 16 24 22 [ ] 17 [ ] [ ] [ ] [ ] 25 19 [ ] [ ] [@] [ ] 20 ``` Tomorrow (16 December) : ``` [ ] 17 25 [ ] [ ] [ ] 19 [ ] 18 21 [ ] 23 24 [ ] [ ] 22 [@] [ ] [ ] [ ] [ ] 20 [ ] [ ] [ ] ``` On every month different than December ``` 18 23 21 12 19 25 24 3 15 14 16 9 17 20 4 8 2 11 5 7 6 13 10 22 1 ``` [Live example](https://tio.run/##hVFNa4MwGL7nVzx4KHEymYPCwAV22LW/wPYgNc4Ul0hMO8bob3dvEpmrO8xLPp73@Yqn@lKPR6sGd395mibWSwdnmvoTgICWH3itneRpGRC6HxGQ6lAy1hoLDg8ouipQ0vos8LilXZYppF8MqqWRooAQUTd/k25ntOt4is2GIX7Ew4JHSwR@8MyH89hxJBUOCSgLrgyyH2VUVzfiM/kv92XFXQ2oGbyuez3EXre1PHg8Wyu1oxEvU9EQPUqkNbGWwK52Xd72xlge97bWjXmngHde0Fv@kANhPjVBazl4aPYr/4mokAlsQ8pFWiDZ670GEmS/45JU@KnROD8Zpemt4OcoGxusooLcY2k5Td8 "JavaScript (V8) – Try It Online") All [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 57 [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") Full program. ``` 5 5⍴('[ ]'¨@{⍵∊⍳d}'[@]'¨@{⍵=d})⍣(</11 25≥m d←2↑1↓⎕TS)?⍨25 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94L@pgumj3i0a6tEKseqHVjhUP@rd@qij61Hv5pRa9WgHuJhtSq3mo97FGjb6hoYKRqaPOpfmKqQ8aptg9KhtouGjtsmP@qaGBGvaP@pdYWQKMvi/AhgUAAA "APL (Dyalog Extended) – Try It Online") `?⍨25` random selection without replacement of 25 out of 1…25 `⍣(`…`)` if:  `⎕TS` date in `[Y,M,D,h,m,s,t]` format  `1↓` drop one element; `[M,D,h,m,s,t]`  `2↑` take two elements; `[M,D]`  `m d←` distribute to variables `m=M` and `d=D` (for **m**onth-of-year and **d**ay-of-month numbers)  `11 25≥` are `[11,25]` greater than or equal to these (gives `[0,1]` during advent, `[1,0]` or `[1,1]` before, and `[0,0]` after)  `</` if the first number is less than the second…  `(`…`)` then apply the following function:   `@{`…`}` at elements where the following condition is true:   `⍵=d` the elements are equal to `d` (today's day-of-month number)   `'[@]'¨` replace each with the constant `"[@]"`   `@{`…`}` at elements where the following condition is true:   `⍵∊⍳d` the elements are members of 1…`d` (today's day-of-month number)   `'[ ]'¨` replace each with the constant `"[ ]"` `5 5⍴` reshape into a five-by-five matrix [Answer] # Python 2, ~~181~~ ~~189~~ ~~181~~ 179 Bytes ### Original Code Since I can't comment on other answers yet, this is a slight improvement on ElPedro's previous answer. [Try it online!](https://tio.run/##FY1BDoMgFET3noK4AaIh0cQutDS9ByFqgFYa@Rj6k8bTU1zNzFu8OU7cIvQ5eznPPhwx4TxXKD2r7YoOfXA1F1cVGO16Mj6BxALOykjFqKINo4S29Em5slKCbqim7WIXrlCECLjduz4mYh@gX1cSD6TY0wo2huL@ruHYHSv77VjX9jfe9gPX1W/zuyNmPJIHLBfiEz0wo8ZB88lIo4ZR5/wH) I changed ElPedro's 5th line to save an additional 9 bytes. ``` i=__import__ t=i("datetime").date.today();n=t.day c=[('['+(' ','@')[d==n]+']',`d`)[t.month<12or d>n]for d in i("random").sample(range(1,26),25)] while c:print' '.join(c[:5]);c=c[5:] ``` ### Correction #1 Gained 6 bytes in order to fix an error where windows remain open after December 25th until the new year. [Try it online!](https://tio.run/##VY5Ba8QgEIXv@RWyPagkSCNkD9m6FNqf0JtI1upsY4kazMCyvz41x17mzWOG9731iXNOct@DmqYQ11xwmhpUgZ28RcAQ4cTFsQrM3j4ZvzQvX7AhcdkDuedCPsFB/IZC7B3rlAPOgnwc10cJiJBITqQ/H3@iJmP7P/sQDwtaVuM31b/yJimsyGfjlGZU05ZRQjv6Trn2SiXTUkO7m79xjSLmhPNbL2uPdJVDFX9N5qjlSUikoopNPscK2mxcF2DV/wDrO3nmnRy4aR5zWIC4cS0hYSWJ3xwSc3ocDL845fQwmn3/Aw) See corrected version of line 3 below: ``` c=[('['+(' ','@')[d==n]+']',`d`)[t.month<12or n>25or d>n]for d in i("random").sample(range(1,26),25)] ``` ### Correction #2 As per AZTECCO's suggestions, I'm back at 181 bytes :) [Try it online!](https://tio.run/##FYxLCsMgFAD3OYV0o5IPjZAukgq9h4gJahtLfIb0QQnk7jbdzcxi1h3nBCLnII0JcU0bGlOgDOziJvQYor/w5o8NJjftjA8g8Qx7YaViVNGSkgdVTkrQJdW0Gt3IFTYxAc51Kw7R1XBA7e5X/UwbcSQAOe/bBC7F8/2Z4rp4dvrLs7YSN16JjuviO4fFE9uvWwCkhDbvFIBZ1XeaD1Za1fU65x8) ``` c=[('['+' @'[d==n]+']',`d`)[t.month-12|25-n|n-d<0]for d in i("random").sample(range(1,26),25)] ``` ### Final With streamlined `import` statements (Thanks to Reinstate Monica) ``` import random,datetime as D t=D.date.today();n=t.day c=[('['+' @'[d==n]+']',`d`)[t.month-12|25-n|n-d<0]for d in random.sample(range(1,26),25)] while c:print' '.join(c[:5]);c=c[5:] ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 91 bytes *-1 bytes thanks to nwellnhof* ``` .put for (("[@]"if Date.today~~/12.(0?@(^26))$/),"[ ]"xx+$0,+$0^..25)[*;*].pick(*).rotor(5) ``` [Try it online!](https://tio.run/##DcNBCoAgEADAr4h02DXZSqhLhzr0CzGISpACRQzq0tetgQl7PLucKVyJWR8ZANej4c6yaUk7Jb8tz/tWjSKohxFm1SEWFUqumeH3XRa1/M9EqkUtemEouPUAgRR98hFazPkD "Perl 6 – Try It Online") ### Explanation: ``` .put for ( ... ) # Print for each of ("[@]"if Date.today~~/12.(0?@(^26))$/), # [@] if today is within the Christmas period "[ ]"xx+$0, # As many [ ]s as the current date +$0^..25 # All the number from today to the 25th [*;*] # Flatten .pick(*) # Randomise .rotor(5) # And split into chunks of 5 ``` [Answer] # JavaScript (ES6), ~~158 ... 150~~ 148 bytes *Saved 2 bytes thanks to @Deckerz* *Note: Strictly speaking, this should be marked as ES9 (ECMAScript 2018), in which the output format of `Date.prototype.toString` has been [standardized](https://www.ecma-international.org/ecma-262/9.0/#sec-date.prototype.tostring).* ``` f=(k=25,m,d=Math.random()*25+1|0,t=(new Date+0).match(/c ([01].|2[0-5])|:/)[1])=>k?(m^(m|=1<<d)?(d^t?d<t?'[ ]':d:'[@]')+` `[--k%5&&1]:'')+f(k,m):'' ``` [Try it online!](https://tio.run/##PYzLboMwFET3/YqrSI2vA@YlsUFQuui2X2A5ioNNQojtCkwrJP6detPOZkZHR/OQ33LupuHLM@uU3tMUVrdAJy14PXsILafr4Cc5raCk13BdYZkHewNi9Q98BISHNYQZw5Q6UAKDnb2WClwPjyV8/Itk7xscm6KMTayaT@nvySStcgbpqSijfMti3@CfHWU0MdJ3d0w7QJ7lItkKnrFS0K1KKc8Fbd7GFs0Zzdbkda1oi@rsW1X7lnAQpFIV4e@C0OjyAhfO2PhaHo@5qEhAPY6xoWHunbOze@rk6W7YI6X7Lw "JavaScript (Node.js) – Try It Online") ### How? `(new Date).toString()` returns the current date in the following format: ``` DDD MMM dd yyyy hh:mm:ss TimeZoneString ``` For instance: ``` Sun Dec 15 2019 12:29:35 GMT+0000 (Coordinated Universal Time) ``` We apply the following regular expression to this string: ``` /c ([01].|2[0-5])|:/ ``` It attempts to match a day of December less than \$26\$ (it's the only month whose 3-letter abbreviation ends in "c"). If not found, we force the first `:` separator to be matched instead, in order to prevent `match()` from returning `null`. Therefore, the variable \$t\$ (for 'today') is set to either a valid day of December, or *undefined* if we're outside the relevant period: ``` t = (new Date + 0).match(/c ([01].|2[0-5])|:/)[1] ``` \$f\$ is a recursive function that generates a random day \$d\$ in \$[1-25]\$ at each iteration and draws the corresponding slot in the calendar. It keeps track of drawn days in the bitmask \$m\$. ``` f = ( // f is a recursive function taking: k = 25, // k = remaining number of days to draw m, // m = bitmask of drawn days d = Math.random() * 25 // d = random day in [1-25] + 1 | 0, // t = ... // t = current day or undefined (see above) ) => // k ? // if k is not equal to 0: ( m ^ (m |= 1 << d) ? // if m is modified by setting the d-th bit: ( d ^ t ? // if d is not equal to t: d < t ? // if t is defined and d is less than t: '[ ]' // draw an opened window : // else: d // draw a closed window : // else: '[@]' // draw today's gift ) + // `\n ` // decrement k; append a linefeed at the end of a row [--k % 5 && 1] // or a space otherwise : // else: '' // we need to pick another day: leave k unchanged and // append nothing ) + f(k, m) // append the result of a recursive call : // else: '' // done: stop recursion ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~231~~ ~~222~~ ~~216~~ ~~202~~ ~~197~~ ~~193~~ 189 bytes ``` i=__import__ t=i("datetime").date.today() y=t.day d=[(((`x`,"[ ]")[x<y],"[@]")[x==y],`x`)[t.month<12or y>25]for x in i("random").sample(range(1,26),25)] while d:print' '.join(d[:5]);d=d[5:] ``` [Try it online!](https://tio.run/##HY1BCsMgFAX3nkLcRCEEIthFGkvvIZII2uaXqCH90Hj61HY3895itoJLTvI8QU8TxC3vOE0ENXDmHQaEGJjofthh9q5wQYrGOhTiteGcz8fcMkMtE@YYi618/7PWVeopDHYxJ1zGXuadlptU9lHhoJBorewu@Rxr4@3itgZe/Rl438qLaKUSlnwWWAP1w7ZDwoY23StD4t4Myoqr196owZ7nFw "Python 2 – Try It Online") -3 with many thanks to @AZTECCO Examples below use an earlier version of the answer but the formula is the same. Before December: [Try it online!](https://tio.run/##PY/BasMwEETv/oolOURqXBELHKgbldL2L4QgTrWp1VqSURbsfL0rm9LTMm92h9nhTl0Mcp6vKXpIbbB5OD/ERA/FymxLSM7jPyW1IEHRtnfGi@0bXmNC@MBP9BdMAt6jRRiTI8IAVb04IA/Vk8intF@yLPbUshHx56Yej7ywSjPGztO53GgwG66nE4kcb7J@XbVSfyAvcU3Cx0DdqZIxwWq8yNrkGjCBC3Br/dAjy998IatKeeSlrLkpxs71CLYZkgu0g534ji4wqw9NbfizVVbXjZnnXw "Python 2 – Try It Online") December after 25th: [Try it online!](https://tio.run/##PY9Ra8MgFIXf8ysu3UN1DVIFC0vrGGz/QoTaaRZH1GDvaPrrMxvGnu493zkcONMdh5zEsvQlRyg2uXpCnHLB52ZlzqLHEP0/RfVADLOzd0Kbpw//6ePFF7j8INge6yckDgzes/NwKwHRJ@ASahDEnr@wWoG7R6fzI1pSe66Kc9o4pQkh5/ncbjSYDdXzCVl1TdVvq1bqD9QQ1chiTjicuMgFVuNVSNNXMUNIcLVxGj2po7484a040FZIaprbEEYPrptKSLiFLfvOIRGn95009OiU07Izy/IL "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ ~~37~~ ~~32~~ ~~31~~ 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žeD₂‹žf‹P'@ú€…[ÿ]Dg25Ÿ«¦.r5ô» ``` -6 bytes thanks to *@Grimmy*. [Try it online](https://tio.run/##yy9OTMpM/f//6L5Ul0dNTY8adh7dl3YYRAeoOxze9ahpzaOGZdGH98e6pBuZHt1xaPWhZXpFpoe3HNr9/z8A) or [try it online with own specified month / day](https://tio.run/##yy9OTMpM/a/km59XkmGloBSjYGikEMql5JJYaQXkAIGhqULY/0iXR01Njxp2RhwGkQHqDod3PWpa86hhWfTh/bEu6UamR3ccWn1omV6R6eEth3b//w8A). **Explanation:** ``` že # Push the current day D # Duplicate it ₂‹ # Check if it's smaller than 26 žf # Push the current month  # Bifurcate it (short for Duplicate & Reverse copy) ‹ # And check if this is smaller than the month itself # (this will check 1-9 < 1-9 (falsey); 10 < 01 (falsey); 11 < 11 (falsey); # and 12 < 21 (truthy) - so this will only be truthy for 12 / December) P # Take the product of the day and both checks, # which result in either the day, or 0 if either check was falsey '@ '# Push character "@" ú # Pad it with the earlier number amount of spaces € # Map over each of these characters: …[ÿ] # Push string "[ÿ]", where the `ÿ` is automatically filled with the character Dg # Duplicate the list, and pop and push its length 25Ÿ # Create a list in the range [length, 25] « # And merge it to the earlier created list ¦ # Then remove the first item (either a "[ ]", or the "[@]" if the checks # were falsey) .r # Randomly shuffle the list 5ô # Split the list into sublists of size 5 » # Join each inner list by spaces, and these strings by newlines # (after which the result is output implicitly) ``` [Answer] # [R](https://www.r-project.org/), ~~113~~ 103 bytes ``` x=as.POSIXlt(Sys.time()) a=sample(25) if(x$mo>10&(y=x$md)<26){a[a<y]="[ ]";a[a==y]="[@]"} write(a,"",5) ``` [Try it online!](https://tio.run/##K/r/v8I2sVgvwD/YMyKnRCO4slivJDM3VUNTkyvRtjgxtyAnVcPIVJMrM02jQiU3387QQE2j0hbITNG0MTLTrE6MTrSpjLVVilaIVbIGcmxtwTyHWKVarvKizJJUjUQdJSUdU83//wE "R – Try It Online") A full program that prints an advert calendar as specified. [Answer] # [Red](http://www.red-lang.org), 135 bytes ``` d: now c: collect[repeat n 25[keep n]]if all[d/3 = 12 d/4 < 26][repeat n d/4[c/:n:"[ ]"]c/:n:"[@]"]random c loop 5[print take/part c 5] ``` [Try it online!](https://tio.run/##RY1BCgIxEATv@4pmPxCMxkNQ8A1ehzmEzAjLxiTEwD4/rih4qqJo6KYy7irEUwtZytO8VAW5bEP8B4gesaSksVPTqqEjwzpaVSsy8/JASInEHHHFwU5iTrjAnvm/3hNF47OfCTzzT2@7fi8Rp1RKhaPaltzRw6qmhtYR4XiMNw "Red – Try It Online") * [Before December](https://tio.run/##RY1BCsIwFAX3PcWj@5I2WsVQwTO4/fxFSL5QGpMQAx4/FhTcDcPAFPHtLp64Kzb69FQvEY@Y3s0bjNMwngc9Thc4A5dCEFepSBZbEaFn2kQyIvP6gA2BvDrgikl3Xh2xQJ/4X@@KnDLR9ATu@Ye3Hb9nuC6klDFTLmusqHYTlW2pcJi5tQ8) * [On Christmas](https://tio.run/##RY1BCsIwEEX3PcXHfYmNVjAoeAa3wyxCZoTSmIQY8PixoODu8d@HV1X6XYV4qD5JfpqXqiDldxcHO4@THe1@OiM4hByjhkZVi/qGtGlaVQsS8/KAj5HEHHDFZAcxR1xgT/x/bxMF45LbEXjHP7xt@C0jDDHngplKXVJD86ua4mtDwMy9fwA) * [After Christmas](https://tio.run/##RY1BCsIwEEX3PcXHfYmNVjAoeAa3wyxCZoTSmIQY8PixoODu8XmfV1X6XYV4qD5JfpqXqiDldxcHexonO9r9dEZwCDlGDY2qFvUNCXamVbUgMS8P@BhJzAFXTHYQc8Rl@/Pf3iYKxiW3I/COf3jb8FtGGGLOBTOVuqSG5lc1xdeGgJl7/wA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~76~~ 75 bytes ``` ⁶o”@;Ø[jⱮ;@Jị@ “j⁶ṖgqS^OßƭẸ#pÆẸ¥aRŀçĠrṬỤ{½9?ȷ²Yḅ»ḲḢ;Ɱ$ŒV12;Ɱ25¤i+Ɱ25ẊÇs5K€Y ``` [Try it online!](https://tio.run/##y0rNyan8//9R47b8Rw1zHawPz4jOerRxnbWD18Pd3Q5cjxrmZAHlHu6cll4YHOd/eP6xtQ937VAuONwGpA4tTQw62nB4@ZEFRQ93rnm4e0n1ob2W9ie2H9oU@XBH66HdD3dserhjkTXQOJWjk8IMjUAsI9NDSzK1wYyHu7oOtxebej9qWhP5/z8A "Jelly – Try It Online") A full program that prints an advent calendar. Longer than most Jelly programs because it has to call `__import__('datetime').datetime.today().month` and `__import__('datetime').datetime.today().day` in Python. If the date and time could be provided as an argument, it could be much shorter: # [Jelly](https://github.com/DennisMitchell/jelly), ~~35~~ 34 bytes ``` ⁶o”@;Ø[jⱮ;@Jị@ 12;Ɱ25¤i+Ɱ25ẊÇs5K€Y ``` [Try it online!](https://tio.run/##y0rNyan8//9R47b8Rw1zHawPz4jOerRxnbWD18Pd3Q5chkbWQJ6R6aElmdpgxsNdXYfbi029HzWtifz//7@hkY6hGQA "Jelly – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 112 bytes ``` x=[*1..25].shuffle;5.times{|c|puts x[c*5,5].map{|w|['[@]','[ ]',w][((d=Time.now).day-(d.month-12)*30)<=>w]}*" "} ``` [Try it online!](https://tio.run/##KypNqvz/v8I2WstQT8/INFavOKM0LS0n1dpUryQzN7W4uia5pqC0pFihIjpZy1QHqCA3saC6prwmWj3aIVZdRz1aAUiWx0ZraKTYhgB16OXll2vqpSRW6mqk6OXm55Vk6BoaaWoZG2ja2NqVx9ZqKSko1f7/DwA "Ruby – Try It Online") [Answer] # [C#](https://docs.microsoft.com/de-de/dotnet/csharp/), 267 bytes ``` using System;using System.Linq;class _{static void Main(){var n=DateTime.Now;var t=n.Month==12?n.Day:0;Console.WriteLine(string.Join(" ",Enumerable.Range(1,25).OrderBy(_=>new Random().Next(-9,9)).Select((d,i)=>(i%5==0?"\r\n":"")+(d<t?$"[ ]":d>t?$"{d}":"[@]"))));}} ``` [.Net Fiddle](https://dotnetfiddle.net/JDNqlm) ]
[Question] [ [Related OEIS sequence: A008867](http://oeis.org/A008867) ## Truncated triangular number A common property of triangular numbers is that they can be arranged in a triangle. For instance, take 21 and arrange into a triangle of `o`s: ``` o o o o o o o o o o o o o o o o o o o o o ``` Let's define a "truncation:" cutting triangles of the same size from each corner. One way to truncate 21 is as follows: ``` . . . o o o o o o o . o o o . . . o o . . ``` (The triangles of `.` are cut from the original). There are 12 `o`s remaining, so 12 is a truncated triangle number. # Task Your job is to write a program or a function (or equivalent) that takes an integer and returns (or use any of the standard output methods) whether a number is a truncated triangle number. # Rules * No standard loopholes. * The input is a non-negative integer. * A cut cannot have a side length exceeding the half of that of the original triangle (i.e. cuts cannot overlap) * A cut can have side length zero. # Test cases Truthy: ``` 0 1 3 6 7 10 12 15 18 19 ``` Falsy: ``` 2 4 5 8 9 11 13 14 16 17 20 ``` **Test cases for all integers up to 50: [TIO Link](https://tio.run/##DchNC8IgGADgvyIMZB@OfUS3CesS7BbVTQxeliyxvYUzIsT9ddvpgWcG91AzOD1CjOnJanRV76/2o1jCjvBcNtuQ0b4/K3iLy@srttd4H3BxgKMSCeGcYJ5iucuqlpTE3NrC5Fg0lNad6ZARj8wERgZ0alJ2kZxzHyRdD9bCb93XUoiykTLGPw)** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so submissions with shortest byte counts in each language win! [Answer] ## Haskell, ~~46~~ 45 bytes ``` f n|t<-scanl(+)0[1..n]=or[x-3*y==n|x<-t,y<-t] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hr6bERrc4OTEvR0Nb0yDaUE8vL9Y2vyi6QtdYq9LWNq@mwka3RKcSSMT@z03MzFOwVSgoyswrUVBR0NDRtNGyS7NRsYs20NMzMoj9DwA "Haskell – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 46 bytes ``` f n=or[mod(gcd(p^n)(4*n-1)-5)12<3|p<-[1..4*n]] ``` [Try it online!](https://tio.run/##DcgxCoAgFADQqzg0aOBHrbY6iRhIZkn2FXPs7tYb32mfa4@xNU9wSUXfydFjczSvyOjYI5eMT0yqeXjzzLUE@NOYdtuASy4Ba@dDrHshFFMFz4gWAEoI0z4 "Haskell – Try It Online") Having thrown a bunch of number theory at the problem (thanks @flawr), I found this characterization: > > **n** is a truncated triangular number exactly if in the prime factorization of **4n-1**, any prime of the form **5 mod 12** or **7 mod 12** appears an even number of times. > > > This means, for instance, that **4n-1** may not be divisible by 5 unless it's further divisible by **52=25** and the total number of **5** factors is even. Haskell doesn't have a factorization-built-in, but we can improvise. If we work with factorizations into primes powers like **12=3\*4**, we can use the equivalent statement: > > **n** is a truncated triangular number exactly if the factorization of **4n-1** into prime powers has no terms of form **5 mod 12** or **7 mod 12**. > > > We can extract the power of a prime **p** appearing in **k** as `gcd(p^k)k`. We then check that the result **r** is not 5 or 7 modulo 12 as `mod(r-5)12>2`. Note that **r** is odd. We also check composites as **p**, lacking a way to tell them from primes, but the check will pass as long as its factors do. Finally, negating `>2` to `<3` and switching `True`/`False` in output saves a byte by letting us use `or` instead of `and`. --- A related characterization is that the divisors of **4n-1** taken modulo 12 have more total 1's and 11's than 5's and 7's. **53 bytes** ``` f n=sum[abs(mod k 12-6)-3|k<-[1..4*n],mod(4*n)k==1]<0 ``` [Try it online!](https://tio.run/##DckxDoQgEADAr2xhAebYgF6s5CWEAqNEAqxGsPPvaDfJ7K7ELaXWPJAudzZuKSwfK0RQg5i4GJ84C6MQ/z3Z3zfsA49aKzvLll0gfV6BaudDqtsFjI6KnoORiIOUtr0 "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes ``` f=lambda n,b=1:b>n+1or(8*n-2+3*b*b)**.5%1>0<f(n,b+1) ``` [Try it online!](https://tio.run/##DcpBCoMwEAXQq8ymkEyqZCyFIupFpIsMmjbQ/kjIpqdPfet3/Oo7Y2gtzp/w1S0QrjrLqAuc5GIejG5wN1ZWy9zfL7L4KZozObHtKAmVVlDMhUAJVAJeuxHvLaVIyJXObJ/tDw "Python 2 – Try It Online") Outputs `True`/`False` flipped. Uses this characterization: > > **n** is a truncated triangular number exactly if **8n-2** has form **a2-3b2** for some integers **a,b**. > > > We check whether any `8*n-2+3*b*b` is a perfect square for any `b` from `1` to `n+1`. We avoid `b=0` because it gives an error for a square root of a negative when `n==0`, but this can't hurt because only odd `b` can work. Done non-recursively: **[Python 2](https://docs.python.org/2/), 53 bytes** ``` lambda n:0in[(8*n-2+3*b*b)**.5%1for b in range(~n,0)] ``` [Try it online!](https://tio.run/##Rcq9DkAwFAbQV7mLpL1@UkQiEk@CoQ2lCR9pLBavXkzmc47rXHYUwbZ9WPVmRk1olEMnakZaxCUbNpI5q6Lc7p4MOZDXmCdxI1FyCId3OKkDfYyfc6UkOUtW4F0P "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 0r+\ð_÷3f⁸ ``` A monadic link accepting an integer and returning a truthy value (a non empty list) or a falsey value (an empty list). **[Try it online!](https://tio.run/##ASEA3v9qZWxsef//MHIrXMOwX8O3M2bigbj/w4fFkuG5mP//MTI "Jelly – Try It Online")** (footer performs Python representation to show the `[0]` results as they are) ...or see a [test-suite](https://tio.run/##y0rNyan8/9@gSDvm8Ib4w9uN0x417gByjQyO7jFUMDjcbv@oaY2K@38A "Jelly – Try It Online") (runs for 0 to 20 inclusive) ### How? Given N, forms the first N triangle numbers, subtracts N from each, divides each result by 3 and keeps any results that are one of the first N triangle numbers. ``` 0r+\ð_÷3f⁸ - Link: integer, N e.g. 7 0r - zero inclusive range N [ 0, 1, 2, 3, 4, 5, 6, 7] +\ - cumulative reduce with addition [ 0, 1, 3, 6, 10,15, 21, 28] ð - start a new dyadic link with that, t, on the left and N on the right _ - t subtract N (vectorises) [ -7,-6,-3, -1, 3, 8, 14, 21] ÷3 - divide by three (vectorises) [-2.33,-2,-1.33,-0.33,1,2.67,4.67, 7] ⁸ - chain's left argument, t [ 0, 1, 3, 6, 10,15, 21, 28] f - filter keep [ 1 ] - a non-empty list, so truthy ``` [Answer] # [R](https://www.r-project.org/), ~~45~~ 43 bytes *-2 bytes thanks to [Vlo](https://codegolf.stackexchange.com/users/30693/vlo)* ``` (n=scan())%in%outer(T<-cumsum(0:n),3*T,"-") ``` [Try it online!](https://tio.run/##K/r/XyPPtjg5MU9DU1M1M081v7QktUgjxEY3uTS3uDRXw8AqT1PHWCtER0lXSfO/icV/AA "R – Try It Online") I'm fairly sure we only need to check the first `n` triangular numbers for this; brute force checks if `n` is in the pairwise differences of the triangular numbers and their triples. [Answer] # [Pyt](https://github.com/mudkip201/pyt), 10 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` Đř△Đ3*ɐ-Ƒ∈ ``` [Try it online!](https://tio.run/##ARwA4/9weXT//8SQxZnilrPEkDMqyZAtxpHiiIj//zIw) Explanation: ``` Implicit input Đ Duplicate input ř Push [1,2,...,input] △ For each element k in the array, get the kth triangle number Đ Duplicate the top of the stack 3* Multiply by 3 ɐ ɐ - All possible: - subtractions between elements of the two arrays Ƒ Flatten the nested array ∈ Is the input in the array ``` [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` f a|u<-[0..a]=or[x^2+x-3*(y^2+y)==2*a|x<-u,y<-u] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hsabURjfaQE8vMdY2vyi6Is5Iu0LXWEujEsio1LS1NdJKrKmw0S3VqQQSsf9zEzPzbAuKMvNKVNIyc0pSixTSQJqNDGL/AwA "Haskell – Try It Online") [Answer] # [J](http://jsoftware.com/), 22 bytes ``` e.[:,@(-/3*])2![:i.2+] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/U/WirXQcNHT1jbViNY0Uo60y9Yy0Y/9rcvk56Sk4JienFpSkpiiUJeaUphZzpSZn5CtoKNcppCmklqUWVWoqZOqZGoCVBqVmpSZjU6qr54Ci@j8A "J – Try It Online") Straightforward and somewhat-poorly-golfed approach. # Explanation ``` e.[:,@(-/3*])2![:i.2+] 2![:i.2+] Range of triangular numbers up to N (-/3*]) All possible subtractions of 3T from T where T is triangular up to the Nth triangular number ,@ Flattened into a single list e. Is N in the list? ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` tQ:qYst!3*-m ``` Outputs `1` for truthy, `0` for falsy. [Try it online!](https://tio.run/##y00syfn/vyTQqjCyuETRWEs39/9/QwMA) Or [verify all test cases](https://tio.run/##DcYrDoAwFEVBf3aBJSHp7R80GyDB4MBTQej@H4yadvXbTuvb8hxvH8I4NVt3c4hApqC/HiVU0YwnkqjMSCigiDIqePcB). ### How it works, with example Consider input `6` ``` t % Implicit input. Duplicate % STACK: 6, 6 Q:q % Increase, range, decrease element-wise. Gives [0 1 ... n] % STACK: 6, [0 1 ... 6] Ys % Cumulative sum % STACK: 6, [0 1 3 6 10 15] t! % Duplicate, transpose % STACK: 6, [0 1 3 6 10 15], [0; 1; 3; 6; 10; 15] 3* % Times 3, element-wise % STACK: 6, [0 1 3 6 10 15 21 28 36 45 55], [0; 3; 9; 18; 30; 45] - % Subtract, element-wise with broadcast % STACK: 6, [ 0 1 3 6 10 15 21; -3 -2 0 3 7 12 18; -9 -8 -6 -3 1 6 12; -18 -17 -15 -12 -8 -3 3; -30 -29 -27 -24 -20 -15 -9; -45 -44 -42 -39 -35 -30 -24; -63 -62 -60 -57 -53 -48 -42] m % Ismember. Implicit display % STACK: 1 ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~65 57 52~~ 48 bytes ``` ->n,b=0{b+=1;(8*n-2+3*b*b)**0.5%1==0||b<n&&redo} ``` [Try it online!](https://tio.run/##NYy7DoIwAEV3voKQSLSIaWkbn3X0C9wMgw0SB1NJoQMRv70@ejud3EeOdXr0rfLl0Sy1oi9dKLafb4gpq4ITTfSCELqSM6YUnSZ9MHlub83z7Ts39Gl2tm64j7ss6dL2Qus/WAAPWKOM4xYrelGBMlD@8ledBP/p@uijHk8c4WEChK9C5pH4CWRJa/8B "Ruby – Try It Online") Inspired by [xnor's python answer](https://codegolf.stackexchange.com/a/157335/77598) [Answer] # [Python 3](https://docs.python.org/3/), 84 bytes ``` lambda n:1in set([((8*(n+(i*(i+1)/2)*3)+1)**0.5)%4==1for i in range(n)])or n in[0,1] ``` [Try it online!](https://tio.run/##XctBCsIwEIXhdXuK2QgzqWhjLUghJ6ldRGzsQDMJMRtPH@PW3cf/ePGTtyBDYR9DyuBt3lpn7mW3/vG0IJNmgfeacUa8KZQOWSF3ms4XUgNVKNWfRjpcjdEuJGCoh2TltaLQQrVILXN/1Ev520dNU9uwA4f8UxMTS64uXw "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` ÅT3*+8*>ŲZ ``` [Try it online!](https://tio.run/##DcY9CoQwEIDR/juFWPoDmWSGmMZTWG23C3sFIWDrhbyAYA4WA694zr4/@ddjz7mWcwvDuAxrOZ/rU3Nf7m5eu3L3U3UIgYi0JEJEPWqYx2MkRJGIV0KTUMXcCw "05AB1E – Try It Online") **Explanation** ``` ÅT # get a list of triangle numbers upto input 3* # multiply each by 3 + # add input to each 8* # multiply each by 8 > # increment each Ų # check each for squareness Z # max ``` This is based on the fact that a number **T** is triangular if `8T+1` is an odd perfect square. We start on the list of triangles we could truncate, calculate the possible larger triangles based on them and check if it in fact is triangular. [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 bytes ``` ò å+ d@Zd_-3*X¶U ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=8iDlKyBkQFpkXy0zKli2VQ==&input=OA==) | [Check all test cases](https://ethproductions.github.io/japt/?v=1.4.5&code=y/Ig5SsgZEBaZF8tMypYtkQ=&input=WzAsMSwzLDYsNywxMCwxMiwxNSwxOCwxOSwyLDQsNSw4LDksMTEsMTMsMTQsMTYsMTcsMjBd) --- ## Explanation ``` :Implicit input of integer U ò :Range [0,U] å+ :Cumulative reduction by addition d@ :Does any X in array Z return true when passed through this function? Zd_ : Does any element in Z return true when passe through this function? -3*X : Subtract 3*X ¶U : Check for equality with U ``` --- [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 36 bytes ``` D,g,@,.5^di= L,ßR¬+A↑>3€*A€+8€*1€+ºg ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ13HQUfPNC4l05bLR@fw/KBDa7QdH7VNtDN@1LRGyxFIaFuAWIYg1qFd6f9VchJzk1ISFQztFAzNufy5kPkWXP7/AQ "Add++ – Try It Online") ]
[Question] [ ## Introduction A decimal is terminating if it has a finite number of decimal digits. For example, 0.4 (2/5) is terminating because it has one decimal digit. A decimal is purely periodic if it has an infinite number of decimal digits and has no decimal digits before its repetent (the part of the decimal that repeats.) For example, 0.142857142857142… (1/7) is purely periodic because it has a repetend 142857, which starts repeating immediately after the decimal point. A decimal is eventually periodic if it has an infinite number of decimal digits and has a finite number of decimal digits before its repetent (the part of the decimal that repeats.) For example, 0.166666666666666… (1/6) is eventually periodic because its repetend 6 starts repeating after a 1. ## Your task Write a program or function that, when given numbers *p* and *q* (integers, 0 <= *p* < *q* <= 100), will determine if the decimal representation of *p*/*q* is terminating, purely periodic, or eventually periodic. You must output `a` if it's Terminating (i.e. 0.1), `b` if it's Purely Periodic (i.e. 0.333...), or `c` if it's Eventually Periodic (i.e. 0.166...), where `a`, `b`, and `c` are any distinct, constant strings of your choice. ## Test cases ``` 0/1 => Terminating 0/2 => Terminating 1/2 => Terminating 0/3 => Terminating 1/3 => Purely Periodic 2/3 => Purely Periodic 0/4 => Terminating 1/4 => Terminating 2/4 => Terminating 3/4 => Terminating 0/5 => Terminating 1/5 => Terminating 2/5 => Terminating 3/5 => Terminating 4/5 => Terminating 0/6 => Terminating 1/6 => Eventually Periodic 2/6 => Purely Periodic 3/6 => Terminating 4/6 => Purely Periodic 5/6 => Eventually Periodic 0/7 => Terminating 1/7 => Purely Periodic 2/7 => Purely Periodic 3/7 => Purely Periodic 4/7 => Purely Periodic 5/7 => Purely Periodic 6/7 => Purely Periodic 0/8 => Terminating 1/8 => Terminating 2/8 => Terminating 3/8 => Terminating 4/8 => Terminating 5/8 => Terminating 6/8 => Terminating 7/8 => Terminating 0/9 => Terminating 1/9 => Purely Periodic 2/9 => Purely Periodic 3/9 => Purely Periodic 4/9 => Purely Periodic 5/9 => Purely Periodic 6/9 => Purely Periodic 7/9 => Purely Periodic 8/9 => Purely Periodic 0/10 => Terminating 1/10 => Terminating 2/10 => Terminating 3/10 => Terminating 4/10 => Terminating 5/10 => Terminating 6/10 => Terminating 7/10 => Terminating 8/10 => Terminating 9/10 => Terminating 0/11 => Terminating 1/11 => Purely Periodic 2/11 => Purely Periodic 3/11 => Purely Periodic 4/11 => Purely Periodic 5/11 => Purely Periodic 6/11 => Purely Periodic 7/11 => Purely Periodic 8/11 => Purely Periodic 9/11 => Purely Periodic 10/11 => Purely Periodic 0/12 => Terminating 1/12 => Eventually Periodic 2/12 => Eventually Periodic 3/12 => Terminating 4/12 => Purely Periodic 5/12 => Eventually Periodic 6/12 => Terminating 7/12 => Eventually Periodic 8/12 => Purely Periodic 9/12 => Terminating 10/12 => Eventually Periodic 11/12 => Eventually Periodic 0/13 => Terminating 1/13 => Purely Periodic 2/13 => Purely Periodic 3/13 => Purely Periodic 4/13 => Purely Periodic 5/13 => Purely Periodic 6/13 => Purely Periodic 7/13 => Purely Periodic 8/13 => Purely Periodic 9/13 => Purely Periodic 10/13 => Purely Periodic 11/13 => Purely Periodic 12/13 => Purely Periodic 0/14 => Terminating 1/14 => Eventually Periodic 2/14 => Purely Periodic 3/14 => Eventually Periodic 4/14 => Purely Periodic 5/14 => Eventually Periodic 6/14 => Purely Periodic 7/14 => Terminating 8/14 => Purely Periodic 9/14 => Eventually Periodic 10/14 => Purely Periodic 11/14 => Eventually Periodic 12/14 => Purely Periodic 13/14 => Eventually Periodic 0/15 => Terminating 1/15 => Eventually Periodic 2/15 => Eventually Periodic 3/15 => Terminating 4/15 => Eventually Periodic 5/15 => Purely Periodic 6/15 => Terminating 7/15 => Eventually Periodic 8/15 => Eventually Periodic 9/15 => Terminating 10/15 => Purely Periodic 11/15 => Eventually Periodic 12/15 => Terminating 13/15 => Eventually Periodic 14/15 => Eventually Periodic ``` You can find all test cases [here](http://pastebin.com/raw/We01u4eF). You are allowed to choose your own 3 values for the output, but it must be clear as to which one it is. Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins. ## Hints Terminating: > > The prime factorization of a terminating decimal's denominator in simplest form consists only of 2s and 5s. > > > Purely Periodic: > > The prime factorization of a purely periodic decimal's denominator in simplest form does not include any 2s or 5s. > > > Eventually Periodic: > > The prime factorization of an eventually periodic decimal's denominator in simplest form includes at least one 2 or 5, but also includes other numbers. > > > ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=95926,OVERRIDE_USER=12537;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## JavaScript (ES6), ~~70~~ .. ~~68~~ 53 bytes ``` f=(a,b,s=[],x)=>a?(s[a]^=a)?f(a*10%b,b,s,x||a):x==a:0 ``` Returns **0** for terminating, **true** for purely periodic and **false** for eventually periodic. ### How it works What we're doing here is actually simulating a division by hand: 1. `a?...:0` - If the numerator is zero, we stop here and return `0`. The sequence is *terminating*. 2. `(s[a]^=a)?...:x==a` - If we've already encountered this numerator before, it means that the sequence is periodic and is going to repeat forever. We stop here and return either `true` if `a` is equal to the first value `x` of the sequence (*purely periodic*) or `false` if it's not (*eventually periodic*). 3. `f(a*10%b,b,s,x||a)` - Else, we multiply the numerator `a` by 10. We compute the remainder of the division by the denominator `b`. And we repeat the process by using this remainder as the new numerator. (We also pass `a` as the first value of the sequence if it's not already stored in `x`.) ### Example * **Blue**: numerator = 1 * **Green**: denominator = 7 * **Red**: multiplications by 10 * **Black**: remainders * **Gray**: quotient digits (we don't really care about them here, and the above code is not computing them at all) [![division](https://i.stack.imgur.com/UfB9t.png)](https://i.stack.imgur.com/UfB9t.png) [Answer] # Python, ~~62~~ ~~61~~ 59 bytes ``` f=lambda n,d,r=[0,0]:(r[:3]+r).count(n)or f(10*n%d,d,r+[n]) ``` Prints **1** for eventually periodic, **2** for purely periodic, and **4** for terminating. Verify all test cases on [repl.it](https://repl.it/Dt9c/3). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` :gÆfḍ⁵ṢQ¬Ḅ ``` Accepts denominator and numerator (in that order) as arguments. Returns **0** for terminating, **1** for purely periodic, and **2** for eventually periodic. [Try it online!](http://jelly.tryitonline.net/#code=OmfDhmbhuI3igbXhuaJRwqzhuIQ&input=&args=MTE+NA) or [verify all test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), n (numerator) g Compute the GCD of d and n. : Divide d by the GCD, yielding the denominator of the simplified form. Æf Yield all prime factors of the previous result. ḍ⁵ Test 10 for divisibility by each prime factor. This yields 1 for 2 and 5, 0 for all other primes. Ṣ Sort the resulting Booleans. Q Unique; deduplicate the sorted Booleans. ¬ Logical NOT; replace 0 with 1 and vice versa to yield one of the following arrays. [ ] <- no prime factors (denominator 1) [ 0] <- only 2 and 5 [1 ] <- neither 2 nor 5 [1, 0] <- mixed Ḅ Unbinary; convert from base 2 to integer. This maps [] and [0] to 0, [1] to 1, and [1, 0] to 2. ``` [Answer] # Perl, ~~49~~ ~~46~~ 45 bytes Includes +3 for `-p` Based on [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)'s elegant idea but implemented in a perlish way Give input numbers on STDIN ``` terminating.pl <<< "2 26" ``` `termninating.pl`: ``` #!/usr/bin/perl -p / /;1until$a{$_=$_*10%$' or$`}++;$_=$a{$`} ``` Prints a 2 if terminating. 1 if periodic and nothing if eventually periodic [Answer] ## Batch, 247 bytes ``` @set/af=%1,g=%2 :g @if not %f%==0 set/ah=g,g=f,f=h%%g&goto g @set/ae=d=%2/g :l @set/ag=-~!(d%%2)*(!(d%%5)*4+1) @if not %g%==1 set/ad/=g&goto l @if %d%==1 (echo Terminating)else if %d%==%e% (echo Purely Periodic)else echo Eventually Periodic ``` Uses my fast gcd10 trick from [Fraction to exact decimal](https://codegolf.stackexchange.com/questions/89215/fraction-to-exact-decimal). Obviously I could save a bunch of bytes by using a custom output format. [Answer] # JavaScript (ES6), ~~91~~ ~~88~~ ~~85~~ ~~79~~ ~~75~~ ~~74~~ 78 bytes ``` f=(n,d,g=(a,b)=>b?g(b,a%b):a,t=g(d/=c=g(n,d),10))=>n*~-d?t-1?f(n/c,d/t)/0:1:+f ``` Outputs `NaN` for terminating, `1` for purely periodic, and `Infinity` for eventually periodic. ### Test snippet ``` f=(n,d,g=(a,b)=>b?g(b,a%b):a,t=g(d/=c=g(n,d),10))=>n*~-d?t-1?f(n/c,d/t)/0:1:+f l=(n,d)=>console.log(n+"/"+d+":",f(n,d)) for(i=1;i<10;i++)for(j=0;j<i;j++)l(j,i); ``` ## Explanation First, we divide both **n** and **d** by **gcd(d,n)**, to reduce the fraction to its simplest form. This lets us avoid situations like **2/6** where the result would otherwise be calculated as purely periodic. We also define variable **t** as **gcd(d,10)**; this will be used later. The first check is whether **n** is **0** or **d** is **1**. If **n\*(d-1)** is 0, we return `+f`, or **NaN**: the fraction is **terminating**. The next check is whether **t** is **1**. If so, we return **1**: the fraction is **purely periodic**. If **t** is *not* **1**, we divide **d** by **t**, run the whole function again, and divide by 0. If **n/(d/t)** is terminating, this returns **NaN/0 = NaN**: the fraction is **terminating**. Otherwise, it returns **1/0 = Infinity**: the fraction is **eventually periodic**. [Answer] # Mathematica, 41 bytes ``` Ordering@{d=Denominator@#,GCD[d,10^d],1}& ``` Outputs `{3,1,2}` if the input has a terminating decimal expansion, `{2,3,1}` if the input has a purely periodic decimal expansion, and `{3,2,1}` if the input has an eventually periodic decimal expansion. Based on the sneaky trick: if `d` is the denominator of a fraction in lowest terms, then the greatest common divisor of `d` and `10^d` equals `d` if `d` has only 2s and 5s in its prime factorization; equals `1` if `d` has neither 2s nor 5s in its prime factorization; and equals some integer in between if `d` has 2s/5s and other primes. The `Ordering` function just reports where the smallest, next smallest, and largest elements of the triple are, with ties broken left-to-right. Flaw: returns the variant output `{1,2,3}` instead of `{3,1,2}` if the input is 0. # Mathematica, 46 bytes, perverse ``` b[a][[Log[d=Denominator@#,GCD[d,10^d]]]][[1]]& ``` Returns `a[[1]]` if the input has a terminating decimal expansion, `b[[1]]` if the input has a purely periodic decimal expansion, and `b[a]` if the input has an eventually periodic decimal expansion. Throws an error in all cases! As above, we want to know whether that greatest common divisor equals 1, d, or somewhere in between. The base-d logarithm of that gcd equals 0, 1, or something in between. Now we start torturing Mathematica. `b[a][[n]]` denotes the `n`th part of the expression `b[a]`. So `b[a][[1]]` returns `a`; `b[a][[0]]` returns `b`; and `b[a][[x]]`, where `x` is a number between 0 and 1, makes Mathematica throw the error "Part::pkspec1: The expression `x` cannot be used as a part specification." and returns `b[a][[x]]` unevaluated. This already distinguishes the three cases appropriately, except that the output for the eventually periodic case is `b[a][[x]]`, which is non-constant because `x` is the actual logarithm of something. So then we apply `[[1]]` to the outputs already described. Because of how Mathematica internally represents `b[a][[x]]`, the result of `b[a][[x]][[1]]` is simply `b[a]`. On the other hand, applying `[[1]]` to `a` results in a different error "Part::partd: Part specification a[[1]] is longer than depth of object." and returns `a[[1]]` unevaluated (and similarly for `b`). Flaw: lies about the input 0, returning `b[a]` instead of `a[[1]]`. [Answer] # C 173 Bytes Takes two integers from stdin, prints 1 for purely periodic, -1 for eventually periodic, and 0 for terminating. ``` int r;main(_,n,d){_-1?_-2?d-1?d%2&&d%5?r=1:d%2?main(3,n,d/5):main(3,n,d/2),r=r?-1:0:r=0:d?main(2,d,n%d):r=n:scanf("%d %d",&n,&d),main(2,n,d),main(3,n/r,d/r),printf("%d",r);} ``` Ungolfed: ``` // returns 1 for periodic, 0 for terminating, <0 for eventually periodic int periodic(int num, int den) { // 3 if (den == 1) return 0; if (den % 2 && den % 5) // pure periodic return 1; if (den % 2) return periodic(num,den/5) ? -1 : 0; return periodic(num,den/2) ? -1 : 0; } int gcd(int num, int den) { // 2 if (den) return gcd(den,num%den); return num; } int main(n,d) // 1 { scanf("%d %d",&n,&d); printf("%d",periodic(n/gcd(n,d),d/gcd(n,d))); return 0; } ``` Half-golfed: ``` int r;main(_,n,d){ _-1? _-2? // periodic d-1? d%2&&d%5? r=1: d%2? main(3,n,d/5): //periodic main(3,n,d/2), //periodic r=r?-1:0: r=0 // gcd :d?main(2,d,n%d):r=n // gcd // main :scanf("%d %d",&n,&d), main(2,n,d), // gcd main(3,n/r,d/r), // periodic printf("%d",r); } ``` [Answer] # [Actually](http://github.com/Mego/Seriously), 15 bytes This is based on [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/95934/47581). **0** is terminating, **1** is purely periodic, and **2** is eventually periodic. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=4pa8Tnk5deKZgCVTUuKZgmLilZQyQMK_&input=WzEsMjBd) ``` ▼Ny9u♀%SR♂b╔2@¿ ``` **Ungolfing** ``` Implicit input [a, b]. ▼ Divide a and b by gcd(a,b). Ny Get the unique prime divisors of the reduced denominator. 9u Push 10. ♀% 10 mod every member of uniq_p_d. SR Sort the mods and reverse. ♂b Logical buffer. Converts every (10 % p != 0) to 1, and everything else to 0. Meaning if 2 or 5 divided b, they are now 0, and every other prime is now 1. ╔ Uniquify the list. If terminating, return [0]. If purely periodic, return [1]. If eventually periodic, return [1, 0]. Else, (if b was 1), return []. 2@¿ Convert from binary to decimal. Return 0, 1, or 2. Implicit return. ``` [Answer] # Mathematica, 44 bytes ``` If[ListQ@Last@#,Length@#==1]&@@RealDigits@#& ``` Returns `Null` for Terminating, `True` for purely periodic, and `False` for eventually periodic. # Explanation ``` RealDigits ``` Find the decimal expansion of N. (repeated digits are surrounded by an extra head `List {}`). ``` ListQ@Last@# ``` Check whether the last element of the decimal expansion is a `List`. ``` Length@#==1 ``` If the above condition is `True`, check whether the entire decimal expansion consists of one thing. (A `List` counts as one entity). (returns `True` or `False`) (If the condition is `False`, then a `Null` is returned because there is no third argument for `If`) [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~31~~ 27 bytes ``` AQ={P/HiGH?l@H=j25T?l-HT1Z2 ``` Input ``` 4,12 ``` You can try it [here](https://pyth.herokuapp.com/?code=AQ%3D%7BP%2FHiGH%3Fl%40H%3Dj25T%3Fl-HT1Z2&input=4%2C12&debug=0). Prints **1** for eventually periodic, **2** for purely periodic, and **0** for terminating. This is my first time answering in codegolf. Any suggestions are welcome. ## Explanation ``` AQ // 1st element to G and 2nd element to H ={P // Assign unique prime factors to H /H // Simplify denominator iGH // Find GCD ?l // Check length of filtered H @H // Filter H by Y =j25T // Assign a set [2,5] to T ?l-HT // Check length of H - T 1Z2 // Print result ``` Note that [2,3] filtered by [2,5] = [2] but [2,3,5] - [2,5] = [3]. [Answer] ## PARI/GP, 64 bytes ``` f(x,y)=if(setminus(factor(y=y/gcd(x,y))[,1]~,[2,5]),gcd(y,10)>1) ``` Outputs nothing for terminating, 0 for purely and 1 for eventually periodic. Not very fancy, I hoped for something better when I started. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 11 bytes Saved 5 bytes thanks to @Adnan! ``` ¿²r/fTrÖbÙJ ``` Prints 0 for Purely Periodic, 1 for Terminating, and 10 for Eventually Periodic. Explanation: ``` # Implicit input # Implicit input ¿ # Take GCD of numbers ² # Push top value from input register r # Reverse stack order / # Divide (denominator by GCD) f # Find unique prime factors TrÖ # Test 10 for divisibility b # Convert (True -> 1, False -> 0) Ù # Deduplicate array J # Join chars in array # Implicit print ``` Input is taken as *p* newline *q*. [Try it online!](http://05ab1e.tryitonline.net/#code=wr_CsnIvZlRyw5Ziw5lK&input=MQoz) [Answer] # PHP, 126 Bytes ``` $d=$argv[2];$a[]=$n=$argv[1];while($n%$d&&!$t){$n*=10;$t=in_array($n%=$d,$a);$a[]=$n;}if($a[1]&&$t)$t+=$a[0]!=end($a);echo+$t; ``` Prints 0 for terminated and 1 for purely periodic 2 for eventually. Let me explain if a numerator is twice in the array here starts the periodic session if it is terminated the `echo end($a);` value is `0` If you not trust me put `$t=count($a)>$d?2:0;` in the loop To make it more clear please add `print_r($a);` or `var_dump($a);` or `json_encode($a);` after the loop you can see one numerator twice or a zero at the end of the array if a numerator is twice count the items between the two items and you can get the length of the periodic and you can see the position by the first numerator where the periodic begins So after that we can find the position and the length of the periodic sequence with `if($t){echo $p=array_search(end($a),$a);echo $l=count($a)-$p-1;}` ## Visualize the periodic ``` $d=$argv[2]; $a[]=$n=$argv[1]; #array numerator $r[]=$n/$d^0; #array result of the division $r[]="."; while($n%$d&&!$t){ $n*=10; $n-=$d*$r[]=$n/$d^0; $t=in_array($n%=$d,$a); #stop if numerator is twice $a[]=$n; } if($a[1]&&$t)$t+=$a[0]!=end($a); #periodic term starts directly? if($t){ echo $p=array_search(end($a),$a)."\n"; #output the beginning position of the periodic term echo $l=count($a)-$p-1; #output the length of the periodic term echo "\n"; echo str_repeat(" ",2+$p).str_repeat("_",$l-1)."\n"; #visualize the periodic term #echo join(array_slice($r,0,1+$p)).join(array_slice($r,1+$p))."\n";# if you want only the periodic term echo join($r); #result if the division } echo+$t; # 0 terminated 1+2 periodic 2 periodic start not directly ``` ## Output visualize the periodic term ``` 1/18 _ 0.05 1/12 _ 0.083 1/13 ______ 0.076923 1/14 ______ 0.0714285 ``` An other way with 130 Bytes ``` $r=bcdiv(($z=$argv)[1],$z[2],400);for($p=2;$i++<200;)if(substr($r,2,$i)==substr($r,2+$i,$i))$p=1;echo strlen(rtrim($r,0))<50?0:$p; ``` Expanded Version ``` $r=bcdiv(($z=$argv)[1],$z[2],400); # 100 is the maximal denominator # we need a string length with the double value of the sum the length from 1 until the denominator for($p=2;$i++<200;)if(substr($r,2,$i)==substr($r,2+$i,$i))$p=1; # all results begin with 0. #take two substrings with the same length after that and comparize both. #if we found 2 same substrings we have a periodic which starts at the first decimal place echo strlen(rtrim($r,0))<50?0:$p; # if we can trim the length of the result we have a terminated result ``` ]
[Question] [ Given an unsorted list of unique, positive integers, output the shortest list of the longest possible ranges of sequential integers. # INPUT * An unsorted list of unique, positive integers + e.g. `9 13 3 11 8 4 10 15` * Input can be taken from any one of the following: + `stdin` + command-line arguments + function arguments # OUTPUT * An ordered list of ranges or individual values printed on one line to stdout or your language's closest similar output. + If two or more sequential integers (sequential by value, not by location in the list) are present, they will be denoted as an inclusive range using -, e.g. `8-11` + All other integers are simply printed with no other notation + A single space will delimit the output * Numbers not present in the input should not be in the output, e.g. `3 5 6` cannot be shortened to `3-6` because `4` is not present # EXAMPLES **Successful:** ``` IN> 9 13 3 11 8 4 10 15 6 OUT> 3-4 6 8-11 13 15 IN> 11 10 6 9 13 8 3 4 15 OUT> 3-4 6 8-11 13 15 IN> 5 8 3 2 6 4 7 1 OUT> 1-8 IN> 5 3 7 1 9 OUT> 1 3 5 7 9 ``` **Wrong:** ``` IN> 9 13 3 11 8 4 10 15 OUT> 3-15 ``` Range contains values not in the input ``` IN> 9 13 3 11 8 4 10 15 OUT> 3 4 8 9 10 11 13 15 ``` All sequential values should be represented as a range ``` IN> 9 13 3 11 8 4 10 15 OUT> 3-4 8-9 10-11 13 15 ``` Divided range, `8-9` and `10-11` should be `8-11` ``` IN> 9 13 3 11 8 4 10 15 OUT> 8-9 13 10-11 3-4 15 ``` Output not ordered correctly # RULES * [Standard loopholes are disallowed](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * If your language has a function to do this it's not allowed * You may write a full program, or a function * trailing whitespace doesn't matter # SCORING * Least bytes wins [Answer] # Python 2, ~~123~~ 120 bytes ``` N=sorted(map(int,raw_input().split(' ')));print(''.join((''if n+1in N else'-'+`n`)if n-1in N else' '+`n`for n in N)[1:]) ``` If the input can be a list as a function argument then (thanks mbomb007 and xnor for the conditionals) # ~~93~~ ~~90~~ 81 bytes ``` def f(N):print''.join((' '+`n`,`-n`*-~-(n+1in N))[n-1in N]for n in sorted(N))[1:] ``` (77 bytes if leading whitespace is acceptable - drop the final `[1:]`) [Answer] # JavaScript (ES6): ~~171~~ ~~154~~ 140 ~~137~~ bytes Thanks edc65 and vihan1086 for the tips! ~~`[...n]` is very nice~~ but it doesn't work in these cases due to multi-digit numbers. ``` f=n=>{s=e=o='';n.split` `.map(Number).sort((a,b)=>a-b).map(v=>{s=s||v;if(e&&v>e+1){o+=`${s<e?s+'-'+e:s} `;s=v}e=v});return o+(s<e?s+'-'+e:e)} ``` ## ES5 variant, ~~198~~ ~~184~~ ~~183~~ 174 bytes ``` f=function(n){s=e=o='';n.split(' ').map(Number).sort(function(a,b){return a-b}).map(function(v){s=s||v;if(e&&v>e+1){o+=(s<e?s+'-'+e:s)+' ';s=v}e=v});return o+(s<e?s+'-'+e:e)} ``` ``` f = function (n) { s = e = 0, o = ''; n.split(' ').map(Number).sort(function (a, b) { return a - b }).map(function (v) { s = s || v; if (e && v > e + 1) { o += (s < e ? s + '-' + e : s) + ' '; s = v } e = v }); return o + (s < e ? s + '-' + e : e) } // Demonstration document.body.innerHTML = f('1 2'); document.body.innerHTML += '<p>' + f('9 13 3 11 8 4 10 15 6'); document.body.innerHTML += '<p>' + f('11 10 6 9 13 8 3 4 15'); document.body.innerHTML += '<p>' + f('5 8 3 2 6 4 7 1'); document.body.innerHTML += '<p>' + f('5 3 7 1 9'); ``` [Answer] # Ruby, 70 bytes Problems like these tend to make me check the Ruby API for suitable methods, and today I discovered a new one: [`Array#slice_when`](http://ruby-doc.org/core-2.2.2/Enumerable.html#method-i-slice_when), newly introduced in Ruby v2.2 and seemingly intended for this exact situation :) ``` f=->a{puts a.sort.slice_when{|i,j|j-i>1}.map{|x|x.minmax.uniq*?-}*' '} ``` After sorting and appropriately slicing the array, it takes each sub-array and creates a string out of the highest and lowest element, and then joins this whole array into a string. Example: `f.call [9,13,3,11,8,4,10,15,6]` prints `3-4 6 8-11 13 15` [Answer] # SWI-Prolog, ~~165~~ ~~162~~ 159 bytes ``` b(Z,C,[D|E]):-Z=[A|B],(A=:=D+1,(B=[],put(45),print(A);b(B,C,[A,D|E]));(E=[],tab(1),print(A);writef('-%t %t',[D,A])),b(B,A,[A]));!. a(A):-sort(A,B),b(B,_,[-1]). ``` Pretty bad but then again Prolog is a terrible golfing language Example: `a([9,13,3,11,8,4,10,15,6]).` outputs `3-4 6 8-11 13 15` [Answer] # Ruby, ~~86~~ 84 bytes ``` s=->*a{puts a.sort.slice_when{|i,j|i+1!=j}.map{|e|e.size<2?e:[e[0],e[-1]]*"-"}*" "} # demo s[9, 13, 3, 11, 8, 4, 10, 15, 6] # => 3-4 6 8-11 13 15 ``` This is a slightly golfed version from an example in the docs for [slice\_when](http://ruby-doc.org/core-2.2.2/Enumerable.html#method-i-slice_when). [Answer] # CJam, 35 bytes ``` l~${__0=f-ee::=0+0#/((oW>Wf*S+oe_}h ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l~%24%7B__0%3Df-ee%3A%3A%3D0%2B0%23%2F((oW%3EWf*S%2Boe_%7Dh&input=%5B9%2013%203%2011%208%204%2010%2015%206%5D). ### How it works ``` l~$ e# Read a line from STDIN, evaluate it and sort the result. { e# Do: _ e# Push a copy of the array. _0=f- e# Subtract the first element from all array elements. ee e# Enumerate the differences: [0 1 4] -> [[0 0] [1 1] [2 4]] ::= e# Vectorized quality: [i j] -> (i == j) 0+ e# Append a zero. 0# e# Push the first index of 0. / e# Split the array into chunks of that size. ( e# Shift out the first chunk. (o e# Print its first element. W> e# Discard all remaining elements (if any) except the last. Wf* e# Multiply all elements of the remainder by -1. S+o e# Append a space and print. e_ e# Flatten the rest of the array. }h e# Repeat while the array is non-empty. ``` [Answer] # CJam, ~~38~~ 33 bytes New version, using ideas and code fragments suggested by @Dennis: ``` l~$_,,.-e`{~T+\_T+:T;(_2$+W*Q?S}/ ``` [Try it online](http://cjam.aditsu.net/#code=l~%24_%2C%2C.-e%60%7B~T%2B%5C_T%2B%3AT%3B(_2%24%2BW*Q%3FS%7D%2F&input=%5B9%2013%203%2011%208%204%2010%2015%5D) The input format is a CJam array in square brackets. The basic idea here is that I subtract a monotonic sequence from the sorted input sequence first: ``` 3 4 8 9 10 11 13 15 0 1 2 3 4 5 6 7 (-) ---------------------- 3 3 6 6 6 6 7 8 ``` In this difference, values that are part of the same interval have the same value. Applying the CJam RLE operator to this difference directly enumerates the intervals. The subtracted sequential values need to be added back during output. I'm not entirely happy with how that's done in my code. I suspect that I could save a few bytes with a more elegant way of handing that. For generating the output of the intervals, this uses Dennis' idea of generating a negative number for the end value, which takes care of producing a `-`, and also simplifies the logic because only one value needs to be added/omitted depending on the interval size. Explanation: ``` l~ Get input. $ Sort it. _,, Create monotonic sequence of same length. .- Calculate vector difference between the two. e` Calculate RLE of difference vector. { Loop over entries in RLE. ~ Unpack the RLE entry, now have length/value on stack. T+ Add position to get original value for start of interval. \ Bring length of interval to top of stack. _T+:T; Add length of interval to variable T, which tracks position. ( Decrement interval length. _ Copy it, we need it once for calculating end value, once for ternary if condition. 2$ Copy interval start value to top... + ... and add interval length - 1 to get end value. W* Negate end value. Q? Output end value if interval length was > 1, empty string otherwise. S Add a space. }% End loop. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` ṢI’kƊ.ịⱮUQ€j€”-K ``` [Try it online!](https://tio.run/##y0rNyan8///hzkWejxpmZh/r0nu4u/vRxnWhgY@a1mQB8aOGubre/w@3A5mR//9HW@ooGBrrKACRoaGOgoWOggmQZQDEpjoKZrE6CtEgYZCAmY4CVK0FWDlInSlIgSlMxAisCChuDpSCyhhDeEC9sQA "Jelly – Try It Online") ## How it works ``` ṢI’kƊ.ịⱮUQ€j€”-K - Main link. Takes an array L on the left Ṣ - Sort L; Call this A Ɗ - Monad. Link the previous three links together f(A): I - Forward differences ’ - Decrement k - Partition This groups consecutive runs Take A = [3, 4, 6, 8, 9, 10, 11, 13, 15] I: [1, 2, 2, 1, 1, 1, 2, 2] ’: [0, 1, 1, 0, 0, 0, 1, 1] k then partitions A at truthy elements in I’ [[3, 4], [6], [8, 9, 10, 11], [13], [15] Ɱ - For each: .ị - Take the 0.5th element For non-integer left argument, x, Jelly's ị atom takes floor(x) and ceil(x) and returns [floor(x)ịy, ceil(x)ịy] As Jelly's indexing is 1-based and modular: 0ị returns the last element 1ị returns the first element .ị returns [0ị, 1ị] U - Reverse each Q€ - Deduplicate each j€”- - Join each with "-" K - Join by spaces ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~21~~ 20 bytes ``` ;moJ'-?I§e←→ε†sġ·=←O ``` [Try it online!](https://tio.run/##yygtzv7/3zo330td197z0PLUR20THrVNOrf1UcOC4iMLD223BQr4////P9pSx9BYx1jH0FDHQsdEx9BAx9BUxywWAA "Husk – Try It Online") A bit lacking in the strings department, but does well. No matter what I tried, it somehow stubbornly stayed at 21. -1 byte from Dominic Van Essen. ## Explanation ``` ;moJ'-?I§e←→ε†sġ§=…eO O order the list ġ group the list by the following: e elements paired §= equal … the range between them? †s convert all the numbers to strings mo map each group to the following: ? ε if it's a single element: I leave as is §e←→ otherwise, move the first and last elements to a list J'- join with '-' ; nest to display in one line ``` [Answer] ## CoffeeScript, ~~178~~ 161 bytes Just like my JavaScript answer. I need to figure out if using comprehensions will result in shorter code. ``` f=(n)->s=e=o='';n.split(' ').map(Number).sort((a,b)->a-b).map((v)->s=s||v;(o+=s+(if s<e then'-'+e else'')+' ';s=v)if(e&&v>e+1);e=v);o+(if s<e then s+'-'else'')+e ``` --- Original: ``` f=(n)->o='';s=e=0;n.split(' ').map(Number).sort((a,b)->a-b).forEach((v,i)->if!i then s=v else(o+=s+(if s<e then'-'+e else'')+' ';s=v)if(v!=e+1);e=v);o+(if s<e then s+'-'else'')+e ``` [Answer] # Python 2, ~~126~~ ~~122~~ 121 Bytes I know this can get shorter, just don't know where.. Requires input in form `[#, #, #, #, ..., #]`. ``` l=sorted(input());s=`l[0]`;c=0;x=1 while x<len(l):y,z=l[x],l[x-1];s+=(('-'+`z`)*c+' '+`y`)*(y-z>1);c=(y-z<2);x+=1 print s ``` [Answer] # Java, 191 bytes ``` void f(int[]a){java.util.Arrays.sort(a);for(int b=a.length,c=b-1,i=0,j=a[0],l=j;++i<b;){if(a[i]!=++j||i==c){System.out.print((l+1==j?l+(i==c?" "+a[c]:""):l+"-"+(i==c?j:j-1))+" ");l=j=a[i];}}} ``` Checks for ranges and prints them accordingly. Unfortunately I had to make a special case for the last element in the array since the program would terminate without printing the last number or range. [Answer] # Java, ~~171~~ 162 bytes ``` String s(int[] n){Arrays.sort(n);int p=0,b=0;String r="",d="";for(int c:n){if(c==++p)b=1;else{if(b==1){r+="-"+--p+d+c;p=c;b=0;}else{r+=d+c;p=c;}d=" ";}}return r;} ``` Takes input as an int array, returns output as a space-separated String list [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), ~~17~~ 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ÍòÈnYÉÃ®é ¯2 Ôq- ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=zfLIblnJw67pIK8yINRxLQ&input=WzkgMTMgMyAxMSA4IDQgMTAgMTUgNl0) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `S`, 120 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 15 bytes ``` s:¯Ǐ⁽ṅḋ•ꜝƛ₍htU\-j ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJTfj0iLCIiLCJzOsKvx4/igb3huYXhuIvigKLqnJ3Gm+KCjWh0VVxcLWoiLCIiLCIhKC4qKSAtPiBcIiguKilcIlxuWzYsIDEsIDIsIDQsIDMsIDUsIDgsIDcsIDEwXSAtPiBcIjEtOCAxMFwiXG5bMTEsIDEwLCA2LCA5LCAxMywgOCwgMywgNCwgMTVdIC0+IFwiMy00IDYgOC0xMSAxMyAxNVwiXG5bOSwgMTMsIDMsIDExLCA4LCA0LCAxMCwgMTUsIDZdIC0+IFwiMy00IDYgOC0xMSAxMyAxNVwiXG5bNSwgOCwgMywgMiwgNiwgNCwgNywgMV0gLT4gXCIxLThcIlxuWzUsIDMsIDcsIDEsIDldIC0+IFwiMSAzIDUgNyA5XCIiXQ==) ## Explained ``` s:¯Ǐ⁽ṅḋ•ꜝƛ₍htU\-j s: # Push two copies of the input list but sorted ¯Ǐ # Forward differences of items with the first item appended - this is for making sure the length of the deltas matches the length of the input ⁽ṅḋ # Grouped by whether they are <= 1 • # Reshape the sorted input to that shape ꜝ # and remove the 0 # the top of the stack will be a list of lists of numbers that are ranges ƛ # to each range ₍htU # either get the first and last item or just the first \-j # join on "-" # S flag joins the result on spaces ``` [Answer] # [Haskell](https://www.haskell.org/), 187 bytes ``` import Data.List g p[x]=[[x]] g p(a:b:c)|let(d:e)=g p(b:c)=if p a b then(a:d):e else[a]:(d:e) p[x]=show x++" " p x=show(head x)++"-"++show(last x)++" " f=concatMap p.g(((-1==).).(-)).sort ``` [Try it online!](https://tio.run/##JY7LCoMwFET3fsVFukgwhoY@aAPZddl@gbi41WhCo4YmUBf9dxvtZmAOh2EMhpd2blns4Kd3hBtG5HcbYtaDr@ZaVSnqtRCUT9nQr9ORtFJTtbKVKNuBB4QnRKPHpLVUatAu6AprubnZNhXM9IG5KHLIMw/z1onR2MJMEy3zotiQwxD/KImdaqaxwfhAD573hJBSKEU55aSklId0ehnQjsq/7Rh33a66MnFgByYEu7AjE3smTuxcLz8 "Haskell – Try It Online") [Answer] # [Scala](https://www.scala-lang.org/), 204 bytes Modified from [@steenslag's Ruby answer](https://codegolf.stackexchange.com/a/52328/110802). --- Golfed version. [Try it online!](https://tio.run/##PU9NT8QgEL3vr5g0HhiLuF0/oigmHj142nja9ICU3aC0W4GYaMNvr1OMkpkwvOG9mReN9no@vr5Zk@BZuwGmubN7iEzLpyGdotzaj902BTccWjV9ag9RaRGPIdnujpUmJX1t2@XFIlsj4rmMInrXEYttECdm@Ijqwe3ZSP26UWpkDaIRbnBJ1swIryMVBbU@WjCyXuQKkEWvRxYKP4jovu39BoPo33/3gkKI1ckUSDyf0V3kcoV5Bljs9OSM6XCIEh5D0F9/jlDCC20ACqYV0BkJTX4gF7ccmgsOFE3D4YbDJVVryisO1/g/m1VQIRI3r/L8Aw) ``` def s(a:Int*):Seq[String]={val s=a.sorted;(Seq[Seq[Int]](Seq(s(0)))/:s.sliding(2)){(c,p)=>if(p(0)+1==p(1))c.init:+(c.last:+p(1))else c:+Seq(p(1))}.map(r=>if(r.size<2)r.mkString else s"${r(0)}-${r.last}")} ``` Ungolfed version. [Try it online!](https://tio.run/##XVHRSsMwFH3fVxyKD4mrYZ1TtFjBR2G@KD6NPVzbdEaztiRB0NFvr2myDTZIQs49595zL9eWpGkY2o8vWTq8kGqwmwCVrGEZ5Xhu3CXP8d4ohyJQwA9p2NY4WfkQifg9Y16p2Ujr@QiF1apSzYbNuahbXS1l7dhSWbcKj3dZrwNme/2npIpzjh0YlWWKjpThKB6DDaBqsDHEZhxTZCiKoGCZT/F6ocZ@82lIFppsAAfFvobUVo7ikQrWJ3x/HMicjhInE1vqWGB8U6GdAIRVfxIPmPOYJrbfb874waObTS52MT7O118d0Nhhn0TjzsudbmI9eyzAEiShtX6y38/WL4uR2dgcT8bQ7yoK1@frsuw@RXadwp8sS3GXYuF/M39vUtzGmv1kGP4B) ``` object Main { def s(a: Int*): Unit = { val sorted = a.sorted val sortedRanges = sorted.sliding(2).foldLeft(List[List[Int]](List(sorted.head))) { (acc, pair) => if (pair(0) + 1 == pair(1)) acc.init :+ (acc.last :+ pair(1)) else acc :+ List(pair(1)) } val ranges = sortedRanges.map(range => if (range.size < 2) range.mkString else s"${range.head}-${range.last}") println(ranges.mkString(" ")) } def main(args: Array[String]): Unit = { s(9, 13, 3, 11, 8, 4, 10, 15, 6) } } ``` [Answer] # [Ly](https://github.com/LyricLy/Ly), 35 bytes ``` a0r[r0Ir::u[ps`=]pl~!['-olu!]p' o]; ``` [Try it online!](https://tio.run/##y6n8/z/RoCi6yMCzyMqqNLqgOME2tiCnTjFaXTc/p1QxtkBdIT/W@v9/Q0MuQwMuMy5LLkNjLgsuYy4TLkNTAA "Ly – Try It Online") This is pretty brute force. It sorts the numbers then iterates until all the numbers have been consumed. After printing the "current" number on the stack, an inner loop consumes all the entries after that which are consequitive. Then it either appends a `-#` string or not before printing a space and iterating again. ``` # prep work... created sorted list of numbers with trailing "0" a0r a - read numbers from STDIN, sort stack 0 - push a "0" r - reverse stack # loop over all numbers, then exit [ ]; [ ] - iterate while top of stack not "0" ; - exit to avoid dumping junk on stack # remember the current number for comparison later r0Ir r - reverse stack 0I - copy bottom of stack entry to the top r - reverse the stack # print the current number, loop/consume all sequential nums on stack ::u[ps`=]p :: - duplicate top of stack twice u - print current number [ ]p - loop until top of stack is "0" p - delete previous number s - save the current number `= - increment current number, compare to next num on stack # print "-X" if needed to cover delete numbers, then print space l~!['-olu!]p' o l - load saved num (last number deleted) ~ - search stack for that number ! - negate result [ ]p - "then" code block '-o - print "-" lu - load last num in sequence (last deleted) ! - flip top of stack to "0" to exit loop ' o - print " " ``` [Answer] # [Perl 5](https://www.perl.org/) `-pa`, 95 bytes ``` $_=join$",sort{$a-$b}@F;$b=$_,s/(\d+)\K (?=(\d+))/$2-$1-1?$":"-"/ge while$_ ne$b;s/(-\d+)+/$1/g ``` [Try it online!](https://tio.run/##HcvNCoJAFIbhW/kYzkLR08yxLErEVm2iOxBEaTBDHFGhRXTrTT@7d/G8o5361Huq8rvrBlLx7KblSTVT8zqeMmpyquJZB@U1CsszgiL/Z6gpYRKWgtRBsdKtxePW9ZYqDJaa7LvwD0aaRLfeb5Biiz0EO4iBCCRBYrB@u3Hp3DB7vqQrI8ZzPX4A "Perl 5 – Try It Online") ]
[Question] [ [Rijndael's S-box](http://en.wikipedia.org/wiki/Rijndael_S-box) is a frequently used operation in [AES](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard) encryption and decryption. It is typically implemented as a 256-byte lookup table. That's fast, but means you need to enumerate a 256-byte lookup table in your code. I bet someone in this crowd could do it with less code, given the underlying mathematical structure. Write a function in your favorite language that implements Rijndael's S-box. Shortest code wins. [Answer] # x86-64 Machine code - ~~23 22 20~~ 19 bytes Uses the AES-NI instruction set ``` 66 0F 6E C1 movd xmm0,ecx 66 0F 38 DD C1 aesenclast xmm0,xmm1 0F 57 C1 xorps xmm0,xmm1 66 0F 3A 14 C0 00 pextrb eax,xmm0,0 C3 ret ``` Using Windows calling conventions, takes in a byte and outputs a byte. It is not necessary to reverse the `ShiftRows` as it does not affect the first byte. [Answer] # GolfScript, 60 characters ``` {[[0 1{.283{1$2*.255>@*^}:r~^}255*].@?~)={257r}4*99]{^}*}:S; ``` This code defines a function named `S` that takes in a byte and applies the Rijndael S-box to it. (It also uses an internal helper function named `r` to save a few chars.) This implementation uses a logarithm table to compute the GF(28) inverses, as [suggested by Thomas Pornin](https://codegolf.stackexchange.com/a/3770). To save a few chars, the whole logarithm table is recalculated for each input byte; even so, and despite GolfScript being a very slow language in general, this code takes only about 10 ms to process a byte on my old laptop. Precalculating the logarithm table (as `L`) speeds it up to about 0.5 ms per byte, at the modest cost of three more chars: ``` [0 1{.283{1$2*.255>@*^}:r~^}255*]:L;{[L?~)L={257r}4*99]{^}*}:S; ``` For convenience, here's a simple test harness that calls the function `S`, as defined above, to compute and print out the whole S-box in hex like [on Wikipedia](//en.wikipedia.org/wiki/Rijndael_S-box#Forward_S-box): ``` "0123456789abcdef"1/:h; 256, {S .16/h= \16%h= " "++ }% 16/ n* ``` [Try this code online.](http://golfscript.apphb.com/?c=IyBGdW5jdGlvbiB0byBjYWxjdWxhdGUgUmlqbmRhZWwgUy1Cb3g6ClswIDF7LjI4M3sxJDIqLjI1NT5AKl59OnJ%2BXn0yNTUqXTpMO3tbTD9%2BKUw9ezI1N3J9NCo5OV17Xn0qfTpTOwoKIyBBcHBseSBmdW5jdGlvbiB0byBhbGwgMjU2IGlucHV0IGJ5dGVzLCBwcmludCByZXN1bHRzIGluIGhleDoKIjAxMjM0NTY3ODlhYmNkZWYiMS86aDsgMjU2LCB7UyAuMTYvaD0gXDE2JWg9ICIgIisrIH0lIDE2LyBuKg%3D%3D) (The online demo precalculates the logarithm table to avoid taking too much time. Even so, the online GolfScript site may sometimes randomly time out; this is a known issue with the site, and a reload usually fixes it.) ### Explanation: Let's start with the logarithm table calculation, and specifically with the helper function `r`: ``` {1$2*.255>@*^}:r ``` This function takes two inputs on the stack: a byte and a reduction bitmask (a constant between 256 and 511). It duplicates the input byte, multiplies the copy by 2 and, if the result exceeds 255, XORs it with the bitmask to bring it back under 256. Within the log-table generating code, the function `r` is called with the reduction bitmask 283 = 0x11b (which corresponds to the [Rijndael GF(28) reduction polynomial](//en.wikipedia.org/wiki/Finite_field_arithmetic#Rijndael.27s_finite_field) *x*8 + *x*4 + *x*3 + *x* + 1), and result is XORed with the original byte, effectively multiplying it by 3 (= *x* + 1, as a polynomial) in the Rijndael finite field. This multiplication is repeated 255 times, starting from the byte 1, and the results (plus an initial zero byte) are collected into a 257-element array `L` that looks like this (middle part omitted): ``` [0 1 3 5 15 17 51 85 255 26 46 ... 180 199 82 246 1] ``` The reason why there are 257 elements is that, with the prepended 0 and with 1 occurring twice, we can find the modular inverse of any given byte simply by looking up its (zero-based) index in this array, negating it, and looking up the byte at the negated index in the same array. (In GolfScript, as in many other programming languages, negative array indexes count backwards from the end of the array.) Indeed, this is exactly what the code `L?~)L=` at the beginning of the function `S` does. The rest of the code calls the helper function `r` four times with the reduction bitmask 257 = 28 + 1 to create four bit-rotated copies of the inverted input byte. These are all collected into an array, together with the constant 99 = 0x63, and XORed together to produce the final output. [Answer] The table can be generated without computing inverses in the finite field GF(256), by using logarithms. It would look like this (Java code, using `int` to avoid problems with the signed `byte` type): ``` int[] t = new int[256]; for (int i = 0, x = 1; i < 256; i ++) { t[i] = x; x ^= (x << 1) ^ ((x >>> 7) * 0x11B); } int[] S = new int[256]; S[0] = 0x63; for (int i = 0; i < 255; i ++) { int x = t[255 - i]; x |= x << 8; x ^= (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7); S[t[i]] = (x ^ 0x63) & 0xFF; } ``` The idea is that 3 is a multiplicative generator of GF(256)\*. The table `t[]` is such that `t[x]` is equal to 3x; since 3255 = 1, we get that 1/(3x) = 3255-x. [Answer] ### Ruby, 161 characters ``` R=0..255 S=R.map{|t|t=b=R.select{|y|x=t;z=0;8.times{z^=y*(x&1);x/=2;y*=2};r=283<<8;8.times{r/=2;z^r<z/2&&z^=r};z==1}[0]||0;4.times{|r|t^=b<<1+r^b>>4+r};t&255^99} ``` In order to check the output you can use the following code to print it in tabular form: ``` S.map{|x|"%02x"%x}.each_slice(16){|l|puts l*' '} ``` [Answer] ## GolfScript (82 chars) ``` {256:B,{0\2${@1$3$1&*^@2/@2*.B/283*^}8*;;1=},\+0=B)*:A.2*^4A*^8A*^128/A^99^B(&}:S; ``` Uses global variables `A` and `B`, and creates the function as global variable `S`. The Galois inversion is brute-force; I experimented with having a separate `mul` function which could be reused for the post-inversion affine transform, but it turned out to be more expensive because of the different overflow behaviour. This is too slow for an online demo - it would time out even on the first two rows of the table. [Answer] ## Python, 176 chars This answer is for Paŭlo Ebermann's comment-question about making the function constant time. This code fits the bill. ``` def S(x): i=0 for y in range(256): p,a,b=0,x,y for j in range(8):p^=b%2*a;a*=2;a^=a/256*283;b/=2 m=(p^1)-1>>8;i=y&m|i&~m i|=i*256;return(i^i/16^i/32^i/64^i/128^99)&255 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 70 bytes ``` ⎕⊃99,1↓(2⊥¨(⊂b⊤99)≠≠⌿(⍳5)∘.⌽⌽p)[⍋2⊥¨p←{(2≠/⍵,0)≠b⊤27×⊃⍵}\,b⍴⊂1⊤⍨b←8⍴2] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkGXI862tNA3EddzZaWOoaP2iZrGD3qWnpohcajrqakR11LLC01H3UuAKGe/RqPejebaj7qmKH3qGcvEBVoRj/q7YaoLwAaVw3U27lA/1HvVh0DkC6QfiPzw9OBhgPFamN0kh71bgGaawgUf9S7IgmoxQIoYhT7H@iM/2lcBlxcaVyGIMIIRBiDCBMA "APL (Dyalog Unicode) – Try It Online") [Answer] ## d ``` ubyte[256] getLookup(){ ubyte[256] t=void; foreach(i;0..256){ t[i] = x; x ^= (x << 1) ^ ((x >>> 7) * 0x1B); } ubyte[256] S=void; S[0] = 0x63; foreach(i;0..255){ int x = t[255 - i]; x |= x << 8; x ^= (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7); S[t[i]] = cast(ubyte)(x & 0xFF) ^ 0x63 ; } return S; } ``` this can generate the lookup table at compile time, I could save some by making ubyte a generic param edit direct `ubyte` to `ubyte` without array lookups, no branching and fully unrollable loops ``` B[256] S(B:ubyte)(B i){ B mulInv(B x){ B r; foreach(i;0..256){ B p=0,h,a=i,b=x; foreach(c;0..8){ p^=(b&1)*a; h=a>>>7; a<<=1; a^=h*0x1b;//h is 0 or 1 b>>=1; } if(p==1)r=i;//happens 1 or less times over 256 iterations } return r; } B s= x=mulInv(i); foreach(j,0..4){ x^=(s=s<<1|(s>>>7)); } return x^99; } ``` edit2 used @Thomas' algo for creating the lookup table [Answer] # [Stax](https://github.com/tomtheisen/stax), 53 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ë■ÿÆ♂◄º5hUø√!«mr¿¡ƒR3Å←ç≥#/$taJkαn∩╓▒ÿ╔τy╫π§╪S♫╔┴H╔║Ö ``` [Run and debug it](https://staxlang.xyz/#p=89fe98920b11a735685500fb21ae6d72a8ad9f52338f1b87f2232f2474614a6be06eefd6b198c9e779d7e315d8530ec9c148c9ba99&i=&a=1&m=2) I have no particular understanding of S-boxes. This is a conversion of [Thomas Pornin's (8 year old!) solution](https://codegolf.stackexchange.com/a/3770/527). ]
[Question] [ Your task: given a nonzero positive number `i`, calculate pi using the Nilakantha series unto `i` terms. The Nilakantha series is as follows: $$\text 3 + \frac{4}{2 \times 3 \times 4} - \frac{4}{4 \times 5\times 6}+\frac{4}{6 \times 7 \times 8} - ...$$ 3 is the first term, `4/2*3*4` is the second, `-4/4*5*6` is the third, and so on. Notice that for the nth term: * $$\text S\_1 = 3$$ * $$\text S\_n = \frac{4 \times (-1)^n}{2n \times (2n-1) \times (2n-2)}$$ * The approximation of pi by summing up these terms is $$\text S\_1 +\text S\_2\text + … +\text S\_n$$ Test cases: ``` In = Out 1 = 3 2 = 3.16666666667 3 = 3.13333333333 4 = 3.1452381 ``` Notice the pattern of the numbers approximating towards pi. Floating point issues are OK. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer wins! **EDIT**: by default this is 1-indexed, but if you want 0-indexed no problem, just mention it. And even infinitely printing the approximations with no input is Okay. **EDIT 2**: Why some activity here? [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 38 bytes (@xnor) ``` f=lambda n,i=.5:i//n/n or 2/i-f(n,i+1) ``` [Try it online!](https://tio.run/##DchBCoAgEADAe6/Yo0vWohGE4GOMshZqFfHS6805Tv7qnWTZcmkt@ie8@xFANPt5dUwkJJAKWOIpqt6jwRZ7MLBACXKdymhr0A2QC0tVUTFi@wE "Python 3.8 (pre-release) – Try It Online") ### [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 40 bytes (@xnor) ``` f=lambda n,i=1:i//2//n/n or 4/i-f(n,i+2) ``` [Try it online!](https://tio.run/##DcnBCoAgDADQe1@x4yRjaB1C6GOMWg1qinjp683re/mrd9J5zaU13p747kcEtbK5IESeSEkhFVhIJsYeozeNOwiIQol6neisdyYMkItoRUYxpv0 "Python 3.8 (pre-release) – Try It Online") ### [Python](https://www.python.org), 45 bytes ``` f=lambda n,s=1:4/(2*s-1)-(s//n/s or f(n,s+1)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3ddNscxJzk1ISFfJ0im0NrUz0NYy0inUNNXU1ivX18_SLFfKLFNI0gJLahpqaUE1KBUWZeSUaaRqGmjppGkYgwhhEGBpASAOYSpg1AA) 1-based. n has to be positive. ### [Python](https://www.python.org), 50 bytes ``` f=lambda n,s=0:n and f(n-1,4/(n+n-1)-s-0**s/n)or s ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3jdJscxJzk1ISFfJ0im0NrPIUEvNSFNI08nQNdUz0NfK0gQxN3WJdAy2tYv08zfwihWKoTqWCosy8Eo00DQNNnTQNQxBhBGZB-AYGmpoQlTC7AA) This uses \$\frac 4 {2x(2x+1)(2x+2)} =\frac 1 x + \frac 1 {x+1} - \frac 4 {2x+1} \$ and that inside the full sum the first two terms cancel. 1-based. Can handle 0. # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 45 bytes (@xnor) ``` f=lambda n:0**n*3or(-1)**n/n/(n-~n)/~n+f(n-1) ``` [Try it online!](https://tio.run/##DcYxCoAwDAXQ3VNkTCpSaxcRPExFqwX9LcHFxatX3/TKcx8Zfixaa5zPcC1rIEy9MTA@K3dO/lpYRvdC7Is2/nVSY1ZKlEAasG889DI1VDTh5shJpH4 "Python 3.8 (pre-release) – Try It Online") ### [Python](https://www.python.org), 50 bytes ``` f=lambda n:0**n*3or 1/(n|1)/(~n-n)/(n%-2^n)+f(n-1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3jdJscxJzk1ISFfKsDLS08rSM84sUDPU18moMNfU16vJ084BUnqquUVyepnaaRp6uoSZUp1JBUWZeiUaahoGmTpqGIYgwArMgfAMDTahKmF0A) 0-based. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` RḤrƝP€4÷Ṛḅ-+3 ``` A monadic Link that accepts a positive integer and yields the approximation (up to the floating point accuracy). **[Try it online!](https://tio.run/##ASIA3f9qZWxsef//UuG4pHLGnVDigqw0w7fhuZrhuIUtKzP///80 "Jelly – Try It Online")** ### How? ``` RḤrƝP€4÷Ṛḅ-+3 - Link: positive integer, n e.g. 4 R - range [1,2,3,4] Ḥ - double [2,4,6,8] Ɲ - for neighbours: r - inclusive range [[2,3,4],[4,5,6],[6,7,8]] P€ - product of each [24,120,336] 4÷ - four divided by those [1/6,1/30,1/84] Ṛ - reverse [1/84,1/30,1/6] ḅ- - convert from base -1 sum([1/84,-1/30,1/6])=0.14523809523809522 +3 - add three 3.14523809523809522 ``` [Answer] # JavaScript (ES6), 32 bytes This version is based on [@loopy-walt's answer](https://codegolf.stackexchange.com/a/251927/58563), golfed by [@xnor](https://codegolf.stackexchange.com/users/20260/xnor). ``` f=(n,i=.5)=>i<n?2/i-f(n,i+1):1/n ``` [Try it online!](https://tio.run/##FYxBCoMwEADvvmIPHrJETVPwoqZ@xZCaEpFd0dJLyNvTeBoYhtnsz17uDMe3JX6vOXsjqAmm69G8wkTzU4XW30pqHLSi7PkUBAb0CAQT6EehlAixAnBMF@9rt/NHLFbUkRKWtI7lgGnBsUr5Dw "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 39 bytes ``` f=n=>--n?f(n)+(4-n%2*8)/(n+=n)/++n/~n:3 ``` [Try it online!](https://tio.run/##FcxBCsIwEEbhfU8xiwozDjFWXYg1epWG2ohS/kgrbkK8eqyrt/l4T//xcz89Xm@DeBtKCQ7uYgyugSHKB4PVbn0Uy1AHsaqwX5z2JcSJQY6alkBnarZLVYVSRdRHzHEcNmO8c@e5Tsiy0Dr9n7mTtsrlBw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = n => // f is a recursive function taking the input n --n ? // decrement n; if it's not 0: f(n) + // do a recursive call and add: (4 - n % 2 * 8) // -4 if n is odd, +4 otherwise / (n += n) // divided by 2n / ++n // divided by 2n + 1 / ~n // divided by -(2n + 2) : // else: 3 // end of recursion: return the integer part ``` [Answer] # [Factor](https://factorcode.org) + `koszul math.unicode`, ~~68~~ 64 bytes ``` [ ""3 rot [0,b) [ -1^ 4 reach Π / * + [ 2 v+n ] dip ] each ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=JYw5CsJAGIVBrXKKRzr3JRaiIHZiYyM2hgjj-McEx5k4mQh6FZs0egHvYZ_bmDjN2z54z3fIuFE6L3bbzWq9nOJMWpJASteMJKcUZ5U-MoELM1EvkzFXR7JFM3kqeZXtcKPqKkWiyZh7omNpMHMc75WZsDspFj7cWr3hetDKwB90Dk346A73GEMT4xG-OfpooV3OI9zaEgGOcVLqnwb258OZEJiHQjGDHrggpi3Jc-s_) 0-indexed. Note the string literal has the control characters 2, 3, and 4 embedded, making it equivalent to the sequence `{ 2 3 4 }`. You can see these characters on ATO. ``` ! 3 "" ! 3 { 2 3 4 } 3 ! 3 { 2 3 4 } 3 rot ! { 2 3 4 } 3 3 [0,b) ! { 2 3 4 } 3 { 0 1 2 } [ ... ] each <<for each element in { 0 1 2 }...>> <<first iteration>> ! { 2 3 4 } 3 0 -1^ ! { 2 3 4 } 3 1 4 ! { 2 3 4 } 3 1 4 reach ! { 2 3 4 } 3 1 4 { 2 3 4 } Π ! { 2 3 4 } 3 1 4 24 / ! { 2 3 4 } 3 1 1/6 * ! { 2 3 4 } 3 1/6 + ! { 2 3 4 } 3+1/6 [ 2 v+n ] dip ! { 4 5 6 } 3+1/6 <<second iteration>> ! { 4 5 6 } 3+1/6 1 <<and so on>> ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 19 bytes ``` ƛune4*nd:‹:‹**/;∑3+ ``` `ḋ` flag to print rationals in their decimal form **Explanation:** ``` ƛune4*nd:‹:‹**/;∑3+ ƛ ; Map lambda through inclusive range 1 to input une Push -1 to the power n 4* Multiply by 4 and push that nd: Multiply n by 2 and duplicate ‹: Decrement and duplicate ‹** Decrement and push product of denominator / Divide 4*(-1)**n by 2n*(2n-1)*(2n-2) ∑3+ Sum list and add 3 ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCLGm3VuZTQqbmQ64oC5OuKAuSoqLzviiJEzKyIsIiIsIjQiXQ==) [Answer] # [R](https://www.r-project.org), 51 bytes ``` \(k,n=2:k*2)`if`(k>1,3+sum(4*1i^n/n/(n-1)/(n-2)),3) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3jWM0snXybI2ssrWMNBMy0xI0su0MdYy1i0tzNUy0DDPj8vTz9DXydA01QaSRpqaOsSZE6-Y0DUNNrjQNIxBhDCJMoDILFkBoAA) Uses the fact that \$(-1)^n=i^{2n}\$. --- ### [R](https://www.r-project.org), 51 bytes ``` \(k,n=2:k)`if`(k>1,3+sum((-1)^n/n/(2*n-1)/(n-1)),3) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3jWM0snXybI2ssjUTMtMSNLLtDHWMtYtLczU0dA014_L08_Q1jLTygGx9DRCpqWOsCdG6OU3DUJMrTcMIRBiDCBOozIIFEBoA) Uses the formula but with simplifying the fraction to \$\frac{(-1)^n}{n(2n-1)(n-1)}\$. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 3λè®Nm4*N·2Ý-P/+ ``` Outputs the 1-based \$n^{th}\$ value (by starting with \$a(0)=3\$ and where \$a(1)\$ is calculated as \$3\$ as well). [Try it online](https://tio.run/##yy9OTMpM/f/f@NzuwysOrfPLNdHyO7Td6PBc3QB9baAwAA) or [verify the infinite sequence](https://tio.run/##yy9OTMpM/f/f@NzuQ@v8ck20/A5tNzo8VzdAX7v20LL//wE). **Explanation:** ``` λ # Start a recursive environment, è # to calculate a(input) # (which is output implicitly afterwards) 3 # Start with a(0)=3 # Where every following a(n) is calculated by: # (implicitly push the previous term a(n-1)) ®Nm # Push (-1) to the power n 4* # Multiply it by 4 N· # Push 2n 2Ý # Push list [0,1,2] - # Subtract each from the 2n: [2n,2n-1,2n-2] P # Take the product of this triplet: 2n*(2n-1)*(2n-2) / # Divide the earlier 4*(-1)**n by this (2n*(2n-1)*(2n-2)) + # Add it to the previous term a(n-1) ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 36 bytes Prints the infinite sequence ``` 23:nao$:1+$:2%8*4$-$2*:1-:1-**,{+10. ``` [Try it online!](https://tio.run/##S8sszvj/38jYKi8xX8XKUFvFykjVQstERVfFSMvKUBeItLR0qrUNDfT@/wcA "><> – Try It Online") # [><>](https://esolangs.org/wiki/Fish), 41 bytes Generates the **nth** term ``` 3$v ;n~< 1->:2(?v::2%8*4$-$2*:1-:1-**,{+} ``` [Try it online!](https://tio.run/##S8sszvj/31ilTME6r86Gy1DXzspIw77MyspI1ULLREVXxUjLylAXiLS0dKq1a////69bZgIA "><> – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~80~~ \$\cdots\$ ~~71~~ 70 bytes ``` i;float s,m;float f(n){for(m=4,s=i=3;i++<2*n;s-=m/i/~-i/(i++-2))m=-m;} ``` [Try it online!](https://tio.run/##XZFtT8MgEMff@ykuTZbAWqxtNx/C6hvjp3B7gQwmcaVNIbFxqR/dSimr00sg3P/ufrk7ODlwPgyKymPNLJikCi@JND7JukVVuUpMqcqCqjje5EtNDSmrVKVfRKXIaSTHuCpJRftBaQsVUxphOF2Bs4klukZwK/YvOyjhVCRQXGe3Z7vzbjGbd1frvLjPeuohvNbGAn9j7dLdgr@LdiJF2@4533YPT@6sowQu/SIK1aGFxqhjrV1VJsjqMsLKPLh1C2icQOm96FzmDQ3PDRj1KWqJzoPgNAjLWaEQxz4be9g0/mgj0TrahIoho3Mo7NwFJbL4vy6cPm/OV@/oH2rDjK9lrwYJIGCw6zQM@pvZtC5XomixB/IICwkLs9VuWTZxvz3vc2TtQgv9VT98c3lkBzOQjx8 "C (gcc) – Try It Online") *Saved ~~5~~ 6 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!!* *Saved 4 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!* [Answer] # [Desmos](https://www.desmos.com/), 36 bytes ``` f(x)=3+∑_{n=2}^x(-1)^n/n(2nn-3n+1) ``` [Try it on Desmos!](https://www.desmos.com/calculator/lv5parlrnm) Near direct copy of the definition, simplified and rearranged only a little bit. 1 indexed. Breakdown: ``` f(x)=3+∑_{n=2}^x(-1)^n/n(2nn-3n+1) full function f(x)= function definition (not sure if required) 3+ 3 plus ∑ The sum from _{n=2} n=2 ^x to n=x (note that this defaults to 0 if x is less than 2) of (-1)^n -1 when n is odd, 1 if n is even / divided by n(2nn-3n+1) 2n^3-3n^2+n ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `ḋr`, 14 bytes ``` Ḣƛd2ʀεΠ4/;uβ3+ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuItyIiwiIiwi4biixptkMsqAzrXOoDQvO3XOsjMrIiwiIiwiNCJd) ``` Ḣ # range(2, n) ƛ ; # map... ε # Difference of... d # 2x 2ʀ # [0, 1, 2] Π # Take the product 4/ # 4 / that uβ # Convert from base -1 (alternate signs) 3+ # Add 3 ``` [Answer] # [Python 3](https://docs.python.org/3/), 49 bytes ``` f=lambda n:n-1and(-1)**n/(2*n*n-n)/~-n+f(n-1)or 3 ``` [Try it online!](https://tio.run/##DcoxDoAgEAXR3lNsuYsSXe1IPAwGURP9EmJj49WRZpo36X32G1MpcT79tQRPcLDqEdiqGIOeRwMDC@k/izZyVbkzTSXWgg5Q9thW1k4HcQ1RygcerqNI@QE "Python 3 – Try It Online") -5 bytes thanks to Mukundan314 [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~36~~ 35 bytes ``` 3.-Sum[(-1)^n/(2n^3+3n^2+n),{n,#}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b731hPN7g0N1pD11AzLk9fwygvzljbOC/OSDtPU6c6T0e5Nlbtv0t@dEBRZl5JdKauXVp0ZmysjkJ1po6Bjmlt7H8A "Wolfram Language (Mathematica) – Try It Online") Alternatively, and more interestingly, we can express the partial sums in terms of a [Lerch transcendent](https://functions.wolfram.com/ZetaFunctionsandPolylogarithms/LerchPhi/): 36 bytes ``` Pi+(-1)^#(1/#-2LerchPhi[-1,1,#+.5])& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyBTW0PXUDNOWcNQX1nXyCe1KDkjICMzWtdQx1BHWVvPNFZT7b9LfnRAUWZeSXSmrl1adGZsrI5CdaaOaW3sfwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # x86 32-bit machine code, ~~37~~ 33 bytes ``` D9 E8 D8 C0 D8 C0 D9 E8 F9 D9 E8 D8 F1 D9 E8 DE C2 D8 F1 D8 C0 F5 72 F5 DE E2 E2 ED DD D8 D9 E1 C3 ``` [Try it online!](https://tio.run/##bVJdbyIhFH2WX3E7GxPQ0ahNmkY7/QXbl33apG0Mw8fIBsEAY8c0/es7vTPWrWvLA4RzD@ceDohJJUTb/jBO2FoquItJGj/d3JP/IGvKSywYV3UYWa95wl1ZJ7VeU6p5TIJbyxhY7yqQvi6tAk2NS@DYCvbeSFBOUrYiPG6Bwq@MkmllfcktaKKXA23lnAw0lxJiojOWH5fvoZ6LPUn4d1Ca/RlrzogJ56K7Dl2cSXzhf9dIbAUZ/BFgApZjXYZLGev9Dvpi2n0aLiMZBJUI3nhJWAZ4a9JFseXG9ZnwUIkcxIYHGI1ws2fklQCOrthAAbMcDt2y6tGXjcE46XjcwF0B8xvWo93Y4ZMkTbPhwsDkHobT@e1P/eSyHJoc828YOyqceE/ugYuNcQqEl2qZfZSbz17Sw@uJDcPZ4jdqHQpKaxdN5ZTsXY@YZo/NePzMVm8nd18Y6PaqgEsYM7nwBHRooDwkFdnR@UcdE6yD63y9kbb9K7TlVWwn2@sFTviLCjyu7Ds "C (gcc) – Try It Online") Following the `fastcall` calling convention, this takes a number `i` in ECX and returns the sum of the first `i` terms on the FPU register stack. In assembly: ``` f: fld1 fadd st(0), st(0) fadd st(0), st(0) # Example execution for 2nd iteration fld1 # FPU register stack (left is bottom): stc # -3 2 (before) r: fld1 # -3 2 1 fdiv st(0), st(1) # -3 2 1/2 ir: fld1 # -3 2 1/2 1 faddp st(2), st(0) # -3 3 1/2 fdiv st(0), st(1) # -3 3 1/(2*3) fadd st(0), st(0) # -3 3 2/(2*3) cmc #[Repeat the 4 instructions above, using an inner loop: jc ir # -3 3 2/(2*3) 1 # -3 4 2/(2*3) # -3 4 2/(2*3*4) # -3 4 4/(2*3*4) fsubrp st(2), st(0) # 3+4/(2*3*4) 4 loop r fstp st(0) fabs ret ``` Each iteration of the outer loop computes one term \$\frac4{2n(2n+1)(2n+2)}\$ and combines it in using the reverse-subtract instruction; as in [my answer to a related problem](https://codegolf.stackexchange.com/a/252080/104752), this handles the alternating signs, but leaves the result with the wrong sign for even `i`, which is corrected for by taking the absolute value at the end (because all the correct results are positive). The first iteration, if left the same as later iterations, would contain a division by 0. This is prevented by setting CF to 1 at the beginning, so that the inner loop executes once instead of twice during the first iteration, and it computes \$\frac2{1\cdot2}\$ instead. [Answer] # [Raku](https://raku.org/), 36 bytes ``` [\+] 3,{-4*($*=-1)/[*] ^3+2*++$}...* ``` [Try it online!](https://tio.run/##K0gtyjH7n1up4FCsYPs/OkY7VsFYp1rXREtDRctW11BTP1orViHOWNtIS1tbpVZPT0/rv7VCcWKlgpJKvIKtHVBbtEp8rJJCWn6RQpyhwX8A "Perl 6 – Try It Online") This is an expression for the infinite sequence of partial sums. 3 is the first term of the sequence, and the curly braces enclose a generating expression for the subsequent terms. * The dividend is `-4 * ($ *= -1)`. The `$` here is an anonymous state variable. The `*= -1` causes it to alternate between -1 and 1. (The first time the expression is evaluated, it's undefined, but since it's being multiplied, it defaults to the multiplicative identity element 1.) Multiplying that by -4 produces the sequence of dividends 4, -4, 4, -4, .... * The divisor is `[*] ^3 + 2 * ++$`. `$` here is another anonymous state variable which the preincrement operator `++` causes to take on the values 1, 2, 3, ..., as it's evaluated for each term of the sequence. Multiplying that by 2 produces 2, 4, 6, .... Those even numbers are added to the range `^3`, which means the integers from 0 to 2, producing a sequence of ranges `2, 3, 4`, `4, 5, 6`, `6, 7, 8`, .... Then `[*]` multiplies those numbers together. `[\+]` produces the sequence of partial sums of the terms. [Answer] # [Fig](https://github.com/Seggan/Fig), \$18\log\_{256}(96)\approx\$ 14.816 bytes ``` +3S\n2@Nere+r3hax4 ``` [Try it online!](https://fig.fly.dev/#WyIrM1NcXG4yQE5lcmUrcjNoYXg0IiwiMyJd) Port of Vyxal. Beats both that and osabie, 1.8 bytes longer than Jelly. 0-indexed. ``` +3S\n2@Nere+r3hax4 ax # Range [1, n] h # Double r3 # [0, 1, 2] e+ # Add ^ to every element of ^^ er # Product of each element @N # Negate n2 # Every other element \ 4 # Four divided by ^ S # Sum +3 # Add 3 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~22~~ 21 bytes [Try it online!](https://tio.run/##TYzNCsIwEIRfpccN1Iv25tFceqgI9QXSZMGF/JRtUvDptwkiepmB@WbGvgzbZLzIgylmuJktw1wCTGaFMa4l30tYkEH13RM5Gn4D9Z2mnRyCRssYMGZ0oFNZfPUpueJTK52VaisKuMFHazjG34Qa/w@@HxU0dGmmriKDnHZ/AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input `n` as a number E Map over implicit range ι Current value ⎇ If nonzero then ι Current value ﹪ Modulo ² Literal integer `2` ⊗ Doubled ⊖ Decremented ∕ Divided by ι Current value × Multiplied by ι Current value ⊕ Incremented × Multiplied by ι Current value ⊗ Doubled ⊕ Incremented ³ Otherwise literal integer `3` Σ Take the sum I Cast to string Implicitly print ``` Edit: Saved 1 byte by adpating @pajonk's simplification. ]
[Question] [ Your task is to take a positive number as input, **n**, and output the length of the longest rep-digit representation of **n** in any base. For example 7 can be represented as any of the following ``` 111_2 21_3 13_4 12_5 11_6 10_7 7_8 ``` The rep-digits are `111_2` and `11_6`, `111_2` is longer so our answer is 3. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with fewer bytes being better. # Test Cases ``` 1 -> 1 2 -> 1 3 -> 2 4 -> 2 5 -> 2 6 -> 2 7 -> 3 8 -> 2 9 -> 2 10 -> 2 11 -> 2 26 -> 3 63 -> 6 1023-> 10 ``` # Sample implementation Here is an implementation in Haskell that can be used to generate more test cases. ``` f 0 y=[] f x y=f(div x y)y++[mod x y] s x=all(==x!!0)x g x=maximum$map(length.f x)$filter(s.f x)[2..x+1] ``` [Try it online!](https://tio.run/##NYy9CsMgGEX3PIUBB0NATHbfoFtHcRDiH/00IWpr@vI2CXQ758C9TqWXBmjNIIYOLmRnUD3BkMW/LxqOcRRhXS6WXUKVKwDCee17NtTOniGo6kMJOKiNgI42O3qeDNh4yHon6TYxU1rHSbagfORbyc@8PyIuEXzU6dqi5NYP/vpNTJTOjMk72r@1Hw "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 thanks to caird coinheringaahing (`‘Ḋ$` -> `‘€` and use of the newer alias for `Ðf`, `Ƈ`.) ``` b‘€EƇZL ``` A monadic link accepting and returning numbers **[Try it online!](https://tio.run/##y0rNyan8/z/pUcOMhzu6VFwPT0iL8vn//785AA "Jelly – Try It Online")** or see a [test suite](https://tio.run/##y0rNyan8/z/pUcOMhzu6VFwPT0iL8vkfdLj9UdOa//@NjQA "Jelly – Try It Online") (inputs one to 32 inclusive). ### How? ``` b‘€EƇZL - Link: number, n € - for each (i in [1..n]): ‘ - increment = i+1 - -> [2,3,4,...,n+1] b - convert (n) to those bases Ƈ - filter keep if: E - all elements are equal Z - transpose L - length (note: length of the transpose of a list of lists is the length of the - longest item in the original list, but shorter than L€Ṁ) ``` --- Or maybe I should have done: ``` b‘€EƇZLo1 ``` ...just for the `Lo1`z. [Answer] ## JavaScript (ES6), 62 bytes ``` f=(n,b=2,l=0,d=n)=>d?n%b<1|n%b-d%b?f(n,b+1):f(n,b,l+1,d/b|0):l ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` [Answer] # [Haskell](https://www.haskell.org/), ~~86~~ ~~81~~ 79 bytes *2 bytes saved thanks to Laikoni* ``` 0!y=[] x!y=mod x y:div x y!y length.head.filter(all=<<(==).head).(<$>[2..]).(!) ``` [Try it online!](https://tio.run/##HYuxDsIgFEX3fkVpOkBqXlpH0@cXuDkSBhIQiECbFrV8PaJnOSc3uVbuT@19KSPJyEVzVIVFtUebL8q9fya5Meh1NMmC1VLBw/mkNyq9x3mmiOw/M6Bzf@VnAFGTsBKki7i@0j1tt9jTYehOHauPIFe62@UDhvEJYBoronwB "Haskell – Try It Online") Since this has died down a bit, here's my approach. It's a golfed version of the sample code I made for the question. I think it can definitely be shorter. I just thought I'd put it out there. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~13~~ 11 bytes -2 bytes thanks to zgarb ``` L←fȯ¬tuMBtN ``` [Try it online!](https://tio.run/##yygtzv7/3@dR24S0E@sPrSkp9XUq8fv//7@hAQA "Husk – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` L>вʒË}нg ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fx@7CplOTDnfXXtib/v@/OQA "05AB1E – Try It Online") -1 thanks to [kalsowerus](https://codegolf.stackexchange.com/users/68910/kalsowerus). [Answer] # Mathematica, 71 bytes ``` Max[L/@Select[Array[a~IntegerDigits~#&,a=#,2],(L=Length)@Union@#==1&]]& ``` [Try it online!](https://tio.run/##BcFNC8IgHAfgrxIIsuAH5no/CAZdAoMgOokHGc4JzcD9D0W0r27PM3oaUjfVXtWrf1sj9D08Q0f2VIr/WD9fMoUYyjnFRNPMOLxiaB0ao0zIkYalfuT0ypopJblzvN5KyrQQuhf6K9FijQ222GGPA46QK0j5q38 "Mathics – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes ``` +₁⟦₁b∋;?ḃ₍=l ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X/tRU@Oj@cuAZNKjjm5r@4c7mh819drm/P9v/j8KAA "Brachylog – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~92~~ 87 bytes 5 bytes thanks to Halvard Hummel. ``` g=lambda n,b,s=1:s*(n<b)or(n%b**2%-~b<1)*g(n//b,b,s+1) f=lambda n,b=2:g(n,b)or f(n,b+1) ``` [Try it online!](https://tio.run/##TYu9DoIwFEZ3n6ILSVs/g221akOfxDjQmCIJXgiwuPjq9bK5fT/nTJ/1NZIrpYtD@07PVhASlmjCoiU1SY2zpCppbavDNzVG6U5SXacN2hu1y39atIFPbI7IW2CgZC4kehJ3AwuHE87wuOCKG8wRhlcP7zhb9whimntaJdtKlR8 "Python 3 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` LḟEMBtN ``` [Try it online!](https://tio.run/##yygtzv7/3@fhjvmuvk4lfv///zc0MDIGAA "Husk – Try It Online") ### Explanation ``` LḟEMBtN tN on numbers 2,3,4... MB map input to digits in base 2,3,4... ḟE find first list that only has one unique element L length of that ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~28~~ 26 bytes Saved 2 bytes thanks to Adám! ``` {⌈/≢¨⍵/⍨1=≢∘∪¨⍵}⊢⊥⍣¯1⍨¨1+⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqRz0d@o86Fx1a8ah3q/6j3hWGtkDeo44ZjzpWgcVqH3UtetS19FHv4kPrDYHyh1YYaj/q3QzUDZLebGjIlaZgZAYkzIyBhKGBkTEA "APL (Dyalog Unicode) – Try It Online") Pretty straightforward implementation. ``` {⌈/≢¨⍵/⍨(1=≢∘∪)¨⍵}⊢⊥⍣¯1⍨¨1+⍳ 1+⍳ ⍝ Make a range [2, n + 1] ¨ ⍝ For each b in that range ⊢⊥⍣¯1⍨ ⍝ Interpret n in base b (gives a vector of integers) ⍵/⍨ ⍝ Keep the representations where 1=≢∘∪¨⍵ ⍝ it's a repdigit ¨⍵ ⍝ For every representation, ≢∘∪ ⍝ is the length of it, without duplicates 1= ⍝ equal to 1? ≢¨ ⍝ Get the length of each of the remaining representations ⌈/ ⍝ Get the biggest length ``` [Answer] # Mathematica, 58 bytes ``` FirstCase[#~IntegerDigits~Range[#+1],l:{a_ ..}:>Tr[1^l]]& ``` Throws an error (because base-1 is not a valid base), but it is safe to ignore. Of course, it is okay to take the length of the first repdigit (`FirstCase`), since numbers in lower bases cannot be shorter than in higher bases. [Answer] ## CJam (17 bytes) ``` {_,2>3+fb{)-!}=,} ``` [Online test suite](http://cjam.aditsu.net/#code=qN%25%7B~%3AE%3B%0A%0A%7B_%2C2%3E3%2Bfb%7B)-!%7D%3D%2C%7D%0A%0A~E%3Do%7D%2F&input=1%201%0A2%201%0A3%202%0A4%202%0A5%202%0A6%202%0A7%203%0A8%202%0A9%202%0A10%202%0A11%202%0A26%203%0A63%206%0A1023%2010). This is an anonymous block (function) which takes an integer on the stack and leaves an integer on the stack. Works with brute force, using `3` as a fallback base to handle the special cases (input `1` or `2`). [Answer] # [Perl 6](https://perl6.org), 49 bytes ``` {+first {[==] $_},map {[.polymod($^b xx*)]},2..*} ``` [Try it online!](https://tio.run/##FYpBCsIwAAS/socibV2CTTQqkpdIlYoGhIaE1END6dtjepjDzG74xFFnl7CzMHnZ22@cfljuxvSonivdEIqJ4Mfk/LuuHi/Mc9v0K6UQ7ZqnIaG25QrrIzpCEoo4EidCE2fiQlyJ7lDY9hK12lyq5pb/ "Perl 6 – Try It Online") ### Explanation ``` { } # A lambda. map { },2..* # For each base from 2 to infinity... .polymod($^b xx*) # represent the input in that base, [ ] # and store it as an array. first {[==] $_}, # Get the first array whose elements # are all the same number. + # Return the length of that array. ``` The [polymod](https://docs.perl6.org/routine/polymod) method is a generalization of Python's `divmod`: It performs repeated integer division using a given list of divisors, and returns the intermediate remainders. It can be used to decompose a quantity into multiple units: ``` my ($sec, $min, $hrs, $days, $weeks) = $seconds.polymod(60, 60, 24, 7); ``` When passing a lazy sequence as the list of divisors, `polymod` stops when the quotient reaches zero. Thus, giving it an infinite repetition of the same number, decomposes the input into digits of that base: ``` my @digits-in-base-37 = $number.polymod(37 xx *); ``` I use this here because it allows arbitrarily high bases, in contrast to the string-based [`.base`](https://docs.perl6.org/routine/base) method which only supports up to base 36. [Answer] ## TI-BASIC, 37 bytes ``` Input N For(B,2,2N int(log(NB)/log(B If fPart(N(B-1)/(B^Ans-1 End ``` Prompts for N, returns output in Ans. # Explanation As an overview, for each possible base B in sequence it first calculates the number of digits of N when represented in base B, then checks whether N is divisible by the value represented by that same number of 1-digits in base B. ``` Input N Ask the user for the value of N. For(B,2,2N Loop from base 2 to 2N. We are guaranteed a solution at base N+1, and this suffices since N is at least 1. int(log(NB)/log(B Calculate the number of digits of N in base B, placing the result in Ans. This is equivalent to floor(log_B(N))+1. (B-1)/(B^Ans-1 The value represented by Ans consecutive 1-digits in base B, inverted. If fpart(N Check whether N is divisible by the value with Ans consecutive 1-digits, by multiplying it by the inverse and checking its fractional part. Skips over the End if it was divisible. End Continue the For loop, only if it was not divisible. The number of digits of N in base B is still in Ans. ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 24 bytes ``` {|/x{#{1=#?x}#y\x}'2+!x} ``` [Try it online!](https://ngn.codeberg.page/k#eJw1j1tugzAQRf9nFVRUaqPKMbaDSbDaLiRFCgLzUChOwZWMKF17oRN/nTN3rjSaKp1/qJvDmb2G724Jpw+3PPGXB7cA2HR+PE+/Q1oFQeDUxVzV86XK2045Nalhly1gz0yxbAVHCMU3HBAxQiISJTYccTohWHQnQ3KJLSmUxD0XikUZAIXG2tuYUlqYUtemq/ajzYurdkWT97XeF+aTfn3r0bamHykTSZLEtGr7kthGk86sndGSQd9I2datBWDrW+QtYMC9CBQOBy+xF+klQRFw9MnJC4u8sLtwiV0p/gMJ2z/bqegPBNpgBQ==) * `x{...}'2+!x` call the inner `{...}` lambda on the input `n`, paired up with each number from `2..n+1` + `y\x` convert the input to the current base + `{1=#?x}#` filter down to representations containing only a single unique digit + `#` return the length of this representation (`0` if it contained multiple digits) * `{|/...}` return the maximum across all potential bases [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` lhf!t{TjLQ}2h ``` [Try it online!](http://pyth.herokuapp.com/?code=lhf%21t%7BTjLQ%7D2h&input=7&debug=0) [Answer] # Java 8, 111 bytes ``` n->{int r=0,i=1,l;for(String t;++i<n+2;r=(l=t.length())>r&t.matches("(.)\\1*")?l:r)t=n.toString(n,i);return r;} ``` Byte-count of 111 is also a rep-digit. ;) **Explanation:** [Try it here.](https://tio.run/##fZExb8IwEIX3/opThsqug0WClAFjOncoC2Pp4AYTTM0FOQdShfjtqUNS0QEh2Trd83f2e/LOnMyoPljcrb/b0pumgXfj8PwE4JBs2JjSwqJrrwKU7C3KlQ2AXEX1EndcDRlyJSwAQUOLo/m5g4Mep05nqVebOrAlBYcVkBLCzVDkKmjmNUlvsaIt43wenknuDZVb27CESb5aZS8Jf/XTwEmjpLq/gmHquAqWjgEhqEurehOH45ePJgYvp9qtYR@zDA9/fILhfZDOTecvelPgZjrrihDDKcDypyG7l/WR5CGOkkfmQEAyhSQWlCVz/Jq@z393IMmLG54Xf/w9spjcyGLyiMzG@T@26/jwC5f2Fw) ``` n->{ // Method with Integer as parameter return-type int r=0, // Result-integer i=1, // Index-integer l; // Length-integer for(String t; // Temp-String ++i<n+2; // Loop from 2 to `n+2` (exclusive) r= // After every iteration, change `r` to: (l=t.length())>r // If the length of `t` is larger than the current `r` &t.matches("(.)\\1*")? // and the current `t` is a rep-digit: l // Change `r` to `l` (the length of the rep-digit) : // Else: r) // Leave `r` as is t=n.toString(n,i); // Set String representation of `n` in base-`i` to `t` // End of loop (implicit / single-line body) return r; // Return the result-integer } // End of method ``` [Answer] # Java 8, 79 bytes A lambda from `Integer` to `Integer`. ``` n->{int m,b=2,l;for(;;b++){for(m=n,l=0;m>0&m%b==n%b;l++)m/=b;if(m<1)return l;}} ``` ## Ungolfed lambda ``` n -> { int m, b = 2, l; for (; ; b++) { for (m = n, l = 0; m > 0 & m % b == n % b; l++) m /= b; if (m < 1) return l; } } ``` Checks radices in increasing order from 2 until a rep-digit radix is found. Relies on the fact that the smallest such radix will correspond to a representation with the most digits. `m` is a copy of the input, `b` is the radix, and `l` is the number of digits checked (and ultimately the length of the radix-`b` representation). [Answer] ## Burlesque, 24 bytes (see correct solution below) ``` J2jr@jbcz[{dgL[}m^>] ``` See in [action](http://cheap.int-e.eu/~burlesque/burlesque.cgi?q=7J2jr%40jbcz%5B%7BdgL%5B%7Dm%5E%3E%5D). ``` J2jr@ -- boiler plate to build a list from 2..N jbcz[ -- zip in N {dgL[}m^ -- calculate base n of everything and compute length >] -- find the maximum. ``` At least if my intuition is right that a rep-digit representation will always be longest? Otherwise uhm... ``` J2jr@jbcz[{dg}m^:sm)L[>] :sm -- filter for "all elements are the same" ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 60 bytes ``` ->n{(2..n).filter_map{d=n.digits _1 !d.uniq[1]&&d.size}.max} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3bXTt8qo1jPT08jT10jJzSlKL4nMTC6pTbPP0UjLTM0uKFeINuRRT9ErzMgujDWPV1FL0ijOrUmv1chMraqFm2BYouEWbxyooK-jaKRhzgXhGZihcM2Mo1wzMNTQwggkYGkAMWbAAQgMA) ]
[Question] [ In English, there is the fun and simple difference between `an` and `a`: you use `an` when preceding a word starting with a vowel sound, and `a` when the word starts with a consonant sound. For the sake of simplicity in this challenge, `an` precedes a word that starts with a vowel (`aeiou`), and `a` precedes a word that starts with a consonant. **Input** A string comprising only printable ASCII characters, with `[?]` appearing in places where you must choose to insert `an` or `a`. `[?]` will always appear before a word. You can assume that the sentence will be grammatically correct and formatted like normal. **Output** The input string with `[?]` replaced with the appropriate word (`an` or `a`). You do have to worry about capitalization! **When to Capitalize** Capitalize a word if it is preceded by no characters (is the first one in the input) or if it is preceded by one of `.?!` followed by a space. **Examples** ``` Input: Hello, this is [?] world! Output: Hello, this is a world! Input: How about we build [?] big building. It will have [?] orange banana hanging out of [?] window. Output: How about we build a big building. It will have an orange banana hanging out of a window. Input: [?] giant en le sky. Output: A giant en le sky. Input: [?] yarn ball? [?] big one! Output: A yarn ball? A big one! Input: [?] hour ago I met [?] European. Output: A hour ago I met an European. Input: Hey sir [Richard], how 'bout [?] cat? Output: Hey sir [Richard], how 'bout a cat? ``` **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!** [Answer] # Perl, 48 bytes *Saved 1 byte due to [Ton Hospel](https://codegolf.stackexchange.com/posts/comments/227428?noredirect=1).* ``` #!perl -p s;\[\?];A.n x$'=~/^ [aeiou]/i^$"x/[^.?!] \G/;eg ``` Counting the shebang as one, input is taken from stdin. **Explanation** ``` #!perl -p # for each line of input, set $_, auto-print result s; # begin regex substitution, with delimiter ; \[\?] # match [?] literally, and replace with: ; A.n x$'=~/^ [aeiou]/i # 'A', concatenate with 'n' if post-match ($') # matches space followed by a vowel ^$"x/[^.?!] \G/ # if the match is preceded by /[^.?!] /, xor with a space # this will change An -> an ;eg # regex options eval, global ``` **Sample Usage** ``` $ echo Hello, this is [?] world! | perl a-an.pl Hello, this is a world! $ echo How about we build [?] big building. It will have [?] orange banana hanging out of [?] window. | perl a-an.pl How about we build a big building. It will have an orange banana hanging out of a window. $ echo [?] giant en le sky. [?] yarn ball? | perl a-an.pl A giant en le sky. A yarn ball? $ echo [?] hour ago I met [?] European. | perl a-an.pl A hour ago I met an European. ``` [Answer] # Ruby, ~~78~~ 72 bytes ``` ->s{s.gsub(/(^|\. )?\K\[\?\]( [aeiou])?/i){"anAn"[$1?2:0,$2?2:1]+"#$2"}} ``` * Saved 6 bytes thanks to [@Jordan](https://codegolf.stackexchange.com/users/11261/) **Ungolfed** ``` def f(s) s.gsub(/(^|\. )?\[\?\]( [aeiou])?/i) do |m| capitalize = $1 vowel = $2 replacement = if vowel then capitalize ? "An" : "an" else capitalize ? "A" : "a" end m.sub('[?]', replacement) end end ``` [Answer] # [V](http://github.com/DJMcMayhem/V), 41 bytes ``` ÍãÛ?Ý ¨[aeiou]©/an ÍÛ?Ý/a Í^aü[.!?] a/A ``` [Try it online!](http://v.tryitonline.net/#code=w43Do8ObP8OdwoUgwqhbYWVpb3VdwqkvYW4Kw43Dmz_DnS9hCsONXmHDvFsuIT9dIMKTYS9B&input=SGVsbG8sIHRoaXMgaXMgWz9dIHdvcmxkIQpIb3cgYWJvdXQgd2UgYnVpbGQgWz9dIGJpZyBidWlsZGluZy4gSXQgd2lsbCBoYXZlIFs_XSBvcmFuZ2UgYmFuYW5hIGhhbmdpbmcgb3V0IG9mIFs_XSB3aW5kb3cuCls_XSBnaWFudCBlbiBsZSBza3kuCls_XSB5YXJuIGJhbGw_Cls_XSBob3VyIGFnbyBJIG1ldCBbP10gRXVyb3BlYW4u), which conveniently can also be used to verify all test cases with no extra byte count. This takes advantage of V's "Regex Compression". It uses a lot of unprintable characters, so here is a hexdump: ``` 0000000: cde3 db3f dd85 20a8 5b61 6569 6f75 5da9 ...?.. .[aeiou]. 0000010: 2f61 6e0a cddb 3fdd 2f61 0acd 5e61 fc5b /an...?./a..^a.[ 0000020: 2e21 3f5d 2093 612f 41 .!?] .a/A ``` [Answer] # PHP, 207 bytes ``` foreach(explode("[?]",$s)as$i=>$b){$r=Aa[$k=0|!strstr(".!?",''==($c=trim($a))?".":$c[strlen($c)-1])].n[!preg_match("#^['\"´`\s]*([aeiou]|$)#i",$d=trim($b))];echo$i?$r.$b:$b;$a=$i?''==$d?a:$b:(''==$d?".":a);} ``` I like solutions more complete from time to time ... but I must admit that this is a little overkill, although it´s not at all finished. Save to file, run with `php <filename>` with input from STDIN. **test cases** ``` How about we build [?] big building ... with [?] orange banana hanging out of [?] window. => How about we build a big building ... with an orange banana hanging out of a window. Hello, this is [?] world! => Hello, this is a world! Should I use [?] '[?]' or [?] '[?]'? => Should I use an 'an' or an 'a'? [?] elephant in [?] swimsuit. => An elephant in a swimsuit. How I met your moth[?]. => How I met your motha. b[?][?][?] short[?]ge! => banana shortage! ``` **breakdown** ``` foreach(explode("[?]",$s)as$i=>$b) { $r= // lookbehind: uppercase if the end of a sentence precedes Aa[$k=0|!strstr(".!?",''==($c=trim($a))?".":$c[strlen($c)-1])] . // lookahead: append "n" if a vowel follows (consider quote characters blank) n[!preg_match("#^['\"´`\s]*([aeiou]|$)#i",$d=trim($b))] ; // output replacement and this part echo$i?$r.$b:$b; // prepare previous part for next iteration $a=$i // this part was NOT the first: ? ''==$d ? a // if empty -> a word ($r from the previous iteration) : $b // default: $b : (''==$d // this WAS the first part: ? "." // if empty: end of a sentence (= uppercase next $r) : a // else not ) ; // golfed down to `$a=!$i^''==$d?a:($i?$b:".");` } ``` [Answer] ## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), 75 bytes ``` od4&r$O."]?["30$Z3&00w4X"Aa"I2-"Aa ."40$Z,*2&$rxr$O" aeiou"od0Z1=3&"n"r5X$r ``` [Try it here!](http://play.starmaninnovations.com/minkolang/?code=od4%26r%24O%2E%22%5D%3F%5B%2230%24Z3%2600w4X%22Aa%22I2-%22Aa%20%2E%2240%24Z%2C*2%26%24rxr%24O%22%20aeiou%22od0Z1%3D3%26%22n%22r5X%24r&input=%5B%3F%5D%20example%3A%20How%20about%20we%20build%20%5B%3F%5D%20big%20building%2E%20It%20will%20have%20%5B%3F%5D%20orange%20banana%20hanging%20out%20of%20%5B%3F%5D%20window%2E%20%5B%3F%5D%20example%2E) ### Explanation ``` od Take character from input and duplicate (0 if input is empty) 4& Pop top of stack; jump 4 spaces if not 0 r$O. Reverse stack, output whole stack as characters, and stop. "]?[" Push "[?]" on the stack 30$Z Pop the top 3 items and count its occurrences in the stack 3& Pop top of stack; jump 3 spaces if not 0 00w Wormhole to (0,0) in the code box 3X Dump the top 3 items of stack "Aa" Push "aA" I2- Push the length of stack minus 2 "Aa ."40$Z, Push ". aA" and count its occurrences, negating the result * Multiply the top two items of the stack 2&$r Pop top of stack and swap the top two items if 0 x Dump top of stack r Reverse stack $O Output whole stack as characters " aeiou" Push a space and the vowels od Take a character from input and duplicate 0Z Pop top of stack and count its occurrences in the stack (either 1 or 2) 1= 1 if equal to 1, 0 otherwise 3& Pop top of stack; jump 3 spaces if not 0 "n" Push "n" if top of stack is 0 r Reverse stack 5X Dump top five items of stack $r Swap top two items of stack ``` Note that because Minkolang is toroidal, when the program counter moves off the right edge, it reappears on the left. Certainly golfable, but because I had to add 21 bytes because of the spec, I may not try. [Answer] # JavaScript (ES6), 90 ~~86 87 85~~ *Edit once more* as the spec for capitalization has changed (more sensible now) *Edit again* 1 byte save thx @Huntro *Edit* 2 more bytes to manage quotes and the like, as pointed out by IsmaelMiguel (even if I don't know if it's requested by op). Note that previously I had counted 86 bytes but they were 85 ~~Trying to follow the capitalization rule stated in the comments event if it's incomplete (at least)~~ ``` x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c)) ``` **Test** ``` f=x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c)) function go() { var i=I.value, o=f(i) O.innerHTML = '<i>'+i+'</i>\n<b>'+o+'</b>\n\n'+O.innerHTML } go() ``` ``` #I { width:80% } ``` ``` <input value='How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.' id=I><button onclick='go()'>GO</button><pre id=O></pre> ``` [Answer] ## Batch, 136 bytes ``` @set/ps= @for %%v in (a e i o u)do @call set s=%%s:[?] %%v=an %%v%% @set s=%s:[?]=a% @if %s:~0,1%==a set s=A%s:~1% @echo %s:. a=. A% ``` Takes a line of input on STDIN. [Answer] # PHP, ~~100~~ 92 bytes ``` <?=preg_filter(["/\[\?]\K(?= [aeiou])/i","/([.?!] |^)\K\[\?]/","/\[\?]/"],[n,A,a],$argv[1]); ``` It was possible to further golf the regular expressions. Gives a notice about an undefined constant but still works. Edit: 8 bytes saved thanks to primo [Answer] # Java, ~~180~~178 bytes My first post here, I did use a part of the **Kevin Cruijssen** post but and up with a different approach, he helped me to reduce a bit more so, thanks to him ! ``` String c(String s){String x[]=s.split("\\[\\?]",2),r=x[0];return x.length>1?r+(r.matches("(.+[.!?] )|(^)$")?"A":"a")+("aeiouAEIOU".contains(""+x[1].charAt(1))?"n":"")+c(x[1]):r;} ``` Here it is ungolfed : ``` static String c(String s) { String x[] = s.split("\\[\\?\\]", 2), r = x[0]; return x.length > 1 ? r + (r.matches("(.+[.!?] )|(^)$") ? "A" : "a") + ("aeiouAEIOU".contains("" + x[1].charAt(1)) ? "n" : "") + c(x[1]) : r; } ``` [And the result](https://ideone.com/3gG1Z1) A simple explanation, I use a recursive approch to find every `[?]`. I couldn't find a way to use the matches with insensitive case (not sure it is possible). 178bytes : Thanks to Martin Ender ! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ ~~36~~ 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2FžNžM‚NèSðì…[?]©ìDu«D®'a'nN׫::}.ª ``` [Try it online](https://tio.run/##yy9OTMpM/f/fyO3oPr@j@3wfNczyO7wi@PCGw2seNSyLto89tPLwGpfSQ6tdDq1TT1TP8zs8/dBqK6tavUOr/v8HSitUJhblKSQl5uTYK4C4SZnpCvl5qYpgTkZ@aZFCYnq@gqdCbmoJWMi1tCi/IDUxT@@/rm5evm5OYlUlAA) or [verify all test cases](https://tio.run/##PY@xTsNADIb3PIWbpUuagbFLloLagSDBWHVwmiM5cdjV5a5REEh9CyQeAAGtEBNjh0R9kb5IuCQSsgf//n7bMheYSNE@b/0FbayZAvhRFXj@jTW9dKq9uDod49Px@rx7i5uPu@anOZx378toVX82h5mt97P6e4xjipvXej@dvoT1VxvUv1E7F0pxACaXBbh0E1CyVunIm3MJmLA1UApIrFRpTxOZDUpSFsLCUakU5LgVPWaNlDk/kgvXpsz5oNvC98N2SSmXodfVmUQyIAiUgOKhGpoVanLzSkX/95jEqGc5Ww2YMSzgUZieX1rNG4EUenNRQSE1LG/lOkedrgLnL2Hc/9BZ12iidjIhnih8qv4A). **Explanation:** ``` 2F # Loop 2 times: žN # Push consonants "bcdfghjklmnpqrstvwxyz" žM # Push vowels "aeiou" ‚ # Pair them together into a list Nè # And use the loop-index to index into this pair S # Convert this string to a list of characters ðì # Prepend a space in front of each character …[?] # Push string "[?] © # Store it in variable `®` (without popping) ì # And prepend it in front of each string in the list as well }D # Then duplicate the list u # Uppercase the characters in the copy « # And merge the two lists together # i.e. for the vowel-iteration we'd have ["[?] a","[?] e","[?] i","[?] o", # "[?] u","[?] A","[?] E","[?] I","[?] O","[?] U"] D # Duplicate it ® # Push "[?]" from variable `®` 'a '# Push "a" 'n '# Push "n" N× # Repeated the 0-based index amount of times (so either "" or "n") « # And append it to the "a" : # Replace all "[?]" with "an"/"a" in the duplicated list : # And then replace all values of the lists in the (implicit) input-string }.ª # After the loop: sentence-capitalize everything (which fortunately retains # capitalized words in the middle of sentences, like the "European" testcase) # (and after the loop the result is output implicitly) ``` [Answer] # Python 3.5.1, ~~153~~ ~~147~~ 141 ~~124~~ Bytes ``` *s,=input().replace('[?]','*');print(*['aA'[i<1or s[i-2]in'.?!']+'n'*(s[i+2]in 'aeiouAEIOU')if c=='*' else c for i,c in enumerate(s)],sep='') ``` Input : `[?] apple [?] day keeps the doctor away. [?] lie.` Output : `An apple a day keeps the doctor away. A lie.` 123 Bytes version - This does not handle capitalization rule. ``` s=list(input().replace('[?]','*'));print(*['a'+'n'*(s[i+2]in 'aeiouAEIOU')if c=='*'else c for i,c in enumerate(s)],sep='') ``` [Try it online!](https://tio.run/##HY29DoIwFIVf5TrdFpBEHZUQBgcnJyfSoSmXcGMtDS0xPH0tbiff@fNbnGZ3SakIVcPOr1HIeiFvtSGBfauwwgLl1S/soih61B32fDvNC4Sej2fFDuv2gKpEh4XIrNwZoCae1@7@eL5Q8gimafIOkA0EBsZc58pADpJbP7ToSCJIVQXyDaJMKT@D9t4S7GrQG7yJfIA4EQyziXlAf/VW/23LVP8A "Python 3 – Try It Online") [Answer] # C#, ~~204~~ 235 bytes ``` string n(string b){for(int i=0;i<b.Length;i++){if(b[i]=='['){var r="a";r=i==0||b[i-2]=='.'?"A":r;r=System.Text.RegularExpressions.Regex.IsMatch(b[i+4].ToString(),@"[aeiouAEIOU]")?r+"n":r;b=b.Insert(i+3,r);}}return b.Replace("[?]","");} ``` Ungolfed full program: ``` using System; class a { static void Main() { string s = Console.ReadLine(); a c = new a(); Console.WriteLine(c.n(s)); } string n(string b) { for (int i = 0; i < b.Length; i++) { if (b[i] == '[') { var r = "a"; r = i == 0 || b[i - 2] == '.' ? "A" : r; r = System.Text.RegularExpressions.Regex.IsMatch(b[i + 4].ToString(), @"[aeiouAEIOU]") ? r + "n" : r; b = b.Insert(i + 3, r); } } return b.Replace("[?]", ""); } } ``` I'm sure this could be improved, especially the Regex part, but can't think of anything right now. [Answer] # Java 7, ~~239~~ ~~214~~ 213 bytes ``` String c(String s){String x[]=s.split("\\[\\?\\]"),r="";int i=0,l=x.length-1;for(;i<l;r+=x[i]+(x[i].length()<1|x[i].matches(".+[.!?] $")?65:'a')+("aeiouAEIOU".contains(x[++i].charAt(1)+"")?"n":""));return r+x[l];} ``` **Ungolfed & test cases:** [Try it here.](https://ideone.com/iwgwyr) ``` class M{ static String c(String s){ String x[] = s.split("\\[\\?\\]"), r = ""; int i = 0, l = x.length - 1; for (; i < l; r += x[i] + (x[i].length() < 1 | x[i].matches(".+[.!?] $") ? 65 : 'a') + ("aeiouAEIOU".contains(x[++i].charAt(1)+"") ? "n" : "")); return r + x[l]; } public static void main(String[] a){ System.out.println(c("Hello, this is [?] world!")); System.out.println(c("How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.")); System.out.println(c("[?] giant en le sky.")); System.out.println(c("[?] yarn ball? [?] big one!")); System.out.println(c("[?] hour ago I met [?] European. ")); System.out.println(c("Hey sir [Richard], how 'bout [?] cat?")); System.out.println(c("[?] dog is barking. [?] cat is scared!")); } } ``` **Output:** ``` Hello, this is a world! How about we build a big building. It will have an orange banana hanging out of a window. A giant en le sky. A yarn ball? A big one! A hour ago I met an European. Hey sir [Richard], how 'bout a cat? A dog is barking. A cat is scared! ``` [Answer] ## Racket 451 bytes (without regex) It is obviously a long answer but it replaces a and an with capitalization also: ``` (define(lc sl item)(ormap(lambda(x)(equal? item x))sl)) (define(lr l i)(list-ref l i))(define(f str)(define sl(string-split str)) (for((i(length sl))#:when(equal?(lr sl i)"[?]"))(define o(if(lc(string->list"aeiouAEIOU") (string-ref(lr sl(add1 i))0))#t #f))(define p(if(or(= i 0)(lc(string->list".!?") (let((pr(lr sl(sub1 i))))(string-ref pr(sub1(string-length pr))))))#t #f)) (set! sl(list-set sl i(if o(if p"An""an")(if p"A""a")))))(string-join sl)) ``` Testing: ``` (f "[?] giant en le [?] sky.") (f "[?] yarn ball?") (f "[?] hour ago I met [?] European. ") (f "How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.") (f "Hello, this is [?] world!") ``` Output: ``` "A giant en le a sky." "A yarn ball?" "A hour ago I met an European." "How about we build a big building. It will have an orange banana hanging out of a window." "Hello, this is a world!" ``` Detailed version: ``` (define(contains sl item) (ormap(lambda(x)(equal? item x))sl)) (define(lr l i) (list-ref l i)) (define(f str) (define sl(string-split str)) (for((i(length sl))#:when(equal?(lr sl i)"[?]")) (define an ; a or an (if(contains(string->list "aeiouAEIOU") (string-ref(lr sl(add1 i))0)) #t #f )) (define cap ; capital or not (if(or(= i 0)(contains(string->list ".!?") (let ((prev (lr sl(sub1 i)))) (string-ref prev (sub1(string-length prev)))))) #t #f)) (set! sl(list-set sl i (if an (if cap "An" "an" ) (if cap "A" "a"))))) (string-join sl)) ``` [Answer] # [J](http://jsoftware.com/), 113 bytes ``` [:;:inv 3(0 2&{(((('aA'{~[)<@,'n'#~])~('.?!'e.~{:))~('AEIOUaeiou'e.~{.))&>/@[^:(<@'[?]'=])1{])\' 'cut' . '([,~,)] ``` [Try it online!](https://tio.run/##fZFta8IwFIW/@yuOG3gbqN3bt06nMhwTBgNhn7oOosY2W5aM2lpE6F93STdfNsG@QHvvc885Sd43ZwHN0Q1B8HGJ0L7tAPfjp4dNFN6GUi9x413iurX27EV8QOsqYp2@T5rOq5hVHgW9JomgWofM/Q2Go@cXLqQp6mLAWOvuoh@9hV6nT1Evpm7MrtYxeyXQtMgJAciL/Mpn8YY1xDQ1oEehlPGRp3IB@3CUJlOzJqEdYn7UtqJboLEVMCX4xBQ5SoFJIdXMikxk8vMtdRJgZHtSKaR8KcA1TMZ1YmGu7W2rOrEYnISZuwRSz0wZ7CIcG7gYJyxc@6RHvYxfl@06Bkgk1zmEhhJYfKx2ARx91NuPrXimrY9SPQzqVEaL5uHsAbANXiN7idQUGXhiMMKnyN0WDYvMfAmu/4T4h7nSntudh1hhITNEYzlNeTaLfTtXgqjeQo4pz3v70z3FOv2abmy@AQ "J – Try It Online") Shame, shame! [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~66~~ 60 bytes ``` i`\[\?\]( ([aeiou]?)[a-z&&[^aeiou]) a$.2*n$1 (^|[.?!] )a $1A ``` [Try it online.](https://tio.run/##PY/BToRADIbvPEU3wRXMSoIvMPFgZK9eBzZblnFoHFszDBKM744DJKY99O/3t029CcRYLnfZ63Wha61rVTcZZBoNydioXOPjz/GoL7vOE0yLpwdOyyS7/OpCHRrIMUnL52WpjHNygtDTADG1amAS77pDUskE2MoYYDLQjuS6jbZkd0VsCzhHSs5Bj99mw@KRbfQjx4htttEH6xZ537cTdzIVyVpbQg5gGJyB4WPemzN6jvPOqf97wuawsV5GD2gFzvBpwsZfRi9fBrlIKjPDQB70G9169F1ziv4J7rcfVusNg/oD) **Explanation:** Do a case-insensitive search for `[?]` followed by a vowel or consonant, where the optional vowel is saved in capture group 2, and the entire match in capture group 1: ``` i`\[\?\]( ([aeiou]?)[a-z&&[^aeiou]) ``` Replace this with an `a`, followed by the length of the second group amount of `n` (so either 0 or 1 `n`), followed by the letter(s) of capture group 1: ``` a$.2*n$1 ``` Then match an `a` at either the start of the string, or after either of `.?!` plus a space: ``` (^|[.?!] )a ``` And uppercase that A, without removing the other characters of capture group 1: ``` $1A ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 154 bytes ``` s->{String v="(?= [aeiou])",q="(?i)\\[\\?]",b="(?<=^|[?.!] )";return s.replaceAll(b+q+v,"An").replaceAll(q+v,"an").replaceAll(b+q,"A").replaceAll(q,"a");} ``` [Try it online!](https://tio.run/##lVLNbqMwEL7nKSa@LGypXyBNUQ@V2kNVaas9EVYawCVOjE1tA0LdPHt2DGq06u6hGGQ0358Gjw/Y4/WhOp5l0xrr4UA177xU/Ptm9Q/22unSS6P/SzpvBTaBKhU6B08o9ep9BbTarlCyBOfR06c3soKG2OjFW6nrLAe0tYsn6WwI66dGOz63wqI39maW3oKF7dld377PNfRbFqVbyFBI0@UxS94CIOPdLtvt0pwlRahvtr9@Zylf5xCzjRW@sxoct6JVWIo7paLi6u2qT9idZvHf8ATiJ5C0pPwkJBmLN6fzR/Oby2@8jM6LhpvO85Za9kpHlmPbqjFiWZrDA9oKPLojZ3H8dds9unGh7UGMKZCXh20dtgVWpUwCfi8d0BsaGIxV1frrCWYALIiCQUDRSVVNKYWs54qGyeGRWKkU7LEXE20s6pr0qOkhWNdh6CHFvM5dSF2ZYdnR1RK1B6FBCXDHcZl5RLo7BSqVXvo3WqwXZexNZwFrA4/QCD/l3HfWtAI1hyXjBCctZD9kuadLlCcUPMC36ZBDZok@vaSdVqfzHw "Java (JDK) – Try It Online") ### Explanation: ``` s->{ String v="(?= [aeiou])", // matches being followed by a vowel q="(?i)\\[\\?]", // matches being a [?] b="(?<=^|[?.!] )"; // matches being preceded by a sentence beginning return s.replaceAll(b+q+v,"An") // if beginning [?] vowel, you need "An" .replaceAll(q+v,"an") // if [?] vowel, you need "an" .replaceAll(b+q,"A") // if beginning [?] , you need "A" .replaceAll(q,"a");} // if [?] , you need "a" ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~225~~ ~~207~~ ~~202~~ 201 bytes Thanks to ceilingcat for -24 bytes ``` #define P strcpy(f+d,index("!?.",i[c-2])+!c? c;d;v(i,g,f)char*i,*g,*f;{for(d=0;i[c];c++,d++)strcmp("[?]",memcpy(g,i+c,3))?f[d]=i[c]:(index("aeiouAEIOU",i[c+4])?P"An ":"an "),d++:P"A ":"a "),d++,c+=3);} ``` [Try it online!](https://tio.run/##TY87b8IwFIVn@BXGXez4glBhASuKGDp0KkunKIPxI7WUlxwDRYjfntoJrerBOj7f1TnXcllKOQwvShvbaHREvXeyuxHDFNhG6W@CF9kKg83l8rWgbCGzueSKX4iFEgyVX8IlFpISEsPvpnVEpWsepgsuGQPFGI2JdUdwnhUYal3H@BIsk7ChNDO5KtI4vyfPPqFtez68vX98jrVsW9DsiA8Nwnsswk1j6j44o/F8g2TphvLHYBuPamEbQu/zWdwOCefyIo31SHRdpZHtkRZeN@h0Q9GV7XU1Cddekan0FYWUdrSs1CftyhXmU1ridd2ltaiqVpIt5XP0PCN02v@y3W73j4Zv99qTwGENE5p1Z9@TsFzUlyggZkOY@aOTfgw/ "C (gcc) – Try It Online") [Answer] # Groovy, ~~73~~ 162 bytes ``` def a(s){s.replaceAll(/(?i)(?:(.)?( )?)\[\?\] (.)/){r->"${r[1]?:''}${r[2]?:''}${'.?!'.contains(r[1]?:'.')?'A':'a'}${'aAeEiIoOuU'.contains(r[3])?'n':''} ${r[3]}"}} ``` *edit: damn, the capitalization totally complicated everything here* [Answer] # C# 209 bytes `string A(string b){var s=b.Split(new[]{"[?]"},0);return s.Skip(1).Aggregate(s[0],(x,y)=>x+(x==""||(x.Last()==' '&&".?!".Contains(x.Trim().Last()))?"A":"a")+("AEIOUaeiou".Contains(y.Trim().First())?"n":"")+y);}` Formatted ``` string A(string b) { var s = b.Split(new[] { "[?]" }, 0); return s.Skip(1).Aggregate(s[0], (x, y) => x + (x == "" || (x.Last() == ' ' && ".?!".Contains(x.Trim().Last())) ? "A" : "a") + ("AEIOUaeiou".Contains(y.Trim().First()) ? "n" : "") + y); } ``` [Answer] # [Perl 6](https://perl6.org), 78 bytes ``` {S:i:g/(^|<[.?!]>' ')?'[?] '(<[aeiou]>?)/{$0 xx?$0}{<a A>[?$0]}{'n'x?~$1} $1/} ``` ## Explanation: ``` { S :ignorecase :global / ( # $0 | ^ # beginning of line | <[.?!]> ' ' # or one of [.?!] followed by a space ) ? # optionally ( $0 will be Nil if it doesn't match ) '[?] ' # the thing to replace ( with trailing space ) ( # $1 <[aeiou]> ? # optional vowel ( $1 will be '' if it doesn't match ) ) /{ $0 xx ?$0 # list repeat $0 if $0 # ( so that it doesn't produce an error ) }{ < a A >[ ?$0 ] # 'A' if $0 exists, otherwise 'a' }{ 'n' x ?~$1 # 'n' if $1 isn't empty # 「~」 turns the Match into a Str # 「?」 turns that Str into a Bool # 「x」 string repeat the left side by the amount of the right # a space and the vowel we may have borrowed } $1/ } ``` ## Test: ``` #! /usr/bin/env perl6 use v6.c; use Test; my &code = {S:i:g/(^|<[.?!]>' ')?'[?] '(<[aeiou]>?)/{<a A>[?$0]~('n'x?~$1)} $1/} my @tests = ( 'Hello, this is [?] world!' => 'Hello, this is a world!', 'How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.' => 'How about we build a big building. It will have an orange banana hanging out of a window.', '[?] giant en le sky.' => 'A giant en le sky.', '[?] yarn ball?' => 'A yarn ball?', '[?] hour ago I met [?] European.' => 'A hour ago I met an European.', "Hey sir [Richard], how 'bout [?] cat?" => "Hey sir [Richard], how 'bout a cat?", ); plan +@tests; for @tests -> $_ ( :key($input), :value($expected) ) { is code($input), $expected, $input.perl; } ``` ``` 1..6 ok 1 - "Hello, this is a world!" ok 2 - "How about we build a big building. It will have an orange banana hanging out of a window." ok 3 - "A giant en le sky." ok 4 - "A yarn ball?" ok 5 - "A hour ago I met an European." ok 6 - "Hey sir [Richard], how 'bout a cat?" ``` [Answer] # Lua, 131 Bytes. ``` function(s)return s:gsub("%[%?%](%s*.)",function(a)return"a"..(a:find("[AEIOUaeiou]")and"n"or"")..a end):gsub("^.",string.upper)end ``` Although lua is a terrible Language for golfing, I feel I've done pretty well. [Answer] ## [Pip](http://github.com/dloscutoff/pip), ~~62~~ ~~55~~ ~~54~~ 50 bytes Takes the string as a command-line argument. ``` aR-`([^.?!] )?\[\?]( [^aeiou])?`{[b"aA"@!b'nX!cc]} ``` [Try it online!](http://pip.tryitonline.net/#code=YVItYChbXi4_IV0gKT9cW1w_XSggW15hZWlvdV0pP2B7W2IiYUEiQCFiJ25YIWNjXX0&input=&args=Wz9dIGhvdXIgYWdvIEkgbWV0IFs_XSBFdXJvcGVhbiEgWz9dIG1hbi4gWz9dIElyaXNobWFuLg) Explanation: ``` a Cmdline argument R Replace... -` ` The following regex (case-insensitive): ([^.?!] )? Group 1: not end-of-sentence (nil if it doesn't match) \[\?] [?] ( [^aeiou])? Group 2: not vowel (nil if there is a vowel) { } ... with this callback function (b = grp1, c = grp2): [ ] List (concatenated when cast to string) of: b Group 1 "aA"@!b "a" if group 1 matched, else "A" 'nX!c "n" if group 2 didn't match, else "" c Group 2 ``` [Answer] ## Racket (with regex) 228 bytes ``` (define(r a b c)(regexp-replace* a b c)) (define(f s) (set! s(r #rx"[a-zA-Z ]\\[\\?\\] (?=[aeiouAEIOU])"s" an ")) (set! s(r #rx"[a-zA-Z ]\\[\\?\\]"s" a")) (set! s(r #rx"\\[\\?\\] (?=[aeiouAEIOU])"s"An ")) (r #rx"\\[\\?\\]"s"A")) ``` Testing: ``` (f "[?] giant en le [?] sky.") (f "[?] yarn ball?") (f "[?] apple?") (f "[?] hour ago I met [?] European. ") (f "How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.") (f "Hello, this is [?] world!") ``` Output: ``` "A giant en le a sky." "A yarn ball?" "An apple?" "A hour ago I met an European. " "How about we build a big building. It will have an orange banana hanging out of a window." "Hello, this is a world!" ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~104~~ 103 bytes -1 bytes, unescaped `]` ``` lambda s:r('(^|[.?!] )a',r'\1A',r('a( [aeiouAEIOU])',r'an\1',r('\[\?]','a',s)));from re import sub as r ``` [Try it online!](https://tio.run/##fZFRa4MwFIXf@ytu@6IBKZS9bQzxobA@DQZ7UgfXGWNYvJEYJ8L@u4u2tOpGURBzvnvOSVL3ttT0MBTPyaCwynKE5tH4nv/xE@/DbQoMvcB4ySFyH99DH2LkUrfR8fT6nrJRQ0oOk5jESZh6gecmGsbYU2F0BYaDrGptLDRtBtiAGWojyfqFv3vhSukAbCkbcG8cptBpo/LtjrHNmVozeCU2m5uP7gAz3VroOGStVPnklUlx/pMk9nByqlQKSvzmk6wNknA8knvcMgnHweiii3MXSbnu9vMyf4PwXgzS/RS8Zcy2M2YLiWSBEygOzVc/LxH9I66mezTkIpUKrwehiW8XJjMmmhErp1K3BlBoOEHF7eR2bI2uOdKy0wp0O59x87viPTTSQPwmP0s0eRq40Q686VRH@0@04eL@7/B4oVeluRCLcnRZGX4B "Python 3 – Try It Online") Starts by replacing all occurences of `[?]` with `a`, Then replaces all `a` followed by a vowel, with `an`. Then replaces all `a` at the start of input or a sentence with `A`. Assumes that `[?]` will never be touching another word, and that lower-case `a` should never begin a sentence. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 124 bytes inspired by Avi's [answer for Java](https://codegolf.stackexchange.com/a/193803/80745). ``` $args-replace(($b='(?<=^|[?.!] )')+($q='\[\?]')+($v='(?= [aeiou])')),'An'-replace"$q$v",'an'-replace"$b$q",'A'-replace$q,'a' ``` [Try it online!](https://tio.run/##fZPBbqMwEIbvPMUkcmvQ0jxAtYjmsNL2ulfKVgNMwVrXDgZCo7bPnh1IkxAqxXDx72/@f2zMxvbkmoq03osXiOB9L9CVzZ2jjcacfF9kkfTjn9HfjyReLVIIZPDDF3Ukn5KnOB0n24GIIEFStksZCEK5NvLosRS12C5DiVMpEzVL65Miagbk/tPzHnwPeIQ@gPzNfdkQ2ko1wG8Sp9Bbp4uFDEdoGHMIj0gw8bE9YGa7FnqCrFO6GL0yVR5mypQreORVpTVUuKVx2To0JfNo@GHZlMzB4GJfDr0oU9h@ddHM9yS8loPmegyeQibbGbJLhaYFMqAJmn@7iybW31dn1Tt0hhO1jk8HYQ0tLk0m0PqMzJwq2znA0sIjvFI7uv3qnN0QmllPM5J3fgan34p20CgHyR@VV@iKNOTKHqQcT3Xwz7GNLy/AtQo88IEXwAfcwPtYJ5oQBL1tKG@p4Gsvng@yo6bTLQu3/DeIZhSXwv/S73KqT1XB/RFfep/7/w "PowerShell – Try It Online") ]
[Question] [ Write a program or function that takes in two integers that represent the X and Y coordinates of a point on a [Cartesian plane](https://en.wikipedia.org/wiki/Cartesian_coordinate_system). The input may come in any reasonable format as long as the X value comes before the Y. For example, `1 -2`, `(1,-2)`, `[1, -2]`, or `1\n-2` would all be fine for X = 1, Y = -2. Print or return a single character string (followed by an optional trailing newline) that describes the location of the point in the plane: * `1` if the point is in [quadrant](https://en.wikipedia.org/wiki/Quadrant_(plane_geometry)) I * `2` if the point is in quadrant II * `3` if the point is in quadrant III * `4` if the point is in quadrant IV * `X` if the point is on the x-axis (lowercase `x` is not allowed) * `Y` if the point is on the y-axis (lowercase `y` is not allowed) * `O` if the point is on the origin (that's a capital letter "oh", not zero) **The shortest code in bytes wins.** Tiebreaker goes to the higher voted answer. ## Test Cases ``` (1,-2) -> 4 (30,56) -> 1 (-2,1) -> 2 (-89,-729) -> 3 (-89,0) -> X (0,400) -> Y (0,0) -> O (0,1) -> Y (0,-1) -> Y (1,0) -> X (-1,0) -> X (1,1) -> 1 (1,-1) -> 4 (-1,1) -> 2 (-1,-1) -> 3 ``` [Answer] # Jelly, 14 bytes ``` Ṡḅ3ị“Y4X13X2YO ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmg4biFM-G7i-KAnFk0WDEzWDJZTw&input=&args=LTEsLTE) ### How it works ``` Ṡḅ3ị“Y4X13X2YO Main link. Input: [x, y] Ṡ Apply the sign function to both coordinates. ḅ3 Convert the resulting pair from base 3 to integer. Because of how base conversion is implemented in Jelly, this maps [a, b] to (3a + b), even if a and b aren't valid ternary digits. Therefore: [0, 1] -> 1 [1, -1] -> 2 [1, 0] -> 3 [1, 1] -> 4 [-1, -1] -> -4 [-1, 0] -> -3 [-1, 1] -> -2 [0, -1] -> -1 [0, 0] -> 0 ị“Y4X13X2YO Retrieve the character at that index from the string. Indexing is 1-based and modular in Jelly, so 1ị retrieves the first character, -1ị the penultimate, and 0ị the last. ``` [Answer] ## Ruby, 35 bytes ``` ->x,y{%w[OY X14 X23][x<=>0][y<=>0]} ``` Leveraging the "spaceship" (`<=>`) operator. `x <=> 0` will return * `0` if `x == 0` * `1` if `x > 0` * `-1` if `x < 0` Hence, * if `x == 0`, we return `'OY'[y<=>0]`. This is + `O` if `y == 0` (string indexing at `0`) + `Y` if `y != 0` (this is true because both `1` and `-1` will result in `Y` when indexing on this string, as `-1` refers to the last character in the string, which also happens to be the one at index 1) * if `x > 0`, we return `'X14'[y<=>0]`. This is `X` if `y == 0`, `1` if `y > 0`, and `4` if `y < 0` (see explanation above). * if `x < 0`, we return `'X23'[y<=>0]`. [Answer] # JavaScript, 44 bytes ``` (x,y)=>x?y?x>0?y>0?1:4:y>0?2:3:'X':y?'Y':'O' ``` ``` f=(x,y)=>x? y? x>0? y>0?1 :4 :y>0?2:3 :'X' :y?'Y':'O' document.body.innerHTML = '<pre>' + 'f(1,-2) -> ' + f(1,-2) + '<br>' + 'f(30,56) -> ' + f(30,56) + '<br>' + 'f(-2,1) -> ' + f(-2,1) + '<br>' + 'f(-89,-729) -> ' + f(-89,-729) + '<br>' + 'f(-89,0) -> ' + f(-89,0) + '<br>' + 'f(0,400) -> ' + f(0,400) + '<br>' + 'f(0,0) -> ' + f(0,0) + '<br>' + 'f(0,1) -> ' + f(0,1) + '<br>' + 'f(0,-1) -> ' + f(0,-1) + '<br>' + 'f(1,0) -> ' + f(1,0) + '<br>' + 'f(-1,0) -> ' + f(-1,0) + '<br>' + 'f(1,1) -> ' + f(1,1) + '<br>' + 'f(1,-1) -> ' + f(1,-1) + '<br>' + 'f(-1,1) -> ' + f(-1,1) + '<br>' + 'f(-1,-1) -> ' + f(-1,-1) + '<br>' + '</pre>'; ``` [Answer] ## ES6, 43 bytes ``` (x,y)=>"OYYX32X41"[3*!!x+3*(x>0)+!!y+(y>0)] ``` A whole byte shorter than all of those ternaries! [Answer] # Japt, ~~30~~ 22 bytes ``` "3Y2XOX4Y1"g4+3*Ug +Vg ``` Inspired by @Dennis' Jelly answer before he added an explanation. [Test it online!](http://ethproductions.github.io/japt?v=master&code=IjNZMlhPWDRZMSJnNCszKlVnICtWZw==&input=MSwgMQ==) Fun fact: this would be two bytes shorter if I had added support for negative numbers in the `g` function for strings. Another attempt, closer to the Jelly one (23 bytes): ``` "3Y2XOX4Y1"gNmg m+1 ¬n3 ``` Sadly, incrementing a list costs 4 bytes... [Answer] # [MATL](https://esolangs.org/wiki/MATL), 22 bytes ``` '3X2YOY4X1'iZSQI1h*sQ) ``` This uses [current release (10.2.1)](https://github.com/lmendo/MATL/releases/tag/10.2.1) of the language/compiler. [**Try it online!**](http://matl.tryitonline.net/#code=JzNYMllPWTRYMSdpWlNRSTFoKnNRKQ&input=Wy04OSwgMF0) ### Explanation This shamelessly borrows the great approach in [Dennis' answer](https://codegolf.stackexchange.com/a/70485/36398). ``` '3X2YOY4X1' % literal string. Will be indexed into to produce result i % input array of two numbers ZS % sign of each number in that array. Gives -1, 0 or 1 Q % add 1 to produce 0, 1 or 2 I1h % array [3 1] *s % multiply both arrays element-wise and compute sum Q % add 1. Gives a value from 1 to 9 ) % index into string. Display ``` [Answer] # Pyth, 18 bytes ``` @"OY4X13X2Y"i._RQ3 ``` Explanation: ``` - Autoassign Q = eval(input()) ._RQ - map(cmp, Q) i 3 - convert to base 3 @"OY4X13X2Y" - "OY4X13X2Y"[^] (A lookup table) ``` [Try it here.](http://pyth.herokuapp.com/?code=%40%22OY4X13X2Y%22i._RQ3&input=%28-89%2C-729%29&test_suite_input=%281%2C-2%29+%0A%2830%2C56%29%0A%28-2%2C1%29+%0A%28-89%2C-729%29%0A%28-89%2C0%29+%0A%280%2C400%29+%0A%280%2C0%29%0A%280%2C1%29%0A%280%2C-1%29%0A%281%2C0%29%0A%28-1%2C0%29+%0A%281%2C1%29%0A%281%2C-1%29+%0A%28-1%2C1%29+%0A%28-1%2C-1%29+&debug=0) [Or the whole test suite](http://pyth.herokuapp.com/?code=%40%22OY4X13X2Y%22i._RQ3&input=%28-89%2C-729%29&test_suite=1&test_suite_input=%281%2C-2%29+%0A%2830%2C56%29%0A%28-2%2C1%29+%0A%28-89%2C-729%29%0A%28-89%2C0%29+%0A%280%2C400%29+%0A%280%2C0%29%0A%280%2C1%29%0A%280%2C-1%29%0A%281%2C0%29%0A%28-1%2C0%29+%0A%281%2C1%29%0A%281%2C-1%29+%0A%28-1%2C1%29+%0A%28-1%2C-1%29+&debug=0) [Answer] ## Python 2, 75 bytes ``` lambda x,y,b=bool:[['OX','YO'][b(y)][b(x)],[[1,2],[4,3]][y<0][x<0]][b(x*y)] ``` Pretty straightforward. [Answer] # Mathematica 81 bytes ``` Switch[Sign@#,{1,-1},4,{1,1},1,{-1,1},2,{-1,-1},3,{0,0},"O",{_,0},"X",{0,_},"Y"]& ``` --- ``` %/@{{1, -2}, {30, 56}, {-2, 1}, {-89, -729}, {-89, -0}, {0, 400}, {0, 0},{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}} ``` > > {4, 1, 2, 3, "X", "Y", "O", "Y", "Y", "X", "X", 1, 4, 2, 3} > > > [Answer] # [Retina](https://github.com/mbuettner/retina), 52 This is a simple substitution-based method: ``` ^0 0 O ^0.* Y .* 0 X -.*-.* 3 ^-.* 2 .*-.* 4 .* .* 1 ``` [Try it online](http://retina.tryitonline.net/#code=bWBeMCAwCk8KbWBeMC4qClkKbWAuKiAwClgKLS4qLS4qCjMKbWBeLS4qCjIKLiotLioKNAouKiAuKgox&input=MSAtMgozMCA1NgotMiAxCi04OSAtNzI5Ci04OSAwCjAgNDAwCjAgMAowIDEKMCAtMQoxIDAKLTEgMAoxIDEKMSAtMQotMSAxCi0xIC0x). The extra `m`` at the start of some lines is only needed to test multiple inputs in one go, so are not counted in the score. --- Previously I tried [this more interesting approach](http://retina.tryitonline.net/#code=WzEtOV1cZCoKMQotMQoyCiguKSAoLikKJDEkKjMkMiQqMQozCjExMQptYF4oLikqJAokIzEKVGBkYE9ZWVgxNFgyMw&input=MSAtMgozMCA1NgotMiAxCi04OSAtNzI5Ci04OSAwCjAgNDAwCjAgMAowIDEKMCAtMQoxIDAKLTEgMAoxIDEKMSAtMQotMSAxCi0xIC0x), but its quite a bit longer (about 65 without the `m` modifiers): ``` [1-9]\d* 1 -1 2 (.) (.) $1$*3$2$*1 3 111 m`^(.)*$ $#1 T`d`OYYX14X23 ``` * substitute all non-zero numbers to `1`, leaving `-` signs in place * Substitute `-1` with `2` * Convert 1st and 2nd numbers unary with `3` and `1` respectively as the unary digits . This effectively gives 2 base3 digits, expressed in unary * Convert to `3`s to `111`. This effectively gives the a single unary number that corresponds to each of the quadrants, axes and origin * Convert the unary to one decimal digit * Transpose the decimal digit to the appropriate output char. [Answer] # Octave, 34 bytes ``` @(p)['3X2YOY4X1'](sign(p)*[3;1]+5) ``` The old base-3 trick through vector multiplication (although I had to add 5 to account for 1-based array indices) plus some Octave indexing magic. Input is a vector of the form `[1, -2]` (with or without the comma), so when assigned to a variable `w`: ``` >> w([1 -2]) ans = 4 ``` Here it is on [ideone](http://ideone.com/oYfMNO). [Answer] # Pyth, 24 Too long, but perhaps an interesting approach: ``` ?Q?sQ?eQh%/yPQ.n04\X\Y\O ``` The input must be specified as a complex number, e.g. `1-2j`. Basically a nested ternary to test: * if input is zero - output `O` * else if real part is zero - output `Y` * else if imaginary part is zero - output `X` * else calculate the complex phase, multiply by 2, integer divide by π, then mod and add to give the appropriate quadrant number. [Try it online.](https://pyth.herokuapp.com/?code=%3FQ%3FsQ%3FeQh%25%2FyPQ.n04%5CX%5CY%5CO&test_suite=1&test_suite_input=1-2j%0A30%2B56j%0A-2%2B1j%0A-89-729j%0A-89%2B0j%0A0%2B400j%0A0%2B0j%0A0%2B1j%0A0-1j%0A1%2B0j%0A-1%2B0j%0A1%2B1j%0A1-1j%0A-1%2B1j%0A-1%2B-1j&debug=0) [Answer] # Java 8, 64 bytes this is a lambda expression for a `BiFunction<Integer,Integer,String>`. ``` (x,y)->"OYYX14X23".charAt(3*(x>0?1:x<0?2:0)+(y>0?1:y<0?2:0))+""; ``` 3 bytes could be saved by returning a `Character` instead of a `String` but i'm not completely sure if autoboxing will play nicely with the lambda. ]
[Question] [ Given the following input: * An integer `n` where `n > 0`. * A string `s` where `s` is not empty and `s~=[0-9A-Z]+` (alpha-numeric capitals only). Using a standard, simplified QWERTY keyboard (as shown below): ``` 1234567890 QWERTYUIOP ASDFGHJKL ZXCVBNM ``` Perform the following operation: * Find the original row that each character is in on the keyboard. * Replace the letter with the correct shifted equivalent for `n` based on its original position + n. + E.G. `s="AB"` and `n=2`: `A` would become `D` and `B` would become `M`. * If `keyboard_row[position + n] > keyboard_row.length`, wrap back to the start. + E.G. `s="0P"` and `n=2`: `0` would become `2` and `P` would become `W`. # Examples: ``` f("0PLM",1) = 1QAZ f("ZXCVB",2) = CVBNM f("HELLO",3) = LYDDW f("0PLM",11) = 1QSV f("0PLM",2130) = 0PHX ``` # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins. --- *This is slightly more difficult than it seems at first glance.* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` ØQØDṭ,ṙ€¥⁸F€y ``` [Try it online!](https://tio.run/##y0rNyan8///wjMDDM1we7lyr83DnzEdNaw4tfdS4ww3IqPx/eLmRfuT//4Y6CkoGAT6@SjoKRkBmVIRzmBOQbQxke7j6@PgD2YbIagyNDWA8AA "Jelly – Try It Online") ### How it works ``` ØQØDṭ,ṙ€¥⁸F€y Main link. Left argument: n (integer). Right argument: s (string) ØQ Qwerty; set the return value to ["QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"]. ØD Digits; yield "0123456789". ṭ Tack, yielding ["QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM", "0123456789"]. ¥⁸ Call the two links to the left as a dyadic chain, with right argument n. ṙ€ Rotate each string in the array n units to the left. , Yield the pair of the unmodified and the rotated string array. F€ Flatten each, mapping, e.g., ["QWERTYUIOP", ..., "0123456789"] to "QWERTYUIOPASDFGHJKLZXCVBNM0123456789". y Translate s according to the mapping we've built. ``` [Answer] # [Python 2](https://docs.python.org/2/), 110 bytes ``` lambda s,n,y='1234567890'*99+'QWERTYUIOP'*99+'ASDFGHJKL'*99+'ZXCVBNM'*99:''.join(y[y.find(c)+n%630]for c in s) ``` [Try it online!](https://tio.run/##TY9Lb8IwEITv/Apfqk3KFuXRAkFyJWgoaTHl1fIKOVAgahB1UGwO@fVpHPfAbecbze7sJZc/KXeKmG6L8@73@7AjAjnmFGzHfXxqttqeBfeeV4fpsj/7XH@9jSdad@f@6yB4HzItN6uXRe9jpEQHoHFKE27kYd6IE34w9mad3zVdK4rTjOxJwokwC3kUUtCwFoI1YSNAG8GedjcQYYmqdYAOgl5bwaDP2BjQRWBr319q@B@u0vPFLXNs18JyDlaKRjV1XD2XHcX1LFWLqkLnkiVcktgoPZNS7SIJSxkhPDwDaqv4Aw "Python 2 – Try It Online") This uses a big enough string (99 copies of each row) and the LCM between the rows lengths (630) to find the correct substitution avoiding individual correction between each row. [Answer] # Java 8, ~~159~~ 158 bytes ``` n->s->{for(int i=s.length,j;i-->0;)for(String x:"1234567890;QWERTYUIOP;ASDFGHJKL;ZXCVBNM".split(";"))if((j=x.indexOf(s[i])+n)>=n)s[i]=x.charAt(j%x.length());} ``` -1 byte thanks to *@OlivierGrégoire* modifying the input-array instead of printing directly. **Explanation:** [Try it online.](https://tio.run/##bVHbTsJAEH33KzZNTHZjuwHxvtIEEa9FULwTHtaywGKZNt2tlhi@vW5xE8WQzMPkzJmZM2em/IN7cSJgOnwvwogrhdpcwtcGQkpzLUM0NQyaaRnRUQahljHQM5scX4IWY5G660jNGFQ2E@lxOOFpf@D7KER1VIDnK8//GsUplqCRrCsaCRjricuZ9Dy/wkhZ6@lUwhjlR051u7azu7d/cFhht0@tu/uXh8tOlzV6p2fnF1fXAXt9bj6e3LQdqpJIauwwhxA5wpjXcyphKPLOCKu@HJAtIH4dSJmbUqmqoTHfzO1@TAhbFMwcbiLJ3iJzu7XgI5ZDNDO2WFn9ASelQwhpoTTedp3GiUPYClLpriDVEgna/1lL8StgzXUuWkHQWe1e216tVf7Ci43fpy0VL1mlyeAi66eyun9@grj5iKI6bpZmpCmfY7sgpDxJojkGQnkYisQYZSu9udJiRuNM08SM1BFgEJ92vmFZKYviGw) ``` n->s->{ // Method with integer and character-array parameters, and no return-type for(int i=s.length,j;i-->0;) // Loop over the input character-array with index for(String x:"1234567890;QWERTYUIOP;ASDFGHJKL;ZXCVBNM".split(";")) // Inner loop over the qwerty-lines if((j=x.indexOf(s[i])+n)>=n) // If the current qwerty-line contains the character // Set `j` to the index of this character on that line + input `n` s[i]=x.charAt(j%x.length());} // Replace the character at index `i` // with the new character (at index `j` modulo length_of_qwerty_line) ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 49 bytes ``` "$&"+T`9o`dQW\ERTYUI\OPQASDFG\HJK\LAZXC\VBNMZ 0A` ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0lFTUk7JMEyPyElMDzGNSgkMtQzxj8g0DHYxc09xsPLO8bHMSrCOSbMyc83isvAMeH/f2MuD1cfH38A "Retina – Try It Online") Takes input `n` and `s` on separate lines. Explanation: ``` "$&"+ ``` Repeat `n` times. ``` T`9o`dQW\ERTYUI\OPQASDFG\HJK\LAZXC\VBNMZ ``` Shift all the characters one key to the right. ``` 0A` ``` Delete `n`. [Answer] # JavaScript (ES6), ~~101~~ 99 bytes Takes input in currying syntax `(s)(n)`. Works with arrays of characters. ``` s=>n=>s.map(c=>(S='1QAZ2WSX3EDC4RFV5TGB6YHN7UJM8IK_9OL_0P')[(p=S.search(c)+n*4)%(-~'9986'[p%4]*4)]) ``` ### Test cases ``` let f = s=>n=>s.map(c=>(S='1QAZ2WSX3EDC4RFV5TGB6YHN7UJM8IK_9OL_0P')[(p=S.search(c)+n*4)%(-~'9986'[p%4]*4)]) console.log(JSON.stringify(f([..."0PLM"])(1))) // 1QAZ console.log(JSON.stringify(f([..."ZXCVB"])(2))) // CVBNM console.log(JSON.stringify(f([..."HELLO"])(3))) // LYDDW console.log(JSON.stringify(f([..."0PLM"])(11))) // 1QSV console.log(JSON.stringify(f([..."0PLM"])(2130))) // 0PHX ``` ### How? We look for the position **p** of each character of the input within a string **S** where the keyboard rows are interleaved: the first 4 characters are **'1QAZ'** (first column of the keyboard), the next 4 characters are **'2WSX'** (second column of the keyboard) and so on. Unused positions are padded with underscores and the last ones are simply discarded. ``` col # | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ------+------+------+------+------+------+------+------+------+------+--- row # | 0123 | 0123 | 0123 | 0123 | 0123 | 0123 | 0123 | 0123 | 0123 | 01 ------+------+------+------+------+------+------+------+------+------+--- char. | 1QAZ | 2WSX | 3EDC | 4RFV | 5TGB | 6YHN | 7UJM | 8IK_ | 9OL_ | 0P ``` This allows us to easily identify the row with **p mod 4** and eliminates the need for explicit separators between the rows. We advance by **4n** positions, apply the correct modulo for this row (40, 40, 36 and 28 respectively) and pick the replacement character found at this new position in **S**. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` ØQØDṭẋ€‘}Ẏ©iЀ⁸+ị® ``` [Try it online!](https://tio.run/##y0rNyan8///wjMDDM1we7lz7cFf3o6Y1jxpm1D7c1XdoZebhCSBu4w7th7u7D637//@/kkGAj6/Sf0MA "Jelly – Try It Online") [Answer] # C, ~~152~~ 149 bytes *Thanks to @gastropner for saving three bytes!* ``` j,l;f(S,n){for(char*s=S,*k;*s;++s)for(k="1234567890\0QWERTYUIOP\0ASDFGHJKL\0ZXCVBNM\0";l=strlen(k);k+=l+1)for(j=l;j--;)k[j]-*s||putchar(k[(j+n)%l]);} ``` [Try it online!](https://tio.run/##dY1dT8IwGIXv@RWkiUnftUvaTUTzphd@oChD0PnNuCCLU9pazDqvgN8@B5E7PJfPk3NOHn7keV1rbrGgKXewLBYlzT9nZeBVygODgUfGPGywUURG8WHnqHt8IjJx99y7f3h9vB6NM3GaXlxe9W8GSSbeXs6fzm6HmSBola9K@@6oATRMWSa3O1pZ1GGIYCZ6GgZ@tfr@qTaf1EyoZg4O7BRwXc9d1f6azR2F1rLVblJQIsbJkHAJ2FQ8JQRwZ7a/hEd7VL@XJCPC4z3qb0/@qyIZi4at618) **Unrolled:** ``` j,l; f(S,n) { for (char*s=S, *k; *s; ++s) for (k="1234567890\0QWERTYUIOP\0ASDFGHJKL\0ZXCVBNM\0"; l=strlen(k); k+=l+1) for (j=l; j--;) k[j]-*s || putchar(k[(j+n)%l]); } ``` [Answer] # [Red](http://www.red-lang.org), 152 bytes ``` f: func[s n][foreach c s[foreach[t l]["1234567890"10"QWERTYUIOP"10"ASDFGHJKL"9"ZXCVBNM"7][if p: find t c[if(i:(index? p)+ n // l)= 0[i: l]prin t/(i)]]]] ``` [Try it online!](https://tio.run/##dY1NT8JAGITv/IrJe2rjobutCm1CDGoFtQjyIehmD6bdDZs0a1Nq4N@XxcCJOKd58iQztSramSogZKsT6F@biy2sFPqnVt/5Bjm25y4alFIQD6Prm9tuL2bEGb2v0tnic/k8mR5pMH98Go5eXjOK6Wv98HH/NqauFEajcuPGFmiQO/RM4jlS@ztU/hUsggCl3wcTJnEnVW0smsAzvnRpNYhNszGBd46mgVW70ljVceLvhRBemlGaZRNCBFy60xz/z4Q8Yu0B "Red – Try It Online") Ungolfed: ``` f: func [s n][1 foreach c s [ foreach [t l] ["1234567890"10"QWERTYUIOP"10"ASDFGHJKL"9"ZXCVBNM"7][ p: find t c if p [ i: (index? p) + n // l if i = 0 [i: l] prin t/(i) ]]]] ``` [Answer] # [Haskell](https://www.haskell.org/), 99 bytes ``` f(s,n)=[dropWhile(/=c)(cycle r)!!n|c<-s,r<-words"1234567890 QWERTYUIOP ASDFGHJKL ZXCVBNM",elem c r] ``` [Try it online!](https://tio.run/##DcnbCoIwAADQX5k@bTDJaVfQh@43K7taiQ8yJ0pzyhZE4L@vzuspUvVinGudQ4UF8uNM1k1UlJzBjk8RpF/KGZDIMERLPUth6VmfWmbKJI7b7fUHw5ENjtH8dHlc14cQjM@zxXK12QbgeZ/eJvudiRlnFaBAJrpKS@E3shTvOIemHQb/FagVnhUTTAh2iGsnif4B "Haskell – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 94 + 1 (`-p`) = 95 bytes ``` $s=<>;for$i(1234567890,QWERTYUIOP,ASDFGHJKL,ZXCVBNM){eval"y/$i/".(substr$i,$s%length$i)."$i/"} ``` [Try it online!](https://tio.run/##K0gtyjH9/1@l2NbGzjotv0glU8PQyNjE1MzcwtJAJzDcNSgkMtTTP0DHMdjFzd3Dy9tHJyrCOczJz1ezOrUsMUepUl8lU19JT6O4NKm4BKhdR6VYNSc1L70kQyVTU08JJFn7/79BgI8vl5GhscG//IKSzPy84v@6vqZ6BoYG/3ULAA "Perl 5 – Try It Online") [Answer] # Japt, 20 bytes Running out the door to dinner so more golfing and an explanation to follow. ``` ;£=D·i9òs)æøX)gV+UbX ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=O6M9RLdpOfJzKeb4WClnVitVYlg=&input=IjBQTE0iLDIxMzA=) [Answer] # Perl, ~~59~~ ~~58~~ ~~57~~ 56 bytes Includes `+` for `-p` Give input on STDIN as 2 lines, first the string, then the repeat ``` (echo 0PLM; echo 2130) | perl -pe '$a="OPQWERTYUILASDF-MZXCVBNM0-90";eval"y/HI$a/J$a/;"x<>' ``` [Answer] # [Perl 5](https://www.perl.org/), 85 bytes **84 bytes code + 1 for `-p`.** ``` eval join"",map"y/$_/@{[/./&&$'.$&]}/;",(1234567890,QWERTYUIOP,ASDFGHJKL,ZXCVBNM)x<> ``` [Try it online!](https://tio.run/##K0gtyjH9/z@1LDFHISs/M09JSSc3sUCpUl8lXt@hOlpfT19NTUVdT0UttlbfWklHw9DI2MTUzNzC0kAnMNw1KCQy1NM/QMcx2MXN3cPL20cnKsI5zMnPV7PCxu7/f4MAH18uQy6wGJcRl4erj48/lzEXRNgQQhsZGhtw/csvKMnMzyv@r1sAAA "Perl 5 – Try It Online") [Answer] # [Clean](https://clean.cs.ru.nl), ~~144~~ 119 bytes ``` import StdEnv ``` # ``` \n s=[l.[(i+n)rem(size l)]\\c<-s,l<-["1234567890","QWERTYUIOP","ASDFGHJKL","ZXCVBNM"],i<-[0..]&j<-:l|j==c] ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r@x/cEliUQmXskKagq1CTJ5CsW10jl60RqZ2nmZRaq5GcWZVqkKOZmxMTLKNbrFOjo1utJKhkbGJqZm5haWBko5SYLhrUEhkqKd/AJDjGOzi5u7h5e0DZEdFOIc5@fkqxepkAjUZ6OnFqmXZ6Frl1GTZ2ibHctkCLTRWiFb3cPXx8VeP/f8vOS0nMb34v66nz3@XyrzE3MxkCAfoTJ/MJAA "Clean – Try It Online") Lambda function with the signature `Int ![Char] -> [Char]` [Answer] # [Ruby](https://www.ruby-lang.org/), 101 bytes ``` ->s,n{n.times{s.tr! '1234567890QWERTYUIOPASDFGHJKLZXCVBNM','2345678901WERTYUIOPQSDFGHJKLAXCVBNMZ'};s} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165YJ686T68kMze1uLpYr6RIUUHd0MjYxNTM3MLSIDDcNSgkMtTTP8Ax2MXN3cPL2ycqwjnMyc9XXUcdrsoQrioQpsoRoipKvda6uPZ/NJeCQrSSQYCPr5KOYawOmAc2R0nHCMr1cPXx8VfSMYZyoWoNUbhGhsYGsVyxeqmJyRkKKfkKNcU6CkU1QAUFpSXFCml6yYk5OQogMa7UvJT/AA "Ruby – Try It Online") I'm honestly a little disappointed that I couldn't do better with 'cleverer' methods. The closest I got was along the lines of ``` a=%w{1234567890 QWERTYUIOP ASDFGHJKL ZXCVBNM} b=a.map{|r|r[1..-1]<<r[0]}*'' a*='' n.times{s.tr! a,b} ``` for a net gain of 7 characters. ]
[Question] [ Inspired by [this Math.SE question](https://math.stackexchange.com/questions/2560570/do-fibonacci-numbers-reach-every-number-modulo-m). # Background The [Fibonacci Sequence](https://en.wikipedia.org/wiki/Fibonacci_number) (called `F`) is the sequence, starting `0, 1` such that each number (`F(n)`) (after the first two) is the sum of the two before it (`F(n) = F(n-1) + F(n-2)`). A Fibonacci Sequence [mod](https://en.wikipedia.org/wiki/Modular_arithmetic) K (called `M`) is the sequence of the Fibonacci numbers mod K (`M(n) = F(n) % K`). It can be shown that the Fibonacci Sequence mod K is cyclic for all K, as each value is determined by the previous pair, and there are only K2 possible pairs of non-negative integers both less than K. Because the Fibonacci sequence mod K is cyclic after its first repeated pair of terms, a number which doesn't appear in the Fibonacci Sequence mod K before the first repeated pair of terms will never appear. For K = 4 ``` 0 1 1 2 3 1 **0 1** ... ``` For K = 8 ``` 0 1 1 2 3 5 0 5 5 2 7 1 **0 1** ... ``` Notice that for K = 8, 4 and 6 do not appear before the repeated `0 1`, so 4 and 6 will never appear in the Fibonacci Sequence mod 8. # Challenge Given an integer K strictly greater than 0, output all of the non-negative integers less than K that *do not* appear in the Fibonacci Sequence mod K. # Rules * [Default loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). * [Default I/O](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * [Programs or functions are acceptable](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet). * You can assume that *K* will fit in your native integer type ([within reason](https://codegolf.meta.stackexchange.com/a/8245/44694)). * If there are non-negative numbers less than K that do not appear in the Fibonacci Sequence mod K, your program/function should output all such numbers in any reasonable manner. * If there are no non-negative integers less than K that do not appear in the Fibonacci Sequence mod K, your program/function may indicate this by returning an empty list, printing nothing, producing an error, etc. * Order does not matter. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in each language wins. # Test Cases [Generate test cases online!](https://tio.run/##bU/RDoIwDHyGr2hMSIaiGWh8MNEfWRaCbkgBuzlHjF@P4wlMfGiTu17vWvvxjaFiHJWuocbr1VB1u2H5MKrsSm9Cez2HymnFuvQUR@8Gew3d@giXM/Sa2LwzjaMZ7iprNamFQGxzuVnCQqZx5LQfHIHApIPaOEBAWlwiTiFMynhm4AyCZ3mggrqd1Eh28GzKtw7Jwyop1Cpps2A6W7qK7pq1KWAdCDL@N@ffx20qx1HknGdFqH2oA@fyCw "Python 2 – Try It Online") ## Non-Empty Test Cases ``` 8 [4, 6] 11 [4, 6, 7, 9] 12 [6] 13 [4, 6, 7, 9] 16 [4, 6, 10, 12, 14] 17 [6, 7, 10, 11] 18 [4, 6, 7, 9, 11, 12, 14] 19 [4, 6, 7, 9, 10, 12, 14] 21 [4, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 19] 22 [4, 6, 7, 9, 15, 17, 18, 20] 23 [4, 7, 16, 19] 24 [4, 6, 9, 11, 12, 14, 15, 18, 19, 20, 22] 26 [4, 6, 7, 9, 17, 19, 20, 22] 28 [10, 12, 14, 16, 18, 19, 23] 29 [4, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 27] 31 [4, 6, 9, 12, 14, 15, 17, 18, 19, 22, 25, 29] 32 [4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30] 33 [4, 6, 7, 9, 15, 17, 18, 20, 24, 26, 27, 28, 29, 31] 34 [4, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 27, 28, 30] 36 [4, 6, 7, 9, 10, 11, 12, 14, 16, 18, 20, 22, 23, 24, 25, 26, 27, 29, 30, 31, 32] 37 [9, 10, 14, 17, 20, 23, 27, 28] 38 [4, 6, 7, 9, 10, 11, 12, 14, 15, 16, 18, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 31, 32, 33, 36] 39 [4, 6, 7, 9, 15, 17, 19, 20, 22, 24, 30, 32, 33, 35] ... 200 [4, 6, 12, 14, 20, 22, 28, 30, 36, 38, 44, 46, 52, 54, 60, 62, 68, 70, 76, 78, 84, 86, 92, 94, 100, 102, 108, 110, 116, 118, 124, 126, 132, 134, 140, 142, 148, 150, 156, 158, 164, 166, 172, 174, 180, 182, 188, 190, 196, 198] ... 300 [6, 18, 30, 42, 54, 66, 78, 90, 102, 114, 126, 138, 150, 162, 174, 186, 198, 210, 222, 234, 246, 258, 270, 282, 294] ... 400 [4, 6, 10, 12, 14, 20, 22, 26, 28, 30, 36, 38, 42, 44, 46, 52, 54, 58, 60, 62, 68, 70, 74, 76, 78, 84, 86, 90, 92, 94, 100, 102, 106, 108, 110, 116, 118, 122, 124, 126, 132, 134, 138, 140, 142, 148, 150, 154, 156, 158, 164, 166, 170, 172, 174, 180, 182, 186, 188, 190, 196, 198, 202, 204, 206, 212, 214, 218, 220, 222, 228, 230, 234, 236, 238, 244, 246, 250, 252, 254, 260, 262, 266, 268, 270, 276, 278, 282, 284, 286, 292, 294, 298, 300, 302, 308, 310, 314, 316, 318, 324, 326, 330, 332, 334, 340, 342, 346, 348, 350, 356, 358, 362, 364, 366, 372, 374, 378, 380, 382, 388, 390, 394, 396, 398] ... ``` ## Empty Test Cases (no output, error, empty list, etc. is acceptable output) ``` 1, 2, 3, 4, 5, 6, 7, 9, 10, 14, 15, 20, 25, 27, 30, 35 ... 100 ... ``` ### Related: [Counting Fibonacci Orbits](https://codegolf.stackexchange.com/q/147200/) [Find the Pisano Period](https://codegolf.stackexchange.com/questions/8765/find-the-pisano-period) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` ²RÆḞ%ḟ@Ḷ ``` [Try it online!](https://tio.run/##ARsA5P9qZWxsef//wrJSw4bhuJ4l4bifQOG4tv///zg) Based on the pisano period `p(n) <= 6n` from [A001175](https://oeis.org/A001175). Also, `p(n) <= 6n <= n^2` for `n >= 6` and `p(n) <= n^2` for `n < 6`. Saved this byte thanks to Dennis. [Answer] # [Haskell](https://www.haskell.org/), 70 bytes *Some amount of bytes saved thanks to Esolanging Fruit* *8 bytes saved thanks to Laikoni* ``` a=1:scanl(+)1a f x=[u|u<-[2..x-1],and[mod b x/=u|(_,b)<-zip[1..x^2]a]] ``` [Try it online!](https://tio.run/##DcpBDoMgEADAe1/BEVKhWY9EHtA3EGzWipWIq1FJiPHv2DnPiPvkYywFDej9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lDoyBt13bIV134GpXRbh9miwEh/wfivpteyTgJ27OLicj3RXfzdCNNi4C5ZLZ7FsDyLmyzWS4GHCnx4g6Nba@SQgy7EPoOsX/q8yuGvuHpHatlG6iRmXu7jzHETpGfGS774fUxVOzOXyyv6zmsUo2MEEAP@xDuGOU72DdTRg79U1gcubxu9AzUdT21WlqQzIXwjbiccy2mMcJ2xKEsM3y2LIt5XEKATzO2JbhZLEtj@UFiQ9kj1BmzQAbStVQplGjhjZNmMbCVPTAJcE0gUuCqZWOyRmASyrnEC4ZppmgxDSXq5rVhRIKdaRRVdxU4VTnrUi9EtRublcb1UkZjxZO0ixQAxoDfQYwDLSYPK43jzuUoy2k7RbaZpM4sm9Qj7eQj7bTt7taYHb0QQBsbUa8qyPRrrbYbb0BAwCIhAYwgI0ROHIhTQtZjj9FDW5wMtBn4hV9@XmWt5a8XjC1whdW2/YmlRuVNV0CNgN9Jq@bhg9pB/oBfQRqpOX24yIBHclJknsFaiTNq68X1kCNQI0gjYCOEvnLgCmoEaQR0BH0EagRqBGkEdAR9BGoEagRpBHQkTvWvwA "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 ^$_ # Range upto and excluding the input ∖ # set minus (U+2216) ( # generate the Fibonacci sequence mod k 1, 1, # seed the sequece (can't be 0,1) ( * + * ) % $_ # add two values and modulus the input (lambda) ... # keep doing that until # it matches 0,1 !* # negate the first param (1 when 0) & # and Junction * # second param == 1 # both match 1 ) } ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 48 bytes ``` 01\ ?!\:&+{:}%:1$0p&$: v0\~:1=? >?!;1-::0g?!nao: ``` [Try it online!](https://tio.run/##S8sszvj/38AwhsteMcZKTbvaqlbVylDFoEBNxYqrzCCmzsrQ1p7Lzl7R2lDXysog3V4xLzHf6v///7plxuYA "><> – Try It Online") Takes input through the -v flag. Prints a lot of excess newlines, but gets the job done. This basically uses the first line to store the set of numbers that have appeared so far in the sequence. ### How It Works: ``` 01\ Input is already on the stack ...... Initialises the sequence with 1 and 0 ...... Goes to the second line ...... ...... ..\:&+{:}% Gets the next number in the modded Fibonacci sequence while preserving the previous number ...... ...... ...... ..........:1$0p&$: Puts a 1 at that cell number on the first line ....... ....... ...... If the number is a 0 go to the third line ?!\..............: Check if the next number is a 1, meaning we've reached the end of the sequence v0\~:1=? Go to the fourth line if so >..... Re-add the 0 and go back to the second line if not ...... While input: ...... Get the cell from the first line ...... If not 0: print the number >?!;1-::0g?!nao: Finally, print a newline and decrement the input ``` [Answer] # [Python 2](https://docs.python.org/2/), 69 bytes ``` m=input();r=set(range(m)) a=b=1 exec"a,b=b,a+b;r-={a%m};"*m*6 print r ``` [Try it online!](https://tio.run/##HcxLCsMgEADQ/ZwiCAW1KTgGQkDmMJoObRYamVpoKT27/ewfrz7bdS@@r/uZSSnVM22l3ps2QejGTUssF9bZGIiUCIEfvKo4JkpjPKYgJ3rFQ34HZbOdocpW2iD9O/3l8Hvt0hEWQAT0gBPgDN45mJz7AA "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~19~~ 18 bytes ``` 0lbU:"yy+]vG\G:qX~ ``` [Try it online!](https://tio.run/##y00syfn/3yAnKdRKqbJSO7bMPcbdqjCi7v9/QwA "MATL – Try It Online") -1 byte thanks to Guiseppe. ``` bU:" ] % Do K^2 (>6K) times. 0l yy+ % Fibbonaci X~ % Set exclusive difference between vG\ % the fibonacci numbers mod K G:q % and 0...K-1 ``` [Answer] # [Python 3](https://docs.python.org/3/), 91 bytes ``` lambda n:{*range(n)}-{*f(n*n,n)} f=lambda c,m,l=[1,0]:f(c-1,m,[(l[0]+l[1])%m]+l)if c else l ``` [Try it online!](https://tio.run/##LYxBCsMgEADvecVeCmoNKLkJvsR6sFbtgm6CzaWEvt0G2tsMDLO99@dKyyj2Nmpo90cAMofogUpixD/zITIjQfLkKdt/EmWT1TotlTeZxVmf7lh1yl@r055f2gkcM0RI9ZWgjrx2QECC33lR3EywdaSdoQRRGHI@vg "Python 3 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~13 12~~ 10 bytes Thanks @Zgarb for -2 bytes! ``` -U2m%⁰İfŀ⁰ ``` Prints an empty list in case all integers appear, [try it online!](https://tio.run/##yygtzv7/XzfUKFf1UeOGIxvSjjYA6f///xsZGAAA "Husk – Try It Online") ### Explanation ``` -U2m%⁰İfŀ⁰ -- named argument ⁰, example with: 8 - -- difference of ŀ⁰ -- | lowered range: [0,1,2,3,4,5,6,7] -- and İf -- | Fibonacci sequence: [1,1,2,3,5,8,13,21,34,55,89,144,233,377… m%⁰ -- | map (modulo ⁰): [1,1,2,3,5,0,5,5,2,7,1,0,1,1… U2 -- | keep longest prefix until 2 adjacent elements repeats: [1,1,2,3,5,0,5,5,2,7,1,0,1] -- : [4,6] ``` [Answer] # [Python 3](https://docs.python.org/3/), 78 bytes ``` def m(K):M=0,1;exec(K*6*'M+=sum(M[-2:])%max(K,2),;'+'print({*range(K)}-{*M})') ``` [Try it online!](https://tio.run/##FctLCoAgFADAq7QJ3zMD@9Ci6ATiCaJFlH0WmpRBEZ3daj2Mvdy8msz7QY2BBoGlrDlLKnWqHgQtKJFRvR8aZBOnZYuh7k4QLEVWkYjYbTEObrp1ZlJffuKbygcJeg2/LMYeDhDR55y/ "Python 3 – Try It Online") Prints a set, so the output for empty test cases is `set()`, which is the empty set. [Answer] # R, ~~92~~ 86 bytes Thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312) for saving 6 bytes! ``` function(k,n=!!0:2){while(any((z=tail(n,2))-n[1:2]))n=c(n,sum(z)%%k);setdiff(1:k-1,n)} ``` [Try it online!](https://tio.run/##FchBCoMwEEbhvbdwIcwPEUzoogZykuJC1MEQnUKNFBXPHnXz8Xi/xC7xKl30X6GgxOV5ZQ2O/@ingVrZiHYXWz@RKAOU8tHWNIC47j7LOtMOFEXIliH2npm0DaVWgjPdjYzp9fB@0DXSBQ) Pretty straightforward implementation (**previous version**, but same concept): ``` function(k, K=1:k-1, #Uses default arguments to preset variables for legibility n=c(0,1,1)){ #(wouldn't change byte-count to put them in the body of the function) while(any((z=tail(n,2))!=n[1:2])) #Do as long as first 2 elements are not identical to last 2 elements n=c(n,sum(z)%%k) #Built the fibonacci mod k sequence K[!K%in%n] #Outputs integers < k if not in sequence. } ``` [Answer] # Python 3,~~173~~ ~~152~~ ~~143~~ 131 bytes ``` f=lambda n,m,a=0,b=1:a%m if n<=0else f(n-1,m,b,a+b) p=lambda n,i=2,y={0}:y^{*range(n)}if f(i,n)==1>f(i-1,n)else p(n,i+1,y|{f(i,n)}) ``` Special Thanks to @ovs. [Try It Online](https://tio.run/##VYxBCsIwEEX3niIbYcamkLQutDgeRUi00UA7htpNqD17DBWUrmYe/78f4vh4cl1el5uSo8709mYEy14aUtKSbsy2F94JPpFqu1crHHCpc26lKSxuwt/xVMlIk5qbeJl2g@F7C4xzlh14yUikz/nLNuMyFSBLhZbxPX0bM6YweB4BAlQaMc//8LjCer/Gw7qsVOb0AQ) How Does It Work? The first function takes two parameters m and n, and it returns the nth Fibonacci number mod m. The second function loops through the Fibonacci numbers mod k and checks if 0 and 1 are repeated. It stores the numbers in a list and compares it with a list containing the numbers 1-n. The duplicate numbers are removed and the remaining numbers are returned. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` L<InLÅfI%K ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fx8Yzz@dwa5qnqvf//4ZmAA "05AB1E – Try It Online") -3 bytes thanks to Emigna. [Answer] # [Ruby](https://www.ruby-lang.org/), 47 bytes ``` ->n{a=b=1;[*1...n]-(1..n*n).map{a,b=b,a+b;a%n}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtE2ydbQOlrLUE9PLy9WVwNI52nlaerlJhZUJ@ok2SbpJGonWSeq5tXW/i9QSNPTMLbU/A8A "Ruby – Try It Online") While it uses some of the same logic, this is not based off [G B's Answer](https://codegolf.stackexchange.com/a/153776/31203). ## Explanation: ``` ->n{ a=b=1; # start sequence with 1,1 [*1...n] # all the numbers from 1 to n-1 as an array # 0 is excluded as it should never be in the final answer - # set operation; get all items in the first set and not in the second (1..n*n).map{ # n squared times a,b=b,a+b; # assign next fibonacci numbers a%n # return a fibonacci number mod n } # Map to an array } ``` [Answer] # Common Lisp, 106 bytes ``` (lambda(k)(do((a 1 b)c(b 1(mod(+ a b)k)))((=(1- b)0 a)(dotimes(i k)(or(member i c)(print i))))(push a c))) ``` [Try it online!](https://tio.run/##FYxJCsQwDAS/omOLITC@5DaPkReIcBQbO/N@R7l1QVelU2dfWDjFYhZURm6AUKDICZECrGV8SJwrMwM/hM3hS/J@b7UyoeRiG7BisQxSSow@9LpJ@ZX6fx6eSL5X2Hk9) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` ʁ⁰²ɾ∆f⁰%F ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLKgeKBsMKyyb7iiIZm4oGwJUYiLCIiLCIxNiJd) ## How? ``` ʁ⁰²ɾ∆f⁰%F # (implicit input) ʁ # Exclusive zero range [0, n) ⁰² # Input squared ɾ # Inclusive one range [1, n] ∆f # Nth fibonacci number (implicit vectorization) ⁰% # Modulo with input F # Remove all values from this list in the other list ``` [Answer] # [Elixir](https://elixir-lang.org/), ~~148~~ 144 bytes ``` fn x->Enum.to_list(1..x-1)--List.flatten Enum.take_while Stream.chunk(Stream.unfold({1,1},fn{p,n}->{rem(p,x),{n,p+n}}end),2),&Enum.sum(&1)!=1end ``` [Try it online!](https://tio.run/##TY3BasMwEER/RckhSFQSUegpEN96KBR66AcYk6ycJdJaWCvq4vrbHcftIZeBNzPMQMAB@9mL0@xJDKZ6oxItd3XAzNJZOxinjPlYyPrQMAOJv0pzg/r7igHEF/fQRHu@FrrJfyjku3CRo9Nu0p7GpGky1dhDlEkPSo@k0wtNE9BF6YPSu3U0lyh3Tm1ObvHn90/bAme53SrxWz1ukFq7aHzGrkZiaKF/mN7KtYuUE5xZBozIR3FE8kjIP2u47KbCeX7d7@8 "Elixir – Try It Online") Not an especially competitive answer, but was really fun to golf! Elixir is a pretty readable language, but an explanation for the the mess of characters in the middle follows. --- This explanation is in two sections, the mod-fibonacci and the operating on it Mod-fib: ``` Stream.unfold({1,1},fn{p,n}->{rem(p,x),{n,p+n}}end) ``` This returns an infinite stream of fibonacci mod `x`. It starts with an accumulator `{1,1}`, and applies the following operation ad infinitum: given accumulator `{p,n}`, output `p mod x` to the stream. Then, set the accumulator to `{n,p+n}`. The rest: ``` fn x-> Define a fxn f(x) that returns Enum.to_list(1..x-1)-- The numbers from 1..x-1 that are not in List.flatten The flattened list constructed by Enum.take_while Taking from mod-fib until Stream.chunk( A 2-size chunk Stream.unfold({1,1},fn{p,n}->{rem(p,x),{n,p+n}}end) (of mod fib) ,2) ,&Enum.sum(&1)!=1 sums to 1, representing [0,1] or [1,0] end ``` [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 153 bytes ``` k =input a =table() y =1 i z =remdr(x + y,k) a<z> =1 x =y y =z i =lt(i,k * 6) i + 1 :s(i) o output =eq(a<o>) lt(o,k) o o =lt(o,k) o + 1 :s(o) end ``` [Try it online!](https://tio.run/##NYxBDoIwFET3/xSzbIUNxpho@NylhC6a1n6FkkAvXyrG5eS9N0uUUcKtFHiwi@81EQw4mTFYpQk7uCOHDJ7ta5rVhgZ76ysxfR6@EBt4P8VMcOCQlGs9LrjrOht0eC7KaRLImuo/2H6U6WXQqKrULwhBzvC3/pFosnEq5fo4AA "SNOBOL4 (CSNOBOL4) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~55~~ 53 bytes ``` ->n{*a=0,b=1;(n*n).times{a<<(b+=a[-2])%n};[*1...n]-a} ``` [Try it online!](https://tio.run/##DcbRCoMgFADQX5FAUNPLrMeyfYj4cGUL9tAlssBhfrvbeTrHFb9tdc0sVBS6h47OToIUSTg/2zsVnGcRe4feDEFyqpNXFgAoGKxN/DtaCRvu5c73fp2JdfzFzMJ46rjPmq0@B/XUobYf "Ruby – Try It Online") [Answer] # JavaScript (ES6), 84 bytes ``` f=(n,a=0,b=1,q=[...Array(n).keys()])=>a*b+a-1?f(n,b,(a+b)%n,q,q[b]=0):q.filter(x=>x) ``` [Answer] # Python 3, 76 bytes ``` def t(n,r=[1]): while n*n>len(r):r+=[sum(r[-2:])%n] return{*range(n)}-{*r} ``` This simply looks over the longest possible cycle of Fibonnaci numbers (n^2), and creates a list of all numbers that occur in that time. To simplify logic the numbers are stored modulo n. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 49 bytes ``` n->[k|k<-[0..n-1],prod(i=0,n^2,k-fibonacci(i)%n)] ``` [Try it online!](https://tio.run/##DctBCoAgEEDRqwxB4MBMaLSsLhIFZRiDMIq07O7m5i8e/HwW4SfXAAtU5XWLX5x5s8Og7HbKJd1GFkt6jBQ5yJX09F6MYK@415CK0bY6gskS5CL6NuiA15ZgFBHrDw "Pari/GP – Try It Online") ]
[Question] [ The crazy mathematician owns a wide collection of numbers, and therefore the space he has left is quite limited. To save some, he must fold his integers, but unfortunately he is really lazy. Your task, if you wish to help him, is to create a function / program that folds a given positive integer for our number maniac. # How to fold an integer? If it is evenly divisible by the sum of its digits, divide it by the sum of its digits. If it doesn't meet that requirement, take its remainder when divided by the sum of its digits. Repeat the process until the result reaches `1`. The folded integer is the number of operations you had to perform. Let's take an example (say `1782`): 1. Get the sum of its digits: `1 + 7 + 8 + 2 = 18`. `1782` is evenly divisible by `18`, so the next number is `1782 / 18 = 99`. 2. `99` is not evenly divisible by `9 + 9 = 18`, hence we take the remainder: `99 % 18 = 9`. 3. `9` is obviously divisible by `9`, so we divide it and obtain `1`. The result is `3`, because 3 operations were required in order to reach `1`. ## Rules and Specs * Some integers might have the sum of digits equal to `1`, such as `10` or `100`. Your program doesn't need to handle such cases. That means, you will be guaranteed that the integer given as input doesn't have the sum of digits equal to `1`, and no operation with the given integer will result in a number whose sum of digits is `1` (except for `1` itself, which is the "target"). For example, you will never receive `10` or `20` as input. * The input will be a positive integer higher than `1`. * **[Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)** apply. * You can take input and provide output by **[any standard mean](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)**. --- # Test Cases ``` Input -> Output 2 -> 1 5 -> 1 9 -> 1 18 -> 2 72 -> 2 152790 -> 2 152 -> 3 666 -> 3 777 -> 3 2010 -> 3 898786854 -> 4 ``` Here is **[a program](https://tio.run/##lZHLjoMwDEX3@QorUlUi0DBoFkiV6C/MZnZtFzzcqSUwNAlFfD1jWuYltYuuovje@B473ehPLb9NE0MGxD4g7nofGKNKKbwq1dm5qj9OKDJ5ymvgvinQAjkdOW8DNqF@2bM2Sg0nqhEYtpBsFJQQZpAooKOUVuD6JmjyThJ8BLeHxkAmKeKFJee9Q5t7ahl0OHvKufl3TqTJAV6Q6xEqupCjQuKKEbzQSXtoj0DeifYph4S0MODVWQm9pOZcXb0WXV97mWCjI47ju2RGoBjiOLsPrgBrh0@Rc@ufpP/HutyanLhCO5M/WuoNffWIfPnT9Z7XC2m00@0P/pA7iTn3ZLGSAX4VJ9u0@Ec77MptcjDTlKbpFw)** that lets you visualize the process and try more test cases. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code *in each language* (scored in bytes) wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes ``` [¼DSO‰0Kθ©#® ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/@tAel2D/Rw0bDLzP7Ti0UvnQuv//LSwtzC3MLExNAA "05AB1E – Try It Online") **Explanation** ``` [ # start loop ¼ # increment counter D # duplicate current value SO # sum the digits in the copy ‰ # divmod the current value by its digit-sum 0K # remove 0 from the resulting list θ # pop the last element © # store a copy in register # # if the current value is 1, break ® # push the copy from register # implicitly output counter ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~63~~ 57 bytes -1 thanks to totallyhuman -1 thanks to Mr. Xcoder -4 thanks to reffu ``` def f(n):a=sum(map(int,`n`));return n>1and-~f(n%a or n/a) ``` [Try it online!](https://tio.run/##HU7BCsIwFLvvK95FaOGpa3FtN5k/IsIKblhxb6PtDl789fpYLiEhJFm/@bWQLuU5TjAJkp3v0zaL2a8iUMaBBimvccxbJKCb8vQ8/jh38LBEoLOXJY8pJ@jhrhEahBZBOQTLSjXatvXOCMYYdq1F0LVi07XOOuOay6OqJu4KEAj2rq4Cxhp5H1KOIsjT572lLFQtkU8GWf4 "Python 2 – Try It Online") [Answer] # Haskell, ~~85~~ 78 bytes ``` f 1=0 f n|r<1=1+f(n`div`s)|1<2=1+f r where s=sum(read.pure<$>show n);r=n`rem`s ``` Saved 7 bytes thanks to Bruce Forte. [Try it online.](https://tio.run/##VZDBboMwEETv/oqRlQMWaoTTtKUUR2oPlaJGyiE/YCOMQAET2VAu/DslNKncuezqzWp3tKVyZ13X01SAi4gUMKNNueBhERiZV9/SsZGnmyuAxVBqq@GE65vAapWvL73V6WrnynaAYW9WGGl1I900k77OPzSSBHvT4WH3V44IGFGQ9xGJDCOUEBkWCVz67tTZgwE9flGC/xrRdnOMoXLaH12Bfr7vDwkowhDBkkixa0/xewmZ9s2MEdKoysxL8nY5Mr/ATxXd4MaH/A4jHvn88cbj1/glfo6ftr65JdMP) [Answer] # JavaScript (ES6), ~~66~~ ~~58~~ ~~51~~ 49 bytes Takes input as an integer. Returns `false` for `0` or `1` and throws an overflow error when it encounters any number whose digits add up to `1`. ``` f=n=>n>1&&f(n%(x=eval([...""+n].join`+`))||n/x)+1 ``` * 8 bytes saved with help from [Justin](https://codegolf.stackexchange.com/users/69583/justin-mariner). --- ## Test it ``` o.innerText=( f=n=>n>1&&f(n%(x=eval([...""+n].join`+`))||n/x)+1 )(i.value=898786854);oninput=_=>o.innerText=f(+i.value) ``` ``` <input id=i type=number><pre id=o> ``` [Answer] ## [Husk](https://github.com/barbuz/Husk), 12 bytes ``` ←€1¡Ṡ§|÷%oΣd ``` [Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/j9omPGpaY3ho4cOdCw4trzm8XTX/3OKU////G3GZcllyGVpwmRtxGZoamVsagCguMzMzLnNzcy4jA0MDLgtLC3MLMwtTEwA "Husk – Try It Online") ## Explanation ``` ←€1¡Ṡ§|÷%oΣd Implicit input, e.g. n=1782 Ṡ§|÷%oΣd This part defines the transformation. oΣ Sum of d digits: s=18 Ṡ % n mod s: 0 §| or (take this branch if last result was 0) ÷ n divided by s: 99 ¡ Iterate the transformation: [1782,99,9,1,1,1,... €1 Index of 1 (1-based): 4 ← Decrement: 3 Print implicitly. ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 87 bytes ``` n=>{int i=0,k,l;for(;n>1;++i){for(l=n,k=0;l>0;l/=10)k+=l%10;n=n%k>0?n%k:n/k;}return i;} ``` [Try it online!](https://tio.run/##fdExa4UwEAfw2XyKWx4o@voSqRqbxg6FTu1QOnQWm0pI3glJLBTxs1tt5/TgDo7fwX@4wZ@Hyalt9hpHePv2QV0FIYPtvYdXshDYy4c@6AG@Jv0BL73GNIM/OOppxuFeYyj27mAECRvKbtk30JIWprDic3KpwI6JPNfZcmxWYmEkFbbb@yIZzUwu7YlRgRJPpqMP@7zDixGrU2F2CFqsmyDJ44R@surm3emgnjWqdEzLLItIFZU2KoxHqYknsapsWvofR62u63hi00StpCweyFve8JpXt8fFSpLk919k3X4A "C# (.NET Core) – Try It Online") Lambda function that takes and returns an integer. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~22~~ ~~19~~ 17 bytes *-3 bytes thanks to @Shaggy.* *-2 bytes thanks to @ETHproductions* ``` ìx >1©1+ßU%VªU/V ``` [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=Cux4Cj4xqTEr31UlVqpVL1Y=&input=ODk4Nzg2ODU0) [Answer] # [Retina](https://github.com/m-ender/retina), 100 bytes ``` $ ; {`(.+); $1$*1;$& (?<=;.*)\d(?=.*;) $* .*;1;(.*) $.1 r`(1)*(\3)*;(1+); $#1;$#2;1 0;(.*);|;.*; $1; ``` [Try it online!](https://tio.run/##HYwxDsIwEAT7/UYOdD4ky3coNuiIUvKJFEaCgoYiooO/G5NqpdHOrI/383VrO77WRnB8KsdDcJCSqNMePF8mjxKWO89TFA8gQV917hQUFWtlDcLLMYizbvbQ3cFckbabf3viH/XWDCPO0BOKQUdDzhmlFFjS9AM "Retina – Try It Online") Link only includes smaller test cases as the larger ones take too long. [Answer] # Mathematica, 73 bytes ``` (t=#;For[r=0,t>1,r++,If[(s=Mod[t,g=Tr@IntegerDigits@t])<1,t=t/g,t=s]];r)& ``` [Answer] # PHP, 68+1 bytes unary output: ``` for($n=$argn;$n>1;$n=$n%($s=array_sum(str_split($n)))?:$n/$s)echo 1; ``` decimal output, 73+1 bytes: ``` for($n=$argn;$n>1;$i++)$n=$n%($s=array_sum(str_split($n)))?:$n/$s;echo$i; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/c8b2510a51d7ad689b4bf8ac7f6a4e081645a62b). --- The Elvis operator requires PHP 5.3 or later. For older PHP, replace `?:` with `?$n%$s:` (+5 bytes). [Answer] # Ruby, 46 bytes ``` f=->n{s=n.digits.sum;n<2?0:1+f[n%s<1?n/s:n%s]} ``` [Answer] # [Haskell](https://www.haskell.org/), ~~94~~ ~~93~~ ~~89~~ 88 bytes This feels really long.. ``` length.fst.span(/=1).iterate g g x|(d,m)<-x`divMod`sum[read[d]|d<-show x]=last$m:[d|m<1] ``` [Try it online!](https://tio.run/##Fc27CsIwFIDh3ac4g0MLNlLwEiWZOgsdhVowmEuDSVqao3bosxvr8I8ffyfiUzmXNHC4JaeCwY7oiCQOImRbXubEohoFKjArA9OcyY3PWTHdpX1fenmPL9@MSshGtrNkRez6D0wtdyLi2p8bOXtWtskLG5bDMNqAQEAv/RFwxsAorPqAKmBM9ESP9ED3u@9DO2FiKq5VXf8A "Haskell – Try It Online") Thanks @Laikoni & @nimi for golfing off 1 byte each! [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~83~~ ~~81~~ ~~76~~ 73 bytes ``` i,k,s;f(n){k=n;for(i=0;k>1;i++,n=k=k%s?:k/s)for(s=0;n;n/=10)s+=n%10;n=i;} ``` [Try it online!](https://tio.run/##dc7BisIwEAbge58iCIWEVkyytkk3xD178gW8LF0qITiKqSfx2buThd0aNw5zmX8@humXh76fJlf7OpiBArt5C2Y4Xaiz3PiNMK6qarDe@jJ8vPtVYHEZcAkGVlZwFioLpcDZOnOfjp8OKCtuBSHY54uDcaCLLZyvI4m13JDddcRpDwtmigcjyW@hEfux/EJSD1QydDNrXrAmZd0L1qVM6AcmZyZ06pTMO/X0nWik6njm3k/@z8433xKbwrZtsxDzpy@VykLMUyi54DkY81TqTivd6mYd5XqWf3nk92L6Bg "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` dDS$Ṛȯ/µÐĿL’ ``` [Try it online!](https://tio.run/##AScA2P9qZWxsef//ZERTJOG5msivL8K1w5DEv0zigJn///84OTg3ODY4NTQ "Jelly – Try It Online") [Answer] # Pyth, ~~20~~ 14 bytes ``` tl.ue-.DNsjNT0 ``` [Try it here.](http://pyth.herokuapp.com/?code=tl.ue-.DNsjNT0&input=898786854&debug=0) [Answer] # Perl, ~~71~~ bytes, ~~64~~ bytes, 63 bytes ``` -pl $c=0;while($_>1){$s=0;$s+=$_ for/./g;$_=$_%$s?$_%$s:$_/$s;++$c};$_=$c ``` [Try it online](https://tio.run/##HYnLCsIwEEX38xUuRlCCzQOTSQzVT8kiVC2EJjRCF@KvG2s393DOLcOcdGsYe@GX55iGA4arPL6xrgEr6zHs7nnmHX94DKvtsd62vWDgWD1jGD/bFVtToMGBtEAKpFbkxB9gjAEiAiWkAOssWWP1@ZvLa8xTbaeSfg) EDIT: saved 7 bytes, thanks to Xcali's comment ``` -p while($_>1){$s=0;$s+=$_ for/./g;$_=$_%$s?$_%$s:$_/$s;++$c}$_=$c ``` EDIT: since 5.14 non destructive substitution s///r ``` -pl while($_>1){$s=eval s/\B/+/gr;$_=$_%$s?$_%$s:$_/$s;++$c}$_=$c ``` [Answer] # Dyalog APL, 36 bytes ``` {x←+/⍎¨⍕⍵⋄1=⍵:0⋄0=x|⍵:1+∇⍵÷x⋄1+∇x|⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqCiChrf@ot@/Qike9Ux/1bn3U3WJoC6StDIAsA9uKGhDbUPtRRzuQcXh7BUgexANL1AJNUTDiSlMwBWJLIDa0ABLmIBFDUyNzSwMIA0iamZmBZMzNgaSRgSFIwsLSwtzCzMLUBAA "APL (Dyalog Unicode) – Try It Online") **How?** ``` { x←+/⍎¨⍕⍵ ⍝ x = digit sum 1=⍵:0 ⍝ if arg = 1: bye 0=x|⍵:1+∇⍵÷x ⍝ if arg divisible by x: recurse with arg/x 1+∇x|⍵ ⍝ recurse with arg mod x } ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 13 bytes ``` -@{:ΣZ¤∨)‡}°\ ``` [Try it online!](https://tio.run/##S0/MTPz/X9eh2urc4qhDSx51rNB81LCw9tCGmP//LSwtzC3MLExNAA "Gaia – Try It Online") ### Explanation ``` - Push -1 (this will be the counter) @ Push input (the starting number) {:ΣZ¤∨)‡}° Repeat this block until the results of 2 consecutive runs are the same: : Copy the number Σ Digital sum Z Divmod number by digital sum ¤ Swap ∨ Logical or: left-most non-zero out of (number mod sum, number div sum) )‡ Increment the counter \ Delete the final 1, implicitly print the counter ``` [Answer] ## Matlab, 150 bytes ``` function[d]=X(x) d=0;while ~strcmp(x,'1')z='sum(str2num(x(:)))';a=eval(['rem(',x,',',z,')']);y=num2str(a*(a>0)+eval([x,'/',z])*(a==0));x=y;d=d+1;end ``` Inputs should be given to the function as a string, such as X('152'). The function works by while looping and incrementing d. The `x=y;` line was necessary to avoid an error of Matlab trying to read and overwrite a variable value at the same time, apparently, which was a new one on me. Ungolfed: ``` function[d]=X(x) d=0; while ~strcmp(x,'1') z='sum(str2num(x(:)))'; a=eval(['rem(',x,',',z,')']); y=num2str(a*(a>0)+eval([x,'/',z])*(a==0)); x=y; d=d+1; end ``` [Answer] # [Haskell](https://www.haskell.org/), 68 bytes ``` f 1=0 f n=1+[f x|x<-[mod n,div n]<*>[sum$read.pure<$>show n],x>0]!!0 ``` [Try it online!](https://tio.run/##VY9Pa4NAEMXv@yleFg@xJmFt09aIKzSHQGgghx4lkJVdUapr8E/jwe9urU3Kdi4z83vDvJlU1J8qz4chgcsZSaC560QJur4LllFRSuiFzL6gT8FDGNVtYVVKyNWlrVRghXVaXkdp0YXsNJuxYezbXG4VfB973WAZ/qUj5jYRON9HzojRQ3AeYwqOS9t8NNVBgx7fKcH/6FE2qaquWa3MUQt097Y/@KBwHMyne4T9U1P8OiFWphjbhBQi0@MSWU4m4@PmVewGH03o3iFzmcmfbtzbeK/ei/e8NsU1Gb4B "Haskell – Try It Online") Based on [w0lf's answer](https://codegolf.stackexchange.com/a/139297/56433). [Answer] # [R](https://www.r-project.org/), 85 bytes ``` function(n){while(n>1){n="if"(x<-n%%(d=sum(n%/%10^(nchar(n):0)%%10)),x,n/d) F=F+1} F} ``` Anonymous function that returns the required output. [Verify all test cases!](https://tio.run/##FcrRCoIwFIDhex9DGJxDJ9xGbjNalz5GINpQWCexJEN89mVXP3z8Uwo@hZnb9/BkYFw//RDvwFeFK/t8CDkslyMLAZ1/zQ9gUQglb8Bt30z7f5YodkCkhbjoMKt9fVBbVm8pNuMYv9CCppIqUo6sJlVqW8l/yBhD1lrSUklylbPOuPKEFDD9AA "R – Try It Online") ]
[Question] [ It's Friday... so let's go golfing! Write code that determines the player's scoring on a hole in a game of golf. The code can be either a function or entire program. As the genre suggests, shortest code wins. Input (parameters or stdin, your choice): * An integer representing the hole's par, guaranteed to be between 3 and 6 * An integer representing the golfer's score, guaranteed to be between 1 and 64 Output (print to stdout or return, trailing newline allowed but not required, your choice): * if score is 1, output "Hole in one" * if score == par - 4 and par > 5, output "Condor" * if score == par - 3 and par > 4, output "Albatross" * if score == par - 2 and par > 3, output "Eagle" * if score == par - 1, output "Birdie" * if score == par, output "Par" * if score == par + 1, output "Bogey" * if score == par + 2, output "Double Bogey" * if score == par + 3, output "Triple Bogey" * if score > par + 3, output "Haha you loser" EDIT Congrats to Dennis on having the shortest answer! [Answer] ## PHP 5.3+, ~~173~~ ~~167~~ ~~166~~ ~~159~~ ~~156~~ ~~151~~ ~~127~~ 121 bytes ``` echo[Condor,Albatross,Eagle,Birdie,Par,$b=Bogey,"Double $b","Triple $b","Haha you loser"][min(4+$s-$p,8)]?:"Hole in one"; ``` **Notice-free version, ~~139~~ 137 bytes** ``` echo$s-1?["Condor","Albatross","Eagle","Birdie","Par",$b="Bogey","Double $b","Triple $b","Haha you loser"][min(4+$s-$p,8)]:"Hole in one"; ``` Set `$s`core and `$p`ar variables before the `echo` and you're off. **exploded view** ``` echo [Condor, Albatross, Eagle, Birdie, Par, $b = Bogey, "Double $b", "Triple $b", "Haha you loser"][ min( 4+$s-$p,8 ) ] ?: "Hole in one"; ``` **Edits** **-6:** Not storing the array, just calling it if need be. **-1:** Flipping the ternary around. **-7:** The lowest `$s-$p` with `$s>1` is `-4`, so the `max()` isn't necessary, since `4+$s-$p >= 0`. **-3:** `Array -> explode()`, thanks CoolestVeto! **-5:** Cheaty ~~string literal~~ undefined constant plus `$r[-1] -> false`, thanks Ismael Miguel! **-24:** Moving from an `explode()` function to a `printf`/`%s` setup, with some tweaks, more thanks to Ismael Miguel for the change of direction. **-6:** *Swerve*, we're back to `echo` again! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~91~~ 90 bytes Code: ``` -5+U“¥Ê€†€µ“ª"0Bogey"ДCondor Albatross²è Birdie Par ÿ‹¶ÿ½¿ÿ”ð¡“Haha€î loser“X0¹1Qm*@0ð:ðÛ ``` Explanation: Part 1: ``` -5+ # Computes Score - Par + 5 U # Store in X “¥Ê€†€µ“ª # Short for "Hole in one" "0Bogey" # Push this string Ð # Triplicate ``` Part 2: ``` ”Condor Albatross²è Birdie Par ÿ‹¶ÿ½¿ÿ”ð¡ ``` This is the same as `"Condor Albatross Eagle Birdie Par 0Bogey Double0Bogey Triple0Bogey"` using string compression and string interpolation. We then split on spaces, using `ð¡`. Part 3: ``` “Haha€î loser“ # Push "Haha you loser" X # Push X 0¹1Qm # Compute 0 ^ (score == 1), this translates 1 to 0 and everything else to 1. * # Multiply the top two items @ # Get the string from that position 0ð: # Replace zeros with spaces ðÛ # Trim off leading spaces ``` Discovered a *lot* of bugs, uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=LTUrVeKAnMKlw4rigqzigKDigqzCteKAnMKqIjBCb2dleSLDkOKAnUNvbmRvciBBbGJhdHJvc3PCssOoIEJpcmRpZSBQYXIgw7_igLnCtsO_wr3Cv8O_4oCdw7DCoeKAnEhhaGHigqzDriBsb3NlcuKAnFgwwrkxUW0qQDDDsDrDsMOb&input=NAoz) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 61 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md) ``` _«4ị“Ƙḷ“&SẆ@ẓ“&T¡UQ“½⁽Ð'÷ṿɼ“½Œż“¡œM“v⁵“¥⁻c“£Ḋ⁶» 瓵ḣ⁻×⁵ñBƑ»’? ``` [Try it online!](http://jelly.tryitonline.net/#code=X8KrNOG7i-KAnMaY4bi34oCcJlPhuoZA4bqT4oCcJlTCoVVR4oCcwr3igb3DkCfDt-G5v8m84oCcwr3FksW84oCcwqHFk03igJx24oG14oCcwqXigbtj4oCcwqPhuIrigbbCuwrDp-KAnMK14bij4oG7w5figbXDsULGkcK74oCZPw&input=&args=Mg+Ng) ### Background This uses Jelly's static dictionary compression. You can find a compressor [here](https://codegolf.stackexchange.com/a/70932). This way, ``` “Ƙḷ“&SẆ@ẓ“&T¡UQ“½⁽Ð'÷ṿɼ“½Œż“¡œM“v⁵“¥⁻c“£Ḋ⁶» ``` and ``` “Bogey“Double Bogey“Triple Bogey“Haha you loser“Condor“Albatross“Eagle“Birdie“Par” ``` as well as ``` “µḣ⁻×⁵ñBƑ» ``` and ``` “Hole in one” ``` are equivalent. ### How it works ``` _«4ị“Ƙḷ“&SẆ@ẓ“&T¡UQ“½⁽Ð'÷ṿɼ“½Œż“¡œM“v⁵“¥⁻c“£Ḋ⁶» Helper link. Arguments: score, par _ Subtract the par from the score. «4 Cap the difference at 4. ị Index into the list at the right. “Ƙḷ“&SẆ@ẓ“&T¡UQ“½⁽Ð'÷ṿɼ“½Œż“¡œM“v⁵“¥⁻c“£Ḋ⁶» Yield a list of strings. 瓵ḣ⁻×⁵ñBƑ»’? Main link. Arguments: score, pair ? If... ’ the decremented score if non-zero: ç Call the helper link on both input arguments. “µḣ⁻×⁵ñBƑ» Else, return “Hole in one”. ``` [Answer] # Vitsy, 131 bytes ``` D1-)["eno ni eloH"rZ;]r-5+D9/([X9]mZ "rodnoC" "ssortablA" "elgaE" "eidriB" "raP" "yegoB" 4m" elbuoD" 4m" elpirT" "resol uoy ahaH" ``` Explanation: ``` D1-)["eno ni eloH"rZ;]r-5+D9/([X9]mZ D1-)[ ] If the second input is 1, do the bracketed stuff. "eno ni eloH"rZ; Output "Hole in one" and quit. r Reverse the stack. - Subtract the top two items. 5+ Add 5 to fix for negative values of score. D9/([ ] If the result of that is greater than 8, do the stuff in brackets. X Remove the top item. 9 Push 9. This forces any items greater than 8 to be 9. m Execute this number line. Z Output everything in the stack. ``` This works by figuring out what the score is relative to the par, then executing different lines (and gaining different strings) thereof. [Try It Online!](http://vitsy.tryitonline.net/#code=RDEtKVsiZW5vIG5pIGVsb0giclo7XXItNStEOS8oW1g5XW1aCiJyb2Rub0MiCiJzc29ydGFibEEiCiJlbGdhRSIKImVpZHJpQiIKInJhUCIKInllZ29CIgo0bSIgZWxidW9EIgo0bSIgZWxwaXJUIgQGCiJyZXNvbCB1b3kgYWhhSCI&input=&args=Ng+MTA) Verbose Mode (for poops and giggles): ``` duplicate top item; push 1; subtract top two; if (int) top is not 0; begin recursive area; toggle double quote; push 14; eval(stack); capture stack as object with next; ; eval(stack); push input item; ; push 14; push length of stack; capture stack as object with next; push all ints between second to top and top; toggle double quote; reverse stack; output stack as chars; generic exit; end recursive area; reverse stack; subtract top two; push 5; add top two; duplicate top item; push 9; divide top two; if (int) top is 0; begin recursive area; remove top; push 9; end recursive area; goto top method; output stack as chars; :toggle double quote; reverse stack; capture stack as object with next; push 13; eval(stack); capture stack as object with next; push cosine of top; toggle double quote; :toggle double quote; push inverse sine of top; push inverse sine of top; capture stack as object with next; reverse stack; push inverse tangent of top; push 10; push 11; push length of stack; push inverse cosine of top; toggle double quote; :toggle double quote; push 14; push length of stack; g; push 10; push e; toggle double quote; :toggle double quote; push 14; push input item; push 13; reverse stack; push input item; B; toggle double quote; :toggle double quote; reverse stack; push 10; push pi; toggle double quote; :toggle double quote; push number of stacks; push 14; g; capture stack as object with next; B; toggle double quote; :push 4; goto top method; toggle double quote; ; push 14; push length of stack; push 11; flatten top two stacks; capture stack as object with next; duplicate top item; toggle double quote; :push 4; goto top method; toggle double quote; ; push 14; push length of stack; push whether (int) top item is prime; push input item; reverse stack; push tangent of top; toggle double quote; ; ; :toggle double quote; reverse stack; push 14; push inverse sine of top; capture stack as object with next; push length of stack; ; flatten top two stacks; capture stack as object with next; push number of stacks; ; push 10; factorize top item; push 10; push all ints between second to top and top; toggle double quote; ``` [Answer] ## LittleLua - 160 Bytes (non-competitive) ``` r()P=I B="Bogey"r()Z={"Hole in one","Condor","Albatross","Eagle","Birdie","Par",B,"Double "..B,"Triple "..B,"Haha, you loser"}p(I=='1'a Z[1]or Z[I-P+6]or Z[10]) ``` I'm relatively certain I did this right. Accepts two integers, par and player's score. The version of Little Lua that I used to make this was uploaded after this challenge was posted, but was not edited afterwards. It's relatively obvious from the code that nothing has been added to simplify this challenge **LittleLua Info:** Once I am satisfied with the built ins and the functionality of Little Lua, source will be available along with an infopage. [LittleLua V0.02](https://www.dropbox.com/s/kjzztvddh6eo5bu/LittleLua%20V0.02.zip?dl=0) [Answer] # JavaScript (ES6), ~~125~~ 124 bytes ``` p=>s=>"Hole in one,Condor,Albatross,Eagle,Birdie,Par,Bogey,Double Bogey,Triple Bogey".split`,`[s-1&&s-p+5]||"Haha you loser" ``` Assign to a variable e.g. `f=p=>s=>`, then call it like so: `f(6)(2)` Par first, then score. May be able to be shortened by combining the `"Bogey"`s. [Answer] # [Mouse-2002](https://github.com/catb0t/mouse2002), ~~223~~ 207 bytes Removing comments would likely help... ``` ??s:p:s.1=["Hole in one"]s.p.4-=p.5>["Condor"]s.p.3-=p.4>["Albatross"]s.p.2-=p.3>["Eagle"]s.p.1-=["Birdie"]s.p.=["Par"]s.p.1+=["Bogey"]s.p.2+=["Double Bogey"]s.p.2+=["Double Bogey"]s.p.3+>["Haha you loser"]$ ``` Ungolfed: ``` ? ? s: p: s. 1 = [ "Hole in one" ] ~ 1 s. p. 4 - = p. 5 > [ "Condor" ] ~ 2 s. p. 3 - = p. 4 > [ "Albatross" ] ~ 3 s. p. 2 - = p. 3 > [ "Eagle" ] ~ 4 s. p. 1 - = [ "Birdie" ] ~ 5 s. p. = [ "Par" ] ~ 6 s. p. 1 + = [ "Bogey" ] ~ 7 s. p. 2 + = [ "Double Bogey" ] ~ 8 s. p. 2 + = [ "Double Bogey" ] s. p. 3 + > [ "Haha you loser" ] $ ``` [Answer] ## bash, ~~150~~ 136 bytes ``` b=Bogey (($2<2))&&echo Hole in one||tail -$[$2-$1+5]<<<"Haha you loser Triple $b Double $b $b Par Birdie Eagle Albatross Condor"|head -1 ``` Test run: ``` llama@llama:...code/shell/ppcg74767golfgolf$ for x in {1..11}; do bash golfgolf.sh 6 $x; done Hole in one Condor Albatross Eagle Birdie Par Bogey Double Bogey Triple Bogey Haha you loser Haha you loser ``` Thanks to Dennis for 14 bytes! [Answer] # Python 2, ~~186~~ ~~179~~ 158 bytes ``` def c(s,p):a="Bogey";print["Condor","Albatross","Eagle","Birdie","Par",a,"Double "+a,"Triple "+a,"Haha you loser","Hole in one"][([[s-p+4,8][s-p>3],9][s==1])] ``` EDIT 1: added the missing "hole in one" case... EDIT 2: golfed out some bytes (thanks to tac) [Answer] # Haskell - 131 bytes (counting newline) ``` 1%p="Hole in one" s%p=lines"Condore\nAlbatros\nEagle\nBirdie\nPar\nBogey\nDouble Bogey\nTriple Bogey\nHaha you loser"!!min(4-p+s)8 ``` `lines` is the only way I can think of to golf in a list of strings that have to contain spaces with access only to `Prelude` so stuck with two character delimiters. Still, Haskell isn't usually this competitive (against general languages at least). [Answer] # Python 2.7, 226 bytes ``` p,s=input() b="Bogey" l={s==1:"Hole in one",5<p==s+4:"Condor",4<p==s+3:"Albatross",3<p==s+2:"Eagle",s==p-1:"Birdie",s==p:"Par",s==p+1:b,s==p+2:"Double "+b,s==p+3:"Triple "+b,s>p+3:"Haha you loser"} for r in l: if r:print l[r] ``` Hard to come up with a short python code when you're late to the party, best I could think of. [Answer] # C, 198 Bytes ``` main(){char s=8,p=4,m[]="Hole in one.Condor.Albatross.Eagle.Birdie.Par.Bogey.Double Bogey.Triple Bogey.Haha you loser",*t,*x,i=0;for(x=m;t=strtok(x,".");x=0,i++)if((s-1?s-p>3?9:s-p+5:0)==i)puts(t);} ``` [Answer] # Japt, 97 bytes ``` `Ho¤ e CÆBr AlßNoss Eag¤ Bir¹e P zD½e zTp¤ zHa y lo r`rz"Bogey " ·g9m´V©V-U+6 ``` Contains a bunch of unprintables. [Test it online!](http://ethproductions.github.io/japt?v=master&code=YEhvpCCIII1lCkPGQnIKQWzfTm9zcwpFYWekCkJpcrllClCHCnpEjL1lIHpUnXCkIHpIYZUgeYwgbG+gcmByeiJCb2dleQoiILdnOW20VqlWLVUrNg==&input=NiAy) ### How it works ``` `Ho¤ e\nCÆBr\nAlßNoss\nEag¤\nBir¹e\nP\nzD½e zTp¤ zHa y lo r` rz"Bogey\n" · g9m´ V© V-U+6 "Hole in one\nCondor\nAlbatross\nEagle\nBirdie\nPar\nzDouble zTriple zHaha you loser"rz"Bogey\n" qR g9m--V&&V-U+6 // Implicit: U = par, V = score "..." // Take this long, compressed string. rz"Bogey\n" // Replace each instance of "z" with "Bogey\n". qR // Split at newlines. --V&&V-U+6 // If V is 1, take 0; otherwise, take V-U+5. 9m // Take the smaller of this and 9. g // Get the item at this index in the previous list of words. // Implicit output ``` [Answer] ## Python 2.7.2, 275 bytes ``` s=int(input()) p=int(input()) a="Bogey" if s==1:b="Hole in one" elif p-4==s:b="Condor" elif p-3==s:b="Albatross" elif p-2==s:b="Eagle" elif p-1==s:b="Birdie" elif p==s:b="Par" elif p+1==s:b=a elif p+2==s:b="Double "+a elif p+3==s:b="Triple "+a else:b="Haha you loser" print b ``` Ungolfed/explained: ``` score = int(input()) par = int(input) foo = "Bogey" # a shortcut for 3 of the outputs if score == 1: output = "Hole in one" elif par - 4 == score: output = "Condor" ... elif par == score: output = "Par" elif par + 1 == score: output = foo # See what I mean? elif par + 2 == score: output = "Double " + foo # Huh? Huh? elif par + 3 == score: output = "Triple " + foo # That makes 3. else: output = "Haha you loser" print output # Make sense? ``` My second answer, ironically both are in Python. Golfing tips appreciated! [Answer] # Python 2, ~~302~~ 284 bytes ``` i=input();j=input() if j==1:print"Hole in one" if(j==i-4)&(i>5):print"Condor" if(j==i-3)&(i>4):print"Albatross" if(j==i-2)&(i>3):print"Eagle" if j==i-1:print"Birdie" if j==i:print"Par" if j>i: k=j-i if k<4: print["","Double ","Triple "][k-1]+"Bogey" else: print"Haha you loser" ``` If leading white space was allowed, that'd be 282 bytes: ``` i=input();j=input() if j==1:print"Hole in one" if(j==i-4)&(i>5):print"Condor" if(j==i-3)&(i>4):print"Albatross" if(j==i-2)&(i>3):print"Eagle" if j==i-1:print"Birdie" if j==i:print"Par" if j>i: k=j-i if k<4: print["","Double","Triple"][k-1],"Bogey" else: print"Haha you loser" ``` ]
[Question] [ What general tips do you have for golfing in T-SQL? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to T-SQL. Please post one tip per answer. Thanks to Marcog for the original idea. :) [Answer] My general bag of tricks:: * `@` is a valid variable in t-sql. * T-sql 2012 added `iif` a VB style case statement. This is almost always shorter than an equivalent `if` `else`. * `\` is a useful way to initialize a number as 0 in a money type. You can convert a value to to a float by adding `e`. e.g. `4e` or `\k` which will set k to the value 0.00 money. * `rCTE` seem to be the best way to create a number table of less than a 100 entries. Even shorter than using spt\_values. If you need more than a 100, cross join and add them. * `+=` and other compound operators were added in 2008. Use them it saves a few characters. * Literals are usually a good enough delimiter for aliasing purposes. You rarely need a space or a `;`. * Use ANSI SQL joins if you need them. `Select*from A,B where condition` is shorter than `select*from A join b on condition` * If you can be assured that the your while loop will do the first iteration it's best to rewrite it as a do-while style `goto` loop. * `STR()` is the shortest function to turn an int into a string. If you are doing more than one conversion or may need to concat numerous different datatypes consider the `concat` function. E.g. `'hello'+str(@)` is shorter than `concat('hello',@)`, but `hello+str(@)+str(@a)` is longer than `concat('hello',@,@a)` For example These two are semantically equivalent. ``` while @<100begin/*code*/set @+=1 end s:/*code*/set @+=1if @<100goto s ``` You can use `Values` to create a table or subquery. This will only really be a benefit if you need a few constant rows. [Answer] **Code compression using SQL** SQL is wordy,scores high, and as much as we love'em, `SELECT FROM WHERE` cost 23 bytes with every use. You can compress these and other repeated words or entire code snippets. Doing this will decrease the marginal cost of repeated code to 1 byte!\* **How this works:** * A variable is declared and assigned compressed SQL code * A table modifies the variable. Each row deflates the variable. * The modified variable is executed. **The problem:** The upfront cost is close to 100 bytes and each row in the replacement table costs another 6 bytes. This kind of logic won't be very effective unless you're working with a lot of code which you can't trim down or the challenge is compression-based. **Here's an example** The challenge is to get the last 10 multiples of 2,3, and 5 leading up to n. Let's say this (**343 bytes golfed**) is the best solution I could come up with: ``` WITH x AS( SELECT 99 n UNION ALL SELECT n-1 FROM x WHERE n>1 ) SELECT w.n,t.n,f.n FROM (SELECT n, ROW_NUMBER()OVER(ORDER BY n DESC)r FROM x WHERE n%2=0 )w , (SELECT n, ROW_NUMBER()OVER(ORDER BY n DESC)r FROM x WHERE n%3=0 )t , (SELECT n, ROW_NUMBER()OVER(ORDER BY n DESC)r FROM x WHERE n%5=0 )f WHERE w.r=t.r AND w.r=f.r AND w.r<11 ORDER BY 1 ``` **Example after code is compressed** This executes the same code as above, is ~**302 bytes golfed**. ``` DECLARE @a CHAR(999)=' WITH x AS(!99n UNION ALL !n-1 @x#n>1) !w.n,t.n,f.n@$2=0)w,$3=0)t,$5=0)f #w.r=t.r AND w.r=f.r AND w.r<11^1' SELECT @a=REPLACE(@a,LEFT(i,1),SUBSTRING(i,2,99)) FROM(VALUES ('$(!n,ROW_NUMBER()OVER(^n DESC)r@x#n%'), ('! SELECT '), ('@ FROM '), ('# WHERE '), ('^ ORDER BY ') )x(i) EXEC(@a) ``` [Answer] Here's a funny one. This will convert the values in a column into a single tuple. EDIT: Thank you for the comments. It seems like the shortest way of rolling up without the XML tags is: ``` SELECT (SELECT column1+'' FROM table ORDER BY column1 FOR XML PATH('')) ``` Note: if XML is a valid output you can omit the outer select and parens. Also the `column1+''`, only works for strings. For number types it's best to do `column1+0` [Answer] It is possible to use some [**bitwise** operators in T-SQL](http://msdn.microsoft.com/en-us/library/ms176122.aspx). I don't have a concrete example, but I believe it is a good-to-know fact when golfing in T-SQL. [Answer] ## Print instead of Select It's as simple as that! So here's a T-SQL / Python polyglot: ``` print'Hello, World!' ``` [**Try it online**](https://data.stackexchange.com/codegolf/query/666656/hello-world) [Answer] Scientific notation is a shorter method to express very large and very small numbers, e.g. `select 1000000000` = `select 1E9` and `select 0.000001` = `select 1E-6`. [Answer] # Use GZIP compression for very long strings! So I knew that SQL 2016 added a [`COMPRESS`](https://docs.microsoft.com/en-us/sql/t-sql/functions/compress-transact-sql?view=sql-server-2017) function (and a [`DECOMPRESS`](https://docs.microsoft.com/en-us/sql/t-sql/functions/decompress-transact-sql?view=sql-server-2017) function), which (finally) brings the ability to GZIP a string or binary. The problem is that it isn't immediately clear how to take advantage of this for golfing; `COMPRESS` can take a string but returns a `VARBINARY`, which is shorter in *bytes* (when stored in a SQL `VARBINARY` field), but is *longer* in characters (raw hex). I've played with this before, but I finally was able to put together a working version, based on [this old answer on SO](https://stackoverflow.com/a/35559661/21398). That post doesn't use the new GZIP functions, but it does convert a `VARBINARY` to a Base-64 encoded string. We just needed to insert the new functions into the right place, and golf it up a bit. Here is the code you can use to convert your very long string to the Base-64 encoded compressed string: ``` DECLARE @s VARCHAR(MAX)='Your really long string goes right here' SELECT CONVERT(VARCHAR(MAX),(SELECT CONVERT(VARBINARY(MAX),COMPRESS(@s)) FOR XML PATH(''),BINARY BASE64)) ``` Take the output, and use it in your code in place of the original long string, along with: ``` --To use your compressed string and return the original: DECLARE @e VARCHAR(MAX)='H4sIAAAAAAAEAIvMLy1SKEpNzMmpVMjJz0tXKC4pygRS6fmpxQpFmekZJQoZqUWpAGGwW5YnAAAA' SELECT CAST(DECOMPRESS(CAST(@e as XML).value('.','varbinary(max)'))AS varchar(max)) ``` So instead of your original code (**1471 bytes**) ``` SELECT'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. But, in a larger sense, we can not dedicate — we can not consecrate — we can not hallow — this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us — that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion — that we here highly resolve that these dead shall not have died in vain — that this nation, under God, shall have a new birth of freedom — and that government of the people, by the people, for the people, shall not perish from the earth.' ``` you would have this (**1034 bytes**): ``` SELECT CAST(DECOMPRESS(CAST('H4sIAAAAAAAEAGVUW47bMAy8Cg/g5hD9aLFA0a8C/aYt2hZWEVNJjpGT5LodinE2i/0JIouPmeFQP3QrVCctQpwDVblKpptwqcSLkt3O3FbBeSy6LWujWUtbSTO1NVaaNLeYJbeBmLLslLlFzYNdTBKvEihm+hVHKe029CZBQpy44aYpighdil60RsvDmRtxSnQGEAasqUiPlX8bpxP91p126TeSF168PtNiYTTFa0y0cxmoSQWwhfZVDL8XPsBpAZLb40hVX9B+QgganCkp6kgOW5ET/fXmZ2mmwdF45NaSfJujpEA6ezfg6PErX8FDz2KEj9pIvUBJ63/E92xoBO3xP3Oi8iBxSTyJKY9ArQJSSiAltFhp8IuFEuBXL/TClc7RhmaXJ3prhJFxarq4KHNsvb6RtikcOkHhuuoGLkH7nE/0fcOIu9SJy4LAKrnKYKGmUdb2Qe3++hXSVpnKl+8rpoxh3t1HC9yVw4n+wA9jMVYwwGC4D3xBGOIY89rKtiwJwzINhkPfow0cAagzY8aj4sZMfFG1n90IKnEIZoEgrfDUvOmuBXT3COulaMM0kCieEdgNUOQsZ9gYEB4K8e0BYNwgbHNm2KBik4LCHgmhbxSigz1mYKPcane/Uxyo9D0bDN8oL0vS5/zYlC3DF7Gu+Ay872gQp9U7mDCzb2jPWN0ZaGJKwOJZx3QD9SvD6uEA4l2feHrvnv9lS93ojeu7ScHAAVFGme3tQOr94eGiZwuHSVeFduKDM70avwscZAtd++er+sqrp068VTf5C63D4HBdRfWtvwxcsYq2Ns8a96dvnTxMD7JYH0093+dQxcFU897DhLgO0V+RK0gdlbopj+cCzoRGPxX+89Se5u/dGPtzOIO5SAD5e3drL7LAfiXDyM13HE+d6CWZY26fjr7ZH+cPgFhJzPspK+FpbuvpP9RXxXK3BQAA'as XML).value('.','varbinary(max)'))AS varchar(max)) ``` See [this answer](https://codegolf.stackexchange.com/a/190643/70172) which saved me nearly 200 bytes. I haven't done the math, but clearly due to the overhead this is only going to be effective for extremely long strings. There are probably other places this can't be used; I've already discovered you have to `SELECT` it, you can't `PRINT` it, otherwise you get: ``` Xml data type methods are not allowed in expressions in this context. ``` **EDIT**: Shorter version of the decompress code, [courtesy of @digscoop](https://codegolf.stackexchange.com/questions/192715/output-a-super-mario-image#comment459401_192718): Save 10 bytes by changing the outer `CAST` to an implicit conversion using `CONCAT`: ``` SELECT CONCAT('',DECOMPRESS(CAST('encoded_string_here'as XML).value('.','varbinary(max)'))) ``` You can also declare a variable of type `XML` instead of `VARCHAR(MAX)`, and save on the inner `CAST`: ``` DECLARE @ XML='encoded_string_here' SELECT CONCAT('',DECOMPRESS(@.value('.','varbinary(max)'))) ``` This is *slightly* longer by itself, but if you need it in a variable for other reasons, then it might help. [Answer] [Michael B mentioned using a recursive CTE for a number table](https://codegolf.stackexchange.com/a/32797/70172), but didn't show an example. Here is a MS-SQL version we [worked out in this other thread](https://codegolf.stackexchange.com/questions/129211/sql-select-number-ranges/129215#129215): ``` --ungolfed WITH t AS ( SELECT 1 n UNION ALL SELECT n + 1 FROM t WHERE n < 99) SELECT n FROM t --golfed WITH t AS(SELECT 1n UNION ALL SELECT n+1FROM t WHERE n<99)SELECT n FROM t ``` Note that you can change the *starting value* (`1 n`), the *interval* (`n + 1`) and the *ending value* (`n < 99`). If you need more than 100 rows, though, you will need to add `option (maxrecursion 0)`: ``` WITH t AS(SELECT 0n UNION ALL SELECT n+1FROM t WHERE n<9999) SELECT n FROM t option(maxrecursion 0) ``` or join the rCTE to itself: ``` WITH t AS(SELECT 0n UNION ALL SELECT n+1FROM t WHERE n<99) SELECT 100*z.n+t.n FROM t,t z ``` Although this last one isn't guaranteed to return in numeric order without an `ORDER BY 1` [Answer] A few thoughts about creating and using tables for challenges: **1. SQL input can be taken via a pre-existing table** [Code Golf Input/Output Methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341): > > SQLs may take input from a named table > > > Creating and populating this table with input values doesn't count toward your byte total, you can just assume it is already there. This means your calculations can output via simple SELECT from the input table: ``` SELECT 2*SQRT(a)FROM t ``` **2. If possible, don't actually create a table at all** Instead of (69 bytes): ``` CREATE TABLE t(b INT) INSERT t VALUES(7),(14),(21),(99) SELECT b FROM t ``` Just do (43 bytes): ``` SELECT b FROM(VALUES(7),(14),(21),(99))t(b) ``` **3. If possible, create the table with a SELECT INTO** Instead of (39 bytes): ``` CREATE TABLE t(p INT) INSERT t VALUES(2) ``` Do this (17 bytes): ``` SELECT 2 p INTO t ``` **4: Consider mashing multiple columns together** Here are two variations that return the same output: ``` SELECT a,b FROM (VALUES('W','Bob'),('X','Sam'),('Y','Darla'),('Z','Elizabeth'))t(a,b) SELECT LEFT(a,1),SUBSTRING(a,2,99)FROM (VALUES('WBob'),('XSam'),('YDarla'),('ZElizabeth'))t(a) ``` After some testing, the top version (multiple columns) seems shorter with *7 or fewer rows*, the bottom version (due to the LEFT and SUBSTRING) is shorter with *8 or more rows*. Your mileage may vary, depending on your exact data. **5: Use REPLACE and EXEC for very long sequences of text** In the vein of [comfortablydrei's excellent answer](https://codegolf.stackexchange.com/a/32841/70172), if you have **15 or more values**, use `REPLACE` on a symbol to get rid of the repeated `'),('` separators between elements: 114 characters: ``` SELECT a FROM(VALUES('A'),('B'),('C'),('D'),('E'),('F'),('G'),('H') ,('I'),('J'),('K'),('L'),('M'),('N'),('O'))t(a) ``` 112 characters: ``` DECLARE @ CHAR(999)=REPLACE('SELECT a FROM(VALUES('' A-B-C-D-E-F-G-H-I-J-K-L-M-N-O''))t(a)','-','''),(''')EXEC(@) ``` If you're *already* using dynamic SQL for other reasons (or have multiple replaces), then the threshold where this is worth it is much lower. **6: Use a SELECT with named columns instead of a bunch of variables** Inspired by [jmlt's excellent answer here](https://codegolf.stackexchange.com/a/118041/70172), re-use strings via a SELECT: ``` SELECT a+b+a+b+d+b+b+a+a+d+a+c+a+c+d+c+c+a+a FROM(SELECT'Hare 'a,'Krishna 'b,'Rama 'c,' 'd)t ``` returns ``` Hare Krishna Hare Krishna Krishna Krishna Hare Hare Hare Rama Hare Rama Rama Rama Hare Hare ``` (For MS SQL I changed the `\t` to an in-line return, and changed `CONCAT()` to `+` to save bytes). [Answer] **Tag your code for T-SQL syntax highlighting** Instead of just: ``` CREATE TABLE t(b INT) INSERT t VALUES(7),(14),(21),(99) SELECT b FROM t ``` Include a language tag like this: ``` <!-- language: lang-sql --> CREATE TABLE t(b INT) INSERT t VALUES(7),(14),(21),(99) SELECT b FROM t ``` and the result will be: ``` CREATE TABLE t(b INT) INSERT t VALUES(7),(14),(21),(99) SELECT b FROM t ``` [Answer] **Take advantage of new features/functions in MS SQL 2016 and SQL 2017** If you don't have local copies to work with, you can play online with the [StackExchange Data Explorer](https://data.stackexchange.com/codegolf/query/new) (SQL 2016) or with [dbfiddle.uk](http://dbfiddle.uk/) (SQL 2016 or SQL "vNext"). **STRING\_SPLIT** ([SQL 2016 and later](https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql)) ``` SELECT * FROM STRING_SPLIT('one,two,three,four,five',',') ``` If you need to alias the table or refer to the column name: ``` SELECT t.value FROM STRING_SPLIT('one,two,three,four,five',',')t ``` **TRIM** ([SQL 2017 or later](https://docs.microsoft.com/en-us/sql/t-sql/functions/trim-transact-sql)) Shorter than `RTRIM()` and certainly shorter than `LTRIM(RTRIM())`. Also has [an option to remove other characters or sets of characters](https://sqlwithmanoj.com/2016/12/26/new-built-in-function-trim-in-sql-server-vnext-2018/) from either the beginning or the end: ``` SELECT TRIM('sq,0' FROM 'SQL Server 2000') ``` returns `L Server 2` **TRANSLATE** ([SQL 2017 or later](https://docs.microsoft.com/en-us/sql/t-sql/functions/translate-transact-sql)) `TRANSLATE` allows you to replace multiple characters in one step, rather than a bunch of nested `REPLACE` statements. But don't celebrate *too* much, it only replaces individual single characters with different single characters. ``` SELECT TRANSLATE('2*[3+4]/{7-2}', '[]{}', '()()'); ``` Each character in the second string is replaced by the *corresponding* character in the 3rd string. Looks like we could eliminate a bunch of characters with something like `REPLACE(TRANSLATE('source string','ABCD','XXXX'),'X','')` --- Some more interesting ones as well, like [`CONCAT_WS`](https://docs.microsoft.com/en-us/sql/t-sql/functions/concat-ws-transact-sql) and [`STRING_AGG`](https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql) that are probably worth a look as well. [Answer] Holy cow, I have discovered the wonder of **`PARSENAME`** ([SQL 2012 or higher](https://docs.microsoft.com/en-us/sql/t-sql/functions/parsename-transact-sql?view=sql-server-2017)). The function was built to isolate the parts of an object name like `servername.dbname.dbo.tablename`, but it works for *any* dot-separated values. Just remember it counts from the *right*, not the left: ``` SELECT PARSENAME('a.b.c.d',1), -- d PARSENAME('a.b.c.d',2), -- c PARSENAME('a.b.c.d',3), -- b PARSENAME('a.b.c.d',4) -- a ``` If you have less than 4 dot-separated values, it will return `NULL` for the remainder (but it *still counts right to left*): ``` SELECT PARSENAME('a.b',1), -- b PARSENAME('a.b',2), -- a PARSENAME('a.b',3), -- NULL PARSENAME('a.b',4) -- NULL ``` Here's where the magic comes in, though: combine it with `STRING_SPLIT` (2016 or higher) to make *in-memory multi-column tables!!* Old and busted: ``` SELECT a,b,c FROM (VALUES('Bob','W','Smith'), ('Sam','X','Johnson'), ('Darla','Y','Anderson'), ('Elizabeth','Z','Turner'))t(a,b,c) ``` New hotness: ``` SELECT PARSENAME(value,3)a,PARSENAME(value,2)b,PARSENAME(value,1)c FROM string_split('Bob.W.Smith-Sam.X.Johnson-Darla.Y.Anderson-Elizabeth.Z.Turner','-') ``` Clearly your actual savings depend on the size and contents of the table, and how exactly you are using it. Note that if your fields are constant-width, you're probably better off using `LEFT` and `RIGHT` to separate them instead of `PARSENAME` (not only because the function names are shorter, but also because you can eliminate the separators entirely). [Answer] A couple more unrelated tricks I saw and wanted to preserve: 1. **Use `GO #` to repeat a block a specific number of times**. Saw this clever trick on [Paul's excellent answer](https://codegolf.stackexchange.com/a/155150/70172). ``` PRINT'**********' GO 10 ``` This would, of course, reset any counter variables in the block, so you'd have to weigh this against a `WHILE` loop or a `x: ... GOTO x` loop. 2. **`SELECT TOP ... FROM systypes`** From the same question as Paul's above, [Anuj Tripathi used the following trick](https://codegolf.stackexchange.com/a/88729/70172): ``` SELECT TOP 10 REPLICATE('*',10) FROM systypes ``` or, as suggested by pinkfloydx33 in the comments: ``` SELECT TOP 10'**********'FROM systypes ``` Note this doesn't rely on any of the actual *contents* of `systypes`, just that the system view exists (which it does in every MS SQL database), and contains at least 10 rows (it looks to contain 34, for most recent versions of SQL). I couldn't find any system views with shorter names (that didn't require a `sys.` prefix), so this may be ideal. [Answer] See [this question on dba.stackexchange](https://dba.stackexchange.com/questions/221290/adding-a-row-number-with-no-column-to-order-by) for some interesting ideas for adding a number column to a STRING\_SPLIT result. Given a string like `'one,two,three,four,five'`, we want to get something like: ``` value n ------ --- one 1 two 2 three 3 four 4 five 5 ``` 1. Per Joe Obbish's answer, use `ROW_NUMBER()` and order by `NULL` or a constant: ``` SELECT value, ROW_NUMBER() OVER(ORDER BY (SELECT 1))n FROM STRING_SPLIT('one,two,three,four,five',',') ``` 2. Per Paul White's answer, [use a `SEQUENCE`](https://docs.microsoft.com/en-us/sql/t-sql/statements/create-sequence-transact-sql?view=sql-server-2017): ``` CREATE SEQUENCE s START WITH 1 SELECT value, NEXT VALUE FOR s FROM STRING_SPLIT('one,two,three,four,five', ',') ``` Sequences are interesting persistent objects; you can define the data type, the min and max value, the interval, and whether it wraps around to the beginning: ``` CREATE SEQUENCE s TINYINT; --Starts at 0 CREATE SEQUENCE s MINVALUE 1; --Shorter than START WITH SELECT NEXT VALUE FOR s --Retrieves the next value from the sequence ALTER SEQUENCE s RESTART; --Restarts a sequence to its original start value ``` 3. Per Biju jose's answer, you can use [the `IDENTITY()` *function*](https://docs.microsoft.com/en-us/sql/t-sql/functions/identity-function-transact-sql?view=sql-server-2017) (which is *not* the same as [the `IDENTITY` *property*](https://docs.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-2017) in conjunction with an INSERT: ``` SELECT value v,IDENTITY(INT) AS n INTO t FROM STRING_SPLIT('one,two,three,four,five',',') SELECT * FROM t ``` Note that the last two parameters in `IDENTITY(INT,1,1)` are optional, and will default to 1 if excluded. [Answer] Just discovered that you can **use numerals for a single-character `REPLACE` to eliminate quotes**: ``` --44 bytes PRINT REPLACE('Baby Shark******','*',' doo') --42 bytes PRINT REPLACE('Baby Shark000000',0,' doo') ``` This is because `REPLACE` does an implicit conversion to string. Both produce the same output: ``` Baby Shark doo doo doo doo doo doo ``` [Answer] \_ and # are valid aliases. I use them with CROSS APPLY to make it appear the columns it returns are part of the FROM clause e.g. ``` SELECT TOP 10 number, n2 FROM master.dbo.spt_values v CROSS APPLY (SELECT number*2 n2) _ ``` I like this when the only purpose of the CROSS APPLY is to compute an expression. For that matter, using APPLY for computing sub-expressions is a neat way to make your code DRY-er (and shorter). From what I've seen in execution plans, there is no added cost to this approach. The compiler figures out you're just computing something and treats it like any other expression. ]
[Question] [ # Code Golf Challenge I have an isdue, my fingrrs are fat and I freqintly jave an isdue of ty[ing one keystrpke to the right on my kryboard. I'm afraid the isdue is getyng worse anf worsr as time goes on. Sopn every keystrpke I make wil; be shiftrd pne to the right! Befpre then I'd like a program (or functipn) to autp shift every keystrpke back to the left one. I'll make sure to take my tome typong the rest of tjis chal;enge so as not to cause anu confudion! --- # Objective: Write a program or function that takes an input of one of the following green keys on a standard QWERTY keyboard and returns the character of the key one to the left of it.[![enter image description here](https://i.stack.imgur.com/x4ImR.jpg)](https://i.stack.imgur.com/x4ImR.jpg) --- # Conditions: •You may assume that the person running this program is using a QWERTY keyboard like the one pictured above. •Input and Output are both case-insensitive, you may use any case (or a mixture of case combinations) for this challenge and you can also assume all input will be in one case if desired. •If your language has no way of allowing a user to input the return key for some reason you may ignore that one keystroke for this •This challenge is just for the default values of the keys, for example if the `4` key is pressed you can assume it will always be `4` and never `$` •You can assume only the green keys will ever be pressed. --- # Example `Input` -> `Output`: `S` -> `a` `4` -> `3` `=` -> `-` `[` -> `p` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program with the shortest bytecount wins! [Answer] ## Ruby, ~~76 71~~ 69 bytes ``` ->a{"`1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./"[/.#{a}/][0]} ``` [Answer] # [Perl 6](https://perl6.org), ~~87~~ ~~83~~ 69 bytes ``` {[Q"`1234567890-=qwertyuiop[]\asdfghjkl;' zxcvbnm,./".comb].&{%(.[1..*]Z=>$_)}{$_}} ``` ``` {~Q"`1234567890-=qwertyuiop[]\asdfghjkl;' zxcvbnm,./".match(/.)>$_/)} ``` [Try it online!](https://tio.run/nexus/perl6#y61UUEtTsP1fXReolGBoZGxiamZuYWmga1tYnlpUUlmamV8QHRuTWJySlp6RlZ1jrc5VVZFclpSXq6Onr6SXm1iSnKGhr6dppxKvr1n7vzixUiFNQalYyZoLyjRBMG0RzGgl6/8A "Perl 6 – TIO Nexus") Wondering if there's a way to encode that hard-coded string to something shorter... *(Stole [G B's regex idea](https://codegolf.stackexchange.com/a/111135/14880) for -14 bytes.)* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~34~~ 33 bytes ``` ØD”`1¦ṭØqż“[]\“;'¶“,./“0-=”Fṡ2UZy ``` [Try it online!](https://tio.run/nexus/jelly#@394hsujhrkJhoeWPdy59vCMwqN7HjXMiY6NAZLW6oe2ASkdPX0gaaBrC1Tn9nDnQqPQqMr/QJFiE9tooNDh9v8A "Jelly – TIO Nexus") ### How it works ``` ØD”`1¦ṭØqż“[]\“;'¶“,./“0-=”Fṡ2UZy Main link. Argument: s (string) ØD Digits; yield "0123456789". ”`1| Replace '0' with a backtick. Øq Qwerty; yield ["qwertyuiop", "asdfghjkl", "zxcvbnm"]. ṭ Tack; add "`123456789" as the last element of the qwerty array. “[]\“;'¶“,./“0-=” Yield ["[]\\", ";'\n", "0-="]. ż Zip; combine the strings of the array to the left with the corresponding strings of the array to the right, yielding an array of string pairs. F Flatten, yielding a string. ṡ2 Obtain all overlapping pairs of characters. U Upend; reverse each pair. Z Zip, yielding a pair of strings. y Translate the input s according to the generated replacement table. ``` [Answer] # Python 3, ~~85~~ 78 bytes: ``` lambda x,k="`1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm<>?":k[k.‌​find(x)-1] ``` [Answer] # [Python](https://docs.python.org/2/), 76 bytes ``` s="1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm<>?" dict(zip(s,'`'+s)).get ``` [Try it online!](https://tio.run/nexus/python2#NctZE4FAAADgZ37Fzr5UyCQ5ihj3fd9as5Ikamu2cvz6PPneP0tFsaO7l6sOAiXIhlQngaOHJguZCkyJYhpiAWP5nBPzUqFYKuPxhK/WMELb/WrX7vY2/eFo2hzM1E5jeWgtjmtE5icNYwxTEhffPAoMYBMA/18WePVt0vAb2Z6vnRAKrjfr/ng6FQaRj/G6ELdaq8Ns5PsmZTklmfCpTUJgZIDFGlz8Aw "Python 2 – TIO Nexus") Makes a dictionary that takes each key to the one to its left by zipping the character string with its shifted version. The bottom line is the function, the top one is a definition. Using `translate` to create a mapping gave a longer solution. [Try it online!](https://tio.run/nexus/python2#NctZE4FAAADgZ37Fzr5UyCQ5ihj3fd9as5Ikamu2cvz6PPneP0tFsaO7l6sOAiXIhlQngaOHJguZCkyJYhpiAWP5nBPzUqFYKuPxhK/WMELb/WrX7vY2/eFo2hzM1E5jeWgtjmtE5icNYwxTEhffPAoMYBMA/18WePVt0vAb2Z6vnRAKrjfr/ng6FQaRj/G6ELdaq8Ns5PsmZTklmfCpTUJgZIDFGlz8Aw "Python 2 – TIO Nexus") ``` lambda s:s.translate("';"*22+"_0__9`12345678_LM-<>_\\VXSWDFGUHJKNBIO=EARYCQZT\nP][___"*4) ``` [Answer] # [Retina](https://github.com/m-ender/retina), 53 51 bytes ``` T`1-90\-=QW\ERTYUI\OP[]\\ASDF-HJ-L;'¶ZXCVBNM,./`\`o ``` [Try it online!](https://tio.run/nexus/retina#@x@SYKhraRCjaxsYHuMaFBIZ6hnjHxAdGxPjGOzipuvhpetjrX5oW1SEc5iTn6@Onn5CTEL@//@GRsYmpmbmFpYGurbhEG1gXUA97h5e3kA9XHAdAA "Retina – TIO Nexus") A simple transliteration shifting every character 1 position backwards. Everything from `1` to `/` is the original character set, while the following part is the new set, using `o` to indicate the Other set. `H` and `L` are special character classes for transliteration in retina (respectively mapping to Hex digits and uppercase Letters), but fortunately they occur on the keyboard inside alfabetically ordered sequences (`FGH` and `JKL`), so we can avoid escaping them by putting them in ranges and gain like that 2 bytes. [Answer] # C++, 109 bytes ``` void f(char i){std::string k="`1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./";std::cout<<k[k.find(i)-1];} ``` [Try it online!](https://tio.run/nexus/cpp-gcc#HcxJDoIwGEDhfU/R4IKSCIqzFLwIkFhbCr@FVpkcCGdH4tt@yZsWoHnZiQyHYJq2zlh1Qag3ILAkvGA1BmdoWhEEM4LOsYqsq7/Z7vaH4@m8dqPnK6vbTwfmEadJwhoh8@KuSmon@vvm/U1XS29l0f@Cm64NQxUrT4IWBBzXT@mIUMVAEwcNCM9JYhe2Q9E4TT8) [Answer] # TI-Basic, 70 bytes I doubt that it could get any shorter than this... ``` Input Str1 "`1234567890-=QWERTYUIOP[]\ASDFGHJKL;'ZXCVBNM,./ sub(Ans,inString(Ans,Str1)-1,1 ``` P.S. The two-byte tokens are `Str1`, ```, `\`, `sub(`, and `inString(`. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~57~~ ~~54~~ 51 bytes *3 bytes saved thanks to @nmjcman101 for using `hxVp` instead of what I had for the multiline keyboard* ``` i`¬190-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./<esc>/<C-r>a hxVp ``` [Try it online!](https://tio.run/nexus/v#@5@ZcGiNoaWBrm1heWpRSWVpZn5BdGxMYnFKWnpGVnaOtXpVRXJZUl6ujp6@tL5QIldGRVjB////owE "V – TIO Nexus") `<esc>` is `0x1b` and `<c-r>` is `0x12` Note: this doesn't not support the enter key Contains unprintables, so here's the hexdump ``` 00000000: 6960 ac31 3930 2d3d 7177 6572 7479 7569 i`.190-=qwertyui 00000010: 6f70 5b5d 5c61 7364 6667 686a 6b6c 3b27 op[]\asdfghjkl;' 00000020: 7a78 6376 626e 6d2c 2e2f 1b2f 1261 0a68 zxcvbnm,././.a.h 00000030: 7856 70 xVp ``` ### Explanation Most of the program generates the keyboard. `i` enters insert mode and every character following it is printed to the buffer. But there is a small quirk here, `¬19` inserts characters between 1 and 9. The program exits insert mode at the `<esc>`. And then here `/<c-r>a` it searches for the argument in the buffer. This brings the cursor on top of the character it found. ``` h " move the cursor to the left x " delete this character Vp " select this line and replace it with the deleted character ``` [Answer] # PowerShell, 82 bytes ``` $k="1234567890-=qwertyuiop[]\asdfghjkl;' zxcvbnm,./";$k[$k.IndexOf((read-host))-1] ``` The Enter key is supported, but cannot be tested with `Read-Host` because the act of hitting enter with no value returns nothing in PowerShell. [Answer] # [Japt](https://github.com/ETHproductions/japt), 56 42 bytes ``` ;D=Dv ·q i"[]\\",A i";'",22 +",./")Dg1nDbU ``` ### Explanation ``` ;D=Dv ·q i"[]\\",A i";'",22 +",./")Dg1nDbU ;D=D // Shortcut for QWERTY (with newlines and spaces), assigning to variable D v // Setting D to lowercase ·q // Joining D into an array with no spaces or newlines i"[]\\",A // Inserting "[]\" into index 10 (A) i";'",22 // Inserting ";'" into index 22 +",./" // Appending ",./" Dg // Returns the character at index: 1n // -1+ DbU // Index of U (the input) ``` [Try it online!](https://tio.run/nexus/japt#@2/tYutSpnBoe6FCplJ0bEyMko6hAZBpra6kY2SkoK2ko6evpOmSbpjnkhT6/79StBIA "Japt – TIO Nexus") [Answer] # Java 8, 99 bytes ``` c->{String r="`1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./";return r.charAt(r.indexOf(c)-1);} ``` **Explanation:** [Try it here.](https://tio.run/##hY/BbsIwDEDvfIXFpYm0ZmNjGyjqpH3A2IFji0RIU0hp3S5JOxjqt3dh5TpVsmXZftKzc9GKsKoV5umxl4WwFj6ExssEQKNTJhNSweraAsiDMCDJUCj3s86nD@uE0xJWgBBBL8O3y9oZjXsw0XQ7e3yaP7@8LpYPYfT1rYw7N7qq402SCJtm@0N@LHiQ4M9Jtjss79j9lBvlGoNg2FX17ohhGlN1@syIpOGM8q7ng7hudoUX3/xtpVMo/fVk0McbEHQ4fX22TpWsahyr/coVSJBJEtiA/j3yPzEfJaJRIh4lErwh3aTrfwE) ``` c->{ // Method with character as both parameter and return-type String r="`1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./"; // Literal String of the qwerty keyboard layout of the challenge return r.charAt( // Return the character at the following index: r.indexOf(c) // The index of the input character -1); // -1 to shift it to the left } // End of method ``` [Answer] ## JavaScript (ES6), 74 bytes ``` c=>(s=".,mnbvcxz\n';lkjhgfdsa\\][poiuytrewq=-0987654321`")[s.indexOf(c)+1] ``` Since `/` isn't in my string, `indexOf` returns `-1`, which when incremented causes `.` to be output. 93 bytes to process a string: ``` s=>s.replace(/./g,c=>s[s.indexOf(c)+1],s="><mnbvcxz\n';lkjhgfdsa\\][poiuytrewq=-0987654321`") ``` [Answer] ## [GNU sed](https://en.wikipedia.org/wiki/Sed), 72 + 1(r flag) = 73 bytes ``` s:$:`1234567890-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./: s:(.).*(.)\1.*:\2: ``` The return key can't be tested, because sed by design splits the input using `\n` as the delimiter and then runs the script as many times as there are lines. **Test run:** continuous input-output pair (when done press Ctrl + D or Ctrl + C) ``` me@LCARS:/PPCG$ sed -rf shift_key.sed s a 4 3 = - a \ 1 ` \ ] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 50 bytes ``` '`žhÀ"-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./"JDÀ‡ ``` [Try it online!](https://tio.run/nexus/05ab1e#@6@ecHRfxuEGJV3bwvLUopLK0sz8gujYmJjE4pS09Iys7Bxr9Zi8qorksqS8XB09fSUvl8MNjxoW/v@fkZqTk69Qnl@UkwIA "05AB1E – TIO Nexus") Explanation: ``` '` # 1 char string: ` žh # Push numbers 0123456789 À # Rotated 1 left (123456890) "-=qwertyuiop[]\\asdfghjkl;'\nzxcvbnm,./" # Push string literal J # Join all elements pushed to the stack to one string D # Duplicate À # Rotate 1 left ‡ # Transliterate: a.get(b.indexOf(input)) ``` [Answer] # Pyth - 56 bytes ``` @K"`1234567890-=qwertyuiop[]\\asdfghjkl;' zxcvbnm,./"txK ``` [Test Suite](http://pyth.herokuapp.com/?code=%40K%22%601234567890-%3Dqwertyuiop%5B%5D%5C%5Casdfghjkl%3B%27%0Azxcvbnm%2C.%2F%22txK&test_suite=1&test_suite_input=%22s%22%0A%224%22%0A%22%3D%22%0A%22%5B%22&debug=0). ]
[Question] [ Today we're going to build a pyramid out of letters! Here's an example letter pyramid for the first 5 letters: 1. Write the first 5 letters with a space between, first ascending and then descending. ``` A B C D E D C B A ``` 2. Do the same thing for the first four letters on the line above, but with two extra leading spaces: ``` A B C D C B A A B C D E D C B A ``` 3. Repeat the same step until the last line is just 'A' ``` A A B A A B C B A A B C D C B A A B C D E D C B A ``` 4. Repeat steps two and three going down instead of going up: ``` A A B A A B C B A A B C D C B A A B C D E D C B A A B C D C B A A B C B A A B A A ``` This same pattern can be extended up to 26 characters. Your challenge is to write a program or function that takes an integer as input, and produces the corresponding letter pyramid. You can choose to use uppercase or lowercase characters. You may always assume that the input will be an integer in `[1, 26]`, and the output may be any reasonable format for a 2d string. For example, a string with newlines in it, an array of characters, printing to a file, etc. Each line may have trailing spaces on it, and you may optionally output one trailing newline. Here are some example inputs/outputs: ``` 1: A 2: A A B A A 3: A A B A A B C B A A B A A 5: A A B A A B C B A A B C D C B A A B C D E D C B A A B C D C B A A B C B A A B A A 13: A A B A A B C B A A B C D C B A A B C D E D C B A A B C D E F E D C B A A B C D E F G F E D C B A A B C D E F G H G F E D C B A A B C D E F G H I H G F E D C B A A B C D E F G H I J I H G F E D C B A A B C D E F G H I J K J I H G F E D C B A A B C D E F G H I J K L K J I H G F E D C B A A B C D E F G H I J K L M L K J I H G F E D C B A A B C D E F G H I J K L K J I H G F E D C B A A B C D E F G H I J K J I H G F E D C B A A B C D E F G H I J I H G F E D C B A A B C D E F G H I H G F E D C B A A B C D E F G H G F E D C B A A B C D E F G F E D C B A A B C D E F E D C B A A B C D E D C B A A B C D C B A A B C B A A B A A 26: A A B A A B C B A A B C D C B A A B C D E D C B A A B C D E F E D C B A A B C D E F G F E D C B A A B C D E F G H G F E D C B A A B C D E F G H I H G F E D C B A A B C D E F G H I J I H G F E D C B A A B C D E F G H I J K J I H G F E D C B A A B C D E F G H I J K L K J I H G F E D C B A A B C D E F G H I J K L M L K J I H G F E D C B A A B C D E F G H I J K L M N M L K J I H G F E D C B A A B C D E F G H I J K L M N O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W X W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W X Y X W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Y X W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W X Y X W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W X W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O N M L K J I H G F E D C B A A B C D E F G H I J K L M N M L K J I H G F E D C B A A B C D E F G H I J K L M L K J I H G F E D C B A A B C D E F G H I J K L K J I H G F E D C B A A B C D E F G H I J K J I H G F E D C B A A B C D E F G H I J I H G F E D C B A A B C D E F G H I H G F E D C B A A B C D E F G H G F E D C B A A B C D E F G F E D C B A A B C D E F E D C B A A B C D E D C B A A B C D C B A A B C B A A B A A ``` As always, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so standard loopholes apply and the shortest answer in bytes wins! [Answer] # Python, ~~184 174~~ 169 bytes ``` R=range def g(a): def f(x,y,z): for i in R(x,y,z):print " "*(i-1)," ".join([chr(65+j) for j in R((a-i))]+[chr(65+(a-i-2)-j) for j in R((a-i-1))]) f(a,0,-1);f(2,a,1) ``` **Edit:** saved 5 bytes thanks to @nedla2004 [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 13 bytes Code: ``` A.ps£û€û€S».c ``` Explanation: ``` A.p # Push all prefixes of the alphabet. s£ # Only get the first input elements. û # Palindromize, turns ['a', 'ab', 'abc'] -> ['a', 'ab', 'abc', 'ab', 'a'] €û # Palindromize each, turns ['a', 'ab', 'abc', 'ab', 'a'] into... ['a', 'aba', 'abcba', 'aba', 'a'] €S # Split each element. » # Gridify, joins the arrays be newlines and the arrays in the arrays by spaces. .c # Centralize, aligning the text to the center. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=QS5wc8Kjw7vigqzDu-KCrFPCuy5j&input=MTM) [Answer] # [MATL](http://github.com/lmendo/MATL), ~~25~~ 24 bytes ``` Zv&+64+G-t64>*1&!t0*hTec ``` [Try it online!](http://matl.tryitonline.net/#code=WnYmKzY0K0ctdDY0PioxJiF0MCpoVGVj&input=MTU) Longer alternatives: * `1Y20hiZv&+G-t0>*1&!t0*hTe)` (26 bytes) * `Zv&+64+G-t64>*l2&Y"tZyP:o*c` (27 bytes) ### Explanation ``` % Implicit input Zv % Symmetric range. For input 3 it gives [1 2 3 2 1] &+ % Matrix of all pairwise additions. For input 3 it gives a 5×5 matrix 64+G % Add 64 and subtract input. This gives the desired ASCII codes in the % central rhombus t64>* % Make values less than 65 equal to 0. This affects entries outside the % central rhombus 1&! % Permute second and third dimensions. Transforms the 5×5 matrix into % a 5×1×5 array t0* % Push a copy of that array with all entries equal to 0 h % Concatenate along the second dimension. Gives a 5×2×5 array Te % Collapse the second and third dimensions. Gives a 5×10 matrix c % Convert to char. Char zero is displayed as space % Implicit display ``` [Answer] # [V](http://github.com/DJMcMayhem/V), 45 bytes ``` i¬A[À|lDybA"Ó./& òÄó¨á© á úe± >>.YGp{òd ``` [Try it online!](http://v.tryitonline.net/#code=acKsQVsbw4B8bER5YkEfEiIbw5MuLyYgCsOyw4TDs8Kow6HCqSDDoSDDumXCsSAKPj4uWUdwe8OyZA&input=&args=MjM) This ended up being *way* less golfy than I had hoped, so I'm not going to post an explanation yet. Hopefully I can whittle it down some more first. As usual, here is a hexdump: ``` 0000000: 69ac 415b 1bc0 7c6c 4479 6241 1f12 221b i.A[..|lDybA..". 0000010: d32e 2f26 200a f2c4 f3a8 e1a9 20e1 20fa ../& ....... . . 0000020: 65b1 200a 3e3e 2e59 4770 7bf2 64 e. .>>.YGp{.d ``` [Answer] # J, 34 bytes ``` (' ',u:65+i.26){~0>.]-[:+/~|@i:@<: ``` Takes the number as input and returns a 2D character array. ## Explanation ``` (' ',u:65+i.26){~0>.]-[:+/~|@i:@<: input y <: y - 1 i: "steps" -- i:2 -> -2 1 0 1 2 | absolute value +/~ addition table [: join right two tines into a conjunction ]- y - this table 0>. max(0, that) (' ',u:65+i.26) the alphabet preceded by a space {~ index ``` ## Decomposed test case ``` n =: 5 <: n 4 i: <: n _4 _3 _2 _1 0 1 2 3 4 | i: <: n 4 3 2 1 0 1 2 3 4 +/~ | i: <: n 8 7 6 5 4 5 6 7 8 7 6 5 4 3 4 5 6 7 6 5 4 3 2 3 4 5 6 5 4 3 2 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 2 3 4 5 6 5 4 3 2 3 4 5 6 7 6 5 4 3 4 5 6 7 8 7 6 5 4 5 6 7 8 n - +/~ | i: <: n _3 _2 _1 0 1 0 _1 _2 _3 _2 _1 0 1 2 1 0 _1 _2 _1 0 1 2 3 2 1 0 _1 0 1 2 3 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 3 2 1 0 _1 0 1 2 3 2 1 0 _1 _2 _1 0 1 2 1 0 _1 _2 _3 _2 _1 0 1 0 _1 _2 _3 0 >. n - +/~ | i: <: n 0 0 0 0 1 0 0 0 0 0 0 0 1 2 1 0 0 0 0 0 1 2 3 2 1 0 0 0 1 2 3 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 3 2 1 0 0 0 1 2 3 2 1 0 0 0 0 0 1 2 1 0 0 0 0 0 0 0 1 0 0 0 0 u:65 A i.26 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 65+i.26 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 u:65+i.26 ABCDEFGHIJKLMNOPQRSTUVWXYZ ' ',u:65+i.26 ABCDEFGHIJKLMNOPQRSTUVWXYZ (' ',u:65+i.26) {~ 0 >. n - +/~ | i: <: n A ABA ABCBA ABCDCBA ABCDEDCBA ABCDCBA ABCBA ABA A ``` Let's try this with input `5`. ## Test cases ``` f =: (' ',u:65+i.26){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NOPQRSTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA ABCDEFGHIJKLMNONMLKJIHGFEDCBA ABCDEFGHIJKLMNMLKJIHGFEDCBA ABCDEFGHIJKLMLKJIHGFEDCBA ABCDEFGHIJKLKJIHGFEDCBA ABCDEFGHIJKJIHGFEDCBA ABCDEFGHIJIHGFEDCBA ABCDEFGHIHGFEDCBA ABCDEFGHGFEDCBA ABCDEFGFEDCBA ABCDEFEDCBA ABCDEDCBA ABCDCBA ABCBA ABA A ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` RØAḣUz⁶ŒBṚŒḄG ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=UsOYQeG4o1V64oG2xZJC4bmaxZLhuIRH&input=&args=MjY)** ### How? ``` RØAḣUz⁶ŒBṚŒḄG - Main link: n e.g. 3 R - range [1,2,3] ØA - uppercase alphabet yield "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ḣ - head ["A","AB","ABC"] U - upend (vectorises) ["A","BA","CBA"] z - transpose with filler... ⁶ - space character ["ABC"," AB"," A"] ŒB - bounce (vectorises) ["ABCBA"," ABA "," A "] Ṛ - reverse [" A "," ABA ","ABCBA"] ŒḄ - bounce (flat) [" A "," ABA ","ABCBA"," ABA "," A "] G - grid format (join each with spaces and join with line feeds) A A B A A B C B A A B A A ``` [Answer] ## Pyke, 12 bytes ``` FhGR<Q{s )OX ``` [Try it here!](http://pyke.catbus.co.uk/?code=FhGR%3CQ%7Bs%0A%29OX&input=4&warnings=0) Disable warnings for specified output [Answer] # Python, ~~158~~ ~~154~~ ~~140~~ 139 bytes ``` r=range s=int(raw_input()) a=map(chr,range(65,91)) for i in r(0,s)+r(0,s-1)[::-1]: print (' '.join(a[:i+1]+a[:i][::-1])).center(s*4-2,' ')) ``` This is my first post so be gentle! I made heavy use of [::-1] to reverse strings, so maybe there's some optimization to be had there. Comments welcome. EDITS: Thanks @Rod for the pointer to the helpful link to the Python code golf topic and also for reminding me that the letters need spaces between them. Also thanks @wec for the general tips about removing spaces. [Answer] ## C#, ~~266~~ ~~263~~ ~~262~~ ~~261~~ ~~245~~ ~~238~~ ~~235~~ 232 bytes Golfed: ``` List<string> F(int n){int i=0;var l=new List<string>();for(;i<n;i++){var h="";for(var c='A';c<'B'+i;c++)h+=" "+c;l.Add(new string(' ',(n-i+1)*2)+h+" "+string.Concat(h.Remove(i*2).Reverse()));}for(i-=2;i>=0;i--)l.Add(l[i]);return l;} ``` Ungolfed with comments: ``` List<string> F(int n) { int i = 0; var l = new List<string>(); //collection of lines for (; i < n; i++) { var h = ""; //half of line //adding letters to first half of line for (var c = 'A'; c < 'B' + i; c++) h += " " + c; //adding leading spaces + half of line + reversed half of line to list l.Add(new string(' ', (n - i + 1)*2) + h + " " + string.Concat(h.Remove(i*2).Reverse())); } //adding lines in descending order for (i -= 2; i >= 0; i--) l.Add(l[i]); return l; } ``` Try it: <http://rextester.com/WIL67940> Returns list of strings. Each string contains one output line. I did that for fun and training. I realize that winning any of code-golf with C# is out of range. EDIT1: Changed string interpolation to `+` operator. EDIT2: `c <= 'A' + i` => `c < 'B' + i` EDIT3: Swapped `char` with `var`. EDIT4: Changed return type from `void` to `List`. EDIT5: Removal of unnecessary variable. EDIT6: New way of separating line halves. EDIT7: @Kaspar Kjeldsen, thank you. [Answer] # C, ~~124~~ 123 bytes Saving 1 byte thanks to Mukul Kumar ~~Currently cant get my head to transform the double loop into a single one, will leave it like this for the moment.~~ Actually, this is larger ``` for(l=0;l<4*n*(4*n+1);++l){ i=l/(4*n+1)-2*n; j=l%(4*n+1)-2*n; ``` So i just let the nested loop. ``` i,j,k;f(n){for(i=-2*n-1;++i<2*n;){for(j=-2*n-1;++j<=2*n;k=abs(i/2)+abs(j/2),putchar(j-2*n?k>=n||i%2||j%2?32:65+n+~k:10));}} ``` Uses the [Manhattan norm](https://en.wikipedia.org/wiki/Taxicab_geometry#Circles) to get the diamond shape. Ungolfed: ``` i,j,k; f(n){ for(i=-2*n-1;++i<2*n;){ for(j=-2*n-1;++j<=2*n; k=abs(i/2)+abs(j/2), putchar(j-2*n?k>=n||i%2||j%2?32:65+n+~k:10) ); } } ``` [Answer] # Brain-Flak, 630 + 3 = 633 bytes *This requires the `-A` flag to run* [Try it Online](http://brain-flak.tryitonline.net/#code=KCh7fSkpeygoe31bKCldKTwoe308KHt9PD4pPjw-KTw-KCh7fTw-KTwoKHt9Wyh7fSkoKV0pPHsoe31bKCldPCh7fTwoKCgoKCgpKCkoKSgpKXt9KXt9KXt9KSk-KT4pfXt9KCh7fTwoKCgoKCgoKSgpKCkoKSl7fSl7fSl7fSl7fSgpPD4pPD4pPik8eyh7fVsoKV08KCgoKSh7fTwoKCgoKCgpKCkoKSgpKXt9KXt9KXt9PD4pPD4pPik8Pik8Pik-KX17fSh7fTwoKCgoKCgpKCkoKSgpKXt9KXt9KXt9PD4pPD4pPikoKCgoKCkoKSgpKCkpe30pe30pe30pPil7KCh7fSlbKCldPCgoe30oKCgoKCkoKSgpKCkpe30pe30pe30pe308Pik8PikoKCgoKCgpKCkoKSgpKXt9KXt9KXt9PD4pPD4pPil9e30-KXsoe31bKCldPDw-KCgoKCgoKSgpKCkoKSl7fSl7fSl7fSkpPD4-KX17fSgoKCgpKCkoKSgpKCkpe308Pik8Pik-KT4pfXt9e317fShbXSl7KCgoe31bKCldKTx7KHt9WygpXTwoe308KHt9PD4pPD4-KT4pfXt9Pik8eyh7fVsoKV08PD4oe308Pik-KX17fT4pfXt9KCgoKSgpKCkoKSgpKXt9KTw-e30oW10peygoKHt9WygpXSk8eyh7fVsoKV08KHt9PCh7fTw-KTw-Pik-KX17fT4pPHsoe31bKCldPDw-KHt9PD4pPil9e30-KX17fXt7fSh7fVsoKCkoKSgpKCkoKSl7fV0pfXt9KFtdKXt7fSh7fTw-KTw-KFtdKX17fTw-&input=) ``` (({})){(({}[()])<({}<({}<>)><>)<>(({}<>)<(({}[({})()])<{({}[()]<({}<(((((()()()()){}){}){}))>)>)}{}(({}<((((((()()()()){}){}){}){}()<>)<>)>)<{({}[()]<((()({}<(((((()()()()){}){}){}<>)<>)>)<>)<>)>)}{}({}<(((((()()()()){}){}){}<>)<>)>)((((()()()()){}){}){})>){(({})[()]<(({}((((()()()()){}){}){}){}<>)<>)(((((()()()()){}){}){}<>)<>)>)}{}>){({}[()]<<>(((((()()()()){}){}){}))<>>)}{}(((()()()()()){}<>)<>)>)>)}{}{}{}([]){((({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}>)<{({}[()]<<>({}<>)>)}{}>)}{}((()()()()()){})<>{}([]){((({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}>)<{({}[()]<<>({}<>)>)}{}>)}{}{{}({}[(()()()()()){}])}{}([]){{}({}<>)<>([])}{}<> ``` This is not a great golf but this challenge is quite difficult in Brain-Flak [Answer] # Pyth, 23 bytes ``` V+SQt_SQp*dy-QNt_pjd<GN ``` [Try it online](http://pyth.herokuapp.com/?code=V%2BSQt_SQp%2ady-QNt_pjd%3CGN&input=13%0A&debug=1) [Answer] # Ruby, ~~137 115 100~~ 84 bytes ``` ->n{e=->s{s+s.reverse[1..-1]};e[(0..n-1).map{|i|" "*(n-i)+e[[*?A..?Z][0..i]*' ']}]} ``` Thanks to manatwork for the comments. [Answer] # [Befunge 93](http://esolangs.org/wiki/Befunge), 175 bytes [Try it online!](http://befunge.tryitonline.net/#code=JjowMHAiQiJcLSA6MTN2CnYsOiBfdiNgIkAiPHA1PAp2LCIgIjx2YCsqOTwKPiIgIiw6IDM1ZzdeCnY0NyJ2Il8-MSsgdgo-cCMgIDBeOj4tIHYKdiJBImc1MzwxdjwKPiswMGctYCB8NTMKdiI-IiwrOTE8cCsKPjc0cDM1Zzp2MTEKX3YjIC1nMDA8K14gX0AjOgoxPjU5Kjo5MXY-IHYKXnArMTk5cDg-IysgPA&input=Mzk) Probably not very well golfed. Oh well. This was hard enough with befunge: ``` &:00p"B"\- :13v v,: _v#`"@"<p5< v," "<v`+*9< >" ",: 35g7^ v47"v"_>1+ v >p# 0^:>- v v"A"g53<1v< >+00g-` |53 v">",+91<p+ >74p35g:v11 _v# -g00<+^ _@#: 1>59*:91v> v ^p+199p8>#+ < ``` Good luck figuring out how it works! I barely know. [Answer] ## Batch, 269 bytes ``` @echo off set/an=%1-1 set a=ABCDEFGHIJKLMNOPQRSTUVWXYZ for /l %%i in (-%n%,1,%n%)do set i=%%i&call:l exit/b :l set s= for /l %%j in (-%n%,1,%n%)do set j=%%j&call:c echo%s% exit/b :c set/aj=n-%i:-=%-%j:-=% call set s= %%a:~%j%,1%%%s% ``` Line 2 ends in 25 spaces; this means that when the alphabet index goes negative those squares simply remain blank. [Answer] ## C#, 199 bytes ``` q=>{Action<int>L=x=>{var s="";var k=0;for(;k<x;)s+=(char)('A'+k++)+" ";for(--k;--k>=0;)s+=(char)('A'+k)+" ";Console.WriteLine(new string(' ',(q-x)*2)+s);};var i=0;for(;i<q;)L(++i);for(;i>1;)L(--i);}; ``` As always, C# is not much of a golfing language, but I prefer "readable" code much more than esoteric Code. Also I just did this for fun :) Here's an ungolfed version, so you can easily understand what I did: ``` Action<int> C = q => { Action<int> L = x => { var s = ""; var k = 0; for (; k < x;) s += (char)('A' + k++) + " "; for (--k; --k >= 0;) s += (char)('A' + k) + " "; Console.WriteLine(new string(' ', (q - x) * 2) + s); }; var i = 0; for (; i < q;) L(++i); for (; i > 1;) L(--i); }; ``` (I think this could be optimized a lot though..) [Answer] ## Java, 213 bytes ``` void p(int n){int i=1,s=1,f,c;while(i>0){f=(n+1-i)*2;System.out.printf("%"+f+"s","");c=65;for(;c<64+i;)System.out.printf("%c ",c++);for(;c>64;)System.out.printf("%c ",c--);System.out.println();if(i==n)s=-1;i+=s;}} ``` Ungolfed: ``` void p(int n) { int i = 1, s = 1, f, c; while (i > 0) { f = (n + 1 - i) * 2; System.out.printf("%" + f + "s", ""); c = 65; for (; c < 64 + i; ) System.out.printf("%c ", c++); for (; c > 64; ) System.out.printf("%c ", c--); System.out.println(); if (i == n) s = -1; i += s; } } ``` [Answer] # TSQL, ~~261~~ 236 bytes ``` DECLARE @i INT =5; WITH C as(SELECT number z,abs(@i+~number)f FROM spt_values WHERE'P'=type)SELECT top(@i*2-1)space(f*2)+v+stuff(reverse(v),1,3,'')FROM(SELECT*,(SELECT top(@i-f)char(65+z)+' 'FROM c for xml path(''),type).value('.','varchar(52)')v FROM c)d ``` **[Fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=1f0c966d605c49d7c0c2e597937d11b8)** [Answer] # Java, 394 Bytes *I normally do C#, but it's good to mix it up...* Golfed: ``` String P(int n){String a="ABCDEFGHIJKLMNOPQRSTUVWXYZ",o="",k="",s="";int i=0,j=0,l=0;java.util.List<String>b=new java.util.ArrayList<String>();for(i=1;i<=n;i++){k="";s=a.substring(0,i);l=s.length();for(j=0;j<l;j++)k+=s.toCharArray()[j]+" ";while(k.length()<n+n)k=" "+k;if(i>1)for(j=l-2;j>=0;j--)k+=s.toCharArray()[j]+" ";k+="\r\n";b.add(k);o+=k;}for(i=b.size()-2;i>=0;i--)o+=b.get(i);return o;} ``` Ungolfed: ``` public String P(int n) { String a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", o ="", k="",s=""; int i =0, j=0, l=0; java.util.List<String> b = new java.util.ArrayList<String>(); for (i = 1; i <= n; i++) { k = ""; s = a.substring(0, i); l = s.length(); for (j = 0; j < l; j++) k += s.toCharArray()[j] + " "; while(k.length() < n + n) k= " " + k; if(i > 1) for (j = l-2; j >= 0; j--) k += s.toCharArray()[j] + " "; k += "\r\n"; b.add(k); o += k; } for (i = b.size()-2; i >= 0; i--) o += b.get(i); return o; } ``` Test: ``` BuildAnAlphabetPyramid b = new BuildAnAlphabetPyramid(); System.out.println(b.P(5)); System.out.println(b.P(26)); A A B A A B C B A A B C D C B A A B C D E D C B A A B C D C B A A B C B A A B A A A A B A A B C B A A B C D C B A A B C D E D C B A A B C D E F E D C B A A B C D E F G F E D C B A A B C D E F G H G F E D C B A A B C D E F G H I H G F E D C B A A B C D E F G H I J I H G F E D C B A A B C D E F G H I J K J I H G F E D C B A A B C D E F G H I J K L K J I H G F E D C B A A B C D E F G H I J K L M L K J I H G F E D C B A A B C D E F G H I J K L M N M L K J I H G F E D C B A A B C D E F G H I J K L M N O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W X W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W X Y X W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Y X W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W X Y X W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W X W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V W V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U V U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T U T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S T S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R S R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q R Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P Q P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O P O N M L K J I H G F E D C B A A B C D E F G H I J K L M N O N M L K J I H G F E D C B A A B C D E F G H I J K L M N M L K J I H G F E D C B A A B C D E F G H I J K L M L K J I H G F E D C B A A B C D E F G H I J K L K J I H G F E D C B A A B C D E F G H I J K J I H G F E D C B A A B C D E F G H I J I H G F E D C B A A B C D E F G H I H G F E D C B A A B C D E F G H G F E D C B A A B C D E F G F E D C B A A B C D E F E D C B A A B C D E D C B A A B C D C B A A B C B A A B A A ``` [Answer] # R, ~~100~~ ~~97~~ 87 bytes ``` x=scan();z=LETTERS;for(i in c(1:x,x:2-1))cat(rep(" ",x-i+1),z[1:i],if(i>1)z[i:2-1],"\n") 4: #> A #> A B A #> A B C B A #> A B C D C B A #> A B C B A #> A B A #> A ``` ( Update: `scan()` for input; abused (x-1):1 == x:2-1. ) Not too shabby for one of the keyword languages by the looks of it (those special-character ones are always going to be better). [Answer] # PHP, ~~122~~ 116 bytes ``` for($i=1-$n=$argv[1];$i<$n;)echo str_pad("",$a=abs($i++)),$s=join(range(A,chr(64+$n-$a))),substr(strrev($s),1),"\n"; ``` is there a shorter way? [Answer] ## JavaScript (ES6), 121 bytes ``` n=>[...Array(n+n--)].map((_,i,a)=>a.map((_,j)=>(j=10+n-g(i)-g(j))>9?(10-j).toString(36):` `,g=i=>i<n?n-i:i-n).join` `).join`\n` ``` Where `\n` represents the literal newline character. Outputs in lower case. [Answer] # [Canvas](https://github.com/dzaima/Canvas), 8 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` Zm[]/ *┼ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNBJXVGRjREJXVGRjNCJXVGRjNEJXVGRjBGJTIwJXVGRjBBJXUyNTND,i=NQ__,v=8) ##### Explanation: ``` Zm[]/ *+ | Full code (chars replaced with ASCII alternatives for monospace) ---------+--------------------------------------------------------------------- Z | Push uppercase alphabet m | Mold to length (i.e. first <input> chars) [] | Prefixes / | Antidiagonal (put spaces before each line/entry) _* | Put a space between each character (space underlined for visibility) + | Quad-palindromize with 1 overlap ``` [Answer] # [Perl 5](https://www.perl.org/) + `-pa -M5.10.0`, 79 bytes ``` @A=A..Z;$\=$s.$/.$\,say$s=" "x--$F[0]."@A[0..--$_,reverse 0..--$_]"for 1..$_}{ ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiQEE9QS4uWjskXFw9JHMuJC8uJFxcLHNheSRzPVwiICBcIngtLSRGWzBdLlwiQEFbMC4uLS0kXyxyZXZlcnNlIDAuLi0tJF9dXCJmb3IgMS4uJF99eyIsImhlYWRlciI6IiMkI3M9MiokXzskXFw9JHMuJC8uJFxcLHNheSgkcz1cIkBzQHtbKEEuLlopWzAuLiRfLHJldmVyc2UgMC4uLS0kX11dfVwiKSwkI3MtPTJmb3IgMC4uJF99e1xuIyQjcz0yKzIqJF87JFxcPSRzLiQvLiRcXCwkI3MtPTIsc2F5JHM9XCJAc0B7WyhBLi5aKVswLi4kXyxyZXZlcnNlIDAuLi0tJF9dXX1cImZvciAwLi4kX317XG4jJCNzPTIqJF87JFxcPSRzLiQvLiRcXCxzYXkoJHM9XCJAc0B7WyhBLi5aKVswLi4kXyxyZXZlcnNlIDAuLi0tJF9dXX1cIiksJCNzLT0yZm9yIDAuLiRffXtcbiNAQT1BLi5aOyQjcz0yKzIqJF87JFxcPSRzLiQvLiRcXCwkI3MtPTIsc2F5JHM9XCJAc0BBWzAuLiRfLHJldmVyc2UgMC4uLS0kX11cImZvciAwLi4kX317XG4jQEE9QS4uWjskXFw9JHMuJC8uJFxcLHNheSRzPSRcIngoKFwiQEZcIi0kXykqMikuXCJAQVswLi4kXyxyZXZlcnN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FsJyRcXD0kcy4kLy4kXFwsc2F5JHM9XCIgIFwieC0tJEZbMF0uXCJAQVswLi4tLSRfLHJldmVyc2UgMC4uLS0kX107XCIneCRffXtcbiNAQT1BLi5aO2V2YWwnJFxcPSRzLiRcXDskXy49JHM9XCIgIFwieC0tJEZbMF0uXCJAQVswLi4kaSsrLHJldmVyc2UgMC4uJGktMl1cbiNcIjsneCRfXG4jQEE9QS4uWjskXz1qb2luJC8sKG1hcHsoQGE9KEBhLFwiICBcIngtLSRGWzBdLlwiQEFbMC4uLS0kXyxyZXZlcnNlIDAuLi0tJF9dXCIpKVskLSsrXX0xLi4kXyksQGFcbiNAQT1BLi5aOyRfPWpvaW4kLywobWFwe0A7PSgkcyxAOyk7JHM9XCIgIFwieC0tJEZbMF0uXCJAQVswLi4tLSRfLHJldmVyc2UgMC4uLS0kX11cIn0xLi4kXyksQFxuI0BBPUEuLlo7c2F5IGZvcihtYXB7QDs9KCRzLEA7KTskcz1cIiAgXCJ4LS0kRlswXS5cIkBBWzAuLi0tJF8scmV2ZXJzZSAwLi4tLSRfXVwifTEuLiRfKSxAXG4iLCJhcmdzIjoiLXBhXG4tTTUuMTAuMCIsImlucHV0IjoiNSJ9) --- # [Perl 5](https://www.perl.org/) + `-pl`, 88 bytes A slightly longer approach, but utilises ANSI escape codes and draws the letters in a spiral, starting with 9 o'clock, moving clockwise. ``` $l=A;$\x=($_-1);//,(map$\.="$l$_"x$',".[A ",". ","....","..[A.."),$\.=$l++.$"while$_--}{ ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiMDAwMDAwMDA6IDI0NmMgM2Q0MSAzYjI0IDVjNzggM2QyOCAyNDVmIDJkMzEgMjkzYiAgJGw9QTskXFx4PSgkXy0xKTtcbjAwMDAwMDEwOiAyZjJmIDJjMjggNmQ2MSA3MDI0IDVjMmUgM2QyMiAyNDZjIDI0NWYgIC8vLChtYXAkXFwuPVwiJGwkX1xuMDAwMDAwMjA6IDIyNzggMjQyNyAyYzIyIDFiNWIgNDEyMCAyMjJjIDIyMGMgMjAyMiAgXCJ4JCcsXCIuW0EgXCIsXCIuIFwiXG4wMDAwMDAzMDogMmMyMiAwODBjIDA4MDggMjIyYyAyMjA4IDFiNWIgNDEwOCAwODIyICAsXCIuLi4uXCIsXCIuLltBLi5cIlxuMDAwMDAwNDA6IDI5MmMgMjQ1YyAyZTNkIDI0NmMgMmIyYiAyZTI0IDIyNzcgNjg2OSAgKSwkXFwuPSRsKysuJFwid2hpXG4wMDAwMDA1MDogNmM2NSAyNDVmIDJkMmQgN2Q3YiAgICAgICAgICAgICAgICAgICAgICBsZSRfLS19eyIsImFyZ3MiOiItcGwiLCJpbnB1dCI6IjEzIn0=) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 8 bytes ``` kA¦Ẏ∞ʁvṄ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJDIiwiIiwia0HCpuG6juKInsqBduG5hCIsIiIsIjEzIl0=) ## How? ``` kA¦Ẏ∞ʁvṄ kA # Push the uppercase alphabet ¦ # Prefixes Ẏ # Get the first input items ∞ # Palindromise this list ʁ # Palindromise each in this list vṄ # Join each on spaces # C flag centers and joins on newlines ``` ]
[Question] [ You task for today: draw a dragon curve! In case you don't know what a Dragon Curve is, [here](https://youtu.be/EdyociU35u8) is an introductory ViHart video (Really cool, please watch!) Your task: draw a dragon curve, iterated at least 9 times. You don't have to show iterations 1 through 9, you just have to show the final curve produced after completing (at least) 9 iterations. The curve must be drawn as straight lines connecting the points on the curve; the output should match one of the images below that shows 9 or more iterations (up to reflection, rotation, scaling, and variation in line width, line color, and background color). Your output must be large enough that the individual lines and the "boxes" that they form can be distinguished from each other; if two lines don't intersect in the curve, they shouldn't occupy the same or adjacent pixels in the output (there should be at least one pixel of the background visible between them). You can either display the image to the screen or saved the image to a file is accepted. The output must be graphical - it can't be ASCII art. The shortest code in bytes wins, *however* include directives for libraries shouldn't be included in the byte count, and you may use graphics libraries or other libraries written for your language of choice if they were written before the posting. Please include an image of the output of your program. [![enter image description here](https://i.stack.imgur.com/0W85S.png)](https://i.stack.imgur.com/0W85S.png) **Skip this paragraph if you watched the video:** For those of you who decided not to watch the video, the first 12 iterations of the dragon curve are shown below. For the purposes of this task, a dragon curve is a curve generated by the following rule: take the end-point of the current curve, create a second curve rotated 90 degrees around that end-point so that the end-point of the original curve is the starting point of the new curve, and join the two curves into a single curve where they meet. In the images shown below, each new iteration is generated by rotating the previous iteration 90 degrees clock-wise around the end-point each iteration. When the curve is displayed on the screen, it's not obvious which end counts as the "end-point", however when the curve is stored as a array of points, it's easy to define the "end-point" as the last point in the array. Ascii art is appreciated, but not accepted: This is graphical output, not ascii-art. [Answer] ## Python 2/3, ~~169~~ ~~167~~ ~~150~~ ~~111~~ ~~98~~ 78 Bytes *Note that the import is not included in the byte count, according to the challenge specs.* Thanks to @AlexHall for saving 39(!) bytes and @nedla2004 for another 13 ``` from turtle import* o=[90] for z in o*9:o+=[90]+[-x for x in o[::-1]] fd(5) for i in o:rt(i);fd(5) ``` Starts by generating a list or right (90) and left (-90) turns, then goes through the list and moves the turtle. Generated Output: [![enter image description here](https://i.stack.imgur.com/tcDDZ.png)](https://i.stack.imgur.com/tcDDZ.png) EDIT: If this is too boring too watch, add `speed(0)` right before the first `fd(5)`. It will run the same, except the turtle will move much faster. [Answer] **x86, MSDOS, 16 bytes** I wrote this a while ago, to my knowledge the smallest routine for producing a dragon fractal. It uses no real iterations, rather plots every contained discrete pixel inside the fractal directly, showing the *final* image. It's included with many other tiny productions in [this pack](http://www.pouet.net/prod.php?which=68474). The 16 byte version was the end of my effort to get the dragon fractal as small as possible, starting 2014 with [this 32 byte production](http://www.pouet.net/prod.php?which=63522). Hex ``` 14 10 19 CA D1 FA 10 DE 01 D1 CD 10 B4 0C EB F0 ``` Code ``` S: adc al,0x10 sbb dx,cx sar dx,0x01 adc dh,bl add cx,dx int 0x10 mov ah,0x0C jmp short S ``` [![screenshot](https://i.stack.imgur.com/vcQ2n.png)](https://i.stack.imgur.com/vcQ2n.png) [Answer] # Logo, 43 bytes ``` for[i 1 512][fd 9 lt :i/(bitand :i -:i)*90] ``` Try with interpreter at <http://www.calormen.com/jslogo/#> This uses the same principle as my [previous ASCII art answer](https://codegolf.stackexchange.com/a/53064/15599) and the formula on at [wikipedia](https://en.wikipedia.org/wiki/Dragon_curve) except I reversed the direction to match the image in the question: > > First, express n in the form `k*(2^m)` where k is an odd number. The direction of the nth turn is determined by k mod 4 i.e. the remainder left when k is divided by 4. If k mod 4 is 1 then the nth turn is ~~R~~ L; if k mod 4 is 3 then the nth turn is ~~L~~ R > > > `bitand :i -:i` finds the least significant bit of `i`. We divide `i` by this to shitft `i` right the required amount, giving the required odd number `k`. There is no need to distinguish between left and right turns; we just turn left by `k*90` degrees and rely on the fact that rotation is a modulo 360 operaton to perform the modulo for us. **Output** use `ht` to hide turtle if required. [![enter image description here](https://i.stack.imgur.com/Lf0jP.png)](https://i.stack.imgur.com/Lf0jP.png) **Output (modified)** The following shows how the curve is a single strand. ``` bk 6 for[i 1 512][fd 6 rt :i/(bitand :i -:i)%4*45-90 fd 3 rt :i/(bitand :i -:i)%4*45-90] ``` [![enter image description here](https://i.stack.imgur.com/g2pfr.png)](https://i.stack.imgur.com/g2pfr.png) [Answer] # Underload, 196 bytes ``` ()()(<svg width="99" height="147">)S(<g transform="translate):S((33,33)">)S((3,0)rotate)*a(*a(~*)*~("><path d="M0h3" stroke="#"/>)~*a(*)**:(-90)a~^~(90)a~^)*::*:**:*^S(</g>)(:*)::*:**:*^S(</svg>)S ``` I thought it might be interesting to try this challenge in a low-powered esolang; Underload does fairly well for a language with such a low number of commands. The output is an SVG file with very heavily nested tags, and some golfing shortcuts. So far, I haven't found a browser that can display it (Firefox hangs for several minutes trying to load it, and both Firefox and Chromium give a blank screen). Most image processing programs can't load it either (making it hard to convert to another format), but I managed to load it in the image viewer Eye of Gnome (which is part of the default install on Ubuntu). So I took a screenshot of the image so that you can see it (the actual image has a transparent background, but you can't really screenshot transparent): [![Screenshot of a dragon curve in Underload](https://i.stack.imgur.com/CTfsD.png)](https://i.stack.imgur.com/CTfsD.png) We need to specify the image size explicitly. Picking an appropriate orientation for the image, drawing everything at the minimum legal size, and doing the minimum number of iterations specified by the challenge, gives us an image that *just* fits into 99 pixels wide, saving a byte. It's nice when things work out like that. The general algorithm used for drawing the image is to maintain two variables (Underload doesn't name variables, but I thought of them as *x* and *y*), both initially empty. Then we repeatedly replace (*x*, *y*) with (*x*, turn left and move forward, *y*) and (*x*, turn right and move forward, *y*). After ten iterations, both *x* and *y* hold a nine-iteration dragon curve. There are a few micro-optimizations and Underload-specific tricks, too. In order to avoid too much messing around with the top of the stack, each loop iteration, we start by combining *x* and *y* into the function "return the string created by concatenating: *x*, a turn instruction, the function argument, a move-forward instruction, and *y*." This function only takes up one space on the stack, so we can duplicate it, call it with `-90` as an argument, swap the return value under the duplicate, and call it with `90` as an argument, to get hold of new values for *x* and *y* without ever needing to touch more than the top two elements of the stack (which are by far the most commonly accessible). This function is code-generated at runtime. The generator itself is also code-generated at runtime, in order to allow it to reuse the string `<g transform="translate` that's also used to set the origin of the image. We generate all the open tags first, and then because all the close tags are just `</g>`, we can output 1024 close tags via simply repeating the string, without worrying about matching them to the open tags. (Writing numbers efficiently in Underload is an interesting problem in its own right; `(:*)::*:**:*` is probably the most efficient way to write 1024, though, translating to "2 to the power of (1 + 2×2) × 2". Underload doesn't have any graphics libraries, so I produce SVG using a combination of drawing lines in a fixed position, and rotating the image around a given point; instead of turning the pen, we turn the paper. The idea is that by drawing a line, rotating the entire image, drawing another line, rotating the image again, etc., we can effectively simulate turtle graphics without having to do any arithmetic or use any graphics libraries, as all the lines are drawn in the same location. Of course, that means that we have some very heavily nested rotate-the-image tags, which confuses many SVG viewers. Styling the image would count against the byte count, so I needed to give the minimum styling needed to display the image. This turns out to be `stroke="#"`, which more or less translates as "the line needs to be some color"; this seems to be expanded to drawing it in black. (Normally you'd specify the color as, say, "#000".) The background is transparent by default. We don't specify a stroke width, but the choice picked by Eye of Gnome leaves everything visible. Many Underload interpreters struggle with this program, e.g. the one on Try It Online crashes, because it generates some very large strings internally. [The original online Underload interpreter](http://esoteric.voxelperfect.net/files/underload/underload.html) works, though. (Interestingly, the very first interpreter was online, so the language was usable online before it was usable offline.) Something I'm slightly uneasy about is that there only seem to be 1023 line segments here, and we'd expect 1024. It could be that one of the segments at the end isn't being drawn with this algorithm (it'd be drawn on the next iteration instead). If that's disqualifying, it may be possible to adapt the program, but it might well end up considerably longer. (It's not like this challenge is going to win the competition anyway; there are already several shorter entries.) [Answer] # [LindenMASM](https://github.com/kade-robertson/pylasma), 51 Bytes LindenMASM was a language I created for a challenge a while ago that will forever live in the Sandbox. It makes use of the concept of [Lindenmayer systems](https://en.wikipedia.org/wiki/L-system) to draw things like Dragon curves, fractal plants, Sierpinski triangles, etc. The source code is as follows: ``` STT AXI FX INC 9 SET F 0 RPL X X+YF+ RPL Y -FX-Y END ``` To set this up for `n = 6` for example: ``` STT AXI FX INC 6 SET F 0 RPL X X+YF+ RPL Y -FX-Y END ``` This produces the following image via Python 3's `turtle`: [![6 generations](https://i.stack.imgur.com/6igZ9.png)](https://i.stack.imgur.com/6igZ9.png) There may be a slight numbering difference for iterations, as in the Lindenmayer system the first iteration is a single line. Here's what it looks like for `n = 10`: [![10 generations](https://i.stack.imgur.com/jAROs.png)](https://i.stack.imgur.com/jAROs.png) Just for fun, here's what it looks like with 15 generations (with an added instruction `MOV 2` to make it a bit smaller): [![15 generations](https://i.stack.imgur.com/Mn6GZ.png)](https://i.stack.imgur.com/Mn6GZ.png) Once you get up to 20 generations (with `MOV 0.5`) you can't really see the lines anymore, and it takes a LOT of steps to create (pairs of `+-` and `-+` are not optimized out). Here's what you get: [![20 generations](https://i.stack.imgur.com/dviUy.png)](https://i.stack.imgur.com/dviUy.png) *Note that the current interpreter may present graphical issues for smaller amounts of generations, i.e. possibly not drawing to the screen. Unfortunately when this interpreter was created there were no issues, a possible change in Python 3 could have caused this or it could just be my system* [Answer] # [MATL](https://github.com/lmendo/MATL), 26 bytes ``` 0J1_h9:"tPJ*h]hYsXG15Y01ZG ``` If different scales in the two axes are accepted, the code can be reduced to 19 bytes: ``` 0J1_h9:"tPJ*h]hYsXG ``` The figures below correspond to the equal-scale (26-byte) version. The code above produces the 9-th (0-based) iteration, that is, the tenth image in the challenge: [![enter image description here](https://i.stack.imgur.com/Cwf31.png)](https://i.stack.imgur.com/Cwf31.png) For other values change the `9` in the code, or replace it by `i` to take the number as user input. For example, the result for `13` is: [![enter image description here](https://i.stack.imgur.com/MkDCY.png)](https://i.stack.imgur.com/MkDCY.png) ### Explanation This uses a loop to gradually build an array of the *steps* followed by the curve in the complex plane. For example, the first two steps are `1j` (up) and `-1` (left). In each iteration, the array of steps so far is copied. The copy of the array is *reversed*, *multiplied* by `1j` (to rotate 90 degrees), and *concatenated* to the original. After the loop, a *cumulative sum* of the steps gives the actual points, which are then plotted in the complex plane. ``` 0 % Push 0 J1_h % Push array [1j, -1]. This defines the first two steps 9: % Push [1, 2, ..., 9] " % For each t % Duplicate the array of steps so far P % Reverse J* % Multiply by 1j h % Concatenate horizontally to previous steps ] % End h % Concatenate with the initial 0 Ys % Cumulative sum XG % Plot. Complex numbers are plotted with real and imag as x and y 15Y0 % Push string 'equal' 1ZG % Set equal scale in the two axes ``` [Answer] # Mathematica 86 bytes ``` {1,-1} r=Reverse;Graphics@Line@Nest[Join[l=Last@#;h=#-l&/@#,r[r@#%&/@h]]&,{{0,0},%},9] ``` How it works: `{1,-1}` Outputs `{1,-1}`. It basically "pushes it to the stack". This value can be recalled with `%`. `r=Reverse` basically just renames the Reverse function because I use it twice in the code. The `Graphics@Line@` just takes a list of points and draws a line connecting them. The real meat of the problem happens in this code segment: `Nest[Join[l=Last@#;h=#-l&/@#,r[r@#%&/@h]]&,{{0,0},%},9]`. Lemme tell you - that segment is complicated as f\*\*\*\*\*\*ck. Here's what `Nest` does: `Nest[f,x,9]`outputs the result of calling `f[f[f[f[f[f[f[f[f[x]]]]]]]]]`. In my code, this first argument `f` is: `Join[l=Last@#;h=#-l&/@#,r[r@#%&/@h]]&`, the second argument `x` is `{{0,0},%}` (which evaluates to `{{0,0},{1,-1}}`), and the third argument is `n`, which is just 9 (which will just apply the first argument to the second argument 9 times). The most complex part of all is this first argument: `Join[l=Last@#;h=#-l&/@#,r[r@#%&/@h]]&`, which is a giant mess of almost pure syntactic sugar. I was *really* abusing mathematica's syntactic sugar for this one. That line of code represents mathematica's version of an anonymous function, except to shorten things I actually defined two separate anonymous functions within that anonymous function. Yep, that's legal, folks. Let's break it down. `Join` takes two arguments. The first is `l=Last@#;h=#-l&/@#`, and the second is `r[r@#%&/@h]`. **The first argument of Join:** Inside the "main" anonymous function, `#` is a list of all the points at the current iteration in the curve. So `l=Last@#;` means "Take the point in the list of points you recieved as input, and assign that point to the variable `l`. The next segment, `h=#-l&/@#`, is a little more complex. It means "You have a function. This function takes a point as input, subtracts `l` from it, and returns the result. Now, apply that function to every element in the list of points you received as input to generate a list of shifted points, and assign that new list to the variable `h`. **The second argument of Join:** `r[r@#%&/@h]` has literally the most complex syntax I've ever written. I can't believe any code segment could contain something like `@#%&/@` - it looks like I'm cursing like a cartoon character in the middle of a program! But it's possible to break it down. Remember - `r[x]` takes a list of points and returns that list in reverse order. `r@#%&` is an anonymous function that reverses it's input, then multiplies it by the value storied in `%` (which is `{1,-1}`), and returns the result. Basically it rotates it's input 90 degrees, but in code as short as I could possibly write. Then `r@#%&/@h` means "Output a new list that is every point in `h` rotated 90 degrees." So overall, `Join[l=Last@#;h=#-l&/@#,r[r@#*%&/@h]]&` is a function that takes a list of points as an input, and adds on that same list of points rotated 90 degrees to get the next iteration of the curve. This is repeated 9 times to get the dragon curve. Then it's the resulting list of points is drawn to the screen as a line. And the output: [![enter image description here](https://i.stack.imgur.com/r6vjg.png)](https://i.stack.imgur.com/r6vjg.png) [Answer] # Python 2, 43 bytes This answer is 43 bytes not including the import statement and it's largely based on [Level River St's Logo answer](https://codegolf.stackexchange.com/a/100602/47581) and their use of `i/(i&-i)` in their code. [Try it online at trinket.io](https://trinket.io/python/56979696a6) ``` from turtle import* for i in range(1,513):fd(9);rt(90*i/(i&-i)) ``` Here is a picture of the output. [![enter image description here](https://i.stack.imgur.com/pO2PX.png)](https://i.stack.imgur.com/pO2PX.png) [Answer] # Mathematica, ~~56~~ 55 bytes ``` Graphics@Line@AnglePath[Pi/2JacobiSymbol[-1,Range@512]] ``` [![enter image description here](https://i.stack.imgur.com/Nrrmi.jpg)](https://i.stack.imgur.com/Nrrmi.jpg) Explanation: [OEIS A034947](http://oeis.org/A034947) Just for fun, here is a colored version of the 19th iteration. [![enter image description here](https://i.stack.imgur.com/1550R.png)](https://i.stack.imgur.com/1550R.png) [Answer] # HTML + JavaScript, 182 ``` <canvas id=C></canvas><script>c=C.getContext("2d") C.width=C.height=400 s=n=9 x=y=200 for(i=d=0;i<=1<<n;d+=++i/(i&-i)) c.lineTo(x,y), d&1?y+=d&2?s:-s:x+=d&2?-s:s c.stroke()</script> ``` [Answer] ## Mathematica, 63 bytes Using `AnglePath` ``` Graphics@Line@AnglePath[Pi/2Nest[Join[#,{1},-Reverse@#]&,{},9]] ``` [![Nine iterations](https://i.stack.imgur.com/bT3OF.png)](https://i.stack.imgur.com/bT3OF.png) [Answer] # Haskell + diagrams, 179 bytes ``` import Diagrams.Prelude import Diagrams.Backend.SVG d 1=hrule 1<>vrule 1 d n=d(n-1)<>d(n-1)#reverseTrail#rotateBy(1/4) main=renderSVG"d"(mkWidth 99)$strokeT(d 9::Trail V2 Double) ``` Output is a 99 pixels wide svg file with transparent background (an image 9 pixels wide would have a stroke too thick to recoqnize anything). Here it is rescaled and composed over a white background: [![Dragon number nine](https://i.stack.imgur.com/IBeEP.png)](https://i.stack.imgur.com/IBeEP.png) [Answer] # [tosh](http://tosh.tjvr.org), 518 bytes tosh is [Scratch](https://scratch.mit.edu), but with text instead of blocks. At 518 bytes, this answer is probably even worse than Java. This answer uses the same logic as [@Theo's Python answer](https://codegolf.stackexchange.com/a/100566/46900), but with strings of "L" and "R" instead of numbers, as Scratch's (and thus tosh's) list capabilities are awful. You can run it as a Scratch project [here](https://scratch.mit.edu/projects/132243830/). (tosh compiles to Scratch projects) ``` when flag clicked set path to "R" go to x: -50 y: 100 point in direction 90 pen down set pen size to 2 clear repeat 9 set path copy to path set path to join (path) "R" set i to length of path copy repeat length of path copy if letter i of path copy = "R" then set path to join (path) "L" else set path to join (path) "R" end change i by -1 end end set i to 0 repeat length of path change i by 1 if letter i of path = "R" then turn cw 90 degrees else turn ccw 90 degrees end move 7 steps end ``` ## Explanation: ``` when flag clicked set path to "R" go to x: -50 y: 100 point in direction 90 pen down set pen size to 2 clear ``` This first part makes the program run when the green flag is clicked (`when flag clicked`), sets the path variable to "R", and gets the sprite and stage in the proper state to be ready to draw. ``` repeat 9 set path copy to path set path to join (path) "R" set i to length of path copy repeat length of path copy if letter i of path copy = "R" then set path to join (path) "L" else set path to join (path) "R" end change i by -1 end end ``` Now we get to the path generation code. It uses the same logic as [@Theo's Python answer](https://codegolf.stackexchange.com/a/100566/46900), except with strings of "R" and "L" instead of numbers, and we use nested loops instead of list comprehensions. ``` set i to 0 repeat length of path change i by 1 if letter i of path = "R" then turn cw 90 degrees else turn ccw 90 degrees end move 7 steps end ``` Finally, we draw the path by going through each letter of the path variable and turning left or right depending on the letter. ]
[Question] [ Given two *non empty* lists of integers, your submission should calculate and return the *discrete convolution* of the two. Interestingly, if you consider the list elements as coefficients of polynomials, the convolution of the two lists represents the coefficients of the product of the two polynomials. ### Definition Given the lists `A=[a(0),a(1),a(2),...,a(n)]` and `B=[b(0),b(1),b(2),...,b(m)]` (setting `a(k)=0 for k<0 and k>n` and `b(k)=0 for k<0 and k>m`) then the convolution of the two is defined as `A*B=[c(0),c(1),...,c(m+n)]` where `c(k) = sum [ a(x)*b(y) for all integers x y such that x+y=k]` ### Rules * Any convenient input and output formatting for your language is allowed. * Built-ins for convolution, creating convolution matrices, correlation and polynomial multiplication are not allowed. ### Examples ``` [1,1]*[1] = [1,1] [1,1]*[1,1] = [1,2,1] [1,1]*[1,2,1] = [1,3,3,1] [1,1]*[1,3,3,1] = [1,4,6,4,1] [1,1]*[1,4,6,4,1] = [1,5,10,10,5,1] [1,-1]*[1,1,1,1,1] = [1,0,0,0,0,-1] [80085,1337]*[-24319,406] = [-1947587115,7,542822] ``` [Answer] # J, ~~10~~ 8 bytes ``` [:+//.*/ ``` Usage: ``` ppc =: [:+//.*/ NB. polynomial product coefficients 80085 1337 ppc _24319 406 _1947587115 7 542822 ``` Description: The program takes takes two lists, makes a multiplication table, then adds the numbers on the positive diagonals. [Answer] # [MATL](https://github.com/lmendo/MATL), 19 bytes ``` PiYdt"TF2&YStpsw]xx ``` [**Try it online!**](http://matl.tryitonline.net/#code=UGlZZHQiVEYyJllTdHBzd114eA&input=WzEsMV0KWzEsNCw2LDQsMV0) ### Explanation This builds a block-diagonal matrix with the two inputs, reversing the first. For example, with inputs `[1 4 3 5]`, `[1 3 2]` the matrix is ``` [ 5 3 4 1 0 0 0 0 0 0 0 1 3 2 ] ``` Each entry of the convolution is obtained by shifting the first row one position to the right, computing the product of each column, and summing all results. In principle, the shifting should be done padding with zeros from the left. Equivalently, *circular* shifting can be used, because the matrix contains zeros at the appropriate entries. For example, the first result is obtained from the shifted matrix ``` [ 0 5 3 4 1 0 0 0 0 0 0 1 3 2 ] ``` and is thus `1*1 == 1`. The second is obtained from ``` [ 0 0 5 3 4 1 0 0 0 0 0 1 3 2 ] ``` and is thus `4*1+1*3 == 7`, etc. This must be done `m+n-1` times, where `m` and `n` are the input lengths. The code uses a loop with `m+n` iterations (which saves some bytes) and discards the last result. ``` P % Take first input (numeric vactor) implicitly and reverse it i % Take second input (numeric vactor) Yd % Build diagonal matrix with the two vectors t % Duplicate " % For each column of the matrix TF2&YS % Circularly shift first row 1 step to the right t % Duplicate p % Product of each column s % Sum all those products w % Swap top two elements in stack. The shifted matrix is left on top ] % End for xx % Delete matrix and last result. Implicitly display ``` [Answer] # Haskell, ~~55~~ 49 bytes ``` (a:b)#c=zipWith(+)(0:b#c)$map(a*)c++[]#b _#c=0<$c ``` Defines an operator `#`. [Answer] # Matlab / Octave, 41 bytes ``` @(p,q)poly([roots(p);roots(q)])*p(1)*q(1) ``` This defines an anonymous function. To call it, assign it to a variable or use `ans`. [**Try it here**](http://ideone.com/mjDuII). ### Explanation This exploits the facts that * The (possibly repeated) roots characterize a polynomial up to its leading coefficient. * The product of two polynomials has the roots of both. The code computes the roots of the two polynomials (function `roots`) and concatenates them into a column array. From that it obtains the coefficients of the product polynomial with a leading `1` (function `poly`). Finally the result is multiplied by the leading coefficients of the two polynomials. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~18~~ 17 bytes ### Code ``` 0Ev²¹g<Å0«y*NFÁ}+ ``` ### Explanation **The theory behind:** To find the convolution, let's take the example `[1, 2, 3]`, `[3, 4, 5]`. We position the values of the first array upside down and vertically, like this: ``` 3 2 1 ``` Now, we place the second array like a ladder and multiply it by : ``` 3 × [3 4 5] 2 × [3 4 5] 1 × [3 4 5] ``` Resulting into: ``` 9 12 15 6 8 10 3 4 5 ``` Then, we add them up, resulting into: ``` 9 12 15 6 8 10 3 4 5 3 10 22 22 15 ``` So, the convolution is `[3, 10, 22, 22, 15]`. **The code itself:** We are going to do this step by step using the `[1, 2, 3]`, `[3, 4, 5]` as the test case. ``` 0Ev²¹g<Å0«y*NFÁ}+ ``` We first push `0` and then we `E`valuate the first input array. We map over each element using `v`. So, for each element, we push the second array with `²` and then the length of the first array using `¹g` and decrease this by 1 (with `<`). We convert this into a **list of zeros** with **(length 1st array - 1)** zeros, using `Å0` and append this to our list. Our stack now looks like this for the first item in the input list: ``` [3, 4, 5, 0, 0] ``` We multiply this array with the current item, done with `y*`. After that, we push `N`, which indicates the index of the current item (zero-indexed) and rotate the array that many times to the right using `FÁ}`. Finally, we add this to our initial value (`0`). So, what basically is done is the following: ``` [0, 0, 9, 12, 15] + [0, 6, 8, 10, 0] + [3, 4, 5, 0, 0] = [3, 10, 22, 22, 15] ``` Which is then implicitly printed. Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=MEV2wrLCuWc8w4Uwwqt5Kk5Gw4F9Kw&input=WzgwMDg1LCAxMzM3XQpbLTI0MzE5LCA0MDZd). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 0;+ ×'Ṛç/ ``` [Try it online!](http://jelly.tryitonline.net/#code=MDsrCsOXJ-G5msOnLw&input=&args=WzgwMDg1LDEzMzdd+Wy0yNDMxOSw0MDZd) or [verify all test cases](http://jelly.tryitonline.net/#code=MDsrCsOXJ-G5msOnLwrDpyJH&input=&args=WzEsMV0sIFsxLDFdLCBbMSwxXSwgWzEsMV0sIFsxLDFdLCBbMSwtMV0sIFs4MDA4NSwxMzM3XQ+WzFdLCBbMSwxXSwgWzEsMiwxXSwgWzEsMywzLDFdLCBbMSw0LDYsNCwxXSwgWzEsMSwxLDEsMV0sIFstMjQzMTksNDA2XQ). ### How it works ``` ×'Ṛç/ Main link. Arguments: p, q (lists) ×' Spawned multiplication; multiply each item of p with each item of q. Ṛ Reverse the rows of the result. ç/ Reduce the rows by the helper link. 0;+ Helper link. Arguments: p, q (lists) 0; Prepend a 0 to p. + Perform vectorized addition of the result and q. ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 48 bytes ``` @(p,q)ifft(fft([p q*0]).*fft([q p*0]))(1:end-1) ``` [**Try it here**](http://ideone.com/To0xFl). ### Explanation Discrete convolution corresponds to multiplication of the (discrete-time) Fourier transforms. So one way to multiply the polynomials would be transform them, multiply the transformed sequences, and transform back. If the [discrete Fourier transform (DFT)](https://en.wikipedia.org/wiki/Discrete_Fourier_transform) is used instead of the Fourier transform, the result is the [*circular* convolution](https://en.wikipedia.org/wiki/Circular_convolution) of the original sequences of polynomial coefficients. The code follows this route. To make circular convolution equal to standard convolution, the sequences are zero-padded and the result is trimmed. [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` mΣ∂Ṫ* ``` [Try it online!](https://tio.run/##yygtzv7/P/fc4kcdTQ93rtL6//9/tKGOrmEsiILCWAA "Husk – Try It Online") **Note:** When supplying the zero-polynomial/empty list, you need to specify its type (ie. `[]:LN`)! ### Explanation ``` mΣ∂Ṫ* -- implicit inputs xs ys, for example: [1,-1] [1,1] Ṫ* -- compute the outer product xsᵀ·ys: [[1,1],[-1,-1]] ∂ -- diagonals: [[1],[1,-1],[-1]] mΣ -- map sum: [1,0,1] ``` [Answer] # Matlab, 33 bytes ``` @(x,y)sum(spdiags(flip(x').*y),1) ``` [Try it online!](https://tio.run/##DYnLDkAwEADvfsSurKar9TpI/If0IKhIiCZF@PrqYeYwc07X@CzBdkKI0MNLH/r7AO/mbVw92H1z8KYosg@JMVgYmNhQtKYqwgaTGBspm5JYqTq@vNCKW9KyMhh@ "Octave – Try It Online") Creates a matrix of all element-wise products of the inputs, then sums along the diagonals. The `,1` at the end forces matlab to sum along the correct direction when one of the input vectors has length 1. In Octave `spdiags` does not work for vectors, resulting in an error when one of the inputs has length 1. Matlab 2016b or newer is required for the explicit expansion of the element-wise product. [Answer] # [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 6 bytes `##C*µS` reads two lists from standard input, returns a list [online interpreter](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=IyNDKrVT&in=WzEsMV0gWzEsNCw2LDQsMV0=) ## Explanation ``` ## ; read two lists from standard input C ; go through all diagonals of the Cartesian product * ; multiplying the elements from the two lists µS ; sum up the diagonals ; implicit output ``` [Answer] # Ruby, 83 bytes Almost directly pulled out of [an answer I did earlier regarding expanding roots into a polynomial](https://codegolf.stackexchange.com/questions/76218/expand-roots-into-a-polynomial/76268#76268). ``` ->a,b{q=a.map{|c|r=b.map{|e|e*c};b=[0]+b;r} q.pop.zip(*q).map{|e|(e-[p]).reduce:+}} ``` [Answer] # Python, 90 bytes ``` lambda p,q:[sum((p+k*[0])[i]*(q+k*[0])[k-i]for i in range(k+1))for k in range(len(p+q)-1)] ``` [Answer] ## JavaScript (ES6), 64 bytes ``` (a,b)=>a.map((n,i)=>b.map((m,j)=>r[j+=i]=m*n+(r[j]||0)),r=[])&&r ``` Returns the empty array if either input is empty. Based on my answer to [Polynomialception](https://codegolf.stackexchange.com/a/78582/17602). [Answer] # Julia, ~~62~~ 55 bytes ``` ~=endof p%q=[sum(diag(p*rot180(q'),-k))for k=1-~q:~p-1] ``` [Try it online!](http://julia.tryitonline.net/#code=ZihwLHEsZT1lbmRvZik9W3N1bShkaWFnKHAqcm90MTgwKHEnKSwtaykpZm9yIGs9MS1lKHEpOmUocCktMV0KCnByaW50bG4oZihbMSwxXSxbMV0pKQpwcmludGxuKGYoWzEsMV0sWzEsMV0pKQpwcmludGxuKGYoWzEsMV0sWzEsMiwxXSkpCnByaW50bG4oZihbMSwxXSxbMSwzLDMsMV0pKQpwcmludGxuKGYoWzEsMV0sWzEsNCw2LDQsMV0pKQpwcmludGxuKGYoWzEsLTFdLFsxLDEsMSwxLDFdKSkKcHJpbnRsbihmKFs4MDA4NSwxMzM3XSxbLTI0MzE5LDQwNl0pKQ&input=) [Answer] ## Clojure, 104 bytes ``` #(vals(apply merge-with +(sorted-map)(for[i(range(count %))j(range(count %2))]{(+ i j)(*(% i)(%2 j))}))) ``` Merging to `sorted-map` guarantees that values are returned in the correct order. I wish there were a few more test cases. [Answer] # [Mathematica](https://www.wolfram.com/wolframscript/), 28 bytes Definitely, Mathematica has built-in for *LinearConvolution (like Polynomial Multiplication) of 2 length-limited lists*. [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98ns7jEOT@vLD@nLDVaWUfZSKfaUEfXsFbHIFbtf1p0tYWBgYWpjoKhsbF5rY5Cta6RibGhpY6CiYFZbayCvn5AUWZeyX8A) ``` ListConvolve[#,#2,{1,-1},0]& ``` ]
[Question] [ # Input Your input in this challenge is a list of integer pairs. They represent the southwest corners of unit squares on the plane, and the list represents their union as a subset of the plane. For example, the list ``` [(0,0),(1,0),(0,1),(1,1),(2,1),(1,2),(2,2)] ``` represents the red-colored set in this picture: ![A domain](https://i.stack.imgur.com/cRDno.png) # Output Yor output is a list of integer quadruples, representing rectangular subsets of the plane. More explicitly, a quadruple `(x,y,w,h)` reperents a rectangle of width `w > 0` and height `h > 0` whose southwest corner is at `(x,y)`. The rectangles must form an exact covering of the input region, in the sense that each of the unit squares is a subset of some rectangle, each rectangle is a subset of the region, and two rectangles may overlap only at their borders. To forbid trivial solutions, the covering must not contain two rectangles that could be merged into a larger rectangle. For example, the list ``` [(0,0,2,1),(0,1,3,1),(1,2,2,1)] ``` represents the legal covering ![A legal covering](https://i.stack.imgur.com/vMJwl.png) of the above region, whereas the covering given by ``` [(0,0,2,2),(2,1,1,1),(1,2,1,1),(2,2,1,1)] ``` is illegal, since the neighboring 1-by-1 squares could be merged: ![An illegal covering](https://i.stack.imgur.com/NWV18.png) # Rules You can give a full program or a function. The precise formatting of the input and output is not important, within reason. The shortest byte count wins, and standard loopholes are disallowed. You are encouraged to provide an explanation of your algorithm, and some example outputs. # Test Cases A U-shaped region: ``` [(0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(1,0),(1,1),(1,2),(1,3),(1,4),(1,5),(2,0),(2,1),(3,0),(3,1),(4,0),(4,1),(4,2),(4,3),(4,4),(4,5),(5,0),(5,1),(5,2),(5,3),(5,4),(5,5)] ``` ![U-shape](https://i.stack.imgur.com/EMj6m.png) A large triangle: ``` [(0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(0,6),(0,7),(0,8),(0,9),(1,0),(1,1),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(1,8),(2,0),(2,1),(2,2),(2,3),(2,4),(2,5),(2,6),(2,7),(3,0),(3,1),(3,2),(3,3),(3,4),(3,5),(3,6),(4,0),(4,1),(4,2),(4,3),(4,4),(4,5),(5,0),(5,1),(5,2),(5,3),(5,4),(6,0),(6,1),(6,2),(6,3),(7,0),(7,1),(7,2),(8,0),(8,1),(9,0)] ``` ![Triangle](https://i.stack.imgur.com/TWekB.png) A square with holes: ``` [(0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(0,6),(0,7),(0,8),(1,0),(1,1),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(1,8),(1,9),(2,0),(2,1),(2,2),(2,3),(2,4),(2,5),(2,6),(2,7),(2,8),(2,9),(3,0),(3,1),(3,2),(3,4),(3,5),(3,6),(3,7),(3,8),(3,9),(4,0),(4,1),(4,2),(4,3),(4,4),(4,5),(4,6),(4,7),(4,8),(4,9),(5,0),(5,1),(5,2),(5,3),(5,4),(5,5),(5,7),(5,8),(5,9),(6,1),(6,2),(6,3),(6,5),(6,6),(6,7),(6,8),(6,9),(7,0),(7,1),(7,2),(7,3),(7,4),(7,5),(7,6),(7,7),(7,8),(7,9),(8,0),(8,1),(8,2),(8,3),(8,4),(8,5),(8,6),(8,7),(8,8),(8,9),(9,0),(9,1),(9,2),(9,3),(9,4),(9,5),(9,6),(9,7),(9,8),(9,9)] ``` ![Holed square](https://i.stack.imgur.com/iGP4b.png) Disconnected regions: ``` [(0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(0,6),(0,7),(0,8),(1,0),(1,1),(1,2),(1,3),(1,4),(1,6),(1,7),(1,8),(1,9),(2,1),(2,2),(2,3),(2,4),(2,5),(2,6),(2,7),(2,8),(2,9),(4,0),(4,1),(4,2),(4,4),(4,5),(4,6),(4,7),(4,8),(4,9),(5,0),(5,1),(5,2),(5,3),(5,4),(5,5),(5,6),(5,7),(5,8),(5,9),(6,0),(6,1),(6,2),(6,4),(6,5),(6,6),(6,7),(6,8),(6,9),(8,0),(8,1),(8,2),(8,3),(8,4),(8,5),(8,6),(8,7),(8,8),(8,9),(9,0),(9,1),(9,2),(9,3),(9,7),(9,8),(9,9),(10,0),(10,1),(10,2),(10,3),(10,4),(10,5),(10,6),(10,7),(10,8),(10,9)] ``` ![Disconnected](https://i.stack.imgur.com/VfQBG.png) # Verifier Use [this](http://pastebin.com/me55KLni) Python 2 program to verify your solution. It takes from STDIN a list of tuples (the input) and a list of quadruples (your output), separated by a comma. I also wrote [this](http://pastebin.com/CmLn4Md1) Python 2 program to generate the pictures, and you can use it too. It takes from STDIN a list of either tuples or quadruples, and produces a file named `out.png`. It requires the PIL library. You can change the size of the grid cells and the width of the gird lines too, if you want. [Answer] # Python - ~~272~~ ~~261~~ ~~258~~ ~~251~~ 224 I think I can golf this more. ~~I'm pretty sure this works, but I haven't finished testing it on all of the test cases yet.~~ I finished testing it. It works for all of the test cases. ``` a=sorted(input()) b=[] r=range for i in a: c=set(a)-set(b);w=h=1;x,y=i if i in b:continue while not{(x,y+h)}-c:h+=1 while all((x+w,y+j)in c for j in r(h)):w+=1 for j in r(w): for k in r(h):b+=(j+x,k+y), print x,y,w,h ``` ~~I'm working on adding images of the results.~~ Edit: Here are the results from the example and the test cases: ![Example output](https://i.stack.imgur.com/KXIcp.png) ![Test case 1 output](https://i.stack.imgur.com/C5tW5.png) ![Test case 2 output](https://i.stack.imgur.com/Bgx2J.png) ![Test case 3 output](https://i.stack.imgur.com/goQ9a.png) ![Test case 4 output](https://i.stack.imgur.com/k2j9d.png) I'm trying to write this in Perl, but I can't figure out how to get multidimensional arrays from stdin without a huge number of characters. Does anyone have any suggestions? [Answer] # Python: ~~196~~ ~~193~~ 182 character ``` def g(r): for p in r: for q in r: for h in 0,1: if p[h::2]==q[h::2]and p[1-h]+p[~h]==q[1-h]:p[~h]+=q[~h];r.remove(q);return g(r) return r f=lambda P:g([x+[1,1]for x in P]) ``` My first solution used the exact same algorithm as KSFT, therefore I experimented with other methods. First I do some preprocessing, I convert all points into small 1x1 rectangles `{x+(1,1)for x in P}`. With these rectangles, I call the function `g`. `g` iterates over each combination of rectangles. If it finds 2 rectangles, that can be merged into a bigger one, it deletes both and append the new one. Afterwards it calls itself with the new set of rectangles. ## Usage ``` f([[0,0],[1,0],[0,1],[1,1],[2,1],[1,2],[2,2]]) ``` ## Results Here are the visualization of the results. Note that they may be a bit different in the current version. The idea is though, that there is no kind of noticeable pattern. A U-shaped region: ![](https://i.stack.imgur.com/Rhd2X.jpg) A large triangle ![](https://i.stack.imgur.com/flFn0.jpg) A square with holes: ![](https://i.stack.imgur.com/3Jrrm.jpg) Disconnected regions: ![](https://i.stack.imgur.com/lFBlZ.jpg) ## Just for fun: Pyth: ~~73~~ 69 character ``` D!HFGHFZHV2I&q%2>GN%2>ZNqs%2>G-1N@Z-1N X-3NG@Z-3NR!-H]Z)))RH!m+d*2]1Q ``` ~~Works only in the offline version.~~ Bug in the online version is fixed now. Try it here: [Pyth Compiler/Executor](https://pyth.herokuapp.com/). Expects a list of lists, not a list of tuples. edit: Used an idea from @edc65: Instead of deleting both rectangles and creating a new one, I manipulate one and only delete one. In the Python solution I could get ride of the sets and the tuple-list-tuple casts. -11 chars in Python / -4 chars in Pyth [Answer] # Python 2, 139 The program accepts lists of ordered pairs surrounded by curly braces on standard input. E.g., `{(0,0),(1,0),(0,1),(1,1),(2,1),(1,2),(2,2)}` ``` s=input() while s:x,y=min(s);w=h=0;exec"while(x+w,y)in s:w+=1\nwhile%s<=s:s-=%s;h+=1"%(("{(X,y+h)for X in range(x,x+w)}",)*2);print x,y,w,h ``` It's often irritating (not only in golf) that Python does not allow an assignment inside of a loop test. To work around this, I used string formatting operations. [Answer] # Mathematica - ~~315 285~~ 267 bytes ``` f=(r={};For[m=MemberQ;t=Table;s=Sort@#,s!={},For[{x,y,w,h}=#~Join~{1,1}&@@s;i=j=0,i<1||j<1,If[s~m~{x+w,y+a-1}~t~{a,h}==True~t~{h},w++,i++];If[s~m~{x+a-1,y+h}~t~{a,w}==True~t~{w},h++,j++]];s=s~Cases~_?(!m[Join@@t[{x+a,y+b}-1,{a,w},{b,h}],#]&);r~AppendTo~{x,y,w,h}];r)& ``` *With some help from @MartinBüttner.* Ungolfed: ``` f = ( rectangles = {}; For[squares = Sort[#], squares != {}, For[{x, y, w, h} = Join[squares[[1]], {1, 1}]; i = j = 0, i < 1 || j < 1, If[Table[MemberQ[squares, {x + w, y + a - 1}], {a, h}] == Table[True, {h}], w++, i++]; If[Table[MemberQ[squares, {x + a - 1, y + h}], {a, w}] == Table[True, {w}], h++, j++]; ]; squares = Cases[squares, _ ? (!MemberQ[Join@@Table[{x + a - 1, y + b - 1}, {a, w}, {b, h}], #] &)]; AppendTo[rectangles, {x, y, w, h}] ]; rectangles )& ``` Usage: ``` In: f @ {{0,0},{1,0},{0,1},{1,1},{2,1},{1,2},{2,2}} Out: {{0, 0, 2, 2}, {1, 2, 2, 1}, {2, 1, 1, 1}} ``` ![enter image description here](https://i.stack.imgur.com/VGJVg.png) # Test Cases **A U-shaped region** ![enter image description here](https://i.stack.imgur.com/96hNU.png) ``` {{0, 0, 6, 2}, {0, 2, 2, 4}, {4, 2, 2, 4}} ``` **A large triangle** ![enter image description here](https://i.stack.imgur.com/ioJwQ.png) ``` {{0, 0, 6, 5}, {0, 5, 3, 3}, {0, 8, 2, 1}, {0, 9, 1, 1}, {3, 5, 2, 1}, {3, 6, 1, 1}, {6, 0, 3, 2}, {6, 2, 2, 1}, {6, 3, 1, 1}, {9, 0, 1, 1}} ``` **A square with holes** ![enter image description here](https://i.stack.imgur.com/3tIzi.png) ``` {{0, 0, 6, 3}, {0, 3, 3, 6}, {1, 9, 9, 1}, {3, 4, 3, 2}, {3, 6, 2, 3}, {4, 3, 6, 1}, {5, 7, 5, 2}, {6, 1, 4, 2}, {6, 5, 4, 2}, {7, 0, 3, 1}, {7, 4, 3, 1}} ``` **Disconnected regions** ![enter image description here](https://i.stack.imgur.com/Y4vFd.png) ``` {{0, 0, 2, 5}, {0, 5, 1, 4}, {1, 6, 2, 4}, {2, 1, 1, 5}, {4, 0, 3, 3}, {4, 4, 3, 6}, {5, 3, 1, 1}, {8, 0, 3, 4}, {8, 4, 1, 6}, {9, 7, 2, 3}, {10, 4, 1, 3}} ``` [Answer] # Haskell, 158 ``` f[]=[] f s@((x,y):_)=(x,y,w-x,h-y):f[r|r@(a,b)<-s,a<x||a>=w||b<y||b>=h]where w=[i|i<-[x..],notElem(i,y)s]!!0;h=[i|i<-[y..],not$all(\x->elem(x,i)s)[x..w-1]]!!0 ``` test cases and images will be here shortly. Algorithm: Take the first square. Reach as far right without encountering a square not in the input. Then reach as far up as possible without having a square not on the input. We now have a rectangle without a missing square. Add it to the output, remove all of its squares from the input and call recursively. [Answer] # JavaScript (ES6) 148 ~~155 199~~ **Edit2** Some more tuning **Edit** Some golfing + rewrite using recursion. Did not expect such a reduction. Now it's a little difficult to follow, but the algorithm is the same. The algorithm is similar to @jakube answer. 1. Each point becomes a 1x1 square (preprocessing) 2. For each element, check if it can be merged with another Yes? First element grows, second element erased, start again at step 2 Else, proceed to next element ``` F=l=> (l.map(x=>x.push(1,1)),R=f=> l.some(u=> (l=l.filter(t=> [0,1].every(p=>u[p]-t[p]|u[p^=2]-t[p]|u[p^=3]-t[p]+u[p^=2]||!(f=u[p]+=t[p])) ),f) )?R():l )() ``` Test in snippet ``` F=l=>(l.map(x=>x.push(1,1)),R=f=>l.some(u=>(l=l.filter(t=>[0,1].every(p=>u[p]-t[p]|u[p^=2]-t[p]|u[p^=3]-t[p]+u[p^=2]||!(f=u[p]+=t[p]))),f))?R():l)() // Test MyCanvas.width= 600; MyCanvas.height = 220; var ctx = MyCanvas.getContext("2d"); ctx.fillStyle="#f23"; Draw=(x,y,f,l)=>l.forEach(p=>ctx.fillRect(x+p[0]*f,y+p[1]*f,p[2]*f-1||f-1,p[3]*f-1||f-1)); test=[ [[0,0],[1,0],[0,1],[1,1],[2,1],[1,2],[2,2]], [[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[1,0],[1,1],[1,2],[1,3],[1,4],[1,5],[2,0],[2,1],[3,0],[3,1],[4,0],[4,1],[4,2],[4,3],[4,4],[4,5],[5,0],[5,1],[5,2],[5,3],[5,4],[5,5]], [[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9],[1,0],[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[1,8],[2,0],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[3,0],[3,1],[3,2],[3,3],[3,4],[3,5],[3,6],[4,0],[4,1],[4,2],[4,3],[4,4],[4,5],[5,0],[5,1],[5,2],[5,3],[5,4],[6,0],[6,1],[6,2],[6,3],[7,0],[7,1],[7,2],[8,0],[8,1],[9,0]], [[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[1,0],[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[1,8],[1,9],[2,0],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[2,8],[2,9],[3,0],[3,1],[3,2],[3,4],[3,5],[3,6],[3,7],[3,8],[3,9],[4,0],[4,1],[4,2],[4,3],[4,4],[4,5],[4,6],[4,7],[4,8],[4,9],[5,0],[5,1],[5,2],[5,3],[5,4],[5,5],[5,7],[5,8],[5,9],[6,1],[6,2],[6,3],[6,5],[6,6],[6,7],[6,8],[6,9],[7,0],[7,1],[7,2],[7,3],[7,4],[7,5],[7,6],[7,7],[7,8],[7,9],[8,0],[8,1],[8,2],[8,3],[8,4],[8,5],[8,6],[8,7],[8,8],[8,9],[9,0],[9,1],[9,2],[9,3],[9,4],[9,5],[9,6],[9,7],[9,8],[9,9]], [[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[1,0],[1,1],[1,2],[1,3],[1,4],[1,6],[1,7],[1,8],[1,9],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[2,8],[2,9],[4,0],[4,1],[4,2],[4,4],[4,5],[4,6],[4,7],[4,8],[4,9],[5,0],[5,1],[5,2],[5,3],[5,4],[5,5],[5,6],[5,7],[5,8],[5,9],[6,0],[6,1],[6,2],[6,4],[6,5],[6,6],[6,7],[6,8],[6,9],[8,0],[8,1],[8,2],[8,3],[8,4],[8,5],[8,6],[8,7],[8,8],[8,9],[9,0],[9,1],[9,2],[9,3],[9,7],[9,8],[9,9],[10,0],[10,1],[10,2],[10,3],[10,4],[10,5],[10,6],[10,7],[10,8],[10,9]] ] Draw(0,0,10,test[0]),Draw(0,110,10,F(test[0])) Draw(50,0,10,test[1]),Draw(50,110,10,F(test[1])) Draw(130,0,10,test[2]),Draw(130,110,10,F(test[2])) Draw(250,0,10,test[3]),Draw(250,110,10,F(test[3])) Draw(370,0,10,test[4]),Draw(370,110,10,F(test[4])) ``` ``` <canvas id=MyCanvas></canvas> ``` [Answer] # Mathematica, ~~153 151 144 136~~ 133 ``` Sort[{##,1,1}&@@@Input[]]//.{a___,r:{x_,y_,__},b___,{X_,Y_,W_,H_},c___}/;r=={x,Y,X-x,H}||r=={X,y,W,Y-y}:>{a,r+Sign@{0,0,X-x,Y-y},b,c} ``` ### Example: Input: ``` {{0, 0}, {1, 0}, {0, 1}, {1, 1}, {2, 1}, {1, 2}, {2, 2}} ``` Output: ``` {{0, 0, 2, 2}, {1, 2, 2, 1}, {2, 1, 1, 1}} ``` ![enter image description here](https://i.stack.imgur.com/7WCfX.png) Input: ``` {{0, 0}, {0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, {0, 8}, {1, 0}, {1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 8}, {1, 9}, {2, 0}, {2, 1}, {2, 2}, {2, 3}, {2, 4}, {2, 5}, {2, 6}, {2, 7}, {2, 8}, {2, 9}, {3, 0}, {3, 1}, {3, 2}, {3, 4}, {3, 5}, {3, 6}, {3, 7}, {3, 8}, {3, 9}, {4, 0}, {4, 1}, {4, 2}, {4, 3}, {4, 4}, {4, 5}, {4, 6}, {4, 7}, {4, 8}, {4, 9}, {5, 0}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {5, 7}, {5, 8}, {5, 9}, {6, 1}, {6, 2}, {6, 3}, {6, 5}, {6, 6}, {6, 7}, {6, 8}, {6, 9}, {7, 0}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, {7, 8}, {7, 9}, {8, 0}, {8, 1}, {8, 2}, {8, 3}, {8, 4}, {8, 5}, {8, 6}, {8, 7}, {8, 8}, {8, 9}, {9, 0}, {9, 1}, {9, 2}, {9, 3}, {9, 4}, {9, 5}, {9, 6}, {9, 7}, {9, 8}, {9, 9}} ``` Output: ``` {{0, 0, 3, 9}, {1, 9, 9, 1}, {3, 0, 3, 3}, {3, 4, 1, 5}, {4, 3, 1, 6}, {5, 3, 1, 3}, {5, 7, 1, 2}, {6, 1, 1, 3}, {6, 5, 1, 4}, {7, 0, 3, 9}} ``` ![enter image description here](https://i.stack.imgur.com/SDhnT.png) ### Algorithm: Cover the region with unit squares, then merge them. ![enter image description here](https://i.stack.imgur.com/ztYjR.gif) ]
[Question] [ ...so this is a challenge to make me a tree. Produce a program or function called tree which takes a single integer argument, N and draws a Pythagorean Tree N levels deep, where level 0 is just the trunk. Each junction of the tree should place the vertex of the triangle at a random point on the perimeter (this point should be uniformly distributed over at least 5 equally spaced points, or uniformly over the whole semicircle). Optionally your tree may be 3d, be colourful, or be lit according to the time of day. However, this is code-golf, so the smallest file wins. EDIT: I'll shut the contest and accept the smallest answer when it's a week old [Answer] ## CFDG, 134 characters This one isn't exactly valid, because you cannot limit the recursion depth. But the problem just calls for a solution in [this one](http://www.contextfreeart.org/). :) ``` startshape t c(q)=cos(q/2)^2 d(q)=1+sin(q)/2 p=acos(-1) shape t{w=rand(p) SQUARE[x .5 .5]t[trans 0 1 c(w) d(w)]t[trans c(w) d(w) 1 1]} ``` The results look something like this ![enter image description here](https://i.stack.imgur.com/ATY6Y.png) For another 46 characters (**180 characters** in total), you can even colour it in: ``` startshape t c(q)=cos(q/2)^2 d(q)=1+sin(q)/2 p=acos(-1) shape t{w=rand(p) SQUARE[x .5 .5 h 25 sat 1 b .2]t[trans 0 1 c(w) d(w) b .08 .8 h 2.2]t[trans c(w) d(w) 1 1 b .08 .8 h 2.2]} ``` ![enter image description here](https://i.stack.imgur.com/4YLsb.png) [Answer] ## Mathematica, ~~246~~ ~~234~~ 221 characters ``` g[n_,s_:1]:={p=RandomReal[q=Pi/2],r=##~Rotate~(o={0,0})&,t=Translate}~With~If[n<0,{},Join[#~t~{0,s}&/@(#~r~p&)/@g[n-1,s*Cos@p],t[#,s{Cos@p^2,1+Sin[2p]/2}]&/@(r[#,p-q]&)/@g[n-1,s*Sin@p],{Rectangle[o,o+s]}]] f=Graphics@g@#& ``` This is certainly not the most elegant/shortest way to do this. Usage: `f[8]` ![enter image description here](https://i.stack.imgur.com/J8QbG.png) And here are example outputs for `f[6]` and `f[10]` respectively. ![enter image description here](https://i.stack.imgur.com/8ER8H.png) ![enter image description here](https://i.stack.imgur.com/910OS.png) Somewhat ungolfed: ``` g[n_, s_:1] := With[{p}, r = Rotate; t = Translate; p = RandomReal[q = Pi/2]; If[n < 0, {}, Join[ (t[#, {0, s}] &) /@ (r[#, p, {0, 0}] &) /@ g[n - 1, s*Cos[p]], (t[#, s {Cos[p]^2, 1 + Sin[2 p]/2}] &) /@ (r[#, p - q, {0, 0}] &) /@ g[n - 1, s*Sin[p]], {Rectangle[{0, 0}, {s, s}]} ] ] ] f = Graphics@g[#] & ``` [Answer] ## Mathematica, 122 characters ``` Graphics[Polygon/@ReIm@NestList[Join@@({##3}+Cos[t=Random[]Pi/2]E^(I t){I Tan@t(#2-{##}),{##}-#}&)@@@#&,{{0,1,1+I,I}},#]]& ``` [![enter image description here](https://i.stack.imgur.com/N56MK.png)](https://i.stack.imgur.com/N56MK.png) Ungolfed version: ``` Clear["`*"]; next=Compile[{{z,_Complex,1},t},{z[[4]]-E^(I t) (z[[1]]-z) Cos[t],z[[3]]+I E^(I t) (z[[2]]-z) Sin[t]},RuntimeAttributes->{Listable}]; n=15; list=ReIm@NestList[next[#,Random[]Pi/2]&,N@{{0,1,1+I,I}},n]; poly=MapIndexed[With[{i=Tr@#2},{ColorData["Rainbow",i/(n+1)],Polygon@Flatten[#,i-1]}]&,list]; Graphics[{Antialiasing->True,poly},PlotRange->{{-7,7},{-1,10}},ImageSize->Large,Background->Black] ``` [![enter image description here](https://i.stack.imgur.com/drxO4.gif)](https://i.stack.imgur.com/drxO4.gif) 3D version, refer to <https://mathematica.stackexchange.com/questions/213727/how-to-draw-a-pythagoras-tree-like-this/213827#213827>, render by POV-Ray [![enter image description here](https://i.stack.imgur.com/rMQpd.png)](https://i.stack.imgur.com/rMQpd.png) [Answer] # Coffeescript ~~377B~~ 352B I feel dirty writing coffeescript but I can't find a decent drawing package for python3 :-/ ``` Q=(n)->X=(D=document).body.appendChild(C=D.createElement('Canvas')).getContext('2d');C.width=C.height=400;M=Math;T=[[175,400,50,i=0]];S=M.sin;C=M.cos;while [x,y,l,a]=T[i++] X.save();X.translate x,y;X.rotate -a;X.fillRect 0,-l,l,l;X.restore();T.push [e=x-l*S(a),f=y-l*C(a),g=l*C(b=M.random()*M.PI/2),d=a+b],[e+g*C(d),f-g*S(d),l*S(b),d-M.PI/2] if i<2**n ``` # Javascript ~~393B~~ 385B Slightly prettier in javascript and I'm much happier with the for-loop but without the [x,y,z]=A syntax I just can't make it short enough to beat coffeescript ``` function Q(n){X=(D=document).body.appendChild(C=D.createElement('Canvas')).getContext('2d');C.width=C.height=600;M=Math;T=[[275,400,50,i=0]];while(A=T[i++]){X.save();X.translate(x=A[0],y=A[1]);X.rotate(-(a=A[3]));X.fillRect(0,-(l=A[2]),l,l);X.restore();S=M.sin;C=M.cos;i<M.pow(2,n)&&T.push([e=x-l*S(a),f=y-l*C(a),g=l*C(b=M.random()*M.PI/2),d=a+b],[e+g*C(d),f-g*S(d),l*S(b),d-M.PI/2])}} ``` Got to say I'm a bit galled this is almost twice as long as the mathematica solution :-/ see it in action: <http://jsfiddle.net/FK2NX/3/> [Answer] ## Postscript, ~~322~~ 270 **Edit:** It appears that `realtime` can't be used as proper random generator seed. Therefore, we'll use environment variable for this purpose and run the program like that: ``` gs -c 20 $RANDOM -f tree.ps ``` or ``` gswin32c -c 20 %RANDOM% -f tree.ps ``` Now our trees are less predictable. 14 bytes are added to total count. Other changes: 1) Program argument is now passed on command line. 2) No explicit iteration counter - stack size serves for this purpose (left branch rotation angle is stored on stack, to draw right branch, later). 3) There's no named variable for required depth - stack size is its offset, on stack. It's left there on exit, i.e. it is not consumed. ``` srand 250 99 translate 50 50 scale /f{ count dup index div dup 1 le{ 0 exch 0 setrgbcolor 0 0 1 1 rectfill 0 1 translate rand 5 mod 1 add 15 mul gsave dup rotate dup cos dup scale f grestore dup cos dup dup mul exch 2 index sin mul translate dup 90 sub rotate sin dup scale 1 f pop }{pop}ifelse }def f ``` I think it's pretty obvious - graphics state is prepared and `f` procedure is called recursively for each consecutive level of depth, twice - for 'left' and 'right' branches. Working with rectangle of `1x1` size (see original scale) saves the trouble of multiplying by side length. Angle of rotation of left branch is randomized - one of 5 random equally spaced divisions is used - I think it prevents possible ugly cases for uniform randomness. It might be slow for required depth of more than 20 or so. Next is golfed version, using ASCII-encoded binary tokens (see luser droog's answer from linked topic). Note, `cos`, `sin`, `rand` can not use this notation. ``` /${{<920>dup 1 4 3 roll put cvx exec}forall}def srand 250 99<AD>$ 50 50<8B>$/f{count(8X68)$ 1 le{0(>)$ 0<9D>$ 0 0 1 1<80>$ 0 1<AD>$ rand 5 mod 1 add 15<~CecsG2u~>$ cos<388B>$ f(M8)$ cos(88l>)$ 2(X)$ sin<6CAD38>$ 90<A988>$ sin<388B>$ 1 f pop}{pop}(U)$}def f ``` . ``` /${{<920>dup 1 4 3 roll put cvx exec}forall}def srand 250 99<AD>$ 50 50<8B>$ /f{ count(8X68)$ 1 le{ 0(>)$ 0<9D>$ 0 0 1 1<80>$ 0 1<AD>$ rand 5 mod 1 add 15 <~CecsG2u~>$ cos<388B>$ f (M8)$ cos(88l>)$ 2(X)$ sin<6CAD38>$ 90<A988>$ sin<388B>$ 1 f pop }{pop}(U)$ }def f ``` ![enter image description here](https://i.stack.imgur.com/peGsG.png) ]
[Question] [ *Inspired by [the problem with the same name](https://puzzling.stackexchange.com/questions/110490/largest-number-with-no-repeating-digit-pairs) on [Puzzling SE](https://puzzling.stackexchange.com) by our very own [Dmitry Kamenetsky](https://codegolf.stackexchange.com/users/92610/dmitry-kamenetsky).* You are to find the largest number that only uses every digit pair once, in a given base. For example, in ternary we have 2212011002. **Challenge:** Given a base from 2-10, output the largest number in that base with no repeating digit pairs. As long as the digits make the number, you may output with anything, or nothing, in between. Whether regularly delimited, or irregularly gibberished. You may also take input in any reasonable way. For example, you might take the base, the max digit, or an ordered list representing the digits available. For octal, this would mean `8`, `7` or `76543210`. If you feel like a challenge, you can take `octal` as input. I won't complain! Note that it need only work for bases from 2-10. Invisible points for doing alphanumeric bases like hex, but not at all required. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least bytes *per language* wins. #### Test Cases ``` Decimal: 10 99897969594939291908878685848382818077675747372717066564636261605545352515044342414033231302212011009 Octal: 8 77675747372717066564636261605545352515044342414033231302212011007 Quaternary: 4 33231302212011003 Ternary: 3 2212011002 Binary: 2 11001 ``` **Edit:** It used to be required for bases 1-10, with the desired output for unary being `00`. However, that was just an obfuscating edge case in some cases when people wanted to manipulate natural numbers. So unary has been dropped; only bases 2-10 required. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) (avoid a reverse by reordering to flatten first.) ``` Żj)ŻFṚ; ``` A monadic Link accepting the maximal digit (e.g. `7` for octal) that yields the digits as a list of integers. **[Try it online!](https://tio.run/##y0rNyan8///o7oc7Z2Vpgik36////5sDAA "Jelly – Try It Online")** ### How? Note that if `x` is the base then the least significant (rightmost) digit of `f(x)` is `x-1`, the previous digits are the same as all but the last digit of `f(x-1)` and the digits before that are: `[x-1, x-1, x-2, x-1, x-3, x-1, x-4, x-1, ..., 0]`, so... ``` Żj)ŻFṚ; - Link: non-negative integer, M (max digit = base - 1) ) - for each (x in [1..M]): Ż - zero-range -> [0,1,2,3,...,x] j - join (x) -> [0,x,1,x,2,x,3,x,...,x] Ż - prepend a zero -> [0,[0,1,1],[0,2,1,2,2],[0,3,1,3,2,3,3],...] F - flatten -> [0,0,1,1,0,2,1,2,2,0,3,1,3,2,3,3,...] Ṛ - reverse -> [...,3,3,2,3,1,3,0,2,2,1,2,0,1,1,0,0] ; - concatenate (M) -> [...,3,3,2,3,1,3,0,2,2,1,2,0,1,1,0,0,M] ``` [Answer] # [R](https://www.r-project.org/), ~~61~~ ~~52~~ 51 bytes *Edit: -9 bytes, and then -1 more byte, thanks to Robin Ryder* ``` for(i in 1:scan())F=c(i,rbind(i,i:1-1),F);c(F,F[1]) ``` [Try it online!](https://tio.run/##K/r/Py2/SCNTITNPwdCqODkxT0NT0802WSNTpygpMy8FSGdaGeoaauq4aVona7jpuEUbxmr@t@TiKsrVAAkllmgoxeQpaXKRYQyXOXWMMaaOMUbUMcbwPwA "R – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 11 bytes ``` Çò qZìÔ+´U Ç // Exclusive range [0..U) where U is the input, mapped to ò // inclusive range [0..Z] of each item Z qZ // joined together by Z. Ã¬Ô // Join and reverse the result, then +´U // append input minus one. ``` [Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=x/IgcVrDrNQrtFU=&input=OA==) [Answer] # JavaScript (ES6), 55 bytes ``` n=>(g=p=>p--?p+(h=q=>q--?[p]+q+h(q):'')(p)+g(p):~-n)(n) ``` [Try it online!](https://tio.run/##ZcjLCoMwEEbhfV/E@QkptboowqQPUroQL9Eik4mKy7566rZkczh8n/Zot26ddbcS@iGNnIQdeVZ2au1TDU0c2cXzX/o20UwU0RQFSGH8meZrBSRIXZAtLMN1CZ5GKm/A5Z8emdSZVJncMymB9AM "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ,€`€j0ṚF;Ø0; ``` [Try it online!](https://tio.run/##y0rNyan8/1/nUdOaBCDOMni4c5ab9eEZBtb///@3BAA "Jelly – Try It Online") Takes `base - 1` for input, so `7` for octal. Does not work for unary, as permitted. ``` ,€`€j0ṚF;Ø0; Main Link € For each x from 1 to N ` Apply the following to (x, x) rather than (x, N): € - For each y from 1 to x , - (y, x) j0 Join the list of sublists of pairs on 0 Ṛ Reverse the whole thing F Flatten ;Ø0 Append 2 zeroes ; Append the input ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ;€`Ṛ)ŻṚj0F; ``` [Try it online!](https://tio.run/##y0rNyan8/9/6UdOahIc7Z2ke3Q0kswzcrIFCDXMUdO0UHjXMtT7cfnTSw50zVLgsj@4@3A5UG/kfAA "Jelly – Try It Online") A monadic link taking the max digit and returning a list of digits. Works for unary as well. ## Explanation ``` ) | For each digit from 1 up to the argument: ;€` | - Concatenate each digit from 1 to that digit together Ṛ | - Reverse Ż | Prepend zero Ṛ | Reverse j0 | Join with zeros F | Flatten ; | Concatenate to original argument ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~56~~ 53 bytes ``` ->n{(?0..n="#{n}").map{|m|[*?0..m]*m}.join.reverse+n} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsPeQE8vz1ZJuTqvVklTLzexoLomtyZaCyScG6uVW6uXlZ@Zp1eUWpZaVJyqnVf7v6C0pFhBw1BPzxKsXEMtTfM/AA "Ruby – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 16 bytes ``` ʁ?²›↔'₌ḢṪZ:U⁼;tṅ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%CA%81%3F%C2%B2%E2%80%BA%E2%86%94%27%E2%82%8C%E1%B8%A2%E1%B9%AAZ%3AU%E2%81%BC%3Bv%E1%B9%85t&inputs=3&header=&footer=) Sorry about that. I wayyyy misinterpreted the question. ##### Explanation: ``` ʁ?²›↔'₌ḢṪZ:U⁼;tṅ # main program ʁ # range 0 to n-1 ?²› # base^2 + 1 ↔ # combination w/ replacement '₌ḢṪZ:U⁼; # filter lambda ₌ḢṪ # a[1:], a[:-1] Z # zip :U⁼ # check if the zip is unique tṅ # tail joined by "" ``` This is really slow, so it will only finish for n <= 3 probably, but it works in theory. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` ⮌⁺⊖θ⭆N⪫…·⁰ιIι ``` [Try it online!](https://tio.run/##HYtBCsJADEWv0mUKFVy4c6kbBaW0J4hjqIFpWjOZuX4MvuV//6UPatowu4/KYjBRIy0EY64FrpSUVhKjN3z7oZstPssDd7jJXu1Z1xcphLhvLLGliLjRhLIQHIeOQ12wGHD/5@x@8kPLPw "Charcoal – Try It Online") Link is to verbose version of code. Takes `b` as input. Works for `b=1`. Explanation: ``` N Input `b` ⭆ Map over implicit range and join …·⁰ι Inclusive range from 0 to current index ⪫ Joined with ι Current index I Cast to string ⁺ Prefixed with θ Input `b` ⊖ Decremented ⮌ Reverse Implicitly print ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 51 bytes ``` .+ $* 1 $`¶ ¶$ 1 $.%_ $.%` ^(.*¶)* $#1$& ¶ O$^`. ``` [Try it online!](https://tio.run/##K0otycxL/M9laKCidWgbF5eKXgKXoWMCl6qGe8J/PW0uFS0uQy6VBKDUoW0qXCC2nmo8SJlqAlechh5Qj6YWl4qyoYoaF0i7v0pcgt7//wA "Retina 0.8.2 – Try It Online") Link includes test suite that generates results for `b=1..10`. Explanation: ``` .+ $* ``` Convert to unary. ``` 1 $`¶ ``` List the values from `0` to `b-1` (in unary). ``` ¶$ ``` Delete the trailing newline that the previous stage generates. ``` 1 $.%_ ``` Replace each `1` with its line number, so now we have a triangle of digits where there are `n` digits `n` on each line. ``` $.%` ``` Intersperse the digits from `0` to `n` around the existing digits `n`. ``` ^(.*¶)* $#1$& ``` Insert an extra digit `b-1` at the beginning. ``` ¶ ``` Join everything together. ``` O$^`. ``` Reverse the string. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~15~~ ~~13~~ 11 bytes *Edit: -2 bytes thanks to Razetime* ``` ↔:¹ṁSoJ←ŀḣ→ ``` [Try it online!](https://tio.run/##AS8A0P9odXNr/23igoH/4oaUOsK54bmBU29K4oaQxYDhuKPihpL///9bMSwyLDMsNyw5XQ "Husk – Try It Online") ``` ↔:¹ṁSoJ←ŀḣ→ # Full program: ṁS # map across ḣ→ # each integer n from 1 to input plus 1: ŀ # integers from zero to n, oJ← # joined-together using n plus 1; :¹ # then, prefix this with the input, ↔ # and reverse it all. ``` [Answer] # [Python 3](https://docs.python.org/3/), 52 bytes ``` f=lambda a,*b:(b and a+a+a.join(b)+f(*b)[:-1]or a)+a ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIVFHK8lKI0khMS9FIVEbCPWy8jPzNJI0tdM0tJI0o610DWPzixQSNbUT/xcUZeaVaADFldxcXZydHC0tzM1MTYyNDA2UNDW5ELK4xLGLYopgCKDzQdz/AA "Python 3 – Try It Online") * Take as inputs each individual available digits in descending order. * Bonus: Base 0 works perfectly fine, so does other bases like Hexadecimal (as long you provide the digits available) ## How it works: Let say your digits are `"43210"`, the expcted result should be `4(4)3(4)2(4)1(4)0__3(3)2(3)1(3)0__2(2)1(2)0__1(1)0__0__[4]` * We can see that each segent contains the numbers up to a certain point separated by the leading number. * These segments repeat in decending order * The first number is added at the end From that I construct the recursive program : * `f=lambda a,*b:`: definition of the function, each individual digit in descending order. Store the first in `a` and the other in `b` * `b and ... or a` if the digits is just `"0"`, `b` is empty and the expression will be equal to `"0"`, else it will be equal to `...` * `a+a+a.join(x)+f(b)[:-1]`, return the string of the available digits separated by the first element (`a`), then recurse over the available digits the first element. Then remove the last digit of it. * `return(...)+a` add the first element of `x` to the result. The previous `[::-1]` is to remove this char from the recursive call but not from the main call. [Answer] # [Python 3](https://docs.python.org/3/), 97 bytes ``` def f(x): k=[] for i in range(x,0,-1):k+=sum([[i-j,i]for j in range(i)],[])+[0] return k+[0,x] ``` [Try it online!](https://tio.run/##Rc1BCoMwEIXhtZ4iywyOkNCd4EmGWQhN7BgaJY2Qnj6alcsHH@8//vmzx1etb@eV1wWmvgszcd/5PSlRElVa4up0QYOjhSkM8@/8aiIZNxRuanuUACMxDGTuh@TymaIK98LCtdHyUIvWtNqRJGbd0lAv "Python 3 – Try It Online") fixed thanks to Jakque Takes `base - 1` for input, so `7` for octal. Does not work for unary, as permitted. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 10 bytes *-3 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs).* ``` ÝεÝy.ý}˜Rš ``` [Try it online!](https://tio.run/##ARsA5P9vc2FiaWX//8OdzrXDnXkuw719y5xSxaH//zk "05AB1E – Try It Online") Takes input as the maximum digit in the base, and outputs as a strangely arranged list of numbers - this is allowed, since > > As long as the digits make the number > > > it is valid. ``` ÝεÝy.ý}˜Rš # full program š # prepend... R # reversed... ˜ # flattened... Ý # [0, 1, 2, ..., # ..., implicit input... Ý # ]... ε # with each element replaced by... Ý # [0, 1, 2, ..., # (implicit) ..., current element in map... Ý # ]... .ý # joined by... y # current element in map... š # to... # implicit input } # exit map # implicit output ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 15 bytes ``` @ORV:0\,_J_MJ,a ``` [Try it online!](https://tio.run/##K8gs@P/fwT8ozMogRifeK97XSyfx////xgA "Pip – Try It Online") ### Explanation We construct (most of) the number backwards and then reverse it: ``` Current value Output a The base, given via command-line 3 , Range(^) [0 1 2] MJ Map this function... 0\,_ Inclusive-range(0, arg) [[0] [0 1] [0 1 2]] J_ joined on arg [0 011 02122] ... and join the results as string 001102122 RV: Reverse 221201100 O Output without a newline 221201100 221201100 @ Get the first character 2 221201100 (Autoprint) 2212011002 ``` [Answer] # [*Acc!!*](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!), 100 bytes ``` N-48 Count i while _+1-i { Count j while _-i-j { Write _-i-j+48 Write _-i+48 } Write 48 } Write _+48 ``` Takes input as (base - 1). [Try it online!](https://tio.run/##S0xOTkr6/99P18SCyzm/NK9EIVOhPCMzJ1UhXttQN1OhGiqaBRPVzdTNAoqGF2WWQHnaQK1wLohTC@UiMeOB4v//WwIA "Acc!! – Try It Online") ### Explanation ``` N-48 # Input a digit and store its value in the accumulator Count i while (_+1)-i { # Loop i from 0 through (acc + 1) - 1 # acc - i is the recurring digit in this block Count j while (_-i)-j { # Loop j from 0 through (acc - i) - 1 # acc - i - j is the changing digit in this block Write (_-i-j)+48 # Write the changing digit Write (_-i)+48 # Write the recurring digit } Write 48 # End the block with a 0 } Write _+48 # End the number with a final digit of (base - 1) ``` ]
[Question] [ The *binary-square-diagonal-sequence* is constructed as follows: 1. Take the sequence of positive natural numbers: ``` 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, ... ``` 2. Convert each number to binary: ``` 1, 10, 11, 100, 101, 110, 111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111, 10000, 10001, ... ``` 3. Concatenate them: ``` 11011100101110111100010011010101111001101111011111000010001 ... ``` 4. Starting with `n=1`, generate squares with increasing side-length `n` which are filled left-to-right, top-to-bottom with the elements of the above sequence: ``` 1 ``` ``` 1 0 1 1 ``` ``` 1 0 0 1 0 1 1 1 0 ``` ``` 1 1 1 1 0 0 0 1 0 0 1 1 0 1 0 1 ``` ``` 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 1 1 0 0 0 0 1 ``` ``` ... ``` 5. Take the diagonal (top left to bottom right) of each square: ``` 1, 11, 100, 1011, 00111, ... ``` 6. Convert to decimal (ignoring leading zeros): ``` 1, 3, 4, 11, 7, ... ``` # Task Write a program or function which outputs the sequence in one of the following ways: * Return or print the sequence infinitely. * Given input `i`, return or print the first `i` elements of the sequence. * Given input `i`, return or print the `i`th element of the sequence (either 0 or 1 indexed). Please state in your answer which output format you choose. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in each language wins. # Test cases Here are the first 50 elements of the sequence: `1,3,4,11,7,29,56,141,343,853,321,3558,8176,3401,21845,17129,55518,134717,151988,998642,1478099,391518,7798320,8530050,21809025,61485963,66846232,54326455,221064493,256373253,547755170,4294967295,1875876391,2618012644,24710258456,6922045286,132952028155,217801183183,476428761596,51990767390,687373028085,1216614609441,7677215985062,15384530216172,22714614479340,15976997237789,0,256145539974868,532024704777005,601357273478135` [Answer] ## [Husk](https://github.com/barbuz/Husk), ~~15~~ 14 bytes ``` zȯḋm←CtNCİ□ṁḋN ``` [Try it online!](https://tio.run/##yygtzv7/v@rE@oc7unMftU1wLvFzPrLh0bSFD3c2AoX8/v8HAA "Husk – Try It Online") Continually prints the results as an infinite list. ### Explanation I wonder whether there's a better way to get every **n**th element from a list than splitting the list into chunks of length **n** and retrieving the head of each chunk. ``` tN Get a list of all natural numbers except 1. (A) N Get a list of all natural numbers. ṁḋ Convert each to its binary representation and join them all into a single list. İ□ Get a list of squares of all natural numbers. C Cut the list of bits into chunks of corresponding sizes. (B) zȯ Zip (A) and (B) together with the following function. C Split the bit list (from B) into chunks of the given length (from A). m← Get the head of each chunk. This is the diagonal of the bit list arranged as a square. ḋ Interpret the resulting bits as binary digits and return the result. ``` To be clear, we extract the diagonal of an **n x n** square by splitting its linear form into chunks of length **n + 1** and retrieving the first element of each chunk: ``` [[1 , 0 , 1 , 0 0],[1 , 0 , 1 1 , 0],[1 , 0 0 , 1 , 0],[1]] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~137~~ 85 bytes ``` lambda n:int(''.join(bin(x+1)[2:]for x in range(n**3))[n*~-n*(2*n-1)/6:][:n*n:n+1],2) ``` [Try it online!](https://tio.run/##Rc2xDsIgFEbhWZ/ibnApqNDEgURfBBloFKXRv03ToS6@OtbJ4YxfzvieHwNczadLfaZXd00EXzBLIXb9UCC7taWxHJyPeZhooQKaEu43CaVa5gD1MVDSKRjL@6OPwUPBo7FRO64/VP7Iantgv92M03qhokmYs9CUZeHafgE "Python 2 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~96~~ 94 bytes ``` lambda i:int(''.join(bin(x+1)[2:]for x in range(i**3))[sum(x*x for x in range(i))::i+1][:i],2) ``` [Try it online!](https://tio.run/##XYxBCoMwEAC/sjezUQpRelnwJTGHSFvdohuJCunrU/VS6GFOM8zy2cYgTZa2y5Of@4cHJpZNFcXtHVhUf5BKg7Ym9woRErBA9DI8FWvdINp1n1XSCf4tIhGXxlliV9WYl3h@rRzmavnXmupu0GH@Ag "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ ~~17~~ 16 bytes ``` °LbJsLn£θs>ô€нJC ``` `°` is replaced by `3m` in the links as `°` tends to get very slow. [Try it online!](https://tio.run/##MzBNTDJM/f/fONcnyavYJ@/Q4nM7iu0Ob3nUtObCXi/n///NAA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##ASoA1f8wNWFiMWX/MjBMdnl5ef8zbUxiSnNMbsKjzrhzPsO04oKs0L1KQ//Lhv8) **Explanation** ``` °L # push the range [1 ... 10^input] bJ # convert each to binary and join to string sLn # push the range [1 ... input]^2 £θ # split the binary string into pieces of these sizes and take the last s>ô # split this string into chunks of size (input+1) €н # get the first digit in each chunk JC # join to string and convert to int ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes This takes a somewhat different approach to [Martin's](https://codegolf.stackexchange.com/users/8478/martin-ender) [answer](https://codegolf.stackexchange.com/a/145428/71256) ``` moḋz!NCNCṘNNṁḋN ``` [Try it online!](https://tio.run/##yygtzv7/Pzf/4Y7uKkU/Zz/nhztn@Pk93NkIFPD7/x8A "Husk – Try It Online") ### Explanation: ``` N List of all natural numbers ṁḋ Convert each to it's binary representation and flatten ṘNN Repeat the list of natural numbers according the natural numbers: [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5...] C Cut the list of bits into lists of lengths corresponding to the above CN Cut that list into lists of lengths corresponding to the natural numbers moḋz!N For each in the list, get the diagonals and convert from binary. m For each list in the list z!N Zip it with natural numbers, indexing. oḋ Convert to binary ``` ### In action `ṁḋN` : `[1,1,0,1,1,1,0,0,1,0,1,1,1,0,1,1,1,1,0,0,0,1,0,0,1,1,0,1,0,1...]` `ṘNN` : `[1,2,2,3,3,3,4,4,4,4,5,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7,7,7,8,8...]` `C` : `[[1],[1,0],[1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1,1],[0,0,0,1]...]` `CN` : `[[[1]],[[1,0],[1,1]],[[1,0,0],[1,0,1],[1,1,0]]...]` `m z!N` : `[[1],[1,1],[1,0,0],[1,0,1,1],[0,0,1,1,1],[0,1,1,1,0,1]...]` `oḋ` : `[1,3,4,11,7,29,56,141,343,853,321,3558,8176,3401,21845...]` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~215~~ ~~212~~ ~~206~~ ~~202~~ 197 bytes ``` i->{String b="",t;int s=0,x=++i,j;for(;--x>0;s+=x*x);while(b.length()<s)b+=i.toString(++x,2);for(j=1,s=0;j<i;System.out.println(i.valueOf(t,2)),s+=j*j++)for(t="",x=s;x<s+j*j;x+=j+1)t+=b.charAt(x);} ``` [Try it online!](https://tio.run/##fZA/b8MgEMVn@1OgTFBslFTqhIlUtUuHqoPHqgN2iIOLwTFHShTls7vkT9fe@O69u6dfLw@ydKOy/eZ71sPoJkB90lgAbdg22Ba0s@zFWR8GNfE8H0NjdItaI71H71JbdMozDxKS@Ger3iyoTk1r1Ggrp2O9D3JSr1p2zkpTq31QtlVIoFmX61MNk7YdasRiUQDXFpAXyyIKSnXR862bMC/LuF5yT0V8iIT/7LRRuGFG2Q52mFSeNFRoBu52ClMai0dyjfZiVaRzvK80r48e1MBcADYmHxiLNTtIE9THFkNKkCK96B96SsklC5dGUXgeK0@TzGPa0hUBKhrW7uT0DDjVOc8JS3bncidxcHqDhkQH3yp9fiFJEil0n@w/MEy2rRoBPy0Jvyayc36efwE "Java (OpenJDK 8) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 91 bytes ``` i=n=1;s='' while 1: s+=bin(i)[2:];i+=1 if s[n*n:]:print int(s[:n*n:n+1],2);s=s[n*n:];n+=1 ``` [Try it online!](https://tio.run/##LYw7CoAwEAX7nGI7P7FJyg17kphGUFyQpxhBPH2MYPGaYeYdz7Xu8AUyFhWIC1maxtyrbjM5NpStTIpWu@g5BbXiDOlCOaIHJz5OxUV1bY78IViXBt/Vm18JqE0pLw "Python 2 – Try It Online") prints the sequence infinitely [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` RBFṁ R²SÇṫ²C$m‘Ḅ ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//UkJG4bmBClLCslPDh@G5q8KyQyRt4oCY4biE/8OH4oKs//8xMA "Jelly – Try It Online") ## Explanation ``` RBFṁ Helper link. Input: integer k R Range, [1, 2, ..., k] B Convert each to a list of its binary digits F Flatten ṁ Mold to length k R²SÇṫ²C$m‘Ḅ Main link. Input: integer n R Range, [1, 2, ..., n] ² Square each S Sum Ç Call helper link on the sum of the first n squares $ Monadic chain ² Square n C Complement, 1-n^2 ṫ Tail, take the last n^2 elements m Modular indexing, take each ‘ (n+1)th element Ḅ Convert from list of binary digits to decimal ``` [Answer] # Mathematica, 96 bytes **Outputs** the `i`th element of the sequence (1-indexed) ``` Diagonal@Partition[TakeList[Flatten@IntegerDigits[Range[#^3],2],Range@#^2][[#]],#]~FromDigits~2& ``` [Try it online!](https://tio.run/##JcqxCsIwEADQXwkEnDJIxFHIUAqCQyluxxUOucbD5gLpzf31CDo@eIXszYVMXtRXd3N9EMpVaUsTNROTqvCkDz9kNxg3MmNNdzXO3AbJYjvMpJnBLxcMEcNPyS8RATxi8HiMrZb/PeKpT03UXHIrXM/Yvw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Completely different approach compared to [Erik's solution](https://codegolf.stackexchange.com/a/145430/59487). ``` Ḷ²S‘ɓ*3B€Fṫ Çm‘ḣµḄ ``` [Try it online!](https://tio.run/##AS8A0P9qZWxsef//4bi2wrJT4oCYyZMqM0LigqxG4bmrCsOHbeKAmOG4o8K14biE////Ng "Jelly – Try It Online") ## How it works ``` Ḷ²S‘ɓ*3B€Fṫ - Helper link (monadic). Ḷ - Lowered range, generates [0, N). ² - Vectorized square (square each). S - Sum. ‘ - Increment, to account for the 1-indexing of Jelly. ɓ - Starts a separate dyadic chain. *3 - The input to the power of 3. B€ - Convert each to binary. F - Flatten. ṫ - Tail. Return x[y - 1:] (1-indexed). Çm‘ḣµḄ - Main link (monadic). Ç - Last link as a monad. m‘ - Modular input + 1. Get each "input + 1"th element of the list. ḣ - Head. Return the above with elements at index higher than the input cropped. µḄ - Convert from binary to integer. ``` Saved 1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` ²Rµ²Ṭ€Ẏ0;œṗBẎ$³ịs³ŒDḢḄ ``` [Try it online!](https://tio.run/##ATgAx/9qZWxsef//wrJSwrXCsuG5rOKCrOG6jjA7xZPhuZdC4bqOJMKz4buLc8KzxZJE4bii4biE////Ng "Jelly – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~27~~ 20 bytes ``` i<%hQ>s.BS^Q3s^R2QQ2 ``` **[Verify the first few test cases.](https://pyth.herokuapp.com/?code=i%3C%25hQ%3Es.BS%5EQ3s%5ER2QQ2&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8&debug=0)** Gets the **I**th term of the sequence, 1 indexed. ## How it works? ``` i<%hQ>s.BS^Q3s^R2QQ2 - Full program. Q represents the input. S^Q3 - Generate the (inclusive) range [1, Q ^ 3]. .B - Convert each to binary. s - Join into a single string. > - Trim all the elements at indexes smaller than: ^R2Q - The elements of the range [0, Q) squared. s - And summed. %hQ - Get each Q + 1 element of the list above. < - Trim all the elements at indexes higher than: Q - The input. i 2 - Convert from binary to integer. ``` [Answer] # [Perl 5](https://www.perl.org/), 92 + 1 (`-p`) = 93 bytes ``` $s.=sprintf'%b',++$"for 1..$_**3;map{say oct"0b".(substr$s,0,$_*$_,'')=~s/.\K.{$_}//gr}1..$_ ``` [Try it online!](https://tio.run/##HctBCsIwEADAr5SwJdqmmxTJSfoC8QdCaMRKQZOQjYdS6tNdxftMuuWHZQbCgVKeQ5lk7aVqWxBTzFWPCK5pDsfnmFYalypeizBe4I5enkoGUkb9BDgl5X54k8bLCVdwm9b3vP07szWfmMocA3F3tmh6w134Ag "Perl 5 – Try It Online") ]
[Question] [ **This question already has answers here**: [Find the Pisano Period](/questions/8765/find-the-pisano-period) (12 answers) Closed 8 years ago. The Fibonacci sequence is a well known and famous sequence, where each successive element is the sum of the previous two. A modular Fibonacci sequence is the same, except that the addition is performed over a finite field, or to put it another way, a modulo operation is performed after each addition. For instance, the modular Fibonacci sequence with starting values `1, 1` and modulus `5` is: ``` 1, 1, 2, 3, 0, 3, 3, 1, 4, 0, 4, 4, 3, 2, 0, 2, 2, 4, 1, 0, 1, 1, ... ``` At this point, the sequence is once again `1, 1`, and so the sequence will repeat, cyclically, with a cycle length of 20. Your challenge is to find the (minimal) cycle length for a specific starting pair and modulus, in the fewest bytes. **Details:** The initial values will both be in the range `0 <= i,j < m`, where `m` is the modulus. The initial values will not both be zero, and the modulus will be at least 2. You may take the input in any standard means or format, in any order, function, program or similar, and output via return or print. Standard loopholes apply. **Examples:** ``` First element, second element, modulus: 1, 1, 5 => 20 1, 1, 4 => 6 2, 4, 6 => 8 3, 3, 6 => 3 ``` This is code golf - shortest code in bytes wins. Good luck! [Answer] # Python, 56 ``` g=lambda a,b,m,u=0:u!=(a,b)and-~g(b,(a+b)%m,m,u or(a,b)) ``` [Answer] # [Retina](https://github.com/mbuettner/retina), ~~69~~ 61 bytes This was great fun to write! ``` (1* )(1*).* x$2$1$0 (1*)(?=.* \1$) )`x(1* 1*) .* \1 .* x x 1 ``` Each line should go to its own file but you can run the code as one file with the `-s` flag. Takes input in unary, in format `j i m` and gives output in unary. The four substitution pairs do the followings: * Add next element and increase step counter. * Take modulo of the new element. * If we reached the starting numbers delete everything except step counter. This will break the loop of the first three steps. * Convert step count to unary number. The string has the following format during the computation (with `(?#comments)`): ``` x*(?#number of steps)(1* )+(?#sequence, reversed)1*(?#modulus) ``` The code makes use of some observations: * The modulus can be part of the sequence as it is bigger than any other number causing no false positive match. * There will always be a number between the two repeating pair. I.e.output will always be at least 3. (The 3rd number can be the same as the 1st if the sequence starts as `x,0,x,x,...`) * You have to subtract the modulo from the new number at most once. Every substitution step shown in its own line for the example `j=1, i=1, m=4`: ``` 1 1 1111 x11 1 1 1111 x11 1 1 1111 x11 1 1 1111 xx111 11 1 1 1111 xx111 11 1 1 1111 xx111 11 1 1 1111 xxx11111 111 11 1 1 1111 xxx1 111 11 1 1 1111 xxx1 111 11 1 1 1111 xxxx1111 1 111 11 1 1 1111 xxxx 1 111 11 1 1 1111 xxxx 1 111 11 1 1 1111 xxxxx1 1 111 11 1 1 1111 xxxxx1 1 111 11 1 1 1111 xxxxx1 1 111 11 1 1 1111 xxxxxx1 1 1 111 11 1 1 1111 xxxxxx1 1 1 111 11 1 1 1111 xxxxxx xxxxxx xxxxxx xxxxxx 111111 ``` [Answer] # Haskell, ~~76~~ 71 bytes ``` p x y m=[i|(p,i)<-zip(x#y)[0..],(x,y)==p]!!1where x#y=(x,y):y#mod(x+y)m ``` Usage example: `p 1 1 5` -> `20`. How it works: `#` builds an infinite list of `(i,i+1)` pairs of the modular Fibonacci sequence. e.g. with `m==5`: `1#1`-> `[(1,1),(1,2),(2,3),(3,0)...]`. The list comprehension `[i| ... ]` returns a list of indices of the positions of `(x,y)` within `x#y`. From this list I take the second element (-> `!!1`), because the first (index `0`) is always at the beginning of `x#y`. Edit: replaced `elemIndices` from `Data.List` with my own version. [Answer] # Pyth, 18 17 16 15 bytes ``` fqQu,eG%sGvzTQ1 ``` Example input: ``` 6 [2, 4] ``` Will output `8`. It works by outputting increasingly long Fibonacci sequences (in pairs), until the end is the same as the start. [Answer] # C, 78 72 bytes An essentially straightforward C solution. Perhaps there is a shorter solution by considering analytic expressions for Pisano periods of generalized Fibonacci numbers, though [this thesis](http://www.diva-portal.org/smash/get/diva2:630928/FULLTEXT01.pdf "this") from 2013 makes it look like such expressions are not known. ``` g(o,t,m,N,M,i,v){N=o;M=t;for(i=1;v=N+M,N=M,M=v%m,N-o|M-t;i++);return i;} ``` Readable version, by way of explanation, is ``` int f(int one, int two, int mod) { int new_one, new_two, i, tmp; new_one = one; new_two = two; for(i = 1; tmp = new_one + new_two, new_one = new_two, new_two = tmp % mod, new_one - one | new_two - two; i++); return i; } ``` And the examples ``` $ ./mod_fib 1 1 5 20 $ ./mod_fib 1 1 4 6 $ ./mod_fib 3 3 6 3 $ ./mod_fib 2 4 6 8 ``` EDIT: returning the value instead of printing it is allowed in the spec and saves 6 bytes. [Answer] # Prolog, 116 bytes ``` a(A,B,M,R):-f([B,A],A,B,M,1,R). f([A,B|T],X,Y,M,Z,R):-Z=0,Y=A,X=B,length(T,R);C is(A+B)mod M,f([C,A,B|T],X,Y,M,0,R). ``` Example: `a(1,1,5,R).` outputs `R = 20 .` [Answer] # CJam, 23 bytes ``` q~:MM*{_2$+M%}*]2ew(a#) ``` Reads whitspace-separated numbers from STDIN, in the same order as in the question. Works by generating **m2** more numbers, pairing all and searching the index of the first pair in the rest. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%3AMM*%7B_2%24%2BM%25%7D*%5D2ew(a%23)&input=1%201%205). [Answer] Much shorter answers have been posted, but: # EcmaScript 6, 67 64 62 56 bytes ``` let f=(d,e,m,a=e,b=d+e)=>a^d||b^e?f(d,e,m,b,(a+b)%m)+1:1 ``` Examples: ``` f(1,1,5) //20 f(1,1,4) // 6 ``` [Answer] ## Perl, 88 bytes ``` ($v,$w,$m)=@ARGV;$x=$v;$y=$w;do{$c++;($x,$y)=($y,($x+$y)%$m)}while($x-$v||$y-$w);print$c ``` Arguments given on the command line, in the order as in the question. ]
[Question] [ The Hamming(7,4) code goes back to 1950. Back then Richard Hamming worked as a mathematician at Bell Labs. Every Friday Hamming set the calculating machines to perform a series of calculation, and collected the results on the following Monday. Using parity checks, these machines were able to detect errors during the computation. Frustrated, because he received error messages way too often, Hamming decided to improve the error detection and discovered the famous Hamming codes. ## Mechanics of the Hamming(7,4) The goal of Hamming codes is to create a set of parity bits that overlap such that a single-bit error (one bit is flipped) in a data bit or a parity bit can be detected and corrected. Only if there occur multiple errors, the Hamming code fails of recovering the original data. It may not notice an error at all, or even correct it falsely. Therefore in this challenge we will only deal with single-bit errors. As an example of the Hamming codes, we will look at the Hamming(7,4) code. Additionally to 4 bits of data `d1, d2, d3, d4` it uses 3 parity bits `p1, p2, p3`, which are calculated using the following equations: ``` p1 = (d1 + d2 + d4) % 2 p2 = (d1 + d3 + d4) % 2 p3 = (d2 + d3 + d4) % 2 ``` The resulting codeword (data + parity bits) is of the form `p1 p2 d1 p3 d2 d3 d4`. Detecting an error works the following way. You recalculate the parity bits, and check if they match the received parity bits. In the following table you can see, that every variety of a single-bit error yields a different matching of the parity bits. Therefore every single-bit error can be localized and corrected. ``` error in bit | p1 | p2 | d1 | p3 | d2 | d3 | d4 | no error -------------|--------------------------------------------- p1 matches | no | yes| no | yes| no | yes| no | yes p2 matches | yes| no | no | yes| yes| no | no | yes p3 matches | yes| yes| yes| no | no | no | no | yes ``` ## Example Let your data be `1011`. The parity bits are `p1 = 1 + 0 + 1 = 0`, `p2 = 1 + 1 + 1 = 1` and `p3 = 0 + 1 + 1 = 0`. Combine the data and the parity bits and you get the codeword `0110011`. ``` data bits | 1 011 parity bits | 01 0 -------------------- codeword | 0110011 ``` Lets say during a transmission or a computation the 6th bit (= 3rd data bit) flips. You receive the word `0110001`. The alleged received data is `1001`. You calculate the parity bits again `p1 = 1 + 0 + 1 = 0`, `p2 = 1 + 0 + 1 = 0`, `p3 = 0 + 0 + 1 = 1`. Only `p1` matches the parity bits of the codeword `0110001`. Therefore an error occurred. Looking at the table above, tells us that the error occurred in `d3` and you can recover the original data `1011`. ## Challenge: Write a function or a program, that receives a word (7 bits), one of the bits might be wrong, and recover the original data. The input (via STDIN, command-line argument, prompt or function argument) format may be a string `"0110001"`, a list or an array `[0, 1, 1, 0, 0, 0, 1]` or an integer in MSB `0b0110001 = 49`. As described above, the order of the input is `p1 p2 d1 p3 d2 d3 d4`. The output (via return value or STDOUT) has to be of the same format, but in the order `d1 d2 d3 d4`. Only return/output the 4 data bits. This is code-golf. Therefore the shortest code wins. ## Test cases: ``` 1110000 -> 1000 # no error 1100000 -> 1000 # error at 1st data bit 1111011 -> 1111 # error at 2nd data bit 0110001 -> 1011 # error at 3rd data bit (example) 1011011 -> 1010 # error at 4th data bit 0101001 -> 0001 # error at 1st parity bit 1010000 -> 1000 # error at 2nd parity bit 0100010 -> 0010 # error at 3rd parity bit ``` ``` 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(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=45684;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var 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>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table> ``` [Answer] # Piet 50x11 = 550 ![enter image description here](https://i.stack.imgur.com/VldlR.png) codel size is 15. Not too concerned about size, but it passed all the tests. [Answer] # Python, 79 ``` f=lambda x,n=0,e=3:e&~-e and f(x,n+1,(n&8)*14^(n&4)*19^(n&2)*21^n%2*105^x)or~-n ``` Take input and output as numbers with the least significant bit on the right. Instead of attempting error recovery, we just try encoding every possible message `n` from 0 to 15 until we get an encoding that's one bit away from what's given. The recursion keeps incrementing `n` until it finds one that works and returns it. Though there's no explicit termination, it must end within 16 loops. The expression `(n&8)*14^(n&4)*19^(n&2)*21^n%2*105` implements the Hamming matrix bitwise. To check for a single error, we xor the given message with a computed one to get `e`, and check if it's a power of two (or 0) with the classic bit-trick `e&~-e==0`. But, we can't actually assign to the variable `e` within a lambda, and we refer to it twice in this expression, so we do a hack of passing it as an optional argument to the next recursive step. [Answer] # JavaScript (ES6), ~~92~~ ~~87~~ 81 Function getting and returning an integer in MSB. The implementation is straightforwrd following @randomra comment: * calc p3wrong|p2wrong|p1wrong (line 2,3,4) * use it as a bit mask to flip the incorrect bit (line 1), * then return just the data bits (last line) ``` F=w=>(w^=128>>( (w^w*2^w*4^w/2)&4| (w/8^w^w*2^w/16)&2| (w/16^w/4^w^w/64)&1 ))&7|w/2&8 ``` **Test** In Frefox/FireBug console ``` ;[0b1110000,0b1100000,0b1111011,0b0110001, 0b1011011,0b0101001,0b1010000,0b0100010] .map(x=>x.toString(2)+'->'+F(x).toString(2)) ``` *Output* ``` ["1110000->1000", "1100000->1000", "1111011->1111", "110001->1011", "1011011->1010", "101001->1", "1010000->1000", "100010->10"] ``` [Answer] # Octave, ~~70~~ ~~66~~ 55 bytes This function `F` is setting up the decoding matrix `H`, finding the error and correcting the position of the error (if there is one). Then it is returning the right data bits. Input is a standard row vector. @Jakube suggested I should use Octave instead of Matlab where you *can* use indices on expressions, which makes the whole thing again shorter 11 bytes: ``` F=@(c)xor(c,1:7==bi2de(mod(c*de2bi(1:7,3),2)))([3,5:7]) ``` Following is the shortest solution in *Matlab*, as you cannot directly use indexing on expressions. (This works in Octave too, of course.) Was able to replace addition/mod2 with `xor`: ``` f=@(c)c([3,5:7]);F=@(c)f(xor(c,1:7==bi2de(mod(c*de2bi(1:7,3),2)))) ``` Old: ``` f=@(c)c([3,5:7]);F=@(c)f(mod(c+(1:7==bi2de(mod(c*de2bi(1:7,3),2))),2)) ``` [Answer] # Python 2, 71 ``` f=lambda i,b=3:i&7|i/2&8if chr(i)in'\0%*3<CLUZfip'else f(i^b/2,b*2) ``` Several characters are unprintable ASCII so here is an escaped version: ``` f=lambda i,b=3:i&7|i/2&8if chr(i)in'\0\x0f\x16\x19%*3<CLUZfip\x7f'else f(i^b/2,b*2) ``` Input and output to the function are done as integers. I'm taking advantage of the fact that the number of valid messages is only 16, and hard-coding them all. Then I try flipping different bits until I get one of those. [Answer] # Haskell, 152 bytes ``` a(p,q,d,r,e,f,g)=b$(d+e)#p+2*(d+f)#q+4*(e+f)#r where b 3=(1-d,e,f,g);b 5=(d,1-e,f,g);b 6=(d,e,1-f,g);b 7=(d,e,f,g-1);b _=(d,e,f,g);x#y=abs$(x+g)`mod`2-y ``` Usage: `a (1,1,1,1,0,1,1)` which outputs `(1,1,1,1)` Straightforward solution: if `p<x>` does not match, set bit `<x>` in a number. If this number is `3`, `5`, `6` or `7`, flip the corresponding `d<y>`. [Answer] # IA-32 machine code, 36 bytes Hexdump: ``` 33 c0 40 91 a8 55 7a 02 d0 e1 a8 66 7a 03 c0 e1 02 a8 78 7a 03 c1 e1 04 d0 e9 32 c1 24 74 04 04 c0 e8 03 c3 ``` Equivalent C code: ``` unsigned parity(unsigned x) { if (x == 0) return 0; else return x & 1 ^ parity(x >> 1); } unsigned fix(unsigned x) { unsigned e1, e2, e3, err_pos, data; e1 = parity(x & 0x55); e2 = parity(x & 0x66); e3 = parity(x & 0x78); err_pos = e1 + e2 * 2 + e3 * 4; x ^= 1 << err_pos >> 1; data = x; data &= 0x74; data += 4; data >>= 3; return data; } ``` x86 CPU automatically calculates the parity of each intermediate result. It has a dedicated instruction `jp` that jumps or not jumps depending on the parity. It wasn't specified explicitly in the challenge, but the convenient property of hamming codes is that you can interpret the parity bits as a binary number, and this number indicates which bit was spoiled during transmission. Actually, this number is 1-based, with 0 meaning there were no transmission errors. This is implemented by shifting 1 left by `err_pos` and then right by `1`. After fixing the transmission error, the code arranges the data bits in the needed order. The code is optimized for size, and it may be unclear at first how it works. To explain it, I denote by `a`, `b`, `c`, `d` the data bits, and by `P`, `Q` and `R` the parity bits. Then: ``` data = x; // d c b R a Q P data &= 0x74; // d c b 0 a 0 0 data += 4; // d c b a ~a 0 0 data >>= 3; // d c b a ``` Assembly source (`fastcall` convention, with input in `ecx`, and output in `eax`): ``` xor eax, eax; inc eax; xchg eax, ecx; test al, 0x55; jp skip1; shl cl, 1; skip1: test al, 0x66; jp skip2; shl cl, 2; skip2: test al, 0x78; jp skip3; shl ecx, 4; skip3: shr cl, 1; xor al, cl; and al, 0x74; add al, 4; shr al, 3; ret; ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~26~~ 25 bytes ``` (⊤⍳7)(3 5 6 7⊇⊢≠≠.∧∧.=⊣)⊢ ``` [Try it online!](https://tio.run/##dZC/TsMwEMb3PMVJLM2Q6o4AnWBhgZXyAoY4UCn/FDy0M1JbIrWCgR0BEiMDb8Cj3IuEiw3kD8JnOTl/P33@bFUkQbRQSX4V6LnRWaSjmteryzxNdWY8IkIZEBxB8wOwA1kOuizz0nNST7MCKAN0YyBSRsHFzJoQEllQRg/czaIWRGvpQByAYdmCMNJzlRaJ9r2G@/FG6ofYM9ddbynnbc8Ypi1UOTMLlxfp34s1eTuoJQmd6@D4JnEHlVetR1y98uZj4o9C2IcDmHC14uqZ755kjnn9JnN8yNWLL7t1zMt73my5uv18D3n5wNvH6dmxrOcnp9M6BrKFrry42/32bk9W6bFDkNXxj47fRKu3fm0n3y8 "APL (Dyalog Extended) – Try It Online") -1 byte thanks to @Adám. A bit shortened further using monadic `⊤`. --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~31~~ 30 [bytes](https://github.com/abrudz/SBCS) ``` ⎕{(1<+⌿⍵)/⍺≠⍵∧.=⍨⍵≠.∧⍺}2⊥⍣¯1⍳7 ``` [Try it online!](https://tio.run/##dZHNSgMxEMfP5ikGvLRI60wVerF9l9TdamG/iDm0FM9txXjzXhDRmwfx4kXwUeZF1nxUNrtiBrKTmd/@808iq2yQrGRWXtW83VyWeZ4WWhAR2gGDKbgE4BiKElKlSiVCq9XzDZAa6EZDIrWE2cKLEBJ50I4WOCqSBkQvGUDsgGeqAaGXLmVeZWlfOO5XG6lt4lxfx9o2grbfo@u2kmqhV8Ev0r8Hc34j1JOEQbWzvXMcofZWhZvmNT88rnt0ccL3X2w@@qdsPnm3tylvX4YTNq8u3e2HdmlbtyO@e2bz9P1GbN7H7nXqo7kgcIEhxKGA3UIo2tkVMPqFAoF/CTwwERGJNkv7/QE "APL (Dyalog Unicode) – Try It Online") -1 byte thanks to @Adám. Full program that takes the boolean vector from stdin. Generalized matrix product `f.g` turns out to be *very* suitable for decoding Hamming code. ### How it works ``` ⎕{(1<+⌿⍵)/⍺≠⍵∧.=⍨⍵≠.∧⍺}2⊥⍣¯1⍳7 ⍝ Full program 2⊥⍣¯1⍳7 ⍝ m←3×7 matrix of bit patterns of 1..7 ⍝ 0 0 0 1 1 1 1 ⍝ 0 1 1 0 0 1 1 ⍝ 1 0 1 0 1 0 1 ⎕ ⍝ Take the length-7 boolean vector v from stdin { } ⍝ Pass to the inline function; ⍺←v ⋄ ⍵←m ⍵≠.∧⍺ ⍝ Calculate parity for each row of m ⍵∧.=⍨ ⍝ Compute which column of m matches the error pattern ⍺≠ ⍝ Flip that bit from the codeword (or nothing if no error) (1<+⌿⍵)/ ⍝ Extract the data bits from the codeword ``` ]
[Question] [ # Introduction How to prove that 1 = 2: ``` 1 = 2 2 = 4 (*2) -1 = 1 (-3) 1 = 1 (^2) ``` You can just multiply both sides by 0, but that's cheating. This is just bending the rules a little bit. # Your challenge: Write a program/function that, when given two integers, outputs a "proof" that the two are equal. # Rules * Your program's output must start with `a = b`, where a and b are the integers, and end with `c = c`, where c can be any number. Don't output the operations. * Your output can only use integers. * The only operations you can use are addition, multiplication, division, subtraction, and exponentiation, and you cannot multiply, divide or exponentiate by 0. * Each line must be one of the above operations done to both sides of the equation in the previous line. For example, you could go: ``` 4 = 9 5 = 10 (+1) 1 = 2 (/5) 8 = 16 (*8) -4 = 4 (-12) 16 = 16 (^2) ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~57~~ 54 bytes ``` a=>b=>a+`=${b} ${a+a}=${b+b} ${a-=b}=${-a} ${a*=a}=`+a ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i7J1i5RO8FWpTqplkulOlE7sRbE1obwdG2TQFzdRDBPyxYomaCd@D85P684PydVLyc/XSNNw1BTw0hT8z8A "JavaScript (Node.js) – Try It Online") ## How? There always exists a multiple of \$0.5\$ which, when subtracted from each number, creates a pair of the form \$-a = a\$. If \$a-x=c\$, then \$b-(a-x+b)=-c\$, so then if \$a-x+b=x\$, then \$x=\frac{(a+b)}2\$. This might not be an integer, so multiply by 2 beforehand. -3 bytes thanks to Arnauld. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes ``` xIÂ-Dn)'=δý» ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/wvNwk65Lnqa67bkth/ce2v3/f7SJjoJlLAA "05AB1E – Try It Online") A port of my [Jelly answer](https://codegolf.stackexchange.com/a/226649/66833). I thought that 05AB1E's stack-based functionality would be shorter, but it isn't great at joining. -1 byte thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)! ``` xIÂ-Dn)'=δý» - Full program. Takes [a, b] on the stack x - Push [2a, 2b]; Stack = [[a, b], [2a, 2b]] I - Push [a, b]; Stack = [[a, b], [2a, 2b], [a, b]] Â - Bifurcate; Stack = [[a, b], [2a, 2b], [a, b], [b, a]] - - Subtract; Stack = [[a, b], [2a, 2b], [a-b, b-a]] D - Duplicate; Stack = [[a, b], [2a, 2b], [a-b, b-a], [a-b, b-a]] n - Square; Stack = [[a, b], [2a, 2b], [a-b, b-a], [(a-b)², (b-a)²]] ) - Wrap into array; Stack = [[[a, b], [2a, 2b], [a-b, b-a], [(a-b)², (b-a)²]]] '= - Push '=' δý - Join each with '=' » - Join array by newlines ``` [Answer] # [R](https://www.r-project.org/), ~~64~~ 51 bytes -7 bytes thanks to Dominic van Essen. ``` cat(sep=c("="," "),x<-scan(),2*x,y<-2*x-sum(x),y^2) ``` [Try it online!](https://tio.run/##K/r/PzmxRKM4tcA2WUPJVklHiUtJU6fCRrc4OTFPQ1PHSKtCp9JGF0jpFpfmalRo6lTGGWn@N1Gw/A8A "R – Try It Online") The steps followed are: ``` a = b 2a = 2b (*2) a-b = b-a (-(a+b)) (a-b)^2 = (b-a)^2 (^2) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ,Ḥ;_U,²$Ɗj€”=Y ``` [Try it online!](https://tio.run/##ASYA2f9qZWxsef//LOG4pDtfVSzCsiTGimrigqzigJ09Wf///1s0LCA5XQ "Jelly – Try It Online") Uses [ophact's observation](https://codegolf.stackexchange.com/a/226648/66833), that for any \$a, b\$, it is sufficient to yield the 4 equations $$ a = b \\ 2a = 2b \\ a-b = b-a \\ (a-b)^2 = (b-a)^2 $$ ## How it works ``` ,Ḥ;_U,²$Ɗj€”=Y - Main link. Takes [a, b] on the left Ḥ - Double, yielding [2a, 2b] , - Pair; [[a, b], [2a, 2b]] Ɗ - Previous three links as a monad f([a, b]): U - Reverse; [b, a] _ - Subtract; [a-b, b-a] $ - Previous two links as a monad f([a-b, b-a]]): ² - Square; [(a-b)², (b-a)²] , - Pair; [[a-b, b-a], [(a-b)², (b-a)²]] ; - Concatenate; [[a, b], [2a, 2b], [[a-b, b-a], [(a-b)², (b-a)²]] j€”= - Join each with "=" Y - Join with newlines ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~79~~ 78 bytes ``` for x in'input()','2*a,2*b','a-b>>1,b-a>>1','a*a,'*2:a,b=eval(x);print a,'=',b ``` [Try it online!](https://tio.run/##FYlBCoAgEEWv4m5UpoWzLPQuM1AkhIpY2OnNVv@998vbzpxojCNX1VVMEFO5mzaAQJaRrEziRUJwKAvP@X0@YGllFL8/fOlutlJjamp2DyhjOFT0AQ "Python 2 – Try It Online") --- # [Python 3](https://docs.python.org/3/), 70 bytes ``` def f(a,b):x=a-b;return f'{a}={b}\n{2*a}={2*b}\n{x}={-x}\n{x*x}={x*x}' ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1EnSdOqwjZRN8m6KLWktChPIU29OrHWtjqpNiav2kgLxDTSAnMqgEzdCjBLC8QGker/C4oy80o00jQMdRSMNDX/AwA "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~84~~ \$\cdots\$ ~~73~~ 71 bytes Saved 5 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! Saved 2 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!! ``` k=a,b=input() d=a-b for a,b in k,[2*a,2*b],[d,-d],[d*d]*2:print a,'=',b ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9s2USfJNjOvoLREQ5MrxTZRN4krLb9IASiqkJmnkK0TbaSVqGOklRSrE52io5sCorRSYrWMrAqKMvNKgOrUbdV1kv7/N9QxAgA "Python 2 – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), 65 bytes ``` #define r;printf("%d=%d\n",a f(a,b){r,b)r+a,b+b)r-=b,-a)r*=a,a);} ``` [Try it online!](https://tio.run/##DYsxCsMwDAB3vyK4BKRGHlq6FOOfZFHiuBhaEZR0Cnm7o@XulpvD/GX5tHbLS6mydBpXrbIX8H1OfR7FE7sCTBMeatDBcjCHNFFg1HtiYoxns6v7cRVAd9jxoCdGt/73Dby3KvCit/lsFw "C (clang) – Try It Online") Uses [ophact's approach](https://codegolf.stackexchange.com/a/226648/98541). Using clang instead of gcc saves a byte, as clang handles the undefined behavior in the second `printf` differently than gcc: ``` printf("%d=%d\n",a-=b,-a); ``` The order of the arguments' evaluation is unspecified. In gcc, the `-a` is evaluated before `a-=b`; thus, the second argument is not affected by the subtraction and must be `b-a` to get the proper value. However, in clang, the `a-=b` is evaluated first so the second argument is affected by the subtraction so `-a` is the correct value. --- # [C (gcc)](https://gcc.gnu.org/), ~~76~~ ~~74~~ 66 bytes *-8 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)* ``` #define r;printf("%d=%d\n",a f(a,b){r,b)r+a,b+b)r-=b,b-a)r*=a,a);} ``` [Try it online!](https://tio.run/##DYsxDsMgDAB3XhFRRbIbMzTKUiF@ksVAqBiKIjedorydeLm75ZL7pNT7I2@ltm0Qv0ttRwE75jDmtVliU4Ap4ikKmTQntQuRomOUZ2Bi9FfXbfhybYDm1OVFM3qz/48fWKtVYKG3@uo3 "C (gcc) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` ≔⁻⊗θΣθηE⟦θ⊗θηXη²⟧⪫ι= ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DNzOvtFjDJb80KSc1RaNQU0chuDQXSAMZGZrWXAFFmXklGr6JBRrRhToKyMoydBQC8stTizSADCPNWB0Fr/zMPI1MHQUlWyVNTU3r//@jo010FCxjY//rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list `[a, b]`. Explanation: Based on @ophact's approach. ``` ≔⁻⊗θΣθη ``` Vectorised subtract the sum of the list from its double, thus giving `[a-b, b-a]`. ``` E⟦θ⊗θηXη²⟧⪫ι= ``` Loop over the lists `[a, b]`, `2[a, b]`, `[a-b, b-a]` and `[a-b, b-a]²`, joining each list with `=` and implicitly printing them on separate lines. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 50 bytes Same as the javascript but using C#'s "superior code golfing" interpolation ``` a=>b=>a+@$"={b} {a+a}={b+b} {a-=b}={-a} {a*=a}="+a ``` [Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXoqOAYBWXFGXmpdvZKaQBhRRsFf4n2tol2dolajuoKNlWJ9VyVSdqJ9YCWdpgtq5tEpCjmwhia9kCJZS0E/9bcznn5xXn56TqhRdllqT6ZOalaoCM07DQ1DDV1LT@DwA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 12 bytes ``` :d?Ḃ-:²Wƛ\=j ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%3Ad%3F%E1%B8%82-%3A%C2%B2W%C6%9B%5C%3Dj&inputs=%5B6%2C%209%5D&header=&footer=) Why write your own original answer when you can just port 05ab1e amiright? :p ## Explained ``` :d?Ḃ-:²Wƛ\=j :d # [a, b], [2a, 2b] ?Ḃ- # [a - b], [b - a] :² # that, but squared Wƛ\=j # join each on "=" and then join that on newlines with the j flag ``` [Answer] # [Julia 1.0](http://julialang.org/), 48 bytes port of [ophact's answer](https://codegolf.stackexchange.com/a/226648/98541) ``` a\b="$a=$b $(2a)=$(2b) $(a-=b)=$(-a) $(a*=a)=$a" ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/PzEmyVZJJdFWJYlLRcMoUdMWSCZpAtmJurZJIJ5uIpinZQuSS1T6X1CUmVeSk6dhGGOkyQXjIFgmMZaa/wE "Julia 1.0 – Try It Online") ## alternative answer, 48 bytes too output is a list of strings ``` a\b=join.([a=>b,2a=>2b,(a-=b)=>-a,a*a=>a*a],'=') ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/PzEmyTYrPzNPTyM60dYuSccISBol6Wgk6tomadra6SbqJGoBhYBErI66rbrmf8MYIwW9GjuFgqLMvJKcvP8A "Julia 1.0 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3), 72 bytes ``` f=lambda a,b:f"{a}={b}\n{2*a}={2*b}\n{a-b}={b-a}\n{(a-b)**2}={(a-b)**2}" ``` Uses [ophact's observation](https://codegolf.stackexchange.com/a/226648/104415) to answer in 4 steps. [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIVEnySpNqTqx1rY6qTYmr9pIC8Q00gJzEnWTQOK6iSCOBpCnqaVlBBSBM5X@/wcA) [Answer] # GolfScript, 37 bytes ``` ~:%;:$' = ':&%n$2*&%2*n$%-&%$-.n\2?.&\ ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v85K1dpKRV3BVkHdSk01T0VFW01VVTtPRVVXTVVFVy8vxsheTy2G6/9/IwVTAA) [Answer] # [Desmos](https://www.desmos.com/), 207 characters [Try it online!](https://www.desmos.com/calculator/crycwwosdl) [Organized for readability](https://www.desmos.com/calculator/rovcaeqlyk) Code: ``` <input 1> <input 2> <input 3> a=ans_0 b=ans_1 c=ans_2 m=-(a+b)/2 #Parenthesises placed here to show that addition occurs before addition; they don't appear in actual graph d=-((a-m)^2-c) l=[a,a+m,(a+m)^2,(a+m)^2+d] l_1=[b,b+m,(b+m)^2,(b+m)^2+d] (-1,[0,-1,-2,-3]) (0,[0,-1,-2,-3]) (1,[0,-1,-2,-3]) (4,0) (4,-1) (4,-2) (4,-3) #LABELS (From higher to lower) ${l} = ${l_1} (given) (${m}) (`^2`) (${d}) ``` Explanation: `a` and `b` are the starting numbers, and `c` is the target number. Like my other programs, `ans_n` correspond to the line number, acting as inputs. `m` is the midpoint of `a` and `b`. The reason that it is subtracted from `a` and `b` is so that they become equidistant from 0. NOTE: `m` is negative simply for formatting the proof; simply treat it as a positive and that all operations involving it are subtractions. `d` is simply the distance between `c` and `(a-m)^2`. The squaring ensures that the term is positive, making both sides of the equation equal to each other. From there, the distance is added on to the result, making both sides of the equation equal to `c`. `l` and `l_1` are lists. This is used to provide the labels. From left to right, the terms in the lists are as follows: the input, the input minus `m`, the square of (the input minus `m`), and the square of (the input minus `m`) plus `d`. The first point, `(-1,[0,-1,-2,-3])`, uses `${l}` as a label. The list within the point creates multiple copies of the point at those y values, and the label uses the corresponding value from `l` to make it have the corresponding value on the graph. For example, `(-1,0)` would have `a` as its label. Likewise, the third point, `(1,[0,-1,-2,-3])`, would use `l_1` to produce its labels in a similar manner. The second point, however, would simply have the label be `=`. Point `(4,0)` has the label `(given)`, which is self explanatory. Point `(4,-1)` has the label `(${m})`, which uses `m` to produce the label of `(m)`. Point `(4,-2)` has the label `(`^2`)`. The backticks are used to format the `^2` as a square and not as `^2`. Point `(4,-3)` has the label `(${d})`, which uses `d` to produce the label of `(d)`. ]
[Question] [ Língua do Pê, or P Language, is a language game spoken in Brazil and Portugal with Portuguese. It is also known in other languages, such as Dutch and Afrikaans. ([Wikipedia](https://en.wikipedia.org/wiki/L%C3%ADngua_do_P%C3%AA)) There are some dialects in this language game. The different languages the game is played with even have their own unique dialects. Some people are fluent in speaking P Language and the best can even translate any text to their preferred dialect on the spot! # P Language In this challenge, we will use the *Double Talk* dialect. To translate text into P Language, any sequence of vowels in the text is appended with a single `p` character followed by a copy of the sequence of vowels. # Challenge Write a function or program that accepts a string as input and outputs its translation in P Language. * The input consists only of printable ASCII characters. * The output consists only of the translated input and optionally a trailing newline. * Vowels are any of the following characters `aeiouyAEIOUY`. * A sequence of vowels is delimited by any other character. The string `"Aa aa-aa"` has three vowel sequences. * Leading and trailing whitespace may optionally be omitted from the translated output string. # Examples ``` "" => "" "Lingua do Pe" => "Lipinguapua dopo Pepe" "Hello world!" => "Hepellopo woporld!" "Aa aa-aa" => "AapAa aapaa-aapaa" "This should be easy, right?" => "Thipis shoupould bepe eapeasypy, ripight?" "WHAT ABOUT CAPS?" => "WHApAT ApABOUpOUT CApAPS?" " Hi " => " Hipi " or "Hipi" ``` The double quotes character `"` is used to delimit the input and output strings in the examples but obviously this character may also appear in any valid input string. [Answer] # JavaScript (ES6), 35 bytes ``` s=>s.replace(/[aeiouy]+/gi,'$&p$&') ``` [Try it online!](https://tio.run/##fdHBToNAFIXhvU9xJU0LsS1PUBt0w6KJTaxxYVzcwhTGTJgTpmj69Dh36IqKLAiL7/xh4Iu/2RWtxnnV2FL1p03vNo9u3SoYLlScfrDStrt8PqSVXi5mc8zmi6QvbOOsUWtjq/gUR1GS0D9XmlIU3Y02O91UHVNpaa/@2MtmpxEQgoNIqJtQroyx9GNbU95PhHK/8wjCMMBxJWNiXjFPHEUqGSMoBOjvN5FDrR252nampKMixe6ypFZX9XkrXYl4givC1UEkBCNwDINx/D3PDpQ9vbwd6Dnbv25HbypxTyAIwjBIBDuO@UGuafK/SSwQeES29Z/QP0b9Lw "JavaScript (Node.js) – Try It Online") Where the special replacement pattern `$&` means *[matched substring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter)*. [Answer] # Sed, ~~30~~, ~~25~~, ~~21~~, 19 Bytes -5 Bytes Thanks to Arnauld! -4 Bytes Thanks to Shaggy! -2 Bytes Thanks to Leo Tenenbaum! ``` s/[aeiouy]\+/&p&/gi ``` [Try it Online!](https://tio.run/##BcGxCsIwEAbg/Z7id@mikkco0SWDYMEUB3U4yZEcBCONofTp4/dVCb1X82DR0rbXc2@G72Ci9k4X/cTGCAWTkJOcC9ay5LAjy2A@MpNPWlFTaTngLRCu2wGLxvQb6e6shz1dZ4@znW4jAXCKPw) [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 bytes ``` r"%y+"_+ip ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIleSsiXytpcA&input=IkhlbGxvIHdvcmxkISI) ``` r"%y+"_+ip :Implicit input of string r :Replace "%y+" :RegEx /[aeiouy]+/gi _ :Pass each match through a function + : Append a copy of the match ip : Prepended with "p" ``` [Answer] # Java 8, 40 bytes ``` s->s.replaceAll("(?i)[aeiouy]+","$0p$0") ``` [Try it online.](https://tio.run/##ZVDBbsIwDL3zFV6ERKrSivPQhrpdetgYUjvtABxMm9GwkFRNwlRNfHsXSjh0u1i233t@tg94wuhQfnWFQK3hFbn8GQFwaVjziQWD5aUEyEzD5R4K6hMdzF3/PHJBGzS8gCVIeOh09KjjhtXCaRMhKKELHqyRcWXbbUimZDyrxzMSdPOLtLY74aR@wknxEo5uA2@y3gIGV3vDtKGE9Ka36sVRLEKpYMWGSMqEUPCtGlHeDZEEATFCHHbzimvQlbKihB0DhrqdQsP3lVkMiR9pkkPy9Paew3Oyyv6gLkk5kH@f6e/qKf55XNbW@MuyVht2jJU1ce1AIySdkEnYU0KyIfewISSUcUGvqtCh3uHc/QI) **Explanation:** ``` s-> // Method with String as both parameter and return-type s.replaceAll("(?i)[aeiouy]+", // Replace the regex matches "$0p$0") // With this replacement ``` *Regex explanation:* ``` (?i)[aeiouy]+ // MATCH: (?i) // Enable case insensitivity + // Match one or more [aeiouy] // Adjacent vowel characters $0p$0 // REPLACEMENT: $0 // The entire match (the vowel 'sequence') p // Appended with a literal "p" $0 // Appended with the entire match again ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 20 bytes ``` s/[aeiouy]+/$&p$&/gi ``` [Try it online!](https://tio.run/##BcGxCsIwEAbg/Z7iF0oXLZmcS3TpULBgxUEcThqSg9ALTYv05Y3fl9wSz6Vk82Inuu3vo6nqVNXGSynUy@w3xqQYHHUuRsVXlzgdyDKYG2Yag2TkoFuc8HFwnPcTFvFhbenZ2RH2cnuMuNrh3hKATvDTtIrOuTTpDw "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 55 bytes ``` lambda s:re.sub('([aeiouy]+)',r'\1p\1',s,0,2) import re ``` [Try it online!](https://tio.run/##BcHBSsQwFAXQfb7iumqCURxdCAMyVDddCA5YcWEHeaVp@yCThJcE6dfXc9JW1hie9vll2D1dx4mQj@Lucx11o3/Icazb5dY0VprhkIZDY7N9sI9G8TVFKRC3z1HwCw4QCovTz@aYhEPRs@aQatHGmF29c1gqYYo4O9U57yP@ovjpRrUEojsi1a@ckddY/YTRwVHeLISXtZzUd9f2aF8/vnq8tefPkwLQMf4B "Python 3 – Try It Online") --- Sans regex: # [Python 3](https://docs.python.org/3/), 101 bytes ``` def f(s,q=''):i=s[:1];t=i in{*'aeiouyAEIOUY'};return(q+(q!='')*'p'+q+i)*0**t+(s and f(s[1:],(q+i)*t)) ``` [Try it online!](https://tio.run/##HYxbS8MwFIDf8yvOnnJpBYcPQkcZUYQKwgZ2yBhjnJG0PVCSNkmRIv72uvn8XYY5dd49LYuxDTQi5mPJuSyojKdifd6kkoDcj@JoyU@zfnvfHY78dxNsmoITYybG1T1QfODZmJFUj0qlTERAZ@6/07o45@KfJCmXxge43I4Q0LVWPMtiCOSSaAS5YUpC3hz2Qa6dEIyHvWWV7XsP3z70ZsU0AuIDIqs7ihA7P/UGrhYsxjmHQG2Xtuyr0jXol92hhle9/9wyAKgI/gA "Python 3 – Try It Online") Python 3.8 (pre-release): [99 bytes](https://tio.run/##DYxdS8MwFIbv8yvOrvLRDhxeKIEy6hAqCBvYIWMMOaNpe6AmaZIiRfzttXfvA8/z@jn1zj4@@7AsbTHg971BiPlYcK7FmIlxsy6puOfZSqSLeNW7m5TqQSmRdEFA9ldxNOSmuXx9O54v/E9mIgLaBloRrzt9y9cnkipJubQuwNfaQEDbGfEktQ9kk2gFWT8lIVeHvZPtJoTGwcmwygyDgx8XhmbDSgTELSKre4oQezcNDdwNGIxzDoG6Pu3ZZ1XWUL4czzUcytPHngFARfAP "Python 3.8 (pre-release) – Try It Online") ## Explanation Recursive function, accepting a string `s` and an optional argument `q`. If the first character of `s` (`i`) is a vowel, it is stored in the queue `q`. If not, a string is returned which is composed of `q`, the letter `'p'`, `q` again, the character `i` and the result of the recursive function with the first character of the string stripped off. Recursion stops when the function encounters an empty string `s`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .γžÁyå}vyžÁyнåi'py}J ``` 05AB1E doesn't have any regexes unfortunately. I don't really like the duplicated `žÁyнå`, but I'm currently a bit too busy to look for alternatives.. -2 bytes thanks to *@Grimy* for showing me a constant I didn't even knew existed (and was missing from the Wiki page.. >.>) [Try it online](https://tio.run/##yy9OTMpM/f9f79zmo/sON1YeXlpbVglmXdh7eGmmekFlrdf//yEZmcUKxRn5pTkpCkmpCqmJxZU6CkWZ6Rkl9gA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf71zm4/uO9xYeXhpbVklmHVh7@GlmeoFlbVe/2t1/nuk5uTkK5TnF@WkKHI5JiokJuomJnKFZGQWKxRn5JfmpCgkpSqkJhZX6igUZaZnlNhzhXs4hig4OvmHhig4OwYE23MpKCh4ZCoAAA). **Explanation:** ``` .γ # Group the characters in the (implicit) input-string by: žÁ # Push vowels builtin: "aeiouyAEIOUY" yå # And check if the current character is in this string }v # After grouping: loop over each group `y`: y # Push group `y` žÁyнåi } # If the first character of the group is a vowel: 'p '# Push a "p" y # And push group `y` again J # Join everything on the stack together to a single string # (after the loop, implicitly output the result) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 17 bytes ``` i`[aeiouy]+ $&p$& ``` [Try it online!](https://tio.run/##BcFBCsIwEAXQ/ZziC6Ub9QwluslCsGBKFyI4kqEZCI0kDdLTx/eybLpya/p@smiq@@tIXf/t@tboputSGT5hFLISY8Iv5egPZBjMZ2ZyQQtKSDV6fATCZT8h6xK2gWZrHMzlPjlczfgYCIBV/AE "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Trivial regexp approach; the `i` flag turns on case insensitivity (Retina already defaults to a global match). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` Żṁe€ØyŒg$$,j”pƊ€ÐeẎḊ ``` [Try it online!](https://tio.run/##y0rNyan8///o7oc7G1MfNa05PKPy6KR0FRWdrEcNcwuOdYGEJqQ@3NX3cEfX////lXwy89JLExVS8hUCUpUA "Jelly – Try It Online") [Answer] # [Red](http://www.red-lang.org), 92 bytes ``` func[s][v: charset"aeiouyAEIOUY"parse s[any[to v copy t any v insert(rejoin["p"t])| skip]]s] ``` [Try it online!](https://tio.run/##TYrBasMwEETv@YqpTi00P5BLUEvBhUJC4lCK0GFrrWMlRhJaOcXQf3fdS@vTzJs3md10YGfsqt1gaofQGLHmtkHTURYuitjHYdQvr7vTh0q/G8RQGE2JuKGJaUTBzDP4IJzLfeZL9MGopIp9@IZcfbJW7JSyDwUtlFr91TcfzgPBRexZAf@i4r6P@Iq5d3eLvyYQrYkWU915gXRx6B0@GUwyPiL7c1e2i9d7pWvop92pxrPeH5cKQOXnmH4A "Red – Try It Online") Of course [Red](http://www.red-lang.org)'s `Parse` is much more verbose than `regex`. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 97 bytes ``` I =INPUT S I ARB . L SPAN('AEIOUYaeiouy') . V REM . I :F(O) O =O L V 'p' V :(S) O OUTPUT =O END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/n9NTwdbTLyA0hCsYyHQMclLQU/BRCA5w9NNQd3T19A@NTEzNzC@tVNcESoQpBLn6AmlPTis3DX9NLk5/BVt/oPIwBfUCdYUwTiuNYE0uf07/0BCggUApLlc/l///fTLz0ksTFVLyFQJSAQ "SNOBOL4 (CSNOBOL4) – Try It Online") Vowel clusters match `SPAN('AEIOUYaeiouy')`. [Answer] # [Stax](https://github.com/tomtheisen/stax), 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` àº`≈Zö=q╦ⁿ↔èblTï÷ ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=85a760f75a943d71cbfc1d8a626c548bf6&i=%0ALingua+do+Pe%0AHello+world%21%0AAa+aa-aa%0A%22This+should+be+easy,+right%3F%0AWHAT+ABOUT+CAPS%3F%0A+++Hi+&a=1&m=2) ### Unpacked (20 bytes) and explanation: ``` Vv'y+c^+:}'++{'pnL}R R Regex replace using Pattern: Vv'y+ Push "aeiou", push "y", and concatenate c^+ Copy, convert copy to all caps, and concatenate :} Enclose in [] '++ Push "+" and concatenate And replacement: { } Block: 'p Push "p" n Copy second item (matching substring) to top L Listify Implicit concatenate Implicit print ``` No case-insensitive regular expressions in Stax, and the vowel builtins don't include Y. The documentation won't tell you about using a block as a replacement, but it's a working feature nevertheless. ]
[Question] [ ## Happy birthday to Me! Write a program that prints `Happy birthday to me!` on its birthday. 1. The program's birthday is the creation, last modification or compilation time of the program (you choose), and must not be hard-coded. 2. The date you use as the birthday must not be affected by the program's invocation or execution in any way. You can't modify your birthday. 3. For extra credit (-15% byte count), print `Happy birthday to you!` on your birthday (hard coded), [if it doesn't coincide](http://xkcd.com/680/) with the program's. Or use some celebrity's birthday and get -14%. 4. It must print only this, and not print anything on any other day. 5. Count bytes, in UTF-8. 6. Use the Gregorian calendar. Good luck and happy birthday (to the newborn programs). P.S. Following Izkata's comment, if you print `Happy birthday to Mel` on [Mel Kaye](http://www.catb.org/jargon/html/story-of-mel.html)'s birthday, you get 20% off. But you have to provide a credible source that it's this date. [Answer] # bash - 65 ``` [ `date +%d%m -r $0` = `date +%d%m` ]&&echo Happy birthday to me! ``` Thanks to *ugoren*, *ace* and *nyuszika7h* for help. [Answer] ## PHP ~~77~~ ~~75~~ ~~74~~ ~~65~~ 60 Many thanks to the superb suggestions from [Tim Seguine](https://codegolf.stackexchange.com/questions/21285/happy-birthday-to-me/21294#comment43024_21294): ``` <?date(dm,getlastmod())-date(dm)&&die?>Happy birthday to me! ``` ## Sneaky PHP: ~~46~~ ~~42~~ ~~41~~ 40 Using [Phil H's idea](https://codegolf.stackexchange.com/a/21291/4040) and again [Tim Seguine's suggestion](https://codegolf.stackexchange.com/questions/21285/happy-birthday-to-me/21294#comment43024_21294): ``` <?touch(__FILE__)?>Happy birthday to me! ``` [Answer] # C# 198.05 (233 - 15%) ``` using s=System;class P{static void Main(){string t=s.DateTime.Now.ToString("Mdd"),b="1202";if(s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd")==t|b==t)s.Console.Write("Happy birthday to "+(b==t?"you!":"me!"));}} ``` Formatted: ``` using s = System; class P { static void Main() { string t = s.DateTime.Now.ToString("Mdd"), b = "1202"; if (s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd") == t | b == t) s.Console.Write("Happy birthday to " + (b == t ? "you!" : "me!")); } } ``` # 191 (No bonus) ``` using s=System;class P{static void Main(){if(s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd")==s.DateTime.Now.ToString("Mdd"))s.Console.Write("Happy birthday to me!");}} ``` # 181,05 (213 - 15%) With some additional instructions (you need to compile this to `b.exe` and run it from the directory the executable is in) I can get it down to this: ``` using s=System;class P{static void Main(){string t=s.DateTime.Now.ToString("Mdd"),b="1202";if(s.IO.File.GetCreationTime("b.exe").ToString("Mdd")==t|b==t)s.Console.Write("Happy birthday to "+(b==t?"you!":"me!"));}} ``` # 171 (No bonus) Same instructions as above, this time only printing a message on it's own birthday (so no -15% bonus). ``` using s=System;class P{static void Main(){if(s.IO.File.GetCreationTime("b.exe").ToString("Mdd")==s.DateTime.Now.ToString("Mdd"))s.Console.Write("Happy birthday to me!");}} ``` [Answer] # Java - 275 - 15% = 233.75 with bonus / 237 without bonus With bonus: ``` import java.util.*;class L{public static void main(String[]y){int s=f(new Date());String j="Happy birthday to ";System.out.print(s==f(new Date(new java.io.File("L.class").lastModified()))?j+"me!":s==183?j+"you!":"");}static int f(Date d){return d.getMonth()*40+d.getDate();}} ``` Without the bonus: ``` import java.util.*;class L{public static void main(String[]y){if(f(new Date())==f(new Date(new java.io.File("L.class").lastModified())))System.out.print("Happy birthday to me!");}static int f(Date d){return d.getMonth()*40+d.getDate();}} ``` I was born in April, 23rd. [Answer] ## Matlab: 66 ``` t=dir('f.m');if strncmp(t.date,date,5),'Happy birthday to me!',end ``` File name has to be 'f.m' [Answer] I'm pretty proud of this little trick to save a few bytes on the message. I hope it will be included in other answers. I was the first to think of this! # Python 105 characters, no extra credit. Save the file as "happy birthday to me" and run. Runs in GMT only, and "birthday" is defined as the date of your birth, not it's anniversary (also often call "birthday"). ``` import sys,os,time if (int(os.stat(*sys.argv).st_atime/86400)==int(time.time()/86400)):print sys.argv[0] ``` For it to work, save this as "happy birthday to me" and run `python "happy birthday to me"` Note: of course, the all but a small bootstrap could be in the filename, making any arbitrarily large code reduce down to the bootstrap. Normally I would consider this "cheating". However, "happy birthday to me" is not an unreasonable filename - it describes what the program does, much better than some programs (e.g. "python"), so in this case I'm going to allow it :) [Answer] **GNU COBOL** with -free, **204** ``` PROGRAM-ID.B.DATA DIVISION.WORKING-STORAGE SECTION. 1 A PIC XXXX/XX. 1 B PIC X(5). 1 C PIC X(21). PROCEDURE DIVISION.ACCEPT A FROM DATE ACCEPT C MOVE WHEN-COMPILED TO B IF A(3:5) = B OR "12/09" DISPLAY C. ``` I break the rules about the celebrity, so no bonus there... The text produced is user-input (requested when run). If that is not good-to-go, then the line defining `C` needs to be deleted, as does `ACCEPT C`, and `DISPLAY C` must become `DISPLAY "HAPPY BIRTHDAY TO ME!"`, for an extra seven characters. `WHEN-COMPILED` is a special-register containing compile date/time which is available to the program (always handy, you can know you have the correct version). It is truncated in the `MOVE` because the rest isn't needed. `DATE` is the current date - this one is yymmdd. The `/` in the definition of A is an insertion editing symbol, since the compile-date contains slashes. An extra character, but eases the compare. [Celebrity = Grace Hopper](http://www.google.com/doodles/grace-hoppers-107th-birthday) [Answer] ## Batch - 37 Bytes Stealing the method used by one of the Bash answers.. ``` @echo.>>%0&echo Happy birthday to me! ``` **Other method - 145 Bytes** ``` @for /f "tokens=2,3 delims=/ " %%a in ("%date%")do @for /f "tokens=1,2 delims=/" %%c in ("%~t0")do @if %%a%%b==%%c%%d @echo Happy Birthday to me! ``` [Answer] # Ruby, 69 characters/bytes ``` puts'Happy birthday to me!'if(Time.new-File.atime($0))%31536000<86400 ``` `31536000` is the number of seconds in a year, and `86400` is the number of seconds in a day. [Answer] # JavaScript ## Node.js, 156 bytes ``` b=new Date(require("fs").statSync(__filename).mtime);d=new Date();b.getDate()==d.getDate()&&b.getMonth()==d.getMonth()&&console.log("Happy birthday to me!") ``` Uses the file's modification time. [Answer] # Powershell - 105 bytes ``` if('{0:M}'-f(gi $MyInvocation.MyCommand.Definition).creationtime-eq(date -f M)){'Happy birthday to me!'} ``` Ungolfed: ``` if('{0:M}' -f (gi $MyInvocation.MyCommand.Definition).creationtime -eq (date -f M)){ 'Happy birthday to me!' } ``` The bonus isn't worth it, I can only get 117.5. [Answer] ### Powershell - 127 ``` if ((gci $MyInvocation.MyCommand.Path).lastwritetime.ToString("MMdd") -eq (get-date).ToString("MMdd")){"happy birthday to me!"} ``` ### For the 15% bonus - 151 bytes, less 15% = 128.4 ``` $r=@{"0308"="you";(gci $MyInvocation.MyCommand.Path).lastwritetime.ToString("MMdd")="me"}[(get-date).tostring("MMdd")] if($r){"Happy birthday to $r!"} ``` [Answer] ## Ruby - ~~80~~ ~~103~~ 87 bytes ``` m=File.mtime $0 t=Time.now puts"Happy birthday to me!"if t.month==m.month&&t.day==m.day ``` --- ## Ruby - ~~123~~ ~~115~~ ~~135~~ 121 - 15% = ~~104.55~~ ~~97.75~~ ~~114.75~~ 102.85 points ``` t=Time.now {me:File.mtime($0),you:Time.at(36e5)}.map{|n,d|puts"Happy birthday to #{n}!"if t.month==d.month&&t.day==d.day} ``` Might be a little longer or shorter depending on where your birthday falls in the year, and the shortest way to represent that. For mine, that's `36e5` (seconds since epoch; time zone dependent). --- Does Mel **Gibson** count? Here's a 138 byte - 35% bonus = **89.7-point** program that celebrates itself, me, and Mel! ``` t=Time.now {me:File.mtime($0),you:Time.at(36e5),Mel:Time.at(2e5)}.map{|n,d|puts"Happy birthday to #{n}!"if t.month==d.month&&t.day==d.day} ``` [Answer] # PureBasic ## Without Bonus - 142 ``` If Bool(FormatDate("%dd%mm",Date())=FormatDate("%dd%mm",GetFileDate(ProgramFilename(),0))) MessageRequester("","Happy birthday To me!") EndIf ``` ## With Bonus - 218 - 15% = 185.3 ``` Dim s$(2) s$(1)="me" s$(2)="you" m$="%dd%mm" d$=FormatDate(m$,Date()) i=Bool(d$=FormatDate(m$,GetFileDate(ProgramFilename(),0)))|(Bool(d$="2301")<<1) If i=0:End:EndIf MessageRequester("","Happy birthday To "+s$(i)+"!") ``` [Answer] ## TI-BASIC, 68 bytes ``` If Ans=0:getDate→G:0:G=G:If getDate=G:Disp "HAPPY BIRTHDAY TO ME!" ``` Remember, these tokens are one byte: `If , Ans, →, Disp`. `getDate` is two bytes. All other one-character symbols are one byte. [Answer] # J 79 ``` echo((6!:0'')(('',:'Happy birthday to me!'){~])@:-:&(1 2&{)&:>])1{,1!:0{:4!:3'' ``` ### Bonus version120 - 15% = 102 Do I get extra credit for also printing both when both are having their birthday? ``` echo((2 6$(6!:0 '') , 0 2 7)(' ','Happy birthday to ',"2 1]3 5$'you! me! both!'){~#.@:(-:&(1 2&{)"1)&:>])1{,1!:0{:4!:3'' ``` Explanation (right to left): ``` last =: {:4!:3'' NB. Take the last script run (i.e. the file itself) time =: 1{,1!:0 last NB. the modification time is the second element in that file's listing ``` The central verb of the [train](http://www.jsoftware.com/help/dictionary/dictf.htm) ``` unbox_both =: &:> NB. unboxes left and right argument match =: -:&(1 2&{)"1 NB. for each date given, left and right, compare them to_int =: #. NB. convert boolean to int from =: {~ NB. from the left array, take element right. NB. H contains messages an empty row, appended to all combinations of messages. H =: (' ','Happy birthday to ',"2 1]3 5$'you! me! both!') V =: (H from to_int)@:match unbox_both NB. after unboxing and comparing, NB. select the according message ``` The left tine for the central train: ``` dates=: (2 6$(6!:0 '') , 0 2 7) NB. the current date, and the relevant fields of my birthday. NB. Combining the bricks: echo (dates V ]) time NB. output the monads result on time. ``` [Answer] # Java - 196 This differs from the other Java submission by using Strings, shaving 41 characters off in the process. It uses String.format("%tj") to format a java.util.Date or a long as a day-of-year String, and then compares these two Strings. ``` class Z{public static void main(String[]y){if("".format("%tj",new java.util.Date()).equals("".format("%tj",new java.io.File("Z.class").lastModified())))System.out.print("Happy birthday to me!");}} ``` Formatted: ``` class Z { public static void main(String[] y) { if ("".format("%tj", new java.util.Date()).equals("".format("%tj", new java.io.File("Z.class").lastModified()))) System.out.print("Happy birthday to me!"); } } ``` [Answer] ## C# 191 no bonus ``` using s=System;class P{static void Main(){if(s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd")==s.DateTime.Now.ToString("Mdd"))s.Console.Write("Happy birthday to me!");}} ``` formatted: ``` using s = System; class P { static void Main() { if (s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd") == s.DateTime.Now.ToString("Mdd")) s.Console.Write("Happy birthday to me!"); } } ``` [Answer] **JavaScript (node.js) - 100 bytes** ``` (require('fs').fstatSync(4).mtime+1).match(Date().substr(4,6))&&console.log('Happy birthday to me!') ``` [Answer] **vb.net ~161c** This will print the celebration message to all whose birthday it is. ``` Module M Sub Main For Each b In{({"1705","Alan"}),({"2012","You"}),({FileDateTime(Process.GetCurrentProcess.MainModule.FileName).ToString("ddMM"),"Me"})} If b(0)=Now.ToString("ddMM") Then Console.WriteLine("Happy Birthday To {0}!",b(1)) Next End Sub End Module ``` Alan => Alan Kaye Score: 253c (-33c vb.net min) = 220 - 15% (my birthday bonus) = 187c - 14% (Celeb Birthday) = 160.82 ~161c or 220c - 29% = 156.2 ~157c [Answer] # Powershell, 82 bytes > > see also answers from [Chris J](https://codegolf.stackexchange.com/a/21306/80745) and [SpellingD](https://codegolf.stackexchange.com/a/21431/80745) > > > ``` "Happy birthday to me!"|?{(gv My* -v|% M*|% p*h|gci|% l*w*e|% D*r)-eq(date|% D*r)} ``` where ``` gv My* -v|% M*|% p*h|gci|% l*w*e|% D*r ``` is the combinations of [shortcuts](https://codegolf.stackexchange.com/a/111526/80745) and [aliases](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_aliases) for the expression: ``` Get-Valiable MyInvocation -value|% MyCommand|% Path|Get-ChildItem|% LastWritetime|% DayOfYear ``` that equivalent a canonical form: ``` (Get-ChildItem $MyInvocation.MyCommand.Path).LastWritetime.DayOfYear ``` --- # Powershell, 119 bytes - 14% = 102.34 Points ``` filter e{$_-eq(date|% D*r)}$('me'|?{gv My* -v|% M*|% p*h|gci|% l*w*e|% D*r|e} 'Prof'|?{3|e})|%{"Happy birthday to $_!"} ``` At [January 3](https://en.wikipedia.org/wiki/J._R._R._Tolkien), the script display `Happy birthday to Prof!`. If this script is saved on January 3, two greetings will be displayed. ]
[Question] [ This challenge initially appeared in [this challenge](https://codegolf.stackexchange.com/questions/141315/) as a an extra brain teaser. I am posting it with permission from the original author so that we can have a formal competition. --- Your task here will be to implement a function1 that forms a permutation on the positive integers. This means that each positive integer should be the output of calling the function with exactly one positive integer. In the earlier challenge we calculated the odd probability for such sequences. We defined it as so: If we have a function \$f\$ the probability of a number being odd will be defined as the limit of ratio odd members of the set to the size of the set \$f\{1\dots n\}\$ as \$n\$ tends towards infinity. $$\lim\_{n\rightarrow \infty}\dfrac{\left|\{x : x \in \{1\dots n\}, \mathrm{odd}(f(x))\}\right|}{n}$$ Your task is to write a function with no defined odd probability. That is a function \$f\$ for which the above limit does not converge. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better. --- 1: Here function will mean program or function. It is just a piece of code that takes input and produces output. [Answer] # JavaScript (ES7), ~~33~~ 29 bytes This is [A307485](https://oeis.org/A307485): one odd, two even, four odd, eight even, etc. ``` n=>n-~n-(4<<Math.log2(n))/3|0 ``` [Try it online!](https://tio.run/##Fcs5DoAgEADA3ldsCTEoHp3gD3wEUfCI2TVobDy@jtJNM4s5zd77eTsE0mCD0wF1i@JFwWqlOnNM2UpjyZDzvLplcOQZgoaiAQQFhZQ/0pTDlQD0hDutNg7mYmmSJ3w "JavaScript (Node.js) – Try It Online") For \$n\in\mathbb{N}^\*\$, this is equivalent to: $$a(n)=2n+1-\left\lceil\frac{2^{\lfloor log\_2 n\rfloor+2}}{3}\right\rceil$$ It produces the sequence: ``` 1 2 4 3 5 7 9 6 8 10 12 14 16 18 20 ... ``` The ratio of odd values is 'bouncing' ad infinitum between \$1/3\$ and \$2/3\$, more and more slowly: [![graph](https://i.stack.imgur.com/cYEZ6.png)](https://i.stack.imgur.com/cYEZ6.png) [Answer] # [sed](https://www.gnu.org/software/sed/) -E, ~~20~~ 17 bytes ``` s/\B(.)(.*)/\2\1/ ``` [Try it online!](https://tio.run/##K05N0U3PK/3/v1g/xklDT1NDT0tTP8YoxlD//39TI3Nji3/5BSWZ@XnF/3VdAQ "sed – Try It Online") *Saved 3 bytes as per user41805's suggestion.* This takes the input number and moves the 2nd digit (from the left) to the end of the number (the one's place). The numbers from 1 to 10*n* are just rearranged, so the proportion of odd numbers for inputs up to 10*n* is 0.5. All the numbers from 10*n*+1 to 10*n*+10*n*-1-1 map to even numbers, so the proportion of odd numbers for inputs up to 10*n*+10*n*-1 is $$\frac{10^n/2+1}{10^n+10^{n-1}}=\frac{5+10^{-(n-1)}}{11},$$ which approaches 5/11 as *n* approaches infinity. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~18~~ ~~17~~ 16 bytes ``` :"vtn@W:2e+!h]G) ``` [**Try it online!**](https://tio.run/##y00syfn/30qprCTPIdzKKFVbMSPWXfP/fyNDAA) This produces the following permutation of the positive integers: ``` 1 2 3 5 4 6 7 9 11 13 8 10 12 14 15 17 19 21 23 25 27 29 16 18 20 22 24 26 28 30 ... ``` The pattern is easier to see if the sequence is arranged as follows (read top to down, then left to right): ``` 1 2 3 5 4 6 7 9 11 13 8 10 12 14 15 17 19 21 23 25 27 29 16 18 20 22 24 26 28 30 ... ``` It's clear that the cumulative proportion of odd values has limit superior `2/3` and limit inferior `1/2`. Or see the proportion graphically at [**MATL Online!**](https://matl.io/?code=%3A%22vtn%40W%3A2e%2B%21h%5DoYstf%2FXG+&inputs=10%0A%25+Let+the+input+number+be+n.+Then+the+code+produces+the+first+2%5E%28n%2B1%29+terms+of+the+sequence%2C+and+plots+its+cumulative+odd+ratio&version=22.2.0) ### Explanation The code produces a longer sequence than needed (with length exponential in the input number), and then outputs the term specified by the input. ``` : % Implicit input, n. Push range [1 2 ... n] " % For each k in [1 2 ... n] v % Concatenate stack vertically. This is only useful in the first % iteration, to produce the empty array [], which will later be % extended with terms of the sequence tn % Duplicate sequence so far. Push its number of elements, say m @W: % Push range [1 2 3 ... 2^k] 2e % Arrange as a two-row matrix in column-major order. Gives % [1 3 5 ... 2^k-1; % 2 4 6 ... 2^k] + % Add, element-wise. Gives % [m+1 m+3 m+5 ... m+2^k-1; % m+2 m+4 m+6 ... m+2^k] !h % Transpose, then concatenate into a row vector. This extends the % sequence. The transpose is needed so that, when concatenating, % the terms are included in the correct order ] % End G) % Take the n-th entry. Implicit display ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~8~~ 4 bytes ``` ⌽1⌽⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@jnr2GQPyodx6I/z@Ny8jE3NjUzIgrjcvSwMAQSBkCAA "APL (Dyalog Extended) – Try It Online") Based on [xnor's idea](https://codegolf.stackexchange.com/a/200948/78410) to keep the first digit and reverse the rest. A full program that takes the input from STDIN as a string, rotates left once (`1⌽`), reverses (`⌽`), and prints to STDOUT. --- # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 8 bytes ``` ⊥1,1⌽1↓⊤ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HXUkMdw0c9ew0ftU1@1LXkf9qjtgmPevse9U319H/U1XxovfGjtolAXnCQM5AM8fAM/p92aIXCo97NxoYA "APL (Dyalog Extended) – Try It Online") Generates a sequence that is very similar to [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/200923/78410): ``` 1 2 3 4 6 5 7 8 10 12 14 9 11 13 15 16 18 20 22 24 26 28 30 17 19 21 23 25 27 29 31 ... ``` ### How it works ``` ⊥1,1⌽1↓⊤ ⊤ ⍝ Convert to binary digits 1↓ ⍝ Remove the leading 1 1⌽ ⍝ Rotate left once; move 2nd bit to last 1, ⍝ Add back the leading 1 ⊥ ⍝ Convert binary digits to integer ``` [Answer] # [Haskell](https://www.haskell.org/), 18 bytes ``` f(h:t)=h:reverse t ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00jw6pE0zbDqii1LLWoOFWh5H9uYmaegq1CbmKBr4JGQWlJcEmRT55eml5xRn65pkK0gY6pjqGRMRAbAJkGBqax//8lp@Ukphf/100uKAAA "Haskell – Try It Online") Based on [Mitchell Spector's idea](https://codegolf.stackexchange.com/a/200926/20260). Leaves the first digit in place and reverses the rest. Input and output are as strings. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~6~~ 5 bytes ``` ,V1,` ``` [Try it online!](https://tio.run/##K0otycxLNPz/XyfMUCfh/38DLlMuQyNjIDYAMg0MTAE "Retina – Try It Online") Link includes test cases shamelessly stolen from @xnor. Uses the same suffix reversal algorithm inspired by @MitchellSpector's `sed` answer. Edit: Saved 1 byte thanks to @FryAmTheEggman. Explanation: ``` V` ``` Reverse the matched characters (defaults to matching each line). ``` , ``` Reverse all matches ``` 1, ``` Exclude the first character of each match from being reversed. (`^0` also works.) [Answer] # [Python](https://docs.python.org/2/), 22 bytes ``` lambda s:s[0]+s[:0:-1] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYqjjaIFa7ONrKwErXMPZ/Wn6RQqZCZp5CtIGOqY6hkTEQGwCZBgamsVZcnAVFmXklCpk6CmkaxSVFGpmamv8B "Python 2 – Try It Online") Based on [Mitchell Spector's idea](https://codegolf.stackexchange.com/a/200926/20260). Leaves the first digit in place and reverses the rest. Input and output are as strings. [Answer] # Pure [Bash](https://www.gnu.org/software/bash/), 27 bytes ``` echo ${1:0:1}${1:2}${1:1:1} ``` [Try it online!](https://tio.run/##S0oszvj/PzU5I19BpdrQysDKsBZEG4FJIKz9//@/oZGxiSkA "Bash – Try It Online") This uses the same method as my sed answer. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~18~~ 17 bytes ``` (.)(.)(.*) $1$3$2 ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0NPE4y0NLlUDFWMVYz@/zcyNjE1@w8A "Retina – Try It Online") This is a port of my sed answer (moving the second digit to the far right). I've never programmed in Retina before, so I took a quick look at the language documentation and put this together. I assume that it can be made much shorter using more advanced features of Retina. Also, if there's any error in the Retina code, please let me know. It does appear to work :) . [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes ``` §θ⁰⮌✂θ¹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMOxxDMvJbVCo1BHwUBT05oLIhqUWpZaVJyqEZyTmZwKkjPUBEr@/29oZGxi@l@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. This is the Charcoal port of the 6-byte Retina 1 answer that I alluded to in my comments to @MitchellSpector's `sed` answer, and then presumably independently discovered by @xnor. I/O as strings (which Charcoal defaults to anyway). Explanation: ``` §θ⁰ ``` Print the first character of the input number. ``` ⮌✂θ¹ ``` Print the remaining characters of the input number, but reversed. ]
[Question] [ ## ...or Toroidal Moore Neighbourhoods Given positive integers `h`, `w` and a non-negative integer `i`, return all of the indices surrounding `i`. You are to assume a matrix consisting of `h` rows of `w` elements, numbered from lowest, in the top left-hand corner, to highest, in the bottom right-hand corner, and return, in any reasonable format, a list of the indices that would surround the index, `i`. This matrix is a torus (an infinite map that wraps around each edge). For example, inputs `h=4` and `w=4`, would result in the matrix: ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ``` but more specifically: ``` **15 12 13 14 15 12** **3** 0 1 2 3 **0** **7** 4 5 6 7 **4** **11** 8 9 10 11 **8** **15** 12 13 14 15 **12** **3 0 1 2 3 0** ``` so that if `i` was `0`, you'd need to return `15, 12, 13, 3, 1, 7, 4, 5` (0-based). ## Examples *0-based:* ``` h w i Expected result 4 4 5 0, 1, 2, 4, 6, 8, 9, 10 4 4 0 15, 12, 13, 3, 1, 7, 4, 5 4 5 1 15, 16, 17, 0, 2, 5, 6, 7 1 3 2 1, 2, 0, 1, 0, 1, 2, 0 1 1 0 0, 0, 0, 0, 0, 0, 0, 0 ``` *1-based:* ``` h w i Expected result 4 4 6 1, 2, 3, 5, 7, 9, 10, 11 4 4 1 16, 13, 14, 4, 2, 8, 5, 6 4 5 2 16, 17, 18, 1, 3, 6, 7, 8 1 3 3 2, 3, 1, 2, 1, 2, 3, 1 1 1 1 1, 1, 1, 1, 1, 1, 1, 1 ``` ## Rules * Your answer may be 0 or 1-indexed, your choice, please specify. * You can assume that `i < h * w` (or `i <= h * w` for 1-indexed answers). * You can assume that `i >= 0` (or `i > 0` for 1-indexed answers). * The order of the returned values is not important as long as just the eight desired values are included. * [Standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/users/31957/conor-obrien). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer, in each language, wins! Thanks to [@Conor O'Brien](https://codegolf.meta.stackexchange.com/users/31957/conor-obrien) for the more technical sounding title and [@ngm](https://codegolf.meta.stackexchange.com/users/79980/ngm) for more test cases! [Answer] # JavaScript (ES6), 75 bytes *Saved 2 bytes thanks to @KevinCruijssen* Expects a 0-based index. ``` (h,w,i)=>[...'12221000'].map((k,j,a)=>(i+w+~-k)%w+~~(i/w+h+~-a[j+2&7])%h*w) ``` [Try it online!](https://tio.run/##bY7NbsJADITvPIUvwG4zbOxNltADvAjisOKnSfgJAtTcePWwWlqEmkqWLNvzeab23/66vlTn2@TUbLbdbt6pEi0qPV8sjTFjsdYKM49X5ujPSu1Rw4ejqpI2uU/2ehjaXVVpm5Rh9ss6saNipYflR6u7dXO6NoetOTRfaqdy5HBaU5oSgwRkQTloCpqBPsOGB32An4C4cA96yUBZhIsIux7iIG9IeC5BydHMRbPiDyLIYH@QKHuGe0Xknl5@UzH@q@4B "JavaScript (Node.js) – Try It Online") The surrounding indices are returned in the following order: $$\begin{matrix}5&4&3\\6&\cdot&2\\7&0&1\end{matrix}$$ ### How? The indices \$I\_{dx,dy}\$ of each surrounding cell at \$(x+dx,y+dy)\$ are given by: $$\begin{align}I\_{dx,dy}&=((x+dx) \bmod w)+w((y+dy) \bmod h)\\&=((N+dx) \bmod w)+w((\left\lfloor\frac{N}{w}\right\rfloor+dy) \bmod h)\end{align}$$ where \$N=wy+x\$ is the index of the target cell. We walk through the list \$[1,2,2,2,1,0,0,0]\$ and subtract \$1\$ to get the value of \$dx\$, which gives: $$[0,1,1,1,0,-1,-1,-1]$$ For the corresponding values of \$dy\$, we use the same list shifted by 2 positions, which gives: $$[1,1,0,-1,-1,-1,0,1]$$ [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 27 bytes ``` {(⍺⊥⍺|(⍺⊤⍵)-⊢)¨1-1↓4⌽,⍳3 3} ``` [Try it online!](https://tio.run/##bY/PSsNAEMbvfYq5JQsGd/OnUd8mpE1YTLJlNxfRXlQKpl0RxKMHq0LvUgTBSx9lXiTOpr0I3YVh2N8333ybzapgcpVVqgzyKjNG5j0@vkiFiyfeF1SvfbQ/2H1Svdm3H2i3LMBuzXYbEQhcPMe4@j1B@xVBNO97Q1Nol7j63m2wu4XjB@0rGKXbUU1y32D3zvDhzTVrdlydq3qWaWlUA7JslJZNCUpPpnrUupyUqqZh7bZ3d8UpZb3w1KWHy3uvyGTlufB2q@eDWTs17cj3Y4hZwlrgICCEGMZwBucg@AFxQiIBEYKgv5EmJU0ywISJAxyDSMkghITGU4ICIhY6SG/OeG/OByIGT/7//gE "APL (Dyalog Classic) – Try It Online") `{` `}` is a function with arguments `⍺` (the dimensions `h w`) and `⍵` (the index `i`) `⍳3 3` is a matrix of all 2-digit ternary numbers: `0 0`, `0 1`, ..., `2 2` `,` enlists the matrix as a vector `1↓4⌽` removes the centre element `1 1` by rotating 4 to the left (`4⌽`) and dropping one (`1↓`) `1-` subtracts from 1, giving all 8 neighbour offsets `(` `)¨` applies the function train in parentheses to each offset `⍺⊤⍵` is the base-`⍺` encoding of `⍵` - the coordinates of `⍵` in the matrix `(⍺⊤⍵)-⊢` subtracts the current offset, giving the coordinates of a neighbour `⍺|` is mod `a` to wrap around coordinates and stay within the matrix `⍺⊥` decodes from base `⍺` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 40 [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 infix function. Takes `h` `w` as left argument and `i` as right argument. ``` {1↓4⌽,3 3↑,⍨⍣2⍪⍨⍣2⊃⊖∘⍉/(¯1+⍺⊤⍵),⊂⍺⍴⍳×/⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sNH7VNNnnUs1fHWMH4UdtEnUe9Kx71LjZ61LsKxupqftQ17VHHjEe9nfoah9Ybaj/q3fWoa8mj3q2aOo@6mkC83i2Pejcfnq4PZNf@TwMa/Ki3D2JHV/Oh9SBzgbzgIGcgGeLhGfzfRMFEIU3BlAtCGwBpUyBtyGWoYAykjYC0IUgcAA "APL (Dyalog Unicode) – Try It Online") `{`…`}` "dfn"; `⍺` is left argument (dimensions) and `⍵` is right argument (index).  `×/⍺` product (multiplication-reduction) of the dimensions  `⍳` the first that many indices  `⍺⍴` use the dimensions to **r**eshape that  `⊂` enclose it (to treat it as a single element)  `(`…`),` prepend the following:   `⍺⊤⍵` encode the index in mixed-radix `h` `w` (this gives us the coordinates of the index)   `¯1+` add negative one to those coordinates  `⊖∘⍉/` reduce by rotate-the-transpose   this is equivalent to `y⊖⍉x⊖⍉`… which is equivalent to `y⊖x⌽`… which rotates left as many steps as `i` is offset to the right (less one), and rotates up as many steps as `i` is offset down (less one), causing the the 3-by-3 matrix we seek to be in the top left corner  `⊃` disclose (because the reduction reduced the vector to scalar by enclosing)  `⍪⍨⍣2` stack on top of itself twice (we only really need thrice for single-row matrices)  `,⍨⍣2` append to itself twice (we only really need thrice for single-column matrices)  `3 3↑` take the first three rows of the first three columns The next two steps can be omitted if returning a 3-by-3 matrix is acceptable:  `,` ravel (flatten)  `4⌽` rotate four steps left (brings the centre element to the front)  `1↓` drop the first element [Answer] # [Python 2](https://docs.python.org/2/), ~~79~~ ~~69~~ 66 bytes ``` lambda h,w,i:[(i+q%3-1)%w+(i/w+q/3-1)%h*w for q in range(9)if q-4] ``` [Try it online!](https://tio.run/##XZBLDsIwDETXcApvEAk1atIPBSS4SMiiCEIjQWkipIrTl9T9LJC88czzxHHz/VTvOunM6dI9y9f1VkKFLdqjYjZyq3Qr@aqNmI3byMXUVZsWzNuDA1uDL@vHnR24NeC2me56g1EAR98DiqkMIVSuEZRAkAgJCTuEPcIhKEJzhIkTPSfzIAdMpggpzRRjyET2wEyGKBkAQdE5RRcDKWk@IZLcYYN5DzFjcnxakPtfmuvjctF4W3@G@6DH9em8RjP@tvsB "Python 2 – Try It Online") 3 bytes gifted by [Neil](https://codegolf.stackexchange.com/users/17602/neil) noting that `(x*w)%(h*w)==((x)%h)*w==(x)%h*w`. 0-indexed solution. [Answer] # [R](https://www.r-project.org/), ~~125 111~~ 108 bytes ``` function(x,i,m=array(1:prod(x),x),n=rbind(m,m,m),o=cbind(n,n,n),p=which(m==i,T)+x-1)o[p[1]+0:2,p[2]+0:2][-5] ``` [Try it online!](https://tio.run/##PcjNCsMgEATge58ix12yQjVJD6G@RW@SQ2qQePAHaal9emsilJnDN5OK6e6sK@bt9csGD5ksObmmtH6BzzGFDTJSrZfpaf0GjmqQgtTn9FSDFOVnt3oHJ6WlB/aZcQwqKr7011lQVOLEoti0FAMaRhqRbnj5mzdPh0XzUE8amvlhjuUH "R – Try It Online") 14 and 8 bytes golfed by @JayCe and @Mark. Input is `[w, h], i` because R populates arrays column first. Makes the array and then "triples" it row- and column-wise. Then locate `i` in the original array and find it's neighborhood. Output without `i`. [Answer] # [PHP](http://www.php.net/), 165 bytes This is "0-based". There must be a better solution in PHP, but this is a starting point! ``` <?list(,$h,$w,$i)=$argv;for($r=-2;$r++<1;)for($c=-2;$c++<1;)$r||$c?print(($k=(int)($i/$w)+$r)<0?$h-1:($k>=$h?0:$k))*$w+(($l=$i%$w+$c)<0?$w-1:($l>=$w?0:$l))%$w.' ':0; ``` To run it: ``` php -n <filename> <h> <w> <i> ``` Example: ``` php -n cell_neighbours.php 4 5 1 ``` Or [Try it online!](https://tio.run/##JcpBDoIwFIThq7gYQ58FBaMboPYspom2sYGmELvh7D5r3U3@@YINzKP2bllFDVsj1XCkcI/P9/CYo0BUzXlAlHLsBirFlGL@BXHbYHSIblqFwEuJPEjAnZBIItLYatim6/N3U7C67fEiOiDJzL2C2@cJU1wqzmeXfs4T5fNY7aq@HZj5wlfuPnNY3Twt3Exf "PHP – Try It Online") [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~27~~ 24 bytes ``` {x/x!''(x\y)-1-3\(!9)^4} ``` [Try it online!](https://tio.run/##VcxBDoIwEIXhvad4JCa0C7RDKQhzDXaAwQ3GYDBhVULw6rUILszs5nv5@2i4D851xWzPNghDYetJRhTpWgS5vCaLK4v5WE3vsehwguX21bNou9vjyZYnHmWzHMpKJEjYSFYgxEiQ4oIcpJqfKclkQDFIQ/tR5kdmV8O0aQrKoHzA@ED2VYLm2Kt/ru2tr3aiNavwd437AA "K (ngn/k) – Try It Online") `{` `}` is a function with arguments `x` (the dimensions `h w`) and `y` (the index `i`) `(!9)^4` is `0 1 2 3 4 5 6 7 8` without the `4` `3\` encodes in ternary: `(0 0;0 1;0 2;1 0;1 2;2 0;2 1;2 2)` `1-` subtracts from `1`, giving neighbour offsets: `(1 1;1 0;1 -1;0 1;0 -1;-1 1;-1 0;-1 -1)` `x\y` is the base-`x` encoding of `y` - the coordinates of `y` in the matrix `-` subtracts each offset, giving us 8 pairs of neighbour coordinates `x!''` is mod `x` for each - wrap coordinates around to stay within the matrix `x/` decodes from base `x` - turns pairs of coordinates into single integers [Answer] # [MATL](https://github.com/lmendo/MATL), 24 bytes ``` *:2Geti=&fh3Y6&fh2-+!Z{) ``` Inputs are `h`, `w`, `i`. The output is a row vector or column vector with the numbers. Input `i` and output are 1-based. [Try it online!](https://tio.run/##y00syfn/X8vKyD21JNNWLS3DONIMSBrpaitGVWv@/2/CZcJlBgA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8F/LysA9tSTTVi0twzjSDEga6WorRlVr/lfX1VWPcAn5b8JlwmXGBSINgdiUywhIGwOhIQgCAA). ### Explanation ``` * % Take two inputs implicitly. Multiply % STACK: 16 : % Range % STACK: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] 2G % Push second input again % STACK: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16], 4 e % Reshape with that number of rows, in column-major order % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16] t % Duplicate % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], % [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16] i= % Take third input and compare, element-wise % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], % [0 0 0 0; 0 1 0 0; 0 0 0 0; 0 0 0 0] &f % Row and column indices of nonzeros (1-based) % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], 2, 2, h % Concatenate horizontally % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], [2 2] 3Y6 % Push Moore mask % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], [2 2], % [1 1 1; 1 0 1; 1 1 1] &f % Row and column indices of nonzeros (1-based) % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], [2 2], % [1; 2; 3; 1; 3; 1; 2; 3], [1; 1; 1; 2; 2; 3; 3; 3] h % Concatenate horizontally % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], [2 2], % [1 1; 2 1; 3 1; 1 2; 3 2; 1 3; 2 3; 3 3] 2- % Subtract 2, element-wise % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], [2 2], % [-1 -1; 0 -1; 1 -1; -1 0; -1 0; -1 1; 0 1; 1 1] + % Add, element-wise with broadcast % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], % [1 1; 2 1; 3 1; 1 2; 3 2; 1 3; 2 3; 3 3] ! % Transpose % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], % [1 2 3 1 3 1 2 3; 1 1 1 2 2 3 3 3] Z{ % Convert into a cell array of rows % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], % {[1 2 3 1 3 1 2 3], [1 1 1 2 2 3 3 3]} ) % Index. A cell array acts as an element-wise (linear-like) index % STACK: [1 2 3 5 7 9 10 11] ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 74 bytes ``` Mod[i=#;w=#2;Mod[i+#2,w]+i~Floor~w+w#&@@@{-1,0,1}~Tuples~2~Delete~5,1##2]& ``` [Try it online!](https://tio.run/##Rcq9CsIwGIXhPVcR@KAo/YpNNFOJZBA3wcGtdCia0kBrpEYyhObW4w8F4QzPgXdsXa/H1plrmzq5Sid7q42Eykvg1e/kwNE3uYnHwdop@txDppQKBcMS2Rwvr8egn5HHgx6001EgA@BNltYVOU/m7moo9p1S0GQbFQgJAunusxlJKP9kSMVCjnSLlC0B@5KQOb0B "Wolfram Language (Mathematica) – Try It Online") Takes input in reverse (`i, w, h`), 0-based. ### 3x3 matrix with the center cell in it, (60 bytes) ``` (Join@@(p=Partition)[Range[#2#]~p~#,a={1,1};3a,a,2a])[[#3]]& ``` Takes (`w, h, i`), 1-based. [Try it online!](https://tio.run/##NcixCsMgFEDR3a8ICEHhhaK2XYLFuVPoKg6PkrQOMSG4ifl1GwOFOxzujPE7zhj9G8ukWWHPxQdj2KoH3KKPfgncvjB8Rksldfu6U0CdBIjcKwQEiY5bS5VzbeE9GTYfoqXdYzKGuvZiEiHpCs3RPcOfovJ2UlaqY0GjKsVJkQnJ5Qc "Wolfram Language (Mathematica) – Try It Online") [Answer] ## Batch, 105 bytes ``` @for /l %%c in (0,1,8)do @if %%c neq 4 cmd/cset/a(%3/%2+%1+%%c/3-1)%%%1*%2+(%3%%%2+%2+%%c%%3-1)%%%2&echo. ``` 0-indexed. Saved 23 bytes by stealing @ChasBrown's modulo 3 trick. [Answer] # MATL, 24 bytes ``` X[h3Y6&fh2-+1GX\1Gw!Z}X] ``` [Try it on MATL Online](https://matl.io/?code=X%5Bh3Y6%26fh2-%2B1GX%5C1Gw%21Z%7DX%5D&inputs=%5B5+4%5D%0A2&version=20.9.1) Takes inputs `[w h]` and `i`. 8 bytes of this was ~~shamelessly stolen from~~ inspired by Luis Mendos' answer, though the overall approach is different. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~85~~ 83 bytes ``` import StdEnv r=(rem) $h w i=tl[r(n+i/w)h*w+r(r(m+i)w)w\\n<-[0,1,h-1],m<-[0,1,w-1]] ``` [Try it online!](https://tio.run/##LcyxDsIgFEDRvV/B0AEEYps4ylYHE7eObQdCUUh41FD0xZ8XGcydznJNsDoW2NZXsAS0j8XDc0uZjHm9xHeTFE0WWNM6gsSrHKZEI/dHZO6APNFEgXuGDOc5nuXUiV442S8C/sCKpYxZ16UiLTnVuvI196Afe5HXWxk@UYM3@w8 "Clean – Try It Online") Treats `i` as a coordinate `(0 <= p < h, 0 <= q < w)`, and generates the values of the adjacent elements where the value is `p'w + q'`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` PRs©Ṫ{œi+€Ø-ݤŒpḊœị® ``` A dyadic link accepting a list of the dimensions on the left, `[h,w]`, and the cell as an integer on the right, `i`, which yields a list of the neighbourhood. Note: the order is different to that in the examples which is allowed in the OP **[Try it online!](https://tio.run/##ATUAyv9qZWxsef//UFJzwqnhuap7xZNpK@KCrMOYLcW7wqTFknDhuIrFk@G7i8Ku////WzQsNV3/Mg "Jelly – Try It Online")** ### How? ``` PRs©Ṫ{œi+€Ø-ݤŒpḊœị® - Link: [h,w], i P - product -> h*w R - range -> [1,2,3,...,h*w] Ṫ{ - tail of left -> w s - split into chunks -> [[1,2,3,...w],[w+1,...,2*w],[(h-1)*w+1,...,h*w]] © - ...and copy that result to the register œi - multi-dimensional index of (i) in that list of lists, say [r,c] ¤ - nilad followed by link(s) as a nilad: Ø- - literal list -> [-1,1] Ż - prepend a zero -> [0,-1,1] +€ - addition (vectorises) for €ach -> [[r,r-1,r+1],[c,c-1,c+1]] Œp - Cartesian product -> [[r,c],[r,c-1],[r,c+1],[r-1,c],[r-1,c-1],[r-1,c+1],[r+1,c],[r+1,c-1],[r+1,c+1]] Ḋ - dequeue -> [[r,c-1],[r,c+1],[r-1,c],[r-1,c-1],[r-1,c+1],[r+1,c],[r+1,c-1],[r+1,c+1]] ® - recall (the table) from the register œị - multi-dimensional index into (1-indexed & modular) ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 66 bytes ``` {a.=[]Moore[Integers@@__2,{Push[a,_]},cycle->1]Flat[a@_][0:3'5:8]} ``` [Try it online!](https://tio.run/##XcpNC4JAFIXhvb9iFlGbW/iREIIhBEGLwkW7y2UYpqsGouJMixB/@zQgQXR2z@FV1irdsKtElrtJ7XKka9@PjJfOcs2jKQopY5jKl2lQgaQZ9Fu3vD1GdG6VRVVIwjBLNml2oNndmB8GV8OgawrK8dnZOxt7UoYNrisQGAg/TEGIPYg9weLwz9Hi9OvY23/Jb@8dUUDkPg "Attache – Try It Online") I still need to implement `Moores` and `NMoore`, but I still have `Moore` which serves as an iteration function. Essentially, `Integers@@__2` creates an integer array of shape `__2` (the last two arguments) of the first `Prod[__2]` integers. This gives us the target array. Then, `Moore` iterates the function `{Push[a,_]}` over each Moore neighborhood of size `1` (implied argument), with the option to cycle each element (`cycle->1`). This adds each neighborhood to the array `a`. Then, `Flat[a@_]` flattens the `_`th member of `a`, that is, the Moore neighborhood centered around `_` (the first argument). `[0:3'5:8]` obtains all members except the center from this flattened array. This solution, with an update to the language, would look something like this (49 bytes): ``` {Flat[NMoore[Integers@@__2,_,cycle->1]][0:3'5:8]} ``` [Answer] # [Kotlin](https://kotlinlang.org), 88 bytes Uses zero based indexes and outputs an 8 element list. ``` {h:Int,w:Int,i:Int->List(9){(w+i+it%3-1)%w+(h+i/w+it/3-1)%h*w}.filterIndexed{i,v->i!=4}} ``` [Try it online!](https://tio.run/##lVfbbtw2EH3XV4yNtNE6Wu3K9xi10SZoigJpAzR@6SNX4q7YSKRKUpENw9@eHl60q3Wdogkcm5KOzsyZGc5Qn5RthPyyOKK3mjPLK1orTbYWhkpVcdqoZk1lzZqGb/hVUlvbmavFwj1zj3JjWfmJ3wEhNzwvVbv4u@fGCiXNoji/vFxeJO@ErMDI6S1vmpeGfudiU69Ur02S5zms3SqtRMUa@k0pzXfPa6UqkyS/iM9cUqeMsFiRkBauaEN1RgMxcDOSSs4l37ApgERGmtteS4L3pNbeB/giSm7I9FqrHhdyQyJPkj9VTwzGrSJmTN9ysLbManGHOEgjIAlIkNSk1WDcaiDe8JZLazKSfbvi2kVPq5YaNSAGGYx5m1Z11PC1ndfO21JpyXXmLNUQOgWulLV4XeP2E7BbBzEezOQ9LplRkq0a7lIGX4GiBo4@lWprZmlQfVNtVY/P@R3ocrp16Y5qsWLwTfe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0zy7Qkkj9DUK3/lca@E/e5kXsy@C/eexi0URBY2pRoiNypqkrJs9873E6CHPKd6B39O/r9V7/DPyZ@4FSXv8M9pD4qC@EUMhF34EIRHR5MY/Oac75r7J4ZW4YZ/e18Rq6r9InDwbfVsq39P0tfS5Okf84k773zd@6r3RgDGpWccXwpb49fYZh/i6c1DaH4THTq4ptNH3z9uXUupNA7E2rsSzvDukO77QsuETJnemCv6SWt2/8NHJFFubuIOA8F71q4qhgNdp91mUfIpDTnj1KFrePzlJaKHRvblob5ynWXwv4X7Pb@J2/chHV6JXWG@SpGixbBL09HwmO/pfBDZ5/mNOLg@fXz8EopX@6PvNuonuw8Cf/Z293qD9h28qoTpGuaz2mbjzo9XrhYnz5PJbjZOnoWpBx99JzQdd0zsLqE30LX35r2QPJ0dHORgEzaNKSM6pMNZ7o7OD8LmViEW6ezRP@0Qbpsepi9G2heR98WW@DC0Phf2NOQZe6973o9ZNBlpXwR8ZPA3G5nOYmo/YLDdlbxzn2kZKhpHTua/KqpphDBw18wdtcKO3o4oF5pHLC2adsrxQaGvMFSxh9y3yCxGbDR5@IZV4VsgQ1pc0iKrOYjOudg6cgPFbsZ8WKfxTzifnc2ybTj3HizRmPduFM9D3dl1Bw3nuON/I8NhbDmbBP0rKXdfLs7hUeu3JPMb0/mVhE5T6q4eY8NJ4hKVm/iF2@Zf/gE "Kotlin – Try It Online") [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 11 bytes ``` Πʀ⁰hẆÞȮ1⁾¹i ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLOoMqA4oGwaOG6hsOeyK4x4oG+wrlpIiwiUyIsIls0LDRdXG42IiwiMy40LjEiXQ==) Output is sorted in footer but is not necessary to the program bytecount input is of the form `[w,h], n` ``` Πʀ⁰hẆÞȮ1⁾¹i­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌­ Πʀ # ‎⁡range [0, w*h) ⁰hẆ # ‎⁢split into chunks of given width ÞȮ1⁾ # ‎⁣grid neighbors with wraparound flattened by one ¹i # ‎⁤at given index 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). ]
[Question] [ Given a fraction in the format `m/n` (where m and n are coprime integers), output the corresponding Unicode fraction. Your program/function will not be expected to take in any input that does not correspond to a Unicode character. Arrays, e.g. `[2, 3]` as opposed to `2/3`, are accepted. `m / n` as opposed to `m/n` is also fine. Two separate inputs `m` and `n` are also valid. The Unicode fractions that must be handled are as follows: ``` ½, ⅓, ⅔, ¼, ¾, ⅕, ⅖, ⅗, ⅘, ⅙, ⅚, ⅐, ⅛, ⅜, ⅝, ⅞, ⅑, ⅒ ``` Thus, the possible inputs are as follows: ``` 1/2, 1/3, 2/3, 1/4, 3/4, 1/5, 2/5, 3/5, 4/5, 1/6, 5/6, 1/7, 1/8, 3/8, 5/8, 7/8, 1/9, 1/10 ``` The Unicode codepoints of the characters are as follows: ``` 188 ¼ 189 ½ 190 ¾ 8528 ⅐ 8529 ⅑ 8530 ⅒ 8531 ⅓ 8532 ⅔ 8533 ⅕ 8534 ⅖ 8535 ⅗ 8536 ⅘ 8537 ⅙ 8538 ⅚ 8539 ⅛ 8540 ⅜ 8541 ⅝ 8542 ⅞ ``` ## Test Cases ``` 1/2 -> ½ 1/3 -> ⅓ 2/3 -> ⅔ 1/4 -> ¼ 3/4 -> ¾ 3/8 -> ⅜ 1/10 -> ⅒ ``` Make your code as short as possible; this is code golf. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~78~~ 77 bytes *Saved 1 byte thanks to @HermanLauenstein* Takes input in currying syntax `(m)(n)`. ``` m=>n=>'¾⅗ ⅜ ⅞⅘½⅓¼⅕⅙⅐⅛⅑⅒⅚⅔⅝⅖'[(m*9+n)%31] ``` [Try it online!](https://tio.run/##HcpLbsIwEIDhfU8xQqqwi0MxIQVUJbueIvLCCaQPQVxB1RvMvoU@gfYklEWOMhdJ7dl8M/NrHuyzXZer@8enqHazeVul7TLN6jTrNifCTwDCA0AYv4RfzR/htjkSvhN@E74Q7glfCTeEO8I3wh/Cj24ulhfTXi3PY23a6zzXamiUN/YOWa1G3pjVKuGecAmOWK2uvAmr1Zid8M@Ee3DMajVl9cCYs37lVje2vBMitwoKIyHNoHT12i3m/YW7FRZ60LnseIuwQRRlEK5KWCkKKWX7Dw "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 6](https://perl6.org), ~~48~~ 43 bytes ``` {chr first *.unival==$^m/$^n,(|^191,|(8528..*))} ``` [Try it](https://tio.run/##Hc5ha4MwEAbg7/kVBytTS0i8GDUiGfslQrGWOVodWgsy99tdXr88cPfeHffTTfdif6OYXUUuzxgYYueIqxRFBizIQQFK4AIGZNi0GLZYtwbBcS0VYpk7ehWqrcVjpfd2vHbk99/2a6JbP81POqtl6F@Xu/en5qFPzSDjreGK5RbjvFLnJPnbw@7nc1rJE2sjA5kkA1hbSRlgnaOXowxYwLqQlAPWJXBIHXqBErCuAKe1EPNlJTUs1059j/0QRzpKJEXkPyiSdLy@HTHdxun4p97/AQ "Perl 6 – Try It Online") ``` {chr first *.unival==$_,(|^191,|(8528..*))} ``` [Try it](https://tio.run/##Hc7taoMwFAbg/7mKAytTS0g8JtGIOHYlK8Va5uh0xFqQddfu8vrngfPxHs5PH27l9kIp@5q8MwwKYu@J6xyFARY4UIIK@EgBDJIWyxZxW2CwX8uFWOaeHqXqGvG90ms3XXpqt9/uM9B1CPOdjmoZh8f51raHk0yfH1yzfKa4rNQxy/62GHu/h5VaYl3IiJFUANZWkgGsHXoOZcQC1qUkB1hXwGPq0YtUgHUNOG@EmM8rqXG59OprGsY00UkmKaH2jRJJ@9eHE12nsP/SbP8 "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 chr first # find the first value *.unival == # which has a unicode value that matches $_, # the input fraction (as a Rational) ( |^191, # ¼(189) ½(188) ¾(190) |(8528..*) # all of the rest ) } ``` Note that the search has to be split up so that it doesn't return other Unicode characters that have the same unival. (otherwise it would be `(1..*)`) [Answer] ## JavaScript (ES6), ~~88~~ ~~86~~ ~~84~~ ~~81~~ 79 bytes *Saved 2 bytes thanks to @Arnauld* ``` m=>n=>String.fromCharCode((4%n?8528:188)|" 130470912"[n]*1.3+~-m/-~"3 1"[n-6]) ``` Not quite as short as the other JS answer, but it was fun to calculate the code-point of each fraction mathematically. ### Test snippet ``` let f = m=>n=>String.fromCharCode((4%n?8528:188)|" 130470912"[n]*1.3+~-m/-~(n-6?n==8:3)) document.body.innerText = [ [1,2], [1,3], [2,3], [1,4], [3,4], [1,5], [2,5], [3,5], [4,5], [1,6], [5,6], [1,7], [1,8], [3,8], [5,8], [7,8], [1,9], [1,10] ].map(([m,n])=>m+"/"+n+": "+f(m)(n)).join('\n') ``` Old method (82 bytes): ``` m=>n=>String.fromCharCode((4%n?8539:189)-("0x"+" 08162b0a9"[n])+~-m/-~"3 1"[n-6]) ``` Saved 4 bytes on this one thanks to @Arnauld. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~88~~ 64 bytes ``` {⎕UCS(⌊(⍺-1)÷(1+⍵≡8)⌈4×⍵≡6)-(291194049⊤⍨10⌿12)[⍵]-189⌈8539××⍵|4} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR31TQ52DNR71dGk86t2la6h5eLuGofaj3q2POhdaaD7q6TA5PB3CM9PU1TCyNDS0NDEwsXzUteRR7wpDg0c9@w2NNKOBKmJ1DS0sgeotTI0tD08Ha6oxqf3/31AhTcGIC0Qag0kTMGkKJs3ApDmYtACTlmDS0IDLCKzBCKzUGKzNGM624DIBs03BRpiCRcxBJAA "APL (Dyalog Unicode) – Try It Online") -3 thanks to [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima). Using ETHproductions's 84-byte approach. The `f←` included on TIO isn't counted, since it's put there just to be able to test the function. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 51 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` 5*+'æ%'⁵%"∫}ΣS“LI─{"#!“+ζ}¹"¾ŗŗŗŗŗŗ⅛ŗ⅜½⅝ŗ⅞ ⅓⅔ŗ ¼”W ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=NSorJTI3JUU2JTI1JTI3JXUyMDc1JTI1JTIyJXUyMjJCJTdEJXUwM0EzUyV1MjAxQ0xJJXUyNTAwJTdCJTIyJTIzJTIxJXUyMDFDKyV1MDNCNiU3RCVCOSUyMiVCRSV1MDE1NyV1MDE1NyV1MDE1NyV1MDE1NyV1MDE1NyV1MDE1NyV1MjE1QiV1MDE1NyV1MjE1QyVCRCV1MjE1RCV1MDE1NyV1MjE1RSUyMCV1MjE1MyV1MjE1NCV1MDE1NyUyMCUyMCVCQyV1MjAxRFc_,inputs=OCUwQTM_,v=0.12) uses the mapping `(m + n*5)%33%22` Explanation: ``` 5* multiply the 1st input by 5 + add to the 2nd input 'æ% modulo 33 '⁵% module 22 "∫}ΣS“ push 2153527158 LI─ base 11 decode that - [10 0 5 6 7 8 9 1 2] { } for each of that "#!“+ add 8528 ζ and convert to a character "...” push "¾ŗŗŗŗŗŗ⅛ŗ⅜½⅝ŗ⅞ ⅓⅔ŗ ¼", replacing ŗ with each character of the above array W and get the (m + n*5)%33%22th item from that ``` [Answer] # Clojure, 127 bytes ``` (comp{2/3\⅔ 4/5\⅘ 1/3\⅓ 1/2\½ 5/6\⅚ 1/5\⅕ 1/4\¼ 3/5\⅗ 1/7\⅐ 3/4\¾ 2/5\⅖ 1/6\⅙ 1/9\⅑ 1/8\⅛ 3/8\⅜ 1/10\⅒ 5/8\⅝ 7/8\⅞}read-string) ``` An anonymous function that takes input as `"1/2"`, and returns the corresponding character. A straight mapping from a Clojure `Ratio` to a fraction character. `comp`, and the fact that Clojure maps are functions really helped here. I needed to pass the string input through `read-string` to evaluate it as a ratio type, since that allows me to discard all the bloating quotes in the map. `comp` let me do that point-free, which was nice. The "full" code would be: ``` (defn to-unicode-fraction [frac] (get {2/3\⅔ 4/5\⅘ 1/3\⅓ 1/2\½ 5/6\⅚ 1/5\⅕ 1/4\¼ 3/5\⅗ 1/7\⅐, 3/4\¾ 2/5\⅖ 1/6\⅙ 1/9\⅑ 1/8\⅛ 3/8\⅜ 1/10\⅒ 5/8\⅝ 7/8\⅞} (read-string frac))) ``` After looking over the other answers, I realized that this approach is pretty naïve. I'm looking for ways of improving it. [Answer] # [Swift](https://swift.org), ~~106~~ 82 bytes *Port of [@Arnaulds JavaScript answer](https://codegolf.stackexchange.com/a/150809/70894)* *Saved 24 bytes thanks to @Mr.Xcoder* ``` {Array("¾⅗ ⅜ ⅞⅘½⅓¼⅕⅙⅐⅛⅑⅒⅚⅔⅝⅖")[($0*9+$1)%31]} ``` [Try it online!](https://tio.run/##Vcy9CsIwFIbh3asIpUKiDk3T2nZw8DrEoUuhi0gsiojj2f3/1ytRh1zKuZEYt5wpPHznzWxRV01i7bzUrBqshlqXSx6YL8KZMYQHY//nhXAxH4S9eSMcEa4IG4Q7whZhh3BDOCA8EU6BGPEw6hTdUIq2kuO1nep60vCKyx6LhWh5VB5jSrcmHhWlW1PapvTYZ0Lp2r7HlNKtGWVOf85p6zOjdG1BKSMh7A8 "Swift 4 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~77~~ ~~48~~ 46 bytes ``` F§§⪪“YW³⦄Eν~vγ@⊖Xμ~?Iw⸿M➙b℅¦⦃”,NN℅⁺℅ι×⁹⁰∨№βι⁹⁴ ``` [Try it online!](https://tio.run/##ZU3JCsIwFLz7FY@cXuAJHhQsnqRudWnr8gNpWjGQpiVNxL@P6cWLcxlmY@RLWNkJHcKzs4Brl5m6@fz43mvlkN1ou5P7KrtsCjrAkU4AZU1nyuFKDIAR4wSZ6b3LfVs1Fvmf5lBaZRym8VBIF71S@wELWysjNKo4eKi2GTCZERQW087HdkUwJsmcj1iFsJgsw/Stvw "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved ~~29~~ 31 bytes by mapping from ASCII chars to multibyte chars. Explanation: ``` “....” Compressed string `R,EFcGbIMDO,H J,K Pd,L,N Q,` ⪪ , Split on commas N First input § Circularly index N Second input § Circularly index F "Loop over" character (loop variable `i`) №βι Count of `i`s in lowercase letters ∨ ⁹⁴ Replace zero result with 94 ×⁹⁰ Multiply by 90 ℅ι Take ordinal of `i` ⁺ Sum ℅ Convert back to character Implicitly print ``` [Answer] # [Python 3](https://docs.python.org/3/), 87 bytes ``` lambda n:'⅛⅑⅜¾⅗⅔⅚⅖⅝⅘⅞⅒½⅓¼⅕⅙⅐'[int(n[::2])%50%36%31%18] ``` [Try it online!](https://tio.run/##Lcw9CsIwHIbx3VNkCWlBaNOolIAnqR0qEixoWkoXD/Dufn/rSdShR/lfJNbi8hue4SlX9bywypnxxC2y5XSWMasF4UbYEO7Nh3Ai7AlXwpHwIJwJT8K2eRN2zYtwIFwIa5HktvZsonWU@nwYcjXiSnIZp84UFbMst0zIIBL9VtUadcpg0Kr@xl2RodA9xsrqdzSe9X33BQ "Python 3 – Try It Online") or ``` lambda n:'⅝⅔⅜⅖__⅞¾⅗⅘_⅒½⅓¼⅕⅙⅐⅛⅑⅚'[int(n[::2])%36%27%22] ``` [Try it online!](https://tio.run/##LcxLCsIwFIXhuavIpKQFoTYRlYArqaVUpFjQtJROXMCd@37rStRBlnI2EmNx8vFzBqdaNfNSS5uPJ3aRLaezjGnFQQ/QHnQHHdMU9DQf0Al0dr01b9DOvEAH0AW0Bt1AG9CVx4VufB0rJZLAkwNPDD0hEpuXNdOs0IxHoeBdp3SK1ijsO@XfUbtEPa46jFX17y73dRDYLw "Python 3 – Try It Online") [Answer] # Python 3, 97 bytes ``` lambda m,n:'½ ⅓⅔ ¼_¾ ⅕⅖⅗⅘ ⅙___⅚ ⅐ ⅛_⅜_⅝_⅞ ⅑ ⅒'.split()[n-2][m-1] ``` [Answer] # Vim Script, 67 bytes ``` fu!F(m,n) if a:n==10|norm a⅒ else|exe'norm a'.a:m.a:n endif endfu ``` The function works with Vim's *digraphs* which are entered after starting them iwth `ctrl-k.` Apparently, the relevant `ctrl-k` character after the `exe'norm` is not rendered in the code block above. ]
[Question] [ Given a polynomial function *f* (e.g. as a list *p* of real coefficients in ascending or descending order), a non-negative integer *n*, and a real value *x*, return: #    *f* n(*x*) i.e. the value of *f* (*f* (*f* (…*f* (*x*)…))) for *n* applications of *f* on *x*. Use reasonable precision and rounding. Solutions that take *f* as a list of coefficients will probably be the most interesting, but if you are able to take *f* as an actual function (thereby reducing this challenge to the trivial "apply a function *n* times"), feel free to include it after your non-trivial solution. ### Example cases *p* =`[1,0,0]` or *f* =`x^2`, *n* =`0`, *x* =`3`: *f* 0(3) =`3` *p* =`[1,0,0]` or *f* =`x^2`, *n* =`1`, *x* =`3`: *f* 1(3) =`9` *p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`0`, *x* =`2.3`: *f* 0(2.3) =`2.3` *p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`1`, *x* =`2.3`: *f* 1(2.3) =`-8.761` *p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`2`, *x* =`2.3`: *f* 2(2.3) =`23.8258` *p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`3`, *x* =`2.3`: *f* 3(2.3) =`-2.03244` *p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`4`, *x* =`2.3`: *f* 4(2.3) =`1.08768` *p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`5`, *x* =`2.3`: *f* 5(2.3) =`-6.38336` *p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`6`, *x* =`2.3`: *f* 6(2.3) =`14.7565` *p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`7`, *x* =`2.3`: *f* 7(2.3) =`-16.1645` *p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`8`, *x* =`2.3`: *f* 8(2.3) =`59.3077` *p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`9`, *x* =`2.3`: *f* 9(2.3) =`211.333` *p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`10`, *x* =`2.3`: *f* 10(2.3) =`3976.08` *p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`11`, *x* =`2.3`: *f* 11(2.3) =`1571775` *p* =`[-0.1,2.3,4]` or *f* =`−0.1x^2+2.3x+4`, *n* =`0`, *x* =`-1.1`: *f* 0(-1.1) =`-1.1` *p* =`[-0.1,2.3,4]` or *f* =`−0.1x^2+2.3x+4`, *n* =`1`, *x* =`-1.1`: *f* 1(-1.1) =`1.349` *p* =`[-0.1,2.3,4]` or *f* =`−0.1x^2+2.3x+4`, *n* =`2`, *x* =`-1.1`: *f* 2(-1.1) =`6.92072` *p* =`[-0.1,2.3,4]` or *f* =`−0.1x^2+2.3x+4`, *n* =`14`, *x* =`-1.1`: *f* 14(-1.1) =`15.6131` *p* =`[0.02,0,0,0,-0.05]` or *f* =`0.02x^4-0.05`, *n* =`25`, *x* =`0.1`: *f* 25(0.1) =`-0.0499999` *p* =`[0.02,0,-0.01,0,-0.05]` or *f* =`0.02x^4-0.01x^2-0.05`, *n* =`100`, *x* =`0.1`: *f* 100(0.1) =`-0.0500249` [Answer] # [Octave](https://www.gnu.org/software/octave/), 49 bytes ``` @(p,x,n)(f=@(r,m){@()p(r(r,m-1)),x}{~m+1}())(f,n) ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQaNAp0InT1MjzdZBo0gnV7PaQUOzQKMIxNY11NTUqaitrsvVNqzV0ASqASr8n5hXrOGgUaFZoRdnpGOsY6T5HwA "Octave – Try It Online") Or, taking coefficients: ## [Octave](https://www.gnu.org/software/octave/), ~~75~~ 57 bytes ``` @(p,x,n)(f=@(f,n){@()polyval(p,f(f,n-1)),x}{~n+1}())(f,n) ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQaNAp0InT1MjzdZBIw3IqHbQ0CzIz6ksS8wBSqWBxHQNNTV1Kmqr6/K0DWs1NDXB6v4n5hVrRBvqGOkYxAIJY83/AA "Octave – Try It Online") A special thanks for Suever over at StackOverflow, for [this answer](https://stackoverflow.com/a/36310726/2816870) some time ago on a question of mine, proving that a recursive anonymous function is possible. This defines an anonymous function, which is a wrapper for a **recursive anonymous function**; something which is not a native Octave concept, and requires some fancy cell array indexing. As a bonus, the second version is a nice lesson in variable scoping in Octave. All instances of `r` can legally be replaced by `f`, which then simply overwrites the existing `f` in the most local scope (similar for `n`) ### Explanation ``` @(p,x,n)(f=@(r,m){@()p(r(r,m-1)),x}{~m+1}())(f,n) @(p,x,n) . .. . .. . % Defines main anonymous function (f=@(r,m). .. . ). . % Defines recursive anonymous function . .. . . . % r: Handle ('pointer') to recursive function . .. . . . % m: Current recursion depth (counting from n to 0) . .. . (f,n) % And call it, with . .. . % r=f (handle to itself) . .. . % m=n (initial recursion) { }{ } % Create and index into cell array ~m+1 % Index: for m>0: 1; for m==0: 2. ,x % Index 2: final recursion, just return x. @() % Index 1: define anonymous function, taking no inputs. p( ) % which evaluates the polynomial r( ) % of the recursive function call r,m-1 % which is called with r % and recursion depth m-1 % (until m=0, see above) () % Evaluate the result of the cell array indexing operation. % which is either the anonymous function % or the constant `x`. ``` The key to this is that anonymous functions are **not** evaluated when they are defined. So, the `@()`, which seems a bit superfluous since it defines an anonymous function which is called with `()` directly after, is actually strictly necessary. It is not called **unless** it is selected by the indexing statement. ### [Octave](https://www.gnu.org/software/octave/), 39 bytes (boring way) ``` function x=f(p,x,n)for i=1:n;o=p(o);end ``` Just for completeness, the Octave solution with the shortest bytecount. [Yawn.](https://tio.run/##FYxBCoMwFAX3PcXbFBMIQi3dtAg9QY9QiPrTBuL/YqKNp091MbuZkT7ZlUpxC/fJCyO3Tk0mG9ZOZvj2cueHtJMS/SAeyg7OeMk82hA2g/Ql2E5Wwk@WMKAjeIZF9PwJhHqE84EMooAF1Z5X8BFMPcVo5@2wj0e3Jepl4XRy6qmyzu/GNPXV3HT5Aw "Octave – Try It Online"). [Answer] # Mathematica, ~~56~~ ~~47~~ 28 bytes ``` Nest[x\[Function]x#+#2&~Fold~#,##2]& ``` `\[Function]` takes 3 bytes in UTF-8. Take parameters in order `p,x,n`. `p` (parameter 1) is in increasing order of degree. Obviously if `f` can be taken as a function this can be reduced just to `Nest`. [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` ←↓¡`B ``` [Try it online!](https://tio.run/##yygtzv7//1HbhEdtkw8tTHD6//9/tIGeoY6ukZ6xjq5J7H8g/d/QAAA "Husk – Try It Online") The key idea here is that evaluating a polinomial at a point *x* is equivalent to performing base conversion from base *x*. `B` when given a base and a list of digits performs base conversion. Here we use its flipped version, in order to take the list of digits first and partially apply this function to it. We obtain then a function which computes the value of the given polynomial at a point, the second part of this solution deals with iterating this function the correct amount of times: # [Husk](https://github.com/barbuz/Husk), 3 bytes ``` ←↓¡ ``` `¡` is the "iterate" function, it takes a function and a starting point and returns the infinite list of values obtained iterating the function. `↓` takes a number (the third argument of this challenge) and drops that many elements from the start of the list. `←` returns the first element of the resulting list. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 31 bytes ``` (p,n,x)->for(i=1,n,x=eval(p));x ``` [Try it online!](https://tio.run/##FcfBCoAgDADQX9lxC41N6hT2KYGHDCFsSIR/b3p7T0NJ9tIWwUNDNdlUsnt8CiYvY/78wo1KtNWmJeUXI/LMbqrHYjukww2sBoTZAM9C1H4 "Pari/GP – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 42 bytes ``` ->c,n,x{n.times{x=c.reduce{|s,r|s*x+r}};x} ``` C is the list of coefficients in descending order Trivial version, where f is a lambda function (**26 bytes**): ``` ->f,n,x{n.times{x=f[x]};x} # For example: # g=->f,n,x{n.times{x=f[x]};x} # p g[->x{0.02*x**4-0.01*x**2-0.05},100,0.1] ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5ZJ0@nojpPryQzN7W4usI2Wa8oNaU0ObW6plinqKZYq0K7qLbWuqL2f4FCWnS0oY6BjkEskDCO5UIWMIQLGOgZGAHFdIG0IZQ2BcobAJXpGcb@BwA "Ruby – Try It Online") [Answer] ## JavaScript (ES6), ~~52 49 44~~ 42 bytes *Saved 5 bytes thanks to [G B](https://codegolf.stackexchange.com/users/18535/g-b) and 2 more bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)* Takes input in currying syntax as `(p)(n)(x)`, where ***p*** is the list of coefficients in descending order. ``` p=>n=>g=x=>n--?g(p.reduce((s,v)=>s*x+v)):x ``` ### Test cases ``` let f = p=>n=>g=x=>n--?g(p.reduce((s,v)=>s*x+v)):x console.log(f([1,0,0])(0)(3)) console.log(f([1,0,0])(1)(3)) console.log(f([0.1,-2.3,-4])(0)(2.3)) console.log(f([0.1,-2.3,-4])(1)(2.3)) console.log(f([0.1,-2.3,-4])(2)(2.3)) console.log(f([0.1,-2.3,-4])(3)(2.3)) console.log(f([0.1,-2.3,-4])(4)(2.3)) console.log(f([0.1,-2.3,-4])(5)(2.3)) console.log(f([0.1,-2.3,-4])(6)(2.3)) console.log(f([0.1,-2.3,-4])(7)(2.3)) console.log(f([0.1,-2.3,-4])(8)(2.3)) console.log(f([0.1,-2.3,-4])(9)(2.3)) console.log(f([0.1,-2.3,-4])(10)(2.3)) console.log(f([0.1,-2.3,-4])(11)(2.3)) console.log(f([-0.1,2.3,4])(0)(-1.1)) console.log(f([-0.1,2.3,4])(1)(-1.1)) console.log(f([-0.1,2.3,4])(2)(-1.1)) console.log(f([-0.1,2.3,4])(14)(-1.1)) console.log(f([0.02,0,0,0,-0.05])(25)(0.1)) console.log(f([0.02,0,-0.01,0,-0.05])(100)(0.1)) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` *⁹LḶ¤×⁹Sµ¡ ``` [Try it online!](https://tio.run/##y0rNyan8/1/rUeNOn4c7th1acng6kBl8aOuhhf///zfSM/4frWuio6ALZOkoGOgZxv43NAAA "Jelly – Try It Online") Takes x, coefficients in ascending order, n in this order. # 4 bytes ``` ⁹v$¡ ``` [Try it online!](https://tio.run/##y0rNyan8//9R484ylUML////b6Rn/F/p0KbD0/UM4w9PB/JU4k2U/hsaAAA "Jelly – Try It Online") Takes x, Jelly link (may need to be quoted/escaped), n in this order. [Answer] # [J](http://jsoftware.com/), 15 bytes ``` 0{(p.{.)^:(]{:) ``` [Try it online!](https://tio.run/##y/r/P03B1krBoFqjQK9aTzPOSiO22kqTiys1OSNfId5EId5Iz1jBQM9QQQMsoZOmqWSoEKsAEtXRU8jUUzA0@v8fAA "J – Try It Online") Takes the polynomial as a list of coefficients of ascending powers. ## Explanation ``` 0{(p.{.)^:(]{:) Input: polynomial P (LHS), [x, n] (RHS) {: Tail of [x, n], gets n ] Right identity, passes n ( )^: Repeat n times starting with g = [x, n] {. Head of g p. Evaluate P at that value Return g = [P(head(g))] 0{ Return the value at index 0 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes -1 byte thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) ``` sF³gݨm*O ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/2O3Q5vTDcw@tyNXy///fSM@Yy4QrWtdERxfI1DHQM4wFAA "05AB1E – Try It Online") Takes x as first argument, n as second and p in ascending order as third. ### Explanation ``` sF³gݨm*O s # Forces the top two input arguments to get pushed and swaped on the stack F # Do n times... ³ # Push the third input (the coefficients) g # Get the length of that array... ݨ # and create the range [0 ... length] m # Take the result of the last iteration to these powers (it's just x for the first iteration) * # Multiply the resuling array with the corresponding coefficients O # Sum the contents of the array # Implicit print ``` [Answer] # [Haskell](https://www.haskell.org/), 15 bytes ``` ((!!).).iterate ``` [Try it online!](https://tio.run/##FcZBCoAgEAXQq/ygxRgoZW3rJBJIaEkWUi48fVO91dvsvbsY2Y@GiapKKKFCdpfNjg8bToxIVzgzaniQKZATqFVdU2YtIEFa9U35Nwh8h@Zn8dGuN8slpRc "Haskell – Try It Online") Thanks to totallyhuman for 11 bytes off of both solutions This defines a tacit function that takes a function as its first argument and `n` as its second argument, and composes that function with itself `n` times. This can then be called with an argument `x` to get the final value. Thanks to the magic of currying, this is equivalent to one function taking three arguments. --- Taking a list of coefficients instead of a function argument: # [Haskell](https://www.haskell.org/), 53 bytes ``` ((!!).).iterate.(\p x->sum$zipWith(*)p[x^i|i<-[0..]]) ``` [Try it online!](https://tio.run/##FcbRCsIgFADQX7mDPVwFL8t6bPuNHuYGMrRdckOmgUTfntV5OqtNDxdC9b2piE0jSBBnd9jsCE2Eoob03NoXxxvnFaWIY5n5zVc1dkTTJOpmeYce4sF7hhY8oCmgBsCOTrLMWoAC1HSW5b@LgN9B18/ig72nqpYYvw "Haskell – Try It Online") This is the same as the above code, but composed with a lambda function that converts a list of coefficients into a polynomial function. The coefficients are taken in reverse order from the examples - as ascending powers of `x`. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~20~~ 9 bytes ``` {⊥∘⍵⍣⎕⊢⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/FR24TqR11LH3XMeNS79VHv4kd9Ux91LXrUu6v2/38DPUMFRwU9AwMjBQMwPLRez8CUy8gUAA "APL (Dyalog Unicode) – Try It Online") This takes `x` as the left argument, the coefficients of the function as the right argument, and `n` from STDIN. Looking back at this after many a long time, I realised I could simplify the calculation by using base conversion `⊥`. --- # APL (Dyalog), 5 bytes If we can take the function as a Dyalog APL function, then this can be 5 bytes. ``` ⎕⍣⎕⊢⎕ ``` Takes `x`, `n` and then the function as input from STDIN. [Answer] # [R](https://www.r-project.org/), ~~96~~ ~~58~~ ~~55~~ 52 bytes ``` f=function(n,p,x)`if`(n,f(n-1,p,x^(seq(p)-1)%*%p),x) ``` [Try it online!](https://tio.run/##LYpJCoBADATv/kNIS0YSxaNfEUEMeBnHFX8/RvBUTVXvOVtvV5zOZY0UOfGDcbHRp1EM@omBjnmjhKAoqzLBL9mo44mEhRXcojBSEd7nm9zW0ngITv3ZASy1Ir8 "R – Try It Online") ### Explanation: `seq(p)` generates the list `1, 2, ..., length(p)` when `p` is a vector, so `seq(p)-1` is the exponents of the polynomial, hence `x^(seq(p)-1)` is equivalent to `x^0` (always equal to 1)`, x^1, x^2, ...` and computing a dot product `%*%` with `p` evaluates the polynomial at `x`. Additionally, if `P` is taken as a function, then this would be **38 bytes:** ``` function(n,P,x)`if`(n,f(n-1,P,P(x)),x) ``` And we can of course always generate `P` by `P=function(a)function(x)sum(x^(seq(a)-1)*a)` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ⁴ḅ$¡ ``` [Try it online!](https://tio.run/##y0rNyan8//9R45aHO1pVDi38//@/gZ7h/2gDPQMjHQMdXSBtCKVNY/8bGhgAAA "Jelly – Try It Online") Full program that takes `x p n` as command line arguments ## How it works ``` ⁴ḅ$¡ - Main link. Takes x and p on the left $ - Previous 2 links as a monad f(x): ⁴ - Yield p ḅ - Convert p from base x ¡ - Apply f(x) to x n times ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~70~~ 69 bytes ``` f=lambda p,n,x:n and f(p,n-1,sum(c*x**i for i,c in enumerate(p)))or x ``` Takes `p` in ascending order, i.e. if `p` is `[0, 1, 2]` then the corresponding polynomial is `p(x) = 0 + 1*x + 2*x^2`. Simple recursion solution. [Try it online!](https://tio.run/##ZU7dDoIgFL73Kc4lOGSAdtPWk7QuSKHY8uhIN3t6O/7Mys4Y43y/tK/u3mA@jv70sPW1stAKFMMRwWIFntGWafHsa1amQ5oG8E2EIEoICA772kXbOdZyzgkfxonFiVMC9DEBmjYG7JhnZ4Im9CIABeScJ8mmjhZvjmnDd5asEJAZmZNTrkbayArrJD@FxNJd7EKK2URBW0ampZ76Pz1SHebfLUcqQ0JD0Kz7l9FDfym1Uot0fAM "Python 3 – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 82 bytes ``` using System.Linq;f=(p,n,x)=>n<1?x:p.Select((c,i)=>c*Math.Pow(f(p,n-1,x),i)).Sum() ``` [Try it online!](https://tio.run/##TY9Na8MwDIbv/hU62sMxS7vT3HSMwk4rDHLYofTguWpnSOQ0dtaM0N@eOTSFoYPQq@fVhw2Z9S2OXXB0gvI3RKw1@1@pd0dnzcjUGBpjEczAbGVCADuwEE10Ft46squD774q3O2loyhvxZzW47HgjSTZi2JNq/ylf25UiRXayLmVLqn2YWvit/rwF36c0CxPcOoIVXY1F6Nm910/3h1gaxxxMTB2XwrNa3uCAggvu/0A2ZOEbKGWEh5VDlfN0k1AN2ShZxf0s6CWafzGU/AVqs/WRUw/43RIAuRkkxMqhGbXKcY/ "C# (.NET Core) – Try It Online") Takes a list of coefficients in the opposite order from the test cases (increasing order?) so that their index in the array is equal to the power x should be raised to. And the trivial version in 30 bytes: ``` f=(p,n,x)=>n<1?x:f(p,n-1,p(x)) ``` [Try it online!](https://tio.run/##VY9Na8MwDIbv/hU62p1jmnSnuekohZ5WGOyws@e6rSGVs9hpPcJ@e2YvHXQI9IXeR5L2hXadGXtv8QhvXz6YsyT3lXix@CkJqrPxrdIG1EB0o7wHPRAfVLAatj3q5a/bu/6jMXwKK24x8P@t8VDTliOPrF7hsnyOT4dcFyVvaWRslOQPenF2DztlkbKBkHs63FjQrrsj1EAzjM5FOdupcBKv7kojrxh7oEUlFrOYk0cmSboGcJJUkkwQiLeGWKTVG4feNUa8dzaY9Lih6bo0wLOM51GWON/Zxh8 "C# (.NET Core) – Try It Online") Takes a delegate and applies it recursively n times. [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` ii:"ZQ6Mw]& ``` [Try it online!](https://tio.run/##y00syfn/PzPTSikq0My3PFbt/38jPWMuY65oAz1DHV0gW0fXJBYA "MATL – Try It Online") Slightly less interesting than my Octave answer, although I think there's some clever juggling of inputs to make sure `n=0` works as expected. [Answer] ## Julia 0.6.0 (78 bytes) `using Polynomials;g(a,n,x)=(p=Poly(a);(n>0&&(return g(a,n-1,p(x)))||return x))` Explainations: The package [Polynomials](https://github.com/JuliaMath/Polynomials.jl) is pretty self explanatory: it creates polynomials. After that it's a pretty basic recursion. In order to have a polynomial: -4.0 - 2.3\*x + 0.1\*x^2 the input `a` must be like `a = [-4, -2.3, 0.1]` [Answer] # Axiom, 91 bytes ``` f(n,g,x)==(for i in 1..n repeat(v:=1;r:=0;for j in 1..#g repeat(r:=r+v*g.j;v:=v*x);x:=r);x) ``` indented ``` fn(n,g,x)== for i in 1..n repeat v:=1; r:=0 for j in 1..#g repeat(r:=r+v*g.j;v:=v*x) x:=r x ``` the input for polynomy g it is one list of numbers in the reverse of the example of exercise. for example ``` [1,2,3,4,5] ``` it would represent the polinomy ``` 1+2*x+3*x^2+4*x^3+5*x^4 ``` test: ``` (3) -> f(0,[0,0,1],3) (3) 3 Type: PositiveInteger (4) -> f(1,[0,0,1],3) (4) 9 Type: PositiveInteger (5) -> f(0,[-4,-2.30,0.1],2.3) (5) 2.3 Type: Float (6) -> f(1,[-4,-2.30,0.1],2.3) (6) - 8.7610000000 000000001 Type: Float (7) -> f(2,[-4,-2.30,0.1],2.3) (7) 23.8258121 Type: Float (8) -> f(9,[-4,-2.30,0.1],2.3) (8) 211.3326335688 2052491 Type: Float (9) -> f(9,[-4,-2.30,0.1,0,0,0,0,1],2.3) (9) 0.4224800431 1790652974 E 14531759 Type: Float Time: 0.03 (EV) + 0.12 (OT) = 0.15 sec (10) -> f(2,[-4,-2.30,0.1,0,0,0,0,1],2.3) (10) 44199336 8495528344.36 Type: Float ``` [Answer] # [Röda](https://github.com/fergusq/roda), 41 bytes ``` f p,n,x{([0]*n)|x=_+p()|reduce _*x+_;[x]} ``` [Try it online!](https://tio.run/##K8pPSfz/P02hQCdPp6JaI9ogVitPs6bCNl67QEOzpig1pTQ5VSFeq0I73jq6Irb2f25iZp5CNRdnGlCpnqGOrpGesY6uSayOgrmOApCtyVX7HwA "Röda – Try It Online") A trivial version: ``` f F,n{([_]..[0]*n)|reduce F(_)+_} ``` [Try it online!](https://tio.run/##FcpBCoAgFAXAdZ7iLbUiwkN4CSmRUmrRLyxBMM9uNOsJ52pr9VA9Za7NNAx6nFoSb3BrXBwUN6IzpfpICxIygntiIKRZorDD7oTMmiveG5cCLzz/Zw8pWKkf "Röda – Try It Online") It takes the the value for `x` from the stream. [Answer] # C++14, 71 bytes As generic unnamed lambda, returning via the `x` Parameter: ``` [](auto C,int n,auto&x){for(auto t=x;t=0,n--;x=t)for(auto a:C)t=a+x*t;} ``` Ungolfed and testcase: ``` #include<iostream> #include<vector> using namespace std; auto f= [](auto C,int n,auto&x){ for( auto t=x; //init temporary to same type as x t=0, n--; //=0 at loop start, also check n x=t //apply the result ) for(auto a:C) t=a+x*t; //Horner-Scheme } ; int main() { vector<double> C = {0.1,-2.3,-4};//{1,0,0}; for (int i = 0; i < 10; ++i) { double x=2.3; f(C, i, x); cout << i << ": " << x << endl; } } ``` [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 19 bytes ``` [:|:=:*c^2+:*c+:}?c ``` Takes inputs as * Number of iterations * starting value of x * Then the 3 parts of the polynomial Sample output: ``` Command line: 8 2.3 0.1 -2.3 -4 59.30772 ``` [Answer] ## Clojure, 66 bytes ``` #(nth(iterate(fn[v](apply +(map *(iterate(partial * v)1)%3)))%2)%) ``` Full example: ``` (def f #(nth(iterate(fn[v](apply +(map *(iterate(partial * v)1)%3)))%2)%)) (f 10 2.3 [-4 -2.3 0.1]) ; 3976.0831439050253 ``` Composing a function is 26 bytes: ``` #(apply comp(repeat % %2)) (def f #(apply comp(repeat % %2))) ((f 10 #(apply + (map * [-4 -2.3 0.1] (iterate (partial * %) 1)))) 2.3) ; 3976.0831439050253 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 bytes Pretty straightforward, does what the challenge says on the tin. ``` o r_VË*ZpVÊ-EÉÃx}W o // Take `n` and turn it into a range [0,n). r_ }W // Reduce over the range with initial value of `x`. VË // On each iteration, map over `p`, yielding the item *Z // times the current reduced value pVÊ-EÉ // to the correct power, Ãx // returning the sum of the results. ``` Takes inputs in order `n`, `p`, `x`. [Try it online!](https://tio.run/##y0osKPn/P1@hKD7scLdWVEHY4S5d18Odh5srasP//zfSUYg20DPU0TXSM9bRNYnVUQAyAA "Japt – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 39 bytes ``` p!x=(iterate(\y->foldl1((+).(y*))p)x!!) ``` [Try it online!](https://tio.run/##LcUxDoMwDADAt0TqYBcSOZUY6UdohwgCRDXUggzweQwDt9wY1l9kVhWz1ZByXEKO8Nntu/9zxx6gQAf7E1FwMwZ1CmmuZUlzfkBDjl4llfba31dfQ86jJ9Kj7TkMq9pW5AQ "Haskell – Try It Online") `(!)` takes as input a polynomial `p`, represented as a list of coefficients, a real number `x` and an integer `n`, and returns \$p^n(x)\$. [Answer] # [Factor](https://factorcode.org/) + `math.polynomials`, 35 bytes ``` [ [ [ polyval ] keep ] times drop ] ``` [Try it online!](https://tio.run/##fU@7DsIwDNz7FfcDrfpggg9ALCyICTFExYWoaRISg1Sqfntx2KksnR9nW3edatmF5Xw6HPdb9BQsGQyKHz8ovDOjdYNWJuJOloIy@qNYOxsR6fki21KED8Q8@qAtY5dNGTChLhrBfIM8VWVRYUaJ@S9XrXD12l16Oi8XpEhy38rgKk7IS2I9iL5bcNLITqdD5Ebmoti7SGLSI7Jq@2L5Ag "Factor – Try It Online") Takes a value, a list of coefficients (high powers on the right), and the number of times to iterate, in that order. `polyval` is a builtin word that evaluates a polynomial given a value and a list of coefficients. ]
[Question] [ Given an integer between 0 and 141 (inclusive), list all 24-hour times whose hour, minute, and second units add to that integer. **Rules of addition** Numbers are added by their time units, not by single digits. For example, take 17:43:59 17+43+59=119 Remember, that is an example of digits being *added.* In reality, you would enter 119, and 17:43:59 would be one of the results. Output should be given as HH:MM:SS or H:MM:SS. Also keep in mind the highest number possible is 141, being 23:59:59. This is code golf, so the lowest amount wins. Trial and error is permitted, but there may be a better way to go about this. Edit: Please specify where in your code the input value is. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ ~~30~~ ~~29~~ 20 bytes Now with the correct output format! Many thanks to Dennis for his help in debugging this answer. Golfing suggestions welcome. [Try it online!](https://tio.run/nexus/jelly#ASoA1f//4oCcw7A8POKAmMWScOKAmVM9wqXDkGZk4oG1auKCrOKAnTpZ////ODE "Jelly – TIO Nexus") **Edit:** +14 bytes from using the correct output format. -1 byte from removing an extra space. -3 from changing from `24,60,60` to `“ð<<‘`. -6 bytes from changing `+100DḊ€€` to `d⁵`. ``` “ð<<‘Œp’S=¥Ðfd⁵j€”:Y ``` **Explanation** ``` “ð<<‘Œp’S=¥Ðfd⁵j€”:Y Main link. Argument: n “ð<<‘ Jelly ord() the string `ð<<` to get [24, 60, 60]. Call this list z. Œp Cartesian product of z's items. Since each item of z is a literal, Jelly takes the range [1 ... item] for each item. ’ Decrements every number in the Cartesian product to get lowered ranges [0 ... item-1]. S=¥ Create a dyadic link of `sum is equal to (implicit n)`. Ðf Filter the Cartesian product for items with sum equal to n. d⁵ By taking divmod 10 of every number in each item, we get zero padding for single-digit numbers and every double-digit number just turns into a list of its digits. j€”: Join every number with a ':'. Y Join all of the times with linefeeds for easier reading. ``` [Answer] # Bash, 71 * 8 bytes saved thanks to @hvd ``` for t in {0..23}+{00..59}+{00..59};{((${t//+0/+}-$1))||echo ${t//+/:};} ``` [Try it online](https://tio.run/nexus/bash#@5@WX6RQopCZp1BtoKdnZFyrXW0AZJhaIhjW1RoaKtUl@vraBvratboqhpqaNTWpyRn5ChBRfata69r///8bGloCAA). [Answer] # [Perl 6](http://perl6.org/), ~~62~~ 56 bytes ``` {map *.fmt('%02d',':'),grep $_==*.sum,(^24 X ^60 X ^60)} ``` Just checks all possible combinations in the cross product of all hours, minutes, and seconds. [Answer] # [Python 3](https://docs.python.org/3/), 91 bytes ``` def f(n): for k in range(86400):t=k//3600,k//60%60,k%60;sum(t)==n!=print('%d:%02d:%02d'%t) ``` There are shorter solutions using `exec` (Python 2) or recursion (Python 3), but both require an unreasonable amount of memory. [Try it online!](https://tio.run/nexus/python3#JcZBCoAgEEDRfaeYFtIMBA4VEoaHCdSIaAqz85vQ5v1ffIgQUcg2EK8EB@wCaZUt4GwmZrLZHVqPhrmvNaxMncryvCdmck5ad6ddMnbKW8XDT6cylYgTlQ8 "Python 3 – TIO Nexus") [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~87~~ 77 bytes Saved 10 bytes thanks to [John L. Bevan](https://codegolf.stackexchange.com/users/6776/johnlbevan) ``` $d=date;0..86399|%{$d+=1e7l;"$d".Split()[1]}|?{("{0:H+m+s}"-f$d|iex)-in$args} ``` [Try it online!](https://tio.run/nexus/powershell#@6@SYpuSWJJqbaCnZ2FmbGlZo1qtkqJta5hqnmOtpJKipBdckJNZoqEZbRhbW2NfraFUbWDloZ2rXVyrpJumklKTmVqhqZuZp5JYlF5c@///f0MTQwA "PowerShell – TIO Nexus") (this will time out, it's very slow) ### Explanation Pretty simple, starting with the current `[datetime]`, add 1 second 86,399 times, format as a string, then keep only the ones where sum adds up. [Answer] ## Haskell, 77 bytes ``` f x=[tail$(':':).tail.show.(+100)=<<t|t<-mapM(\x->[0..x])[23,59,59],sum t==x] ``` [Answer] ## Haskell, 90 bytes ``` p x=['0'|x<10]++show x i=[0..59] f x=[p h++':':p m++':':p s|h<-[0..23],m<-i,s<-i,h+m+s==x] ``` Returns a list of HH:MM:SS strings, e.g. `f 140` -> `["22:59:59","23:58:59","23:59:58"]`. It's three simple loops through the hours, minutes and seconds. Keep and format all values where the sum is the input number `x`. [Answer] # Pyth - 30 bytes Takes all possible times then filters. ``` mj\:%L"%02d"dfqsTQsM*U24*KU60K ``` [Test Suite](http://pyth.herokuapp.com/?code=mj%5C%3A%25L%22%2502d%22dfqsTQsM%2aU24%2aKU60K&test_suite=1&test_suite_input=119%0A141&debug=0). [Answer] # [Julia 0.5](http://julialang.org/), 69 bytes ``` !n=[h+m+s==n&&@printf("%d:%02d:%02d ",h,m,s)for s=0:59,m=0:59,h=0:23] ``` [Try it online!](https://tio.run/nexus/julia5#@6@YZxudoZ2rXWxrm6em5lBQlJlXkqahpJpipWpgBCG4lHQydHJ1ijXT8osUim0NrEwtdXIhVAaQMjKO/a9o8h8A "Julia 0.5 – TIO Nexus") [Answer] ## Batch, 168 bytes ``` @for /l %%t in (0,1,86399)do @call:c %1 %%t @exit/b :c @set/ah=%2/3600,m=%2/60%%60,s=%2%%60,n=%1-h-m-s @set m=0%m% @set s=0%s% @if %n%==0 echo %h%:%m:~-2%:%s:~-2% ``` Outputs single-digit hours. [Answer] ## Mathematica, 79 bytes ``` Cases[Tuples@{(r=Range)@24-1,x=r@60-1,x},t_/;Tr@t==#:>DateString@TimeObject@t]& ``` [Answer] # Octave, ~~83~~ , 87 bytes ``` @(a){[H,M,S]=ndgrid(0:23,s=0:59,s);printf("%d:%02d:%02d\n",[H(x=H+M+S==a),M(x),S(x)]')} ``` [Try it Online!](https://tio.run/#es3Ej) [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~82~~ 72 bytes ``` :[0,23|[0,59|[0,59|~b+c+d=a|?!b$+@:`+right$(@0`+!c$,2)+A+right$(B+!d$,2) ``` This hits an unfortunate spot in QBasic, with casting to number, trimming and prepending a `0` when necessary is really costly. Sample output: ``` Command line: 119 1:59:59 2:58:59 2:59:58 3:57:59 [... SNIP 270 lines ...] 23:58:38 23:59:37 ``` ~~Explanation~~ I wrote a novel about it: ``` : Get N, call it 'a' [0,23| Loop through the hours; this FOR loop is initialised with 2 parameters using a comma to separate FROM and TO, and a '|' to delimit the argument list [0,59| Same for the minutes [0,59| And the seconds QBIC automatically creates variables to use as loop-counters: b, c, d (a was already taken by ':') ~b+c+d=a IF a == b+c+d | THEN ? PRINT ! CAST b 'b' $ To String; casting num to str in QBasic adds a space, this is trimmed in QBIC +@:` Create string A$, containing ":" +right$ This is a QBasic function, but since it's all lowercase (and '$' is not a function in QBIC) it remains unaltered in the resulting QBasic. (@0`+!c$,2) Pad the minutes by prepending a 0, then taking the rightmost 2 characters. +A Remember that semicolon in A$? Add it again +right$ Same for the seconds (B+!d$,2) Reusing the 0-string saves 2 bytes :-) ``` [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), 67 ~~79~~ Bytes (nasty version) Since the rules say nothing about completing in a certain time (or at all), and nothing about no duplicates, here's a horrific solution: ``` for(){if(("{0:H+m+s}"-f($d=date)|iex)-in$args){"{0:H:mm:ss}"-f$d}} ``` [Answer] ## Racket 39 bytes ``` (for*/sum((h 24)(m 60)(s 60))(+ h m s)) ``` Ungolfed: ``` (for*/sum ; loop for all combinations; return sum of values for each loop ((h 24) ; h from 0 to 23 (m 60) ; m from 0 to 59 (s 60)) ; s from 0 to 59 (+ h m s)) ; sum of all 3 variables ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 29 bytes ``` 24:q60:qt&Z*t!si=Y)'%i:'8:)&V ``` [Try it online!](https://tio.run/nexus/matl#@29kYlVoZmBVWKIWpVWiWJxpG6mprppppW5hpakW9v@/oaElAA "MATL – TIO Nexus") ### Explanation ``` 24:q % Push [0 1 ... 23] 60:q % Push [0 1 ... 59] t % Duplicate &Z* % Cartesian product of the three arrays. This gives a matrix with each % on a different row Cartesian tuple t! % Push a transposed copy s % Sum of each column i= % Logical mask of values that equal the input Y) % Select rows based on that mask '%i:' % Push this string 8:) % Index (modularly) with [1 2 ... 8]: gives string '%i:%i:%i' &V % Convert to string with that format specification. Implicitly display ``` [Answer] # JavaScript, ~~122~~ 120 bytes Takes one additional empty string as input, ~~which I presume doesn't count towards the size~~. *Updated bytecount (including historical) to add two bytes for the string's initialization.* ``` console.log(( //Submission starts at the next line i=>o=>{for(h=24;h--;)for(m=60;m--;)for(s=60;s--;)if(h+m+s==i)o+=`${h}:0${m}:0${s} `;return o.replace(/0\d{2}/g,d=>+d)} //End submission )(prompt("Number:",""))("")) ``` [Answer] # JavaScript (ES6), 110 ``` v=>eval("o=[];z=x=>':'+`0${x}`.slice(-2);for(m=60;m--;)for(s=60;s--;h>=0&h<24&&o.push(h+z(m)+z(s)))h=v-m-s;o") ``` *Less golfed* ``` v=>{ o=[]; z=x=>':' + `0${x}`.slice(-2); for(m = 60; m--;) for(s = 60; s--; ) h = v - m - s, h >= 0 & h < 24 && o.push(h + z(m) + z(s)) return o } ``` **Test** ``` F= v=>eval("o=[];z=x=>':'+`0${x}`.slice(-2);for(m=60;m--;)for(s=60;s--;h>=0&h<24&&o.push(h+z(m)+z(s)))h=v-m-s;o") function update() { O.textContent=F(+I.value).join`\n` } update() ``` ``` <input id='I' value=119 type=number min=0 max=141 oninput='update()'><pre id=O></pre> ``` [Answer] # JavaScript, 96 bytes ``` v=>{for (i=86399;i;[a,b,c]=[i/3600|0,i%3600/60|0,i--%60]){v-a-b-c?0:console.log(a+":"+b+":"+c)}} ``` Expanded view: ``` v => { for (i = 86399; i; [a, b, c] = [i / 3600 | 0, i % 3600 / 60 | 0, i-- % 60]) { v - a - b - c ? 0 : console.log(a + ":" + b + ":" + c) } } ``` Loop through all possible times by looping 86399 to 1, * convert the integer to time by dividing by 3600 to get the first digit * the 2nd digit by taking the integer mod 3600 and then dividing by 60 * and the last digit is the integer mod 60 Subtract all 3 numbers from the input value to return a falsey value if the three numbers add up to the input value. If the value is falsey, output the value. [Answer] # bash, 78 bytes (using a BSD utility) or 79 bytes (non-BSD also) This is a little longer than @DigitalTrauma and @hvd's nice 71-byte bash solution, but I kind of liked the idea here of using numbers in base 60; I'm curious if anybody can golf this down a little more. With the BSD-standard jot utility: ``` jot '-wx=`dc<<<60do3^%d+n`;((`dc<<<$x++'$1'-n`))||tr \ :<<<${x:3}' 86400 0|sh ``` With the more universally available seq utility: ``` seq '-fx=`dc<<<60do3^%.f+n`;((`dc<<<$x++'$1'-n`))||tr \ :<<<${x:3}' 0 86399|sh ``` The idea is to generate the numbers from 0 to 83699 and use dc to convert them into base 60. The "digits" in dc's base-60 output are 2-digit numbers from 00 to 59, with spaces separating the "digits", so this lists all the desired times from 00 00 00 to 23 59 59 in almost the format needed. If you literally carry that out, though, numbers below 60^2 aren't 3-digit numbers in base 60, so the initial 00 or 00 00 is missing. For that reason, I'm actually generating the numbers from 60^3 to 60^3+83699; this ensures that all the numbers generated are exactly 4 digits long in base 60. This is OK as long as I eventually throw away the extra first digit (01) that isn't needed. So, once the desired times are generated, I just take each quadruple from 01 00 00 00 to 01 23 59 59, add the last three numbers and subtract the argument $1. If that's 0, I then take everything in the quadruple from the 3rd character on (throwing away the "01 "), use tr to convert spaces to colons, and print the result. [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), 91 ~~97~~ bytes (including input) ``` param($x)1..864e3|%{($d=date($_*1e7l))}|?{("{0:H+m+s}"-f$_|iex)-eq$x}|%{"{0:H:mm:ss}"-f$_} ``` ~~`param($x)0..23|%{$h=$_;0..59|%{$m=$_;0..59|?{$h+$m+$_-eq$x}|%{"{0:0}:{1:00}:{2:00}"-f$h,$m,$_}}}`~~ or `param($x)0..23|%{$h=$_;0..59|?{($s=$x-$h-$_)-le59-and$s-ge0}|%{"{0:0}:{1:00}:{2:00}"-f$h,$_,$s}}` <\s> Expanded & commented ``` param($x) #loop through the hours 0..23 | %{ $h=$_ #loop through the minutes 0..59 | %{ $m=$_ #loop through the seconds 0..59 | ?{ #filter for those where the sum matches the target $h + $m + $_ -eq $x } | %{ #format the result "{0:#0}:{1:00}:{2:00}" -f $h, $m, $_ } } } ``` NB: Surpassed by @Briantist's version: <https://codegolf.stackexchange.com/a/105163/6776> ]
[Question] [ Given an integer `N > 1`, output all other numbers which prime decompositions have the same digits as the prime decomposition of `N`. For example, if `N = 117`, then the output must be `[279, 939, 993, 3313, 3331]`, because ``` 117 = 3 × 3 × 13 ``` therefore, the available digits are `1`, `3`, `3` and `3` and we have ``` 279 = 3 × 3 × 31 939 = 3 × 313 993 = 3 × 331 3313 = 3313 3331 = 3331 ``` Those are the only other possible numbers, because other combination of these digits yield non-prime integers, which can't be the result of prime factorization. If `N` is any of `117`, `279`, `939`, `993`, `3313` or `3331`, then the output will contain the five other numbers: they are prime factors buddies. You cannot use leading zeroes to get primes, e.g. for `N = 107`, its only buddy is `701` (`017` is not considered). ### Input and Outputs * The input and output buddies must be taken and returned in the decimal base. * `N` will always be strictly greater than `1`. * The output can be formatted rather freely, as long as it only contains the buddies and separators/list syntactic elements. * The ordering of the output is unimportant. * You may take the input through `STDIN`, as a function argument or anything similar. * You may print the output to `STDOUT`, return it from a function, or anything similar. ### Test cases Your program should solve any of the test cases below in **less than a minute**. ``` N Buddies 2 [] 4 [] 8 [] 15 [53] 16 [] 23 [6] 42 [74, 146, 161] 126 [222, 438, 483, 674, 746, 851, 1466, 1631, 1679] 204 [364,548,692,762,782,852,868,1268,1626,2474,2654,2921,2951,3266,3446,3791,4274,4742,5426,5462,6233,6434,6542,7037,8561,14426,14642,15491,15833,22547] ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] ## PowerShell v3+, 450 bytes ``` param($n)function f{param($a)for($i=2;$a-gt1){if(!($a%$i)){$i;$a/=$i}else{$i++}}} $y=($x=@((f $n)-split'(.)'-ne''|sort))|?{$_-eq(f $_)} $a,$b=$x $a=,$a while($b){$z,$b=$b;$a=$a+($a+$y|%{$c="$_";0..$c.Length|%{-join($c[0..$_]+$z+$c[++$_..$c.Length])};"$z$c";"$c$z"})|select -u} $x=-join($x|sort -des) $l=@();$a|?{$_-eq(f $_)}|%{$j=$_;for($i=0;$i-le$x;$i+=$j){if(0-notin($l|%{$i%$_})){if(-join((f $i)-split'(.)'|sort -des)-eq$x){$i}}}$l+=$j}|?{$_-ne$n} ``` ***Finally!*** PowerShell doesn't have any built-ins for primality checking, factorization, or permutations, so this is completely rolled by hand. I worked through a *bunch* of optimization tricks to try and reduce the time complexity down to something that will fit in the challenge restrictions, and I'm happy to say that I finally succeeded -- ``` PS C:\Tools\Scripts\golfing> Measure-Command {.\prime-factors-buddies.ps1 204} Days : 0 Hours : 0 Minutes : 0 Seconds : 27 Milliseconds : 114 Ticks : 271149810 TotalDays : 0.000313830798611111 TotalHours : 0.00753193916666667 TotalMinutes : 0.45191635 TotalSeconds : 27.114981 TotalMilliseconds : 27114.981 ``` ### Explanation There's a lot going on here, so I'll try to break it down. The first line takes input `$n` and defines a `function`, `f`. This function uses accumulative trial division to come up with a list of the prime factors. It's pretty speedy for small inputs, but obviously bogs down if the input is large. Thankfully all the test cases are small, so this is sufficient. The next line gets the `f`actors of `$n`, `-split`s them on every digit ignoring any empty results (this is needed due to how PowerShell does regex matching and how it moves the pointer through the input and is kinda annoying for golfing purposes), then `sort`s the results in ascending order. We store that array of digits into `$x`, and use that as the input to a `|?{...}` filter to pull out only those that are themselves prime. Those prime digits are stored into `$y` for use later. We then split `$x` into two components. The first (i.e., smallest) digit is stored into `$a`, while the rest are passed into `$b`. If `$x` only has one digit, then `$b` will be empty/null. We then need to re-cast `$a` as an array, so we use the comma operator quick-like to do so. Next, we need to construct all possible permutations of the digits. This is necessary so our division tests later skip a *bunch* of numbers and make things faster overall. So long as there's element left in `$b`, we peel off the first digit into `$z` and leave the remaining in `$b`. Then, we need to accumulate into `$a` the result of some string slicing and dicing. We take `$a+$y` as array concatenation, and for each element we construct a new string `$c`, then loop through `$c`'s `.length` and insert `$z` into every position, including prepending `$z$c` and appending `$c$z`, then `select`ing only the `-u`nique elements. That's again array-concatenated with `$a` and re-stored back into `$a`. Yes, this does wind up having goofy things happen, like you can get `3333` for input `117`, which isn't actually a permutation, but this is much shorter than attempting to explicitly filter them out, ensures that we get every permutation, and is only very marginally slower. So, now `$a` has an array of all possible (and then some) permutations of the factor's digits. We need to re-set `$x` to be our upper-bound of possible results by `|sort`ing the digits in `-des`cending order and `-join`ing them back together. Obviously, no output value can be larger than this number. We set our helper array `$l` to be an array of values that we've previously seen. Next, we're pulling out every value from `$a` (i.e., those permutations) that are prime, and enter a loop that is the biggest time sink of the whole program... Every iteration, we're looping from `0` to our upper bound `$x`, incrementing by the current element `$j`. So long as the `$i` value we're considering is *not* a multiple of a previous value (that's the `0-notin($l|%{$i%$_})` section), it's a potential candidate for output. If we take the `f`actors of `$i`, `sort` them, and they `-eq`ual `$x`, then add the value to the pipeline. At the end of the loop, we add our current element `$j` into our `$l` array for use next time, as we've already considered all those values. Finally, we tack on `|?{$_-ne$n}` to pull out those that are not the input element. They're all left on the pipeline and output is implicit. ### Examples ``` PS C:\Tools\Scripts\golfing> 2,4,8,15,16,23,42,117,126,204|%{"$_ --> "+(.\prime-factors-buddies $_)} 2 --> 4 --> 8 --> 15 --> 53 16 --> 23 --> 6 42 --> 74 146 161 117 --> 279 939 993 3313 3331 126 --> 222 438 674 746 1466 483 851 1679 1631 204 --> 782 2921 3266 6233 3791 15833 2951 7037 364 868 8561 15491 22547 852 762 1626 692 548 1268 2654 3446 2474 5462 4742 5426 4274 14426 6542 6434 14642 ``` [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), ~~26~~ 23 bytes ``` {_mfs$:XW%i){mfs$X=},^} ``` [Try it online](http://cjam.tryitonline.net/#code=MjA0Cgp7X21mcyQ6WFclaSl7bWZzJFg9fSxefQoKfnA&input=MjA0) ### Explanation Concatenating two numbers always gives a bigger result than multiplying them. So the largest number we possibly need to consider is the largest number we can form from the digits of the input's prime factorisation, which is just all digits sorted in descending order. For the given numbers this upper bound is easily small enough that we can exhaustively check every number in range for whether it's a prime factor buddy: ``` _mf e# Duplicate input N and get a list of its prime factors. s$ e# Convert the list to a (flattened) string and sort it. :X e# Store this in X for later. W% e# Reverse it. This is now a string repesentation of the largest e# possible output M. i) e# Convert to integer and increment. { e# Get a list of all integers i in [0 1 ... M] for which the following e# block gives a truthy result. mf e# Get list of prime factors of i. s$ e# Get a sorted list of the digits appearing in the factorisation. X= e# Check for equality with X. }, ^ e# Symmetric set difference: removes N from the output list. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 17 bytes Code: ``` ÒJ{©RƒNÒJ{®QN¹Ê*– ``` Explanation: ``` Ò # Get the factorization with duplicates, e.g. [3, 3, 13] J # Join the array, e.g. 3313 {© # Sort and store in ©, e.g. 1333 R # Reverse the number, e.g. 3331. This is the upperbound for the range ƒ # For N in range(0, a + 1), do... NÒ # Push the factorization with duplicates for N J # Join the array { # Sort the string ®Q # Check if equal to the string saved in © N¹Ê # Check if not equal to the input * # Multiply, acts as a logical AND – # If 1, print N ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w5JKe8KpUsaSTsOSSnvCrlFOwrnDiirigJM&input=NDI) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆfVṢṚḌ ÇÇ€=ÇTḟ ``` Execution time could be halved with `DF` instead of `V`, but it still completes the combined test cases in under thirty seconds. [Try it online!](http://jelly.tryitonline.net/#code=w4ZmVuG5ouG5muG4jArDh8OH4oKsPcOHVOG4nw&input=&args=MTE3) or [verify all test cases](http://jelly.tryitonline.net/#code=w4ZmVuG5ouG5muG4jArDh8OH4oKsPcOHVOG4nwrDh-KCrEc&input=&args=MiwgNCwgOCwgMTUsIDE2LCAyMywgNDIsIDEyNiwgMjA0). ### How it works ``` ÆfVṢṚḌ Helper link. Argument: k (integer) Æf Decompose k into an array of primes with product k. V Eval. Eval casts a 1D array to string first, so this computes the integer that results of concatenating all primes in the factorization. Ṣ Sort. Sort casts a number to the array of its decimal digits. Ṛ Reverse. This yields the decimal digits in descending order. Ḍ Undecimal; convert the digit array from base 10 to integer. ÇÇ€=ÇTḟ Main link. Argument: n (integer) Ç Call the helper link with argument n. This yields an upper bound (u) for all prime factorization buddies since the product of a list of integers cannot exceed the concatenated integers. Ç€ Apply the helper link to each k in [1, ..., u]. Ç Call the helper link (again) with argument n. = Compare each result to the left with the result to the right. T Truth; yield all 1-based indices of elements of [1, ..., u] (which match the corresponding integers) for which = returned 1. ḟ Filter; remove n from the indices. ``` [Answer] ## Pyth, 17 ``` LSjkPb-fqyTyQSs_y ``` [Test suite](https://pyth.herokuapp.com/?code=LSjkPb-fqyTyQSs_y&input=117&test_suite=1&test_suite_input=2%0A4%0A8%0A15%0A16%0A23%0A42%0A126%0A204%0A279&debug=0). Uses the same observation as from [Martin's post](https://pyth.herokuapp.com/?code=LSjkPb-fqyTyQSs_y&input=117&test_suite=1&test_suite_input=2%0A4%0A8%0A15%0A16%0A23%0A42%0A126%0A204%0A279&debug=0). ### Expansion: ``` LSjkPb ## Define a function y(b) to get the sorted string of digits ## of the prime factors of b Pb ## prime factors jk ## join to a string with no separator S ## Sort -fqyTyQSs_yQQ ## Auto-fill variables _yQ ## get reversed value of y(input) Ss ## convert that string to a list [1 ... y(input)] fqyTyQ ## keep numbers T from the list that satisfy y(T)==y(input) - Q ## remove the input from the result ``` [Answer] ## JavaScript (ES6), ~~163~~ 158 bytes ***Edit**: It has been clarified that a prime such as 23 should return [6] rather an empty result set. Saved 5 bytes by removing a now useless rule that was -- on purpose -- preventing that from happening.* The last test case is commented so that this snippet runs fast enough, although it should complete in less than one minute just as well. ``` let f = n=>[...Array(+(l=(p=n=>{for(i=2,m=n,s='';i<=m;n%i?i++:(s+=i,n/=i));return s.split``.sort().reverse().join``})(n))+1)].map((_,i)=>i).filter(i=>i&&i-n&&p(i)==l) console.log(JSON.stringify(f(2))); console.log(JSON.stringify(f(4))); console.log(JSON.stringify(f(8))); console.log(JSON.stringify(f(15))); console.log(JSON.stringify(f(16))); console.log(JSON.stringify(f(23))); console.log(JSON.stringify(f(42))); console.log(JSON.stringify(f(126))); //console.log(JSON.stringify(f(204))); ``` [Answer] # Powershell, 147 bytes (CodeGolf version) ``` param($n)filter d{-join($(for($i=2;$_-ge$i*$i){if($_%$i){$i++}else{"$i" $_/=$i}}if($_-1){"$_"})|% t*y|sort -d)}2..($s=$n|d)|?{$_-$n-and$s-eq($_|d)} ``` Note: The script solve last test cases less than 3 minutes on my local notebook. See "performance" solution below. Less golfed test script: ``` $g = { param($n) filter d{ # in the filter, Powershell automatically declares the parameter as $_ -join($( # this function returns a string with all digits of all prime divisors in descending order for($i=2;$_-ge$i*$i){ # find all prime divisors if($_%$i){ $i++ }else{ "$i" # push a divisor to a pipe as a string $_/=$i } } if($_-1){ "$_" # push a last divisor to pipe if it is not 1 } )|% t*y|sort -d) # t*y is a shortcut to toCharArray method. It's very slow. } 2..($s=$n|d)|?{ # for each number from 2 to number with all digits of all prime divisors in descending order $_-$n-and$s-eq($_|d) # leave only those who have the 'all digits of all prime divisors in descending order' are the same } } @( ,(2 ,'') ,(4 ,'') ,(6 ,23) ,(8 ,'') ,(15 ,53) ,(16 ,'') ,(23 ,6) ,(42 ,74, 146, 161) ,(107 ,701) ,(117 ,279, 939, 993, 3313, 3331) ,(126 ,222, 438, 483, 674, 746, 851, 1466, 1631, 1679) ,(204 ,364,548,692,762,782,852,868,1268,1626,2474,2654,2921,2951,3266,3446,3791,4274,4742,5426,5462,6233,6434,6542,7037,8561,14426,14642,15491,15833,22547) ) | % { $n,$expected = $_ $sw = Measure-Command { $result = &$g $n } $equals=$false-notin(($result|%{$_-in$expected})+($expected|?{$_-is[int]}|%{$_-in$result})) "$sw : $equals : $n ---> $result" } ``` Output: ``` 00:00:00.0346911 : True : 2 ---> 00:00:00.0662627 : True : 4 ---> 00:00:00.1164648 : True : 6 ---> 23 00:00:00.6376735 : True : 8 ---> 00:00:00.1591527 : True : 15 ---> 53 00:00:03.8886378 : True : 16 ---> 00:00:00.0441986 : True : 23 ---> 6 00:00:01.1316642 : True : 42 ---> 74 146 161 00:00:01.0393848 : True : 107 ---> 701 00:00:05.2977238 : True : 117 ---> 279 939 993 3313 3331 00:00:12.1244363 : True : 126 ---> 222 438 483 674 746 851 1466 1631 1679 00:02:50.1292786 : True : 204 ---> 364 548 692 762 782 852 868 1268 1626 2474 2654 2921 2951 3266 3446 3791 4274 4742 5426 5462 6233 6434 6542 7037 8561 14426 14642 15491 15833 22547 ``` --- # Powershell, 215 bytes ("Performance" version) ``` param($n)$p=@{} filter d{$k=$_*($_-le3e3) ($p.$k=-join($(for($i=2;!$p.$_-and$_-ge$i*$i){if($_%$i){$i++}else{"$i" $_/=$i}}if($_-1){($p.$_,"$_")[!$p.$_]})-split'(.)'-ne''|sort -d))}2..($s=$n|d)|?{$_-$n-and$s-eq($_|d)} ``` Note: I believe the performance requirements are in conflict with the GodeGolf principle. But since there was a rule `Your program should solve any of the test cases below in less than a minute`, I made two changes to satisfy the rule: * `-split'(.)'-ne''` instead the short code `|% t*y`; * a hashtable for cashing strings. Each change reduces evaluation time by half. Please do not think that I have used all the features to improve performance. Just those were enough to satisfy the rule. Less golfed test script: ``` $g = { param($n) $p=@{} # hashtable for 'all digits of all prime divisors in descending order' filter d{ # this function returns a string with all digits of all prime divisors in descending order $k=$_*($_-le3e3) # hashtable key: a large hashtable is not effective, therefore a key for numbers great then 3000 is 0 # and string '-le3e3' funny ($p.$k=-join($( # store the value to hashtable for($i=2;!$p.$_-and$_-ge$i*$i){ if($_%$i){$i++}else{"$i";$_/=$i} } if($_-1){ ($p.$_,"$_")[!$p.$_] # get a string with 'all digits of all prime divisors in descending order' from hashtable if it found } )-split'(.)'-ne''|sort -d)) # split each digit. The "-split'(.)-ne''" code is faster then '|% t*y' but longer. } 2..($s=$n|d)|?{ # for each number from 2 to number with all digits of all prime divisors in descending order $_-$n-and$s-eq($_|d) # leave only those who have the 'all digits of all prime divisors in descending order' are the same } } @( ,(2 ,'') ,(4 ,'') ,(6 ,23) ,(8 ,'') ,(15 ,53) ,(16 ,'') ,(23 ,6) ,(42 ,74, 146, 161) ,(107 ,701) ,(117 ,279, 939, 993, 3313, 3331) ,(126 ,222, 438, 483, 674, 746, 851, 1466, 1631, 1679) ,(204 ,364,548,692,762,782,852,868,1268,1626,2474,2654,2921,2951,3266,3446,3791,4274,4742,5426,5462,6233,6434,6542,7037,8561,14426,14642,15491,15833,22547) ) | % { $n,$expected = $_ $sw = Measure-Command { $result = &$g $n } $equals=$false-notin(($result|%{$_-in$expected})+($expected|?{$_-is[int]}|%{$_-in$result})) "$sw : $equals : $n ---> $result" } ``` Output: ``` 00:00:00.0183237 : True : 2 ---> 00:00:00.0058198 : True : 4 ---> 00:00:00.0181185 : True : 6 ---> 23 00:00:00.4389282 : True : 8 ---> 00:00:00.0132624 : True : 15 ---> 53 00:00:04.4952714 : True : 16 ---> 00:00:00.0128230 : True : 23 ---> 6 00:00:01.4112716 : True : 42 ---> 74 146 161 00:00:01.3676701 : True : 107 ---> 701 00:00:07.1192912 : True : 117 ---> 279 939 993 3313 3331 00:00:07.6578543 : True : 126 ---> 222 438 483 674 746 851 1466 1631 1679 00:00:50.5501853 : True : 204 ---> 364 548 692 762 782 852 868 1268 1626 2474 2654 2921 2951 3266 3446 3791 4274 4742 5426 5462 6233 6434 6542 7037 8561 14426 14642 15491 15833 22547 ``` [Answer] # PHP 486 bytes could probably be shorter with an algorithm that´s not so by the book. (but I like the current byte count) ``` function p($n){for($i=1;$i++<$n;)if($n%$i<1&&($n-$i?p($i)==$i:!$r))for($x=$n;$x%$i<1;$x/=$i)$r.=$i;return $r;}function e($s){if(!$n=strlen($s))yield$s;else foreach(e(substr($s,1))as$p)for($i=$n;$i--;)yield substr($p,0,$i).$s[0].substr($p,$i);}foreach(e(p($n=$argv[1]))as$p)for($m=1<<strlen($p)-1;$m--;){$q="";foreach(str_split($p)as$i=>$c)$q.=$c.($m>>$i&1?"*":"");foreach(split("\*",$q)as$x)if(0===strpos($x,48)|p($x)!=$x)continue 2;eval("\$r[$q]=$q;");}unset($r[$n]);echo join(",",$r); ``` **breakdown** ``` // find and concatenate prime factors function p($n) { for($i=1;$i++<$n;) // loop $i from 2 to $n if($n%$i<1 // if $n/$i has no remainder &&($n-$i // and ... ?p($i)==$i // $n!=$i: $i is a prime :!$r // $n==$i: result so far is empty ($n is prime) ) ) for($x=$n; // set $x to $n $x%$i<1; // while $x/$i has no remainder $x/=$i) // 2. divide $x by $i $r.=$i; // 1. append $i to result return $r; } // create all permutations of digits function e($s) { if(!$n=strlen($s))yield$s;else // if $s is empty, yield it, else: foreach(e(substr($s,1))as$p) // for all permutations of the number w/o first digit for($i=$n;$i--;) // run $i through all positions around the other digits // insert removed digit at that position and yield yield substr($p,0,$i).$s[0].substr($p,$i); } // for each permutation foreach(e(p($n=$argv[1]))as$p) // create all products from these digits: binary loop through between the digits for($m=1<<strlen($p)-1;$m--;) { // and insert "*" for set bits $q=""; foreach(str_split($p)as$i=>$c)$q.=$c.($m>>$i&1?"*":""); // test all numbers in the expression foreach(split("\*",$q)as$x) if( 0===strpos($x,48) // if number has a leading zero |p($x)!=$x // or is not prime )continue 2; // try next $m // evaluate expression and add to results (use key to avoid array_unique) eval("\$r[$q]=$q;"); } // remove input from results unset($r[$n]); // output #sort($r); echo join(",",$r); ``` [Answer] # Actually, 27 bytes This uses the same algorithm that [Martin](https://codegolf.stackexchange.com/a/93869/47581), [Adnan](https://codegolf.stackexchange.com/a/93870/47581), [FryAmTheEggman](https://codegolf.stackexchange.com/a/93892/47581), and [Dennis](https://codegolf.stackexchange.com/a/93903/47581) have been using. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=YHciaSRuIsKjTc6jU1LiiYhg4pWX4pWcxpI74pWdUmDilZzGkuKVmz1g4paR&input=MTAy) ``` `w"i$n"£MΣSR≈`╗╜ƒ;╝R`╜ƒ╛=`░ ``` **Ungolfing** ``` Implicit input n. `...`╗ Define a function and store it in register 0. Call the function f(x). w Get the prime factorization of x. "..."£M Begin another function and map over the [prime, exponent] lists of w. i Flatten the list. Stack: prime, exponent. $n Push str(prime) to the stack, exponent times. The purpose of this function is to get w's prime factors to multiplicity. Σ sum() the result of the map. On a list of strings, this has the same effect as "".join() SR≈ Sort that string, reverse it and convert to int. ╜ƒ Now push the function stored in register 0 and call it immediately. This gives the upper bound for any possible prime factor buddy. ;╝ Duplicate this upper bound and save a copy to register 1. R Push the range [0..u] `...`░ Filter the range for values where the following function returns a truthy. Variable k. ╜ƒ Push the function in register 0 and call it on k. ╛= Check if f(k) == f(n). Implicit return every value that is a prime factor buddy with n, including n. ``` [Answer] # Japt, 18 bytes ``` k ¬ñ Ôn õ f@¥Xk ¬ñ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=ayCs8QrUbiD1IGZApVhrIKzx&input=MjA0) ]
[Question] [ In the strategy game ["Hexplode"](https://en.wikipedia.org/wiki/Hexplode), players take turns placing tokens on a hexagonal board. Once the number of tokens equals the number of adjacent tiles, that tile *hexplodes*, and moves all of the tokes on it to the surrounding neighbors. You can play the game online [here](http://manahlcoderprize.elasticbeanstalk.com/). I like this game, but sometimes it's hard to know exactly how many tokens go on a specific tile; I'm always *counting* the number of neighbors. It would really convenient if I had an ASCII-art to help me remember how many tokens go on each tile. You need to write a program or function that takes a positive integer as input, and produces this ASCII representation of hexagon of size **N**. Each tile will be the number of neighbors that tile has. Since 1 is a weird corner case with zero neighbors, you only have to handle inputs larger than 1. You may take this number in any reasonable format, such as STDIN, function arguments, command-line arguments, from a file, etc. The output may also be in any reasonable format, such as printing to STDOUT, writing to a file, returning a list of strings, a newline separated string, etc. Here is some sample output for the first 5 inputs: ``` 2) 3 3 3 6 3 3 3 3) 3 4 3 4 6 6 4 3 6 6 6 3 4 6 6 4 3 4 3 4) 3 4 4 3 4 6 6 6 4 4 6 6 6 6 4 3 6 6 6 6 6 3 4 6 6 6 6 4 4 6 6 6 4 3 4 4 3 5) 3 4 4 4 3 4 6 6 6 6 4 4 6 6 6 6 6 4 4 6 6 6 6 6 6 4 3 6 6 6 6 6 6 6 3 4 6 6 6 6 6 6 4 4 6 6 6 6 6 4 4 6 6 6 6 4 3 4 4 4 3 6) 3 4 4 4 4 3 4 6 6 6 6 6 4 4 6 6 6 6 6 6 4 4 6 6 6 6 6 6 6 4 4 6 6 6 6 6 6 6 6 4 3 6 6 6 6 6 6 6 6 6 3 4 6 6 6 6 6 6 6 6 4 4 6 6 6 6 6 6 6 4 4 6 6 6 6 6 6 4 4 6 6 6 6 6 4 3 4 4 4 4 3 ``` And the pattern continues in a similar manner. As usual, standard loopholes apply, and the answer with the lowest byte-count will be crowned the winner! ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=92194,OVERRIDE_USER=31716;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## JavaScript (ES6), ~~118~~ 117 bytes ``` n=>[...Array(m=n+--n)].map((_,i,a)=>a.map((_,j)=>(k=j-(i>n?i-n:n-i))<0?``:k&&++j<m?i/2%n?6:4:3+!i%n).join` `).join`\n` ``` Where `\n` represents a literal newline character. Explanation: Suppose `n=4`. We start with the following space-separated digit square: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` The first `|n-i|` `0`s are deleted, but the spaces remain: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` Instant hexagon! It then suffices to calculate the appropriate value in place of each `0` by checking whether we're on the first or last row and/or column. Edit: Saved 1 byte thanks to @Arnauld. [Answer] # [MATL](http://github.com/lmendo/MATL), ~~39~~ 37 bytes ``` 4*3-:!G:+o~YRtP*!tPw4LY)vtI5&lZ+47+*c ``` [Try it online!](http://matl.tryitonline.net/#code=NCozLTohRzorb35ZUnRQKiF0UHc0TFkpdnRJNSZsWis0NysqYw&input=NQ) Or [verify all test cases](http://matl.tryitonline.net/#code=IkAKNCozLTohQDorb35ZUnRQKiF0UHc0TFkpdnRJNSZsWis0NysqYwowY1hE&input=Mjo2). ### Explanation *I get to use convolution again!* Consider input `n = 3`. The code first builds a matrix of size `4*n-3`×`n` by adding the column vector `[1; 2; ...; 9]` to the row vector `[1, 2, 3]` with broadcast. This means computing a 2D array array of all pairwise additions: ``` 2 3 4 3 4 5 4 5 6 5 6 7 6 7 8 7 8 9 8 9 10 9 10 11 10 11 12 ``` Replacing even numbers by `1` and odd numbers by `0` gives the checkerboard pattern ``` 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 ``` This will be used for generating (part of) the hexagonal grid. Ones will represent points in the grid, and zeros will represent spaces. The upper-right corner is removed by zeroing out all entries above the main "diagonal" of the matrix: ``` 1 0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 ``` Element-wise multiplying this matrix by a vertically flipped version of itself removes the lower-right corner as well. Transposing then gives ``` 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 0 0 1 0 1 0 1 0 0 ``` This begins to look like a hexagon. Using symmetry, the grid is extended to produce the upper half: ``` 0 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 1 0 1 0 1 0 0 0 1 0 1 0 1 0 0 ``` Now we need to replace each entry equal to one by the number of neighbours. For this we use convolution with a 3×5 neighbourhood (that is, the kernel is a 3×5 matrix of ones). The result, ``` 2 3 4 5 5 5 4 3 2 4 5 7 7 8 7 7 5 4 4 6 7 8 7 8 7 6 4 4 5 7 7 8 7 7 5 4 2 3 4 5 5 5 4 3 2 ``` has two issues (which will be solved later): 1. The values have been computed for all positions, whereas we only need them at the positions of the ones in the zero-one grid. 2. For each of those positions, the neighbour count includes the point itself, so it is off by `1`. The code now adds `47` to each computed value. This corresponds to subtracting `1` to solve issue (2) and adding `48` (ASCII for `'0'`), which converts each number to the code point of its corresponding char. The resulting matrix is then multiplied by a copy of the zero-one grid. This solves issue (1) above, making the points that are not part of the hexagonal grid equal to zero again: ``` 0 0 51 0 52 0 51 0 0 0 52 0 54 0 54 0 52 0 51 0 54 0 54 0 54 0 51 0 52 0 54 0 54 0 52 0 0 0 51 0 52 0 51 0 0 ``` Finally, this array of numbers is cast to a char array. Zero chars are displayed as space, which gives the final result: ``` 3 4 3 4 6 6 4 3 6 6 6 3 4 6 6 4 3 4 3 ``` [Answer] # Python 2, ~~125~~ 123 bytes ``` def h(n):m=n-1;t=[' '*(m-r)+' '.join(('46'[r>0]*(r+m-1)).join('34'[r%m>0]*2))for r in range(n)];print'\n'.join(t+t[-2::-1]) ``` Tests are on [**ideone**](http://ideone.com/vpwfFh) Runs through the top to the middle rows, `for r in range(n)`, constructing strings: - making two corners or two edges, `'34'[r%m>0]*2`; - filling by joining them with repeated `'6'` or `'4'`, `'46'[r>0]*(r+m-1)`; - joining the corners and edges with `' '`; - prepending with spaces, `' '*(m-r)`; Then prints this and it's reflection in the middle row joined by new lines, `print'\n'.join(t+t[-2::-1])` [Answer] ## Python 2, 96 bytes ``` n=input();m=n-1 while n+m:n-=1;j=abs(n);c='34'[0<j<m];print' '*j+c+' '+'46 '[j<m::2]*(2*m+~j)+c ``` This looks pretty messy and somewhat golfable... [Answer] # Java, ~~375~~ ~~363~~ ~~361~~ ~~339~~ ~~329~~ ~~317~~ 293 bytes ``` interface J{static void main(String[]r){int i=0,k,h=Integer.decode(r[0]),a=1,l,n=0;for(;i++<h*2-1;n+=a){if(n==h-1)a=-1;String s="";for(k=0;k<n+h;k++,s+=" ")s+=n==0?k==0||k==n+h-1?3:4:k!=0&&k!=n+h-1?6:n==h-1?3:4;l=(h*4-3-s.trim().length())/2;System.out.printf((l==0?"%":"%"+l)+"s%s\n","",s);}}} ``` **Ungolfed** ``` interface J { static void main(String[] r) { int i = 0, k, h = Integer.decode(r[0]), a = 1, l, n = 0; for (; i++ < h * 2 - 1; n += a) { if (n == h - 1) { a = -1; } String s = ""; for (k = 0; k < n + h; k++, s += " ") { s += n == 0 ? k == 0 || k == n + h - 1 ? 3 : 4 : k != 0 && k != n + h - 1 ? 6 : n == h - 1 ? 3 : 4; } l = (h * 4 - 3 - s.trim().length()) / 2; System.out.printf((l == 0 ? "%" : "%" + l) + "s%s\n", "", s); } } } ``` **Usage**: ``` $ java J 5 3 4 4 4 3 4 6 6 6 6 4 4 6 6 6 6 6 4 4 6 6 6 6 6 6 4 3 6 6 6 6 6 6 6 3 4 6 6 6 6 6 6 4 4 6 6 6 6 6 4 4 6 6 6 6 4 3 4 4 4 3 ``` I am sure that the horrible nested if-else block can be rewritten to be smaller but I can't figure it out at the moment. Any suggestions are welcome :-) **Update** * Followed Kevin Cruijssen's suggestion and used decode instead of parseInt. * Rewrote some ifs by using the ternary operator. * More ternary operators. * Moar ternary operators! I think I have created a monster! * Rewrote the if-else block regarding the printing. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 44 bytes ``` FN_i4ë6}ð«¹ÍN+×ðìN_N¹<Q~i3ë4}.ø¹<N-ð×ì})¦«» ``` **Explanation** As the top and bottom of the hexagon are mirrored we only need to generate the upper part. So for an input of **X** we need to generate **X** rows. That is what the main loop does. ``` F } ``` Then we do the center part of the rows. This is **4** for the first row and **6** for the rest (as we're only doing the upper part). We concatenate this number with a space as the pattern will require spacing between numbers. ``` N_i4ë6}ð« ``` We then repeat this string **X-2+N** times, where N is the current row 0-indexed and prepend a space character on the left side. ``` ¹ÍN+×ðì ``` After this it's time for the corners. They will be **3** for the first and last row and **4** for the middle rows. ``` N_N¹<Q~i3ë4}.ø ``` Now we need to make sure the rows are lined up correctly by adding spaces to the front of each row. The number of spaces added will be **X-1-N**. ``` ¹<N-ð×ì ``` Now that we have the upper part of the grid done, we add the rows to a list, create a reversed copy and remove the first item from that copy (as we only need the central row once), then merge these 2 lists together and print. ``` )¦«» ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Rk5faTTDqzZ9w7DCq8K5w41OK8OXw7DDrE5fTsK5PFF-aTPDqzR9LsO4wrk8Ti3DsMOXw6x9KcOCwqbCq8K7&input=NQ) **Additional solution, also 44 bytes:** ``` ÍÅ10.øvN_i4ë6}ð«¹ÍN+×ðìyi4ë3}.ø¹<N-ð×ì})¦«» ``` [Answer] # Ruby, 87 bytes Anonymous function takes n as argument and returns an array of strings. ``` ->n{(1-n..n-=1).map{|i|j=i.abs " "*j+(e=j%n>0?"4 ":"3 ")+["6 ","4 "][j/n]*(2*n-1-j)+e}} ``` **Ungolfed in test program** Input through stdin. Writes the whole shape to stdout. Pretty self explanatory. ``` f=->n{ (1-n..n-=1).map{|i| #reduce n by 1 and iterate i from -n to n j=i.abs; #absolute magnitude of i " "*j+ #j spaces + (e=j%n>0?"4 ":"3 ")+ #start the string with 3 or 4 + ["6 ","4 "][j/n]*(2*n-1-j)+ #2*n-1-j 6's or 4`s as appropriate + e #end the string with another 3 or 4 } } puts f[gets.to_i] ``` [Answer] # [V](http://github.com/DJMcMayhem/V), 60 bytes ``` Àé x@aA4 xr3^.òhYpXa 6^òkyHç^/:m0 Pç 3.*6/^r4$. òÍ6 4./6 ``` [Try it online!](http://v.tryitonline.net/#code=w4DDqSB4QGFBNCAbeHIzXi7DsmhZcFhhIDYbXsOya3lIw6deLzptMApQw6cgMy4qNi9ecjQkLgrDssONNiDCkzTChS4vNg&input=&args=Mw) This is really way too long. Here is a hexdump, since this contains unprintable characters: ``` 0000000: c0e9 2078 4061 4134 201b 7872 335e 2ef2 .. x@aA4 .xr3^.. 0000010: 6859 7058 6120 361b 5ef2 6b79 48e7 5e2f hYpXa 6.^.kyH.^/ 0000020: 3a6d 300a 50e7 2033 2e2a 362f 5e72 3424 :m0.P. 3.*6/^r4$ 0000030: 2e0a f2cd 3620 9334 852e 2f36 ....6 .4../6 ``` [Answer] # Racket, 487 bytes ``` (λ(n c e o)(let((sp(append(range(- n 1)-1 -1)(reverse(range(- n 1)0 -1)))) (mm(append(range(- n 2)(-(+ n(- n 1))2))(range(-(+ n(- n 1))2)(-(- n 1)2)-1))) (r""))(for((i sp)(j mm))(define str"")(for((ss i))(set! str(string-append str" "))) (set! str(string-append str(if(or(= i 0)(= i(- n 1))(= i(* 2(- n 1))))c e)" ")) (for((jj j))(set! str(string-append str(if(= j(- n 2))e o)" ")))(set! r(if(or(= i 0) (= i(- n 1))(= i(* 2(- n 1))))c e))(set! str(string-append str r))(displayln str)))) ``` Testing: ``` (f 4 "3" "4" "6") 3 4 4 3 4 6 6 6 4 4 6 6 6 6 4 3 6 6 6 6 6 3 4 6 6 6 6 4 4 6 6 6 4 3 4 4 3 (f 5 "o" "*" "-") o * * * o * - - - - * * - - - - - * * - - - - - - * o - - - - - - - o * - - - - - - * * - - - - - * * - - - - * o * * * o ``` Detailed version: ``` (define(f1 n c e o) (let ((sp(append(range(sub1 n) -1 -1) (reverse(range(sub1 n) 0 -1)))) (mm(append(range(- n 2)(-(+ n(sub1 n)) 2)) (range(-(+ n(sub1 n)) 2)(-(sub1 n)2) -1) )) (r "")) (for((i sp)(j mm)) (define str "") (for((ss i))(set! str(string-append str " "))) (set! str(string-append str (if(or(= i 0)(= i(sub1 n)) (= i(* 2(sub1 n)))) c e) " ")) (for((jj j)) (set! str(string-append str (if(= j(- n 2)) e o) " "))) (set! r(if(or(= i 0) (= i(sub1 n)) (= i(* 2(sub1 n)))) c e)) (set! str(string-append str r)) (displayln str)))) ``` ]
[Question] [ # Symbolic Differentiation 1: Gone Coefishin' ## Task Write a program that takes in a polynomial in *x* from stdin (1 < deg(p) < 128) and differentiates it. The input polynomial will be a string of the following form: ``` "a + bx + cx^2 + dx^3 +" ... ``` where the coefficient of each term is an integer (-128 < a < 128). Each term is separated by one space, a +, and another space; linear and constant terms appear as above (i.e., no `x^0` or `x^1`). Terms will appear in order of increasing degree, and those powers with zero coefficient **are omitted.** All terms with coefficient 1 or -1 display that coefficient explicitly. Your output must have precisely the same form. Note that coefficients in the output might be as big as 127\*127 == 16129. ## Examples ``` "3 + 1x + 2x^2" ==> "1 + 4x" "1 + 2x + -3x^2 + 17x^17 + -1x^107" ==> "2 + -6x + 289x^16 + -107x^106" "17x + 1x^2" ==> "17 + 2x" ``` ## Scoring Your score is the length of your program in bytes, multiplied by three if you use a built-in or a library that does symbolic algebra. [Answer] # [Retina](https://github.com/mbuettner/retina), ~~53~~ ~~43~~ ~~42~~ ~~41~~ ~~40~~ 35 bytes ``` ^[^x]+ |(\^1)?\w(?=1*x.(1+)| |$) $2 ``` For counting purposes each line goes in a separate file, but you can run the above as a single file by invoking Retina with the `-s` flag. This expects the numbers in the input string [to be given in unary](http://meta.codegolf.stackexchange.com/q/5343/8478) and will yield output in the same format. E.g. ``` 1 + 11x + -111x^11 + 11x^111 + -1x^11111 --> 11 + -111111x + 111111x^11 + -11111x^1111 ``` instead of ``` 1 + 2x + -3x^2 + 2x^3 + -1x^5 --> 2 + -6x + 6x^2 + -5x^4 ``` ## Explanation The code describes a single regex substitution, which is basically 4 substitutions compressed into one. Note that only one of the branches will fill group `$2` so if any of the other three match, the match will simply be deleted from the string. So we can look at the four different cases separately: ``` ^[^x]+<space> <empty> ``` If it's possible to reach a space from the beginning of the string without encountering an `x` that means the first term is the constant term and we delete it. Due to the greediness of `+`, this will also match the plus and the second space after the constant term. If there is no constant term, this part will simply never match. ``` x(?= ) <empty> ``` This matches an `x` which is followed by a space, i.e. the `x` of the linear term (if it exists), and removes it. We can be sure that there's a space after it, because the degree of the polynomial is always at least 2. ``` 1(?=1*x.(1+)) $1 ``` This performs the multiplication of the coefficient by the exponent. This matches a single `1` in the coefficient and replaces it by the entire corresponding exponent via the lookahead. ``` (\^1)?1(?= |$) <empty> ``` This reduces all remaining exponents by matching the trailing `1` (ensured by the lookahead). If it's possible to match `^11` (and a word boundary) we remove that instead, which takes care of displaying the linear term correctly. For the compression, we notice that most of the conditions don't affect each other. `(\^1)?` won't match if the lookahead in the third case is true, so we can put those two together as ``` (\^1)?1(?=1*x.(1+)| |$) $2 ``` Now we already have the lookahead needed for the second case and the others can never be true when matching `x`, so we can simply generalise the `1` to a `\w`: ``` (\^1)?\w(?=1*x.(1+)| |$) $2 ``` The first case doesn't really have anything in common with the others, so we keep it separate. [Answer] # CJam, ~~43~~ 41 bytes ``` Qleu'^/';*'+/{~:E[*'x['^E(]]E<}/]1>" + "* ``` *Thanks to @jimmy23013 for pointing out one bug and golfing off two bytes!* Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=Qleu'%5E%2F'%3B*'%2B%2F%7B~%3AE%5B*'x%5B'%5EE(%5D%5DE%3C%7D%2F%5D1%3E%22%20%2B%20%22*&input=1%20%2B%202x%20%2B%20-3x%5E2%20%2B%2017x%5E17%20%2B%20-1x%5E107). ### How it works ``` Q e# Leave an empty array on the bottom of the stack. l e# Read a line from STDIN. eu'^/';* e# Convert to uppercase and replace carets with semicolons. '+/ e# Split at plus signs. { e# For each resulting chunk: ~ e# Evaluate it. "X" pushes 1 and ";" discards. e# For example, "3X" pushes (3 1) and "3X;2" (3 2). :E e# Save the rightmost integer (usually the exponent) in E. [ e# * e# Multiply both integers. e# For a constant term c, this repeats the empty string (Q) c times. 'x e# Push the character 'x'. ['^E(] e# Push ['^' E-1]. ] e# E< e# Keep at most E elements of this array. e# If E == 1, 'x' and ['^' E-1] are discarded. e# If E == 2, ['^' E-1] is discarded. e# If E >= 3, nothing is discarded. }/ e# ] e# Wrap the entire stack in an array. 1> e# Discard its first element. e# If the first term was constant, this discards [""]. ["" 'x'] e# or ["" 'x' ['^' E-1]], depending on the constant. e# In all other cases, it discards the untouched empty array (Q). " + "* e# Join all kept array elements, separating by " + ". ``` [Answer] # Julia, 220 bytes No regular expressions! ``` y->(A=Any[];for i=parse(y).args[2:end] T=typeof(i);T<:Int&&continue;T==Symbol?push!(A,1):(a=i.args;c=a[2];typeof(a[3])!=Expr?push!(A,c):(x=a[3].args[3];push!(A,string(c*x,"x",x>2?string("^",ex-1):""))))end;join(A," + ")) ``` This creates a lambda function that accepts a string and returns a string. The innards mimic what happens when Julia code is evaluated: a string is parsed into symbols, expressions, and calls. I might actually try writing a full Julia symbolic differentiation function and submit it to be part of Julia. Ungolfed + explanation: ``` function polyderiv{T<:AbstractString}(y::T) # Start by parsing the string into an expression p = parse(y) # Define an output vector to hold each differentiated term A = Any[] # Loop through the elements of p, skipping the operand for i in p.args[2:end] T = typeof(i) # Each element will be an integer, symbol, or expression. # Integers are constants and thus integrate to 0. Symbols # represent x alone, i.e. "x" with no coefficient or # exponent, so they integrate to 1. The difficulty here # stems from parsing out the expressions. # Omit zero derivatives T <: Int && continue if T == Symbol # This term will integrate to 1 push!(A, 1) else # Get the vector of parsed out expression components. # The first will be a symbol indicating the operand, # e.g. :+, :*, or :^. The second element is the # coefficient. a = i.args # Coefficient c = a[2] # If the third element is an expression, we have an # exponent, otherwise we simply have cx, where c is # the coefficient. if typeof(a[3]) != Expr push!(A, c) else # Exponent x = a[3].args[3] # String representation of the differentiated term s = string(c*x, "x", x > 2 ? string("^", x-1) : "") push!(A, s) end end end # Return the elements of A joined into a string join(A, " + ") end ``` [Answer] # Perl, ~~64~~ 63 bytes 62b code + 1 command line (-p) ``` s/(\d+)x.(\d+)/$1*$2."x^".($2-1)/eg;s/\^1\b|^\d+ . |x(?!\^)//g ``` Usage example: ``` echo "1 + 2x + 3x^2" | perl -pe 's/(\d+)x.(\d+)/$1*$2."x^".($2-1)/eg;s/\^1\b|^\d+ . |x(?!\^)//g' ``` *Thanks Denis for -1b* [Answer] # C, ~~204~~ 162 bytes ``` #define g getchar()^10 h,e;main(c){for(;!h&&scanf("%dx%n^%d",&c,&h,&e);h=g?g?e?printf(" + "):0,0:1:1)e=e?e:h?1:0,e?printf(e>2?"%dx^%d":e>1?"%dx":"%d",c*e,e-1):0;} ``` Basically parse each term and print out the differentiated term in sequence. Fairly straightforward. [Answer] # JavaScript ES6, 108 bytes ``` f=s=>s.replace(/([-\d]+)(x)?\^?(\d+)?( \+ )?/g,(m,c,x,e,p)=>x?(c*e||c)+(--e?x+(e>1?'^'+e:''):'')+(p||''):'') ``` ## ES5 Snippet: ``` // ES5 version, the only difference is no use of arrow functions. function f(s) { return s.replace(/([-\d]+)(x)?\^?(\d+)?( \+ )?/g, function(m,c,x,e,p) { return x ? (c*e||c) + (--e?x+(e>1?'^'+e:''):'') + (p||'') : ''; }); } [ '3 + 1x + 2x^2', '1 + 2x + -3x^2 + 17x^17 + -1x^107', '17x + 1x^2' ].forEach(function(preset) { var presetOption = new Option(preset, preset); presetSelect.appendChild(presetOption); }); function loadPreset() { var value = presetSelect.value; polynomialInput.value = value; polynomialInput.disabled = !!value; showDifferential(); } function showDifferential() { var value = polynomialInput.value; output.innerHTML = value ? f(value) : ''; } ``` ``` code { display: block; margin: 1em 0; } ``` ``` <label for="presetSelect">Preset:</label> <select id="presetSelect" onChange="loadPreset()"> <option value="">None</option> </select> <input type="text" id="polynomialInput"/> <button id="go" onclick="showDifferential()">Differentiate!</button> <hr /> <code id="output"> </code> ``` [Answer] # Python 2, 166 bytes Boy, this seems longer than it should be. ``` S=str.split def d(t):e="^"in t and int(S(t,"^")[1])-1;return`int(S(t,"x")[0])*(e+1)`+"x"[:e]+"^%d"%e*(e>1) print" + ".join(d(t)for t in S(raw_input()," + ")if"x"in t) ``` The function `d` takes a non-constant term `t` and returns its derivative. The reason I `def` the function instead of using a lambda is so I can assign the exponent minus 1 to `e`, which then gets used another four times. The main annoying thing is having to cast back and forth between strings and ints, although Python 2's backtick operator helps with that. We then split the input into terms and call `d` on each one that has `"x"` in it, thereby eliminating the constant term. The results are joined back together and printed. [Answer] # CJam, ~~62~~ ~~57~~ ~~55~~ 49 bytes Well, Dennis put this to shame before I even noticed that the site was back up. But here is my creation anyway: ``` lS/{'x/:T,({T~1>:T{~T~*'xT~(:T({'^T}&}&" + "}&}/; ``` Latest version saves a few bytes with shortcuts suggested by @Dennis (use variables, and split at space instead of `+`). [Try it online](http://cjam.aditsu.net/#code=lS%2F%7B'x%2F%3AT%2C(%7BT~1%3E%3AT%7B~T~*'xT~(%3AT(%7B'%5ET%7D%26%7D%26%22%20%2B%20%22%7D%26%7D%2F%3B&input=1%20%2B%202x%20%2B%20-3x%5E2%20%2B%2017x%5E17%20%2B%20-1x%5E107) [Answer] # Pyth, 62 bytes ``` jJ" + "m::j"x^",*Fdted"x.1$"\x"x.0"kftTmvMcd"x^"c:z"x ""x^1 "J ``` Pretty ugly solution, using some regex substitutions. [Answer] # Python 3, 176 bytes ``` s=input().split(' + ') y='x'in s[0] L=map(lambda x:map(int,x.split('x^')),s[2-y:]) print(' + '.join([s[1-y][:-1]]+['x^'.join(map(str,[a*b,b-1])).rstrip('^1')for a,b in L])) ``` Indeed, the main annoyance is having to convert between strings and ints. Also, if a constant term was required, the code would only be **153** bytes. [Answer] ## Python 2, 229 bytes ``` import os print' + '.join([i,i[:-2]][i[-2:]=='^1'].replace('x^0','')for i in[`a*b`+'x^'+`b-1`for a,b in[map(int,a.split('x^'))for a in[[[i+'x^0',i+'^1'][i[-1]=='x'],i]['^'in i]for i in os.read(0,9**9).split(' + ')]]]if i[0]!='0') ``` [Answer] # Python 2, 174 bytes ``` print' + '.join(['%d%s%s'%(b[0]*b[1],'x'*(b[1]>1),'^%d'%(b[1]-1)*(b[1]>2))for b in[map(int,a.split('x^')if 'x^'in a else[a[:-1],1])for a in input().split(' + ')if 'x'in a]]) ``` Unfortunately, DLosc's trick to rename the split method and perform the differentiation in a specific function does not shorten my code... ]
[Question] [ ## Background [**Penney's game**](https://en.wikipedia.org/wiki/Penney%27s_game) is a two-player game about coin tossing. Player A announces a sequence of heads and tails of length \$n\$, then player B selects a different sequence of same length. The winner is the one whose sequence appears first as a substring (consecutive subsequence) in repeated coin toss. [**Conway's algorithm**](https://mathoverflow.net/a/357282) describes how to calculate the odds of a single sequence of length \$n\$ in Penney's game: > > For every integer \$1\le i \le n\$, add \$2^i\$ if its first \$i\$ items match the last \$i\$ items. The sum is the expected amount of tosses before you will see the exact pattern. For example (all examples being \$n=6\$), > > > * `HHHHTT`: Only matches at \$i=6\$, so the expected number of tosses is \$64\$. > * `TTHHTT`: Matches at \$i=1,2,6\$, so the expected number of tosses is \$2+4+64=70\$. > * `HHHHHH`: Matches everywhere, so \$2+4+8+16+32+64=126\$. > > > This generalizes easily to \$p\$-sided dice: for each match, add \$p^i\$ instead. > > > ## Task Suppose we play Penney's game with \$p\$-sided dice, where \$p\ge 2\$. Given the value of \$p\$ and a sequence of outcomes \$S\$ as input, calculate the expected tosses before you get the exact pattern \$S\$. The elements of \$S\$ can be \$1 \dots p\$ or \$0 \dots p-1\$. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` p S ans ------------------------------------------ 2 [0, 0, 0, 0, 1, 1] 64 2 [1, 1, 0, 0, 1, 1] 70 3 [1, 1, 1, 1, 1] 363 9 [0, 1, 2, 3, 4, 5, 6, 7, 8] 387420489 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 9 bytes Port of [@*Dingus*'s Ruby answer](https://codegolf.stackexchange.com/a/203788/92069), so make sure to upvote him! -7 bytes thanks to Grimmy. ``` η¹.sÀgmO ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3PZDO/WKDzc/alqTnuv//3@0oY4CEBmAEYgdy2UEAA "05AB1E – Try It Online") ## Explanation ``` η Find all prefixes of the input ¹ Re-take the first input .s Find all suffixes of the input à Find the two lists' intersection €g Find the length of each m Exponentiation by the second input O Sum the output list ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 57 bytes Modification of @math junkie's code making use of the walrus operator. ``` lambda p,S,i=0:sum(p**(i:=i+1)*(S[:i]==S[-i:])for _ in S) ``` [Try it online!](https://tio.run/##bYzLCsIwEEX3fsUskzhCY33UQL4iyxikIsEBmw6xLvz6GBSKoHBW91wOP6frmNqOc4n2WG79cL70wOiQbGPuj0GwUoKMpaWWSjhvKFjr/IpMkHHMcAJK4GThTGkSUawRfIMwoytBysW31@/5v29nr3/l4ROvc83U5wZhi7BD2CN09Vhe "Python 3.8 (pre-release) – Try It Online") --- An alternative 51-byte solution assuming that we may take an extra argument \$ l \$ denoting the length of the list. # [Python 2](https://docs.python.org/2/), 51 bytes ``` f=lambda p,S,l:l and(S[:l]==S[-l:])*p**l+f(p,S,l-1) ``` [Try it online!](https://tio.run/##dc3NCsMgDMDx@54iR3Up1O6zgk/hUTw4imyQWRm97Olt6MDtMsjt/0tS3st9zkOtyVJ83qYIBR2SIYh5Es4bCtY635EJUhWlaJ/EJjota3k98gJJDAi@R2ijeQLCWe5@hd7CP3FoQrd8@ubx84IDn2J75Mr7CBeEK9NR1hU "Python 2 – Try It Online") [Answer] # [J](http://jsoftware.com/), 18 15 bytes ``` #.0,~<\.=[:|.<\ ``` [Try it online!](https://tio.run/##Xc29CsJAEATg3qcYtAjCuuz9eHc5cpVgZWVrOjEEG19A8uqXxYiiMNvMtzD3uuZmQMloQBBkvR3jcD4d64aFpq7ncslP7vq6Xd2u4wPBo8BigNA3RrNwlDebV/vPLjh193Hzgyl6Kz61@tIuC4qW4AiesCcEQiSkOgM "J – Try It Online") * Create the boxed suffixes `<\.` and reversed prefixes `[:|.<\`... * and check where they match elementwise `=`... * This will be a boolean mask representing the number we seek in base `p`, but shifted right one. * `0,~` shifts it back how we want... * `#.` converts it using base `p` [Answer] # [Python 2](https://docs.python.org/2/), 55 bytes ``` f=lambda p,l,i=0:l==l[:i]or(l[:i]==l[-i:])+p*f(p,l,i+1) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoUAnRyfT1sAqx9Y2J9oqMza/SANMg7i6mVaxmtoFWmkaYFXahpr/C4oy80oU0jSMdBSiDXQU4MgQiGI1uZClDcGiWKWN4dKGGHKWEJOBokBDgApNdBRMdRTMdBTMdRQsYjX/AwA "Python 2 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk/wiki/Commands), ~~12~~ ~~10~~ 9 [bytes](https://github.com/barbuz/Husk/wiki/Codepage) ``` ΣMo^L§nṫḣ ``` Port of [*@petStorm*'s 05AB1E answer](https://codegolf.stackexchange.com/a/203789/52210), so make sure to upvote him! -2 bytes thanks to *@Zgarb*. -1 byte thanks to *@Leo*. [Try it online.](https://tio.run/##yygtzv7//9xi3/w4n0PL8x7uXP1wx@L///9HG@oY6hgAIZCO/W8EAA) **Explanation:** ``` § # Using the first argument-list twice: ḣ # Take its prefixes ṫ # And its suffices n # List intersection; keep only the sublists which are present in both M # Map over each remaining sublist as left argument, o # using the following two commands: L # Take the length of the sublist ^ # take the power of the two: input^length Σ # And then sum the integers in the mapped list # (after which the result is output implicitly) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~55~~ ~~53~~ 49 bytes ``` ->p,s{(1..s.size).sum{|i|s[0,i]==s[-i,i]?p**i:0}} ``` [Try it online!](https://tio.run/##ZYvNCsIwEITvfYo5atmGxn@F6IOEPai0mEOhuOlBkz57DBYKIgzDMt@3z@H2Sq1J1bknCQutlChx72apZOhCdFFsTY6NEVu5fFz6snSnehyTb8QLDGwB2BVlDXN0DjNNBFZ/lz@0npH@2Y@Ua1Lzd7Y2hC1hR9gTDswFq@Z6fyAg@ogerS09Y0wf "Ruby – Try It Online") Similar to the non-recursive [Python answer](https://codegolf.stackexchange.com/a/203785/92901). [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 20 bytes ``` {⍺+.*≢¨(⌽¨,\⌽⍵)∩,\⍵} ``` ``` {⍺+.*≢¨(⌽¨,\⌽⍵)∩,\⍵} ,\⍵ prefixes ∩ intersect (⌽¨,\⌽⍵) suffixes ≢¨ length of each ⍺+.* exponentiation and sum ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR7y5tPa1HnYsOrdB41LP30AqdGCD1qHer5qOOlUB279ba/2mP2iY86u171NX8qHfNo94th9YbP2qb@KhvanCQM5AM8fAM/m@kkKZgAIWGCoZcID6QhvONoXww5LIEqzZUMFIwVjBRMFUwUzBXsAAA "APL (Dyalog Extended) – Try It Online") [Answer] # [Red](http://www.red-lang.org), 87 bytes ``` func[p s][o: 0 repeat n d: length? s[if(at s d + 1 - n)= copy/part s n[o: p ** n + o]]] ``` [Try it online!](https://tio.run/##Zcy9CsIwFIbhPVfxjdoiNtbfgHgPruEMpUm0UJKQxMGrjwldFDnT98B7glb5rpUkZkQ2LztKj0jSCXQsaK@HBAslMGv7SM8bopzMqmCEQguODez6ykbn31s/hOq2xh5NU8IWjoiyD5NNMNhBdliOgxP78rL/vV@c/@qlfuEl6rHHAUeccKb8AQ "Red – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 31 bytes ``` {x/|0,{(y#x)~|y#|x}/:[y;1+!#y]} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qukK/xkCnWqNSuUKzrqZSuaaiVt8qutLaUFtRuTK29n@aQrSltYGCoYKRgrGCiYKpgpmCuYJF7H8A "K (oK) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` eÐƤ¹Ƥ$;0ḅ ``` A dyadic Link accepting a list on the left and an integer on the right which yields an integer. **[Try it online!](https://tio.run/##y0rNyan8/z/18IRjSw7tPLZExdrg4Y7W////RxvqKACRARiB2LH/jQA "Jelly – Try It Online")** ### How? ``` eÐƤ¹Ƥ$;0ḅ - Link: list, S; integer, p e.g. [2,3,1,2,3]; 4 $ - last two links as a monad: Ƥ - for prefixes (of S): [2] [2,3] [2,3,1] [2,3,1,2] [2,3,1,2,3] ¹ - identity [2] [2,3] [2,3,1] [2,3,1,2] [2,3,1,2,3] - } =[[2],[2,3],[2,3,1],[2,3,1,2],[2,3,1,2,3]] ÐƤ - for post-fixes (of S): [2,3,1,2,3] [3,1,2,3] [1,2,3] [2,3] [3] e - exists in (the collected prefixes)? 1 0 0 1 0 - } =[1, 0, 0, 1, 0] 0 - literal zero 0 ; - concatenate [1, 0, 0, 1, 0, 0] ḅ - convert from base (p) 1×4⁵+0×4⁴+0×4³+1×4²+0×4¹+0×4° =1024+16 =1040 ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 55 bytes ``` ~[".+¶$.("|'_Lv$`((,\d+)+)$(?<=^(\d+)\1\b.*) $#2*$($3$* ``` [Try it online!](https://tio.run/##K0otycxLNPyvqpEQHasQHcv1vy5aSU/70DYVPQ2lGvV4nzKVBA0NnZgUbU1tTRUNexvbOA0QJ8YwJklPS5NLRdlIS0VDxVhF6/9/Ix0FhWgDHQU4MgSiWC6wsCGYhyxsjBA2hIlZQk0A8oC6gCpMdBRMdRTMdBTMdRQsYgE "Retina – Try It Online") Link includes test suite. Takes input as a comma-separated list, but the test suite removes spaces and brackets for ease of use. Explanation: ``` Lv$`((,\d+)+)$(?<=^(\d+)\1\b.*) ``` Match all (necessarily overlapping) suffixes of the input starting with a comma that also match immediately after the base. ``` $#2*$($3$* ``` For each match, output a string of the form `2*2*` where `2` is the input base and the number of `2`s is the number of matched integers. (The trailing `)` is implied.) ``` [".+¶$.("|'_ ``` Join the matches with a `_` and prefix the whole output with the following: ``` .+ $.( ``` For the second example, this results in the following: ``` .+ $.(2*2*2*2*2*2*_2*2*_2* ``` Note that the `_)` at the end of the program is implied. ``` ~ ``` Evaluate the generated Retina program, thus computing the desired result. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` I×θ↨θEη⁼…η⁻Lηκ✂ηκ ``` [Try it online!](https://tio.run/##HUnLCsIwEPyVPW5hBfXam8GbBUFvpYclBBNcU9ukQr9@TTIM87SeVzuzqN7XEDMaThmf4eMSLgQXTq76wF/0BNdlY0lodivO@LltQ4hbwpuLr@zRdwTvrshDgnX1Lq2hVx3PBDCeCAqPjTVPkx5@8gc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Eη Map over elements of `S` ✂ηκ `S` sliced starting at that element ⁼ Is equal to …η⁻Lηκ Prefix of `S` with that length ↨θ Convert from base `p` ×θ Multiply by `p` I Cast to string for implicit print ``` [Answer] # Pure [Bash](https://www.gnu.org/software/bash/), 70 bytes ``` for((i=$#;--i;)){ [ "${*:2:$i}" = "${*: -$i}" ]&&$[s+=$1**i];};echo $s ``` [Try it online!](https://tio.run/##S0oszvifnFiiYKdQUJSfXpSYq2Bjo@Tq76b0Py2/SEMj01ZF2VpXN9NaU7NaIVpBSaVay8rISiWzVknBFsJT0AXzYtXUVKKLtW1VDLW0MmOta61TkzPyFVSK/wPN4krOyM1PUSjVroBZwsWlpw@zz0jBAAoNFQxRxIF8LOLGYHFDNFFLsDojoKyJgqmCmYK5gsV/AA "Bash – Try It Online") The input is passed in the arguments: first `p`, then the items (each as a separate argument). Output is on stdout. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 16 bytes ``` sm*q<Qd>dQ^vzdSl ``` [Try it online!](https://tio.run/##K6gsyfj/vzhXq9AmMMUuJTCurColOOf//2hDHQUEiuUyBgA "Pyth – Try It Online") Map (`m`) over the 1-indexed range of the sequence (`Sl(Q)`). If the first `d` elements of the sequence (`<Qd`) equals the last `d` elements (`>dQ`), map to "p to the power of d" (`^vzd`). Sum the result (`s`). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes ``` {{a₀.&a₁}ᵗlᵗ^}ᶠ+ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv7o68VFTg54akGwECkzPAeK42ofbFmj//x@tEG2kE22gA4GGOoaxsTogESALWcQYImII41uC9BjqGOkY65jomOqY6ZjrWMTGKsQCAA "Brachylog – Try It Online") ``` + The output is the sum of { }ᶠ every possible output from: a₀. find a prefix &a₁ which is also a suffix { }ᵗ of the last item of the input, lᵗ take its length, ^ and take the first element to the power of that length. ``` ]
[Question] [ When you look at the last decimal digit of each power of a non-negative integer a repeating pattern forms. For example, 3: ``` 3^1 = 3 3^2 = 9 3^3 = 27 3^4 = 81 3^5 = 243 3^6 = 729 3^7 = 2187 3^8 = 6561 3^9 = 19683 ``` The last digits go `3971` which repeats indefinitely. In fact any number we choose that ends in 3 has that same pattern because none of the other digits can have an effect on the ones place during repeated multiplication. What's curious is that some numbers have a much shorter cycle of power-ending digits. For example with 5 the powers all end in 5 so the pattern, written as short as possible, is simply `5`. Looking at the minimal power-ending digits patterns for 0 through 9 we get: ``` 0 -> 0 1 -> 1 2 -> 2486 3 -> 3971 4 -> 46 5 -> 5 6 -> 6 7 -> 7931 8 -> 8426 9 -> 91 ``` (The lengths of these being `11442` repeated is a curious tidbit itself.) Remember, any numbers above 9 will have the same pattern as their last digit as was explained above with 3. # Challenge Your challenge here is to write a program that takes in any non-negative integer and outputs its minimal power-ending digit pattern. The exact output formatting, whether string or list, doesn't matter. For example, here are some potential inputs followed by valid potential outputs: ``` 900 -> [0] 11 -> 1 2 -> 2486 303 -> 3, 9, 7, 1 44 -> 4 6 45 -> 5 666 -> "6" 3857 -> [7 9 3 1] 118 -> '8426' 129 -> [9, 1] ``` **The shortest code in bytes wins.** [Answer] # Python 3, ~~44~~ ~~43~~ 40 bytes Based off of [mabel's answer](https://codegolf.stackexchange.com/a/198817/75323) but using dictionary comprehensions: ``` lambda n:[*{n**i%10:0for i in[1,2,3,4]}] ``` Saved 1 byte thanks to mabel. Saved 3 bytes thanks to xnor. You can [try it online](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRIc8qWqs6T0srU9XQwMogLb9IIVMhMy/aUMdIx1jHJLY29j9ILA8oplCUmJeeqmFoYqZpxaUABAVFmXklGmlK1Xm1Crp2CtVpGnmatUqa/wE) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` *Ɱ4%⁵Q ``` A monadic link which accepts an integer and yield a list of integers. **[Try it online!](https://tio.run/##y0rNyan8/1/r0cZ1JqqPGrcG/v//39DIEgA "Jelly – Try It Online")** ### How? ``` *Ɱ4%⁵Q - Link: integer, n 4 - four Ɱ - map across (implicit range of [1..4]) with: * - exponentiate ⁵ - ten % - (powers) mod (ten) Q - de-duplicate ``` [Answer] # JavaScript (ES6), 41 bytes ``` n=>[n%=10]+[[,,486,971,6,,,931,426,1][n]] ``` [Try it online!](https://tio.run/##Zc9BDsIgEIXhvadgY9LG0TJAKSzqRQiLprbGpgFjjddHktnB@sufmbdNv@mYP6/39xriY0nrmMJ4d@E8IvcX5wCU0WAHBA0AViIooQG9C96nOYYj7sttj89mbZjlvG1Z1zF@KoQhkmAlTJCIfKdEySWhzA9UpVKEStfUE/WlaK1JykaafiAZ8sgyQzSEJq@vUFhCi@kP "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 42 bytes A recursive version. ``` n=>(g=k=>(d=(k*n)%10)-n?[k]+g(d):k)(n%=10) ``` [Try it online!](https://tio.run/##Zc1NDsIgFATgvadg0wQ0tTygFEzQgxgXTf@iNGCs8frY5O1gM4v5MplX/@u34fN8f@sQxynNLgV3pYvze46O@mNgFXBWh9vdP04LHdnFMxoqt5dpiGGL63Re40JnSiznjJGmIfyQCQFAgUKIQBHK6Bwll4jSduVSKUSlS2qR2ly01ij5Rpq2Q@msLL4ADKJRongDYREtpD8 "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 54 bytes ``` lambda n:list(dict.fromkeys(n**i%10for i in(1,2,3,4))) ``` [Try it online!](https://tio.run/##NcrBCoMwDADQXwmCkEgZVj0JfonzUKfRME2l9iLit3envfM7rrh6rRNDB@@0uX2cHGi7yRlxkk98cfD7d75O1KKQ3JbsAwiIojWVqU1DRKk/gmhEzm55WrgZhZ6M4F8hOF1mtCUN6Qc "Python 3 – Try It Online") Could have been 38 bytes if `set()` was ordered. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 6 bytes -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) ``` 4LmT%Ù ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fxCc3RPXwzP//DY0sAQ "05AB1E – Try It Online") Just a port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/198811/91097). [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` 4:^10\u ``` [Try it online!](https://tio.run/##y00syfn/38QqztAgpvT/f2MLU3MA "MATL – Try It Online") ### Explanation ``` 4: % Push [1 2 3 4] ^ % Implicit input, n. Element-wise power: gives [n n^2 n^3 n^4] 10\ % Modulo 10 u % Unique (remove duplicates). Implicit display ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~10~~ 8 bytes Jo King suggested a shorter function than what I originally had, `∪10⊤*∘⍳∘4` (a train at 9 bytes) vs my 10-byter dfn, and ngn pointed out a tradfn would be shorter than both altogether ``` ∪10⊤⎕*⍳4 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9DUisMjSoedQ3VetR72YTkNj/NC5DYyMA "APL (Dyalog Unicode) – Try It Online") `⍳4` the vector 1 2 3 4 `⎕*` the input raised to the power of, i.e. `(⍵*1)(⍵*2)(⍵*3)(⍵*4)` (using `⍵` to represent the value of the input) `10⊤` mod 10 `∪` unique [Answer] # Haskell, ~~48~~ 46 bytes `import Data.List;f n=nub[n^i`mod`10|i<-[1..4]]` -2 bytes thanks to @Laikoni Having to import `nub` is really annoying... Any suggestions to remove it? You can [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrTSHPNq80KTovLjMhNz8lwdCgJtNGN9pQT88kNvZ/bmJmnoKtQkFpSXBJkYKKQnFGfjmQyk0sUEhTACkyMoj9/x8A) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 42 bytes ``` n=>new Set([1,2,3,4].map(v=>(n%10)**v%10)) ``` [Try it online!](https://tio.run/##Zc1NDoIwFATgvafoxqQQhL7@0S7gEi6NC4LFaLAlQvD4VfN27WqS@TKZ57AP6/h@LNvJh5uLUxd913v3IWe30QtUvBKVvNavYaF711N/BFaU5f6PIo7Br2F29RzudKLEsl9JmoawQyIEAAUyIRyFS6NTFEwgCtvmSykRpc5JIalUtNYo6UYY1aK0VmRfAAbRSJ69AbeIFuIX "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 37 bytes This solution is suggested by @Expired Data, it is shorter, elegant but it will have problems when working with large number. ``` n=>new Set([1,2,3,4].map(v=>n**v%10)) ``` [Try it online!](https://tio.run/##Zc29DoIwGIXh3avoYlIIQr/@0Q54E47GgWAxGGyJELz8SvJt7XqenLzvfu/X4Tst28WHp4tjF3139e5Hbm6jd6h4JSr5qD/9QvcDynI/AyuKOAS/htnVc3jRkRLLjpE0DWGnRAgACmRCOAqXRqcomEAUts2fUiJKnZNCUqlorVHSjzCqRWmtyFoABtFIntWAW0QL8Q8 "JavaScript (Node.js) – Try It Online") [Answer] # x86-16 machine code, IBM PC DOS, 26 bytes **Binary:** ``` 00000000: b380 8a07 d72c 308a d850 0430 b40e cd10 .....,0..P.0.... 00000010: 58f6 e3d4 0a3a c375 f0c3 X....:.u.. ``` **Unassembled:** ``` B3 80 MOV BL, 80H ; BX to command line input tail 8A 07 MOV AL, BYTE PTR[BX] ; input length into AL D7 XLAT ; AL = [BX+AL] (get the last char of input) 2C 30 SUB AL, '0' ; convert from ASCII 8A D8 MOV BL, AL ; save N to BL for compare/multiply POW_LOOP: 50 PUSH AX ; save AX 04 30 ADD AL, '0' ; convert to ASCII B4 0E MOV AH, 0EH ; BIOS tty function CD 10 INT 10H ; call BIOS, write char to console 58 POP AX ; restore AX F6 E3 MUL BL ; AX = AL * BL D4 0A AAM ; AL = AL % 10 3A C3 CMP AL, BL ; is sequence repeating? 75 F0 JNE POW_LOOP ; if not, keep looping C3 RET ; return to DOS ``` A standalone PC DOS executable program. Input via command line args. **I/O:** [![enter image description here](https://i.stack.imgur.com/3jH3H.png)](https://i.stack.imgur.com/3jH3H.png) [![enter image description here](https://i.stack.imgur.com/gmaOX.png)](https://i.stack.imgur.com/gmaOX.png) [Answer] # [PHP](https://php.net/), ~~54~~ 50 bytes ``` for($n=$o=$argn%10;print$n;$n-$o||die)$n=$n*$o%10; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFTybFXybVUSi9LzVA0NrAuKMvNKVPKsVfJ0VfJralIyUzVBKvK0VPJB0v//m5iaGf3LLyjJzM8r/q/rBgA "PHP – Try It Online") --- Alternate Solution: # [PHP](https://php.net/), ~~50~~ 45 bytes ``` for(;$i<'11442'[$argn%5];)echo$argn**++$i%10; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRoPA/Lb9Iw1ol00bd0NDExEg9WiWxKD1P1TTWWjM1OSMfzNPS0tZWyVQ1NLD@/9/Y@F9@QUlmfl7xf103AA "PHP – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~58~~ 50 bytes ``` .*(.) $1$1$*_,,486,971,6,,,931,426,1 +`_\d*, ,.* ``` [Try it online!](https://tio.run/##PcFLDkAwFAXQ@V0HSdVN41WVrsAmJEgYmBiI/dffOdu8L@sYU9UO0WhlMiRy1j3pGs9QCz3JUAqd9RTkQ99NmgCNRowFRGCtRXmCu6C6wT9Qv9B8EH4H "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 8 bytes by not including the input digit in the digit patterns. Explanation: ``` .*(.) $1$1$*_,,486,971,6,,,931,426,1 ``` Create a unary copy of the last digit and append the list of power-ending digit pattern suffixes. ``` +`_\d+, ``` Delete the appropriate number of entries from the start of the list. ``` ,.* ``` Delete unneeded entries from the end of the list. Actually calculating the digits takes 69 bytes: ``` M!`.$ {`(.).* $&;$1$*_,$&$* _(?=.*,(1*))|,1* $1 ;(1{10})*(1*) $.2 D`. ``` [Try it online!](https://tio.run/##Pcm7DoJAEEbh/n8Lk4HMTjYTZgWUEGNjYsUzsBQWNBaGDnz2Fbx95TmP2zTeh5TxNaZuF5UwR1anAspbMpLeU06Cns8nFc8mzi3e1m1o2WYrnk62CtKAS9SUCpghhID9CuUG1RvqDxy@cPxB8/cC "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` M!`.$ ``` Modulo the input by 10. ``` {` ``` Repeat while new digits can be added. ``` (.).* $&;$1$*_,$&$* ``` Create unary copies of the first digit and power-ending digits so far. ``` _(?=.*,(1*))|,1* $1 ``` Multiply them together. ``` ;(1{10})*(1*) $.2 ``` Take the remainder modulo 10 and convert it to decimal. ``` D`. ``` Deduplicate the digits. Of course it only takes 34 bytes in Retina 1: ``` L`.$ {`(.).* $&_$.(*$1* _.*\B D`. ``` [Try it online!](https://tio.run/##PcG7DkBAEAXQ/n7HkjXFxKx3KxKNT5BYhUKjEJ2PH2/nrNM2L6NoYFuvnWeD3VuOmGDCwbAlI4SBqa@BxrNqDBE455CckF6Q3ZA/ULxQflD9Dg "Retina – Try It Online") Link includes test cases. Explanation: ``` L`.$ ``` Modulo the input by 10. ``` {` ``` Repeat while new digits can be added. ``` (.).* $&_$.(*$1* ``` Multiply the power-ending pattern so far by its first digit. (`*` has higher precedence than `$^`, so multiplying by its reverse ends up costing a byte more than it saves.) ``` _.*\B ``` Modulo the result by 10. ``` D`. ``` Deduplicate the digits. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 23 bytes ``` ((*X**1..4)X%10).unique ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfQ0MrQkvLUE/PRDNC1dBAU680L7OwNPW/NVdxYqWCHlBNWn6RAlDe8j8A "Perl 6 – Try It Online") Returns the unique values of the input to the power of 1 through 4 modulo 10. [Answer] # Excel, 53 bytes ``` =CHOOSE(RIGHT(A1)+1,,1,2486,3971,46,5,6,7931,8426,91) ``` `RIGHT(A1)` defaults to `RIGHT(A1,1)`, making it more efficient than `MOD(A1,10)` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` 4╒#♂%▀ ``` port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/198811/52210), so make sure to upvote him as well! [Try it online.](https://tio.run/##y00syUjPz0n7/9/k0dRJyo9mNqk@mtbw/7@lgQGXoSGXEZexgTGXiQmXiSmXmZkZl7GFqTlQ3ILL0MgSAA) **Explanation:** ``` 4╒ # Push the list [1,2,3,4] # # Take the (implicit) input-integer to each of this power ♂% # Take modulo-10 for each of these ▀ # Uniquify the list # (after which the entire stack is output implicitly) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~56~~ 51 bytes Saved 5 bytes thanks to [S.S. Anne](https://codegolf.stackexchange.com/users/89298/s-s-anne)!!! ``` i;f(n){for(i=n%10;putchar(i+48),i=n*i%10,i-n%10;);} ``` [Try it online!](https://tio.run/##HYzBCoMwEETv@YpgKWwaLbb0UIj2S3qRtakL7So2QkDy7enqZYZ5MwxWb8ScyXlgs/pxBmr5eKndtAQcOon2djelwBMJLqnaW@NSPhDjZ@lfuvmFnsbz8FDfjhjMqvR@xEHHtnY6NldRa@PWaA/ROPFploGH4snFlpNK@Q8 "C (gcc) – Try It Online") [Answer] # x86\_64 machine code, ~~63~~ 61 bytes ``` B8 BF 84 7B 09 B9 0A 00 00 00 31 D2 C7 44 24 FC A4 10 0A 00 48 C1 E0 22 48 89 44 24 EC 48 B8 3C 00 00 00 00 00 5E 24 48 89 44 24 F4 89 F8 66 F7 F1 48 89 D0 83 E0 0F 66 03 54 44 EC C3 ``` Disassembly: ``` 00000000 B8BF847B09 mov eax,0x97b84bf 00000005 B90A000000 mov ecx,0xa 0000000A 31D2 xor edx,edx 0000000C C74424FCA4100A00 mov dword [rsp-0x4],0xa10a4 00000014 48C1E022 shl rax,byte 0x22 00000018 48894424EC mov [rsp-0x14],rax 0000001D 48B83C0000000000 mov rax,0x245e00000000003c -5E24 00000027 48894424F4 mov [rsp-0xc],rax 0000002C 89F8 mov eax,edi 0000002E 66F7F1 div cx 00000031 4889D0 mov rax,rdx 00000034 83E00F and eax,byte +0xf 00000037 66035444EC add dx,[rsp+rax*2-0x14] 0000003C C3 ret ``` Input: `edi`, Output: `dx`, requires `rsp` to be set to a correct value. Example call: ``` main: mov edi, 1337 call f movzx eax, dx ret ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 30 bytes ``` ->n{(1..4).map{|g|n**g%10}|[]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNQT89EUy83saC6Jr0mT0srXdXQoLYmOrb2v6GBXklmbmpxdU1RTYFCdJFOWnRRLFAcAA "Ruby – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 9 bytes ``` {m%^QdTS4 ``` [Try it online!](https://tio.run/##K6gsyfj/vzpXNS4wJSTY5P9/43/5BSWZ@XnF/3VTAA "Pyth – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` ⭆⁺0§⪪”←‴Ki⦃k‽” Iθ﹪⁺IθIιχ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaATklBZrKBko6Sg4lnjmpaRWaAQX5GSWaCgpKBiZmSiYmVgoGAEllRSUNHUUnBOLSzQKNTWBTN/8lNKcfIh2qDBUPhMkbWgAVGX9/7@FxX/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Uses the repetition between the first and second halves of the table. Explanation: ``` ”←‴Ki⦃k‽” Compressed string ` 264 648 2` ⪪ Split on literal space § Iθ Cyclically index by the input as a number ⁺0 Prefix a literal `0` ⭆ Map over characters and join ﹪⁺IθIιχ Add to the input and reduce modulo 10 ``` [Answer] # Jelly, 7 bytes ``` 4R*@%⁵Q ``` You can [try it online](https://tio.run/##y0rNyan8/98kSMtB9VHj1sD///8bmhgBAA). [It doesn't beat Jonathan's answer nor was it posted first. I just got to this answer by myself and I like posting Jelly answers while I'm learning] [Answer] # [C (gcc)](https://gcc.gnu.org/), 116 bytes ``` x,c,a[4];f(n){n%=10;for(c=0,x=n;c<4;x*=n)a[c++]=x%10;n=*a*10+a[1];n=a[2]*10+a[3]-n?n*100+a[2]*10+a[3]:*a-a[1]?n:*a;} ``` Can almost certainly be golfed more but I haven't figured it out yet. [Try it online!](https://tio.run/##RY7NDoIwEITvfYoGQ9IfMEU5WSoPUntoimgTXQyiaUJ4dmz14FxmZuc7rCsvzq1rKFxhdW1kT4DOkKtKyH4YiVOiCAqka2oZmAJqtePcqJBHABSzrBLc6srEYvXO/OrelNBCzKn8jwdmy8S2EJNc1o0Hd3t1Z9w8p84P2@sRIQ8TvlsP5D34jqIZ4aj0SRoCVljIaA2uknNOv3vSY4xET7K8O0FW4J4ESiVa1g8 "C (gcc) – Try It Online") [Answer] # [J](http://jsoftware.com/), 15 bytes ``` [:~.10|]^1+i.@4 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63q9AwNamLjDLUz9RxM/mtyKXClJmfkK6QpqOnZKWQCJf8DAA "J – Try It Online") # [K (Kona)](https://github.com/kevinlawler/kona), 14 bytes ``` {?(x^1+!4)!10} ``` [Try it online!](https://tio.run/##y9bNzs9L/P8/zaraXqMizlBb0URT0dCg9n@aOpD6DwA "K (Kona) – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 12 bytes ``` ri4ro?^)[~NB ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/KNOkKN8@TjO6zs/p/39DQ0MA "Burlesque – Try It Online") ``` ri # Read input to int 4ro # Range [1,4] ?^ # Raise input to powers [1,4] )[~ # Take last digit of each NB # Remove duplicates ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 12 bytes ``` UQ(a**\,4)%t ``` takes range from 1 to 4, takes powers, mod 10, uniquify. [Try it online!](https://tio.run/##K8gs@P8/NFAjUUsrRsdEU7Xk////xgbGAA "Pip – Try It Online") ]
[Question] [ You're at integer coordinates \$(x,y)\$ facing one of North, South, East, or West. Your goal is to walk home to \$(0,0)\$. At each step, you may do one of: * Walk one step in the current facing direction, that is to whichever of \$(x+1,y)\$, \$(x-1,y)\$, \$(x,y-1)\$, or \$(x,y+1)\$ you're facing. * Rotate 90 degrees left, staying in place. * Rotate 90 degrees right, staying in place. Your goal is to write code that will eventually get you home to \$(0,0)\$ if called repeatedly, each time with your current position and facing. Your code must always give the same output for a given input, which precludes using randomness or past state. **Input:** Two integers \$(x,y)\$ and a facing direction. The 4 possible facing directions are given as numbers 0 through 3, or alternatively 1 through 4, matched as you choose. The position can also be taken as a vector or point or complex number. You won't be given \$(0,0)\$ where you're already home. Don't worry about overflows caused by huge inputs. **Output:** One of three distinct consistent outputs corresponding to the possible actions of walking straight, turning left, and turning right. [Answer] # [Haskell](https://www.haskell.org/), 21 bytes ``` (!!).([(<0),(>0)]<*>) ``` [Try it online!](https://tio.run/##y0gszk7Nyflfraus4JOYl16amJ6q4BwQoKxby5VmG/NfQ1FRU08jWsPGQFNHw85AM9ZGy07zf25iZp6CrUJKPpeCQkFRZl6JgopCmkK0kY6uUayCIYagIRZBBQMcgkaogobYBA0ggv8B "Haskell – Try It Online") Outputs a boolean with `True` being move forward and `False` being turn right. # [Haskell](https://www.haskell.org/), 28 bytes Here's a version that is easy to understand / translate into any language. ``` f(x,y)d=[x<0,y<0,x>0,y>0]!!d ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02jQqdSM8U2usLGQKcSiCvsgLSdQayiYsr/3MTMPAVbhZR8LgWFgqLMvBIFFYU0BQ0jHV0jTQVDDEFDLIIKBjgEjVAFDbEJGkAE/wMA "Haskell – Try It Online") ## Explanation The idea here is two-fold * We notice that we only ever need to turn in one direction. A turn left is just 3 turns right. So we will limit ourselves to only right turns. * Now we notice that given a direction there is a simple condition that can check if we ought to move forward. Namely the sign of one of the two variables. With this information we construct out solution, by making a list of the conditions and indexing the list with the direction. `True` means the condition was passed and we can move forward (so we do), `False` means the condition was failed and we should not move forward, so we rotate. Now the specification allows us to just output these values as is, since they are distinct and we have no intention of turning left. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` qi<L0E2 ``` [Try it online!](https://tio.run/##K6gsyfj/vzDTxsfA1ej//2gDHQWDWC5DAA "Pyth – Try It Online") Input is in the form: ``` 3 [3, 4] ``` The solution is simple: * `<L0E` maps each coordinate to `0` if the coordinate is positive, and `1` if the coordinate is nonpositive. * `i ... 2` converts the list to a number by interpreting it as binary. * `q` checks whether the resulting number is equal to the other input. * `True` means forward, `False` means turn, the direction is irrelevant, the third output is irrelevant. We use the following mapping: * `0`: up - the positive y direction. * `1`: right - the positive x direction. * `2`: left - the negative x direction. * `3`: down - the negative y direction. The path the walk takes is a sort of a staircase - from the `(-, -)` quadrant to `(-, 1)` to `(1, 1)` to `(0, 1)` to `(0, 0)` for instance. [Answer] # [Python 2](https://docs.python.org/2/), 30 bytes ``` lambda i,d:abs(i+1j**d)<abs(i) ``` [Try it online!](https://tio.run/##VYw9DoMgGIZnOQUdmoB8TaR1MuUEHsE6aICIoDXVpHJ6CjYdurzJ8/4tfhue8zVo8Qium3rZYQOy6vqVGMbHPJf0fgANUmlckx08WFqh7D0YpzDZmc/5SE@iGKOZLS8zb/goRTIaa/KrpFlKxM4aDgVcorSNbcGzpoCvkzjulFtVha0glnF6LtHfLarJDUrgNHwA "Python 2 – Try It Online") Takes as input a Gaussian integer for position, and an integer in `{0,1,2,3}` for the direction; outputs `True` for forward, `False` for rotate counter-clockwise, and whatever you like for rotate clockwise, because that never happens :). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` >-Ḅ⁼ ``` [Try it online!](https://tio.run/##AXIAjf9qZWxsef//Pi3huITigbz/MTF4MljigqxfNSAsNFjigJnCpCxA4oCY4buLw5guLFU7VU4kJMKkK8qLwqVAL@KAmCU0xooywqbDpy8/4bq44oKs4biiJMOQwr/CteG5vjvigJwgLT4g4oCdO8OnLylZ//8 "Jelly – Try It Online") A dyadic link taking the co-ordinates as the left argument and the direction faced as the right. Returns `0` for turn and `1` for move forwards. The TIO footer picks a random starting point and demonstrates that the link will ultimately reach `[0,0]` Based on [@isaacg’s Pyth answer](https://codegolf.stackexchange.com/a/198752/42248) so be sure to upvote that one too! ## Explanation ``` >- | Greater than -1 Ḅ | Convert from binary time decimal integer ⁼ | Equal to right argument ``` [Answer] # [J](http://jsoftware.com/), ~~12~~ 11 bytes ``` [>&|[+0j1^] ``` [Try it online!](https://tio.run/##PY5BS8NAEIXv8yueObgNXZct9bQQD614Eg9ei4U0meCmdRe2jabgf48TEz0MzMz7eO@1Q2ZUg8JBQcPCydwZbF@fn4bdw@33bmnb1f5tyIleNgafnA5oYsIlInUBsUv4KH1AzZU/@xgm4lBWxxGx2pJggZME3MNZIq7eIxaZ63OtNJTO3JXINwZ9YVFHQ8Avoh5j4BslZ@JLl4IhDrUh@ipPx0JoNLhS7ZPs0hB7zDajPvsseiwhSI6pgyB8OvMo9f8vQVaTdT6XW7frP9UOPw "J – Try It Online") ## idea Our idea is simple: Walk straight, and see if that gets us closer in Euclidean distance. If yes, return "walk straight". If not, return "turn left". ## input / output Take position as a complex number (left arg) and direction as a 0-indexed int (right arg). Similar to @PostRockGarfHunter's answer, we constrain our output to two values: 1. `1` - Walk straight 2. `0` - Turn left ## how 1. `[+0j1^]` First we convert our right arg integer to a complex number by raising *i* `0j1` to the right arg `0j1^]`. Then we add that `+` to the left arg `[`. This represents our "next position", if we were to walk straight. 2. `[>&|` Is the left arg `[` (current position) greater than `>` the next position after converting both to Euclidean distance from origin `&|`? [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~10~~ 9 bytes ``` ⊣⊃0(>,<)⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/H3UtftTVbKBhp2Oj@ahr0f80oOij3j6g2KH1xo/aJgJVFhclA8mSjMzi/@lA2epHvVsfdS40UDCwMnjU3VIE1rArDSTa3WKorWFSA@Tq1hVpPupoBwpqFx2eDhQAGqhhqGCgqWGgYKipcWg9lA1kaNZyaTzq3WwCVD9DL10hTxfIMXrUu8VQ2@jw9Dyg6cYA "APL (Dyalog Classic) – Try It Online") all credit to [Post Rock Garf Hunter's answer](https://codegolf.stackexchange.com/a/198738/24908) the tio link shows numbers of steps for the square area around (0,0) for the 4 initial directions `⊣` left arg: direction `⊢` right arg: coord pair `,` concatenation `0(>,<)⊢` is equivalent to `(0>⊢),(0<⊢)`, i.e. the 4-vector `(0>x),(0>y),(0<x),(0<y)` `⊣⊃`.. indexing with the left arg [Answer] # [JavaScript (Node.js)](https://nodejs.org), 26 25 24 bytes ``` (x,y,d)=>--d%2*x<--d%2*y ``` [Try it online!](https://tio.run/##XY9BboMwEEXX4RRfSJWgmCakXZWQbQ@BskDYBCoXRxi1WA1npx5MSVovZsb@b/6M34vPQpddc@njVnExVdkUDMwwHmbHOOYP@8fh4LKZKtUhkKKHHpAhTnYpVQckCRVRFOLbgz03zqyc@eXMjfvLcssSyS35QtmBG6IIoJl6YCBPbRiI1zx1wKXoa3sfEMFnvo0GkSs4Pb36C/dVN1IgGHC9wqz2m6ZCUAVkbn3D@X0WrF@GPE4YdgwUTzk/pYtoZnERmP3nvTgvZHX/SKM3I4TUYvWl3XPbtmd4/ue6Nnau0W24pO22VK1WUjxJdQ4IDS00eg4ZvXvVf1M9avUh0LQopEQvdI@y0EL7YTr9AA "JavaScript (Node.js) – Try It Online") `d` is direction one of `[0, 1, 2, 3]` for [west, north, east, south] The expression `(d - 1) % 2` gives `deltaX` one of `[-1, 0, 1, 0]`and `(d - 2) % 2` gives `deltaY` one of `[0, -1, 0, 1]` Either `x * deltaX` or `y * deltaY` will be non zero and will be negative if we are heading towards home. So if `(deltaX * x + deltaY * y < 0)` also expressed as `(deltaX * x < deltaY * -y)` we go forward = `true`, else we turn left = `false`. To get to 24 I swapped north and south to change '-y' to 'y' [Answer] # JavaScript (ES6), ~~28~~ 27 bytes Takes input as `(x,y,d)` with \$d=0\$ for *North*, \$1\$ for *South*, \$2\$ for *West*, \$3\$ for *East*. Output: * *true* : turn right * *false* : walk straight ``` (x,y,d)=>(x&&2|x<0||y<0)!=d ``` [Try it online!](https://tio.run/##XZBBbsMgFET3PsV0E4GKI@yomxKSg1heoIDbRFaIbDcClZzdBTu1FC9AGubN/yMu6q76U3e@DfnVajM2ciSOeaapPBC32ZTB7XkIfs/pm9TjYPoBEhGBZ9AU8oDfDGhsR1Q0qlrAIQR4QScDUNvbT/9NqmeEoYtcs0yoqcgm7tyQ7j8D6DRsx1AycIairnQtJusx3abtzcI6vMsUkChxRF7gc1a7qJLg4gn6BeQvYPEKphXprJqnpsDJXnvbmm1rv4iKL48sS59C8MGAWJjTWecrnfx85c96/AM "JavaScript (Node.js) – Try It Online") ### How? This is parsed as: ``` +--------------------> 0 if x = 0, 3 if x < 0, 2 if x > 0 | +---> 1 if the first expression is 0 and y < 0, 0 otherwise ________|_______ _|_ / \ / \ ((x && (2 | (x < 0))) || (y < 0)) != d ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~38~~ 35 bytes ``` . (-?).*( -?).* $*-$2$1$1 ^(-*) \1$ ``` [Try it online!](https://tio.run/##TccxCoAwDEDRPafIEKEtpDSpzo5eQkQHBxcH8f4VEhSX//jXfh/n1rowrS1j4DHmFNAASkxKQgJL4BRxFmpNcMAK1arW8lWtYi1WFpCX3qmOOuIUh23r3wJqPA "Retina 0.8.2 – Try It Online") Link includes demonstration of path taken from `5 3` to the origin. Takes input as direction first, then coordinates. Edit: Saved 3 bytes by porting @isaacg’s Pyth answer. Direction encodes as `y--`, `x--`, `x++`, `y++`. Outputs `1` to move, `0` to turn. Explanation: ``` . (-?).*( -?).* ``` Capture the signs of the coordinates. ``` $*-$2$1$1 ``` Convert the direction to unary, and convert the coordinate signs from base 2, discarding everything else. ``` ^(-*) \1$ ``` Compare the direction to the base 2 decoded signs. [Answer] # [C (gcc)](https://gcc.gnu.org/), 47 bytes ``` z;m(x,d)int*x;{x=abs(z=x[d/2])>abs(z+d%2*2-1);} ``` Returns `0` to move forward and `1` to turn clockwise. It never moves counterclockwise but let's just call that `2`. North is `3`, south is `2`, east is `1`, and west is `0`. *-2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!* [Try it online!](https://tio.run/##dVJNT4NAEL3zKyaYJkDBFjx4QJp4aOLJJrbGA3Kou9Ru5MMAtVjKb8edZYFKdC/73uzMezOTJdY7IU1zcmOtNKnOksIo3ar0tm@5dvJKn86cQF8INqUTx3AsW3fr5oolJDrQEO7ygrL0er9QlDA5xEBZFpKCpYlSKcDP4@pp8wAe3JiCrlfPgjotXd6vN5zZLXtZCjY3ldodywGJUvJxZHnoB@BJcR/rOW1lWxFfYAyinIwhxJDoRsYExiCKtJZkv83A4J55kV3a9KmqQOrYSRWoC3dNqQjUUQcqArW148uGeMsS7StlVJdmGCRpmtHcd7Cgsuy5Cbc8H19HS@Gom57rYcJxz6JQkwLzAM7nTs0OdJHR2uD5zLjZTlNLrjGhJnzLm@Kdvyay94vT65qDqglyYfwKdLcvYTstlo2IFF3vn6pfujgx45Y4zKz7GZfnJB8n4IABjqv80RLDXQ14yosssIfUukdhlIf/dNKuc/hpONFYolbq5gc "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` d2βQ ``` Port of [*@NickKennedy*'s Jelly answer](https://codegolf.stackexchange.com/a/198766/52210), so make sure to upvote him as well! First input is the coordinate, second input is the current direction digit (in the range `[0,3]`). Outputs `0` to turn, and `1` to move forward. [Try it online](https://tio.run/##yy9OTMpM/f8/xejcpsD//6N1jXWMYrkMAQ) or [verify a random coordinate will eventually result in `[0,0]`](https://tio.run/##yy9OTMpM/R/ionF0h8u5lcXnVj5qmBVqfHjuuZVh0REu9vEBykoKiXkpCkr2kfZKCo/aJoFYEf9TjM5tCvxvmxkRGZ9pYBisfXh1ZGYImLIB0rqHVwMFdWtra0OBInYmqmG1/wE) or [verify all coordinates in the range `[[-1,1],[1,1]]` with all possible directions `[0,3]`](https://tio.run/##yy9OTMpM/W98eK6hi8bRHYcXn9vyqGHWo6Y1CWWVCfZKCol5KQpK9kDGo7ZJQEZlwv8Uo3ObAv/r/AcA). **Explanation:** ``` d # Check for both values in the (implicit) input-coordinate whether it's non-negative (>=0) 2β # Convert this from a binary-list to an integer Q # And check whether it's equal to the (implicit) direction input-integer # (after which this is output implicitly) ``` [Answer] # [Pure Data](https://puredata.info), 65 bytes ``` #X obj 0 0 expr (8*($i1<0)+4*($i2<0)+2*($i1>0)+($i2>0)&1<<$i3)<1; ``` This line can be added to a pure data patch to make an object positioned at `0 0` which takes 3 inputs and produces one output. The first two are the x and y and the last is the direction (range 0 to 3). Here is an example of how it can be called: [![enter image description here](https://i.stack.imgur.com/7PRY2.png)](https://i.stack.imgur.com/7PRY2.png) This ports [my haskell answer](https://codegolf.stackexchange.com/a/198738/56656) in logic, however since arrays are a nightmare in pure-data we use arithmetic and bitwise operations instead. We pack the 4 booleans (ints in pd) into a four bit integer and use `&` to index them. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~13~~ 9 bytes ``` ⁼↨E²›⁰N²N ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO1sDQxp1jDKbE4VcM3sUDDSEfBvSg1sSS1SMNAR8Ezr6C0xK80NwnI1dTU1FEw0sQQtP7/X9dUwVjB6L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 4 bytes by porting @isaacg’s Pyth answer. Uses the same "move or turn" approach; `-` means move, no output means turn. The directions encode as `y--`, `x--`, `x++`, `y++`. Explanation: ``` ² Literal 2 E Map over implicit range ⁰ Literal 0 › Is greater than N Input coordinate ↨ ² Convert from base 2 ⁼ Equals N Input direction ``` ]
[Question] [ Your mission is to build an algorithm (program or function) that can optimize packing fruit from a conveyor belt into bags to be sent off to retailers, optimizing for a largest number of bags. Each bag has to weight at least a certain amount, but any excess is lost profit since that weight could be used to fill another bag. Your bagging machine has always a lookahead of `n` fruits from the queue and may only choose to add any of these `n` fruits to the (single) bag that is being processed. It cannot look beyond the `n` first elements in the queue. The program always knows exactly how much weight there already is in the bag. Another way to visualize this is having a conveyor belt with a loading area of size `n` at the end, from where a fruit has to be taken before a new fruit arrives. Any leftover fruit and a non-full bag at the end are discarded. [![Figure 1: Fruit bagging factory](https://i.stack.imgur.com/ToCHh.png)](https://i.stack.imgur.com/ToCHh.png) ## Inputs * List/array of weights of fruits in queue (positive integers) * Minimum total weight for bags (positive integer) * Lookahead `n` (positive integer) ## Output Your algorithm should return for all bags the weights of the fruits in them, by whatever means is convenient for you and your language, be that stdin or a return value or something else. You should be able to run the program and calculate your score in one minute on your computer. ## Example ``` Total weight 1000, lookahead of 3 and fruit queue: [171,163,172,196,156,175,162,176,155,182,189,142,161,160,152,162,174,172,191,185] One possible output (indented to show how the lookahead affects the bagging): [171,163,172, 156,175, 176] [162, 155,182,189, 161,160] [152,162,174,172,191,185] ``` ## Scoring Your algorithm will be tested on six runs on a [batch of 10000 oranges](https://gist.github.com/angs/0a17ff0ef08136770c7e7cedeaf4a4d9) I have prepared for you, on lookaheads ranging from 2 to 7, inclusive on both ends. You shall pack them into bags weighing at least 1000 units. The oranges are normally distributed with a mean weight of 170 and a standard deviation of 13, if that is of any help. Your score will be the sum of number of bags from the six runs. The highest score wins. Standard loopholes are disallowed. [Simple example implementation and test suite boilerplate in Haskell](https://tio.run/##jX1rjx1HcuV3/oprYgyQXlGoyszIjBRWAowx1hAwCxm2F/tBEuyW1BQJUd3a7uZqxvB/H9@qihPnVM8MxgNoSN5H3ap8xOPEiZPvbh5/uv3w4Y/vf/7l/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E5h1xim6ol36YkU3B72psEXZD9Sfnamp@90khlDO@kp@EviTXcdusv8uY5dJjmNqJUUOP8EpkvN7rbGOnHNZeBb8VF515/PAn7qeS2VyHo2fz1fJ86nnOU5G3RP6TujFzz64LrrEsoZOtrpLP7jqShVip6ldJj2xLpxM13O1hpyvvkrPofZbFvKztX85xyL2T1MMcyHfdK7EXV24WtkX0zlnwH6B0ZmRbzectd2u58c28tRSuzVyqDnPOeFo7BlXXEZ1J8E/aIV1nC0/a8B8tH92slYFnDc1kkRzBedpZkyJM0Mq66PgR0zpZUPdDP28OEs5db5d9NP1vC7wfXBORGf/QJ4nKfwP8CWVL9D7eX8m72xlPD40Nw3fYeWswTZcMLHDx@zn@rny5io1epKPJes44209a6mT46J6P9jfqVm4kLOMOSv1fGY1zlDr0guCM7tVO3Kuwp2b1FQz6cc3je0L63h6rq3Ws5DLwDbbkLMThF@IWG6GnanG@MLkLIxWpT6p/cty1jt6txBnIT8H5jgEY07@vNgQ8MaAsQ3h5tYm8ehCXhYwAeusGYNHaPOsCdulVw/3O57pAWGep/RJI49JPhJqesCm5n8B) [Answer] # [Python 3](https://docs.python.org/3/), 9796 bags Building on Jonathan's answer: ``` import itertools as it def powerset(iterable): s = list(iterable) return it.chain.from_iterable(it.combinations(s, r) for r in range(len(s)+1)) def f(a,m,l): r=[];b=[] while a: c = min(list(powerset(a[:l])),key=lambda w: abs(sum(b)+sum(w)-m)) if sum(c)==0: c = a[:l] b+=[a.pop(a.index(min(c,key=lambda w: abs(sum(b)+w-m))))] if sum(b)>=m:r+=[b];b=[] return r ``` This relies on powerset from itertool's cookbook. First finds optimal subset of the buffer based on minimizing difference from target weight for all subsets, and then picks an element out of this subset based on same criterion. If no optimal subset selects from the whole buffer. [Answer] ## Python 3, ~~9964~~ 9981 bags The idea of this solution is similar to those of Jonathan, JayCe and fortraan, but with a scoring function =) This solution appends the best subsets of the lookahead area accoring to the `score`. `score` provides an order over the subsets using the following scheme: * A subset completing a bag is better than one that's not * One subset completing a bag is better than another if it has less excess weight * One subset not completing a bag is better than another if its mean is closer to what's expected to be in a bag `expected_mean` tries to predict what the rest of the values should look like (assuming their choice is optimal). **UPD**: Here is another observation: you can place any oranges from the best subset into the bag without hurting the algorithm's performance. Moving any part of it still allows to move the rest afterwards, and the remainder should still be the best option (without new oranges) if the scoring is right. Moreover, this way there is a chance to dynamically improve the set of candidates to put into the bag by seeing more oranges before filling the bag. And you want to know as much information as possible, so there is no point in moving more than one orange to the bag at any given time. ``` import itertools as it import math from functools import partial from collections import Counter mean, std = 170, 13 def powerset(list_, max_items): return it.chain.from_iterable(it.combinations(list_, r) for r in range(1, max_items + 1)) def expected_mean(w): spread = std * 1 return max(mean - spread, min(mean + spread, w / max(1, round(w / mean)))) def score(weight_needed, candidate): c_sum = sum(candidate) c_mean = c_sum / len(candidate) if c_sum >= weight_needed: return int(-2e9) + c_sum - weight_needed return abs(expected_mean(weight_needed) - c_mean) def f(oranges, min_bag_weight, lookahead): check = Counter(oranges) oranges = oranges.copy() result = [] bag = [] while oranges: weight_needed = min_bag_weight - sum(bag) lookahead_area = oranges[:lookahead] tail = oranges[lookahead:] to_add = min(powerset(lookahead_area, lookahead), key=partial(score, weight_needed)) to_add = min(powerset(to_add, 1), key=partial(score, weight_needed)) bag.extend(to_add) for x in to_add: lookahead_area.remove(x) oranges = lookahead_area + tail if sum(bag) >= min_bag_weight: result.append(bag) bag = [] assert check == Counter(oranges) + Counter(bag) + sum(map(Counter, result), Counter()) return result if __name__ == '__main__': with open('oranges') as file: oranges = list(map(int, file)) res = [f(oranges, 1000, l) for l in range(2, 7+1)] print(sum(map(len, res))) ``` [Try it!](https://tio.run/##pX3bjh3JkeQ7v6KAfRhy1erJjAiPcBegfdnPEASC6q5WE@INJHtb@nrtyUw3N8uaAfZhCRBk1blkZlz8Ym5u8eVf33/9/Kn/@9/vP375/PX70/vvz1@/f/784dvTu2@PH17lrz@@@/7rq1@@fv749Mtvn3663pAvfXn39fv7dx@uV3/6/OHD80/f33/@VK//78@/fXp86atXrz4@v/v0w9O37z8//flpX9sPT3t//Pbn51@evnz@/fnrt@fvrz@8//b97Q@Py/3z7eNOPn5786dXT48/X5@///b10@N@fvzp13fvP/14XOt4w9d3f/vw/Pr49eePf3v/6d15YXzJ1zdPv3z@@vT16f2np6/vPv39@fUu3/z0h6f9zZu8/vM/vzzu@vnnt8ctvv49r/rty9fnd8fNHrf8P592vZXH97w@3vz0x3zb46vff7p@9Yf61e9P/3m@83Hhr49h@Pn1@YvHe968qWt/@@nz1@fXvz@///uv399@en7@@fnxwZ/effr5/c/vvj/nrfz09ttvH487@e3ja76WL50X/XO@5z@fPjx/evme97/kq//rz0@3K13frkP86fvrP7bnePN4iusjf7x/Qgfh3d@@vX4xdPrWN4/PXneHZ/3l9edzJr6do/X2b@/@/vb6xA9PHz5//se7Xx@jhif@9fmnfzyeKpcPPvj4puPV/Onxev7vsQK@/Ov1m7y7b799@P547S9/PX9@XOb64fzp91/ff3jGx/j8tzt/vP1@f8c0P4b@8Yu8geNP3fLbd4/p5r385U/1yl/rzd/fvf8gb6l3/Omv/MLvn9@@@zkv/pp74nYZHakf6pO3P/94/tefc1e@PlfXD/ene/Pm/3HF67eP/fn/cYX64GPMfnz@5/fnx@q/vpdXP7bnP4/teb3wp9vF7o/949fnj5//z/Prf/LTXAMvJuIP52DzDh6rH5N3bID7zN4vei2dH999@XLc7znd@vJ9Jf2Ph4389jCXWKv/dbE@bgW/Oq/@h/NGPr778jp//UNe8c0P9UaMXe6x6/XH/nk8xdu3n959fH779rjUf7x9@/FhCt@@/Y8/vdgRfzn28PtPX377/viuc4zfigncHn/e/BX75Hi7bMrj1ccCuz71gZ9qPzytP@z5sS9fjwvgQR7W5nyIw6D9@9/73F61bXu123z83V/tc7za/fi3XT8ve/z8eH09/vrjd@vx@ozH38fv57o@d7xu/fHz4288/vrjtfV4bT3@3/16fe7XZ9bxvfmzPV7r/Xrv8Px9fu/xvuM@7HGtvq77Wce1xvX95@ePezo@n/e78J7jnh/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N7Zznh8aW6avsPaXYNtuWBil485z/Vz5c11avQUH0vWccXbetbSJMdF9X6wv0uzcCNnGXPW@v3MapyhNqUXBGd2q3Zk7MKdC2qqmfTjm8b2jXU8PddW61nIZWCbbcnZCcIvRCwXaWe6Mb4wOQtjdKlPav@ynPWO3i3EWcjPgTkuwZiLPy82BLwxYGxLuLl9SDy6kZcFTMAma8bgEVrcNWGn9OrhftcLPSDMc0ifNPKY4iOhpgdsKl79Xw) [Answer] # C++17, 9961.58 (average over some random seeds) (scroll down for explanation if you don't know C++) ``` #include<iostream> #include<vector> #include<random> std::mt19937 engine(279); // random engine // random distribution of the oranges std::normal_distribution dist (170.,13.); int constexpr N_NEW_ORANGES=7; /** Input format: Current remaining weight of the bag (remain) and the weight of the oranges (weights) Output: the index of the orange to be pick. */ struct pick_orange{ std::vector<int>weights,sum_postfix;int remain; /// returns {min excess, mask}, (index) is the LSB std::pair<int,int> backtrack(int index, int remain) { if(sum_postfix[index]<remain)return {1e9,0}; int min_excess=1e9, good_mask=0; for(int next=index;next<N_NEW_ORANGES;++next){ if(weights[next]==remain){ return {0, 1<<(next-index)}; }else if(weights[next]>remain){ if(weights[next]-remain<min_excess){ min_excess=weights[next]-remain; good_mask=1<<(next-index); } }else{ auto[excess,mask]=backtrack(next+1,remain-weights[next]); if(excess<min_excess){ min_excess=excess; good_mask=(mask<<1|1)<<(next-index); } } } return {min_excess,good_mask}; } int ans; pick_orange(std::vector<int> weights_,int remain_) :weights(std::move(weights_)),remain(remain_){ int old_size=weights.size(); std::vector<int> count (N_NEW_ORANGES, 0); weights.resize(N_NEW_ORANGES, 0); sum_postfix.resize(N_NEW_ORANGES+1); sum_postfix.back()=0; for(int _=0; _<500; ++_){ for(int i=old_size;i<N_NEW_ORANGES;++i) weights[i] = dist(engine); // prepare sum postfix for(int i=N_NEW_ORANGES;i-->0;) sum_postfix[i]=weights[i]+sum_postfix[i+1]; // auto[excess,mask]=backtrack(0,remain); int mask = backtrack(0,remain).second; for(int i=0; mask // i < N_NEW_ORANGES ; mask>>=1, ++i){ // if(mask&1)std::cout<<'('; // std::cout<<weights[i]; // if(mask&1)std::cout<<')'; // std::cout<<' '; count[i]+=mask&1; } // std::cout<<"| "<<remain<<" | "<<excess<<'\n'; } std::vector<double> count_balanced(old_size, -1); for(int i=0;i<old_size;++i){ if(count_balanced[i]>-1)continue; int sum=0,amount=0; for(int j=i;j<old_size;++j) if(weights[j]==weights[i]){sum+=count[j];++amount;} double avg=sum;avg/=amount; for(int j=i;j<old_size;++j) if(weights[j]==weights[i])count_balanced[j]=avg; } ans=old_size-1; for(int i=ans;i-->0;) if(count_balanced[i]>count_balanced[ans])ans=i; // Fun fact: originally I wrote `<` for `>` here and wonder // why the number of bags is even less than that of the // randomized algorithm } operator int()const{return ans;} }; #include<iostream> #include<fstream> #include<algorithm> int main(){ // read input from the file "data" std::ifstream data ("data"); std::vector<int> weights; int weight;while(data>>weight)weights.push_back(weight); int constexpr BAG_SIZE=1000; int total_n_bag=0; for(int lookahead=2;lookahead<=7;++lookahead){ auto weights1=weights; std::reverse(weights1.begin(),weights1.end()); int remain=BAG_SIZE,n_bag=0; std::vector<int> w; for(int _=lookahead;_--;){ w.push_back(weights1.back()); weights1.pop_back(); } while(!weights1.empty()){ int index=pick_orange(w,remain); remain-=w[index]; if(remain<=0){ ++n_bag;remain=BAG_SIZE; if(n_bag%100==0) std::cout<<n_bag<<" bags so far..."<<std::endl; } w[index]=weights1.back();weights1.pop_back(); } while(!w.empty()){ int index=pick_orange(w,remain); remain-=w[index]; if(remain<=0){++n_bag;remain=BAG_SIZE;} w.erase(w.begin()+index); } std::cout<<"lookahead = "<<lookahead<<", " "n_bag = "<<n_bag<<'\n'; total_n_bag += n_bag; } std::cout<<"total_n_bag = "<<total_n_bag<<'\n'; } ``` > > // Fun fact: originally I wrote `<` for `>` here and wonder > > // why the number of bags is even less than that of the > > // randomized algorithm > > > (if `<` is used basically the algorithm tries to *minimize* the number of bags) Inspired by [this answer](https://stackoverflow.com/a/23853848). TIO link for 250 repetitions: [Try it online!](https://tio.run/##tX1rbx1Xlt13/oobB4nJ1sNV531MUcBM0Bk0EPQA6Q8B0jHUtETL7JZIgaRsdzz@6@lUndprr1WX9HRmgBiQJfLWrcepc/Zj7bXXefvp04v3b9/@7W//8frm7YfP765e/XD19uH27vWJ/@Lu8ubd7cfXJyf3D@@@/vrjw9x7rIerm/fXN1enofaz88NXXx22o@zXJ/zFu@v7h7vrbz8/XN/eHG6/Ozx8f3W4XT57f3W/nfDm9u7j5Yc3u@PWHw6nc51ePp/jy7Pzk5Prm4fD29ub@4ernz7dHX7/5ve//R9v/vm//8Pv/@m3f7ioy@df/eY3h9/dfPr8cPhuPd/D14f/8vnu7mr51t3Vx8vrm@ub94cfr67ff/@Am/j28v3hdPvw7LDc6@Fk/e3@GLvRw@n26/uzk3/@/LBc5Ovx6fXNu6uf9oceHm4P314dPl2//cvLk998tTzh3ee3D@PnN9sRP58clv/Gk28j/Wp5tNd2/uf3nz@@@XR7//Dd9U/n137zy/OtX/pqHdWrh893N/eHnz9e3xyufnp7dX///PDx8v4vvzw/nI4bOjtc3487@m9/@Ede69Pl9bjS8/Vqy7O//cvD3fK/0/Ui42vPD7ze2WG7y/W/6@9O5ab@OI795pUdt93N4ef5qj@ffjnnl5ZTLTf4ZrvBi/Xjw/vb23dv1ju9mHjg8rLGLdxc/fRwMc59vv7z1e4Fnz97tv7yjDdlN2aj9sf1028uLuym9oet/@E2p@eH@dWr0/XwF9tYyT2v//1y9eH@6tGZX//qiY@PfLEd@YrP/sSX1v9kcJ46wfmTX@IIHj3F48N/efxYj2/k8vPD7R9tDq2n/eaC82I9@7P5@XY7L3b3@MTllnHYzvNvevLtr7/3rKfr/1@9mv9lPvs3PvXJ439hJvAunvuVbC78cthW2zotL2/ube3JCj49XrxmNO7fPOcSenPm1/zaPt6@9/H2hytMmjdnZzbCp/jWzye7RXT74d2b@@v/fYVZ8nL94fTsnEc9upm3t5@XL57uVtDzwyTDhXPdXY2zPX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HQnVUZ9YMmtYotZ5RiKs32YO5iy6u4xOyn5DvLdZEKxnaT3nPOXU9PbFnnnsc7RmcZQ9u912qnVroW3SfQK8zdtEVLdIXK7o56E2FLfJ@oHK0p6au9ywxhHLWZ/KTwJ8sOnad/Xceu3RyHF0ryXL4Dk6R7N@bE@vI/i4D94LvyqsufB7406b7UmXZj6bt91fx/an7Pk5G3RP6TujF9z64IrrEMod2trpIP7jqSgVip65dJj2xTTiZTffVqrK/@iw9h9pvGcjP1v5lHwtbP0kxzIl80z4Td23C1fK@mMJ3BuwXGF3O5NvVxtpu0f1jE3lqrt1qOVTv@5ywJvaMKy6jupPgH6TAOs6anyVgPto/21mrAs7rGkmiuYL9ND2mxJ4hkfVR8CO69LKhboZ@Xuyl7DrfTfTTdb8u8H2wT0Rh/4DvJyn8D/AllS9Qyn59Ou9sZjxeNTc135HDXoOtNsHENh8z9vVrypuL1OhxPpbMY4@3da@lQo6L6v1gfbtm4UTOMt5ZiPs9q7GHWpFeEOzZrdqRfRbuXKemWpZ@/KyxfWAdT/e11XoWchnY5lxl7wThFyKW62ZnYmZ8kWUvjBSlPqn9y7LXO3q3EGchPwfmWAVjdv682BDwxoCxVeHmxiTx6EReFjCBXFgzBo8w970mbJFePdxvPdIDwnvu0ieNPMb5SKjpAZvqJ//n7XcfLt/f/@3F/cO7i7fPns31/wI) --- Defines a function (actually it just looks like a function, it's a struct) `pick_orange` that, given a `vector<int> weights` the weight of the oranges and `int remain` the remaining weight of the bag, returns the index of the orange that should be picked. Algorithm: repeat `500` times `{` generates *random* (fake) oranges (normal distribution with mean 170 and stddev 13) until there are `N_NEW_ORANGES=7` oranges pick any subset whose sum is smallest and not smaller than `remain` (the function `backtrack` does that) mark all oranges in that subset as *good* `}` average out the number of times an oranges being marked as *good* of the (real) oranges with equal weight return the best orange --- There are 3 hardcoded constants in the program that cannot be inferred from the problem: * The random seed (this is not important) * `N_NEW_ORANGES` (the prediction length). Increasing this makes the program runs exponentially longer (because backtrack) * number of repetitions. Increasing this makes the program runs linearly longer. [Answer] # [Python 2](https://docs.python.org/2/), 9756 bags Let's get the orange rolling... ``` def f(a,m,l): r=[];b=[] while a: b+=[a.pop(a.index(min(a[:l],key=lambda w:abs(sum(b)+w-m))))] if sum(b)>=m:r+=[b];b=[] return r ``` **[Try it online!](https://tio.run/##bV3Lsh3HcVybX3F3AEMwY6a7q7uKDnrhtSP8AbQWl0GQQgivACDL@nr6zExlZc6VFQERuPc8Znq665GVlfX5H9/@8ulj@@PTl@ePv7/9@vTT04fnz6/fffz25unVq1f73L5r2/bdbvPxZ/9un@O73Y//tuvfyx7/fvx@Pf7442fr8fsZjz@Pn891ve/4vfXHvx9/4vHHH79bj9@tx9@7X7@f@/WedXxu/tsev@v9eu3w/Hl@7vG64zrs8V19Xdezju8a1@ef7z@u6Xh/Xu/Ca45rfnzeiuu/uBez6/3H9x1/P@7V8ppW/v147XmdM6@pXd9xroHz58f3R@NnHNd53P@Y11qdr92un3mu4blWK98z8prjWies88jrOb7juK8RueZ5vb1d63Nc03mt7XoeuMbjdcdzslzX8xryv8dnz@Oe1uOZT37/8f7IdfFc62Odeq7/@R7Ltcb15/Mb2/X7Yz2wjp5/P69lv@7juMfRHt97PCtZi@PnhmvI53jen19rsrB3tnyOnuu18pmMfKb4b7v24PHneJ3nc18b12JOrvt57ev6/oU/@brj2R/P71zLed2/5fM41tjn9fPz@ci5CM@z0vI@2rWHj9djb1t@T8/rOfbIaOezub738Xlx/Gzl52/X746/j3xGgeed339e@7z23rmG@/W780yOvN5jb/Xr9@dn77keOD8468b1PX5/rMP5jJeswZI9iGte@Yws97Rde93zuo49eNzfsa@P30X@/Dyn2/W7Y/0iv/u8vnV9//nvKWfKcs3jet95XSvf2/IMxvUdx/dZXv/xM8s9e1yb5b/LJgRfd96X536y3A8h19evfXvuh7QfJmcunOf1uPbztTPXY@PvjrUck@touR7n2m/Xdx/25nh/t7S3YkePZ33ui@1uH1eez9NeWNp55/N@/Ow6k9jrnmcTezj3/fm7SR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mZJ1SzxVy0kqH9ZHfOaenpiT2r3OPFzGCTGdzlu1Q7ddK36JzAqjOG6IpO6YsV3Rz0psIWVT/QfDFTU8@7SQyhnPWd/CTwJ6euXbD/rmKXIMextJIyhw9wimR@rw3WketZNs6CD@VVT94P/KnrXCqTeTR@n69S86njHiej7gl9J/TiVx/cFF1i2UM3Wz2lH1x1pRqx09Iuk55YF06m61ytJfPVd@k51H7LRn629i/XWuT5GYphbuSbxk7c1YWrVX0xk88M2C8wOjPy7Zaztjt1fuwgT620WzOHirjnhGuwZ1xxGdWdBP9gNNZxjvxsAPPR/tlgrQo4b2kkieYK5mlWTImZIZ31UfAjQnrZUDdDPy9mKZfOt4t@us7rAt8HcyIm@wdqnqTwP8CXVL7AnPfzWbyznfH40tw0fYe1uwbbcsHELh9zzvVz5c11avQUH0v2ccXbOmtpkuOiej8436VZuJGzjGfW@n1mNWaoTekFwcxu1Y6MXbhzQU01k35809i@sY6nc221noVcBrbZlsxOEH4hYrlIO9ON8YXJLIzRpT6p/csy6x29W4izkJ8Dc1yCMRd/XmwIeGPA2JZwc/uQeHQjLwuYgE3WjMEjtLhrwk7p1cP1rhd6QHjOIX3SyGOKj4SaHrCpePXq1Q9fP79/9@31q//@@Or77//49e1vT7@9fn7z4c3773/87unLTz//@d9@efzfd09//8u792@fnh8/fPrlTz/9/PzD50@fXz//8O7jr2//9/WHdx9fP//84/s/v/nr23/89P75wy@/Pj/9/cfnX76@/vq3D69/@f5Pf//XD98//vf4oKd3vz1dP/z3nz78@OXxWb/gO768/fa3Lx@fvvzxy/Pv//nu67evTz89PX7@26cvT@8/ffrr81/ePv/69O7j0@v2pr8Zb@zNfLMel/kvePkPz58/v/346@vfXn/68vzx97dff/7xz2@e9m3b3vADvv/@u2@fvj2//4/n37/@1/@8/XL8@vE9xyV9eP78@v3bj2@e8IGP137@8u7jt6dXj598/fHp1Zun1//05u//@D8 "Python 2 – Try It Online")** Always picks the fruit from the buffer which minimises the absolute difference of the new weight and the target weight. [Answer] # Python 3, 9806 bags Building on Jonathan and JayCe's answers: ``` import itertools as it def powerset(iterable): s = list(iterable) return it.chain.from_iterable(it.combinations(s, r) for r in range(len(s)+1)) def f(a,m,l): r=[];b=[] while a: c = min(list(powerset(list(reversed(sorted(a[:l]))))),key=lambda w: abs((sum(b)+sum(w))-m)) if sum(c)==0: c = a[:l] b+=[a.pop(a.index(min(c,key=lambda w: abs((sum(b)+w)-m))))] if sum(b)>=m:r+=[b];b=[] return r ``` [Try it online!](https://tio.run/##fX3bjh1Jktyz@ivqrYsYqpEZER7h3kLvg54F6ANGA6E4zZ4hljeQ3B3t149OZrq5WdYKaoBNVp1LZsbFL@bmFl//48ffv3zu//zy7eXz395/f/rt6eOH7z@eP718ff7w@cfbp59//nmf209t237abT7@7D/tc/y0@/F3u35e9vj58fp6/PHH79bj9RmPP4/fz3V97njd@uPnx594/PHHa@vx2nr8u/v1@tyvz6zje/Nne7zW@/Xe4fn7/N7jfcd92ONafV33s45rjev7z88f93R8Pu934T3HPT@@b8X1N57F7Pr8cb3j38ezWt7Tyn8f7z3vc@Y9tesa5xg4f39cPxq/47jP4/nHvMbqfO92/c5zDM@xWvmZkfcc1zhhnEfez3GN47lG5Jjn/fZ2jc9xT@e9tms@cI/H@455shzX8x7y7@O75/FM6zHnk9c/Ph85Lp5jfYxTz/E/P2M51rj/nL@xXa8f44Fx9Pz3eS/79RzHM472uO4xVzIWx@8N95DzeD6fX2OysHa2nEfP8Vo5JyPnFH@3aw0ef473ec772jgWc3Lcz3tf1/UX/uT7jrk/5u8cy3k9v@V8HGPs8/r9OT@yL8Jzr7R8jnat4eP9WNuW1@l5P8caGe2cm@u6j@@L43crv3@7Xjv@PXKOAvOd1z/vfV5r7xzD/Xrt3JMj7/dYW/16/fzuPccD@wd73Ti@x@vHOJxzvGQMlqxB3PPKObJc03atdc/7Otbg8XzHuj5ei/z9uU@367Vj/CKvfd7fuq5//jxlT1mOeVyfO@9r5Wdb7sG4rnFcz/L@j99Zrtnj3ix/L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vHXN7/9tp3Pflzv/J7HD@/@9NufX375@uXr88svHz7//v7/PB838tf/z5f/4/zeN2/@wq9@9@Zffvv067fHV73D4@U4fvvnu5e//Y/HgxzD/fj9MVQfv3z515e/v3/5/Riy5/a2vx1v7e18ux4j9F/w9l9evn59//n35z@ev5yj@v3Pv/7l7dO@bdtbfsHj8X58@fHy8b@//O37/3yM0/Hy4zrHLX16@XpMxNsnfOHjvV@/ffj8WDSP33z/9ennpz89ff/x7fk/fcFjPf1f "Python 3 – Try It Online") ### How it works Say that the bag has 900 units in it, and there are 2 fruit available: a 99 unit fruit and a 101 unit fruit. If the 99 unit fruit is closer to the beginning of the lookahead list, then `min` will select it instead of 101. If this happens, we would now need another fruit to fulfill the remaining 1 unit needed. I changed the program to favor the higher-valued fruit in these cases. It does this by sorting and then reversing the lookahead list before powersetting. [Answer] # PHP, 9975 bags * If possible go for 5 oranges * When starting bag pick extreme value, balance later * If possible fill bag immediately * Try to keep bag weight close to estimated curve (n\*200 for 5bag, n\*167 for 6bag, etc) longest out of all submissions but should be readable ``` class Belt { private $file; private $windowSize; private $buffer = []; public function __construct($filename, $windowSize) { $this->file = new \SplFileObject($filename); $this->windowSize = $windowSize; $this->loadBuffer(); } public function reset($windowSize) { $this->file->seek(0); $this->windowSize = $windowSize; $this->buffer = []; $this->loadBuffer(); } public function peekBuffer() { return $this->buffer; } public function pick($index) { if (!array_key_exists($index, $this->buffer)) { return null; } $value = $this->buffer[$index]; unset($this->buffer[$index]); $this->buffer = \array_values($this->buffer); $this->loadBuffer(); return $value; } private function loadBuffer() { for ($c = count($this->buffer); $c < $this->windowSize; $c++) { if ($this->file->eof()) { return; } $line = $this->file->fgets(); if (false !== $line && "" !== $line) { $this->buffer[] = trim($line); } } } } class Packer { const BAG_TARGET_WEIGHT = 1000; const MEAN_WEIGHT = 170; const MEAN_COUNT = 6; //ceil(self::BAG_WEIGHT/self::MEAN_WEIGHT); const MEAN_TARGET_WEIGHT = 167; //ceil(self::BAG_WEIGHT/self::MEAN_COUNT); public static function pack(Belt $belt, Picker $picker) { $bag = ["oranges" => [], "buffers" => []]; $bags = []; while ($oranges = $belt->peekBuffer()) { $index = $picker->pick($oranges, \array_sum($bag["oranges"])); $orange = $belt->pick($index); $bag["oranges"][] = $orange; $bag["buffers"][] = $oranges; if (\array_sum($bag["oranges"]) >= self::BAG_TARGET_WEIGHT) { $bags[] = $bag; $bag = ["oranges" => [], "buffers" => []]; } } return $bags; } } class Base { public static function bestPermutation($elements, $weight = 0) { if (\array_sum($elements) < Packer::BAG_TARGET_WEIGHT - $weight) { return null; } $permute = function ($weight, $elements) use (&$permute) { if ($weight >= Packer::BAG_TARGET_WEIGHT) { return []; } $best = \PHP_INT_MAX; $bestElements = []; foreach ($elements as $key => $value) { $sum = $weight + $value; $els = [$value]; if ($sum < Packer::BAG_TARGET_WEIGHT) { $subSet = $elements; unset($subSet[$key]); $els = $permute($weight + $value, $subSet); $els[] = $value; $sum = $weight + \array_sum($els); } if ($sum >= Packer::BAG_TARGET_WEIGHT && $sum < $best) { $best = $sum; $bestElements = $els; } } return $bestElements; }; $best = $permute($weight, $elements); return $best; } public function pickLightestOutOfHeavierThan($buffer, $targetWeight) { $b = -1; $bW = PHP_INT_MAX; foreach ($buffer as $key => $value) { if ($targetWeight <= $value && $value < $bW) { $b = $key; $bW = $value; } } return $b; } public function pickClosestTo($buffer, $targetWeight) { $b = -1; $bW = PHP_INT_MAX; foreach ($buffer as $key => $value) { $diff = \abs($targetWeight - $value); if ($diff < $bW) { $b = $key; $bW = $diff; } } return $b; } public function pickFurthestFrom($buffer, $targetWeight) { $b = -1; $bW = \PHP_INT_MIN; foreach ($buffer as $key => $value) { $diff = \abs($targetWeight - $value); if ($diff > $bW) { $b = $key; $bW = $diff; } } return $b; } public function findMax($buffer) { $i = -1; $m = 0; foreach ($buffer as $k => $v) { if ($v > $m) { $m = $v; $i = $k; } } return $i; } public function findMin($buffer) { $i = -1; $m = \PHP_INT_MAX; foreach ($buffer as $k => $v) { if ($v < $m) { $m = $v; $i = $k; } } return $i; } public function minimalOrangeCount($buffer, $weight) { $elementsToAdd = ceil((Packer::BAG_TARGET_WEIGHT - $weight) / Packer::MEAN_WEIGHT); $buffer = \array_merge($buffer, \array_fill(0, \floor($elementsToAdd / 2), Packer::MEAN_WEIGHT - 7), \array_fill(0, \floor($elementsToAdd / 2), Packer::MEAN_WEIGHT + 7), \array_fill(0, $elementsToAdd - \floor($elementsToAdd / 2) * 2, Packer::MEAN_WEIGHT) ); \rsort($buffer); $orangeCount = 0; foreach ($buffer as $w) { $weight += $w; $orangeCount++; if ($weight >= Packer::BAG_TARGET_WEIGHT) { return $orangeCount; } } return $orangeCount + (Packer::BAG_TARGET_WEIGHT - $weight) / Packer::MEAN_WEIGHT; } } class Picker extends Base { public function pick($buffer, $weight) { $weightNeeded = Packer::BAG_TARGET_WEIGHT - $weight; $minimalOrangeCount = $this->minimalOrangeCount($buffer, $weight); $orangeTargetWeight = ceil($weightNeeded / $minimalOrangeCount); if (0 === $weight) { $mean = \array_sum($buffer) / count($buffer); if ($mean > $orangeTargetWeight) { return $this->findMin($buffer); } elseif ($mean < $orangeTargetWeight) { return $this->findMax($buffer); } return $this->pickFurthestFrom($buffer, $orangeTargetWeight); } $i = $this->pickLightestOutOfHeavierThan($buffer, $weightNeeded); if (-1 !== $i) { return $i; } $i = $this->pickClosestTo($buffer, $orangeTargetWeight); return -1 !== $i ? $i : 0; } } $bagCount = 0; $belt = new Belt(__DIR__ . "/oranges.txt", 0); for ($l = 2; $l <= 7; $l++) { $belt->reset($l); $bags = Packer::pack($belt, new Picker()); $bagCount += count($bags); printf("%d -> %d\n", $l, count($bags)); } echo "Total: $bagCount\n"; ``` > > 2 -> 1645 > 3 -> 1657 > 4 -> 1663 > 5 -> 1667 > 6 -> 1671 > 7 -> 1672 > Total: 9975 > > > [Try It](https://tio.run/##zX39jx3VteXv/iv6Ib@oPYCoOp/7YOCJRPmSJoAmjBgpINSY67gn7bblbkPejPjbM7eq9tpr1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3kDOYhfXEDn5DzhOJsMZNeyej9VPec0@inJ/osYo@TM4OrnMEdtkt7pzbaFj0nMPKMQ/qKNqmLlb45qE2FLop6oHZypqbKexUfQjnrM/lJ4E82nbvB@rvwXQY5jtEryWP4AU6RnN9bC/PIsZaJZ8EP5VU3vg/sqem5VFXOo7H9@SpxPvXY@8nIe6K/E2rxow6uSV9i2UM7Xd2kHlz7SiVip9G7TGpiTTiZpudqdTlffZaaQ623TORna/1yzIXLT1EMcyLfdMzEXU24WlEX07hmwH6B0dVKvl035nabnh9byFOL3q0eQ42xjwl7Yc244jLadxL8g5KYx1niswLMR@tnB3NVwHmjR5L0XMF5muFT4syQzPwo@BFDatmQN0M9L85Sjj7fJv3T9bwu8H1wTkRj/UCcJyn8D/AllS/Q2l4@g3c20x/vGpu67ahp34Otm2Bim41Zz/Uz5c1l9ugJPpbs4/C39aylRo6L9vuBfEfPwomcZaxZyvszq3GGWpNaEJzZrb0jxyzcucGealXq8av69ol5PD3XVvNZiGWgm2uXsxOEXwhfbrieyZX@RZWzMEqW/KTWL8tZ76jdgp@F@ByYYxeMOfjzokPAGwPG1oWbm4v4oxN5WcAEamPOGDzCOvY9YZvU6mG8/aQfENZ5SJ004pjgIyGnB2xq3Pt/) [Answer] # Python 3, ~~9855~~ ~~9928~~ ~~9947~~ ~~9956~~ 9964 bags Based on Jonathan Allan's starter code, but ungolfed to be readable. Idea: Since 1000/170 = 5.88, we try to select fruits close to 1000/6 (I fiddled with the magic constants). However, if the last fruit in the bag can minimize waste, we use that instead. This solution has bag sum targets for each fruit added. I'll probably stop here. I used Nelder-Mead to find my `targets` array: ``` [ 165.79534144 343.58443287 522.58081597 680.76516204 845.93431713 1063.17204861] ``` ``` def f(a, m, l, targets): bags = [] bag = [] bag_sum = 0 while a: buffer = a[:l] finishers = tuple(filter(lambda w: bag_sum + w >= m, buffer)) if finishers: next_fruits = [min(finishers)] else: ind = len(bag) next_fruits = [min(buffer, key=lambda w: abs(targets[ind]-bag_sum-w))] for next_fruit in next_fruits: bag.append(a.pop(a.index(next_fruit))) bag_sum += bag[-1] if sum(bag) >= m: bags.append(bag) bag = [] # Reset bag bag_sum = 0 return bags ``` --- **9956 bags** ``` from itertools import combinations def f(a,m,l): bags = [] bag = [] while a: buffer = a[:l] next_fruit = None single_fruit = True finishers = [w for w in buffer if sum(bag) + w >= m ] if finishers: next_fruit = min(finishers) if not next_fruit: if len(buffer) >= 4 and sum(bag) < 600: next_fruits = min(combinations(buffer, 2), key= lambda ws: abs(2*169-sum(ws))) for fruit in next_fruits: bag.append(a.pop(a.index(fruit))) single_fruit = False # Skip adding single fruit else: next_fruit = min(buffer, key=lambda w: abs(171.5-w)) if single_fruit: bag.append(a.pop(a.index(next_fruit))) if sum(bag)>=m: bags.append(bag) bag = [] return bags oranges = [int(x.strip()) for x in open("fruit.txt").readlines()] bagLists = [] for lookahead in (2,3,4,5,6,7): bagLists.append(f(oranges[:], 1000, lookahead)) totalBagsOver1000 = sum(map(len, bagLists)) print('bags: ', (totalBagsOver1000)) ``` --- The **9947 bags** program is particularly simple: ``` def f(a,m,l): bags = [] bag = [] while a: buffer = a[:l] next_fruit = None finishers = [w for w in buffer if sum(bag) + w >= m ] if finishers: next_fruit = min(finishers) if not next_fruit: next_fruit = min(buffer, key=lambda w: abs(171.5-w)) bag.append(a.pop(a.index(next_fruit))) if sum(bag)>=m: bags.append(bag) bag = [] return bags ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 9967 bags ``` def pick a, n if a.sum < n #return a.max d = n % 170 return a.min_by{|w| [(w - d).abs, (w - d - 170).abs].min } end subsets = (0..a.length).map do |i| a.combination(i).to_a end.flatten(1) subsets.select!{|s|s.sum >= n} least_overkill = subsets.min_by{|s|s.sum} #puts "best: #{least_overkill.sort}" return least_overkill.min end def run list, weight, n bags = 0 in_bag = 0 while list.size > 0 x = pick(list[0...n], weight - in_bag) i = list.index(x) raise new Exeption("not a valid weight") if(!i || i >= n) list.delete_at i in_bag += x if in_bag >= weight #puts in_bag in_bag = 0 bags += 1 end end return bags end ``` [Try it online!](https://tio.run/##XVJhb@IwDP3Or/BAJ7W6LGq4Qdlp27f7FQihlBqIVlLUpGt3dL@ds5NyJ65q0/jZfo5f3LTF5/Va4h7OZvcOWoCdAJg9aOnaE7wEE2DWoG8bS@hJ9wEp4RUsfAOVZ8H@F2Dstvi8DN0QcIB10sEjlKnUhRMQDfooMUAbzgihX7SiLWml17WFQ@@oSpJJqWWF9uCPKdU/Q1nDYCK9lrv6VBirvaltYlLp662OPHJfae/RJiq9o5QOK9z5h8vgBhe6fKNWuHiF2vlt/YHNu6kqKn3LuPU0JnDs7NzS6aYFOv8TZpf7VOnqxn9NJ39l@c/NHXOnExa@aclvnBfQoTkcfbyCQh@4eRaXi@vDaHRHU2GIl878RniDqH9Pfr7ChF1rkkzazY2R1I4caQg1FBoIjC2xT/qINto4BIsd/OrxHOSc2tqDhg9dmXKkmqY0HMmDgWEgHhYuZge@koT1uNUeTCwUD/79FeLM0FiNECVGvnFGoprROUJ3XfMTFCEuFew4KHEdReYAlvVaaq8pca1yJdTyh1D5XKjnpVAL@vIFYWTnbNN@RfvVs1BP9F9yfEb4fIx5GnMJXy02k0k4Jl8YlxCgsiwTML/@AQ "Ruby – Try It Online") If you have enough weight to fill the bag, find the lightest subset that can fill the bag and use the lightest orange of that subset. Otherwise, get the remaining weight as close as possible to a multiple of 170. [Answer] # Racket/Scheme, 9880 bags To decide which piece of fruit to add to the bag, compare the optimal bag weight to the weight of the bag with the additional piece of fruit. If it's the optimal weight, use it. If it's overweight, minimize the excess amount. If it's underweight, minimize the excess amount after trying to leave an optimal gap. ``` ;; types (define-struct bagger (fruit look tray bag bags)) ; fruit bagger ;; constants (define MBW 1000) ; minimum bag weight (define AFW 170) ; average piece-of-fruit weight (define GAP (- MBW AFW)) ; targeted gap (define FRUIT (file->list "fruit-supply.txt")) ; supplied fruit ;; utility functions (define (weigh-it ls) (if (empty? ls) 0 (+ (car ls) (weigh-it (cdr ls))))) (define (ref-to-car ls ref) (if (zero? ref) ls (let ((elem (list-ref ls ref))) (cons elem (remove elem ls))))) ;; predicates (define (bag-empty? bgr) (empty? (bagger-bag bgr))) (define (bag-full? bgr) (>= (weigh-it (bagger-bag bgr)) MBW)) (define (fruit-empty? bgr) (empty? (bagger-fruit bgr))) (define (tray-empty? bgr) (empty? (bagger-tray bgr))) (define (tray-full? bgr) (= (length (bagger-tray bgr)) (bagger-look bgr))) (define (target-not-set? target value) (and (empty? target) (empty? value))) ;; pick best piece of fruit (define (pf-rec tray bag i target value diff) (if (or (target-not-set? target value) (< diff value)) (pick-fruit (cdr tray) bag (add1 i) i diff) (pick-fruit (cdr tray) bag (add1 i) target value))) (define (pick-fruit tray bag i target value) (if (empty? tray) target (let ((weight (weigh-it (cons (car tray) bag)))) (cond ((= weight MBW) i) ((> weight MBW) (pf-rec tray bag i target value (- weight MBW))) ((< weight MBW) (if (> weight GAP) (pf-rec tray bag i target value (- weight GAP)) (pf-rec tray bag i target value (modulo (- MBW weight) AFW)))))))) ;; load tray, bag, bags, etc. (define (load-bag bgr) (let* ((tray (bagger-tray bgr)) (bag (bagger-bag bgr)) (weight (+ (weigh-it tray) (weigh-it bag)))) (if (= weight MBW) (struct-copy bagger bgr (tray empty) (bag (append tray bag))) (let ((new-tray (ref-to-car tray (pick-fruit tray bag 0 empty empty)))) (struct-copy bagger bgr (tray (cdr new-tray)) (bag (cons (car new-tray) bag))))))) (define (load-bags bgr) (struct-copy bagger bgr (bag empty) (bags (cons (bagger-bag bgr) (bagger-bags bgr))))) (define (load-tray bgr) (struct-copy bagger bgr (fruit (cdr (bagger-fruit bgr))) (tray (cons (car (bagger-fruit bgr)) (bagger-tray bgr))))) ;; run the bagger factory (define (run-bagger-aux bgr) (cond ((bag-full? bgr) (run-bagger-aux (load-bags bgr))) ((bag-empty? bgr) (cond ((tray-full? bgr) (run-bagger-aux (load-bag bgr))) ((tray-empty? bgr) (if (fruit-empty? bgr) (length (bagger-bags bgr)) (run-bagger-aux (load-tray bgr)))) (else (if (fruit-empty? bgr) (run-bagger-aux (load-bag bgr)) (run-bagger-aux (load-tray bgr)))))) (else (cond ((tray-full? bgr) (run-bagger-aux (load-bag bgr))) ((tray-empty? bgr) (if (fruit-empty? bgr) (run-bagger-aux (load-bags bgr)) (run-bagger-aux (load-tray bgr)))) (else (if (fruit-empty? bgr) (run-bagger-aux (load-bag bgr)) (run-bagger-aux (load-tray bgr)))))))) (define (run-bagger fruit look) (run-bagger-aux (make-bagger fruit look empty empty empty))) ;; stackexchange problem run (define (run-problem fruit looks) (if (empty? looks) 0 (+ (run-bagger fruit (car looks)) (run-problem fruit (cdr looks))))) (run-problem FRUIT '(2 3 4 5 6 7)) ; result = 9880 ``` [Answer] # [Haskell](https://www.haskell.org/), 9777 bags This was my first attempt: * it greedily filled a bag with a batch when it could, * or flushed all oranges into the bag when it could not. ``` options[]=[(0,([],[]))] options(first:rest)=[option|(sum,(now,later))<-options rest, option<-[(sum+first,(first:now,later)),(sum,(now,first:later))]] bags _[_]_=[] bags(w_sum,w_bag)(w_kilo:w_iyts)w_view= let(w_take,w_remd)=splitAt(w_view)w_iyts; w_fill=filter((>=(w_kilo-w_sum)).fst)(options w_take) in if null w_fill then bags(w_sum+sum w_take,w_bag++w_take)(w_kilo:w_remd)w_view else let(_,(w_now,w_later))=minimum w_fill in (w_bag++w_now):bags(0,[])(w_kilo:w_later++w_remd)w_view main=print.sum$map(length.bags(0,[])(1000:batch))[2..7] ``` [Try it online!](https://tio.run/##bX3bjh1HkuS7voIP@0Ci2UJmRHiEe89wgf0OQiC0O@xpoil2Q@KMsMD@u7Yy0s3NsmYEUGTVuWRmXPxibm7xt59/@/vnr1//@OMf//z@5R/ffvv404ePb4/3bz/@9P7jT@/e/fRD/v7tX7/8@tv3v/z6@bfv7z58vH/5/97@9h@/vH/77R@/v//68/fPv757969/zre/ud74/oc394//@ueP11v/tL/jfX6VfOw9v@h@LX//008//O@f//23N58@fvrp04eP909vf/90vfv3Ty8/vHv54e9fvv7jL79/@vJ/v//27vdP//nl8@8ffnjz9fP3l5e@//z3zy9v/PXzL//27sNv//z65fv/un59vefd/Yl/@eHN9d/vn/765evXDy//e7nu27f/80N@75/3td69@/GvL4/9Fs92f/G7H958@fbmy1/ffPuPr1/zG958/9vnb294l396@fOm7uPl93/6U36YN77v7r6pfTOfv/72ed//p/cvb7rG5PdPOR4ffvny7csv@yv31b58u2//@u9tff/LR979Zd/Dcc0hr7S/5XqHXvKXn798@/DPX798@/7jy83@j19@/ufbr5@//fv3v/0oX3Eex/Hyld//z9/evfvYfvxx/fTH/unDx3Me79txvD9tvvw5359zvD/9@rvdPy97@fnl9fXyx19@t15en/Hy5@X3c92fu163/vLzy594@eMvr62X19bLv7vfr8/z/sy6vjd/tpfXer/fOzx/n997ve@6D3u5Vl/3/azrWuP@/v35656uz@f9LrznuueX71tx/41nMbs/f13v@vf1rJb3tPLf13v3fc68p3ZfY4@B8/fX9aPxO677vJ5/zHus9nuP@3eeY7jHauVnRt5z3OOEcR55P9c1rucakWOe99vbPT7XPe17bfd84B6v913zZDmu@x7y7@u75/VM62XOJ69/fT5yXDzH@hqnnuO/P2M51rj/nL9x3K9f44Fx9Pz3vpfzfo7rGUd7ue41VzIW1@8N95DzuJ/P7zFZWDtHzqPneK2ck5Fzir/bvQavP9f7POd9HRyLOTnu@97Xff2FP/m@a@6v@dtjOe/nt5yPa4x93r/f8yP7Ijz3SsvnaPcavt6PtW15nZ73c62R0fbc3Nd9@b64frfy@4/7tevfI@coMN95/X3v8157ewzP@7W9J0fe77W2@v36/u4zxwP7B3vdOL7X69c47DleMgZL1iDueeUcWa5pu9e6531da/B6vmtdX69F/n7v0@N@7Rq/yGvv@1v39ffPU/aU5ZjH/bl9Xys/23IPxn2N63qW93/9znLNXvdm@XPZhOD79nN5rifL9RByf/1et3s9pP0w2XPh3K/Xve/3zhyPg69dYzkmx9FyPPbYH/e1L3tzfb5b2luxo9dc73VxPO3jyv257YWlnXfO98vv7j2Jte65N7GGc93v1yZt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nBJmdwl@9S7dRJ36LnBFadMURXdEpfrOjmoDcVtqj6gearMzV1v5vEEMpZP8lPAn9y6tgF@@8qdglyHEsrKXP4AKdIzu@1wTpyzWXjWfChvOrJ54E/dT2XyuQ8Gn@er1LnU8czTkbdE/pO6MWvPrgpusSyhh62eko/uOpKNWKnpV0mPbEunEzXc7WWnK9@Ss@h9ls28rO1f7nGIvfPUAzzIN80TuKuLlyt6ouZnDNgv8DozMi3W87a7tTzYwd5aqXdmjlUxDMnXIM944rLqO4k@AejsY5z5WcDmI/2zwZrVcB5SyNJNFdwnmbFlDgzpLM@Cn5ESC8b6mbo58VZyqXz7aKfrud1ge@DcyIm@wfqPEnhf4AvqXyBOZ/7s3hnJ@Pxpblp@g5rTw225YKJ3T5mn@vnypvr1OgpPpas44q39aylSY6L6v1gf5dm4UHOMuas9eeZ1ThDbUovCM7sVu3IOIU7F9RUM@nHN43tG@t4eq6t1rOQy8A225KzE4RfiFgu0s50Y3xhchbG6FKf1P5lOesdvVuIs5CfA3NcgjEXf15sCHhjwNiWcHP7kHj0IC8LmIBN1ozBI7R4asJO6dXD/a5XekCY55A@aeQxxUdCTQ/YVPz0xx//Hw "Haskell – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 9981 bags The [Angs](https://codegolf.stackexchange.com/questions/162453/fruit-bagging-factory/163190) → [Jonathan Allan](https://codegolf.stackexchange.com/a/162498/58925) → [JayCe](https://codegolf.stackexchange.com/a/162852/58925) → [fortraan](https://codegolf.stackexchange.com/a/162863/58925) → [Alex](https://codegolf.stackexchange.com/a/162969/58925) → [Roman Czyborra](https://codegolf.stackexchange.com/a/163052/58925) codegolf python could cyclize back to Haskell for some added mathematical purity along the same major train of thought * only one orange gets sacked before a new orange is added into consideration * bias prefers sufficing fruits (`(<miss)==False<True`) * bias prefers fruits close to the most likely integer fill * for that integer reverse the `(m-n)/sqrt(n)==(n+1-m)/sqrt(n+1) <==> n=sqrt(m^2-1/4)-1/2` from a <https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables> [![https://m.wolframalpha.com/input/?i=plot+abs(1-x)*sqrt(1),abs(2-x)*sqrt(2),abs(3-x)*sqrt(3),abs(4-x)*sqrt(4)](https://i.stack.imgur.com/L8KHs.png)](https://i.stack.imgur.com/L8KHs.png) seasoned with some unecessary pointlessnesses ``` subsets[]=[[]];subsets(f:t)=[r|s<-subsets t,r<-[s,f:s]] mean=uncurry(div).(id***max 1).(sum&&&length) bags[]_ _=[];bags batch(miss:have)n=let goal=div miss$ceiling(sqrt((fromIntegral miss/170)^2+1/4)-1/2) best=minimumBy.comparing.(((<miss)&&&(abs.(goal-))).); desk=take n batch pick=best id.best(if sum desk<miss then mean else sum).filter(>[]).subsets$desk in if pick < miss then bags(delete pick batch)(miss-pick:pick:have)n else (pick:have):bags(delete pick batch)[miss+sum have]n main=print$id&&&sum$map(length.bags batch[1000])[2..7] ``` [Try it online!](https://tio.run/##dX1brx5Hktw7f8V5GAzIWYnTXVVZlakZGvDlxYAB/wCCXlASJRFDUjJJrb2A/7v2dHdGRvTZtQCKPOe7dHdd8hIZGfXL2y//ePfhwx/vP/726@evD//t7de3L//n5x@f6c//4/2Xr/jFf/3109fPv354@Z8/f/71//zx5ffvv7z7@uX1m1evX79587f88flP33198er15//35e/f5q8evn7z@e/fvv7yzU/ffXnz5tnHd28/vfr90w@/f/78r89/fP8vL14@f//jX/7yl49v/@/D/vjDl98//vnPf/7w7tPPX3958ez7tz8/XuKfH/751es3fzt@ePj@7dcffnn@8f2XL9/98vZf3r349OrDu6/PHn7@9e2HV49f93C88qcf3r3/8P7Tz8@//O/PX58//@nzrx//@6ev737@/PbD@fpf97W9@F/tn/a/jhff7n9tL549fP/uy9dXH99/ev/x94//5V9f/vDrx9/efn78ipfPnz//@/GZF4939fzt919ePj8u9e2LFy9evvjbw4/vvvzj1de3/3j38Om6s2cPv73/4R@vjq97eP/jy@Pv5@9/enh8qvO951c9fP3l3aeHYyAe3n348u548cXLn95/@Pru8/P/9PrNi5c5cn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U3SJZQ3dbPWUfnDVlWrETku7THpiXTiZrudqLTlffZeeQ@23bORna/9yjUXun6EY5ka@aezEXV24WtUXMzlnwH6B0ZmRb7ectd2p58cO8tRKuzVzqIh7TrgGe8YVl1HdSfAPRmMd58jPBjAf7Z8N1qqA85ZGkmiu4DzNiilxZkhnfRT8iJBeNtTN0M@Ls5RL59tFP13P6wLfB@dETPYP1HmSwv8AX1L5AnPe92fxznbG40tz0/Qd1u4abMsFE7t8zHmunytvrlOjp/hYso4r3tazliY5Lqr3g/1dmoUbOcuYs9bvZ1bjDLUpvSA4s1u1I2MX7lxQU82kH980tm@s4@m5tlrPQi4D22xLzk4QfiFiuUg7043xhclZGKNLfVL7l@Wsd/RuIc5Cfg7McQnGXPx5sSHgjQFjW8LN7UPi0Y28LGACNlkzBo/Q4q4JO6VXD/e7nugBYZ5D@qSRxxQfCTU9YFPx5o8//g0 "Haskell – Try It Online") without yielding a different numeric gain atop the 9981 nets of oranges harvested afore while [my 10k011 bags packer grabbing unfit oranges back out of unclosed bags](https://codegolf.stackexchange.com/a/163190/58925) was disqualified by [user69850](https://codegolf.stackexchange.com/users/69850/user202729) in persona [user202729](https://codegolf.stackexchange.com/a/162914/58925) → [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) → [ovs](https://codegolf.stackexchange.com/users/64121/ovs) hencefore the deserved bounty went to [Alex](https://codegolf.stackexchange.com/a/162498/58925) [![GIMME BOUNTY!](https://i.stack.imgur.com/JZ5Yx.jpg)](https://i.stack.imgur.com/JZ5Yx.jpg) ]
[Question] [ The [Collatz conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture) postulates that if you take any positive integer, then repeat the following algorithm enough times: ``` if number is odd, then multiply by three and add one if number is even, then divide by two ``` you'll eventually end up at 1. It seems to always work, but it's never been proven that it always does. You've already golfed [calculating how long it takes to get to 1](https://codegolf.stackexchange.com/questions/12177/collatz-conjecture-oeis-a006577), so I thought I'd switch things up a bit. Starting with a given positive integer, calculate how long it takes to get to 1 (its "stopping time"). Then find *that* number's stopping time. Repeat until you get to 1, or until you get to the entirely arbitrary limit of 100 iterations. In the former case, print how many iterations it took. In the latter case, print "Fail" or some other consistent output of your choice, as long as it's not an integer `1≤n≤100`. You may not output an empty string for this option. Outputting an integer outside of the range [1, 100], however, is allowed. ## Examples: ``` Input: 2 2->1 Output: 1 Input: 5 5->5->5->5->5->... Output: Fail Input: 10 10->6->8->3->7->16->4->2->1 Output: 8 Input: 100 100->25->23->15->17->12->9->19->20->7->16->4->2->1 Output: 13 Input: 10^100 10^100->684->126->108->113->12->9->19->20->7->16->4->2->1 Output: 13 Input: 12345678901234567890 12345678901234567890->286->104->12->9->19->20->7->16->4->2->1 Output: 11 Input: 1 --Depending on your code, one of two things may happen. Both are valid for the purposes of this question. 1 Output: 0 --Or: 1->3->7->16->4->2->1 Output: 6 ``` As I calculated `10^100` and `12345678901234567890` using a language that only supports reals for that size, if your language is more accurate you may get different results for those. ## Scoring As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the answer with the shortest amount of bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), 70 bytes ``` f=lambda n,k=0,j=0:n-1and-~f(k*[n/2,n*3+1][n%2]or f(j/99or n,1),k,j+1) ``` Returns **199** for one hundred or more iterations. [Try it online!](https://tio.run/##RYy9DoIwFIVneYouJlAu0hZRIeFJCAMKjeXnlrR1YPHVsejg8J185wxnWd1To9jUvGjjiF1t4DnZ3pn@8TJWaZzUrFwoGGPRJqupne9dSxDGisFQsRIT3mKXvGU40hpTAUizmDc1HkWjDZHhkBaFFwQewQhDzP3N3olCIoDkQDjb@QalPxHZOb9cbwX7m1/L4LAYhc6/YrR9AA "Python 2 – Try It Online") [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/attache), 40 bytes ``` `-&3@`#@PeriodicSteps[CollatzSize@Max&1] ``` [Try it online!](https://tio.run/##SywpSUzOSP3vkpqWmZcarZKm8z9BV83YIUHZISC1KDM/JTM5uCS1oDjaOT8nJ7GkKjizKtXBN7FCzTD2fyxXQFFmXolDtVd@Zl50WHS8Tlp0fGysjpKCrp2CUmytgq2dQli0oY6CkY6CqY6CoQEIAwkjU7PY/wA "Attache – Try It Online") This is a new language that I made. I wanted to get around to making a proper infix language, and this is the result: a mathematica knock-off. Hooray? ## Explanation This is a composition of a few functions. These functions are: * `PeriodicSteps[CollatzSize@Max&1]` This yields a function which applies its argument until the results contain a duplicate element. This function, `CollatzSize@Max&1`, is applying `CollatzSize` to the greater of the input and `1`, to avoid the invalid input `0` to CollatSize. * ``#` is a quoted operator; when applied monadically in this sense, it obtains the size of its argument * ``-&3` is a bonded function, which bonds the argument `3` to the function ``-`, which reads as "minus 3". This is because the PeriodicSteps application yields `0`s, which need to be accounted for. (It also neatly handles out-of-bounds numbers like `5`, which map to `-1`.) [Answer] # [J](http://jsoftware.com/), ~~49~~ 45 bytes -4 bytes thanks to shorter Collatz Sequence code taken from @randomra's comment [here](https://codegolf.stackexchange.com/a/12186/42833). ``` (2-~[:#(>&1*-:+2&|*+:+>:@-:)^:a:)^:(<101)i.1: ``` Outputs `101` for invalid results. [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NYx066KtlDXs1Ay1dK20jdRqtLSttO2sHHStNOOsEkGEho2hgaFmpp6h1X9NrtTkjHwFDR09hTRNhdSy1KJKBUMFIwVTBUMDIALiVDBpZGxiamZuYWmAYP0HAA "J – Try It Online") # Explanation Unsurprisingly, this explanation has become quickly outdated. I'm going to leave it in terms of the old 49 byte answer I had, which I'm including below. If you want an update, just let me know. The way that it finds the length of the recursive sequence remains the same, I've just used a shorter Collatz Sequence method. ``` (1-~[:#%&2`(1+3&*)@.(2&|)^:(1&<)^:a:)^:(<101)i.1: ``` ### Finding the length of the Collatz Sequence This section of the code is the following ``` (1-~[:#%&2`(1+3&*)@.(2&|)^:(1&<)^:a:) ``` Here's the explanation: ``` (1 -~ [: # %&2`(1+3&*)@.(2&|) ^: (1&<) ^: a:) Given an input n ^: a: Apply until convergence, collecting each result in an array. ^: (1&<) If n > 1 do the following, else return n. (2&|) Take n mod 2. %&2 If n mod 2 == 0, divide by 2. (1+3&*) If n mod 2 == 1, multiply by 3 and add 1. # Get the length of the resulting array. 1 -~ Subtract 1. ``` Unfortunately, the apply verb (`^:`) when told to store results stores the initial value too, so it means we're (like always) off by one. Hence why we subtract 1. ### Finding the length of the recursive sequence ``` (1-~[:#%&2`(1+3&*)@.(2&|)^:(1&<)^:a:) ^: (< 101) i. 1: Given an input n. ^: (< 101) Apply 100 times, collecting results in an array. (1-~[:#%&2`(1+3&*)@.(2&|)^:(1&<)^:a:) Collatz sequence length. i. 1: Index of first 1 (returns 101, the length of the array if 1 not found). ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 75 bytes ``` i,j;f(n){for(j=0;(i=n)&&j++<100;)for(n=0;i-1;++n)i=i&1?i*3+1:i/2;i=!i*j-1;} ``` Returns `-1` for `n>=100` iterations. [Try it online!](https://tio.run/##fclBDoIwEEDRPaeoJDYzFGKLcePQeBE3pqZmmjAa4o5w9lL2yl/@F7pXCDlzmyiC4BzfEyRvCdgLap2MGZy1hNuX8rlzZIwge9buxs3ZuCufemJ/4CYVXDLLV40PFsBqrlTpM5UVoT4@71K3KkKPSL/l8lec3aEd22TJKw) # [C (gcc)](https://gcc.gnu.org/), 73 bytes ``` i,j;f(n){for(j=-1;(i=n)&&j++<99;)for(n=0;i-1;++n)i=i&1?i*3+1:i/2;i=!i*j;} ``` Returns `0` for `n>=100` iterations. [Try it online!](https://tio.run/##fclBDoIwEEDRPaeoJDYzFCLFsMCx8SJuTE3NNGEkxB3h7LXslb/8zzcv71PiOlIAwSW8Z4iusQTsBLWOxlyHgXD74lriTMYIsmNtb1ydjb3wqSN2B64irYnlo8YHC2CxFCo3zXkFKI/Pu5S1CtAh0m/p/4ptd2jHNlnTFw) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` ×3‘$HḂ?’пL’ Ç1¹?ȷ2Сi1’ ``` [Try it online!](https://tio.run/##y0rNyan8///wdONHDTNUPB7uaLJ/1DDz8IRD@32ANNfhdsNDO@1PbDcCiizMNAQK/f//39DAAAA "Jelly – Try It Online") [Answer] # JavaScript (ES6), 57 bytes Returns `true` when it fails. Returns `0` for `1`. ``` f=(n,k=i=0)=>n>1?f(n&1?n*3+1:n/2,k+1):k?i>99||f(k,!++i):i ``` ### Test cases ``` f=(n,k=i=0)=>n>1?f(n&1?n*3+1:n/2,k+1):k?i>99||f(k,!++i):i console.log(f(2)) // 1 console.log(f(5)) // fail console.log(f(10)) // 8 console.log(f(100)) // 13 console.log(f(1)) // 0 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~39~~ ~~60~~ ~~53~~ ~~52~~ 49 bytes -3 bytes thanks to @ngn ``` 0∘{99<⍺:⋄1=⍵:0⋄1+(⍺+1)∇{1=⍵:0⋄1+∇⊃⍵⌽0 1+.5 3×⍵}⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSDRx0zqi0tbR717rJ61N1iaPuod6uVAYilrQEU0zbUfNTRXo0sDOQ/6moG8h/17DVQMNTWM1UwPjwdyK8FYaCpCoYGXCACRJoCAA "APL (Dyalog Unicode) – Try It Online") Uses @ngn code for Collatz, but previously used @Uriel's code. Here's the old version that didn't meet the specification: ``` {1=⍵:0⋄1+∇{1=⍵:0⋄2|⍵:1+∇1+3×⍵⋄1+∇⍵÷2}⍵} ``` [Answer] # [Perl 6](http://perl6.org/), 56 bytes ``` {($_,{($_,{$_%2??$_*3+1!!$_/2}...1)-1}...1).head(102)-1} ``` [Try it online!](https://tio.run/##RYhBDoIwFAWv8iBfU2qtbRHUBXKUHxJpWGg0uCJNz17FLly8eZN5jfO9TY8FW48uBUGsMog3ru@JZb2zRUF8cFFrbau9za@ncbgJa9xakn/OEE6hUbBm3Q9SZnH1sWlP54v527dWCHgPC0pidFcED@JYIqYP "Perl 6 – Try It Online") Returns `101` for a non-terminating sequence. [Answer] # [Husk](https://github.com/barbuz/Husk), 21 bytes ``` ←€1↑101¡ȯ←€1¡?½o→*3¦2 ``` [Try it online!](https://tio.run/##yygtzv7//1HbhEdNawwftU00NDA8tPDEeqjAoYX2h/bmP2qbpGV8aJnR////DQ0MAA "Husk – Try It Online") Returns `-1` on failure, `0` on input `1`. ## Explanation ``` ←€1↑101¡ȯ←€1¡?½o→*3¦2 Implicit input (a number). ?½o→*3¦2 Collatz function: ? ¦2 if divisible by 2, ½ then halve, o→*3 else multiply by 3 and increment. ȯ←€1¡?½o→*3¦2 Count Collatz steps: ¡ iterate Collatz function and collect results in infinite list, €1 get 1-based index of 1, ȯ← decrement. ¡ Iterate this function on input, ↑101 take first 101 values (initial value and 100 iterations), ←€1 get index of 1 and decrement. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~70~~ 73 bytes ``` g(x){x=x-1?g(x%2?3*x+1:x/2)+1:0;}f(x,m){for(m=0;(x=g(x))&&100>m++;);x=m;} ``` [Try it online!](https://tio.run/##fctBCsIwFATQfU9RCi3/mwaTihtD7EXclEhCwaQSBT@UXN0YXauzmYHHGO6MydkB4UqauBzLbIdxtyEmD7QdsJRQyQL1Hle7RPBaKCD9vmDXSSGOnjGFirRXKftpDhCxWqu65BrncLfQtOdTaPragkRU32X/U6T4Qx9L@WnsZXK3zB8v "C (gcc) – Try It Online") Returns `101` when number of iterations exceeds 100. [Answer] # [Clean](https://clean.cs.ru.nl), ~~146~~ ... 86 bytes *-11 bytes thanks to Ørjan Johansen* ``` import StdEnv ?f l n=hd[u\\1<-iterate f n&u<-l] ``` # ``` ?(?(\b|isOdd b=3*b+1=b/2)[0..])[0..99] ``` As a partial function literal. [Try it online!](https://tio.run/##HcqxCsIwEADQ3a@4SarSmupUaMiigyA4dGw7XJq0BpKrNIkg@O1GcXnTG6xGSm5W0WpwaCgZ95iXAE1QZ3quxAgWiN9VG7uurHMT9IJBwwi0jnVu@9QE/HUOIhNZJ9/G35QCyY9buSu53B82LSuK/m9V9VAylj7DaHHyKb9c0@lF6Mzgvw) Aborts with `hd of []` if the number of iterations exceeds 100. Exits with `Heap Full` for inputs above ~`2^23` unless you specify a larger heap size. [Answer] # [Python 2](https://docs.python.org/2/), ~~99~~ ~~98~~ 97 bytes * Saved a byte by using `c and t or f` instead of `t if c else f`. * Saved a byte by outputting `-1` instead of `f` or `'f'` for non-halting inputs. ``` exec"f,F="+"lambda n,i=0:n<2and i or %s"*2%("f([n/2,3*n+1][n%2],-~i),","i>99and-1or F(f(n),-~i)") ``` [Try it online!](https://tio.run/##RY7BDoIwDIZfpWmyZIMSYYgKEY@8BOGAwuISLQR20IuvPocXk/7N/7df0s5vd59Yez@@xhsaamqM8dE/r0MPTLZOKz7rngewMC0gVoy0kGhkyztNecRx1rUsdEfJxypCQnspy8AnWcAbaSSr3wqVN2HiwDJITVAQZOmmrYXS@b44HE9l@ncUWCezMTBKVTAvIQI2UqwK6u0VECAdhStOKf8F "Python 2 – Try It Online") [Answer] ## [BiwaScheme](http://www.biwascheme.org/), 151 chars ``` (define(f n i s)(if(= s 0) 'F(if(= n 0)i(f(letrec((c(lambda(m k)(if(= m 1)k(c(if(=(mod m 2)0)(/ m 2)(+(* m 3)1))(+ k 1))))))(c n 0))(+ i 1)(- s 1))))) ``` You can try it [here](https://repl.it/repls/YellowIncompleteWhapuku). [Answer] # [R](https://www.r-project.org/), ~~119~~ 107 bytes Partially uses Jarko Dubbeldam's collatz code from [here](https://codegolf.stackexchange.com/a/102170/59052). Returns `0` for >100 iterations (failure). ``` pryr::f(x,{N=n=0 while(x-1){while(x-1){x=`if`(x%%2,3*x+1,x/2);n=n+1} x=n n=0 N=N+1 if(N==100)return(0)} N}) ``` [Try it online!](https://tio.run/##TctBCgIxDEDRfe4xkNiKScXNSK7QM8xmggUpUhQjQ89eGdy4efzNb8N0PNqnzbOhxy1rVYb3rdxX9KPQ9peuS7EFfZpSPB88SPRTomvVGqSDa4X9zZqDQDHMqsJMbX2@WkWmDrnTMEwEhpcd4Z9M4ws "R – Try It Online") [Answer] # APL NARS, 115 bytes, 63 chars ``` {d←0⋄{⍵=1:d⋄99<d+←1:¯1⋄∇{c←0⋄{1=⍵:c⋄c+←1⋄2∣⍵:∇1+3×⍵⋄∇⍵÷2}⍵}⍵}⍵} ``` Probably using loops it would be more clear... There are 4 functions, 2 nested and ricorsive, and the first only for define and initialize to =0, the variable d, seen from the 2th function as a global variable counter. ``` q←{c←0⋄{1=⍵:c⋄c+←1⋄2∣⍵:∇1+3×⍵⋄∇⍵÷2}⍵} ``` This 3th function, would be the function that return how many call there are for resolve the Collatz conjecture for its arg ``` {⍵=1:d⋄99<d+←1:¯1⋄∇q⍵} ``` This is the 2th function, if has its arg =1,stop its recursion and return d the number of time it is called itself-1; else if itself is called more than 99times stop its recursion and return -1(fail) else calculate Collatz conjecture for its arg, and call itself for the Collatz sequence length value. For me even if all this seems run could be a big problem if is defined a global variable and one variable in a function of the same name, when the programmer sees it as just a local variable. ``` f←{d←0⋄{⍵=1:d⋄99<d+←1:¯1⋄∇{c←0⋄{1=⍵:c⋄c+←1⋄2∣⍵:∇1+3×⍵⋄∇⍵÷2}⍵}⍵}⍵} f 2 1 f 3 5 f 5 ¯1 f 10 8 f 100 13 f 12313 7 f 1 0 ``` [Answer] **(Emacs, Common, ...) Lisp, 105 bytes** Returns t for iterations > 100 ``` (defun f(n k c)(or(> c 100)(if(= n 1)(if(= k 0)c(f k 0(1+ c)))(f(if(oddp n)(+ n n n 1)(/ n 2))(1+ k)c)))) ``` Expanded: ``` (defun f (n k c) (or (> c 100) (if (= n 1) (if (= k 0) c (f k 0 (1+ c))) (f (if (oddp n) (+ n n n 1) (/ n 2)) (1+ k) c)))) (f (read) 0 0) ``` ]
[Question] [ [The Goldbach conjecture](https://en.wikipedia.org/wiki/Goldbach%27s_conjecture) states that every even number greater than two can be expressed as the sum of two primes. For example, ``` 4 = 2 + 2 6 = 3 + 3 8 = 5 + 3 ``` However, once we get to 10 something interesting happens. Not only can 10 be written as ``` 5 + 5 ``` but it can also be written as ``` 7 + 3 ``` Since 10 can be expressed as the sum of two primes *two ways*, we say that the "Goldbach partition" of 10 is `2`. Or more generally, > > The Goldbach partition of a number is the total number of distinct ways of writing `n = p + q` where `p` and `q` are primes and `p >= q` > > > Your challenge is to write a program or function that finds the Goldbach partition of a number. Now, technically the term "Goldbach partition" is used only to refer to even numbers. However, since the odd integer **p + 2** can *also* be expressed as the sum of two primes if **p > 2** is prime, we will extend this to all positive integers ([A061358](https://oeis.org/A061358)). You may safely assume that your input will always be a positive integer, and you may take input and output in any of our [default allowed methods](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), for example function arguments and return value, STDIN and STDOUT, reading and writing to a file, etc. The Goldbach partitions of the positive integers up to 100 are: ``` 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 0, 1, 1, 2, 1, 2, 0, 2, 1, 2, 1, 3, 0, 3, 1, 3, 0, 2, 0, 3, 1, 2, 1, 4, 0, 4, 0, 2, 1, 3, 0, 4, 1, 3, 1, 4, 0, 5, 1, 4, 0, 3, 0, 5, 1, 3, 0, 4, 0, 6, 1, 3, 1, 5, 0, 6, 0, 2, 1, 5, 0, 6, 1, 5, 1, 5, 0, 7, 0, 4, 1, 5, 0, 8, 1, 5, 0, 4, 0, 9, 1, 4, 0, 5, 0, 7, 0, 3, 1, 6 ``` As usual, standard loopholes apply, and the shortest answer in bytes wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` _ÆRÆPSHĊ ``` [Try it online!](http://jelly.tryitonline.net/#code=X8OGUsOGUFNIxIo&input=&args=MTAw) or [verify all test cases](http://jelly.tryitonline.net/#code=X8OGUsOGUFNIxIoKMTAww4figqzFk3M0Rw&input=). ### How it works ``` _ÆRÆPSHĊ Main link. Argument: n (positive integer) ÆR Prime range; yield [2, 3, 5, ..., n]. _ Subtract all primes in this range from n. ÆP Compute the primality of the resulting differences. This returns 1 for each prime p such that n - p is also prime. S Compute the sum of the resulting Booleans. H Divide it by 2, since [p, n - p] and [n - p, p] have both been counted. Ċ Ceil; round the resulting quotient up (needed if n = 2p). ``` [Answer] ## Python 2, 76 bytes ``` g=lambda n,k=2:n/k/2and all(x%i for x in[k,n-k]for i in range(2,x))+g(n,k+1) ``` Recursively crawls up from `k=2` to `n/2`, adding up values where both `k` and `n-k` are prime. It would be nice to count `n` down at the same time instead, but this has a problem that `k=0` and `k=1` are falsely called prime: ``` g=lambda n,k=0:n/k and all(x%i for x in[k,n]for i in range(2,x))+g(n-1,k+1) ``` The primality check is trial-division, shortened by checking both `k` and `n-k` together. I found this to be shorter than using a Wilson's Theorem generator (79 bytes): ``` f=lambda n,k=1,P=1,l=[]:n/k and P%k*(n-k in l+P%k*[k])+f(n,k+1,P*k*k,l+P%k*[k]) ``` The idea for this one is to keep a list of all primes in the bottom half to be checked by the time we get to the top half, but for the midpoint `k=n/2`, we haven't had time to add `n-k` to out list when we get to `k`. An iterative version gets around this, but is 82 bytes: ``` n=input() s=P=k=1;l=[] while k<n:l+=P%k*[k];s+=P%k*(n-k in l);P*=k*k;k+=1 print~-s ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 8 bytes ``` tZq&+=Rz ``` [**Try it online!**](http://matl.tryitonline.net/#code=dFpxJis9Uno&input=MTAw) ### Explanation Consider input `8` as an example ``` % Take input implicitly t % Duplicate % STACK: 8, 8 Zq % All primes up to that number % STACK: 8, [2 3 5 7] &+ % Matrix with all pairwise additions % STACK: 8, [4 5 7 9 5 6 8 10 7 8 10 12 9 10 12 14] = % True for entries that equal the input % STACK: [0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0] R % Extract upper triangular part (including diagonal). % This removes pairs that are equal up to order % STACK: [0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0] z % Number of nonzero entries % STACK: 1 % Display implicitly ``` --- It's interesting to observe the **graph of the sequence**, using a slightly modified version of the code: ``` :"@ % Input n implicitly. For each k from 1 to n, push k tZq&+=Rz % Same code as above. Pushes the result for each k ]v'.'&XG % End. Concatenate all results into a vector. Plot as dots ``` For input `10000` the result is [![enter image description here](https://i.stack.imgur.com/xZuXR.png)](https://i.stack.imgur.com/xZuXR.png) You can try it at [**MATL Online**](https://matl.io/?code=%3A%22%40tZq%26%2B%3DRz%5Dv%27.%27%26XG&inputs=3000&version=19.3.0) (Refresh the page if the "Run" button doesn't change to "Kill" when pressed). It takes several about 25 seconds to produce the graph for input `3000`; inputs above a few thousands will time out. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` ;ÅP-pO ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f@nBrgG6B////hgYA "05AB1E – Try It Online") Explanation: ``` # implicit input (example: 10) ; # divide input by 2 (5) ÅP # primes up to that ([2, 3, 5]) - # subtract from the implict input ([8, 7, 5]) p # isPrime? ([0, 1, 1]) O # sum (2), implicit output ``` [Answer] # Regex `🐇` (ECMAScript[RME](https://github.com/Davidebyzero/RegexMathEngine/) / Perl / PCRE), ~~38~~ ~~33~~ 32 bytes ``` ^(xx+)(?=\1(x*))(?!\2?(xx+)\3+$) ``` [Try it on replit.com!](https://replit.com/@Davidebyzero/regex-Goldbach-partitions) - ECMAScript (RegexMathEngine) [Try it online!](https://tio.run/##RU9BTsMwELz3FcZaVV6ctHFROdRxnUrlyqk3UqwStZIl04Y4SEEhHHkAT@QjwQlIXFY7s7O7M@Wxcsv@@Y1AJUnrLsXBEZjLAFW63ew2625yulQMvEpkupbYEnsKCNuysuea0PxMZUcyp3zpbM1oTCP/@uTrsGKiWEQCjy@DSP@zSeBxBQblcMuHj4cqc@kC28w9iL0KNdnLbkLI@Nn@EWBTNQpCxzm2UARLhNGGNmBRfcyZXkGFTOuWcyiipMMhh59OR6uj0xBDSPJrHeyMku/PL0JnUAThexh1nTF391tj@kfWNDwcu2Kza6ZVLgBRj1x@wwFz0fdJvFje/gA "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##hVXrTuN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hs5pgJUnuw87CjHMME1Xh5G7b0l0ngoVA9eBgKPwDX5e2IF6R8ooBOKSNk50ZgSJg6lNb8zIjzUwr//PU34KeF45UZIehYy5rpJdWUr9mlidnuKHSaY0Po34rTuLZlpMGacwb3sA/b29bGVmi7bjy@HEcXl5@OJydn9JWipl@rvRYTQ1YNe2OD4VdnTXc1/XF@24g3THL1PHdW702NlVWMkVV86w1tBJZ72p6I5hJnxnJgm0jw0/HS7@HH8d8ky@Np/dLLtVLv4D8 "C++ (gcc) – Try It Online") - PCRE2 Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.) ``` ^ # tail = N = input number (xx+) # \1 = conjectured first prime, automatically asserted # to be ≥ 2; # tail = N-\1 == conjectured second prime (?= \1 # tail -= \1; assert that second prime ≥ first prime; # since the first prime is ≥ 2, this automatically # asserts the second also to be so. (x*) # \2 = tail == N-2*\1 == tool to make tail = \1 ) (?! # Assert there is no way to make the following match: \2? # either leave tail unchanged, or tail = \1 (xx+)\3+$ # Assert that tail is composite (which is only the same # as being not prime for numbers ≥ 2) ) ``` # Regex `🐝` (ECMAScript 2018 or better), 36 bytes ``` (?<=(x+x))(?=\1(x*))(?!\2?(xx+)\3+$) ``` Returns its output as the number of matches. [Try it online!](https://tio.run/##TY7NToNAFIVfBYnJ3OuUCdToAjpl5aKbLnQpJp3AlF4DAw7TlvRn6wP4iL4IUqNJdyf5zjn53tVOdbml1gWmKfRwkGFi5bMun/oWXpwlUwqr9qsB0pmEnveIkMosgv7ukm6yaQp9zzG757c4rERXUa4hmgQRTljJMLH6Y0tWA7NaFRUZzVDkY3Z6YZy2azXWj2TarYtb2@S660TnCjJnFI0B9ruYVHJ@LGUlurYiBywYf2kNYGQpKm1Kt8H59HSibqmWQLJVtru8Q/kaviH@A30NzDxKo/iC0W1ss/cXZqcqKjyrTKljz@dVsm4sJDSTOiHO8VhLv/eF1e0oD4SiVi7fgMXkyrvZOrG35DTAIWWZYTFjyIkz7/vzy2Mc6rT@U45DxOQgo/MZhzCYPjz@AA "JavaScript (Node.js) – Try It Online") - ECMAScript 2018 [Try it online!](https://tio.run/##JY5NboMwEIX3nGI66sITDMKJ2gXU4iAhi0iYxJIZkPHCyQF6gB6xF6F2s3vS@97P@gj3hU@7ndfFB9gem/TmZmIHXntE3EX/pUUsI5Ho9aBEPGT1Nhx7EWNJw6l8pz2BZ9VW6tLBUzfFtHhwYDnX1VsYLbcFOO3qbXU2CKyQCsgQZ8hf@WaE5SDcubmQfKlURqWiFAQ7wbOF1WcjBdOE6mDWzrD4/1pPlserc8JLwIgHpky9eJb4@/2DcpaGR41Ie1MdPz7/AA "Python 3 – Try It Online") - Python (`import [regex](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)`) [Try it online!](https://tio.run/##RY9BboMwEEWv4lojYcd1BFTtItQiUtc9AbBA1AmWzBiBI6xEbHuAHrEXoRC16urP@5r5mt@7SQ9jq61dYFDFoM86VIcD6okdo4Xlr4oFEThnuSoTFnbb9FCmOQtB8PJJAF@i4yN9c11vrP6gPIOrirOTG3TdtAwsMUjAYH/x/Aa1AivH3hpPJc3MiUG9b9wFvbSepNuCUFAXcTWvAQxQFQZ9dXcyQGn1HycbC7FedAqG/Xvtm1aPLArRDpDfk6/8Ng3Ga9m60c/rV0n2z0SiWztag5pQQPL9@UWAQbe3Gs@@/RVO53mJZfr88gM "PowerShell – Try It Online") - .NET # Regex `🐝` (ECMAScript 2018 or better / Java), 37 bytes ``` (?<=^(xx+))(?=\1(x*))(?!\2?(xx+)\3+$) ``` [Try it online!](https://tio.run/##TY7NToNAFIVfBRuTuVfKBGp0AZ2yctFNF7oUTScwnV4DAw7TlvRn6wP4iL4I0kaT7k7ud@7J9yG3ss0tNS4wdaH6vQgTK56VfuoaeHGWjOZW7pY9pFPxDl3nI0Iqsgi6u3O6ySbp5Zrd@7fYL3lbUq4gGgcRjplmmFj1uSGrgFkli5KMYsjzITs1N07ZlRzqBzLNxsWNrXPVtrx1BZkT8toAu3yMSzE7aFHytinJAQuGXVoBGKF5qYx2a5xNjkdqF3IBJBpp2/M66NfwDfEfqGtgZlEaxWeMbm3r3WhutrKkwrPSaBV7I79MVrWFhKZCJeT7eKjEqBtxq5pBHgh5JV2@BovJlXe9cXxnySmAfcoyw2LG0CefeT9f3x7zoUqrP@U4REz2IjqdsA@DycPjLw "JavaScript (Node.js) – Try It Online") - ECMAScript 2018 **[Try it online!](https://tio.run/##bVLLbtswELznKzZCA5N@MHaK9lCaMNqiBQI0bZEcbRegJcqmQ1EqScVKglz7Af3E/oi7lNVHAOuy3N3RLGe4W3knR9vsdq@LqnQBtpgzXbI@h/8rddDmaM2ptWqwc1LVK6NTSI30Hq6ktvAIXc0HGTDclTqDAjvkJjht1yDd2s@XFMLGlTsPH5pUVUGX@OcJwEdtFOTCql17JAlLy0wx7CeUv6vzXDmVXSuZKQerFva8SP782aU5pbyb64eB7zaRnxAvVqhBZp@0VYTSU2FrY6jOiWfqey2NJ8l5v99PKH18Dj0wEBKOEjwiQ/jLgATnyLBC3C33A9Fb2F6MgT8dak9fZQjKWXCiO6HaoooDPOXoxqosjZIWHkSOjIrDTSqtRenaVnUAAVFtVyM39z6ogmlLOXQ6WxjbSP9ZNQGv2VoM0Bli8O7IcQBZRHQSu/58CQbbEcV8ZXQgyQgfAfEB7Bg7lzbgGjhWSecVJsTMx0s6BDs52mRG2XXYTC9gBhEJbzBMlsiYbqSbL5tOT5vZyZLDW@fkvWe5NoY0w17Ta00ByEsXteE1hB1zsFNhJxgGAxR4JUO6QYcKZHOsOGSk3VyLC/4eyQ8bw3ZOVqQbkZbV/Zf8Wtq1wknjoaW4N2BKdCkVBb60r03whCKwRi3RhZw80M7yEv3bOR0UiU9M@YMIro6v9a9doaMhJ8lZBr9@/ISzLEGfhpBS/oTfSVy2PZlNxTfSNANKyUwsJqTpx9Pp4mLWVhcvBy/oPm7Vfjy6ePX6Nw "Java (JDK) – Try It Online") - Java** [Try it online!](https://tio.run/##JY7BrcIwEETvqWJZ/YNNnCgGwSHBSiEEJKQ4YMnZRI4PhgIo4Jf4G8m34TbaeTOz89M/JtqvZpwn52F5LsLpuw4NOOUQcWXtSV1ZCDnnrFWdZGGb1KbbtZ9rt89/@BrJs6wLeWngpapsmBxYMJT6ysX3huoMrLLlMlvjGRbIM0gQJcjd6K6ZIc/subpw8VWxjOeSxyCYAV41zC4ZMRgnZAOjsprY59lyMNTfrGVOAAbcEk/UlyeBf@9fFKPQ1CtEvlbF7nD8Bw "Python 3 – Try It Online") - Python (`import [regex](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)`) [Try it online!](https://tio.run/##RY/RaoQwEEV/JQ0DJmsjq6V9WBtc6HO/QC2IO7sGYiIxi7KLr/2AfmJ/xKq09Gnuucxc7nR2QNc3qPUMTuYOLziWh4PBgR2DmWWv8oONY8g5y2QRs3G3qociyTa3eAqBz8Hxkb7ZtlMaT5SncJP79GwdVnXDQBNlCCjTXT2/QyVBi77TylNBU3VmUEW1vRovtCfJuhBKqPJ9OS0BDIzMlfHl5qRghMY/jlcOw@WileCi98rXDfYsGIMdGL4l3/h9cMqjaGzvp6VVnP4zEcYuT2plkFAw5PvziwCDNtJoLr75HZxO07wXyfPLDw "PowerShell – Try It Online") - .NET [Answer] # JavaScript (ES6), ~~77~~ ~~73~~ 70 bytes *Saved 3 bytes thanks to @Arnauld* ``` f=(n,x=n)=>--x<2||n%x&&f(n,x) g=(a,b=a>>1)=>b>1?f(b)*f(a-b)+g(a,b-1):0 ``` `f` is a primality-test function; the relevant function is `g`. `f` works by recursively counting down from **n-1**; the control flow at each stage goes like this: * `x<2||` If **x < 2**, the number is prime; return **1**. * `n%x&&` Otherwise if **n mod x = 0**, the number is not prime; return `n%x`. * `f(n,x-1)` Otherwise, the number may or may not be prime; decrement **x** and try again. `g` works in a similar fashion, though with not so much control flow. It works by multiplying **f(b)** by **f(a-b)** for each integer **b** in the range **[2, floor(a/2)]**, then summing the results. This gives us the number of pairs that sum to **a** where both numbers in the pair are prime, which is exactly what we want. [Answer] ## [GAP](http://www.gap-system.org), 57 bytes ``` n->Number([2..QuoInt(n,2)],k->IsPrime(k)and IsPrime(n-k)) ``` I don't think GAP has a shorter way than this obvious one. `Number` counts how many elements of a list satisfy a predicate. Using it to compute the first 100 values: ``` gap> List([1..100],n->Number([2..QuoInt(n,2)],k->IsPrime(k)and IsPrime(n-k))); [ 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 0, 1, 1, 2, 1, 2, 0, 2, 1, 2, 1, 3, 0, 3, 1, 3, 0, 2, 0, 3, 1, 2, 1, 4, 0, 4, 0, 2, 1, 3, 0, 4, 1, 3, 1, 4, 0, 5, 1, 4, 0, 3, 0, 5, 1, 3, 0, 4, 0, 6, 1, 3, 1, 5, 0, 6, 0, 2, 1, 5, 0, 6, 1, 5, 1, 5, 0, 7, 0, 4, 1, 5, 0, 8, 1, 5, 0, 4, 0, 9, 1, 4, 0, 5, 0, 7, 0, 3, 1, 6 ] ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 22 bytes ``` :{,A:B>=.:#pa+?,.=}fl ``` [Try it online!](http://brachylog.tryitonline.net/#code=OnssQTpCPj0uOiNwYSs_LC49fWZsCg&input=MTAw&args=Wg) ### Explanation A straight up transcription of the problem. ``` :{ }f Find all valid outputs of the predicate in brackets for the Input l Output is the number of valid outputs found ,A:B>=. Output = [A, B] with A >= B :#pa Both A and B must be prime numbers +?, The sum of A and B is the Input .= Label A and B as integers that verify those constraints ``` [Answer] # Mathematica, 52 bytes ``` Count[IntegerPartitions[#,{2}]//PrimeQ,{True,True}]& ``` The result is provided as an anonymous function. Try to plot a graph over it: ``` DiscretePlot[ Count[IntegerPartitions[#, {2}] // PrimeQ, {True, True}] &[i], {i, 1, 1000}] ``` [![plot of the sequence](https://i.stack.imgur.com/9A3kT.png)](https://i.stack.imgur.com/9A3kT.png) By the way, the code has the same length with function version of demo code on OEIS. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~10~~ 8 bytes Extremely inefficient. ``` D!f-pO;î ``` [Try it online!](http://05ab1e.tryitonline.net/#code=RCFmLXBPO8Ou&input=OA) or [Try a less efficient way of generating primes](http://05ab1e.tryitonline.net/#code=RExEcMOPLXBPO8Ou&input=OTY) **Explanation** `n = 10` used as example. ``` D # duplicate # STACK: 10, 10 ! # factorial # STACK: 10, 3628800 f # unique prime factors # STACK: 10, [2,3,5,7] - # subtract # STACK: [8,7,5,3] p # is prime # STACK: [0,1,1,1] O # sum # STACK: 3 ; # divide by 2 # STACK: 1.5 î # round up # STACK: 2 # implicit output ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ½~æ-æ∑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIxMDDGmyIsIsK9fsOmLcOm4oiRIiwiO1xcLGoiLCIiXQ==) Includes header and footer to produce first 100 results. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` HRð,_@ÆPð×/S ``` **[TryItOnline](http://jelly.tryitonline.net/#code=SFLDsCxfQMOGUMOww5cvUw&input=&args=MjI)** **[1-100](http://jelly.tryitonline.net/#code=SFLDsCxfQMOGUMOww5cvUwrCs8OH4oKs&input=)** ### How? ``` HRð,_@ÆPð×/S - Main link: n e.g. 22 H - halve R - range [1,2,3,4,5,6,7,8,9,10,11] (note this will be 1 to n//2) ð - dyadic chain separation , - pair with _@ - n - [[1,2,3,4,5,6,7,8,9,10,11],[21,20,19,18,17,16,15,14,13,12,11]] ÆP - is prime? (1 if prime 0 if not) [[0,1,1,0,1,0,1,0,0,0,1],[0,0,1,0,1,0,0,0,1,0,1]] ð - dyadic chain separation ×/ - reduce with multiplication [0,0,1,0,1,0,0,0,0,0,1] S - sum 3 ``` [Answer] ## Racket 219 bytes ``` (let*((pl(for/list((i n) #:when(prime? i))i))(ll(combinations(append pl pl)2))(ol'()))(for/list((i ll))(define tl(sort i >)) (when(and(= n(apply + i))(not(ormap(λ(x)(equal? x tl))ol)))(set! ol(cons tl ol))))(length ol)) ``` Ungolfed: ``` (define(f n) (let* ((pl ; create a list of primes till n (for/list ((i n) #:when (prime? i)) i)) (ll (combinations (append pl pl) 2)) ; get a list of combinations of 2 primes (ol '())) ; initialize output list (for/list ((i ll)) ; test each combination (define tl (sort i >)) (when (and (= n (apply + i)) ; sum is n (not(ormap (lambda(x)(equal? x tl)) ol))) ; not already in list (set! ol (cons tl ol)))) ; if ok, add to list (println ol) ; print list (length ol))) ; print length of list ``` Testing: ``` (f 10) (f 100) ``` Output: ``` '((5 5) (7 3)) 2 '((97 3) (89 11) (83 17) (71 29) (59 41) (53 47)) 6 ``` [Answer] # [Actually](http://github.com/Mego/Seriously), 11 bytes ``` ;R`p`░@-♂bΣ ``` [Try it online!](http://actually.tryitonline.net/#code=O1JgcGDilpFALeKZgmLOow&input=MTA) Explanation: ``` ;R`p`░@-♂bΣ R`p`░ prime values in [1, n] ; @- subtract each value from n ♂b convert each value to boolean Σ sum ``` [Answer] ## Haskell, 73 bytes ``` f n|r<-[a|a<-[2..n],all((<2).gcd a)[2..a-1]]=sum[1|p<-r,q<-r,q<=p,p+q==n] ``` Usage example: `map f [1..25]` -> `[0,0,0,1,1,1,1,1,1,2,0,1,1,2,1,2,0,2,1,2,1,3,0,3,1]`. Direct implementation of the definition: first bind `r` to all primes up to the input number `n`, then take a `1` for all `p` and `q` from `r` where `q<=p` and `p+q==n` and sum them. ]
[Question] [ Write a program or function that takes in a multiline string of `0`'s and `1`'s. No other characters will be in the string and the string will always be rectangular (all lines will have same number of characters), with dimensions as small as 1×1, but otherwise the `0`'s and `1`'s may be arranged arbitrarily. You may assume the string has an optional trailing newline, and if desired you may use any two distinct [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters in place of `0` and `1`. Print or return a [truthy value](http://meta.codegolf.stackexchange.com/a/2194/26997) if ***all* of the [path connected](https://en.wikipedia.org/wiki/Connected_space#Path_connectedness) regions of both `0`'s and `1`'s in the string are *solid rectangles***, else output a [falsy value](http://meta.codegolf.stackexchange.com/a/2194/26997). A *path connected region* of `0`'s means that from any one `0` in the region, all the other `0`'s can be reached by only moving up, down, left and right to other `0`'s (and *not* moving diagonally, *not* moving to any `1`, and *not* moving outside the string bounds). The same idea applies to `1` path connected regions. A *solid rectangle* of `0`'s means the entire area of the rectangle is filled with `0`'s and no `1`'s. The same idea applies to `1` solid rectangles. **The shortest code in bytes wins. Tiebreaker is earlier answer.** (Note that the string does not wrap around with [toroidal boundary conditions](https://en.wikipedia.org/wiki/Periodic_boundary_conditions).) # Examples **1)** This input string has 3 path connected regions (2 for `0` and 1 for `1`). Only the bottom right `00` region is a solid rectangle though, so the output would be falsy. ``` 0011 0111 0100 ``` **2)** This input string has 4 path connected regions (2 for both `0` and `1`). All of them are solid rectangles so the output would be truthy. ``` 0011 0011 1100 ``` **3)** This input has 2 path connected regions, but only one of them is a solid rectangle, so the output would be falsy. ``` 00000000 01111110 00000000 ``` **4)** This input has only 1 path connected region and is trivially a solid rectangle, so the output is truthy. ``` 11111111 11111111 11111111 ``` # Test Cases A `T` just below the input string means truthy, `F` means falsy. ``` 0 T 1 T 00 T 01 T 10 T 11 T 0000000 T 1111111 T 011100100100101100110100100100101010100011100101 T 00 11 T 01 10 T 01 11 F 00 01 F 11 11 T 110 100 F 111 000 T 111 101 111 F 101 010 101 T 1101 0010 1101 0010 T 1101 0010 1111 0010 F 0011 0111 0100 F 0011 0011 1100 T 00000000 01111110 00000000 F 11111111 11111111 11111111 T 0000001111 0000001111 T 0000001111 0000011111 F 0000001111 1000001111 F 1000001111 1000001111 T 1110100110101010110100010111011101000101111 1010100100101010100100010101010101100101000 1110100110010010110101010111010101010101011 1010100100101010010101010110010101001101001 1010110110101010110111110101011101000101111 F ``` [Answer] ## [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṣ⁷^2\⁺€FS¬ ``` Massive thanks to @Dennis for golfing this one down to half its original size (via undocumented features). [Try it online](http://jelly.tryitonline.net/#code=4bmj4oG3XjJc4oG64oKsRlPCrA&input=&args=IiIiMTExMDAKMTExMDAKMDAwMTEKMTExMDAiIiI)! Note that the triple quotes are for a multiline string. ### Explanation The basic algorithm is: return true iff every 2x2 subgrid has an even number of 1s (or, equivalently, 0s). It's clear why an odd number of 1s can't work, since we would have one of the following: ``` 10 01 00 00 01 10 11 11 00 00 01 10 11 11 10 01 ``` Note that the first 4 are rotations of the same thing, and ditto for the last 4. The reflex angle can't be part of a rectangle, hence why it would be invalid. In other words, all 2x2 subgrids must be one of the following: ``` 00 00 11 01 10 01 10 11 00 11 00 01 10 10 01 11 ``` which, if we look at the boundaries, can be imagined as the following "puzzle pieces": ``` ___ ___ ___ ___ | | | | | | | | | | | | | | | |---| |-|-| |___| |_|_| |___| |_|_| ``` And try forming a non-rectangle with those puzzle pieces :) (whilst having the ends match up) The actual implementation is thus: ``` ṣ⁷ Split input by newlines to give rows ^2\ Taking overlapping sets of 2 rows at a time: accumulate rows by XOR Note that strings cast to integers automatically for bitwise operators ⁺€ Repeat the previous link (⁺), on each (€) element in the resulting array F Flatten the array S Sum (effectively reducing by OR) ¬ Logical negation of the result ``` For example, for the input ``` 100 010 000 101 ``` we have: ``` ṣ⁷: ["100", "010", "000", "101"] ^2\: [[1, 1, 0], [0, 1, 0], [1, 0, 1]] (e.g. first entry is "100" ^ "010") ^2\€: [[0, 1], [1, 1], [1, 1]] (e.g. the first entry is [1^1, 1^0] - this gives the counts of 1s in each subgrid, mod 2) F: [0, 1, 1, 1, 1, 1] S: 5 (this gives the number of invalid 2x2 subgrids, which is indeed all but the top left) ¬: 0 ``` [Answer] # Ruby, 76 ``` ->s{j=!r=1 s.lines{|t|i=t.to_i(2) j&&r&&=(j^i)%t.tr(?0,?1).to_i(2)<1 j=i} r} ``` In any grid composed entirely of rectangles, each line must be identical to the line before, or have all bits flipped from 0 to 1 and vice versa. This is easy to prove. Take a piece of paper and draw arbitrary vertical and horizontal lines all the way across it. Now colour the rectangles using only 2 colours. You will end up with a distorted checkerboard, where all the colours flip at each line. Want to draw rectangles with lines only part way across? try deleting a segment of any of your lines. You will now need more than 2 colours to colour your design, because you will have points where 3 rectangles meet (2 corners and an edge.) Such designs are therefore irrelevant to this question. I'm surprised answers so far haven't noticed this. I think this algorithm should be a lot shorter in some other language. **Ungolfed in test program** ``` f=->s{ j=!r=1 #r = truthy, j=falsy s.lines{|t| #for each line i=t.to_i(2) #i = value of current line, converted to a number in base 2 (binary) j&& #if j is truthy (i.e this is not the first line) r&&=(j^i)%t.tr(?0,?1).to_i(2)<1 #XOR i with the previous line. Take the result modulo (current line with all 0 replaced by 1) #if the result of the XOR was all 0 or all 1, the modulo == zero (<1). Otherwise, it will be a positive number. j=i} #j = value of current line (always truthy in ruby, even if zero) r} #return 1 or true if all the modulo calculations were zero, else false. #text to print after test case to check answer is as desired T='T ' F='F ' #test cases puts f['0'],T puts f['1'],T puts f['00 '],T puts f['01'],T puts f['10'],T puts f['11 '],T puts f['0000000'],T puts f['1111111'],T puts f['011100100100101100110100100100101010100011100101'],T puts f['00 11'],T puts f['01 10'],T puts f['01 11'],F puts f['00 01'],F puts f['11 11 '],T puts f['110 100'],F puts f['111 000'],T puts f['111 101 111'],F puts f['101 010 101 '],T puts f['1101 0010 1101 0010'],T puts f['1101 0010 1111 0010'],F puts f['0011 0111 0100 '],F puts f['0011 0011 1100'],T puts f['00000000 01111110 00000000'],F puts f['11111111 11111111 11111111'],T puts f['0000001111 0000001111'],T puts f['0000001111 0000011111'],F puts f['0000001111 1000001111'],F puts f['1000001111 1000001111'],T puts f['1110100110101010110100010111011101000101111 1010100100101010100100010101010101100101000 1110100110010010110101010111010101010101011 1010100100101010010101010110010101001101001 1010110110101010110111110101011101000101111'],F ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṣ⁷µ=ḢZE ``` This uses the same algorithm as [@LevelRiverSt's Ruby answer](https://codegolf.stackexchange.com/a/77157). The actual algorithm fits in the last 4 bytes; the first 3 bytes are required to parse the input format. [Try it online!](http://jelly.tryitonline.net/#code=4bmj4oG3wrU94biiWkU&input=&args=MDAxMQowMDExCjExMDA) ### How it works ``` ṣ⁷µ=ḢZE Main link. Argument: t (string) ṣ⁷ Split t at linefeeds.. µ Begin a new, monadic link. Argument: A (list of strings) Ḣ Pop the first string of A. = Compare all other strings in A with the first. = compares characters, so this yields a list of Booleans for each string. For a truthy input, all pairs of lines now have been transformed in lists of only 1's or only 0's. That means all columns must be equal. Z Zip; transpose rows with columns. E Check if all rows (former columns) are equal to each other. ``` [Answer] # [Snails](https://github.com/feresum/PMA), 20 bytes ``` !{to{\0w`3\1|\1w`3\0 ``` Prints the area of the grid if there isn't a 2x2 square with 3 zeroes and a one or 3 ones and a zero, or `0` if such a 2x2 square exists. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 12 bytes ``` Ybc2thYCs2\~ ``` Same algorithm as [@sp3000's great answer](https://codegolf.stackexchange.com/a/77141/36398). To allow multiline input, MATL needs the row char array (string) to be explicitly built using character `10` for newline. So the input of the four examples are (note that `[]` is concatenation, so each of these is a row array of chars): ``` ['0011' 10 '0111' 10 '0100'] ['0011' 10 '0011' 10 '1100'] ['00000000' 10 '01111110' 10 '00000000'] ['11111111' 10 '11111111' 10 '11111111'] ``` and the last three test cases are ``` ['0000001111' 10 '1000001111'] ['1000001111' 10 '1000001111'] ['1110100110101010110100010111011101000101111' 10 '1010100100101010100100010101010101100101000' 10 '1110100110010010110101010111010101010101011' 10 '1010100100101010010101010110010101001101001' 10 '1010110110101010110111110101011101000101111'] ``` Truthy output is an array containing only ones. [**Try it online!**](http://matl.tryitonline.net/#code=WWJjMnRoWUNzMlx-&input=WycwMDAwMDAwMCcgMTAgJzAxMTExMTEwJyAxMCAnMDAwMDAwMDAnXQ) ### Explanation This uses the fact that the parity of chars `'0'` and `'1'` is the same as that of numbers `0` and `1`, so there's not need to convert from char to the digit it represents, ``` Yb % split implicit input by whitespace. Gives a cell array c % concatenate cell contents into 2D char array 2th % push array [2 2] YC % get 2×2 sliding blocks and arrange as columns s % sum of each column 2\ % modulo 2 of each sum ~ % negate. Implicit display ``` [Answer] ## JavaScript (ES6), 69 bytes ``` s=>!s.split` `.some((t,i,u)=>[...t].some((v,j)=>v^t[0]^u[0][j]^s[0])) ``` I believe that the path connectedness rectangle criterion is equivalent to requiring that given any four points that form the corners of an arbitrary rectangle that there is an even number of `1`s. Note that the parity of the rectangle (0, b), (x, y) is the same as (0, b), (a, y) `^` (a, b), (x, y) so I only have to check those rectangles whose top left corner is at (0, 0). Also by De Morgan's laws, `!.some()` is the same as `.every(!)` which saves me a couple of bytes. Edit: I notice that the Jelly solution checks the parity of the corners of all 2×2 rectangles, which can be shown to be equivalent. [Answer] # JavaScript (ES6), 79 Same algorithm of Jelly answer from @Sp3000 (and happy not having to prove it works). Just *8 times* longer ``` s=>[...s].every((x,i)=>[++i,i+=s.search` `,i+1].some(p=>!(x^=p=s[p],p>` `))|!x) ``` *Less golfed* ``` s=>[...s].every((x,i)=> // repeat check for every sub square [++i, // array of position for next char in row i+=s.search`\n`, i+1] // and 2 chars at same column in next row .some(p=> // for each position !( x^=s[p], // xor current value with value at position p s[p]>`\n` // true if value at position p is valid ) // the condition is negated ) // if any value scanned is not valid, .some return true // else, we must consider the check for current square | !x // x can be 0 or 1, to be valid must be 0 ) ``` **Test suite** ``` f=s=>[...s].every((x,i)=>[++i,i+=s.search` `,i+1].some(p=>!(x^=p=s[p],p>` `))|!x) testData=` 0 T 1 T 00 T 01 T 10 T 11 T 0000000 T 1111111 T 011100100100101100110100100100101010100011100101 T 00 11 T 01 10 T 01 11 F 00 01 F 11 11 T 110 100 F 111 000 T 111 101 111 F 101 010 101 T 1101 0010 1101 0010 T 1101 0010 1111 0010 F 0011 0111 0100 F 0011 0011 1100 T 00000000 01111110 00000000 F 11111111 11111111 11111111 T 0000001111 0000001111 T 0000001111 0000011111 F 0000001111 1000001111 F 1000001111 1000001111 T 1110100110101010110100010111011101000101111 1010100100101010100100010101010101100101000 1110100110010010110101010111010101010101011 1010100100101010010101010110010101001101001 1010110110101010110111110101011101000101111 F` console.log=x=>O.textContent+=x+'\n' testData.split('\n\n').forEach(t=>{ var k=t.slice(-1)=='T', r=f(t.slice(0,-1)) console.log(t+' '+r+ (k==r?' OK\n':' KO\n')) }) ``` ``` <pre id=O></pre> ``` [Answer] ## [Grime](https://github.com/iatorm/grime/tree/v0.1) v0.1, 31 bytes ``` E=\0+|\1+ N=.+&E! e`(E/N|N/E)#! ``` Prints `1` for match and `0` for no match. [Try it online!](http://grime.tryitonline.net/#code=RT1cMCt8XDErCk49LismRSEKZWAoRS9OfE4vRSkjIQ&input=MDAxMTEwCjAwMTExMAoxMTAwMDE) ## Explanation Grime is my 2D pattern matching language. I did modify it today, but only to change the character of a syntax element (``` instead of `,`), so it doesn't affect my score. I'm using a similar approach to that of [Sp3000](https://codegolf.stackexchange.com/a/77141/32014): an input is falsy if it contains a 2×N rectangle whose one row contains both `0` and `1`, and the other row does not. ``` E= Define a nonterminal E, which matches \0+| a horizontal run of one or more 0s, OR \1+ a horizontal run of one or more 1s. N= Define a nonterminal N, which matches .+ a horizontal run of one or more characters, &E! which is NOT matched by E (so contains both 0 and 1). e` Match entire input to this pattern: ! not # contains (E/N|N/E) E on top of N, or N on top of E ``` [Answer] # JavaScript (ES6), 64 bytes ``` s=>(a=s.split` `).every(l=>l==a[0]|l==a[0].replace(/./g,n=>n^1)) ``` Based on @LevelRiverSt's observation that each line must either be the same or the opposite of the first. ]
[Question] [ In this challenge, you're given a list of overlapping waves. Each wave is a finite list with `n` truthy values, then `n` falsy values, then `n` truthy and so on, where `n` is the wavelength (or half the wavelength I guess, but it really doesn't matter in this challenge). The values of a wave may have an offset, so a wave of wavelength 3 could be something like `001110001110001`. The overlapping waves all have the same length, and the result of an overlap is the exclusive or operator applied to both other waves. Applying the exclusive or operator to more than two booleans returns true if and only if the number of truthy values is odd. Example: ``` 1000111000111 + 0101010101010 + 0001111000011 = 1100010101110 ``` The values of a list without any waves are all falsy. Your task is to create a program or function that, given a list of truthy and falsy values, returns the smallest number of waves that can be used to create that list. ## Test cases ``` 101010101 = 101010101 -> 1 wave 10100001 = 10011001 + 00111000 -> 2 waves 110101110 = 001100110 + 111000111 + 000001111 -> 3 waves 00100101011011100100 = 10101010101010101010 + 10001110001110001110 + 00000001111111000000 -> 3 waves 1 = (any wave) -> 1 wave 0 = (any or no wave(s)) -> 0 waves (empty list of booleans) = (any or no wave(s)) -> 0 waves ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission in bytes wins! [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~41~~ 39 bytes ``` K]QWshK=hZ=KSmxMCd*Ksm.:*lQS*hdU2lQlQ;Z ``` [Try it online!](https://tio.run/##K6gsyfj/3zs2MLw4w9s2I8rWOzi3wtc5Rcu7OFfPSisnMFgrIyXUKCcwJ9A66v//aEMdAx0QhkDDWAA "Pyth – Try It Online") ### Explanation ``` # implicitly assign Q = eval(input()) K]Q # assign K to a list containing Q WshK # while the first element of K is not all zeros =hZ # increment Z (which is auto-initialized to 0) =K # assign K to *K # cartesian product of K and sm.:*lQS*hdU2lQlQ # all possible waves mxMCd # xor'ed together S # sort so the all zeros element will be at the start if present ;Z # outside of loop, print Z ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~40~~ 37 bytes ``` ⊞υSWΣ⌊υ«≔ΣEυΣEκE⊗⊕ν⭆κ﹪⁺Iρ÷⁻ςξ⊕ν²υ→»Iⅈ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VU8xjsJADKzJK1apbClIhOp0VAgaCqToaJDQFSFZktVtdlF2HZAQL6GhuNPxJX7AM3AIFLixPbbHM6dLVqZ1ZlN9Pv-R3_Q_rreEXAkUiZnZkl_4WpkCEEfBrlRaClhQBXNlVMWZEFEcgt7YOVWYbpRu2-NX-ROJNk0trbXMYWayWlbSeK4NIu89-F-bNidtIdHkYJI6DzW2MvxUNSqX7VceNJHYP-A3JkaG2EUkiNX25raR8PmlitJzewwSfuQ72iX7wdGvW2fu6fp_FfYbHX5f4kE84Ig7-A4) Link is to verbose version of code. Explanation: ``` ⊞υS ``` Start with the input string. ``` WΣ⌊υ« ``` Repeat until the input has been cancelled by the waves. ``` ≔ΣEυΣEκE⊗⊕ν⭆κ﹪⁺Iρ÷⁻ςξ⊕ν²υ ``` Calculate the effect of at least all possible single waves on all of the waves calculated so far, and collect all of the results. (The code is pathological and generates far too many duplicates but it would cost too many bytes to uniquify them.) ``` → ``` Increment the count of waves, using the X-position to keep track. ``` »Iⅈ ``` Output the final count. [Answer] # [Python 2](https://docs.python.org/2/), 141 bytes ``` lambda s:g([int("0"+s,2)],len(s)) g=lambda l,n:min(l)and-~g([x^(1<<n+j)/-~(1<<i)%(1<<n)for i in range(1,n+1)for j in range(i*2)for x in l],n) ``` [Try it online!](https://tio.run/##ZY5NCoMwEIX3niIECpkaaeJS9CTWQoo/jcRR1IXdePU0CaWtdGYWbz7ePGZ6ro8RU9sWV2vUcK8VWbKOlRpXRgWNF55CxU2DbAGIuuLtMRyzQSMzoLBOdnew3ZjMc4x7uCS7lxpOgUA7zkQTjWRW2DVMcoxlgP0X6nMa0OaRqTiCnWb3A2kZpRB9tPhd5GERUrj6Y6EPEd4YqJ@gXap9AQ "Python 2 – Try It Online") Link includes test cases. Explanation: Uses bit-twiddling to calculate the effect of at least all possible single waves on the input, recursing until a set of waves that cancels the input wave out is found. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` āεÅ1D_«Ig·∍ŒIgù}€`æé.ΔIš.«^O_}g ``` Input as a list. Brute-force, and extremely slow (times out for test cases of length \$n>4\$). [Try it online](https://tio.run/##AUAAv/9vc2FiaWX//8SBzrXDhTFEX8KrSWfCt@KIjcWSSWfDuX3igqxgw6bDqS7OlEnFoS7Cq15PX31n//9bMCwxLDFd) or [verify most lists of lengths 0 to 4..](https://tio.run/##AVEArv9vc2FiaWX/NMaSMcOdTsOjdnk/IiDihpIgIj95RFX/xIHOtcOFMURfwqtYZ8K34oiNxZJYZ8O5feKCrGDDpsOpLs6UWMWhLsKrXk9ffWf/LP8) **Original 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:** (which doesn't time out for the test cases..) ``` OĀiāεÅ1D_«Ig·∍ŒIgù}€`[¼D¾ãÅΔ.«^IQ}d#]¾ ``` Input as a list. Brute-force, and also pretty slow (but it's able to complete all test cases at once nonetheless). [Try it online](https://tio.run/##yy9OTMpM/f/f/0hD5pHGc1sPtxq6xB9a7Zl@aPujjt6jkzzTD@@sfdS0JiH60B6XQ/sOLz7cem6K3qHVcZ6BtSnKsYf2/f8fbahjqGMAhoZwDBaLBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeXhCaFK//2PNGQeaTy39XCroUv8odUR6Ye2P@roPTopIv3wztpHTWsSog/tcTm07/Diw63npugdWh0XEVibohx7aN9/Jb0wHb1DW/9HRxvqGOoYgKEhHIPFYnWiDVFEgRhJDKoHLIJFJxCDaBAF14CsDK4YJgtWCRSJjQUA). **Explanation:** ``` āεÅ1D_«Ig·∍ŒIgù}€` # Generate a list of all valid waves of the input-length: ā # Push a list in the range [1, (implicit) input-length] ε # Map over each of those integers Å1 # Convert the integer to a list of that many 1s D_« # Merge an inverted copy (that many 0s) Ig # Push the input-length · # Double it ∍ # Extend the list of 1s/0s to that list's length Œ # Get all sublists of this list Igù # Only keep all sublists of a length equal to the input-list }€` # After the map: flatten it one level down æ # Get the powerset of this list of lists é # Sort it by length .Δ # Find the first that's truthy for: Iš # Prepend the input-list to the list of lists .« # Reduce the list of lists by: ^ # Vectorized bitwise-XOR the values in the lists together O # Then check if the sum of the resulting list _ # is equal to 0 }g # After the find_first loop: pop and push the length of the found # list of lists # (which is output implicitly as result) ``` ``` OĀi # If the sum of the (implicit) input-list is NOT 0: āεÅ1D_«Ig·∍ŒIgù}€` # Generate a list of all valid waves same as above [ # Start an infinite loop: ¼ # Increase the counter variable `¾` by 1 (0 by default) D # Duplicate the current list of lists ¾ã # Get the `¾` cartesian power, to create all possible `¾`-sized # tuples of the list of lists ÅΔ # Pop and get the first index that's truthy for, # or -1 if none are truthy: .« # Reduce the current list of lists by: ^ # Vectorized bitwise-XOR the values in the lists together IQ # Check if this list is equal to the input-list }d # Check if the found index is non-negative (aka NOT -1) # # If it is: stop the infinite loop ] # Close both the infinite loop and if-statement ¾ # Push the counter variable # (which is output implicitly as result) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~26~~ 22 bytes ``` a:[λ?żD›v+$Ẋvƒḭ↔Ṡ∷?c;Ṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJhOlvOuz/FvETigLp2KyThuop2xpLhuK3ihpThuaDiiLc/YzvhuYQiLCIiLCJbMF0iXQ==) Surprisingly it only times out for the longest test case despite using a brute force method. ``` a:[ # if the input doesn't contain a 1 return 0 λ ;Ṅ # find the first n where the following is truthy: ?żD›v+$Ẋvƒḭ # get all waves as lists of numbers where odd numbers represent 1 and even 0 ?ż # range [1, len(input)] D # triplicate › # increment v+ # addition vectorised over the left operand $ # swap top two items on the stack Ẋ # cartesian product vƒḭ # reduce each by integer division ↔ # all combinations with replacement of length n Ṡ # vectorising sum ∷ # mod 2 ?c # does it contain input? ``` [Answer] # [Haskell](https://www.haskell.org), ~~177~~ 161 bytes *-16 bytes thanks to [@Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)* ``` (#)=replicate f n|l<-length n=until(\x->any((==n).foldl(zipWith$(fromEnum.).(/=))(l#0))$sequence(x#[take l$drop o$(k#)=<<cycle[0,1]|k<-[1..l],o<-[1..2*k]]))(+1)0 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVGxboMwEFVXf8UpYTi3QCFdqgiydajUrZU6EA8WMcHCGApGClX-pEs6VP2m9mtqIKkSW7LevffufPZ9fOe8LYRSh8NXZzLv_ucT5zRuRK1kyo0gGei9ijwl9NbkoONOG6lwvfNWXPeIcaypn1Vqo_Bd1q_S5A5mTVU-6K70qY-3MaWo5gGlTiveOqFTgbt5YnghQDmbpqqhcrCwV0ZR2qdKJIEbsn0ReUno-4q51YQW1wVjttRNSIOp0d8raE0j9falepKtgeUSnscYvBUkj9owcqHHUPIacJ0OeiP4BpKUUUKMaE1r1YQA4CwMjnvmQkjdf86ugVqcqNFjT8vdHblgsE38KA3hmXxeceCDIx4hI6QfesAMnMtnSRcqCnvACUQejA0zUnKpbUptvcYmcaUAO512TdODHQul0E8fdZrsHw) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ...but Golf-SlowTM! :) ``` LḤ+€J:ⱮJẎḂŒPḊ^/⁼¥Ƈ⁸ẈṂ×Ṁ ``` A monadic Link that accepts a, potentially empty, list of zeros and ones and yields the minimal number of waves required. Don't [Try it online!](https://tio.run/##AUwAs/9qZWxsef//SlLhuaA7wqzhuZlKJMay4oKs4bqO4bmB4oKs4oG4xZJQ4biKXi/igbzCpcaH4oG44bqI4bmCw5fhuYD///9bMCwxLDFd "Jelly – Try It Online") it will time out even at length three! Modifying a little will allow length four [TIO](https://tio.run/##AUMAvP9qZWxsef//Sl/isa5M4oCYJDrisa5K4bqO4biCxZJQ4biKXi/igbzCpcaH4oG44bqI4bmCw5fhuYD///9bMCwxLDFd) (considers a window of only one greater than the length rather than double the length and also deduplicate the waves prior to getting the powerset). It would, however, take many more bytes to make this memoised and recursive! ### How Builds a set of "sea-position" lists that cover having position zero at every index of the input and another that would have zero at one end if extended by one (the code produces more than required). Integer divide the results by each of one through to the length of the list and modulo each result by two to get all possible single waves that could cover the input (with repeats). Take the powerset to get all combinations of waves. Filter these sets to those that become the input when reduced with a vectorising XOR. Get the minimum length of the remaining sets. Handle empty and all-zero input lists by multiplying the result by the maximum value in the input or zero if there are none. ``` LḤ+€J:ⱮJẎḂŒPḊ^/⁼¥Ƈ⁸ẈṂ×Ṁ - Link: list, A L - length (A) Ḥ - double J - range of length (A) € - for each (i in [1..2*length(A)]): + - (i) add (range of length (A)) (vectorises) J - range of length (A) Ɱ - map with: : - integer division (vectorises) Ẏ - tighten -> all waves (with loads of duplicates :p) Ḃ - modulo two (vectorises) ŒP - powerset Ḋ - dequeue -- since we cannot reduce an empty list ⁸ - chain's left argument -> A Ƈ - filter (the dequeued powerset) keeping those for which: ¥ - last two links as a dyad - f(set of waves, A): / - reduce (the set of waves) by: ^ - logical XOR (vectorises) ⁼ - equals (A)? Ẉ - length of each Ṃ - minimium Ṁ - maximum (A) -- given an empty list Ṁ yields zero × - multiply -- this forces the `1` to a `0` when A=[] or is all zeros ``` [Answer] # JavaScript (ES6), 119 bytes ``` f=(a,n=0)=>(F=(a,k=n)=>a.join``<1||k--&&a.some((_,n)=>(g=o=>o--&&g(o)||F(a.map(v=>v^o++/n&1),k))(++n*2)))(a)?n:f(a,n+1) ``` [Try it online!](https://tio.run/##lY/NDoIwEITvPgUnsmsLtHozFm@@hPGnQSCKdo0YTrw7Uox/qKjbbDLJ5JvZbnWh8@i4OZw8Q@u4qhIFmhslUIUwtTpTptba39LGrFZjWZaZ57mu9nPaxwBLbm1IFamQrJECYVlOQft7fYBChcWCGAuMK5FniMCY6Q@wFhonZpTYNiaxisjktIv9HaWQwExywZ92jui8nyBwZO8DfnkdcIMPXvF7d6M724dtXNzaH2NuYVfXhr7DO8/9/nfxFy7a@O90g1dn "JavaScript (Node.js) – Try It Online") ]
[Question] [ There exists a bijection between the natural and rational numbers that works (approximately) like this: 1. You create a 1-indexed 2-dimensional grid. 2. In every field of this grid with position `(x, y)`, put the number `x / y`. 3. You start at `(1,1)` and iterate over the field in the following way: [![Bijection](https://i.stack.imgur.com/l1bCZ.png)](https://i.stack.imgur.com/l1bCZ.png) However, this task is not about outputting rational numbers, but about following this pattern in a finite rectangle. This algorithm is best described by an image, but can also be described using words (0-indexing is used this time): 1. Start at `(0,0)`. 2. Go one field down, if in bounds, else right. 3. Go one field to the right and one up (in one step), if in bounds, else go to step 5. 4. Repeat step 3. 5. Go one field to the right, if in bounds, else down. 6. Go one field to the left and one down (in one step), if in bounds, else go to step 2. 7. Repeat step 6 until you reach an edge. 8. Go to step 2. If at any point you encounter the bottom right field, stop. ## Task Given a rectangle defined by two positive integers `w` and `h` (for **w**idth and **h**eight), output all points `(x, y)` on the rectangle in the order in which the above algorithm visits them. * You must handle the possibility of `w` and `h` being equal to zero. * The points can be 1- or 0-indexed. * The first step must be downwards, not right. * You can use any ordered sequence format as the return value. * The length of the output sequence must always be `w * h`. * The first and last element will always be `(0,0)` (or `(1,1)` one-indexed) and `(w-1, h-1)` (or `(w,h)`), respectively. * Standard input / output rules apply. * Standard loopholes are forbidden. ## Example 1 `w = 5`, `h = 3` [![Visual depiction of the algorithm](https://i.stack.imgur.com/mpAch.png)](https://i.stack.imgur.com/mpAch.png) In this case, you should thus output: ``` 0,0 0,1 1,0 2,0 1,1 0,2 1,2 2,1 3,0 4,0 3,1 2,2 3,2 4,1 4,2 ``` ## Example 2 `w = 4`, `h = 7` [![isu](https://i.stack.imgur.com/SDYIE.png)](https://i.stack.imgur.com/SDYIE.png) Following the red line, the expected output is: ``` 0,0 0,1 1,0 2,0 1,1 0,2 0,3 1,2 2,1 3,0 3,1 2,2 1,3 0,4 0,5 1,4 2,3 3,2 3,3 2,4 1,5 0,6 1,6 2,5 3,4 3,5 2,6 3,6 ``` ## Test cases (zero-indexed) | Input | Output | | --- | --- | | `w=0`, `h=0` | `[]` | | `w=0`, `h=123` | `[]` | | `w=123`, `h=0` | `[]` | | `w=1`, `h=1` | `[(0,0)]` | | `w=2`, `h=2` | `[(0,0), (0,1), (1,0), (1,1)]` | | `w=10`, `h=1` | `[(0,0), (1,0), (2,0), (3,0), (4,0), (5,0), (6,0), (7,0), (8,0), (9,0)]` | | `w=1`, `h=10` | `[(0,0), (0,1), (0,2), (0,3), (0,4), (0,5), (0,6), (0,7), (0,8), (0,9)]` | | `w=3`, `h=3` | `[(0,0), (0,1), (1,0), (2,0), (1,1), (0,2), (1,2), (2,1), (2,2)]` | | `w=4`, `h=4` | `[(0,0), (0,1), (1,0), (2,0), (1,1), (0,2), (0,3), (1,2), (2,1), (3,0), (3,1), (2,2), (1,3), (2,3), (3,2), (3,3)]` | | `w=4`, `h=7` | `[(0,0), (0,1), (1,0), (2,0), (1,1), (0,2), (0,3), (1,2), (2,1), (3,0), (3,1), (2,2), (1,3), (0,4), (0,5), (1,4), (2,3), (3,2), (3,3), (2,4), (1,5), (0,6), (1,6), (2,5), (3,4), (3,5), (2,6), (3,6)]` | | `w=5`, `h=3` | `[(0,0), (0,1), (1,0), (2,0), (1,1), (0,2), (1,2), (2,1), (3,0), (4,0), (3,1), (2,2), (3,2), (4,1), (4,2)]` | This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest output (measured in bytes) wins. [Answer] # [J](http://jsoftware.com/), 18 15 bytes ``` #:&;<@|.`</.@i. ``` [Try it online!](https://tio.run/##bY6xCsIwEIb3PMVfFWOhjU0iQs4WCoKTk7tQkBYVRAcXwXePlzbqoJAc4bvvz93Zu4T0fpmQk1KMlOxQESQyFCC@ucJ6t934MU1XZf1UTTlX9Un5VLSX2/2BSrFkMAGnRXs4XjHwnNBxp/jDtLE/lNnbnWXEuTRy6EgX/RTuIHwBPkUoOooGJoruIwZP9@t9XzqYQ41JC@tf "J – Try It Online") Very similar to [Gareth's answer in Zigzagify a matrix](https://codegolf.stackexchange.com/a/75594/15469). This is the standard J approach for these types of problems, and all I do here is combine it with self-indexing. Consider `3 3`: * `i.` Create the matrix: ``` 0 1 2 3 4 5 6 7 8 ``` * `<@|.`</.` For each diagonal, alternate reverse-and-box and box. This is the heart of the logic: ``` ┌─┬───┬─────┬───┬─┐ │0│1 3│6 4 2│5 7│8│ └─┴───┴─────┴───┴─┘ ``` * `#:&;` Unbox and convert each number to mixed-base `3 3` -- this gives each number's self-index within the original matrix: ``` 0 0 0 1 1 0 2 0 1 1 0 2 1 2 2 1 2 2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` pS;ị¥$Þ ``` A dyadic Link that accepts \$w\$ on the left and \$h\$ on the right and yields the path as a list of 1-indexed coordinates. **[Try it online!](https://tio.run/##y0rNyan8/78g2Prh7u5DS1UOz/v//7/pf2MA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/78g2Prh7u5DS1UOz/uvc3i5/qOGmSpHJz3cOeNR05qsRw1zFGztFB41zNXMetS479C2Q9v@/4@ONtBRMIjl0gHRhkbGIBaQgooZAsVAtJGOghGYbwAVAEmAVQBVgvWY6CiYQGlzEG0KFo8FAA "Jelly – Try It Online") (converts the output to 0-indexing). ### How? Each anti-diagonal consists of the maximal subset of coordinates that have the same sum. The path traverses these anti-diagonals in this coordinate-sum order. Those with odd sums are traversed in row order, while those with even sums are traversed in column order. (This is all true regardless of whether 0 or 1 indexing is employed.) ``` pS;ị¥$Þ - Link: integer, w; integer h p - ([1..w]) Cartesian product ([1..h]) -> coordinates Þ - sort by: $ - last two links as a monad - f([r, c]): S - sum ([r, c]) -> r+c = #diagonal ¥ - last two links as a dyad -f (#diagonal, [r, c]): ị - (#diagonal) index into ([r, c]) - 1-based and modular -> r if #diagonal is odd; c otherwise ; - (#diagonal) concatenate (that) ``` [Answer] # [Haskell](https://www.haskell.org), 65 bytes ``` w#h=[[n-m,m]|n<-[0..w+h],m<-cycle[id,(n-)]!!n<$>[0..n],n-m<w,m<h] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWNx3LlTNso6PzdHN1cmNr8mx0ow309Mq1M2J1cm10kyuTc1KjM1N0NPJ0NWMVFfNsVOxA8nmxOkANNuVANRmxEIO25CZm5inYKhQUZeaVKKgomCgoK5hDpGB2AQA) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~66 64~~ 61 bytes ``` ->w,h{[*1..w].product([*1..h]).sort_by{|a|[q=a.sum,a[~q%2]]}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165cJ6M6WstQT688Vq@gKD@lNLlEA8zPiNXUK84vKolPqqyuSayJLrRN1CsuzdVJjK4rVDWKja2t/V@gkBZtomMU@x8A "Ruby – Try It Online") ### How it works: First, create the set of coordinates from the cartesian product of X and Y, then sort by sum and then by ascending or descending X alternatively. [Answer] # [JavaScript (V8)](https://v8.dev/), 73 bytes Expects `(w)(h)`. Prints the coordinates. ``` w=>h=>{for(i=j=0;~j||(j=++i)<w+h;j--)i-(x=i&1?i-j:j)<h&x<w&&print(x,i-x)} ``` [Try it online!](https://tio.run/##LY7BCoMwEETvfsUeiiSYFLWWluraU79CBEWQJIdWrBhB7a/bJHp6szOzMKoe62/Ty27g431rcdOYC8zn9tMTiQrD9KeWhSgMAkkzHYhUcU4lJxNKP3pKrh6KZsKfMu37XS/fA5mY5BNdt7SAImQQlswxii9WGRxeZDzLmEHs7vAwbOAapul@EgbJwZvl1fpQemez8lU3gpBCMxAlBcxh9gD2IZXG06xXkxiKtaKpiVqiKRFO7i0jV7r9AQ "JavaScript (V8) – Try It Online") ### How? We walk through the upper-left diagonals of a square of width \$w+h\$, going alternately from top-right to bottom-left and the other way around. We print only the coordinates that are within the target rectangle. Below is an example for \$w=3\$ and \$h=2\$: [![example](https://i.stack.imgur.com/iTXFo.png)](https://i.stack.imgur.com/iTXFo.png) **NB**: Processing the longest diagonal never brings any new cell. It's just golfier to include it. [Answer] # [sclin](https://github.com/molarmanful/sclin), 46 bytes ``` O>a Q*"_`"map"+/"group""sort"rev2% \_` &#"mapf ``` [Try it here!](https://replit.com/@molarmanful/try-sclin) Takes input as list `[ h w ]`. For testing purposes: ``` [3 5] ; \>A map f>o O>a Q*"_`"map"+/"group""sort"rev2% \_` &#"mapf ``` ## Explanation Prettified code: ``` O>a Q* \_` map \+/ group () sort ( rev 2% \_` &# ) mapf ``` Assuming input [ *h* *w* ]. * `O>a` vectorized range over [ *h* *w* ] * `Q* \_` map` Cartesian product and reverse each generated pair to get properly ordered matrix coordinates * `\+/ group () sort` group pairs by sum and sort by sum + this creates a nicely ordered set of diagonals * `( rev 2% \_` &# ) mapf` reverse every odd (0-indexed) diagonal and flatten into a list of pairs [Answer] # [Alchemist](https://github.com/bforte/Alchemist), 145 bytes ``` _->In_r+In_d+s s+r+d->z z+0m->z+m+Out_l+Out_","+Out_u+Out_"\n" 0b+m+l+d->r+u 0b+m+0l+d->b+u 0b+m+r+0d->b+l b+m+r+u->b+l+d b+m+r+0u->l b+m+0r+d->u ``` [Try it online!](https://tio.run/##Nc2xCoUwDAXQPZ/R9SoEHq7uTv6AUNQKCq1DaxZ/vtbUt9zLIQmZ/bpv4UhXzrbth9NGlHBIlBDh2v6mGxxKI2CUy3pN0xhtqZpOQ7yUDf@eREgVK5c/I1jpqUoUcB@5uI5YP0vOHf0e "Alchemist – Try It Online") After the first two iterations, the atoms are a direct representation of the current state of the traversal. `_`: starting atom `s`: needed to initialize `r` and `d` properly `z`: initialization complete `u`, `d`, `l`, `r`: number of tiles away from top/bottom/left/right boundary `m`: should move next iteration (otherwise output coordinates) `b`: current direction is up+right. There was a complementary `a` atom, but removing it saved 5 bytes. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes ``` NθFNFθ⊞υ⟦⁺ικ§⟦ικ⟧⁺ικκι⟧≔⟦⟧ηW⁻υη⊞η⌊ιIEη✂ι² ``` [Try it online!](https://tio.run/##TYw9D4IwFEV3f8UbX5O6aJyYiBMDhsSRMFSs9oVSoB/qv68PY6J3u@fc3N4o30/K5ly5OcVTGi/a4yKKzW3ygP9QCPiwRUCTgsEkoW1sCkgSBiGhjJW76he2a@8k/BzLQQJ1/FqGQHeHLXvD9WnIasCaHG/Tyr7nRgJDGtOIJHjYeHIRjypErNW86rOlXq//O8Epcj7APm8f9g0 "Charcoal – Try It Online") Link is to verbose version of code. Port of @JonathanAllen's Jelly answer. Explanation: ``` NθFNFθ⊞υ⟦⁺ικ§⟦ικ⟧⁺ικκι⟧ ``` Generate a list of coordinates and their sort order. ``` ≔⟦⟧ηW⁻υη⊞η⌊ι ``` Sort them. ``` IEη✂ι² ``` Output just the coordinates. 38 bytes using the newer version of Charcoal on ATO: ``` Nθ≔ΣENEθ⟦⁺ιλ§⟦ιλ⟧⁺ιλλι⟧ηW⁻ηυ⊞υ⌊ιIEυ✂ι² ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY-xCsJADIZ3nyJ0ysF1UQTBqTh1qBQ6lg61Vi9wPbV3p76LS0FF38Bn8W1MVdAt-b_wJTndK1W21abUXXf1bhVOno_YbL2b-2ZRt7gT00FkLa0NZr7BpNziPxYS-mgnIU-1t0gSNGeRi82yPmLe94WEH2OoJVAh-kqx_KBI14AJGR5RErwQkHqr0LOaDDW8lQQPpi0Zh7PSuvcVjDNNVd1rh2wT04tdVPb7xC0Pwr0OivMYRp_kBQ "Charcoal – Attempt This Online") Link is to verbose version of code. I also tried a canvas-walking approach but that weighed in at a massive 69 bytes: ``` UONN*≔⁵θ⊞υ⟦ⅈⅉ⟧W№KM*«≔⊟Φ⟦⁻⁶÷׳⊖θ²÷׳⊖θ²θ⟧℅⌊KD²✳κι✳ιψ⊞υ⟦ⅈⅉ⟧¿⁻ιθ≦⁻⁶θ»⎚Iυ ``` [Try it online!](https://tio.run/##jVDLTsMwEDwnX2H1tEbm0qq99IQSISERmgMHUNWDm2ybVR079aMIIb49OAkPCXHAt/HszuxM1UhbGan6frNXRh/hTnfBP4R2jxa4YL/g7GrG1@mNc3TUsBTsHFEZXANBsO3TMPEMfBc/XxpSyCAzQXsoEU@FMRa/JDh7S5NPldJ0cEvKR4NtQTo4WA22PqcL1QiP1KKDhWA5VhZb1B5rOPMoNOf8v4Px0J1gG1uTlgqiC7WhHc/KyWLlyWiYx81vcOLjE4xilqS0FFP8sBSJ15H4K3pCBwZTEhoa4qyQ3RT2Hg9@ogRbTe29p5lCGcuNRY42mXQeAufrvl@yRX99UR8 "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ý€¨`âΣODyRsè‚ ``` Input as a pair `[w,h]`. Uses 0-based output. Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/254378/52210), so make sure to upvote him as well! Unfortunately, this approach doesn't port too well to 05AB1E, since it's almost double the byte-count of his answer.. :/ [Try it online](https://tio.run/##ASUA2v9vc2FiaWX//8Od4oKswqhgw6LOo09EeVJzw6jigJr//1s0LDdd) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VT@Pzz3UdOaQysSDi86t9jfpTKo@PCKRw2z/tfqHNpm/z862kDHIFYHSBoaGQNpIAnmG@oYAkkjHSMQ2wDMAQqBZIx1QOpMdEzApDmQNAWKxAIA). **Explanation:** ``` Ý # Convert the values in the (implicit) input-pair to a list in the range [0,v] €¨ # Remove the last value from each to make the ranges [0,v) # (note: we can't use `L` instead of `Ý€¨` for a [1,v]-ranged list, since it # would result in [1,0] for input 0) ` # Pop and push both lists separated to the stack â # Take the cartesian product of the two list, creating pairs Σ # Sort these pairs by: O # Take the sum of the pair D # Duplicate this sum y # Push the pair again R # Reverse it (necessary, since 05AB1E uses 0-based indexing instead of 1-based) s # Swap so one of the sums is at the top of the stack è # Modular 0-based index it into the pair ‚ # Pair it together with the other sum # (after which the sorted list of pairs is output implicitly) ``` The `ODyRsè‚` can be a lot of other alternatives (some examples below), but I've been unable to find anything shorter: ``` OyRyOè‚ RDODŠè‚ O©y®<è‚ ÐO<è‚€O ÂsOè}ΣO ... ``` [Answer] # [R](https://www.r-project.org), 63 bytes ``` \(w,h,x=matrix(1:w,w,h),y=col(x))(x+y*1i)[order(s<-x+y,x*s%%2)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LYxBCsIwEEX3niKbwkydQNIqSDF6EHUhanCgNpJGmp7FTRU8lLcxEFf__8fnPV9-elvzeQQrV9_tHga6UjS3Y_AcQTcDJYA0mpNrISJCnI-lZtw5f7546NcyAYplXxQVHv6ajQVd1aRwZkFRqqk4Dyy4E6pZoLh77gJYYGKUWiZfei6pziNbpinnDw) Since R is not very good at working with matrices of pairs, this returns the coordinates as the components of a complex number (1-indexed, converted to 0-indexed in the footer for convenience). Thanks to pajonk for spotting an unnecessary byte. ]
[Question] [ [Landau's function](https://en.wikipedia.org/wiki/Landau%27s_function) \$g(n)\$ ([OEIS A000793](https://oeis.org/A000793)) gives the maximum order of an element of the symmetric group \$S\_n\$. Here, the order of a permutation \$\pi\$ is the smallest positive integer \$k\$ such that \$\pi^k\$ is the identity - which is equal to the least common multiple of the lengths of the cycles in the permutation's cycle decomposition. For example, \$g(14) = 84\$ which is achieved for example by (1,2,3)(4,5,6,7)(8,9,10,11,12,13,14). Therefore, \$g(n)\$ is also equal to the maximum value of \$\operatorname{lcm}(a\_1, \ldots, a\_k)\$ where \$a\_1 + \cdots + a\_k = n\$ with \$a\_1, \ldots, a\_k\$ positive integers. ## Problem Write a function or program that calculates Landau's function. ## Input A positive integer \$n\$. ## Output \$g(n)\$, the maximum order of an element of the symmetric group \$S\_n\$. ## Examples ``` n g(n) 1 1 2 2 3 3 4 4 5 6 6 6 7 12 8 15 9 20 10 30 11 30 12 60 13 60 14 84 15 105 16 140 17 210 18 210 19 420 20 420 ``` ## Score This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): Shortest program in bytes wins. (Nevertheless, shortest implementations in multiple languages are welcome.) Note that there are no requirements imposed on run-time; therefore, your implementation does not necessarily need to be able to generate all the above example results in any reasonable time. Standard loopholes are forbidden. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` Åœ€.¿Z ``` [Try it online!](https://tio.run/##yy9OTMpM/W9s4O5nr6Sga6egZO/3/3Dr0cmPmtboHdof9V/nv/l/Xd28fN2cxKpKAA "05AB1E – Try It Online") ``` Åœ # integer partitions of the input €.¿ # lcm of each Z # maximum ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes ``` Max[PermutationOrder/@Permutations@Range@#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7876Ng@983sSI6ILUot7QEKJaf51@Uklqk74AkUuwQlJiXnuqgHKv2P6AoM68kWlnXzidaOTZWTUHfQQEsGW1oEPsfAA "Wolfram Language (Mathematica) – Try It Online") # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes @DanielSchepler has a better solution: ``` Max[LCM@@@IntegerPartitions@#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7876Ng@983sSLax9nXwcHBM68kNT21KCCxqCSzJDM/r9hBOVbtf0BRZl5JtLKunU@0cmysmoK@g0JQYl56arSRQex/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python](https://docs.python.org/2/), 87 bytes ``` f=lambda n,d=1:max([f(m,min(range(d,d<<n,d),key=(n-m).__rmod__))for m in range(n)]+[d]) ``` [Try it online!](https://tio.run/##RcoxDoMwDEDRuT1FRluYSmk3RE6CUJTKpI1aOyhigNMHKoau7/95W95Z77VG9w3y5GCU2NlOwgpDBCFJCiXoawIm7vujIn2mzYG2gjfvi2T2HjHmYsQkNeesODYDj1h/rn@3ZB/YXS9zSbpAPD6sOw "Python 2 – Try It Online") A recursive function that tracks the remaining `n` to partition and the running LCM `d`. Note that this means we don't need to track the actual numbers in the partition or how many of them we've used. We try each possible next part, `n-m`, replacing `n` with what's left `m`, and `d` with `lcm(d,n-m)`. We take the maximum of those recursive results and `d` itself. When nothing remains `n=0`, the result ist just `d`. The tricky thing is that Python doesn't have any built-ins for LCM, GCD, or prime factorization. To do `lcm(d,m-n)`, we generate a list of multiples of `d`, and take the value attaining the minimum modulo `n-m`, that is with `key=(n-m).__rmod__`. Since `min` will give the earlier value in case of a tie, this is always the first nonzero multiple of `d` that's divisible by `n-m`, so their LCM. We only multiples of `d` up to `d*(n-m)` to be guaranteed to hit the LCM, but it's shorter to write `d<<n` (which is `d*2**n`) which suffices with Python's upper bounds being exclusive. Python 3's `math` library has `gcd` (but not `lcm`) after 3.5, which is a few bytes shorter. Thanks to @Joel for shortening the import. **[Python 3.5+](https://docs.python.org/3/), 84 bytes** ``` import math f=lambda n,d=1:max([f(m,d*(n-m)//math.gcd(n-m,d))for m in range(n)]+[d]) ``` [Try it online!](https://tio.run/##RcoxDsIwDEDRmZ7Cow2BKupWqSepOhhM2kjYiaIMcPpAJsb/9POnHsmm1qLmVCoo12MIy4v1LgzmZPGz8hvXgOrkjHZVGsd@3faH9HRCFFIBhWhQ2PYnGm2XVTZq3e3v3vmJ5uGUS7SK4fdR@wI "Python 3 – Try It Online") Using `numpy`'s `lcm` is yet shorter. **Python with [numpy](https://numpy.org/), 77 bytes** ``` from numpy import* f=lambda n,d=1:max([f(m,lcm(d,n-m))for m in range(n)]+[d]) ``` [Try it online!](https://tio.run/##RcoxDoMwDADAubzCo03DEEYkXoIY0ga3kbATWalUXp@WifV05ajvrGNrbFlAP1IOSFKy1b7jeQ/yiAHUxdlPEr64MIrbn4LR6SBEnA0EkoIFfW2otN6XuFI7XS/3znuauluxpBX5/6j9AA "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 44 bytes ``` (%1) n%t=maximum$t:[(n-d)%lcm t d|d<-[1..n]] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX0PVUJMrT7XENjexIjO3NFelxCpaI083RVM1JzlXoUQhpSbFRjfaUE8vLzb2f25iZp6CrUJuYoGvQkFRZl6JggqIo5CmAFJhaBD7/19yWk5ievF/3eSCAgA "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Œṗæl/€Ṁ ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7px9elqP/qGnNw50N/60fNcxR0LVTeNQw1/pwO5eRweF2oEzkfwA "Jelly – Try It Online") A monadic link taking an integer as its argument and returning an integer. ## Explanation ``` Œṗ | Integer partitions æl/€ | Reduce each using LCM Ṁ | Maximum ``` [Answer] # JavaScript (ES6), 92 bytes Computes the maximum value of \$\operatorname{lcm}(a\_1,\ldots,a\_k)\$ where \$a\_1+\ldots+a\_k\$ is a partition of \$n\$. ``` f=(n,i=1,l=m=0)=>n?i>n?m:f(n-i,i,l*i/(G=(a,b)=>b?G(b,a%b):a)(l,i)||i)&f(n,i+1,l)|m:m=l>m?l:m ``` [Try it online!](https://tio.run/##FczNDoIwEATgu0/RA5pdKQrxVlw48hq0CGZNfwwYL8Cz13qYZJKZfC/91csw8/tT@PAYY5wIvGSqpCVHJVLjW05xagJfsGRpz3yFjkBLk1bTdmCkPhpUGsFKxm1jPE1/JE8Ibk45so1rrXJxCjN4QaKqhRd3ErcylTxHsR6EGIJfgh0vNjyh15Ctfsf0zdaE4d5jfdjjDw "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 95 bytes ``` f=(n,i=1,m)=>i>>n?m:f(n,i+1,i<m|(g=(n,k=2,p=0)=>k>n?p:n%k?p+g(n,k+1):g(n/k,k,p*k||k))(i)>n?m:i) ``` [Try it online!](https://tio.run/##HY5LDoMwEEP3nGIWVMo06ScsgcBVQBRQOjCJoOoGOHsaurJlP1l@t9927RbrPzd2rz6EwQhW1mg1o6lsVXE958MZSa1sOe9iPAEymfLmGRGKhM/5QrWX49lIjXk0D1Kk/JX2nRCFxf@QxTC4RTAY0AUwlKCzqFIibAlA53h1U3@f3CiaVqQbHxjRdIsH8GiwSI7wAw "JavaScript (Node.js) – Try It Online") ### How? We define: $$\cases{ g(1)=0\\ g(n)=\sum\_{j=1}^{N}{p\_j}^{k\_j}\quad\text{for}\enspace n>1\enspace\text{and}\enspace n=\prod\_{j=1}^{N}{p\_j}^{k\_j} }$$ (this is [A008475](https://oeis.org/A008475)) Then we use the formula (from [A000793](https://oeis.org/A000793)): $$f(n)=\max\_{g(k)\le n}k$$ [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 50 bytes ``` {max .map:{+(.[$_],{.[@^a]}...$_,)}}o&permutations ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjexQkEvN7HAqlpbQy9aJT5Wp1ov2iEuMbZWT09PJV5Hs7Y2X60gtSi3tCSxJDM/r/i/NVdxYqWCkkq8gq2dQrWCHtCcWiWFtPwiBUM9PfP/AA "Perl 6 – Try It Online") Checks all permutations directly, like @histocrat's Ruby solution. ### Explanation ``` &permutations # Permutations of [0;n) { }o # Feed into block .map:{ } # Map permutations ... # Construct sequence .[$_] # Start with permutation applied to itself [1] ,{.[@^a]} # Generate next item by applying permutation again $_, # Until it matches original permutation [2] +( ) # Length of sequence max # Find maximum ``` 1 We can use any sequence of n distinct items for the check, so we simply take the permutation itself. 2 If the endpoint is a container, the `...` sequence operator smartmatches against the first item. So we have to pass a single-element list. [Answer] # [Ruby](https://www.ruby-lang.org/), 77 bytes ``` f=->n{a=*0...n;a.permutation.map{|p|(1..).find{a.map!{|i|p[i]}==a.sort}}.max} ``` [Try it online!](https://tio.run/##KypNqvyfZgtEunZ51Ym2WgZ6enp51ol6BalFuaUliSWZ@Xl6uYkF1TUFNRqGenoqKpp6aZl5KdWJIFHF6prMmoLozNhaW9tEveL8opLaWqB4Re3/gtKSYgWQBgtNiPaKmrToitja/wA "Ruby – Try It Online") `(1..)` infinite range syntax is too new for TIO, so the link sets an arbitrary upper bound. This uses the direct definition--enumerate all possible permutations, then test each one by mutating `a` until it gets back to its original position (which also conveniently means I can just mutate the original array in each loop). [Answer] # [Gaia](https://github.com/splcurran/Gaia), ~~25~~ ~~23~~ 22 bytes ``` ,:Π¤d¦&⊢⌉/ 1w&ḍΣ¦¦⇈⊢¦⌉ ``` [Try it online!](https://tio.run/##S0/MTPz/X8fq3IJDS1IOLVN71LXoUU@nPpdhudrDHb3nFh9admjZo/YOoDCQ7un8/98UAA "Gaia – Try It Online") Not having LCM or integer partitions makes this approach rather long. ``` ,:Π¤d¦&⊢⌉/ ;* helper function: LCM of 2 inputs 1w&ḍΣ¦¦ ;* push integer partitions ¦ ;* for each ⇈⊢ ;* Reduce by helper function ⌉ ;* and take the max ``` [Answer] ## Haskell, ~~70~~ 67 bytes ``` f n=maximum[foldl1 lcm a|k<-[1..n],a<-mapM id$[1..n]<$[1..k],sum a==n] ``` [Try it online!](https://tio.run/##JcpNCoAgEEDhq8zSIIV2EXmEThASQyWJM1P0Ay26uyWtHg@@BY84E6XkQSzjHfji3q80UQU0MuATW91XxogrsdWMW6ea/4uc6Mrj@pi14hJjELCQ0QBq24OcxheQXe3SCw "Haskell – Try It Online") Edit: -3 bytes thanks to @xnor. [Answer] # [Python 3](https://docs.python.org/3/) + numpy, 115 102 99 bytes *-13 bytes thanks to @Daniel Shepler* *-3 more bytes from @Daniel Shepler* ``` import numpy c=lambda n:[n]+[numpy.lcm(i,j)for i in range(1,n)for j in c(n-i)] l=lambda n:max(c(n)) ``` [Try it online!](https://tio.run/##Rcw7DoMwEEXRnlVMOVYAkaRDYiWIwji/QZ5ny3KksHpDaCjvKW5c8yfgXopoDCkTvhrXyg3e6vywhH7EdBkPbb1Tlnoxr5BISEDJ4v3ka42Dlj85RiNmqvx5UPvjnY0pMQkye751e2w "Python 3 – Try It Online") Brute force method: find all possible sequences a,b,c,... where a+b+c+...=n, then pick the one with the highest lcm. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~24~~ 15 bytes ``` eSm.U/*bZibZd./ ``` [Try it online!](https://tio.run/##K6gsyfj/PzU4Vy9UXyspKjMpKkVP//9/Q3MA "Pyth – Try It Online") ``` ./Q # List of partitions of the input m # map that over lambda d: .U d # reduce d (with starting value first element of the list) on lambda b,Z: /*bZgbZ # (b * Z) / GCD(b, Z) S # this gives the list of lcms of all partitions. Sort this e # and take the last element (maximum) ``` -9 bytes: paid attention and noticed that Pyth actually has a GCD builtin (`i`). ]
[Question] [ **This is Hole-3 from [*The Autumn Tournament* of APL CodeGolf](https://apl.codegolf.co.uk/problems#3). I am the original author of the problem there, and thus allowed to re-post it here.** --- Given: 1. a number of turns (please state if no movements is 0, otherwise we'll assume it is called 1) and 2. a list of one or more starting positions (in any form, e.g. 0 or 1 indexed coordinates or 64 consecutive numbers/characters or A1–H8 – state which), on an 8-by-8 chessboard, return (in any order) the list of unique positions (in the same format as the input) that knight(s) can be at after the given number of turns. * Each knight must move with every turn, but you do not have to worry about multiple knights occupying the same square. * A knight can only move to the positions marked with X relative to its current position, marked with ♞: [![where a knight can move](https://i.stack.imgur.com/uYFbI.png)](https://i.stack.imgur.com/uYFbI.png) ### Examples (1-indexed coordinates) `1` move from `[[1,1]]`: `[[2,3],[3,2]]` `2` moves from `[[1,1]]`: `[[1,1],[1,3],[1,5],[2,4],[3,1],[3,5],[4,2],[4,4],[5,1],[5,3]]` `1` move from `[[1,1],[5,7]]`: `[[2,3],[3,2],[3,6],[3,8],[4,5],[6,5],[7,6],[7,8]]` `2` moves from `[[1,1],[5,7]]`: `[[1,1],[1,3],[1,5],[1,7],[2,4],[2,6],[2,8],[3,1],[3,3],[3,5],[3,7],[4,2],[4,4],[4,6],[4,8],[5,1],[5,3],[5,5],[5,7],[6,4],[6,6],[6,8],[7,3],[7,7],[8,4],[8,6],[8,8]]` `0` moves from `[[3,4]]`: `[[3,4]]` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 45 bytes Because the other solution is incorrect (see Martin's comment below), so I decide to post my solution: ``` 8~KnightTourGraph~8~AdjacencyList~#&~Nest~##& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d@izjsvMz2jJCS/tMi9KLEgo86izjElKzE5NS@50iezuKROWa3OLxVEK6v9j6421FEwqtVRMIyN/Q8A "Wolfram Language (Mathematica) – Try It Online") Ultimate infix notation... Takes 2 input, the first one is a list of numbers in range `[1,64]` describe the starting positions of the knight, the second one is the number of steps. This solution relies on the extreme convenience of Mathematica builtin functions: * `AdjacencyList` may takes a list of vertices on its right side, and return a list of vertices adjacent to any of those, **already removed duplicates and sorted**. * `KnightTourGraph` is a builtin. Not surprise. * `Nest` takes arguments in order `Nest[f, expr, n]`, which we can splat the `##` over its right side as `Nest[f, ##]`. * And finally, Mathematica parse `a~b~c~d~e` as `(a~b~c)~d~e`, so no square bracket is necessary. Without infix notation and flatten `##`, it would be `Nest[AdjacencyList[KnightTourGraph[8, 8], #] &, #, #2]&`. [Answer] # JavaScript (ES7), 99 bytes Input/output format: squares indices in **[0 ... 63]**. ``` f=(a,n)=>n--?f([...Array(64).keys()].filter(p=>!a.every(P=>(p%8-P%8)**2^((p>>3)-(P>>3))**2^5)),n):a ``` ### Test cases This snippet includes two helper functions to translate from and to the format provided by the OP. ``` f=(a,n)=>n--?f([...Array(64).keys()].filter(p=>!a.every(P=>(p%8-P%8)**2^((p>>3)-(P>>3))**2^5)),n):a c2s = a => a.map(c => (c[0] - 1) * 8 + c[1] - 1) s2c = a => JSON.stringify(a.map(s => [(s >> 3) + 1, s % 8 + 1])) console.log(s2c(f(c2s([[1,1]]), 1))) console.log(s2c(f(c2s([[1,1]]), 2))) console.log(s2c(f(c2s([[1,1],[5,7]]), 1))) console.log(s2c(f(c2s([[1,1],[5,7]]), 2))) console.log(s2c(f(c2s([[3,4]]), 0))) ``` ### How? A move from **(x,y)** to **(X,Y)** is a valid knight move if we have either: * **|x-X| = 1** and **|y-Y| = 2**, or * **|x-X| = 2** and **|y-Y| = 1** By squaring instead of using absolute values, this can be expressed as: * **(x-X)² = 1** and **(y-Y)² = 4**, or * **(x-X)² = 4** and **(y-Y)² = 1** Because **1** and **4** are the only perfect squares that give **5** when XOR'd together, we have a valid knight move if: **(x-X)² XOR (y-Y)² XOR 5 = 0** We apply this formula to each square **p = 8y + x** on the board and each knight square **P = 8Y + X** to deduce the new possible knight target squares, and recursively repeat this process **n** times. [Answer] # Octave , 69 bytes ``` function a=f(a,n,b=~a)for k=1:n;a=b&imdilate(a,de2bi(")0#0)"-31));end ``` [Online Demo!](http://rextester.com/RRVU73688) The input/output is the configuration of the board at start/end as a binary 8\*8 matrix. Explanation: For `n` steps repeat morphological dilation of the board with the following mask: ``` 01010 10001 00100 10001 01010 ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~147~~ 102 bytes ``` .$ $* ¶ ¶ {s`((?<=N(....|.{11}|.{13})?.{7})|(?=.{8}(....|.{11}|.{13})?N))\S(?=.* ) n Ts` Nn`_:N`.*¶ ``` [Try it online!](https://tio.run/##K0otycxL/P9fT4VLRYuT69A2LgUgri5O0NCwt7H109ADghq9akPDWhBpXKtpr1dtXqtZo2Fvq1dtUYtF3k9TMyYYJK3FqcmVxxVSnMDpl5cQb@WXoKd1aBvn//9@VhDAZUWI4YdXjREA "Retina – Try It Online") Takes input as an 8x8 board of `:`s with the knights marked with `N`s, with a digit for the number of turns on the next line (it makes no sense to have more than 9 turns, but if you insist I can support it for an extra byte). Note that the output contains additional white space. Edit: Saved 45 bytes thanks to @MartinEnder. Explanation: The first stage converts the number of turns to unary, but using tab characters, so that they don't get matched later by accident, while the second stage adds some spaces to the right of the board to stop the regexes from wrapping across the edge. The third stage replaces all `N`s and `:`s that are a knight's move away from an `N` with an `n` while the fourth stage deletes any remaining `N`s, changes the `n`s to `N`s, and subtracts 1 from the move count. This repeats until the move count is zero. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes ``` +þ1,2Œ!×þ1,-p`¤¤Ẏ¤Ẏ⁼%8$$ÐfQµ¡ ``` [Try it online!](https://tio.run/##y0rNyan8/1/78D5DHaOjkxQPTwexdAsSDi05tOThrj4w8ahxj6qFisrhCWmBh7YeWvj////oaAMdg1idaBMds9jY/0YA "Jelly – Try It Online") 0-indexed coordinates. Almost certain this is suboptimal. -1 byte thanks to user202729 # Explanation ``` +þ1,2Œ!×þ1,-p`¤¤Ẏ¤Ẏ⁼%8$$ÐfQµ¡ Main Link +þ Addition Table (all pairs using + as combining function) with 1,2Œ!×þ1,-p`¤¤Ẏ¤ All knight moves: 1,2 [1, 2] Œ! All permutations ([1, 2], [2, 1]) ×þ Product Table (all pairs using × as combining function) with 1,-p`¤ [1, 1], [1, -1], [-1, 1], [-1, -1] 1,- [1, -1] p` Cartestian Product with itself ¤ All knight moves (in a nested array) as a nilad Ẏ¤ Tighten (flatten once); all knight moves in a (semi-)flat array Ðf Keep elements where ⁼%8$$ The element equals itself modulo 8 (discard all elements out of the range) Q Remove Duplicates µ Start new monadic chain (essentially, terminates previous chain) ¡ Repeat n times; n is implicitly the second input (right argument) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~27~~ 25 bytes Thanks to *Emigna* for saving 2 bytes! Uses 1-indexed coordinates. ### Code: ``` F•eĆ•SÍü‚Dí«δ+€`Ùʒ{`9‹*0› ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##AUEAvv8wNWFiMWX//0bigKJlxIbigKJTw43DvOKAmkTDrcKrzrQr4oKsYMOZypJ7YDnigLkqMOKAuv//MgpbWzEsIDFdXQ "05AB1E – Try It Online") ### Explanation: ``` F # Do the following <input_1> times.. •eĆ•SÍ # Push [-1, -2, 1, 2, -1] ü‚ # Pairwise pairing: [[-1, -2], [-2, 1], [1, 2], [2, -1]] D # Duplicate the array í # Reverse each element « # Concatenate to the previous array ``` This gives us the following array: ``` [[-1, -2], [-2, 1], [1, 2], [2, -1], [-2, -1], [1, -2], [2, 1], [-1, 2]] ``` Which are the deltas of the moves of the knight. ``` δ+ # Addition vectorized on both sides €` # Flatten each element Ù # Uniquify ʒ # Keep elements which.. {`9‹ # Has a maximum element smaller than 9 *0› # And a minimum element larger than 0 ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 124 bytes ``` (m,p)->{for(;m-->0;)for(long a=p,i=p=0,j;i<64;i++)for(j=64;j-->0;)p|=(p=i%8-j%8)*p+(p=i/8-j/8)*p==5?(a>>i&1)<<j:0;return p;} ``` [Try it online!](https://tio.run/##hVLLbtswELznKxYGFJA2pcitGxiWqKCXnNxTejN8YCzJIGuJBEm5CBR9u0tRsuO2BnLQYzmz5MxwBTuyUKqiFvmvE6@U1BaEW4sayw/RNLn7b61s6p3lsu5B1bwe@A52B2YM/GC8hvYOgNe20CXbFfAMLRxkvYcSuUWoiC8UTqBzPGOZdd3PUAKFE6qIwmHWllKjpArDLE5w/@9bGFWEU0VjIhKePi4SPpt5VFBXiIGt3ilSlAfLUARLPFWzvnpw1UNfUfrtCbEs4/dznKZiFSe6sI2uQSXdKXFyRjOjqqPkOVTOEnqxmtf7zRaY3hvsHQLYwlg0J1AXv3u/m@1m27YxibsOJx@EL58Rbu1A2gV5/HyfG7T4H9pXshgJV3F7Y57ur0QeC0POLaDkxaHP/VUynbvbiYdT@sQ9FdTqmgsj8Z3CfA1pCkht4u10OVOb@XZU2H3sqgvTHKzbtoxKNCjw/SNzzY1N/TEZaMfqPX3Xmr15IEP4LzHAaexmYulH4qLnDAoHCgeKa9CNaInQqOIe0Hydpog7uQJjnMVYRyzP0SXKlhNxzvnsY3i/vBlbVJFsbKTckNgSTYLcZxoYKLWsIDAr9wT1hJyj9h@gLil4gslkBRPjQO/PRHlRqJ9ymDjUB3wb0ZGVfh05wcP9dqc/ "Java (OpenJDK 8) – Try It Online") ## Input / Output format The input/output is represented as bits in a `long` (64 bits): set bits mean a horse is present, unset bits mean no horse. Example: ``` // [[0, 0]] 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000001L ``` ## Explanations ``` (m, p) -> { // Lambda. No currying because m and p are modified for(;m-->0;) // For each move for(long a=p,i=p=0,j;i<64;i++) // Declare variables, move p to a, create a new p and loop on bits of a. for(j=64;j-->0;) // Loop on bits of p. p |= // Assign to p a value. (p=i%8-j%8)*p+(p=i/8-j/8)*p==5 // If i -> j is a valid horse move, see Arnauld's JavaScript answer for full explanations ? (a>>i&1)<<j // Assign the presence of the horse (i-th bit of a) to the resulting board (j-th bit of p). : 0; // Else it's not a valid horse move return p; } ``` ## Credits * 19 bytes saved thanks to Nevay! * Reused the `(X-x)²+(Y-y)²==5` trick from Arnauld's [JavaScript answer](https://codegolf.stackexchange.com/a/145676/16236) * 1 more byte saved thanks to Nevay in the new algorithm! * 7 more bytes saved thanks to Nevay again by switching from `int[]` to 64-bits `long`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ 28 bytes ``` 8Rp` “¦Ʋƈ2’D_2ṡ2+€µẎ ÇƓ¡f1£Q ``` [Try it online!](https://tio.run/##AUAAv/9qZWxsef//OFJwYArigJzCpsayxogy4oCZRF8y4bmhMivigqzCteG6jgrDh8aTwqFmMcKjUf//Mv9bWzEsMV1d "Jelly – Try It Online") Number of turns is through STDIN, and squares is an argument. ~~This ties @HyperNeutrino's Jelly solution, but with a different approach.~~ Now beating @HyperNeutrino by 1 whole byte! Any suggestions to knock off some bytes are wanted! ## Link 1 (The chessboard) ``` 8Rp` 8R = The list [1,2,3,4,5,6,7,8] p` = cartesian multiplied with itself (this results in the chessboard) ``` ## Link 2 (Move generation) ``` “¦Ʋƈ2’D_2ṡ2+€µẎ “¦Ʋƈ2’ = the number 103414301 D = converted into a list of digits _2 = subtract two from each element ṡ2 = overlapping pairs +€ = add to the list of squares µ = Make sure the next part isn't treated as a right argument Ẏ = Tighten the list (Reducing the depth by one) ``` ## Link 3 (square checking) ``` ÇƓ¡f1£Q ÇƓ¡ = Repeat link #2 the requested amount of times f1£ = Remove everything not a member of link #1 (not on the chess board) Q = Make sure squares don't appear more than once ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 18 bytes ``` u!¡ṁö`fΠR2ḣ8=5ṁ□z- ``` Uses 1-based indexing of squares and steps. [Try it online!](https://tio.run/##yygtzv7/v1Tx0MKHOxsPb0tIO7cgyOjhjsUWtqZAgUfTFlbp/v//PzraUMcwNva/EQA "Husk – Try It Online") ## Explanation ``` u!¡ṁö`fΠR2ḣ8=5ṁ□z- Implicit inputs, say P=[[1,1],[5,7]] and n=2 ¡ Iterate on P: ṁö Map the following function, then concatenate: Argument is a pair, say p=[5,7]. ḣ8 The range [1,2,..,8] ΠR2 Repeat twice, take cartesian product: [[1,1],[1,2],..,[8,8]] `f Filter with this predicate: Argument is a pair, say q=[3,8]. z- Zip p and q with difference: [-2,1] ṁ□ Sum of squares: 5 =5 Is it 5? Yes, so [3,8] is kept. ! Take n'th step of the iteration. u Remove duplicates, implicitly print. ``` [Answer] # **Python 3, 105 bytes** ``` p=lambda g,i:i and list(set(p([x+y for x in g for y in[6,10,15,17,-6,-10,-15,-17]if 0<=x+y<64],i-1)))or g ``` Have to use a named lambda for the recursion. Not sure if that's disqualifying. Pass in starting positions as 0-indexed square number list. 0 counts as no moves. [Answer] # [R](https://www.r-project.org/), ~~145~~ ~~183~~ 134 bytes This is the result of Giuseppe's excellent golfing of my initial not-too-golfy algo (see comment below) ``` function(x,n){x=x%/%8*24+x%%8 t=c(49,47,26,22) t=c(t,-t) for(i in 1:n)x=intersect(v<-outer(1:8,0:7*24,"+"),outer(x,t,"+")) match(x,v)} ``` [Try it online!](https://tio.run/##LY5NT4QwEIbv/IqGhDAjg24rcZFsDx7k5M2Lya4H7LLag0VLIQXjb8fK7vF9Zt4Pu9Rsly@nwSinOwOeDP546ZObpLwSReaTpIycVFDcU7ElcUdC4Aoc5Q6jU2dBM20Yrwx6qY1rbd8qB@Mu74YggFclbaptCKM4i5HO1JNbJUafjVMfQY/4u3gmmQJektiQ4JjxSDUO4qYPDUet2p6BaZweW6wOJsZokjWEfxJ0i8Qx@rJhAPSddTCF6NV8MMEeSqz2DI7t2/B@Mc9zaDsfIL1OqaTyH@6nV5m@pJeseabvoXOtrB@enh9x@QM "R – Try It Online") Input and output are 1...64 based. Takes a vector of position using the 1...64 notation. Maps it to a 1:576 notation, that is a super-board made of nine boards. In this notation, at each iteration, each knight should be able to move by +/- 22,26,47,49 Return future positions back in the 1...64 notation, excluding those that fall off the central board. The TIO example displays the result using an 8x8 matrix. ]
[Question] [ Whenever you make a move on a Rubik's Cube, there is a reverse move which undoes the first move. Because of this, every algorithm (set of moves) has a reverse algorithm which undoes the first algorithm. The goal of this challenge is to find the reverse of a given algorithm. # Specification: The input consists of an array of individual moves. Each move is a string of length 1 or 2. Of course, you can use whatever input format makes the most sense in your language. Each move consists of the structure `X` or `X'` or `X2`, where `X` is an uppercase or lowercase letter. To reverse `X`, simply replace it with `X'`. Likewise, `X'` becomes `X`. `X2` on the other hand does not get changed. To create the output, reverse each move, and then reverse the array. # Examples (strings separated by spaces): `R` => `R'` `D U'` => `U D'` `S T A C K` => `K' C' A' T' S'` `A2 B2` => `B2 A2` # Scoring: This is code-golf, so the fewest amount of bytes win. Standard loopholes are not allowed. [Answer] # [Python 2](https://docs.python.org/2/), ~~71~~ ~~57~~ ~~54~~ 53 bytes *-15 bytes thanks to ovs! -3 bytes thanks to Rod.* ``` lambda l:[i.strip("'")+" '"[len(i):]for i in l[::-1]] ``` [Try it online!](https://tio.run/##RY49C8IwFEX3/IpHltdiFcwY6FB1c/Njim@o2NJATEOSxV8fkyL1DYfL4cJ97hOn2Yo0to9k@vfz1YORSu9C9NpVHHm94YBcmcFWupY0zh40aAtGSbndE6U4hBigBcUgn8ILUvOLJ2yA35Gv4poF3gq6gmPB@d/vRBEHgcSIsXVqWZBLx3ltI4z5lfQF "Python 2 – Try It Online") ## String I/O, 70 bytes ``` lambda s:' '.join(i.strip("'")+"'"*(len(i)<2)for i in s.split()[::-1]) ``` [Try it online!](https://tio.run/##PY27DsIwFEP3fIWV5SY8KpExokOBjY3HVDqAaMVFJY2aLHx9iArCg2XZ0rF/x8fgTOrKS@qvr9v9imAJVDwHdoqLEEf2SpLU82wz1be51Wuju2EEgx1CEXzPUena2uWq0Sm2IQaUqAWy6ECLKcgdziS/mY44ocIW@99IlcHGkGiE@IMnjp1mP7KL6PJz@gA "Python 2 – Try It Online") [Answer] # [V](https://github.com/DJMcMayhem/V), ~~13~~ 10 bytes ``` æGÇä/á'Ó'' ``` [Try it online!](https://tio.run/##K/v///Ay98Pth5foH16ofniyuvr//8FcIUZcjupczlze6gA "V – Try It Online") 3 bytes saved thanks to @nmjmcman pointing out my favorite feature. Explanation: ``` æG " Revere the order of every line Ç " On every line not containing... ä/ " a digit: á' " Append an ' Ó " Remove every instance on this line '' " Of two single quotes ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~27~~ 26 bytes ``` \w $&' '' '2' 2 O$^`.'?2? ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP6acS0VNnUtdnYtL3Uidy4jLXyUuQU/d3sj@//8gLpdQda7gEEdnby5HIycjAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: The first stage adds an apostrophe after every alphanumeric. This results in double apostrophes (with or without an inclusive 2) which need to be removed. The final stage reverses the moves. [Answer] # JavaScript (ES6), 45 bytes ``` s=>s.map(([a,b])=>b?+b?a+b:a:a+"'").reverse() ``` Shortest solution is to take Array IO. Simple and appropriate use of argument destruction. String output is +8 bytes for `.join` ``. ## String input, Array output: 69 bytes ``` (s,k=[])=>s.replace(/\S\S?/g,([a,b])=>k.unshift(b?+b?a+b:a:a+"'"))&&k ``` ``` f= (s,k=[])=>s.replace(/\S\S?/g,([a,b])=>k.unshift(b?+b?a+b:a:a+"'"))&&k ; console.log(["R", "D U'", "S T A C K", "A2 B2"].map(e => `${e} => ${f(e)}`)); ``` ``` <textarea oninput="out.value=(f(this.value)||[]).join` `" placeholder="input here"></textarea> <textarea id="out" readonly></textarea> ``` [Answer] # JavaScript (ES6), 46 bytes Takes input as an array of moves. ``` a=>a.map(m=>m[1]?+m[1]?m:m[0]:m+"'").reverse() ``` --- ## Test it Enter a comma separated list of moves. ``` o.innerText=(f= a=>a.map(m=>m[1]?+m[1]?m:m[0]:m+"'").reverse() )((i.value="S,T,A,C,K").split`,`);oninput=_=>o.innerText=f(i.value.split`,`) ``` ``` <input id=i><pre id=o> ``` --- ## Explanation ``` a=> ``` Anonymous function taking the array of moves as an argument via parameter `a`. ``` a.map(m=> ) ``` Map over the array, passing each string through a function, where `m` is the current string. ``` m[1]? ``` Check if the string contains a second second character (`"'"` or `"2"`). ``` +m[1]? ``` If it does try to cast that character string to an integer. If the string is `"2"`, it becomes `2`, which is truthy. If the string is `"'"`, it becomes `NaN`, which is falsey. ``` m ``` If the previous test is truthy, simply return `m`. ``` :m[0] ``` Otherwise, return the first character of `m`. ``` :m+"'" ``` If the string does not contain a second character then return `m` appended with a `'`. ``` .reverse() ``` Reverse the modified array. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḟ;ċ?”'ḣ2)Ṛ ``` A monadic link taking an returning a list of lists of characters (an "array" of "strings"). **[Try it online!](https://tio.run/##y0rNyan8///hjvnWR7rtHzXMVX@4Y7GR5sOds/4fbvf@/z9aKUJJR0EpQh1MGinFAgA "Jelly – Try It Online")** (The footer avoids smashing the output, displaying the list split with spaces.) ### How? ``` ḟ;ċ?”'ḣ2)Ṛ - Link: list of lists of characters e.g. ["F'", "D2" , "R"] ) - for each turn instruction: ”' - literal "'" character ? - if: ċ - count (number of "'" in the instruction) i.e.: 1 , 0 , 0 ḟ - then: filter out "F" ; - else: concatenate "D2'", "R'" ḣ2 - head to index 2 "F" , "D2" , "R'" Ṛ - reverse ["R'", "D2" , "F"] ``` [Answer] # [Python](https://docs.python.org/), ~~51~~ 48 bytes ``` lambda a:[(v+"'")[:2-("'"in v)]for v in a[::-1]] ``` An unnamed function taking and returning lists of strings. **[Try it online!](https://tio.run/##JcqxCsMgFEbhPU/x4@KVkkAdhax9gEIm62BppZZUJbkR@vQ2oduB75Qvv3LSLYy3NvvP/eHhjaV6ElIoa3RPe8SEqlzICyr29taY/uxc4@fKGCGumCQuWgxrmSOT6vLGZTso0PGoriwxMSTk8M4x0d9V@wE "Python 2 – Try It Online")** Reverses the input list with `a[::-1]`; appends a `'` to *every* entry with `v+"'"`; heads each one to 1 or 2 characters depending on whether the original had a `'` in or not with `[:2-("'"in v)]`. [Answer] # [Python 3](https://docs.python.org/3/), ~~91~~ ~~89~~ ~~72~~ ~~70~~ ~~69~~ 65 bytes ``` lambda s:[i[0]+(len(i)-2and"'"or"2"*("2"==i[1]))for i in s[::-1]] ``` [Try it online! (With testcases)](https://tio.run/##RYvLCsIwEADP7VcsC9JEq9jqqdCDj5s3H6cYJNJUV2pakir49TWtBxdmmR3Y5tPea7PoyvzcVep5LRS4TJCYywmrtGHEp6kyBUZYW0xxzPzKcxKJ5LysLRCQASeybJpI2fXl0herzE2zJc/CgEyT67eqmJdXyzgPg8aSaVkkYORAgtVvbZ0ugBz8UjRiGAPOHjWZ/o3H/7Mcgp9O4B5lKHCLMZ6iQQ9ej56VZ@PZDXWVel2nKL8 "Python 3 – Try It Online") Apparantly you don't need to take input and output as strings, so a 69 byte solution is possible [Answer] # [Haskell](https://www.haskell.org/), 43 bytes ``` map f.reverse f[x]=x:"'" f[x,c]=x:[c|c>'1'] ``` [Try it online!](https://tio.run/##y0gszk7NyflfrauskJOYl16amJ6q4BwQoKCsW8uVbhvzPzexQCFNryi1LLWoOJUrLboi1rbCSkldCcTUSQZxopNrku3UDdVjgWoz8xRsFVLyuRQUCooy80oUVBTSFaKVgpRi0URclHSUQtUxhIOBwiFA7AjEzkDsjaHC0Qgo7GSkFPsfAA "Haskell – Try It Online") Declares an anonymous function `map f.reverse`. Bind to `g` and use as `g["S","T","A","C","K"]`. [Answer] # [PHP](https://php.net/), 81 bytes ``` <?foreach(array_reverse($_GET)as$v)$r[]=$v[1]?$v[1]<2?$v[0]:$v:"$v'";print_r($r); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwJWWX5SamJyhER2tFKQUqxOt5KKkoxSqDmYGA5khQOwIxM5A7A0WdTQCMp2MlGJjE4tV4t1dQzSrS/OKU0s0VIo0rf/DzEssKkqsjC9KLUstKk7VgKgDqi/TVCmKjrVVKYs2jLUHkzZGINog1kqlzEpJpUxdybqgKDOvJL4IYl7tfwA "PHP – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` RεÐ1èQ''si«ëK ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/6NzWwxMMD68IVFcvzjy0@vBq7///o5VclHQUlELVQaSbkVIsAA "05AB1E – Try It Online") ### Explanation ``` RεÐ1èQ''si«ëK R # Reverse input array ε # Map over each element... Ð1èQ # Is the second char in the element the first one? (Uses the fact that in python indexing loops) '' # Push ' s # Swap top items of stack i # If the question above is true... « # Concatenate ë # Else K # Push element without ' ``` [Answer] # J, 25 bytes J handles this one well, other than the unfortunate escape sequence needed to represent a single quote: ``` |.,&''''`}:@.(''''={:)&.> ``` We need to represent the list using boxed data, since it's a mix of one and two character items, hence: * `&.>` - "under unbox", which means unbox each element, perform the operation that follows (ie, the symbols explained below) and then rebox when done * `(''''={:)` "if the 2nd character is a single quote".... * `@.` (J's agenda verb, a kind of generalized ternary statement, or a case statement) "then perform the 2nd item on the agenda list, otherwise perform the first" * `}:` (the 2nd item on the agenda list), "remove the last character", ie, the single quote * ` (J's tie verb) You can think of this as the agenda item separator * `,&''''` (first item on agenda list) "add a single quote to the end" * `|.` "reverse" [Try it online!](https://tio.run/##y/pfbKtnY60Xb6igrhCq4KLgo66uEKGu4Oekp1CcmFuQk6qQkliS@D81OSNfoZgLTNXo6aipA0FCrZWDngaIZVttpammZ6dQ/P8/AA "J – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Rε''«¤ºK2£ ``` I/O as a list of moves. This is a subset of [my answer for the *Expand a Rubik's Cube Commutator* challenge](https://codegolf.stackexchange.com/a/240973/52210). [Try it online](https://tio.run/##yy9OTMpM/f8/6NxWdfVDqw8tObTL2@jQ4v//o5VclHSUQtWBRJCRUiwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/oHNb1dUPrT605NAub6NDi//X6vyPjlYKUorVUYhWclHSUQpVh7CDgewQIHYEYmcg9oYIOxoB2U5GSrGxAA). **Explanation:** ``` R # Reverse the (implicit) input-list ε # Map over its strings: ''« # Append a "'" to each string ¤ # Push the last character (the "'") without popping the string º # Mirror it to "''" K # Remove all "''" from the string 2£ # Only keep the first two characters of the string # (after which the result is output implicitly) ``` [Answer] # [R](https://www.r-project.org/), 51 bytes ``` function(u)sub("((2)|')'","\\2",paste0(rev(u),"'")) ``` [Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP0@jVLO4NElDSUPDSLNGXVNdSUcpJsZISacgsbgk1UCjKLUMqEJHSV1JU/N/mkayhpKjko6Cko8RiHRSB5EuYDkA "R – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 44 bytes ``` ->a{a.reverse.map{|i|i[1]?i.tr(?',''):i+?'}} ``` [Try it online!](https://tio.run/##Xc3NCoJAFAXgfU9xmBZXyYRmGaiMunPnz8pcGChMUMmoQajPbgMRMl04u/Odq8bre229y3r066l2VfNqVN@497qbZjnL8lQF0h2UFZBDZJ/lIaBlWbtx6MFS/M7zsZ/asmQpqyr39pQPAi2wUrLZ7luOUdBfOWYOK8gUBeLNZMghECHZTKZNriN0Ip3E5AkhIghCTsi2IcERcvO54FqH3OS6JLjN1g8 "Ruby – Try It Online") [Answer] # Java 8, ~~141~~ ~~128~~ ~~126~~ 115 bytes ``` a->(new StringBuffer(a).reverse()+"").replaceAll(".","'$0").replace("'''","").replaceAll("('(2)'|('))(.)","$4$2$3") ``` Takes input as single `String` without spaces (i.e. `RUR'URU2R'U`). [Try it online.](https://tio.run/##hY9BS8QwEIXv@yuGUMgE3SDR26Kw6k3cQ9aexEPMppI1m5YkrYj2t9esBgRBCknIvPlmeG@vBrVsO@P3u9dJOxUj3CvrPxYA1icTGqUNbI4lwDYF619AY/kotsr6mG8@MalkNWzAwyVManmF3ryVkeu@aUxAxXgwgwnRIDsh5Fh1Lu9fO4eEk1NCq7NfFQmlNIt/OKQoGP1EyhhylvvVRSWqc8Km1Y@Rrn922UjxM7R2B4ecqJh@fFKspHmPyRx42yfe5U5yHj3XSCRh37n@J25rOstsH9Y3d/ObhBSzkKwlrWUt8lvYcTFOXw) **Explanation:** ``` a-> // Method with String as both parameter and return-type (new StringBuffer(a).reverse()+"") //1 Reverse the input .replaceAll(".","'$0") //2 Prepend an apostrophe before each character .replace("'''","") //3 Remove all occurrences of three adjacent apostrophes .replaceAll("('(2)'|('))(.)","$4$2$3") //4 Replace '2'C with C2 OR 'C with C' (C is any character) ``` Example of the result after each step, with `RUR'URU2R'U` as given input: 1. `U'R2URU'RUR` 2. `'U'''R'2'U'R'U'''R'U'R` 3. `'UR'2'U'R'UR'U'R` 4. `U'RU2R'U'RU'R'` [Answer] # [Scala](http://www.scala-lang.org/), 47 bytes Golfed version. [Try it online!](https://tio.run/##VY8xawMxDIV3/wrhxTYNN2Q88MG13ZouTTO1oagXO1VwLsE2gRLy26@Wh3LR8NB7iI@nNGDA6fR9cEOGV6QRrkJcMIBv9YpS/ljnSON@a7u5M2Bh@mqiu7iYXHPEsybbkdfUBEzZWvWplCFwITmgBwlKmgmAudmlnFqotDlyW5DstYAydZNv0ixm9lkuQG7Ufbjm8J2lZ3liebk/6ZccPi6lKaERRXbOw7E8qzHuS5k@Rvz9/62FzUi51LlWRi3c@FN0OPxodmA7OJfbHEbta2IMo2/iNv0B) ``` _.reverse.map(i=>if(i.last=='\'')i else i+" '") ``` Ungolfed version. [Try it online!](https://tio.run/##VVCxbsIwFNzzFScvtlWUgREplVK60S4FppbhNbWpkQnItpCqim9P/QyqkuXsOz2/u3PsyNMwnD4Ppkt4JdfjtwK@jIVVfoEXF9P7OgXX73d6StGUUcDXwVxMiKY@0lk5NI9wFsrVnmJC00B@SKnhYHw0@XiAgBQ6v71WGS7kkUxM8b5@7MEmzFUxKjfxJvRsRJ/FDGIrp@KaxQ1Dy7BkWE1H2jmLT/MSRFf30sf8A4rCPodpQ6CfUfdt79J/5xK4tqdgqPtWzLj2Oc8m3ytbFK1vHa/D8Ac) ``` object Main { def f(l: List[String]): List[String] = { l.reverse.map(i => if (i.last == '\'') i else i + " '") } val tests: List[List[String]] = List( List("R"), List("D", "U'"), List("S", "T", "A", "C", "K"), List("A2", "B2") ) def main(args: Array[String]): Unit = { tests.foreach(test => println(f(test))) } } ``` ]
[Question] [ Earlier, we did the [pseudofactorial](https://codegolf.stackexchange.com/questions/82494/pseudofactorial) of a number, which is the LCM of the numbers from `1` to `n`. It would be useful in adding fractions together. However, we find that the denominator of `1/1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6` is `20` instead of the pseudofactorial of `6`, which is `60`. Your task is to find the denominator of `1/1 + 1/2 + ... + 1/n` given positive integer `n`. # Testcases ``` n result 1 1 2 2 3 6 4 12 5 60 6 20 7 140 8 280 9 2520 10 2520 11 27720 12 27720 13 360360 14 360360 15 360360 16 720720 17 12252240 18 4084080 19 77597520 20 15519504 21 5173168 22 5173168 23 118982864 24 356948592 25 8923714800 26 8923714800 27 80313433200 28 80313433200 29 2329089562800 30 2329089562800 ``` * [List for `n` from `1` to `200`](https://oeis.org/A002805/b002805.txt). * [List for `n` from `1` to `1000`](http://pastebin.com/raw/z1WaZQ87). * [List for `n` from `1` to `10000`](https://gist.githubusercontent.com/kckennylau/a5a09ae50268a6e99cac30e15a25486a/raw/929b7ea98b38a3443cb4b6e1059bfe71598a3bc9/ppcg-q82815,%2520oeis-a002805). # References * Obligatory OEIS [A002805](https://oeis.org/A002805) (thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman)) # Leaderboard ``` var QUESTION_ID=82815,OVERRIDE_USER=48934;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [M](http://github.com/DennisMitchell/m), ~~9~~ 6 bytes Thanks to **FryAmTheEggman** for saving 3 bytes! Code: ``` RİSg¹İ ``` **M** has a huge advantage here, because it works with fractions rather than floats. Explanation: ``` R # Get the list [1 ... n]. İ # Inverse each, resulting into [1/1, 1/2, 1/3, ..., 1/n]. S # Sum it up. (86021/27720 for n=12) g¹ # Compute the greatest common denominator with n. (1/27720 for n=12) İ # Calculate the inverse again. (27720 for n=12) ``` Uses the **Jelly encoding**. [Try it online!](http://m.tryitonline.net/#code=UsSwU2fCucSw&input=&args=MTI). --- Also, there is a **4-byte** solution, which outputs a leading zero sometimes (e.g. `280 -> 0280`). I'm not sure if this is allowed or not: ``` RİSV ``` [Try it online!](http://m.tryitonline.net/#code=UsSwU1Y&input=&args=OA). [Answer] # Julia, 22 bytes An anonymous function. ``` n->1.//(1:n)|>sum|>den ``` [Answer] ### Ruby, ~~57~~ 47 bytes ``` ->n{(1..n).reduce{|a,i|a+1.to_r/i}.denominator} ``` Thanks to **Kevin Lau** for shortening this by ten bytes. [Answer] # Mathematica, 27 bytes An anonymous function. ``` Denominator@*HarmonicNumber ``` For example: ``` In[1] := (Denominator@*HarmonicNumber)[10] Out[1] = 2520 ``` [Answer] # Python 2, ~~69~~ 67 bytes ``` a=b=k=r=1 exec'a=a*k+b;b*=k;k+=1;'*input() while r*a%b:r+=1 print r ``` Test it on [Ideone](http://ideone.com/RBXZCS). ### How it works Let **H(n)** be the sum of the multiplicative inverses of the first **n** positive integers. At all times, we have that **a / b = 1 + H(k - 1)**. In fact, **a**, **b**, and **k** are all initialized to **1**, and **1 / 1 = 1 = 1 + H(0)**. We repeat the code snippet ``` a=a*k+b;b*=k;k+=1; ``` (as a string) **n** (input) times and execute the result. In each step, we update **a**, **b**, and **k** using the identity **a / b + 1 / k = ak / bk + b / bk = (ak + b) / bk**. After all copies have been executed, **a / b = 1 + H(n)**, which has the same denominator as **H(n)**. The fully reduced form of **a / b** is **(a ÷ gcd(a,b)) / (b ÷ gcd(a,b))**. Instead of calculating the greatest common divisor, we initialize **r** as **1** and keep incrementing **r** until **ra** is a multiple of **b**. Clearly, this makes **ra** the least common multiple of **a** and **b**. Since **gcd(a,b) · lcm(a,b) = ab**, we have that **b ÷ gcd(a,b) = lcm(a,b) ÷ a = ra ÷ a = r**, making **r** the desired output. [Answer] # Haskell, 52 ``` Import Data.Ratio f n=denominator$sum[1%k|k<-[1..n]] ``` If the file is loaded into GHCI, f can be used as a function. [Answer] # Jelly, 9 bytes ``` !©÷RSg®®÷ ``` [Try it here.](http://jelly.tryitonline.net/#code=IcKpw7dSU2fCrsKuw7c&input=&args=MTA) ``` Argument: n ! ÷R Compute [n!÷1, n!÷2, … n!÷n]. © (And store n! in the register.) S Find the sum of this list. g® GCD with n!. ®÷ Divide n! by this GCD. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~14~~ 13 bytes ``` :p:G:!/s1\&X< ``` [**Try it online!**](http://matl.tryitonline.net/#code=OnA6RzohL3MxXCZYPA&input=Ng) ### Explanation For input *N*, the output is upper-bounded by *N*! (factorial of *N*). The code computes *n*/*k* for *n* = 1, ..., *N*! and for *k* = 1, ..., *N*. Then it sums over *k*, which gives the harmonic number multiplied by each *n*. The desired result is the index *n* of the first of those values that is an integer. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes Code: ``` !йL/O¿/ ``` Explanation: ``` ! # Take the factorial of the input. Ð # Triplicate this. ¹L # Get the list [1 ... input]. /O # Divide and sum up. ¿ # Get the GCD of the sum and the factorial. / # Divide the factorial by this. ``` There might be some accuracy problems for n > 19 due to Python's division... Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=IcOQwrlML0_Cvy8&input=Ng). [Answer] ## Mathematica, 26 bytes ``` Denominator@Tr[1/Range@#]& ``` An unnamed function taking `n` as input and returning the denominator. Uses the standard trick of abusing `Tr` (trace) to sum the list of reciprocals. [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` is\ṁ\ḣ ``` [Try it online!](https://tio.run/##yygtzv7/P7M45uHOxpiHOxb////f2AAA "Husk – Try It Online") Not too hard in Husk since it can do math with rational numbers. The hard part was extracting the denominator, I ended up inverting the fraction, converting it to string, and getting the first number from that string. ### Explanation ``` is\ṁ\ḣ ḣ range [1..n] ṁ sum the result of this function for each number: \ inverse \ invert s convert to string i get the first number in the string (the numerator) ``` [Answer] ## JavaScript (ES6), 88 bytes ``` m=>{for(d=1,i=0;i<m;d*=++i);for(n=i=0;i<m;n+=d/++i);for(g=d;g;[g,n]=[n%g,g]);return d/n} ``` Only works up to m=20 because of the limits of JavaScript's numeric precision. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 30 bytes ``` n->denominator(sum(i=1,n,1/i)) ``` [Try it online!](https://tio.run/nexus/pari-gp#S1OwVfifp2uXkpqXn5uZl1iSX6RRXJqrkWlrqJOnY6ifqan5Pw0olgdUZ6ijYGygo1BQlJlXAhRQUtC1AxJpGnmaQEUA "Pari/GP – TIO Nexus") [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ┬ΓΣ╞] ``` [Run and debug it](https://staxlang.xyz/#p=c2e2e4c65d&i=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21%0A22%0A23%0A24%0A25%0A26%0A27%0A28%0A29%0A30&m=2) 6 bytes without packing. [Answer] # [Whispers v3](https://github.com/cairdcoinheringaahing/Whispers), 79 bytes ``` > Input >> 1! >> 2∕R >> (1] >> Each 3 4 >> ∑5 >> 6⊓2 >> 2∕7 >> Output 8 ``` [Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hMvOTsFQEUQaPeqYGgRiaBjGgijXxOQMBWMFExD7UcdEUxBt9qhrshFMsTmI4V9aAjRFweL/f0MLAA "Whispers v3 – Try It Online") Same idea as Lynn's Jelly answer. [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 12 \log\_{256}(96) \approx \$ 10 bytes (Actually 9.88 bytes but that doesn't show up on the leaderboard) ``` Fztz!R+/SAG/ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZr3KpKqhSDtPWDHd31IUJQmQULzSAMAA) Port of Adnan's 05AB1E answer. #### Explanation ``` Fztz!R+/SAG/ # Implicit input Fzt # Get factorial and triplicate z!R+ # Push range(1, input+1) /S # Divide and sum AG/ # Get GCD and divide ``` [Answer] # J, 20 bytes ``` (!%!+.[:+/!%1+i.)@x: ``` Based on the approach used by @Lynn's [solution](https://codegolf.stackexchange.com/a/82825/6710). If precision is not necessary for large values of **n** or if we can assume **n** will be passed as an extended integer, suffixed by `x`, a shorter solution can be used for **15 bytes**. ``` !%!+.[:+/!%1+i. ``` ## Usage ``` f =: (!%!+.[:+/!%1+i.)@x: f 30 2329089562800 (,:f"0) >: i. 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 6 12 60 20 140 280 2520 2520 27720 27720 360360 360360 360360 ``` ## Explanation ``` (!%!+.[:+/!%1+i.)@x: Input: n x: Convert n into an extended integer i. Creates the range [0, 1, ..., n-1] 1+ Add one to each, range is now [1, 2, ..., n] ! Get factorial of n % Divide n! by each value in the range [1, 2, ..., n] [:+/ Sum those values ! Get n! +. Get gcd between n! and the sum ! Get n! % Divide n! by the gcd and return ``` [Answer] # [Perl 6](http://perl6.org), ~~36~~ 32 bytes ``` ~~{([+] 1.FatRat X/1..$\_).denominator}~~ {([+] 1.FatRat X/1..$_).nude[1]} ``` ### Explanation: ``` { ( [+] # reduce with &infix:<+> # the following produces a Seq of Rational numbers # 1/1, 1/2, 1/3 ... 1/n 1.FatRat # FatRat.new: 1,1 X/ # crossed using &infix:</> 1 .. $_ # Range from 1 to the input inclusive ) # resulting in a FatRat .nude # (nu)merator (de)nominator .[1] # grab the denominator } ``` ### [Test:](https://ideone.com/zEwFij) ``` my &hd = {([+] 1.FatRat X/1..$_).nude[1]} say (1..10)».&hd; # (1 2 6 12 60 20 140 280 2520 2520) say hd 100; # 2788815009188499086581352357412492142272 say chars hd 1000; # 433 say chars hd 10000; # 4345 ``` [Answer] ## [Hoon](https://github.com/urbit/urbit), 95 bytes ``` |= @ =+ n=(gulf 1 +<) =+ f=(roll n mul) (div f d:(egcd f (roll (turn n |=(@ (div f +<))) add))) ``` Create list `[1...n]`, fold over it with `++mul` for the factorial, create list `[n!/1, n!/2, ... n!/n]` and sum it, find GCD of `n!` and the list, and divide the factorial by that number. There's probably a much easier way to calculate the denominator, but I can't figure it out :/ [Answer] **Python 3, 153 150 146 142 bytes** I'm sure this can golfed further. But I'm new here ``` f=lambda x:0**x or x*f(x-1) z=int(input());i=f(z) r=sum(i/y for y in range(1,z+1)) p=lambda a,b:a if b<1else not a%b+b or p(b,a%b) print(i/p(r,i)) ``` [Answer] # Axiom, 34 bytes ``` f(x)==denominator(sum(1/n,n=1..x)) ``` test ``` (24) -> [[i,f(i)] for i in 1..30] (24) [[1,1], [2,2], [3,6], [4,12], [5,60], [6,20], [7,140], [8,280], [9,2520], [10,2520], [11,27720], [12,27720], [13,360360], [14,360360], [15,360360], [16,720720], [17,12252240], [18,4084080], [19,77597520], [20,15519504], [21,5173168], [22,5173168], [23,118982864], [24,356948592], [25,8923714800], [26,8923714800], [27,80313433200], [28,80313433200], [29,2329089562800], [30,2329089562800]] Type: List List Expression Integer ``` [Answer] # PHP, 81 Bytes ``` for($p=1;$z++<$argn;$n=$n*$z+$p/$z)$p*=$z;for($t=1+$n;$p%--$t||$n%$t;);echo$p/$t; ``` [Try it online!](https://tio.run/nexus/php#HcpBCoAgEAXQfef4QSoSrsehs0RUrnQQV@Ldzdw@nj8kyIIzv5Gdo/6kvEHYEaoxfjohMqIeANlRFUQzKs1Z2BmMIau1KK0hriik6L5C@neh3j8 "PHP – TIO Nexus") [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` l /yNÎõ@/XÃx ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bAoveU7O9UAvWMN4&input=OA) ``` l\n/yNÎõ@/XÃx :Implicit input of integer U l :Factorial \n :Reassign to U / :Divide by y :GCD with N : Array of all inputs Î : First element (i.e., original input) õ : Range [1,NÎ] @ : Map each X /X : Divide U by X à : End map x : Reduce by addition ``` [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 35 bytes ``` [ 1 swap [1,b] n/v Σ denominator ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJtYkgEm9IoS89JTiyHsslSQUiinNC8zOT8lVaGgKLWkpLKgKDOvRMGai8vsf7SCoUJxeWKBQrShTlKsQp5@mcK5xQopqXn5uZl5iUADFGL/Jyfm5Cjo/QcA "Factor – Try It Online") [Answer] # [Arturo](https://arturo-lang.io), 38 bytes ``` $=>[denominator∑map..1&=>reciprocal] ``` [Try it](http://arturo-lang.io/playground?auFcT5) ]
[Question] [ ... Ah sorry, no popcorn here, just POPCNT. Write the shortest **program** or **function** which takes in a number `n` and **output** all integers from 0 to 2n - 1, in ascending order of *number of 1 bits in the binary representation of the numbers* (popcount). No duplicates allowed. The order of numbers with the same popcount is implementation-defined. For example, for `n = 3`, all these output are valid: ``` 0, 1, 2, 4, 3, 5, 6, 7 [0, 4, 1, 2, 5, 3, 6, 7] 0 4 2 1 6 5 3 7 ``` The input and output format are implementation-defined to allow the use of language features to further golf the code. There are a few restrictions on the output: * The numbers must be output in decimal format. * The output must contain a reasonable separator between the numbers (trailing separator allowed, but not leading). Line feed (`\n`), tab (`\t`), space, `,`, `.`, `;`, `|`, `-`, `_`, `/` are quite reasonable separator. I don't mind additional spaces for pretty printing, but don't use letter or digits as separators. * The numbers and separators can be surrounded by `[ ]`, `{ }` or any array or list notation. * Don't print anything else not stated above. ### Bonus Multiply your score by **0.5** if your solution can generate the number on the fly. The spirit of this bonus is that if you were to directly convert your printing solution to a generator, the generator only uses at most O(n) memory where n is the number of bits as defined above. (You don't have to actually convert your solution to generator). Note that while I impose n <= 28, the memory needed to store all numbers still grows exponentially, and a naive sorting solution would hog up at least 4 GB of memory at n = 28. Please add some simple explanation of how your solution works before claiming this bonus. [Answer] # Pyth, 9 bytes ``` osjN2U^2Q ``` `o`rder by the `s`um of the base 2 representation (`jN2`) over the range (`U`) of `2 ^ Q`. (`Q` = `eval(input())`). [Try it here.](http://pyth.herokuapp.com/) [Answer] # [Python 2](https://docs.python.org/2/), 72 bytes \* 0.5 = 36 ``` N=1<<input() for k in range(N*N): if bin(k%N).count('1')==k/N:print k%N ``` [Try it online!](https://tio.run/##K6gsycjPM/r/38/W0MYmM6@gtERDkystv0ghWyEzT6EoMS89VcNPy0/TikshM00hKTNPI1vVT1MvOb80r0RD3VBd09Y2W9/PqqAoM69EASj1/78pAA "Python 2 – Try It Online") A new method for this now-ancient challenge. The less-golfed below below might be easier to understand: **87 bytes** ``` n=input() for i in range(n+1): for x in range(2**n): if bin(x).count('1')==i:print x ``` [Try it online!](https://tio.run/##Rci9CoAgFAbQ3ae4mz9BoG2CD1ORdZdPEQV7esOpM5781ifBjYHAyK0qLWIqxMSgsuO@FBarvaC5/V9nDGYTRzoYquv1TA1VSSt1COxzYVTqY2wf "Python 2 – Try It Online") We loop over target popcounts `i` in increasing order, and for each one iterate over the `n`-bit numbers and prints those with exactly `i` set bits. Even though this loops over the `n`-bit numbers many times, it still satisfies the efficiency bonus criteria of only using `O(n)` memory if the loop were converted to a generator. If fact, the golfed code allocates `n` bits to the target popcount as well as `n` bits to the number being checked. They are stored as a `2*n`-bit number, which allows counting up this single number and extracting the first and last `n` bits as needed. --- # [Python 2](https://docs.python.org/2/), 59 bytes ``` lambda n:sorted(range(1<<n),key=lambda x:bin(x).count('1')) ``` [Try it online!](https://tio.run/##LclBCoAgEADAr3hzhQgKuoj@pIuWllSr2Ar2euvQdSY9tEccm9dzO81lV8NQ3jGTWyEb3BwMSqHoDvfo/6u0AaGKfokFCfjAhWgpByTmIWAqBB9MLw "Python 2 – Try It Online") A short sorting-based approach that does not qualify for the bonus. --- # [Python 2](https://docs.python.org/2/), 75 bytes \* 0.5 = 37.5 ``` N=2**input()-1 v=N-~N while v:t=1+(v|~-v);v=N&t|~-(t&-t)/(v&-v)/2;print v^N ``` [Try it online!](https://tio.run/##K6gsycjPM/r/38/WSEsrM6@gtERDU9eQq8zWT7fOj6s8IzMnVaHMqsTWUFujrKZOt0zTGiilVgJkapSo6ZZo6muUqQFF9Y2sC4oy80oUyuL8/v83BQA "Python 2 – Try It Online") Repeatedly generates the next highest `v` with the same POPCOUNT by [this bit-twiddling algorithm](https://stackoverflow.com/q/8281951). Actually, it turned out easier to generate them in decreasing pop-count, then print the complement to make it increasing. That way, then `v` overflows `2**n`, we simply remove all but `n` bits with `&N` where `N=2**n-1`, and that gives the smallest number one popcount lower. That way, we can just do one loop. There's probably a better solution that directly finds the next *lower* number with the same POPCOUNT. Due to a fencepost issue, we need to start with `v=2**(n+1)-1` so that the operation produces `v=N-1` on the first loop. Output for `4`: ``` 0 8 4 2 1 12 10 9 6 5 3 14 13 11 7 15 ``` [Answer] ## J, 19 characters, no bonus. ``` [:(/:+/"1@#:)@i.2^] ``` * `2 ^ y` – two to the power of `y`. * `i. 2 ^ y` – the integers from `0` to `(2 ^ y) - 1`. * `#: i. 2 ^ y` – each of these integers represented in base two. * `+/"1 #: i. 2 ^ y` – the sums of each representation * `(i. 2 ^ y) /: +/"1 #: i. 2 ^ y` – the vector `i. 2 ^ y` sorted by the order of the items of the previous vector, our answer. [Answer] ## Python, 63 chars ``` F=lambda n:`sorted(range(1<<n),key=lambda x:bin(x).count('1'))` >>> F(3) '[0, 1, 2, 4, 3, 5, 6, 7]' ``` [Answer] ## Mathematica, 50 46 ``` SortBy[Range[0,2^#-1],Tr@IntegerDigits[#,2]&]& ``` . ``` SortBy[Range[0,2^#-1],Tr@IntegerDigits[#,2]&]& {0, 1, 2, 4, 8, 16, 3, 5, 6, 9, 10, 12, 17, 18, 20, 24, 7, 11, 13, 14, 19, 21, 22, 25, 26, 28, 15, 23, 27, 29, 30, 31} ``` [Answer] **C 179 \* 0.5 = 89.5** ``` main(){int n,i=0,m,o;scanf("%d",&n);m=~((~0)<<n);for(;n--;++i){for(o=0;o<m;++o){int bc=0,cb=28;for(;cb--;)bc+=o&(1<<cb)?1:0;if(bc==i)printf("%d ",o);}}printf("%d\n",m);return 0;} ``` **EDIT: 157 \* 0.5 = 78.5** ``` main(){int n,i=0,m,o;scanf("%d",&n);m=~((~0)<<n);for(++n;n--;++i){for(o=0;o<=m;++o){int bc=0,cb=28;for(;cb--;)bc+=o&(1<<cb)?1:0;if(bc==i)printf("%d ",o);}}} ``` **EDIT: 132 \* 0.5 = 66** ``` main(){int n,i=0,m,o;scanf("%d",&n);m=~((~0)<<n);for(++n;n--;++i){for(o=0;o<=m;++o){if(__builtin_popcount(o)==i)printf("%d ",o);}}} ``` or a bit nicer formatted: ``` main() { int n, i = 0, m, o; scanf("%d", &n); m = ~((~0) << n); for(++n; n--; ++i) { for(o = 0; o <= m; ++o) { if (__builtin_popcount(o) == i) printf("%d ", o); } } } ``` What it does? ``` m = ~((~0) << n); ``` calculates the last number to show (pow(2, n) - 1) ``` for(++n; n--; ++i) { for(o = 0; o <= m; ++o) { ``` the outer loop iterates over the bit count (so 0 to n-1) while the inner loop just counts from 0 to m ``` if (__builtin_popcount(o) == i) printf("%d ", o); ``` On x86 there is the POPCNT instruction that can be used to count the set bits. GCC and compatible compilers may support the \_\_builtin\_popcount function that basically compiles to that instruction. [Answer] # CJam, 13 bytes ``` 2ri#,{2b1b}$p ``` Pretty straight forward implementation. **How it works**: ``` 2ri#, "Get an array of 0 to 2^n - 1 integers, where n is the input"; { }$ "Sort by"; 2b1b "Convert the number to binary, sum the digits"; p "Print the array"; ``` [Try it online here](http://cjam.aditsu.net/#code=2ri%23%2C%7B2b1b%7D%24p&input=3) [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~18~~ ~~9~~ 8 bytes -9 bytes from @ngn's improvements -1 byte from using `where` instead of `take` ``` <+/!2+&: ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NykZbX9FIW83qf5qCMVeagsl/AA "K (ngn/k) – Try It Online") A tacit function, equivalent to `{<+/!2+&x}`. * `2+&:` generate `x` 2's * `!...` generate "odometer" of the input (in this case this provides the binary representation of the numbers from 0 to pow(2,x)) * `+/` sum column-wise * `<` "grade up" the sums (i.e. sort them by the number of 1's in the binary-representation of each value) [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ÖoΣḋŀ`^2 ``` [Try it online!](https://tio.run/##yygtzv7///C0/HOLH@7oPtqQEGf0//9/YwA "Husk – Try It Online") ``` `^2 flip ^, partially applied, gets fully applied with implicit input, 2 ^ n ŀ range from [0, n) Ö sort by o composed function Σ sum ḋ binary digits ``` [Answer] # JavaScript (ES6) 41 (82\*0.5) The simplest way, golfed ``` F=b=>{ for(l=0;l<=b;l++) for(i=1<<b;i;t||console.log(i)) for(t=l,u=--i;u;--t) u&=u-1; } ``` **Ungolfed** ``` F=b=> { for (l = 0; l <= b; l++) { for (i = 1 << b; i > 0; ) { --i; for (t = 0, u = i; u; ++t) // Counting bits set, Brian Kernighan's way u &= u - 1; if (t == l) console.log(i); } } } ``` **Test** In Firefox/FireBug console ``` F(4) ``` > > 0 > > 8 > > 4 > > 2 > > 1 > > 12 > > 10 > > 9 > > 6 > > 5 > > 3 > > 14 > > 13 > > 11 > > 7 > > 15 > > > [Answer] # Bash + coreutils, 66 One to get you started: ``` jot -w2o%dpc $[2**$1] 0|dc|tr -d 0|nl -ba -v0 -w9|sort -k2|cut -f1 ``` [Answer] # Haskell, (87 \* 0.5) = 43,5 ``` f n=[0..n]>>=(\x->x#(n-x)) a#0=[2^a-1] 0#_=[0] a#b=[1+2*x|x<-(a-1)#b]++[2*x|x<-a#(b-1)] ``` Usage example: `f 4`, which outputs `[0,1,2,4,8,3,5,9,6,10,12,7,11,13,14,15]` How it works: neither sorting nor repeatedly iterating over [0..2^n-1] and looking for numbers containing i 1s. The `#` helper functions takes two parameters `a` and `b` and constructs a list of every number made up of `a` 1s and `b` 0s. The main function `f` calls `#` for every combination of `a` and `b` where `a+b` equals `n`, starting with no 1s and `n` 0s to have the numbers in order. Thanks to Haskell's laziness all those lists don't have to be constructed completely in memory. [Answer] ## Ruby 47 chars Much like the Python one from @KeithRandall : ``` f=->n{(0..1<<n).sort_by{|x|x.to_s(2).count ?1}} ``` [Answer] # Mathematica, 26 ``` Tr/@(2^Subsets@Range@#/2)& ``` Example: ``` Tr/@(2^Subsets@Range@#/2)&[4] ``` > > {0, 1, 2, 4, 8, 3, 5, 9, 6, 10, 12, 7, 11, 13, 14, 15} > > > [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` 2*’BS$Þ ``` [Try it online!](https://tio.run/##y0rNyan8/99I61HDTKdglcPz/v//bwwA "Jelly – Try It Online") ## Explanation ``` 2*’BS$Þ 2* 2^n ’ decremented $Þ sort the (implicit) range using the following two functions: B binary S summed ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` oL<Σb1¢ ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/38fm3OIkw0OL/v83BgA "05AB1E – Try It Online") ``` oL<Σb1¢ # full program Σ # sort... L # [1, 2, 3... o # ...2 **... # implicit input L # ]... < # with one subtracted from... # (implicit) each element... Σ # by... ¢ # number of... 1 # ones... ¢ # in... # (implicit) current element in list... b # in binary # implicit output ``` # Alternative, 7 bytes ``` oL<Σ2вO ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/38fm3GKjC5v8//83BgA "05AB1E – Try It Online") ``` 2вO # full modified section O # sum of... в # list of (base-10) values of digits of... # (implicit) current element in list... в # in base... 2 # literal ``` # Another alternative, 7 bytes ``` oL<ΣbSO ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/38fm3OKkYP///40B "05AB1E – Try It Online") ``` bSO # full modified section O # sum of... S # list of characters of... # (implicit) current element in list... b # in binary ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ‹Eʁµb∑ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%80%B9E%CA%81%C2%B5b%E2%88%91&inputs=4&header=&footer=) ``` ʁ # 0... ‹E # 2 ** (n-1) µ # Sorted by b # binary ∑ # Summed ``` [Answer] # Java 8, 205 ``` public class S{public static void main(String[] n){java.util.stream.IntStream.range(0,1<<Integer.parseInt(n[0])).boxed().sorted((a,b)->Integer.bitCount(a)-Integer.bitCount(b)).forEach(System.out::print);}} ``` [Answer] C++11, 117 characters: ``` using namespace std;int main(){ set<pair<int,int> > s;int b;cin>>b;int i=0;while(++i<pow(2,b))s.insert({bitset<32>(i).count(),i});for (auto it:s) cout <<it.second<<endl;} ``` Ungolfed: ``` using namespace std; int main() { set<pair<int,int> > s; int b; cin>>b; int i=0; while (++i<pow(2,b)) { s.insert({bitset<32>(i).count(),i}); } for (auto it:s) { cout <<it.second<<endl; } } ``` Explanation: Create a set of int,int pairs. The first int is bit count, the second one is the number. Pairs compare themselves according their first parameter, so the set is sorted by bit count. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` óráÅàç ``` [Try it online.](https://tio.run/##y00syUjPz0n7///w5qLDCw@3Hl5wePn//4ZcRlzGXCZcpgA) **Explanation:** ``` ó # Push 2 to the power of the (implicit) input-integer r # Pop and push a list in the range [0,2**input) á # Sort this list by, Å # using the following two characters as inner code-block: à # Convert it to a binary-string ç # And only leave the truthy digits, removing the 0s ``` [Answer] # Perl, 64/2 = 32 ``` #!perl -ln for$i(0..$_){$i-(sprintf"%b",$_)=~y/1//||print for 0..2**$_-1} ``` Simply iterate over the range `[0..2^n-1]` `n + 1` times. In each iteration print only the numbers that have number of 1 bits equal to the iteration variable (`$i`). Bits are counted by counting `1`'s (`y/1//`) in the number converted to binary string with `sprintf`. Test [me](http://ideone.com/q2wj7G). # Perl, 63 Sorting approach: ``` #!perl -l print for sort{eval+(sprintf"%b-%b",$a,$b)=~y/0//dr}0..2**<>-1 ``` ]
[Question] [ Inspired by the [Google Code Challenge](https://code.google.com/codejam/contest/351101/dashboard#s=p2): > > The Latin alphabet contains 26 characters and telephones only have ten digits on the keypad. We would like to make it easier to write a message to your friend using a sequence of keypresses to indicate the desired characters. The letters are mapped onto the digits as shown below. To insert the character B for instance, the program would press 22. In order to insert two characters in sequence from the same key, the user must pause before pressing the key a second time. The space character ' ' should be printed to indicate a pause. For example, 2 2 indicates AA whereas 22 indicates B. > > > Each message will consist of only lowercase characters a-z and space characters ' '. Pressing zero emits a space. > > > ![enter image description here](https://i.stack.imgur.com/1xcix.png) Your challenge is to write the smallest function which takes the input string, and returns the sequence of keypresses necessary to produce the input as string or output it to stdout. The function which is the least amount of bytes wins. **Example Input/Output** ``` phone("hi") 44 444 phone("hello world") 4433555 555666096667775553 ``` **Other clarifications** * Pauses **must** only be added when necessary and must be a space ' '. * Each message will consist of only **lowercase** characters a-z and space characters ' '. Print `0` to signify spaces. * No external libraries. * Only the input string may be passed to your function. * To make other languages competitive, the primary function declaration doesn't count, and nor does importing other standard libraries. `#include`s, `import`s, and `using`s don't count. Everything else does. This does include `#define`s and helper functions. See [rule 2](https://codegolf.stackexchange.com/q/21841/2852) in this question if you are confused. * Multiple spaces can be denoted as `00` or `0 0` since you don't really have to pause between a space [Answer] # Ruby, ~~129~~ ~~122~~ ~~115~~ ~~111~~ ~~108~~ ~~107~~ 105 Done with golfing... Oops, completely forgot to remove unnecessary spaces - fixed... Saved 2 chars thanks to Peter Taylor. [Online version](http://ideone.com/L5FgUm) ``` def t9(t) (t.tr(" ",?`).bytes.map{|c|"09998887777666555444333222"[96-c..-1][/(.)\1*/]}*' ').gsub /(\d) (?!\1)/,'\1' end ``` Explanation: space is translated to the char with the ordinal 96 ``` (t.tr(" ",?`).bytes ``` characters are first mapped to series of numbers: - a to 2 - b to 22 - d to 3222 - h to 444333222 a regex expression then matches the first group of equal digits ``` map{|c|"09998887777666555444333222"[96-c..-1][/(.)\1*/]} ``` the array is joined ``` *' ') ``` all spaces in the occurences of "digit space different\_digit" are removed ``` gsub /(\d) (?!\1)/,'\1' ``` [Answer] ## [REBEL](http://kendallfrey.com/projects/rebel.php) - 154 110 103 ``` ;0 2abc3def4ghi5jkl6mno7pqrs8tuv9wxyz/^;/$<;/([^\d-])(?=\D.*(\d)(\w)*\1)/$2$3-/(\d)-+\1/$1 $1/-//;/$>$` ``` This 'function' accepts input from stdin and sends results to stdout. Test runs (so you don't have to install the interpreter): ``` hi 44 444 hello world 4433555 555666096667775553 yes 999337777 kthxbai 558449922 2444 ``` [Answer] # JavaScript (124) Run in Firefox. ``` t9=s=>s.replace(/./g,c=>'099998887777666555444333222'.slice(36-parseInt(c,36)).match(/(.)\1*/)[0]+' ').replace(/(.) (?!\1)/g,'$1') ``` [Answer] ## GolfScript, 46 chars ``` {).," adgjmptw"&.,.1>*`@@)\;-*}/]{.2$^!" "*\}* ``` As usual, reads input from stdin, prints to stdout. See [online demo (with canned input).](http://golfscript.apphb.com/?c=IyBDYW5uZWQgaW5wdXQ6CjsiaGVsbG8gd29ybGQiCgojIFByb2dyYW06CnspLiwiIGFkZ2ptcHR3IiYuLC4xPipgQEApXDstKn0vXXsuMiReISIgIipcfSo%3D) Note that this code relies on a very strict interpretation of the input spec (only lowercase letters and spaces): in particular, any newlines in the input will crash it! This issue can be fixed, at the cost of two extra chars, by prepending `n-` to the code to filter any newlines out. [Answer] # C++ - 365 characters without `int main(){}` ``` #include<iostream> #include<string> #include<cmath> #define o std::cout<< int main(){std::string s;getline(std::cin,s);for(int i=0;i<s.size();i++){if(s[i]==32)o 0;int j=s[i]-97;if(i>0&&j/3==(s[i-1]-97)/3)o ' ';if(-1<j&j<15){for(int k=j-j%3-1;k<j;k++)o 2+j/3;}if(14<j&j<19){for(int k=14;k<j;k++)o 7;}if(18<j&j<22){for(int k=18;k<j;k++)o 8;}if(21<j&j<26){for(int k=21;k<j;k++)o 9;}}} ``` Uses the same reasoning as my answer [here](https://codegolf.stackexchange.com/a/21352/10766), only using `for` loops to output each letter the appropriate number of times. [Answer] # Perl - 107 ~~110~~ ``` $_=<>;y/ /0/;$z='a';$==2;for$l((3)x5,4,3,4){for$q(1..$l){s/$z/$=x$q.$"/ge,$z++}$=++}s/(.) (?!\1)/\1/g;print ``` Here's my previous solution in 120 ~~128 130 155~~: ``` $_=<>;s//_/g;y/sz/79/;for$x(cfilorvy,behknqux,adgjmptw){s/(\d)_/\1\1_/g,eval"y/$x/2-9/"}y/ _/0 /;s/(.) (?!\1)/\1/g;print ``` Tests: ``` hi 44 444 hello world 4433555 555666096667775553 jackdaws loves my big sphinx 52 222553297777055566688833777706999022444 407777 744 4446699 ``` [Answer] ## VBA 220 253/258/219 Not counting `Function` lines here: With `String`, **253**: ``` Function t(s) For Each c In Split(StrConv(s,64),Chr(0)) If c<>""Then If c=" "Then t=t & 0 Else b=Asc(c)-91:n=String(IIf(b>27,(b-4)Mod 4+1,IIf(b>23,(b-1)Mod 4+1,b Mod 3+1)),Trim(Str(Int(b/3)-IIf(b=24Or b=27Or b>29,1,0)))):t=t &IIf(Right(t,1)=Left(n,1)," " &n,n) Next End Function ``` With a `For` loop **258**: Added corrections for 7/9 key (thanks, Danny), which added a lot of chars. ``` Function t(s) For Each c In Split(StrConv(s,64),Chr(0)) If c<>""Then n="" b=Asc(c)-91 For i=1To IIf(b>27,(b-4)Mod 4+1,IIf(b>23,(b-1)Mod 4+1,b Mod 3+1)) n=n &Int(b/3)-IIf(b=24Or b=27Or b>29,1,0) Next t=t &IIf(c=" ",0,IIf(Right(t,1)=Left(n,1)," " &n,n)) End If Next End Function ``` Using `Choose` **219**: I didn't want to run with this one, since is more basic in functionality, but it *is* the shorter code... ``` Function t(s) For Each c In Split(StrConv(s,64),Chr(0)) If c<>"" Then:b=Asc(c)-96:n=Choose(b,2,22,222,3,33,333,4,44,444,5,55,555,6,66,666,7,77,777,7777,8,88,888,9,99,999,9999):t=t &IIf(c=" ",0,IIf(Right(t,1)=Left(n,1)," " &n,n)) Next End Function ``` [Answer] # C, 165 163 153 149 138 chars ``` k(char*s){char*m="`cfilosvz",l=0,i,c;while(*s^0){for(i=0;*s>m[i];i++);c=*s-m[i-1];i==0?i=-1,c=1:i==l?putchar(32):1;while(c--)putchar(i+49);l=i;s++;}} ``` My first attempt at code golfing, any suggestions are appreciated. [Answer] # C++ - 170 168 160 **Golfed:** ``` #define t std::cout<< void g(char*s){char v,p,b,l=1;while(*s){v=*s++-97;p=(v==18)+(v==25)+(v-=v/18+v/25)%3;b=v<0?48:v/3+50;if(l==b)t' ';while(p--+1){t(l=b);}}} ``` **Ungolfed** ``` void numpresses(char* s) { char lastbutton = 1; const char asciiOffset = 97; while(*s) { char val = *s++ - asciiOffset; char presses = (val == 18) + (val == 25) //Z and S are special cases. Check for their ascii codes. + (val -= val / 18 + val / 25) % 3; //Simple mod 3 for number of presses. Also apply offset for characters above s and z. char button = val < 0 //If the character is a space... ? '0' //The button character needs to be 0 : val / 3 + '2'; //Buttons are offset by the ascii code for the number 2 if (lastbutton == button) //Add a space if we need to pause { std::cout << ' '; } while (presses-- + 1) //Print the button once for each press required { std::cout << button; lastbutton = button; } } } ``` [Answer] # C: 136 characters ``` p(char*s){int i,c,l=1;while(c=*s%32,*s++)for(i=l!=(l=(c+149-c/18-c/25)/3-!c);i++<(c-!!c-c/18-c/25)%3+(c==19)+c/26+2;putchar(i^1?l:32));} ``` And slightly ungolfed (yes, that is how it was written): ``` p(char*s){ int i,c,l=1; while(c=*s%32,*s++)for( i=l!=(l=(c+149-c/18-c/25)/3-!c); i++<(c-!!c-c/18-c/25)%3+(c==19)+c/26+2; putchar(i^1?l:32) ); } ``` I might be able to cut it down a little by applying some recursion, black magic and a fair amount of chili powder. [Answer] # Java - 243 Pretty naive java solution. Thanks to commenters for suggestions. Fixed a bug that sometimes inserted unnecessary spaces, e.g. for the input "hello worlds sup". ``` private static void t9(String s) { String[]t=",,abc,def,ghi,jkl,mno,pqrs,tuv,wxyz".split(",");String o="";int i,j,k,l=0;for(char c:s.toCharArray()){if(c==32){o+='0';l=0;}else for(j=0;j<10;j++){int n=t[j].indexOf(c);if(n>=0){if(j==l)o+=' ';for(k=0;k<n+1;k++)o+=j;l=j;}}}return o; } ``` [Answer] # CoffeeScript - 202 (210 - 8) ``` t9=(s)-> t=[3,3,3,3,3,4,3,4];l=-1;r="" for c in s n="";d=c.charCodeAt(0)-96 if c is ' ' n=0 else((n+=k+2 for x in[0...d];break)if d<=v;d-=v)for v,k in t r+=if n[0]is l[0] then " "+n else n l=n r ``` [Answer] # APL, 77 chars ``` {{⍵,⍨⍺,''↑⍨=/↑¨⍺⍵}/('0',⍨(⌈3.1×y-⌊y)/¨⍕¨2+⌊y←7.99,⍨.315×⍳25)[⍵⍳⍨⎕UCS 96+⍳26]} ``` **Explanation** * `2+⌊y←7.99,⍨.315×⍳25` or, ungolfed, `y←(0.315×⍳25),7.99 ◇ 2+⌊y` samples a suitably tilted line (y = 0.315 x) on the points from 1 to 25; the line is tilted in such a way that the floor of these y values follows the repeating pattern 000111...777 except for the sixth group of digits 5555; a number is appended at the end to get the fourth 7, so that the final array plus 2 is 22233344455566677778889999; * `⌈3.1×y-⌊y` amplifies the difference between those y values and their floors, so that the ceilings of the differences give the pattern 123123... with a 4 on the last digits of the two groups of 4 digits; * `'0',⍨( ... )/¨⍕¨ ...` or `(( ... ) /¨ ⍕¨ ...),'0'` uses the latter result to duplicate digits from the former, so that the output is the array of strings "2" "22" "222" "3" "33" "333"... with the correct "7777" and "9999" in place, and a "0" appended to the end; * `⍵⍳⍨⎕UCS 96+⍳26` or `(⎕UCS 96+⍳26)⍳⍵` computes the index of each input char, where "a" is 1, "z" is 26, and space (and every other char) is 27; * `{ ... }/( ... )[ ... ]` takes the latter result, the index for each input char, to translate each char into the respective string of digits, then concatenates the strings using the function in braces; * `{⍵,⍨⍺,''↑⍨=/↑¨⍺⍵}` or `{(⍺,(=/↑¨⍺,⍵)↑''),⍵}` appends each new string ⍺ to the accumulator ⍵, interposing a single space only if both arguments start with the same char. **Examples** ``` {{⍵,⍨⍺,''↑⍨=/↑¨⍺⍵}/('0',⍨(⌈3.1×y-⌊y)/¨⍕¨2+⌊y←7.99,⍨.315×⍳25)[⍵⍳⍨⎕UCS 96+⍳26]} 'hello world' 4433555 555666096667775553 {{⍵,⍨⍺,''↑⍨=/↑¨⍺⍵}/('0',⍨(⌈3.1×y-⌊y)/¨⍕¨2+⌊y←7.99,⍨.315×⍳25)[⍵⍳⍨⎕UCS 96+⍳26]} 'the quick brown fox jumped over the lazy dog' 84433077884442225502277766696603336669905886733 3066688833777084433055529999 999036664 ``` [Answer] # Python ~~155~~ 150 I wish i was better at this XD. Function definition not counted. First indentation level is a space, second is a tab, and third 2 tabs. ``` def p(s,l=None): for c in s: for i,g in enumerate(" ,,abc,def,ghi,jkl,mno,pqrs,tuv,wxyz".split(",")): if c in g:print"\b"+[""," "][l==i]+str(i)*(g.index(c)+1),;l=i ``` [Answer] # JavaScript 234 `for(l=-1,r="",I=0,y=(s=prompt()).length;I<y;I++){c=s[I];n="";d=c.charCodeAt(0)-96;if(0>d)n=0;else for(k=J=0;J<8;k=++J){v="33333434"[k];if(d<=v){for(x=K=0;0<=d?K<d:K>d;x=0<=d?++K:--K)n+=k+2;break}d-=v}r+=n[0]==l[0]?" "+n:n;l=n}alert(r)` [Answer] ## R 224 I'm sure there's a better way to do this, so I'm going to keep working on it. ``` a=strtoi(charToRaw(scan(,'',sep='\n')),16L)-95;a[a<0]=1;b=c(0,2,22,222,3,33,333,4,44,444,5,55,555,6,66,666,7,77,777,7777,8,88,888,9,99,999,9999)[a];c=append(b[-1],0)%%10;d=b%%10;b[c==d]=paste(b[c==d],'');paste(b,collapse='') ``` ]
[Question] [ This is different from [Floating Point XOR](https://codegolf.stackexchange.com/questions/192862/floating-point-xor), and more in the spirit of a comment by R.. GitHub STOP HELPING ICE on that challenge, but I thought of this idea independently. ## Generalized XOR The bitwise exclusive or (XOR) operation is usually considered in terms of integers, but it can be naturally generalized (extended, in fact!) to real numbers. There are some finicky details when asking which representation to choose for finite expansions, but to simplify matters, we will only use binary floats. For example, `3.141592653589793 ^ 0.2` is ``` 3.141592653589793: 11.001001000011111101101010100010001000010110100011000 0.200000000000000: 00.0011001100110011001100110011001100110011001100110011010 11.000101110000110001011001101110111011011010010000010... ≈ 3.090032203987506 ``` The values were written out exactly and a bitwise XOR performed. Note that the result is not always exactly representable as a double, but we can round. ## Challenge Given two positive (IEEE-754) double-precision floating-point numbers, find their XOR as *numbers*. The answer must have a *relative* accuracy of `1e-6`, i.e., the error should be at most `1e-6` times the correct answer. (The error bound is there because the result is not always exactly representable.) Examples (rounded to within 1 ulp—answers may vary): ``` 1 ^ 2 -> 3 3.141592653589793 ^ 2.141592653589793 -> 1 2.718281828459045 ^ 2.141592653589793 -> 0.5776097723422073 (funnily close to the Euler–Mascheroni constant) 1000000000 ^ 0.1 -> 1000000000.1 0.002 ^ 0.0016666666666666668 -> 0.0036340002590589515 0.002000000000000001 ^ 0.002 -> 8.6736173798840355e-19 1e+300 ^ 1 -> 1e+300 1e+300 ^ 4e299 -> 1.2730472723278628e+300 0.1 ^ 0.1 -> 0 7.888609052210118e-31 ^ 5.380186160021159e-32 -> 8.426627668212235e-31 ``` ### Notes Subnormal numbers ([1](https://en.wikipedia.org/wiki/Subnormal_number)), nonpositive numbers, and non-finite numbers do not need to be supported, but it should output zero when the operands are equal. Standard loopholes are of course not allowed, and the inputs may be given in any format corresponding closely to a float (decimal, 64-bit integer bit representation, etc.). This is a code golf question; may the shortest answer win. [Answer] # JavaScript, 47 bytes ``` f=(x,y,k=8**341)=>k&&k*(x<k^y<k)+f(x%k,y%k,k/2) ``` [Try it online!](https://tio.run/##dU/tasMgFP29PoV/1mhqnVdjq9D0RUILIejYDLVUKcnTZ3FhZR3swIV7zz3nfny29zZ2t49r2t71NLkaD3SkvtZlKSsg9dGv177Ew8Gfx4MnG4eHV0/HOfybIFOyMXVttBHVqGmAInGiqJEMKlBG7JRU2uyNnPm/VNYJtgctdI5KGV6pf3TAf0ARZ5ApzjgXueIcds/Qjz5/Aizy7wvBbmSeBr@LygpjFjMsi04rF24I9zahhIJDj3fJ6qULlxh6y/rwjlPDZ19xLihKTZ5ZbI9z7jBjLBEyfQE "JavaScript (V8) – Try It Online") `k` runs through every representable power of 2 and adds it to the result, or not, as appropriate. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes ``` Plus@@Apply@Xor//@{0,(i=#2;2^--i#&/@#)&@@@#~RealDigits~2}& ``` [Try it online!](https://tio.run/##bU7BasMwDL3nNwxhC45jybFjMzo02LmU7TIYC5jSboa0K212GCH59SzuCKyjD4Skp6cn7Xz7sdn5Nqz9uF2Mq@brRPRwODTf9PJ5LArqJL8JC4Z3WOd5YGlB7DYlIjY8bXzzGN5DexqwT8fVMezbV5bfL2lL7C2lbDk8r/1@6JIOOPY86ZSAErRDo5W2rnKK438mylBUYNHGKLWTpb4uAzmDSwGRkWJqkMcE5hJ2nqO8AJzV5@8gq9XkBX/qMqvRud9VmK9UwlprpJMaESSAzepcAddCWQnWgJn8YPo20tgn/fgD "Wolfram Language (Mathematica) – Try It Online") Input two `Real`s in a list. Also works with an arbitrary even number of `Real` arguments. [Answer] # [Python 3](https://docs.python.org/3/), 57 bytes ``` f=lambda a,b,e=8**341:e and(a//e+b//e)%2*e+f(a%e,b%e,e/2) ``` [Try it online!](https://tio.run/##bVDLbsMgELz7K7hEAodgdjH2EikfgxuiIsUP2e4hX@9CqkZ125VmQcvszIjpsb6Pg9liP43zypbHUiSoJaxzePuYlzgO99jHlYMuSyu22@Xu@@7qmZedDBcqS1PDOTA/XLmvqnDsUhMHLMPxxv0hyC4hVJg2xzkvsTgwXnCjoAbrsLHGkmudkVqh3pWQBQeJ@fjLxt@TTEPVAiFl1Nbp2v5Pg5dFMoU80UprlLlDsy96Pe/DwZP9DAfhaJIU/LjXAZ372oRvj1YRUaOdtoigASicDEirDGmgBpqkBilqmmZVcWbTHIeVp1@UnRDF9gk "Python 3 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~202~~ 196 bytes *-6 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` double a,b,t;long*c=&a,*d=&b,r,e,m=1L<<52;main(){scanf("%lf%lf",c,d);b>a?t=a,a=b,b=t:0;for(r=(*c&m-1|m)^(*d&m-1|m)>>(*c>>52)-(*d>>52),e=*c&m*4095;*c^*d&&!(r&m);r+=r)e-=m;*c=e|r&~m;printf("%f",a);} ``` [Try it online!](https://tio.run/##bY5bCsIwFES3ooIhibfSV9Qab9yAaxCSNBWhaSXWLx9br1H8FOZjOByYscnJ2nGs@5tp3USDgUG2fXfiFokGXiMxEMCBx@yw24lcen3uKLtfre4aOpu3TcwMLNRMGqX3A2rQaMDgsE1l0wcakHJLfJI9PDtSXv@qUhErJXKWRPgt4PBj8jKthOT2GF0ypYF4JsMCA3MJ@sjRPQJ5eXkJ5274fIj7msnnOBbLrMxEla9EITbVuircIk0n@T/6Bg "C (gcc) – Try It Online") What the program basically does: * save two doubles from `stdin` into variables `a` and `b`; if needed, swap the two doubles so `a>b` always; * take the exponent of `a` as the exponent of the result; * take the fraction parts of `a` and `b`, the leading implicit bit, left shift `b` (according to the exponents difference), and XOR the two values to obtain the fraction of the result; * finally, in the result if there are leading zeros in the fraction, remove them (and decrement the exponent). [Answer] # x86-64 machine code, x32 ABI, ~~64~~ ~~58~~ ~~55~~ ~~54~~ ~~53~~ ~~49~~ ~~48~~ ~~46~~ 44 bytes xxd output: ``` 00000000: 87fc 5859 5e5a 6629 d17d 0548 96f7 d9eb ..XY^Zf).}.H.... 00000010: 01ca 6683 f940 7d0f 48d3 ee48 31f0 87d1 ..f..@}.H..H1... 00000020: 7805 48d1 e0e2 f951 5089 fcc3 x.H....QP... ``` In assembly, with comments: ``` xor_double: xchg esp,edi # save stack pointer and points new stack at the input # long doubles are 80-bit floating point numbers, # with the low 8 bytes giving the significand and the high 2 bytes giving the exponent # Conveniently, long doubles have an alignment of sixteen, so the "stack" now looks like: # rsp --> significand of first argument # rsp+8 --> exponent of first argument (plus six bytes of junk) # rsp+10 --> significand of second argument # rsp+18 --> exponent of second argument (plus six bytes of junk) # So, just 4 pops puts all the arguments into registers: pop rax # rax=sig1 pop rcx # rcx=junk48:exp1 pop rsi # rsi=sig2 pop rdx # rdx=junk48:exp2 # check which argument is greater and swap the two if the second is greater. Otherwise swap them sub cx,dx # find difference of exponents jge good # jmp if exp1 >= exp2 # exp1 < exp2, switch around the arguments xchg rsi,rax neg ecx # note that dx is unchanged and is now the biggest exponent- this will also be true in the other branch # This next two opcodes assemble together to EB 01 CA. If decoded from here, that is "JMP $+1 ; .byte CA", which skips the CA byte # But the "jge good" earlier jumps to the middle of EB 01 and so it is instead decoded as "01 CA", or "add edx,ecx" .byte 0xEB good: add edx,ecx # dx=cx-dx+dx=original value of cx, the biggest exponent switched: cmp cx,0x40 #ratio >= 2**64, just return initial number jge dontxor shr rsi,cl #shift the smaller significand so they line up xor rax,rsi # the significand of a floating point number always has 1 as its MSB. # so if it's missing, shift the bits around to restore it # i.e. multiply significand by two and subtract one off the exponent until the MSB is 1 xchg ecx,edx subnormal_loop: #multiply significand by two and subtract exponent by 1 until either exponent is zero or the number is normal js dontxor #done shl rax loop subnormal_loop #decrements ecx and jmp if not zero dontxor: # return output in long_double[1] # put exponent in place push rcx # put significand in place push rax # restore the stack pointer mov esp,edi ret ``` Takes a pointer to an array of [80-bit x87 long doubles](https://en.wikipedia.org/wiki/Extended_precision#x86_extended_precision_format) and returns in the 2nd element of the array. Uses the [x32 ABI](https://en.wikipedia.org/wiki/X32_ABI) (not to be confused with x86-32), which is just like the usual System V ABI, but all pointers are 32 bits. The padding outside the actual 10-byte long doubles is allowed to be garbage, not zero, which means we have to be careful when comparing or using FLAGS results from operations on exponents: 16-bit operand-size is necessary because we loaded the whole qword including high garbage into the full register. Because it uses the x32 calling convention, you can compile this and link it with a C program to test it, with the function prototype `void xor_double(long double[2])`. You will need to compile it as x32, though. The strategy is to shift the smaller number's significand to the right, by the difference in exponent. This aligns the significand to the place-value position of the significand of the larger, like they were fixed-point. (This may mean shifting out all the bits if the exponents are different by 64 or more, but x86 scalar shifts mask the count by &63 or &31 so we need to special-case that). Then xor the aligned significands and use this as the 64-bit significand with the larger exponent. 80-bit long double has an *explicit* leading 1 in the 64-bit significand, unlike 64-bit double (IEEE binary64) using an implicit 1 (implied by a non-zero exponent field). That means shift/xor Just Works on the significand field directly. But we still need to renormalize when equal exponents cause the leading 1 bits cancel between significands. Other than subnormals (where the exponent field is zero), `long double` values with bit 63 clear are not valid. (8087 and 80287 allow them as "unnormal" according to Wikipedia, but hardware operations on such a value on 387 and later treat them as invalid, producing NaN. All x86-64 CPUs include 387-compatible FPUs, and we need 64-bit mode to make it convenient to deal with a 64-bit significand.) The renormalization uses a `loop` command, which decrements the exponent and jumps back to the start of the loop. This is necessary because if the significand is zero, the exponent must also be cleared or the result is an invalid floating point number. This actually clears `rcx` in that case, not just `cx`, which potentially makes the program take (much) longer, but is harmless otherwise. The renormalization loop also handles the case of two equal inputs, where xoring aligned significands leaves zero. We shift left (and decrement the exponent) until a 1 bit appears at the top of the significand (normal case), or the exponent field becomes zero. (Producing a subnormal or a zero). This handles the equal-input case because left-shifting an all-zero significand will never shift a 1 to the top, so eventually the exponent becomes zero. If there is a 1 bit somewhere but the exponent becomes zero before it gets to the top, in that case it is a valid subnormal value. (Too small to be representable as a normalized float.) The question doesn't require us to support subnormal inputs or outputs so the actual correct value isn't required in this case, although it probably is correct. This ended up being shorter than `lzcnt` / `shl` plus branching for special cases. At the end, it returns a `long double*`, which "conveniently" points to `[rsp]` right after the function call. Returning a pointer into the calling function's stack frame is perhaps somewhat malicious compliance with the calling conventions, but it works! Some general notes on registers: * I avoid `rbx`, `rbp`, and `rsp` as registers because the System V ABI forbids changing them without saving their previous value, which costs some bytes. * I avoid `r8-r15` because they cost an extra byte for most uses. * In most cases using a 32-bit register saves some bytes, so I only use `cx` and `dx` when the junk in the higher bits of the registers would get in the way. * Using `rax` instead of any other register for one of the significands saves a byte on `xchg`, since `xchg rax,[anything]` is two bytes instead of three. * `ecx` has many special uses. It is the only register allowed for `shr [reg],cl`, and `rcx` is the only one used by `loop`. That is why the `xchg ecx,edx` is required to put the exponent in this special register. [Try it online!](https://tio.run/##jVZtj@O2Ef6uXzG1GzTN2j692ZK3vQC5Qz6kaNACybfLYUFLtMxdmRRIaa3tn788JCVL@5JrDvCeTc7M88zwmSGZMfx8qJ/WVVF82QjZ8vrOPMmW9SRVo/lR9MGmqtWB1dQrfVeq7lDzINiUrGWBKZg83h2VPrP2NtiYVgtZ0eKbf/9I@PwmF0GDlfZ4x3Rl/tCO1t/T1fItIxuoUCW/q7ms2tNs89cTJ7tDwtA3gg5PLTd/seZ9X87M3nVGvzsI@Q7LC5Bved9@mdK5DQj/@uJUETfNipeClmTYIyfTsuKBGmULo4nJ0n83JPll2GQttWAhZNO1gQu0pFoB1cc2xDSnPFwfREvHWrHWMnJRSHbnA9dmNXhdRHtysWp1odwnQ5V4tA522YhKiqMoLA37sWsnUZ0ofm3L@0ZJLtsh9EclH7kUWKifVs/pnWyeTBKrEf4MC1JHQPUt53JFRrlwC5frApq4wFs9GKrFw1C3JZE2jf22xkHOSSLQUWjTogRV50LPHG5y7zAyfcP626bujOUy5AeL@04@/H0eJQrfgjW8ULZKb@FG@Svcl@b/B/gXtcJvME1xkI0hnDyOua5dqcYgBpJoFWleCQPxmFsvDjiQRnct7d/3oB1Ny4VbLvr3FizNb0FxtmusKvHXOsXTcumcyrlTPOqwOHEo9HISxWlKDq1Sac5GQZsLaxzx9qJIHL3SfD0myw39B@v6Igy/Opw9iukOVPQr0LCIRwG/UhyPXHNZcFu5sdDGmd9XnCqlSk/w/txYTJsoff@e5tzd2j/dEmSI3nA5qG4Q/rXMwdS8KM4KVXULkqOZi36MJlWLDE9oVhBFXp0sTkxW3HcSFqyybdyDqCqOox1Zr7GK7YvA8bIa7XBAHN3Zhnf2ytaFDpoh4Aj2q/WQmDGupqqxEwoC8aMW7qrizgvy@PEDhRF9/GFDPx2p5NaypKNWZ4IBX3nKiLb418//pb/eRPQP2lhNwmWxGk7WPAiI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LY7wAJTGcWZJttvguzPAuTdJclWb7NYBzF4TYJk12OaGv7g6LNNsriaJulIdDSbJtFaZru4jQK4Z5kqbNLfwc "Assembly (gcc, x64, Linux) – Try It Online") Note that TIO doesn't appear to support the x32 ABI, so I simulated it by using `mmap` to create a new stack at a 32 bit address. [Answer] # [C (gcc)](https://gcc.gnu.org/), 223 bytes ``` typedef double D;D f(D x,D y){D z;long m,o,a,c,b,d;x<y?z=x,x=y,y=z:0;m=-1lu>>12;o=1l<<52;a=*(long*)&x;b=*(long*)&y;c=a>>52;d=b>>52;b=__builtin_clzl(a=(a&m|o)^(b&m|o)>>(c-d<53?c-d:53))-11;a=a?a<<b&m|c-b<<52:0;return*(D*)&a;} ``` [Try it online!](https://tio.run/##fVFtb4IwEP6sv6IxmSmukB5QBUvxCz9jmSkvGhIEw2ChOn@7K/g2t2SXtNd77ulzd21ibpPkfG7UPkuzDUqrNi4yFPEIbXCEOhIhZRwjdOBFVW7RjlREkoTEJOVdoFYH0ZFOKKLEYUn5TphQtGEINq8EFEHAbC7FDPdXZ8a04/EjUDwRMgw1IxXx4GOxXsdtXjR5uU6KQ4GlwHK6@6qMdxwPPgxxYqYBc1baLZljGCaAriBXMgh6SmLGfVHdSp01bV3OcKRLSX46f1Z5iprso8HXCTtym1UZ6DgeXYMaCT24TiqDj0f7Oi@bDZ68WMAydNnN8HJ4KyekV1EE1Zp7Go81F@1kXuJBcCgGBNm90BA4FrjAfHvOHOb5C9/Ryd/QnWxbC/Bsr18u86nL/iMDvRlB1II7Ti1K7R6iFObP5j2T6JPB5c6jdchenV4c/iBuZvv@Dy24d3D5AkT125y/AQ "C (gcc) – Try It Online") (-11 bytes @ceilingcat) I thought directly manipulating the bit representation would be the shortcut, but it wasn't.. A bit ungolfed, ``` typedef double D; D f(D x,D y){ D z; long m,o,a,c,b,d; x<y?z=x,x=y,y=z:0; m=-1lu>>12; o=1l<<52; a=*(long*)&x; b=*(long*)&y; c=a>>52; d=b>>52; b=__builtin_clzl(a=(a&m|o)^(b&m|o)>>(c-d<53?c-d:53))-11; a=a?a<<b&m|c-b<<52:0; return*(D*)&a; } ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes ``` F²⊞υN≔X²⁺φ²³η≔⁰ζW⌈υ«F﹪ΣEυ‹κη²≧⁺ηζ≧﹪ηυ≧∕²η»⭆¹ζ ``` [Try it online!](https://tio.run/##bY7BisIwEIbP9inmOGGrpHEv4knwItil6BNUzTbBtJGmo8suPnuc2MOCeMrk/4bvn6Op@6OvXYzfvgdUAioKBimHTXeh4Yvag@5RiGW2CsE2HVb@xoHKoXIUsJBS5qDmQuRg/pc4@@XfzVinAcv6x7bUIgkBf9nkWVT6EzmPe47L@pL6tjoEPCdNkineZTD6drYxA6ZCxqN68gJH3xPTG7y2V3vSrB3PvGdVb7sB9wM/TTqgSFqxjLGYSf0xlxI@06AWizi9ugc "Charcoal – Try It Online") Link is to verbose version of code. Note: Charcoal requires floating-point numbers to contain a `.`, which is why the link uses `1.0e+300` as the first input. Explanation: ``` F²⊞υN ``` Input the two numbers. ``` ≔X²⁺φ²³η ``` Start at `2¹⁰²³`. ``` ≔⁰ζ ``` Start with a zero result. ``` W⌈υ« ``` Repeat until the inputs are zero. ``` F﹪ΣEυ‹κη² ``` If exactly one of the inputs is less than the power of `2`, then... ``` ≧⁺ηζ ``` ... add that power of `2` to the total. ``` ≧﹪ηυ ``` Subtract the power of `2` from those inputs that are not lower. ``` ≧∕²η ``` Halve the power of `2`. (Sadly I can't use `Halve` here because it rounds the result for some inexplicable reason.) ``` »⭆¹ζ ``` Format the result as a float. (Charcoal defaults to formatting large floats as an integer.) [Answer] # [Swift Language](https://www.swift.org), 113 bytes ``` typealias D=Double;let c=D(bitPattern:1<<32);let x:(D,D)->D={D(bitPattern:($0*c).bitPattern^($1*c).bitPattern)/c} ``` [Try it online!](https://tio.run/##bY/dSsQwEIXvfYpc7EWiaZzJX5N161UewCcQuiVCoKxlN@KK@Ow1VRabxQMJzJczcyan9/SS9Tznjyn2Y@pPJHTh9W0/xocxZjJ0ge5TfupzjsfDFnc7JdnPy3lLAw@seQzdZ@WhG7gdmPgjz3SDNWH3w9c8HdMh0zNFLhm7uVRiSpyUq8EVlKJFJ91ytPGgDSdSoEbjpTXKON96tbIjXMQJiPUgEABygQBoa7lrG1TC3671qhjv1BKB/zAdpffVRLzepRXOOQsejJQIiC42qpiMUA7QWbQlDcsXC15S528) Based on the 87 byte GCC answer. Unfortunately swift's verbosity gets in the way of brevity when bitcasting [Answer] # [Assembly (gcc, x64, Linux)](https://gcc.gnu.org/), custom ABI, ~~39~~ 37 bytes xxd dump: ``` 00000000: 5f58 595e 5a29 d17d 0548 96f7 d9eb 01ca _XY^Z).}.H...... 00000010: e305 48d1 eee2 f948 31f0 87d1 7805 48d1 ..H....H1...x.H. 00000020: e0e2 f957 c3 ...W. ``` Uses the System V ABI, but returns long doubles in cx:rax, high bits of variables passed on the stack must be zeroed, and `rsp` is decremented by `0x20` per call. ``` xor_double: # Custom ABI: like System V but returns long doubles in cx:rax, zeroes out high bits of stack variables, and decreases rsp by 0x20 # System V passes long doubles on the stack. long doubles are 80-bit floating point numbers, # with the low 8 bytes giving the significand and the high 2 bytes giving the exponent # Conveniently, long doubles have an alignment of sixteen, so the stack looks like # rsp --> return address # rsp+8 --> significand of first argument (plus six bytes of zeroes) # rsp+10 --> exponent of first argument # rsp+18 --> significand of second argument (plus six bytes of zeroes) # rsp+20 --> exponent of second argument # So, just 5 pops puts all the arguments into registers: pop rdi # rdi=return address pop rax # rax=sig1 pop rcx # rcx=0:exp1 pop rsi # rsi=sig2 pop rdx # rdx=0:exp2 # check which argument is greater and swap the two if the second is greater. Otherwise swap them sub ecx,edx # find difference of exponents jge good # jmp if exp1 >= exp2 # exp1 < exp2, switch around the arguments xchg rsi,rax neg ecx # note that edx is unchanged and is now the biggest exponent- this will also be true in the other branch # This next two opcodes assemble together to EB 01 CA. If decoded from here, that is "JMP $+1 ; .byte CA", which skips the CA byte # But the "jge good" earlier jumps to the middle of EB 01 and so it is instead decoded as "01 CA", or "add edx,ecx" .byte 0xEB good: add edx,ecx # dx=cx-dx+dx=original value of cx, the biggest exponent switched: jrcxz equal shr rsi #shift the smaller significand so they line up loop switched equal: xor rax,rsi # the significand of a floating point number always has 1 as its MSB. # so if it's missing, shift the bits around to restore it # i.e. multiply significand by two and subtract one off the exponent until the MSB is 1 xchg ecx,edx subnormal_loop: #multiply significand by two and subtract exponent by 1 until either exponent is zero or the number is normal js done #not subnormal shl rax loop subnormal_loop done: push rdi #push return address ret ``` [Try it online!](https://tio.run/##lVZtb9s2EP6uX3FzVqxDbFdvtpVsLdAU/dBhxQa02JeuCGiJkplIpEpKttw/n92Rki0n7tAGcBKTd/c8d/fwSGYMr9blflak6cNcyIaXt2YvG9aBVLXmuei8eVGqNSuhU/o2U@265J43z1jDPJMymd/mSlesufbmptFCFjB59udbwM@/cuLVuNLkt0wX5pt2MHsFB8tzRhQoVRm/Lbksms1o8@OGA@2AMPBMwHrfcPMTmXddNjJ70Rr9Yi3kC1yeIPmGd83DMZ1rzwP8uYA3rWlUBa9v3l1DKe45fNibhlfwD6zbBjRvWi0NlApjOk8DQoJm3bXOuil85VrhkkLbjSg2sBYNfsvBNCy9hy3TgpHPFJjMIOOp5sygvTY1Mge/C/2ByAG3ZoZMTiCVhAbztlHnp1tMc0j8GQJDXirWUPa1wsKCbKs112baA@xEs7FRSrWDxBUOCrElBxtcFFLkIiWm9KE1m1P41JZ3tZJcNkMRldxyKXCh3E9P6W3YlmM4YCWGr9DCVkd0DedyCkYd80I/dW9sE/qwtkz4M0O1uE4AyzLNjRkZXCbOYEwfIXKhTYPFKVoL@rwuW0O4fS5o4Vr36zhU4NtQQ3ZP45wYJ@dwDU8VFfDHgMOnwI8CDSpRU7hDycICm1wbqFvUGytLW8bBliTaKCxZIVBT2vRiRwfQmcAo@PvlmYJaAxwDF/T7JSYWHJdTu5x2L/1rZDnaMDagEWQfjnCsfdbbh4PK0w3HTu82It0ca4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mQS7HEp2KkIb1/4twp0XDvw1gbdJSmd5mSAvTfCp33DgmktknxTEI73haeg8BhF44D@JgcRUuF9EiuVpdRRA9XjljE85XQRIm9IkXV3688NDPi/ks8H0fFu6vF8zDyA@j4CoMg2UQBKtgtbyKgsUiSYIoXC0TfnnlU7B46cfLKInjKAzDKI4WUbKM0H6JkIhpzbzVfJEs/VWy8qN4uYpWyWKFxkHoLyI/WiYYbUZfIJgvglUYLFaxj2jxarEK4jhehnHgo3u0iq1d/B8 "Assembly (gcc, x64, Linux) – Try It Online") The overall strategy is similar to my [other answer](https://codegolf.stackexchange.com/a/247235/58834), and most of @PeterCordes's very helpful contribution still applies. This answer saves: * two bytes by avoiding otherwise useless pushes at the end (and thus decrements `rsp` by two). This also makes a loop strategy `jrcxz; shr rsi; loop` shorter than `cmp cx,0x40; jge; shr rsi,cl`. I can't use that in the first answer because it depends on `rcx`, which is full of junk. * one byte every time `ecx` or `edx` is used instead of `cx` (which can only be done by insuring that the higher bits are set to zero in the function call). * five bytes by returning in `rax:rdx` instead of the x87 stack, which removes the need to push the result back on the stack and use `fld tbyte ptr [rsp]` to load it into the x87 stack. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 10 bytes ``` k⁋E*÷꘍k⁋E/ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCJr4oGLRSrDt+qYjWvigYtFLyIsIiIsIlszLjE0MTU5MjY1MzU4OTc5MywwLjIwMDAwMDAwMDAwMDAwMF0iXQ==) or [Verify all test cases!](https://vyxal.pythonanywhere.com/#WyLhuItqIiwixpsiLCJr4oGLRSrDt+qYjWvigYtFLyIsIjtaxpvDt8O44biLJHbDuOG4i2AsIGBqw7hCJFwiYCA9PiBgaiIsIltbMSwyXSxbMy4xNDE1OTI2NTM1ODk3OTMsMi4xNDE1OTI2NTM1ODk3OTNdLFsyLjcxODI4MTgyODQ1OTA0NSwyLjE0MTU5MjY1MzU4OTc5M10sWzEwMDAwMDAwMDAsMC4xXSxbMC4wMDIsMC4wMDE2NjY2NjY2NjY2NjY2NjY4XSxbMC4wMDIwMDAwMDAwMDAwMDAwMDEsMC4wMDJdLFszLjE0MTU5MjY1MzU4OTc5MywwLjIwMDAwMDAwMDAwMDAwMF0sWzFlKzMwMCwxXSxbMWUrMzAwLDRlKzI5OV0sWzAuMSwwLjFdXSJd) For the `0.002000000000000001 ^ 0.002` test case, it unfortunately fails because it seems to automatically round it to `0.002`. It does work with three zeros removed, though. This seems to be a problem with `sympy.nsimplify`: ``` >>> sympy.nsimplify(0.002000000000000001, rational=True) 1/500 >>> sympy.nsimplify(0.002000000000001, rational=True) 2000000000001/1000000000000000 ``` (from Python REPL) ## How? ``` k⁋E*÷꘍k⁋E/ k⁋ # Push 1024 E # Push 2**1024 * # Multiply the (implicit) input pair by that ÷ # Push both elements of the multiplied pair to the stack ꘍ # Bitwise XOR them k⁋E/ # Divide by 2**1024 ``` [Answer] # [Julia 1.0](http://julialang.org/), 51 bytes ``` f(a,b,e=8^341.)=e>0&&(a÷e+b÷e)%2*e+f(a%e,b%e,e/2) ``` [Try it online!](https://tio.run/##dZDfSvNAEMXv8xRjwZJ8TdaZ2f9CeulTSCFtt5CPEEtawQvfywfwweok0YqIAxvYM7@ZPSf/n7u2oZfL5ZA35bZMddhoQ6qo0xqXy7x5f0urrXyKW/6XVgLdpnIrJ91xcTk8DdBC28OQmn3X9umUFxlIjat2UMOxGU5J5Q/dU3N2poTTsWvPeVvCsHjcvFbrRTHzg7CTgfl6HNr@3PX5pEC9huELu6lhB8vllVjs28PhHhaysdoVWer3F4INMFRr0JlWZMhGdlbbEH3UY@uXJihlrDwFDuMxNqKxf6GorPcOo/esDTN6nRF@lQyhomnjVVOUoULkqYdI7meFeSmidtoIzvK6vGbJzmP4o@hzyxQwKOe1I699DMGgtjZVFDNKKz1ZmY1Mt2/RJI5xaij2Go1nCcI@OA4zOQa4xsDMqxCC5EXLTEgUUqVHwCodkIIjJ25IfpPon64MO8deojExazsOfAA "Julia 1.0 – Try It Online") port of [m90's answer](https://codegolf.stackexchange.com/a/247204/98541) I tried so many things but always landed on 51 bytes [Answer] # C (gcc), 87 bytes ``` typedef double d;d c=1LL<<32;d x(d a,d b){return((long long)(a*c)^(long long)(b*c))/c;} ``` In the spirit of the Python answer above, converts to a fixed point integer and does the XOR, before converting back. It only has 32 bits of precision to either side of the decimal point, assuming `long long` is 64 bits wide, which is exactly the worst precision allowed by the challenge (1e-6). Because of this, the 1e300 answers overflow. If your platform has 64-bit `long`s 11 bytes can be saved, for a total of 76 bytes: ``` typedef double d;d c=1L<<32;d x(d a,d b){return((long)(a*c)^(long)(b*c))/c;} ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 25 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ∩√=êⁿ;r⌂$══▓ìêCO¥ÇnµtƒÉd+ ``` [Run and debug it](https://staxlang.xyz/#p=effb3d88fc3b727f24cdcdb28d88434f9d806ee6749f90642b&i=1.0+2.0%0A3.141592653589793+2.141592653589793%0A2.718281828459045+2.141592653589793%0A1000000000.0+0.1%0A0.002+0.0016666666666666668%0A0.002000000000000001+0.002%0A1e300+1.0%0A1e300+4e299%0A0.1+0.1%0A7.888609052210118e-31+5.380186160021159e-32&a=1&m=2) [Answer] # [C (gcc)](https://gcc.gnu.org/), 96 bytes ``` #define D double #define P*(long*) D z;D f(D x,D y){P&z=P&x^P&y;z=x>=y&x<2e-308?z:f(y/2,x/2)*2;} ``` [Try it online!](https://tio.run/##fZDhToMwFIV/r09xMyMpWFhbYKMi8w8PwAMYE4WykMxikBlg2bNjGRuKJt6kTe/p6Xdumtq7NO37m0zmhZIQQ1YeXvcSXYXEwvtS7SwTxdCFMeQ4hobE0JrHxOiixGieE6MNu6jZRq3RPHBpuzR47O5z3K44aVbctHh46j/LIoNaftR4DNCQS5RGwREtLk0Fkc7Ql60ZosV7Vag6x8tbh/kSxt3ejocntSQDpSVQae8JIe2Ft5dC4TPwHMYI8AF0blyHecwXfO27fiA2wtWXv6XJzJ0NC3gwLM8X1PP/MzN6LQLUYZNOHUr5IFHK1vMK5iY6Kza@@R6dyTt3gLM/iie5ED9YbJqgkvWhUkD13/Rf "C (gcc) – Try It Online") subnormal number is good # [JavaScript (Node.js)](https://nodejs.org), 81 bytes ``` f=(x,y)=>x+y>1e60?+[g(x)^g(y)]:f(x*2,y*2)/2 g=x=>BigInt(x%1?0:'0o'+x.toString(8)) ``` [Try it online!](https://tio.run/##fY5NT8MwDIbP66/IBS1ZS7DTjzVD7SRunDlOIE0ljYqmBK0BpUL89tJ2MChIvJIPfvLY8dP@dd9Wx@bZXRr7qPq@LqiPOlaUPuxKVBlsw52mnj1o2rH7TU39SkTdSrArEejCF@VNo2@No/4Ct7BZgl2Gnjt7546N0TRnrK9fTOUaa4hT7eBFpGPkLVhU1rT2oPjB6glGpJ5@ZtfBexAsJhkjIob@1MQcE0ylyNI4zeVaxsPjb3SWBV9jLvKxklRCkv4nI3wlIsDxzIEDiBEBYDZPPpdgFjzNfJ@OKozH5fiHJEpI@WMXfl7QfwA "JavaScript (Node.js) – Try It Online") Base 8 to avoid `e+66`, `>1e60` to avoid overflow ]
[Question] [ For our purposes, a trend is a contiguous subsequence of an array that falls into one of three categories: * increasing, e.g. `[1,2,3,10,239]` * decreasing, e.g. `[8,5,0,-3,-50]` * stable, e.g. `[7,7,7,7]` Note that `[1,1,2,3]` is not a valid trend. It can be broken up into a stable trend `[1,1]` and an increasing trend `[1,2,3]`. In the event an array has more than one trend, its trends will always overlap by one number. ## Task Given an array of at least two integers in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), output the trends of the array. ## Rules * You must output the smallest possible number of trends. `[[1,1], [1,2], [2,3]]` is not valid output for `[1,1,2,3]`. * You must output trends in the order they occur in the input. * You may output in any format you like as long as we can tell the trends apart. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes (in each language) wins. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. ## Test cases | Input | Output | | --- | --- | | ``` [1,2][1,2,1][1,1,2,3][1,-1,2,-2,3,-3][0,0,0,4,10,96,54,32,11,0,0,0][-55,-67,-80,5,5,5,9,9,9,9,14,20,25] ``` | ``` [[1,2]][[1,2], [2,1]][[1,1], [1,2,3]][[1,-1], [-1,2], [2,-2], [-2,3], [3,-3]][[0,0,0], [0,4,10,96], [96,54,32,11,0], [0,0,0]][[-55,-67,-80], [-80,5], [5,5,5], [5,9], [9,9,9,9], [9,14,20,25]] ``` | [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 30 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {(ùï©‚äèÀú+`)‚åæ‚àæ0‚àæ¬®=Àú‚äî+`¬ª‚ↂüú¬´√ó1‚Üì-‚üú¬ªùï©} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHso8J2VqeKKj8ucK2Ap4oy+4oi+MOKIvsKoPcuc4oqUK2DCu+KJoOKfnMKrw5cx4oaTLeKfnMK78J2VqX0KCuKImOKAvzEg4qWKIEbCqCDin6gK4p+oMSwy4p+pCuKfqDEsMiwx4p+pCuKfqDEsMSwyLDPin6kK4p+oMSwtMSwyLC0yLDMsLTPin6kK4p+oMCwwLDAsNCwxMCw5Niw1NCwzMiwxMSwwLDAsMOKfqQrin6gtNTUsLTY3LC04MCw1LDUsNSw5LDksOSw5LDE0LDIwLDI14p+pCuKfqQ==) | Code | Explanation | Example | | --- | --- | --- | | `x` | Argument | `‚ü® 1 1 2 4 ‚ü©` | | `1‚Üì-‚üú¬ª` | Differences of adjacent arguments | `‚ü® 0 1 2 ‚ü©` | | `√ó` | Sign of each value | `‚ü® 0 1 1 ‚ü©` | | `¬ª‚ↂüú¬´` | Mark starts of runs of equal adjacent values with a 1, except the first. | `‚ü® 0 1 0 ‚ü©` | | `+`` | Cumulative sum | `‚ü® 0 1 1 ‚ü©` | | `‚äî` | Group indices by their value | `‚ü® ‚ü® 0 ‚ü© ‚ü® 1 2 ‚ü© ‚ü©` | | `=Àú` | Self-equal; replace all values by 1's | `‚ü® ‚ü® 1 ‚ü© ‚ü® 1 1 ‚ü© ‚ü©` | | `0‚àæ¬®` | Prepend a 0 to each group | `‚ü® ‚ü® 0 1 ‚ü© ‚ü® 0 1 1 ‚ü© ‚ü©` | | `+`‚åæ‚àæ` | Cumulative sum under flattening the list | `‚ü® ‚ü® 0 1 ‚ü© ‚ü® 1 2 3 ‚ü© ‚ü©` | | `ùï©‚äèÀú` | Index into the argument | `‚ü® ‚ü® 1 1 ‚ü© ‚ü® 1 2 4 ‚ü© ‚ü©` | [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` I·π†≈í…†1;√Ñr∆ù·ªã ``` [Try it online!](https://tio.run/##y0rNyan8/9/z4c4FRyedXGBofbil6Njch7u7/x9uPzrp4c4ZmpH//0dHG@oYxepwgSgdQwgDxDSGMHVBbF0gV0cXLGKgA4ImOoYGOpZmOqYmOsZAXYZgQQOQvK6pqY6umbmOroWBjikYWkKhoYmOkYGOkWlsLAA "Jelly ‚Äì Try It Online") ``` ·π† Take the signs of the I differences between adjacent elements. ≈í…† Count the lengths of consecutive runs of equal signs, 1; prepend a 1, √Ñ take the cumulative sums, r∆ù get the inclusive ranges between each pair of adjacent values, ·ªã and index each number in each range back into the input. ``` [Answer] # [R](https://www.r-project.org), ~~83~~ ~~74~~ 73 bytes *Edit: -9 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).* ``` \(x,`?`=diff)Map(\(i,j)x[i:j],c(1,w<-which(!!?sign(?x))+1),c(w,sum(x|1))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PU4xDoJAEOz9Bd1tnEvugEMwEmoLXyAmGMzJkWiMSKCw9Bc2aOKj_I2AQKbYmdmdyT5f1-atw09509z_rmNWI4mS8GC0ps3-wmJmkFO9Nct8h5RJVCteZSbNmGVFhTmeWVQTzSW1ywpFeWL1XRLRUPjQrAvZRLOBQU68U86keCd564CPpkAHF1Ig8KBcOG1c9qYYTrhS4N4C3BdQPYIB0oUtYKvxl6b5zx8) Pretty straightforward: 1. Get signs of differences (identify trends). 2. Find starting positions of the trends. 3. Those (shifted by one) are also the ends of the trends. 4. `Map` over trends and extract them using `start:end`. --- Alternative inspired by [Unrelated String's Jelly answer](https://codegolf.stackexchange.com/a/246412/55372): ### [R](https://www.r-project.org), ~~73~~ 71 bytes *Edit: -2 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).* ``` \(x)Map(\(i,j)x[i:j],head(w<-diffinv(rle(sign(diff(x)))$l)+1,-1),w[-1]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY5LDoJAEET3nsNFd6xOZpBBNLp25QmABVFGhxhi_HIAb-EGTTyUtxF0NLXoqpeuTt_u--ZhZ8_T0Ur8mqdU8yLfUUoOJdeJm5QZNkW-ostUVs5aV51pvy3o4NYVdaAtMPe3PNAQzbgkojP2566WlqQRMPe8g_77Lg3_SbooLYH8oEKnEFphHMGEGLZ1_YHKr4gxkGgEiRXMR2MvHSJQCAz7X5rmO98) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` ¬Ø¬±ƒ†vL0p¬¶2lv∆í·π°ƒ∞ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCr8KxxKB2TDBwwqYybHbGkuG5ocSwIiwiIiwiWy01NSwtNjcsLTgwLDUsNSw1LDksOSw5LDksMTQsMjAsMjVdIl0=) Port of Unrelated String's Jelly answer. ``` ƒ†vL # Get the lengths of the runs of identical...' ¬± # Signs ¬Ø # In the forward differences of the input 0p¬¶ # Prepend a zero and get cumulative sums lv∆í # Over runs of length... 2 # 2 ·π° # Inclusive range ƒ∞ # Index those into the original array ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 60 bytes ``` ->a,*w{a.each_cons(2){|x,y|(a!=a=x<=>y)&&w<<[x];w[-1]<<y};w} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RR6u8OlEvNTE5Iz45P69Yw0izuqZCp7JGI1HRNtG2wsbWrlJTTa3cxia6Ita6PFrXMNbGprLWurz2f4FCWnS0oY6RjnFsLBecYwjjGCNzDHUMUTlGIH1AGqxKB2rKfwA "Ruby ‚Äì Try It Online") ### How it works ``` ->a,*w{ ``` Initialize `w` as an empty array, we will store the result there ``` a.each_cons(2) ``` Iterate on all pairs of consecutive elements of `a` ``` {|x,y|(a!=a=x<=>y) ``` Use `a` as a temporary variable to store the result of the last comparison. At the beginning its value will be different from anything else. On every iteration, check if the result of the comparison of the next 2 values is different from the previous result. ``` &&w<<[x] ``` If it's different, put the first of the two value in a new array inside of `w`. ``` ;w[-1]<<y ``` Append the second value to the last array (continuation of sequence if the comparison result is the same, new array if it is different.) ``` };w} ``` Return `w` after the last iteration. [Answer] # [Perl 5](https://www.perl.org/), 107 bytes ``` sub{my@r;!@r?push@r,$l=[$_]:@$l<2||($_<=>$L)==($L<=>$$l[-2])?push@$l,$_:push@r,$l=[$L,$_]and$L=$_ for@_;@r} ``` [Try it online!](https://tio.run/##VZLPbtpAEMbP5Smm0RLsarb@A6bFjsMecitqLr0Z16LCTlGNcddYSgT02AfoI@ZF6M6uRYzW0n77zW@@mYPrXJbBmRXxuWl/HLYvQkbvhZzXbfNTSGRlnLAsDQUr7/zj0WLZXXzPFnYcW2xBkpUJ91Pb8KxEloX91oUy0lW1ZouYZVDspMgiIU/naKC0NQBI1Oehn0J8D4lWKUCKbxX0ejWEhIxrhKDxBfIIMtY1xsnkykf@RnON80s21zdRdGu0n@IinQl6Ls6mGExwrNbxtOl2mUYjsR1HjyvaVAnrZ/MgQD79hPyzi4E@s@54E/Rd9INuQg/UyxJPQjcZMdMzTbuRlwwz0j6oqQDbF4ttqhpZ/lzbsWBZ1NniabePb1lhCarbxq7lptoXN8NG6SEfT@l@/fuPSsNmWd0grLe1pbMg/60fCQWlNsxhtPs1ghBGXx@/weOXEb7TLIVjn4wGp0Hb5PCw2q/C8KHd1rmMQP2aBB3WebGp8jXLEjedm6JV79Tqfxpn2Rwjx3mSpL9//DBfJk7iyLCtVNPp/B8 "Perl 5 ‚Äì Try It Online") [Answer] # JavaScript, 84 bytes -2 bytes from Arnauld, thanks! ``` f=([n,...a],d,s=[g=[]])=>1/n?f(a,D=Math.sign(a[0]-n,g.push(n)),d-D?[...s,g=[n]]:s):s ``` [Try it online!](https://tio.run/##dVBLbtswEN37FLMoIhIYqpJjJbED2pt02RMQBCLYtCzHIAVTDloEWXbXI7SX60Vc/qTaQEMuOJ/3hu/Nvn6t7frYdj3TZqPO5y0nQmOe57XEDVouGi6kpHxZftarLanxiX@t@11u20aTWhSSaWzy7mR3RFOKG/a0Eo5t0fG0lAtLF/b8OJmsjbY9tLo79RY4iAmIEqcS44tlinx8m2LmE@ZyZLFUoL8zLAuc32E1w1tHLEOxCABWVcju7pE9FFiFO0@3nOG0wGnlYHJUY079hZygJ4yJykB4WUOh9IWobiixUGMjmIWXBQMgguoITQK9gSTeJ1cWYtfDIuXCSRjqDfkguIrBPAyJ/mI4mkwu47bzrTl@qdc7QkKO0FLgS3ibAFyuwW0h7UO0jjw0j8qeDr65jXT6r9XV1o6s/KB00@@Ac544Q@XmxjGuTmKoV3X8TojxmvZBk/nfHLGXH4/68JiLDxBe4vjrqeJF0tGOOaj8YBoSTK0g@/PrRwYL9/7@mQFCWl3GlhmOq0AY0B76TNS3Tq17tYFPb9HiO312H7zTx/Nf "JavaScript (Node.js) ‚Äì Try It Online") Explained ``` f = ( [n, ...a], // n: first item of array, a: remaining items d, // d: previous difference s = [g = []] // s: partial output, g: current group ) => 1 / n ? // if n is a number, recurse, else return s f( // call f() again a, // remaining items D = Math.sign(a[0] - n, g.push(n)), // assign new d to D d - D ? // check if direction changes (sneakily push n to g) [...s, g = [n]] : // if new direction, start a new group s, // else keep the same ) : s ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¬•.¬±Œ≥‚Ǩg.¬•√º≈∏√® ``` -3 bytes porting [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/246412/52210). [Try it online](https://tio.run/##yy9OTMpM/f//0FK9QxvPbX7UtCZd79DSw3uO7ji84v//aF1TUx1dM3MdXQsDHVMwtIRCQxMdIwMdI9NYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/0NL9Q5tPLf5UdOadL1DSw/vObrj8Ir/Ov@jow11jGJ1QKSOIZgGsYzBLF0QUxfI09EFCRjogKCJjqGBjqWZjqmJjjFQiyFY0AAorWtqqqNrZq6ja2GgYwqGllBoaKJjZKBjZBobCwA). **Original 14 bytes answer:** ``` √º2.Œ≥`.S}ŒµÀúŒπ`Œ∏¬™ ``` [Try it online](https://tio.run/##yy9OTMpM/f//8B4jvXObE/SCa89tPT3n3M6EczsOrfr/P1rX1FRH18xcR9fCQMcUDC2h0NBEx8hAx8g0FgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w3uM9M5tTtALrj239fScczsTzu04tOp/rc7/6GhDHaNYHRCpYwimQSxjMEsXxNQF8nR0QQIGOiBoomNooGNppmNqomMM1GIIFjQASuuamurompnr6FoY6JiCoSUUGproGBnoGJnGxgIA). **Explanation:** ``` ¬• # Get the forward-differences of the (implicit) input-list .¬± # Get the sign (-1 if <0; 0 if 0; 1 if >0) for each value Œ≥ # Split it into equal adjacent values ‚Ǩg # Get the length of each inner list .¬• # Undelta with leading 0 √º # For each overlapping pair: ≈∏ # Create an inclusive ranged list √® # (0-based) index those lists into the (implicit) input # (after which the resulting list of lists is output implicitly) √º2 # Split the (implicit) input-list into overlapping pairs .Œ≥ # Adjacent group these pairs by: ` # Pop and push both values in the pair to the stack .S # And compare them (-1 if a<b; 0 if a==b; 1 if a>b) }Œµ # After the adjacent group-by: map over each list of pairs: Àú # Flatten the list Œπ # Uninterleave it into two parts ([a,b,c,d,e,f] ‚Üí [[a,c,e],[b,d,f]]) ` # Pop and push both lists to the stack Œ∏ # Pop the second list and leave just its last value ¬™ # Append it to the first list ([a,c,e,f]) # (after which the resulting list of lists is output implicitly) ``` [Answer] # TI-Basic, 65 [bytes](https://codegolf.meta.stackexchange.com/a/4764/98541) ``` Input A tanh(99ŒîList( üA augment(Ans,{9‚ÜíB 1‚ÜíI For(J,1,N If  üB(I)= üB(J End Disp seq( üA(X),X,I,J J‚ÜíI End ``` prints each sublist on a new line * `ŒîList(` is a `diff` function * `tanh(99X)` is a `sign` function for integers: `tanh(0)=0`, `tanh(99)=1` and `tanh(-99)=-1` * we add a 9 at the end of `üB`, different than any value a diff can take, so that the last sublist is always printed * `I` stores the index of the start of the current sublist * if the signs are equal, we cut the `For` loop short with the `End` * otherwise, the `End` is skipped, so we print the sublist from `I` to `J` and set `I` to `J` [![demo](https://i.stack.imgur.com/hkGAWm.jpg)](https://i.stack.imgur.com/hkGAWm.jpg) [Answer] # [Haskell](https://www.haskell.org/), 95 bytes ``` (!)=compare x#y=show x++' ':y f(a:x@(b:c:t))|a!b==b!c=a#f x|1>0=a#(b#('|':f x)) f[x,y]=x#(y#"") ``` [Try it online!](https://tio.run/##bY/BioMwEIbveYpYF0zoBBKrbRWy7APsbY/iIdpKl21raV02gu/uOkkpu1TmMDP//2f4cjC3r/3xOI4s4LpuTxdz3RMb9vp2aH@oXS4jGuU9aZjJ7Rur8jrvOB9MUGldBbU2YUPtoF7lNLEqZNEQ5ZPCOWkKC32pbcj6cLHg48l8nvWuJfTy3X101/czfaENLRTE5YwGakZFfTWjCzTE5IF4tiVgJaAkZGtIE1hNx5UT5VNYpCmI9QbEVkLqKruXSiCWEKclGQsHXRLfgRZI61eFq8f0gnCKeASF68iK3QFj0NMA0t5JcfnH612M4YM/oO4g8uLgoP2QuRMe34@PP5TkFw "Haskell ‚Äì Try It Online") A bit weird output: a string where *trends* are separated by `|` and elements are space separated. **Alternatively** Output a list of lists for *111 bytes*. ``` f l=l?(l!2) (#)=compare (a:t@(b:c:r))!x|a#b==b#c=t!(x+1)|1>0=x:t!2 _!x=[x] l?(h:t)=take h l:drop(h-1)l?t _?x=[] ``` [Try it online!](https://tio.run/##XczBioMwGATge54iwR4S9g8kqem2gb/uexQp0VoU0yo2hxz67q6WvazM7ZthWv/qmxDm@U4DhoIHZgThmcB6eIx@agj3Lv7wytVuEoKlt88qxCqrMTKevrR467PC5CIz5MoSXlJJlpvWRYHR9w1taXC3aRh5K7UIRSTXYlmV88N3T7wNhI5T94x0R@/0osGUWwC9pRX3W5SryqUAuekUrMlBKzgdwOawXz71B9X/pbQW5OEb5FGB/eT0F52DUWBsSeZf "Haskell ‚Äì Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes ``` ¬Ø¬±ƒ†vL1p¬¶2lv∆í·π°‚Äπƒ∞ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCr8KxxKB2TDFwwqYybHbGkuG5oeKAucSwIiwiIiwiWy01NSwtNjcsLTgwLDUsNSw1LDksOSw5LDksMTQsMjAsMjVdIl0=) ## How? ``` ¬Ø¬±ƒ†vL1p¬¶2lv∆í·π°‚Äπƒ∞ ¬Ø # Deltas (consecutive differences) of (implicit) input ¬± # Sign of each ƒ† # Group consecutive identical items vL # Length of each 1p # Prepend a one ¬¶ # Cumulative sums 2lv∆í·π° # For each overlapping pair, get an inclusive range between them ‚Äπ # Decrement each ƒ∞ # Index each into the (implicit) input ``` [Answer] # JavaScript (ES6), 90 bytes ``` f=(a,s,c=[],[v,...b]=a,x=[...c,v],q=Math.sign(b[0]-v))=>1/v?s-q?[x,...f(a,q)]:f(b,q,x):[c] ``` [Try it online!](https://tio.run/##bY1NDsIgFIT3ngSSeQi1@JegJ/AEhAVFqzWmtWJIb1@pcWczm5f5Zt7cffIxvJrnm9rufBnH2jCPiGCsg00QQlTOeAzG5jMgOfTm5N83EZtryyorHSXOzUEt0zFSf7TD1Knzk567fc0q9Bj43gY3hq6N3eMiHt2V1cwqFI7zxb8LNetPZDVLaEKUKWguIDGphJLYraFLrPKE@ppyJk5ag9Yb0FZCf7X7SZUoJAqdS@MH "JavaScript (Node.js) ‚Äì Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 75 bytes ``` \d+ * L$`(?<=((_+)))((,(?<2>\2_+))+|(,(?!\1|\6)(_+))+|(,\1)+)\b $1$& _+ $.& ``` [Try it online!](https://tio.run/##K0otycxLNPz/PyZFm0uLy0clQcPexlZDI15bU1NTQ0MHyDOyizECcbVrQFzFGMOaGDNNDZhIjKGmtmZMEpeKoYoaV7w2l4qe2v//hjogaKJjaKBjaaZjaqJjbKRjCBE0BAA "Retina ‚Äì Try It Online") Only supports positive integers due to language limitations. Explanation: ``` \d+ * ``` Convert to unary. ``` (?<=((_+))) ``` For each trend starting just after a value (either the first value or the last value of the previous trend)... ``` ((,(?<2>\2_+))+|(,(?!\1|\6)(_+))+|(,\1)+)\b ``` ... match either a trend where the value increases each time, a trend where the value decreases each time, or a trend where the value doesn't change, ... ``` L$` $1$& ``` ... and output the matched trend preceded by the initial value. ``` _+ $.& ``` Convert to decimal. [Answer] # [Julia](http://julialang.org/), 62 bytes ``` !x=(a=1;~ =diff;findall(~[sign.(~x);9].!=0).|>i->x[a:(a=1+i)]) ``` [Try it online!](https://tio.run/##LUtLDoIwEN1zirJr45S0QFUk5QaegLBoQjFjmmoADQvD1bFF5yUzb97n/nJo5LJt6aKp0bJeie5xGOoBfW@co2s74c1ndF1YXXVZqgXLPg3yZmnNJTYOyDq2DY@RIEFPRmt6h95OlCUkDBJN7Ns4erWzyZ5mnCxF9vOeI/rZeRoyDUmRJdb3Wysh75K4Qe43smJnPFIePuBREBBRghRQHUGVUISK3EURbK4U8OMJ@FmA2lH9IUvIBeSq@wI "Julia 1.0 ‚Äì Try It Online") [Answer] # [Python](https://www.python.org), 132 bytes ``` c=lambda a,b,*_:(a>b)-(a<b) f=lambda h,*t,v=3:([[[h]],[]][c(h,*t)==v]+((r:=f(v=c(h,*t),*t))[0].insert(0,h)or r)if t else[[h]])[v>2:] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NZBNbsMgEIXX8SmQV4M7RPgvTaySiyBU4dTISK5j2dRy971FN9m0N-hhepuC6-gJ5s0bAZ_4_B7eXXvtb7evN2fY8ffjIjr9Wr9oorHG5LkCfa4pA_1U08jcZy0mDmeRVyClbJVCqZS8QIipELN6ABgrYWAWWxgWlVztbT81owOOLb2OZKTWEEeabmrWe6icz1mlNpYfSwSJ4ziSKWZq3TFda3D56liwzHfIQsAxqMCU4-mAZYG5P5KuIfdjVpbIDo_IjhzLVadNaYEZx6xUUXjQeLaF2J7Y_TR01nW2byagVbTzvIsvu8WjNbPuYKG-G0bbOzCQLJT-w98_9A8) # [Python](https://www.python.org), ~~138~~ 136 bytes *-2 bytes thanks to @[Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)* ``` t=lambda a,b,*c:(a>b)-(a<b) def f(x): i=j=0 while-~i<len(x): k=t(*x[j:]) while-~j<len(x)and t(*x[j:])==k:j+=1 yield x[i:j+1];i=j ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PVBBUsMgFF0np2CygvpxIE1qG4sXyWRBDExJkWbaqOnGtXdw043uPJC3EWh0_gy8_94D_uPjaziPu4O7XD6fR03XP--jsPKp7SSS0MLiscLyoSUUy21L0k5ppPFEqjQxohcsTV53xir6ZrZWuauQ7MWIF1PdVw3x3WzoZ4N0HfqXhdhX_Y3g3nY2ynZoqo0neHPvb5_n-TZIoCzL0ppD3sQVeNwDWkZEA6S-AxoIBqEK4Aw2KygLWPojPJLMy7Qsga7ugK4ZlLE2c_ECcgZ52aThQX04ogkZh8ztabBmtMapE47ZNZpC0uFonA-jsXqR1ocj5Dr032f-Ag) [Answer] # [MATLAB](https://www.gnu.org/software/octave/), 92 bytes ``` function t(m) d=[1 find(diff(sign(diff(m))))+1 numel(m)];for i=2:numel(d) m(d(i-1):d(i)),end ``` [Try it online!](https://tio.run/##JYgxDoAgDEV3TsHYRh1gxHgSw2AsNU2kJIpeH0n8y3vvl71ub2qNH92rFLUVMhpaVmdZlICEGW459LeMfYOz@uR09oozl8vK4sP/EJoMBDI5DB2IY1JqbXWjjx8 "Octave ‚Äì Try It Online") ]
[Question] [ > > And no, This is not a dupe of [Translate ASCII text to braille](https://codegolf.stackexchange.com/questions/32924/translate-ascii-text-to-braille). > > > There are 28=256 [Braille patterns](https://en.wikipedia.org/wiki/Braille_Patterns) in Unicode. (By 'Braille' I mean 8-cell ones) W, wait. How many ASCII characters were there? 27 = 128? Well then, Let's turn ASCII into Braille, 'cause there is absolutely no reason not to! --- # The way from ASCII, to Braille We can see each cells represent a bit, which each cell is 'punched' or not. Now we can allocate each cells to represent the bits of the ASCII character as binary. ``` (1 )(16 ) (2 )(32 ) (4 )(64 ) (8 )( - ) ``` \* `( - )` is blank Now we can convert ASCII to Braille. For example, `A`(65=01000001) equals to `⠡`. # Examples ``` Input -> Output Braille! -> ⠢⠺⠱⡱⡴⡴⠵⠑ (Upscaled) .. .o o. o. .. .. o. o. o. oo .o .o .o .o .o .o .o .o .o .o oo oo oo .. .. .. .. o. o. o. .. .. ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~27~~ 26 bytes ``` 80qf{i2b7Te[4/~\)\@+++2bc} ``` [Try it online!](https://tio.run/nexus/cjam#@29hUJhWnWmUZB6SGm2iXxejGeOgra1tlJRc@/@/U1FiZk5OqiIA "CJam – TIO Nexus") ### Explanation The Braille code points are neatly ordered so that the individual dots do count up in binary. However, the ordering of the bits in the code points is different. We want the following order: ``` 04 15 26 37 ``` Whereas the characters are laid out in Unicode in this order: ``` 03 14 25 67 ``` (Which kinda makes sense, because historically, Braille only used the first six dots.) Note that we don't need the `7` dot, since the input is guaranteed to be in the ASCII range. So given a list of bits `[6 5 4 3 2 1 0]` of an input character, we want to reorder them into `[3 6 5 4 2 1 0]`, to pull the bit representing the bottom-left dot to the most significant position. ``` 80 e# Push 80... we'll need this later. q e# Read all input. f{ e# Map this block onto each character, putting a copy of the 80 e# below each character. i e# Convert the character to its code point. 2b e# Get its binary representation. 7Te[ e# Pad it to 7 bits with zeros. We've now got some bit list e# [6 5 4 3 2 1 0]. 4/ e# Split into chunks of 4: [[6 5 4 3] [2 1 0]] ~ e# Dump them onto the stack: [6 5 4 3] [2 1 0] \ e# Swap them: [2 1 0] [6 5 4 3] ) e# Pull off the last element: [2 1 0] [6 5 4] 3 \ e# Swap: [2 1 0] 3 [6 5 4] @ e# Rotate: 3 [6 5 4] [2 1 0] ++ e# Concatenate twice: [3 6 5 4 2 1 0] e# That's the reordering done. + e# Prepend the 80. That puts it in the 2^7 position of the e# binary digit list, which gives it a value of 10240, which e# is where the Braille characters start. 2b e# Convert the bits back to an integer. c e# Convert the code point to the corresponding integer. }% ``` [Answer] ## JavaScript (ES6), 83 bytes ``` f= s=>s.replace(/./g,c=>String.fromCharCode((c=c.charCodeAt())&7|c*8&64|c/2&56|10240)) ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~98~~ ~~71~~ 66 bytes ``` lambda s:''.join(chr(i*8&64|i//2&56|i&7|10240)for i in map(ord,s)) ``` [Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqhQbKWurpeVn5mnkZxRpJGpZaFmZlKTqa9vpGZqVpOpZl5jaGBkYqCZll@kkKmQmaeQm1igkV@UolOsqfm/oCgzr0QjTUPJqSgxMycnVVEJKAgA "Python 3 – TIO Nexus") [Answer] ## [CJam](https://sourceforge.net/p/cjam), 27 bytes *1 byte stolen from Neil.* ``` q{i__8&8*@7&@2/56&++'⠀+}% ``` [Try it online!](https://tio.run/nexus/cjam#@19YnRkfb6FmoeVgruZgpG9qpqatrf5oQYN2rer//05FiZk5OamKAA "CJam – TIO Nexus") ### Explanation This uses the same basic idea as [my other CJam answer](https://codegolf.stackexchange.com/a/117206/8478) but uses bitwise arithmetic instead of base conversion and list manipulation to reorder the bits. ``` q e# Read all input. { e# Map this block over each character... i__ e# Convert the character to its code point and make two copies. 8& e# AND 8. Gives the 4th bit, which we need to move to the 7th place. 8* e# Multiply by 8 to move it up three places. @7& e# Pull up another copy and take it AND 7. This extracts the three e# least significant bits which shouldn't be moved at all. @2/ e# Pull up the last copy and divide by 2 to shift all bits down e# by one place. 56& e# AND 56. Extracts the three most-significant bits. ++ e# Add all three components back together. '⠀+ e# Add to the empty Braille character which is the offset for all e# the code points and which converts the value to a character. }% ``` [Answer] # PHP, 109 Bytes ``` foreach(str_split($argn)as$c)echo json_decode('"\u'.dechex(10240+(($d=ord($c))&7)+($d/2&56)+(($d&8)*8)).'"'); ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/89375bd968dad87a240ec8bdea94efa143988d20) [Answer] ## Mathematica 100 Bytes ``` FromCharacterCode[10240+#~Drop~{4}~Prepend~#[[4]]~FromDigits~2&/@ToCharacterCode@#~IntegerDigits~2]& ``` Ungolfed: ``` ToCharacterCode["Braille!0"] PadLeft@IntegerDigits[%,2] Prepend[Drop[#,{4}],#[[4]]]&/@% FromDigits[#,2]&/@% FromCharacterCode[%+10240] ``` +60 bytes of this tied up in long function names. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes ``` O&€“¬®p‘æ.1,8,.+“'ṁ’Ọ ``` [Try it online!](https://tio.run/nexus/jelly#@@@v9qhpzaOGOYfWHFpX8KhhxuFleoY6Fjp62kAx9Yc7Gx81zHy4u@f///9ORYmZOTmpigA "Jelly – TIO Nexus") ### How it works ``` O&€“¬®p‘æ.1,8,.+“'ṁ’Ọ Main link. Argument: s (string) O Ordinal; map all characters to their Unicode code points. “¬®p‘ Yield the code points of the enclosed characters in Jelly's code page, i.e., [1, 8, 112]. &€ Take the bitwise AND of each code point to the left and the three code points to the right. 1,8,. Yield [1, 8, 0.5]. æ. Take the dot product of the array to the right and each flat array in the array to the left. “'ṁ’ Yield 10240 = 250 × 39 + 239, where 39 and 239 are the indices of ' and ṁ in Jelly's code page. + Add 10240 to all integers to the left. Ọ Unordinal; convert all code points to their respective Unicode charcters. ``` [Answer] # [Retina](https://github.com/m-ender/retina), 59 bytes ``` T`-- -'0-7@-GP-W\`-gp-w--(-/8-?H-OX-_h-ox-`⠀-⡿ ``` [Try it online!](https://tio.run/nexus/retina#@x@SwKDLLqArrqCrbqBr7qDrHqAbHpOgm16gW86hyy@hK6@hq2@ha@@h6x@hG5@hm1@hW5/waEGD7qOF@///dypKzMzJSVUEAA "Retina – TIO Nexus") Hex dump: ``` 0000 54 60 00 2a 07 10 2a 17 20 2a 17 30 2a 17 40 2a T`-- -'0-7@- 0010 47 50 2a 57 5c 60 2a 67 70 2a 77 08 2a 0f 18 2a GP-W\`-gp-w-- 0020 1f 28 2a 2f 38 2a 3f 48 2a 4f 58 2a 5f 68 2a 6f (-/8-?H-OX-_h-o 0030 78 2a 7f 60 e2 a0 80 2a e2 a1 bf x-`⠀-⡿ ``` [Answer] # C#, 63 bytes ``` s=>string.Concat(s.Select(c=>(char)(c*8&64|c/2&56|c&7|10240))); ``` [Try it online!](https://dotnetfiddle.net/heZ5wC) Inspiration from @ovs and @Neil [Answer] # [Chip](https://github.com/Phlarx/chip), ~~62~~ 59 bytes ``` h* Z~. z.g+b >xv< ||sf Zx^< Z< | A/a/D B/b C/c E/d F/e G/f ``` [Try it online!](https://tio.run/nexus/chip#@5@hxaUQVafHVaWXrp3EZVdRZsNVU1OcxhVVEWfDFWWjUMPlqJ@o78LlpJ/E5ayfzOWqn8Llpp/K5a6f9v@/gqKSsoqqmrqGpoGhkbGDo5NzQmJSMgA "Chip – TIO Nexus") I suspect I can golf it more, just gotta figure out how... Chip reads in each byte of input as a collection of bits, referred to by the first eight letters of the alphabet (uppercase is input, lower is output): ``` HGFEDCBA ``` We simply need to map those bits of the input to the following three bytes of output: ``` 11100010 101000hd 10gfecba ``` The top half of the code is doing all the sequencing, and generates the first two bytes, the bottom half generates the third byte. Since the specification only requires handling 7 bits for ASCII, we don't examine `H`. To include the eighth bit, change line `B/b` to `B/b/H`. ]
[Question] [ I recently saw [this](https://stackoverflow.com/questions/36260956/all-possible-ways-to-interleave-two-strings) question on stackoverflow. It's a great question, but there's one fatal problem with the question. They are asking for the best way to do it. E.g, easiest to read, most idiomatic, neatest etc. Don't they know that isn't what matters? You're supposed to ask about how to do it with the fewest bytes of code! Since I doubt that question will be appreciated on stackoverflow, I decided to ask it here. # The challenge You must write the shortest possible program or function that generates all possible ways to interleave any two arbitrary strings. For example, if the two strings are `'ab'` and `'cd'`, the output is: ``` ['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab'] ``` As you can see, `a` is always before `b`, and `c` is always before `d`. IO can be in any reasonable format. Use this python code to verify to check your output. (credit: [JeD](https://stackoverflow.com/a/36261206/3524982)) ``` def shuffle(s,t): if s=="": return [t] elif t=="": return [s] else: leftShuffle=[s[0]+val for val in shuffle(s[1:],t)] rightShuffle=[t[0]+val for val in shuffle(s,t[1:])] leftShuffle.extend(rightShuffle) return leftShuffle ``` # Sample IO: ``` shuffle("$", "1234"): ['$1234', '1$234', '12$34', '123$4', '1234$'] shuffle("az", "by"): ['azby', 'abzy', 'abyz', 'bazy', 'bayz', 'byaz'] shuffle("code", "golf"): ['codegolf', 'codgeolf', 'codgoelf', 'codgolef', 'codgolfe', 'cogdeolf', 'cogdoelf', 'cogdolef', 'cogdolfe', 'cogodelf', 'cogodlef', 'cogodlfe', 'cogoldef', 'cogoldfe', 'cogolfde', 'cgodeolf', 'cgodoelf', 'cgodolef', 'cgodolfe', 'cgoodelf', 'cgoodlef', 'cgoodlfe', 'cgooldef', 'cgooldfe', 'cgoolfde', 'cgoodelf', 'cgoodlef', 'cgoodlfe', 'cgooldef', 'cgooldfe', 'cgoolfde', 'cgolodef', 'cgolodfe', 'cgolofde', 'cgolfode', 'gcodeolf', 'gcodoelf', 'gcodolef', 'gcodolfe', 'gcoodelf', 'gcoodlef', 'gcoodlfe', 'gcooldef', 'gcooldfe', 'gcoolfde', 'gcoodelf', 'gcoodlef', 'gcoodlfe', 'gcooldef', 'gcooldfe', 'gcoolfde', 'gcolodef', 'gcolodfe', 'gcolofde', 'gcolfode', 'gocodelf', 'gocodlef', 'gocodlfe', 'gocoldef', 'gocoldfe', 'gocolfde', 'goclodef', 'goclodfe', 'goclofde', 'goclfode', 'golcodef', 'golcodfe', 'golcofde', 'golcfode', 'golfcode'] ``` As usual, standard loopholes apply, and the shortest answer in bytes wins. Since the question was originally about python, I'd love to see the shortest python answer. (And no, pyth is not python). However, answers in any language are encouraged. [Answer] # Haskell, 47 ``` (x:s)#b=(x:)<$>s%b a#b=[] []%b=[b] a%b=a#b++b#a ``` `%` is the operator that solves this challenge. `#` is an operator that takes in two lists and finds all the ways to interleave them such that the first character is from the first string (with an edge case - if the first list is empty, then the result is an empty list) by recursing to `%`. then, `%` works by just applying `#` twice. **Edit:** The previous version had a bug in which `""%""` returned `["",""]`, so I fixed it up. It was fixed by adding a base case to `%`, which then allowed to remove a base case of the same length from `#` (which really, didn't make much sense). [Answer] ## Haskell, ~~53~~ 48 bytes ``` a%""=[a] a%b=[x:t|(x:y,z)<-[(a,b),(b,a)],t<-y%z] ``` Defines a function `%` for which `a%b` with strings `a,b` gives a list of strings. Given two strings, we choose one of the two to take the first character from. We then recurse on the remainder of two strings, prepending that character to each result. When one of the string is empty, the only possible result is the other string. `""%""=[""]` would also suffice, but's it's longer. --- **53 bytes:** ``` a@(b:c)%d@(e:f)=((b:)<$>c%d)++((e:)<$>a%f) a%d=[a++d] ``` Defines a function `%` for which `a%d` with strings `a,d` gives a list of strings. The function is defined recursively. If we take a character from the first string, then it must be prepended to each result of the recursive call on the remained of the first string with the second string. Symmetrically for the other string. For the base case, if one of the strings is empty, the result is a single-element list of their concatenation. This is shorter than two cases for each string being empty. [Answer] ## Python 2, 71 bytes ``` f=lambda*p:[x[0]+t for x,y in p,p[::-1]for t in x and f(x[1:],y)]or[''] ``` Example run: ``` >> f('ab','AB') ['abAB', 'aABb', 'aAbB', 'ABab', 'AabB', 'AaBb'] ``` Given two strings `x,y` we can take the first character of `x` and prepend it to each result of the recursive call with it missing `f(x[1:],y)`. Or, we can do the same with `x` and `y` switched. By taking `x,y` as either the input `p` or its reversal `p[::-1], we get both possibilities. To avoid taking from an empty string `x`, we logical short-circuit with `x and`. If both strings are empty, neither string can be `x` and we get and empty list of possibilities, which we fix with `or` to the correct base case `['']`. A similar generative strategy in Python 3 (73 bytes): ``` f=lambda p,s='':[f((x[1:],y),s+x[0])for x,y in[p,p[::-1]]if x]or print(s) ``` [Answer] # Python, 80 As requested, here's a python answer: ``` f=lambda a,b,c='':[c+x for x in[a+b][a>''<b:]or f(a[1:],b,a[0])+f(a,b[1:],b[0])] ``` Thanks Sp3000 for eating 4 bytes :) [Answer] # CJam, 38 ``` q~L{_2$e&{_2$(\@jf+@@(@@jf++}{+a}?}2jp ``` [Try it online](http://cjam.aditsu.net/#code=q~L%7B_2%24e%26%7B_2%24(%5C%40jf%2B%40%40(%40%40jf%2B%2B%7D%7B%2Ba%7D%3F%7D2jp&input=%22ab%22%20%22cd%22) Dynamic programming (using memoized recursion). **Explanation:** ``` q~ read and evaluate the input (2 strings) L{…}2j calculate with memoized recursion with no initial cache and 2 arguments _2$ copy the 2 strings e&{…} if they are both non-empty _2$ copy the strings again (they're in reverse order) ( take out the first character of the first string \@ move the strings after the character j solve recursively f+ prepend the character to all results @@ bring the other copy of the strings on top (in order) ( take out the first character of the second string @@ move the strings after the character j solve recursively f+ prepend the character to all results + concatenate the 2 sets of results {…} else + concatenate the 2 strings (at least one is empty) a put the result in an array ? end if p pretty-print the results for the input strings ``` [Answer] ## CJam, 32 bytes ``` qN/_:,eeWf%e~e!\f{\{_2$=(ot}/No} ``` [Test it here.](http://cjam.aditsu.net/#code=qN%2F_%3A%2CeeWf%25e~e!%5Cf%7B%5C%7B_2%24%3D(ot%7D%2FNo%7D&input=1234%0A%24!) This feels really golfable, but so far I've only found 4 alternative solutions that all have the same byte count: ``` qN/_ee{),*~}%e!\f{\{_2$=(ot}/No} l_:!l_0f>@+])e!\f{\{_2$=(ot}/No} ll__3$:!+.=])e!\f{\{_2$=(ot}/No} qN/[_:,2,]ze~e!\f{\{_2$=(ot}/No} (found by Sp3000) ``` The basic idea is to generate all permutations of `0`s and `1`s corresponding to which string to take each character in the result from. That's everything up to and including the `e!`. The rest simply pulls out characters in that order from the two strings then. [Answer] ## JavaScript (Firefox 30-57), ~~88~~ ~~84~~ 81 bytes ``` (s,t,g=(v,w)=>v[1]?f(v.slice(1),w).map(x=>v[0]+x):[v+w])=>[...g(s,t),...g(t,s)] ``` Edit: Saved 4 bytes by improving my termination condition. Saved 3 bytes thanks to @edc65. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` p~cᵐz₁cc ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/wV1yUCq6lFTY3Ly///R0UoqSjpKhkbGJkqxOtFKiVVAXlIlmJ2cn5IK5KXn56QpxcYCAA "Brachylog – Try It Online") Takes input as a list of two strings through the input variable, and [generates](https://codegolf.meta.stackexchange.com/a/10753/85334) all possible interleavings through the output variable. Since the test cases seem to permit duplicate interleavings where there are shared letters, I haven't taken any care to avoid them, but this generates a *lot* more duplicates and not just with shared letters. (If this isn't allowed, but the shared letter duplicates aren't necessary, just add three bytes to wrap in `{}ᵘ` for output as a list with no duplicates.) ``` p A permutation of the input variable ᵐ with each element ~c arbitrarily partitioned, z zipped ₁ without cycling, cc and concatenated twice is the output variable. ``` Essentially, this generates every partition of both strings, then interleaves them in the normal deterministic fashion in either order. The extra duplicate interleavings are due to partition pairs where the difference between the length of the first and the length of the second has some value other than 0 or 1, so that one of them has chunks that get concatenated to each other at the end. So, to produce output with the same multiplicities as the sample output: # [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes ``` p~cᵐ{lᵐ-ℕ<2&}z₁cc ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFqRbK9VlKz3c1fmoqbH24dYJ/wvqkoFUdQ6Q0H3UMtXGSK22CiiXnPz/f3S0koqSjpKhkbGJUqxOtFJiFZCXVAlmJ@enpAJ56fk5aUqxsQA "Brachylog – Try It Online") The extra code, `{lᵐ-ℕ<2&}`, fails any partition pair where any extraneous divisions are made. (I altered the header on TIO to print with quotes for easier output checking in the Python shell.) [Answer] # Pyth, 26 ``` M?G?H++LhGgtGH+LhHgGtH]G]H ``` [Try it here](https://pyth.herokuapp.com/?code=M%3FG%3FH%2B%2BLhGgtGH%2BLhHgGtH%5DG%5DHgzw&input=ab%0Acd&debug=0) This is a very basic implementation of the given recursive formula. It defines a function `g` that performs the required task. The link is a modified program that reads the strings from STDIN newline separated, to be more convenient. To call the function do `g<string1><string2>`. ### Expansion: ``` M ## Define a function g taking two arguments: G and H ?G?H ... ]G]H ## Two ternaries: if G is empty return a list containing H ## if H is empty return a list containing G + ## otherwise return these next two lists joined together +LhGgtGH ## the first letter of G added to each result of a recursive call to g ## with G missing its first character and H +LhHgGtH ## the same as above but with G and H swapped ``` The two recursive calls are very similar, but I haven't been able to find a way to golf them any more. [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~34~~ 30 bytes ``` h1Mgw~hY@Xu!ttYs*w~tYs1Gn+*+!) ``` This uses an idea from [this answer](https://stackoverflow.com/a/36271870/2586922): if the lenghts of the strings are `m` and `n`, enumerate all `m+n` bit patterns with `m` bits set. One way do that that enumeration is: generate all permutations of a vector with `m` ones and `n` zeros and then remove duplicates. [**Try it online!**](http://matl.tryitonline.net/#code=aDFNZ3d-aFlAWHUhdHRZcyp3fnRZczFHbisqKyEp&input=J2FiJwonY2QnCg) ### Explanation ``` h % implicitly input the two strings of lengths m and n. Concatenate 1M % push the two strings again g % convert the second strings into ones w~ % swap. Convert the second string into zeros h % concatenate: vector of zeros and ones Y@ % 2D array with all permutations of that vector, each on a row Xu % remove duplicate rows ! % transpose ttYs % duplicate twice. Cumulative sum along each column * % element-wise product. Produces, in each column, indices for % elements of the first string; 1, 2,...,m. The rest are 0 w~ % swap, negate tYs % duplicate. Cumulative sum along each column 1Gn+ % add length of first input * % element-wise product. Produces, in each column, indices for % elements of the second string: m+1,...,m+n. The rest are 0 + % add. This gives indices into the concatenated string created initially ! % transpose back ) % index into concatenated string. Implicitly display ``` [Answer] # Ruby, 83 bytes A recursive function that returns `[a+b]` if either of those strings are empty. Otherwise, it returns a list of strings `a[0] + every string in v[a[1..-1],b]` added to a list of string `b[0] + every string in v[a,b[1..-1]]` ``` v=->a,b{a[0]&&b[0]?v[a[1..-1],b].map{|i|a[0]+i}+v[a,b[1..-1]].map{|i|b[0]+i}:[a+b]} ``` [Answer] ## Batch, ~~154~~ 152 bytes ``` @if "%~1%~2"=="" echo %3 @set t=%~1 @if not "%t%"=="" call %0 "%t:~1%" "%~2" %3%t:~,1% @set t=%~2 @if not "%t%"=="" call %0 "%~1" "%t:~1%" %3%t:~,1% ``` ]
[Question] [ Consider the function `Remove(n, startIndex, count)` that removes `count` digits from the number `n` starting from the digit at position `startIndex`. Examples: ``` Remove(1234, 1, 1) = 234 Remove(123456, 2, 3) = 156 Remove(1507, 1, 2) = 07 = 7 Remove(1234, 1, 4) = 0 ``` We will call the prime number X fragile if every possible `Remove` operation makes it non-prime. For example, 80651 is a fragile prime because all of the following numbers are not prime: ``` 651, 51, 1, 0, 8651, 851, 81, 8, 8051, 801, 80, 8061, 806, 8065 ``` ## Goal Write a program that finds the largest fragile prime. **Edit:** removed the time limit because there was a relatively fair way to circumvent it. The score is the fragile prime number found by your program. In the event of a tie, the earlier submission wins. ## Rules * You may use any language and any third-party libraries. * You run the program on you own hardware. * You may use probabilistic primality tests. * Everything is in base 10. ## Leading entries * 6629 digits by Qualtagh (Java) * 5048 digits by Emil (Python 2) * 2268 digits by Jakube (Python 2) **Edit:** I've added my own answer. * 28164 digits by Suboptimus Prime, based on Qualtagh's algorithm (C#) [Answer] ## Python 2 - ~~126~~ ~~1221~~ ~~1337~~ ~~1719~~ 2268 digits ``` 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999799999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 '9' * 1944 + '7' + '9' * 323 ``` There are at about len(n)^2 resulting numbers of Remove(n, startIndex, count). I tried to minimize those numbers. If there are lots of digits next to each other are the same, lots of these resulting numbers can be ignored, because they appear multiple times. So I took it to the extreme, only 9s and a little prime in the middle. I also took a look at the fragile prime under 1 million, and saw, that there are such fragile prime. Searching for numbers with 2 9s at the end works really good, not sure why. 1 number, 3, or 4 9s at the end results in smaller fragile primes. It uses the [pyprimes module](https://pypi.python.org/pypi/pyprimes/0.1.1a). I'm not sure, if it is any good. It uses the miller\_rabin test, so it's probabilistic. The program find this 126-digit fragile prime in about 1 minute, and for the rest of the time it searches without success. ``` biggest_found = 80651 n = lambda a,b,c: '9'*a + b + '9'*c for j in range(1000): for digit in '124578': for i in range(2000): number = int(n(i,digit,j)) if is_prime(number): if (number > biggest_found): if all(not is_prime(int(n(i,digit,k))) for k in range(j)): biggest_found = number print(i+j+1, biggest_found) break ``` ### edit: Just saw, that you removed the time limit. I will run the program over night, maybe some really big fragile primes appear. ### edit 2: Made my original program faster, so but still no solution with more than 126 digits. So I jumped on the train and searched for x 9s + 1 digit + y 9s. The advantage is, that you have to check O(n) numbers for primality, if you fixe y. It finds a 1221 rather quickly. ### edit 3: For the 2268 digit number I use the same program, only divided the work on multiple cores. [Answer] # Java - ~~3144~~ ~~3322~~ 6629 digits ~~`6 0{3314} 8969999`~~ ``` 6 0{6623} 49099 ``` This solution is based on [FryAmTheEggman's answer](https://codegolf.stackexchange.com/a/41656/32921). 1. The last digit is 1 or 9. 2. If the last digit is 1 then a previous one is 0, 8 or 9. 3. If the last digit is 9 then a previous one is 0, 4, 6 or 9. 4. ... What if we dig deeper? It becomes a tree structure: ``` S ----------------------- 1 9 ------------------ ---------------- 0 8 9 0 4 6 9 --------- ----- 0 8 9 ... ``` Let's call number R right composite if R and all its endings are composite. We're gonna iterate over all right composite numbers in breadth-first manner: 1, 9, 01, 81, 91, 09, 49, 69, 99, 001, 801, 901 etc. Numbers starting with zero are not checked for primality but are needed to build further numbers. We will look for a target number N in the form X00...00R, where X is one of 4, 6, 8 or 9 and R is right composite. X cannot be prime. X cannot be 0. And X cannot be 1 because if R ends with 1 or 9 then N would contain 11 or 19. If XR contains prime numbers after "remove" operation then XYR would contain them too for any Y. So we shouldn't traverse branches starting from R. Let X be a constant, say 6. Pseudocode: ``` X = 6; for ( String R : breadth-first-traverse-of-all-right-composites ) { if ( R ends with 1 or 9 ) { if ( remove( X + R, i, j ) is composite for all i and j ) { for ( String zeros = ""; zeros.length() < LIMIT; zeros += "0" ) { if ( X + zeros + R is prime ) { // At this step these conditions hold: // 1. X + 0...0 is composite. // 2. 0...0 + R = R is composite. // 3. X + 0...0 + R is composite if 0...0 is shorter than zeros. suits = true; for ( E : all R endings ) if ( X + zeros + E is prime ) suits = false; if ( suits ) print R + " is fragile prime"; break; // try another R // because ( X + zeros + 0...0 + R ) // would contain prime ( X + zeros + R ). } } } } } ``` We should limit zeros quantity because it may take too long to find a prime number in form X + zeros + R (or forever if all of them are composite). The real code is quite verbose and can be found [here](https://gist.github.com/anonymous/127f7c45a77c4e33e894). Primality testing for numbers in long int range is performed by deterministic variant of Miller test. For BigInteger numbers a trial division is performed first and then BailliePSW test. It's probabilistic but quite certain. And it's faster than Miller-Rabin test (we should do many iterations for such big numbers in Miller-Rabin to gain enough accuracy). **Edit:** the first attempt was incorrect. We should also ignore branches starting with R if X0...0R is prime. Then X0...0YR wouldn't be fragile prime. So an additional check was added. This solution seems to be correct. **Edit 2:** added an optimization. If ( X + R ) is divisible by 3 then ( X + zeros + R ) is also divisible by 3. So ( X + zeros + R ) cannot be prime in this case and such R's may be skipped. **Edit 3:** it was not necessary to skip prime digits if they're not in the last or first position. So endings like 21 or 51 are ok. But it doesn't change anything much. **Conclusions:** 1. My last answer was checking for being fragile for 100 minutes. The search of the answer (checking all preceding variants) took about 15 minutes. Yes, it makes no sense to restrict search time (we can start searching from the target number, so time would be zero). But it could be meaningful to restrict checking time like in [this question](https://codegolf.stackexchange.com/questions/35441/find-the-largest-prime-whose-length-sum-and-product-is-prime). 2. The answer 60...049099 has digit 4 in the middle. If the "remove" operation touches it, the number becomes divisible by 3. So we should check remove operations in left and right sides. Right side is too short. Left side length is almost n = length( N ). 3. Primality tests like BPSW and Miller-Rabin use constant quantity of modular exponentiations. Its complexity is O( M( n ) \* n ) according to [this page](http://en.wikipedia.org/wiki/Computational_complexity_of_mathematical_operations), where M( n ) is multiplication complexity. Java uses Toom-Cook and Karatsuba algorithms but we'll take scholar algorithm for simplicity. M( n ) = n2. So primality testing complexity is O( n3 ). 4. We should check all numbers from length = 6 to 6629. Let's take min = 1 and max = n for commonality. The whole check complexity is O( 13 + 23 + ... + n3 ) = O( ( n \* ( n + 1 ) / 2 )2 ) = O( n4 ). 5. [Emil's answer](https://codegolf.stackexchange.com/a/41671/32921) has the same checking asymptotics. But the constant factor is lower. Digit "7" is standing in the middle of the number. Left side and right side can be almost equal. It gives ( n / 2 )4 \* 2 = n4 / 8. Speedup: 8X. Numbers in the form 9...9Y9...9 can be 1.7 times longer than in the form X0...0R having the same checking time. [Answer] ## Python 2.7 - 429623069 ~~99993799~~ No optimizations whatsoever, so far. Just using some trivial observations about fragile primes (thanks to Rainbolt in chat): 1. Fragile primes must end in 1 or 9 (Primes are not even, and the final digit must not be prime) 2. Fragile primes ending in 1 must start with 8 or 9 (the first number can't be prime, and 11, 41 and 61 and are all primes) 3. Fragile primes ending in 9 must start with 4,6 or 9 (see reasoning for 1, but only 89 is prime) Just trying to get the ball rolling :) This technically runs slightly over 15 minutes, but it only checks a single number in the extra time. `is_prime` is taken from [here](http://codepad.org/KtXsydxK) (isaacg used it [here](https://codegolf.stackexchange.com/a/35444/31625)) and is probabilistic. ``` def substrings(a): l=len(a) out=set() for i in range(l): for j in range(l-i): out.add(a[:i]+a[len(a)-j:]) return out import time n=9 while time.clock()<15*60: if is_prime(n): if not any(map(lambda n: n!='' and is_prime(int(n)), substrings(`n`))): print n t=`n` if n%10==9 and t[0]=='8':n+=2 elif n%10==1 and t[0]!='8':n+=8 elif t[0]=='1' or is_prime(int(t[0])):n+=10**~-len(t) else:n+=10 ``` Just a note, when I start this with `n=429623069` I get up to `482704669`. The extra digit really seems to kill this strategy... [Answer] # Python 2, ~~828 digits~~ 5048 digits ``` 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999799999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 155*'9'+'7'+4892*'9' ``` As @Jakube pointed out, the first prime I submitted was not actually fragile due to a bug in my code. Fixing the bug was easy but it also made the algorithm significantly slower. I limited myself to an easily searchable subset of the fragile primes, namely those that only consist of the digit 9 and exactly one digit 7. ``` def fragile_prime_generator(x, b_max): bs, cs = set(), set() prime = dict() def test_prime(b,c): if (b,c) not in prime: prime[(b,c)] = is_prime(int('9'*b+`x`+'9'*c)) return prime[(b,c)] def test_frag(b,c): for b2 in xrange(b): if test_prime(b2,c): bs.add(b2) return False for c2 in xrange(c): if test_prime(b,c2): cs.add(c2) return False return True a = 1 while len(bs)<b_max: for b in xrange(min(a, b_max)): c = a-b if b not in bs and c not in cs and test_prime(b,c): bs.add(b) cs.add(c) if test_frag(b,c): yield b,c a += 1 print "no more fragile primes of this form" for b,c in fragile_prime_generator(7, 222): print ("%d digit fragile prime found: %d*'9'+'%d'+%d*'9'" % (b+c+1, b, x, c)) ``` I used the same `is_prime` function (from [here](http://codepad.org/KtXsydxK)) as @FryAmTheEggman. **Edit:** I made two changes to make the algorithm faster: * I try to skip as many primality checks as possible and only go back when a potential fragile prime is found to make sure it's really fragile. There's a small number of duplicate checks, so I crudely memoized the prime checking function. * For the numbers of the form `b*'9' + '7' + c*'9'` I limited the size of `b`. The lower the limit, the less numbers have to be checked, but chances increase to not find any large fragile prime at all. I kind of arbitrarily chose 222 as the limit. At a few thousand digits a single prime check already can take my program a few seconds. So, I probably can't do much better with this approach. Please feel free to check the correctness of my submission. Due to the probabilistic primality check my number could theoretically not be prime, but if it is, it should be fragile. Or I've done something wrong. :-) [Answer] ## C#, 10039 28164 digits ``` 6 0{28157} 169669 ``` **Edit:** I've made another program based on Qualtagh's algorithm with some minor modifications: * I'm searching for the numbers of the form L000...000R, where L is left composite, R is right composite. I allowed the left composite number L to have multiple digits, although this is mostly a stylistic change, and it probably doesn't affect the efficiency of the algorithm. * I've added multithreading to speed up the search. ``` using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Threading; using System.Threading.Tasks; using Mpir.NET; class Program { const int PrimeNotFound = int.MaxValue; private static BitArray _primeSieve; private static HashSet<Tuple<int, int>> _templatesToSkip = new HashSet<Tuple<int, int>>(); static void Main(string[] args) { int bestDigitCount = 0; foreach (Tuple<int, int> template in GetTemplates()) { int left = template.Item1; int right = template.Item2; if (SkipTemplate(left, right)) continue; int zeroCount = GetZeroCountOfPrime(left, right); if (zeroCount != PrimeNotFound) { int digitCount = left.ToString().Length + right.ToString().Length + zeroCount; if (digitCount >= bestDigitCount) { string primeStr = left + " 0{" + zeroCount + "} " + right; Console.WriteLine("testing " + primeStr); bool isFragile = IsFragile(left, right, zeroCount); Console.WriteLine(primeStr + " is fragile: " + isFragile); if (isFragile) bestDigitCount = digitCount; } _templatesToSkip.Add(template); } } } private static int GetZeroCountOfPrime(int left, int right) { _zeroCount = 0; int threadCount = Environment.ProcessorCount; Task<int>[] tasks = new Task<int>[threadCount]; for (int i = 0; i < threadCount; i++) tasks[i] = Task.Run(() => InternalGetZeroCountOfPrime(left, right)); Task.WaitAll(tasks); return tasks.Min(task => task.Result); } private static int _zeroCount; private static int InternalGetZeroCountOfPrime(int left, int right) { const int maxZeroCount = 40000; int zeroCount = Interlocked.Increment(ref _zeroCount); while (zeroCount <= maxZeroCount) { if (zeroCount % 1000 == 0) Console.WriteLine("testing " + left + " 0{" + zeroCount + "} " + right); if (IsPrime(left, right, zeroCount)) { Interlocked.Add(ref _zeroCount, maxZeroCount); return zeroCount; } else zeroCount = Interlocked.Increment(ref _zeroCount); } return PrimeNotFound; } private static bool SkipTemplate(int left, int right) { for (int leftDiv = 1; leftDiv <= left; leftDiv *= 10) for (int rightDiv = 1; rightDiv <= right; rightDiv *= 10) if (_templatesToSkip.Contains(Tuple.Create(left / leftDiv, right % (rightDiv * 10)))) return true; return false; } private static bool IsPrime(int left, int right, int zeroCount) { return IsPrime(left.ToString() + new string('0', zeroCount) + right.ToString()); } private static bool IsPrime(string left, string right, int zeroCount) { return IsPrime(left + new string('0', zeroCount) + right); } private static bool IsPrime(string s) { using (mpz_t n = new mpz_t(s)) { return n.IsProbablyPrimeRabinMiller(20); } } private static bool IsFragile(int left, int right, int zeroCount) { string leftStr = left.ToString(); string rightStr = right.ToString(); for (int startIndex = 0; startIndex < leftStr.Length - 1; startIndex++) for (int count = 1; count < leftStr.Length - startIndex; count++) if (IsPrime(leftStr.Remove(startIndex, count), rightStr, zeroCount)) return false; for (int startIndex = 1; startIndex < rightStr.Length; startIndex++) for (int count = 1; count <= rightStr.Length - startIndex; count++) if (IsPrime(leftStr, rightStr.Remove(startIndex, count), zeroCount)) return false; return true; } private static IEnumerable<Tuple<int, int>> GetTemplates() { const int maxDigitCount = 8; PreparePrimeSieve((int)BigInteger.Pow(10, maxDigitCount)); for (int digitCount = 2; digitCount <= maxDigitCount; digitCount++) { for (int leftCount = 1; leftCount < digitCount; leftCount++) { int rightCount = digitCount - leftCount; int maxLeft = (int)BigInteger.Pow(10, leftCount); int maxRight = (int)BigInteger.Pow(10, rightCount); for (int left = maxLeft / 10; left < maxLeft; left++) for (int right = maxRight / 10; right < maxRight; right++) if (IsValidTemplate(left, right, leftCount, rightCount)) yield return Tuple.Create(left, right); } } } private static void PreparePrimeSieve(int limit) { _primeSieve = new BitArray(limit + 1, true); _primeSieve[0] = false; _primeSieve[1] = false; for (int i = 2; i * i <= limit; i++) if (_primeSieve[i]) for (int j = i * i; j <= limit; j += i) _primeSieve[j] = false; } private static bool IsValidTemplate(int left, int right, int leftCount, int rightCount) { int rightDigit = right % 10; if ((rightDigit != 1) && (rightDigit != 9)) return false; if (left % 10 == 0) return false; if ((left + right) % 3 == 0) return false; if (!Coprime(left, right)) return false; int leftDiv = 1; for (int i = 0; i <= leftCount; i++) { int rightDiv = 1; for (int j = 0; j <= rightCount; j++) { int combination = left / leftDiv * rightDiv + right % rightDiv; if (_primeSieve[combination]) return false; rightDiv *= 10; } leftDiv *= 10; } return true; } private static bool Coprime(int a, int b) { while (b != 0) { int t = b; b = a % b; a = t; } return a == 1; } } ``` ### Old answer: ``` 8 0{5436} 4 0{4600} 1 ``` The are a few notable patterns for fragile primes: ``` 600..00X00..009 900..00X00..009 800..00X00..001 999..99X99..999 ``` where X can be 1, 2, 4, 5, 7 or 8. For such numbers we only have to consider (length - 1) possible `Remove` operations. The other `Remove` operations produce either duplicates or obviously composite numbers. I tried to search for all such numbers with up to 800 digits and noticed that 4 patterns come up more frequently than the rest: 8007001, 8004001, 9997999 and 6004009. Since Emil and Jakube are using the 999X999 pattern, I decided to use 8004001 just to add some variety. I've added the following optimizations to the algorithm: * I start searching from numbers with 7000 digits and then increment length by 1500 every time a fragile prime is found. If there is no fragile prime with a given length then I increment it by 1. 7000 and 1500 are just arbitrary numbers that seemed appropriate. * I'm using multithreading to search for the numbers with different length at the same time. * The result of each prime check is stored in a hash table to prevent duplicate checks. * I'm using Miller-Rabin implementation from [Mpir.NET](https://www.nuget.org/packages/Mpir.NET/), which is very fast (MPIR is a fork of GMP). ``` using System; using System.Collections.Concurrent; using System.Threading.Tasks; using Mpir.NET; class Program { const string _template = "8041"; private static ConcurrentDictionary<Tuple<int, int>, byte> _compositeNumbers = new ConcurrentDictionary<Tuple<int, int>, byte>(); private static ConcurrentDictionary<int, int> _leftPrimes = new ConcurrentDictionary<int, int>(); private static ConcurrentDictionary<int, int> _rightPrimes = new ConcurrentDictionary<int, int>(); static void Main(string[] args) { int threadCount = Environment.ProcessorCount; Task[] tasks = new Task[threadCount]; for (int i = 0; i < threadCount; i++) { int index = i; tasks[index] = Task.Run(() => SearchFragilePrimes()); } Task.WaitAll(tasks); } private const int _lengthIncrement = 1500; private static int _length = 7000; private static object _lengthLock = new object(); private static object _consoleLock = new object(); private static void SearchFragilePrimes() { int length; lock (_lengthLock) { _length++; length = _length; } while (true) { lock (_consoleLock) { Console.WriteLine("{0:T}: length = {1}", DateTime.Now, length); } bool found = false; for (int rightCount = 1; rightCount <= length - 2; rightCount++) { int leftCount = length - rightCount - 1; if (IsFragilePrime(leftCount, rightCount)) { lock (_consoleLock) { Console.WriteLine("{0:T}: {1} {2}{{{3}}} {4} {2}{{{5}}} {6}", DateTime.Now, _template[0], _template[1], leftCount - 1, _template[2], rightCount - 1, _template[3]); } found = true; break; } } lock (_lengthLock) { if (found && (_length < length + _lengthIncrement / 2)) _length += _lengthIncrement; else _length++; length = _length; } } } private static bool IsFragilePrime(int leftCount, int rightCount) { int count; if (_leftPrimes.TryGetValue(leftCount, out count)) if (count < rightCount) return false; if (_rightPrimes.TryGetValue(rightCount, out count)) if (count < leftCount) return false; if (!IsPrime(leftCount, rightCount)) return false; for (int i = 0; i < leftCount; i++) if (IsPrime(i, rightCount)) return false; for (int i = 0; i < rightCount; i++) if (IsPrime(leftCount, i)) return false; return true; } private static bool IsPrime(int leftCount, int rightCount) { Tuple<int, int> tuple = Tuple.Create(leftCount, rightCount); if (_compositeNumbers.ContainsKey(tuple)) return false; using (mpz_t n = new mpz_t(BuildStr(leftCount, rightCount))) { bool result = n.IsProbablyPrimeRabinMiller(20); if (result) { _leftPrimes.TryAdd(leftCount, rightCount); _rightPrimes.TryAdd(rightCount, leftCount); } else _compositeNumbers.TryAdd(tuple, 0); return result; } } private static string BuildStr(int leftCount, int rightCount) { char[] chars = new char[leftCount + rightCount + 1]; for (int i = 0; i < chars.Length; i++) chars[i] = _template[1]; chars[0] = _template[0]; chars[leftCount + rightCount] = _template[3]; chars[leftCount] = _template[2]; return new string(chars); } } ``` [Answer] **Haskell - 1220 1277 digits** **fixed for really reals** ``` 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997999999999999999999999999999999999999999999999999999999999999999999999 9{1150} 7 9{69} ``` Better one - 1277 digits ``` 9{871} 8 9{405} ``` Haskell code ``` downADigit :: Integer -> [Integer] downADigit n = f [] 1 where f xs a | nma /= n = f (((n `div` a10)*a + nma):xs) a10 | otherwise = xs where a10 = a * 10 nma = n `mod` a isFragile = all (not . isPrime') . downADigit findNextPrime :: Integer -> Integer findNextPrime n | even n = f (n + 1) | otherwise = f n where f n | isPrime' n = n | otherwise = f (n + 2) primesFrom n = f (findNextPrime n) where f n = n:f (findNextPrime $ n + 1) primeLimit = 10000 isPrime' n | n < primeLimit = isPrime n isPrime' n = all (millerRabinPrimality n) [2,3,5,7,11,13,17,19,984,7283,6628,8398,2983,9849,2739] -- (eq. to) find2km (2^k * n) = (k,n) find2km :: Integer -> (Integer,Integer) find2km n = f 0 n where f k m | r == 1 = (k,m) | otherwise = f (k+1) q where (q,r) = quotRem m 2 -- n is the number to test; a is the (presumably randomly chosen) witness millerRabinPrimality :: Integer -> Integer -> Bool millerRabinPrimality n a | a <= 1 || a >= n-1 = error $ "millerRabinPrimality: a out of range (" ++ show a ++ " for "++ show n ++ ")" | n < 2 = False | even n = False | b0 == 1 || b0 == n' = True | otherwise = iter (tail b) where n' = n-1 (k,m) = find2km n' b0 = powMod n a m b = take (fromIntegral k) $ iterate (squareMod n) b0 iter [] = False iter (x:xs) | x == 1 = False | x == n' = True | otherwise = iter xs -- (eq. to) pow' (*) (^2) n k = n^k pow' :: (Num a, Integral b) => (a->a->a) -> (a->a) -> a -> b -> a pow' _ _ _ 0 = 1 pow' mul sq x' n' = f x' n' 1 where f x n y | n == 1 = x `mul` y | r == 0 = f x2 q y | otherwise = f x2 q (x `mul` y) where (q,r) = quotRem n 2 x2 = sq x mulMod :: Integral a => a -> a -> a -> a mulMod a b c = (b * c) `mod` a squareMod :: Integral a => a -> a -> a squareMod a b = (b * b) `rem` a -- (eq. to) powMod m n k = n^k `mod` m powMod :: Integral a => a -> a -> a -> a powMod m = pow' (mulMod m) (squareMod m) -- simple for small primes primes :: [Integer] primes = 2:3:primes' where 1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]] primes' = p : filter isPrime candidates isPrime n = all (not . divides n) $ takeWhile (\p -> p*p <= n) primes' divides n p = n `mod` p == 0 isPrime :: Integer -> Bool isPrime n | n < 2 = False | otherwise = f primes where f (p:ps) | p*p <= n = if n `rem` p == 0 then False else f ps | otherwise = True main = do print . head $ filter isFragile (primesFrom $ 10^1000) ``` ]
[Question] [ The goal is to produce a single line of R code that: 1. Does as little as possible 2. In as many characters as possible (max of 100 characters) 3. And is as ugly as possible (where "ugly" can be taken to mean inefficient computational strategies, extraneous characters such as a terminating semicolon, and so forth). Do your worst, gentlefolk! **Objective criteria for winning** The winning answer will be judged according to the following point scale (the answer with the most points wins): * Generate a sequence from 0 to 10 (*100 points)* * In as many characters (N) as possible + *0 points* if N=100 + *N-100 points* if N<100 (i.e. lose a point for every character under 100) + *2(100-N) points* if N>100 (i.e. lose two points for every character over 100) * Using as many negative examples from the [R Inferno](http://www.burns-stat.com/pages/Tutor/R_inferno.pdf) as possible + *6 points* per cited example + Each example only counts once. This is so because a "heretic imprisoned in [a] flaming tomb" can only be so imprisoned one time. Thus two global assignments in your line of code only net you 6 points. [Answer] ## 72 96 characters. ``` `c`<-function(...){list(...)[[-1]];}->>`c`;`[`=0;`]`=10;c(c,c)(c,c)(c,invisible)(`[`[]:`]`[])[]; ``` Ugliness: * Reusing a standard function name * Using symbols as variable names * Global assignment * Right assignment * Self-redefinition of function * Unnecessary trailing semicolon(s) * Unnecessary sub-scripting numbers * Unnecessary quoting of variable name * Leaves the workspace in a state which will almost certainly break any subsequent code run Generates the sequence 0-10 (thanks to Andrie for the idea to do that). ### output: ``` [1] 0 1 2 3 4 5 6 7 8 9 10 ``` [Answer] Generate a sequence from 0 to 10. **100 characters** ``` {.=0;for(`~1` in c(1,2,3,4,5,6,7,8,9,10)){.=c(., `~1`,recursive=F)};print(unname(.[drop=T]));rm(.)} [1] 0 1 2 3 4 5 6 7 8 9 10 ``` [Answer] **100 characters:** Generate a sequence from 1 to 10. Note that the numbers 2-10 are NOT in the code... - Bonus points? :-) Also note that it uses `lapply` for maximum performance :) ``` unlist(lapply(LETTERS[-(11:26)],function(x) as.integer(charToRaw(x))-as.integer(charToRaw('A'))+1L)) #[1] 1 2 3 4 5 6 7 8 9 10 ``` [Answer] ### 100 characters ``` assign("a",1:10);b<<-paste(c(a),collapse=";");unlist(lapply(strsplit(b,";")[[1]],function(c)c[[1]])) ``` Not sure if `lapply` on `strsplit` is a negative example but it sure should be. Returns as a character: ``` [1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" ``` [Answer] ``` I(cumsum(Reduce("sum", replicate(paste0(as.integer(T),as.integer(T)), T), accumulate=1-F) - T >0)) ``` should have slightly less than 100 characters and somehow produce 0:10 ]
[Question] [ Related: [Name the poker hand](https://codegolf.stackexchange.com/questions/6494/name-the-poker-hand) > > A straight flush is a poker hand containing five cards of sequential rank, all of the same suit. As part of a straight flush, an ace can rank either above a king or below a two. An ace can rank either high (e.g. A♥ K♥ Q♥ J♥ 10♥ is an ace-high straight flush) or low (e.g. 5♦ 4♦ 3♦ 2♦ A♦ is a five-high straight flush), but cannot rank both high and low in the same hand (e.g. Q♣ K♣ A♣ 2♣ 3♣ is an ace-high flush, not a straight flush). > > > **Challenge** Given `N` cards (in any reasonable format) output a truthy value if a straight flush is contained in the poker hand. **Input** * `N` numbers of cards. (In any reasonable format) There are four suits; hearts, spades, diamonds, and clubs `(H, S, D, C)`. Each suit has one card for the numbers 2 to 10, plus 4 'picture' cards, Ace, Jack, Queen, and King `(A, J, Q, K)` *Note: You can take 10 as T* **Output** * `Truthy/Falsy` value **Test case** ``` ["AS", "2S", "3S", "4S", "5S"] => true ["3D", "9C", "4S", "KH", "AD", "AC"] => false ["5D", "6D", "7D", "8H", "9D", "10D", "JD"] => false ["JC", "7C", "5D", "8C", "AC", "10C", "9C", "5S"] =>true [] => false ["AS", "2S", "3S"] => false ["JC", "QC", "KC", "AC", "2C"] => false [ "2H", "3H", "4H", "5H", "6H", "7H"] => true ``` --- Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Winning criteria: Shortest code in each lang [Answer] # [Python 2](https://docs.python.org/2/), 95 bytes ``` lambda a:any(set('A234567891JQKA'[i/4:][:5])<={r['HCSD'[i%4]in r]for r in a}for i in range(40)) ``` [Try it online!](https://tio.run/##bY9PC4IwGMbvfYoxCBWC1Gb@oQ4yD6En8Wg7LNISasnyEtFnX@5VKKPLbw97n@fZu/bRnW/CVfV2ry78ejhyxCMuHua96kwjdlfEW/tB6KR5FhtlsyQRKyOPWZvtU5bGjhZJfzsnrBFIsvomkUS95C8tGy0lF6fKJLZlqVY2okO1WeIixguECxe4AhKgh5k1@/gSmNHw49hlmgnkafzj9mC2BvrgDkBDPnFsONJpiKZQBfahgAZjueYQGjeYbjep@fnRvydyYPZV7vY@9QY "Python 2 – Try It Online") There are 40 possible straight flushes, and this simply checks them all. Chas Brown saved 2 bytes; Jo King saved 4 more. [Answer] # [R](https://www.r-project.org/), ~~128 126~~ ~~94~~ 91 bytes ``` function(x,r=rle(outer(y<-chartr("J-X","A2-9TJQKAS",LETTERS),y,paste0)%in%x))any(r$l>4&r$v) ``` [Try it online!](https://tio.run/##dZBPa8JAFMTvfopl1bILGyj5YxRUCIkgSS82OfQaQoJCiOW5KebTp2TUbi3p5XfY9@bNzFJfsbXF@qptCn06N@KqaEN1Kc6tLkl0a6s45qRJ8Nj64IoHtrXK4kMSpFy97bJs955K1anP/KLLVzk/NfOrlHnTCZrVW/eFZl@yr0Qh@CBg3AYd0AW9lEvJpmyzZZracjLBthMNs1Vo9pL9wADvQfijqfL68hB5GC5AH1xClEWGcTQqjeHkg7czy/DuNEhDk8bkNXHHLv7p@7/pAUx@2dnj9WyUcUAX9MAF6O@f/rH/Bg "R – Try It Online") Original logic shortened considerably by @J.Doe. Makes a 26 by 26 matrix with mostly nonsense but all the cards (with the Aces repeated at the bottom) contained in rows 10 to 23 of columns 3,4,8 and 24. The matrix is created by concatenating all combinations of the upper case alphabet with letters J through X replaced by A,2-9,T,J,Q,K,A,S via `chartr`. We get C, D, H for free! The `%in%` flattens the matrix column-wise into a vector. Then see if run-length encoding is greater than 4 for any run of `TRUE` matches. [Answer] # JavaScript (ES6), 116 bytes ``` a=>[...'CDHS'].some(s=>a.map(c=>m|=c.match(s)&&2<<"234567891JQKA".search(c[0]),m=0)|(g=k=>k&&1+g(k&k/2))(m|m>>13)>4) ``` [Try it online!](https://tio.run/##jZHJboMwEIbvfQrkA7HV1OybFFtCcEDkFHFEHCwKtAVChGlPvDtNpkuitEp7@Tyy5/9n8Yt4E7Icnw/Tw354rJaaLYLxnFK6iuIkWxVUDn2FJeOC9uKAS8b7mZXHeCqfsCSqam42yLRsx/X8wEh32xBRWYnx@FrmekHWPdPJjBvWMt6qqnHf4FZtNZMQ3M8954ZFuE2WctjLoatoNzS4xjkKM7RWkAm0gDbQyVBBiKJpyjS@VnfXMis@JQXRWbBNTgzhPoy@xLXo5E@1A1ku0AP6oA4gNnQ40vi2SQrFPeCHoR99FgeT6Nzh9zC/zXKzyNV6/tHQDri9aMX8YxsmzG4BbaADdIFecvkRyzs "JavaScript (Node.js) – Try It Online") ### How? For each suit \$s\$, we convert all cards \$c\$ of suit \$s\$ into a 14-bit bitmask \$m\$, duplicate bit #13 (Ace) to bit #0 to handle the *steel wheel* (A,2,3,4,5) and count the number of consecutive bits. If it's greater than 4, we have a straight flush. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 31 bytes ``` tᵍkᵐ²cᵐ{ps₅~s"A23456789TJQKA"}ᵉ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v@Th1t7sh1snHNqUDCSrC4ofNbXWFSs5GhmbmJqZW1iGeAV6OyrVPtza@f9/tJKXs5KOgpI5mDR1AZEWYLYjmAwBk5YQ2WCl2P8A "Brachylog – Try It Online") ``` ᵍ Group input by t each element's "tail" (i.e. suit) kᵐ² Knife off the suit character from each element in each array cᵐ Concatenate the elements of each suit array into a string { }ᵉ There exists at least one string in that such that p it has a permutation s₅ which has a substring of length 5 ~s which is also a substring of "A23456789JQKA" ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 66 bytes ``` J 11 Q 12 K 13 A 1$%'¶14 \d+(.) $1$&$* O` ^ ¶ ((?(1)\1.|¶.+)){5}\b ``` [Try it online!](https://tio.run/##K0otycxL/P/fi8vQkCuQy9CIy5vL0JjLkctQRVX90DZDE66YFG0NPU0uFUMVNRUtLv8ErjiuQ9u4NDTsNQw1Ywz1ag5t09PW1Kw2rY1JAhrjzGXuzGXqwmXhzOXozGVo4MxlCeQHAwA "Retina 0.8.2 – Try It Online") Explanation: ``` J 11 Q 12 K 13 ``` Convert the picture cards into their values. ``` A 1$%'¶14 ``` `A` can be 1 or 14. ``` \d+(.) $1$&$* O` ``` Convert the value to unary, and suffix it so that the cards sort properly. ``` ^ ¶ ((?(1)\1.|¶.+)){5}\b ``` Match 5 cards that increase by 1 each time, and ensure that the last increase was exactly 1. [Answer] # JavaScript (ES6), 106 bytes ``` h=>h.map(([r,s])=>[..."HSDCA23456789TJQKA"].map(c=>i+=c==s?i*15:c==r?d[i]=1:1,i=0),d=[])|/(,1){5}/.test(d) ``` Accepts an array of string representations of cards, replacing `10` with `T`. [Try it online!](https://tio.run/##jZC9boMwFIX3PIXFErt1IfyFJJWJEEhFMKFkQwwISHFFIcIoS9tnp3DTQlp16PLZOj73@Oi@pJdUZC0/dw91kxf9ifUls0v5NT1jHLdUJITZsSzLkn/wXEfTDXNtbbbHIAodKQFbxmx@zzLGxJ7fqeZuuLX7POYJU3cq5WxFaM7ihLwrmKrkzfxQ5K4QHc5J3yGGSsRslDW1aKpCrppnfMIloWi5W1JUksfFQlHQE78UNRqnUJaKQiw6HEvOQaJI0oA60ACaBykZ5kaL7o3C1p0fQ3@kA7rjTkYThDXQAm7AuIW7uoIj8CZ/AJEW8Dq7cb8iBx7d@du5zffsr94/IyNgeBOmzS016KQDDaAJXAMtH4zjvpw85x1v6rT619KmCpAT@TeLunK2XIU/iwyW/hM "JavaScript (Node.js) – Try It Online") # Explanation Iterates over each card and sets a flag in an array of booleans using an index computed from the unique combination of its rank and suit. This array is then stringified to permit matching a pattern of 5 consecutive truthy values. For example, a hand with a straight flush may produce the following as a substring of the full string representation of the boolean array: `,,,,1,1,1,1,1,,,,` Because the first rank value (i.e. A) is offset from the start of the string, there will always be empty values preceding all `1`'s in the array, ensuring the string representation will begin with a `,` ``` h => h.map(([r, s]) => // destructure card value, e.g. "JH" => ["J", "H"] [..."HSDCA23456789TJQKA"].map(c => // mapping accounts for both positions of 'A' i += // increment index value c == s // if found index of suit... ? i * 15 // buffer so that cards from different suits cannot be confused : c == r // if found index of rank... ? d[i] = 1 // set flag to denote card is in hand : 1, i = 0 ), d = [] ) | /(,1){5}/.test(d) // implicitly converts to string joined with a , ``` [Answer] # Java 10, ~~189~~ ~~167~~ ~~165~~ ~~164~~ ~~160~~ ~~157~~ 156 bytes ``` s->{int i=10;for(;i-->0;)i=s.matches("AKQJT98765432A".substring(i,i+5).replaceAll(".","(?=.*$0\\\\1)").replaceFirst(".1","([HSDC])")+".*")?-2:i;return-1>i;} ``` Takes the input as a single space-delimited String (i.e. `"AS 2S 3S 4S 5S"`). -22 bytes thanks to *@OlivierGrégoire*. -1 byte thanks to *@AlexRacer*. [Try it online.](https://tio.run/##jZDdT8IwFMXf@StOGh82ZZWB48MFyNLGEIgkZHtTH8qcWh0dWTsSY/jbsXz5RmbTPtycc29/536KjfA@X792aS60xqOQ6qcBSGWy8k2kGeb7ElgWRZ4JhdSJTSnVO7QbWmFrn73aCCNTzKEwxE57ox87AHLot8K3onRC6XmjVujKoaYrYdKPTDskmi2myaDf6wZ3nXZEqK6W@jDakU15E7i0zNa5JYjy3CGUNIkzHtLrq9azPb5L/vQHWWpjHf7e8jSJOXux6g2h18Qde@17GZaZqUrl@SMZbnfhkXhdLXNLfALfFPIVK5v9lO7pBcI9Br@9RVJW5uP7/lDG39pkK1pUhq6t0@TKUTS1aWK0Y3Ri3MUIYuIetnPZPmXoMQQMfYaIIWEYsJq@k3KGehC5zmqgOnw/1hLNJoi4/aiWK@DocvQ4@hMMOBKOKa9tOmevNf5nLQuG2WEn7XraS/m2je3uFw) Golfed version of [the code that I've used](https://projecteuler.net/thread=54;page=6#291807) for [Project Euler #54](https://projecteuler.net/problem=54), which I primarily did with regexes (for fun and to learn more about regexes). Without regexes it would probably have been better for performance and easier (probably also applies for golfing this answer; will take a look later on). **Explanation:** ``` s->{ // Method with String parameter and boolean return-type int i=10;for(;i-->0;) // Loop `i` in the range (10,0]: i=s.matches( // If the input matches the following regex: "AKQJT98765432A".substring(i,i+5) .replaceAll(".","(?=.*$0\\\\1)") .replaceFirst(".1","([HSDC])") // Five adjacent cards +".*")? // With optionally zero or more other characters -2 // Set `i` to -2, which also stops the loops at the same time :i; // Else: leave `i` unchanged to continue return-1>i;} // Return whether `i` is not -2 (so whether the loop has finished) ``` **Additional regex explanation:** * `"AKQJT98765432A".substring(i,i+5)` takes five adjacent cards based on `i` * `.replaceAll(".","(?=.*$0\\\\1)")` replaces each of those cards with `"(?=.*c\\1)"` (where `c` is the card-character) * `.replaceFirst(".1","([HSDC])")` will then replace the first `\\1` with `([HSDC])`. I.e. the total regex to check the Straight Flush for cards in the value-range `[9,5]` will become: `^(?=.*9([HSDC]))(?=.*8\\1)(?=.*7\\1)(?=.*6\\1)(?=.*5\\1).*$` ``` ^(?=.*9([HSDC]))(?=.*8\\1)(?=.*7\\1)(?=.*6\\1)(?=.*5\\1).*$ ^ $ Match the entire string (?= )(?= )(?= )(?= )(?= ) Do positive lookaheads to check each card .* .* .* .* .* With optional leading characters in front of every card .* And any trailing characters at the end of the entire hand 9 8 7 6 5 The five adjacent values [HSDC] With a suit ( ) \\1 \\1 \\1 \\1 which is the same for all cards ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~145~~ 135 bytes ``` import StdEnv,Data.List ?l=or[isInfixOf(map hd h)['A234567891JQKA']\\a<-l,b<-l,c<-l,d<-l,e<-l,h<-[[a,b,c,d,e]]|tl(nub(map last h))==[]] ``` [Try it online!](https://tio.run/##LY5PC4IwHIbvfYrdTJhBmv2BRII6VEKFx7nDz01zsM3QFQV99paWl@fhvbzvy2QB2qqa32WBFAhthbrVjUGp4Tv9wFswMElEa0axjOqGiHavS/E8lWMFN1RxVLnE2fjBLJwvlqvp4XLcODTLYO1JnPdgPXiPoke19ggBnGOGOS4ofRs51vf81yahNV2fG0WEUpsa6G5EKEakW0gdihFx/MHB4NngsDO1H1ZKuLbW2yd2@9KgBPuHswRT1o36Ag "Clean – Try It Online") Simplified: ``` ? l // function ? taking argument l = or [ // is at least one of these true isInfixOf (map hd h) ['A234567891JQKA'] // do the first characters of a hand appear in this string, in order \\ a <- l // loop level 1, assigns `a` , b <- l // loop level 2, assigns `b` , c <- l // loop level 3, assigns `c` , d <- l // loop level 4, assigns `d` , e <- l // loop level 5, assigns `e` , h <- [[a,b,c,d,e]] // trick to assign `h`, because it's cheaper than let .. in .. | tl (nub (map last h)) == [] // only take the loop iterations where all the suits are the same ] ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 37 bytes Takes input as a 2D array. ``` "AJQKA"i1Aò2 q)øUñÌòÏ̦XÌÃËmάú5 á5Ãc ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=IkFKUUtBImkxQfIyIHEp+FXxzPLPzKZYzMPLbc6s+jUg4TXDYw==&input=W1siQSIsIlMiXSxbIjIiLCJTIl0sWyIzIiwiUyJdLFsiNCIsIlMiXSxbIjUiLCJTIl1d) --- ## Explanation ``` "AJQKA" :String literal i1 :Insert at (0-based) index 1 Aò2 : Range [2,10] q : Join ) :End insert ø :Does that string contain any element in the following array? U :Input ñ :Sort Ì : By last element (grouping suits together) òÏ :Partition between X & Y where Ì : Last element of Y ¦ : Does not equal XÌ : Last element of X à :End partition Ë :Map m : Map Î : First elements (card values) ¬ : Join ú5 : Right pad with spaces to length 5 á5 : Permutations of length 5 à :End map c :Flatten ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` Ṣœc5Uµ13R;1wṪ€ȧEµƇ ``` [Try it online!](https://tio.run/##y0rNyan8///hzkVHJyebhh7aamgcZG1Y/nDnqkdNa04sdz209Vg7UHY1kKf7qGGOo5GxiamZuYWlgVegN5Dv7OIR/KhhbqbSo43rDrcfnfRw54z//6OVvJyVdBSUzMGkqQuItACzHcGkoQGYsoRIByvFAgA "Jelly – Try It Online") Actual input format: list (`[..., ...]`) of lists of 2 integers each; the first is an integer in \$[1,13]\$, for \$A23456789TJQK\$ respectively, and the second is in \$[1,4]\$, for \$CDHS\$ respectively. The TIO link accepts input in the format of the test cases. Output format: empty list as falsy, non-empty list as truthy. [Answer] # [PHP](https://php.net/), 264 bytes It echos `1` if it is a straight flush and `0` or `null` if not. If you name the file `1X` then you can save `11 bytes` as you don't need to change `$argv[0]`. Not sure at the moment why the filename can break it. For some reason the strings `:;<=>` get sorted before the strings `0123456789` by `asort` in TIO even though `:;<=>` have ASCII values 58-62 and `0123456789` have ASCII values 48-57. So if you take the code from the TIO link or below and use [PHPTester](https://phptester.net/) with the following test suite it works. ``` $argb[0] = [".code.tio", "AS", "2S", "3S", "4S", "5S"]; // => true $argb[1] = [".code.tio", "3D", "9C", "4S", "KH", "AD", "AC"]; // => false $argb[2] = [".code.tio", "5D", "6D", "7D", "8H", "9D", "TD", "JD"]; // => false $argb[3] = [".code.tio", "JC", "7C", "5D", "8C", "AC", "TC", "9C", "5S"]; // => true $argb[4] = [".code.tio", ]; // => false $argb[5] = [".code.tio", "AS", "2S", "3S"]; // => false $argb[6] = [".code.tio", "JC", "QC", "KC", "AC", "2C"]; // => false $argb[7] = [".code.tio", "TC", "JC", "QC", "KC", "AC", "2C"]; // => true $argb[8] = [".code.tio", "2H", "3H", "4H", "5H", "6H", "7H"]; // => true for ($z=0; $z<9;$z++){ $argv=$argb[$z]; array_shift($argv); unset($a,$b,$c,$d,$e,$f,$g,$h,$i); $f=false; // not needed, just removes several notices // TIO code here echo "<br>"; ``` TIO Code ``` for($b=count($a=$argv);$b;){$a[0]='1X';$a[--$b]=strtr($a[$b],'ATJQK','1:;<=');$a[]=($a[$b][0]==1?">".$a[$b][1]:1);}asort($a);foreach($a as$c){$d[$c[1]][]=$c[0];}foreach($d as$e){if(4<$g=count($e)){for($h=0;$g>$i=4+$h;){$f|=(ord($e[$i])-ord($e[$h++])==4);}}}echo$f; ``` [Try it online!](https://tio.run/##PY9Pa8MwDMW/yigCx6QZCWRsq6OW4p2601gPg@CD89e51MFJd8ny2T15tLuIJ@snvefRjL44jFQ76yKosLbXyxyBRtCu/@YCKsEX0GWqkGVfTJBMEqgUTrObaUOX1GzZ8Xz6eGdblu1EgYwHTOFtGnYxO2z2m8fbQ6Z2GRernqwLXlyQeatrQ/pBT1CTY1NCTZyiMyRSJdZ/pglMy5ehi/IC@nvklvPl7xMGUwH9HgbMYzAhfveDkXUNMSUMiid3beJYccScsqxrWxsLnfDen6R/lv7pzb9If5T@LP0rtZ@/ "PHP – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), 226 bytes Used T for 10 so all cards are 2 characters in length. ``` {h:List<String>->val m=List(4){mutableSetOf<Int>()} for(c in h)m["CDHS".indexOf(c[1])].add("A23456789TJQK".indexOf(c[0])) var r=0>1 for(b in m){if(b.contains(0))b.add(13) for(i in 0..9)r=b.containsAll((i..i+4).toList())||r} r} ``` [Try it online!](https://tio.run/##fVbbbttGEH3XVwyEACERhrr6pkYuBLmpbaUOXBkoCsMPS2llEaZIdnfp2LD1IXk22g/Lj7gzs7xIshQ/jEnunLmemdVdYqIwfm00YKikMHIKs0SBmYcaJslUwm0SzWAyF1Ek41vZq6Hi3JhU9xoNOqdjXxsxuZMPqIUq/iRZNP7JpDZhEutGa/@o0zwk2Jm2ZgVoo0R4OzcwizI9/xUP6fxPGZH/HlyIhURVCWlyJxWg1WmuMtiAApur1DDk2IgwDuNbmIX3kjAToaYakhloiVHFJhQRKBHfeYA50XfypMmlzkLjsxsNqVCGDjeDRVQMYiLRbMxmSF@GaEOBCJJ7iYg7co9FDGSUfMN38y3xYVDCCEHIAjZH6@BI/xaVfnz/F0YkLkmck2g1SVKijEQjHxmxHpdLDsmdNbT34/t/0CXRQUG4Nr0MSHDNqDpb7XgQZIbCjBNTRhokZm7jpCKTmzCu6saVt34x7BdCYQ4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Qt7oHA6XEYzUZxVx8WR@pbYYss1PoW0S7vQ/BIzp/fZr3Vsft4zFPQD@n/tMW4i9raN@ZMOPdxRuSVwzfSWzLau53v3ncYnsBt9d9CmdOsNbNoOwgqYVl41Q/2OgSduhDd6Ulz89qWVPLV854bAeB6q13F8ge9/GmxkJjqBFawn87bqacCbTr8RdUofuzi6lA4PZeQfzsWioQV8XdtILbfh2t@MAvV@t3UoWunkrAepJvHFXXz7qL9loy2@@eAlHeQDus2zRGO9KgBIp1WK4l6hn9dtJpJB65rWS43Hq8GsvrwI6jX2wWHr98DHWxVlKcBOPUr@srS6PY8aRY7Ixc7x2dYXBuBY5ix16x755S9uEu@bjcC/xAg/36Pw "Kotlin – Try It Online") [Answer] # [Pascal (FPC)](https://www.freepascal.org/), ~~223~~ ~~216~~ ~~210~~ 209 bytes ``` var a,b:char;c:set of byte;i:byte;begin repeat readln(a,b);i:=pos(b,'HDC')*14+pos(a,'23456789TJQK');c:=c+[i];if a='A'then c:=c+[i+13]until eof;i:=0;while not([i..i+4]<=c)or(i mod 14>9)do i:=i+1;write(i<52)end. ``` [Try it online!](https://tio.run/##LYw7b4MwFIV3/4q72S4UlVfbQKiE3CFKpohsEYMxplyJ2gjcRv311Kk6HZ3Hd2a5Kjk9DrPatm@5gAy7Qo1yKVWxagd2gO7H6RKLP@n0BxpY9Kyl8yL7yTBPcN9Xs11ZF9LDu6D8Ic6Cu5chTdIsf3553V2O5xPl/rZSwRXbEgeQFa2pG7WB/zSI0/bLOJxA2@H@@VTeRpw0GOvYFaMIg6zdV4rbhSF82h7i7G3Hewt@6@nytqDTDPd5wrXpo21LGpI2JGtI3pD6QGpBLoIcBTkLchK/ "Pascal (FPC) – Try It Online") Uses `T` for 10. Input contains 1 card per line. Now I golfed it so much that I don't know how it works anymore... ## Explanation: ``` var a,b:char; //for reading cards c:set of byte; //this set is for remembering which cards are present in the input //14 numbers used for each suit i:byte; begin repeat readln(a,b); //read rank into a, suit into b and a newline i:=pos(b,'HDC')*14+pos(a,'23456789TJQK'); //temporary use i to calculate corresponding number for the card //pos() gives 0 if b is not found //1st pos() is for the group of numbers for that suit, 2nd pos() is for offset c:=c+[i]; //include i into set if a='A'then c:=c+[i+13] //if rank is A, include the number at the end of group as well until eof; i:=0; while not( ([i..i+4]<=c) //if NOT 5 cards in a row are present... and //while the check is started from 10 (T)... (i mod 14<10) //(otherwise, it is checking across 2 different suits) )do i:=i+1; //increment i, otherwise stop write(i<52) //if i<=51, there is a straight flush starting at the card corresponding to i //(if there isn't a straight flush, i stops at 252 due to i..i+4, I don't know why) end. ``` ]
[Question] [ Take a matrix of positive integers as input, and output the individual sums of the elements on the diagonal lines through the matrix. You shall only count the lines that goes diagonally down and to the right. You must start with the diagonal that contains only the bottom-left element, then the length-two diagonal above that (if it exists) and so on through to the diagonal that contains only the top-right element, as illustrated below. **Example:** ``` Input: 8 14 5 1 10 5 5 8 6 6 8 10 15 15 4 11 Output: 15, 21, 20, 32, 29, 13, 1 (Diagonals: {{15},{6,15},{10,6,4},{8,5,8,11},{14,5,10},{5,8},{1}}) Input: 1 Output: 1 Input: 1 5 Output: 1, 5 Input: 4 1 Output: 1, 4 Input: 17 4 5 24 16 5 9 24 10 1 14 22 1 21 24 4 4 17 24 25 17 Output: 24, 29, 22, 39, 47, 70, 43, 9, 5 ``` Input and output formats are optional as always. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission in each language wins. [Answer] # [Haskell](https://www.haskell.org/), ~~40~~ 37 bytes ``` z=0:z foldl1$(.(++z)).zipWith(+).(0:) ``` [Try it online!](https://tio.run/nexus/haskell#lYpNCoAgFAb3neItWih@iA8yIvAcLcRFEJLQH9HKy5sdod0wMyU7M@Ymunhuy8at0EKpLKXO6ZrSswoltTCjLPucDnJ03el4qKVI3g/gDhYc4NlUsBgq9uhRi/lsjRYdmEMoP/8X "Haskell – TIO Nexus") Usage: `(foldl1$(.(++z)).zipWith(+).(0:)) [[1,2,3],[4,5,6]]`. **Edit:** Thanks to Ørjan Johansen for -3 bytes! ### Ungolfed: ``` z = 0:z s#t = zipWith(+)(0:s)(t++z) f m = foldl1 (#) m ``` `z` is a list of infinitely many zeros. In `f` we fold over the list of lists `m` by combining two lists with the function `#`. In `#` the first list `s` contains the accumulated column sums so far and the second list `t` is the new row which should be added. We shift `s` one element to the right by adding a zero to the front and element-wise add `s` and `t` with `zipWith(+)`. Because `s` might be arbitrarily large, we have to pad `t` with enough zeros by appending `z`. [Answer] # Mathematica, ~~53~~ 54 bytes ``` l=Length@#-1&;Tr@Diagonal[#,k]~Table~{k,-l@#,l@#&@@#}& ``` Pure function taking a 2D-array as input and returning a list. (Entries don't have to be integers or even numbers.) `Diagonal[#,k]` returns the `k`th diagonal above (or below, if `k` is negative) the main diagonal. `{k,-l@#,l@#&@@#}` computes the range of diagonals needed based on the dimensions of the input array. And `Tr` sums the entries of each diagonal. [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` T&XdXs ``` [Try it online!](https://tio.run/nexus/matl#@x@iFpESUfz/f7SFgqGJgqmCobWCoQGQNlWwsFYwA0KguAFQzBSETBQMDWMB "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#HUw5DsAgDNv7Ck@dSUSAirVPYEBCSB36g/5f1EG5HMfxs9rZ3/6tu61RIBEGqZDAaSgViUE@kDPPCJF5jF0w9siLL5knq1AKkoNrQ/9zV1UHyqQ@ukveWqVpnj8). ### Explanation ``` T&Xd % All diagonals of implicit input arranged as zero-padded columns Xs % Sum of each column. Implicitly display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` 0;+µ/ ``` [Try it online!](https://tio.run/nexus/jelly#TU7JDYQwDPynivkTidgKx4oCtogozfChGb40AJ3QSNZOAtnHSJ5TTm7pzqNP13av@zelYBACZgvyFhgEFK0BArnKFXPRMMqt0LyrOfEVkD5RFDEv/l268TJfl16fptKVTHZYd8bG8bHImnua5VfmxlnxLPv6y9T2eMg8mvgD "Jelly – TIO Nexus") ### How it works ``` 0;+µ/ Main link. Argument: M (matrix / array of rows) µ Combine all links to the left into a chain (arity unknown at parse time) and begin a new monadic chain. / Reduce M by that chain. This makes the chain dyadic. Let's call the arguments of the chain L and R (both flat arrays). 0; Prepend a 0 to L. + Perform element-wise addition of the result and R. When the chain is called for the n-th time, R has n less elements, so the last n elements of L won't have matching elements in R and will be left unaltered. ``` [Answer] ## JavaScript (ES6), ~~65~~ 58 bytes ``` a=>a.map(b=>b.map((c,i)=>r[i]=~~r[i]+c,r=[,...r]),r=[])&&r ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~22~~ 21 bytes Saved 1 byte thanks to Martin Ender ``` {_,({0\f+}*ee::m<:.+} ``` Anonymous block expecting the argument on the stack and leaves the result on the stack. [Try it online!](https://tio.run/nexus/cjam#K6z7Xx2vo1FtEJOmXauVmmpllWtjpadd@7@u4H90tKG5AhCYgAjTWK5oIxDL0AzGVbAEMiBiBiCuIYgF4hoZwbhGYMIExDWBGWVoDjPKyBTCjQUA "CJam – TIO Nexus") **How it works** ``` _ e# Duplicate the matrix ,( e# Get its length (# of rows) minus 1 {0\f+}* e# Prepend that many 0s to each row ee e# Enumerate; map each row to [index, row] ::m< e# Rotate each row left a number of spaces equal to its index :.+ e# Sum each column ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` Rvy¹gÅ0«NFÁ}})øO¨ ``` [Try it online!](https://tio.run/nexus/05ab1e#@x9UVnloZ/rhVoNDq/3cDjfW1moe3uF/aMX//9HRhuY6JjqmsTrRRiY6hmZglqUOiG0AZBnqGJroGBmBWUZAZAJkmQDVG5pDNBiZgpixAA "05AB1E – TIO Nexus") **Explanation** ``` R # reverse input v # for each N,y (index, item) y¹gÅ0« # pad y with as many zeroes as the number of rows in the input NFÁ} # rotate each row N times right }) # wrap the result in a list øO # sum the columns ¨ # remove the last element of the resulting list (the padded zeroes) ``` [Answer] # [J](http://jsoftware.com/), 7 bytes ``` +//.@|. ``` [Try it online!](https://tio.run/nexus/j#U9JTT1OwtVJQV9BRMFCwAmJdPQXnIB0ft//a@vp6DjV6/zW5UpMz8hXSFEwUTFSU9NQV1LPyM/OKS4oy89JtrPXiDWutNHzcoNo1uRQsFBQUDE2AhIIpiDDkMjSAc8CEBZeCGYgGE2DVBlyGIBkwoQDSamjIpfkfAA "J – TIO Nexus") This is pretty simple: ``` +//.@|. +/ sum /. on oblique lines @|. on the reversed array ``` Oblique reversed lines are the diagonals of the array, so this is just summing the diagonals. [Answer] # [Python 2](https://docs.python.org/2/), 62 bytes ``` lambda M:reduce(lambda x,y:map(sum,zip([0]+x,y+[0]*len(x))),M) ``` [Try it online!](https://tio.run/nexus/python2#bU/LCoMwELznK/aY1ByS4KtCP8EvSHOwVUFQEVvB9uftrkak4GFIZrIzs6nhBvelLbpHWUCejVU5PSvu@Sw/WVcM/DV18tsM3CoXoBbgeWmrns9CCJmLZRib/g01Z2AtpBJ0KAEihHaSAVitPCekmwYx3gk0r/wcvhMA/Vo7xwRjf9mnGuWe6KHvOfHoZOtA3zpjqC8@OFwlrJraM7Y/GXNwQ9g7Qr9zcuSZaOXYvfwA "Python 2 – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒDS€ṙZL$ ``` **[Try it online!](https://tio.run/nexus/jelly#@390kkvwo6Y1D3fOjPJR@f//f3S0obmOgomOgmmsDpdCtJGJjqEZjKNgqQPiG0A4hjqGJjpGRjCOERCZQDgmIAMMzWEGGJmCOLEA "Jelly – TIO Nexus")** Half of the code is used to put the results into the correct order. ### How? ``` ŒDS€ṙZL$ - Main link: list of lists of numbers ŒD - diagonals (starts with the diagonal containing the top left element, - then the next diagonal to the right, and so on wrapping around) S€ - sum €each $ - last two links as a monad Z - transpose the matrix L - length (width of the matrix) ṙ - rotate the results left by that amount ``` [Answer] # Perl 5, 47 bytes ``` map{$j=--$.;map{@a[$j++]+=$_}split}<> print"@a" ``` [Answer] ## R, 45 bytes Unnamed function taking a matrix-class object as input: ``` function(x)sapply(split(x,col(x)-row(x)),sum) ``` Using the idea explained in [this](https://codegolf.stackexchange.com/a/100958/56989) answer. [Answer] # Octave, 71 bytes Assuming A is a matrix, for example: ``` A = [17 4 5;24 16 5; 9 24 10; 1 14 22; 1 21 24; 4 4 17;24 25 17]; ``` Then we have: ``` [m,n]=size(A); a=[zeros(m,m-1),A]'; for i=1:m+n-1 trace(a(i:end,:)) end ``` Notice that transposing the matrix reverses the ordering of the diagonal sums, which saved an overall two bytes in the for loop. Output: ``` ans = 24 ans = 29 ans = 22 ans = 39 ans = 47 ans = 70 ans = 43 ans = 9 ans = 5 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ÞD?L‹ǔṠ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnkQ/TOKAuceU4bmgIiwiIiwiW1sxNywgNCwgNV0sIFsyNCwgMTYsIDVdLCBbOSwgMjQsIDEwXSwgWzEsIDE0LCAyMl0sIFsxLCAyMSwgMjRdLCBbNCwgNCwgMTddLCBbMjQsIDI1LCAxN11dIl0=) Takes 4 bytes to get it in the right order. If the order didn't matter, it would be 3 bytes (remove the `?L‹ǔ`). [Answer] # Python, 126 bytes ``` x=input() f=lambda k:[x[i+k][i]for i in range(len(x)-k)] a=map(f,range(4)[::-1]) x=zip(*x) print(map(sum,a+map(f,range(1,4)))) ``` `f` only works on the lower triangular section, so I transpose it and get the upper triangular section that way. Don't know why the `f` function doesn't work for negative values (I changed `f` to be shorter because the part to get the negatives didn't work). [Answer] # C, 148 bytes [**Try Online**](http://ideone.com/oRcerv) ``` s;g(int i,int j,int**m,int x){for(s=0;x;x--)s+=m[i++][j++];printf(" %d",s);} k;f(int n,int**m){for(k=n;--k;)g(k,0,m,n-k);for(;k<n;k++)g(0,k,m,n-k);} ``` [Answer] # PHP, 81 Bytes Take Input as 2 D Array ``` <?foreach($_GET as$k=>$v)foreach($v as$x=>$y)$r[$x-$k]+=$y;ksort($r);print_r($r); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUol3dw2xjY620DE00THVMYzl0ok2NACyTHUsQGwzHTMdoJwBWBwob6pjomNoGBtr/T8tvyg1MTlDA2yCQmKxSratnUqZJly4DCRWARSr1FQpilap0FXJjtW2Vam0zi7OLyrRUCnStC4oyswriS8Cs///BwA "PHP – TIO Nexus") [Answer] # Awk, 67 Bytes ``` {for(f=0;f++<NF;)s[NF-NR+f]+=$f}END{i=0;while(i++<NR*2)print s[i]} ``` Ungolfed: ``` { for (f = 0; f++ < NF;) s[NF-NR+f] += $f } END { i = 0 while (i++ < NR*2) print s[i] } ``` Awk splits on whitespace `$n` is the `n`th field (1-indexed); `NF` is the number of fields on the line, `NR` is the number of the current row. Undefined variables are 0 and created on first use. [Answer] # PHP, 86 bytes a memory friendly solution in two variants: ``` <?for($i=$c=count($a=$_GET);--$i>-$c;print$s._)for($s=0,$d=$c;$d--;)$s+=$a[$i+$d][$d]; <?for($i=$c=count($a=$_GET);--$i>-$c;print$s._)for($s=$d=0;$d<$c;)$s+=$a[$i+$d][$d++]; ``` takes input from script parameters, uses underscore as delimiter; use default settings (not default php.ini) or [try them online](http://sandbox.onlinephpfunctions.com/code/8d0eacededdc003bc00054e0805c2dae98177eb8) [Answer] ## Clojure, 81 bytes ``` #(apply map +(map(fn[i c](concat(repeat(-(count %)i 1)0)c(repeat i 0)))(range)%)) ``` Quite verbose, as it pads lists with zeros so that we can just calculate the column-wise sum. [Answer] ## mathematica 73 bytes ``` Plus@@@Table[Diagonal[Partition[#1,#2[[1]]],k],{k,-#2[[2]]+1,#2[[1]]-1}]& ``` This one works for ANY 2D-array m x n (not only nxn) input the array at the end of the code like this (the last test case) ``` [{17,4,5,24,16,5,9,24,10,1,14,22,1,21,24,4,4,17,24,25,17},{3,7}] ``` > > {24, 29, 22, 39, 47, 70, 43, 9, 5} > > > input in form [{a,b,c,d...},{m,n}] [Answer] # [Husk](https://github.com/barbuz/Husk/wiki/Commands), 6 [bytes](https://github.com/barbuz/Husk/wiki/Codepage) ``` mΣ∂m↔T ``` [Try it online.](https://tio.run/##yygtzv7/P/fc4kcdTbmP2qaE/P//PzraQsfQRMdUxzBWJ9rQAMgw1bEAMs10zHSAMgYgUaCkqY6JjqFhbCwA) **Explanation:** ``` T # Transpose the (implicit) argument; swapping rows/columns m↔ # Reverse each row ∂ # Take the anti-diagonals of this matrix mΣ # And sum each inner anti-diagonal list # (after which the result is output implicitly) ``` ]
[Question] [ # [The Baum-Sweet Sequence (A086747 with a Twist)](https://oeis.org/A086747) Take in a positive integer `n` and print the integers from 1 to n for which the Baum-Sweet sequence returns true. The Baum-Sweet sequence should return **falsy** if the binary representation of the number contains an odd number of consecutive zeros anywhere in the number, and **truthy** otherwise. For more information, click the link. Here's a couple of examples: ``` 1 -> 1 -> Truthy 2 -> 10 -> Falsy 3 -> 11 -> Truthy 4 -> 100 -> Truthy (Even run of zeros) ``` # Here's an example given `n=32` Step 1: The Baum-Sweet sequence visualized for `n=32` ``` 1 1 (1) 1 0 0 (2) 11 1 (3) 1 00 1 (4) 1 0 1 0 (5) 11 0 0 (6) 111 1 (7) 1 000 0 (8) 1 00 1 1 (9) 1 0 1 0 0 (10) 1 0 11 0 (11) 11 00 1 (12) 11 0 1 0 (13) 111 0 0 (14) 1111 1 (15) 1 0000 1 (16) 1 000 1 0 (17) 1 00 1 0 0 (18) 1 00 11 1 (19) 1 0 1 00 0 (20) 1 0 1 0 1 0 (21) 1 0 11 0 0 (22) 1 0 111 0 (23) 11 000 0 (24) 11 00 1 1 (25) 11 0 1 0 0 (26) 11 0 11 0 (27) 111 00 1 (28) 111 0 1 0 (29) 1111 0 0 (30) 11111 1 (31) 1 00000 0 (32) ``` So, after computing the Baum-Sweet sequence for n, take the numbers that were truthy for the sequence and collect them for the final result. For `n=32` we would have: ``` [1, 3, 4, 7, 9, 12, 15, 16, 19, 25, 28, 31] ``` As the final answer. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest byte count wins. [Answer] # JavaScript (ES6), ~~70~~ ~~68~~ 63 bytes ``` g=n=>n?g(n-1).concat(/0/.test(n.toString(2).split`00`)?[]:n):[] console.log(g(1000).join(", ")) ``` Slightly more interesting recursive solution: ``` n=>[...Array(n+1).keys()].filter(f=n=>n<2?n:n%4?n&f(n>>1):f(‌​n/4)) ``` 67 bytes thanks to @Neil. `g` is the function to call. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes Saved a byte thanks to *Adnan* ``` ƒNb00¡SP– ``` [Try it online!](https://tio.run/nexus/05ab1e#@39skl@SgcGhhcEBjxom//9vbAQA "05AB1E – TIO Nexus") **Explanation** ``` ƒ # for N in [0 ... input] Nb # convert N to binary 00¡ # split at "00" S # convert to list of digits P # product of list – # if 1, print N ``` [Answer] ## Python 2, 62 bytes ``` g=lambda n:n*[0]and g(n-1)+[n]['0'in`bin(n)[1:].split('00')`:] ``` Checks for odd runs of 1's in the binary representation by splitting on `00` and checking if any zeroes remain in the string representation of the resulting list. Annoyingly, binary numbers start with `0b`, which has a zero that needs to be removed to avoid a false positive. The enumeration is done by recursing down. [Answer] # Bash, ~~58~~, 46 bytes EDITS: * Replaced *bc* with *dc* (Thx @Digital Trauma !) * Start with 1; **Golfed** ``` seq $1|sed 'h;s/.*/dc -e2o&p/e;s/00//g;/0/d;x' ``` **Test** ``` >./baum 32 1 3 4 7 9 12 15 16 19 25 28 31 ``` **Explained** *shell* ``` seq $1 #generate a sequence of integers from 1 to N, one per line |sed #process with sed ``` *sed* ``` h #Save input line to the hold space s/.*/dc -e2o&p/e #Convert input to binary, with dc s/00//g #Remove all successive pairs of 0-es /0/d #If there are still some zeroes left #(i.e. there was at least one odd sequence of them) #drop the line, proceed to the next one x #Otherwise, exchange the contents of the hold #and pattern spaces and (implicitly) print ``` [Try It Online !](https://www.jdoodle.com/embed/v0/bash/4.2.42/1Gd) [Answer] ## Batch, 143 bytes ``` @for /l %%i in (1,1,%1)do @call:c %%i @exit/b :c @set/ai=%1 :l @if %i%==1 echo %1&exit/b @set/ar=%i%%%4,i/=4-r%%2*2 @if %r% neq 2 goto l ``` [Answer] # [Perl 6](https://perl6.org), 40 bytes ``` {grep {.base(2)!~~/10[00]*[1|$]/},1..$_} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS0oszdUtLk9NLVGw/V@dXpRaoFCtl5RYnKphpKlYV6dvaBBtYBCrFW1YoxKrX6tjqKenEl/7Py2/SCEnMy@1WENToZpLQaE4sVIBySSVeGuu2v/GRlyGRhYA "Perl 6 – TIO Nexus") ``` { grep # find all of them { .base(2) # where the binary representation !~~ # does not match / 10 # 「10」 [ 00 ]* # followed by an even number of 「0」s [ 1 | $ ] # either at end or before a 「1」 / }, 1 .. $_ # from one to the input } ``` ( `[]` are used for non-capturing grouping, with `<[]>` used for character classes ) [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~79~~ 61 bytes ``` 1..$args[0]|?{0-notin([convert]::ToString($_,2)-split'1|00')} ``` [Try it online!](https://tio.run/nexus/powershell#@2@op6eSWJReHG0QW2NfbaCbl1@SmacRnZyfV5ZaVBJrZRWSH1xSlJmXrqESr2OkqVtckJNZom5YY2Cgrln7//9/YyMA "PowerShell – TIO Nexus") I had inspiration this morning to change how I perform the `-split` operation, then see that it's similar to how [xnor's answer](https://codegolf.stackexchange.com/a/104279/42963) is constructed, so, I guess great minds think alike? We loop from `1` up to input `$args[0]`, and use a `Where-Object` operator to pull out the appropriate numbers `|?{...}`. The clause is a simple Boolean value -- we're ensuring that `0` is `-notin` the results of `(...)`. Inside the parens, we `[convert]::` the current number `$_` `ToString` with the base `2` (i.e., turn it into a binary string). We then `-split` the string on the regex `1|00` -- this is a greedy match, and results in an array of strings (for example, `100010` would turn into `'','','0','','0'` and so forth). Thus, if every run of `0`s in the binary string is even (meaning the regex has split them out into empty strings), then `0` will be `-notin` the result, so the `Where` clause is true, and the number is selected. Those numbers are left on the pipeline and output is implicit. [Answer] # [Python 2](https://docs.python.org/2/), ~~67~~ 47 bytes ``` f=lambda n,k=1:n/k*[1]and[k]+f(n,k-~k)+f(n,4*k) ``` *Thanks to @xnor to golfing off 20(!) bytes!* Returns an unordered list. It's quite efficient: input **100,000** takes roughly 40 ms on TIO. [Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCnk21raJWnn60VbRibmJcSnR2rnaYBFNWty9YEs0y0sjX/FxRl5pUoFOcXlaSmaKRpGBqAgKbmfwA "Python 2 – TIO Nexus") [Answer] ## Mathematica, 59 bytes ``` Select[Range@#,!Or@@OddQ/@Tr/@Split[1-#~IntegerDigits~2]&]& ``` Mathematica answer number 4... [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12~~ 11 bytes ``` :"@BY'og)?@ ``` [Try it online!](https://tio.run/nexus/matl#@2@l5OAUqZ6frmnv8P@/sREA "MATL – TIO Nexus") ### Explanation To detect if a number is valid this converts to binary, applies run-length encoding, keeps only runs of odd length, and checks if no run of zeros survives. ``` : % Take input n implicitly. Push range [1 2 ... n] " % For each k in [1 2 ... n] @ % Push k B % Convert to binary Y' % Run-length encoding. Pushes array of values and array of run-lengths o % Parity. Gives array that contains 0 for even lengths, 1 for odd g) % Convert to logical and use index into the array of values ? % If the result does not contain zeros @ % Push k % End % End % Implicitly display stack ``` [Answer] ## R, 75 bytes ``` for(i in 1:scan()){x=rle(miscFuncs::bin(i));if(!any(x$l%%2&!x$v))cat(i,"")} ``` Reads input from stdin and uses the `bin` function from the `miscFuncs` package to convert from decimal to binary vector. Consequently performs run-length encoding to check values `== 0` and lengths are odd. [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 69 bytes [Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html) ``` :>1+[bits{e.b:e b 0#=}chunkby[0 has]filter$sizemap 2%0 eq all]"filter ``` Or, noncompeting at 67 bytes: ``` :>1+[bits{e.b:e b 0#=}chunkby[0 has]filter$sizemap even all]"filter ``` And, even more noncompeting at 49 bytes: ``` :>1+[bits rle{k:k 0=}filter values even all]fkeep ``` All take input as TOS and leaves output on TOS. ## Explanation ``` :>1+[...]"filter input: n :> range from [0, n) 1+ range from [1, n] [...] a function "filter apply to each cell and filter ``` The function: ``` bits{e.b:e b 0#=}chunkby[0 has]filter$sizemap 2%0 eq all input: c bits convert c to binary {e.b:e b 0#=}chunkby split into chunks of contiguous 0s [0 has]filter take only chunks with 0s $sizemap map each chunk to its size 2% vectorized modulus 2 0 eq vectorized equality with 0 all all of them are of even lengths ``` ### Explanation of noncompeting: It's the same as above, with a few key differences: ``` :>1+[bits rle{k:k 0=}filter values even all]fkeep input: y rle run length encode y {k:k 0=}filter keep keys that = 0 values get those values fkeep like `filter`, but is implemented with taking `f` as a boolean mask ``` [Answer] # Befunge, ~~84~~ ~~51~~ 49 bytes After a bit of experimentation, I realised I could do quite a bit better than my original solution by using a technique similar to the [Batch answer](/a/104231/62101) that [Neil](/users/17602/neil) came up with. ``` <v::\<&1 :_v#:/+2*2!%2:_v#-2%4 :$<@_v#!:-1\+1$<:. ``` [Try it online!](http://befunge.tryitonline.net/#code=PHY6Olw8JjEKOl92IzovKzIqMiElMjpfdiMtMiU0CjokPEBfdiMhOi0xXCsxJDw6Lg&input=MzI) As with my original solution, there are two loops - the outer loop iterating over the numbers we want to test, and an inner loop testing the bit sequence for each number. The way the test works is by examining two bits at a time (modulo 4 of the current value). If that's equal to 2 we've got an odd sequence of zeros and can abort the inner loop and proceed to the next number. If the modulo 4 is not equal to 2, we need to continue testing the remaining bits, so we shift up the bits that have already been tested. This is done by dividing the value, lets call it *n*, by `2+2*!(n%2)`. This means if the first bit was a 1, we divide by 2 (dropping that 1 bit), but if it was a 0, we divide by 4, so we'll always be dropping pairs of zeros. If we eventually get down to zero, that means there weren't any odd sequences of zero bits, so we write out the number. [Answer] # Visual Basic(.net 4.5) 163 bytes First ever answer here so I'm sure I've screwed something up. Let me know and I'll fix. Are Visual Basic lambdas even allowed? Thanks to MamaFunRoll for the remove consecutive zeroes idea ``` Dim R=Sub(m)System.Console.WriteLine(String.Join(",",System.Linq.Enumerable.Range(1, m).Where(Function(s) Not Convert.ToString(s,2).Replace("00","").Contains(0)))) ``` R(32) outputs ``` 1,3,4,7,9,12,15,16,19,25,28,31 ``` [Answer] ## Java, ~~144~~ ~~130~~ 128 Bytes This isn't as golfed as I think it can be, but I thought it'd be a cute solution to use a Regex, despite never having used one. Golfed: `static String a(int n){String s="";for(Integer i=0;i++<n;)if(i.toString(i,2).replaceAll("00|1","").isEmpty())s+=i+" ";return s;}` Ungolfed: ``` static String a(int n){ String s=""; //Cheaper than using a list/array for(Integer i=0;i++<n;) //Loop n times if(i.toString(i,2) //Convert int to base 2 string .replaceAll("00|1","")//Find and remove ones and consecutive zeroes .isEmpty()) //If any chars remain, i is truthy s+=i+" "; //Append i to the storage string return s; //Return all values } ``` **Edit:** I was able to save 14 bytes by making the regex 00|1 instead of 00, and removing ".replace("1","")" between the replaceAll and isEmpty! **Edit 2:** I was able to save 2 bytes by making i an Integer and referencing Integer.toString with i.toString. [Answer] ## Clojure, 103 bytes I don't think this is the shortest way... ``` #(remove(fn[v]((set(map(fn[s](mod(count s)2))(re-seq #"0+"(Integer/toString v 2))))1))(range 1(inc %))) ``` Uses `re-seq` to find consecutive zeros, maps their modulo-2 lengths to a `set`, discards them if number `1` is found from the set. [Answer] # [Wonder](https://github.com/wonderlang/wonder), 38 bytes ``` @(!>@=1len iO0Rstr#["00"]bn#0)rng1+1#0 ``` Usage: ``` (@(!>@=1len iO0Rstr#["00"]bn#0)rng1+1#0) 32 ``` # Explanation More readable: ``` @( fltr@ = 1 len iO 0 Rstr #["00"] bn #0 ) rng 1 +1 #0 ``` `rng 1 +1 #0`: Range from 1 to input. `fltr@ ...`: Filter range with the following predicate. `bn #0`: Convert current item to binary. (This will have a leading `0b`). `Rstr #["00"]`: Recursively prune any occurrences of `00` in the string. `len iO 0`: Count the amounts of `0`s in the string. `=1`: Check if the amount is equal to 1. If the only `0` left in the string after pruning is in the leading `0b`, then this returns true; otherwise, this returns false. [Answer] # Ruby, ~~78~~ ~~69~~ 68 bytes ``` ->n{(1..n).select{|m|m.to_s(s=2).split(?1).map{|i|s|=i.size};s&1<1}} ``` Older versions: ``` ->n{(1..n).select{|m|m.to_s(2).split(?1).select{|i|i.size%2>0}[0].!}} ->n{(1..n).select{|m|b=z=0;(m.to_s(2)+?1).each_char{|i|z+=i>?0?b|=z:1};b&1<1}} ``` [Answer] # Mathematica, 81 bytes ``` Select[Range@#,FreeQ[Union@#+Mod[Length@#,2,1]&/@Split[#~IntegerDigits~2],{1}]&]& ``` Computes, for each run of consecutive digits in a number, { the common digit in that run plus (1 if the length is odd, 2 if the length is even) }; if any of the answers is {1} then the number isn't in the sequence. [Answer] ## Mathematica, 75 bytes ``` Select[Range@#,And@@EvenQ/@Length/@Cases[Split[#~IntegerDigits~2],{0..}]&]& ``` `#~IntegerDigits~2` computes the list of binary digits of the input `#`. `Split` that list into runs of identical elements, take the `Cases` that match `{0..}`, take the `Length` of each of them, take `EvenQ` of the lengths and then return `And` of the results. [Answer] # Python 3, ~~86~~ 82 bytes Golfing in progress... ``` lambda n:[x for x in range(1,n+1)if 1-any(i%2for i in map(len,bin(x).split('1')))] ``` Golfed off 4 bytes by changing `bin(x)[2:]` to just `bin(x)` - this leaves `0b` at the start of the string, but I realised this does not actually affect the calculations :) [Answer] # Python, 142 bytes This is mainly just to practice golfing my Python. ``` def o(n): r=0 for i in bin(n)[2:]: if i=='1': if r&1:return 0 r=0 else:r+=1 return ~r&1 lambda n:[i for i in range(1,n+1)if o(i)] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` 2ṗx"`ḂḄf@R ``` Terribly inefficient. [Try it online!](https://tio.run/nexus/jelly#@2/0cOf0CqWEhzuaHu5oSXMI@v//v6EZAA "Jelly – TIO Nexus") [Answer] # Ruby, 54 53 48 bytes ``` ->n{(1..n).reject{|x|x.to_s(2)=~/10(00)*(1|$)/}} ``` I didn't think the regex for this was going to be quite so basic. **edit 1:** switched to reject to get rid of negation for -1. **edit 2:** switched `match` to `=~` for -5. [Answer] # C# ~~159~~ ~~157~~ 155 bytes Saved 2 x two bytes thanks to TuukkaX. Note: prints out the ints in reverse order. ``` void B(int n){var b=Convert.ToString(n,2);int c=0,i=0;for(;i<b.Length;){if(b[i++]<49)c++;else if(c%2>0)break;}if(c%2<1)Console.WriteLine(n);if(n>1)B(--n);} ``` Explanation: ``` void B(int n) { // convert our int to a binary string var b = Convert.ToString(n, 2); // set our '0' counter 'c' and our indexer 'i' int c = 0, i = 0; // loop over the binary string, without initialisation and afterthought for (; i < b.Length;) { // check for '0' (48 ASCII) and increment i. increment c if true if (b[i++] < 49) c++; // otherwise check if c is odd, and break if it is else if (c%2 > 0) break; } // print the int if c is even if (c%2 < 1) Console.WriteLine(n); // recursively call B again with the next number if (n > 1) B(--n); } ``` [Answer] # Mathematica, 69 bytes ``` Select[Range@#,FreeQ[#~IntegerDigits~2//.{x___,0,0,y___}:>{x,y},0]&]& ``` The same length: ``` Select[Range@#,#~IntegerString~2~StringDelete~"00"~StringFreeQ~"0"&]& ``` [Answer] ## Ruby, 53 Bytes ``` ->n{(1..n).each{|n|p n if n.to_s(2).count(?0).even?}} ``` [Answer] # Jelly, ~~15~~ ~~13~~ 10 bytes *saved two bytes after looking at other answers, another 3 bytes thanks to Dennis* ``` Bœṣ0,0Ȧµ€T ``` # Explanation ``` Bœṣ0,0Ȧµ€T -Helper link: argument K (integer): ex. 24 B -Convert K to a list of its binary digits: 24 -> [1,1,0,0,0] 0,0 -Create a list of two 0's: [0,0] œṣ -Split the binary digits on instances of the sublist: [1,1,0,0,0]-> [[1,1],[0]] Ȧ -Any and All: Check if our list has any falsy values or is empty µ -Take all our previous atoms and wrap them into one monad. € -Map this new monad over a list. Since our input is an integer, this implicitly maps it over the range [1..N] (Like the 'R' atom) T -Get the indices of all truthy values (1's) ``` ]
[Question] [ I like to play [(*The Settlers of*) *Catan*](https://en.wikipedia.org/wiki/Catan) on [Board Game Arena](https://boardgamearena.com) with totally random number tokens. These tokens determine the production rate of the terrain tiles beneath: ![](https://i.stack.imgur.com/VWCy7.jpg) There are 18 number tokens, two each of 3, 4, 5, 6, 8, 9, 10, 11 and one each of 2 and 12. A valid arrangement of these tokens on the board (19 hexes in a side-3 hexagon) has each token placed in exactly one hex, leaving one empty hex (the desert), *and none of the 6 and 8 tokens adjacent*. So a 6 cannot be adjacent to the other 6, an 8 cannot be adjacent to the other 8 and a 6 cannot be adjacent to an 8. ## Task Output a valid random arrangement of the number tokens. Each possible arrangement only needs a nonzero probability of being output. You may output in any reasonable format, which may be 2D (like the valid and invalid outputs below) or 1D (e.g. mapping the hexes to a 19-character string in a fixed and consistent order). In either case it must be specified how the different positions in the output map to the hexagon. You may use any set of 11 different symbols to denote the number tokens or lack thereof. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins. ## Valid outputs These use `A B C` for `10 11 12` respectively and `.` for the empty desert hex. ``` 6 3 8 2 4 5 A 5 9 . 6 9 A B 3 C 8 4 B ``` ``` B 9 A 5 6 C 8 6 4 B 5 3 2 8 9 3 A . 4 ``` ``` B B C 3 3 A A 2 4 6 . 6 4 5 9 9 8 5 8 ``` ## Invalid outputs This one has three 5s and only one 4: ``` 6 A 2 C 5 9 3 8 B 3 6 A . 9 4 5 5 B 8 ``` The two 6s are adjacent here: ``` 5 2 4 3 8 B 4 9 B 3 5 8 A 6 9 C . 6 A ``` A 6 and an 8 are adjacent here: ``` 4 3 A . 8 2 5 4 6 A 8 B 5 C 3 9 B 6 9 ``` [Answer] # JavaScript (ES6), 162 bytes ``` f=(s=` . 2 3 3 4 4 5 5 6 6 8 8 9 9 A A B B C`,a=s.match(e=/\S/g).sort(_=>Math.random()-.5))=>/[68](.|[^]{8,10})[68]/.exec(s)?f(s.replace(e,_=>a.pop())):s ``` [Try it online!](https://tio.run/##FcxNC4JAFIXhvb/iLu8FvfZlWDBGtW7V0iyHcdRCHXEkguq328QDZ/EuzkM@pVXDvR@DzhR6mkqBVuQADAtYAnhuVk4EXgRrJ4bYg42zdzyAg3PMfSkst3JUNWoRXs5hRWzNMOJNJCc51jzIrjAtUsARkUjCdB1nyJ/0mr1jfz770j@ErF9aoaVdiZYH3TdSadS@O5Hcmx6JaGsnZTprGs2NqbB0bfoB "JavaScript (Node.js) – Try It Online") ### Uniform distribution, 163 bytes The ways the grid is shuffled in the above version, some patterns have a higher probability than others -- which is fine as per the challenge rules. But getting a uniform distribution just costs one extra byte. ``` f=(s=` . 2 3 3 4 4 5 5 6 6 8 8 9 9 A A B B C`,a=s.match(e=/\S/g))=>/[68](.|[^]{8,10})[68]/.exec(s)?f(s.replace(e,_=>a.splice(Math.random()*n--,1),n=19)):s ``` [Try it online!](https://tio.run/##FcjLCsIwEIXhfZ9iljOSptZLaYUo6tqVy1o1xPQiNSlNEUF99hr54Idz7vIpneqbbgiNvelxLAU6cQXgMIM5QOCz8JYQLCHxUkgDyLytFwDsvP2VSeH4Qw6qRi2i0zGqiMQ6ypO0QP7Jz8U7ZfH0S/8j4vqlFTralOh4r7tWKo2aXcRacte1jV8HOdS8l@ZmH0gTE4YsJmZEnBGt3KiscbbVvLUVlkg0/gA "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: s = `...`, // s = initial 2D grid, with an invalid pattern a = // a[] = array of s.match(e = /\S/g) // non-space characters .sort(_ => // shuffled Math.random() - .5 // using a random sort() callback ) // ) => // /[68](.|[^]{8,10})[68]/ // test the validity of the grid by detecting .exec(s) // 6's or 8's separated by 1, 8 or 10 characters // (line-break included) ? // if it's not valid: f( // try again with another grid: s.replace( // replace in s: e, // each non-space character with _ => a.pop() // the next character taken from a[] ) // end of replace() ) // end of recursive call : // else: s // success: return s ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 79 bytes ``` . 2 3 ¶ 3 4 4 5 ¶5 6 6 8 8¶ 9 9 A A ¶ B B C /[68](?s:.|.{8,10})[68]/+O?`\S ``` [Try it online!](https://tio.run/##K0otycxLNPz/n0tBQU/BSMFYQeHQNiBpAoSmQKapghkQWihYAEUtgdARCIFMBScgdObSjzaziNWwL7bSq9GrttAxNKjVBInoa/vbJ8QE//8PAA "Retina – Try It Online") Explanation: Based on @Arnauld's JavaScript answer. ``` . 2 3 ¶ 3 4 4 5 ¶5 6 6 8 8¶ 9 9 A A ¶ B B C ``` Insert the tokens in an invalid layout. ``` /[68](?s:.|.{8,10})[68]/+` ``` Repeat while the layout is invalid... ``` O?`\S ``` ... shuffle the tokens. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 39 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ỊTḤ>þ“©©©Çð ‘S+Ɗạþ`Ff“£µ¿‘ 17Ż%⁵⁵;ẊÇ¿ ``` A niladic Link that yields a flat list of the tokens to be placed in row-major order. The mapping from question values to the outputted tokens is: ``` Catan (Question): 2 3 4 5 6 8 9 10 11 12 . Token (code): 9 3 4 5 0 1 2 6 7 8 10 ``` [Try it online!](https://tio.run/##y0rNyan8///h7q6QhzuW2B3e96hhzqGVIHi4/fAGBQWFRw0zgrWPdT3ctfDwvgS3NJD04kNbD@0HinMZmh/drfqocSsQWT/c1XW4/dD@//8B "Jelly – Try It Online") Or see a **[formatted version](https://tio.run/##y0rNyan8///h7q6QhzuW2B3e96hhzqGVIHi4/fAGBQWFRw0zgrWPdT3ctfDwvgS3NJD04kNbD@0HinMZmh/drfqocSsQWT/c1XW4/dD@/4cWPdzdDVRlYWlsYuro5GykZ/aoYS5I29JD6w63HZ4O1Hh08sOd07wfNa2xdlB61Lg34NB@l4e7uh0eNW47tCTyPwA "Jelly – Try It Online")** (translates tokens to Catan values and pretty-prints as a hexagon). (Also [here](https://tio.run/##y0rNyan8///h7q6QhzuW2B3e96hhzqGVIHi4/fAGBQWFRw0zgrWPdT3ctfDwvgS3NJD04kNbD@0HinMZmh/drfqocSsQWT/c1XW4/dD@/4cWPdzdDVRloQcDZo8a5oK0LT207nDb4elAjUcnP9w5zftR0xprB6VHjXsDDu13ebir2@FR47ZDSyL/AwA) is version that only prints the sixes and eights.) ### How? ``` ỊTḤ>þ“©©©Çð ‘S+Ɗạþ`Ff“£µ¿‘ - Helper Link, is invalid?: list of tokens Ị - insignificant? (abs(x)<=1 - i.e. is Catan 6 or 8?) (vectorises) T - truthy, 1-indexed indices Ḥ - double (vectorises) Ɗ - last three links as a monad f(X=that): “©©©Çð ‘ - code-page indices = [6,6,6,14,24,32,32,32] þ - (X) table with (that) using: > - greater than? S - (column-wise) sum + - add (X) (vectorises) ` - use (that) as both arguments of: þ - table using: ạ - absolute difference F - flatten “£µ¿‘ - code-page indices = [2,9,11] f - filter keep -> nonempty list (truthy) if invalid empty list (falsey) if valid 17Ż%⁵⁵;ẊÇ¿ - Link, get random Catan Distribution: no arguments 17 - seventeen Ż - zero range -> [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17] ⁵ - ten % - modulo -> [0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7] ⁵ - ten ; - concatenate -> [10,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7] ¿ - while... Ç - ...condition: call the Helper Link (above) Ẋ - ...action: shuffle ``` [Answer] # Excel VBA, ~~408~~ ~~361~~ 352 bytes Saved 9 bytes thanks to [Taylor Raine](https://codegolf.stackexchange.com/questions/255009/totally-random-catan-number-distributions/255067?noredirect=1#comment572655_255067) **Golfed code:** (Note: VBA will autoformat this code by adding spaces in many places and a few other niceties.) ``` Sub z Set g=[C4:E6,F2:G4,D3:E3,E2,F5] x: Set c=New Collection c.Add 2 c.Add 12 For i=1To 2 For j=3To 11 c.Add j Next j,i c.Remove 7 For Each s In g k=CInt(1+Int(Rnd*c.Count)) s.Value=c(k) c.Remove k Next For Each s In g u=0 For Each t In Union(s.Offset(-1,0).Resize(2,2),s.Offset(0,-1).Resize(2,2)) If t=6Or t=8Then u=u+1 Next If u>2GoTo x Next End Sub ``` **Formatted and commented code:** ``` Sub z() ' Define our game board Set g = [C4:E6,F2:G4,D3:E3,E2,F5] ' Setup a label so we can loop back here and start over as needed ' I know this uses GoTo which is [bad] but it's the shortest way to loop x: ' Create a list of all the numbers we want to populate into the grid ' We need to recreate this on each loop because it'll be emptied later in this process Set c = New Collection c.Add 2 c.Add 12 For i = 1 To 2 'Add all the numbers 3-11 twice For j = 3 To 11 c.Add j Next Next c.Remove 7 ' As it happens, the 7th term will be one of the "7" values and we only need one of those. ' Populate the grid with a random entry from that list and then remove it from the list. For Each s In g k = CInt(1 + Int(Rnd * c.Count)) s.Value = c(k) c.Remove k Next ' Look for more than one instance of 6 or 8 in each set of adjacent hexes For Each s In g u = 0 ' Check a rotated hexagonal-ish shape centered on the current cell For Each t In Union(s.Offset(-1, 0).Resize(2, 2), s.Offset(0, -1).Resize(2, 2)) ' This is less bytes than something like "If Abs(s-7)=1Then" because this has more spaces than can be removed If t = 6 Or t = 8 Then u = u + 1 Next If u > 2 Then GoTo x ' Loop if you found more than two (since we check the center cell twice) Next End Sub ``` **Output format:** Output is in a spaced out grid spanning the range `C2:G6` in the active sheet. The values are 2-12 with 7 being the desert. It is a rotated and compressed version of the hexagonal grid. If you translated the first example in the question into Excel, you may want it to look like image below. I've added colors for clarity later and outlined all the cells that would be considered adjacent to the desert in the middle of the board. [![Spaced Out Grid](https://i.stack.imgur.com/a0idk.png)](https://i.stack.imgur.com/a0idk.png) However, that spaced out thing is not very byte-friendly. We're going to rotate it 45° and compress it. Here's the same board with the same colors and the same cells outlined in a border showing they're adjacent to the desert: [![Rotated and Compressed Grid](https://i.stack.imgur.com/wpMqF.png)](https://i.stack.imgur.com/wpMqF.png) To better show how this looks like the original board, I'm going to rotate the text 45°. Tilt your head to the left and you should see a perfectly normal Catan board. [![Rotated Text](https://i.stack.imgur.com/e2EJg.png)](https://i.stack.imgur.com/e2EJg.png) **Example board generation:** With the colors and borders back in place, here's a video showing the generation of some random boards. The top left board is where the code is outputting data. The bottom left board is full of formulas show it shows the same data as the top left but in the more expanded layout. The diamond shape to the right is a snapshot of the same results (again linked by formulas) but with the text rotated 45° CCW and then the whole snapshot rotated 45° CW so it looks like a normal board. The places where it pauses is where a good board was found, I waited, then ran the script again. [![Board Generation GIF](https://i.stack.imgur.com/X1ftN.gif)](https://i.stack.imgur.com/X1ftN.gif) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 73 bytes ``` W¬KA«⎚P→↙×ψ³‖C‖O↓≔⟦⟧υW⁻…³¦²²υ⊞υ‽κ¤⭆υ⁺§…α¹¹κ F⁵F⁹«J⁻λ²κ¿‹IKK¿‹I⌈⊞OKM⊟KD³→⎚ ``` [Try it online!](https://tio.run/##VVDLasMwEDw7XyF8WoF7SEIPTU/BoZASNybNrfQgnLUtIktGkvOg5NvdlRpoKxDSPmZ2dqpW2MoINY7nVipk8GY8lIjHpVLAOWdfkyRXKCzw50lSDMrL3krtYbGTTesztliZs95gTd@97NDBNWNzHpp3WCusfG76K/yJtye0SvQQgSG/dE42Gj4@MzaE@C6kkHpwsBO6QZhnbDbjoc5ZObgWhoxR5WA6OMZZL5LkvntS1hTETeVSEXrp1/qAF8ivlcK8NT2IjE2nxHSkm7KUR3RtLINHzuL7FHdOXoeu35u7CkXzI4iaE1kz2KBzkK5TmkNeRaP@pwtxkd3QQVC77dEKb2z0tTDGIhBZSWpCYiUtuSKNDlv@uMrjYb@@3ya3cRwfTuob "Charcoal – Try It Online") Link is to verbose version of code. Uses `A`, `B` and `C` to represent `2`, `12` and the desert, `J` and `K` to represent `6` and `8` and intervening letters for the remaining tokens. Explanation: ``` W¬KA« ``` Repeat while the canvas is empty. ``` ⎚P→↙×ψ³‖C‖O↓ ``` Outline a hexagon. (The extra `Clear();` at the beginning ensures that the cursor is at the origin, as it is not there at the end of the loop.) ``` ≔⟦⟧υW⁻…³¦²²υ⊞υ‽κ¤⭆υ⁺§…α¹¹κ ``` Shuffle the tokens and fill in the hexagon. ``` F⁵F⁹«J⁻λ²κ ``` Loop over the canvas. ``` ¿‹IKK¿‹I⌈⊞OKM⊟KD³→⎚ ``` If an adjacent pair of `J` and/or `K` are found then clear the canvas. [Answer] # [Python](https://www.python.org), 184 bytes ``` from random import* f=lambda s=".2C"+2*"345#%9AB":any((x:=(*s[:3],"_",*s[3:-3],"_",*s[-3:],*"___"))[i]<'.'>min(x[i+4:i+6]+~-~-i%5*(x[i+1],))for i in range(20))and f(sample(s,k=19))or s ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lVFRTsMwDP3vKaKganabTmu7IRZRJOAYXVUVtYGIJY2SIm0_uwg_-4EzcBVuQ7apYsAXliXbz7b8bL--m-3w1Ov9_u1lEMnV54ewvSK20a03UpneDlEginWjHtqGuIJOs3saZxHN54uLcHl7R3mjtwAbXkDkSp5XjNaUeTfnyXeQ5LxiEa3rmiKWsrqeTCc3SmrYlDKecxlfVvEu2SUyXERHLK0YougtkUTqA5_HDrIZoidGBLhGmXUHjj0X6RLRl7mRf9sJYsAhD4gXY6UeAFbH4CCUkNCddKVpfIaP8J_MWeIfXT_mYOiP4xcKgl8rpTPkBgQgnviPf_gC) `#` and `$` represent tiles 6 and 8 respectively; the rest of the encoding are the same as in the example. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~56~~ 54 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 12L7Kû¨¨[.rD18Ýü2ZÝ3LÌû£ü2εé`δ‚εND>‚è}}˜2ô«èJ€ê68æδÊß# ``` Uses `1` for the empty desert hex. The other numbers are the same. Outputs as a flat list. [Try it online](https://tio.run/##AV4Aof9vc2FiaWX//zEyTDdLw7vCqMKoWy5yRDE4w53DvDJaw50zTMOMw7vCo8O8Ms61w6lgzrTigJrOtU5EPuKAmsOofX3LnDLDtMKrw6hK4oKsw6o2OMOmzrTDisOfI///) or [try it with pretty-print](https://tio.run/##yy9OTMpM/f/f0MjH3Pvw7kMrDq2I1ityMbQ4PPfwHqOow3ONfQ73AMUXA3nnth5emXBuy6OGWee2@rnYAenDK2prT88xOrzl0OrDK7weNa05vMrM4vCyc1sOdx2er/y/1ujw3BBtw0Orju4LUtc7tPpRw0KYcYd26yX/BwA). **Explanation:** ``` 12L7Kû¨¨ # Get a list of the numbers: 12L # Push a list in the range [1,12] 7K # Remove the 7 û # Palindromize it ¨¨ # Remove the trailing [2,1] [ # Start an infinite loop: .r # Randomly shuffle the list D # Duplicate this list 18Ýü2ZÝ3LÌû£ü2εé`δ‚εND>‚è}}˜2ô«èJ€ê68æδÊß# # Pop the copy, and check whether it's valid (see below) # # If it is valid: stop the infinite loop # (after which the valid shuffled list is output implicitly as result) ``` ``` 18Ý # Push a list in the range [0,18] ü2 # Get its overlapping pairs: [[0,1],[1,2],...,[16,17],[17,18]] Z # Push its flattened maximum (18), without popping the list Ý # Push a list in the range [0,18] again 3L # Push list [1,2,3] Ì # Increase each by 2 to [3,4,5] û # Palindromize it to [3,4,5,4,3] £ # Split the [0,18] list into parts of those sizes ü2 # Get overlapping pairs of these lists ε # Map over each pair of lists: é # Sort the lists by length ` # Pop and push both lists separated to the stack δ # Apply double-vectorized: ‚ # Pair values together ε # Inner map over these lists of pairs: N ‚ # Pair the current index D> # With the index+1 è # Use this [index,index+1] to get the pairs at those indices }} # Close the nested maps ˜2ô # Flatten it two levels down to a single list of pairs: ˜ # Flatten the list of lists of pairs 2ô # Split the flattened list back into parts of size 2 « # Merge it to the list of overlapping pairs of [0,18] è # Get the values at those indices from the shuffled list J # Join each inner pair together to a string €ê # Sorted-uniquify the digits of each inner string 68 # Push 68 æ # Pop and push its powerset: ["",6,8,68] δ # Apply double-vectorized: Ê # Not equals check ß # Get the flattened minimum to verify none are falsey ``` The index-pairs to check each adjacent hex, generated by `18Ýü2ZÝ3LÌû£ü2εé`δ‚εND>‚è}}˜2ô«`, are: ``` [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11],[11,12],[12,13],[13,14],[14,15],[15,16],[16,17],[17,18],[0,3],[0,4],[1,4],[1,5],[2,5],[2,6],[3,7],[3,8],[4,8],[4,9],[5,9],[5,10],[6,10],[6,11],[7,12],[8,12],[8,13],[9,13],[9,14],[10,14],[10,15],[11,15],[12,16],[13,16],[13,17],[14,17],[14,18],[15,18]] 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ``` [Try it online.](https://tio.run/##yy9OTMpM/f/f0OLw3MN7jKIOzzX2OdxzePehxUDeua2HVyac2/KoYda5rX4udkD68Ira2tNzjA5vObT6/38A) [Answer] # Python 3, 391 bytes: ``` from random import* R=range P=lambda i:' '*int((9-(i*2-1))/2) def b(): while 1: t=[*'2C.'+'345689AB'*2];shuffle(t) B,f=[P(i)+' '.join(t.pop(0)for _ in R(i))+P(i)for i in[3,4,5,4,3]],1 for x in R(5): for y in R(9): for X,Y in[(1,1),(-1,1),(1,-1),(-1,-1),(0,2),(-2,0)]: if 0<=(j:=x+X)<5 and 0<=(k:=y+Y)<9 and {'6','8'}&{B[x][y],B[j][k]}=={B[x][y],B[j][k]}:f=0 if f:yield B ``` [Try it online!](https://tio.run/##ZZDPboMwDMbP4yl8WhIIHX9KVVhzGHuBaqdWUTS1gqxpKSCWaaCqz84S2E47RI5//mzZXzvoU1PH67YbR9k1V@gOdWGCurZNp13njRnwUTpbVh2ux@IAKkOAXFVrjFMfKzfyQ0KeIuIUpYQjJpkD3ydVlRCaH2jGXRS9LpCH4mWyWqcvOXIj8fx5@pKyKrEmRpRTyfgWK@KZ0Ytzo2qsF23T4oDIpoN3UDW8mTLxrMgiZRCP6ZIm5sVC0NCMsYV@1iZ2jZkMM0lnMqEd3dt@HNKQUOzPIaT@bzbFgEY2i2hAxNwJSkKwYficsd7bkU0CxqmJXDI2eHuySSdyQytE0RrdH2857wUfBM35WfCLuDP2D2WSBc40W2aDKqsC8vHvQqjLXmPjqdn9oe2s54qMPw) [Answer] # JavaScript (ES6), 157 bytes The output format for this version was inspired by [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/255022/58563). Returns a flat array with the following mapping: ``` -1 0 1 2 3 4 5 6 7 8 9 . 6 8 9 3 4 5 A B C 2 ``` ``` f=_=>(a=[...s="8889999_____0000111"].map((_,i)=>~-i%10).sort(_=>Math.random()-.5)).some((v,i)=>227259>>i&(g=k=>3>>a[i+k]&3>>v&1)(1)|g(q=s[i]-5)|g(q+1))?f():a ``` [Try it online!](https://tio.run/##TZDLboJAGIX3PMUJSc0/QUYHi8UmM43ae2tvLinRCSJSL1AgrJq@Oh1d9VudnMvmfOlGV3GZFbV7yFdJ267lQirSMuScV9IOgmBkWBzpG4QQdsT3uiBadDMm1a@bnYk@41Ve1mSmM11veKkPq3xPzOU@O0b7hKg51T3vwvNHSmUdSuVWqoFSOsycbdQxqukIRoL9pPQtqzCLXP@kHcHY1ZrYpW7j/FDlu4Tv8pQ0JIzLrP/m0gLGmGAKWLjGDW5xB@seD3jEE54tzPCCV7yZFO/4wHzJy6TY6Tih3ue8l3YRQyrYfBiMBuf@eDL17FCHMY83upyah8Y1MbgY@hEciIix9g8 "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 132 bytes ``` f=->{a=([*0..10]*2)[i=0,q=19].shuffle "&&X,,,^1,,,]+&&WKK".bytes{|b|q&&=a[i]/2+[a[i+=1]|b&64,a[b/5%5+i],a[b%5+i]].min/2>0} q ?a:f[]} ``` [Try it online!](https://tio.run/##ZYzhCsIgFIX/7ylEmNQ0p6MFBa4H2AMUiIHCJKGitQ0a257drKCCDod7vsvlnltneu@tWBSDFjOZMEo5U0k2l04wUgu@VrQ5dtaeqggitCeEHHgYCiO0K0tITd9WzTCasUZIaOlUmmEZEguuRoNWS6KlSfM4x0498QWKnt0lzQo2RTXY6o2VavLXrm0ABCC@vx196Ln88N/t@wPjUAWC/AM "Ruby – Try It Online") Outputs a flat array. Uses the same tokenization as Jonathan Allen. (the footer of the TIO link converts `10` to hexadecimal `A` for better presentation.) ``` Catan (Question): 2 3 4 5 6 8 9 10 11 12 . Token (code): 9 3 4 5 0 1 2 6 7 8 10 ``` **Explanation** We generate a flat array of all 11 tokens, duplicate it to 22 elements, truncate to 19 elements to discard the extra `8 9 10`, then shuffle. We check if the arrangement is valid, and if so, return it. Otherwise we call recursively to try again. For each element (except the last one) we check if any of the (up to 3) adjacent elements following it are incompatible. The elements to be checked (to the right, below, and diagonally) are shown as an offset in the table below. ``` 134 134 .34 145 145 145 .45 1.5 145 145 145 .4. 1.4 134 134 .3. 1.. 1.. ... ``` This was encoded in a magic string as follows. For the below and diagonal offsets, we subtract 1 from each and encode as a two-digit base 5 number. Thus `.45` becomes `34` becomes 3x5 + 4 = decimal 19. If a below or diagonal check is NOT required, we pick a number that gives a duplicate check in one of the other directions. We then add a multiple of 25 to it to bring it into the printable ASCII range. If checking of an element to the right is NOT required, we add a further multiple of 25 to increase the value above 64. Decoding should be apparent from the code, but I will add commented code later when I have time. ]
[Question] [ Note to those without experience in music: Through making an attempt to solve this problem, you may find that music and computer programming are similar in the ways that they implement rules and syntax. With some help from Wikipedia, you can likely solve this problem with no prior knowledge of music theory. Write a program that can take a string representing **any** valid [key signature](https://en.wikipedia.org/wiki/Key_signature) (ex: C, D#, Ab) and return the appropriate chord progression for a [12 bar blues](https://en.wikipedia.org/wiki/Twelve-bar_blues) in that key. Many aspiring jazz musicians begin their musical journey by learning the 12 bar blues. It is a popular chord progression that consists of the I, IV, and V chords of a key. There are a few variations of the 12 bar blues, we will use the following: ``` I I I I IV IV I I V IV I I ``` Where each numeral represents the chords of the given key. ``` Examples ------------------------ Input: C Output: C C C C F F C C G F C C ------------------------ Input: Eb Output: Eb Eb Eb Eb Ab Ab Eb Eb Bb Ab Eb Eb ------------------------ Input: F# Output: F# F# F# F# B B F# F# C# B F# F# ``` Note: In music, you can write some [notes two different ways](https://4.bp.blogspot.com/-O8RpvqrcHEk/WtIPBdoT4qI/AAAAAAAAAEk/wHpwIqCbnl0TUz43qqLXIKdRK02iefMDgCEwYBhgL/s1600/What%2Bis%2BPiano%2BNotes%2B03.png). (ex: F# is equivalent to Gb). Consequently, a given input may have multiple valid answers. An answer is correct as long as it outputs chords that are correct, regardless of how they are represented. ``` Example - F# Alternative solution Input: F# Output: Gb Gb Gb Gb Cb Cb Gb Gb Db Cb Gb Gb ``` Answers should be returned in one of the following formats: ``` Examples - Valid Formatting (Given input C) Valid output 1 (multi-line string): C C C C F F C C G F C C Valid output 2 (single line string): C C C C F F C C G F C C Valid output 3 (1d list/array): ['C', 'C', 'C', 'C', 'F', 'F', 'C', 'C', 'G', 'F', 'C', 'C'] Valid Output 4 (2d list/array): [['C', 'C', 'C', 'C'], ['F', 'F', 'C', 'C'], ['G', 'F', 'C', 'C']] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): The solution with the fewest bytes wins. # [Python 3](https://docs.python.org/3/) - Sample Code, not Golfed ``` def twelve_bar_blues(k_input): chords = ['Ab', 'A', 'Bb', 'B', 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G']*2 if k_input not in chords and k_input[1] == '#': k_index = chords.index(k_input[0]) + 1 k = chords[k_index] else: k = k_input I_index = chords.index(k) I = chords[I_index] IV_index = I_index + 5 IV = chords[IV_index] V_index = I_index + 7 V = chords[V_index] return f'{I} {I} {I} {I} {IV} {IV} {I} {I} {V} {IV} {I} {I}' ``` [Try it online!](https://tio.run/##dZLfaoMwFMavzVMc8CJNO8a6MQqCF7Z2xRfwxonUGalMosS4P4w9u0uyRNvVXeQj55zf@XJI0n6KU8MehqGgJYh3Wr/RLD/yLK972i1es4q1vSAeQs7LqeFFBz4kOMjxDeBAyVZvt0p2SkIdh0r2ertX8qTkoOMDTpf30q4qwbgDawRUDMwBR1bYSrJOwfcBu9hDjqOSBf2QE/yStzq0MyZ3KYEVrBU4IonpSZFD6456pmha5BTRP55EliaXyLrIbDx22N4VPKr8GR5P/By@kemJPoM5FT1nUOKv6BsuVzyKWX8SeGh5xcQC7zx5y1cPKR@HyMt/ZpggA4buPBm6V2iQz6PyH1h0@AE "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3.8/), 113 110 bytes ``` l='C Db D Eb E F Gb G Ab A Bb B'.split() def f(a):c,*a=l.index(a),a,a;I=[l[c-7]];return a*2+I*2+a+[l[c-5]]+I+a ``` Doesn't accept `#` ones. Uses flats only. Thanks to @ovs and @l4m2 for -3 bytes. [Try it online!](https://tio.run/##Vcm7CsIwFIDhvU9xtiRN7aCI0tIhvVj6DCXDSS8YCDHECPr0sToIDv/w8btXuN7s4ex8jKYiDbQKWugUdHCBXkEPQoGAWkFN8rszOlCWzMsKK0VWTFmKlcm1nZfn5gwzLIdqNOO0O0lZ@iU8vAVM93zYQv49Ryn5wDE6r22gKyWdIowlPzZ/Ep8Z3w) # [Python 3](https://docs.python.org/3.8/), 129 bytes ``` l='C Db D Eb E F Gb G Ab A Bb B'.split() def f(a):b="#"in a;c,*a=l.index(a[:~b+3])+b,a,a;I=[l[c-7]];return a*2+I*2+a+[l[c-5]]+I+a ``` This version accepts `#` keys. Additional 19 bytes :( [Try it online!](https://tio.run/##Vcu9CoMwFIbh3as41MHEWIdKaVEy@I/XIBnO8YcKwQZroV1666l0KDh8w8PLZ97r7T5HV7NYq6WXQ0FQQElQQgU1QQ0pQQoZQeaFD6OnlXGnH0YYGfKY5ME9TDNg0gU@Sh1Ocz@8GLbxh0SkuKAAA0wa2eq2O16USpZhfS7bwT@JZhuKXzkrJRqB1izTvLKReSV5nDt/5jul@1i5G@0X) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 34 bytes ``` «⟑,HǎẆṀ,‹¹β»Ẇ→| e׫⌈:?ḟ»Ǎ‹ǒr$»fḢ+İ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCq+KfkSxIx47huobhuYAs4oC5wrnOssK74bqG4oaSfCBlw5fCq+KMiDo/4bifwrvHjeKAuceSciTCu2bhuKIrxLAiLCIiLCJiYiJd) Takes input as notes in lowercase (`db` not `Db` or `C#`, this doesn't allow sharps) Thanks to Unrelated String for saving a byte on the numbers ocmpression ``` «...« # Compressed string `c db d eb e f gb g ab a bb b` ⌈: # Split on spaces and make a copy ?ḟ # Find the index of the input in those »...»fḢ # The list [0,0,0,0,5,5,0,0,7,5,0,0] # Note: This is surprisingly difficult to compress. The leading and trailing zeroes resist base compression, the high numbers make base compression inefficient, but attempting to index into [0,5,7] is worse. +İ # Add those numbers to the input's number and modularly index into the notes. ``` [Answer] # Excel, 75 bytes (44 formula, 31 data) ``` =INDEX(G:G,MOD(B6:E8+MATCH(A1,G:G,)-1,12)+1) (44 bytes) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnhT8RAuw5b525azp?e=ekANr0) `B6:E8` are blank for the cells corresponding to the I chord; are 5 for the IV chord; and 7 for the V chord. (4 bytes) `G:G` contains the list of keys both sharp and flat. (27 bytes) [Answer] # x86-16 machine code, ~~77~~ ~~71~~ 68 bytes ``` 00000000: adbb fc00 d780 fc23 7c06 7502 2c0a 040b .......#|.u.,... 00000010: 92be 3701 33c9 acd4 108a cce3 1902 c2d4 ..7.3........... 00000020: 0cbb 4401 bd48 204b 4d38 077f fa95 7402 ..D..H KM8....t. 00000030: b423 f3ab ebe0 c340 2520 1715 2000 0203 .#.....@% .. ... 00000040: 0507 080a .... ``` Listing: ``` AD LODSW ; AH = note accidental, AL = note name BB 00FD MOV BX, OFFSET SLT-'A' ; BX = semitone table (ASCII offset index) D7 XLAT ; convert to semitones 80 FC 23 CMP AH, '#' ; is it sharp? 7C 06 JL START_SONG ; if has no accidental, let's jam 75 02 JNZ IS_FLAT ; if not, it's a flat IS_SHARP: 2C 0A SUB AL, 10 ; "sharp" the note up one semitone IS_FLAT: 04 0B ADD AL, 11 ; "flat" the note up 11 semitones START_SONG: 92 XCHG AX, DX ; DL = root note (key) relative to A BE 0138 MOV SI, OFFSET SNG ; SI = song pattern data 33 C9 XOR CX, CX ; clear CX for counter SONG_LOOP: AC LODSB ; AL = length and note packed nibbles D4 10 AAM 16 ; AH = # of repeats, AL = note 8A CC MOV CL, AH ; CX = bar repeat counter E3 1A JCXZ SONG_DONE ; end, if the song is over 02 C2 ADD AL, DL ; transpose note to correct key D4 0C AAM 12 ; AL = output note (mod 12 to fix wraparound) BB 0144 MOV BX, OFFSET SLT+7 ; BX = end of semitone table BD 2048 MOV BP, 02048H ; H=' ', L='H' (G+1 since loop pre-decrements) NOTE_LOOP: 4B DEC BX ; loop backwards through semitone table 4D DEC BP ; walk down notes starting from G 38 07 CMP BYTE PTR[BX], AL ; compare note to semitone 7F F9 JG NOTE_LOOP ; if note is higher than target, keep looping 93 XCHG AX, BP ; move output to AX 74 02 JZ WRITE_NOTE ; if note is exactly target, it's natural B4 23 MOV AH, '#' ; otherwise, it's sharp (ouch!) WRITE_NOTE: F3 AB REPZ STOSW ; write to output string (repeatedly) EB DF JMP SONG_LOOP ; jump to next song pattern SONG_DONE: C3 RET ; return to caller ; packed song data: ; high nibble = repeats, low nibble = note interval SNG DB 40H, 25H, 20H, 17H, 15H, 20H ; semitone lookup table ; A B C D E F G SLT DB 0, 2, 3, 5, 7, 8, 10 ``` Callable function. Input string at `[SI]`, output to `[DI]`. Accepts sharps *or* flats in input. **Explanation:** The first character of input string pointer is converted to a semitone scale relative to A, based on the table `[0,2,3,5,7,8,10]`. The pointer of this table is actually offset by `0x41` (ASCII `'A'`) so that the index is the ASCII value, eliminating the need to ASCII convert to 0-based index in the program. The second character's ASCII value is checked and if it's less than a `'#'` (ASCII `0x23`) (white space, CR/LF, null, etc), the note is natural. If it is a `'#'`, 10 is subtracted from the value followed by adding 11, for a net +1 (this is a machine code optimization to eliminate the need for a branch/jump). If it's a flat, the subtraction of 10 is skipped and only 11 is added, for a (relative) net -1. The remaining number is the input note's number of semitones relative to A -- the key, effectively. Next, the "song" is loaded from a packed array of bytes `[0x40,0x25,0x20,0x17,0x15,0x20]` where the first nibble is the number of times the bar repeats and the second is the relative number of semitones up from the tonic. That number is added with the key from earlier and mod 12 to handle wraparound, leaving the root note of the chord transposed to the correct key. Last, the note is compared to the semitone table again. Searching from the end, if it matches, the note is natural. If it's lower, the note is one note name lower and sharped. Output is then written as an array of two byte strings to the buffer passed in `[DI]`. [![enter image description here](https://i.stack.imgur.com/C50mc.png)](https://i.stack.imgur.com/C50mc.png) [![enter image description here](https://i.stack.imgur.com/EuhTz.png)](https://i.stack.imgur.com/EuhTz.png) Jam on! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~35~~ 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` A7£ÀÀSD¤«s.馄fbKDIk•íƒò=Z•¦S+è ``` Port of [*@emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/242324/52210). It also only uses lowercase inputs without sharps; and outputs (in lowercase) as single list. [Try it online](https://tio.run/##AT0Awv9vc2FiaWX//0E3wqPDgMOAU0TCpMKrcy7OucKm4oCeZmJLRElr4oCiw63GksOyPVrigKLCplMrw6j//2Ji) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/X9H80OLDzccbgh2ObTk0OpivXM7Dy171DAvLcnbpTL7UcOiw2uPTTq8yTYKyDy0LFj78Ir/Ov@jlZKVdJRSk4BEepJSLAA). **Explanation:** ``` A # Push the lowercase alphabet 7£ # Only leave the first 7 letters: "abcdefg" ÀÀ # Rotate it right twice: "cdefgab" S # Convert it to a list of characters D # Duplicate it ¤ # Push the last character (without popping): "b" « # Append it to each in the copy: # ["cb","db","eb","fb","gb","ab","bb"] s.ι # Swap, and interleave the lists: # ["cb","c","db","d","eb","e","fb","f","gb","g","ab","a","bb","b"] ¦ # Remove the first ("cb") „fbK # As well as the "fb" # ["c","db","d","eb","e","f","gb","g","ab","a","bb","b"] D # Duplicate it Ik # Get the index of the input in this list •íƒò=Z• # Push compressed integer 1000055007500 ¦ # Remove the leading 1: "000055007500" S # Convert it to a list of digits + # Add the earlier index to each è # Use that to 0-based modular index into the list of notes # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•íƒò=Z•` is `1000055007500`. [Answer] # [Subleq](https://esolangs.org/wiki/Subleq), 112 bytes ``` 0:-1 6 -1 : Load first Character to [6] 3:5 6 -28 : [6] = [6] + 28 6:0 27 9 : Load address in 6 to 27 9:-1 32 21 : Load second Character to [32]: if nil goto 21: 12:55 32 18 : if [32] < 66 goto 18: 15:17 27 4 : [27] = [27] - 4: move 2 notes down 18:20 27 -2 : [27] = [27] + 2: move one note up 21:27 29 24 : [29] = [29] - [27] : [29] = -[27] 24:29 30 -1 : [30] = [30] - [29] : [30] = 1 - [29] 27:0 -1 0 : print base chord 30:1 -1 0 : print flat or space 33:0 39 -1 : [39] = [39] + 1 36:0 42 -1 : [42] = [42] + 1 39:99 27 -1 : [27] = [27] - [99*] : if <=0 exit 42:99 30 -1 : [30] = [30] - [99*] 45:54 -1 -1 : print space 48:18 18 27 : [18] = 0 goto 27: Data 51:65 98 65 32 : Ab & A 55:66 98 66 32 : Bb & B 59:67 32 : C 61:68 98 68 32 : Db & D 65:69 98 69 32 : Eb & E 69:70 32 : F 71:71 98 71 32 : Gb & G 75:65 98 65 32 : Ab & A 79:66 98 66 32 : Bb & B 83:67 32 : C 87:68 98 68 32 : Db & D 91:69 98 69 32 : Eb & E 95:-53 -57 -59 -63 -67 -69 -73 : Negative Starting Key addresses 100:0 0 0 -10 0 10 0 -14 4 10 0 127 : Chord changes ``` [Link to Subleq emulator spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnhbLS6wxzBP2OXh1?e=BnV4Vh) > > Got just one instruction; that's all I can use. > > > Don't have no functions; I'm very confused. > > > Coding reduction; I've got the Subleq Blues. > > > [Answer] # Excel, ~~125~~ 123 bytes (doesn't use helper data) Saved 2 bytes thanks to Axuary ``` =LET(n,"G GbF E EbD DbC B BbA Ab",f,FIND(LEFT(A1),n),MID(n&n,IFERROR(MAX(f,FIND(A1,n)),f-2)+{0,0,0,0;7,7,0,0;5,7,0,0}*2,2)) ``` * `n,"G GbF E EbD DbC B BbA Ab"` stores the string of notes in reverse order. * `f,FIND(LEFT(A1),n)` finds the first character of the note. This is why the string is in reverse order so we find "G " instead of "Gb". * `IFERROR(MAX(f,FIND(A1,n)),f-2)` adjusts for sharps and flats. * `{0,0,0,0;7,7,0,0;5,7,0,0}*2` array to add to the `FIND()` position from earlier. * `MID(n&n,IFERROR(~)+{~},2)` pulls out all the character pairs based on `FIND()` and offset by the array of fixed values. [![Screenshot](https://i.stack.imgur.com/Yu11R.png)](https://i.stack.imgur.com/Yu11R.png) Screenshot shows the 125 bytes version of the formula. [Answer] # [Prelude](https://esolangs.org/wiki/Prelude), ~~468~~ 324 bytes ``` v4 7- + v vv3v8- 1-(1-(1-(1-(1-(1-(1-))#7-0))))v++^ vv^^vvvv (! ? 6 9+ 4+ 4+ 4+ 4+ 4+ 0 # #v# ( v(0 )0) v ? vv03+ 4+ # ^ #v #0 # #^ #0 v#v^^vv^^^^(!0)#9!) ^ 8(1-)## 7^+# ( ^(0 )0)^^ # ^ ``` [Try it online](https://tio.run/##fY8xDsMwCEV3n@JHLEaWJapEdTJl6zGYmq1DValc3yXJ4ihtnxgAwefzfC2P932pFbABLSXjTPKxALPexoxLjqdgppKFHUtJvyiYqZqD2IU5XNfWlDAcQwBqdsiaKsKigIXdyexy0m8rfyCoS4Bky0n3zGhzok7shGnqOPjguD5BhKKJfktG6G5CtblS640@ "Prelude – Try It Online") or [run the test suite](https://tio.run/##fY/daoNAEIXvfYojQ8FFNJsm1OSmIf8PUboYU0ukQRe7bpGYZ7eThILBth8De2aYOTNbVkndtvF@ZxBmua5MaLICzyhTWxwr1vnwMdRlGjsPXy9zLLDECmtssMU8wSLBMsEqwTrBljVhQ69hutsfcELzkdYN2PITsS6z3LyDTlw7N7o2hyLHoNBmwN7H6i39eUNd93fj3LaAHaNLFKCPz20OrB3ZSYBh4PVCCIoCKRjr@@oXB2uVsgw815k5T5fS1Mf4PiRAnRmyncyD9SSEFHzJjO3k6DryDwTFFiB51aRuytL1EsV4rhQ0dYXDjZPLJ4gQKZ/@tvSgbkco1dnyDQ "Ruby – Try It Online"). Input is an uppercase letter possibly followed by an accidental (`#` or `b`). Output is enharmonically correct. Inputs of `Fb`, `B#`, or other non-standard keys that require double sharps or double flats are not supported. ### Explanation Prelude is a 2D language inspired by music. Each line, known as a *voice*, has its own stack. Instructions in the same column are executed simultaneously, representing notes sounding simultaneously in different voices. Loops, demarcated by `()` pairs, run in parallel across all voices. There are no conditionals but testing for equality to zero is possible with loops. Each chord name consists of two characters: a letter name (e.g. `C`) and an accidental (e.g. `#`). (Natural notes have an 'empty' accidental.) Let the codepoints of these characters be \$c\_j\$ and \$a\_j\$, respectively, with \$j = \text{I, IV, or V}\$. In Prelude, our goal in this challenge is to find all the \$c\_j\$ and \$a\_j\$. Chord I is easy: the `?` instructions in Voices 3 and 5 read \$c\_\text{I}\$ and \$a\_\text{I}\$ directly from STDIN. (If there is no accidental, \$a\_\text{I}\$ is read as \$0\$ (EOF), which will prove to be convenient later.) Three tasks remain: 1. Find \$c\_\text{IV}\$ and \$c\_\text{V}\$. 2. Find \$a\_\text{IV}\$ and \$a\_\text{V}\$. 3. Print the 12 bar blues progression. #### 1. Finding \$c\_\text{IV}\$ and \$c\_\text{V}\$ Focus first on the \$c\_\text{IV}\$ calculation, which takes place in Voice 2. Observe that $$c\_\text{IV} = \begin{cases}c\_\text{I}+3\text{ if }c\_\text{I}<69,\\ c\_\text{I}-4\text{ if }c\_\text{I}\ge69. \end{cases}$$ Our strategy, therefore, is to get \$+3\$ or \$-4\$ on the stack as appropriate, then add this to \$c\_\text{I}\$. Because there is no direct way to test whether \$c\_\text{I}<69\$ in Prelude, we have to resort to a series of nested loops that function like conditional branches. The code between dashed lines below is only executed if \$c\_\text{I}\ge69\$. ``` 3 Push 3. Stack: [3] v Push cI from voice below. Stack: [3, cI] 8- (In loop) 8 times, subtract 8. Stack: [3, cI-64] 1-( If cI-65 = 0, skip ahead to the matching ). Stack: [3, cI-65] -+ 1-( If cI-66 = 0, skip ahead to the matching ). Stack: [3, cI-66] | . . | . . etc. | . . | ------------------------------------------------------------- | 1-)) End of loops. If here, cI >= 69. Stack: [3, 0] | # Discard top of stack. Stack: [3] | 7- Subtract 7. Stack: [-4] | 0 Push 0. Stack: [-4, 0] | ------------------------------------------------------------- | )))) End of loops. Stack: [3, 0] or [-4, 0] <-----------------------+ v Push cI from voice below. Stack: [3, 0, cI] or [-4, 0, cI] + Pop top two elements and push their sum. Stack: [3, cI] or [-4, cI] + Pop top two elements and push their sum. Stack: [cIV] ``` Notice that in the inner section, we have to do `#7-0` rather than just `4-` because in the latter case, the stack would be `[3, -4]` and the loop would not terminate. (Loops terminate only if \$0\$ is on top of the stack.) Here is another way to visualise how the nested loops work, with the letter names corresponding to \$c\_\text{I}\$ included. At each `(`, we effectively test whether \$c\_\text{I}\$ exactly corresponds to the indicated letter. If it does, we go no deeper. Thus, we see that the top branch is followed if \$c\_\text{I}\$ corresponds to a letter between A and D (inclusive); the bottom branch is followed otherwise. ``` A B C D 1-(1-(1-(1-(1- )))) -> cIV = cI+3 (1-(1-))#7-0 -> cIV = cI-4 E F ``` Up in Voice 1, we perform an analogous calculation for \$c\_\text{V}\$: $$c\_\text{V} = \begin{cases}c\_\text{I}+4\text{ if }c\_\text{I}<68,\\ c\_\text{I}-3\text{ if }c\_\text{I}\ge68. \end{cases}$$ The code looks much simpler because we are piggybacking on the nested loops/conditionals in Voice 2, which apply across *all* voices. #### 2. Finding \$a\_\text{IV}\$ and \$a\_\text{V}\$ Observe that $$ a\_\text{IV} \ne a\_\text{I}\text{ if and only if }c\_\text{I}=70,\\ a\_\text{V} \ne a\_\text{I}\text{ if and only if }c\_\text{I}=66.$$ Musically speaking, there are only four keys for which we cannot simply copy the accidental from chord I to chords IV and V. These keys are `F` (chord IV `Bb`), `F#` (chord IV `B`), `B` (chord V `F#`), and `Bb` (chord IV `F`). The \$a\_\text{IV}\$ and \$a\_\text{V}\$ calculations partly involve piggybacking on the loops in Voice 2, this time to pre-load values onto the stacks in Voices 4 and 6 that are then manipulated further. Let's look at how \$a\_\text{V}\$ is determined in Voices 5 and 6. (The procedure for \$a\_\text{IV}\$ is similar in Voices 4 and 5.) The accidental calculation itself is performed by this snippet: ``` #v #0 # ( ^(0 )0)^ ``` There are three execution branches depending on the values of \$c\_\text{I}\$ and \$a\_\text{I}\$ and it's easiest to consider these branches separately. In each case, the stack in Voice 5 (V5) is pre-loaded with two copies of \$a\_\text{I}\$. The value on top of the stack in Voice 6 (V6) when the snippet ends is \$a\_\text{V}\$. *Note that for the following explanations the code runs vertically, with Voice 5 in the left column and Voice 6 in the right column.* (This vertical format is used to maximise readability of the comments, but isn't a valid way to write Prelude code.) 1. If \$c\_\text{I}\ne 66\$ (i.e. the input is not `B` or `Bb`), the stack in V6 is cleared during the pre-load stage, leaving \$0\$ as the top element. The outer loop in V6 is not entered, and a copy of \$a\_\text{I}\$ (whose value may be \$0\$, \$35\$, or \$98\$) is simply yanked (`^`) from V5. ``` V5 stack: [aI, aI], V6 stack: [0] ( Top of stack is 0 so skip ahead to the matching ). -+ # | v^ | ( | #0 | 0 | ) | 0 | ) <---------------------------------------------------+ #^ Discard top of stack in V5, but only after yanking it into V6. V5 stack: [aI], V6 stack: [0, aV = aI] ``` 2. If \$c\_\text{I} = 66\$, we push \$35\$ (the codepoint of `#`) onto the stack in V6 during the pre-load stage. If \$a\_\text{I}=0\$ (i.e. the input is `B`) then we need \$a\_\text{V}=35\$. After a bit of back and forth between the voices, we see that \$35\$ does indeed end up back on top of the stack in V6 at the end of the snippet. ``` V5 stack: [0, 0], V6 stack: [35] ( Top of stack is 35 so enter the loop. # Discard top of stack in V5. V5 stack: [0], V6 stack: [35] v^ Swap top stack values between V5 and V6. V5 stack: [35], V6 stack: [0] ( Top of stack is 0 so skip ahead to the matching ). -+ #0 | 0 | ) <---------------------------------------------------+ 0 Push 0 in V6. V5 stack: [35], V6 stack: [0, 0] ) End loop. #^ Discard top of stack in V5, but only after yanking it into V6. V5 stack: [0], V6 stack: [0, 0, aV = 35] ``` 3. If \$c\_\text{I} = 66\$, we push \$35\$ onto the stack in V6 during the pre-load stage. If \$a\_\text{I}=98\$ (i.e. the input is `Bb`) then we need \$a\_\text{V}=0\$, which is indeed the value on top of the stack in V6 at the end of the snippet. ``` V5 stack: [98, 98], V6 stack: [35] ( Top of stack is 35 so enter the loop. # Discard top of stack in V5. V5 stack: [98], V6 stack: [35] v^ Swap top stack values between V5 and V6. V5 stack: [35], V6 stack: [98] ( Top of stack is 98 so enter the loop. #0 Discard top of stack in V5. Push 0 in V6. V5 stack: [0], V6 stack: [98, 0] 0 Push 0 in V5. V5 stack: [0, 0], V6 stack: [98, 0] ) End loop. 0 Push 0 in V6. V5 stack: [0, 0], V6 stack: [98, 0, 0] ) End loop. #^ Discard top of stack in V5, but only after yanking it into V6. V5 stack: [0], V6 stack: [98, 0, 0, aV = 0] ``` #### 3. Printing the progression Printing the progression is an exercise in stack management. The goal is to get all of the \$c\_j\$ onto one stack (Voice 2) and all of the \$a\_j\$ onto another (Voice 5), then churn them all out in a single loop. There's more than one way to do this, and the code went through several iterations before I settled on the current order of voices. The print loop is spread across two voices and is notable for the fact that the starting `(` and ending `)` are not in the same voice (a byte-saving optimisation). The `!` in Voice 2 prints each of the letters \$c\_j\$. The accidentals \$a\_j\$ require special treatment. For any \$a\_j=0\$ (corresponding to a natural note) no character should be printed, but a bare `!` will print a null byte. The way around this is to use `(!0)#` to print only if \$a\_j\ne0\$. Finally, a separator is needed. It's cheap to push and print a tab (codepoint \$9\$) on demand. --- # [Fugue](https://esolangs.org/wiki/Fugue) [![enter image description here](https://i.stack.imgur.com/aEWjd.png)](https://i.stack.imgur.com/aEWjd.png) Fugue and Prelude are dual languages: Fugue uses musical notation to encode Prelude instructions. I'm not sure how it should be scored (no pun intended) but I'd suggest that the byte count of its Prelude twin (above) is a reasonable measure. The musical score was generated from the Prelude source code using a custom [Ruby](https://www.ruby-lang.org) script to metaprogram the [LilyPond](http://lilypond.org/) engraving. You can listen to the MIDI or view the PDF score, Ruby script, and LilyPond source on [Github](https://github.com/Dingus357/fugacity). There is a very old [Fugue compiler](https://github.com/graue/esofiles/blob/master/fugue/impl/fugue_x86.c) that reads MIDI files as source code, but I was unable to get it to work. The piece, titled *Fugacity*, is scored for trumpet, electric guitar, tenor sax (two-note cameo), double bass, and piano. (The choice of instruments is artistic and arbitrary as far as Fugue is concerned.) How does it sound? Not at all bluesy, but I've definitely heard worse. ### Generating the score To get a basic score to begin with, all no-ops (spaces) are converted to crotchet rests and most Prelude instructions are converted to crotchets. There are two exceptions: 1. Push commands are converted to a pair of quavers. The first quaver represents the push instruction itself (ascending or descending third) and the second quaver represents the value being pushed. 2. Some effort is taken to keep the parts within the playing ranges of the instruments. To this end, jumps of 10 semitones or more (which are no-ops) are automatically added. These range-limiting jumps become the second of a pair of quavers, with the first quaver being the instruction that triggered the range limiter. All voices are padded to the same length with rests, which isn't necessary for Fugue but does make the score a bit nicer to read. With this basic score to work from, some artistic embellishments are introduced for increased musicality. The following adjustments occur automatically: * A crotchet followed by one, two, or three crotchet rests in the same bar is replaced by a minim, dotted minim, or semibreve with \$50\;\%\$ probability. * Consecutive rests are consolidated. * An accent is added to each note with \$25\;\%\$ probability. * A dynamic change is added to each run of notes with \$50\;\%\$ probability. An initial forte dynamic is applied to all voices. Louder dynamics are favoured over softer ones. * A crescendo or decrescendo hairpin is added between runs of at least three notes with \$50\;\%\$ probability. * Slurs are added between runs of at least two non-unison notes with \$50\;\%\$ probability. The first note in each voice is arbitrary. I toyed with several ideas but finally settled on a unison C. It's interesting to hear how the parts diverge from a common starting point. [Answer] # [Python 3](https://docs.python.org/3/), 201 bytes ``` def b(m): c=['Ab','A','Bb','B','C','Db','D','Eb','E','F','Gb','G']*2 if m not in c and m[1]=='#':k=c[c.index(m[0])+1] else:k=m o=c.index(k) I,F,V=c[o],c[o+5],c[o+7] return 4*[I]+[F,F,I,I,V,F,I,I] ``` [Try it online!](https://tio.run/##ZZDBisIwEEDPyVcM9DBNG2RdFaGQQ7VW@gNeYg62jVg0qdQK69fXKdbTEl5mhpeBzNxf/aX1i2Go7RnK0ImEs0ppTEuUmBKbMdkQWyIbi4zYjcmOyIn9WOzRRL@cNWdw4NseGg8VnHwNTs@NUhhgclWVrmaNr@1f6PSPEfHccGZvD0vKcdaqr70KzgqZywN1tEbSFa8@YU0dne2fnYdlpAsT65zeFXQOn2iGe9f4PsRtgpImon8LCXj0KPhksmBSWfDPpeXkaAFfN7wB "Python 3 – Try It Online") [Answer] # JavaScript (ES6), 106 bytes *-4 bytes thanks to @l4m2* Expects a string in `[A-G][#b]?` format. Returns a list of strings in the same format. ``` s=>[..."000055007500"].map(n=>a[+n+a.indexOf(s)%12],a="C#DD#EFF#GG#AA#BCDbDEbEFGbGAbABb".match(/.[b#]?/g)) ``` [Try it online!](https://tio.run/##bcy7CsIwAIXh3cdIEBKqaRWKUyppcxl9gNIhSS9WalJMEd8@ZhYP/Ms3nId@62Bf87odne@HONIYaNUSQkCRVpZFcUmBjjz1ihytdJu5TJPZ9cPnNqKA96dzd9AUNJBzKKSESkHGYN1ww4URUhnFDKsNSA@bvaOctAZ213zCOFrvgl8GsvgJjQg0AOPdjwnzByVMGL8 "JavaScript (Node.js) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 109 bytes ``` $ $`¶$` T`FCGDA\EB`Bo`^. ^B Bb T`B\EADGCF`Fo`¶. ¶F ¶F# b#|#b (.+ )(.+)(¶.+) $2 $2 $2 $2¶$1$1$2 $2$3 $1$2 $2 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX4VLQSXh0DaVBK6QBDdndxfHGFenBKf8hDg9rjgnLqckoLBTjKuji7uzW4JbPlClHtehbW4grMyVpFyjnMTFpaGnraAJJDQ1gLLamlwqRgowBDTYEAhBTBVjBSjr/39nLtckLjdlAA "Retina 0.8.2 – Try It Online") Link includes test cases. Enharmonic-free, but uses `##` instead of `x`. Explanation: ``` $ $`¶$` ``` Make two copies of the input, with space and newline as separators. ``` T`FCGDA\EB`Bo`^. ``` Transpose the first copy down a fifth. ``` ^B Bb ``` But `F` transposes to `B♭`. ``` T`B\EADGCF`Fo`¶. ``` Transpose the last copy up a fifth. ``` ¶F ¶F# ``` But `B` transposes to `F♯`. ``` b#|#b ``` Cancel out the sharps and flats if transposing `F♯` to `B` or `B♭` to `F`. ``` (.+ )(.+)(¶.+) $2 $2 $2 $2¶$1$1$2 $2$3 $1$2 $2 ``` Generate the desired chord layout. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes ``` ≔FCGDAEBηF⁺⊖⪪”)∨|7B”¹⁺⌕η§θ⁰×⁷⁻№θ#№θb«§ηι×#÷ι⁷×b±÷ι⁷→ ``` [Try it online!](https://tio.run/##ZY5Bi8JADIXP668I4yUDI7ReBPdU7VY8KKL@gdrGNlCnazsWQfztY@queDCQw3vvyyNZmTZZnVbeR23LhUWVzBdx9DNTBkr9PTjWDeCmurQYU9bQiayjHHe/FTtUoUwQhOFYVvhQawNPNmGbY2kgckub0xXPBoI@3POJWpwYWLEVbF5frOtDNVSSvuVB6efAbfC1aVjcV5OUspa//u2/Qjk3sLQu5o5zQjYw0Z/QQaA1Fakj/GB7eFV3hNMtF6UTefc@GfpRVz0A "Charcoal – Try It Online") Link is to verbose version of code. Outputs all chords on one line. Enharmonic-free, but uses `##` instead of `x`. Explanation: ``` ≔FCGDAEBη ``` Get the list of fifths. ``` F⁺⊖⪪”)∨|7B”¹⁺⌕η§θ⁰×⁷⁻№θ#№θb« ``` Split the compressed string `111100112011` into digits, decrement each, and add on the index of the input in the list of fifths, adding `7` for each `#`, and subtracting `7` for each `b`. Loop over the resulting list. ``` §ηι ``` Output the appropriate fifth by cyclic indexing. ``` ×#÷ι⁷×b±÷ι⁷ ``` Output the appropriate number of sharps or flats. ``` → ``` Leave a space between chords. [Answer] # [Ruby](https://www.ruby-lang.org/), 89 bytes ``` ->n{"444455443544".bytes.map{|i|"BEADGCF"[-7+x=(n[-1].ord/32*7-n.ord*2%7+i)%12]+?b*x/=7}} ``` [Try it online!](https://tio.run/##VczJCoMwFIXhfZ@ipAitIREnsrLF@SHERYMVXNSKAyjqs6dq4UAvXPjO5m8HOanSU@xez8TZznUdx96ecDn1r46/n828VAsJYj9Kw4RkTNDRu9YZM3P@aQvDtnTB6p26pQla3TTTyulD6qPhiXVVzbnMSCJJfjoUQikUQT4UQ8Ghoe9@M0EJIXSQQQWR/8YFESiFIsiHYijYpb4 "Ruby – Try It Online") An anonymous function taking a flat, sharp or natural key signature as an argument `n` and outputting the following chords in order to keep with the convention of naming major chords as flats to avoid double sharps. (Chords are listed here as a circle of 5ths: `B E A D G C F Bb Eb Ab Db Gb`; note all the natural notes come first with the flats together at the end.) `n.ord*2%7` finds the letter in the input. The ASCII code for `F` is 70 so this becomes `0`. `G` is 2 steps further round the cycle of 5ths and becomes `2`, while `C` fills in the gap with the value `1` `n[-1].ord/32*7` adjusts for flats and sharps. If the last character of the input is an uppercase letter (i.e. same as the first) it evaluates to `2*7`. If it is a lowercase `b` it evaluates to `3*7` and if it is a symbol like `#` it evaluates to `1*7` . A few bytes could be saved if only handling flats is required, because it will enable a count of the length of the string to be used instead of checking for the difference between `#` and `b` Internally, `B` is assigned the value `0`, `F` is `6` and `Bb` is `7`. To take advantage of Ruby's wraparound index on the string `BEADGCF`, `-7` is subtracted from all values when indexing the string. **Commented code** ``` ->n{"444455443544".bytes.map{|i| #convert the magic string into bytes and iterate through the 12 chords "BEADGCF"[-7+ # when indexing the output string, use wraparound index -7 =B through 0 =Bb to 4 =Gb x=(n[-1].ord/32*7 #7 for sharp, 14 for natural, 21 for flat -n.ord*2%7 #subtract note letter as a position in the cycle of 5ths +i #in order to make the chord changes, adjust by the value in the first magic string )%12 #take the note value mod 12 to get into a nice 12-note range ]+ ?b*x/=7} #divide x by 7. Then add x flat symbols ?b. x is either 0 or 1. } ``` ]
[Question] [ [Lucky numbers](https://en.wikipedia.org/wiki/Lucky_number) ([A000959](https://oeis.org/A000959)) are numbers generated by applying the following sieve: Begin with the list of natural numbers: ``` 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, ... ``` Now, remove every second element (\$n = 2\$, the smallest element in the list aside from 1): ``` 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, ... ``` Now, remove every third element (\$n = 3\$, the next remaining element after 2): ``` 1, 3, 7, 9, 13, 15, 19, 21, 25, ... ``` Now, remove every seventh element (\$n = 7\$, the next remaining element after 3): ``` 1, 3, 7, 9, 13, 15, 21, 25, ... ``` Then continue removing the \$n\$th remaining numbers, where \$n\$ is the next number in the list after the last surviving number. Next in this example is 9, then 13 and so on. Eventually, this converges to the lucky numbers: ``` 1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 69, 73, 75, 79, 87, 93, 99, ... ``` --- However, we've already [looked at](https://codegolf.stackexchange.com/q/45785/66833) the lucky numbers. Today, we'll be looking at a related sequence: the lucky factors ([A264940](https://oeis.org/A264940)). These are the values of \$n\$ that remove a specific integer \$x\$. For example, \$x = 2\$ is removed when \$n = 2\$, so \$2\$'s lucky factor is \$2\$ Additionally, \$x = 19\$ is removed when \$n = 7\$, so \$19\$'s lucky factor is \$7\$ If \$x\$ is lucky, its lucky factor is \$0\$. The first 50 elements of this sequence are ``` 0, 2, 0, 2, 3, 2, 0, 2, 0, 2, 3, 2, 0, 2, 0, 2, 3, 2, 7, 2, 0, 2, 3, 2, 0, 2, 9, 2, 3, 2, 0, 2, 0, 2, 3, 2, 0, 2, 7, 2, 3, 2, 0, 2, 13, 2, 3, 2, 0, 2 ``` --- This is a standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge. You may choose to: * Take a positive integer \$x\$ and output the lucky factor of \$x\$ * Take a positive integer \$x\$ and output the lucky factors of each integer \$1 \le i \le x\$ * Output the infinite list of lucky factors This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins --- ## Test cases ``` x n 15 0 57 9 26 2 41 3 50 2 13 0 48 2 20 2 19 7 22 2 24 2 27 9 60 2 54 2 49 0 2 2 7 0 45 13 55 15 ``` [Answer] # [Python 2](https://docs.python.org/2/), 72 bytes Takes a positive integer \$ x \$ and outputs the lucky factor of \$ x \$. Outputs via exit code. ``` x=input() R=range(1,x+1) for i in R:i+=i<2;del R[i-1::i];x>R[-1]<exit(i) ``` [Try it online!](https://tio.run/##TZBPj4IwFMTv/RRzMaURiUXQFWVve9ib4Wo8sFDXJlIaKBE/PduW/XdpXmbmTX95@mlurYqnqq0FclBKpzGXSg8mYKTIu1J9ioCH45Izcm07SEiFIpPLXB7jQy3uKM5yxbNMXg7ja3Fe8ctRjNIEkk22jBDZ6LYz6IcP3bWV6Ptf5dkT8pDmhlYLFVBHEOknDUEflKHscc0IcI0enTQicDazdUp7TA9zl0o4HlsV9aaWyi6MIZRNNKUOpDKhz0S9vlskxgi@9xc1xQIjgYOywh9edPI4Z6rnyzieH7RLCP9N/j/@fnpjc09UtU0zKFmVltff0F3SmxZljnTCDJ2ar51DTTwF1iTdAXsSb4GYJBzYkHTtZr5xbvLi5nhW9sCOxLFXEv/63a13U68ke7cFn8HON6TgttO@6Rc "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~75~~ ~~73~~ ~~71~~ 63 bytes ``` x=scan();a=b=1:x;while(x%in%a)a=a[-b*(T=c(a,0)[F<-F+1]+!T-1)];T ``` [Try it online!](https://tio.run/##VcqxCoMwEADQvV9xpYh31YAZuhiz@gXZrMMZDA2UKNFioPTbUzp2fbyYHXQC3CvY3S8BE8EbNsvhTynBxczbDkfkdZ1jTvp3kBTrScs2qePhnzOmwoeCiTUPYrqi0Ra5bmjoO9FXcqzORkgalcmfk1sievABZHtryPKOvgaHnmoo76Gk/AU "R – Try It Online") Returns the \$n\$-th lucky factor. Thanks for -2 bytes to Giuseppe and -8 bytes to Dominic van Essen. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 27 bytes ``` 2ịŻ‘ɼ»2$‘¤ị,ḟm¥@¥ƊƲƬṪċ¥Ðḟ⁸Ḣ ``` [Try it online!](https://tio.run/##JYwxCsJAFET7PcUUlgrJmjUGQTyF4AFsRK0stIs2AW0sBRVBTKFYichKrDYa8Bi7F1l/1mZ4vP9nBv3hcGYt19nqk5l4832pjFcI1IlUVcvDSKUdlRbL4lZc9fPyXqk0X5M3c6nl0XrqrJ/blol3qLVh4n0rT5jO7hOzuJr5Q8sbQVfLJT0T5QlFz1pMgTHzBeAxEQIR4w2As8AH6kx4Jfv18ho0S@Z/EwEh49yZwKXrNtxVOBNEZQvuB6FbEPBpk1L8AA "Jelly – Try It Online") A full program taking an integer as its argument and printing an integer. Could almost be used as a monadic link, but the register needs to be reset to zero before each call. The TIO link has a footer that runs all of the test cases. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~73~~ 67 bytes ``` i=1 f@n_:=0Module[{k=++i},f@_/;n∣k++=n] Print@f@Max[,2]~Do~{,∞} ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/T1pArzSEv3srWwDc/pTQnNbo621ZbO7NWJ80hXt8671HH4mxtbdu8WK6Aosy8Eoc0B9/Eimgdo9g6l/y6ap1HHfNq//8HAA "Wolfram Language (Mathematica) – Try It Online") Prints lucky factors indefinitely. `f` is designed to be called on consecutive natural numbers, starting with `2,2,3,4...`. Initially there is only one rule defined for `f`, a generic definition which is called only when `n` is lucky. It returns 0, and adds a new, more specific definition: a sieve which returns `n` every `n`th it's called. Mathematica tries more specific definitions before more general ones. When rules have the same generality (as will be generated by the lucky numbers), they're tried in order of definition. Thus a sieve is only attempted if earlier ones did not filter that number. --- ### ~~69~~ ~~67~~ 69 bytes ``` Array[Clear@f;f[i=1]=f@2;f@n_:=0Module[{k=++i},f@_/;n∣k++:=n];f,#]& ``` [Try it online!](https://tio.run/##FYzRCoIwFIbv9xpCFFuktlkpi0W3BUGXQ2SYM1EX2LoI0eveozfrRdbx4ud8fOfnb5W9F62yVa5cyd2h69RbHptCdUInWlY8SLkWYaKFyWLunx@3V1PIvuYYVwPRIlsl5vf51hjH3KSJJl46c5euMlZ6y/38pJ5WAHizhSgF/MZrrszYo4ARxDYEhRFBNAD2CQrWwFtwE@/ghhAKgV4EjgHTyRMEhk4LDA3uDw "Wolfram Language (Mathematica) – Try It Online") Function which returns the lucky factors of `1..x`. [Answer] # [Python 2](https://docs.python.org/2/), 143 bytes ``` def f(x): m=1;n=range(1,x+1) while x in n and max(n)>m:m=min(q for q in n if q>m);n=[q for i,q in enumerate(n)if-~i%m] print 1-(x in n)and m ``` [Try it online!](https://tio.run/##JU7LbsIwEDzHXzGXSrYaEDYxaajCV/RWVVUkHLCEF8ckIlz666ntXHZXMzsP/xqvd1LLcjY9ej6LIytcKz@pDR1dDJfl/C4FK55XezOYYQmEjs5w3cxJnNzRtc4SH9DfA4aVtz2GkxPR5HvFbZkZQ5MzoRtNVNp@82ff3A8rfLA0Qm746i6y@7IGfoXJxEZziRfamOl5/C0RuuevJT@NXGwf/mbjjh1T/UVqYMd0DTRMHQDFKgnsmd6lW@4TW32kW61IA9RMqYxUeWbtIbM6I1WTVMg/qLODhoyecep/ "Python 2 – Try It Online") a very unintelligent and trivial implementation of this [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 69 bytes ``` f=lambda n,k=2:n>=k and(f(n+n//k*~-t,k+1)if(t:=k>2<=f(k))+n%k else k) ``` [Try it online!](https://tio.run/##NY7BbsMgEETP4Sv2YpmNSROwiWOr@F9c2SgIh6KYKsqlv@6GQC/7doZhwD/D9dvVF3/fNq2W8fY1jeCYVaJ3g7Iwuolq6ip3PNr97yEwW3E0moZe2UF8Kk0tYuUKC/OyzmBxe1zNMgPvyc6wWd1GT40LzDj/Eyh@rH4xgZZwGKBEJDt/f53SshATqAEKuUJZUMM0NYjvqdSMG5fxwonINrIj4hwpSMMjayJPSfM65ZpL0uLf7yJbIkT2m8zcd845mf2mSz2Q89Dm3vc/@OvBtMg/ "Python 3.8 (pre-release) – Try It Online") Direct recursion. Returns the lucky factor of `x`, using `False` instead of `0`. [Answer] # [Java (JDK)](http://jdk.java.net/), 107 bytes ``` x->{int s[]=new int[x+1],i=1,j,c;for(;++i<x;)for(c=j=s[i]<1?0:x;j++<x;)s[j]+=s[j]<1&&++c%i<1?i:0;return s;} ``` [Try it online!](https://tio.run/##NY87b4MwEMf3fIpTJCJSEwvULcbpVqlDp4yIweWRnEsMso@UKMpnp3ZKB9/Dv/@9tLqqna6/Z7wMvSXQPucjYcfb0VSEveEvYlV1yjn4VGjgvgIYxq8OK3CkyLtrjzVcPIuPZNGcihKUPbntUwrwYeh9aZWjoaI8QAtynnaHu0/BFaU0zQ8ENLGsTFBmiU4q0fY2FoxhPoltiCuppSuwzLO3dD8JzVggrtAlk8Hm2WbDWBWhF@A@Fbah0Rpw4jGL5yJXZcE2buwIJLRcDUN3i7M03f7hMCNI0NNMeJcvat415kRn/8XY/1EAx5uj5sL7kfjgr6Y2Xkev9R6iOjLrBDBZqv3Gy4DHKrzH/As "Java (JDK) – Try It Online") * This outputs the lucky factors of each integer \$1 \le i \le x\$ in a 0-indexed array, but the mapping basically stays `result[x] = factor` (plus has `result[0] = 0`, which shouldn't be taken into consideration). ### Explanation This answer basically counts the number of zeroes, and every "lucky"-th zero is changed into the current lucky factor. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepade) ``` L∞IFD®LKн©ôD€θI£®‚ˆ€¨˜}I£ILå≠÷¯vy`¸Þ‡ ``` It's slow, ugly, and long, but it works.. :/ I might try to revisit this one from scratch later on. Given an input \$n\$, outputs the first \$n\$ values. [Try it online.](https://tio.run/##AU0Asv9vc2FiaWX//0ziiJ5JRkTCrkxL0L3CqcO0ROKCrM64ScKjwq7igJrLhuKCrMKoy5x9ScKjSUzDpeKJoMO3wq92eWDCuMOe4oCh//8yMA) **Explanation:** ``` L # Push a list in the range [1, (implicit) input] ∞ # Push an infinite positive list: [1,2,3,...] IF # Loop the input amount of times: D # Duplicate the infinite list ®L # Push a list in the range [1,`®`] # (`®` is -1 by default, so the first iteration is [1,0,-1]) K # Remove these values from the duplicated infinite list н # Pop and only leave the first (smallest) value # (this is basically the smallest value above `®` (and 1)) © # Store it as new `®` (without popping) ô # Split the infinite list into parts of that size D # Duplicate this list of parts €θ # Only leave the last value of each part I£ # Only keep the first input amount of values of this infinite list ®‚ # Pair it with `®` ˆ # And pop and add it to the global array €¨ # Remove the last value from each part ˜ # And flatten the list }I£ # After the loop: only leave the first input amount of values IL # Push a list in the range [1,input] å≠ # Check for each that it's NOT in this list ÷ # Integer-divide the initial [1,input] list by these 0s/1s, # where division-by-0 results in 0 # (this basically mapped all Lucky numbers to 0s) ¯ # Push the global array vy # Loop over each pair `y`: ` # Pop and push the list and integer separated to the stack ¸Þ # Create an infinite list only containing this integer ‡ # Transliterate all values in the list to the integer in our list # (after which the list is output implicitly as result) ``` [Answer] # [Dart](https://www.dartlang.org/), 151 143 138 bytes ``` f(x)=>([n,c,i,s]){for(s=[for(;i<x;)++i];n<s.last;i=s.length)for(n=s[c];i>0;c=s[i]>n?i:c)if(i--%n<1&&s.removeAt(i)==x)return n;}(0,1,0)??0; ``` [Try it online!](https://tio.run/##PY9NboMwEIX3nGI2jWzFQUAgNBgT9QA9QcQCOaYdNTGR7aBEUc5OgeJuPJ/ee56fU2PcMLTkTkVFjppJhszW9Nl2hlhxnArH8s7peo0116UNz411HMUISn@5bzpFtLBHWXOsIi5HxLrSBywkxZbgZvOmy3i1sqFRl65XH44gFeJOjXI3o0HzF4lYzCJ6OER8kJ22Dj6ba4naMRifCmRjlQUBzwAgzgqI2AhZXsB@gmRXQDJBGhewna1oUeLtEk7fFyX5t/YF5LOSeCv14DvvfDjzVrpfGoL/BbkfMS4W/42fKGPBiwdB3@EJLg1qQuf1r2a8iMwHhUo7g1PtlXkQIimICloiwx/1GFmADPvmfFOU8uA1/AI "Dart – Try It Online") Takes a positive integer `x` and output the lucky factor of `x`. I tried to reduce this as much as possible since Dart is a little verbose and that's the best I could come with. Ungolfed: ``` int f(int x) { int c = 1; var s = [for(int i = 1; i <= x; i++) i]; for (int n = 0; n < s.last;) { n = s[c]; for (int i = s.length; i > 0; --i) { if ((i + 1) % n == 0) { if (s.removeAt(i) == x) return n; } if (s[i] > n) c = i; } } return 0; } ``` ]
[Question] [ ## Challenge: ## Input: Two integer parameters `a` and `b` (where `a<b` and the difference is at least 2) ## Output: Output or return this text, where `a` and `b` are filled in: ``` (a,b) = ]a,b[ = {a<x<b} = {a<x&&x<b} = a+1..b-1 [a,b) = [a,b[ = {a<=x<b} = {a<=x&&x<b} = a..b-1 (a,b] = ]a,b] = {a<x<=b} = {a<x&&x<=b} = a+1..b [a,b] = [a,b] = {a<=x<=b} = {a<=x&&x<=b} = a..b ``` ## Challenge rules: * I/O is flexible. Can be printed to STDOUT, returned as a string/character-array, etc. Can be inputted as two integers, decimals, strings (not sure why since you need to calculate the `a+1` and `b-1`, but be my guest..), etc. * Any amount of leading and/or trailing new-lines are allowed, and any amount of trailing and/or leading spaces for each line is allowed. * The spaces at the equal signs (including those to align them in the same column) are mandatory, spaces between the other characters are not allowed. * `a+1` and `b-1` are replaced with the correct values after these calculations. * You are not allowed to use `≤` instead of `<=`. * You are not allowed to use `&` instead of `&&`. * You are allowed to output the numbers with `.0` (as long as it's consistent, and not more than one decimal zero). * You can assume `a` is at least 2 lower than `b` (in order for `(a,b)` to be correct). * The lines should be output in the order shown. ## Example: Input: `a=-5, b=10` Output: ``` (-5,10) = ]-5,10[ = {-5<x<10} = {-5<x&&x<10} = -4..9 [-5,10) = [-5,10[ = {-5<=x<10} = {-5<=x&&x<10} = -5..9 (-5,10] = ]-5,10] = {-5<x<=10} = {-5<x&&x<=10} = -4..10 [-5,10] = [-5,10] = {-5<=x<=10} = {-5<=x&&x<=10} = -5..10 ``` ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, please add an explanation if necessary. *PS: For those who had [seen this challenge in the Sandbox](https://codegolf.meta.stackexchange.com/a/16101/52210) when it was still a [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenge with `a` and `b` hard-coded, I've changed it to an input challenge to prevent boring hard-coded and encoded answers like we usually see with KC challenges.* [Answer] # JavaScript (ES6), ~~184~~ ~~182~~ ~~181~~ 180 bytes Takes input in currying syntax `(a)(b)`. Returns an array of 4 strings. ``` a=>b=>[1,2,3,4].map(k=>'31,23 = 31,23 = {10x72}4{10x&&x72}45..6'.replace(/\d/g,(n,i)=>[(+n?k<3:k&1)?'<':'<=',a,b,'][)([[]('[(i*17^k*718)%9],' = '.slice(k/2),a+k%2,b-(k<3)][n%7])) ``` [Try it online!](https://tio.run/##hY3BboMwEETv/QousLvBGGySkkSYfIjjSIaQiJgaFKqqUtVvpzRSDzn1MjMajd7c7Iedmns3vid@OLfzRc1WVbWqtGCS5Wxt@Jsd0akK8qXJAxX8@ZfIPgv5vf71KHrEDeevwO/t2NumxfR4Tq8MPeto4WHsD67M9y4SdIAS9lAqYJbVDIwm1NogaOxWoji5VSG2FO4MgyBYnoBPfbcAXSqJ2diFktUJLjAy2oeFIZqbwU9D3/J@uOIFkw2hyIjfhs4jHD1Q/NCX51lGKP8dJZLwCUXzDw "JavaScript (Node.js) – Try It Online") ### How? For each row **k** with **1 ≤ k ≤ 4**, we start with the following template: ``` "31,23 = 31,23 = {10x72}4{10x&&x72}45..6" ``` and replace each decimal digit **n** at position **i** according to the following table: ``` n | Replaced with | Code -----+-------------------------+------------------------------------------ 0,7 | comparison operator | (+n ? k < 3 : k & 1) ? '<' : '<=' 1 | a | a 2 | b | b 3 | interval bound | '][)([[]('[(i * 17 ^ k * 718) % 9] 4 | a substring of ' = ' | ' = '.slice(k / 2) 5 | either 'a' or 'a + 1' | a + k % 2 6 | either 'b' or 'b - 1' | b - (k < 3) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~225~~ ~~203~~ 195 bytes ``` a,b=input() for d in 0,1: for m in 0,1:k=`a`+','+`b`;o='{'+`a`+'<'+m*'=';c='x<'+d*'='+`b`+'}'+' '[m+d:];print' = '.join(['(['[m]+k+')]'[d],']['[m]+k+'[]'[d],o+c,o+'x&&'+c,`a+1-m`+'..'+`b-1+d`]) ``` [Try it online!](https://tio.run/##PY1BCoMwEEX3niIrv3ai1EI32pwkBKKGUitJRCxYSs@eJpQWZuC/xzB/eW43704h9HwQk1seW1FmV78ywybHjrxpM5bQ/nAWutcEDtKD7rzAK6ZkLiB7gEA3CuwRTIJ0RHiDwBikJdOqblknt4EJhvruJ1dIxJFW0UwoFaRRHOpv5Nd4GuNiz3PEpHtqKhs/13WqqBoyWpUhVGfeHD8 "Python 2 – Try It Online") [Answer] # [m4](https://www.gnu.org/software/m4/manual/m4.html), 194 Seems like a job for a macro processor. Not sure if m4 meets our standards for a programming language. It does have looping ability and arithmetic eval, so I assume its close to the mark. ``` define(l,`$1a,b$2 = $3a,b$4 = {a<$5x<$6b} $8= {a<$5x&&x<$6b} $8= $7')dnl l(`(',`)',],[,,,incr(a)..decr(b),` ') l([,`)',[,[,=,,a..decr(b),` ') l(`(',],],],,=,incr(a)..b,` ') l([,],[,],=,=,a..b,) ``` This is my first non-trivial look at m4, so I suspect there are more golfing opportunities I've missed. Inputs are passed using `-D` macro definitions at the command line. Not sure if anything needs to be added to the score for these, as as far as I can tell this is the only way to meaningfully pass parameters: ``` $ m4 -Da=-5 -Db=10 intnot.m4 (-5,10) = ]-5,10[ = {-5<x<10} = {-5<x&&x<10} = -4..9 [-5,10) = [-5,10[ = {-5<=x<10} = {-5<=x&&x<10} = -5..9 (-5,10] = ]-5,10] = {-5<x<=10} = {-5<x&&x<=10} = -4..10 [-5,10] = [-5,10] = {-5<=x<=10} = {-5<=x&&x<=10} = -5..10 $ ``` [Try it online](https://tio.run/##TYzBCsIwEETvfkUOS5PAtlht1UNz8y9CIYmtEGhTUQ@C@OvGbaBS5rCz@2ZnrGLs@qsPvRjQQGnRwY4pBvvZVeTetoH61cDBfRiclj3LVic4ctmFYTMIIzgaybFFjYg@XO7CyqLoejJOomGMS4rpFNIkhWjXPOG5pU0i/i9xC9apviWm5meHMsbvdHv6KTxifrYqr2k4VW5/). --- Thanks @Dennis for [adding m4 to TIO](https://tio.run/##yzX5DwQA) so quickly! [Answer] # [Python 2](https://docs.python.org/2/), 187 bytes ``` t=a,b=input() for j in 1,0: for i in 1,0:print"%%s%d,%d%%s = "%t*2%('[('[i],'])'[j],'[]'[i],']['[j])+"{%d<%sx%%s<%s%d}%s = "%(a,'='[i:],'='[j:],b,' '*(i+j))*2%('','&&x')+`a+i`+'..'+`b-j` ``` [Try it online!](https://tio.run/##NYzRCoMgGIXvewoJ7Nf8ixbsJvJJRLCIMb2wKAeNsWd3Fg0OfHxwzlne4Tn7NsYgBxyl9csrMJ495pU4Yj25YdNl5FD712W1PuSUbnRCOiUSSXIaypYyUClWI2gOyiUqfbk6nIv8Q6eebnta9cfB91qzAUGmaqdPusQRgUDJrHCcn9@AUBQ7cGEGYY2AugZhxsqZGKs73pof "Python 2 – Try It Online") [Answer] # [Java (JDK 10)](http://jdk.java.net/), 251 bytes ``` a->b->("(a,b)q]a,b[q{a<x<b} q{a<x&&x<b} q"+-~a+".."+~-b+"\n[a,b)q[a,b[q{a<=x<b} q{a<=x&&x<b} qa.."+~-b+"\n(a,b]q]a,b]q{a<x<=b} q{a<x&&x<=b} q"+-~a+"..b\n[a,b]q[a,b]q{a<=x<=b}q{a<=x&&x<=b}qa..b").replace("a",a+"").replace("b",b+"").replace("q"," = ") ``` [Try it online!](https://tio.run/##jZA/b4MwEMX3fIqTh8gW2GqHTgXGSh06ZaQMZ0KQiWP@mahRRL46NYa06dbFvjv/3nvyVXhGXu2PU66x7@EDlYHrBqAZpFY59Batu8612sPJvdGd7ZQp0wywK3vmUYDKmYjBKi0Og8mtqo14W4vo3diiLLrwf9BinyRwgBgm5InkCSUUQ8nazJ1pe8XoK5IjgK@227UhAb9hQIQgwY3LgHya1IvSuyj24FKtqhYf8Dkj8xnZkhGvuKd985MhF/esTe947JFf97lx7pIw0RWNxrygBEno1I8TSUL5d9KSkLifEza9@s3uLr0tTqIerGjcZqw29CCwafSF8he2Vs9PjM34uBmnbw "Java (JDK 10) – Try It Online") ## Credits * -50 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] ## [Perl 5](https://www.perl.org/), 181 bytes I thought this would have worked out a lot shorter... ``` $_="sd,ds = sd,ds = {dsxsd}s= {dsx&&xsd}s= d..d "x4;s!s!("()][<< [)[[<=< (]]]<<= [][]<=<= "=~s/[<= ]+/$&$&/gr=~/ +|<=|./g)[$-++]!ge;s/d/$F[$x%2]+{8,1,9,-1,19,-1,28,1}->{$x++}/ge ``` [Try it online!](https://tio.run/##NYnLCoMwFET3/YqrpKIkMVUqtJh02Z8Il1KISKFU8XYh@Pj0pqGPzcycM30z3Cvv2cXE5IQjMPDvydFIbqHvSpIfuDx3m3jc1xRRlMZphlZrALCZtdqElSKi1iYYtBiMgdispMIJyBVLWKLawawK@KzNnKs2s0xyjlHb1KScYmfLxm2JfDqIQhyFLETxyTLwIk8TGzlfVNt4Lysodq@uf966B3nZX98 "Perl 5 – Try It Online") ### Explanation Originally this was using a `printf` format string, but just having `s` and `d` was shorter when combined with `s///`. First the format string is built into `$_` and quadruplicated, then all `s`s are replaced with the corresponding bracket, `<`, `<=` or spaces, depending on the replacement index. I hoped to save some more bytes with the duplication of the last 5 chars of each block, but this only ended up saving 2 bytes. The resultant string is split up into elements of spaces, `<=` or single characters. Finally all `d`s are replaced with the desired number which is adjusted based on the index of the current replacement via a hash key. [Answer] # JavaScript, ~~190~~ 189 bytes ``` x=>y=>`(0)7]0[7{1<x<2} 7{1<52} 73..4 [0)7[0[7{18x<26{185261..4 (0]7]0]7{1<x826{1<5=263..2 [0]7[0]7{18x82}7{185=2}71..2`.replace(/\d/g,d=>[[x,y],x,y,x+1,y-1,`x&&x<`,`} = `,` = `,`<=`][d]) ``` [Try it online](https://tio.run/##JY7LCoMwFET3/QpXktD4SFofi8QfSQMRE6VFVLSUSPHb7U26mRk4HJhX@2m3bn0u72SajT17cTrR7KLRKMeVymX1pdxxdkSRX0UYtzS9XyRwGXgNvIQqWEk9QbkCUwWz9oQXgpUgMZBUJQOqAR2@gR0VeEynq13GtrMoe5hsIEY0UjqyKwJB3JWSPaFEuzh2XBMNR0QE/U8utJJG4bObp20ebTrOA@pRUmBEc4zPHw) [Answer] # [Stax](https://github.com/tomtheisen/stax), 74 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ÉyU≤₧pΔz▀σ┬`♪•a≤☻Σ╕←k►¬╗Ö)ßâL╫§▐ƒ┼°╚íS3:Y¶7]7♂e╖à╙ô≥;M0h8♦Oún┼ë`←B╠╫║┌♂α▲╚ ``` [Run and debug it](https://staxlang.xyz/#p=907955f39e70ff7adfe5c2600d0761f302e4b81b6b10aabb9929e1834cd715de9fc5f8c8a153333a5914375d370b65b785d393f23b4d306838044fa36ec589601b42ccd7bada0be01ec8&i=-5+10&a=1) This uses stax's string templates heavily. Unpacked, ungolfed, and commented, it looks like this. ``` Y save second input in Y register (first is already in X) .)].([|* cross product of ")]" and "(["; this produces [")(", ")[", "](", "]["] { begin block to map over interval delimiters E"`x,`y"a++ push delimiters separately, then wrap them around the inputs e.g. "(-5,10)" c"(])["|t copy last value, then replace parentheses with braces e.g. "]-5,10[" ih'= push half the iteration index and "=" e.g. 0 "=" |;'= push iteration parity (alternating 0 and 1) and "=" e.g. 0 "=" 0 "=" "{`x<`*x<`*`y}" multiply each equal sign by its occurrence, and template e.g. "{-5<x<10}" c'x.x&:mR copy last value, then replace "x" with "x&&x" e.g. "{-5<x&&x<10}" yvih xi|e calculate final bounds offsets e.g. -5 1 10 -1 "`+..`+" add inputs to offsets, and embed in template e.g. "-4..9" 5l combine last 5 values into array m map [")(", ")[", "](", "]["] using block :< left-align grid colums to add extra spaces m" = "* for each row, join with " = " and output ``` [Run this one](https://staxlang.xyz/#c=Y++++++++++++++++%09save+second+input+in+Y+register+%28first+is+already+in+X%29%0A.%29].%28[%7C*+++++++++%09cross+product+of+%22%29]%22+and+%22%28[%22%3B+this+produces+[%22%29%28%22,+%22%29[%22,+%22]%28%22,+%22][%22]%0A%7B++++++++++++++++%09begin+block+to+map+over+interval+delimiters%0A++E%22%60x,%60y%22a%2B%2B++++%09push+delimiters+separately,+then+wrap+them+around+the+inputs%09e.g.+%22%28-5,10%29%22%0A++c%22%28]%29[%22%7Ct++++++%09copy+last+value,+then+replace+parentheses+with+braces+++++++%09e.g.+%22]-5,10[%22%0A++ih%27%3D+++++++++++%09push+half+the+iteration+index+and+%22%3D%22+++++++++++++++++++++++%09e.g.+0+%22%3D%22%0A++%7C%3B%27%3D+++++++++++%09push+iteration+parity+%28alternating+0+and+1%29+and+%22%3D%22+++++++++%09e.g.+0+%22%3D%22+0+%22%3D%22%0A++%22%7B%60x%3C%60*x%3C%60*%60y%7D%22%09multiply+each+equal+sign+by+its+occurrence,+and+template++++%09e.g.+%22%7B-5%3Cx%3C10%7D%22%0A++c%27x.x%26%3AmR++++++%09copy+last+value,+then+replace+%22x%22+with+%22x%26%26x%22+++++++++++++++%09e.g.+%22%7B-5%3Cx%26%26x%3C10%7D%22%0A++yvih+xi%7Ce++++++%09calculate+final+bounds+offsets++++++++++++++++++++++++++++++%09e.g.+-5+1+10+-1%0A++%22%60%2B..%60%2B%22+++++++%09add+inputs+to+offsets,+and+embed+in+template++++++++++++++++%09e.g.+%22-4..9%22%0A++5l+++++++++++++%09combine+last+5+values+into+array%0Am++++++++++++++++%09map+[%22%29%28%22,+%22%29[%22,+%22]%28%22,+%22][%22]+using+block%0A%3A%3C+++++++++++++++%09left-align+grid+colums+to+add+extra+spaces%0Am%22+%3D+%22*++++++++++%09for+each+row,+join+with+%22+%3D+%22+and+output&i=-5+10&a=1) [Answer] # [Python 2](https://docs.python.org/2/), ~~277~~ ~~199~~ ~~193~~ 189 bytes ``` a,b=input() for i in 4,3,2,1:x,y=i%2,i>2;e='=';p=`a`+','+`b`;print'(['[x]+p+'])'[y],e,']['[x]+p+']['[y],e,2*('{%d<%s<%s%d} %s= '%(a,e*x+'%sx',e[y:],b,i/2*' '))%('','x&&')+`a+1-x`+'..'+`b-y` ``` [Try it online!](https://tio.run/##Rc2xCsIwGEXh3afIEm/S/FUbdbHGFwmBtFgxSxtshQTx2WsFQTjTWb6Yp/vQ63luqDWhj89JyNVteLDAQs8OtCdN1SlRNoFrChdddwYGdTS@8QoE5Vtfx0foJwgLm5yKCk7CZkcdwf2f/T1dCLz49czHJX59Mz4aBi4a6oqkwMcE6mw@OWopbHUBBim5wIKl9RpS@UZVZVr0zebLl9nPc3mkavcB "Python 2 – Try It Online") [Answer] # Excel, 399 bytes ``` ="("&A1&","&B1&") = ]"&A1&","&B1&"[ = {"&A1&"<x<"&B1&"} = {"&A1&"<x&&x<"&B1&"} = "&A1+1&".."&B1-1&" ["&A1&","&B1&") = ["&A1&","&B1&"[ = {"&A1&"<=x<"&B1&"} = {"&A1&"<=x&&x<"&B1&"} = "&A1&".."&B1-1&" ("&A1&","&B1&"] = ]"&A1&","&B1&"] = {"&A1&"<x<="&B1&"} = {"&A1&"<x&&x<="&B1&"} = "&A1+1&".."&B1&" ["&A1&","&B1&"] = ["&A1&","&B1&"] = {"&A1&"<=x<="&B1&"} = {"&A1&"<=x&&x<="&B1&"} = "&A1&".."&B1 ``` Nothing particularly interesting here. [Answer] # [C (gcc)](https://gcc.gnu.org/), 224 237 bytes ``` f(a,b,c,m,n,o){for(c=0;++c<5;printf("%c%d,%d%c = %c%d,%d%c = {%d<%sx<%s%d}%*s= {%d<%sx&&x<%s%d}%*s= %d..%d\n","[("[m],a,b,"])"[n],"[]"[m],a,b,"]["[n],a,"="+m,"="+n,b,o,"",a,"="+m,"="+n,b,o,"",a+m,b-n)){m=c%2;n=c<3;o=3-c/2;}} ``` [Try it online!](https://tio.run/##ddCxboMwEAbgPU9xcuUIw0ETokzGeRHqAc4lsRTsCmhUCfHsrsnQ0qGDrf//brDOlF@Jwot1dP8071CNk7G@uF12f@hu22ihSxpskbBHh17MnR8SUgeZZVSd5cdg3dQljBM3yA0nULDNMzcVH7/i4Wbh6fgj@/0WuSkKbt4cQ1YnrO41rm8yLVjtdDS9sfppDTLFsv55u@geGfsHI7S5E2LuFfFSOkXVSXp1yum1lMsS4gbQN9Yla2iGKyHQrRkgTWN5CJh3AGDjN8TRpRQQ0@TtWh/1UQuE31pqIeRuCSE/h@PhGw "C (gcc) – Try It Online") Moving the "<[=]" into the format string allowed me to remove the array altogether. Also, moving `printf()` into the `for` loop saved a semicolon. **Original answer** ``` f(a,b,c,m,n,o){char*e[]={"<=","<"};for(c=0;++c<5;){m=c%2;n=c<3;o=3-c/2;printf("%c%d,%d%c = %c%d,%d%c = {%d%sx%s%d}%*s= {%d%sx&&x%s%d}%*s= %d..%d\n","[("[m],a,b,"])"[n],"[]"[m],a,b,"]["[n],a,e[m],e[n],b,o,"",a,e[m],e[n],b,o,"",a+m,b-n);}} ``` [Try it online!](https://tio.run/##bZBNboMwEEb3nMJy5QjDQBOirIxzEdcLGENiKdgV0KgS4uyuqVSVSl3N@94s5geLG2J4sQ4fH6Yj9TQb68v7NfmjHraNLvRpAy0gDODA8wXvzZh1SsuF1pICrekqej@mKI8iz7G@CL4MElklnMT6LLw8F/haiffRurlPKUNmgBmGRJI9L7FOn2xiZmXZ9JMPh51ipiyZeXNxqkqpGjRsm1HNqXI6Or1z6ts10G2q27gFD5T@q/IB2sJxsa4hLkmGxrp0g2a8IZDtYpJlMTw5WRJCiI0/ia1rxUmk2dstPtVJcyC/sdKci2QNobiE0/EL "C (gcc) – Try It Online") There's nothing particularly noteworthy here: I used the usual tricks for shaving the size of the function (hoisting `int` autos into the function header, using K&R style, indexing into string constants.) Storing the {"<=","<"} into an array proved more size-efficient than inserting a format specifier for this challenge as it was used more than once. [Answer] # Javascript, ~~273~~ ~~258~~ 232 bytes Thanks Kevin Cruijssen for saving me 15 bytes ! ``` e=>f=>'(j)h]j[h{a<x<b} h{a<x&&x<b} hc..d\n[j)h[j[h{a<=x<b} h{a<=x&&x<b} ha..d\n(j]h]j]h{a<x<=b} h{a<x&&x<=b} hc..b\n[j]h[j]h{a<=x<=b}h{a<=x&&x<=b}ha..b'.replace(/a|b|c|d|h|j/g,m=>{return{a:e,b:f,c:e+1,d:f-1,h:" = ",j:e+","+f}[m]}) ``` [Try it online](https://tio.run/##TY1BDoMgAAS/wkkhRa2HXoj4EcsBEEwbBaO2aaK@3aKi7Wl3k53Mk795L7tHO0TGlmrRdFE01zQPIccCAQqYy8LlyLNPJmYAfA@Cc8o4Lu@m8EDxA@h@8f0gKOAbsBqYN7DDQE9g@/vpDGI3MG9gp2G9/Bn26QwijDvV1lwqmPBJTHIqkwo3NB87Nbw6M3KisCAaS6IuKS6JjtK5aNiMFmlNb2sV17aCGkY3BNMrQssX) Thanks for TFeld for giving me that idea, saving around 60 bytes from my original answer. **Ungolfed :** ``` e => f => '(j)h]j[h{a<x<b} h{a<x&&x<b} hc..d' + '\n[j)h[j[h{a<=x<b} h{a<=x&&x<b} ha..d' + '\n(j]h]j]h{a<x<=b} h{a<x&&x<=b} hc..b' + '\n[j]h[j]h{a<=x<=b}h{a<=x&&x<=b}ha..b' .replace(/a|b|c|d|h|j/g, m=>{ return {a:e,b:f,c:e+1,d:f-1,h:" = ",j:e+","+f}[m] } ) ``` --- # Javascript (original answer), 340 bytes ``` (a,b)=>alert(`(${a},${b}) = ]${a},${b}[ = {${a}<x<${b}} = {${a}<x&&x<${b}} = ${a+1}..${b-1}\n[${a},${b}) = [${a},${b}[ = {${a}<=x<${b}} = {${a}<=x&&x<${b}} = ${a}..${b-1}\n(${a},${b}] = ]${a},${b}] = {${a}<x<=${b}} = {${a}<x&&x<=${b}} = ${a+1}..${b}\n[${a},${b}] = [${a},${b}] = {${a}<=x<=${b}} = {${a}<=x&&x<=${b}} = ${a}..${b}\n`) ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 216 bytes ``` .+ $&()][<< ¶$&[)[[<=< ¶$&(]]]<<= ¶$&[][]<=<= ((.*),(.*))(.)(.)(.)(.)(<=?)(<=?)( *) $4$1$5 = $6$1$7 = {$2$8x$9$3}$10 = {$2$8x&&x$9$3}$10 = $2_$8..$3_$9 _<= \d+_ $&*___ T`<`_` _+<|\.-_+< ___< _ __< -1 _(_*) $.1 -0 0 ``` [Try it online!](https://tio.run/##TY5NCsIwEIX3c4oshpD0JyTVagsTvIS7NEwFXbhxIS4E9VoewIvFVEUKw/ce3@bN@XA5nnYuJVMCSqVjIBLi9UQZdAjk6dNVjJHIf30MMXsPSplCVxO0MrMjv/lBFBpwiQ5b4QWuclnncsMGuyv2uHigs38h5dxhw9gZgwvGHjivwbAvOb9YMDNsRxp5FFzSfTB1Dsg2AybWDljxNG0c1BZsSm3l7Bs "Retina – Try It Online") Explanation: ``` .+ $&()][<< ¶$&[)[[<=< ¶$&(]]]<<= ¶$&[][]<=<= ((.*),(.*))(.)(.)(.)(.)(<=?)(<=?)( *) $4$1$5 = $6$1$7 = {$2$8x$9$3}$10 = {$2$8x&&x$9$3}$10 = $2_$8..$3_$9 ``` Build up the main bulk of the result. ``` _<= ``` If the variable is involved in a loose inequality, then the value is inclusive, so we can delete the placeholder. ``` \d+_ $&*___ ``` Convert the value to unary and add 2. ``` T`<`_` _+<|\.-_+< ``` Remove the placeholder for a strict lower inequality or a negative strict upper inequality. It's still had 2 added, but 1 will be subtracted later, giving the desired result. ``` ___< _ ``` Subtract 2 from the other non-zero strict inequalities, restoring the original value, from which 1 will be subtracted later. ``` __< -1 ``` Change a strict upper inequality of `0` to `-1`. ``` _(_*) $.1 ``` Subtract 1 from the remaining strict inequalities and convert to decimal. ``` -0 0 ``` Fix up another edge case. [Answer] # Python 3, 180 bytes: ``` lambda a,b:[eval('f"'+"{%r[j]}{a},{b}{%r[i]} = "*2%('([',')]','][','[]')+"{{{a}<{'='[:j]}x%s<{'='[:i]}{b}}}{' '[i+j:]} = "*2%('','&&x')+'{a+j}..{b-i}"')for i in(1,0)for j in(1,0)] ``` ## explanation Basically builds an f-string that is evaluated in a list comprehension. Old-style `%` string interpolation is used to delay evaluating the expressions until the f-string is evaluated. ``` lambda a,b:[ eval( 'f"' + # f-string prefix "{%r[j]}{a},{b}{%r[i]} = "*2%('([',')]','][','[]') + # first two terms "{{{a}<{'='[:j]}x%s<{'='[:i]}{b}}}{' '[i+j:]} = "*2%('','&&x') + # second two terms '{a+j}..{b-i}"' # last term ) for i in(1,0)for j in(1,0) ] ``` The first part of the string, 'f"', will become the prefix for the f-string. The second part of the string builds the format string for the first two interval expressions. `%r` is used to save from needing to put quotes in the format, i.e., `"{%r[j]}"` is the same as `"{'%s'[j]}"`. When the f-string is evaluated, the correct bracket is selected. The third part of the string builds the next two interval expressions. The last part formats the "a..b" part of the f-string. The assembled f-string looks like: `f"{'(['[j]}{a},{b}{')]'[i]} = .... = {a+j}..{b-i}"` When the f-string is evaluated, all the expressions in braces `{}` are are replaced by their value. So, `{a}` gets replaced by the value of `a`, and `{'(['[j]}` gets replaced by `(` if j is 0 or `[` if j is 1. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 110 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` <ŗŗ}”⁴ "{ŗ<ŗx³ W}↔b ,e++Κ+² 4∫2\f»¹Aa{Ƨ[(²a{Ƨ[]²ba{ =*}eο+++:³⁴;³&&x⁴a_beh+H⁶;!+ƨ.+Κο++++}⁰№Iā;0E{┼ē4=‽"δY↑æ‘┼ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTNDJXUwMTU3JXUwMTU3JTdEJXUyMDFEJXUyMDc0JTBBJTIyJTdCJXUwMTU3JTNDJXUwMTU3eCVCMyUwQVclN0QldTIxOTRiJTIwJTJDZSsrJXUwMzlBKyVCMiUwQTQldTIyMkIyJTVDZiVCQiVCOUFhJTdCJXUwMUE3JTVCJTI4JUIyYSU3QiV1MDFBNyU1QiU1RCVCMmJhJTdCJTIwJTNEKiU3RGUldTAzQkYrKyslM0ElQjMldTIwNzQlM0IlQjMlMjYlMjZ4JXUyMDc0YV9iZWgrSCV1MjA3NiUzQiUyMSsldTAxQTguKyV1MDM5QSV1MDNCRisrKyslN0QldTIwNzAldTIxMTZJJXUwMTAxJTNCMEUlN0IldTI1M0MldTAxMTM0JTNEJXUyMDNEJTIyJXUwM0I0WSV1MjE5MSVFNiV1MjAxOCV1MjUzQw__,inputs=LTUlMEExMA__,v=0.12) [Answer] # Python 3, 248 bytes ``` def f(a,b): l=[['(',')','[','<',1],['[',']',']','<=',0]] r=[0,1] for i in r: for j in r: print(('%s%d,%d%s='*2+'{%d%sx%s%d}={%d%sx&&x%s%d}=%d..%d')%((l[j][0],a,b,l[i][1],l[1-j][2],a,b,l[i][2])+(a,l[j][3],l[i][3],b)*2+(a+l[j][4],b-l[i][4]))) ``` [Try it online!](https://tio.run/##TY89DsIwDIX3niJLcEzdqj@wIHISy0NRqCiq2qowgBBnLyYgxPDk9z5bjjPdr6dxqJclHFvTuoYOuEtM75nBAQGqWLUHKoU4evlq74EKkcTMngttJ6YdZ9OZbjCz7ojp/Etmmrvh6hzYiw1kg714WFcpPN729oZP//Gr1TfakOc2AFrnej4LF0J6H/XcCes1PZeZ0uqPVoKp/iFO1/JhWg@oL7kmjXyjOYudjSDi0rpsS2WByws) ]
[Question] [ The least common multiple (LCM) of a set of numbers `A` is the smallest integer `b` such that `b/a` is an integer for all integers `a` in `A`. This definition can be extended to rational numbers! # Task Find the smallest positive **rational** `b` such that `b/a` is an **integer** for all **rationals** `a` in the input. # Rules * Standard loopholes are forbidden. * You may take numerators and denominators separately in the input, but may not take doubles, floats, etc. * The input may not be fully reduced. * You may take integer inputs as rationals with denominator of `1`. * Submissions that would feed rational numbers to an LCM/GCD builtin are allowed, but non-competing. # Test Cases ``` In: 3 Out: 3 In: 1/17 Out: 1/17 In: 1/2, 3/4 Out: 3/2 In: 1/3, 2/8 Out: 1 In: 1/4, 3 Out: 3 In: 2/5, 3 Out: 6 In: 1/2, 3/4, 5/6, 7/8 Out: 105/2 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so submissions using the fewest bytes win! [Answer] # J, 3 bytes ``` *./ ``` Given a list of rational inputs, this folds LCM through it. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` g/:@$€Z©Ḣæl/;®Ḣg/$¤ ``` [Try it online!](https://tio.run/##y0rNyan8/z9d38pB5VHTmqhDKx/uWHR4WY6@9aF1QFa6vsqhJf8PtwOl/v@P5uKMjjbWMYyN1QGxDHUMzeFMo1gdoJQJnG8M5BvpWMD5JmB5mFYjHVMUPkK/TrSpjhmQNIfojQUA "Jelly – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` :g/æl/;g/}ɗ/ ``` [Try it online!](https://tio.run/##y0rNyan8/98qXf/wshx963T92pPT9f8fbv//PzraUEfBWEfBVEfBPFZHIdpIR8FER8FMR8EiNhYA "Jelly – Try It Online") Takes input as `[[list of numerators], [list of denominators]]`. [+2 bytes](https://tio.run/##y0rNyan8/z/KKl1f5fCyHH3rdP3ak9P1////Hx1tqKNgFKujEG2so2ACok11FMxAtLmOgkVsLAA) to take input as a list of `[numerator, denominator]` pairs ## How it works ``` :g/æl/;g/}ɗ/ - Main link. Takes a pair of lists [N, D] on the left / - Columnwise reduce by: g - GCD : - Divide, reducing the fractions to their simplest form ɗ - Group the previous 3 links into a dyad f(N, D): æl/ - LCM of N } - To D: g/ - GCD ; - Concatenate / - Reduce; Yield f(N, D) where N is the first list and D the second ``` The 14 byte version transposes the input with `Z` to get it into the `[N, D]` format, then uses `$` as a "grouping" construct the make the `:g/` act on that [Answer] # sed, 374 (373+1) bytes sed's `-E` flag counts as one byte. Note: I haven't tried to golf this yet, and probably won't for quite some time. Input is taken in unary, and output is in unary. Spaces must surround every fraction. Example: `echo " 1/111 111/11111 111111/111 "`. ``` :d;s, (1*)/\1(1*), \1/\22,;s,(1*)(1*)/\2 ,2\1/\2 ,;td;s,1*(1/22*),\1,g;s,(22*/1)1*,\1,g;:r;s,((1*)/1*)2,\1\2,;s,2(1*/(1*)),\2\1,;tr;h;s,1*/,,g;:g;s/^(1*) 1(1*) 1(1*)/1\1 \2 \3/;tg;s/ */ /g;s/^/ /;/1 1/bg;x;s,/1*,,g;s/^( 1*)( 1*)/\1\2\2/;:l;s/^(1*) (1*) \2(1*)/\1\2 \2 \3/;tl;/ $/be;/ /{s/^(1*) 1* 1*( 1*)/ \1\2\2/;bl};s/^(1* 1* )(1*) (1*)/\1\2\3 \3/;bl;:e;G;s, *\n *,/, ``` [Try it online!](https://tio.run/##XZDBasMwDIbvegoddkiMh5B6y85jL2F2CA3dILSjyaEw9urzftluwhqwhX79@iRnmY45D0daIncaeknqIXJSSWYRuue1ZByt6Bxp9RYNnYoZ/Enjyb1IRHsNVRiurpVmHIOYCtIgictoBBG0K30UnkRvA0revc6636JJGbPTQWh1B3MQluJFJFFWGU90AwjjHOQU9vW5Pg3DTGiYN3y5knX38safCfgnGSeP8r2tExin4rjxXsb5pwG93m/gOvBQgONMw0Rv/ptDOnOIEnNmVcXWhL318Wtqtey5C/Lgubs8bcV/5J1Raq2dG2Sn/V6@1s/LecnPr38 "sed – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 65 bytes ``` lambda x:reduce(lambda x,y:x*y/gcd(x,y),x) from fractions import* ``` [Try it online!](https://tio.run/##TcjLCsIwEEDRfb5ilkkZEFtfFLr1J7SLmDQayIsxQvL10YVKd/fcVPMjhr6Z6dqc9DctoYy06Jda@M9Yx9LVzV1p/mmBRTBD0YMhqbKN4QnWp0i5a266nL@TbxF6gfD3gLBbe49wWPuIcBIzY4lsyGC4E@0N "Python 2 – Try It Online") [Answer] ## JavaScript (ES6), 85 bytes ``` a=>a.reduce(([b,c],[d,e,g=(b,c)=>c?g(c,b%c):b,h=g(b*e,c*d),i=g(b*d,h)])=>[b*d/i,h/i]) ``` Look no builtins! No doubt someone will beat this using a recursive approach or something. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 30 bytes This only apply the `lcm` built-in on integers. ``` a->d=denominator(a);lcm(a*d)/d ``` [Try it online!](https://tio.run/##XcxLCoAgFIXheau4Qw3jkvaCqI1Eg0tWCGUi7d8iKMjh@Tj8jrzJVhcW6CBQ1utOz/bYjaXz8Ix4u007o1Rz1MF5Y0@2sEGNnCffyjGvI5ACFBYRKgESmwiL@/kjiWVMb09AiZWA@omECw "Pari/GP – Try It Online") --- # [Pari/GP](http://pari.math.u-bordeaux.fr/), 3 bytes This feeds rational numbers to the `lcm` built-in, so it is non-competing. ``` lcm ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D8nOfd/QVFmXolGmka0caymJhecZ6hvaI4mYKSjYKxvgiZorKNgpG@BJmgCVIkiZKRvii4EM09HwVTfTEfBHGzIfwA "Pari/GP – Try It Online") [Answer] # [Perl 6](https://perl6.org), ~~46~~ 42 bytes ``` {[lcm](@_».numerator)/[gcd] @_».denominator} ``` [test it](https://tio.run/##XZDPboJAEMbvPMUXQ3SpyAoqNhL/XHtq0vQmxiCshgQWskCjsfbFeuuL0V1EDp5m5rcz334zOROJW1cFw5drhZ6WXtAPs4hhWV@3SZjuyGb/92vxKmUiKDNh0O0pjHZoaMR4lsZc8VtdVAdEcZEnwWV0FEFYxhkH@QhUDBLoewNXDdAplpB6EfNUNcYPelS3eziD6DZWsA1Puykfm5IVpWxOYs4KYlgnwXKyfjHkx2GWHgiFHw2xHdCBSnZrUPUkP7REJh0RRwqpxT6ljKdJXxzDRtPTjplo5UcrEPgxz6vShM/OOQtLFuHuVZrwBSuqRNlQVyHfTaehrMcF7m8mHmNmS6z@8yHkSvUbXwAT7b0qFzJoTWlTe34nTfaAjokJnbat1On4xIRDX9uBjk7NZ1mHzjrmPqmamFHXxLzTGc@o8w8 "Perl 6 – Try It Online") ``` {[lcm](($/=@_».nude)[*;0])/[gcd] $/[*;1]} ``` [test it](https://tio.run/##XZBNb4JAEIbv/Io3huiiKyuo2Ej8uPbUpOkNiEFYDQkC4aPRWPvHeusfw11EDp5m5p3ZZ9@ZjOexVVcFx7elB7ZyuqAfpCHHqr46cXDyCFHZarv7/9OTKuSaM7QnnsacYxB6UJkoDe9WF9UeYVRksX8ZH3I/KKM0Afn0ZfRjqDsNVwViHis0HFtWE/yix1SjhzOIamANQ7OVm/SwLXlRiuE4SnhBNP2Y84xshpqwEaSnPWFwwxGcARvIxNuAyZb4UM/TMs2JKUByqS@BsRXhK8GoYdrKIc1b/HgNAjdKsqqkcPk540HJQzy8ChNuzosqljbkRchPM6lJ61GBR4/i@Yy2it5/PYRYqX5PlsBU@ajKpQhKUxrMWDyUJnuKJsWUzdpRZnb6lMJkb@2DTp3RV6zJ5p1mvVAp5syiWHScyZyZdw "Perl 6 – Try It Online") Input is a list of [Rational](https://docs.perl6.org/type/Rational) numbers. ## Expanded: ``` { # bare block lambda with implicit parameter list 「@_」 [lcm]( # reduce using &infix:<lcm> ( $/ = @_».nude # store in 「$/」 a list of the NUmerators and DEnominiators # ((1,2), (3,4)) )[ *; # from all of the first level 「*」, 0 # but only the 0th of the second level (numerators) ] ) / [gcd] $/[ *; 1 ] # gcd of the denominators } ``` [Answer] # [Retina](https://github.com/m-ender/retina), 117 bytes ``` \d+ $* \b(1+)(\1)*/(\1)+\b $#2$*11/$#3$* {`^((1+)\2*)/(1+)+ (\2)+/\3+\b $1 $#4$*1/$3 }`\G1(?=1* (1+))|\G 1+ $1 1+ $.& ``` [Try it online!](https://tio.run/##Hc2xCgIxDMbxPU8RaJCmBUPa83QRx3uJIOehg4vD4ab37LVx@fMNP/jWx/v5urVm9wyUwJaomaMpJ/FmW4BCoaQqFGoXn/ka3VhJLD4yRiucxeofK1IYuheqsM02abycNaFL/tqE2n8UvPtdayoFqwx4kBGPcvoB "Retina – Try It Online") Takes input as a space-separated series of improper fractions (no integers or mixed numbers). Explanation: ``` \d+ $* ``` Converts decimal to unary. ``` \b(1+)(\1)*/(\1)+\b $#2$*11/$#3$* ``` This reduces each fraction to its lowest terms. Capture group 1 represents the GCD of the numerator and denominator, so we count the number of captures before and after the `/`. `\b(1+)+/(\1)+\b` doesn't seem to count the number of captures correctly for some reason, so I use an extra capturing group and add 1 to the result. ``` {`^((1+)\2*)/(1+)+ (\2)+/\3+\b $1 $#4$*1/$3 ``` This does a number of things. Capture group 2 represents the GCD of the numerators of the first two fractions, while capture group 3 represents the GCD of the denominators. `$#4` is therefore the second numerator divided by their GCD. (Again, I couldn't could the number of captures of the first numerator, but I only need to divide one numerator by their GCD, so it doesn't cost me quite so much.) ``` }`\G1(?=1* (1+))|\G 1+ $1 ``` Now that the second numerator has been divided by their GCD, we just use this expression from the unary arithmetic tutorial to multiply the two together, resulting in the LCM. We then repeat the exercise for any remaining fractions. ``` 1+ $.& ``` Converts unary back to decimal. [Answer] # Common Lisp, 154 bytes ``` (defun f(l &aux(s(pairlis l l)))(loop(and(eval`(=,@(mapcar'car s)))(return(caar s)))(let((x(assoc(reduce'min s :key'car)s)))(rplaca x(+(car x)(cdr x)))))) ``` [Algorithm used](https://en.wikipedia.org/wiki/Least_common_multiple#A_simple_algorithm) (specified for integers, but works also for rationals). First make an associative list of the input data with itself, to get track of the initial values of the elements, so the operating sequence is given by the “car”s of the list. ``` (defun f(l &aux (s (pairlis l l))) ; make the associative list (loop (when (eval `(= ,@(mapcar 'car s))) ; when the car are all equal (return (caar s))) ; exit with the first one (let ((x (assoc (reduce 'min s :key 'car) s))) ; find the (first) least element (rplaca x (+ (car x) (cdr x)))))) ; replace its car adding the original value (cdr) ``` Test cases: ``` CL-USER> (f '(3)) 3 CL-USER> (f '(1/17)) 1/17 CL-USER> (f '(1/2 3/4)) 3/2 CL-USER> (f '(1/3 2/8)) 1 CL-USER> (f '(1/4 3)) 3 CL-USER> (f '(2/5 3)) 6 CL-USER> (f '(1/2 3/4 5/6 7/8)) 105/2 ``` Note: The solution is without the use of the builting `lcm` and `gcd`, that accept integers. [Answer] # [PHP](https://php.net/), 194 bytes ``` <?for(list($n,$d)=$_GET,$p=array_product($d);$x=$n[+$k];)$r[]=$x*$p/$d[+$k++];for($l=1;$l&&++$i;$l=!$l)foreach($r as$v)$l*=$i%$v<1;for($t=1+$i;$p%--$t||$i%$t;);echo$p/$t>1?$i/$t."/".$p/$t:$i/$t; ``` -4 Bytes with PHP>=7.1 `[$n,$d]=$_GET` instead of `list($n,$d)=$_GET` [Try it online!](https://tio.run/##JY3NasMwEITveYpUTIIVOwlK@kcVNYdiQi/tJTchjLHdWtTYYqOGFEJf3ZXdw8fuzuzsutr1u72r3XRSEXWUUeU68rb9jH7T7O39@PqScjlBdkiPSmsmWMK2gbvAAzOJZpvQ3QbuA4/MGNl/dBQ19uQjtAlKrsZwAqdyovwnc9SV30VwSy5xUWh1jC8jOUgbhcsCbo1y0OLYyOEWGiUkmvk8jmFDo27Q8GBUeVFHoGl@wpmjWSjYGc478R/ySozrbrZcwl@vg@kll1VRd8ML/yz2sKGu2JqtRuVpnGXf/wE "PHP – Try It Online") [Answer] ## Common Lisp, ~~87~~ 78 bytes Using `lcm` and `gcd`, which have integer inputs: ``` (defun l(a)(/(apply #'lcm(mapcar #'numerator a))(apply #'gcd(mapcar #'denominator a)))) ``` More golfed: ``` (defun l(a)(eval`(/(lcm,@(mapcar'numerator a))(gcd,@(mapcar'denominator a)))) ``` [Answer] # Mathematica, 3 bytes ``` LCM ``` Mathematica's built-in [`LCM` function](https://reference.wolfram.com/language/ref/LCM.html) is capable of handling rational number inputs. ]
[Question] [ We have a strictly increasing sequence of non-negative integers, like: ``` 12 11 10 ``` Wait! This sequence isn't strictly increasing, is it? Well, the numbers are written in different bases. The least possible base is 2, the biggest is 10. The task is to guess bases each number is written, so that: * the sequence is strictly increasing, * the sum of the bases is maximised. For instance, the solution for the sample will be: ``` 6 8 10 ``` because under those bases the sequence becomes `8 9 10` decimal - a strictly increasing sequence, and we are not capable of finding bases for which the sequence remains strictly increasing and whose sum is bigger than `6+8+10` . Due to the second limitation a solution `3 5 7` is not satisfactory: in spite of fact that the sequence becomes `5 6 7` under those bases - we need to maximise the bases sum, and `3+5+7 < 6+8+10`. If under no bases `2<=b<=10` is it possible for the series to be strictly increasing, for instance: ``` 102 10000 10 ``` single ``` 0 ``` should be output. The input sequence can be passed in the way it's most convenient for your solution (standard input / command line parameters / function arguments...). [Answer] # Pyth, ~~31~~ ~~30~~ 29 bytes ``` e+0f.x!sgM.:iVczdT2ZosN^STlcz ``` *1 byte thanks to @Jakube.* [Demonstration.](https://pyth.herokuapp.com/?code=e%2B0f.x!sgM.%3AiVczdT2ZosN%5ESTlcz&input=100+11+10+10&test_suite_input=12+11+10%0A10+10000+10%0A11+10+10+10%0A10+10+10+10+10&debug=0) [Test Harness.](https://pyth.herokuapp.com/?code=e%2B0f.x!sgM.%3AiVczdT2ZosN%5ESTlcz&input=100+11+10+10&test_suite=1&test_suite_input=12+11+10%0A10+10000+10%0A11+10+10+10%0A10+10+10+10+10&debug=0) Input is given on STDIN, space separated. If newline separated input is allowed, I can shorten the program by 2 bytes. Explanation: ``` e+0f.x!sgM.:iVczdT2ZosN^STlcz Implicit: z = input(), T = 10, Z = 0, d = ' ' ST [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] lcz len(z.split()) ^ All combinations w/replacement of that length. osN Order by increasing sum. f Filter on czd z.split(' ') iV T Vectorize the "Convert to base" operation over the integers as strings and the base sequence. .: 2 Take length 2 subsequences. gM Map the >= operation over them. !s Sum and logically negate. .x Z If that throws an error, returns 0 (e.g. reject) +0 Prepend a 0, in case no sequences are found. e Take the end of the list. ``` Including `1` in the list of possible bases is safe because `i`, which uses Python's `int` builtin, doesn't allow `1` as a base, and therefore always throws an error, which is caught and filtered out. [Answer] # CJam, 43 bytes ``` 0B,2>ea,m*{:+~}${ea::~_2$.b__Q|$=*@.b=}=p]; ``` Reads command-line arguments and prints an array. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q%3AE%3B%7BS%2F%7D%3AA%3B%20e%23%20Emulate%20the%20operator%20%60ea'%20as%20%60EA'.%0A%0A0B%2C2%3EEA%2Cm*%7B%3A%2B~%7D%24%7BEA%3A%3A~_2%24.b__Q%7C%24%3D*%40.b%3D%7D%3Dp%5D%3B&input=12%2011%2010). ### Examples ``` $ cjam rise.cjam 12 11 10 [6 8 10] $ cjam rise.cjam 19 18 17 0 ``` ### How it works ``` 0 e# Push a 0 (default return value). B,2> e# Push [0 ... 10] and remove the first two elements. ea, e# Push the number of command-line arguments (n). m* e# Cartesian power. Pushes all vectors of {2 ... 10}^n. {:+~}$ e# Sort by the negated sums. { e# Find; for each vector V in {2 ... 10}^n: ea::~ e# Evaluate each character of each command-line argument. _2$ e# Copy the results and V. .b e# Vectorized base conversion (list to integer). __ e# Push two copies. Q|$ e# Deduplicate and sort the last copy. = e# Compare it to the first. Pushes 1/0 if equal/unequal. * e# Repeat the original result of .b that many times. @.b e# Vectorized base conversion (integer to list). = e# Compare the result to the modified command-line arguments. e# Equality makes sure that the base was greater than all digits. }= e# If pushed 1, push V and break. p e# Print. Either prints the last V or 0 if none matched. ]; e# Clear the stack to avoid implicitly printing the 0 (if still present). ``` [Answer] # Julia, ~~176~~ ~~156~~ ~~145~~ ~~118~~ ~~109~~ ~~99~~ 97 bytes ``` A->try p=NaN;flipud(map(i->(k=11;t=p;while t<=(p=parseint("$i",k-=1))end;k),flipud(A)))catch;0end ``` Ungolfed: ``` function anonfunc(i) # Start with k=11 so that it evaluates to 10 on first while iteration k=11 # set t to the previous value of p # Note: p here gets held over between iterations within the map t=p # Iterate through, dropping k by 1 and evaluating the integer in # base k and stopping if the value drops below t # Note: "p=" expression inside conditional to ensure k-=1 is evaluated # at least once (to make NaN work as desired) while t<=(p=parseint("$i",k-=1)) end # if it dropped below t, return the base, k to be the corresponding # element in the map return k end function f(A) # Using try/catch to return 0 if no acceptable base found try # This is a trick to make sure the comparison in the while loop # evaluates to false on the first use of it (last value in A) p=NaN # Apply anonfunc to each element of A, starting with the last element # and store the result in S S=map(anonfunc,flipud(A)) # S is backwards, so flip it and return it return flipud(S) catch # Will throw to here if parseint fails with the base due to having # a digit not acceptable in the base return 0 end end ``` Used with a 1d array input. If the function is assigned to `c`, then you would call `c([12,11,10])` and it would output `[6,8,10]`. Note: I had used `dec(i)` inside the parseint command, but because `i` is a single-character variable name, and I don't need to access a component, I used `"$i"` to get the same result. [Answer] # Julia, ~~259~~ ~~204~~ 183 bytes Saved a bunch with help from Glen O. ``` A->(M(x)=maxabs(digits(x))+1:10;S=[];X={};for i=M(A[1]),j=M(A[2]),k=M(A[3]) s=map(parseint,map(dec,A),[i,j,k]);all(diff(s).>0)&&(S=[S,sum(s)];X=[X,{[i,j,k]}])end;X==[]?0:X[indmax(S)]) ``` Ungolfed + explanation: ``` function f(A) # Define a function to obtain the smallest possible base range M(x) = (maxabs(digits(x)) + 1):10 # Define container arrays for the sums and bases S = [] X = {} # Loop over all possible bases for each of the elements for i = M(A[1]), j = M(A[2]), k = M(A[3]) # Parse each element of the input as a string # in the given base s = map(parseint, map(dec, A), [i,j,k]) # Push the sum and bases if s is rising if all(diff(s) .> 0) S = [S, sum(s)] X = [X, {[i,j,k]}] end end # If X is empty, return 0, otherwise return the bases isempty(X) ? 0 : X[indmax(S)] end ``` [Answer] ## CJam (39 bytes) ``` {Afb:X,9,2f+m*{X\.b__$_&=*},{:+}$0\+W=} ``` This is an anonymous function which takes the input as an array of decimal integers on the stack and leaves the output as an array or the integer `0` on the stack. [Online demo](http://cjam.aditsu.net/#code=%5B19%2018%2017%5D%0A%0A%7BAfb%3AX%2C9%2C2f%2Bm*%7BX%5C.b__%24_%26%3D*%7D%2C%7B%3A%2B%7D%240%5C%2BW%3D%7D%0A%0A~%60). [Answer] ## Python 2 (147 bytes) ``` def x(s): q=int;c=10;o=q(s[-1])+1;l=[] for i in map(str,s)[::-1]: n=q(i,c) while o<=n: c-=1;n=q(i,c) if 3>c:return 0 l=[c]+l;o=n return l ``` Call the function `x` with a list of the ints. Example: ``` print x([12,11,10]) ``` prints ``` [6, 8, 10] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` ⁵ḊœċLḅI>0Pʋ@ƇDSÐṀḢ ``` [Try it online!](https://tio.run/##y0rNyan8//9R49aHO7qOTj7S7fNwR6unnUHAqW6HY@0uwYcnPNzZ8HDHov@H2x81rfn/P9rQSMfQUMfQIFYn2tAAyDYAAihXx1jHFEyb6xgZxQIA "Jelly – Try It Online") ## How it works ``` ⁵ḊœċLḅI>0Pʋ@ƇDSÐṀḢ - Main link. Takes a sequence S on the left ⁵ - 10 Ḋ - Dequeue; [2, 3, 4, 5, 6, 7, 8, 9, 10] L - Length of S œċ - Combinations with replacement D - Convert each in S to digits ʋ@ - Group the previous 4 links together into a dyad f(s, l): ḅ - Convert from base I - Forward differences >0 - Greater than 0? P - True for all? Ƈ - Filter the combinations over f(s, l) with the digits on the right SÐṀ - Take those with a maximal sum Ḣ - Take the first one or 0 if empty ``` ]
[Question] [ Arrr... Ahoy there, me maties! Unfurl tha' mainsail! Full to starboard! Ah, feel th' wind in yer hair! Right, me hearties... I be needin' a bit of yer codin' skills! Me crew are a li'l more modernized than meself... I still be preferrin' th' points of th' compass (see [here](http://en.wikipedia.org/wiki/Points_of_the_compass) for more info, Arrr...) while me crew are always usin' a headin'... I be wantin' an easy way of convertin' this twaddle they call a headin' into what I be able to understand, Arrr! What I be needin' is code tha' be takin' input of a number (decimals are okay) such tha' `0 <= the headin' < 360` and it be spittin' out th' answer as th' closest compass point! Arrr! Here be some examples: `> heading 0.1` `North` `> heading 11.25` `North by East` `> heading 22.7` `North Northeast` `> heading 44.99` `Northeast` `> heading 91` `East` Now, if'n th' headin' ye be givin' be such that it falls exactly in th' middle of two compass points, don' ye be frettin', me hearties... I be expectin' th' code to spit out `Between <point 1> and <point 2>`, e.g. `heading 5.625` will say `Between North and North by East` This only be happenin' for a headin' tha' be satisfyin' the equation `H = 5.625 + 11.25(N)` where H be th' headin' and N be an integer between 0 and 31 inclusive... Two restrictions tho'... 1) I not be wantin' ye to use arrays for storin' yer data for the points or th' headin's... Tha' be cheatin', sir, an' ye be gettin' a taste of me blunderbuss... This has t' be calculated, jus' like th' old days! Arrr! 2) Shortest code wins, or I'll be makin' ye walk th' plank... Arrr! [Answer] I be spendin' way too much time on this here treasure hunt, but here's a solution in **Java**: ``` public class Aaaaarrrr { public static void main(String[] aaarrrgs) { float heading = Float.parseFloat(aaarrrgs[0]); final List<String> points = Arrays.asList("North", "North by east", "North-northeast", "Northeast by north", "Northeast", "Northeast by east", "East-northeast", "East by north", "East", "East by south", "East-southeast", "Southeast by east", "Southeast", "Southeast by south", "South-southeast", "South by east", "South", "South by west", "South-southwest", "Southwest by south", "Southwest", "Southwest by west", "West-southwest", "West by south", "West", "West by north", "West-northwest", "Northwest by west", "Northwest", "Northwest by north", "North-northwest", "North by west"); float cp = heading / 360.0f * 32.0f; if (cp % 1 == 0.5f) System.out.print("Between " + points.get((int)Math.floor(cp)) + " and "); System.out.println(points.get(Math.round(cp))); } } ``` *edit* If I minimize the above code and make it real ugly it would become this: ## Java, 770 chars ``` import java.util.*;class A{public static void main(String[] r){List<String> l=Arrays.asList("North","North by east","North-northeast","Northeast by north","Northeast","Northeast by east","East-northeast","East by north","East","East by south","East-southeast","Southeast by east","Southeast","Southeast by south","South-southeast","South by east","South","South by west","South-southwest","Southwest by south","Southwest","Southwest by west","West-southwest","West by south", "West","West by north","West-northwest","Northwest by west","Northwest","Northwest by north","North-northwest","North by west");float c=Float.parseFloat(r[0])/360.0f*32.0f;if (c%1==0.5f) System.out.print("Between "+l.get((int)Math.floor(c))+" and ");System.out.println(l.get(Math.round(c)));}} ``` [Answer] ## Perl 5.10 using substitution, 231 228 226 224 ``` @c=(north,east,south,west); @q=qw(P PbR P-Q QbP Q QbR R-Q RbP); sub p{$j=$_[0]>>3&3;$_=$q[7&pop];s/P/$c[$j]/;s/Q/$c[$j+1&2]$c[$j|1]/;s/R/$c[$j+1&3]/;s/b/ by /;ucfirst} $a=<>/11.25+.5; say$a==int$a&&'Between '.p($a-1).' and ',p$a ``` Four newlines added for readability. **Edit:** Golfed 2 more bytes using `pop`. Thanks @Dom Hastings **Edit:** 2 bytes less using `qw()` [Answer] ## Python, 264 ``` n='north' e='east' s='south' w='west' b=' by ' def f(H):x,y,z=(n,e,s,w,e,s,w,n,n+e,s+e,s+w,n+w)[int(H%360/90)::4];return(x,x+b+y,x+'-'+z,z+b+x,z,z+b+y,y+'-'+z,y+b+x)[int(H%90*4/45)].capitalize() h=input()+5.625 print h%11.25and f(h)or'Between '+f(h-1)+' and '+f(h) ``` This uses capitalisation as per the wikipedia page and should work for any number. [Answer] ### Arrr Python, 336 ``` A,R,r=int,input()/360.*32,' by #South#north#West#East#south#North#west#east#-#/#Between#and'.split('#') a=''.join(r[A(c,16)]for c in'6A608A6928A6802A68A6808A4928A402A4A405A4958A1808A18A1805A1958A108A1A107A1957A1705A17A1707A3957A305A3A302A3927A6707A67A6702A6927A607').split('/') if R%1==.5:print r[11],a[A(R)],r[12], print a[A(round(R))] ``` Thanks @Jeen [Answer] ## Perl 5.10, 262 257 254 Somewhat similar to one of the Python solutions: ``` $n=north;$e=east;$s=south;$w=west; @d=($n,$n.$e,$e,$s.$e,$s,$s.$w,$w,$n.$w,$n); sub p{$j=pop;$i=$j>>2;ucfirst(($d[$i],"$d[$i] by $d[$i+2&~1]","$d[$i+1&~1]-$d[$i|1]","$d[$i+1] by $d[$i&~1]")[$j&3])} $a=<>/11.25+.5; say$a==int$a&&'Between '.p($a-1).' and ',p$a ``` Four newlines added for readability. **Edit:** Three bytes less thanks to @Dom Hastings ]
[Question] [ Given two positive integers **p** and **q**, your task is to return the array **A** created by applying the following algorithm: 1. Start with **A = [p, q]** and **d = 2** 2. For each pair **(x, y)** of contiguous numbers in **A** whose sum is divisible by **d**, insert **(x + y) / d** between **x** and **y**. 3. If at least one matching pair was found, increment **d** and go on with step #2. Otherwise, stop and return **A**. ## Example Below is the detail of the process for **p = 1** and **q = 21**. ``` 1 21 | Iteration #1: we start with d = 2 and A = [1, 21] \/ | 1 + 21 is divisible by 2 -> we insert 11 22/2=11 | | 1 11 21 | Iteration #2: d = 3, A = [1, 11, 21] \/ | 1 + 11 is divisible by 3 -> we insert 4 12/3=4 | | 1 4 11 21 | Iteration #3: d = 4, A = [1, 4, 11, 21] \/ | 11 + 21 is divisible by 4 -> we insert 8 32/4=8 | | 1 4 11 8 21 | Iteration #4: d = 5, A = [1, 4, 11, 8, 21] \/ \/ | 1 + 4 is divisible by 5 -> we insert 1 5/5=1 15/5=3 | 4 + 11 is divisible by 5 -> we insert 3 | 1 1 4 3 11 8 21 | Iteration #5: d = 6, A = [1, 1, 4, 3, 11, 8, 21] | no sum of two contiguous numbers is divisible by 6 | -> we stop here ``` Hence the expected output: **[1, 1, 4, 3, 11, 8, 21]** ## Clarifications and rules * Input and output can be handled in any reasonable format. The integers **p** and **q** are guaranteed to be greater than 0. If that helps, you may assume **q ≥ p**. * The 2nd step of the algorithm should ***not*** be recursively applied to elements that have just been inserted at the same iteration. For instance, **A = [1, 1]** and **d = 2** should lead to **[1, 1, 1]** (not an infinite list of 1's). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! ## Test cases ``` p | q | Output ----+-----+------------------------------------------------------------------------------- 1 | 1 | [1,1,1] 1 | 2 | [1,2] 1 | 3 | [1,1,2,3] 2 | 6 | [2,1,2,1,4,1,2,6] 3 | 13 | [3,1,8,1,3,1,7,1,2,1,5,1,3,2,13] 9 | 9 | [9,6,9,6,9] 60 | 68 | [60,13,1,4,31,2,3,5,2,19,64,7,13,1,2,5,2,27,44,3,4,8,2,1,12,1,5,3,28,2,4,16,1, | | 2,12,1,2,1,10,1,6,68] 144 | 336 | [144,68,3,4,8,1,12,1,4,2,28,13,128,44,17,92,240,58,108,5,17,1,2,5,3,28,3,1,11, | | 60,3,6,2,42,2,4,26,192,54,132,7,1,15,1,3,1,18,1,4,2,30,3,1,12,1,9,78,46,336] ``` If you'd like to test your code on a slightly bigger test case, [**here**](https://pastebin.com/6giBKNhC) is the expected output for: * **p = 12096** (26\*33\*7) * **q = 24192** (27\*33\*7) [Answer] # Mathematica, ~~72~~ ~~64~~ ~~59~~ 58 bytes ``` (d=2;#//.x_:>Riffle[x,(x+{##2,}&@@x)/d++]~Cases~_Integer)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPF1shaWV9fryLeyi4oMy0tJzW6QkejQrtaWdlIp1bNwaFCUz9FWzu2zjmxOLW4Lt4zryQ1PbVIU@1/QFFmXomCvoNCGoio5lIAgmpDHQXDWh042wiJbQxjG@komMHYxkD1cAlLHQVLGNvMAKjKAq7dxARogLFZLVftfwA "Wolfram Language (Mathematica) – Try It Online") ### How it works We take the input as a list `{p,q}`. The iteration step is reformulated as: 1. Insert `(a+b)/d` between *every* two elements `a` and `b`: `(x+{##2,}&@@x)` computes the sequence of `a+b`'s, with an `a+Null` at the end. We divide by `d`, and `Riffle` inserts each `(a+b)/d` between `a` and `b`. Increment `d`. 2. Pick out the `Integer` elements of the resulting list. (This gets rid of the `Null` introduced by `{##2,}`, too.) This is repeated until the result doesn't change (which can only happen because we removed all the new elements, because none of them were integers). *-8 bytes thanks to @MartinEnder from using `//.` instead of `FixedPoint` (and from taking input as a list).* *-6 more because `ListConvolve` actually isn't that great* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~28~~ ~~19~~ 18 bytes ``` [Ðü+NÌ/‚ζ˜ʒ.ï}DŠQ# ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/@vCEw3u0/Q736D9qmHVu2@k5pybpHV5f63J0QaAyUNbQyMDSTMfIxNDSKBYA "05AB1E – Try It Online") --- ~~eh, can definitely be improved hardcore. still working to refactor.~~ ~~Probably as good as I'm getting it.~~ ***-1 thanks to, who else but, Emigna! For pointing out swap worked better than the registers.*** --- ``` [ // Infinite loop. Ð // Triplicate [p, ..., q] U // Pop 1 of 3 copies into register X. ü+ // Pairwise addition. NÌ/ // Divide by current iteration + 2 (which is d). ‚ // Group original [p, ..., q] with pairwise additives. ζ˜ // Transpose together and flatten. ʒ.ï} // Filter out non-integer entities (includes the space added by zip). DXQ // Dupe result, see if equal to original. # // If new array is original array, nothing happened, quit & return. ``` --- Debug dump for `[p,q] = [1,3]`: ``` Full program: [ÐUü+NÌ/‚ζ˜ʒ.ï}DXQ# current >> [ || stack: [] ÐUü+NÌ/‚ζ˜ʒ.ï}DXQ# Full program: ÐUü+NÌ/‚ζ˜ʒ.ï}DXQ# current >> Ð || stack: [] current >> U || stack: [[1, 3], [1, 3], [1, 3]] current >> ü || stack: [[1, 3], [1, 3]] Full program: + current >> + || stack: [1, 3] stack > [4] current >> N || stack: [[1, 3], [4]] current >> Ì || stack: [[1, 3], [4], 0] current >> / || stack: [[1, 3], [4], 2] current >> ‚ || stack: [[1, 3], [2.0]] current >> ζ || stack: [[[1, 3], [2.0]]] current >> ˜ || stack: [[[1, 2.0], [3, ' ']]] current >> ʒ || stack: [[1, 2.0, 3, ' ']] Filter: .ï Full program: .ï current >> . || stack: [1] stack > [1] Full program: .ï current >> . || stack: [2.0] stack > [1] Full program: .ï current >> . || stack: [3] stack > [1] Full program: .ï current >> . || stack: [' '] invalid literal for int() with base 10: ' ' stack > [] current >> D || stack: [[1, 2.0, 3]] current >> X || stack: [[1, 2.0, 3], [1, 2.0, 3]] current >> Q || stack: [[1, 2.0, 3], [1, 2.0, 3], [1, 3]] current >> # || stack: [[1, 2.0, 3], 0] stack > [[1, 2.0, 3]] Full program: ÐUü+NÌ/‚ζ˜ʒ.ï}DXQ# current >> Ð || stack: [[1, 2.0, 3]] current >> U || stack: [[1, 2.0, 3], [1, 2.0, 3], [1, 2.0, 3]] current >> ü || stack: [[1, 2.0, 3], [1, 2.0, 3]] Full program: + current >> + || stack: [1, 2.0] stack > [3.0] Full program: + current >> + || stack: [3.0, 2.0, 3] stack > [3.0, 5.0] current >> N || stack: [[1, 2.0, 3], [3.0, 5.0]] current >> Ì || stack: [[1, 2.0, 3], [3.0, 5.0], 1] current >> / || stack: [[1, 2.0, 3], [3.0, 5.0], 3] current >> ‚ || stack: [[1, 2.0, 3], [1.0, 1.6666666666666667]] current >> ζ || stack: [[[1, 2.0, 3], [1.0, 1.6666666666666667]]] current >> ˜ || stack: [[[1, 1.0], [2.0, 1.6666666666666667], [3, ' ']]] current >> ʒ || stack: [[1, 1.0, 2.0, 1.6666666666666667, 3, ' ']] Filter: .ï Full program: .ï current >> . || stack: [1] stack > [1] Full program: .ï current >> . || stack: [1.0] stack > [1] Full program: .ï current >> . || stack: [2.0] stack > [1] Full program: .ï current >> . || stack: [1.6666666666666667] stack > [0] Full program: .ï current >> . || stack: [3] stack > [1] Full program: .ï current >> . || stack: [' '] invalid literal for int() with base 10: ' ' stack > [] current >> D || stack: [[1, 1.0, 2.0, 3]] current >> X || stack: [[1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3]] current >> Q || stack: [[1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3], [1, 2.0, 3]] current >> # || stack: [[1, 1.0, 2.0, 3], 0] stack > [[1, 1.0, 2.0, 3]] Full program: ÐUü+NÌ/‚ζ˜ʒ.ï}DXQ# current >> Ð || stack: [[1, 1.0, 2.0, 3]] current >> U || stack: [[1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3]] current >> ü || stack: [[1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3]] Full program: + current >> + || stack: [1, 1.0] stack > [2.0] Full program: + current >> + || stack: [2.0, 1.0, 2.0] stack > [2.0, 3.0] Full program: + current >> + || stack: [2.0, 3.0, 2.0, 3] stack > [2.0, 3.0, 5.0] current >> N || stack: [[1, 1.0, 2.0, 3], [2.0, 3.0, 5.0]] current >> Ì || stack: [[1, 1.0, 2.0, 3], [2.0, 3.0, 5.0], 2] current >> / || stack: [[1, 1.0, 2.0, 3], [2.0, 3.0, 5.0], 4] current >> ‚ || stack: [[1, 1.0, 2.0, 3], [0.5, 0.75, 1.25]] current >> ζ || stack: [[[1, 1.0, 2.0, 3], [0.5, 0.75, 1.25]]] current >> ˜ || stack: [[[1, 0.5], [1.0, 0.75], [2.0, 1.25], [3, ' ']]] current >> ʒ || stack: [[1, 0.5, 1.0, 0.75, 2.0, 1.25, 3, ' ']] Filter: .ï Full program: .ï current >> . || stack: [1] stack > [1] Full program: .ï current >> . || stack: [0.5] stack > [0] Full program: .ï current >> . || stack: [1.0] stack > [1] Full program: .ï current >> . || stack: [0.75] stack > [0] Full program: .ï current >> . || stack: [2.0] stack > [1] Full program: .ï current >> . || stack: [1.25] stack > [0] Full program: .ï current >> . || stack: [3] stack > [1] Full program: .ï current >> . || stack: [' '] invalid literal for int() with base 10: ' ' stack > [] current >> D || stack: [[1, 1.0, 2.0, 3]] current >> X || stack: [[1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3]] current >> Q || stack: [[1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3]] current >> # || stack: [[1, 1.0, 2.0, 3], 1] [1, 1.0, 2.0, 3] stack > [[1, 1.0, 2.0, 3]] ``` [Try it online with debug!](https://tio.run/##MzBNTDJM/f8/@vCE0MN7tP0O9@g/aph1btvpOacm6R1eX@sSEagMlDU0MdExNjaL/a@bAgA "05AB1E – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 80 bytes ``` ->a,d=2{*b=a[0];a.each_cons 2{|x,y|z=x+y;b+=z%d>0?[y]:[z/d,y]};b==a ?a:f[b,d+1]} ``` [Try it online!](https://tio.run/##bc7dCoIwFAfw@57iYHSTq9wmwynTBxkjNk26qsgE58ezmxqKQjcHdn7/c87epbF9LvpTrFEmSHM0QktPRfp80@n9mj4fBZCmrZBta1G5NjKuqA9Z7CXSqlDWlwxZ1UVGCA2JDnNpUOZi1fWv8lOAA4ChhV/dN7mUGAFWqnN2WycrJ3@crpxunEzOZicI2MbHScDLPB3ubxfwaQGfAxwBXzvzRmfB7MwbLgSrBPb9wShdvjA00PgeM/0X "Ruby – Try It Online") Recursive function `f` taking input as the array `[p, q]`. [Answer] ## Haskell, ~~85~~ 81 bytes ``` (a:b:c)#d=a:[div(a+b)d|mod(a+b)d<1]++(b:c)#d l#d=l l%d|l==l#d=l|e<-d+1=l#d%e (%2) ``` [Try it online!](https://tio.run/##XYpLCsMgFAD3nuJBKyhaqFlIkXiS4ML0GSp9@dCGrLy7/WTV7maGucXnPRHVKqLr3VUe0EfXYd5EVL3EMs64U2uCUmJfGL03YsSxkPdfKak9oTIf4YkNXvBG1jHmCTzgDAxgeeRphSMM0Bltwm9ptP0r9qztJdQX "Haskell – Try It Online") The input is taken as a list, e.g. `[1,2]`. Edit: -4 bytes thanks to @Laikoni. [Answer] # [Python 2](https://docs.python.org/2/), ~~112~~ ~~110~~ ~~108~~ ~~105~~ 103 bytes -2 bytes thanks to Jonathan Frech -5 bytes thanks to Erik the Outgolfer ``` y=input() x=d=1 while x!=y: d+=1;x=y;y=x[:1] for a,b in zip(x,x[1:]):c=a+b;y+=[c/d,b][c%d>0:] print x ``` [Try it online!](https://tio.run/##BcFBCsMgEADA@75ieygkKLQ2N2X7EfEQtSVCMRIM3e3n7UyTvu31MYZQqe3s0wxMmQx8t/J5IV9ILGBWZByTOCH21gTA937gqiOWir/SJtbsjQ2zTbSq6ESRT7esY/Dpmp93G6AdpXbkMfyi0SzhDw "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 98 bytes ``` f=lambda A,B=0,d=2:A*(A==B)or f(sum([[(l+r)/d,r][(l+r)%d>0:]for l,r in zip(A,A[1:])],A[:1]),A,d+1) ``` Invoke as `f([p,q])`. [Try it online!](https://tio.run/##JYxBCsMgEEWv4qYwNgONLoUpTK4hLlJEKhgj03TRXt4IWf3H4/Hb73jv1faeqKzbK66KcaEZI1nHd2CiRe@iEny@G3gPZRL9iCjhwlt8zi6kURQUlav65waM7I0LOox1JmhkjJPRvUmux7jyBu3Q/QQ "Python 2 – Try It Online") Jonathan Allan saved 12 bytes. Thanks~! ## Explanation `f` is a recursive function: `f(A, B, d)` evalutes to `f(next_A, A, d+1)`, unless `A == B`, in which case it returns `A`. (This is handled by `A*(A==B)or …`: if A ≠ B, `A*(A==B)` is the empty list, which is false-y, so the `…` part is evaluated; if A = B then `A*(A==B)` is `A`, which is non-empty and thus truthy, and it gets returned.) `next_A` is computed as: ``` sum([[(l+r)/d,r][(l+r)%d>0:]for l,r in zip(A,A[1:])],A[:1]) ``` This is best explained by example. When e.g. `d = 5` and `A = [1, 4, 11, 8, 21]`: ``` sum([[(l+r)/d,r][(l+r)%d>0:]for l,r in zip(A,A[1:])],A[:1]) = sum([[(1+4)/d, 4], [(4+11)/d, 11], [8], [21]], [1]) = [1] + [1, 4] + [3, 11] + [8] + [21] = [1, 1, 4, 3, 11, 8, 21] ``` [Answer] # [Python 2](https://docs.python.org/2/), 111 bytes ``` A=input() m=d=1 while m: m=o=0;d+=1 while A[o+1:]: o+=1;s=A[o-1]+A[o] if s%d<1:A[o:o]=s/d,;m=1;o+=1 print A ``` [Try it online!](https://tio.run/##JcpBCgIxDIXh9eQU2QhKRzTOrjWLnmPorsoUbFNsRTx9jbh6vI@/fvom5TKG51Tqq@8PkDkywXtLjxtmC5hZ@OyiUcS/@lUM2WBhElXXWOFIwegEmNId2y5eyeq1Erid4uyydr8Y6jOVjn6MdZmRlvAF "Python 2 – Try It Online") -8 thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod). -2 thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn). [Answer] # [Husk](https://github.com/barbuz/Husk), 22 bytes ``` →UG`λf£NΣẊṠeo/⁰+:.)⁰tN ``` Takes a 2-element list, returns list of integers and floats. [Try it online!](https://tio.run/##yygtzv7//1HbpFD3hHO70w4t9ju3@OGuroc7F6Tm6z9q3KBtpacJpEr8/v//H22sY2gcCwA "Husk – Try It Online") ## Explanation ``` →UG`λf£NΣẊṠeo/⁰+:.)⁰tN Input is a list L. G tN Cumulative reduce over the list [2,3,4.. ⁰ with initial value L `λ ) using flipped version of this function: f£NΣẊṠeo/⁰+:. Arguments are a list, say K=[1,3,3], and a number, say d=4. :. Prepend 0.5: [0.5,1,2,3] Ẋ For each adjacent pair, + take their sum, o/⁰ divide by d, Ṡe and pair it with the right number in the pair: [[0.375,1],[1.0,3],[1.5,3]] Σ Concatenate: [0.375,1,1.0,3,1.5,3] f£N Remove non-integers: [1,1.0,3,3] Now we have an infinite list of L threaded through 2,3,4.. using the expansion operation. U Take longest prefix of unique elements, → then last element of that. ``` [Answer] # [Perl 5](https://www.perl.org/), 92 + 1 (`-a`) = 93 bytes ``` do{$c=0;@n=shift@F;$.++;push@n,($t=$_+$n[-1])%$.?$_:($c=$t/$.,$_)for@F;@F=@n}while$c;say"@F" ``` [Try it online!](https://tio.run/##DcvRCsIgFADQX4lxgw2nuYc9LJHuk299QYSMtaEwVKYREf16t533k@Zt7Yke8QOTlgqDzs4vBY0CwZhKz@wwtDUUDZZBuPHu3hxBXMCe631AOYFowTZL3PaDRmP4vpxfZ5hUHt8VmopoOAy/mIqPIRO/9kJ2kvj4Bw "Perl 5 – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 111 bytes ``` \d+ $*1; ^ 11@ {+`(1+); (1+); $1; $1$2 $2; (?<=(?=(1+)).*) (\1)+ a$#2$*1; 1+ .*a 1$& )`a 1+@ 1+ $.& ; ``` [Try it online!](https://tio.run/##HYwxCsMwEAT7fcVBDqPTgWDVXoz9EBMsiAs3KUK6PF6J3Aw7LMz7@Jyv1vv2dGhm4AFyxdf3RLeQi1CGKLWK1kBa7nNa5vFYySZpo7lAmt7qSPwnh6PkBuoE2xtAXwegZUKgd0rlDw "Retina – Try It Online") Takes the input as space separated numbers. Quite naively follows the given algorithm, with the only notable technique being to use a marker symbol, `a`, to note when any of the numbers had been kept. This is used to work with Retina's somewhat limited looping capabilities, which only allows you to loop until a set of stages makes no overall change to the input to those stages. ### Explanation: This will use the same example as in the question. ``` \d+ $*1; ``` We change the input array of numbers into a semicolon separated unary array, so we'd have: ``` 1; 111111111111111111111; ^ 11@ ``` Put `d` into our code at the beginning, giving us: ``` 11@1; 111111111111111111111; {+`(1+); (1+); $1; $1$2 $2; ``` This is slightly more complicated. `{` starts a group of stages that will be executed until they reach a fixed point. Then, `+` indicates that this stage itself should be executed until a fixed point. This stage adds each pair of adjacent numbers but inserts them without the additional semicolon. Now we'd have: ``` 11@1; 1111111111111111111111 111111111111111111111; (?<=(?=(1+)).*) (\1)+ a$#2$*1; ``` The other tricky stage, this one accumulates our divisor in the first capture group, and replaces any number in our list without a trailing semicolon with that number divided by `d`. We also add a leading `a` to these numbers, to indicate that something was kept, along with the `;` to indicate it should be permanently part of the array. Now we'd have: ``` 11@1; a11111111111; 111111111111111111111; ``` ``` 1+ ``` This deletes numbers that were not divisible by `d` nor in the array before this round. This makes no changes in our example. ``` .*a 1&$ ``` This greedily matches from the beginning of the string to the last letter `a` in the input. This means there can be at most one match. If we made any changes, we add one to `d`, otherwise leaving it the same so we can exit the loop. ``` 111@1; a11111111111; 111111111111111111111; ``` ``` )`a ``` The `)` closes the loop started by `{` (don't question it!) and otherwise this stage just removes the markers we put down earlier. Since this is the end of the loop, we would repeat the above stages many times, however I'm just going to continue as though I had forgotten the loop, since it makes the example more continuous. ``` 111@1; 11111111111; 111111111111111111111; ``` ``` 1+@ ``` This stage removes from our output: ``` 1; 11111111111; 111111111111111111111; 1+ $.& ``` This stage replaces the unary numbers with decimal numbers: ``` 1; 11; 21; ``` ``` ; ``` The final stage gets rid of the semicolons: ``` 1 11 21 ``` Obviously, skipping out on the loop makes us have an incorrect result here, but hopefully that isn't too confusing. [Answer] # JavaScript (ES6), ~~89~~ ~~87~~ 82 bytes *Thanks [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for -2 bytes and for helping save 5 more bytes.* ``` f=(a,d=2,r)=>a.map(v=>b.push(v,...(v+=a[++i])%d<1?[r=v/d]:[]),b=i=[])|r?f(b,d+1):a ``` Takes input as an array: `f([p,q])`. ## Test Cases ``` f=(a,d=2,r)=>a.map(v=>b.push(v,...(v+=a[++i])%d<1?[r=v/d]:[]),b=i=[])|r?f(b,d+1):a ;[[1,1],[1,2],[1,3],[2,6],[3,13],[9,9],[60,68],[144,336],[12096,24192]] .forEach(test=>O.innerText+=JSON.stringify(test)+" -> "+JSON.stringify(f(test))+"\n") ``` ``` <pre id=O></pre> ``` [Answer] # [Röda](https://github.com/fergusq/roda), 90 bytes ``` f a,d=2{A=[a()|slide 2|[_,(_1+_)/d]if[(_1+_2)%d=0]else[_1]]+a[-1]f A,d=d+1 if[a!=A]else A} ``` [Try it online!](https://tio.run/##Rc1BCoMwEIXhtZ5iuigYnFITRWohC88RQggmAcFqMdmpZ7diSguz@BY/8@bJ6H13oNFwtrRc6IysfuiNBbYKhZmiuSJ3I3snTjNyNbyQdvBWKCplrsWNSgft8cDkFI5OX3h7BtBu@0v3IyxpEqwPqtPeenhyEGmSCIqMSoz6gUUwrCNKpGVUg01EXWD9@PZVhWVZyzQ57j33Y8iEy0JHJAE3zRA6OOb/2@m2fwA "Röda – Try It Online") [Answer] # Java 8, 180 bytes ``` import java.util.*;p->q->{List<Integer>r=new Stack();r.add(p);r.add(q);for(int d=1,f=d,i;f==d++;)for(i=1;i<r.size();i++)if((q=r.get(i)+r.get(i-1))%d<1)r.add(i++,q/(f=d));return r;} ``` **Explanation:** [Try it here.](https://tio.run/##lZBNT8JAEIbv/Iq5mOzadrFAiGZpjyYmmphwNB6WdosLZXe7nWKQ8NvroqXxZknm8Gbmma93I/YiMlbqTb5t1c4ah7DxOdagKtktB4DxGF6FT5sC8EPC6oAyykyjcTTKSlHX8CKUPo4AahSosj/tRaMzVEazx04snjTKtXThMOhZ1ZimkEECrY3SKkqP59QFSF2i5ScsUWRbQrljIs@JvYiK8sI4ojRCnsRhkeSh4kWS5EHA6U8liblaOFarL@nbVRBQVRBSJY6tJRJFg05EMaU3@SKmv4M9GFZj4gdSv0ti4zQ4fmq5t8CHbVald6EzY29UDjtvEFmiU3r99g6Cns0CWB5qlDtmGmTWl7DUJGPC2vJAYtqJiV/NB9NXwZNr4OkAeHKB5wPgaX/zkNEPtBf/w/O7/pD7IT/OZv2X0@700@jUfgM) ``` import java.util.*; // Required import for List and Stack p->q->{ // Method with two integer parameters and List return-type List<Integer>r=new Stack(); // Result-list r.add(p);r.add(q); // Add the two input-integers to the List for(int d=1, // Divisible integer (starting at 1) f=d, // Temp integer (starting at `d` / also 1) i; // Index-integer f==d++;) // Loop (1) as long as `f` and `d` are equal // (and raise `d` by 1 so it starts at 2 inside the loop) for(i=1; // Reset index-integer to 1 i<r.size();i++) // Inner loop (2) over the List if((q=r.get(i)+r.get(i-1)) // If the current + previous items (stored in `q`) %d<1) // are divisible by `d`: r.add(i++,q/(f=d)); // Insert `q` divided by `d` to the List at index `i` // (and raise `i` by 1 and set `f` to `d` in the process) // End of inner loop (2) (implicit / single-line body) // End of loop (1) (implicit / single-line body) return r; // Return the result-List } // End of method ``` [Answer] **C#, 280 bytes** ``` using System.Linq;class A{static void Main(string[] p){var l=new System.Collections.Generic.List<int>(p.Select(int.Parse));int r,d=2,c;do{c=0;for(int i=1;i<l.Count;++i){if((r=l[i-1]+l[i])%d==0){l.Insert(i++,r/d);++c;}}++d;}while(c>0);l.ForEach(v=>System.Console.Write((v+" ")));}} ``` First attempt at code golf, which is the whole program. [Test It](https://tio.run/##PY7BSgMxEIZfJRSEhGzjri29pFkQUREUhB48lD2EJLUDMamZdIss@@wxPehpZvi/@fgNLg2aUs4I4ZPsfjC7L/EK4VsarxHJ/YRZZzBkjGDJm4ZAMafK7gdyYtOoE/EquMvf60P03pkMMaB4dsElMFWHeQsh9/Qkdu4a03qJd53QMSbrTlJj1V1jpI2TUa08xHRFCKhOwtZX6zlkyTmwCQ6UJuX3sOwGXsfAbqxSLZu8eAnoUnVz3qRbyypv5DxzbuV8OYJ31PQtk148xfSozZGOqv9vHTB6Jz4SZEfpyBdkwWq1eS6ldOt1Wa02vw) **Attempt 2, 159 bytes** Taking away the scaffolding, since the task is to provide a function that can take a pair of numbers (an array works) and returns an array. Given that a Func<int[],int[]> *F* can be used to satisfy the requirements, just define *F*: ``` F=v=>{var l=new List<int>(v);int i,r,d=2,c;do{c=0;for(i=1;i<l.Count;++i){if((r=l[i-1]+l[i])%d==0){l.Insert(i++,r/d);++c;}}++d;}while(c>0);return l.ToArray();}; ``` [Test Full Program Here](https://tio.run/##XZJPa@MwEMXv/hRDYUHCjvOHvakOlEJKoQsLDewh5KCVJ82ALGUlOdkS/Nm9Y9el3V489vB7mnlPNnFmounbSO4Fnl9jwkZln7/Ke28tmkTexfIBHQYyX4gncn@@tLb4N6ksM1bHCHeJW6e0vfjsmkFMOpGBs6cafmhyIqbAyt0edHiJMgNmYD6H7RHh0LpxMjRtTKCNwRMXOGkK4A/g2uY3hghCOxYH/QqG347e1hMkQbsaAqY2MDFBJQBP2PDRt@TSbl@MzzVsVL@pztX6etYBbOXwAk8U0wCtxVkqrkBFKOpqVRhV@6upFurgg6BqqejWclKtSyrPSV7pIESo7I5my33OZS@/1VW1kFdbPrqIIQnK8yLMa8m8UV2X57XqLkeyKMx6IdW0sy23/m5YWkjVqf4tGOQs0ud03qIfWsY3DVueWXI45slOBzvkTm2CCv43NQDlMw7XK7hR/tQhopRqEgWMrU2RZRsxHvCxzMiwd9TmKD5YnvOuknDPf4y3WP4KlFBMQA43cCMV30CXdX2/XPWr7/8A) This could be smaller if a generic List is considered a valid output (drop the .ToArray() to save 10 bytes). If the input can also be modified, then passing in a List<int> instead of an array removes the need to initialize the output (comes out at 126 bytes). Taking this a step further, there doesn't really need to be a return value in this case. Using an Action instead removes the 9 bytes used by the return statement. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` ®‘©‘÷@+2\⁸żFfṀR$µÐL ``` [Try it online!](https://tio.run/##y0rNyan8///QukcNMw6tBBKHtztoG8U8atxxdI9b2sOdDUEqh7YenuDz//9/QxMTHQVjYzMA "Jelly – Try It Online") ]
[Question] [ ## Challenge **Peter has risen again to save us from the duplicate challenges!** ~~[Peter Taylor is dead](http://chat.stackexchange.com/transcript/240?m=24491073#24491073), and there's no doubt about it (well, apart from the huge amount of doubt we have... but just ignore that). In his memory,~~ you must write a program which determines whether a given user is alive or dead. ## Further Information A user is dead if they haven't been seen for more than a day, any less than that then they are alive. Check the last seen section found here: [![Location of last seen](https://i.stack.imgur.com/yE7Oe.png)](https://i.stack.imgur.com/yE7Oe.png) The input will be a user id (for example, mine is 30525, and Peter Taylor's is 194). Assume that all inputs are valid PPCG IDs. If the user is alive, you should output: ``` [User name] is alive! ``` Where you replace [User name] for their username *not* their user id. If the user is dead, you should output: ``` Sadly, [User name] is dead. ``` T-SQL entrants using the [SE Data Explorer](http://data.stackexchange.com/codegolf/query/new) are disallowed. ## Winning The shortest program in bytes wins. ## Leaderboard ``` var QUESTION_ID=59763;OVERRIDE_USER=30525;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Bash, 151 bytes ``` r="curl -L codegolf.xyz/u/$1";u=`$r|grep -Pom1 '(?<="User )[^"]*'` $r|grep -Pq '^[^>]*s="r.*(da|[A-Z])'&&echo "Sadly, $u is dead."||echo "$u is alive!" ``` As usual, [output to STDERR is ignored](http://meta.codegolf.stackexchange.com/a/4781). ### Example run ``` $ ./is-dead 30525 2>&- Beta Decay is alive! $ ./is-dead 44935 2>&- Sadly, Alpha Decay is dead. ``` ### Idea This code greps for lines containing `s="r` that do not have `>` before its occurrence. For example: ``` Last seen <span title="2015-09-17 12:00:00Z" class="relativetime">just now</span> ``` * If the match is followed by the string `da`, it contains the word `yesterday` or `days` (as in `2 days ago`). * If the match is followed by an uppercase letter, it contains the name of a month. * In all other cases, the user is ~~undead~~ alive. The user's name is extracted from a Twitter meta tag. Example: ``` <meta name="twitter:title" property="og:title" itemprop="title name" content="User Dennis"> ``` [Answer] # Javascript ES6, 234 bytes ``` document.write(`<script src="//api.stackexchange.com/users/${prompt(a=d=>{n=(x=d.items[0]).display_name,alert((Date.now()/1e3)-x.last_access_date>86400?`Sadly, ${n} is dead.`:n+' is alive!')})}?site=codegolf&callback=a">\x3C/script>`) ``` Annotated version ``` // Inserts a script tag to perform a JSONP callback request on the stackexchange API document.write(` <script src="//api.stackexchange.com/users/${ prompt( // interpolate user input into url a = d =>{ // declare a in global scope n = (x = d.items[0]).display_name, // alias the user object and name alert( (Date.now() / 1e3) - x.last_access_date > 86400 ? `Sadly, ${n} is dead.` // a day or less since last seen : n + ' is alive!' // more than a day since last seen ) } ) }?site=codegolf&callback=a">\x3C/script>` // escaping that prevents early termination of enclosing script tag ) ``` [Answer] ### PowerShell (v4), 228 217 209, 157 bytes ``` $u=($x=curl "codegolf.xyz/u/$args").BaseResponse.ResponseURI.Segments[-1] if($x-match'n <(.*?)((c|n|ur)s* ago|w)<'){"$u is alive!"}else{"Sadly, $u is dead."} ``` e.g. ``` PS C:\> test.ps1 30525 beta-decay is alive! C:\> test.ps1 67 Sadly, keith-randall is dead. #Previous 209 byte version: $f={$u=((curl "api.stackexchange.com/2.2/users/$($args)?&site=codegolf" )|ConvertFrom-Json).Items;$d=$u.display_name;if((get-date -U %s)- $u.last_access_date-gt86400){"Sadly, $d is dead."}else{"$d is alive!"}} ``` (Sorry, Keith Randall, you were just the first account I found with >1 day since last seen date). I was happy with the solid, reliable 209 byte one calling the API, but screen-scraping is the way to go for golf. * This now pulls the username from the redirected URI - but it is a name rather than a numeric ID, as required. * And it matches the line `Last seen <span title="2015-10-03 13:15:38Z" class="relativetime">2 days ago</span>` with `n <... [nr]s ago<` trying to catch sec(s) ago, min(s) ago, hour(s) ago, and just now, and miss "days weeks, months" ago, or the long term dates+times. And trying to catch 'last seen' and not the other relativetimes. (Thanks Dennis). NB. `curl` is a default alias for `Invoke-WebRequest`, it's not the standard curl program ported to Windows. [Answer] # R, ~~384~~ 350 bytes This one's for you, Peter! ``` u=scan();D=as.POSIXlt;J=jsonlite::fromJSON(gsub("/\\*\\*/a|[()]|;$","",httr::content(httr::GET(paste0("http://api.stackexchange.com/2.2/users/",u,"?site=codegolf&callback=a")),,"text")))$items;l=D(J$last_access_date,z<-"UTC","1970-01-01");n=D(Sys.time(),z);U=J$display_name;if(as.Date(n)-as.Date(l)>1)cat("Sadly,",U,"is dead.")else cat(U,"is alive!") ``` Note that this requires the `httr` and `jsonlite` packages to be installed, though they don't have to be imported for this code to work since we're referencing namespaces explicitly. Ungolfed: ``` # Read a user ID from STDIN u <- scan() # Create a request object using the SE API v2.2 request <- httr::GET(paste0("http://api.stackexchange.com/2.2/users/", u, "?site=codegolf&callback=a")) # Read the contents of the request into a ill-formed JSON string body <- httr::content(request, type = "text") # Parse out a valid string and get the associated fields J <- jsonlite::fromJSON(gsub("/\\*\\*/a|[()]|;$", "", body))$items # Get the last accessed date as a POSIX datetime object l <- as.POSIXlt(J$last_access_date, "UTC", "1970-01-01") # Get the current date n <- as.POSIXlt(Sys.time(), "UTC") # Extract the username U <- J$display_name # Determine whether the user has died if (as.Date(n) - as.Date(l) > 1) { cat("Sadly," U, "is dead.") } else { cat(U, "is alive!") } ``` Saved 5 bytes on my previous approach and corrected an error in my current approach thanks to minxomat! [Answer] # AutoIt, ~~320~~ ~~316~~ 308 bytes ``` #include<String.au3> #include<Date.au3> $0=_StringBetween $1=BinaryToString(InetRead('http://codegolf.xyz/u/'&ClipGet())) $2=_DateDiff('D',StringReplace($0($1,'Last seen <span title="',' ')[0],'-','/'),@YEAR&'/'&@MON&'/'&@MDAY) ConsoleWrite(($2?'Sadly, ':'')&$0($1,'r ','- P')[0]&'is '&($2?'dead.':'alive!')) ``` `_DateDiff` calcs the difference in days (`'D'`). It will be 0 if the difference is less than 1 day, so we can use it as a boolean value. The title tag of the "last seen" value contains a (almost) standard timestamp. [Answer] # CJam, 115 bytes ``` "codegolf.xyz/u/"r+g_N/{"s=\"r"/_0='>&!*1>s_"da"#)\_el=!|}#)"Sadly, %s is dead.""%s is alive!"?\"\"User "/1='"/1<e% ``` The idea is the same as in [my Bash answer](https://codegolf.stackexchange.com/a/59803), except that this answer doesn't use regular expressions, because CJam doesn't have regular expressions... The online interpreter doesn't perform web requests, so this will only work from the command line. [Answer] # Groovy, 355 bytes ``` import groovy.json.JsonSlurper;import java.util.zip.GZIPInputStream;def d = new JsonSlurper().parseText(new GZIPInputStream(new URL("http://api.stackexchange.com/2.2/users/${args[0]}?site=codegolf").newInputStream()).getText()).items[0];def n = d.display_name;println d.last_access_date*1000l<new Date().time-8.64E7?"Sadly, ${n} is dead.":"${n} is alive!" ``` Uncompressed source ``` import groovy.json.JsonSlurper; import java.util.zip.GZIPInputStream; def rawText = new GZIPInputStream(new URL("http://api.stackexchange.com/2.2/users/${args[0]}?site=codegolf").newInputStream()).getText() def json = new JsonSlurper().parseText(rawText).items[0] def name = json.display_name //We have to correct for java date returning in millis def lastAccess = json.last_access_date * 1000l def yesterday = new Date().time - 86400000 if (lastAccess < yesterday) { println "Sadly, ${name} is dead." } else { println "${name} is alive!" } ``` [Answer] # PHP, 187 bytes Fairly simplistic approach, using the codegolf.xyz domain, only slightly different item here is that I attempt to get both variables at once. Tested on a few users with correct results, please let me know if there are some problem areas though! ``` <?preg_match('/"User ([^"]+)".+?"([^"]+)" class="r/s',file_get_contents("http://codegolf.xyz/u/$argv[1]"),$m);echo time()-strtotime($m[2])<86400?"$m[1] is alive!":"Sadly, $m[1] is dead."; ``` Usage: ``` php 59763.php 30525 ``` ]
[Question] [ Your job is to generate a heightmap and show it as a parallel projected, voxel landscape. The rules are the following: * The (heightmap of the) landscape has to be randomly generated * You also have to *describe* how the algorithm you are using works, so everyone can learn something new here * You have to also either generate an image or display the generated landscape on the screen * The resulting image has to be paralell projected (so not perspective), and it can only contain voxels (so it has to be made out of small boxes) * This is a popularity contest, so you might want to add some additional features to your program to get more upvotes. * The winner is the most upvoted valid answer 7 days after the last valid submission. All valid submissions need to follow the rules, including the description of the used algorithm. You can add additional features which do not follow some of the rules (like adding a perspective mode), but in this case they have to be optional features (e.g. when turning them off the result should follow all of the rules) * My submission doesn't count as valid. An example result image is the following: ![voxel landscape](https://i.stack.imgur.com/WmTOC.jpg) [Image taken from here](http://pixelpaton.com/?p=3713) [If you need some algorithms check here](https://code.google.com/p/fractalterraingeneration/w/list) [Answer] # Python2 3D Function Plotter Voxel Edition This is my entry in this competition: ``` import math import random import Image terrain="" randA=(random.random()*4+5) randB=(random.random()*4+10) randC=(random.random()*4+1) randD=(random.random()*4+1) im = Image.new("RGBA", (1248, 1000), "black") tile=[Image.open("voxel/1.png"),Image.open("voxel/2.png"),Image.open("voxel/3.png"),Image.open("voxel/4.png"),Image.open("voxel/5.png"),Image.open("voxel/6.png"),Image.open("voxel/7.png"),Image.open("voxel/8.png"),Image.open("voxel/9.png")] for y in range (-40,40): for x in range (-10, 10): val=int(1+abs(4+2.5*(math.sin(1/randA*x+randC)+math.sin(1/randB*y+randD)))) if (val<9): terrain+=str(val) else: terrain+="9" print terrain for i in range (0,80*20): if((i/20)%2==0): shift=0 else: shift=-32 im.paste(tile[int(terrain[i])-1],((i%20)*64+shift,((i/20)*16-(32*(int(terrain[i])-1)))-32),tile[int(terrain[i])-1]) im.show() ``` As clearly stated in the title it works as a 3D function plotter, but since this competition requires the terrain to be randomly generated it this random sine function `1.5*(math.sin(1/randA*x+randC)+math.sin(1/randB*y+randD))` That depends on 4 random variables. This creates terrains like this: ![Random output](https://i.stack.imgur.com/t4kRE.png) We can ofcourse replace this random function by any 2 variable function, for example `sin(sqrt((x/2)²+(y/2)²))*3` gives this terrain: ![3Dfunction](https://i.stack.imgur.com/3xssG.png) and `-x*y*e^(-x^2-y^2)` gives this: ![3Dfunction2](https://i.stack.imgur.com/Ob1h4.png) (the plots on the right are computed by wolfram alpha) And while we're at it, Riemann zeta along the critical strip: ![Riemann zeta function](https://i.stack.imgur.com/dD0zv.jpg) For the people who aren't familiar with it, as you can see these pools of water (wich represent the zero's of the function) all lie on a straight line (real part = 0.5). If you can prove this, you will get $1000000! [See this link.](http://en.wikipedia.org/wiki/Millennium_Prize_Problems#The_Riemann_hypothesis) I hope you like it! [Answer] ## C#, WPF I have experimented with a [random walk](http://en.wikipedia.org/wiki/Random_walk), which works better than I had anticipated. I start somewhere on the map, walk to a random adjacent tile and increment its *height* value, then move to the next and so on. This is repeated thousands of times and eventually leads to a height map like this (100 x 100): ![magnified height map](https://i.stack.imgur.com/9Gge4.png) ![height map](https://i.stack.imgur.com/UP2qy.png) Then, I "discretize" the map, reduce the number of values to the given height levels and assign terrain/color based on that height: ![magnified terrain map](https://i.stack.imgur.com/bTPov.png) ![terrain map](https://i.stack.imgur.com/PtrNe.png) ![voxel terrain 1](https://i.stack.imgur.com/RwKUJ.png) More similar archipelago-like terrains: ![voxel terrain 2](https://i.stack.imgur.com/2LMPU.png) ![voxel terrain 3](https://i.stack.imgur.com/wVCxM.png) ![voxel terrain 4](https://i.stack.imgur.com/r3MPW.png) ![voxel terrain 5](https://i.stack.imgur.com/bf7St.png) Increased number of random steps and height levels to get more mountainous terrain: ![enter image description here](https://i.stack.imgur.com/ZKwWi.png) ![enter image description here](https://i.stack.imgur.com/hVEZ9.png) ![enter image description here](https://i.stack.imgur.com/BzQEM.png) ![enter image description here](https://i.stack.imgur.com/rcA9Y.png) ![enter image description here](https://i.stack.imgur.com/5foHD.png) --- ### Code Features: Recreate terrain with a button. Show 3D terrain and 2D map. Zooming (mouse wheel) and 3D scrolling (arrow keys). But it's not very performant - after all, this is written purely in WPF, not DirectX or OpenGL. MainWindow.xaml: ``` <Window x:Class="VoxelTerrainGenerator.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Voxel Terrain Generator" Width="550" Height="280" KeyUp="Window_KeyUp"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <Viewport3D x:Name="ViewPort" MouseWheel="ViewPort_MouseWheel"> <Viewport3D.Camera> <OrthographicCamera x:Name="Camera" Position="-100,-100,150" LookDirection="1,1,-1" UpDirection="0,0,1" Width="150" /> <!--<PerspectiveCamera x:Name="Camera" Position="-100,-100,150" LookDirection="1,1,-1" UpDirection="0,0,1" />--> </Viewport3D.Camera> </Viewport3D> <Grid Grid.Column="1" Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Image Grid.Row="0" x:Name="TopViewImage"/> <Button Grid.Row="1" Margin="0 10 0 0" Click="Button_Click" Content="Generate Terrain" /> </Grid> </Grid> </Window> ``` MainWindow.xaml.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Input; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Media.Media3D; namespace VoxelTerrainGenerator { public partial class MainWindow : Window { const int RandomSteps = 20000; const int MapLengthX = 100; const int MapLengthY = 100; const int MaxX = MapLengthX - 1; const int MaxY = MapLengthY - 1; const bool ForceIntoBounds = true; readonly Random Random = new Random(); readonly List<Color> ColorsByHeight = new List<Color> { Color.FromArgb(0, 0, 50), Color.FromArgb(170, 170, 20), Color.FromArgb(0, 150, 0), Color.FromArgb(0, 140, 0), Color.FromArgb(0, 130, 0), Color.FromArgb(0, 120, 0), Color.FromArgb(0, 110, 0), Color.FromArgb(100, 100, 100), }; public MainWindow() { InitializeComponent(); TopViewImage.Width = MapLengthX; TopViewImage.Height = MapLengthY; } public int[,] CreateRandomHeightMap() { var map = new int[MapLengthX, MapLengthY]; int x = MapLengthX/2; int y = MapLengthY/2; for (int i = 0; i < RandomSteps; i++) { x += Random.Next(-1, 2); y += Random.Next(-1, 2); if (ForceIntoBounds) { if (x < 0) x = 0; if (x > MaxX) x = MaxX; if (y < 0) y = 0; if (y > MaxY) y = MaxY; } if (x >= 0 && x < MapLengthX && y >= 0 && y < MapLengthY) { map[x, y]++; } } return map; } public int[,] Normalized(int[,] map, int newMax) { int max = map.Cast<int>().Max(); float f = (float)newMax / (float)max; int[,] newMap = new int[MapLengthX, MapLengthY]; for (int x = 0; x < MapLengthX; x++) { for (int y = 0; y < MapLengthY; y++) { newMap[x, y] = (int)(map[x, y] * f); } } return newMap; } public Bitmap ToBitmap(int[,] map) { var bitmap = new Bitmap(MapLengthX, MapLengthY); for (int x = 0; x < MapLengthX; x++) { for (int y = 0; y < MapLengthY; y++) { int height = map[x, y]; if (height > 255) { height = 255; } var color = Color.FromArgb(255, height, height, height); bitmap.SetPixel(x, y, color); } } return bitmap; } public Bitmap ToColorcodedBitmap(int[,] map) { int maxHeight = ColorsByHeight.Count-1; var bitmap = new Bitmap(MapLengthX, MapLengthY); for (int x = 0; x < MapLengthX; x++) { for (int y = 0; y < MapLengthY; y++) { int height = map[x, y]; if (height > maxHeight) { height = maxHeight; } bitmap.SetPixel(x, y, ColorsByHeight[height]); } } return bitmap; } private void ShowTopView(int[,] map) { using (var memory = new System.IO.MemoryStream()) { ToColorcodedBitmap(map).Save(memory, ImageFormat.Png); memory.Position = 0; var bitmapImage = new System.Windows.Media.Imaging.BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = memory; bitmapImage.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad; bitmapImage.EndInit(); TopViewImage.Source = bitmapImage; } } private void Show3DView(int[,] map) { ViewPort.Children.Clear(); var light1 = new AmbientLight(System.Windows.Media.Color.FromArgb(255, 75, 75, 75)); var lightElement1 = new ModelUIElement3D(); lightElement1.Model = light1; ViewPort.Children.Add(lightElement1); var light2 = new DirectionalLight( System.Windows.Media.Color.FromArgb(255, 200, 200, 200), new Vector3D(0, 1, -0.1)); var lightElement2 = new ModelUIElement3D(); lightElement2.Model = light2; ViewPort.Children.Add(lightElement2); for (int x = 0; x < MapLengthX; x++) { for (int y = 0; y < MapLengthY; y++) { int height = map[x, MapLengthY-y-1]; for (int h = 0; h <= height; h++) { Color color = ColorsByHeight[h]; if (height > 0 && h == 0) { // No water under sand color = ColorsByHeight[1]; } ViewPort.Children.Add(CreateCube(x, y, h, 1, System.Windows.Media.Color.FromArgb(255, color.R, color.G, color.B))); } } } } private ModelVisual3D CreateCube(int x, int y, int z, int length, System.Windows.Media.Color color) { List<Point3D> positions = new List<Point3D>() { new Point3D(x, y, z), new Point3D(x + length, y, z), new Point3D(x + length, y + length, z), new Point3D(x, y + length, z), new Point3D(x, y, z + length), new Point3D(x + length, y, z + length), new Point3D(x + length, y + length, z + length), new Point3D(x, y + length, z + length), }; List<List<int>> quads = new List<List<int>> { new List<int> {3,2,1,0}, new List<int> {0,1,5,4}, new List<int> {2,6,5,1}, new List<int> {3,7,6,2}, new List<int> {3,0,4,7}, new List<int> {4,5,6,7}, }; double halfLength = (double)length / 2.0; Point3D cubeCenter = new Point3D(x + halfLength, y + halfLength, z + halfLength); var mesh = new MeshGeometry3D(); foreach (List<int> quad in quads) { int indexOffset = mesh.Positions.Count; mesh.Positions.Add(positions[quad[0]]); mesh.Positions.Add(positions[quad[1]]); mesh.Positions.Add(positions[quad[2]]); mesh.Positions.Add(positions[quad[3]]); mesh.TriangleIndices.Add(indexOffset); mesh.TriangleIndices.Add(indexOffset+1); mesh.TriangleIndices.Add(indexOffset+2); mesh.TriangleIndices.Add(indexOffset+2); mesh.TriangleIndices.Add(indexOffset+3); mesh.TriangleIndices.Add(indexOffset); double centroidX = quad.Select(v => mesh.Positions[v].X).Sum() / 4.0; double centroidY = quad.Select(v => mesh.Positions[v].Y).Sum() / 4.0; double centroidZ = quad.Select(v => mesh.Positions[v].Z).Sum() / 4.0; Vector3D normal = new Vector3D( centroidX - cubeCenter.X, centroidY - cubeCenter.Y, centroidZ - cubeCenter.Z); for (int i = 0; i < 4; i++) { mesh.Normals.Add(normal); } } Material material = new DiffuseMaterial(new System.Windows.Media.SolidColorBrush(color)); GeometryModel3D model = new GeometryModel3D(mesh, material); ModelVisual3D visual = new ModelVisual3D(); visual.Content = model; return visual; } private void Button_Click(object sender, RoutedEventArgs e) { int[,] map = CreateRandomHeightMap(); int[,] normalizedMap = (Normalized(map, ColorsByHeight.Count-1)); ShowTopView(normalizedMap); Show3DView(normalizedMap); ToBitmap(Normalized(map, 255)).Save("heightmap-original.png"); ToBitmap(Normalized(normalizedMap, 255)).Save("heightmap.png"); ToColorcodedBitmap(normalizedMap).Save("terrainmap.png"); } private void ViewPort_MouseWheel(object sender, MouseWheelEventArgs e) { // Zoom in or out Camera.Width -= (double)e.Delta / 100; } private void Window_KeyUp(object sender, KeyEventArgs e) { // Scrolling by moving the 3D camera double x = 0; double y = 0; if (e.Key == Key.Left) { x = +10; y = -10; } else if (e.Key == Key.Up) { x = -10; y = -10; } else if (e.Key == Key.Right) { x = -10; y = +10; } else if (e.Key == Key.Down) { x = +10; y = +10; } Point3D cameraPosition = new Point3D( Camera.Position.X + x, Camera.Position.Y + y, Camera.Position.Z); Camera.Position = cameraPosition; } } } ``` [Answer] # JavaScript and Crafty.JS, to be much improved Here's a sample output: ![screenshot](https://i.stack.imgur.com/ElsU0.png) And here's the code (full webpage): ``` <!DOCTYPE html> <html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> <script type="text/javascript" src="http://craftyjs.com/release/0.4.2/crafty-min.js"></script> <script type="text/javascript"> $(document).ready(function() { Crafty.init(); var tilesize = 20 Crafty.sprite(20, "sprite.png#UPDATE", { grass1: [0,0,1,3], grass2: [1,0,1,3], grass3: [2,0,1,3], stone1: [3,0,1,3], stone2: [4,0,1,3] }); genTerrainInit() while(1) { try { stepTerrainGen() } catch(e) { break } } iso = Crafty.isometric.init(20); var z = 0; for(var i = tdata.length - 1; i >= 0; i--) { for(var y = 0; y < tdata[i].length; y++) { var which = Math.max(0, Math.round(tdata[i][y])) var tile = Crafty.e("2D, DOM, "+["grass1", "grass2", "grass3", "stone1", "stone2"][which]) .attr('z',i+1 * y+1) iso.place(i,y,0, tile); } } Crafty.addEvent(this, Crafty.stage.elem, "mousedown", function(e) { if(e.button > 1) return; var base = {x: e.clientX, y: e.clientY}; function scroll(e) { var dx = base.x - e.clientX, dy = base.y - e.clientY; base = {x: e.clientX, y: e.clientY}; Crafty.viewport.x -= dx; Crafty.viewport.y -= dy; }; Crafty.addEvent(this, Crafty.stage.elem, "mousemove", scroll); Crafty.addEvent(this, Crafty.stage.elem, "mouseup", function() { Crafty.removeEvent(this, Crafty.stage.elem, "mousemove", scroll); }); }); }); function genTerrainInit() { //Variables size = Math.pow(2, 6) + 1; //MUST be a power of 2 plus 1! initHeight = 2; rndRange = 4; smoothSpeed = 0.5; // lower is faster tdata = new Array(size); toAverage = new Array(size); for (var i = 0; i < size; i ++) { tdata[i] = new Array(size); toAverage[i] = new Array(size); for (var i2 = 0; i2 < size; i2 ++) { tdata[i][i2] = null; toAverage[i][i2] = false; } } //Generate corners tdata[0][0] = initHeight; tdata[size-1][0] = initHeight; tdata[0][size-1] = initHeight; tdata[size-1][size-1] = initHeight; } function stepTerrainGen() { //The square step - for each square, take the center point and set it to the average of its corners plus a random amount oldi = 0; for (var i = 1; i < size; i ++) { if (tdata[0][i] != null) { oldi2 = 0; for (var i2 = 1; i2 < size; i2 ++) { if (tdata[i2][i] != null) { pointDistance = (i - oldi)/2; tdata[(oldi2 + i2)/2][(oldi + i)/2] = ((tdata[oldi2][oldi] + tdata[i2][oldi] + tdata[oldi2][i] + tdata[i2][i])/4) // average of 4 corners + Math.random() * rndRange - (rndRange/2.0); // plus a random amount // Now mark the squares for the diamond step toAverage[(oldi2 + i2)/2][oldi] = true; toAverage[oldi2][(oldi + i)/2] = true; toAverage[(oldi2 + i2)/2][i] = true; toAverage[i2][(oldi + i)/2] = true; oldi2 = i2; } } oldi = i; } } //The diamond step - same as the square step but with newly formed diamonds for (var i = 0; i < size; i ++) { for (var i2 = 0; i2 < size; i2 ++) { if (toAverage[i][i2]) { diamondArray = []; if (i-pointDistance >= 0) diamondArray = diamondArray.concat(tdata[i-pointDistance][i2]); if (i+pointDistance < size) diamondArray = diamondArray.concat(tdata[i+pointDistance][i2]); if (i2-pointDistance >= 0) diamondArray = diamondArray.concat(tdata[i][i2-pointDistance]); if (i2+pointDistance < size) diamondArray = diamondArray.concat(tdata[i][i2+pointDistance]); addedPoints = 0; for (var i3 = 0; i3 < diamondArray.length; i3 ++) addedPoints += diamondArray[i3]; tdata[i][i2] = addedPoints/diamondArray.length + Math.floor(Math.random() * rndRange - (rndRange/2.0)); } } } rndRange *= smoothSpeed; resetToAverage(); } function resetToAverage() { for (var i = 0; i < size; i ++) { for (var i2 = 0; i2 < size; i2 ++) { toAverage[i][i2] = false; } } } </script> <title>Iso</title> <style> body, html { margin:0; padding: 0; overflow:hidden } </style> </head> <body> </body> </html> ``` Here is `sprite.png`: ![sprite.png](https://i.stack.imgur.com/jrqyk.png) Now, I have a few things to say. 1. Don't judge me for that terrible code! :P I wrote it many years ago when I was a terrible programming. In fact, it's from the old days of the website I had that I didn't even remember I had! <http://oddllama.cu.cc/terrain/> 2. I kind of sort of copied lots of code from the Crafty.JS [Isometric demo.](http://craftyjs.com/demos/isometric/) :P 3. Explanation will come soon! I have to go to sleep now since it's late here. (That's also why the sprite is so terrible!) Basically, it's really unpolished and it will be vastly improved later! It uses the same diamond-square algorithm mentioned in the OP's answer. [Answer] # Ruby + RMagick I'm using the [Diamond-Square](http://en.wikipedia.org/wiki/Diamond-square_algorithm) [algorithm](http://www.gameprogrammer.com/fractal.html) to generate the heightmap. The algorithm in short: * Use a wrapping array matrix, with a size of 2^n * Wrapping means that any index outside of the bounds wrap around, e.g. if the array's size is 4 `[0,0] == [4,0] == [0,4] == [4,4]`. Also `[-2,0] == [2,0]`, etc. * Set `[0,0]` to a random color * Follow the steps shown in the image. ![Explanation image](https://i.stack.imgur.com/qeKa9.png) * Note, that since the array wraps around, when you have to index something outside of the bounds, you can use the data from the other side of the array. * Also note, that in the very first step the four corners mean exactly the same value (as `[0,0] == [4,0] == [0,4] == [4,4]`) * To calculate the value of the black dot, you have to average the four points surrounding it * As this will result in a boring, gray image, you have to add a random number to this value at each step. It is preferred that this random value spans the whole range at the first iteration, but decreases over time when you are addressing smaller and smaller subsets of the array. The less this randomness decreases over time, the more noisy the image will be. * After I'm done I'm simply assigning a color for each height value. Code: **generate.rb** ``` #!/usr/bin/env ruby require 'rubygems' require 'bundler/setup' Bundler.require(:default) class Numeric def clamp min, max [[self, max].min, min].max end end class WrappedArray def initialize(size) @size = size @points = Array.new(size){Array.new(SIZE)} end def [](y,x) @points[(@size+y) % @size][(@size+x) % @size] end def []=(y,x,value) @points[(@size+y) % @size][(@size+x) % @size] = value.clamp(0,@size*@size-1) end end SIZE = 256 MAXHEIGHT = 256*256 points = WrappedArray.new(SIZE) points[0,0] = 0 s = SIZE d = [] sq = [] r = MAXHEIGHT while s>1 (0...SIZE).step(s) do |x| (0...SIZE).step(s) do |y| d << [y,x] end end while !d.empty? y,x = *d.shift mx = x+s/2 my = y+s/2 points[my,mx] = (points[y,x] + points[y,x+s] + points[y+s,x] + points[y+s,x+s])/4 + rand(r)-r/2 sq << [my,x] sq << [my,x+s] sq << [y,mx] sq << [y+s,mx] end while !sq.empty? y,x = *sq.shift points[y,x] = (points[y-s/2,x] + points[y+s/2,x] + points[y,x-s/2] + points[y,x+s/2])/4 + rand(r)-r/2 end s = s / 2 r = r * 2 / 3 end def get_color(height) val = height.to_f/MAXHEIGHT*3-1 r = 0 g = 0 b = 0 if val<=-0.25 Magick::Pixel.new(0,0,128*256) elsif val<=0 Magick::Pixel.new(0,0,255*256) elsif val<=0.0625 Magick::Pixel.new(0,128*256,255*256) elsif val<=0.1250 Magick::Pixel.new(240*256,240*256,64*256) elsif val<=0.3750 Magick::Pixel.new(32*256,160*256,0) elsif val<=0.7500 Magick::Pixel.new(224*256,224*256,0) else Magick::Pixel.new(128*256,128*256,128*256) end end canvas = Magick::ImageList.new canvas.new_image(SIZE+1, SIZE+1) 0.upto(SIZE) do |y| 0.upto(SIZE) do |x| canvas.pixel_color(x,y,get_color(points[y,x])) end end canvas.write('result.png') ``` **Gemfile** ``` source "https://rubygems.org" gem 'rmagick' ``` Note: The Imagemagick I'm using is 16bit Result image: ![result image](https://i.stack.imgur.com/JsDEA.png) Note: this image is a top-down, isometric representation, where the size of one voxel is exactly one pixel, so it's valid according to the rules (except one: that my answer is not considered valid) [Answer] # Java (using @fejesjoco's color-image as base algorithm) After playing a bit around with the FullRGB color images from @fejesjoco i noticed that they could be used as a base for interesting cliffy voxel landscapes. Instead of reimplementing the algorithm i used his code as a external executable (download it from <http://joco.name/2014/03/02/all-rgb-colors-in-one-image/> and place it named as artgen.exe in same directory ) Preview: ![Preview](https://i.stack.imgur.com/UVXLz.jpg) heightmap used (stored in blue channel) ![Heightmap](https://i.stack.imgur.com/KgNN5.png) Input image: ![Input](https://i.stack.imgur.com/KUEe4.png) The subalgorithm i use from it works in that way: 1. Sorting 2. Start with a black pixel at the center 3. Until all colors are used: place the current color at the closest fitting spot and add the unused neighbors as new usable spots When it finished i mangle it to get it reduced to 256 different values `red&(green|blue)` 4. then i use pregenerated sprites and generate the image layer by layer ``` import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStreamReader; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.imageio.ImageIO; import javax.xml.bind.DatatypeConverter; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author LH */ public class Voxelizer2 { static final String zipembeddedsprites = "UEsDBAoAAAA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AEl9Y0Q2U8gdJwEAACcBA"+ "AAJAAAAd2F0ZXIucG5niVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsT"+ "AAALEwEAmpwYAAAAB3RJTUUH3gMDDioRvrDDEQAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAi0lEQV"+ "RIx+2VQQ6AMAgEwd/Kg/juerEaUQJt8dY515nUJsAAKAMzPQ4CxKnvooAVW6KQG4jE2dAr0CuOQldgVuyFmAil4tcvItrPgBarxQYaW"+ "iL+uIFFp8SJQDYk2TeI0C7xQGCMjX5mBVagYNjd41qKx7Wys3AEFeLEyhTMiDuWvmBEnA54oUjcOAD4sVBwKhEKKQAAAABJRU5ErkJg"+ "glBLAQI/AAoAAAAAAJy4Y0RIepnubQEAAG0BAAAJACQAAAAAAAAAIAAAAAAAAABncmFzcy5wbmcKACAAAAAAAAEAGAD1dUScLDfPAeY"+ "u0WzuNs8B5i7RbO42zwFQSwECPwAKAAAAAADBuGNEZnqWnksBAABLAQAACQAkAAAAAAAAACAAAACUAQAAc3RvbmUucG5nCgAgAAAAAA"+ "ABABgAjxW2wyw3zwGyVc6t7jbPAbJVzq3uNs8BUEsBAj8ACgAAAAAASX1jRDZTyB0nAQAAJwEAAAkAJAAAAAAAAAAgAAAABgMAAHdhdG"+ "VyLnBuZwoAIAAAAAAAAQAYAM5emMbuNs8BrSG4se42zwGtIbix7jbPAVBLBQYAAAAAAwADABEBAABUBAAAAAA="; public static void main(String[] args) throws Exception { //embedded zip idea borrowed from over here: //http://codegolf.stackexchange.com/a/22262/10801 //algorithm and embedded executable borrowed from //http://joco.name/2014/03/02/all-rgb-colors-in-one-image/ //256 8192 2048 4096 1024 1000 9263 11111111 hue-0 one /**/ ProcessBuilder p = new ProcessBuilder("artgen","64","512","512","256","256","1",((int)(Math.random()*(2<<32)))+"","11111111","hue-0","one"); Process po = p.start(); BufferedReader x = new BufferedReader(new InputStreamReader(po.getInputStream()),1024); String xl = x.readLine(); //String x2l = x2.readLine(); while(!xl.startsWith("Press ENTER to exit")) { System.out.println(xl); xl=x.readLine(); } System.out.println(xl); po.destroy();/**/ BufferedImage source = ImageIO.read(new File("result00000.png")); BufferedImage heightmap = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB); for (int i = 0; i < source.getWidth(); i++) { for (int j = 0; j < source.getHeight(); j++) { int basecolor=source.getRGB(i, j)&0x00FFFFFF; int r = (basecolor&0x00FF0000)>>16; int g = (basecolor&0x0000FF00)>>8; int b = (basecolor&0x000000FF); int color = r&(g|b);//Math.max(r,Math.max(g,b)); heightmap.setRGB(i, j, color); } }/**/ ImageIO.write(heightmap, "png", new File("heightmap.png")); //generate sizedata for Sprites.... ZipInputStream zippedSprites = new ZipInputStream(new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(zipembeddedsprites))); ZipEntry z = zippedSprites.getNextEntry(); BufferedImage water=null,grass=null,stone=null,air = new BufferedImage(24,24, BufferedImage.TYPE_INT_ARGB); while(z!=null) { String name = z.getName(); switch(name) { case "water.png": water=ImageIO.read(zippedSprites); System.out.println("water"); break; case "stone.png": stone=ImageIO.read(zippedSprites); System.out.println("stone"); break; case "grass.png": grass=ImageIO.read(zippedSprites); System.out.println("grass"); break; } z=zippedSprites.getNextEntry(); } //int height = heightmap.getHeight()*12+12; int width16 = heightmap.getWidth()/16; int height16=heightmap.getHeight()/16; int widthtemp1 = 384+(height16-1)*(384/2); int width = (width16-1)*(384/2)+widthtemp1; //int heightt1=height16*(12*16)+12*16; int height = (width16-1)*(12*16)+(12*16); System.out.println(width*height); //if(true)return; int StartPos =heightmap.getHeight()*12; //BufferedImage[] layers = new BufferedImage[256]; BufferedImage complete = new BufferedImage(width, height+(255*12), BufferedImage.TYPE_INT_ARGB); int mergeOffset=255*12; for (int i = 0; i < 256; i++) { System.out.println("Rendering layer"+i); BufferedImage layer = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); int basePointerX = StartPos-12; int basePointerY=0; Graphics g = layer.getGraphics(); for (int k = 0; k < heightmap.getHeight(); k++) { //System.out.println("Processing line"+k); int pointerX = basePointerX; int pointerY = basePointerY; for (int j = 0; j < heightmap.getWidth(); j++) { Image tile = air; int pxheight =heightmap.getRGB(j, k)&0x00FFFFFF; if(pxheight>i) { tile=stone; } if(pxheight==i) { if(i<64) { tile=stone; } else { tile=grass; } } if(pxheight<i) { if(i<64) { tile=water; } else { tile=air; } } g.drawImage(tile, pointerX, pointerY, null); pointerX+=12; pointerY+=6; } basePointerX-=12; basePointerY+=6; } // complete.getGraphics().drawImage(layer, 0, mergeOffset, null); mergeOffset-=12; } ImageIO.write(complete, "png", new File("landscape.png")); } } ``` [Answer] # HTML + JavaScript Here is my attempt at the competition: ``` <html> <head> <script type='text/javascript' language='JavaScript'> function create() { var con = document.getElementById("can").getContext("2d"), map = new Array(), p = new Array(15 + Math.floor(Math.random() * 10)), tc = ["#000040", "#000070", "#0000a0", "#5050ff", "#f0f000", "#007000", "#00aa00", "#00c000", "#00e000", "#00ff00", "#90ff90", "#a0ffa0", "#c0ffc0", "#e0ffe0", "#f0fff0"], sc = ["#000020", "#000050", "#000085", "#3030df", "#d0d000", "#005000", "#008000", "#008000", "#00b500", "#00d000", "#00ea00", "#80ff80", "#a0ffa0", "#c0ffc0", "#d0ffd0"]; for (var n = 0; n < p.length; n++) { p[n] = [15 + Math.floor(Math.random() * 70), 15 + Math.floor(Math.random() * 70)]; } for (var x = 0; x < 100; x++) { map[x] = new Array(); for (var y = 0; y < 100; y++) { map[x][y] = 0; for (var n = 0; n < p.length; n++) { if (20 - Math.sqrt(Math.pow(x - p[n][0], 2) + Math.pow(y - p[n][1], 2)) > map[x][y]) { map[x][y] = 20 - Math.sqrt(Math.pow(x - p[n][0], 2) + Math.pow(y - p[n][2], 2)); } } } } for (var x = 0; x < 100; x++) { for (var y = 0; y < 100; y++) { if (map[x][y] < 0) { map[x][y] = 0; } map[x][y] = Math.floor(map[x][y] / 2); con.fillStyle = tc[map[x][y]]; con.fillRect(x * 10, y * 10 - map[x][y] * 4, 10, 10); con.fillStyle = sc[map[x][y]]; con.fillRect(x * 10, y * 10 - map[x][y] * 4 + 10, 10, map[x][y] * 4); } } } </script> </head> <body> <canvas id='can' width='1000' height='1000' style='border: 1px solid #000000;'></canvas> <button onclick='create();'>Create</button> </body> </html> ``` I use the Euclidean F1 [Cell Noise](https://code.google.com/p/fractalterraingeneration/wiki/Cell_Noise) algorithm to generate a heightmap which I then transform into an image by taking the appropriate colour from an array and drawing a square at 10x,10y-height so higher pixels are raised up. I then draw a rectangle as the side using the same colour from a different array. ![Cell Noise 1](https://i.stack.imgur.com/60A47.png) ![Cell Noise 2](https://i.stack.imgur.com/Mc9J7.png) Here is the same code using a 10,000-step random walk algorithm: ``` <html> <head> <script type='text/javascript' language='JavaScript'> function create() { var con = document.getElementById("can").getContext("2d"), map = new Array(), l = 10000, tc = ["#000040", "#000070", "#0000a0", "#5050ff", "#f0f000", "#007000", "#00aa00", "#00c000", "#00e000", "#00ff00", "#90ff90", "#a0ffa0", "#c0ffc0", "#e0ffe0", "#f0fff0"], sc = ["#000020", "#000050", "#000085", "#3030df", "#d0d000", "#005000", "#008000", "#008000", "#00b500", "#00d000", "#00ea00", "#80ff80", "#a0ffa0", "#c0ffc0", "#d0ffd0"]; for (var x = 0; x < 100; x++) { map[x] = new Array(); for (var y = 0; y < 100; y++) { map[x][y] = 0; } } x = 49; y = 49; for (var n = 0; n < l; n++) { var d = Math.floor(Math.random() * 4); if (d == 0) { x++ } else if (d == 1) { y++ } else if (d == 2) { x-- } else if (d == 3) { y-- } map[(x % 100 + 100) % 100][(y % 100 + 100) % 100]++; } for (var x = 0; x < 100; x++) { for (var y = 0; y < 100; y++) { if (map[x][y] < 0) { map[x][y] = 0; } map[x][y] = Math.floor(map[x][y] / 2); con.fillStyle = tc[map[x][y]]; con.fillRect(x * 10, y * 10 - map[x][y] * 4, 10, 10); con.fillStyle = sc[map[x][y]]; con.fillRect(x * 10, y * 10 - map[x][y] * 4 + 10, 10, map[x][y] * 4); } } } </script> </head> <body> <canvas id='can' width='1000' height='1000' style='border: 1px solid #000000;'></canvas> <button onclick='create();'>Create</button> </body> </html> ``` ![Random Walk 1](https://i.stack.imgur.com/bgqNs.png) ![Random Walk 2][4] When it 'walks' off one edge it wraps onto the other, so it still looks good tiled. It is still technically parallel, just from a different angle. ]
[Question] [ What general tips do you have for golfing in Raku? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Raku (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] Avoid `sub` literals. In many cases, you can simply use `{}` for code blocks. For example, don't write the following code. ``` sub ($a){$a*2} ``` Instead, use blocks syntax. This also lets you to use `$_`, `@_`, and `%_` placeholder variables, if you only need a single variable. If you need more, you can use `$^a`, `$^b` variables, and so on. ``` {$_*2} ``` Also, in certain rare cases, it's possible to use whatever code (especially when you have simple expressions). The `*` replaces the placeholder argument. ``` * *2 ``` [Answer] Raku has a really bizarre feature where it allows *all* Unicode characters in categories **Nd**, **Nl**, and **No** to be used as rational number literals. Some of these are shorter than writing their numeric values out in ASCII: * `¼` (2 bytes) is shorter than `.25` or `1/4` (3 bytes). * `¾` (2 bytes) is shorter than `.75` or `3/4` (3 bytes). * `৴` (3 bytes) is shorter than `1/16` (4 bytes). * `𐦼` (4 bytes) is shorter than `11/12` (5 bytes). * `𒐲` (4 bytes) is shorter than `216e3` (5 bytes). * `𒐳` (4 bytes) is shorter than `432e3` (5 bytes). [Answer] Learn the functions to read the input. Raku has many interesting functions that can easily read the input from ARGV, or STDIN (if nothing was specified on ARGV), which can shorten your code if used correctly. If you call them as filehandle methods, you can force them to work on particular filehandle (useful if you for example read from `STDIN`, but you have to read arguments on ARGV). # `get` This function gets a single line, and automatically chomps it, so you don't have to. This is useful if you need to read just a one line. # `lines` This function gets all lines from the file or STDIN. It's a lazy list, so if you use it with `for`, it will only read what you need. For example. ``` say "<$_>"for lines ``` # `slurp` This will read the entire file or STDIN, and will return the result as a single string. [Answer] **Warning**: Wall of text approaching. It's a lot of small tricks I gathered over time. # Write your solutions as anonymous blocks This was mentioned already but I'd like to reiterate it. In TIO, you can write `my $f =` into the header, the block into the code proper, and start the footer with a `;`. This seems to be by far the shortest way to get the job done (since you don't need to care about reading any input, it's given to you in the arguments). Another nice way is using the `-n` or the `-p` switch, but I didn't find a way to make it work in TIO. # Use the colon syntax for passing arguments That is, instead of `thing.method(foo,bar)`, you can do `thing.method:foo,bar` and save 1 character. Unfortunately, you can't call another method on the result for obvious reasons, so it makes sense to use only for the last method in a block. # Use `$_` as much as you can Sometimes it's better to take a single list argument than several separate arguments because of this. When accessing `$_`, you may call methods on it just by starting with a dot: e. g. `.sort` is equal to `$_.sort`. However, bear in mind that each block gets its own `$_`, so the parameters of the outer block won't propagate into the inner ones. If you need to access the parameters of the main function from an inner block, ... # Use the `^` variables if you can't use `$_` Insert a `^` between the sigil and the variable name, like this: `$^a`. These work only inside a block. The compiler first counts how many of these you have in the block, sorts them lexicographically, and then assigns the first argument to the first one, the second to the second one and so on. The `^` needs to be used only in the first occurrence of the variable. So `{$^a - $^b}` takes 2 scalars and subtracts them. The only thing that matters is the alphabetical order, so `{-$^b + $^a}` does the same thing. If you ever feel like using the pointy block syntax (like `->$a,$b {$a.map:{$_+$b}}`), you're far better off writing bogus statement at the start of the block using the `^` for each argument you're not going to use in the main block (like `{$^b;$^a.map:{$_+$b}}`) (Note that better way to golf this is `{$^a.map(*+$^b)}`. I just wanted to show off the concept.) # Read through the [operator docs](https://docs.perl6.org/language/operators) carefully The operators are very powerful and often they're the shortest way to get things done. Especially the meta-operators (operators that take operators as an argument) `[]`, `[\]`, `X`, `<<`/`>>` and `Z` are worth of your attention. Don't forget that a meta-op can take another meta-op as an argument (like a `XZ%%` I managed to use [here](https://codegolf.stackexchange.com/a/140803/30415)). You can use `>>` for a method call too, which can be a lot cheaper than a map (`@list>>.method` instead of `@list.map(*.method)`, but beware, *they're not same!*). And, finally, before you use a binary `<< >>`, bear in mind that `Z` will often do the same thing in much fewer characters. If you heap a lot of meta-ops onto each other, you can specify precedence using square brackets `[]`. That will save you when you pile up so many operators that it confuses the compiler. (That doesn't happen very often.) Finally, if you need to coerce things to Bool, Int or Str, don't use the methods `.Bool`, `.Int` and `.Str`, but rather the operators `?`, `+` and `~`. Or even better, just put them into an arithmetic expression to force them into Int and so on. The shortest way to get the length of a list is `+@list`. If you want to calculate 2 to the power of the length of a list, just say `2**@list` and it will do The Right Thing. # Use the free state variables `$`, `@` and `%` In each block, every occurence of `$` (or `@` or `%`) refers to a shiny new scalar (or array, or hash) state variable (a variable whose value persists across calls to the block). If you need a state variable that needs to be referenced *only once* in the source code, these three are your big friends. (Most often the `$`.) For instance, in the [Reverse Math Cycles](https://codegolf.stackexchange.com/a/142439/30415) challenge, it could be used to choose the operators cyclically from an array, which was indexed by `$++%6`. # Use the sub forms of `map`, `grep` et al. That means: do rather `map {my block},list` than `list.map({my block})`. Even if you manage to use `list.map:{my block}`, these two approaches come out at the same number of bytes. And often, you would need to parenthesize the list when calling a method, but not when calling a sub. So the sub approach comes out always better or at least the same as the method one. The only exception here is when the object which is to be `map`ped, `grep`ped and so on, is in `$_`. Then `.map:{}` obviously beats `map {},$_`. # Use junctions (`&` and `|`) instead of `&&` and `||`. Obviously, they are 1 byte shorter. On the other hand, they must be collapsed by being forced into a boolean context. This can be always done with a `?`. Here you should be aware of a meta-op `!`*`op`* which forces bool context, uses *`op`* and negates the result. If you have a list and you want to turn it into a junction, don't use `[&]` and `[|]`. Instead use `.any` and `.all`. There is also `.none` which cannot be so easily mimicked by the junction ops. [Answer] # Reduce the space used for variables There's a few parts to this. ### Remove whitespace Variables declared using `my` can usually be declared without the space between `my` and the variable name. `my @a` is equivalent to `my@a`. ### Use sigil-less variables You can declare variables using a backslash to remove the sigil before the variable name, like so: ``` my \a=1; ``` (unfortunately you can't remove the space :( ) This is useful as you can then refer to them as just the bare variable name later. ``` a=5; a.say ``` Basically this saves bytes if you use the variable more than once elsewhere in your code. The downside is that the variable needs to be initialised. ### Use `$!` and `$/` These pre-declared variables are usually used for exceptions and regex matches respectively, but don't need to be defined using `my`. ``` $!=1; $/=5; ``` Especially useful is using `$/` as an array and using the shortcuts `$` followed by a number to access that element of the `$/` array; ``` $/=100..200; say $5; #105 say $99; #199 ``` [Answer] ## Use `...` instead of `first` Typically, if you want to find the first number that matches some condition `&f`, you can represent it like: ``` first &f,1..* ``` However, instead you can use the `...` operator: ``` +(1...&f) ``` If you have to start from `0`, you can have `-1` afterwards instead of `+`. If you want the index of the first element in a list `@a` that has condition `&f`, normally you do: ``` first &f,@a,:k ``` Instead: ``` (@a...&f)-1 ``` (or vice-versa if you want 0 indexed). In the same way, you can get all the elements up to the first one that passes the condition. Downsides to this is that the list *has* to pass the condition at some point, otherwise the `...` operator will try to extrapolate off the end of the list, and most likely throw an error. You also can't use Whatever code in the left hand side, since it would be interpreted as part of the sequence. ]
[Question] [ [Sandbox](https://codegolf.meta.stackexchange.com/a/18273/78850) Have y'all ever written an answer with unprintable ASCII characters in it and wished that there was an easy way to represent those characters in a printable way? Well, that's why the [Control Pictures](https://unicode-table.com/en/blocks/control-pictures/) Unicode block was invented. However, manually substituting these characters into one's answer is time-consuming, so that's what today's challenge is about: swapping out the nasty invisible characters for nice, readable characters. ## Input You will be given strings that contain a mix of ASCII-only characters (i.e. the UTF-8 code point of each character will be in the range: \$0 \lt char \le 127\$). ## Output For all unprintable characters, replace it with its corresponding character in the Control Pictures Unicode range. In other words: * Characters in the range \$0 \lt char \lt 9\$ are replaced with their corresponding character * Horizontal tabs and newlines (9 and 10) *aren't* replaced * Characters in the range \$11 \le char \lt 32\$ are replaced with their corresponding character * Spaces (32) *aren't* replaced * The delete character (127) is replaced with its corresponding character: `␡` ## Tests *Characters are given as escapes for nice formatting here, but each character will be replaced with the unprintable character* ``` In -> Out \x1f\x1c\x1f\x1e\x1f\x1e\x1f\x1f\x1e\x1f\x1e\x1f -> ␟␜␟␞␟␞␟␟␞␟␞␟ Hello\x07World! -> Hello␇World! \x01\x02\x03\x04\x05\x06\x07\x08\x0c\x0b\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x7f -> ␁␂␃␄␅␆␇␈␌␋␎␏␐␑␒␓␔␕␖␗␘␙␚␛␜␝␞␟␡ \r -> ␍ ``` ## Rules * All standard loopholes are forbidden * Character substitutions *must* be made according to the Control Pictures Unicode block * Input will be given with the literal unprintable characters ## Scoring This is code-golf so the answer with the fewest amount of bytes wins. ## Test-Case Generator I have provided a test case generator for y'all. It prints inputs in the way they will be passed to your program and outputs the expected result. [Try it here!](https://tio.run/##XVJbbtswEPyWTrHwlxgzhin1lQDuEXqBwDAEmbYJ2JRAqYCav/QNNI9N2iZ9F73aXsTdtWwj7YewImd2Z2ek6kWzKH22Xk/tDJbJwUodQ5XXdSznufWTIq9tMnF@9Kz0Vh3HkVtVZWgg5H5aruKoboLzcxhBrxdHxSIPk2JRusLWfHViNKQaMg0PNDzU8EjDYw1PNBgGDCOG7w0DhhHDkBHsiJuG/Egzc1JuT5mXMi9lXsq8lHkp8zLmZZtZ0pyNuw020sUiJK2CWRmgBefh/mrjmG3MwJcNsDP2FAnNCY1tzW3CYzt/AynON4mID5X4j3aW@yMQkS2xG53cl1GK2SzA63QtcWSXtZUZ@9QYjqNtcKu8khwJzwhfEr4ifE34hvAt4TvC94TnhB8ILwmvCJHwmvCG8CPhJ8LPhLeEd4RfCL8SfiP8TviD8CfhL8LfhH8IL/gLtawwdUWTnLpqs2ytYScu@0oQcpYs2n827V4GwVbLfGtUQ3sidazEQ7DN8@DFEfShd/i0x2Xne/1fwGYoUVZBot3/ZUqt/wI "Python 3 – Try It Online") ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=196014; var OVERRIDE_USER=78850; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ``` body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ``` [Answer] # [Zsh](https://www.zsh.org/), ~~83 79~~ 78 bytes *-4 bytes by changing to a recursive solution, (-0 from bugfix,) -1 by abusing unquoted empty parameters expanding to 0 words* ``` <<<${1+"${(#)$((x=#1,x>126?x+9122:(x<9)^(x<11)^(x<32)?x+9216:x))}`$0 ${1:1}`"} ``` ~~[Try it online!](https://tio.run/##HY3BCsIwEETv@YqF5rBLpbArVBoT/RNBosV4sGAuwZJvj0kuMwxvmPnFV1mRsKzbFzyg3jEaQ5wpjq6GgTRicoM/pAvLfE3jwiIGk13oVpW521GoIeHZJKKsrLU6FlKqz26PJ4QP7DxNLKd8hnv0IYwO@0HDuVWhxnc97zSXPw) [Try it online!](https://tio.run/##ZY7BDoIwEETvfMUGemhDQ9yiNdSiH2IwEJSIRpoIhyrpt1fgiJfdZN7szH77u28oo15rTUZUMRlpxAilNo@Q2yMKebJxhkIoanXGLtNEXFYq2IwESmUZc2FJNjBHoCtD51kQNOYNtbneoO1gxCRBsXcHqPq6beOcLkUzdrN1uqQPpdhCz8hTLBwARDAYA6@q@8CU9uzBdDC0Zu1PBZdp4day3PJs9y9nkk@vFM7/AA "Zsh – Try It Online")~~ [Try it online!](https://tio.run/##ZY7BDoIwEETvfMUGemhDQ9yiNdSiH2IwEJSIRpoIhyrpt2PhiJfdZN7szH77@9RQRietNRkxDslII0YotXmE3B5RyJONMxRCUaszdvETcVmpYDMSKJVlzJVkAz5BoStDN7EgaMwbanO9QdvBiEmCYu8OUPV128Y5XXpm7Garv6QPpdhCz8hTLBwARDAYA6@q@4BPe/ZgOhhas/angsu0cGtZbnm2@5czyf0rhZt@ "Zsh – Try It Online") In arithmetic contexts, `#1` is the code of the first character of `$1`. We use it 7 times, so `x=#1,` saves us 2 bytes. There may be a more compact way to do `(x<9)^(x<11)^(x<32)`. The `${1+foo}` expands to `foo` *unless* `$1` is undefined, providing our recursive base case. The `"`$0 ${1:1}`"` is the actual recursive call. When an empty parameter is unquoted, it is removed from the word list, thus causing the final recursion be run with zero arguments. Running strings longer than about 35 characters with the recursive solution causes TIO to complain: "fork failed: resource temporarily unavailable". However, with usual resource limits on a desktop, there shouldn't be a problem. **Potential changes:** * With the flag `-oCPRECEDENCES`, `<` binds more tightly than `^`, which would save 6 bytes by removing parentheses. * With the flag `-oEXTENDEDGLOB`, we gain access to backreferences using `(#m)` and the `$MATCH` parameter. An approach like Arnauld's Javascript answer could be used, but it ends up being longer than the purely arithmetic approach. * I also tried a transliterate solution, but the larger codepoints of the control pictures grew the bytecount too quickly. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~67~~ 66 bytes *Saved 1 byte thanks to @Grimmy* ``` s=>s.replace(/[^ -~ \n]/g,c=>(B=Buffer)([226,144,B(c)[0]%94+128])) ``` includes a literal `TAB` [Try it online!](https://tio.run/##Dc69DoIwGIXhWa7iWwxf0wJCiD/BMuAlOCImTW0Rgy1p0cXorWOn551OzkO8hZdumObE2JtaNF88r33q1DQKqTBrr5D8VhfTZT2TvMaGNy@tlSPYFsWW5WXJGpSk3XTrQ0nzYt8Rsmjr0AOHOGZggnkVOAaLXShKCXwiAA@Uw3l2g@lT7ezzdBfuFE6gIVX0jaQ13o4qHW2PGn2Y/QM "JavaScript (Node.js) – Try It Online") ### How? We match all characters that are: ``` +-------> neither printable | +----> nor a tabulation | | +--> nor a linefeed / \ | | [^ -~\t\n] ``` and replace them with the UTF-8 sequence \$[226, 144, (n\bmod94)+128]\$, where \$n\$ is the ASCII code of the original character. This is equivalent to generating the code point \$(n\bmod94)+9216\$. But given the length of the corresponding JS method names, that would be ~~74~~ 73 bytes in plain ES6: ``` s=>s.replace(/[^ -~ \n]/g,c=>String.fromCharCode(c.charCodeAt()%94+9216)) ``` [Try it online!](https://tio.run/##bY5Ba8JAFITPza94FUp2iW6IlBaxK0gu3hU8NC0sm01MWd@TfYsX0b@e7sGTCAPfMDDD/JmzYRuGU5whtW7s9Mh6xSq4kzfWifL7F2a3lwZ/yn5q9Wobw4C96gId64MJdeoIq@zdrqOQb4v3YjGvPqQcOwqCQUOeTwETq2XCV@L8M7mikHDJABgKDc92US6za2YJmbxTnnrRCZbyIZlsnPfUxD0F3742uDsMDElIEWIwyOnF0bVgIhjv1ST9@gc "JavaScript (Node.js) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 119 109 108 89 75 bytes Thanks to ceilingcat and Arnauld for the suggestions. Like my original submission, the UTF-8 code sequence is largely hard-coded, but instead of using string literals an integer is used instead. This takes advantage of the fact that the LSB of an integer (on a little-endian processor) is the first byte stored in memory, and `0` MSB bytes map to `NUL` which terminates the string. For unprintable characters that map to the control pictures, three bytes are used to represent the value; one byte is used for everything else. One trick which I use is to force the comparison of a contiguous range of values to zero so that I can use unsigned comparisons. This wraps around any values below the range to high values, allowing me to use a single compare (the `d-9U>1`, which is true for x<9 or x>10.) ``` d;f(char*s){for(;d=*s++;printf(&d))d=d>126|d<32&d-9U>1?d%94<<16|8425698:d;} ``` [Try it online!](https://tio.run/##ZZBNT8JAEIbv/RVrjaS7BdMtUFq3xasH4o14EA9lp4UmlZJuURLgr1veKmqihyfzkX1mJqsHK63bllTu6HVaC8MPeVU7ihJhXFdt62LT5E6POKeEptIPjhQP/R4NovlU3tNNNIpjGRzDkT8OovCO1Km9Lja63FHGYtNQUd2up5aFKew1LTbOW1UQZweLsW4dE@b5JekqxuzFXuZAX2L2J/7r2f0v7yEry2qx9yZPVV3S1XcbHQl8MAQjMAZB9xKEAKu8JcA4rxvrATgSjoQj4Ug4Eo6EI@HICKRgeTmVfs@a/Jy0qC/Z43w2Q3LqMyGaxCgLxef/MtEott01xrFtzlnuiMZ1ubJO7YfOy3Rl2sH7GQ "C (gcc) – Try It Online") ## Original version (89 bytes) As C doesn't handle UTF-8 natively, I output the hard-coded prefix bytes and compute the trailing byte (which is the only byte that requires changing) if I need to print a control picture glyph. Other than that, it's a pretty standard string-processing function. ``` d;f(char*s){for(;d=*s++;printf(d>126|d<32&d-9U>1?"\xE2\x90%c":"%2$c",d%94+128,d));} ``` [Try it online!](https://tio.run/##ZZBNT8JAEIbv/RXrKqa7LaZTEKgL9WTigXgjHqyHskuhSaWkW5QE@evUt4qa6OHJfGSfmcnq7lLrpjEqc/UqraQV@6ysXGUm0nqe2lT5us5cE1M4eDfjXnhputEsplue7O7CZBcFHc1veCe80Nw3najvUTjyjRDq0Jzna11szYKNbW3y8moVOw6msZc0X7uvZW4E2zuMtWuZtE/Pk7ZiDJMpA/oUF3/ivx73v7z7RVGUyS4YPpZVYc6@2@gQwLFBD/TBNRi0L8EIYFUwBxgXtGMDAIfgEByCQ3AIDsEhOBSBFMxPp5rfs4Y/JyXVKXuYTadIDj6Tsp5Y5aD4/Gcma8U229q6nAvBMlfWnieUc2iOOivSpW26bx8 "C (gcc) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 69 bytes ``` lambda s:s.translate({i%128:i%34+9216for i in{*range(-1,32)}-{9,10}}) ``` [Try it online!](https://tio.run/##PYyxDsIgFAB3vwKHBtC2KcWobeLuH7h0QVvsMwgNMGgI344kRm@@u@XtZ6N5kqchKfG8jgK53tXeCu2U8BMJULD22EPBd9uuZXtpLAIEOmyycp9IxUre0liFrmRNjDQtFrQnkmBcPwxocpstAfrL0LfKS5pZ/eXzpJQZXs3hYqwa15jS9AE "Python 3 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~27~~ 24 bytes ``` T`-`␁-␟␡`[^ \n] ``` [Try it online!](https://tio.run/##VY5ZasJwGMSJu1bctS4xiQfIFXz2AIIPLkSoD4WgIL5LWjdQdLTVLlYlV5uLpOlfBMvAD@b7GGaGvdFzv@s4dUPS1bFBWDpxIWyj2Qm3@m3HUWVVcSWg6VVNvH8Ez3f8ZyO1nmkOgo3B0Hyq/IWEJ@bXS0TyeH3@QDAUfYjFE8lUOpPNPeYLxZJcVtTxtcQiXohXYkJMiZkbJhbEilgSa2JDgNgSO@KNeCf2xIH4ID6JL@KbOIqlp9s0@xc "Retina 0.8.2 – Try It Online") `T`ransliterates the unprintables to the appropriate control pictures, but the tabs and newlines are excluded (for a 3-byte saving). Note: No CRs in the test cases because I don't know how to demonstrate them in TIO. Code would probably work with nulls with the obvious adjustments for the same byte count, but I don't know how to test that either. [Answer] # [Red](http://www.red-lang.org), ~~94~~ 92 bytes ``` func[s][n: charset[not{ }#" "-#"~"]parse s[any[p: change n(to sp p/1 % 94 + 9216)| skip]]s] ``` [Try it online!](https://tio.run/##LctNCsIwGIThtTnFmCIoItIiSnsC125DFqVNtFi@hCQiUuvVY/92w8O8TtXxpmohmS4Q9Ysq4aWgAtWjdF4FQSZ0K9YnHPyQ8B@XdnR4UdJH2OlHdwXaBgNvYY8pNshP2CPP0vPuC/9srJReRqesKgMIaXYRsK4hoTFUnGNuSUo2chhoGdDorqptDXsb19brfnENPvFqZh7/ "Red – Try It Online") A port or @Arnauld's 74-byte [JavaScript solution](https://codegolf.stackexchange.com/a/196021/75681), don't forget to upvote his answer! [Answer] # [Perl 5](https://www.perl.org/) (`-pC -Mutf8`), 27 bytes same as Neil's retina solution ``` y;- -;␁-␈␋-␟␡ ``` [Try it online!](https://tio.run/##VY7LSsNQGISprbYk0tp6qdpL6lY4ZiUIATduunHtCzSCEExI2oWrEm8VlDpaq/VOXm0epKfHEwTlh/mZgWG@wA29XRnZLbG/s23bjjxzMqJgCqvvELEgbohb9b6JREqrbjXVaVGNls4/tH790X/WaLue5@eP/NDrbP2UtCcGaWJk5rK5@YV8YdEslpbKleWV1bXq@sZmrd5oWv10JCbOiQvikrgirlVZg90pNmJI3BMgHohHYkQ8EWPimXghJsQr8Ua8a9LPX7Rk6gfdE/80kiI4kOKw1z3emwE "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` 32R;Ø⁷’ḟ9ḟ⁵ż%94+⁽ ḥƊ$ỌFy ``` [Try it online!](https://tio.run/##AVQAq/9qZWxsef//MzJSO8OY4oG34oCZ4bifOeG4n@KBtcW8JTk0K@KBvSDhuKXGiiThu4xGef874oCcIC0@IOKAnTvDhwoxMjjhuLZzOOG7jMOH4oKsWf8 "Jelly – Try It Online") A monadic link taking a Jelly string and returning a Jelly string with the desired substitutions. [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, 36 bytes `\0` should really be a null byte but I was having trouble getting it in the code, oh well. Input in STDIN should be the direct bytes but I put in some boilerplate code to make it more readable and obvious that they were the test cases. ``` $_.tr!"\0- -","␀-␈␋-␟␡" ``` [Try it online!](https://tio.run/##ZY49CsJAEIVb0UO4GVK6Yce/aKG1N7BZCIkmEAgm5EdipaVgkxuIV8tBXF8gIGjx8Zhhv9mXV8HF2J7YiPDsJ8L2MDhlbpFWcjCS4ytNqG1usm3ubfNAPNvmRSarykLEkbAdsRVsSNccgUOf4U/@7WhIuzBJUl0rd5/mydHCBgODKZiBOViAZfcIrAA@UAHAEdUdUwAOw2E4DIfhMByGw3B4DXwQ9AWP3zJuV0Tn9E6zMk5PhZHZBw "Ruby – Try It Online") ]