text
stringlengths 180
608k
|
---|
[Question]
[
*This little piggy went to market, this little piggy wrote some code...*
Ah wait, we're not talking about *that* bacon, we're talking about Sir Francis Bacon! Specifically, [the cipher Bacon devised](https://en.wikipedia.org/wiki/Bacon%27s_cipher) in the [late 1500s](http://www.cabinetmagazine.org/issues/40/sherman.php), as a method of hiding a message within another message, a method of [steganography](https://en.wikipedia.org/wiki/Steganography).
The cipher works by concealing the message in the **presentation** of text, rather than its content. First, the letters of your message are encoded into binary (from 0 to 25) as follows:
Note: Please use the following encoding in your code and do not worry about numbers, spaces, or other symbols in the input, though I may devise some bonus for those who include these characters in their encoding. If you do include other symbols, the letters must still occupy spaces 0-25 in the encoding.
```
Letter Encoding
A AAAAA
B AAAAB
C AAABA
D AAABB
E AABAA
F AABAB
G AABBA
H AABBB
I ABAAA
J ABAAB
K ABABA
L ABABB
M ABBAA
N ABBAB
O ABBBA
P ABBBB
Q BAAAA
R BAAAB
S BAABA
T BAABB
U BABAA
V BABAB
W BABBA
X BABBB
Y BBAAA
Z BBAAB
```
Having encoded all of the letters in your message into the `A`s and `B`s above, you must now select two **typefaces** for your code. For this example, I will use normal text for typeface `A` and **bold text** for typeface `B`.
So the message
```
HELLOWORLD
```
is encoded to
```
AABBB AABAA ABABB ABABB ABBBA BABBA ABBBA BAAAB ABABB AAABB
```
And now we conceal this binary with a **carrier text**.
>
> The quick brown fox jumps over the lazy dogs, gamboling in the fields where the shepherds keep watch.
>
>
>
It is alright if the carrier message is longer than the actual encoded message, though it cannot be shorter. Now we turn the carrier text into bold according to where the `B`s are in the encoded message,
>
> Th**e** **qu**ic**k** bro**w**n **fo**x **j**u**mp**s **ove**r **t**h**e** **l**az**y** **do**g**s**, gam**b**o**l**i**ng** in t**he** fields where the shepherds keeps watch.
>
>
>
Which without Markdown reads as
```
Th**e** **qu**ic**k** bro**w**n **fo**x **j**u**mp**s **ove**r **t**h**e** **l**az**y**
**do**g**s**, gam**b**o**l**i**ng** in t**he** fields where the shepherds keeps watch.
```
Note that I did not use the punctuation in the carrier message to encode the message, but whether the punctuation is encoded or not is up to you/.
**Rules**
* Your input will be the message you to be encoded and a carrier message. If the carrier message is too short, return some sort of error message.
* You must select two typefaces for encoding `A` and `B`, such as UPPERCASE, lowercase, *italic*, **bold**, ***bold italic***, ~~strikethrough~~, `in code format` and so on. You must use Stack Exchange's form of Markdown to encode these typefaces, i.e.
```
UPPERCASE, lowercase, *italic*, **bold**,
***bold italic***, <s>strikethrough</s>, `in code format`
```
* Your output must be your now-encoded carrier message, either shown with Markdown or shown without, as seen in the above example.
* You are only required to make an encoding algorithm. Any decoding algorithms you wish to provide are welcome, but **at time of writing** will not help or hinder your score.
* Your code must be a program or a function.
* This is code golf, so the smallest number of bytes wins.
As always, if the problem is unclear, please let me know. Good luck and good golfing!
[Answer]
## Pyth, 47 bytes
```
Vsm.[05jxGd2r~zw0#I}Jr@z~Z+1Z0GBpJ)p?NrJ1J;>zZ
```
Try it [here](http://pyth.herokuapp.com/?code=Vsm.%5B05jxGd2r%7Ezw0%23I%7DJr%40z%7EZ%2B1Z0GBpJ%29p%3FNrJ1J%3B%3EzZ&input=HELLOWORLD%0AThe+quick+brown+fox+jumps+over+the+lazy+dogs%2C+gamboling+in+the+fields+where+the+shepherds+keep+watch.&debug=0).
Explanation:
```
~zw - Get the first line of input and
- set z to the next line
r 0 - Turn it to lower case
m - Map each character
xGd - Get it's position in the alphabet
j 2 - Turn it to base 2
.[05 - Pad the start with 0's
s - Turn it to a 1d-array (flatten it)
V ; - For N in above array:
# ) - While 1:
@z~Z+1Z - Get the current position in the
- second line and increment the position
Jr 0 - Set J to it lowercased
I} GB - If it's a letter, break
pJ - Otherwise, print it
?N - Is the character code
- (the current 1d-array) 1
rJ1 - Get the current char uppered
J - Leave it lowered
p - Print the character
>zZ - Print out the rest of the second input
```
[Answer]
# Python 3, ~~216~~ ~~211~~ ~~231~~ ~~225~~ 207 bytes
~~This is a solution that uses normal text and Markdown-style italics for its two typefaces. And it encodes everything in the carrier message except the spaces.~~
**Edit:** Had to fix the code so that the result would print correctly and added examples below the code.
**Edit:** Edited the code to previously worse uppercase/lowercase solution, due to problems in printing the italics correctly.
```
def g(s,c):
c=c.lower();w=[h.upper()for h in s if h.isalpha()];t=''.join("{:05b}".format(ord(i)-65)for i in w);r='';j=m=0
while t[j:]:a=c[m];x=a!=" ";r+=[a,a.upper()][x*int(t[j])];j+=x;m+=1
return r+c[m:]
```
**Examples**
```
>>> g('HELLOWORLD', 'The quick brown fox jumps over the lazy dogs, gamboling in the fields
where the shepherds keep watch')
'thE QUicK broWn FOx JuMPs OVEr ThE LazY DOgS, gaMbOlINg in THe fields where the shepherds keep watch'
```
**Ungolfed:**
```
def bacon(message, carrier):
# Lowers the case of the carrier message
carrier = carrier.lower()
# Removing all non-alphabetic characters and making the rest uppercase
words = ""
for char in message:
if char.isalpha():
words += char.upper()
# Encoding the message
binary = ""
for letter in words:
encode = ord(letter) - 65
binary += "{:05b}".format(encode)
# Encoding the carrier message
result = ""
bin_index = 0
char_index = 0
while bin_index < len(binary):
letter = carrier[char_index]
# If letter isn't a space and it needs to be encoded
if letter != " " and int(binary[bin_index]):
letter = letter.upper()
result += type + letter + type
# The encoding only proceeds if letter wasn't a space
bin_index += letter != " "
# char_index increments whether or not letter was alphabetical
char_index += 1
# Return the encoded text and any leftover characters from the carrier message
return result + carrier[char_index : ]
```
[Answer]
# C, 124 bytes
This requires the arguments to be in an ASCII-compatible encoding (e.g. ISO-8859.1 or UTF-8). It modifies the carrier in-place, and returns 0 on success, or non-zero otherwise. The encoding is `A`==lower-case and `B`==upper-case. Unused carrier letters are set to upper.
```
int f(char*p,char*s){int m=16;do{if(isalpha(*s)){*s|=32;*s-=(*p-1)&m?32:0;if(!(m/=2)){m=16;p+=!!*p;}}}while(*++s);return*p;}
```
### Explanation
Including a test program. Pass the letters to encode as the first argument, and the carrier string as the second.
```
#include <stdio.h>
#include <ctype.h>
/* ASCII or compatible encoding assumed */
int f(char *p, char *s) /* plaintext, carrier */
{
int m=16; /* mask */
do {
if (isalpha(*s)) {
*s |= 32;
*s -= (*p-1)&m ? 32 : 0;
if (!(m/=2)) {
/* reset mask and advance unless we reached the end */
m=16;
p+=!!*p;
}
}
} while (*++s);
/* 0 (success) if we finished p, else non-zero */
return *p;
}
int main(int argc, char **argv)
{
int r = argc < 3 || f(argv[1], argv[2]);
if (r)
puts("~!^%&$+++NO CARRIER+++");
else
puts(argv[2]);
return r;
}
```
Test output:
```
$ ./66019 "HELLOWORLD" "The quick brown fox jumps over the lazy dogs, gamboling in the fields where the shepherds keep watch."
thE QUicK broWn FOx JuMPs OVEr ThE LazY DOgS, gamBoLiNG in tHE FIELDS WHERE THE SHEPHERDS KEEP WATCH.
```
] |
[Question]
[
**Monday Mini-Golf:** A series of short [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenges, posted (hopefully!) every Monday.
Sorry it's late; I realized 90% of the way through writing out a different idea that it was a duplicate.
My family is rather large, so we eat a lot of food. We usually need to double, triple, or even quadruple recipes to make enough food! But as multiplying the measurements can be a pain, it'd be nice to have a program to do this for us.
# Challenge
Your challenge is to create a program or function that takes in a measurement as a number *N* and a letter *L*, and returns the same measurement, simplified as much as possible. Here's the required measurement units (all are American, like my family), and their corresponding letters:
```
1 cup (c) = 16 tablespoons (T) = 48 teaspoons (t)
1 pound (l) = 16 ounces (o)
1 gallon (g) = 4 quarts (q) = 8 pints (p) = 128 fluid ounces (f)
```
"simplified as much as possible" means:
* Using the largest measurement unit possible. Each unit can have a remainder of 1/4, 1/3, 1/2, 2/3, or 3/4.
* Turning the result into a mixed number, if necessary.
For example, `4 o` is four ounces, which becomes `1/4 l`, a quarter pound. `8 t`, 8 teaspoons, becomes `2 2/3 T`.
## Details
* The input may be taken in any reasonable format; same with output. (`1 t`, `1,"t"`, `1\nt`, etc.)
* Make sure any fractional part is dealt with properly. (`11/4` in place of `1 1/4` is not allowed.)
* The number will always be a mixed number, and will always have a denominator of `2`, `3`, or `4` (or none). (no `1 1/8 T`, no `1.5 T`, etc.)
* As a result of the above, no downward conversions (e.g. cups to tablespoons) are ever needed.
* The letter will always be one of the letters listed above (`Tcfglopqt`).
# Test-cases
Here's an large list, hopefully covering all types of cases:
```
Input | Output
--------+--------
1/2 t | 1/2 t
3/4 t | 1/4 T
1 t | 1/3 T
1 1/2 t | 1/2 T
2 t | 2/3 T
2 1/4 t | 3/4 T
2 1/2 t | 2 1/2 t
3 t | 1 T
10 t | 3 1/3 T
16 t | 1/3 c
5 1/3 T | 1/3 c
8 T | 1/2 c
16 T | 1 c
36 T | 2 1/4 c
1/4 c | 1/4 c
1024 c | 1024 c
1 o | 1 o
4 o | 1/4 l
5 1/3 o | 1/3 l
5 2/3 o | 5 2/3 o
8 o | 1/2 l
28 o | 1 3/4 l
28 l | 28 l
2 f | 2 f
4 f | 1/4 p
8 f | 1/4 q
16 f | 1/2 q
32 f | 1/4 g
64 f | 1/2 g
128 f | 1 g
2/3 p | 1/3 q
1 1/3 p | 2/3 q
2 p | 1/4 g
1 q | 1/4 g
```
# Scoring
Our kitchen is very small, so the code should be as short as possible, so as not to make the kitchen more cramped. Shortest valid code in bytes wins; tiebreaker goes to submission that reached its final byte count first. The winner will be chosen next Monday, Nov 9. Good luck!
Please note that this challenge is similar to, but not a duplicate of, [World Big Dosa](https://codegolf.stackexchange.com/questions/54224/world-big-dosa).
[Answer]
# Mathematica, ~~349 334 330~~ 322 bytes
This answer section felt a little lonely. So uh, here's my attempt. Input should be given as in the test cases.
```
n=ToExpression@StringSplit@InputString[];i=#~Mod~1&;b=#&@@n;If[Length@n==3,{x,y,z}=n,{x,y,z}=If[IntegerQ@b,{b,0,Last@n},{0,b,Last@n}]];v={0,1/4,1/3,1/2,2/3,3/4};s=<|T->16,t->3,o->16,q->4,p->2,f->16|>;r=<|T->c,t->T,o->l,f->p,p->q,q->g|>;If[v~MemberQ~i[a=(x+y)/s@z],{x,y,z}={Floor@a,i@a,r@z}]~Do~3;Print@Row[{x,y,z}/. 0->""]
```
## Explanation
First get the user input, split that input on whitespace, and assign that to `n`. `i=#~Mod~1&` creates a function that gets the fractional part of a number, by taking it mod 1. `b=#&@@n` will simply get the first item in `n`; that would be everything up to the first space.
If `n` is 3 elements long, that means we have an integer, a fraction, *and* a unit. `{x,y,z}=n` will assign `x`, `y` and `z` to be the three parts of `n`.
The other case is that `n` is not 3 elements long; that means it’ll be 2 elements long instead. To stay consistent with above, we want `x` to be the integer part, `y` to be the fraction, and `z` the unit. So in this case, we need to check:
* If `b` (the first element of `n`) is an integer, then `x=b`, `y=0` and `z=Last@n` (the last element of `n`).
* If `b` isn’t an integer, that means we only have a fraction with no integer. So we want to swap `x` and `y` from above; instead, `x=0`, `y=b`, and `z` is the same as above.
Now we need to set up some lists:
`v = {0, 1/4, 1/3, 1/2, 2/3, 3/4}` is the list of acceptable fractions, as stated in the question.
`s = <|T -> 16, t -> 3, o -> 16, q -> 4, p -> 2, f -> 16|>` is an association (key-value pair, like a dictionary in Python) that represents the amount needed of a given unit to go “up” to one of the next largest unit. For example, `o -> 16` is because 16 ounces are required before we go up to 1 pound.
`r = <|T -> c, t -> T, o -> l, f -> p, p -> q, q -> g|>` is the association that actually represents what the next unit up is. For example, `T -> c` means one unit larger than Tablespoons is cups.
`If[v~MemberQ~i[a = (x + y)/s@z], {x, y, z} = {Floor@a, i@a, r@z}]~Do~3`
Now, the maximum number of times we need to go up a unit is 3; that would be fluid ounces (f) -> pints (p) -> quarts (q) -> gallon (g). So, now we do the following 3 times:
* Add `x` and `y`, (the integer and fractional parts)
* From the `s` association above, get element `z`; that is, access the current unit, and get the corresponding value in that association.
* Divide (x+y) by that value we got above, assign it to `a`, then get its fractional part.
* If that part is in the list `v`, then we can go up one unit; set `x` to `a` rounded down (integer part), set `y` to the fractional part of `a`, then access the association `r` with the current unit `z` to get the next unit up, and set that to `z`.
* If it’s *not* part of `v` instead, we don’t do anything, since it can’t be simplified.
Once that’s done 3 times, we print out the result:
`Print@Row[{x,y,z}/. 0->””]`
This simply prints out `{x,y,z}` in a row, but replaces any zeroes (if there’s no integer, or no fraction), with an empty string, so those don’t print out.
] |
[Question]
[
In [this challenge](https://codegolf.stackexchange.com/q/248577/56656) we considered a frog hopping around a lily pond. To recap the lily pond was represented as a finite list of positive integers. The frog can only jump forward or backwards by a distance equal to the number at its current location. So for example:
```
[2, 3, 1, 4, 1]
üê∏
```
Here the frog is on a `1` so it can move forward 1 to the `4` or backwards 1 to the `3`. In the last challenge the frog had a specific starting location, but in this one we don't care about that. We just care what jumps a frog can make from a particular lily pad.
We can represent these as a directed graph, where each pad is a vertex and the edges represent hops the frog can make. Thus each vertex can have at most 2 children (forward and backwards), vertices can have fewer children if jumping in a certain direction would put them out of bounds. And indeed at least two vertices in every lily pond have fewer than two children.
As an example the pond shown above `[2,3,1,4,1]` can be represented as the graph:
```
{ 0 : [ 2 ]
, 1 : [ 4 ]
, 2 : [ 1, 3]
, 3 : []
, 4 : [ 3 ]
}
```
[](https://i.stack.imgur.com/LnkUR.png)
Of course not all graphs where each node has fewer than 2 children represents a lily pond. For example, the complete graph of order 3:
```
{ 0 : [ 1, 2 ]
, 1 : [ 0, 2 ]
, 2 : [ 0, 1 ]
}
```
Each node has two children, but the first element of the list can have at most 1 child (can't go backwards from the start). So none of the elements can go first, thus this can't be a lily pond.
## Task
Your answer should take as input a directed graph which satisfies the following properties:
* it doesn't have a vertex with more than 2 outgoing edges (children).
* it doesn't have a self loop (an edge from a vertex to itself).
* it doesn't have two edges with the same origin and destination vertices (the graph is simple).
Graph nodes are unlabeled and unordered.
Your answer should output one of two consistent values. The first if the input represents some lily pond, the second if it does not. What the two values are are up to you to decide.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the goal is to minimize your source code as measured in bytes.
## Test cases
Test cases are given where each element is a list of indices that are children. Note that since graph nodes are unlabeled and unordered the order given in the input in the case below **does not** represent positioning of the potential solution. The second test case should demonstrate this.
### Represents a lily pond
Here each input is provided with a potential solution. The solution does not need to be output it is just there to help you.
```
[[2],[4],[1,3],[],[3]] ~ [2, 3, 1, 4, 1]
[[],[2],[0],[4],[0,1]] ~ [2, 3, 1, 4, 1]
```
### Represents no lily ponds
```
[[1,2],[0,2],[0,1]]
[[1,2],[],[],[0,1]]
[[1,2],[],[],[],[1,2]]
```
[Answer]
# Python3, 264 bytes:
```
def f(g):
for i in permutations(g,len(g)):
G=dict(enumerate(i))
for p in c(G):
if len(G[p[0]])==1and len(G[p[-1]])<2and p:return 1
def c(g,s=0,k=[0]):
if not g[s]:yield k;return
for i in g[s]:
if(i in k)^1:yield from c(g,i,k+[i])
from itertools import*
```
[Try it online!](https://tio.run/##fY7BaoUwEEX3fsUskzYFo10UW9d@RLAgmthBTUKMi/f1dpInbSmlMBnInXNnrr/FD2frFx/Oc9IGDJt5U4BxARDQgtdhO@IQ0dmdzWLVloBEQNdOOEam7bHpMETNkHOSk9Mn58i6zAEaSLZOeVX2PW9bOdjpS3qSpL1VSfJN0PEIFmSRoox0b29LsbTkS6tokXURZrX3zQ31OsHyenf8CJynRbrK8n/h7/KiTXBb3opieVTY8yIrGHWIzq074OZdiA@nD2gjM0ypqhfqmZ4UNXWqmtLy4hsgKTHlxZVC/gKkyPOr/z291//THKJKwPkJ)
] |
[Question]
[
Similar to [this question](https://codegolf.stackexchange.com/questions/76966/read-a-crossword), but this is a crossword variation!
Instead of only one letter per grid square, you can have *one **or** two*.
# Input:
* A 2d array, or whatever works in your language.
* You can assume valid inputs
* Any array size must work
# Output:
* An array of all the words
+ Across and down
+ All words must be joined together, i.e. linked in an unbroken chain of words (if not return false)
+ Words must be at least two *grid squares*, not letters
### Example:
```
[["", "wo", "r", "k"],
[ "", "r", "", ""],
[ "he", "l", "lo", ""],
[ "", "d", "ad", ""]]
```
### Returns:
```
["work", "world", "hello", "load", "dad"]
```
### Example:
```
[["he", "ll", "o"],
[ "", "", ""],
[ "wo", "r", "ld"]]
```
### Returns:
```
false
```
This is [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'"), so I'll be running this on windows 7 with 2.5ghz and 16gb of ram. If your code is really esoteric, provide a link to the compiler so I can actually run it.
[Answer]
# Python 3
```
import numpy
from scipy.ndimage import measurements
def crosswords(arr):
M=numpy.asarray(arr)
# check connectivity
if measurements.label(numpy.where(M!='',1,0))[-1] != 1:
return 'false'
words = []
def get_words(mat):
for r in mat:
word,counter='',0
for c in r:
if c=='':
if counter>1:
words.append(word)
word, counter = '', 0
else:
word, counter = word+c, counter+1
if counter > 1:
words.append(word)
get_words(M)
# transpose M
get_words(M.T)
return words
```
# Usage:
Function takes an array of array of strings as input:
`crosswords(
[["", "wo", "r", "k"],
[ "", "r", "", ""],
[ "he", "l", "lo", ""],
[ "", "d", "ad", ""]])`
Returns the string `false` when connectivity returns multiple labels.
Returns array of valid words otherwise.
I timed it with `timeit`, `time.time()` and using the console command `time` and but I don't know which one to use or which one to post here.
] |
[Question]
[
Consider a date formatted in `YYYY-MM-DD`.
You can use the joker `*` at the end of the date string. E.g. `2016-07-2*` describes all the dates from `2016-07-20` to `2016-07-29`.
Now, consider a period represented by a start date and an end date.
The algorithm must find the smallest possible list of dates representing the period.
Let's use an exemple. For the following period:
* start date: `2014-11-29`
* end date: `2016-10-13`
The algorithm must return an array containing the following list of dates:
* `2014-11-29`
* `2014-11-30`
* `2014-12-*`
* `2015-*`
* `2016-0*`
* `2016-10-0*`
* `2016-10-10`
* `2016-10-11`
* `2016-10-12`
* `2016-10-13`
[Answer]
# PHP, ~~541~~ 343 bytes
I wanted to get the algorithm working in the first place; but golfing it down was actually far more fun than I expected (especially browsing the [supported date & time formats](http://php.net/manual/datetime.formats.php)).
Three major actions saved about 130 bytes; but the 70 bytes from minor golfings
(which also rendered one of the large steps obsolete) carried a lot of fun.
```
for($a=($f=strtotime)($argv[1]);!$p=$a>$z=$f($argv[2]);$a+=86400){$x=$z<$e=$f(Dec31,$a);(101<$q=date(md,$a))?$q-1001|$x?:$a=$e+$p="1*":($x?($t=$f(IX30,$a))>$z?:$a=$t+$p="0*":$a=$e+$p="*");$p?:($q%100>1|$z<($t=$f(date(Ymt,$a)))?$q%10>0&$q%100>1|$z<($t=min($t,$a+777600))?:$a=$t+$p="m-$q[2]*":$a=$t+$p="m-*");echo date("Y-".($p?:"m-d"),$a),"
";}
```
takes input from command line arguments. Run with `-nr`or [test it online](http://sandbox.onlinephpfunctions.com/code/ecf460593269939f8c1e1a45ace3116b88ffa6da).
**notes**
* prints `Y-m-3*` for `Y-m-30`; add 7 bytes to fix: Insert `|$a==$t` after `777600))`.
* throws warnings in PHP 7.1; add 5 bytes to fix: Replace `+$p` with `+!$p`.
* A breakdown and some golfings explained are ready to be posted;
but I´ll wait a bit to see if someone else submits before I spoil.
] |
[Question]
[
Inspired by [Project Euler #17](https://projecteuler.net/problem=17), this is your challenge. Write a full program or function that takes a number as input, then print or return how many letters it would take to count up to and including that number in English (starting at one). You do not include spaces, commas, or hyphens, but you should include the word `and`. For example. 342 is spelled: `Three Hundred and Forty-Two`. This is 23 letters long.
Your input will be a positive integer. You do not have to handle invalid inputs. Built-ins or libraries that convert numbers to English are not allowed.
Here are all of the rules for how to spell numbers. (Note: I realize that some people use a different set of rules for how to spell numbers. This will just be the official rules for the purpose of this challenge)
# 1 to 20
>
> one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty
>
>
>
# 21 to 99
Join these:
>
> Twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety
>
>
>
to these:
>
> -one, -two, -three, -four, -five, -six, -seven, -eight, -nine,
>
>
>
Note that **four** has a **u** but **forty** does not!
Examples:
```
53: Fifty-three
60: sixty
72: seventy-two
99: ninety-nine
```
# 100 to 999
Write out how many hundreds (one hundred, two hundred, three hundred, etc.), an "**and**", and the rest of the number as above. The **and** does count towards your letter score.
Examples:
```
101: One hundred and one
116: One hundred and sixteen
144: One hundred and forty-four
212: Two hundred and twelve
621: Six Hundred and twenty-one
```
# 1,000 to 999,999
Write how many thousands (one thousand, two thousand, etc.), a comma, then the rest of the number as above. Note that if you have no hundreds, you still need the **and**.
Examples:
```
1,101: One thousand, one hundred and one
15,016: Fifteen thousand and sixteen
362,928: Three hundred and sixty-two thousand, nine hundred and twenty-eight
```
# Millions
Write out how many millions, then the rest of the number as above. Note that "A million" is 6 zeroes "1,000,000".
Examples:
```
191,232,891: One hundred and ninety-one million, two hundred and thirty-two thousand, eight hundred and ninety-one
1,006,101: One million, six thousand, one hundred and one
```
The same rule applies to billions, trillions, quadrillions and above, but for the purpose of this challenge, you don't have to handle any number above 999,999,999 (Nine Hundred and ninety-nine million, nine-hundred and ninety-nine thousand, nine hundred and ninety-nine.)
# Python solver
Here is a short python script to verify answers:
```
import en
def get_letter_num(s):
count = 0
for c in s:
if c.isalpha():
count += 1
return count
number = input()
count = 0
for i in xrange(1, number + 1):
count += get_letter_num(en.number.spoken(i))
print count
```
Note that this usesthe NodeBox linguistics library to convert numbers to English. (yes, I just broke my own rule, but this isn't a competing answer) This is freely available [here](https://www.nodebox.net/code/index.php/Linguistics).
# Sample I/O
```
7: 27
19: 106
72: 583
108: 1000
1337: 31,131
1234567: 63,448,174
```
[Answer]
# Python 2, ~~266~~ ~~259~~ ~~236~~ ~~229~~ 228 bytes
This works for all inputs below one billion. This works for all test cases.
```
def l(n):b=[6,3,2][(n<1000)+(n<10**6)];c=10**b;return int("0335443554"[n%10])+int("0366555766"[n/10])+(n-10in[4,6,7,9])if n<100else l(n/c)+(l(n%c)or-3*(b<3))+7+(b<6)+2*(b<3)+3*(b>2)*(0<n%c<101)
print sum(map(l,range(input()+1)))
```
To modify it to fit the question as stated (e.g. don't treat numbers ending with 100 special) simply replace the number 101 at the end of the first line with 100.
Explanation:
```
def l(n):
b=[6, 3, 2][(n < 1000) + (n < 10**6)] # b = 2 if n < 1000 else 3 if n < 1000000 else 6
c=10**b
return ( # Parenthesis added for readability.
int("0335443554"[n % 10]) + # Compute length of last digit. one -> 3, seven -> 5, etc.
int("0366555766"[n / 10]) + # Compute length of second to last digit. ten -> 3, eighty -> 6, etc.
(n - 10 in[4, 6, 7, 9]) # Add one to length if the number is 14, 16, 17, or 19.
if n < 100 else # Use above procedure if the number is under 100.
# If otherwise, use below procedure.
l(n / c) + # Compute length of the top portion of number.
(l(n % c) or # Compute length of bottom portion of number.
-3 * (b < 3)) + # If the number < 1000 and is a multiple of 100,
# subtract 3 from the length because of missing and.
7 + # Add 7 to the length for "million"
(b < 6) + # Add 8 to the length for "thousand"
2 * (b < 3) + # Add 10 to the length for "hundred and"
3 * # Add 3 to the length for another "and"
(b > 2) * # if the number >= 1000
(0 < n % c < 101) # and the bottom portion > 0 and <= 100
)
print sum(map(l,range(input()+1))) # For the reader to figure out.
```
] |
[Question]
[
7-segment digits can be represented in ASCII using `_|` characters. Here are the size `1` digits:
```
_ _ _ _ _ _ _ _
| _| _| |_| |_ |_ | |_| |_| | |
| |_ _| | _| |_| | |_| _| |_|
```
Larger sizes are formed by making each segment proportionately longer. Here are a couple size 3 digits.
```
___ ___ ___ ___ ___ ___ ___
| | | | | | | | | |
| | | | | | | | | |
|___| |___ | |___ ___| | | |___|
| | | | | | | | | |
| | | | | | | | | |
|___| |___| | ___| ___| |___| ___|
```
## Goal
In this challenge, you are to write a program/function that can take a single digit as input and identify its size. The catch: if the input is not a valid digit, then your program should output `0`.
This is **code-golf**, fewest bytes wins.
You can write either a program or a function, which can receive the digit either as STDIN or an argument, and print/return the value.
Digits will be provided as a multi-line string, padded with the minimal amount of trailing whitespace needed to make it a perfect rectangle. The trailing newline is an optional part of input. There will be no unneeded leading spaces.
When a non-digit is passed, it will still be comprised of `_|` characters, padded to a rectangle, and have no unneeded leading spaces. There will be no blank lines. You won't have to deal with empty input.
Output should be a single non-negative integer, with optional trailing newline. If the input is not a proper digit of any size, output `0`. Else, output the size.
Here is a handy guide for the widths and heights of each digit for a given size `N`.
```
Digit Height Width (not counting newlines)
1 2N 1
2 2N+1 N+2
3 2N+1 N+1
4 2N N+2
5 2N+1 N+2
6 2N+1 N+2
7 2N+1 N+1
8 2N+1 N+2
9 2N+1 N+2
0 2N+1 N+2
```
## I/O Examples
In:
```
__
|
__|
|
__|
```
Out:
```
2
```
In:
```
|
|
|
```
Out:
```
0 //because it is of an invalid height. Either 1 char too short or tall.
```
In:
```
| |
| |
| |
|____|
|
|
|
|
```
Out:
```
4
```
In:
```
___
|
|___
| |
|___|
```
Out:
```
0 //1 char too wide
```
In:
```
_
|_|
| |
```
Out:
```
0 //it's not a digit
```
In:
```
__
|
|__
|
__|
```
Out:
```
2
```
In:
```
_ _
_| _|
|_ _|
```
Out:
```
0 //both would be valid individually, but input should be a *single* digit
```
In:
```
_
|_|
|_|
```
Out:
```
1
```
In:
```
|
|
```
Out:
```
1
```
In:
```
__|_
|
_ |
_
|__
```
Out:
```
0
```
---
This is approximately the *inverse* of [Transform number into 7-segment display pattern](https://codegolf.stackexchange.com/questions/19196/transform-number-into-7-segment-display-pattern), from 3 years back.
[Answer]
# Ruby, 250
```
->x{d=y=0
x.size.downto(0){|n|y=n
a=["|
"*2*n]
"XNRDqpm@A".bytes{|z|p=[?|,' ','']
h=s=""
(n*2).times{|i|
i%n<1&&(d=z>>i/n*3&7)&&h=[?_,' '][d/3%2]*n
s=p[d%3]+h+p[d/6]+"
"+s
h=' '*n}
z!=68&&s=' '*(1-d%3/2)+?_*n+"
"+s
a<<s};puts a
a.index(x)&&break}
y}
```
Given that there are so many possible invalid inputs, the only way to do this was to generate all the correct digits and check to see if the input matches.
I build each digit up from bottom to top, in 2 halves plus the top line. Although there are 12 possibilities (considering that the left segment can be on, off, or in the case of `3`and `7`completely absent) only 7 are actually present and careful choice of encoding enables all info (except the top line) to be encoded into a single character.
the digit `1` doesn't really fit the pattern and is handled separately, being used to initialize the array.
**Ungolfed in test program**
This version uses `.` instead of spaces for diagnostic reasons.
```
#Encoding used for half-digits (radix 3,2,2 most significant digit at right)
#000 |_| 0
#100 ._| 1 . = space
#200 X_| 2 X = no space (for digits 3 and 7)
#010 |.| 3
#110 ..| 4
#210 X.| 5
#001 |_. 6
f=->x{d=y=0 #d and y required to be intialized for scoping reasons
x.size.downto(0){|n|y=n #Assume max possible size of character = length of input and iterate down through all possible sizes n
a=["|\n"*2*n] #Make an array containing the digit 1 (different shape to others)
"XNRDqpm@A".bytes{|z| #Each character encodes the pattern for a digit. Iterate through them
p=['|','.',''] #Possible components for left and right of digit
h=s="" #h initialized for scoping reasons. s will contain the digit string
(n*2).times{|i| #For each row
i%n<1&& #If i%n==1 we are at the bottom of a half digit
(d=z>>i/n*3&7)&& #so extract info from z and store in d
h=[?_,'.'][d/3%2]*n #h is the horizontal part of the half digit, either _ or spaces
s=p[d%3]+h+p[d/6]+"\n"+s #Build one row of digit, working upwards: left,middle,right
h='.'*n #If row i%n!=0 (not bottom row of half digit)the middle section must contain spaces
} #We now have both halves of the digit, only the top segment missing
z!=68&&s='.'*(1-d%3/2)+?_*n+".\n"+s #If z!=68 (digit 4) add a top to the digit, with appropriate leading and trailing spaces
a<<s #Add the completed digit of size n to a
}
#puts a #Diagnostic: uncomment to print all the strings checked
a.index(x)&&break #If string x is in a, break
}
y #and return last value of n
}
# digit 7, size 2. Trailing newline required. Outputs 2
puts f[
"__.
..|
..|
..|
..|
"]
```
] |
[Question]
[
*[Related](https://codegolf.stackexchange.com/questions/60443/s%e1%b4%8d%e1%b4%80%ca%9f%ca%9f-c%e1%b4%80%e1%b4%98%ea%9c%b1-c%e1%b4%8f%c9%b4%e1%b4%a0%e1%b4%87%ca%80%e1%b4%9b%e1%b4%87%ca%80)*
# Exposition
After winning the SO raffle, you could have been on top the world, and you were! The raffle had been going on for a year, now, and you were one of a hundred programmers who were selected to enter into the SO stronghold. And finally, the wait is over. Today is the day you go to--[obfuscated text proceeds].
Whoops. Sorry, not supposed to tell.
Anyhow, you finally have arrived to meet a stoic-faced man in a black suit with the tiny SO emblem on it. He frowns at you. "The others are already inside," he said, noting that you had been identified at the gate. "Quickly."
You rush inside, a tad scared. *What on earth had gone on? What was wrong at SO?* Inside, you observe the other 99 programmers are staring intently at their screens, typing. You take the remaining seat, and are greeted with the following message:
>
> Hello, programmer! It seems that we have encountered a problem; SO has been penetrated, by whom we don't know. (Personally, I suspect it was a Pyth or CJam programmer, but hey.) However, all that has been harmed is the Markdown editor. Well, actually, that's quite a lot, but that's where you come in.
> I want you to create a program (or function, we're not picky) that will interpret a markdown file and convert it to our new "SO Beautifier-Arity-Decomposer" (a.k.a. "SOBAD") format. You must do this in the shortest amount of bytes--we are running on lowdown until we resolve this hacking issue. Thanks for your time, and best of luck!
>
> Sincerely,
> The Maker of Stack Overflow
>
>
>
---
**Objective** Given a valid markdown file as input to your submission, perform and output the following transformations on the input:
(When I use the `+` symbol, I mean the RegExp "one or more instances of previous character" operator, not a literal plus sign.)
* Transform all Level 1 headers (`# ...` or `...\n=+`) to `{ ... }`, with `...` becoming ALL CAPS.
* Transform all Level 2 headers (`## ...` or `...\n-+`) to `{{ ... }}`, with every word capitalized
* Transform all Level 3 headers (`### ...`) to small caps; that is, all letters (case insensitive) are mapped to `ᴀʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ` in a respective fashion.
* Transform all bold instances (`**...**`) to `...`, with `...` becoming ALL CAPS.
* Transform all italic instances (`_..._`) to `. . .`, where a space has been inserted between each pair of characters.
* Transform all code instances (``...``) to `< ... >`.
* Transform all strikethrough instances (`---...---`) to `-.-.-.-`, where a `-` has been inserted between each pair of characters.
* Transform all numbered list instances (`N. {a}\nN. {b} ...` where `N` matches the regex `[0-9]+`) to (`1. {a}\n 2. {b}...`)
* Transform all unordered list instances (`* ...\n* ...`...) to (`o ...\n o ...`...)
## More details
* Headers and list instances will only be found at the beginning of lines, however, they may be surrounded by an amount of whitespace.
* There will be no linked instances, e.g., `*a_*a_` is not valid for our standards, nor will anything like `__a__`, `*_a_*`, or `_*a*_` appear in an input.
* A multiline header is valid if and only if the `-` or `=`s directly follows a line of text.
* No headers will contain other markdown entities. E.g., `# `code` snippet` is not a valid input for our purposes
* You do not have to account for Level 4+ headers
* You do not have to preserve excess spaces (i.e. `> 1` spaces) within the file, so it is O.K. to have `**hello there**` to become `**hello there**` but not `**hellothere**`. Similarly, trailing and leading spaces found on a line does not have to be preserved
* No tabulators will be found in the input.
* **THERE WILL BE NO NESTED INSTANCES.** For example, `***...***` would never occur.
* A space will always follow an unordered bullet point (E.g., `* ...` not `*...`)
* List items in ordered and unordered lists will always consist of a single line.
* Unmatched pairs of characters should be ignored. E.g., `** cool` and ``java::def` should remain the same.
---
## Input methods
The input must be one of the following:
1. An array/tuple/list/etc. of strings.
2. OR a string containing newlines to separate lines.
Use your language's closest equivalent to the aforementioned data types if your language does not support them. (E.g., TI-BASIC doesn't support (1.)… not that TI-BASIC can compete, anyhow :P).
## Test cases
A `}` signifies input, and the next line signifies output. Multiple `}`s signify newline-separated lines of text.
```
} Hello!
Hello!
} That _2 + 2 = 5_ challenge sure was **intense!**
That 2 + 2 = 5 challenge sure was INTENSE!
// note that there are spaces also padding it
} It's `s/a/e/g` **not** `sudo g/a/e/s`, stupid.
It's < s/a/e/g > NOT < sudo g/a/e/s >
} **WHAT!** He did _WHAT?!_
WHAT! He did W H A T ? !
} _WHAT_ is undefined, here!
W H A T is undefined, here!
} OI)(EJDSFIJK L:JP #@*REF&WDS F*(D+S +&(SDFWEF )DSF _DSF_F #R#
OI)(EJDSFIJK L:JP #@*REF&WDS F*(D+S +&(SDFWEF )DSF D S F F #R#
} # So, you wanna be a programmer, eh?
} ## Step 1: learn recursion
} ### Learning recursion requires learning recursion
} **Programming** is a futile task. _Leave w h i l e you still can!_
{SO YOU WANNA BE A PROGRAMMER, EH?}
{{Step 1: Learn Recursion}}
ʟᴇᴀʀɴɪɴɢ ʀᴇᴄᴜʀsɪᴏɴ ʀᴇǫᴜɪʀᴇs ʟᴇᴀʀɴɪɴɢ ʀᴇᴄᴜʀsɪᴏɴ
PROGRAMMING is a futile task. L e a v e w h i l e y o u s t i l l c a n ! // trailing space not required
} Haha, you're a _Java_ golfer? You'd be better of with brainf***.
Haha, you're a J a v a golfer? You'd be better of with brainf***. // less than four asterisks, do nothing
} # Reasons why NOT to use C--:
} 1. It doesn't exist.
} 2. I don't care.
{REASONS WHY NOT TO USE C--:}
1. It doesn't exist.
2. I don't care.
} 1. This is a test!
} 1. <-- And this actually works in Markdown.
1. This is a test!
2. <-- And this actually works in Markdown. // less than three -s, ignore
} * no.
} * NOOO.
} * fine.
o no.
o NOOO.
o fine.
} Python, ---34--- 3 bytes.
Python, -3-4- 3 bytes.
} ---Long line of crossed text.---
-L-o-n-g- -l-i-n-e- -o-f- -c-r-o-s-s-e-d- -t-e-x-t-.-
} ** cool!
** cool! // is not a bullet point, because a space doesn't follow the *; Isn't bold, because there is no matching **
-- end of test cases --
```
# Bonus
1. -19 bytes if you support the escaping of characters (so that they are treated as "normal"); you may choose any escape character, but I'd suggest `\` or `^`. Note that the escaping system on SO sites is different from what I am suggesting (and more complicated), so don't do it! SO would treat ``\`` as `\`, but I would want you to treat the second ``` as then a regular character, and instead match the *next* ``` character.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~652~~ 640 bytes
```
import re
def N(o):c,t,_=o.groups();x=' -'[c<'_'];return['< %s >'%t,t.upper()][c<'`']if c in'**`'else x+x.join(t)+x
def f(s):
S=[];i=0
while s:
l=s.pop(0);n=set(*s[:1])
if n<={*'=-'}and n:s=s[1:];l='#'*('-'in n)+'# '+l
if'# '==l[:2]:l='{%s}'%l[2:].upper()
if'## '==l[:3]:l='{{%s}}'%l[3:].title()
if'### '==l[:4]:l=''.join('ᴀʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ'[ord(c)-65]if'@'<c<'['else c for c in l[4:].upper())
l=re.sub(('(\*\*|_|---|`)(.*?)'*2)[:-5],N,re.sub(r'^\s*[*] (.*)',r' o \1',l))
if re.match(r'\s*\d+\. ',l):i+=1;l=re.sub(r'\s*\d+\.(.*)',' %d.'%i+r'\1',l)
else:i=0
S+=[l]
return S
```
[Try it online!](https://tio.run/##fVRBT@NGFL77VzwSsWNPErMJ0IODy64KEVAKiCChykmNsSfJLGYmnRkvQctKe2hVqVXVQy@tulLbPbZX/4cKjv0H/iX02QnLtode7JnvffPmfW@@mem1mUixen/PL6dSGVDMStgIDmzpeHHTNENfumMls6m2ne7MJ9AiQbxBQjLsKmYyJQKyAcsaPibLpmncbDplynaGJeeMDPkIYuCCUHpGWKoZzBoz94XkwjZOY1btNLK141nQ94Nhl/tPLbia8JSBRgxSX7tTObWfOl3ha2ZsqgOvPXQwhJnFhv@KEr9FXkciAeFpXwdtb9hNfVIn1CYtwgUIp0HqQBpptaYc@n4aeJ2hh7RXy/o1WU6Djjd8qHxBe@CtznklsWKuItNwk7JH5gN1raKSuTxS5G/ufi7yr4r86yL/5u8fb9/dvb39o8i/LfLv7n4t8u9v8yL/och/@uvPuze6yH8p8rdF/luR/z67Q/gdCaRK7NhpfbSOXSTPyAZ2NJg3MYaRVFVjIQ3WHmt3qpYp5urs3LaJPaADehPetFqtmzPHdummQ2jHCbzW@rB50FzwFPlioGlAh4AMhzQVAQmDNmmmzqLPSLyMTDxBKjIHSWPgQhn2eMNvd99v@BidJyKwnLhkmTcwUKXDbGX5XnXK0G/4QTq0YO4i6N@XZhjbvDRDKS8t5Y1s7uppyo1NBoI4jjdVXBi7zDUfOZZlje3aDktTuTQQvj8QOxwHqLnmfBBaTE4mkYGwAw3ogA/rIcSTKE2ZGKPhMsXgKtJAKSZmQrMlShfLdg3RcKZXohW2Mj5DhpCGUkSyRMK4gvVZE7TJpjxxF4soPd15foJJYIdBwhMIy/nmUriIV9MQuIZMoHYuWNKECVPsodjDXcfe3tvq93b3PoV9b@8I6s/o8XbvyelWH3rU3mr0ofHE7m/1Trd74CARQvyEPagf1xc5arU69GUTrmWG4oSI4JxBhM2TYxVdXjLVBDbZtNDEfcOm0PYgZREeh2JxpjSXwioNvl9iXIwfYRx9mXHF9Jz/r5hF6dEiP@KoHyVGMMpMea9NpC9cCDHjS2w3TIDjSbOqPo2EFOJIYItqD6cXTaKqeqLKusO96GUUwlimI6Y24XPEk1LROTOGKZAjuOJmAucq4mJEKXU/aMMxi7QUGt@Xazg4PAEjIcPL9Emr5VltF3YNJJJpQQywGdfGtToIIlYicYQmf19UrYb8kwnKqpQZps1SmWKj1YLn@BSZMhTFJkNvXcOVVBe6NPNnkbpI5JVw/5cLGPwP/4ONKQjpWhQFHB6W/9I2j/Gj6jFvArp/dQ0/sArn11jeQxsQ2pd4VCmuKpsVK6k1wyLYzLiPVwaPLJYyLX14/w8 "Python 3 – Try It Online")
] |
[Question]
[
I was looking for this page to help me enhance my first [answer](https://codegolf.stackexchange.com/a/147101/15214) with SQLite, but I couldnt find one. So here we are!
What general tips do you have for golfing in SQLite? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to SQLite. Please post one tip per answer.
Thanks to Michael B for the idea. :)
Related: [Tips for Golfing in T-SQL?](https://codegolf.stackexchange.com/questions/32796/tips-for-golfing-in-t-sql)
]
|
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/117339/edit).
Closed 4 years ago.
[Improve this question](/posts/117339/edit)
From [Wikipedia](https://en.wikipedia.org/wiki/Chopsticks_%28hand_game%29?wprov=sfla1):
>
> Chopsticks is a hand game for two players, in which players extend a number of fingers from each hand and transfer those scores by taking turns to tap one hand against another.
>
>
>
In this challenge "splits" can only be 4->2+2 or 2->1+1.
## Challenge
Your challenge is to make a bot (think the AI and framework of a chess program, but not chess) to play Chopsticks.
The game is as follows:
* Both players (computer and player) start with 2 hands, and 1 finger raised on each hand. (aka the player and computer hands are both `[1,1]`)
* The players alternate turns. To move, the player taps one of his hands against the other person. Let player 1's hands be `[2,3]` and player 2's hands be `[3,4]`. If player 1 taps his first hand against player 2's second (`2` vs `4`), then player 1's first hand is added to the total of player 2's second hand, modulo five (`6 mod 5 = 1)`.
* Another explanation: `x` is the hand player 1 uses to tap player 2, and `y` is the hand getting tapped (which belongs to player 2), `y += fingers(x); y = y mod 5`.
You cannot make a move with a hand that has `0`. However, if one of your hands is empty and the other one has 2 or 4 sticks, you can split that hand to make your hands `[1,1]` or `[2,2]` (this counts as a move, so you don't tap that turn)
If your hands are `[0,0]`, you lose. Same with the other player.
Chopsticks is more or less a solved game1, meaning that neither player 1 nor player 2 can win if the other is a perfect player. Your bot must be a perfect player. (aka it will keep going forever or until it wins, it will never lose) This also means your program must loop indefinitely, it can't rely on recursion (just as an example).
Input and output can be in any acceptable way.
## Examples
IO is the right column, odd rows are first player's moves, even rows are second player's moves. Left column is the fingers of the players at that point.
Your bot will always be the second player.
```
First Second I/O
[1,1] [1,1]
[1,2]
[1,1] [1,2]
[2,2]
[1,3] [1,2]
[2,1]
[1,3] [4,2]
[1,1]
[0,3] [4,2]
[2,2]
[0,3] [4,0]
S
[0,3] [2,2]
[2,2]
[0,3] [2,0]
[1,2]
[0,0] [2,0]
Result: 0-1
```
Also, there are many variations of this game. For example, some variants have your hand empty if it's above or equal to 5, i.e. `2` vs `4` will give `0`, instead of `1` (which is `2+4 mod 5`). The rules listed here are the ones you will use however.
Good luck and happy golfing!
---
**[1]:** [citation-needed]. I found on the internet that the second player can always win if splits can be arbitrary but neither players have a winning strategy, but I don't know if I should be trusting random blogs. Games like Connect 4 game have a few papers on them, but I could find none on this game.
]
|
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/57166/edit).
Closed 7 years ago.
[Improve this question](/posts/57166/edit)
The interpreter executable for [FALSE](http://esolangs.org/wiki/False) is 1020 bytes large. I think we can do better than THIS:
```
��Û������������������ˆ��È���ˆB0�ˇ*,x�r�pH@NÆ˝T,�g�Œ$F(FIÏa®.GÏu0C˙íp%NÆ˝ÿJÄg�™,@"$<��ÌNÆˇ‚JÄg�í*�"�$&<��a®NÆˇ÷,�"NÆˇ‹F�k�r‹Ç*BA˙¸C˙Ra�ºª∆j��Úp�@�0j�^@�[f(¸A˙�8¸+(¸`�ˇ¯&Ã`‘@�]f8¸Nu c êàTÄ1@ˇ˛`º@�aj�T@�!kÆ@�{fª∆j��ö�}fÙ`ö@�"fB(¸A˙�(¸`��� Lª∆j
�"g›`ÚRçB ���gB êàTÄ1@ˇ˛(¸"NÆ8¸¸L`�ˇT@�'fp�8¸+<(¿`�ˇ@@�`f
$Uå8¿`�ˇ0A˙�ˆ∞(�fVàr�8ÿQ…ˇ¸`�ˇ2g��p–¡`‡A˙TC˙^a��∫ ��gB\ êáÄ��� ‰à(¸��Ú G!@�!@�A˙¬"$<��ÓNÆˇ‚(�g��$"�$&ñáNÆˇ–"NÆˇ‹"N,x�NÆ˛bap�NuaÓ`"JNÆ˝Np
Nu@�:j�˛ûr�¬¸�
@�0“Ä�0k�:jp�`‰8¸+<(¡`�˛d@�{j�˛®@�aÂH8¸AÏ8¿8¸+`�˛H êà‚àSÄ8ÿQ»ˇ¸Nu�+ —ï�- ëï�* ¡Ì�*Ä�/ "É¿H¡*Å�. `%ld�A˙ˇ˙"$
NƸFXç�! ]Nê�: ] ù�; ]+�= ∞ïW¿HÄH¿*Ä�? ] gNê�$�+�%�Xç�\ *≠�+@��@ -�+m��+U�*Ä�_�Dï�& ¡ï�| Åï�~�Fï�> ∞ï[¿HÄH¿*Ä�#L›�HÁ�¿ o�NêJùg WNê`Pè�,"$NÆ˛»�^"NÆ˛Œ+��¯ Âà+5���fl"NÆ˛ò"NÆ˛òa.out���Û���������������������È����KÔ˜�IÔ¯�(à,x�C˙�p%NÆ˝ÿJÄfNu,@NÆˇƒ,�NÆˇ *�`dos.library�"N,x�NÆ˛bp�Nu����Ú
```
# Challenge
Write a FALSE interpreter in any language (doesn't have to be an executable!). As usual, shortest bytes wins. Make sure to try to get it under 1020 though :)
# Language Specs
**Literals**
* `123` put integer onto the stack
* `'c` put character code onto the stack
**Stack**
* `$` DUP
* `%` DROP
* `\` SWAP
* `@` ROT
* `ø` PICK (dup the nth stack item)
**Arithmetic**
* `+` ADD
* `-` SUBTRACT
* `*` MULTIPLY
* `/` DIVIDE
* `_` negate (negative numbers are entered `123_`)
* `&` bitwise AND
* `|` bitwise OR
* `~` bitwise NOT
**Comparison** (false is zero, true is all bits set (-1 or ~0) so that bitwise operators may be used)
* `>` greater than
* `=` equals
**Lambdas and flow control** (tests are for non-zero)
* `[...]` define and put a lambda onto the stack
* `!` execute lambda
* `?` conditional execute: `condition[true]?`.
+ An if-else can be expressed as: `condition$[\true\]?~[false]?`
* `#` while loop: `[condition][body]#`
**Names**
* `a-z` put a reference to one of the 26 available variables onto the stack
* `:` store into a variable
* `;` fetch from a variable
**Input and Output**
* `^` read a character (-1 for end-of-input)
* `,` write a character
* `"string"` write a string (may contain embedded newlines)
* `.` write top of stack as a decimal integer
* `ß` flush buffered input/output
**Other**
* `{...}` comment
* whitespace is ignored, may be needed to separate consecutive integers
# Examples
Copy file:
```
{ copy.f: copy file. usage: copy < infile > outfile }
ß[^$1_=~][,]#
```
Factorial:
```
{ factorial program in false! }
[$1=~[$1-f;!*]?]f: { fac() in false }
"calculate the factorial of [1..8]: "
ß^ß'0-$$0>~\8>|$
"result: "
~[\f;!.]?
["illegal input!"]?"
"
```
Primes to 100:
```
{ writes all prime numbers between 0 and 100 }
99 9[1-$][\$@$@$@$@\/*=[1-$$[%\1-$@]?0=[\$.' ,\]?]?]#
```
]
|
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 6 years ago.
[Improve this question](/posts/125989/edit)
You should code a piece of code that looks like it outputs the language name but actually outputs the name reversed.
E.g. a Python program should look like it outputs `Python` but should actually output `nohtyP`.
The winner is the answer with the most upvotes in a week!
[Answer]
# [PHP](https://php.net/), 3 bytes
```
PHP
```
[Try it online!](https://tio.run/##K8go@P8/wCPg/38A "PHP – Try It Online")
It looks like it outputs the language name, but it's actually the letters in reversed order.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix)
Because Cubix doesn't always need to be indecipherable
```
begin;
print "Cubix" > output;
end@?;
```
[Try it online!](https://tio.run/##Sy5Nyqz4/z8pNT0zz5qroCgzr0RByRkkqKRgp5BfWlJQWmLNlZqX4mBv/f8/AA "Cubix – Try It Online")
[Watch it running](https://ethproductions.github.io/cubix/?code=YmVnaW47CnByaW50ICJDdWJpeCIgPiBvdXRwdXQ7CmVuZEA/Ow==&input=Cg==&speed=5)
[Answer]
# R, 8 bytes
Took me a while to figure this one out, but I think I've solved it!
```
cat("R")
```
[Answer]
# HTML, 11 Bytes
```
‮HTML
```
-4 Bytes hardcoding the unicode character in a html file
# HTML, 12 Bytes
```
‮HTML
```
The browser do the rest in a html file
```
‮HTML
```
[Answer]
# C++
```
#include <iostream>
int main()
{
char C = 1;
std::string CPP;
for(C++; C++ < 42; C++)
CPP += "C++";
std::cout << CPP[C++];
std::cout << CPP[C++];
std::cout << CPP[C++];
return 0;
}
```
[Try it online!](https://tio.run/##pYyxDsIgGIR3nuJSlzaNiRqnQl14ge7GgVCsJBYaCpPx2fEvLu7e8Of@@y6nl2U/aZ3zzjr9TKOBsH6Nwaj5wqyLmJV1dcNeDCT9UAESPY68/Gscu47a1k2Qw/AN7z7Usm056EDgfCquKWwTFdH2qCisfma0TxFCbPhK6PYPCiam4HDg7J3zBw)
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), 20 bytes
```
"Braingolf"@@@@@@@@@
```
[Try it online!](https://tio.run/##SypKzMxLz89J@/9fyQnGVnKAgf//v@bl6yYnJmekAgA "Braingolf – Try It Online")
`@` Prints a character as ASCII, however because `"Braingolf"` pushes the string in order, the last item on the stack is `f`, so the first `@` prints `f`, and so on.
Because of this quirk, the first `Hello, World!` program in Braingolf was actually:
```
"!dlroW ,olleH"@@@@@@@@@@@@@
```
Sidenote: Braingolf backwards is `Flogniarb`, which might actually be a better language name than Braingolf!
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 8 bytes
```
"><>">o<
```
[Try it online!](https://tio.run/##S8sszvj/X8nOxk7JLt/m/38A "><> – Try It Online")
Fun fact, this actually reverses the name of the language. The name, however, is a palindrome. Which is extra funny to me, because 'paling' (which almost spells the start of 'palindrome') is a kind of eel in Dutch.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~20~~ 18 bytes
*-2 bytes thanks to cleblanc.*
Specification says nothing about any output on STDERR so...
```
main(){puts("C");}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oLSkWEPJWUnTuvb/fwA "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
“Jelly”U
```
[Try it online!](https://tio.run/##y0rNyan8//9RwxwvEOtRw9zQ//8B "Jelly – Try It Online")
"U" is a meaningless enough atom for "reverse an array" that 99% of programmers will likely assume that this program will output "Jelly". Maybe not so much code-golfers, though.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 24 bytes
Outputs on STDERR. This is a simple identity reduction, but APL goes right-to-left!
```
{⍺⊣⍞←⍵}/' APL'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdLzE39X/1o95dj7oWP@qd96htwqPerbX66gqOAT7qIAX/QSoA "APL (Dyalog Unicode) – Try It Online")
---
Alternate, tacit, self-documenting version:
```
Print←⍞∘←
Identity←⊣
All←/
Identity∘Print All' APL'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBAFFmXklj9omPOqd96hjBpDB5ZmSmleSWVIJEuxazOWYkwNk6SOEO2aA9SgAJdQVHAN81AE)
---
A.P.L.: An Interactive Approach ([pun intended](http://book-pdf-pkr6.fplys.com/index.php?page=37206)). Let's ask for the three letters and input them in proper order:
```
⎕⎕⎕
'A'
'P'
'L'
```
Works because APL evaluates from right to left and thus asks for the rightmost letter first, but we enter the "A" first, etc.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBI/6pkIQl7qjOpd6ABD7qAMA)
[Answer]
# J, 3 bytes
Jumping on the language-is-palindrome bandwagon:
```
'J'
```
[Answer]
# q, 5 bytes
a one letter language name makes this problem trivial
```
1"q";
```
Output:
```
q
```
[Answer]
# Bash, 10 bytes
```
rev<<<Bash
```
[Try it online!](https://tio.run/##S0oszvj/vyi1zMbGxgnMBgA)
] |
[Question]
[
## Challenge
* Given a non-negative integer, find the sum of its digits.
### Rules
* Your program must take a non-negative integer as input.
* Your program should output the sum of the digits of the input integer.
* Your program should be able to handle inputs up to 10^100.
### Examples
* If the input is 123, the output should be 6 (1 + 2 + 3).
* If the input is 888, the output should be 24 (8 + 8 + 8).
* If the input is 1024, the output should be 7 (1 + 0 + 2 + 4).
* If the input is 3141592653589793238462643383279502884197169399375105820974944592, the output should be 315.
### Format
* Your program should take input from standard input (stdin) and output the result to standard output (stdout).
* Your program should be runnable in a Unix-like environment.
### Test cases
Input:
```
123
```
Output:
```
6
```
Input:
```
888
```
Output:
```
24
```
Input:
```
1024
```
Output:
```
7
```
Input:
```
3141592653589793238462643383279502884197169399375105820974944592
```
Output:
```
315
```
### Scoring
* This is a code-golf challenge, so the shortest code (in bytes) wins.
[Answer]
# [Trilangle](https://github.com/bbrk24/Trilangle), 15 bytes
```
'0.<"@(+>i(^-<!
```
Test it on [the online interpreter](https://bbrk24.github.io/Trilangle/#%270.%3C%22%40(%2B%3Ei(%5E-%3C!)!
---
Roughly equivalent to this C code:
```
#include <stdio.h>
int main() {
int total = 0;
int i;
while ((i = getchar()) != EOF) {
total += i - '0';
}
printf("%d\n", total);
}
```
Control flow is kinda weird so it actually calls `getchar()` a couple times even after EOF is reached.
---
Unfolds to this:
```
'
0 .
< " @
( + > i
( ^ - < !
```
With code paths highlighted:
[](https://i.stack.imgur.com/Xurqf.png)
Control flow starts at the north corner heading southwest (on the red path). Instructions are executed as follows:
* `'0`: Push a 0 to the stack
* `<`: Change the direction of control flow
(Walk off the edge of the grid and wrap around)
* `i`: Get a single character from stdin (-1 on EOF) and push it to the stack
* `>`: Branch on the sign of the top of the stack
If the value is positive (any character that isn't EOF), the IP takes the green path:
* `"0`: Push the value of the character '0' (i.e. 48) to the stack
* `-`: Subtract the two values on top of the stack
* `+`: Add the two values on top of the stack
* `<`: Redirect control flow, merging with the red path
Once EOF is read, the IP takes the blue path, printing out the stored value... eventually. As you can see from the image it takes the scenic route.
* `-`: Subtract the two values on top of the stack. There's now only one value, `total - -1` (i.e. `total + 1`).
* `i`: Attempt to read another character from stdin (always sees EOF)
* `<`: Redirect control flow
* `-` Subtract the two values on top of the stack. Again, there's now only one value: `total + 2`.
* `^`: Redirect control flow
* `((`: Decrement the top of the stack twice, undoing the effects of `i-i-`.
* `!`: Print the value on top of the stack as a decimal integer
* `i`: Another attempt to read stdin, though at this point the values on the stack don't matter
* `@`: End program.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 30 bytes
```
f(int*s){s=*s?*s-48+f(s+1):0;}
```
[Try it online!](https://tio.run/##fYxNDoIwEEb3nIJgTFoQ03amdEb8uYBHcGOKKImisbginB2Je/mW7@V9Pr96P461aNouDbIPuzQc0pAjZbUImZYbVQ7jomn9/VNd4m3oqua5vu2jaArix7lphYz6KJ72ek@oFsmyOrXJKq7FMdEGEinLf5qI5rRWBuc8aNSWTWHBEjsGA4SFKRCAwDi2yhChZqcLBmZwVitLRrFDRpzC3/cwfgE "C (gcc) – Try It Online")
# [C (clang)](http://clang.llvm.org/), 31 bytes
```
f(*s){return*s?*s-48+f(s+1):0;}
```
[Try it online!](https://tio.run/##fcxBDoIwEAXQPacgGJMWxLSdKZ1RoxfwCG4IiJJoNRRWxLMjcS9/@V/@r/LqUfrbNDUiDXLsrv3Q@TSc0pAjZY0ImZY7tf9Mq9ZXj6G@xofQ1@1rez9GUev7@Fm2XshojOI5726uGpGs64tPNnEjzok2kEi5/8dEtMRaGVxy0Kgtm8KCJXYMBggLUyAAgXFslSFCzU4XDMzgrFaWjGKHjDgPf9@f6Qs "C (clang) – Try It Online")
# [C89](https://gcc.gnu.org/), 35 bytes
```
f(char*s){return*s?*s-48+f(s+1):0;}
```
[Try it online!](https://tio.run/##fY/NasMwEITvegrjUrCcuEhaydqt@/MivRjJTgSpEiwnl5BXryrSczOnYT5mYFy3cy7nuXH7cWkTvy7Tel5imz7b1GnczE3aSP4qhlt@CtEdzn6q3tLqw/Fl/8FYiCv7HkNsLsfgObuyqui0lHhu6mf/FettVZxUUHM@/EMR8QGVQukHGKSWhlRvwCBZAgWoe9VrAARlyQiFqCVZ2RMQgTVSGFSCrCatS/E@fd/@e16Jgd3yj5sP4y7lrlx9d0i5O01@jGtwvw "C (gcc) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 0 bytes
```
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiIiwiIiwiNjk0MjAiXQ==)
That's right. No bytes needed.
Alternatively
## [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
‚àë
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiJEiLCIiLCI2OTQyMCJd)
Just the built-in that works on numbers
[Answer]
>
> NOTE: Since many/most of the answers seem to ignore the requirement in the question that the input must be taken from `stdin` and the output must be sent to `stdout`, I suppose it is reasonable if I do so, too. I think that's a silly and arbitrary requirement, because it makes many languages non-competitive. The standard on Code Golf is to [allow functions](https://codegolf.meta.stackexchange.com/a/2422), and to [allow functions taking input via arguments and outputting via their return value(s)](https://codegolf.meta.stackexchange.com/q/2447), so this is what I will follow.
>
>
>
# x86-64 Assembly, standard Linux calling convention, 17 bytes
```
64 31 C0 0F B6 0F E3 09 48 FF C7 8D 44 01 D0 EB F2 C3
```
**[Try it online!](https://tio.run/##jZFfa8IwFMWfcz9FKIgbU2mb1iaDDfxTnwYb05ehY8S2SkaalrSO6pd3UatUxsA@BHryu@fce8OLIkmXcttdR9G@J1SZyK9iq0peYZXlOlmJaj/dpGOxFmXxCKjKNEp41cHmgJcsy42WZj@7CiWRUYcfsxC/zd7xXMfiE9C3jqodClUMSKgIGRGQTPjJYm4u8QPWJquL23b7wKc5OriCKTHOOin3vbXMlhKnXCiAEZfRQMVjUeSSb0/ZSBeig4/WEZcSXdo93SZx3W39Z9jXyWQazvAk0ykvp6UGXH/H@lybNayO4QCH2HNMo3RQZ133A3/B4a3g6FZwfCsY/gOeh716yrN4HPqyGDN5jxeR2GHrstW7VnG/KJ@eF2Vrs1AWDBqQ4xILhg2BUmrBqEnYrmfBuKEQx3N85vZ94lMWMOIS6vXdvkcIJW7AfNul1HNY4PQZYYwEvmP71LVZ4DHPM4UWhA03C/a/ "Assembly (gcc, x64, Linux) – Try It Online")**
This is a minor, iterative improvement on [qwr's answer](https://codegolf.stackexchange.com/a/258254), which is 18 bytes.
It saves 1 byte by using the relatively-obscure `JECXZ` instruction (actually `JRCXZ`, since this is 64-bit mode), which jumps if the value of the `rcx` register is zero.
It also improves on qwr's original (arguably fixes a bug?) in that it supports the case where the input is an empty string, returning a sum of zero. (To be fair, the challenge doesn't specify whether it is required to handle this, so maybe it cannot be termed a "bug", and, in fact, my next attempt will have this same "bug", so I can hardly ding qwr for taking advantage of it, too!)
```
SumDigits:
31 C0 xor eax, eax
Loop:
0F B6 0F movzx ecx, BYTE PTR [rdi]
E3 09 jrcxz End
48 FF C7 inc rdi
8D 44 01 D0 lea eax, [rcx + rax - '0']
EB F2 jmp Loop
End:
C3 ret ; result is in eax
```
# x86-64 Assembly, fully custom calling convention, 14 bytes
```
64 31 C0 31 D2 AC 8D 54 02 D0 38 26 75 F7 C3
```
**[Try it online!](https://tio.run/##jZFva9swEMZfS5/icCndaBpsy46tQAf547wqbCx5M5pRFNtNVGTJSPLq9MunSppmDmMQIQS6@z3P6U7MmLJaie3dOs93fS5tKZ7MVlrWglS1Lp95u5s31ZSvuTVDfIVyUaAreC0hZxKYMU1Vgt0w6w5uwG0mXtnWQC5KpkFJeOCyaTFqlUYla3vgjuOt2N@KFj8oVQ8xEqowK@fNRA/GvxYZ/Fj8hEdt@G@XK9kH/6iLFm5Bu/fdwY1/43J5VaNzvgdsg9GLfEN7a5zJwtnr0u76a6FWAirGJcYTJvKRLKbc1IJtHVE3ZoOc3lkyIdCpbZdR9UeiUn@QLngPvs9m82wBM6UrZudWYziug7TWbpLPh5oY76sNj1LzVzo6ljl/Bv4XHF8KTi4Fp5eC2X/Az2bPPvUzeGj6NBjXeZ@ZnL@Bdxrol2vzdWnvvy3tdbOUHh51oCAkHh53AmmaenjSJfww8vC0EyFBFMQ0HMQkTmlCSUjSaBAOIkJSEiY09sM0jQKaBANKKCVJHPhxGvo0iWgUOaGHs46bh3fv "Assembly (gcc, x64, Linux) – Try It Online")**
This is a variation on the same theme (it still takes the input as a pointer to the beginning of a NUL-terminated ASCII string), but it pulls out all the stops to really optimize for size:
* It uses the ultra-compact x86 string instructions. In this case, `lods`, which loads a byte into `al` from the address in `rsi`, and also increments `rsi` to point to the next byte, using a single-byte encoding.
+ In order to know whether to increment or decrement the source pointer, the `rsi` instruction implicitly depends on the direction flag (`DF`). Normally, you'd need to explicitly clear that flag with the `cld` instruction, but, in this case, since we're running on a \*nix-like operating system, per the challenge, we can assume it is already clear. (Also, when you're defining a custom calling convention, the state of the flags can be part of that; see below.)
* It uses a custom calling convention so that we can (A) take the input string in the `rsi` register, which is what the `lods` instruction expects, saving us from having to copy it from one register to another, and (B) build the result in a custom register (`edx`), freeing up `eax` to use as a scratch register (because this is what the `lods` instruction uses as an implicit destination operand).
* The `lods` instruction is only loading a single byte, so it only modified the low-order byte of the `eax` register (`al`). But the `lea` instruction that we use to perform multiple arithmetic operations in a single instruction only works on the full 64-bit register, so we need to make sure that the high values are clear. We could do this with an explicit `movzx` after the `lods` instruction, but that would consume a lot of bytes. So, instead, we do it once, outside of the loop, with a single `xor` instruction. This clears the entire `rax` register, which works because we only ever touch the low-order byte (`al`).
+ Another neat trick falls out of this: because we don't touch the high-order byte (`ah`), it's guaranteed to be zero through all iterations of our loop, so we can compare (`cmp`) the source pointer (string) to `ah` instead of comparing it to a literal 0, which saves us one byte in the encoding.
```
SumDigits:
-- ; cld ; can assume DF is always clear on Linux)
31 C0 xor eax, eax ; eax = 0 (al = 0, ah = 0)
31 D2 xor edx, edx ; edx = 0 (holds result)
Loop:
AC lods ; al = BYTE PTR [rsi]
8D 54 02 D0 lea edx, [rdx + rax - '0'] ; edx += (eax - '0')
38 26 cmp BYTE PTR [rsi], ah ; is BYTE PTR [rsi] == ah (which is 0)?
75 F7 jne Loop ; loop back if not equal (non-zero)
C3 ret ; result is in edx
```
The custom calling convention is a pretty major "cheat" here, but it's not unusual in the "real world" to use a custom calling convention when writing code in assembly. If you're going to call it from C, you need to take steps to match the standard C calling convention, but who says we're calling it from C?! We don't need no stinkin' C! :-)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 23 bytes
```
n=>eval([...n].join`+`)
```
[Try it online!](https://tio.run/##bcxNCoMwEEDhfY/hSikNmZ8kMwt7kVIwWC2KJFKL109dF7cfvDfHPW79Z1q/t5RfQxnbktr7sMelfhhj0tPMeUrdtWtKn9OWl8Es@V2PdQVIVdNc/lREThQs8gkTMDhF78iJBiUkYY@eiYQwqLMowqABvJIqBQfWCVoNrMxHeCzLDw "JavaScript (Node.js) – Try It Online")
Takes input as a string
## [JavaScript (Node.js)](https://nodejs.org), 26 bytes
```
n=>eval([...""+n].join`+`)
```
[Try it online!](https://tio.run/##ZcixDoIwEADQ3a@4MEGIRdCBBT7A1dGYcIEDSpo7Qg/072tX4/KGt@CBvt/sqmeWgcLYBG5aOtClT2NMkuT8MotY7vIuC72wF0fGyZSOaVlds@z0e3Vd/115qW4xiwIcegWlSI@ewHpQkbjbRDDKBvdHDJiRB0fwtjrLrrB7yxPQZxUmVosOWBTVCocv "JavaScript (Node.js) – Try It Online")
Takes input as a number, doesn't work if the number is too large for JavaScript to stringify naturally
[Answer]
# MATL, 3 bytes
```
!Us
```
Try it out at [MATL Online](https://matl.io/?code=%21Us&inputs=%27123%27&version=22.7.4)
**Explanation**
```
% Implicitly read in first input, a 1 x N string
! % Flip it so that it is N x 1 character array (one character per row)
U % Convert each row from a string to a number
s % Sum the resulting N x 1 numeric array
% Implicitly display the result
```
[Answer]
# [Python](https://www.python.org), 24 bytes
```
lambda n:sum(map(int,n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY7chJzk1ISFfKsiktzNXITCzQy80p08jQ1IdIbC4qAfI00oGhBaYmGJkx8wWJDI2MIEwA)
Input as a string.
## [Python](https://www.python.org), 29 bytes
```
lambda n:sum(map(int,str(n)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhZ7cxJzk1ISFfKsiktzNXITCzQy80p0ikuKNPI0NTUharYVFAEFNdJAUkBcUFqioQmXXLDY0MgYwgQA)
Input as an integer.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
SO
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/2P//f0MjYwA "05AB1E – Try It Online")
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 14 bytes
```
digits(10)+sum
```
[Try it online!](https://tio.run/##Dcs5DoQwEATAnJfYIvFcnumA36xYOeAQmPcbKq/zOvqxj3VJ49f@rd@JSp7vZxt5ms6r7T2tSUjJwNXEAg5hCa1cVSSEHVY4QglOFQKIGxULLnCF6hdzHi8 "Proton – Try It Online")
`digits(x, y)` converts `y` into digits in base `x` and `sum` performs sum. Therefore, `digits(10)` is a partial function that becomes `y => digits(10, y)` and `+ sum` chains it with `sum` so an input will be called with `digits(10)(...)` first, and then the result is called with `sum(...)`.
This is 6 bytes shorter than the straightforward `x=>sum(digits(10,x))`.
[Answer]
# Excel, ~~32~~ ~~31~~ 30 bytes
```
=SUM(0+(0&MID(A1,ROW(A:A),1)))
```
Input in cell `A1`.
*Thanks to **user117069** and **EngineerToast** for the two bytes saved*.
[Answer]
# [Vyxal 3.0.0-beta.1](https://github.com/Vyxal/Vyxal/tree/version-3), 9 bytes
```
'%%O48-/+
```
[Try it online! (link is to literate version)](https://vyxal.github.io/#WyJsIiwiIiwiIiwiJyUlIG9yZCA0OCAtIGZvbGQtICsgIiwiMjAwMDAwMDAwNCJd)
Unlike my v2 answer, there is no sum flag, sum built-in, cast to int or cast to string built in in this version of vyxal (because it's a beta release - what do you expect?).
## Explained
```
'%%O48-/+
'%% ## Format the input as a string
O48- ## get the ordinal value of each character and subtract 48 to get the digit value
/+ ## fold by addition
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~29~~ ~~27~~ 25 bytes
```
f(i){i=i?i%10+f(i/10):0;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI1OzOtM20z5T1dBAG8jTNzTQtDKwrv2vnJmXnFOakqpgU1ySkpmvl2HHlZlXopCbmJmnoclVzaUABAVFQKE0DSXVlJg8JR2FNA1DI2NNTWvschYWFjjlDA2MTECStf8B "C (gcc) – Try It Online")
*-2 bytes thanks to Giuseppe*
*-2 bytes thanks to c--*
Takes input as `int`.
C's `int` isn't large enough for the last test case.
~~The bracket around the ternary is truly awful. Wish I could remove that.~~ Thanks c-- again.
# [C (gcc)](https://gcc.gnu.org/), ~~38~~ 36 bytes (no recursion).
```
a;f(i){for(a=0;i;i/=10)a+=i%10;a=a;}
```
[Try it online!](https://tio.run/##dclBDoIwEEDRfU/RYEhmomKLLpqM9SRuJq3VSbAYxBXh7BX38pf/hf09hFKYEghOqR@AvSEhOXhrkLdeamuIPdNcNpJD94k3fX6PUfrmcVGSR/1kyYBqUnrpNSwrQVXHa652OoFtj4j035xzq2ZNe/rhXL4 "C (gcc) – Try It Online")
*-2 bytes thanks to Giuseppe*
Takes input as `int`.
C's `int` isn't large enough for the last test case.
# [C (gcc)](https://gcc.gnu.org/), 56 bytes (no recursion) (outgolfed by [c--](https://codegolf.stackexchange.com/a/258280/108879) using recursion).
```
a,n;f(char*s){for(a=0,n=strlen(s);n--;++s)a+=*s-48;a=a;}
```
Takes input as string
[Try it online!](https://tio.run/##fYzBjoIwFEX3fAVhMkkrYNq@V/peOvglbpoiSuJUQ3Fl/HaGzF7v6uSe3Bvbc4zrGprkRxEvYd5l@Rxvswi9alKfl/l6SiJLn9rW13WWoe53uUXyoQ/@tX5NKV4fw6n8ycsw3faXQzGlpfwNUxKyeBbllvu8VaOovodjqppyI22gktK/sUT0wWpl8IMGjdqy6SxYYsdggLAzHQIQGMdWGSLU7HTHwAzOamXJKHbIiNvw//q1/gE "C (gcc) – Try It Online")
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$1\log\_{256}(96)\approx\$ 0.823 bytes
```
S
```
[Try it online!](https://fig.fly.dev/#WyJTIiwiMTIzNDUiXQ==)
Builtin
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 9 bytes
```
sumdigits
```
[Try it online!](https://tio.run/##FctNCsIwEEDhqwxdNZBC5ifJzEIvIi4K0hJQGdq68PSx7t63eD5vbVq9L3CBvn9ej7a2Y@@z@/M7OkxX8K29jzOHPwZYRg8hwg2JI6hqBEwkERgFs1HJnNWqMbFKoSLMylQtJ1IVtIrF2IxrxpSVklUxkXO8h/4D "Pari/GP – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 6 bytes
```
.
$*
1
```
[Try it online!](https://tio.run/##DcsxDsJADATA3u8IEkqBzl77vPuCfAMKChqKKP8/mH7O9/X5vtbtfjzXw7bdfC0PGEnzEWnw9FLMQlEtBJgzZgJEtGoEma72KUjo8lGMoU5l/uMP "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.
$*
```
Convert each digit to unary.
```
1
```
Convert the sum to decimal.
[Answer]
# Typescript Type System + `hotscript`, ~~92~~ 87 bytes
```
import{Pipe,S,T}from"hotscript"
type _<U>=Pipe<U,[S.Split<"">,T.Map<S.ToNumber>,T.Sum]>
```
I just found out about this library that basically turns the Typescript Type System into a full-on functional programming language and it's amazing
Saved 5 bytes by taking input as a string instead of a number
[TS Playground Link](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgVAQwM4AIASKBmUIgEQAWEMSAxlMGDHgFAwCeYApigPoA8AqgHwC8aAOgAKlJlwA0AbUEBlATLAAbYDHZ483cYIAqAgLIIw7WQO0QAcgFcQAIyZRNO+dYC63GnUYsoTJAEYUXjY1PwAmAGYNGgB6aJR4gD0Afk9mFB8kUMDgvAAOfKjY+JRk1O9fcOyOPD8ABlCAFkK4xKSgA)
```
import{Pipe,S,T}from"hotscript"
type _<U>= // define hotscript lambda with string argument U
Pipe<U,[ // pipe U to:
S.Split<"">, // split on "" (= character list)
T.Map<S.ToNumber>, // map each letter to number
T.Sum // sum
]> // end pipe
```
[Answer]
# Julia, 12 10 bytes
Tacit Julia strikes again!
```
sum‚àòdigits
```
Explanation:
```
digits: take an integer and return a vector of its digits in base 10 (default)
‚àò: function composition
sum: sum a collection
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v9i2uDT3UceMlMz0zJJiLkMjY4UaO4ViEFFQlJlXkpP3/z8A)
-2 thanks to MarcMush
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$2 \log\_{256}(96)\approx\$ 1.646 bytes
```
dS
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhaLUoIhDCh_wWJDI2MIEwA)
```
d digits of input
S calculate sum
```
[Answer]
# [Perl 5](https://www.perl.org/) -p, 19 bytes
```
s/./$s+=$&/ge;$_=$s
```
[Try it online!](https://tio.run/##DctNCsIwEAbQywQ3UpP5y8yH9CyuShHEBuP5Hfv2b2yfl2XOeqtlXtdyqft2L4@1zEwhJQN3Ews4hCW0c1eREHZY4wglOHUIIG7ULLjBFapn/B3j@zzeM5fxBw "Perl 5 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 22 bytes
```
f=n=>n&&n%10+f(n/10|0)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9mC0R5tnZ5amp5qoYG2mkaefqGBjUGmv@T8/OK83NS9XLy0zXSNAyNjDU1uVDFLCwsMMQMDYxMNDX/AwA "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 21 bytes
```
f=n=>n&&n*9%9-f(n/~9)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9mC0R5tnZ5amp5WpaqlrppGnn6dZaa/5Pz84rzc1L1cvLTNdI0DI2MNTW5UMUsLCwwxAwNjEw0Nf8DAA "JavaScript (Node.js) – Try It Online")
It is shorter, but with floating point errors...
[Answer]
# x86-64 Linux assembly, 18 bytes
Lazy C translation. Follows calling convention of System V AMD64 ABI: input null-terminated string in rdi, output in rax.
```
sum_digits:
xor eax, eax ; sum = 0
L:
movsx edx, BYTE [rdi] ; c = *str
inc rdi ; ++str
lea eax, [rax-48+rdx] ; sum += c - '0'
cmp BYTE [rdi], 0
jne L ; while (*str)
ret
```
Objdump:
```
0000000000401110 <sum_digits>:
401110: 31 c0 xor eax,eax
0000000000401112 <L>:
401112: 0f be 17 movsx edx,BYTE PTR [rdi]
401115: 48 ff c7 inc rdi
401118: 8d 44 10 d0 lea eax,[rax+rdx*1-0x30]
40111c: 80 3f 00 cmp BYTE PTR [rdi],0x0
40111f: 75 f1 jne 401112 <L>
401121: c3 ret
```
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), ~~19~~ 16 bytes
```
say [+] get.comb
```
[Try it online!](https://tio.run/##K0gtyjH7/784sVIhWjtWIT21RC85Pzfp/39DI2MA "Perl 6 – Try It Online")
`get()`: gets a single line from stdin (parens not required)
~~`.univals()`: maps a string of numerical unicode chars to a list of their values. I'm just using it in place of `.split("")`, which would be 2 bytes longer.~~
`.comb`: splits out to list of characters (thanks
[@Mark Reed](https://codegolf.stackexchange.com/users/4133/mark-reed))
`[+]`: reduces the list by addition.
`say`: writes to stdout
[Answer]
## Pascal, 114 bytes
This is a full `program` according to ISO standard 7185 “Standard Pascal”.
The built-in data type `integer` comprises (at least) all integral values in the range `‚àímaxInt..maxInt`.
The value of `maxInt` is *implementation-defined*.
In order to successfully test values up to and including one googol you will need a processor (this refers to the specific combination of machine, compiler, OS, etc.) defining `maxInt` ≥ 10100.
```
program p(input,output);var x,y:integer;begin y:=0;read(x);repeat y:=y+x mod 10;x:=x div 10 until x=0;write(y)end.
```
Ungolfed:
```
program digitSum(input, output);
var
x, digitSum: integer;
begin
digitSum := 0;
read(x);
repeat
begin
digitSum := digitSum + x mod 10;
x := x div 10;
end
until x = 0;
write(digitSum);
end.
```
Because in Pascal `mod` is defined to always yield a non-negative result, `digitSum` works incorrectly for negative inputs.
Injecting an `x := abs(x);` prior the loop will resolve this issue.
---
Another method is of course to *process characters*.
In Pascal it is guaranteed that the characters `'0'` through `'9'` are in ascending order and consecutive, thus `ord('9') − ord('0')` is guaranteed to yield the `integer` value `9`.
```
program p(input,output);var x:integer;begin x:=0;while not EOF do begin x:=x+ord(input^)-ord('0');get(input)end;write(x)end.
```
Input must not be followed by a newline, or replace the `EOF` by `EOLn`.
This `program` is ≥ 124 bytes
[Answer]
# [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), 35 bytes
```
for(;i<length(a);i++)b+=a/10^i%10;b
```
[Try it online!](https://tio.run/##TYvLCsIwEADv/YqACA09mM0mzS61vyJ9RQ1olKb1In577UGwx2Fmun4Z/DlEL4ZwSfM9b@U71KrqarWcH2NehePNx8t0XUUVikJ2Rd0eQJ3CHtZq@WRZrH8raJR/IqINgdJmgwgGLOvSoiV2jBrJlLo0iITasVWayAA7KBmZ0VlQlrRiZ9iYdZRZthNNbETfTv3VJzH6aR6jeLW32Ys8zc/n6FNaRaOaJJcv "bc – Try It Online")
Using the default `scale=0` i.e. no decimals, divide by `1,10,100,...` successively (`a/10^i`), and `%10` to add only the last digit to `b`. When the `for` loop finishes, print the sum. `;b`
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 5 bytes
```
+/10\
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs9LWNzSI4eJKUzA0MDIB0RYWFgA0VARb)
[Answer]
# APL, 5 bytes
```
+/⍎¨⍞
```
Explanation:
* `‚çû` reads standard input as a character vector
* `⍎¨` converts each digit to its numeric value
* `+/` computes the sum
[Try it online!](https://tryapl.org/?clear&q=%7B%2B%2F%E2%8D%8E%C2%A8%E2%8D%95%E2%8D%B5%7D%C2%A8123%20888%201024%20%273141592653589793238462643383279502884197169399375105820974944592%27&run)
[Answer]
# Javascript, 42 bytes
This new and improved version supports BigInt, as well as numbers and strings. It uses tsh's idea, but it first changes the type and uses the ES10 BigInt. (It also happens to be the shortest I could come up with!)
```
a=n=>eval("x=BigInt(n);x&&x%10n+a(x/10n)")
```
I also tried playing around and created these functions:
```
// BigInt/String/Number
b=n=>eval("l=0;(n+[]).split('').forEach(t=>l+=+t);l")
// String only
c=n=>eval("l=0;n.split('').forEach(t=>l+=+t);l")
// BigInt only
d=n=>n&&n%10n+d(n/10n)
// String/Number
e=n=>+n&&+n%10+e(+n/10|0)
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 39 bytes
```
param([string]$i)($i|% t*y)-join"+"|iex
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXI7q4pCgzLz1WJVNTQyWzRlWhRKtSUzcrPzNPSVupJjO14v///4aW5kYmZsaGZhZmxhamAA "PowerShell – Try It Online")
[Answer]
# Rust, ~~54~~ ~~47~~ 30 bytes
```
|n|n.map(|b|b as u64-48).sum()
```
A function that takes a `std::str::Bytes` and returns a `u64`. For the purpose of this challenge, I consider `std::str::Bytes` to be an iterator of ASCII-characters, which meets our general criteria for a string.
Previous versions:
```
|mut n|{let mut s=0;while n>0{s+=n%10;n/=10;}s}
```
```
|n|n.to_string().bytes().map(|d|u64::from(d)-48).sum()
```
[Answer]
# [Leaf-Lang](https://gitlab.com/Breadleaf/leaf-lang), 95 bytes
`macro p pop pop end""input splitString 0:s""=0=while p p toNumber s+:s""=0=stop p p 1p s print`
## Explaination
Leaf Lang is a lang I made in my free time in college. It is a stack-based programming language. It can be hard to understand, so I wrote a step-by-step golf of my solution.
### The readable solution
```
"" input splitString # split input into array of strings
0 : sum # sum = 0
"" = 0 = # loop condition
while
pop pop pop pop # clean stack of condition
toNumber sum + : sum # sum = sum + toNumber
"" = 0 = # loop condition
stop
pop pop pop pop # clean stack of condition
pop # clean stack of stop condition
sum # add sum to stack
print
```
### Compressed readable solution, 109 bytes
`""input splitString 0:sum""=0=while pop pop pop pop toNumber sum+:sum""=0=stop pop pop pop pop pop sum print`
### Macro optimization #1, 98 bytes
`macro p pop end""input splitString 0:s""=0=while p p p p toNumber s+:s""=0=stop p p p p p s print`
This uses a macro to shorten the long chains of `pop` calls.
### Macro optimization #2, 96 bytes
`macro p pop pop end""input splitString 0:s""=0=while p p toNumber s+:s""=0=stop p p pop s print`
### The final golf code, 95 bytes
`macro p pop pop end""input splitString 0:s""=0=while p p toNumber s+:s""=0=stop p p 1p s print`
The final code abuses my parser to push a `1` to the stack then call the `p` macro to essentially make a single `pop` call.
] |
[Question]
[
This is a simple challenge.
The task is to write code that outputs a 448\*448 square image with 100% transparency. The output should follow the [standard image rules](https://codegolf.meta.stackexchange.com/questions/9093/d).
[Answer]
# Imagemagick in some shell, 35
```
convert -size 448x448 xc:none a.png
```
Is this allowed?
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 [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. Prints 448-by-448-by-4 array representing a 448-by-448 rgba image.
```
448 448 4⍴0
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@JiYUCGD/q3WIAEvqvAAYFAA "APL (Dyalog Unicode) – Try It Online")
`⍴` is **r**eshape
[Answer]
# Go, 70
```
import i"image";func a()i.Image{return i.NewRGBA(i.Rect(0,0,448,448))}
```
Never seen a golf in Go before. Defines a function called a that outputs the image
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
448ṁ4¬¥þ
```
A niladic Link which yields a 448 by 448 RGBA array of transparent black pixels.
**[Try it online!](https://tio.run/##y0rNyan8/9/ExOLhzkaTQ2sOLT287/9/AA "Jelly – Try It Online")**
### How?
```
448ṁ4¬¥þ - Link: no arguments
448 - 448
þ - outer-product with: -- i.e. [[f(x,y) for y in [1..448]] for x in [1..448]]
¥ - last two links as a dyad:
ṁ4 - mould like [1,2,3,4] -- e.g. x=7 -> [7,7,7,7]
¬ - logical NOT -> [0,0,0,0]
```
[Answer]
## JavaScript (ES6), ~~74~~ 69 bytes
```
f=
(_=document.createElement`canvas`)=>_.toDataURL(_.height=_.width=448)
;document.write(f());
```
Returns a PNG image encoded as a data: URL suitable e.g. for setting as the `src` of an `HTMLImageElement`. Edit: Saved 3 bytes thanks to @Shaggy and a further 2 bytes thanks to @Arnauld.
[Answer]
# Java 8, 23 (or 20) bytes
```
v->new int[448][448][4]
```
Returns a 3D array of 448x448x4 0s.
[Try it online.](https://tio.run/##LU5LCoMwEN17ilkmC7NyUZAWeoC6sXRTXKQxldg4Sn5FimdP44eBBzPvM6/nged9@4lCc2vhxhX@MgCFTpo3FxKqdd0Oz2YdEOQxqhYCLROxZAms404JqADhDDHkF5TfzVAUp@aAJpardPIvnaSHI6xBQ3pJamcUdimdm87S/WU9WycHNnrHpsQ6jaRPbZl3SrOrMXy2rJVyuo@7myATBL3WlB7dlvgH)
**Explanation:**
```
v-> // Method with empty unused parameter and 3D integer-array as return-type
new int[448][448][4]
// Create a 3D array of dimensions 448 by 448 by 4 (filled with 0s by default)
```
---
```
v->new int[448][448]
```
Returns a 448x448 matrix of 0s.
In Java, RGBA values can be [represented by an integer](https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/image/BufferedImage.html#TYPE_INT_ARGB). The hexadecimal `0x00000000` would represent `00` for red, green, blue, and alpha respectively. And `0x00000000` is equal to the integer `0`.
[Try it online.](https://tio.run/##LY47DoMwEER7TrGlXeCKIhJKpBwgNInSIArHOMjELMi/CEWc3TGfZqWdfTszPQ8879tPFJpbCzeu8JcBKHTSvLmQUK3rJtRN3YAgz1G1EGiZ5CVLwzrulIAKEM4QQ35B@d3wojg124jlyk3@pRN34GF1GVIauTujsEvW3HSW7mn32To5sNE7NqWr00j6VJR5pzS7GsNny1opp8e4fxNkgqDXmtKj2BL/)
[Answer]
# Java 8
**Saving the image to a file with path `s`, 101 bytes**
```
s->javax.imageio.ImageIO.write(new java.awt.image.BufferedImage(448,448,2),"png",new java.io.File(s))
```
[Try it online... somehow](https://tio.run/##XY4xa8MwEIV3/YrDkwSOhpKhYJohEEOGkiFj6XCxT845tmwkJQ4Y/3ZXTkKHDMcb7vser8YbruryMhcNeg/fyHYUbAM5gwVBPt46LsHIY3BsKzDckMWWVDi7bvCwuxfUB@5sNon@emq4AB8wxHh4bax7qT@/gK7yCt7NUeRgvma/2tRxy11zixVxp/dL7g96cBxIWhpg@WscwhPR26sx5Kh8gHK9/kyX@1Bp0tsqSf@N2JXH2dIrNWfCaCOTZ8GCqUxM0/wH)
**Returning the BufferedImage, 46 bytes**
```
v->new java.awt.image.BufferedImage(448,448,2)
```
**Saving the image to the file `f`, 83 bytes**
```
f->javax.imageio.ImageIO.write(new java.awt.image.BufferedImage(448,448,2),"png",f)
```
**Dumping PNG to STDOUT, 92 bytes (thanks ASCII-only!)**
```
v->javax.imageio.ImageIO.write(new java.awt.image.BufferedImage(448,448,2),"png",System.out)
```
[Try it online!](https://tio.run/##XY4xa8MwEIV3/YojkwSOhpChYNqh0ECGkiHQpXS42if3XFsy0tlOMf7trp1uHY5veN97XI0D7uvyeykaTAlekf2k2AtFhwXBaRoCl@D024bByFcMY4KXW0GdcPD5rLr@s@ECkqCsuOvtuqKvEtlX7x@AsUoG/jcndQL3uAz7p3p94Wa5xYo42PPG88WOkYW0pxG23OIof4p97p2jSOVd1MfjQ7bdwWS7zle77PqThFobejFLrpx12vdNY3I1z8sv)
Thanks to Kevin for saving a byte for the second and fourth solutions!
[Answer]
# [05AB1E](https://tio.run/##AR0A4v9vc2FiaWX//zTDhTDCuDQ4OMKp0LjCuMKu0Lj//w), ~~12~~ ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
448LDδ4Å0
```
[Try it online.](https://tio.run/##yy9OTMpM/f/fxMTCx@XcFpPDrQb//wMA)
or alternatively:
```
¾4Ž1ÂDиии
```
[Try it online.](https://tio.run/##yy9OTMpM/f//0D6To3sNDze5XNgBgv//AwA)
-2 bytes thanks to *@Emigna*.
-1 byte thanks to *@Adnan*.
Outputs a 448x448x4 3D list of 0s.
**Explanation:**
```
448LD # Push a list in the range [1,448], and duplicate it
δ # Outer product; apply the following double-vectorized:
4Å0 # Push a list of 4 0s: [0,0,0,0]
# (and output the result implicitly)
Ž1ÂD # Push compressed integer 448, and duplicate it
и # Create a list of 448 times 448
4 и # Transform it into a list of 448 times 448 times 4
¾ и # Transform it into a list of 448 times 448 times 4 times 0
# (and output the result implicitly)
```
[See this 05AB1E answer of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž1Â` is `448`.
[Answer]
# Processing, 66 bytes
```
PGraphics g=createGraphics(448,448);g.beginDraw();g.save("a.png");
```
[Answer]
# Python 2.7, 17 Bytes (22 With Print)
```
[[[0]*4]*488]*488
```
With Print:
```
print[[[0]*4]*488]*488
```
As variable:
```
x=[[[0]*4]*488]*488
```
As an array of RGBA is allowed, that is what I have created above, defaulting to all 0's - meaning black, but totally transparent.
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM68kOjraIFbLBIgsLMDE//8A "Python 2 – Try It Online")
[Answer]
# HTML, 25 bytes
Is this valid?
```
<svg height=448 width=448
```
[Test it](https://codepen.io/anon/pen/VRrQPY) (`background` applied with CSS so you can "see" it)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 21 bytes
```
_=>new int[448,448,4]
```
[Try it online!](https://tio.run/##TcixCsMgEADQvV/hqOQKGRwKpxn7Cx2CFCoKd4KBxNCh@O3WBAod3vL8dvUbtfuevVleHHwBymUGcJOItj3tlMNbHKX1DU6u4SUuq@wpyI5IpjfSMKjPr7k3n83/nXqLZDSmYx8rlSCjHNVMwJCcwlpr@wI "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# Rust - ~~206~~ ~~201~~ 168 bytes
```
use std::{io::Write,fs::File};fn main(){let mut v=vec![0,0,2,0,0,0,0,0,0,0,0,0,192,1,192,1,32,0];v.extend(vec![0u8;802816]);File::create("o.tga").unwrap().write(&v);}
```
This writes an actual, readable o.tga file, without any libraries or builtin functions, using the TGA binary format per <http://paulbourke.net/dataformats/tga/> , by hard coding the width and height into the binary file header.
---
-5 bytes shorten filename, fix img size, @ASCII-only
[Answer]
# [dzaima/APL + APLP5](https://github.com/dzaima/APL#processing-integration), ~~18~~ 16 bytes
```
{P5.img⍴∘0,⍨448}
```
Function that outputs an image object that can be drawn to the screen (for no effect) or converted back to pixel values.
-2 thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn)!
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 48 bytes
```
_=>(Enumerable.Repeat((0,0,0,0),200704),448,448)
```
Apparently outputting `[1D array of pixels, width, height]` is ok, so this outputs a tuple of `(IEnumerable of pixels, width, height).
[Try it online!](https://tio.run/##TcxBC4JAEAXge7@i40xusopQsCp0MBA6dekYuowwi66h6yn67ZsKYQwPHh@P0eNRj@yvk9VpXxvSTkBZ2KmjoapbSoGtE3/BfGtNlvtnlsM2D@/0osoBSLEeiljKk0xQJMl5CXq1a/ph@brnTCpOZ1QcBPj@sZnZrGxmfgzsCBqIMSwddVFYtNSRdRcHfIhkYBDVurmxJUD18V8 "C# (Visual C# Interactive Compiler) – Try It Online")
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 58 bytes
```
_=>Enumerable.Repeat(Enumerable.Repeat((0,0,0,0),448),448)
```
The original matrix returning answer.
Since the image IO rules allow output as a matrix of RGB values, this submission outputs a matrix of RGBA values, represented by tuples with four values, all being 0.
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5@UlZpcouPpmleam1qUmJSTaoPM1sjMK9FBwpp2dnZptnb/423tEKr0glILUhNLNDBFNAx0wFBTx8TEAkL8t@ZKyy9KTUzO0ChLLFJIVMjMU0jTMNTUrEYRzwSJJ2pyhRdllqRqZGorKShpWoM5Ppl5qRqa1ly1/wE "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# PHP, 192 bytes
Sadly, PHP kinda sucks in that aspect because it requires a whole lot of code. But then again, where doesn't PHP suck.
```
$i=imagecreatetruecolor(448,448);imagesavealpha($i,true);$b=imagecolorallocatealpha($i,0,0,0,127);imagefill($i,0,0,$b);imagepng($i,'i.png');header('Content-type: image/png');readfile('i.png');
```
Ungolfed:
```
$i=imagecreatetruecolor(448,448); // Create a new image with a set width
imagesavealpha($i,true); // Tell PHP to save alphachannels on that image
$b=imagecolorallocatealpha($i,0,0,0,127); // set the actual transparency values
imagefill($i,0,0,$b); // Fill the image with the color saved above
imagepng($i,'i.png'); // Save the file as PNG
header('Content-type: image/png'); // Set the content type for the browser
readfile('i.png'); // Read the file and output it
```
Obviously, if you just want to create it without outputting it, you can omit the `header()` and `readfile()` commands. Still, it's idiotically long.
[Answer]
**Python 3.7 - PIL Imported, 30 bytes**
```
Image.new("LA",[448]*2).show()
```
This requires an import but has the benefit of creating and displaying an actual image file rather than an abstract empty array.
Explanation:
```
from PIL import Image
Image.new( // create a new image
mode="LA" // select LA colour mode, this is grey-scale plus an alpha channel
size=[448]*2 // size argument needs to be a 2D tuple, [448*2] is a better golf shot than (448,448)
color=0 // populates the image with the specified colour, helpfully preset to transparent
).show() // display the image object
```
Image.show() will open the image in your default image program. In my case this opens a temporary bitmap file in Windows Photo Viewer but results may vary. Arguably this is cheating since the bitmap representation contains no transparency
Variations...
```
Image.new("LA",[448]*2) // 24 bytes but doesn't open image
Image.new("LA",[448]*2).show() // 30 bytes, shows you a bitmap
Image.new("LA",[448]*2).save("x.png") // 37 bytes, saves image to disk
```
[Answer]
# MATLAB, 31 bytes
```
imwrite(nan(448),'.png','tr',1)
```
Creates a 448 x 448 matrix of `NaN` values, and then uses `imwrite` to save them to a PNG file named `'.png'` and sets the transparency to 1, making it transparent. The [`'Transparency'` parameter name](https://www.mathworks.com/help/matlab/ref/imwrite.html#btv3cny-1-Transparency) is able to be abbreviated to `'tr'` as MATLAB allows for partial string matching of parameter names as long as the shortened version is unique among available parameters.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes
```
x4Wẋ448Ɗ⁺
```
[Try it online!](https://tio.run/##y0rNyan8/7/CJPzhrm4TE4tjXY8ad/3/DwA "Jelly – Try It Online")
Outputs a 448x448x4 array
Thanks to @JonathanAllan for saving a byte.
[Answer]
# [Red](http://www.red-lang.org), 33 bytes
```
a: make image![448x448 0.0.0.255]
```
Opacity defaults to fully opaque(0)
This is how to use it /a full program/ :
```
Red [ ]
a: make image! [ 448x448 0.0.0.255 ]
view [ image a ]
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 10 bytes
```
º4♦7*_ß{.a
```
[Try it online!](https://tio.run/##y00syUjPz0n7///QLpNHM5eZa8Ufnl@tl/j/PwA "MathGolf – Try It Online")
## Explanation
```
º push [0]
4 push 4
♦7* push 64*7=448
_ duplicate TOS
ß wrap last three elements in array (stack is now [[0], [4, 448, 448]])
{ foreach in [4, 448, 448]
. repeat TOS x times
a wrap TOS in array
```
This method saves 1 byte compared to the "standard" `♦7*_4º*a*a*`
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 39 bytes
```
_=>[w=448,w,Array(w*w).fill([0,0,0,0])]
```
Apparently outputting `[height, width, 1d array of RGBA values]` is ok.
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1i663NbExEKnXMexqCixUqNcq1xTLy0zJ0cj2kAHDGM1Y/9bcyXn5xXn56Tq5eSna6RpaGr@BwA "JavaScript (Node.js) – Try It Online")
-3 bytes thanks to @Arnauld
[Answer]
# SmileBASIC, 27 bytes
```
DIM A[448,448]SAVE"DAT:I",A
```
Saves a 2-dimensional 448x448 array filled with 0s to a file named `DAT:I` (Which is shorter than defining a function that returns the array, somehow)
The standard formats (used by all graphics functions) for colors in SmileBASIC are 32 bit ARGB and 16 bit 5551 RGBA, and `0` is transparent in both of them.
[Answer]
# [ScPL for iOS Shortcuts](https://scpl.dev), 98 bytes
```
Text"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
Base64Encode Decode
ResizeImage 448
```
[](http://preview.scpl.dev/?shortcut=a010eff12cab4f4c94a15f8d4bc6109c)
[Shortcut iCloud Link](https://www.icloud.com/shortcuts/a010eff12cab4f4c94a15f8d4bc6109c)
Takes a 1x1 transparent gif encoded as base64 and resizes it
[Answer]
# [Jstx](https://github.com/Quantum64/Jstx), 24 [bytes](https://quantum64.github.io/Jstx/codepage)
```
♪☺ü@/øP♦£Q)%)£Q◄úæD)%)£Q
```
Explanation
```
♪☺ü@ # Push literal 448
/ # Store the first stack value in the a register.
ø # Push literal 0
P # Push four copies of the first stack value.
♦ # Push literal 4
£Q # Push stack values into a list of the size of the first stack value starting with the second stack value.
) # Push the value contained in the a register.
% # Push the second stack value the absolute value of the first stack value times.
) # Push the value contained in the a register.
£Q # Push stack values into a list of the size of the first stack value starting with the second stack value.
◄úæ # Push literal \n
D # Push the sum of the second and first stack values.
) # Push the value contained in the a register.
% # Push the second stack value the absolute value of the first stack value times.
) # Push the value contained in the a register.
£Q # Push stack values into a list of the size of the first stack value starting with the second stack value.
```
[Try it online!](https://quantum64.github.io/Jstx/JstxGWT-1.0.3/JstxGWT.html?code=4pmq4pi6w7xAL8O4UOKZpsKjUSklKcKjUeKXhMO6w6ZEKSUpwqNR)
[Answer]
# [R](https://www.r-project.org/), 21 bytes
```
array(0,c(448,448,4))
```
[Try it online!](https://tio.run/##K/r/P7GoKLFSw0AnWcPExEIHjDU1//8HAA "R – Try It Online")
Returns a 3D-array of zeroes.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
```
448ÆZç4Æ0
```
[Try it online!](https://tio.run/##y0osKPn/38TE4nBb1OHlJofbDP7/1w0EAA "Japt – Try It Online")
[Answer]
## C++, SFML, 131 bytes
```
#include <SFML/Graphics.hpp>
void f(){sf::Image i;i.create(448,448);i.createMaskFromColor(sf::Color::Black);i.saveToFile("a.png");}
```
[Answer]
# JavaScript + HTML, 56 bytes
```
location=C.toDataURL()
```
```
<canvas id=C width=448 height=448>
```
Clicking "Run code snippet" will generate a 448x448 transparent PNG in an IFRAME. You may then right-click "Save image as..." to download it to your computer.
] |
[Question]
[
In this challenge you've to print multiplication tables by input, Here are some examples:
```
Input: 2
Output:
0 2 4 6 8 10 12 14 16 18 20
Input: 20
Output: 20 40 60 80 100 120 140 160 180 200
```
# Rules
1. The shortest code in bytes wins.
2. This challenge is a code-golf, It follows code-golf general rules ([code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"))
3. If, just if, your code can't print number, you can use letters, Here is an example:
Input: B
Output: B D F H J L N P R T
4. You can choose to start from 0 or your number (like 20). You can choose if put spaces or don't. The challenge is free, just take an input and print multiplication tables.
5. Your output must list the first 10 members of the times table for the given number. You may leave out 0\*n.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 4 bytes
```
10:*
```
Breakdown:
```
% Implicit input
10: % Create a list from 1 2 ... 10
* % Multiply list by input
% Implicit output
```
**[Try it online](http://matl.tryitonline.net/#code=MTA6Kg&input=NQ)**
[Answer]
# C#, ~~105~~ ~~96~~ ~~67~~ 56 bytes
Now that I know how lambda's work in C#, here is an update to my first answer:
```
n=>{for(int i=0;i++<10;)System.Console.Write(i*n+" ");};
```
Saves 11 bytes.
---
First post, please forgive me for anything I've done wrong. Also, feel free to give me golfing tips, as I haven't really tried it before!
```
void c(int n){for(int i=0;i++<10;){System.Console.Write(i*n+" ");}}
```
Ungolfed:
```
void c(int n)
{
for (int i = 0; i++ < 10 ; )
{
System.Console.Write(i*n+" ");
}
}
```
Thank you Jonathan Allan, can't add comments yet.
And thank you Kevin Cruijssen. I assumed I had to always include the entire program unless the question specified that snippets were allowed. Would I also be able to leave out the System. call to print to console in this case, or are using/imports required then?
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁵R×
```
Test it at [**TryItOnline**](http://jelly.tryitonline.net/#code=4oG1UsOX&input=&args=Mw)
Or first 256 cases, nicely aligned, also at [**TryItOnline**](http://jelly.tryitonline.net/#code=4oG1UsOXCuKBucOH4oKsRw&input=&args=)
How?
```
⁵R× - main link takes one argument, n
⁵ - literal 10
R - range [1,2,...,10]
× - multiply by input (implicit vectorization)
```
[Answer]
## Clojure, 70 ~~80~~ bytes
This is my first post on CG, I hope the input is OK:
**70 bytes**
```
(defn -main[& a](println(map #(* %(read-string(first a)))(range 10))))
```
**80 bytes**
```
(defn -main[& a](let[n(read-string(first a))](println(map #(* % n)(range 10)))))
```
The program will read a number as a stdin argument and display the result:
## Output
```
lein run 10
(0 10 20 30 40 50 60 70 80 90)
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes
```
TL*
```
**Explanation**
```
T # literal predefined as 10
L # 1-based range: [1,2,3,4,5,6,7,8,9,10]
* # multiply with input
```
[Try it online!](http://05ab1e.tryitonline.net/#code=VEwq&input=MjA)
[Answer]
# Perl, 19 bytes
Includes +1 for `-n`
Run with the input on STDIN:
```
perl -M5.1010 -n table.pl <<< 8
```
`table.pl`:
```
say$_*$`for/$/..10
```
[Answer]
## Haskell, 16 bytes
```
(<$>[1..10]).(*)
```
Usage example: `(<$>[1..10]).(*) $ 4` -> `[4,8,12,16,20,24,28,32,36,40]`.
Pointfree version of: `f n = map (n*) [1..10]`.
[Answer]
# [Jellyfish](http://github.com/iatorm/jellyfish), 8 bytes
```
p*r11
i
```
[Try it online!](http://jellyfish.tryitonline.net/#code=cCpyMTEKIGk&input=MjA)
Quite simple: `r11` gives the list `[0, 1, ..., 9, 10]`, `i` reads the input, `*` multiplies them and `p` prints the resulting list.
[Answer]
# R, 11 bytes
```
scan()*0:10
```
30 char.
[Answer]
# PHP, 34 bytes
(34 bytes)
```
for(;$i++<10;)echo$i*$argv[1].' ';
```
(34 bytes)
```
for(;++$i%11;)echo$i*$argv[1].' ';
```
(34 bytes)
```
while($i++<10)echo$i*$argv[1].' ';
```
(35 bytes)
```
for(;$i++<10;)echo' '.$a+=$argv[1];
```
(~~41~~ 40 bytes)
```
<?=join(' ',range(0,10*$a=$argv[1],$a));
```
```
<?=join(' ',range($a=$argv[1],10*$a,$a));
```
(44 bytes)
```
foreach(range(1,10)as$i)echo$i*$argv[1].' ';
```
[Answer]
# J, 8 bytes
```
(i.10)&*
```
This is the range from `0` to `9` inclusive (`i.10`) *bonded* (`&`) wit the multiplication function (`*`). This starts at zero.
## Test cases
```
k =: (i.10)&*
k 2
0 2 4 6 8 10 12 14 16 18
k 10
0 10 20 30 40 50 60 70 80 90
k"0 i.10
0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9
0 2 4 6 8 10 12 14 16 18
0 3 6 9 12 15 18 21 24 27
0 4 8 12 16 20 24 28 32 36
0 5 10 15 20 25 30 35 40 45
0 6 12 18 24 30 36 42 48 54
0 7 14 21 28 35 42 49 56 63
0 8 16 24 32 40 48 56 64 72
0 9 18 27 36 45 54 63 72 81
```
[Answer]
# Zsh, 19 characters
```
echo {0..${1}0..$1}
```
Sample run:
(This is the interactive way to run it, equivalent with `zsh scriptfile.sh 20`.)
```
~ % set -- 20
~ % echo {0..${1}0..$1}
0 20 40 60 80 100 120 140 160 180 200
```
[Answer]
## Python 3, ~~52~~ ~~33~~ 30 bytes
```
lambda n:list(range(0,11*n,n))
```
3 bytes saved thanks to @manatwork
Formatting the output is visibly not necessary
[Answer]
## Mata, 15 29 Bytes
```
args i
mata
A=1..10
B=`i'*A
B
```
Mata is the matrix programming language in the Stata commercial statistics package. Code creates a matrix, multiplies by the input (2 in this case) and the outputs the new matrix
## Output
```
1 2 3 4 5 6 7 8 9 10
+---------------------------------------------------+
1 | 2 4 6 8 10 12 14 16 18 20 |
+---------------------------------------------------+
```
[Answer]
# Pure Bash, 18
```
echo $[{0..10}*$1]
```
The input is taken as a command-line parameter.
[Answer]
## Stata, 46 bytes
```
args i
set obs `i'
gen x=_n
gen y=x*`i'
list y
```
## Output
For i=15
```
+-----+
| y |
|-----|
1. | 15 |
2. | 30 |
3. | 45 |
4. | 60 |
5. | 75 |
|-----|
6. | 90 |
7. | 105 |
8. | 120 |
9. | 135 |
10.| 150 |
|-----|
11.| 165 |
12.| 180 |
13.| 195 |
14.| 210 |
15.| 225 |
```
[Answer]
# [Cheddar](http://cheddar.vihan.org), 20 bytes
```
n->(|>11).map(n&(*))
```
Yay for functional \o/
I don't think this needs explanation but if you'd like to me add one just ask :)
[Answer]
# Java 7, ~~61~~ 57 bytes
```
void c(int n){for(int i=0;i++<10;)System.out.print(i*n);}
```
**Ungolfed & test cases:**
[Try it here.](https://ideone.com/yozUSX)
```
class M{
static void c(int n){
for(int i = 0; i++ < 10; ){
System.out.print(i*n);
}
}
public static void main(String[] a){
c(2);
System.out.println();
c(20);
}
}
```
**Output:**
```
2468101214161820
20406080100120140160180200
```
[Answer]
# JavaScript (ES6), ~~33~~ 31 bytes
```
f=(x,i=11)=>--i&&f(x,i)+" "+x*i
```
It's a recursive solution.
[Answer]
**T-SQL 61 bytes**
Replace n with the number for which table needs to be populated. [Demo](https://data.stackexchange.com/stackoverflow/query/edit/536152)
```
SELECT TOP 11 number*n FROM master..spt_values WHERE type='P'
```
spt\_value is a undocumented table in SQL Server, you can read more about this table in
* [Purpose and meaning of spt\_values table](https://stackoverflow.com/questions/4273723/what-is-the-purpose-of-system-table-table-master-spt-values-and-what-are-the-me)
* [What does Spt\_value means](https://stackoverflow.com/questions/5229392/what-does-from-master-spt-values-mean)
I hope someone will come up with better TSQL solution.
[Answer]
# Scala, 24 bytes
```
(n:Int)=>0 to 10 map(n*)
```
Explanation:
```
(n:Int)=> //define an anonymous function
0 to 10 //create a range from 0 to 10
map(n*) //multiply each element by the input
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 12 bytes
```
,10y:[?]z:*a
```
[Try it online!](http://brachylog.tryitonline.net/#code=LDEweTpbP116Oiph&input=MjA&args=Wg&debug=on)
I need to implement that `I * [A, B, C] = [I*A, I*B, I*C]`…
### Explanation
```
,10y The range [0, 1, …, 10]
:[?]z The list [[0, Input], [1, Input], …, [10, Input]]
:*a The list [0*Input, 1*Input, …, 10*Input]
```
[Answer]
# [brainf\*\*\*](http://esolangs.org/wiki/Brainfuck), 84 bytes
```
,[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++<<<<<<<<<<-]>[.>]
```
Expects input as a single byte (as BF can only operate on numbers up to 255) and returns results as single bytes. Some values may look like ASCII, but they should not be treated as such; look at the decimal representation of the returned bytes.
[Try it online!](http://brainfuck.tryitonline.net/#code=LFs-Kz4rKz4rKys-KysrKz4rKysrKz4rKysrKys-KysrKysrKz4rKysrKysrKz4rKysrKysrKys-KysrKysrKysrKzw8PDw8PDw8PDwtXT5bLj5d&input=QQ&debug=on)
[Answer]
# JavaScript, 42 bytes
```
function f(a){for(i=0;i<11;i++)alert(i*a)}
```
[Answer]
# MATLAB, 12 bytes
```
@(x)x*[1:10]
```
Not really much to it. An anonymous function that takes `x` as input and multiplies it by the vector `[1:10]`. Displays as `ans = 2 4 6 ..`. Also works in Octave.
**[Try it online](https://ideone.com/MrtnwH).**
[Answer]
## PowerShell v2+, 23 bytes
```
param($n)1..10|%{$_*$n}
```
Takes input via command-line argument, loops over the range `1` to `10`, each loop placing that number `*$n` on the pipeline. Output via implicit `Write-Output` at end of program execution results in newline separated values.
```
PS C:\Tools\Scripts\golfing> .\multiplication-table.ps1 2
2
4
6
8
10
12
14
16
18
20
PS C:\Tools\Scripts\golfing> .\multiplication-table.ps1 20
20
40
60
80
100
120
140
160
180
200
```
[Answer]
# C89, 44 bytes
```
k;main(n){for(k=n*11;k-=n;)printf("%d ",k);}
```
### Ungolfed:
```
k;
main(n)
{
for (k=n*11 ; k-=n ;)
printf("%d ", k);
}
```
### Compile and run with (input 4)
```
gcc -ansi main.c && ./a.out 2 3 4
```
### Output
```
40 36 32 28 24 20 16 12 8 4
```
### Test it
`[Demo](http://coliru.stacked-crooked.com/a/3b16e8684c36b850)`
[Answer]
## Pyke, 5 bytes
```
TSQm*
```
[Try it here!](http://pyke.catbus.co.uk/?code=TSQm%2a&input=2)
Or `TQm*` if allowed to do numbers `0-9` rather than `1-10`
Or `TL*` if we're going non-competitive.
[Answer]
# Javascript (ES6), 34 31 bytes
```
a=>{for(i=0;i<11;)alert(++i*a)}
(a)=>{for(i=0;i<11;++i)alert(i*a)}
```
Saved 3 bytes thanks to grizzly.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 24 bytes
```
;;..I1.N-?W.;;)W@/So..*O
```
Cubix is a 2-dimensional, stack-based esolang. Cubix is different from other 2D langs in that the source code is wrapped around the outside of a cube.
[Test it online!](https://ethproductions.github.io/cubix) Note: you'll have to copy-paste the code, and there's a 50 ms delay between iterations.
## Explanation
The first thing the interpreter does is figure out the smallest cube that the code will fit onto. In this case, the edge-length is 1. Then the code is padded with no-ops `.` until all six sides are filled. Whitespace is removed before processing, so this code is identical to the above:
```
; ;
. .
I 1 . N - ? W .
; ; ) W @ / S o
. .
* O
```
] |
[Question]
[
*Take a list of 2-digit hexadecimal numbers as input, and output the binary value, replacing each 1 with an 'X', and each 0 with a space.*
**For example**
Input = `FF, 81, 47, 99`.
* `FF` = `11111111` in binary, so print `XXXXXXXX`
* `81` = `10000001` in binary, so print `X X`
* `47` = `01000111` in binary, so print `X XXX`
* `99` = `10011001` in binary, so print `X XX X`
Full output:
```
XXXXXXXX
X X
X XXX
X XX X
```
**Clarifications**
* The hexadecimal numbers will always be 2-digits.
* There can be any number of hexadecimal numbers.
* You can choose to input in whatever format you want (separated by a space, comma, newline, etc.)
* The character to output for a `1` is `X`, and for `0` it is a . This will not change.
* The outputs must be padded to length 8
Also, [apparently I wasn't clear enough](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges?answertab=modifieddesc#comment78489_25167): **the input is in Hexadecimal (Base 16) *not denary (Base 10)***
**This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!**
[Answer]
# Excel (ms365), ~~74~~, ~~72~~, ~~59~~, 58 bytes
-14 Byte thanks to @[jdt](https://codegolf.stackexchange.com/users/41374/jdt)
```
=SUBSTITUTE(SUBSTITUTE(HEX2BIN(+A1:A4,8),"0"," "),"1","X")
```
[](https://i.stack.imgur.com/qrp2y.png)
---
Original answer using `BYROW()` for 71 bytes:
```
=BYROW(A:A,LAMBDA(a,CONCAT(IF(-MID(HEX2BIN(a,8),ROW(1:8),1),"X"," "))))
```
[](https://i.stack.imgur.com/Vfjdv.png)
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-p`, ~~40~~ 31 bytes
Takes input on stdin separated by newlines.
```
$_=("%08b
"%$_.hex).tr"01"," X"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6BUuyCpaUlaboW-1XibTWUVA0skriUVFXi9TJSKzT1SoqUDAyVdJQUIpQgqqCKF6x2c-OyMOQyMeeytIQIAQA)
[Answer]
# [Python](https://www.python.org), 58 bytes
```
while 1:print(f"{int(input(),16):08b}".translate(" X"*99))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3rcozMnNSFQytCooy80o00pSqQVRmXkFpiYamjqGZppWBRVKtkl5JUWJecU5iSaqGkkKEkpalpaYmxASoQQvWublxGRhwWRhymZhzWVpCRAE)
Takes each hex code on a new line from input, prints to standard out. Terminates on error (is that allowed?)
---
# [Python](https://www.python.org), 67 bytes
```
lambda n:"\n".join(f"{int(x,16):08b}".translate(" X"*99)for x in n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3nXMSc5NSEhXyrJRi8pT0svIz8zTSlKoz80o0KnQMzTStDCySapX0SooS84pzEktSNZQUIpS0LC010_KLFCoUMvMU8jShRmkUFIG0pWlEK7m5KekoKBkYgEgLQxBpYg4iLS2VYjWh6hcsgNAA)
Takes input as a list of hex strings and returns a string with newlines separating lines.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-mR`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
nG" X" ù8
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1S&code=bkciIFgiIPk4&input=WyJGRiIgIjgxIiAiNDciICI5OSJd)
```
nG" X" ù8 :Implicit map of input array
n :Convert from base
G :16
" X" :To base " X"
ù8 :Left pad with spaces to length 8
:Implicit output joined with newlines
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~61~~ 57 bytes
```
.
$&
(?=..[89A-F]|.[4-7C-F]|[2367ABEF])
X
+T`dA-F` Xo
```
[Try it online!](https://tio.run/##K0otycxL/P9fj0tBQUFFjUtBw95WTy/awtJR1y22Ri/aRNfcGcSKNjI2M3d0cnWL1eSK4NIOSUgBKkhQiMj//9/NjcvCkMvEnMvSEgA "Retina 0.8.2 – Try It Online") Explanation:
```
.
$&
```
Precede each digit with three spaces.
```
(?=..[89A-F]|.[4-7C-F]|[2367ABEF])
X
```
Replace the spaces with `X`s where appropriate.
```
+T`dA-F` Xo
```
Reduce the remaining digit modulo 2 and replace with space or `X` as appropriate.
[Answer]
# [Perl 5](https://www.perl.org/), `-p` 30 bytes
```
$_=sprintf"%08b
",hex;y/01/ X/
```
Pretty much identical to [Jordan's Ruby answer](https://codegolf.stackexchange.com/a/252383/108444)
[Try it online!](https://tio.run/##K0gtyjH9/18l3ra4oCgzryRNSdXAIolLSScjtcK6Ut/AUF8hQv//fzc3LgtDLhNzLkvLf/kFJZn5ecX/dQsA "Perl 5 – Try It Online")
[Answer]
# [sed 4.2.2](https://www.gnu.org/software/sed/), `-E` ~~[178](https://tio.run/##VYzNDoIwEITvfYoeCCmguxZRYG/@wDOYWHsgGuNFTNoTxle3LiQc3GSTb2dmx92uITgEpLhtjof9rq7K7aZY53qFd0HCISlIQJ0tXVKjEySjTc6WZ2sUUfLBKeCKiWSGMQ/@I@FkRgyCOiarIEuMJuSVY8JKBemsnFD4bn6jYbThvSg/EUqu80MIbSsqLYpS1PW3f/lH/3Rh2fwA "sed 4.2.2 – Try It Online")~~ 141 bytes
```
s/./&FEDCBA9876543210:/g
s/(\w)\w*\1//g
s/\w/ /g
s/ +/&&&&/
s/ +/&&&&/
s/://
:
s/^(.+)\1:/\1: /
s/^ (.*)\1:/\1:X/
t
s/://
:z
s/^.{,7}$/ &/
tz
```
Takes newline-separated input
-35 thanks to [DLosc](https://codegolf.stackexchange.com/users/16766/dlosc)
### Explanation
```
s/./&FEDCBA9876543210:/g add hex digits to each input char
s/(\w)\w*\1//g find index of input char in hex string
s/\w/ /g left is 2 strings which lengths corresponds to the input
s/ +/&&&&/
s/ +/&&&&/ multiply first strings' length by 16
s/:// add the 2 strings, left is a unary number
:
s/^(.+)\1:/\1: / convert to base 2, one bit at a time
s/^ (.*)\1:/\1:X/
t
s/://
:z
s/^.{,7}$/ &/ pad with spaces until length > 7
tz
```
[Answer]
# JavaScript (ES6), 60 bytes
*-1 thanks to [@MatthewJensen](https://codegolf.stackexchange.com/users/87728/matthew-jensen)*
Expects a list of 2-character hexadecimal strings.
```
a=>a.map(s=>(g=k=>k--?" X"['0x'+s>>k&1]+g(k):'')(8)).join`
`
```
[Try it online!](https://tio.run/##FcTRCoIwFADQ975C7kO7F9tICNJg681vCETwYjp0tomT6O8Xnocz85djv03rLn14D2nUibVh9eEVozZotdPGSfmE7AWNuP5EHo1x56LNLTp6CEFYEqk5TL47dakPPoZlUEuwOGIDdQ2XDMri@HY/ripoidIf "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array
a.map(s => // for each string s in a[]:
( g = k => // g is recursive function taking a counter k
k-- ? // if k is not equal to 0 (decrement it afterwards):
" X"[ // append either ' ' or 'X':
'0x' + s // parse s as a hexadecimal string
>> k // right-shift it by k position
& 1 // and isolate the least significant bit
] // end of lookup
+ g(k) // append the result of a recursive call
: // else:
'' // stop the recursion
)(8) // initial call to g with k = 8
).join`\n` // end of map(); join with line-feeds
```
[Answer]
# [Brainfuck](https://github.com/TryItOnline/brainfuck), 442 bytes
```
++++++++++>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[<<+>+>-]<----------------------------<++++++++++++++++++++++++++++>>,[------------------------------------------------[-[-[-[-[-[-[-[-[-[--------[-[-[-[-[-[<<<.>>>[-]>]<[<....>>]>]<[<...>.>]>]<[<..>.<.>>]>]<[<..>..>]>]<[<.>.<..>>]>]<[<.>.<.>.>]>]<[<.>..<.>>]>]<[<.>...>]>]<[.<...>>]>]<[.<..>.>]>]<[.<.>.<.>>]>]<[.<.>..>]>]<[..<..>>]>]<[..<.>.>]>]<[...<.>>]>]<[....>],]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70yqSgxMy-tNDl7wYKlpSVpuha3GHdpw4GdnZ02BSDaxkbbTttON9ZGFw-wwWeEnZ1OND7N2EA0FogpZWNjowf0X7RurF2sTbSNHhDY2cHZdnpwtp2eDZKMnR5cBiSBkAErQ5JD1mWnB9OlZ4OwB6wdIY5kD5gHk0GyRQ_JDj0kG8COj9WJhUQhNCYXrHZzU7AwVDAxV7C0hAgBAA)
The input can be separated by every character with a value bigger than 'F'.
```
The working section looks like this:
| '\n' | 'X' | ' ' | {input character} | 0 (used for stopping loops) |
prepare the initial state
++++++++++ newline
prepare space and X
>>> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [<<+>+>-]
< ---------------------------- space
< ++++++++++++++++++++++++++++ X
Go to start position and read char
>>,
[
subtract '0'
------------------------------------------------
[ if !0
-[ if !1
-[ if !2
-[ if !3
-[ if !4
-[ if !5
-[ if !6
-[ if !7
-[ if !8
-[ if !9
subtract difference between 'A' and '9'
-------
-[ if !A
-[ if !B
-[ if !C
-[ if !D
-[ if !E
-[ if !F
print newline
<<<.>>>
clear input character
[-]>
]
<[ print 'F' <....>> ]>
]
<[ print 'E' <...>.> ]>
]
<[ print 'D' <..>.<.>> ]>
]
<[ print 'C' <..>..> ]>
]
<[ print 'B' <.>.<..>> ]>
]
<[ print 'A' <.>.<.>.> ]>
]
<[ print '9' <.>..<.>> ]>
]
<[ print '8' <.>...> ]>
]
<[ print '7' .<...>> ]>
]
<[ print '6' .<..>.> ]>
]
<[ print '5' .<.>.<.>> ]>
]
<[ print '4' .<.>..> ]>
]
<[ print '3' ..<..>> ]>
]
<[ print '2' ..<.>.> ]>
]
<[ print '1' ...<.>> ]>
]
<[ print '0' ....> ]
read next input
,
]
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~10~~ 8 bytes
```
H‛ Xτ8↳⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJI4oCbIFjPhDjihrPigYsiLCIiLCJbXCJGRlwiLFwiODFcIixcIjQ3XCIsXCI5OVwiXSJd)
-2 thanks to Steffan
Port of Japt.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~[34](https://tio.run/##AUIAvf9odXNr//9tyK/DtuKGkV84K1I4JyBtISJYICLhuItCMTZt4oKs4bmB4oCmQzIiMTlBRiJ3////RkYgODEgNDcgOTk "Husk – Try It Online")~~ ~~[31](https://tio.run/##AT0Awv9odXNr//9tyK/DtnRtISJYICLhuIsrMjU2QjE2beKCrOG5geKApkMyIjE5QUYid////0ZGIDgxIDQ3IDk5 "Husk – Try It Online")~~ 28 bytes
```
mȯötm!"X "ḋ+256B16m€f□…"1F"w
```
[Try it online!](https://tio.run/##AToAxf9odXNr//9tyK/DtnRtISJYICLhuIsrMjU2QjE2beKCrGbilqHigKYiMUYid////0ZGIDgxIDQ3IDk5 "Husk – Try It Online")
Takes input as a space-separated argument
Husk is missing some useful functions such as pad and hex which makes this answer so long, or maybe I'm just bad.
-3 [DLosc](https://codegolf.stackexchange.com/users/16766/dlosc)
-3 [Razetime](https://codegolf.stackexchange.com/users/80214/razetime)
### Explanation
```
mȯötm!"X "ḋ+256B16m€f□…"1F"w
w split on spaces
mȯö map the following ultra composed penta-function
m€f□…"1F" map input to indices the generated string "1-9A-F"
B16 convert from digits in base 16
+256 add 256 to make the binary string 9 chars long
ḋ convert to digits in base 2
m!"X " index into "X ", one-indexed modular
t chop of first bit
implicit output joined on newlines
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~80~~ 74 bytes
```
i;f(**b){for(i=8;*b;)putchar(i--?strtol(*b,0,16)&1<<i?88:32:(b++,i=8)+2);}
```
-3 bytes thanks to Arnauld!!
[Try it online!](https://tio.run/##HYvRCoMgGEbve4qfLoaaQrWxWRbd9RJjFyqzCa1GOXYRvfqc7rs48ME5mulRToP3VhhEiMKbmRdkWy6IEvj1dvohw2esW93i5hERRXNanPGhaBrbcV4fyxqpLKOhwVmJxe6f0k4IbwmExZyAu6/ueoMWNkj7PqWQ8iLydImsqkDIYRf/xKCoY5Hs/qvNKIfVs88P "C (clang) – Try It Online")
### Alternative method proposed by Arnauld:
# [C (clang)](http://clang.llvm.org/), 73 bytes
```
i;f(**b){while(*b)putchar(++i%9?strtol(*b,0,16)&1<<8-i%9?88:32:!++b+10);}
```
[Try it online!](https://tio.run/##HYzNDoIwEITvPMVKomkpJFSMForxxksYD6Xhp0lFAzUcGl7d2jqHL5uZ2ZGZ1GIanFO8R0nSYruOSnfIX@@PkaOYESFqX94WM5uX9n6ap/SMD7SuWRYCxqriWO0IaQnNMd/cU6gJYRuBVxhIwHSLuT/gChbipolTiBkNPF0Cy9ITctj4/6VHoY55tLmv7LUYFpetPw "C (clang) – Try It Online")
This will only work correctly for the first 477,218,588 lines.
[Answer]
# [Factor](https://factorcode.org/), 60 bytes
```
[ [ hex> "%08b"sprintf "10""X "zip substitute print ] each ]
```
[Try it online!](https://tio.run/##HcnBCoJAFAXQvV9xGWgbCkFa0NJo0yaCQFyMwzMHbUbnPTGKvn2KVmdxWm3Eh3i9nM7HHVofHlrEujt@dutRB6YAzewNw3r0FBwNYJpmcoYY04J9kkzLG2WJPMNmi6LAJ1ao0NHzALVK80bxGKyTFipLlbpBvewInhsWK7MQ/osapE2HOho9DPEL "Factor – Try It Online")
* `[ ... ] each` Call `[ ... ]` on each hex string in the input sequence
* `hex>` convert from hex to decimal
* `"%08b"sprintf` format as a binary number string left-padded with spaces 8 wide
* `"10""X "zip` create the following associative mapping: `{ { 49 88 } { 48 32 } }`
* `substitute` substitute characters in the binary string according to the mapping
* `print` print to stdout with a newline
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
WS⟦◧⍘⍘↧ι¹⁶ X⁸
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjejyjMyc1IVNDzzCkpLgkuKMvPSNTQ1FQKAjBKN6IDEFJ_UtBINp8TiVKgkEtMnvzy1KBnI18jU1FEwNAMSSgoRSkDKQjNW03pJcVJyMdSe5dFKumU5SrFr3Ny4LAy5TMy5LC25IFIA) Link is to verbose version of code. Explanation:
```
WS Loop over all lines of input
⟦ Output each result on its own line
ι Current line
↧ Lowercased
⍘ ¹⁶ Converted from base `16`
⍘ X Converted to custom base ` X`
◧ ⁸ Left padded to length `8`
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 29 bytes [SBCS](https://github.com/abrudz/SBCS)
```
⍉' X'⌷⍨∘⊂2⊥⍣¯1(16⊥(⎕D,⎕A)∘⍳)¨
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=e9Tbqa4Qof6oZ/uj3hWPOmY86moyetS19FHv4kPrDTUMzYBsjUd9U110gISjJkhB72bNQysA&f=S1NQd3NTV1C3MAQSJuZAwtJSHQA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
[Answer]
# [Python](https://docs.python.org/3/), 89 bytes
```
lambda n:[print(bin(int(i,16))[2:].zfill(8).replace("1","X").replace("0"," "))for i in n]
```
Function which takes in a list of hexadecimal strings.
[Try it online!](https://tio.run/##TcyxCsIwEIDhVzluykEJRkXbgmufQagdUm3w4LyGGAd9@Rg3px@@4Y/vfF91V8LpUsQ/5psH7ceYWLOZWc2v3LgD0bjtJ/sJLGJasmmJ4q@LQYcNnvEPNhUAicKagIEVdCqhfuIrG7LPKFxLZRigdbA/Qtd9AQ "Python 3 – Try It Online")
# [Python](https://docs.python.org/3/), 98 bytes
```
[print(*('X'if int(b)else' 'for b in bin(int(a,16))[2:].zfill(8)),sep='')for a in input().split()]
```
Takes input itself, no header/footer code.
[Try it online!](https://tio.run/##FYpBCoMwEEWvMruZERGsYrXQrWcoiAsDCR0IcTDpol4@mtX7vP/0n7576HJe9JCQqCL8oDgo27D10SKg2w8wtwIjgcqz1e3AvDxea3M68Z5G5jpafSNyibcSS9BfIm6ierm55jzPMLbQP2GaLg "Python 3 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
1ZA8&B88*c
```
[Try it online!](https://tio.run/##y00syfn/3zDK0ULNycJCK/n//2p1Nzd1HQV1C0MQaWIOIi0t1WsB)
### How it works
```
% Implicit input: cell array of char vectors.
1ZA % Convert each char vector to number. Gives a numeric vector
8&B % Convert each number to 8-digit binary. Gives an 8-column binary matrix
88* % Multiply each element by 88 (ASCII code of 'X')
c % Convert to char
% Implicit display. char(0) is displayed as space
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 45 bytes
```
{"\n"/|'8$|'" X"@+2\16/+"0123456789ABCDEF"?x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pWislT0q9Rt1CpUVdSiFBy0DaKMTTT11YyMDQyNjE1M7ewdHRydnF1U7KvqOXiSjCwSlPQUHJzU7JWsjAEEibmQMLSUkkTAKftENM=)
This is way too long...
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils + dc, ~~68~~ ~~58~~ 51 bytes
Takes input as arguments.
-10 bytes thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)
-7 bytes thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork)
```
for a;{
printf "%08s
" `dc<<<2o16i$a?n`|tr 01 \ X
}
```
[Try it online!](https://tio.run/##S0oszvj/Py2/SCHRupqroCgzryRNQUnVwKKYS0khISXZxsbGKN/QLFMl0T4voaakSMHAUCFGIYKr9v///25u/y0M/5uY/7e0BAA "Bash – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-l`, 17 bytes
```
" X"@S*TDgFB16+E8
```
Takes the hex pairs as command-line arguments. [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJcIiBYXCJAUypURGdGQjE2K0U4IiwiIiwiIiwiLWwgRkYgODEgNDcgOTkiXQ==)
### Explanation
```
" X"@S*TDgFB16+E8
g ;; List of command-line arguments
FB16 ;; Converted (each) from base 16
+ ;; Add (to each):
E8 ;; 2 to the 8th power (256)
TD ;; Convert (each) to binary as a list of digits
S* ;; Get all but the first element of each
" X"@ ;; Use those 0's and 1's to index into this string
```
The result is a depth-2 nested list of spaces and X's. The `-l` flag concatenates each sublist together and outputs it on a separate line. (For a flagless version, add `P*` to the beginning of the code and `u` to the end.)
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 75 bytes
```
;=fB;=n 4W+=n-nT1O I%/-aI>60a 48 55^2n 2'X\'' \'W=pP;=aAp;Cf;=aA GpT1;CfO''
```
[Try it online!](https://knight-lang.netlify.app/#WyI7PWZCOz1uIDRXKz1uLW5UMU8gSSUvLWFJPjYwYSA0OCA1NV4ybiAyJ1hcXCcnIFxcJ1c9cFA7PWFBcDtDZjs9YUEgR3BUMTtDZk8nJyIsIkZGXG44MVxuNDdcbjk5Il0=)
Input each hexidecimal value on a separate line.
Could be a bit shorter if it isn't required to output X's and spaces:
### [Knight](https://github.com/knight-lang/knight-lang), 72 bytes
```
;=fB;=n 4W+=n-nT1O++''%/-aI>60a 48 55^2n 2'\'W=pP;=aAp;Cf;=aA GpT1;CfO''
```
[Try it online!](https://knight-lang.netlify.app/#WyI7PWZCOz1uIDRXKz1uLW5UMU8rKycnJS8tYUk+NjBhIDQ4IDU1XjJuIDInXFwnVz1wUDs9YUFwO0NmOz1hQSBHcFQxO0NmTycnIiwiRkZcbjgxXG40N1xuOTkiXQ==)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 63 bytes
```
%{[convert]::ToString("0x1$_",2)}|% S*g 1|% *ce 1 X|% *ce 0 ' '
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmv7uamrqOgbmEIIk3MQaSlpbpCzX/V6ujk/Lyy1KKSWCurkPzgkqLMvHQNJYMKQ5V4JR0jzdoaVYVgrXQFQyCtlZyqYKgQAWUZKKgrqP//DwA "PowerShell – Try It Online")
Input comes from the pipeline.
Pretty straightforward; converts to binary, replaces 0 and 1.
```
%{[convert]::ToString("0x1$_",2)}|% S*g 1|% *ce 1 X|% *ce 0 ' '
%{ } # % is an alias for ForEach-Object, which processes the scriptblock {...} for each string coming in from the pipeline.
[convert]::ToString("0x1$_",2) # converts the hexadecimal string in $_ to binary, with a leading 1 to avoid padding (saves one byte)
|% S*g 1 # pipe the binary string to ForEach-Object again, and call the MemberName method Substring(1), stripping off the leading "1"
|% *ce 1 X|% *ce 0 ' ' # Pass the binary string through two more calls of the MemberName Replace(); output is implicit.
```
[Answer]
# [simply](https://github.com/ismael-miguel/simply), 88 bytes
It's a long mess, but *works*!
(I've used `\n` for style, but an actual newline works as well, and that is reflected in the size of the answer.)
```
fn($L){$T=" X\n"&array_map($L,fn($V)each$x in run&format("%'08s2"&cb($V,16,2))out$T[$x])}
```
Creates an anonymous function that **outputs** the result.
This works by left-padding all binary values to 8 characters, then ends with "2".
For each character of the binary string, it outputs the *n* character in the string `" X\n"`.
For 0 outputs `" "`, for 1 outputs `"X"` and for 2 outputs `"\n"`.
## Example
```
$fn=fn($L){$T=" X\n"&array_map($L,fn($V)each$x in run&format("%'08s2"&cb($V,16,2))out$T[$x])};
run $F(["FF", "81", "47", "99"]);
```
Should output the expected result.
## Slightly more readable
Both versions do exactly the same.
```
fn($list) => {
&array_map(
$list, fn($line) => {
$translation = " X\n";
$temp = call &format("%'08s2", &convert_base($line, 16, 2));
each $char in $temp {
echo $translation[$char];
}
}
);
}
```
For some reason, JavaScript doesn't like the original order, when I untangle the code.
[Answer]
# [J](https://www.jsoftware.com), 26 bytes
```
' X'{~(8#2)#:[:".'16b'&,&>
```
Tacit function that expects a list of boxes using `[0-9a-f]`.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxS10hQr26TsNC2UhT2SraCqjc0CxJXU1HzQ6iYJMmV2pyRr5CmoKRQq2egmOQexhEYke0Ulqako6CkoUhiDQxB5GWlkqxCyDyAA)
```
' X'{~(8#2)#:[:".'16b'&,&>
'16b'&,&> : prepend '16b' to each input cell and unbox
". : Do, eval the list of strings
[: : Cap, makes do and the prepend eval as f(g(x))
(8#2)#: : convert to binary and pad to length 8
' X'{~ : use result to index into ' X'
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Hb8j»T„X ‡
```
[Try it online.](https://tio.run/##yy9OTMpM/f/fI8ki69DukEcN8yIUHjUs/P8/WsnNTUlHycIQSJiYAwlLS6VYAA)
Or alternatively:
```
H„ XÅвJ8j»
```
[Try it online.](https://tio.run/##yy9OTMpM/f/f41HDPIWIw60XNnlZZB3a/f9/tJKbm5KOkoUhkDAxBxKWlkqxAA)
**Explanation:**
```
H # Convert the values in the (implicit) input-list from hexadecimal to integers
b # Then convert those base-10 integers to binary
8j # Pad leading spaces so all become length 8
» # Join the list with newline delimiter
‡ # Transliterate all
T # 10
„X # to "X ", replacing all 1s with "X" and 0s with " "
# (after which the result is output implicitly)
H # Convert the values in the (implicit) input-list from hexadecimal to integers
„ XÅв # Convert each integer to custom base-" X", which basically means to
# base-length (2 in this case) and then indexing into the string
J # Join the inner character-lists to strings
8j» # Same as above
# (after which the result is output implicitly)
```
[Answer]
# C# 10 (.NET 6) and later, 184 bytes
Doesn't work in TIO as it doesn't support .NET 6.
```
foreach(var i in Console.ReadLine().Split(',')){var a=Convert.ToString(Convert.ToInt32(i,16),2).Replace("1","X").Replace("0"," ");a=new string(' ',8-a.Length)+a;Console.WriteLine(a);}
```
Asks for the hex numbers as input when started.
Output:
```
FF,81,47,99
XXXXXXXX
X X
X XXX
X XX X
```
Ungolfed version:
```
var input = Console.ReadLine(); // Ask for input
foreach (var i in input.Split(',')) { // Split with a comma, and for each part:
var hex = Convert.ToInt32(i, 16); // Convert it to an integer
var bin = Convert.ToString(hex, 2); // Convert it to it's binary representation
var art = bin.Replace("1", "X").Replace("0", " "); // Replace 1 with X, 0 with a space
var padding = new string(' ', 8 - art.Length); // Repeat a space as much as needed for padding
art = padding + art; // Append the padding to the start of the art string
Console.WriteLine(art); // Write the final result
}
```
## Function version (155 bytes)
Thanks to [Seggan](https://codegolf.stackexchange.com/users/107299/seggan) for the suggestion.
```
void art(int[] n){foreach(var i in n){var a=Convert.ToString(i,2).Replace("1","X").Replace("0"," ");a=new string(' ',8-a.Length)+a;Console.WriteLine(a);}}
```
[Try it online!](https://tio.run/##TU5NSwMxED3v/oohlya4XVoRbAk9FXqqIFZQEA9DnG4HtokkcVWW/PY1aS9eHsN78z5MmBvnaZq@AtsODr8h0lnXpscQ4NG7zuMZxroKESMbGBx/wAOylSH6bHh7B/RdUOWluojoo2Qbs2DVeMzRaE5yQA8MbAtXbtxsnR3Ix/bZHS5Bkptb1T7RZ4@GpFiKRryKf8QiEyCUxo2lb7iWyxnMmtUc2z3ZLp7UDeocG1xP7YvnSHu2JFHplPK4sqtYr9tGWPzsdk3G1bLg3X3B9RqS0nWV6jRNfw "C# (.NET Core) – Try It Online")
Usage and output:
```
art(new int[] { 0xFF, 0x81, 0x47, 0x99 });
/* gives this output:
XXXXXXXX
X X
X XXX
X XX X*/
```
[Answer]
# [Rust](https://www.rust-lang.org/), 99 bytes
```
|a|a.map(|s|format!("{:>8b}",u8::from_str_radix(&s,16).unwrap()).replace('0'," ").replace('1',"X"))
```
[Try it online!](https://tio.run/##bY9Ra4MwEMff/RTnPawJOJkwNps6Hwt9HgxhlJBpMgRNuiSug9rP7nQrUtz@cBz3u/tzd7ZzflAaWlFrQuEUNNKDYqA0cb5i7FOWjO20Nzsvbfbsba3fcwq3OXB4GnrRi7gVB9K7XhnbCh8SPLE8fTtj1KWMKWta7rzlVlT1F7lxUfJA404f7WiiNLby0IhSktXdKkLAK5CMoEBKh00gnJPWc/kRkgAuUmS8LHzF7RZjb7g5alkRGgGmyQLcPy7Aen0N9nE9fsfr8b3poNI0jSw9Y9mLLDOe55Nl3vqzc64mYXERRgv@m/9wmBr/zxdT4Iz3dBOch28 "Rust – Try It Online")
Can be assigned a variable of type `fn(std::vec::IntoIter<String>)->_`
[Answer]
# [sed](https://www.gnu.org/software/sed/) `-E`, ~~131~~ 121 bytes
*-10B thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)*
```
s/./X&/g
s/X([0-7])/ \1/g
y/89ABCDEF/01234567/
s/[4-7]/X&/g
s/[0-3]/ &/g
s/[2367]/X&/g
s/[0145]/ &/g
y/01234567/ X X X X/
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlWbSSrqtS7IKlpSVpuhY3K4v19fQj1PTTuYr1IzSiDXTNYzX1FWIMgQKV-haWjk7OLq5u-gaGRsYmpmbm-kBV0SZANTAtQA3GsfoKUI6RsRmylKGJKVSuEmGCQgQE6kMcAHXHgtVublwWhlwm5lyWlhAhAA)
[Answer]
# [Windows Batch](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cmd), 145 bytes
Length calculated by using Unix/LF as EOL, without an EOL at the end of the last line.
```
:s
@if %1.==. exit/b
@set/an=0x%1&set b=
:w
@set/ar=n%%2&set/an/=2
@set b=%r%%b%
@set b=%b:0=.%&if %b:~7,1%.==. goto w
@echo.%b:1=X%&shift&goto s
```
Input as command line parameters.
### Ungolfed
The `@` suppresses the output of the command currently processed that would otherwise be echoed; "@echo off\n" would use 10 bytes, so suppressing lines individually is cheaper.
```
:s &REM Start label
@if %1.==. exit/b &REM Leave if no more parameter from the command line
@set /a n=0x%1 &REM set n to the value of the first parameter (%1) as hexadecimal ("set /a" is an arithmetic operation)
@(set b=) &REM Clear b (the output string)
:w &REM Start of the loop to calculate the binary representation of n
@set /a r=n%%2 &REM Set r to the remainder of n/2; % is the modulo operator, which must be doubled inside a batch script
@set /a n/=2 &REM Divide n by 2
@set b=%r%%b% &REM Add the remainder to the output string
@set b=%b:0= % &REM Replace every 0 in the output string with a space
@if %b:~7,1%.==. goto w &REM If the eight character in the output string is not set yet, continue with the conversion
@echo.%b:1=X% &REM Replace every 1 in the output string with an X, and write the string
@shift &REM Shift the command line parameters to the left (former %2 is now %1, etc.)
@goto s &REM Lather, rinse, repeat
```
```
D:\cmd>.\CGSE_252379.cmd FF 81 47 99
XXXXXXXX
X X
X XXX
X XX X
```
[Answer]
# sh + coreutils, ~~82~~ 72 bytes
```
xxd -r -p|xxd -b|sed -E "s/^.{10}(.{53}).*/\1/g;s/ *$//g"|tr 01\ \ X\\n
```
[Try it online!](https://tio.run/##RcbNCkBAFAbQV/mS8lPmmhCy5hksbspfrJCxUMazD9lYndO1ajZjP69wqgqZRJwiz/E/c6DNeQ4IdgSb/tZpNb6UsBQ14pLh7YoriW5P@MSSpkIRfJtosvSxI5QMMGrmxZgH "Bash – Try It Online")
] |
[Question]
[
## Challenge
Create a new file and write the string `Hello World` to it.
## Restrictions
* Your challenge must write to a file on disk, in the file system.
* The file may not be a log file generated during normal operation of the interpreter.
* The file must contain **only** the string `Hello World`. It is allowed to contain a trailing newline or minimal whitespace. No other content.
* No command-line flags/pipes (etc) allowed, except when necessary to run the program. (e.g. `perl -p`)
## Notes
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program in bytes wins.
* Follow the spirit, not the letter, of the rules.
[Answer]
# Python 2, 32 bytes
```
print>>open(*"ww"),"Hello World"
```
[Yes, this is valid python](https://www.python.org/dev/peps/pep-0214/).
[Answer]
# Haskell, 25 bytes
```
writeFile"o""Hello World"
```
[Answer]
## zsh, 17 bytes
```
<<<Hello\ World>x
```
Outputs to a file called `x`.
[Answer]
# [Vyxal 2.5.3](https://github.com/Vyxal/Vyxal/releases/tag/v2.5.3), 32 bytes
```
kh→@|;@+open(*"ww").write(VAR_)#
```
Vyxal can't really do anything with external files, which would normally render this challenge impossible. However, in Vyxal 2.5.3 and prior, there was an ACE exploit allowing for arbitrary Python execution. [Yep, I found another one.](https://codegolf.stackexchange.com/a/231059/101522)
---
#### The ACE:
Vyxal is a transpiled language, so every Vyxal command is translated to some Python code, and then all of the translated commands are executed. Previously, I found that you could escape a string to insert any Python commands you wanted into the transpiled code. It turns out that you can do something similar with function names.
When defining a function in Vyxal, the resulting python looks something like this:
```
def FN_func(parameter_stack, arity=None):
...setup stuff...
...commands...
...finishing stuff...
return stack
```
When calling a function in Vyxal, the resulting Python code looks something like this:
```
stack += FN_func(stack)
```
The thing is, when parsing the name of a function, the strategy was to just read characters until reaching a `:`, `|`, or `;`, which are the delimiters of different parts of the function declaration/call. This meant that you could put any characters you wanted into the name, and it would attempt to transpile it the same way.
In this case, I used a `+` in the function name when I called it. That results in this transpiled code:
```
stack += FN_+open(*"ww").write(VAR_)#(stack)
```
This code will error when ran, because it tries to add together a function and the None that is returned from the `open` command. However, even though it errors, the `open` command still runs, meaning that we have executed arbitrary Python. If you wanted to write longer sections of Python code, you could replace the `+` with `([])` and add a newline after it.
---
#### The program:
In this program, the payload (the arbitrary Python code) is the following:
```
open(*"ww").write(VAR_)
```
The basis of this code is the `open().write()` command, which creates a file named `w` if it doesn't exist, then writes the contents of `VAR_` to it.
The `VAR_` variable is set at the beginning of the Vyxal program with `kh→`. This pushes the builtin `Hello World` and saves it to the nameless variable. All variable names are prepended with `VAR_` internally, so the variable `VAR_` is created and contains `Hello World`, which is written to the newly created file. Even though this has the overhead of the ACE setup, it ends up being shorter than the Python solutions due to the builtin.
This ACE has not been fixed in the repo, but it had a patch applied server-side for the online interpreter. It was also fixed in the rewrite and subsequent 2.6 release. If you want to try out this program for yourself, you can download the 2.5.3 version [here](https://github.com/Vyxal/Vyxal/releases/tag/v2.5.3).
[Answer]
# Ruby, 26 bytes
Writes to file `f`.
```
open(?f,?w)<<"Hello World"
```
[Answer]
# **Batch, 18 bytes**
```
echo Hello World>f
```
[Answer]
## Batch, 19 bytes
```
@echo Hello World>o
```
[Answer]
# Vim, 15 + 2 == 17 bytes
```
iHello World<esc>ZZ
```
+2 bytes for launching this with `vim f` instead of `vim`. Additionally, this version works to:
```
iHello World<C-o>ZZ
```
If launching vim like this is not allowed, there is also:
### Vim, 18 bytes
```
iHello World<esc>:w f<cr>
```
Side note: this is a polyglot. The same thing works in V, except that it is one byte shorter (since the `<cr>` at the end is implicit.)
[Answer]
# C, 44 bytes
```
main(){fputs("Hello World",fopen("o","w"));}
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 19 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
⎕NPUT⍨'Hello World'
```
Creates a file with the name and contents "Hello World".
[Answer]
# PowerShell, 15 bytes
```
"Hello World">o
```
`>` redirects the string to a file called `o` in the current directory.
[Answer]
# Node.js, 42 bytes
```
require("fs").writeFile('o','Hello World')
```
i don't think this needs explanation
# Node.js REPL, 31 bytes
```
fs.writeFile('o','Hello World')
```
for some reason in repl you dont need to include `fs`
[Answer]
## Bash, 18 bytes
```
echo Hello World>a
```
[Answer]
## Pyth, 14 bytes
```
.w"Hello World
```
Outputs to a file called `o.txt`.
[Answer]
# ed, 19 characters
```
i
Hello World
.
w o
```
Sample run:
```
bash-4.3$ ed <<< $'i\nHello World\n.\nw o'
12
bash-4.3$ cat o
Hello World
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
'Hello World'Z#
```
This creates a file called `inout` and writes the string to it.
[Answer]
## K, 20 Bytes
```
`:f 0:,"Hello World"
`:f
```
Confirmation;
```
mmm@chromozorz:~/q$ cat f.txt
Hello World
```
[Answer]
# Clojure, 23 bytes
```
#(spit"x""Hello World")
```
Anonymous function which creates file called `x` and writes `Hello World` there.
[Answer]
# C#, ~~93~~ ~~77~~ 76 bytes
~~`using System.IO;namespace N{class C{static void M(){File.WriteAllText("f", "Hello World");}}}`~~
~~`class C{static void Main(){System.IO.File.WriteAllText("f", "Hello World");}}`~~
```
class C{static void Main(){System.IO.File.WriteAllText("f","Hello World");}}
```
[See it work](http://ideone.com/eQ5VAY), with an exception for unauthorized file access.
## Changelog
### Rev2
* Removed unnecessary namespace
* Changed function name to Main (because otherwise it won't be detected as main function)
* Removed `using` directive (thanks [Jean Lourenço](https://codegolf.stackexchange.com/users/57027/jean-louren%C3%A7o))
### Rev3
* Removed space that sneaked in.
# C# (without boilerplate), 47 bytes
```
void M(){File.WriteAllText("f","Hello World");}
```
[Answer]
# R, ~~38~~ ~~36~~ 35 bytes
```
sink(" ");cat("Hello World");sink()
```
I like how the created file has no name ! It's just ~~`.txt`~~ anything, in fact !
**-2** bytes thanks to @PEAR remark !
**-1** bytes thanks to @BartvanNierop !
This code will produce a file with no name.
[Answer]
# Python, 34 bytes
```
open("h","w").write("Hello World")
```
Outputs to a file called `h`.
[Answer]
# [APLX](http://www.dyalog.com/aplx.htm), 15 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
'Hello World'⍈1
```
Creates an APL component file containing just one component; the desired string. It can be read back with:
```
'Hello World'⍇1
Hello World
```
[Answer]
# Gema, 28 characters
```
\A=@write{o;Hello World}@end
```
Sample run:
```
bash-4.3$ gema '\A=@write{o;Hello World}@end'
bash-4.3$ cat o
Hello World
```
[Answer]
# Racket, 43 bytes
```
(display"Hello World"(open-output-file"f"))
```
[Answer]
# Julia, 47 bytes
```
f=open("o","w");write(f,"Hello World");close(f)
```
I tried using `writedlm`, but it didn't work out.
[Answer]
# C, 37 bytes
```
main(){system("echo Hello World>o");}
```
[Answer]
# [Perl 6](http://perl6.org), ~~27~~ 23 bytes
```
~~'o'.IO.spurt: 'Hello World'~~
spurt 'o','Hello World'
```
[Answer]
# Java 7, ~~100~~ 95 bytes
```
void f()throws Exception{java.io.Writer p=new java.io.PrintWriter("x");p.print("Hello World");}
```
Or if you want to close the writer after using it (**101 bytes**):
```
void f()throws Exception{try(java.io.Writer p=new java.io.PrintWriter("x")){p.print("Hello World");}}
```
**Ungolfed:**
```
class Main{
static void f() throws Exception{
try(java.io.Writer p = new java.io.PrintWriter("x")){
p.print("Hello World");
}
}
public static void main(String[] a){
try{
f();
} catch(Exception ex){
}
}
}
```
**Usage:**
```
java -jar Main.jar
```
[Answer]
# [eacal](https://github.com/ConorOBrien-Foxx/eacal), 26 bytes
```
write a string Hello World
```
This `write`s a `string` `Hello World` to file `a`, creating it if not present. Basically:
```
write <fileName> <exec>
```
and
```
string <params to convert to string>
```
Run the program as:
```
λ node eacal.js writeFile
```
[Answer]
# J, 21 bytes
```
'Hello World'1!:3<'o'
```
This writes to a file `o` in the current directory, or, if not called from a file, in your `j64-804` file. `1!:3` is the write foreign, and `<'o'` is the boxed filename (filenames need to be boxed). The LHS is the string to write.
] |
[Question]
[
This was related to a program I am writing. Although the title is simple, the challenge is a lot more complicated.
## Your challenge
You must write a program that takes an input, and your answer must match the sample outputs in this question.
What the program should be is that you must output "HelloWorld" with the length of the input matching the length of what you output. If the input's length is not divisible with 10, you should cut off the last few letters until it matches the length of the last few letters of the input. More clarification in the examples.
**Standard loopholes apply, except that answers should be full programs, and the input has to be printable ASCII.**
## Example inputs
```
Input: how are you
Output: HelloWorldH
Note: In the above example, there is an extra H due to the
characters in the input being 11, so we add an extra letter
Input: hrienehwnv
Output: HelloWorld
Input: kill him at dawn
Output: HelloWorldHelloW
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins!
---
Steffan won the first +50 bounty reputation award for 5 bytes. I know lyxal also had a 5 bytes with the same language, but previously he had his answer with 8 bytes, before he shortened it to 5 bytes, but after Steffan's answer had already been posted.
[Answer]
# JavaScript, ~~45~~ 35 bytes
```
s=>"".padEnd(s.length,"HelloWorld")
```
[Try it online!](https://tio.run/##BcExDoAgDADAr5hOkCizC24m/sCZSAFNQwk06O/x7nHdtaveRZa@jmBHsxuAKc7v2atmCHOUNMOBRHxyJQ96XJwbExriqIKCNznBjnUS/AS0Hj8 "JavaScript (V8) – Try It Online")
−10 thanks to Arnauld.
[Answer]
# [sed](https://www.gnu.org/software/sed/), ~~111~~ ~~55~~ ~~51~~ 44 bytes
```
s/./a/
:a
s/^/HelloWorld/
s/.\{10\}$//
/a/ba
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlwYKlpSVpuhY3dYr19fQT9bmsErmK9eP0PVJzcvLD84tyUvSBfL2YakODmFoVfX0uoJqkRIgeqNYFN9Uz8ssVEotSFSrzS7kyijJT81IzyvPKuLIzc3IUMjJzFRJLFFISy_Mg6gE)
[Answer]
# [Haskell](https://www.haskell.org/), 30 bytes
```
map fst.zip(cycle"HelloWorld")
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzexQCGtuESvKrNAI7kyOSdVyQMolR@eX5SToqQJlM7MU7BVAKryVdAoKC0JLinyydNL01RQUYhWysgvV0gsSlWozC9V0lFQyijKTM1LzSjPKwPxEMZAWEqx//8lp@Ukphf/100uKAAA "Haskell – Try It Online")
A cute way to truncate one string to the length of another is to `zip` them together, which truncates the longer string, then extract the desired string with `map fst`.
Longer alternatives:
```
fst.unzip.zip(cycle"HelloWorld")
zipWith const$cycle"HelloWorld"
```
[Answer]
# [Python](https://www.python.org), 39 bytes
```
lambda s:('HelloWorld'*len(s))[:len(s)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYwxCgIxEEV7TzHdZEV7CdjrCSzWLSJJSHB2siRZw57FJiB6J28jS6zef_B5z8-0ZBe4vuzx-p6z3R--SGq8aQVJCjwZonAJkTRuybBIXdfLNob__WxDhASeoUcXCqhoYAkz7gBd9IaNK_xY7e6JwPkRVAatCuMgNwBT9JyFXcstWGvjDw)
# [Python](https://www.python.org), 39 bytes
Alternative version proposed by `mazunki`:
```
lambda s:('HelloWorld'*(l:=len(s)))[:l]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxBCsIwEADvvmJvm4reJdC7vsBD20MkCQluNyVJDX2Ll4Don_yNlHoaBoZ5fqYlu8D1Zdv-PWd7PH2R1HjTCpIUeDZE4RoiadwLki0ZFqlpmk7S8M8vNkRI4Bk6dKGAigaWMOMB0EVv2LjCj9XungicH0Fl0KowDnIHMEXPWdj1ug1r3fgD)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
…HelloWorldLS
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO5Mjkn1Tkjv0BDySM1Jyc/PL8oJ0VJR8EnNS@9JEPDM6@gtCS4BKg0XUMTCKz//8/IL1dILEpVqMwv5fqvW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
HelloWorld Literal string `HelloWorld`
… Reshaped to length
L Length of
S Input string
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
”Ÿ™‚ï”áI∍
```
Input as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f//UcPcozsetSx61DDr8Hog5/BCz0cdvf//RytlKOko5QNxORArAHEiEBcBcSqUXwmVL1WKBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVw6P9HDXOP7njUsuhRw6zD64GcwwsjHnX0/tf5H62UkV@ukFiUqlCZX6qko6CUUZSZmpeaUZ5XBuJlZ@bkKGRk5iokliikJJbngcQMjYxNlGIB).
**Explanation:**
```
”Ÿ™‚ï” # Push dictionary string "Hello World"
á # Only keep letters to remove the space: "HelloWorld"
I # Push the input-list
∍ # Shorten/extend the "HelloWorld" string to its length
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `”Ÿ™‚ï”` is `"Hello World"`.
[Answer]
# Excel, 38 bytes
```
=LEFT(REPT("HelloWorld",3276),LEN(A1))
```
Input is in the cell `A1`. Output is wherever the formula is.
Repeats the string as many times as allowed based on the limitations of inputs to `LEFT()` and the truncates all but the left-most characters based on the length of the input.
[](https://i.stack.imgur.com/2WToP.png)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 55 bytes
```
main(c){for(;~getchar();)printf(L"dHelloWorl"+c++%10);}
```
[Try it online!](https://tio.run/##BcHBCoQgEADQX5EgUCSo2y7SvUP3zsOYJk0aKnSI9tN3eg87j8h8QIgS1e1Slubn14obZKmMOnOI1cm5sdNKlJaUqdGodTv0yjzMeyASWzgEVGHhin90BL5wV6od8fN9AQ "C (gcc) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 25 bytes
```
FNrZlwp@"HelloWorld"%N 10
```
[Try it online!](https://tio.run/##K6gsyfj/382vKCqnvMBBySM1Jyc/PL8oJ0VJ1U/B0OD//4z8coXEolSFyvxSAA "Pyth – Try It Online")
PS: first time using Pyth & this platform is awesome!
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 27 bytes
```
T`p`~
Y`~`\He\l\l\oW\or\l\d
```
[Try it online!](https://tio.run/##K0otycxLNPz/PyShIKGOKzKhLiHGIzUmBwjzw2Pyi4B0yv//GfnlColFqQqV@aUA "Retina – Try It Online") Explanation:
```
T`p`~
```
Translate all the characters to `~`s.
```
Y`~`\He\l\l\oW\or\l\d
```
Cyclically translate all the `~`s to the characters `HelloWorld`. Note that unfortunately most of them have special meanings to translate so that they have to be quoted.
[Answer]
# [Perl 5](https://www.perl.org/) + `-pl`, 23 bytes
Inspiration taken from [@Neil's Retina answer](https://codegolf.stackexchange.com/a/250518/9365). 3 bytes saved thanks to [@Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus)!
```
$_&=HelloWorld x y//./c
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiMDAwMDAwMDA6IDI0NWYgMjYzZCA0ODY1IDZjNmMgNmY1NyA2ZjcyIDZjNjQgMjA3OCAgJF8mPUhlbGxvV29ybGQgeFxuMDAwMDAwMTA6IDIwNzkgMmYyZiBmZjJmIDYzICAgICAgICAgICAgICAgICAgICAgICAgIHkvLy4vYyIsImFyZ3MiOiItcGwiLCJpbnB1dCI6ImFcbmFCQ1xuQWJDRGVmZ0hJamtsbW5PUHFyU3RVdiJ9)
## Explanation
Sets `$_` (which will be implicitly output via `-p`) to the result of stringwise `AND`ing a string of `HelloWorld`s repeated once for the count of each char in the input (implicitly stored in `$_` via the implicit `-n` from `-p`) when `tr///`ansliterated (`y///`) from any char to `\xFF`s. This operation results in a string the length of the original input with the content `HelloWorld` truncated accordingly.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 5 bytes
```
ẏkhȧİ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwi4bqPa2jIp8SwIiwiIiwiR2FtaW4iXQ==)
Can't believe I had to find a new 5 byter because someone got my answer by 2 bytes shorter :p.
## Explained
```
ẏkhȧİ
ẏ # The range [0, len(input)]
khȧ # The string "HelloWorld"
İ # The range indexed into the characters of the string.
```
## [Vyxal](https://github.com/Vyxal/Vyxal) `sr`, 5 bytes
```
khȧf•
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzcmEiLCIiLCJraMinZuKAoiIsIiIsImJcbnJcbnVcbmhcbm1cbm9cbm1cbmVcbm5cbnRcbi4iXQ==)
More flags and more ways that I won't be outgolfed again. Takes input as a list of characters
### Explained
```
khȧf•
khȧf # The string "HelloWorld" as a list of chars
• # Molded to the shape of the input
```
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 23 bytes
```
O G*"HelloWorld"=cL P0c
```
[Try it online!](https://tio.run/##rVltU9tIEv5s/4rBKSyNLCeyYKu2bGSKZIGjjkAWks0H8AUhy1h1suyTZFiOcH89293zopFtspe75YNlzTzd0/1MT3ePibp3UfTtVZJF6XIc7xXlOJm/ng6b5kia3NaGovJxEa@A8iS7qw2VyUxgxvEkyWKWpiydZ3f00dSjH88@vWe96vXy4wXzq9ffDi7YbvV6dPaO/Vy9XnxivQp8dHppYM8@nRrQT2fvDy7/bhec2fjRZv/p/cT17MElLCsmo2mYM4dXAiYKbNUqhkO2W82dHX7GyQwmyaOvDL/v7a1gcBnCoJuASVOOwBrm7fn5KYHwY5@c7KNvhiEXxwIA8oat92G6jDm/yka82SQ/YFeuRsFF6/D8yP52zo6d1t/iNJ1/nufpuBVEp@yDF33jMNsaCAEHJOJwxgIUHTSboH8R5kVsc/bUbCRZyZJBswGjtJbLnMkyi2CEhCN4L2cLt1hkV/4oePJc7xl0NBJQR3h4ejjw5g2qTxbsYZqUcbEIo7jZgO9pbMM4iNvCDJe1rsvr7HpynbOn56uRzfuvWpxMaSQTZmtrA2a9sjgTKtToFoxeZzDc6YgRsLMRp0VsDjwLc6JpHP2TTeY5y5az2zgvpD3MTopxcpeUSiusju70XO2ReDqs57EOc6TlnQ5nXWZ5FiyBliac5XG5zDOmokOIUYAMVm24D/MkvE1jZQUYkc4f4tyOYD1lCPv6lSnjInqLiIgvFpf0JBtcT4KeC3sU6OEV6/C8ybgESDZeLmzcUiY57TJ4WzdYnP5CaBNmXFtWZVPLEpsGwuCBNoqBEsgW8B0sW4RFycppDMrCvASw3ABHMYobGnH0RBlrHKIXjYXPHqeNblRkkPkYumUyz8BsjFhvBKZFipFiuVgg4VxFlRox6TfjD2g3yEYdKpQXGcQxZC6MXGm5YOWjpY@3GDjCAcxifcxeaKYKMkp8wlUb7UZTQzjJkb3ruT2ODuKwdoIczJZpGuaPpqPV/lwY2/PB0pbRglJ@ma1I0xI9XEImhU2eHhy@fXfz69bpL@eGw6ba22SjXn9d71ZN8fHJ5QsayzgnlWE2Zv9ahuoV1d6bS@ysLyEIOLY0FycbuCDh3bpwHfNMqTJfZrhDA5l9nXJe2CpX0gGA0C6TiNHs7XJy5e@OpB1io9uUHrQBxQKOVTmxAQr@b6eQtFXeoerjopJVBXAotAJR18T6Ndwe6@3U/UTnMRb3WavMl3ELYlCPY0jC@CSEDIITLYysVkUC@om@ywJEdHx5O5@nMHNbZ@BFXyu3vueQ8@MemWberpmZoo3ZX2ojBG05T1PbNNVlngsV4n8wOVszGavw@4MPZy7WYhFo8Hpy1fM8D8IJXIFX9VYk/46/lAwfAyNGDW@RAXhz8cOnz52gp0o6Zjis6vigT188dgBwdHJ66LAJJMdBQ4e2XA/TcBQu3DTOqAMwuFL9keAMzt1LZKwKYm3C0oYFx06ol4BavEdcDKCoJDip80Y0W6zsAJGUjKoUgjQlI1ymeEjKaGo7wMxaOwUcMfkXYZ2yDqw@w1UEIEBCsSGDLMzb5JRUL1vCWsjyAVXhCkF9Z5lj6aLW82rEn6owgwaKcrtY@AIWruvOIePZvO39PsG/CvkBkKBVcHQXlyl0jXab9rKNO4QlcpxkfJBMbJv2ExuCaJqjLS7EKedimwNvsNFWeHBqA8R6h2I90TliNpCEDJS9SJLMnZWVbyt/BF7PvKtmUNKkWGNuAIPRAPEXLOaLOLONhd1W3qJWAawKZqJSQjwGvrf7M43L5sIWHckETB@jU9DCQci62N8BHHoHesM1YGkVXjYMsk5ArRCeWEBySTfoobWIatTgBMw3e5aKxsqTX8GT@Hdo4/C0r/m5Vdt1uhxsYSZbA56uhQesktZ5MeC/WH3ZJ24IZJ35ZAVqnVFbbGMN4qoIDYe7vGos19KhEr2k5tDeLlCwfhjWhYFOaH3MdSGT8lYFVRNYXuIwk2pfKmGyZpk7IHOLZOG8YgEPhrj4IGliP2vUsXabblTdLkJHos29pna7oczafu0UYI8Nb5ypo5Yb5i/LQu2@jgnR6wmDOtogypOQLzElY2gZ2yO66UZ9t8X1FNHQ9zMVS77Yc@x/6TCIDSAUDuMpD5SXPt8cqlFYqofsOnudiiauvqMuDt2oS89S5gjpV3ctOo1ox1a9bq8Qcqrd2cDCannewIOzxoPY100szDa45hAmMJWQANQgmzJkYF3DJQ9Bg26X9EmiqGSubrRgtKyd/jffJebNZmK2vyu0vVnoH8RmzSFxdaAx3/RyIGkXrAes29MsExao78E56/bgjPVMsP@D6D1IjzVsECCU1u2rEU9RTkT7Q09y7XNqV5yA@G@uHgiaJFfgjkAJFksMfMcrwzTOY6tg2Rx66CQtk4w9hI/AGxvP4U5axndxDjKLeRZnZRLiLQJO8pw9xGwa3scAlIoQXrJZmC0hfB5f4yh6d4uMAxXERLFMS/zRgBbXCU9BuiZGLblCmSmnISvqUd/LSO9lQzRsr4by6H4eplgbH8HrbJzGY3ZTmX2jtTzhN9GYGYtUzgxRWber3jnBGxLqGKY/6zy4R8G6Uvgw6dXyYlDPivvMPPx75jFA0b784a3NBGCf1RpFGnSZkQ1RhyckVcn1RR1A7FYA1cbogoZwKDG05uN5n83iWbTAMMvY8Gb//3Vl@Be4MlSubG3wJZC@SFf2X2ZfrLrBZJzeZzWArxG@KqBbm@ysXrR7KvOYCrR57Sr9oS@basO@KSlTiZb/@t/IyxxkqNHyA6tvomtt7io2qLJuffqHLzKqt61uMohr1G4zOhUSBjWOgpq0kSZRAhGdjhYTJn8G98SvXmajWfOOmb2LFDupd@0INeT3/f6OQcuxuDIERofVMQvQ@h0pkxcPV5@FnVpDeymIXlE6WC15/qaSt8N1H@Br6V0a/JOGCA3DJ25FpJt/3Q6ZvZEPHuKqnR42SdQgiPgXk/QgREeeBFh9HE9CSJLgmeowkwwmkzH9iBRGJZQpazuysOfEEc5euMWiMl0DoRuUPyTMwiTDZpWF@V3kklLHge/3HH@uovsl/h/H9sia@jXu@dsU/5vwBw)
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 180 bytes
```
>+[++[++>]<<+]>+[->>+>+>+>+>+>+>+>+>+<<<<<<<<<<]-[>+<-------]>->-------->>++++++>+++>--------------------->+++>>>------->,[>+<,]>[-<<[[->+<]<]>>.>>>>>>>>>[-<<<<<<<<<<+>>>>>>>>>>]>]
```
[Try it online!](https://tio.run/##XY1BCsMwDAS/4ruivkDsR8we3JRQkzSHkpDnu1ZSG9qRQFotku7vlNdpH@dSIFE8QTNhVQrIf1iHGqvUC0LxbX3rxEsf/nA6aB4GPzQQUc1i/SpGI3BDw42G9CkIljLnZQnP/AppC490rB8 "brainfuck – Try It Online")
Can likely be golfed quite a bit more, as the majority of the code is setting up the string "HdlroWolle" on the tape.
Explanation:
```
>+[++[++>]<<+]>+ 108 = 'l'
[->>+>+>+>+>+>+>+>+>+<<<<<<<<<<] ptr before '\0lllllllll'
-[>+<-------]>- ptr on 'H'
>-------- 'd'
> 'l'
>++++++ 'r'
>+++ 'o'
>--------------------- 'W'
>+++ 'o'
> 'l'
> 'l'
>------- 'e' ("HdlroWolle")
> ,[>+<,] [Read all input, counting the length of it 2 cells after the string.]
>[-< Do len(input) times:
<[ Shift the string right by 1
[->+<]
<
]
[see https://www.codingame.com/playgrounds/50443/brainfuck-part-2---working-with-arrays]
[Print the first character of the string and move the far
right cell back to the beginning, rotating the string.]
>>.>>>>>>>>>[-<<<<<<<<<<+>>>>>>>>>>]
>] End loop
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
LkhȧẎ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJMa2jIp+G6jiIsIiIsImhvdyBhcmUgeW91Il0=)
[Answer]
# [Haskell](https://www.haskell.org/), 33 bytes
```
($cycle "HelloWorld").take.length
```
[Try it online!](https://tio.run/##DcoxDoAgDADArxDCoAs/YPcHzg0WIVSaQI3h9ZWbL8OoSKQPlBZKE@wQxY3Mn0@awubijITGHivxyZ0uu3uBip6w3ZJVVzXQ0Ux@fw "Haskell – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `sequences.repeating`, 33 bytes
```
[ "HelloWorld"swap length cycle ]
```
[Try it online!](https://tio.run/##RcsxDsIwDAXQvaf4ygF6ADgAdGFBiAExWKnbRjVOcIyqnj6wsb3lTRQ9W7tdh8vpgJVNWVD5/WGNXP/qjQuTJ51RjN33Ykkdx64LaxLBkl4gx0ibhvZAOLNIvmeTMdSNCoR19gVxj8J4tki/07cv "Factor – Try It Online")
[Answer]
# [lin](https://github.com/molarmanful/lin), 25 bytes
```
"HelloWorld"`cyc.~ len `t
```
[Try it here!](https://replit.com/@molarmanful/try-lin) Returns an iterator.
For testing purposes:
```
"how are you" ; `_` outln
"HelloWorld"`cyc.~ len `t
```
## Explanation
Cycle and take (input length) items.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“ ⁷ỴNt»ṁ
```
A monadic Link that accepts a list of characters and yields a list of characters.
**[Try it online!](https://tio.run/##ASgA1/9qZWxsef//4oCcIOKBt@G7tE50wrvhuYH///8naG93IGFyZSB5b3Un "Jelly – Try It Online")**
### How?
Pretty simple...
```
“ ⁷ỴNt»ṁ - Link: list of characters, S
“ ⁷ỴNt» - dictionary lookup -> "HelloWorld"
ṁ - mould like S
```
[Answer]
# vim, 46 bytes
```
$mma<C-R>=col('$')
aHelloWorld<C-V><ESC><ESC>`mlDo<ESC>@"khjllDkdd
```
## Annotated
```
$mm # Go to the end of input and mark our position
a # Append...
<C-R>=col('$') # The column offset/line length
aHelloWorld<C-V><ESC> # This exact string
<ESC> # ...which yields a command that prints "HelloWorld"
# once per char in the original input. (All that matters
# is that this string is at least as long as the output
# needs to be.)
`mlD # Delete the string we just appended, copying into register "
o<ESC>@" # Run the command, putting a bunch of "HelloWorld"s on next line
khjllD # Make the new line the same length as the input
kdd # delete the input
```
`<C-R>` is 0x12, `<ESC>` is 0x1b, `<C-V>` is 0x16.
[Try it online!](https://tio.run/##K/v/XyU3N1HINjk/R0NdRV2TK9EjNScnPzy/KCdFTFo6ITfHJV/aQSk7IysnxyU7JQWi3sZZN8gOrgfI87VD0gfkh9nZuAY7QwiwGWAWkjkA "V (vim) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 37 bytes
```
-join($args|%{'HelloWorld'[$i++%10]})
```
[Try it online!](https://tio.run/##VY/BjoIwEIbvfYo5lC1ETNwHMCExMd7W6MGDMYaFEeqWVtuyaJBnZwuoq3OazPfN385JVahNjkK09ABTqNvxUXHp01hn5ubVbOGQ2igtUralfDTyPie7JmgbQiKfhD7LVQWxRriqkoUv9oIFPdYcJeaV/H2jA/zhQkDOC4gtpHEl3wP6zokB3MCDmoAraqzmMguB4uWEicXU/ZnuB6bRlMK6wYc7JRrMnmyX61lprCq@vo9uaRcNYV2tyyRBY7qU@/oYz//pT2/1yL5rTzDXqujGL881pGn/AA "PowerShell – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org) (full program), 145 bytes
The full program rule doubles the length.
```
fn main(){for l in std::io::stdin().lines(){print!("{}",(0..).zip(l.unwrap().chars()).map(|i|b"HelloWorld"[i.0%10]as char).collect::<String>())}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY69CsIwFIVfJRaEFDXUTYI4uzs4iENsEs1Pk5KkCLZ9CGeXDvpQvo231Oncw_nO5bzeoYlpGD5NkqvN9ykdqphyOG-lD8gi5VBMnFLlKYVjTIhVTkQg6qBcmuGs7bMlLgjJyUPV2JLG3QOrASxvLACYkwpsp7pLthfW-qMPlmcnRYr5ujiziEYOaG-tKBOl20OCz9cdNPt-GvbfN3wX0XCpDZokIqONRiZyLY0GJ0blECcR5NT5AQ)
# [Rust](https://www.rust-lang.org) (function), 85 bytes
```
|l:&str|(0..).zip(l.chars()).map(|i|b"HelloWorld"[i.0%10]as char).collect::<String>()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NU47TgMxFOx9isdKRLYAa-mQA9T0KEqBKJa1HWy_2Cvbq0jJ7kloUsABOE5ug60Vr5k3mo_m6zuOKZ9_tYd9ZzxlcEKVQT_9jFnfPVw2E4pVynGiLeeMH81AkfefXUyUMb7vBjqZ6aN5UYhhGyLK5s3w9vq-fe8SVB_jfUBUfRbi8TVH43fPlP2XrwnRIQIar8B4SFkKYYIQ5albeBVS3USg3lDiGf0VbU5zcwuarqqBj_4QyxDG2JrMZF7Kz5eb5KS2DhZI4Kyz4JK02tnCVEVZ5KyiXjJ_)
[Answer]
# [Alice](https://github.com/m-ender/alice), 54 bytes
```
/ H l o o l " \w>?hn$vihn$@?]oK
" e l W r d ! ^(H' <
```
[Try it online!](https://tio.run/##S8zJTE79/19fwUMhRyEfCHMUlBRiyu3sM/JUyjKBhIN9bL43F1AwFSgVrlCkkKKgqKAQp@GhrmDz/392Zk6OQkZmrkJiiUJKYnkeAA "Alice – Try It Online")
# Flattened
```
/"HelloWorld"!\w>?hn$vihn$@?]oK
^(H' <
/"HelloWorld"!\ Pushes the hello world string on the tape
w ihn$@ K While where are characters to read on the input
>?hn$v If the tape is outside of "HelloWorld"
^(H' < Rewind the tape
?]o Print one character from the tape and move to the next one
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~37~~, 35 bytes
```
->x{('HelloWorld'*l=x.size)[0...l]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf166iWkPdIzUnJz88vygnRV0rx7ZCrzizKlUz2kBPTy8ntvZ/QVFmXolCml5yYk6OhnpGfrlCYlGqQmV@qbrmfwA)
-2 bytes thanks to @Steffan
[Answer]
# [Zsh](https://www.zsh.org/), 26 bytes
```
<<<${(r:$#1::HelloWorld:)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuha7bGxsVKo1iqxUlA2trDxSc3Lyw_OLclKsNGshCqDqtkUrFZanFpVUlmbmFyQWp6SlZ2RlK8VCZQE)
[Answer]
# x86‑64 machine code on Linux, 97 B
## input
* `/dev/stdin` connected to a pipe or terminal in cooked mode
* possibly empty input
* Linux zeros processor registers upon process initialization (with the obvious exception of `rsp`).
## source code
Uses NASM – the Netwide Assembler.
Overview of algorithm:
1. Infinitely wait until data become available. (`select`)
2. Query total number of Bytes immediately available for reading. (`FIONREAD`)
3. Discard input. (`TCIFLUSH`)
4. Integer division: Bytes that were available for reading count divided by 10.
5. Loop: Whole 10 Byte writes of `'HelloWorld'`.
6. Write remainder of integer division Bytes.
```
global _start
bits 64
default rel
; These two constants rather serve as documentation:
STDIN_FILENO equ 0
STDOUT_FILENO equ 1
; Linux (`syscall`) system call numbers used in this program:
sys_exit equ 60
sys_ioctl equ 16
sys_select equ 23
sys_write equ 1
; `ioctl(2)` requests used:
FIONREAD equ 0x0000541B
TCFLSH equ 0x0000540B
; Argument to `TCFLSH` request:
TCIFLUSH equ 0
; ==============================================================
section .text
hello_world:
db 'Hello'
db 'World'
; 'HelloWorld'’s length is `10`, but this is cleaner style:
hello_world_length equ $ - hello_world
_start:
; rax rdi rsi rdx r10 r8
; select( 1, [rsp], NULL, NULL, NULL)
push 1 ; bitfield with LSB set
mov rsi, rsp ; *readfds
pop rdi ; nfds
push rdi ; rsp for get_iteration_count
mov al, sys_select
syscall
get_input_length:
; rax rdi rsi rdx
; ioctl(STDIN_FILENO, FIONREAD, [rsp])
xor edi, edi ; fd := 0 (STDIN_FILENO)
xchg rsi, rdx ; bytes available buffer
mov si, FIONREAD ; ioctl(2) request number
mov al, sys_ioctl
syscall
discard_input:
; rax rdi rsi rdx
; ioctl(STDIN_FILENO, TCFLSH, TCIFLUSH)
mov edx, edi ; TCIFLUSH = 0 → copy zero
mov sil, TCFLSH & 0xFF ; TCFLSH − 0x10 = FIONREAD
mov al, sys_ioctl
syscall
; `rax` may be non-zero now, in particular −ENOTTY.
test eax, eax ; for dumb last char = "\n" test
setns dil ; subtrahend = 0 for ENOTTY
get_iteration_count:
; Retrieve number of Bytes that were available for reading.
pop rax
sub eax, edi ; subtract 1 if this is terminal
jc exit ; user typed ^D (detach input)
; Load divisor.
push hello_world_length
pop rcx
; eax := number of whole writes; edx := Bytes in partial write
div ecx
; Save Bytes in partial write for `finish_write` below.
; The `push rdx`/`pop rdx` pattern is just two 2 Bytes.
push rdx
; Use `ebx` as loop counter, because `syscall` clobbers `rcx`
; and this does not require a REX prefix like r8 – r15 do.
xchg eax, ebx
write:
; rax rdi rsi rdx
; write(STDOUT_FILENO, hello_world, 10)
xchg edx, ecx
lea rsi, [hello_world]
mov dil, STDOUT_FILENO
test ebx, ebx ; zero _whole_ writes test
jz finish_write ; zero entire 10B writes
keep_writing:
mov al, sys_write
syscall
dec ebx
jnz keep_writing
; Write the remainining ≤ 9 Bytes.
finish_write:
pop rdx
mov al, sys_write
syscall
exit:
xchg ebx, edi ; rdi := 0 (= “successful”)
push sys_exit ; need to wipe entire register
pop rax ; because we may have jumped
syscall ; here from get_iteration_count
; vim: ft=nasm:
```
## disassembly
```
helloWorld.o: file format ELF64-x86-64
Disassembly of section .text:
0000000000000000 <hello_world>:
0: 48 rex.W
1: 65 6C gs ins byte ptr es:[rdi], dx
3: 6C ins byte ptr es:[rdi], dx
4: 6F outs dx, dword ptr ds:[rsi]
5: 57 push rdi
6: 6F outs dx, dword ptr ds:[rsi]
7: 72 6C jb 75 <exit + 0x1B>
9: 64 fs
000000000000000A <_start>:
A: 6A 01 push 0x1
C: 48 89 E6 mov rsi, rsp
F: 5F pop rdi
10: 57 push rdi
11: B0 17 mov al, 0x17
13: 0F 05 syscall
0000000000000015 <get_input_length>:
15: 31 FF xor edi, edi
17: 48 87 F2 xchg rdx, rsi
1A: 66 BE 1B 54 mov si, 0x541B
1E: B0 10 mov al, 0x10
20: 0F 05 syscall
0000000000000022 <discard_input>:
22: 89 FA mov edx, edi
24: 40 B6 0B mov sil, 0xB
27: B0 10 mov al, 0x10
29: 0F 05 syscall
2B: 85 C0 test eax, eax
2D: 40 0F 99 C7 setns dil
0000000000000031 <get_iteration_count>:
31: 58 pop rax
32: 29 F8 sub eax, edi
34: 72 24 jb 5A <exit>
36: 6A 0A push 0xA
38: 59 pop rcx
39: F7 F1 div ecx
3B: 52 push rdx
3C: 93 xchg ebx, eax
000000000000003D <write>:
3D: 87 D1 xchg ecx, edx
3F: 48 8D 35 BA FF FF FF lea rsi, [rip + 0XFFFFFFFFFFFFFFBA]
46: 40 B7 01 mov dil, 0x1
49: 85 DB test ebx, ebx
4B: 74 08 je 55 <finish_write>
000000000000004D <keep_writing>:
4D: B0 01 mov al, 0x1
4F: 0F 05 syscall
51: FF CB dec ebx
53: 75 F8 jne 4D <keep_writing>
0000000000000055 <finish_write>:
55: 5A pop rdx
56: B0 01 mov al, 0x1
58: 0F 05 syscall
000000000000005A <exit>:
5A: 87 DF xchg edi, ebx
5C: 6A 3C push 0x3C
5E: 58 pop rax
5F: 0F 05 syscall
```
Having the `'HelloWorld'` string in the `.text` section is weird, but putting (read-only) data into an already/definitely existing section, i. e. `.text`, makes the executable file smaller.
The stripped ELF64 executable file has a size of merely 440 B, not that *that* really mattered for *code* golfing.
## output
* output lacks of a trailing newline
* `HelloWorld` repeating until the input’s length is reached
* on a terminal *input length − 1* accounting for a presumed terminating `"\n"` [even if the user actually detached from input `Ctrl‑D`]
## limitations
* I am *not sure*, but *maybe* the `FIONREAD` `ioctl(2)` I am utilizing is capped at `0x7FFFF000` because *one* `read(2)` can transfer at most this many Bytes? Therefore this program’s output will be limited to 2,147,479,552 Bytes accordingly.
* At any rate, there’s a 32-bit `div ecx`, so a string length ≥ 232 is not handled correctly.
* If we’re reading from a pipe, the pipe’s capacity may be the limiting factor. In `pipe(7)`, § pipe capacity, it says the default value is 65536 B (so it can be changed). Similarly, a terminal’s input buffer may have comparable “low” dimensions. Yet these are implementation details *outside* of this program.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 15 bytes
```
"HelloWorld"⥊˜≢
```
[Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=UmVwZWF0SGVsbG9Xb3JsZCDihpAgIkhlbGxvV29ybGQi4qWKy5ziiaIKUmVwZWF0SGVsbG9Xb3JsZCAiVGhlIHJhaW4gaW4gU3BhaW4gZmFsbHMgbWFpbmx5IG9uIHRoZSBwbGFpbiI=)
```
"HelloWorld"⥊˜≢
≢ # get the shape (length) of the input
⥊˜ # and use this to reshape
"HelloWorld" # the string "HelloWorld"
# (recycling elements if required)
```
[Answer]
## [Kustom](https://help.kustom.rocks/s1-general/knowledgebase/top/c2-functions), 39 bytes
Basically just [this Javascript answer](https://codegolf.stackexchange.com/a/250523/112863).
The extra byte is for the global variable name.
```
$tc(rpad,"",tc(len,gv(i)),HelloWorld)$
```
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 35 bytes
```
% L*h|%{'HelloWorld'*$_|% S*g 0,$_}
```
[Try it online!](https://tio.run/##Fcw9DsIwDAbQq3xDI0tRkThGBzYGxiqiFo4wMTI/UUU4eyjjW97dKvtDWHV3NudOYhXJGau9aASJZy4stbz/umZVSL4hPbGkWgitBxyitPChaUvsZK4LxWFuAcd4wX4c5m/vPw "PowerShell Core – Try It Online")
# Windows PowerShell, 38 bytes
```
% L*h|%{'HelloWorld'*$_|% S*g -a 0,$_}
```
Same as above, but PS 5.1 requires actually naming the parameter "-ArgumentList" (shortened to "-a") for the Substring() method call.
Input comes from the pipeline.
Nothing fancy; this is basically
`ForEach-Object {$l = $_.Length; ('HelloWorld' * $l).Substring(0, $l)}`
```
% L*h|%{'HelloWorld'*$_|% S*g 0,$_}
% L*h # "ForEach-Object -MemberName Length": invoke the method "Length" for the string passed in the pipeline
| # Pipe the length of the input string to the next cmdlet
%{ # "ForEach-Object -ScriptBlock {"
'HelloWorld'*$_ # repeat the string 'HelloWorld' <Length> times
| # and pipe the 'HelloWorldHelloWorld...' to the next cmdlet
% S*g 0,$_ # "ForEach-Object -MemberName Substring -ArgumentList 0, <Length>": invoke the method "Substring" for the string passed in the pipeline, get <Length> chars starting at 0
} # }: end of the scriptblock; Output is implicit
```
[Answer]
# [simply](https://github.com/ismael-miguel/simply), ~~111~~ 106 bytes
This is (yet another) language I'm just working on, for fun.
It is a very verbose language, and still in progress, which is why the algorithm is ... less conventional and very convoluted...
```
def&f($v){$C=&str_chunk("HelloWorld"&len($v));send$C[0];}echo&join(&array_map(&str_chunk($argv[0]10)&f)'')
```
Due to oversights in the parser, the values don't have to have to be separated by commas.
---
## Ungolfed:
```
Create a function called &handle_chunk with arguments ($value).
Begin
Assign $len the value of executing the function &len with argument $value.
Set the variable $chunks with the value of calling the function &str_chunk with the arguments "HelloWorld", $len.
Return the value $chunks[0].
End.
Display the result of calling &join(
Call the function &array_map with the arguments (
Run &str_chunk($argv[0], 10),
&handle_chunk
),
""
).
```
Should be self-explanatory.
---
## How to run:
Download the repository and open `índex.html`.
---
---
## Unintended method:
This is simply a re-implementation of [m90's answer](https://codegolf.stackexchange.com/a/250523):
```
%c="";def&f($s)call%c->padEnd(&len($s)"HelloWorld");
```
Works the same way as the intended way.
] |
[Question]
[
\$\left\{ n \atop k \right\}\$ or \$S(n, k)\$ is a way of referring to the [Stirling numbers of the second kind](https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind), the number of ways to partition a set of \$n\$ items into \$k\$ non-empty subsets. For example, to partition \$\{1,2,3,4\}\$ into \$2\$ non-empty subsets, we have
$$\begin{matrix}
\{\{1\},\{2,3,4\}\} & \{\{2\},\{1,3,4\}\} & \{\{3\},\{1,2,4\}\} & \{\{4\},\{1,2,3\}\} \\
\{\{1,2\},\{3,4\}\} & \{\{1,3\},\{2,4\}\} & \{\{1,4\},\{2,3\}\}
\end{matrix}$$
So \$\left\{ 4 \atop 2 \right\} = S(4,2) = 7\$
Here, we'll only be considering the sequence \$\left\{ n \atop 3 \right\} = S(n, 3)\$, or the ways to partition \$n\$ items into \$3\$ non-empty subsets. This is [A000392](https://oeis.org/A000392). There is also the related sequence which ignores the three leading zeros (so is \$1, 6, 25, 90, 301, ...\$)\${}^\*\$.
This is a standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge, where you can choose which of the two related sequences to handle (leading zeros or not). Regardless of which sequence you choose, you should do one of the following:
* Take an integer \$n\$ and output the \$n\$th element of the sequence. This can be \$0\$ or \$1\$ indexed, your choice, and \$n\$'s minimum value will reflect this.
* Take a positive integer \$n\$ and output the first \$n\$ elements of the sequence
* Take no input and infinitely output the sequence
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
\${}^\*\$: I'm allowing either sequence, as handling the leading zeros can "fail" for some algorithms that have to compute empty sums
---
## Test cases
If you ignore the leading zeros, the first 20 elements are
```
1, 6, 25, 90, 301, 966, 3025, 9330, 28501, 86526, 261625, 788970, 2375101, 7141686, 21457825, 64439010, 193448101, 580606446, 1742343625, 5228079450
```
Otherwise, the first 20 elements are
```
0, 0, 0, 1, 6, 25, 90, 301, 966, 3025, 9330, 28501, 86526, 261625, 788970, 2375101, 7141686, 21457825, 64439010, 193448101
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
3Ḋ*)SI
```
[Try it online!](https://tio.run/##y0rNyan8/9/44Y4uLc1gz/@H2x81rfn/3xQA "Jelly – Try It Online")
*-1 byte thanks to Jonathan Allan*
1-indexed sequence without leading zeros. Uses the formula \$\sum\_{k=1}^{n} 3^k - 2^k\$.
## Explanation
```
3Ḋ*)SI Main monadic link
) For each k in the range [1..n]:
3Ḋ Remove the first element from the range [1..3]
* Raise each to the power of k
S Sum (producing [sum(2^k), sum(3^k)])
I Increments
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
cþæ*2FS
```
[Try it online!](https://tio.run/##y0rNyan8/z/58L7Dy7SM3IL/Gxocbn/UtOY/AA "Jelly – Try It Online")
Now that [xigoi has outgolfed me](https://codegolf.stackexchange.com/a/231668/66833), I thought I'd share my answer.
This outputs the \$n\$ term of the sequence without leading zeroes.
## How it works
We generate the matrix
$$\left[\begin{matrix}
\binom 1 1 & \binom 2 1 & \cdots & \binom n 1 \\
\binom 1 2 & \binom 2 2 & \cdots & \binom n 2 \\
\vdots & & \ddots & \vdots \\
\binom 1 n & \binom 2 n & \cdots & \binom n n
\end{matrix}\right]^2
= \left[\begin{matrix}
1 & 2 & \cdots & n \\
0 & 1 & \cdots & \frac {n(n-1)} 2 \\
\vdots & & \ddots & \vdots \\
0 & 0 & \cdots & 1
\end{matrix}\right]^2
= \left[\begin{matrix}
1 & 4 & \cdots & \sum^n\_{i=1} i \binom n i \\
0 & 1 & \cdots & \sum^n\_{i=1} \binom i 2\binom n i \\
\vdots & & \ddots & \vdots \\
0 & 0 & \cdots & 1
\end{matrix}\right]$$
We then calculate \$A^2\$ and get the sum of each element, by flattening and taking the total sum. As to *why* this works, I have no idea - I just discovered it after playing around with `þæ*` patterns in Jelly.
```
cþæ*2FS - Main link. Takes n on the left
þ - Generate an n x n matrix where each cell (i,j) is:
c - iCj (binomial choose)
æ*2 - Matrix square
FS - Flatten and sum
```
[Answer]
# [R](https://www.r-project.org/), 23 bytes
```
3^(n=scan()+2)/2-2^n+.5
```
[Try it online!](https://tio.run/##K/qfZptWmpdckpmfp5GpWa1QnJyYhxDRzFT4bxynkWcLEtbQ1DbS1DfSNYrL09Yz/V/LFZaaXJJflFmVqpGmqWFgZWSg@R8A "R – Try It Online")
Outputs without the leading zeros, 0-indexed.
Uses formula from [OEIS page](https://oeis.org/A000392):
$$ a(n) = 9 \cdot 3^n/2 - 4 \cdot 2^n + 1/2 $$
[Answer]
# [Alchemist](https://github.com/bforte/Alchemist), 76 bytes
```
_+0j->2c
b+0j->3d
0j+0_+0b->j
c+j+x->_+j
d+j->x+b+j
j+0c+0d->Out_x+Out_" "!b
```
[Try it online!](https://tio.run/##S8xJzkjNzSwu@f8/XtsgS9fOKJkrCcwwTuEyyNI2AIom6dplcSVrZ2lX6NrFa2dxpWgDpSu0k4BMoIJkbYMUXTv/0pL4Cm0QqaSgpJj0/z8A "Alchemist – Try It Online")
Outputs nonzero values infinitely using the formula \$S(n, 3) = \sum\_{k=1}^{n-2} (3^k - 2^k)\$.
On TIO, this computes up to the 13th element (2375101) before timing out.
[Answer]
# [Python 2](https://docs.python.org/2/), 24 bytes
```
lambda n:3**n/6-~-2**n/2
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPylhLK0/fTLdO1wjEAErmFynkKWTmKRQl5qWnahgZaFpxcRYUZeaVKOTpKKRp5Gn@BwA "Python 2 – Try It Online")
Formula from OEIS for \$n>0\$:
$$ f(n) = \frac{1}{2}(3^{n-1}-2^n+1)$$
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 bytes
Anonymous tacit prefix function using [xnor's formula](https://codegolf.stackexchange.com/a/231656/43319). 1-indexed.
```
2÷⍨1-2∘*-3*-∘1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3@jw9ke9Kwx1jR51zNDSNdbSBdKG/9MetU141Nv3qKv5Ue@aR71bDq03ftQ28VHf1OAgZyAZ4uEZ/D9N4VHvZiMjAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
3ẹ@þṗ¥ẠƇṢ€QL
```
[Try it online!](https://tio.run/##y0rNyan8/9/44a6dDof3Pdw5/dDSh7sWHGt/uHPRo6Y1gT7/DQ0OtwNZ/wE "Jelly – Try It Online")
A monadic link that takes \$n\$ as its argument and returns \$a(n)\$. This is longer and less efficient than the answers based on the OEIS formulae, but should work for any value of \$k\$ by varying the first number in the link from 3.
Also, removing the `L` at the end yields the actual sets.
## Explanation
```
3 ¥ | Using 3 as the left argument and n as the right argument:
ṗ | - Cartesian power of 3 and n (call this x)
ẹ@þ | - Find indices of each of 1 to 3 in each of x
ẠƇ | Keep only those lists where all are non-empty
Ṣ€ | Sort each list
Q | Unique
L | Length
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Surely there is an eight or less out there...
```
1×Ɱ3$¡FQS
```
A full program that accepts a non-negative integer from STDIN and prints the result using the 0-indexed, no leading zeros option.
**[Try it online!](https://tio.run/##y0rNyan8/9/w8PRHG9cZqxxa6BYY/P@/CQA "Jelly – Try It Online")**
### How?
```
1×Ɱ3$¡FQS - Main Link: no arguments
1 - start with x=1
¡ - repeat this (read from STDIN) times:
$ - last two links as a monad, x=f(x):
3 - three
×Ɱ - map (across y in [1..3]) with multiplication
FQS - flatten, deduplicate, sum -> sum of the set of integers encountered
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
Port of [xnor's answer](https://codegolf.stackexchange.com/a/231656/95792), made/fixed and golfed with hyper-neutrino's and caird coinheringaahing's help.
```
’3*_2*$‘H
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw0xjrXgjLZVHDTM8/hsZBB1uf9S05j8A "Jelly – Try It Online")
This doesn't handle leading zeroes.
```
’3*_2*$‘H
’ n-1
3* 3^(n-1)
_ From that, subtract
2*$ 2^n
‘ Increment that
H Halve it
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes
```
#~StirlingS2~3&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X7kuuCSzKCczLz3YqM5Y7X9AUWZeiYK@Q7q@Q1BiXnpqtIGOoYFB7P//AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Scala, 132 bytes
```
n=>(for{i<-1 to n-1
j<-i+1 to n-1
p<-1.to(n).permutations}yield{Set(p.slice(0,i),p.slice(i,j),p.slice(j,n))map(_.toSet)}).toSet.size
```
[Try it online!](https://scastie.scala-lang.org/hVP2ddi2TEifRNLu26aFeg)
Is it short? No. Is it efficient? No. Is it clever? No. Why did I make it? I...don't know. I'll try golfing it later, if possible.
[Answer]
# [Rattle](https://github.com/DRH001/Rattle), 24 bytes
```
|s>-s=3e~s<=2e~sg1-~+/R1
```
[Try it Online!](https://www.drh001.com/rattle/?flags=&code=%7Cs%3E-s%3D3e%7Es%3C%3D2e%7Esg1-%7E%2B%2FR1&inputs=19)
This is a port of [xnor's Python answer](https://codegolf.stackexchange.com/a/231656/95671) into Rattle using this formula:
$$ f(n) = \frac{1}{2}(3^{n-1}-2^n+1)$$
# Explanation
```
| takes the user's input
s saves the user's input (n) to memory slot 0
> move pointer right
- decrement user's input
s save (n-1) to memory slot 1
=3 set the value on top of the stack to 3
e~ perform 3^(n-1)
s save in memory slot 1
< move pointer left
=2 set the value on top of the stack to 2
e~ perform 2^(n)
s save in memory slot 0
g1 get value from slot 1
-~ subtract value in slot 0
+ increment
/ divide by 2
R1 reformat as int (which is printed implicitly)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 34 bytes
```
f(n){n=n<3?0:5*f(n-1)-6*f(n-2)+1;}
```
[Try it online!](https://tio.run/##VVDBboMwDL3zFRZSJaBBI4SEMMp2mPYVKweUhg5tSyuotGoVvz5mt7TbosSJ37Md@5l4a8w0tYELT65yK/GY3MsI3ZiHsTo/0nDJy3Hq3AE@ms4FoXfyABcB9ri35mA3LzVUcEoYXDZnoBikkkGBnkjQL5Si1xkTAtFUS8K1kinFKq6Iy7UucmJFLjnxOc@40hTBM5lrilFZJoqE0z@FyDKNcWN5bsm8Nn2E1po322NPQF356@Nzuj4WT3ikz@CvL/w5s931ENBEDlOSEq8VDN2X3bXBdcbwbgaiG1LCculCuOhx1WTACqRn@Q@1iN7UcvUvue@RbgN/sYH4AdAuhrXDNh2Dgd1msVU11HPJ0Runb9O@N9thij9/AA "C (gcc) – Try It Online")
Inputs \$0\$-based \$n\$.
Returns \$S(n,3)\$.
Uses the formula: \$a(n) = 5\cdot a(n-1) - 6\cdot a(n-2) + 1\$, for \$n > 2\$.
[Answer]
# [Factor](https://factorcode.org/) + `math.extras`, 18 bytes
```
[ 3 + 3 stirling ]
```
Ignoring leading zeroes. Zero-indexed. `stirling` is bugged in the build TIO uses. It was fixed about three years ago, so here's a picture of running it in the listener with a more recent build.
[](https://i.stack.imgur.com/aqDWA.png)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 [bytes](https://github.com/abrudz/SBCS)
```
-/3 2⊥¨∘⊂1,⍴∘1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X1ffWMHoUdfSQysedcx41NVkqPOodwuQafg/7VHbhEe9fY/6pnr6P@pqPrTe@FHbRCAvOMgZSIZ4eAb/Tzu0QuFR72YjAwA "APL (Dyalog Unicode) – Try It Online")
A function implementing the sum formula using base conversion:
$$
a(n) = \sum\_{k=0}^n \left( 3^k-2^k \right) = \sum\_{k=0}^n 3^k - \sum\_{k=0}^n 2^k = (\underbrace{1 \cdots 1}\_{n+1})\_3 - (\underbrace{1 \cdots 1}\_{n+1})\_2
$$
```
⍴∘1 ⍝ a vector of n 1's
1, ⍝ prepend an additional 1
⊂ ⍝ enclose in a length 1 list
3 2⊥¨ ⍝ for each of 2 and 3 decode the vector from that base
-/ ⍝ reduce the result by subtraction
```
If we use a full program instead of a function, this and a port of caird's Jelly answer are 13 bytes:
[`-/3 2⊥¨⊂1,⎕⍴1`](https://tio.run/##SyzI0U2pTMzJT///qKM97b@uvrGC0aOupYdWPOpqMtR51Df1Ue8WQ5Dc/zQuEwA) and [`+/∊+.×⍨∘.!⍨⍳⎕`](https://tio.run/##SyzI0U2pTMzJT///qKM97b@2/qOOLm29w9Mf9a541DFDTxFE925@1DcVJP8/jcsEAA)
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 16 bytes
```
L,Rd3€^¦+$2€^¦+_
```
[Try it online!](https://tio.run/##S0xJKSj4/99HJyjF@FHTmrhDy7RVjKCM@P///5v@yy8oyczPK/6vmwkA "Add++ – Try It Online")
Frick you caird for making such a painful esolang (:p). Port of everyone's favourite Jelly answer by xigoi.
## Explained
```
L,Rd3€^¦+$2€^¦+_
L, # make a lambda that:
Rd # pushes the range [1, input] twice and
3€^ # raises 3 to the power of each item,
¦+ # summing that list (can't use s to sum here because frick you caird)
$2€^¦+ # do the same with 2
_ # subtract the two items. The i flag automatically runs the lambda and implicitly outputs the result
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
Same approach as my APL answer.
```
$>и32SβÆ
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fxe7CDmOj4HObDrf9/28MAA "05AB1E – Try It Online")
```
$ # push 1 and input n
> # increment n
и # a list of n+1 1's
32S # push list [3, 2]
β # for each of those numbers, convert the list of 1's from that base
Æ # reduce by subtraction
```
The first three bytes could be `>Å1` instead: [Try it online!](https://tio.run/##yy9OTMpM/W9o4HNu63@7w62GxkbB5zYdbvv/3xgA "05AB1E – Try It Online")
A few alternatives from 8 to 11 bytes:
```
o3I<mα>; port of xnor's answer [Try it online!](https://tio.run/##yy9OTMpM/f8/39jTJvfcRjvr//9NAQ "05AB1E – Try It Online")
32SILδmOÆ the sum formula [Try it online!](https://tio.run/##yy9OTMpM/f/f2CjY0@fcllz/w21ADgA "05AB1E – Try It Online")
o<·3ILmOα sum(3^k, k=1..n)-(2^n-1)*2 [Try it online!](https://tio.run/##yy9OTMpM/f8/3@bQdmNPn1z/cxv//zcGAA "05AB1E – Try It Online")
Î>FNo-3Nm+ sum using a for loop [Try it online!](https://tio.run/##yy9OTMpM/W9o4HNu638fl3Nbkl0O7zi3Rev0HP///40B "05AB1E – Try It Online")
LDδcDøδ*˜O port of caird's answer [Try it online!](https://tio.run/##yy9OTMpM/W9o4HNu638fl3Nbkl0O7zi3Rev0HP///40B "05AB1E – Try It Online")
3Å0λ5*₂6*-> a(n)=5*a(n-1)-6*a(n-2)+1 [Try it online!](https://tio.run/##yy9OTMpM/f/f@HCrwbndplqPmprMtHTt/v8HAA "05AB1E – Try It Online") (infinite sequence)
```
[Answer]
# [Risky](https://github.com/Radvylf/risky), 10 bytes
```
+0?+1+_0+0__!2?-+_{0
```
[Try it online!](https://radvylf.github.io/risky?p=WyIrXG4wPysxK18wKzBcbl9cbl8hMj8tK197MCIsIlsyXSIsMF0)
1-indexed sequence without leading zeros. Uses the formula \$\sum\_{k=0}^{n} 3^k - 2^k\$.
## Explanation
```
+ sum
0 range
? n
+ +
1 1
+ copy-last
_
0 0
+ +
0 0
_ map
_
! 3
2 ^
? k
- -
+ 2^
_ [k,n]
{ index
0 0
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `sr`, 6 bytes
```
ƛ23fe¯
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=sr&code=%C6%9B23fe%C2%AF&inputs=5&header=&footer=)
A port of xigoi's Jelly answer
## Explained
```
ƛ23fe¯
ƛ # over the range [1, input] (call each item n)
23f # the list [2, 3]
e # ^ ** n
¯ # deltas of ^
# the s flag auto-sums the result
```
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
IΣE⊕N⁻X³ιX²ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUDDMy@5KDU3Na8kNQXILigt8SvNTUot0tDU1FHwzcwrLdYIyC8H8o11FDKBQhCOEYgDBtb//xsZ/NctywEA "Charcoal – Try It Online") Link is to verbose version of code. Uses @xigoi's Risky formulation of @Nitrodon's formula. Explanation:
```
N Input integer
⊕ Incremented
E Map over implicit range
X³ι Power of 3
⁻ Subtract
X²ι Power of 2
Σ Sum
I Cast to string
Implicitly print
```
I tried porting a couple of the other formulae too but they weighed in at 14 bytes.
[Answer]
# [Haskell](https://www.haskell.org/), 21 bytes
```
s n=div(3^n-3*2^n+3)6
```
$$\left\{n\atop3\right\}=\frac{3^n-3!\left\{n\atop2\right\}-3\left\{n\atop1\right\}}{3!}=\frac{3^n-3!\frac{2^n-2}{2!}-3}{3!}=\frac{3^n-3(2^n-2)-3}{3!}=\frac{3^n-3\cdot2^n+6-3}{6}=\frac{3^n-3\cdot2^n+3}6$$
[Try it online!](https://tio.run/##y0gszk7Nyfn/v1ghzzYls0zDOC5P11jLKC5P21jT7H9uYmaebUFRZl6JSrGNil20gZ6ekXHsfwA "Haskell – Try It Online")
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 17 bytes
```
n->(2^n-3^n\3)\-2
```
With leading zeros.
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWG_N07TSM4vJ0jePyYow1Y3SNIOI3VdLyizTyFGwVDHQUjIC4oCgzrwQooKSgawck0jTyNDU1IWoXLIDQAA)
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 18 bytes
```
n->stirling(n,3,2)
```
With leading zeros.
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWm_J07YpLMotyMvPSNfJ0jHWMNCESN1XS8os08hRsFQx0FIyAuKAoM68EKKCkoGsHJNI08jQ1oWoXLIDQAA)
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 14 bytes
```
n->-3^n\-2-2^n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboW6_J07XSN4_JidI10jeLyIII3VdLyizTyFGwVDHQUjIC4oCgzrwQooKSgawck0jTyNDU1IWoXLIDQAA)
This gives the sequence `0, 0, 1, 6, 25, 90, 301, 966, ...`. I'm not sure if this is allowed.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-mx`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
3p°U -2pU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW14&code=M3CwVSAtMnBV&input=OA)
```
3p°U -2pU :Implicit map of each U in [0,input)
3p :3 raised to the power of
°U : U, prefix incremented
- :Subtract
2pU :2 raised to the power of U
:Implicit output of sum of resulting array
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 13 bytes
```
Đ1⇹«⇹⁻3⇹^⇹-⁺₂
```
[Try it online!](https://tio.run/##K6gs@f//yATDR@07D60GEo8adxsDqTgg1n3UuOtRU9P//yYA "Pyt – Try It Online")
Port of [xnor's answer](https://codegolf.stackexchange.com/a/231656/95792)
] |
[Question]
[
You are given a string, which will contain ordinary a-z characters. (You can assume this will always be the case in any test, and assume that all letters will be lowercase as well). You must determine how many unique combinations can be made of the individual characters in the string, and print that number.
However, duplicate letters can be ignored in counting the possible combinations. In other words, if the string given is "hello", then simply switching the positions of the two `l`s does not count as a unique phrase, and therefore cannot be counted towards the total.
Shortest byte count wins, looking forward to seeing some creative solutions in non-golfing languages!
**Examples:**
```
hello -> 60
aaaaa -> 1
abcde -> 120
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~50~~ 48 bytes
```
f=lambda s:s==''or len(s)*f(s[1:])/s.count(s[0])
```
[Try it online!](https://tio.run/##ZVC7bhwxDOz9FcQ1vg2MjZPSwMGNA6RImypwwaW4d4T1skT68fUX6jYBErgRxCE5nJn6rqeSv57P6yFiWgJCv@uHw/V1aRA57/v0ad33X1/uHqfPfaZiWb28fZzOtUlWWPc7xIV209WlvvoHxWVZPuLfyyskoxO8lhL8sRgALwWdjJ5ge2X9H7yMbf@B3n/k/VEaJ5DaLUEo0eV3UcDEeuPruTMpqzXAIFU6ST4CR/Fm5@ALwGI9uSLlVH1ZMkmQ4HbBFCIuTg@sGzVDwmNGwCjPhjP8VOAsybkhyfi8eInpBp5NOuTStVkAfuNGoqhSMlj0uKlszGNIuoxLF0qpPgyMLjy5prIZ8FM6w8OgRFMGaeZKNq@SoXFtfOIcuLlxB15KtOrn2OW4U@DeGUhi/JuQGzJY7SiokIcgqNi8sDbDtzfiqmwjRs@gECGTz5FVCahjw13UViRwHimOpPwoWaw4fENZVyFBCNy5jW4qccjAEZB4HP1Prpbm3XT@DQ "Python 2 – Try It Online")
No boring built-ins! To my surprise, this is even shorter than the brute force approach, calculating all of the permutations with `itertools` and taking the length.
This function uses the formula
\$\text{# of unique permutations} = \frac{\text{(# of elements)!}}{\prod\_{\text{unique elements}}{\text{(# of occurences of that element)!}}}\$
and computes it on the fly. The factorial in the numerator is calculated by multiplying by `len(s)` in each function call. The denominator is a bit more subtle; in each call, we divide by the number of occurences of that element in what's left of the string, ensuring that for every character `c`, all numbers between 1 and the amount of occurences of `c` (inclusive) will be divided by exactly once. Since we divide only at the very end, we're guaranteed not to have any problems with Python 2's default floor division.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
œÙg
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6OTDM9P//89IzcnJBwA "05AB1E – Try It Online")
**Explanation**
```
g # length of the list
Ù # of unique
œ # permutations
# of the input
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 4 bytes
```
le!,
```
[Try it online!](https://tio.run/##S85KzP3/PydVUef//4zUnJx8AA "CJam – Try It Online")
### Explanation
Read line as a string (`l`), unique permutations as an array of strings (`e!`), length (`,`), implicit display.
[Answer]
# [R](https://www.r-project.org/), ~~69~~ 65 bytes
```
function(s,`!`=factorial)(!nchar(s))/prod(!table(strsplit(s,"")))
```
[Try it online!](https://tio.run/##DcsxDoAgDADA3VdIpzbR@AH9CwUhkjRASn0/ut1yOvN67uvMb41WWsWxeeevzNGaFhZCV@PDioPo6NpudMZBEg7T0aXYHwCIaGaEJ4k0oOUnM4cQgOYH "R – Try It Online")
4 bytes saved thanks to [Zahiro Mor](https://codegolf.stackexchange.com/users/65449/zahiro-mor) in both answers.
Computes the multinomial coefficient directly.
# [R](https://www.r-project.org/), ~~72~~ 68 bytes
```
function(s,x=table(strsplit(s,"")))dmultinom(x,,!!x)*sum(1|x)^sum(x)
```
[Try it online!](https://tio.run/##FcixDoQgDADQ3a/QTq3hhtv1V0xAIUdSwEhJOty/o24v7@phXD5jDy3vEkvGanQV69hjlaueHOUpACI6UmOJuSRUY6ZJaa4t4fevtL1Q6gHh55kL0PDQWuucA@o3 "R – Try It Online")
Uses the multinomial distribution function provided by `dmultinom` to extract the multinomial coefficient.
Note that the usual (golfier) `x<-table(strsplit(s,""))` doesn't work inside the `dmultinom` call for an unknown reason.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 49 bytes
`t=t*` is used instead of `t*=` to avoid rounding error (the `|t` rounds down the number) as `t=t*` guarantees that all intermediate (operator-wise) results are whole numbers.
```
a=>[...a].map(g=x=>t=t*y++/(g[x]=-~g[x]),t=y=1)|t
```
[Try it online!](https://tio.run/##dcs7DsIwEEXRnlWgVDZJjKjRZCNRivH4Q5Cxo3iEEgmxdQO9qV5x3r3jEzOt88J9TMYWBwVhGJVSOKkHLsLDBgMDn/a2PQs/bhP079/IjmGHi3xxuVKKOQWrQvLCiQYRjfVOa01EjZSHyuE/3mwIqVppMtZV5Zh5naP/WvkA "JavaScript (Node.js) – Try It Online")
```
a=>
[...a].map( // Loop over the characters
g=x=>
t=t* // using t*= instead may result in rounding error
y++ // (Length of string)!
/(g[x]=-~g[x]) // divided by product of (Count of character)!
,t=y=1 // Initialization
)
|t
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 [bytes](https://github.com/abrudz/SBCS)
```
!∘⍴÷⊂×.(!∘⍴∩)∪
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X/FRx4xHvVsOb3/U1XR4up4GlP@oY6Xmo45V/9MetU141Ntn9Kir@VHf1OAgZyAZ4uEZ/D9NQT0xMTEpKSk5OVmdC8jLSM3JyQezHJ2cXVzdwMxEheKSosy8dHUA "APL (Dyalog Unicode) – Try It Online")
Returns the result as a singleton.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~5~~ 3 bytes
*-2 bytes thanks to @Shaggy*
```
á l
```
[Try it online!](https://tio.run/##y0osKPn///BChZz//5UyUnNy8pX@AwA "Japt – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~15~~, 14 bytes
```
[:#@=i.@!@#A.]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62UHWwz9RwUHZQd9WL/a3KlJmfkK6QpqGek5uTkq/8HAA "J – Try It Online")
*-1 byte thanks to FrownyFrog*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
Œ!QL
```
[Try it online!](https://tio.run/##y0rNyan8///oJMVAn////2cAufkA "Jelly – Try It Online")
Simply does what was asked: find permutations of input, uniquify and print the length.
[Answer]
# [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 59 bytes
```
f=s=>s==""?1:s.Length*f(s.Substring(1))/s.Count(c=>c==s[0])
```
Port of [*@ArBo*'s Python 2 answer](https://codegolf.stackexchange.com/a/187003/52210).
[Try it online.](https://tio.run/##JY2xDsIgFAD3fgV5E1hFuxapg4lTtw4O6gBIW5KGGt6ri/HbsYnLTZc7hzuHIV@W6I5IKcRhy0KkhuVeo25Qa4BTVaNsfRxo3PQcZbfYv8orIfYoz/MSiTvdOK3xdniIrIp@Tt64kb9NYrgWGYx@mmZFHkkZY91zpbHWKmNBdq8pEAcFQnwKxq4pkG9D9BxLqO8E5boVQhXf/AM)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
pᶜ¹
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv@DhtjmHdv7/H62UkZqTk6@ko5QIAiA6KTklVSkWAA "Brachylog – Try It Online")
```
The output is
ᶜ¹ the number of unique
p permutations of
the input.
```
`pᵘl` does pretty much exactly the same thing.
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
lambda s:len(set(permutations(s)))
from itertools import*
```
[Try it online!](https://tio.run/##BcExDoAgDADA3VcQptbR0cSfuBSF2AQoaevg6/FufP5I32Y5zlmppZuC7TV3sOwwsrbXyVm6gSHiUlRaYM/qItUCtyHq6xzK3aFAJEpXRJw/ "Python 2 – Try It Online")
Self-documenting: Return the length of the set of unique permutations of the input string.
# [Python 3](https://docs.python.org/3/), 55 bytes
Credit goes to [ArBo](https://codegolf.stackexchange.com/users/82577/arbo) on this one:
```
lambda s:len({*permutations(s)})
from itertools import*
```
[Try it online!](https://tio.run/##BcExDoAgDADA3VcQp5bVzcSfuBSFSAKUlDoY49vrXX/04rZY2nYrVMNJbqwlNnh9j1JvJc3cBgz8cErC1WWNosxluFw7i3rrkptCgpkoHDOi/Q "Python 3 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 24 bytes
```
⎕CY'dfns'
{≢∪↓⍵[pmat≢⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVOdI9ZS0vGJ1rupHnYsedax61Db5Ue/W6ILcxBKQQO/W2Nr/aY/aJjzq7QOq9vR/1NV8aL3xo7aJQF5wkDOQDPHwDP6fpqCemJiYlJSUnJyszgXkZaTm5OSDWGYQtY4Kj3rnKqRlFhWXKJgp5KSWlKQWFSvkpymUZKQqJOYUZCQmpZaANCYqFJcUZealqwMA "APL (Dyalog Unicode) – Try It Online")
Simple Dfn, takes a string as argument.
### How:
```
⎕CY'dfns' ⍝ Copies the 'dfns' namespace.
{≢∪↓⍵[pmat≢⍵]} ⍝ Main function
≢⍵ ⍝ Number of elements in the argument (⍵)
pmat ⍝ Permutation Matrix of the range [1..≢⍵]
⍵[ ] ⍝ Index the argument with that matrix, which generates all permutations of ⍵
↓ ⍝ Convert the matrix into a vector of strings
∪ ⍝ Keep only the unique elements
≢ ⍝ Tally the number of elements
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
```
f=->s{s.chars.permutation.to_a.uniq.size}
```
[Try it online!](https://tio.run/##ZcgxDoAgDADA3VcYJh3sD3T2F6YlGEmAKoUYNb4dZ/XGi5mOUua@G@QS0AtGgdVEnxMmywESTwg52A3EnuYua05Sz6DRuUYtxjlWbfVKRNL/QyL67sh77b/p2Zqg2vIA "Ruby – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 43 bytes
Uses the method in @ArBo's Python answer.
```
sub c{!@_||@_*c(@_[1..$#_])/grep/$_[0]/,@_}
```
[Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhuVrRIb6mxiFeK1nDIT7aUE9PRTk@VlM/vSi1QF8lPtogVl/HIb72f3FipUKyhr6efrqmQlp@kYKN3f@M1JycfK5EEOBKTEpOSf2XX1CSmZ9X/F/X11TPwNAAAA "Perl 5 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 33 30 chars (34 31 bytes)
Fairly straight forward `Whatever` block. `comb` splits the string into letters, `permutations` gets all possible combinations. Because of the way coercion to `Set` need be `join`ed first ( `»` applies `join` to each element in the list).
```
+*.comb.permutations».join.Set
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX1tLLzk/N0mvILUot7QksSQzP6/40G69rPzMPL3g1JL/1lxcxYkgxRpKGak5OflKmtZwgUQQQBFISk5JBQr8BwA "Perl 6 – Try It Online")
(previous answer used `.unique` but `Set`s guarantee uniqueness, and numerify the same, so it saves 3).
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 12 bytes
**Solution:**
```
#?x@prm@!#x:
```
[Try it online!](https://tio.run/##y9bNz/7/X9m@wqGgKNdBUbnCSikjNScnX@n/fwA "K (oK) – Try It Online")
**Explanation:**
Uses the oK built-in `prm`:
```
{[x]{[x]$[x;,/x ,''o'x ^/:x;,x]}@$[-8>@x;!x;x]}
```
... which, due to `x^/:x` basically generates the permutations of `"helo"` not `"hello"`, hence we need to generate the permutations of `0 1 2 3 4`, use them to index into `"hello"` and then take the count of the unique.
```
#?x@prm@!#x: / the solution
x: / store input as x
# / count (#) length
! / range (!) 0..n
prm@ / apply (@) to function prm
x@ / apply permutations to input x
? / take the distinct (?)
# / count (#)
```
[Answer]
# Java 8, ~~103~~ 102 bytes
```
s->{int r=1,i=s.length();for(;i>0;)r=r*i/~-s.substring(--i).split(s.charAt(i)+"",-1).length;return r;}
```
Port of [*@ArBo*'s Python 2 answer](https://codegolf.stackexchange.com/a/187003/52210).
-1 byte thanks to *@OlivierGrégoire* by making it iterative instead of recursive.
[Try it online.](https://tio.run/##ZZCxTsMwEIb3PsUpk00aQ1fcRGJBYmDqCAx26jQXXCeyz5Wqqrx6SFNLQFlOvu@Xfn3nTh1U0W0/x9qqEOBVoTstAAIpwhq6KRWR0Iomupqwd@I5PdYb8uh2S3hxZHbGV9CUYyiqEzoCX66WWAZhjdtRy7hses8kVg@S@9Lf4f1XEUSIOswdrCiQizBYJBZE3Sr/RAx5nmXLYsVTifSGonfg5XmUi0lxiNpOisn00OMW9pM9u3q9fYDil0sAyARiWWus7TMuf6HL/EuU0vX2Fimt9S2r/7O0nxc/3zdLzfFVCtANkZLW5hjI7EUfSQxTSNaxOc6zx3fK8kaoYbDHK@Op@jx@Aw)
Actually generating all unique permutations in a Set and getting its size would be **221 bytes**:
```
import java.util.*;s->{Set S=new HashSet();p(s,S,0,s.length()-1);return S.size();}void p(String s,Set S,int l,int r){for(int i=l;i<=r;p(s.replaceAll("(.{"+l+"})(.)(.{"+(i++-l)+"})(.)(.*)","$1$4$3$2$5"),S,l+1,r))S.add(s);}
```
[Try it online.](https://tio.run/##XVE9T8MwEN37K05WBrtJXMLHAKFIbCx0yQgMTuK2Lq4T2ZeiUuW3F8cNFXQ5@71n3b173oidSDf151Ft28YibDzmHSrNpznMZhBn94AN4FpCuUeZVk1ncFJp4Ry8CmUOEwBlUNqlqCQsBhgIqGiBVpkVOJZ7sp/4sgADczi69OlQSIRibuQXvAi39oiyvKUuKZKrxHEtzQrXlKUZy63EzhoouFPf0r/q812jamjP/ZPQKxmG6lAtOywbS4ermutcPc7t0Jtb2Wrv8llrSig/kFjHpGeUswCoiuNUszM1ZSQhURbdRjfRdXRHmPem4yyxjBVc1DX1i/XHfNir7UqtKnAo0B/B3tZnMzp8@wDBTsGgdEjJWmrdkBDLLzXU/4wQZVVfUqIsywtuxCHfvwaCPEakTNvhaKHYO5Rb3nTIWy@iNjTIMXl4RxIPPzL8K2Xc8OoksXFCf/wB)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
jY@XuZy1)
```
[Try it online!](https://tio.run/##y00syfn/PyvSIaI0qtJQ8///jNScnHwA "MATL – Try It Online")
Explanation:
```
j input as string
Y@ get permutations
Xu unique members
Zy size matrix
1) first member of size matrix
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, 35 bytes
```
@(s)size(unique(perms(s),'rows'),1)
```
Anonymous function that takes a character vector and produces a number.
In MATLAB this can be shortened to `size(unique(perms(s),'ro'),1)` (33 bytes).
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo1izOLMqVaM0L7OwNFWjILUotxgopqNelF9erK6pY6j5P01DPSM1JydfXfM/AA "Octave – Try It Online")
### Explanation
```
@(s) % Anonymous function with input s
perms(s) % Permutations. Gives a char matrix
unique( ,'rows') % Deduplicate rows
size( ,1) % Number of rows
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 73 bytes
```
(.)(?=(.*?\1)*)
/1$#2$*1x1$.'$*
^
1
+`1(?=1*/(1+)x(\1)+$)|/1+x1+$
$#2$*
1
```
[Try it online!](https://tio.run/##Hco7CoAwEAXAfq/hgvuBhGcvuYiIFgGFoCAWKbx7FKeeK9/7sbYmQSWNEixNUFOK4G5gQwWHno1mAvmC78CiwLXKF531ifAKZ/o/obUtl3K@ "Retina 0.8.2 – Try It Online") Uses @ArBo's formula, but evaluates from right-to-left as this can be done in integer arithmetic while still minimising the size of the unary values involved. Explanation:
```
(.)(?=(.*?\1)*)
/1$#2$*1x1$.'$*
```
For each character, count how many remaining duplicates there are and how many further characters there are, add one to each to take the current character into account, and separate the values so we know which ones are to be divided and which are to be multiplied.
```
^
1
```
Prefix a 1 to produce a complete expression.
```
+`1(?=1*/(1+)x(\1)+$)|/1+x1+$
$#2$*
```
Repeatedly multiply the last and third last numbers while dividing by the second last number. This replaces the last three numbers.
```
1
```
Convert to decimal.
[Answer]
# K, 27 bytes
```
*/[1+!#:x]%*/{*/1+!x}'#:'x:
```
# K, 16 bytes - not a real answer
```
#?(999999#0N)?\:
```
Take 999999 random permutations of the input string, take the unique set of them and count the length.
Most of the time it will give the right answer, for shortish strings.
Improved thanks to @Sriotchilism O'Zaic, @Selcuk
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes
```
Characters/*Permutations/*Length
```
[Try it online!](https://tio.run/##JYk5CsAgEAC/IpYS8AUBIW0Kv7Br1ih4gG6qkLebq5oZJgMHysDRwfBiHkuABo6pda0stXzw82p5aqWycxi2xcJGeaGNOGWglKqchGTq/BIA3fYLIOJnKK9xAw "Wolfram Language (Mathematica) – Try It Online")
Explanation: Right-composition with [`/*`](https://reference.wolfram.com/language/ref/RightComposition.html) applies these three operators one after the other to the function argument, from left to right:
* [`Characters`](https://reference.wolfram.com/language/ref/Characters.html) converts the input string to a list of characters.
* [`Permutations`](https://reference.wolfram.com/language/ref/Permutations.html) makes a list of all unique permutations of this character list.
* [`Length`](https://reference.wolfram.com/language/ref/Length.html) returns the length of this list of unique permutations.
This method is very wasteful for long strings: the unique permutations are actually listed and counted, instead of using a [`Multinomial`](https://reference.wolfram.com/language/ref/Multinomial.html) to compute their number without listing.
[Answer]
# [F# (Mono)](http://www.mono-project.com/), 105 bytes
```
let rec f s=if s=""then 1 else s.Length*(f(s.Substring 1))/(s|>Seq.sumBy(fun c->if c=s.[0]then 1 else 0))
```
[Try it online!](https://tio.run/##TY4xC4MwEIV3f8UjICQFU11bDLSzm6M4VHupgsbWi0PB/26jU294HI933zvLyTi5adsG8piphQXn/S5C@I4cMtDABNYFuZfvTtJK1uXSsJ9790Km1Fnyakr6aF7G@1faxaFNTGC0Oesqrf8xqVJHU7hm5KggOhqGSVwhHvscS9M@SaCOjtBqUPTsde9pxgFnJAbv0O6tg4j5gvgmgivD10pF0fYD "F# (Mono) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~5~~ 4 bytes
```
l{.p
```
[Try it online!](http://pythtemp.herokuapp.com/?code=l%7B.p&input=%22hello%22&debug=0)
This assumes the input is a python string literal. If input must be raw text, this 5-byte version will work:
```
l{.pz
```
Either way, it just computes all permutations of the input as a list, deduplicates it and gets the number of elements in it, and implicitly prints that number.
*-1 byte thanks to @hakr14*
[Answer]
# [J](http://jsoftware.com/), ~~14~~13 bytes
```
#(%*/)&:!#/.~
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/lTVUtfQ11awUlfX16v5rcqUmZ@QrpCmoZ6Tm5OSrw7mJIIDETUpOSVX/DwA)
*1 byte thanks to miles*
```
# length
#/.~ counts of each unique character
(%*/) divide left by the product of right
&:! after applying ! to both
```
[Answer]
# [PHP](https://php.net/), 77 bytes
```
function f($s){return!$s?:strlen($s)*f(substr($s,1))/substr_count($s,$s[0]);}
```
[Try it online!](https://tio.run/##TY6xasMwFEV3fcVtEMgqgjgdOsR1TYaUFgIxZExDcFQJFYxkJLlLyLc7Ut2hb3rncB/vDmaYXprBDITQqEIMqHEkADOq7x1D/YrnUmTR5fkVq5kv8kvN/FSSUzXp0cr47Sx0QQO/ehVHbx9oaNYh@l7ZbB91EcZL4gRixflyprN0o43Z0XAsT7y6Tdp51UmDAn@9upC2/I56cFxTBSWNS05g8RkXAvQnddc5D/7f1fmiAWs3hwPDGuxt87FjAu17e97udxW5TXc "PHP – Try It Online")
This is basically just a PHP port of [@ArBo's winning Python answer](https://codegolf.stackexchange.com/questions/186996/count-all-possible-unique-combinations-of-letters-in-a-word/187003#187003) which is ridiculously more clever than the recursive answer I originally had. Bravo!
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 4 bytes
```
ψD∩l
```
[Try it online!](https://tio.run/##y8/INfr//3yHy6OOlTn//2ek5uTkAwA "Ohm v2 – Try It Online")
**Explanation**
```
l output the lenght of
∩ the set intersection between
ψD two copies of all possible permutation of input
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 3 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
═1╪
```
[Run and debug it](https://staxlang.xyz/#p=cd31d8&i=hello%0Aaaaaa%0Aabcde&a=1&m=2)
] |
[Question]
[
I have a string like this:
```
s = "helloworldandhellocodegolf"
```
I want to make every [consonant](https://en.wikipedia.org/wiki/Consonant) after a [vowel](https://en.wikipedia.org/wiki/Vowel) uppercase.
Desired output:
```
heLloWoRldaNdheLloCoDeGoLf
```
As you can see, `l` gets uppercased because it's right after the vowel `e` etc..
If there are repeated vowels, like:
```
s = "aabeekad"
```
Desired output:
```
s = "aaBeeKaD"
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
The consonants are all alphabet characters except for `aeiou`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 47 bytes
Expects and returns a string.
```
s=>Buffer(s).map(c=>c^s&~(s=68174912>>c)&32)+''
```
[Try it online!](https://tio.run/##XYy7DsIwDAB3PqNDmwhRqQXxGJKBD0EyjlOgJq5iHhu/HipGxtOd7gYvUMzX6bFKEqhEV9T54zNGykZte4fJoPN40vpj1G333W5z6Hrv0dbr3i6bpqAkFaaWZTDRVBdilrdkDpDCD3AeD8KxsnbxFwOciUYIsypf "JavaScript (Node.js) – Try It Online")
### How?
The constant \$68174912\$ (which I've already used [here](https://codegolf.stackexchange.com/a/201521/58563)) is a bitmask describing the positions of the vowels:
```
00000100000100000100010001000000
v v v v v
zyxwvutsrqponmlkjihgfedcba`_^]\[
```
### Commented
```
s => // s = input string
Buffer(s) // turn it into a buffer
.map(c => // for each ASCII code c:
c ^ // toggle the case if
s & // the previous letter was a vowel
~( // and the current letter is a consonant
s = // save in s the new state obtained by
68174912 // right-shifting the bit-mask
>> c // by c positions (mod 32)
) & 32 // isolate the case bit
) + '' // end of map(), coerce back to a string
```
---
# JavaScript (ES6), 38 bytes
Expects and returns an array of ASCII codes.
```
a=>a.map(p=c=>c^p&~(p=68174912>>c)&32)
```
[Try it online!](https://tio.run/##lY07DsIwEAV7jpEi8haslID4FHbBFSgRSIs/IeB4LcdAx9VNRIVERfdminlXetCoUx/zPLCxxclCUhEOFEWUWip9ivVrmqtNs15um1YpDfWihaI5jOwteu7E7u6cTegSD8KJAyJ@m@pivecnJ28omA/o6atj7yo4AmDmfU596ATA7I8s0dnaG5mfSHkD "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 61 bytes
A full program that takes input from STDIN, and outputs to STDOUT.
```
c;main(d){for(;read(0,&c,1);)putchar(c^d-(d='Xz'%c>0)&32);}
```
[Try it online!](https://tio.run/##HcfBCoMwDADQo/6ImoAFncei37GTEJKqg9hIUQaTfXsHe7fHjpXimjP7nV4RBO/FEvgUSKBra2579HhcJ2@UgGdxIGPz/JRFU/HUYT080H9z3oKqvS2pUJR/2CSspssP "C (clang) – Try It Online")
I use the same formula to check for vowels as in [this](https://codegolf.stackexchange.com/a/240487/88546) other task. Here, `(d='Xz'%c>0)` sets `d` equal to \$ 0 \$ if the current letter `c` is a vowel, and \$ 1 \$ otherwise. `c` should be uppercased if and only if the current `d` is \$ 1 \$, and the previous `d` is \$ 0 \$. To apply the uppercasing, `c` is XOR'ed with \$ 32 \$, but only when the conditions are met. Below is a table to visualize what is happening:
```
| prev_d | d | prev_d - d | & 32 | ^ c |
-+--------+---+------------+------+------+-
| 0 | 0 | 0 | 0 | c |
| 0 | 1 | -1 | 32 | 32^c |
| 1 | 0 | 1 | 0 | c |
| 1 | 1 | 0 | 0 | c |
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 56 bytes
```
x=>x.replace(/(?<=[aeiou])[^aeiou]/g,x=>x.toUpperCase())
```
[Try it online!](https://tio.run/##XY1BDsIwDATvfKS2BO0HCBx4A6cKJDdxQsGKo6TQ/j5U5cZtRzPSPulDxeYxTYeojqs3dTGnpc2chCxDB@ej6YlHfd@wv/9GF/ZbNOk1Jc4XKgyI1WosKtyKBvDQPFhEZ83iKLoN7PoQVHyDuPuLiQbmF7lV1S8 "JavaScript (Node.js) – Try It Online")
# [Perl 5](https://www.perl.org/) `-p`, ~~30~~ ~~27~~ 26 bytes
```
s/[aeiou]\K[^aeiou]/\U$&/g
```
[Try it online!](https://tio.run/##K0gtyjH9/79YPzoxNTO/NDbGOzoOwtKPCVVR00///z8jNScnvzy/KCclMS8FzEnOT0lNz89J40pMTEpNzU5M@ZdfUJKZn1f8X7cAAA "Perl 5 – Try It Online")
-3 bytes thanks to Sisyphus
-1 byte thanks to Jo King
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
\zp⁽AḊ⁽ǐẆṅḢ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiXFx6cOKBvUHhuIrigb3HkOG6huG5heG4oiIsIiIsImhlbGxvd29ybGRhbmRoZWxsb2NvZGVnb2xmXG5hYWJlZWthZCJd)
This is a terrible way to do it but it works.
```
\zp⁽AḊ⁽ǐẆṅḢ
\zp # Prepend "z" so that there is a leading consonant
⁽AḊ # Adjacent-group by is-vowel
⁽ǐẆ # Title-case every second item, starting on the first item
ṅḢ # Join by nothing and remove the leading "z"
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
`° ß`$‡ǐNøṙ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgwrAgw59gJOKAoceQTsO44bmZIiwiIiwiaGVsbG93b3JsZGFuZGhlbGxvY29kZWdvbGYiXQ==)
An alternate 11 byter that uses regex
See [this golfing tip of mine](https://codegolf.stackexchange.com/a/238374/78850) that explains why the string `"° ß"` is `"[aeiou] [bcdfghjklmnpqrstvwxyz]"`
## Explained
```
`° ß`$‡ǐNøṙ
`° ß` # The string `[aeiou] [bcdfghjklmnpqrstvwxyz]`
$ # Make the stack input, ^
‡ǐN # Push a function that title cases a string and then swapscase.
# This is because regex matches will be vowel-consonant, and title case makes the vowel uppercase, consonant lowercase, swapcase inverts that for the desired result
øṙ # Apply that function to regex matches in the input
```
[Answer]
# [R](https://www.r-project.org), 48 bytes
```
\(s)gsub("(?<=[aeiou])([^aeiou])","\\U\\1",s,,T)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3DWI0ijXTi0uTNJQ07G1soxNTM_NLYzU1ouOgLCUdpZiY0JgYQyWdYh2dEE2oPt00DaWM1Jyc_PL8opyUxLwUMCc5PyU1PT8nTUmTCyifmJiUmpqdmKIE1bRgAYQGAA)
[Answer]
# [Go](https://go.dev), ~~170~~ 164 bytes
```
import(."regexp";."strings")
func f(s string)string{return MustCompile(`[aeiou][^aeiou]`).ReplaceAllStringFunc(s,func(x string)string{return x[:1]+ToUpper(x[1:])})}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY_NSsQwFIX3fYqQ1Q1qYXYyrkRwJ4o_q1KZ2N7EMGluyA8WhnkSN0X0IXwU38ZpMwsXrg73cM_HOe8fmqZvL7ut1MgGaVxlBk8h1VwNiX_lpM7Ofz6LBzUPqHH0_KLmMQXjdOSiUtl1TEFkxRJFdgFTDo7d5JiuaPDGImwaiYZy2zwX3Yj6Hr2VHV5a-7DErg8wiKczE8b_iWOzXrUnj_TkPQYYm9W6FXuxP3a9XerMS0CwXXV3SCbrQAF_RWvpjYLtpeuXo6MeNVnFhfj7KOUL4lb2s33ETlPRXw)
No `(?<=)`, non-capturing groups only work with `Find(All)String(Submatch)` which leads to a longer solution, so this mess is what I've had to come with.
* -6 bytes for simplifying the regex.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~78~~ ~~66~~ 65 bytes
```
d=0
for c in input():print(end=[c,c.upper()][d>(d:=c in"aeiou")])
```
Complete program. Thanks to @Neil and @Steffan for making this more concise. [Try it online!](https://tio.run/##Hco9CoAwDEDh3VOIUwsigosI9SLiIE3UQklCaBFPX3/gLR88udPJNIyipYDrq5219nWgN8nJ2Ek0UDJI4Bbf@i6LoBq7LjAbmNy3NhsGzo1dbSknxsgXa4SN4IdnwIPj/gA "Python 3.8 (pre-release) – Try It Online")
## [Python 3](https://docs.python.org/3/), 73 bytes (@Steffan)
```
lambda x:re.sub("(?<=[aeiou])[^aeiou]",lambda a:a[0].upper(),x)
import re
```
Function solution. [Try it online!](https://tio.run/##LcpBCsIwEEDRvaco3TSBUgR3xeJBYoWpmdjANDOMCdbTR1B3/8GXd145nWqYrpVgWzw0@6g4PMtiWnM5Tw4wcpmtu/2i7f8bjOCO81BEUI3td3uIm7DmRrGKxpRNMN2KRPxiJQ/Jf3Fnjw@m0FlbPw "Python 3 – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~21~~ 16 bytes
```
aRXV.XC;@_.UC_@1
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhUlhWLlhDO0BfLlVDX0AxIiwiIiwiaGVsbG93b29vcmxkYW5kaGVsbG9jb2RlZ29sZiIsIi1wIl0=)
-5 bytes thanks to @DLosc
Regex solution, ported from [@Steffan's regex](https://codegolf.stackexchange.com/a/255609/110555), with some pip builtin regex patterns used to save bytes
# [Pip](https://github.com/dloscutoff/pip), ~~21~~ 17 bytes
```
{Iy>YaNVWUC:aa}Ma
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJ7SXk+WWFOVldVQzphYX1NYSIsIiIsImhlbGxvd29vb3JsZGFuZGhlbGxvY29kZWdvbGYiLCIiXQ==)
-4 bytes thanks to @DLosc
Non-regex alternative
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 30 bytes
```
"aeiou"0>ir[sp<l~!' **lf-ol~>]
```
[Try it online!](https://tio.run/##y6n8/18pMTUzv1TJwC6zKLq4wCanTlFdQUsrJ003P6fOLvb//@TE3PzStJzE9NSk/NK8lMSizNRiAA "Ly – Try It Online")
This isn't even close to the smallest, but the way it works is probably very different from other languages, so I thought it was worth posting.
It uses two stacks, one with a list of vowels, and one with the STDIN string. Each character on the STDIN stack is copied to the vowel stack and the code search to see if there's a match. That "am I a vowel" result is combined with a "was the last char as vowel" result that lives on the stack to decide whether or not to capitalize the current character before printing it.
```
"aeiou" - push "is a vowel" comparison data on stack
0 - push "0" as "was last char a vowel" starter val
>i - switch to new stack, read STDIN onto it
r - reverse stack
[ ] - for each input char/codepoint
sp<l - stash the char, delete, switch stacks and restore
~! - search for the char in "aeiou", negate result
' - push " " (32), the "capitalize" codepoint offset
* - multiple to clear if not this IS a vowel
* - multiple against "was previous char vowel?" result
l - reload the current char/codepoint
f- - flip stack and subtract to capitalize if needed
o - output current char
l~ - reload char, search against vowels
> - switch back to the STDIN stack
```
[Answer]
# Vim, 23 keystrokes
```
:s/[aeiou]\+\zs./\u&/g<cr>
:s/ # Search and replace...
[aeiou]\+ # A string of one or more vowels
\zs # (start the match here)
. # Any character
# (because of greedy matching, this will always be the first consonant)
/ # Replace with
\u # Make uppercase
& # The matched string (after \zs)
/g<cr> # Replace all occurrences
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 25 bytes
```
T`aeioul`aeiouL`[aeiou]+.
```
[Try it online!](https://tio.run/##K0otycxL/P8/JCExNTO/NAdC@SREg@lYbb3//zNSc3Lyy/OLclIS81LAnOT8lNT0/Jw0rsTEpNTU7MQUAA "Retina 0.8.2 – Try It Online") Explanation: Transliterates vowels to themselves and other lowercase letters to uppercase letters, but only the letter after a run of vowels. (This is so that a double vowel doesn't confuse the transliteration.)
Alternative, also 25 bytes:
```
rT`aeioul`aeiouL`[aeiou].
```
[Try it online!](https://tio.run/##K0otycxL/P@/KCQhMTUzvzQHQvkkRIPpWL3//zNSc3Lyy/OLclIS81LAnOT8lNT0/Jw0rsTEpNTU7MQUAA "Retina 0.8.2 – Try It Online") Explanation: The `r` makes it match the pattern from right to left solving the double vowel problem.
Both programs work in Retina 1 but 8 bytes can be saved because the `aeiou` can be replaced by `v` in the transliteration patterns.
[Answer]
# [Dart (v2.18.4)](https://dartpad.dev/?id=b36328ec7279f5a14f1251485c40aa30), ~~149~~ 80 bytes
```
f(s,[d=0])=>String.fromCharCodes([for(s in s.runes)s^d&~(d=68174912>>s%32)&32]);
```
* [Try it online](https://tio.run/##XY/LagJBEEX3@YreRLtBJI4hD2Rm4ydkKQYqXdVa2A@p6saFJL8@mbgK7u69HA5cBKnjGKwudtg/7V0/fFThfFgGKWl7BNkWJLW7UMSq4Wx0KS2TOv3E2Y/F/uVt9fr8vuqGQR/XnZutu73bjAk4W2euD8acJ121wc6PFGO5FIkIGW/FT@5DiWHu3OY/CfBFdAK832MRSnzWlrBMWblConpPZUjQfC0CuRJFSpRrSyC@RfCcGcBTY01/xyrDNLPeHN/jLw).
* [Full source](https://github.com/alexrintt/algorithms/tree/master/codegolf/make-every-consonant-after-a-vowel-uppercase/dart-2.18).
Extra test-cases:
| Input | Output |
| --- | --- |
| loremipsumdolorsitamet | loReMiPsuMdoLoRsiTaMeT |
| namauctoranteelementumarculaciniaaceuismodestiaculis | naMauCtoRaNteeLeMeNtuMaRcuLaCiNiaaCeuiSmoDeStiaCuLiS |
---
*Thanks to [@steffan](https://codegolf.stackexchange.com/users/92689/steffan) who cut down to 80 bytes (!) by porting [@arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) answer.*
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
r"%v%c"ÈÎ+XÌu
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIldiVjIsjOK1jMdQ&input=ImhlbGxvd29ybGRhbmRoZWxsb2NvZGVnb2xmIg)
```
r"%v%c"ÈÎ+XÌu :Implicit input of string
r :Replace
"%v%c" :RegEx /[aeiou][b-df-hj-np-tv-z]/gi
È :Pass each match through the following function as X
Î : First character
+ : Append
XÌ : Last character
u : Uppercased
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 48 bytes
```
d;f(*s){for(d=1;*s;)*s++^=d-(d='Xz'%*s>0)&32;}
```
[Try it online!](https://tio.run/##LYtbCsIwFEQ/tVlFCNQmqQUfnyGuwAUIohDyqIWYSG5AsHTtsUrnb86c0Z32KvSlGOEoBza6mKiRe8FBMA5te5emm0Fz@axXTc3htGOb40FM5amGQBkaUTWEjLOFfL1hic/kYb2P75i8UcH8i47G9tE7IlDl6E9lAuElrzT/HSW1B7LFyziVLw "C (clang) – Try It Online")
[dingledooper's answer](https://codegolf.stackexchange.com/a/255612/41374) as a function.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
⭆θ⎇№⌕A⭆θ№aeiouλ10⊖κ↥ιι
```
[Try it online!](https://tio.run/##VYoxCkIxEAWvElJlIYLWVqLYCYJ6gCVZ/w@u2bjmK54@Rq2shnnzwogaBLm1vaZc3aF2DDss7ubNkTSjvtxapp62KccV8//llyxSksl6wwDe2MXcdmwoKF0pV4ru8tlPpZAGvJNL3RIALFsbiVmeohwxx68EiTQIn9vswW8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Maps each letter to its vowel-ness as a binary flag, then searches for the substring `10` in the result, the second character of which is where the consonants that needs to be uppercased are.
```
θ Input string
⭆ Map over letters and join
№ Count of
κ Current index
⊖ Decremented
θ In input string
⭆ Map over letters and join
№ Count of
λ Inner letter in
aeiou Literal string `aeiou`
⌕A Find all matches of
10 Literal string `10`
⎇ If found then
ι Current consonant
↥ Uppercased
ι Else current letter
Implicitly print
```
[Answer]
# [sed](https://www.gnu.org/software/sed/), 25 bytes
```
s/[aeiou][^aeiou]/\U\l&/g
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlwYKlpSVpuhY7i_WjE1Mz80tjo-MgtH5MaEyOmn46RB6qbMFN5YzUnJz88vyinJTEvBQwJzk_JTU9PyeNKzExKTU1OzEFohYA)
It makes the whole match uppercase and then it turns first letter to lowercase. This is 5 bytes shorter than `s/([aeiou])([^aeiou])/\1\u\2/g` solution and it also doesn't require `-E` flag.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'zì.γžMså}2Å€™}J¦
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fverwGr1zm4/u8y0@vLTW6HDro6Y1j1oW1XodWvb/f0ZqTk5@eX5RTkpiXgqYk5yfkpqen5MGAA "05AB1E – Try It Online")
* -4 thanks to Kevin Cruijssen
Port of [Steffan's Vyxal answer](https://codegolf.stackexchange.com/a/255607/114446)
```
'zì.γžMså}2Å€™}J¦ # Implicit input TOP OF THE STACK:
'zì # Prepend a 'z' "zhelloworldandhellocodegolf"
.γ } # Group by
žM # The string of vowels 'aeiou'
så # Contains the letter ["zh", "e", "ll", "o", "w", "o", "rld", "a", "ndh", "e", "ll", "o", "c", "o", "d", "e", "g", "o", "lf"]
2Å€ } # Every second item:
™ # Convert to title case ["Zh", "e", "Ll", "o", "W", "o", "Rld", "a", "Ndh", "e", "Ll", "o", "C", "o", "D", "e", "G", "o", "Lf"]
J # Join everything 'ZheLloWoRldaNdheLloCoDeGoLf'
¦ # And remove the leading 'z' 'heLloWoRldaNdheLloCoDeGoLf'
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 23 bytes
```
(?<=[aeiou])[^aeiou]
$u
```
[Try it online!](https://tio.run/##K0otycxLNPz/X8PexjY6MTUzvzRWMzoOwuBSKf3/PzExKTU1OzEFAA "Retina – Try It Online")
`$u` is replace with uppercase.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œue€ØḄ<ƝŻTƲ¦
```
A monadic Link that accepts a list of lowercase characters and yields a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8///opNLUR01rDs94uKPF5tjco7tDjm06tOz///9JSYlJiUCUBCJBBBgkJQEA "Jelly – Try It Online")**
### How?
```
Œue€ØḄ<ƝŻTƲ¦ - Link: list of lowercase characters, S
¦ - sparse application (to S)...
Ʋ - ...to indices: last four links as a monad - f(S):
ØḄ - lowercase consonants
€ - for each (character in S):
e - exists in? -> 1 if a consonant else 0
Ɲ - for neighbours:
< - less than? -> 1 if [0,1] else 0
Ż - prepend a zero
T - truthy indices -> indices of consonants directly after a vowel
Œu - ...action: convert to uppercase
```
[Answer]
# [Factor](https://factorcode.org/), 51 bytes
```
[ R/ [aeiou][^aeiou]/ [ "\0 "v- ] re-replace-with ]
```
[Try it online!](https://tio.run/##JY69DoJAGAR7nmJjD1rrAxgbC40VYvJxt/zEgzuOAzTGZ0fUarKzzRSigvXz5Xw47rfwLPlwaCRUycjv08N5hvB0vm4DenYDW8Ue3YRdFHXTCxWNsZP1Rkurf0NZzdKaAiI5eRcNyZUmAqVZnFJ4zylOa6TC2g5ZevtzEVhdN1iNMbKlJfZ0RhTjqQ4VsrkRh2T@AA "Factor – Try It Online")
[Answer]
# [Zsh](https://zsh.sourceforge.io/) `--extendedglob`, 52 bytes
```
<<<${1//(#m)[aeiou][^aeiou]/$MATCH[1]${(U)MATCH[2]}}
```
[Try it Online!](https://tio.run/##JYyxDoIwFEV3v4JEhnYiOLMYFxc3nQgmj/YBjW0foa/RSPj22sh0z70nud8wpUFIEZBp5gI/jF6jHi31qWmacq2rShydbAENxa597lmVt/P9cm3rrlzFQ@7l1G1bkoehmNBaetNiNXj9L4o0jmSHLAF6xBfojJYWdGYO0WnKHAyDQ87Cg4OomBbwjGjRoefoYFHRgjLeACiMJrj8GthAnk1IPw) ~~[69 bytes](https://tio.run/##LYy9CsIwFIV3n6Jgh3Yq7l2KCAqKi52Kwm1yW4NJbmluUCx59hpap/PzHc7XPecuyzOHTAMn@GG0EmWvqZ3LskyndNoVRbY1eQOoyN@bx6pFOmV1fqlu@2MI/0V1OF3rhZxXUoQw55sueaLW9KZRS7ByCYIk9qS7CAFaxBfIaDWNaNTgvJEUvVMMBjkCCwa8YBrBMqJGg5a9gVF4DUJZBSDQK2fiq2MFsVZu/gE)~~
Hat-tips: [one](https://codegolf.stackexchange.com/a/254319/15940) [two](https://codegolf.stackexchange.com/a/248255/15940)
[Answer]
# [Python 3](https://docs.python.org/3/), 90 bytes
```
lambda x:"".join(b.upper()if a in"aeiou"and b not in"aeiou"else b for a,b in zip(" "+x,x))
```
Would be 71 bytes if didn't have to deal with repetitive vowels, still got 90 bytes though. [Try it online!](https://tio.run/##RcwxDsIwDIXhnVNYXpqIqgsbEjdhcRqHBkwchVQULh8iBhjfp6c/v@qi6dDC6dyE7s4TbEfE6aoxGTetOXMxNgYgiAmJo65IyYODpPVPLA/uFrQAja47vGM2CLjfxs3alktM1QQzLCyiTy3ie@U7ZvV8UQmDtbvfjcgx38h3bB8 "Python 3 – Try It Online")
[Answer]
# [Raku](https://raku.org/), 26 bytes
```
{S:g[<[aeiou]>+<(.]=$/.uc}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OtgqPdomOjE1M7801k7bRkMv1lZFX680ufZ/cWKlgpJKvIKtnUJ1moJKfK2SQlp@kYJ6RmpOTn55flFOSmJeCpiTnJ@Smp6fk6auo6CemJiUmpqdmKL@HwA "Perl 6 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-p`, 36 bytes
```
gsub /(?<=[aeiou])[^aeiou]/,&:upcase
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6BUuyCpaUlaboWN1XSi0uTFPQ17G1soxNTM_NLYzWj4yAMfR01q9KC5MTiVIhaqJYFN5UzUnNy8svzi3JSEvNSwJzk_JTU9PycNK7ExKTU1OzEFIhaAA)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 19 bytes
```
sm?*Z!=Z}d"aeiou"r1
```
[Try it online!](https://tio.run/##K6gsyfj/vzjXXitK0TaqNkUpMTUzv1SpyPD/f6WM1Jyc/PL8opyUxLwUMCc5PyU1PT8nTQkA "Pyth – Try It Online")
### Explanation
```
sm?*Z!=Z}d"aeiou"r1ddQ # implicitly add ddQ to the end
# implicitly assign Q = eval(input())
s # sum of
m Q # map lambda d over Q
? # ternary if (
*Z! # Z and not
=Z}d"aeiou" # assign Z to d being a vowel):
r1d # d capitalized
d # else: d
```
[Answer]
# [Ruby 2.7](https://www.ruby-lang.org/), 110 bytes
```
->(s){v="aeiou";s.chars.map.with_index{v.include?(s[_2-1])&&!v.include?(_1)?(_1.upcase):_1}.join}
```
] |
[Question]
[
>
> **This contest is over.**
>
>
> There are no remaining crackable answer in the cops challenge.
>
>
>
# Companion thread of [Cryptographic hash golf](https://codegolf.stackexchange.com/q/51068)
As a reminder, here are the rules for robbers from the main challenge:
>
> ### Task
>
>
> Crack any of the cops' submissions by posting the following in the
> robbers' thread: two messages **M** and **N** in **I** such that
> **H(M) = H(N)** and **M ≠ N**.
>
>
> ### Scoring
>
>
> Cracking each cop submissions gains you one point. The robber with the most points wins.
>
>
> In the case of a tie, the tied robber that cracked the longest
> submission wins.
>
>
> ### Additional rules
>
>
> * Every cop submission can only be cracked once.
> * If a cop submission relies on implementation-defined or undefined behavior, you only have to find a crack that works (verifiably) on
> your machine.
> * Each crack belongs to a separate answer in the robbers' thread.
> * Posting an invalid cracking attempt bans you from cracking that particular submission for 30 minutes.
> * You may not crack your own submission.
>
>
> ### Example
>
>
>
> >
> > # Python 2.7, 22 bytes by user8675309
> >
> >
> >
> > ```
> > 1
> >
> > ```
> >
> > and
> >
> >
> >
> > ```
> > 18
> >
> > ```
> >
> >
>
>
>
### Leaderboard
1. eBusiness: 3 cracks, 393 bytes
2. Martin Büttner: 3 cracks, 299 bytes
3. jimmy23013: 3 cracks, 161 bytes
4. Sp3000: 3 cracks, 44 bytes
5. tucuxi: 2 cracks, 239 bytes
6. Vi.: 2 cracks, 87 bytes
7. feersum: 1 crack, 216 bytes
8. mathmandan: 1 crack, 139 bytes
9. squeamish ossifrage: 1 crack, 134 bytes
[Answer]
# [Python, 109 bytes by Sp3000](https://codegolf.stackexchange.com/a/51079/8478)
Note that Martin cracked first, so I'm not sure if this deserves points. On the other hand, I did make a preimage attack rather than a simple collision - a much stronger result. This means that you can give it an arbitrary hash value, and it will construct an input that generates that hash value.
```
M = 2**128
# The hash to crack.
def jenkins(n):
h = 42
while n:
h += n & (M - 1)
n >>= 128
h *= 1025
h ^= h >> 6
h %= M
h *= 9
h ^= h >> 11
h *= 32769
return h % M
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def invxorshift(h, s):
r = h >> s
while r:
h ^= r
r >>= s
return h
def moddiv(a, b):
return (a * modinv(b, M)) % M
def jenkins_crack(h):
h = moddiv(h, 32769)
h = invxorshift(h, 11)
h = moddiv(h, 9)
h = invxorshift(h, 6)
h = moddiv(h, 1025)
h -= 42
return h
```
And to show that it works:
```
>>> from crack import *
>>> n = 2**128 + 1337
>>> h = jenkins(n)
>>> n2 = jenkins_crack(h)
>>> h2 = jenkins(n2)
>>> n != n2
True
>>> h == h2
True
```
And to give a particular set of numbers that collide:
```
N: 2**128
M: 43617
```
[Answer]
# [Python, 109 bytes by Sp3000](https://codegolf.stackexchange.com/a/51079/8478)
```
340282366920938463463374607431768211414
```
and
```
113982837842983129870077688367927159293402923522160868689804433865221255200726
```
both yield
```
132946164914354994014709093261515948032
```
The algorithm splits the input into chunks of 128 bits, and repeatedly modifies the hash (seeded to `42`) with each chunk, before doing some extra hashing at the end. To find a collision, our goal is to find two numbers that yield the same result after running the following pseudo code on each chunk:
```
hash += chunk
hash += (hash << 10)
hash ^= (hash >> 6)
hash %= 2**128
```
Since the hash is taken mod 2128 we want to look for numbers that shift all the interesting stuff outside of this bit range. But the hash is seeded to `42` so it has some not-so-significant bits set to begin with:
```
000000000000000000000000 ... 000000000000000000101010
```
My idea was to get rid of those bits when adding the first chunk. So let's try 2128-42:
```
000000000000000000000000 ... 000000000000000000101010 hash = 42
111111111111111111111111 ... 111111111111111111010110 chunk = 2**128 - 42
1000000000000000000000000 ... 000000000000000000000000 hash += chunk
10000000001000000000000000000000000 ... 000000000000000000000000 hash += hash << 10
10000010001000001000000000000000000 ... 000000000000000000000000 hash ^= hash >> 6
000001000000000000000000 ... 000000000000000000000000 hash %= 2**128
```
That's fairly simple so let's try to use that as one of the two numbers. (Indeed, the first number of the collision I used is 2128-42.
Now how do we find another number with the same result? Well after one iteration the hash isn't `42` any more, but `2**122` as we've just shown. Now by adding a second chunk to our input number, we can run another iteration. We can choose the second chunk by the same argument as this one, i.e. we want 2128-2122. Then the intermediate result after `hash += chunk` will be identical and we end up with the same result at the end.
So we can compute the two numbers of the collision:
```
>>> 2**128-42
340282366920938463463374607431768211414L
>>> 2**128-42 + ((2**128-2**122)<<128)
113982837842983129870077688367927159293402923522160868689804433865221255200726L
```
We can easily generate many more collisions like this.
[Answer]
# [Mathematica, 89 bytes by LegionMammal978](https://codegolf.stackexchange.com/a/51080/8478)
```
0
```
and
```
16
```
Both yield `0`.
The principle of this cop is to evolve a "random" binary 1-D cellular automaton from a "random" initial condition for a "random" number of steps, and then interpret the first 128 cells of the result as an integer.
The problem is that the rule is determined simply by `Mod[#^2,256]`, such that any multiple of 16 gives rule `0`, which is the trivial rule where all cells are always zero. If the input is not divisible by 99 then we will evolve at least 1 step, so the output is always zero. So any two multiples that aren't multiples of 99 definitely collide. However, input `0` *also* gives 0 (despite never using the rule), because the initial condition is just the binary representation of the input (which is all zeroes in this case).
As an aside, we can find other collisions that are completely independent of the rule. As noted above, any multiple of 99 means that the cellular automaton isn't evolved at all, so the result is simply the first (most significant) 128 bits of the initial condition... which is itself just the input number. So if we take two multiples that don't differ in the first 128 bits (padded to the right with zeroes), we also get a collision. The simplest example of this is `M = 99`, `N = 99*2 = 198`.
[Answer]
# [J, 39 bytes](https://codegolf.stackexchange.com/a/51083/21487)
The first number is:
```
10000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000
```
That is, `10000000` repeated 64 times. The second number is that plus one, i.e.
```
10000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000001
```
Both yield
```
322124197561777885386414076216564234267
```
## Explanation
Let's start with `x := H 10000000 = 146018215378200688979555343618839610915`, and `y := 2^128`. Rather than finding `a, b` such that `a == b mod y`, we'll look for `a, b` such that `x^a == x^b mod y`, making use of the power towers in the algorithm.
But there must be some `k` such that `x^k == 1 mod y`, since `x, y` are coprime, and for that `k` we must have `a == b mod k`. So we can find the [discrete logarithm](http://en.wikipedia.org/wiki/Discrete_logarithm) of 1 mod `y`, and for the first step we get
```
x ^ (k = 85070591730234615865843651857942052864) == 1 mod 2^128
```
So now we want to find two numbers `a, b` such that `a == b mod k`. To do this, we set `y` to be `k` and try to find `a, b` such that `x^a == x^b mod y` again. Using the same logic, we take the discrete logarithm again and get
```
x ^ (k = 21267647932558653966460912964485513216) == 1 mod 85070591730234615865843651857942052864
```
We repeat this until we get to a small `y`, at which point it is trivial to find two numbers which hash to the same thing modulo `y`. After 63 iterations `y = 4`, at which point basically any two numbers work.
Here's the Mathematica code to generate the discrete log chain:
```
k = 0; x = 146018215378200688979555343618839610915; y = 2^128; While[y > 10, y = MultiplicativeOrder[x, y]; k++; Print[k, " ", y]];
```
This gives the [following output](http://pastebin.com/jhFa2dCF).
[Answer]
## [Pyth, 8 bytes by FryAmTheEggman](https://codegolf.stackexchange.com/a/51074/21487)
```
99999999999999999999999999
```
and
```
99999999999999999999999998
```
Floating point precision isn't big enough for this.
[Answer]
# [CJam, 44 bytes, ~~user~~ jimmy23013](https://codegolf.stackexchange.com/a/51103/21487)
The numbers are too big to post, so here they are on Pastebin: [num 1](http://pastebin.com/raw.php?i=CT25Av3y), [num 2](http://pastebin.com/raw.php?i=uZinA136).
The first number is `600^2 = 360000` ones. The second number is the same, except for the following changes:
```
Positions to change to "2": 605, 1811, 3001, 6603
Positions to change to "4": 1805, 3003, 57348, 208895
Positions to change to "5": 602, 1201, 2405, 3004
Positions to change to "6": 1203, 1802
Positions to change to "7": 12, 609, 5401, 7200
Positions to change to "8": 1, 2, 4, 6, 600, 1200, 1808, 2400, 3600, 4803
```
Both hash to `271088937720654725553339294593617693056`.
## Explanation
Let's take a look at the first half of the code:
```
lW% e# Read input number as string, and reverse
600/ e# Split every 600 digits, forming a 2D array
_z e# Duplicate and zip, swapping rows and columns
{ }% e# For both arrays...
JfbDb e# Find sum of S[i][j]*13^i*19^j, where S are the character values
e# and the indices are from right to left, starting at 0.
GK# e# Take modulo 16^20
... ... e# (Rest of code irrelevant)
```
So if we can find two input numbers so that the sums of `S[i][j]*13^i*19^j` are the same modulo `16^20` for both the initial 600-wide array and the zipped array, then we're done.
To make things a little easier, we'll consider only `600^2 = 360000`-digit input numbers, so that the 600-wide array is just a 600 by 600 square of digits. This makes things easier to visualise, and is valid since `10^360000 ~ 2^(2^20.19) < 2^(2^30)`. To simplify things even further, we'll only consider such input strings whose digit square is symmetric along the main diagonal, so that the original array and the zipped array are the same. This also allows us to ignore the initial string reversal and the right-to-left index numbering, which cancel each other out.
To start us off, we can take the first number to be `360000` ones. To get the second number, we want to modify this by changing some of the digits so that the sums are the same modulo `16^20`, while preserving the digit square's symmetry. We accomplish this by finding a list of triples `(i, j, k)` so that
```
sum of k*(13^i 19^j + 19^i 13^j) == 0 mod 16^20
```
where `1 <= k <= 8` is the amount to increase the digit 1 by (i.e. changing to a digit from 2 to 9 – we could have included 0 but we didn't need it) and `0 <= i < j < 600` are index pairs.
Once we have the `(i, j, k)` triplets, we change the digits at `(i, j)` and `(j, i)` to `1+k` to get the second number. The triplets were found using a greedy backtracking algorithm, and for the second number above the digit square looks like:
```
188181811111711 ...
815112111711111 ...
851611111111111 ...
116114118112111 ...
811115111111111 ...
121451111111111 ...
811111111111111 ...
111111111111111 ...
111811111111111 ...
171111111111111 ...
111111111111111 ...
111211111111111 ...
711111111111111 ...
111111111111111 ...
111111111111111 ...
............... .
............... .
............... .
```
For example, `(i, j, k) = (0, 1, 7)` corresponds to changing the digits `(0, 1)` (position `600*0 + 1 = 1`) and `(1, 0)` (position `600*1 + 0 = 600`) to `1 + 7 = 8`.
---
Here's the backtracker in Python 3, although closer inspection revealed that we were pretty lucky, as no backtracking actually happened:
```
n = 16**20
L = [(k *(pow(13,i,n)*pow(19,j,n) + pow(19,i,n)*pow(13,j,n)) % n, i, j, k)
for i in range(600) for j in range(600) for k in range(1, 9) if i < j]
L.sort(reverse=True)
stack = [(n, 0, [])]
while stack:
k, index, result = stack.pop()
if k == 0:
print(result)
break
if index == len(L):
continue
stack.append((k, index+1, result)) # Don't include triplet
if L[index][0] <= k:
stack.append((k - L[index][0], index+1, result + [L[index][1:]])) # Include
```
For a bonus, [here's](http://ideone.com/UuC6Ur) a not-so-efficient port of the hash in Python 3. It was useless.
[Answer]
# [C, 122 bytes - by: Mr. Llama](https://codegolf.stackexchange.com/a/51224/101)
```
bmaj8PCosFLAJjeHaevvvchnJedmg2iujpePOPivI2x2asw0yKa2eA15xvFJMFe82RGIcdlvxyaAPRuDuJhFjbh78BFsnCufJkarwEyKa0azHxccw5qegpcP9yaO0FKoohanxgiAfK1Lqwba51bKtjacbvdjMmcBkiv8kd62sBd98c4twa98sgj3iPh7nkP4
rlaejTPrua1DhBdg0jrIoDBi8fc1GIJAigivIGaxs1OmfPcctNadK3HErvzPLCeDPD8fkMNPCBcIwuoGfEHegOfk9k9pwktslqaBenaati1uNthMiyk9ndpy7gdIz88iot6A09cbNeIMheyjBvbeegL7aGp7mCb91hCxnvgV5abfImrPfLbrbraAsN6loJgh
```
Both strings hash to `bb66000000000000d698000000000000`
Just like "C, 128 bytes - by: squeamish ossifrage" the higher order bits never influence the lower order bits, this can be exploited.
### Code
Visual C++, uses "[unsafe](https://stackoverflow.com/a/20753468/305545)" string operations
```
#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>
long long x, y;
//Original hash function (not used for cracking).
void h(char inp[]){
long long c;
int index = 0;
int len = strlen(inp);
x = 0;
y = 0;
long long p = 0;
for (c = 9; c ; c = (index<len?inp[index++]:-1) + 1) {
for (++p; c--;) {
x = x*'[3QQ' + p;
y ^= c*x;
y ^= x ^= y;
}
}
printf("%016llx%016llx\n", x, y);
}
//Partial hash, takes a string and a starting point in the stream.
//The byte 0x08 must be prepended to a string in order to produce a full legal hash.
void hp(char inp[],long long p){
long long c;
int index = 0;
int len = strlen(inp);
x = 0;
y = 0;
for (index = 0; index<len; index++) {
c = inp[index] + 1;
for (++p; c--;) {
x = x*'[3QQ' + p;
y ^= c*x;
y ^= x ^= y;
}
}
}
//Reverse partial hash, backtracks the inner state.
void hprev(char inp[], long long p){
long long c;
long long clim;
int index = 0;
int len = strlen(inp);
p += len + 1;
x = 0;
y = 0;
for (index = len-1; index>=0; index--) {
clim = inp[index] + 1;
c = 0;
for (--p; c<clim;c++) {
y ^= x;
x ^= y;
y ^= c*x;
x -= p;
x = x * 17372755581419296689;
//The multiplicative inverse of 1530089809 mod 2^64.
}
}
}
const int rows = 163840;
const int maprows = 524288;
//Store for intermediate input strings, row 0 contains 64 columns with 3-char strings,
//row 1 contain 32 columns with 6-char strings and so forth, the final strings will
//contain one string from each column, in order.
char store[7][rows][512];
//Storage for a hashmap, used for matching n strings with n string in O(n) time.
char map[maprows][512];
int _tmain(int argc, _TCHAR* argv[])
{
char alpha[] = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int row;
int col;
int layer;
int a=0, b=0, c=0;
int colzero;
//Produce some starting strings.
for (row = 0; row < rows; row++){
//All column 0 strings begin with 0x08 in order to imitate the hash.
store[0][row][0] = 8;
colzero = 1;
for (col = 0; col < 64; col++){
store[0][row][col * 8 + colzero] = alpha[a];
store[0][row][col * 8 + colzero + 1] = alpha[b];
store[0][row][col * 8 + colzero + 2] = alpha[c];
store[0][row][col * 8 + colzero + 3] = 0;
colzero = 0;
}
a++;
if (a >= 52){
b++;
a = 0;
if (b >= 52){
c++;
b = 0;
}
}
}
//Layer for layer, column for column, build strings that preserve successively
//more zero bits. Forward calculated partial hashes are matched with backwards
//calculated partial hashes.
for (layer = 1; layer < 7; layer++){
int slayer = layer - 1;
int swidth = 1 << (slayer + 3);
int width = 1 << (layer + 3);
int slen = 3 << slayer;
int len = 3 << layer;
int colnum;
int layershift=slayer*8;
for (col = 0,colnum=0; col < 512; col+=width,colnum++){
printf("Layer: %i, column: %i\n",layer,colnum);
memset(map, 0, sizeof map);
int col2 = col + swidth;
for (row = 0; row < rows; row++){
hprev(store[slayer][row] + col2, 1 + slen*(1 + colnum * 2));
x = (x >> layershift) & 255;
y = (y >> layershift) & 255;
int index = (x << 3) | (y << 11);
for (a = 0; a < 8; a++){
if (map[index + a][0] == 0){
strcpy_s(map[index + a], store[slayer][row] + col2);
break;
}
}
}
int destrow = 0;
for (row = 0; row < rows && destrow < rows; row++){
hp(store[slayer][row] + col, !!colnum + slen*(colnum * 2));
x = (x >> layershift) & 255;
y = (y >> layershift) & 255;
int index = (x << 3) | (y << 11);
for (a = 0; a < 8 && destrow < rows; a++){
if (map[index + a][0]){
strcpy(store[layer][destrow] + col, store[slayer][row] + col);
strcat(store[layer][destrow] + col, map[index + a]);
destrow++;
}
}
}
}
}
memset(map, 0, sizeof map);
char temp[1000];
std::ofstream myfile;
myfile.open("hashout.txt");
for (row = 0; row < rows; row++){
hp(store[6][row], 0);
sprintf(temp, "%016llx%016llx", x, y);
myfile << store[6][row] <<" " << temp << "\n";
}
myfile << "\n";
//The final hash set has 96 of 128 output bits set to 0, I could have gone all
//the way, but this is enough to find a collision via the birthday paradox.
for (row = 0; row < rows; row++){
hp(store[6][row], 0);
long long xc = x;
long long yc = y;
int pos = (xc >> 45 | ((yc >> 48) & 7)) & (maprows-1);
while (map[pos][0]!=0){
hp(map[pos], 0);
if (x == xc && y == yc){
myfile << store[6][row] << "\n" << map[pos] << "\n";
sprintf(temp,"%016llx%016llx", x, y);
myfile << temp << "\n\n";
}
pos = (pos + 1) % maprows;
}
strcpy_s(map[pos], store[6][row]);
}
myfile.close();
printf("done");
getchar();
return 0;
}
```
[Answer]
# [PHP 4.1, 66 bytes](https://codegolf.stackexchange.com/a/51118/7773) by [Ismael Miguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel)
```
$ A=0111129112911291111111111111111111111111 php hash.php 2> /dev/null ; echo
0100038003800381129111111111111111111111
$ A=0111129112911291129111111111111111111111 php hash.php 2> /dev/null ; echo
0100038003800381129111111111111111111111
$ cat hash.php
<? $a = getenv("A"); for($l=strlen($b.=$a*1);$i<40;$o.=+$b[+$i]^"$a"/$a,$i++);echo$o;
```
Found using simple iterated hashing, starting from 1:
```
$ i=1; while true; do i=$(A=$i php hash.php 2> /dev/null); echo $i; done | head -n 10
0111111111111111111111111111111111111111
0100000000000001129111111111111111111111
0111129111111111111111111111111111111111
0100038000000001129111111111111111111111
0111129112911111111111111111111111111111
0100038003800001129111111111111111111111
0111129112911291111111111111111111111111
0100038003800381129111111111111111111111
0111129112911291129111111111111111111111
0100038003800381129111111111111111111111
```
[Answer]
# [Python 3 (216) by Sp3000](https://codegolf.stackexchange.com/a/51126/30688)
My messages are
```
5012053369354645637214643587103597313576086380250249302980438772005248488380915054746146050001036696049972235875591571028140916001206596142280971107479334216535925703480968283657357930602076844092875640359192729378384507238123245417656548512647301639542279794868512420586823155070914644206130805893968511673770843170450832829657206145931885656157628306896903719624729809643572222159364893644113710867223921580178741177106141068298067479650611992859787419779579962211254029169589775046869542029842374359998053713002047081002506346875804341770199884355810931652447801492691887376948615365487982834690942054717077615539311699691010938426302886867891090301248321702485904291177813145565144089044261424329155436660979948932491709511914065619715728353376578192548334780893602675684085757434059540582004872746967999949306946618036846307799677491651967418565531672392468089533111553281620101129322575737949904022139471688252420467041529301533363008476437812216585923822571793353317799365005036029476865
5012053369354645637214643587103103086948976188724715498910865650846170784131001427390927276355140411160919276493388206817700368694224128444524223814513348177926532982330730066315320819293979046126543806115318009892783577432467861426768883700930779409885418980853424256180864755881414774514084197887594253752179391098292488771920695965135791582218083012144604515253506370334133858904659263953147111654656123599460222236152128559750436960308887683690915261431659087040402402092795259541564130228515353133867041828417398395559815392177084002004583988047406317670433664624642858480970640416500369367395538257341309676777745698712896295462462064271676447460293684100001583256400774270688958051470568447233589146620275159126426142305307007744396679875427883384557759778766330566230012377845843842097372663092379922300568052486301863154557664156185573021849420011058607321977550938866119133331529852821217331665195832442542012455132139770813510559894254061471149750738447764616026512400623344132554752
```
I used this Python 2 code to generate them:
```
a,b = 14460445391122031029,16815296360833931837 #http://www.numberempire.com/numberfactorizer.php
pr = ~-a * ~-b
m0 = reduce(long.__or__, [long(b) << 26*i for i,b in enumerate(bin(pr)[2:])])
m1 = 1 << 26*i-1
m0 |= m1
#print m0, m1
print f(m0), f(m1)
```
The big modulus was a product of two primes `a` and `b`. I guess the hope was that it would be NP-impossible for us to factor the semiprime, but I guess 128 bits is too small as some webpage gave me the answer right away.
The multiplicative group modulo `ab` will have order *(a - 1)(b - 1)* which means if we raise any number to that power it will have to result in 0 or (usually) 1. So I put 1 bits in places that resulted in *2(a-1)(b-1)* being multiplied into the hash. Then the other message is basically 0, but I set one other bit in each number to make the lengths the same.
I think it would have been more annoying were the hash squared on every bit, rather than only after using all the primes. Then it wouldn't have been so simple to build arbitrary exponents for them.
[Answer]
# [C, 128 bytes - by: squeamish ossifrage](https://codegolf.stackexchange.com/a/51190/101)
The following two strings both hash to all zeroes:
```
dddl|lddH4|@dhxdxXdh0TXPdhhdx(dTxtlpdd@4Lhd|hdDpdhDdXLdXP4(PdddL|ldXdD(lddX4|0hddp4|ddP4Lxdp0dP@dhpTxPdhXdXxdhHDxHdllLttdhPT8pd(pT8Pdd0TL8dlLLTtddPtl8dP@DPPdhhDxhd804(pdh0Txpd@DDpLdhL4xtdXXdHXdd04lXht40dlddh4|@ddPTLXdhhDXHhtPH40dh0t8pd(pt80dhPtX0dhLtXtdhLT8thlLplTdhpt80dh0txpdhHDX(hdX8txdhhdxHdp|d@tdhlTx4dlptdxdh0T8PdT@t|Hdd@tL(ht(8DhdhHD8(hpHHP8dhLtXtdX8dhxdhpt8Pd@(D@Hdd@tLhdtxTLPdd0tlxhhL8X|dd8t|0dT04|Xddxt|phxxxhhdhpt8PhhxX8hdhlTX4dd4l||dd@TLHdXlTHtdhHd8hdX0THPdh(D8(d8xdh8dhp4xPd0HDp(dhl4xTdxlthtdhlTx4d8lT(TdhhdXHdphdP(dhp4x0d0Xd0XddTl||d88DH8dhhdxhdx|tHDdhLT8Thll0lTddPTlXdxXd(xdd0Tlxdhp480dhp4x0dd|LltdhPt80dtll|dddPTlXdxXd(xdd0Tlxdhp480dhp4x0dd|LltdhPt80dtll|dddP4Lxd|ptT8dhddxldH|4xDdhp4x0dDdl|LdhtD8|hhHx88ddpTL8hhphx@dhtd8|dphDP(dh0tx0hhDHx4dhpt8Pd@(D@HddLLLDhh|xxldhl4xTdhL4x4dhPt8Pd(HDx(dh(D8Hd4PT|8ddH4|@hh4H8ddhxd8XdDP4lxdhHd8hdl04d8ddXT|phdh8Thdd@TlHdhXdxxdllL44dD@4lHdhxdxXhd8XtxddLlLddT@T|(dhxdXXd|P44Xdhpt8pdlHDT0dhL4Xtd@ldpDdddl|LdXP4h0dhltXtdX8d(Xdh|tXdhhLXX|dhxd8XdP@D0PdhXDxXhtpHtPdd84|pddtl||dh(dx(d88Dh8ddx4|PhtT0DLdd@tL(hdX8Txdhp480d08d08dlll44d4dLLldhTdX|hh8Xxhdh048pd08d08ddPtL8d4H4l@dhhdxHd|pt4Xddp4lXhp(hPxdh|48DdxhDh(ddLlldd8XdH8dddl|LdLHDT0dhpt8pdlHDT0dh(d8hdTHtl@ddptl8dt84LPdh8dxxdlptD8dd04lxhhH8XxddDl|ldP|D@4ddTl||d|ptT8dh(dXhhd8X48dhPtXpd(8DxXdh@TX@dDP4L8dhpTX0d4@4|hdhHdxHdX8DHxdhPT8PhllplTdh0TXPhlXHLXddp4lXhtHXD(dhP4X0htH8dhdhLTx4hpxHPHdhhd8(dX8DHxdhpt80hhdHxTdlll44d@Hd@(dhhDxhdh0t8Pddh4|@ddh4|@dhptx0dpPD0@ddPtlxdhPT8pdhhdX(htTpDLdd@4L(dLHDtpdhxd8xdt84lPdlpTdxdDPTLXddLLLDdxlThtdlhd4PdXLTh4ddptLxd|@44(dhhd8HdtDLLlddxt|pd|hDd0ddPtLXhl@H|pdhDD8ld8dDhLdhXDXxdDxT|PdhHD8hdp8dpxdhp480d@XD@xddpTLXdHhD8(ddllLDdD|LL4dhpt80d@LdPDdh|4xDdP8dpXddLllddl8d4@dhptXpdd(4|@dhltx4d0Dd@LdhptxphdPHdpdhl4xTdxlthtdhHD8HdTdllldhLtX4dXP4(PdhLTxTd4X4LpddlllDdlpTD8dllltTdL(dtPdhDDxLdhLTx4dhptx0d|0T4Xdhl4xTdHL4XtdhpTXpdLp4dxddHt|@dHL484dhHDXHdHLtxtdhDdXldxL4H4dh|TxDhh8xX(dhLt8td8Lt(TdhHDx(d4DlLlddXT|PdHHD8(dlll44dlP4dxdd@tL(dL@4dhdd0tLxd4X4l0dhhdxhdDlLldddLLlddD04l8ddPtlxd(hd8hdd(T|@hdDp4|ddP4Lxdp0dP@dhptXpd(p4X0dhhd8(d8pT(0dh8d8Xhd(XT(dhddxLd@XD@8dd@tlhd@ld0ddhTD8|hhPH8@ddtl||dH0Tx0ddLlLddhp480dhHdxhd4lL|DdhXD8xdhhDX(dh048pd4Ll|ddddl|LdXP4h0dlll4thhdhxtddP4LXdhXdxXdhpTX0hdXXtxddlLLddx0Th0ddTl||hlhhlHdd|Ll4dHDdXldhhDX(hpxh0HdhDDXLdXDDhLdlhDTpht8Xdxdhpt8phhHXX8dd(t|@dHl4xtddp4LXhxhXH8dhDDxldDXt|PdhTDX|d|0ttxdhdDXLdDLLLddd84|PdT84LpdlhDTphl8hlxdhXD8xdHpt8Pdlhd40ddHT|@dhxdX8dhlT84dh|T8dhlXHLxdhxDxXdT4lL|dlllttd@xd@xdhhDXHhtXXD8dh(d8(d4p4|8dd04lxdxPThpdhHD8Hhdhx4hdhl4xthl|pLDdhltX4dhP4XPdd0Tlxdl@tDhddP4lXd0xD0xdhHD8Hd@8D@xdh0T8Pd0XDpxddPtl8dP@DPPdhhDxhd804(pdd04L8hpxHphdhDdxLdppD0@dd@tl(d88dHXdh0txpdXhDhHdd@Tlhdx8DHXdh0tXPdxxdH8dhPT8Pd484LPdlhD4pdxxdHxdd|Lltdhptx0dhlTx4hp8HPhdhPt8pdt4lL|ddtl||dH0Tx0dhxd8xhl@H|pddLllDhldP||dhdD8ldXLTHTdlhDTpddllLddd04lxhhH8Xxdh|48DdP8d0XddLLldd|@44hdhhd8hd4x4L0dhltXthh4H8Ddh4DX|dD@Tlhdh0tXpd8|T(ddhtDX|dlhdTPdd@tLhdThTl@dh8D8xdT(TL@dd@Tl(d8Hd(hdhXdxxhtHXdhdd0tl8d|HDDPdd8T|PdH04xPdd@Tl(d|@4t(dd(4|@dHp4xpdhpt80dh0txpdhp48phdXxTxdhhDXHhtPH40dh0t8pd(pt80dd8T|pdlxdt@dhp48PdD0TLXdh0t8Pd|lldTdh|t8DhphHp8
ddTl||d4|L|4dhptX0d4dllLddxT|pdxXdH8dlhDtPhlpH|@dd|Lltdhptx0dhlTx4hp8HPhdhPt8pdt4lL|ddtl||dH0Tx0ddLLLDd8tdH|dhDD8LdtxtLpdhxD8Xhd8xtxdhPt8Pd(8DX8dhddxLd0xd08dd0Tlxdxdd(Lddh4|@dXpt(Pdh048pd0xd0xdhhDX(d8p4Hpdh0480d(8DX8dhL4x4d4PT|XddPTLXdPDd@Ldddl|ld(P4X0ddDL|lht88DXdhPtxpd((Dx(dh0tx0dxXd(8dhpT8Pd0xD0XdlhD4pdT0T|8dh04XPht0H40dlhDtpdpHDP(dhlTXtdPHdpHdhXDxXhpPH0pddDl|lhltp|Ldh04x0dtXTL0ddLLLDdLhdtpdhL4xtdHDdXLddxt|0d4X4l0dh(Dxhdx04h0ddllLDd0PD0@dhXDxxhdx848dhDDxldpXDpXdhPt8pdhltxTdd04lxhhH8Xxdh|48DdP8d0XddLLldd|@44hdhhd8hd4x4L0dhltXthh4H8Ddh4DX|dD@Tlhdh0tXpd8|T(ddhtDX|dlhdTPdhlTXtdTX4L0dd@Tlhhh8xXHdhPt80d|XdD@dhp4xphd4Ptldd|LL4dL|ltDdhPTx0d80T(pdhpt8pd|pTtXdhpTX0hhth8Ddhxd8xdphdP(dh8D88dp(DPhdhHD8(htxXdXdh8dXXdXpTH0ddx4|PdpXDPxdhXDXXdxxdhXdhlt8Td@xD@8dhP4XPdhltX4dd@tlHdhXDxxdhPtXPd(8Dxxdh0t8PhdpHd0dh(D8HdX(D(Hdd@tLhht|@4Tdd@4lHdttll|dd0tlXhh|xxldd@TLHdlHdTPdd|LL4dt@T|hddx4|PdlHdtPddTl||d88DH8dlhdTpd40t|xddht|@dpPDP@dhHDxHhxthHDdhddxldxtDH|dhltx4d8Dd(ldd|LLthp0H0Pdhl4x4d|0T4Xdd|ll4dt8tLPdd@4lhd|0TTXddPtLXd(8d8xdhPTxPdHxd8xdhHDX(ddLllddhp48Pd0@d0PdhptxpdX(DhHdd0TlXhtPHTPddh4|@dTDlLldhDDxLhp(hPxdhdD8ldXLTHTddPtLXdTh4L@dhLtxTdlpTd8dhPtXpdhLtX4ddPTlXdxxdhXdhhd8(d404|8dhTd8|dhL4Xtddp4l8d4X4LpdhL4Xtd@ldpDdddl|LdXP4h0dhpTX0htXxDxdhpt8pddLlLddhp4XPhp0H00dh4Dx|dlp4D8dhPtxpd((Dx(dh0tx0dxXd(8dhDDxlhlL0ltdhhDxHd@|d0TdhHdxhdL0tD8dhhD8hhl|pLdddxt|pd|hDd0ddPtLXhl@H|pdhxDXxd8DdhldlhdtphpphppdhpT8PdH8dxXdlhd40dtXtlPdhTd8|dXlthtdhTDX|dx|4HDddxT|pdHDd8ldhL4X4dhP4XpdhtDx|ddXt|Pdh|T8DdHhdxhddLLLDhlxHl8dh0tXPd|(ddPddDL|LdHhdxhdhp4x0dl8dT@ddXT|phdh8Thdh(DXhd0HDP(dddl|lhd(xT(dhXdXxdTxtl0dd|lLtd8|4hddd4l||dXLTh4dd04lxdP8DP8ddxT|0dXXdh8ddP4lxd0@DpPdh8dXxddp4lxdhLt8tdHTdx|dh4Dx|dxLTHtdhhd8hd@DDpldd04LXdXlT(tdhXdXxdhPT8pdh(DXHdP@dp0ddP4LXdXpThPdllL4td((D8(dh0tXpd|(ddpdh(DxhhdL@DDdhHDx(dxL4(tdhLtXtdl@4dHdhxd8xdTh4L@dhXDXXhhdH8Tdd8T|PdH04xPdlllT4hllpLtdhhDXHhxxXhhdhXDxXdPDd@Ldd0TlXdHLtX4ddDL|ldXLT(4dhPtXPdXXd(8dhpt8phdH8thddxT|pd(ptXpddP4LxdLXDT@dhpT80dLptDxddxt|pdP@Dp0dhptx0d|0T4XdlpTdxdxpt(PdhHD8(d4TlL|dhHDx(d@hD@(dd@tl(d88dHXdh(Dx(d4pT|xddPtl8dP@DPPdhhDxhd804(pdhHD8Hhdhx4hddP4lxhdhXt(dhxdX8dp@DppdlllT4dP0dp@dddl|ldH8DXXdllLT4dPXdp8dd@tLHdlPTd8ddtL||d8PtHpddHt|@hd|@d4dh(dX(hdhXT(dhpT80hdHX4(dlpTdxdtDlLlddxT|pd(ptXpddP4LxdLXDT@dhpT80dLptDxddxt|pdP@Dp0dhptx0d|0T4XdlpTdxdxpt(PdhHD8(d4TlL|dhHDx(d@hD@(dddL|lhtph40dhpTxPdlp4dXdhDDxldpxD08dh(dX(dHlTxTdd|ll4d40t|Xdh0480ht@hT@dhptXphdHxT(dh(D8Hd4PT|8dhpt8pd88dhXddDl|LhxdHHtddPtlXd|pt4Xdd0Tl8d0(D0hdhhd8hdppd0@ddPTlXd8P4hpdhlTx4d8dDhLdd@TLhhllplTddXT|0dH|4XDdh|4xDht8XD8ddptl8dH8d88dd|LLTdh(DXhddHt|@hpXhp(dhdDxLdDhT|@dhP4X0dXhDHhdh0T8Pd((dxhdhhDx(hdx8Txddp4LXd8xDH8dhPTXpdlPtD8dh(DxHd@8D@Xdhl48Td00Dp@dhLT8Tdp(d0(dhhd8(d404|8dhhdx(dx0T(pdd|lL4ddXt|Pdd0TlXhxdH(4ddllLDhhLXX|dhXDx8hl8hLxdhpT80dLPtDXdhptX0dPXd0XddP4lxd0@DpPdlptd8dl(dTPdhxDx8d(ptX0dhpT80htxxdXdhhDxhdXltHtddh4|@d@|dPTdhdDXLhpph0Pdhp48Pdt4lL|dh04xpdLpTD8dd@4lhdl8dt@ddhT|@dPxDp8dd04lXd40t|xdd0TLxdTdlLLddpTLXd|pTT8dd04lxhhH8XxdhddxlhddPT|dd04LXdlhd4pdh8d8xhh|8XLdhxd8xd(8d8xdhp48pd(8DX8dhhDXHd4dllLddx4|0d8PTH0ddPtlxd|P44XdlpTdxd(XDXXddpTlxdHltX4dhLTxtd|HDD0
```
The hash function is built so that higher order bits never influence lower order bits, therefore I can generate a collection of strings where all of the `x` lower order bits are zero, then I can try concatenated combinations of these strings to find some where more of the lower bits are zero etc. I'm pretty sure that there are more ways of breaking this, and also ways that produce significantly shorter strings, but this way I avoided doing a lot of maths.
[Answer]
# [Python 3, 118 bytes](https://codegolf.stackexchange.com/a/51144/41288)
```
int(H("9"+"0"*400))
```
and
```
int(H("9"+"0"*4000))
```
(that is: 9E400 and 9E4000)
Both produce
```
83909358607540647658718900164058931893
```
Digging somewhat deeper, it seems that any integer followed by k repeated digits such that k > 128 and (k%4 == 0) will return the same hash. For example, `H("1"+"1"*32*4)` and `H("1"+"1"*33*4)` are both `13493430891393332689861502800964084413`. Hmmm, 128...
[Answer]
# [Python 2, 161 bytes, by Puzzled](https://codegolf.stackexchange.com/a/51193/25180)
```
340282366920938463463374607431768211456 (decimal)
100000000000000000000000000000000 (hexadecimal)
```
and
```
340282366920938468780317283222139437056 (decimal)
100000000000001203B66F94300000000 (hexadecimal)
```
Both have the output:
```
83F172CC3D050D131F64FD04B8181DC2
```
The numbers are 2^128 and 2^128 + (3\*5\*7\*11\*13\*17)^2\*19\*2^32.
[Answer]
# [Java, 299 bytes by SuperJedi224](https://codegolf.stackexchange.com/a/51087/8478)
[Pastebin for `M`.](http://pastebin.com/JDeSB2ua) In binary, `M` has 65535 `1`s, followed by 2 `0`s.
[Pastebin for `N`.](http://pastebin.com/u14drwgf) In binary, `N` has 21845 `1`s, followed by 174766 `0`s.
Both yield `0`.
Note that the basis of the algorithm is `i.bitCount()*i.bitLength()+1` and ultimately, we take the result to the power of `i` and take it mod 2128. So the idea was just to find two `i` that are divisible by four, but where the first expression gives 232. That was easily done by factoring 232-1 and picking two factors for the count of 1s and total bit width of the number.
**Edit:** Actually, there's a bit more to why `M` yields zero, but we can easily find more numbers that yield zero because of my explanation by using other factors of 232-1 such that there are at least 64 zeroes at the end.
[Answer]
# [C, 134 bytes (by Barteks2x)](https://codegolf.stackexchange.com/a/51094/11006)
```
10
```
and
```
20
```
both hash to
```
0xa609779942cb9ef1
```
because the algorithm only hashes the last digit!
[Answer]
## [C, 87 bytes](https://codegolf.stackexchange.com/a/51146/7773)
```
$ echo B075343F9832CD60 | ./hash6_ ; echo
fc2e9f02bd284bd1
$ echo 5914BD1B71164C77 | ./hash6_ ; echo
fc2e9f02bd284bd1
```
Found using my collision bruteforcer.
[Answer]
# [Python 2, 115 bytes, by squeamish ossifrage](https://codegolf.stackexchange.com/a/51313/25180)
```
1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222
```
and
```
2222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222211111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
```
The hash value had nothing to do with the order of blocks.
[Answer]
# [Python 2.x, 139 bytes by Puzzled](https://codegolf.stackexchange.com/a/51177/36885)
`H(2)`
and
`H(128)`
both return
`16645614427504350476847004633262883518`.
[Answer]
# [C++, 239 bytes by SpelingMistake](https://codegolf.stackexchange.com/a/51175/41288)
Using the provided "main" program, the following two inputs produce the same hash:
```
echo -n "dog" | ./h
481c27f26cba06cf
```
and
```
echo -n "fog" | ./h
481c27f26cba06cf
```
The *first 8 bytes of input are never processed*, due to this bug in the code:
```
for(I i=n;--i;) // and then we use q[i] for this iteration
```
because `--i` evaluates to false when `i==1`, `q[0]` (the first 8 bytes: `I` is an `int64`). Replacing the loop condition with `for(I i=n;i--;)` would have fixed this.
[Answer]
# [Ruby, 90 Bytes, by MegaTom](https://codegolf.stackexchange.com/a/51237/25180)
```
4271974071841820164790043412339104229205409044713305539894083215644439451561281100045924173873152
```
and
```
23495857395130010906345238767865073260629749745923180469417457686044416983587046050252582956302336
```
which are 2 and 11 followed by 40 zero bytes. So they both have 41 bytes. The hash value is added by the input length for each byte, and then it is reversed in decimal. A input length ending with `1` can make sure the hash value will end with a `0` pretty quickly. Then reversing it reduces the length of the hash value by 1.
Both have the hash value `259`.
[Answer]
# [C# - 393 bytes - by: Logan Dam](https://codegolf.stackexchange.com/a/51265/101)
`70776e65642062792031333337206861786f72` and `70776e65642062792031333337206861786f7200` both hash to `18E1C8E645F1BBD1`.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** [Update the question](/posts/3245/edit) so it's [on-topic](/help/on-topic) for Code Golf Stack Exchange.
Closed 12 years ago.
[Improve this question](/posts/3245/edit)
Make a story out of your programming.
Example in JavaScript:
```
self.book = {
"story": function() {
var once = "upon",
aTime = setTimeout(function() {
// Code would continue...
}, 1000)
}
};
self.book.story();
```
**Stipulations:**
* Must run error-free before, during, and after it's compiled.
* You can only use up to two words for the story per String/name.
+ JavaScript Example:
`var story = "Once upon a"; // Wrong (Using more than two words)`
`var story = "Onceupona"; // Wrong (Using more than two "words")`
`var onceUponA = "time"; // Wrong (more than two words as a variable name)`
`var onceUpon = "a time"; // This is fine`
`var story = "Once upon"; // This is fine`
* The story must be a complete sentence (at least).
* Having some sort of output (such as "printing" the story itself) is not necessary, but it's a plus.
* Bring some creativity into it.
Since there are no length rules, the answer with the most votes / best creativity will win. :)
[Answer]
# JavaScript
Not sure how historically accurate this, but it's a mini-history of ECMAScript. Please feel free to suggest improvements.
```
function story() {
var IE = {
from: "Microsoft"
},
Netscape = {
from: "Mozilla"
};
var setUp = {
oncethere: "were two",
browsers: IE + Netscape
};
var parts = {
And: function() {
var theyfought = "to be",
theBest = "browser";
},
oneday: function() {
var they = {
added: function() {
var add = "scripting languages";
Netscape.language = add;
IE.language = add;
return add;
},
thought: function() {
if (what(they.added) === good) {
they.wouldBeat = "the other";
}
}
};
},
andso: function() {
function callLanguage(name) { return name };
Netscape.language = callLanguage("Javascript");
IE.language = callLanguage("JScript");
},
butThen: function() {
var ECMA = "Standards Committee";
(function standardized(languages) {
(function into() {
return "ECMAScript";
})();
})([IE.language, Netscape.language]);
},
theEnd: function() {
return {
andWe: "all lived",
happilyEver: "after..."
};
},
what: function(thing) {
return thing;
},
good: true || false
};
}
story();
```
[Answer]
Reminds me of [LOLCode](http://lolcode.com/examples/count-1), everything is sort of a story (or at least a "conversation"):
```
HAI
CAN HAS STDIO?
I HAS A VAR
IM IN YR LOOP
UPZ VAR!!1
VISIBLE VAR
IZ VAR BIGR THAN 10? GTFO. KTHX
KTHX
KTHXBYE
```
[Answer]
# JavaScript
```
'How';do{'computers'^Function}while(0);'they have'|'no power?'
```
The output is: `0` on console :D
[Answer]
It's not so much of a *story*, and what the program does has nothing to do with what the code says, but...
# C++
```
/* Preface (assuming nobody reads it anyway): */
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <functional>
#include <time.h>
using namespace std;
int
/*Beginning the*/ main(){//story:
#define a string
ofstream ing___water; a river;
#define the
long rivers,
each, is
(a ( river +"of").length() > 4 );
a normal ( river +"has the");
a bility; for ( float ing; short (~1 - - 2 );){
char coal, loaded, ships, on, its, water;
coal = is; a lot, lighter;
if ( lighter .compare ( normal ))water = 'H'*2+'O'; }
a heavier, ship, may; do { a worse, job; a nd, run;
a ground; }while ( "you"&&false)//ly
;try { a nd ( "navigate through");
a ny, such ( normal.size()==rivers ?
the "ship" : may + "then"); }
catch ( exception ally ) { a wful;}} struct ural___damage {
long before ( the time_t o) const{
return "to" == a( "harbour");
for ( a rescue ("from leaking"),
its ("load or");o<the'r';) {
ofstream ing, substances;
if ("not"=="even"||substances/*that*/.put( 'a').bad())
double damage, to, both the ((short) "river"[1]);
a nd the ("overall environment[2].");}}
a sentient, ship_owner, should, h;int //to
the operator<( struct ural___damage might) const{
a lso( "occur"), to( "his own"),health( "when not");
using the ::map;
to .find( a ( "river that's"),long( ~3 ) );
(to+="avoid")+=the "trouble and";
(to+="cause")+=(less</*r*/ural___damage>()
(*this,/*seems like*/*this)?"is": a( "good idea"));
return before ( the time(0))||"is"==to +"late";}};
```
As plain text:
>
> Beginning the main story:
>
>
> define a string ofstreaming water a river;
>
> define the long rivers, each is a river of length > 4;
>
> a normal river has the ability for floating short (~1--2) charcoal-loaded ships on its water; coal is a lot lighter if lighter compare normal water = H2O;
>
> a heavier ship may do a worse job and run aground while you falsely try and navigate through any such normalsize rivers, the ship may then
> catch exeptionally awful structural damage long before the time toconst return to a harbour for a rescue from leaking its load or other ofstreaming substances, if not even substances that put a bad double damage to both the short river [1] and the overall environment[2].
>
> a sentient ship\_owner should hint to the operator structural damage mightconst also occur to his own health when not using the map to find a river that's long(~3) to avoid the trouble and to cause less rural damage. this seems like this is a good idea.
>
>
> return before the time is to late.
>
[Answer]
# Brainfuck
```
+++++ + + +++++ +++++ +++++ +++++ +++++
+ + + + + + + + +
+ +++++ +++ +++++ +++ + +++++
+ + + + + ++ + + .
+ + + +++++ + + +++++ +++++ +++++
+++++ + + + + + +++++ + + +.+++
[ + ]+ + + + + + + ++ + +
+ + + [ + ] + + + + + + +++
+ + + ++ + + + + + ++ +
+++++ + + +++++ + ++++. + + +++++
++++ +++++ +++++ +++++ + +
+ + + + + + + ++ +
++++ +++++ +++++ + + + +
+ + + + + + + + ++ +
++++ + + + + +.[+] + + +
+++++ + + +++++ + + +++++ +++++ +++++ .
+ + + + + + + + + + +
+++ + + + +++ +++ +++++ +++++ +
+ + + + + + + + ++ +
. +++++ +++++ + + +++++ + + +++++ .
```
I "accidentally" ran this through `bf` and that came out
```
It's Me
```
\*SCNR\* :)
[Answer]
# BASIC
slightly simplistic, but very true for those of us who stay up till 3 AM debugging...
```
On Error GoTo sleep
```
[Answer]
## Python Love
```
def initely(there, were):
if not None:
atLeast = not "many"
who.made("my heart")
"beat as", you.do(_,_)
return your.smile
warm = "ly"
try:
toKeep = "it" + warm
while walkingHome: pass
ing(emptyWindows)
except:ionally = "sad"
finally: it = "'s over"
your = not any([1, "to me"]) or "just my toy" and \
type("",(), {"youWere": "more"} )()
your.smile = "kept me"
_ = warm in "these days"
but, you = "were failed by", your #love: me
if _: only(I)
hadKnown, you.were = "innocent as a", lambda \
young, blueEyed: \
[("but ", "the retribution") for myMisdoings #comes
in "time"]
sometimes, you.do = ("make me", #think of who
you.were)
""in "another story"
I, who = "I've been", your#'s
"sit" in "my room"
"look"in"g at" #old photographs
#relentlessly remembering
the, love = you.do, "give to me"
who.made = all #these mistakes
"Had thought" + it + "would go"
on = "inf"+initely(
"Oh!, the", "fool I've")#been
regretting = all("my errors") #today
_, im = "hold" in "paraly","sys"
_ = open; "cans" and "cans of"
_ = _(__import__(#ed beer
im).#in a d
argv[0]#id
).read() #sad poems
love, is_ = the, "thing I" #miss forever
iTake = "my camera"
go = "out to have"
new, photos = "to look", _ #at
print ("them" if 0 #they're dull
else _); "they make" + "me think of", love("lost", "for me")
```
EDIT: This is now a (if cheated) quine.
[Answer]
bash or other shells on Unix or Linux:
```
who am I & whereis edit || eliza && find ada
```
[Answer]
I really can't claim this one to myself, but I think it would be really good for you all to be able to look at it.
This is called PHP Sad Poem, and comes from [here](http://mundogris.wordpress.com/sad-php-poem/).
```
$timeWaiting = 0;
while (!$you->near($me)) {
$me->thinkAbout($you);
switch (true) {
case $timeWaiting < 5:
$me->wait($you);
break;
case $timeWaiting < 10:
$me->worry();
break;
case $timeWaiting < 20:
$me->lookFor($you);
break;
case $timeWaiting < 40:
$me->worry();
$me->lookFor($you);
break;
case $timeWaiting < 80:
$me->worry();
$me->cry();
$me->lookFor($you);
$me->lookFor($you);
$me->lookFor($you);
break;
case $timeWaiting < 160:
$me->worry();
$me->cry();
$me->drink();
$me->lookFor($you);
$me->lookFor($you);
$me->lookFor($you);
$me->thinkAbout($you);
$me->thinkAbout($you);
$me->cry();
$me->lookFor($you);
$me->lookFor($you);
$me->drink();
$me->drink();
break;
default:
throw new CantLiveWithoutYou();
die(“alone”);
}
$timeWaiting++;
}
$me->happy = true;
```
] |
[Question]
[
Given an integer `n`, print out `n * reversed(n)`
`reversed(n)` is the number you get when you `reverse` the digits of `n`.
---
```
reverse(512) = 215
reverse(1) = 1
reverse(101) = 101
>>>>>>>>
```
---
```
func(5) = 5*5 = 25
func(12) = 12*21 = 252
func(11) = 11*11 = 121
func(659) = 659*956 = 630004
```
Shortest code wins!
## Leaderboard
```
var QUESTION_ID=144816,OVERRIDE_USER=71625;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]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
R*
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/SOv/fzNTSwA "05AB1E – Try It Online")
In 05AB1E, integers and strings are treated as equivalent types, so reversal (`R`) converts to string and reverses, whilst multiplication (`*`) treats the reverse and the input as integers.
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), ~~45~~ ~~35~~ ~~33~~ 28 bytes
```
n=>n*[...n].reverse().join``
```
[Try it online!](https://tio.run/##BcFRCoAgDADQu/ilQYP6t4tEoNgMzTZxIXR6ey/77iW0VN9ZajqxPUw3fiPaQXajaQcAOqBhxyaoDWRO5NwITMIFofClo1bLqowZPw "JavaScript (SpiderMonkey) – Try It Online")
* Saved 2 bytes thanks to [dennis](https://codegolf.stackexchange.com/users/12012/Dennis)
* Saved 8 bytes thanks to [kamoroso94](https://codegolf.stackexchange.com/users/57013/kamoroso94)
* Saved 2 bytes thanks to [ATaco](https://codegolf.stackexchange.com/users/58375/ataco)
* Saved 5 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
×ṚḌ
```
I'm new to Jelly, so please let me know if there is a way to do this in 1 or 2 bytes!
[Try it online!](https://tio.run/##y0rNyan8///w9Ic7Zz3c0fP//38jQwA "Jelly – Try It Online")
### Explanation
```
×ṚḌ (Input: 12)
Ṛ Reversed decimal digits (Stack: [2, 1])
× Multiply by input (Stack: [24, 12])
Ḍ Convert to decimal (Stack: 252)
Implicit print
```
[Answer]
# Ruby, ~~25~~ 24 bytes
```
->n{n*eval(n.digits*'')}
```
[Try It Online!](https://tio.run/##PYtNDoIwGET3nOILG35SCa1Cogl6ENJFpUWakNrQ1mjEs9eihN2beTOTu7583/jdWb1VLh5sTFXB5U1akydJ9vFtBNBWCEhF0YKYLEzWgBFggv@hro4I6n1Zlgca0UKwbgB@h1kq7SwC8dSis4LPYTsJ40YLDfTtz9LQ6Ukqu5lm28MF4lQzYzKI4RS4Z3IMvFycNesjEor7Lw).
`Integer#digits` returns a list of reversed digits, so further reversing is not necessary.
Thanks to [@benj2240](https://codegolf.stackexchange.com/users/77973/benj2240) for golfing a byte!
[Answer]
# [Perl 5](https://www.perl.org/), 11 + 1 (`-p`) = 12 bytes
```
$_*=reverse
```
[Try it online!](https://tio.run/##K0gtyjH9/18lXsu2KLUstag49f9/E9N/@QUlmfl5xf91CwA "Perl 5 – Try It Online")
[Answer]
# [ARBLE](https://github.com/TehFlaminTaco/ARBLE), 12 bytes
Takes input as an int.
```
a*reverse(a)
```
[Try it online!](https://tio.run/##SyxKykn9/z9Rqyi1LLWoOFUjUfP///9GhgA "ARBLE – Try It Online")
[Answer]
# Python 3, ~~35~~ 28 bytes
```
lambda m:m*int(str(m)[::-1])
```
[Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRIdcqVyszr0SjuKRII1cz2spK1zBW839BEUgsTQNEZuYVlJZoaALBfwsDAA "Python 3 – Try It Online")
Saved 7 bytes by fixing a bug pointed out by Dennis.
[Answer]
# J, 7 bytes
```
*|.&.":
```
[Try it online!](https://tio.run/##y/r/P03BVk9Bq0ZPTU/Jiis1OSNfIU3BFMYwNIKzDGEsM1PL//8B)
Couldn't think of a shorter way, though I feel like this is pretty elegant.
### Explanation
```
*|.&.":
&.": Convert to string, apply next function, then undo conversion
|. Reverse
* Multiply by input
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~27~~ 23 bytes
*4 bytes saved thanks to Lynn and Laikoni*
```
(*)=<<read.reverse.show
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX0NL09bGpig1MUWvKLUstag4Va84I7/8f25iZp5tQVFmXolKmoKJxf9/yWk5ienF/3WTCwoA "Haskell – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), 10 bytes
```
{$_*.flip}
```
[Try it](https://tio.run/##K0gtyjH7n1upoJZWmpesYPu/WiVeSy8tJ7Og9n9xYqUCSFTDVNOaiwvOMzRC5RqicM1MLTWt/wMA "Perl 6 – Try It Online")
## Expanded
```
{ # bare block lambda with implicit parameter $_
$_
*
.flip # implicit method call on $_
}
```
[Answer]
# bash, ~~52~~ 48 bytes
```
for((i=n=$1;r=r*10+i%10*n,i/=10;));{ :;};echo $r
```
[Answer]
# C# .NET, 55 bytes
```
n=>{int i=n,j=0;for(;i>0;i/=10)j=j*10+i%10;return n*j;}
```
**Explanation:**
[Try it here.](https://tio.run/##jc0xC8IwFATgvb/iLUJaa02EChLTRXCyk4NziRFeqS@QpIKU/vZYEXG0y8HBx532K22dibprvId6SAB8aAJqOD99MPfi2JPeI4UcpqhAg4qkqmEqgIryVnF5s45JrLjEtRI8bVWbCb7EheDSmdA7AspaOUaZ/NYfFq9QN0gsfX/C9@5gydvOFBeHwZyQDNOsTFP5z4jNHCRmoG25mzPFxSzFP2pMxvgC)
```
n=>{ // Method with integer as both parameter and return-type
int i=n, // Integer `i` (starting at the input)
j=0; // Integer `j` (starting at 0)
for(;i>0; // Loop as long as `i` is not 0
i/=10) // After every iteration: Remove the last digit of `i`
j=j*10 // Add a trailing zero to `j`,
+i%10; // and then sum this new `j` with the last digit of `i`
// End of loop (implicit / single-line body)
return n*j; // Return the input multiplied with `j`
} // End of method
```
[Answer]
# [Ohm v2](https://github.com/MiningPotatoes/Ohm), 2 bytes
```
œΠ
```
[Try it online!](https://tio.run/##y8/INfr//@jkcwv@/zcztQQA "Ohm v2 – Try It Online")
Explanation:
```
œΠ Main wire, arguments: n
œ Pushes [n, n.reverse]
Π Multiplies that array together
Implicit output
```
[Answer]
## Batch, 87 bytes
```
@set s=%1
@set r=
:l
@set/ar=r*10+s%%10,s/=10
@if %s% gtr 0 goto l
@cmd/cset/a%1*r
```
Need to take the arithmetic route here as string reversal fails for some numbers such as 80.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 49 bytes
```
i,a;f(n){for(i=0,a=n;a>0;a/=10)i=i*10+a%10;n*=i;}
```
[Try it online!](https://tio.run/##LY3BCoMwEETP@hVBEBJdMSlYKGn8kdZDiNruobGo9FDJt6eJ9fZmZ2fGVA9jvEfQcqSWbeM0U1QctLJSt1zqWgnOUGEheKlzwaUtFErn0a7kpdHSCHp@GDBPPRdF5A/b0iTe12FZl1tHFNkacQIBggtoIKKAc3NxMk32xfAbViVeF/wO00j3IKsPFWwmsSxjbfKegxxplvekakne320G/x3s4EgGZCx0u9T5Hw "C (gcc) – Try It Online")
[Answer]
# LISP, ~~91~~ *64* bytes
~~(defun R (N)(defvar M (write-to-string N)) (parse-integer (reverse M))) (write (\* x (R x)))~~
```
(defun R(N)(write(* N(parse-integer(reverse(write-to-string N))))))
```
Where ~~x~~ N is your integer you want to work with, of course.
I'm pretty new to programming, but I've found that trying these Code Golf problems has been nice practice. Is there something I'm missing that could help with this?
EDIT: Thanks to some tips from ceilingcat, I was able to shave off a few bytes. Old program preserved in strikethrough for reference.
[Answer]
# Bash + GNU utilities, 18
```
bc<<<$1*`rev<<<$1`
```
[Try it online](https://tio.run/##S0oszvifll@kUJJaXJKcWJyqkJmnYKpgaKRgaKhgZmpprZCSz1WcWqKgq6ugAlPzPynZxsZGxVAroSi1DMxK@J@Sn5f6HwA).
[Answer]
# [Batch](https://technet.microsoft.com/en-us/library/bb490869.aspx?f=255&MSPPError=-2147217396), ~~150~~ ~~125~~ 121 bytes (+ 5 bytes? `cmd/q`)
```
set l=%1
set n=0
set r=
:L
call set t=%%l:~%n%,1%%%
set/an+=1
if [%t%] neq [] set r=%t%%r%&goto L
set/ar=%r%*%l%
echo %r%
```
Saved 25 bytes thanks to [user202729](https://codegolf.stackexchange.com/users/69850/user202729)!
Saved 4 bytes thanks to [Matheus Avellar](https://codegolf.stackexchange.com/users/66000/matheus-avellar)!
[Answer]
# ><>, ~~41~~ 39 Bytes
```
:&>:a%:}-\
/~\?)0:,a/
>l1-?\&*n;
\ +*a/
```
## How it works:
```
:&
```
Assume input has been pushed to the stack (<https://codegolf.meta.stackexchange.com/a/8493/76025>). Duplicate it and store a copy in the register.
```
>:a%:}-\
\?)0:,a/
```
Converts this to its individual digits, leaving them on the stack.
```
/~
>l1-?\
\ +*a/
```
The top value will always be a zero due to the number-to-digit conversion process; drop it from the stack. Now, while the length is >1, multiply the first item by ten and add it to the item below it. This results in the number reversed.
```
&*n;
```
Multiply the original number by the reverse, print the answer, and stop.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
Ṙ*
```
[Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZgqIiwiIiwiMTIiXQ==), or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4bmYKiIsIiIsIjVcbjEyXG4xMVxuNjU5Il0=).
[Answer]
# [Julia](https://julialang.org), 28 bytes
```
~n=parse(Int,reverse("$n"))n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6Fnvq8mwLEouKUzU880p0ilLLUkFsJZU8JU3NPIiSm8Fp-UUKGnk6qRUFqcklqSmathoapjpGppo6GoZGQNoIxDDUMTQyBDLMTC11zIwNDAxMNDW5OAuKMvNKcvI0gLbYwrVzpealQIyGuQIA)
[Answer]
# [Leaf Lang](https://gitlab.com/breadleaf/leaf-lang), 41 bytes
Note: The interpreter does not have a stable release. If I introduce a breaking change I will update this post.
```
import"string.lf"argv:o o reverse o*print
```
Explained:
```
import "string.lf" - import stdlib's string.lf
argv - push all of argv onto stack
:o - set o to top value from stack (pops top)
o - push o to top of stack
reverse - reverse the string
o - push o to top of stack
* - leaf lang will implicitly convert strings to numbers when applicable
print - print top value of stack with no newline
```
Ungolfed:
```
import "string.lf"
argv : num
num reverse num *
print
```
[Answer]
# Mathematica, 19 bytes
```
# IntegerReverse@#&
```
Takes an integer input.
[Answer]
# [cQuents 0](https://github.com/stestoltz/cQuents/tree/cquents-0), 8 bytes
```
#|1:A\rA
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/X7nG0Moxpsjx/38zU0sA "cQuents 0 – Try It Online")
## Explanation
```
#|1: Output first term in sequence
A\rA Each term in the sequence equals:
A * \reverse(A)
```
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 7 bytes
```
nsSrJl*
```
[Try it online!](https://tio.run/##y6n8/z@vOLjIK0fr/38TYwA "Ly – Try It Online")
[Answer]
# Casio-Basic (fx-CP400), 44 bytes
```
ExpToStr n,a
StrInv a,a
Print n*strToExp(a)
```
There's no built-in for reversing an integer, but there is one for reversing a string.
`ExpToStr n,a` turns n into a string and stores it in `a`, then `StrInv a,a` overwrites `a` with the reversed version of itself. The last line turns `a` into a number, and prints `n*a`.
43 bytes for the code, +1 to input `n` into the parameters box.
[Answer]
# Japt, 2 bytes
Takes input as a string, outputs an integer.
```
*w
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=Knc=&input=IjEyIg==)
[Answer]
# MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~33~~ 31 bytes
```
@(n)str2num(flip(int2str(n)))*n
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPs7ikyCivNFcjLSezQCMzr8QIKAAU1tTUyvufmFesYWZqqfkfAA "Octave – Try It Online")
Octave/MATLAB anonymous function. This is a pretty naïve approach - converts the integer to a string, flips the string, converts the result back to an integer and multiplies it by the original.
---
* Save 2 bytes by using `flip` instead of `fliplr`.
[Answer]
# [Python 2](https://docs.python.org/2/), 25 bytes
```
lambda n:n*int(`n`[::-1])
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKk8rM69EIyEvIdrKStcwVvN/moaCgqmmgq2tAggYmXIBBQyNYAJGpkZgAUOYgKGRIVDAzNQSLGBmbGBgYMJVUAQ0VElP6T8A "Python 2 – Try It Online")
[Answer]
# PHP, 23+1 bytes
```
<?=$argn*strrev($argn);
```
Save to file and run as pipe with `-nF`.
] |
[Question]
[
## Challenge
Predict the distance between the Sun and the nth planet when using **any formula** that gives the same result as the [Titius–Bode law](https://en.wikipedia.org/wiki/Titius%E2%80%93Bode_law): `d=(3*2^n+4)/10`.
**BUT WAIT**... there is one restriction:
* Your source code can not include any of the Titius–Bode law's digits
* So, your program can not contain the characters `0`, `1`, `2`, `3`, or `4`
## Input
`n` a non-negative integer value:
* For Mercury `n` is -∞ no need to handle this case.
* `n=0` for Venus
* `n=1` for Earth
* `n=2` for Mars, and so on ...
## Output
Distance in astronomical unit between the Sun and the nth planet (decimal with at least one decimal place).
## Titius–Bode law
Distance in astronomical unit between the Sun and the nth planet is estimated by `d=(3*2^n+4)/10`.
## Example
```
0 --> 0.7
1 --> 1.0 or 1
11 --> 614.8
```
## Rules
* The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963).
* No need to handle **invalid input values**
* 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.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
oxOÌÌT/
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/v8L/cM/hnhD9//8NDQE "05AB1E – Try It Online")
**Explanation**
```
o # push 2^input
x # pop a and push a, 2*a
O # sum stack
ÌÌ # add 2 twice
T/ # divide by 10
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 22 bytes
```
-Df(x)=((6<<x)+8.)/''
```
[Try it online!](https://tio.run/##S9ZNT07@/18fK/jPlZlXopCbmJmnoalQrVBQBOSmKWgoqaYp6SikaRhralor1P7/l5yWk5he/F/XJU2jQtNWQ8PMxqZCU9tCT1NfXUQdAA "C (gcc) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~29~~ ~~28~~ ~~27~~ 25 bytes
```
s=9-7
d n=(6*s^n+8)/5/s/s
```
~~Nothing special, I'm afraid.~~ All allowed digits exactly once!
[Try it online!](https://tio.run/##y0gszk7Nyfn/v9jWUtecK0Uhz1bDTKs4Lk/bQlPfVL9Yv/h/bmJmnoKtQm5igW@8QkFRZl6JgoqCRoqCjYqdpp2dbVpOZoFCFRCrKEQb6ukZGsb@BwA "Haskell – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~20~~ 19 bytes
```
n=>((6<<n)+8)/5/~-5
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k5Dw8zGJk9T20JT31S/Ttf0f3J@XnF@TqpeTn66RpqGgaamgr6@goKurp2CgZ45F6qsIZKsIbocUBImZ2ZoomfxHwA "JavaScript (Node.js) – Try It Online")
[Answer]
# JavaScript (ES6), 20 bytes
*Saved 2 bytes thanks to @l4m2*
Does not support Mercury.
```
n=>(5-9-(9-6<<n))/~9
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k7DVNdSV8NS18zGJk9TU7/O8n9yfl5xfk6qXk5@ukaahoGmpoK@voKCrq6dgoGeOReqrCGSrCG6HFASJmdmaKJn8R8A "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES7), 27 bytes
Supports Mercury.
```
n=>(k=5,--k+--k*--k**n)/-~9
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k4j29ZUR1c3WxuItUBYK09TX7fO8n9yfl5xfk6qXk5@ukaahq5nXlpmXmZJpaamgr6@goKurp2CgZ4JF6oqAxRZczRZQyRZQ3Q5oCRMzszQRM/iPwA "JavaScript (Node.js) – Try It Online")
[Answer]
# Java 8, ~~20~~ 18 bytes
```
n->((6<<n)+8f)/''
```
Port of l4m2's C [answer](https://codegolf.stackexchange.com/a/161898/79343), thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). Try it online [here](https://tio.run/##jY09C8IwFEXnZPYHvK0J0qqLCFanrk4dxSEmqaSmr6VJCyL97TF@4KrT43LPPa8Wo0jbTmOtrqEbztZIkFY4BwdhEO6UGPS6r4TUUDwjqWwrPCjjvECpWawB@ZaSiZLPPjY@nrE1CppoYaXvDV6OJxD9xfGXpQAFOwiY7hlb5zny@abii2SWBEKijJQ353WTtYPPujj2FpnKvk@XnP@GVn9Bb2qiU3gA).
# Java 8, ~~30~~ 24 bytes
```
n->(9-5+(9-6<<n))/(5f+5)
```
My original approach; admittedly, it's not very creative. Try it online [here](https://tio.run/##jY09D4IwEIbn8itubENAHTAxohOrE6NxqG0xxXIltJAYw2@v9SOuutzl8j73vC2feGZ7ha28hn48Gy1AGO4cHLhGuCdEo1dDw4WC6nmSxljuQWrnOQpFYwzItgmZE/L5j4mPa7JaQhcttPaDxsvxBHy4OPayVCBhBwGzPd1kRRrHuiyRsQUtmrRggZCoJPXNedXldvR5HxXeIJX5t3rJ2G9o9Rf0puZkDg8).
Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for golfing 6 bytes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-3 thanks to miles (use of `æ«`, bit-shift) ..and -3 more by golfing from there
```
6æ«+8H÷⁵
```
**[Try it online!](https://tio.run/##y0rNyan8/9/s8LJDq7UtPA5vf9S49f///4aGAA "Jelly – Try It Online")**
### How?
```
6æ«+8H÷⁵ - Link: number, N (including -inf)
6 - literal six
æ« - bit-shift = 6*(2^N)
+8 - add eight = 6*(2^N)+8
H - halve = 3*(2^N)+4
⁵ - literal ten
÷ - divide = (3*(2^N)+4)/10
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~18~~ 17 bytes
```
zzrkr^zz+*8z/+A/p
```
[Try it online!](https://tio.run/##S0n@b/i/qqoouyiuqkpby6JKX9tRv@C/oUFAMld0Sp6pRQCGZHJscQiXQXFmdE5mTkhFTqahdkpxprOdU2xKsVPFfwA "dc – Try It Online")
Assuming *n* is all that's on the stack, we get the stack depth twice to push `1` and `2` onto the stack. Reverse these and use the `1` to set our precision (`k`). Reverse so that our stack is now `2 n`, exponentiate (`^`). Use `z` to get stack depth twice, again pushing `1` and `2` onto the stack. Add them (`+`) to get `3`, multiply (`*`) by our previous result. Push `8`, get the stack depth with `z` to push `2`, divide these (`/`) to push `4`. Add this (`+`) to the previous result, and divide by 10 (`A/`). Finally, `p`rint.
Knocked off a byte using `8z/` instead of `zF+v` to make a `4`.
[Answer]
# Google Sheets, ~~27~~ ~~26~~ ~~25~~ 23 bytes
```
~~=((8-5)\*(7-5)^A5+9-5)/(5+5)~~
~~=(9^.5\*(7-5)^A5+9-5)/(5+5)~~
~~=(9^.5\*(7-5)^A5+9-5)\*.7/7~~
=(7-5)^A5*(.8-.5)+.9-.5
```
Take input from cell A5.
For a no-digit version (except the A5 is unavoidable),
```
=(code("")*code("")^a5+code(""))/code("
```
(there is a trailing newline)
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 325 bytes
```
> 8
> 8
> 8
> 8
> 9
> 6
> Input
>> 5-6
>> 5-55
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 7
>> 9+9
>> 9*7
>> 55-56
>> 57⋅58
> 8
> 8
> 8
> 8
> 8
>> 58+55
>> 59+56
>> 66÷65
>> Output 67
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsGCCxVbArEZEHvmFZSWcNnZKZjqmkEoU1MuTOVDAZuD3G@pbQmmtMA8U6B3IN4yf9TdaopDJ1DaQhvkbSDDUhuiwczs8HYzsJB/aQkwiBTMzP//NzQEAA "Whispers v2 – Try It Online")
Let me outline the problem with using Whispers:
Whispers is a single-expression, line-based programming language. Each line consists of a single mathematical expression. However, if the line starts with `>>`, the numbers used have different values to what they would normally express.
When a line begins with `>` (such as `> 8`) the value returned is the number shown, so that example would return `8` when referenced. `Input` returns an evaluated line from STDIN.
However, when the line starts with `>>`, such as `>> 5-6`, the numbers are interpreted as line references, i.e. the above line would call line `5`, then line `6`, then subtract the results.
Let's create a program that half-sticks to the rules first. This program doesn't use `0`, `1`, `2`, `3`, or `4` to represent those numbers, but does use them as line references. This 'half' solution is 96 bytes:
```
> 6
> 9
> Input
>> 2-1
>> 1=1
>> 4-5
>> 6*3
>> 7⋅4
>> 6+6
>> 8+9
>> 2+5
>> 10÷11
>> Output 12
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsGMy07BEog98wpKS7js7BSMdA1BlKEtmDLRNQVRZlrGIMr8UXerCZivbQaiLLQtwVq0wYoMDQ5vNwTr8i8tAZqmYAi0wdAQAA "Whispers v2 – Try It Online")
Unfortunately, the challenge disallows the *characters* `0`, `1`, `2`, `3`, and `4` from appearing in the program, irregardless of what they represent. So, to work around this, we have to use line references with only the numbers `5`, `6`, `7`, `8` and `9` in their digits. This has the consequence that we cannot use any lines between `10` and `54`, which is what the massive chain of `> 8` are. In fact, all lines that represent a forbidden line reference has `> 8`, just for consistency.
So, let's remove those lines, but pretend they're still there, we just can't see them:
```
> 9
> 6
> Input
>> 5-6
>> 5-55
> 7
>> 9+9
>> 9*7
>> 55-56
>> 57⋅58
>> 58+55
>> 59+56
>> 66÷65
>> Output 67
```
Which is a very similar structure to the 'half' solution. Here's how this shortened solution works, with an input `11`:
```
> 9 ; Line 5: Yield 9
> 6 ; Line 6: Yield 6
> Input ; Line 7: Yield a line of input (11)
>> 5-6 ; Line 8: Yield 3 - 9 - 6
>> 5-55 ; Line 9: Yield 2 - 9 - 7
⋮
> 7 ; Line 55: Yield 7
>> 9+9 ; Line 56: Yield 4 - 2 + 2
>> 9*7 ; Line 57: Yield 2048 - 2 ^ 11
>> 55-56 ; Line 58: Yield 3 - 7 - 4
>> 57⋅58 ; Line 59: Yield 6144 - 2048 ⋅ 3
⋮
>> 58+55 ; Line 65: Yield 10 - 3 + 7
>> 59+56 ; Line 66: Yield 6148 - 6144 + 4
>> 66÷65 ; Line 67: Yield 614.8 - 6148 ÷ 10
>> Output 67 ; Line 68: Output 614.8
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 27 bytes
```
l$:?!vll-+$:+!
:*lrl<;n,a+l
```
[Try it online!](https://tio.run/##S8sszvj/P0fFyl6xLCdHV1vFSluRy0orpyjHxjpPJ1E75////7plhoYA "><> – Try It Online")
Some heavy abuse of the stack length command (`l`) command here. Luckily, most of the numbers needed are in ascending order. Takes input through the `-v` flag
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~54~~ ~~42~~ 35 bytes
```
.+
@@@$&$*_@@@@
+`@_
_@@
M`@
.$
.$&
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@by8HBQUVNRSseSDtwaSc4xHMBmVy@CQ5ceipApPb/vwGXIZcRlwmXKZcZlzmXoSEA "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 12 bytes thanks to @Leo. Explanation:
```
.
@@@$&$*_@@@@
```
Generate a pseudo-binary number using `@` as 1 and `_` as `*2`, having `3` as the first digit and `4` as the last digit, thus representing `3*2^n+4`.
```
+`@_
_@@
```
Convert to unary.
```
M`@
```
Convert to decimal.
```
.$
.$&
```
Divide by 10.
[Answer]
# [Raku](https://raku.org/), 13 bytes
```
³+<*/Ⅹ+⅖
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPv/0GZtGy39R60rtR@1TvtvrVCcWKmgpBKvYGunUJ2moBJfq6SQll@kEGdo8B8A "Perl 6 – Try It Online")
This formula uses Unicode characters with the right numeric values to stand in for the forbidden characters.
* ³ - SUPERSCRIPT THREE - value = 3
* Ⅹ - ROMAN NUMERAL TEN - value = 10
* ⅖ - VULGAR FRACTION TWO FIFTHS - value = 0.4
[Answer]
# [Mathics](https://github.com/mathics/Mathics), 34 bytes
```
d[n_]:=((9-6)*(8-6)^n+(9-5))/(5+5)
```
[Try it here!](https://mathics.angusgriffith.com/#cXVlcmllcz1kJTVCbl8lNUQlM0ElM0QoKDktNikqKDgtNiklNUVuJTJCKDktNSkpJTJGKDUlMkI1KSZxdWVyaWVzPWQlNUItSW5maW5pdHklNUQmcXVlcmllcz1kJTVCMCU1RCZxdWVyaWVzPWQlNUIxJTVEJnF1ZXJpZXM9ZCU1QjExJTVE)
My first time golfing in Mathics, so there's probably a bit more optimizing to be done.
[Answer]
# [Symbolic Python](https://github.com/FTcode/Symbolic-Python), ~~69~~ 56 bytes
```
___=_==_
__=-~___
_=__**~-_*-~__+___+___**-___
_/=__-~__
```
[Try it online!](https://tio.run/##K67MTcrPyUzWLagsycjP@/8/Pj7eNt7WNp4LSOvWAXlcQH68lladbrwWiK8dD8FaWrpgSX2gLEj8////hoYA "Symbolic Python – Try It Online") Implements `(3*2^(n-1)+2)/5`
### How?
```
# Input is stored in _ initially
___=_==_ # ___ = True (=1)
__=-~___ # __ = -~1 = 1 + 1 = 2
_=__**~-_*-~__+___+___**-___
# _ = 2**~-_ * -~2 + 1 + 1**-1 = 2**(n-1) * 3 + 1 + 1.0 = 3 * 2**(n-1) + 2.0
_/=__-~__ # _ = _ / (2 -~ 2) = _ / (2 + -~2) = _ / (2 + 2+1) = _ / 5
# Implicit output of _
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
â╬╫▓♠âε
```
[Run and debug it](https://staxlang.xyz/#p=83ced7b20683ee&i=0.0%0A1.0%0A11.0&a=1&m=2)
PackedStax source encoding makes the character restrictions trivial. Unpacked, ungolfed, and commented this is the same program.
```
|2 2 to the power
3* multiply by 3
4+ add 4
A/ divide by 10
```
[Run this one](https://staxlang.xyz/#c=%7C2%092+to+the+power%0A3*%09multiply+by+3%0A4%2B%09add+4%0AA%2F%09divide+by+10&i=0.0%0A1.0%0A11.0&a=1&m=2)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~27~~ 26 bytes
```
lambda n:((6-9<<n)-~-5)/~9
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPSkPDTNfSxiZPU7dO11RTv87yf1p@kUKmQmaeQlFiXnqqhqGpphWXQkFRZl6JRppGpqbmfwA "Python 3 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), ~~38~~ ~~34~~ ~~31~~ ~~28~~ 27 bytes
```
lambda n:((6-9<<n)-9.+5)/~9
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPSkPDTNfSxiZPU9dST9tUU7/O8n9afpFCpkJmnkJRYl56qoahqaYVl0JBUWZeiUKaRqbmfwA "Python 2 – Try It Online")
---
Saved:
* -4 bytes, thanks to Giuseppe
* -1 byte, thanks to Jonathan Allan
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 12 bytes
```
‘⁺
¢*+Ḥ$Ç⁺÷⁵
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw4xHjbu4Di3S0n64Y4nK4XYg7/D2R41b////b2gIAA "Jelly – Try It Online")
About time for an explanation
## How it works
```
‘⁺ - Helper link. Can be called monadically, or niladically.
- When called niladically, `0` is the left argument.
⁺ - Perform the previous command twice:
‘ - Increment the left argument
¢*+Ḥ$Ç⁺÷⁵ - Main link. 1 argument: n
¢* - Yield 2n
$ - Perform the next two commands on 2n:
Ḥ - Halve. Yields 2n-1
+ - Add to 2n. Yields 3⋅2n
Ç - Add 2. Yields 3⋅2n + 2
⁺ - Add 2 again. Yields 3⋅2n + 4
⁵ - Yield 10
÷ - Divide by 10. Yields (3⋅2n + 4)/10
```
[Answer]
# BRASCA, 29 bytes
```
ig$}}:a$^A}:a*A}+:l/ml%mn'.on
```
[Try it!](https://sjoerdpennings.github.io/brasca-online/?code=ig%24%7D%7D%3Aa%24%5EA%7D%3Aa*A%7D%2B%3Al%2Fml%25mn%27.on&stdin=11)
BRASCA only supports whole integers, so I had to spend a couple bytes to at least get one decimal, to pass the test cases.
## Explanation
```
- Implicit input
ig - Turn 0-9 into the actual numbers and concatenate
$}}:a$^ - 2^n
A}:a* - (3*
A}+ - +4)
:l/ - /10
ml%mn'.on - Get the first decimal, and print the number.
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 8 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
ó∙☻√ΓΣ♂/
```
[Try it online.](https://tio.run/##ASUA2v9tYXRoZ29sZv//w7PiiJnimLviiJrOk86j4pmCL///MAoxCjEx)
Actually the same amount of bytes as the straight-forward approach without [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'"):
```
ó3*4+♀√/
```
[Try it online.](https://tio.run/##y00syUjPz0n7///wZmMtE@1HMxsedczS///fgMuQy9AQAA)
**Explanation:**
```
ó # Take 2 to the power of the (implicit) input-integer
∙ # Triplicate it
☻ # Push 16
√ # Take the square-root of that: 4.0
Γ # Wrap the four values on the stack into a list
Σ # Sum this list together
♂/ # Divide it by 10
# (after which the entire stack is output implicitly as result)
ó # Take 2 to the power of the (implicit) input-integer
3* # Multiply it by 3
4+ # Add 4
♀√/ # Divide it by the square-root of 100 (10.0),
# since `/` will be integer-division if both arguments are integers
# (after which the entire stack is output implicitly as result)
```
[Answer]
# C# .NET, 18 bytes
```
n=>((6<<n)+8f)/''
```
`''` is an unprintable ASCII character with value `20`.
Port of [*@l4m2*'s C answer](https://codegolf.stackexchange.com/a/161898/52210).
[Try it online.](https://tio.run/##jcyxCsIwEIDhPbMPcFsT1KqLCE27CE52cnAOMYGD9AK9UxDps0cExVH37/89L30eQ/HJMUP/UAAsTtDD6c4ShvpwJW@RZAExZScdRGihUNtpvbWWzHwXzaqaVaVR3/aW8QK9Q9LmdYTPbJ@Jcwr1eUQJR6Sgo14b0/wym3/MG01qKk8)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes
```
->n{6-5.6+6%5.7*(9-7)**n}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6v2kzXVM9M20zVVM9cS8NS11xTSyuv9n9BaUmxQlq0QSwXlGWIYBnG/gcA "Ruby – Try It Online")
Output ±ε due to float imprecision.
[Answer]
# Whispers v2, 91 bytes
```
> Input
>> 9*56
>> 57⋅8
>> 58+7
>> 59÷6
> 5
>> ≺6
>> ≺7
>> ≺8
>> 5÷9
>> Output 65
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hMvOTsFSy9QMRJuaP@putQCzLLTNwbTl4e1AKQVTEOdR5y4zKG0OpSGKD2@3BNH@pSVAAxXMTP//NzQEAA)
[Answer]
# Lua, 55 bytes
```
o=#" "t=o+o function x(m)return((o+t)*t^m+t^t)/(5*t)end
```
[Try it online!](https://tio.run/##TccxCoAwDAXQ3VMUXRI7qINjr1IQrSBoIuUXevvoIri9d5bFTEPXuhZBvbq9yIpDxVW6OCeULETqwT3i5RHBA809OMlmdz4EVGlkbj5Pf7@xBw)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 38 bytes
```
(.9-.6)*[math]::pow(8-6,"$args")+.9-.5
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0PPUlfPTFMrOjexJCPWyqogv1zDQtdMR0klsSi9WElTGyRv@v//f0NDAA "PowerShell – Try It Online")
-11 bytes thanks to @mazzy
[Answer]
# [Scala](https://www.scala-lang.org/), 41 bytes
A port of [@O.O.Balance's answer](https://codegolf.stackexchange.com/a/161892/110802).
[Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnUM2loJCSmqaQC@RoJBalF1spOBYVJVZGB5cUZealx2paKYTmZZYo2CpU/y9LzFFIsfLMK7G1c8vJTyyxzbO107DUNdUGEmY2Nnmamvoapmnappr/FYCAC0QUAA0pycnTSNEw0NREEzHEFIEI1XLV/gcA)
```
val d:Int=>Float=n=>(9-5+(9-6<<n))/(5f+5)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
à╙i;?«°☻
```
[Run and debug it](https://staxlang.xyz/#p=85d3693b3faef802&i=0%0A1%0A11&m=2)
I think this is a little bit unfair because the original code contains digits, but PackedStax doesn't... here's what it unpacks to:
# [Stax](https://github.com/tomtheisen/stax), 9 bytes
```
|23*4+A:_
```
[Run and debug it](https://staxlang.xyz/#c=%7C23*4%2BA%3A_&i=0%0A1%0A11&m=2)
```
|23*4+A:_
|2 # 2**n
3* # *3
4+ # +4
A:_ # float divided by 10
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
ET⇧⇧₀/
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJFVOKHp+KHp+KCgC8iLCIiLCIwIl0=)
`₀` != `0`
## Explained
```
ET⇧⇧₀/
E # 2 ** n
T # * 3
⇧⇧ # + 2 + 2
₀/ # divided by 10
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2/tree/main), 8 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ODḌ+ƙƙT/
```
Port of [Emigna's 05AB1E answer](https://codegolf.stackexchange.com/a/161886/114446).
#### Explanation
```
ODḌ+ƙƙT/ # Implicit input
O # Push 2 ** input
DḌ # Duplicate and double
+ # Add (triple)
ƙƙ # Add 2 twice (add 4)
T/ # Divide by ten
# Implicit output
```
---
**Screenshot:**
[](https://i.stack.imgur.com/S6NXR.png)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 13 bytes
```
U(U Ea*@PI)/t
```
Contains no digits at all. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZrQzVCFVwTtRwCPDX1SyBiUKkl0YaGsVA2AA)
### Explanation
Uses a slightly modified formula:
$$\frac{3\cdot(2^n+1)+1}{10}$$
```
U(U Ea*@PI)/t
a ; Command-line input
E ; 2 to that power
U ; Increment
* ; Times
@PI ; the first character of pi
U( ) ; Increment that result
/t ; Divide by 10
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/41626/edit).
Closed 2 years ago.
[Improve this question](/posts/41626/edit)
The aim of this challenge is to write a program that satisfies the following conditions:
* The program is not palindromic, or essentially palindromic (meaning that it is possible to remove characters to make it a palindrome without changing the effects of the program).
* The program is not an involution (meaning that it does not produce its original input when run on its output)
* The **reversed-polarity** program is the inverse of the normal program; so when the reversed program is run on the output of the normal program, it returns the original input.
What does **reversed-polarity** mean? Well, it differs between languages.
* For most non-esolangs, this means reversing the order of sub-operations in a single operation, reversing the order of arguments, and reversing the contents of hard-coded lists/arrays/tuples/dictionaries/stacks/queues/etc, as well as reversing the order of code-blocks and stand-alone lines (but not lines within blocks)
Examples:
**Haskell**:
`x`mod`y` -> `y`mod`x`;`zipWith ((*3).(+)) [1,2,3] [4,5,6]` -> `zipWith ((+).(*3)) [6,5,4] [3,2,1]`
**Python**: `2**3` -> `3**2`; `for x,y in [(1,2),(3,4),(5,6)]` -> `for y,x in [(6,5),(4,3),(2,1)]`
* For languages that have 1-character functions (like Pyth, APL), simply reverse the string of instructions
* For 1-dimensional esolangs like BF, reverse the instructions **or** swap the polarity; polarity swaps are `[]` -> `{}`, `+` -> `-`, `-` -> `+`, `>` -> `<`, `<` -> `>`, `.` -> `,` and `,` -> `.` (but not both)
* For 2-dimensional esolangs like Befunge, you may either perform a reflection across the x- or y- axes or a diagonal, rotate 180 degrees, or do a combination of a reflection and a rotation
Commutative operations are allowed, but palindromic ones are not: `2*x` is fine, but `x+x` is bad. The definition of a polarity-reversal is pretty loose, but use your judgment as to what makes sense; the object isn't to find the most clever loophole, but to find the most clever solution.
This is a popularity contest, so a very clever loophole may be popular, but try to keep within the spirit of this challenge. The winner will be announced once there are at least 10 solutions with at least 1 upvote, and there is at least one solution with more upvotes than there are submissions with at least 1 upvote; or in 1 month, whichever comes first. This is my first challenge, so try to be fair and give me constructive feedback, but also let me know if this is an unreasonable challenge or it is in any way miscategorized or ambiguous. If you have questions about a language that don't fit into any of the pigeonholes I have set out here, comment, and I will bend to the will of the community if there is a strong outcry for a particular clarification or rule-change.
# UPDATE
It has been exactly 1 month since this contest was started (I just happened to check on it by chance, not knowing that I was actually on time). As this is a popularity contest, the winner (by a landslide) is
[Pietu1998-Befunge](https://codegolf.stackexchange.com/a/41651/31387). Even though the bottom components (the text reverser and the backwards-alphabet) are both involutions, the encoder/decoder are not, so there is no problem there. Bonus points (in my mind) for managing to write "BEFUNGE" down the middle. I personally liked the novelty of [Zgarb's Theseus solution](https://codegolf.stackexchange.com/a/41699/31387), because the language looks cool (if restricted). Thanks to everyone for participating, and while the winner has been chosen, I am leaving this contest completely open, and welcome future submissions.
[Answer]
# [Befunge](http://esolangs.org/wiki/Befunge)
Whoa, that was a job, even with the [editor I made](http://pietu1998.net/pages/en/programming/complete/mirroreditor.html) for this challenge. Here's what I got, a nice 11x12 block:
```
v$,g6<6g,$v
v,$ _^_ $,v
1W>v\B\v>L1
~T+:1E1:-O~
+F00-F-02L+
>:|6gUg6|:>
{a@>^N^>@z`
>1+|@G$| +>
:^9< E< ^1
~>7^@_,#:>:
xD>65 ^=P~
v,-\+**< v
```
It does a couple of things, sadly only for lowercase letters.
## What it does
When run normally, it performs a [Caesar cipher](http://en.wikipedia.org/wiki/Caesar_cipher) on the input.
```
abcxyz -> bcdyza
exampletext -> fybnqmfufyu
```
When flipped horizontally, it reverses said cipher. This is the requirement for the challenge, but it doesn't end here.
```
bcdyza -> abcxyz
fybnqmfufyu -> exampletext
```
When flipped *vertically*, it ciphers input with a reverse alphabet. This can be considered the opposite approach to the Caesar cipher.
```
abcxyz -> zyxcba
exampletext -> vcznkovgvcg
```
Finally, when rotated 180 degrees, it reverses input. I have a feeling it has to be a reverse of something (hint: the input).
```
abcxyz -> zyxcba
exampletext -> txetelpmaxe
```
## How it works
The block basically consists of four semi-overlapping algorithms.
### Caesar cipher encoder
```
v$,g6<
v,$ _^
1 >v\
~ +:1
+ 00-
>:|6g
{a@>^
```
### Caesar cipher decoder (flipped horizontally)
```
v$,g6<
v,$ _^
1 >v\
~ -:1
+ 20-
>:|6g
`z@>^
```
### Reverse alphabet cipher (flipped vertically)
```
v,-\+**<
>65 ^
~>7^
:^9<
>1+|@
>^
```
### Text reverser (rotated 180 degrees)
```
v <
~
:>:#,_@
1^ <
>+ |$
>^
```
[Answer]
# Brainfuck, 5
```
,+.-,
```
Possibly for the first time ever, Brainfuck produces an answer that is competitive on code length. Shame it's not a code-golf question.
Inputs a byte (character) , increments it, and outputs the result. The comma at the end is waiting for another input, which if given will be ignored. There is nothing in the spec about proper termination :-)\*
\*(or about doing something useful with all the code in both directions)
**Typical results (second character if given is ignored).**
Forward: `B` --> `C`
Reverse: `B` --> `A` or `C` --> `B`
[Answer]
# [Marbelous](https://github.com/marbelous-lang/docs/blob/master/spec-draft.md)
Here is a simple one to start us off. It reads one character from STDIN, increments and prints it.
```
--
]]
00
]]
++
```
If we rotate this by 180° (without swapping brackets), or mirror it in the x-axis, we get
```
++
]]
00
]]
--
```
which reads a byte from STDIN and decrements it.
You can [test it here](https://codegolf.stackexchange.com/a/40808/8478).
I might look into some more complicated Marbelous programs, but I'm sure es1024 will beat me to it. ;)
## Explanation
The `00` is a marble with value 0 (which is arbitrary). The `]]` devices read a byte from STDIN - that is, if a marble falls through them, the marble's value is changed into the read byte. The `++` and `--` devices simply increment or decrement a marble's value (mod 256) and let it fall through. When a marble falls off the board, the byte is written to STDOUT.
Therefore, the two devices at the top are simply ignore because control flow never reaches them.
[Answer]
# [Marbelous](https://github.com/marbelous-lang/docs/blob/master/spec-draft.md)
This board takes one argument (`x`) and returns `(101 * x) mod 256`.
```
.. @5 .. }0 }0 @1 .. @0 .. @2 ..
.. /\ Dp << \\ .. &0 >0 &1 .. ..
!! @3 .. << }0 .. \/ -- \/ .. }0
@4 .. .. &0 @1 /\ &0 65 &1 /\ @2
/\ Dp .. @4 .. .. @3 @0 @5 !! \\
```
Mirroring the **cells** along the y-axis will result in a board that takes one argument (`y`) and returns `(101 * y + 8 * y) mod 256`, which is the inverse of the first board.
```
.. @2 .. @0 .. @1 }0 }0 .. @5 ..
.. .. &1 >0 &0 .. \\ << Dp /\ ..
}0 .. \/ -- \/ .. }0 << .. @3 !!
@2 /\ &1 65 &0 /\ @1 &0 .. .. @4
\\ !! @5 @0 @3 .. .. @4 .. Dp /\
```
[Test this here](https://codegolf.stackexchange.com/a/40808/8478). Cylindrical boards and Include libraries should both be checked.
**Example input/output**:
```
Original Board: Mirrored Board:
Input Output Input Output
025 221 221 025
042 146 146 042
226 042 042 226
```
Please note that Marbelous only allows for passing of positive integers as arguments, and these integers are passed into the program modulo 256 by the interpreter.
`101` was chosen for two reasons: it is a prime (and every possible input to this program results in a unique output), and the inverse operation involved `109`, which is a convenient distance of 8 away from `101`.
## Brief Explanation
The column containing the cells (from top to bottom) `@0 >0 -- 65 @0` runs the same in both boards, and loops `101` times before heading to the right. On either side of the `>0` branch is a different synchroniser; which one is chosen depends on whether the board is mirrored or not.
On each side, in sync with the center loop, the input is repeatedly summed, thus obtaining `101*x mod 256`. On the reversed board, two copies of the input are also bit shifted twice to the left (`input * 4`), then summed and left in a synchroniser.
Once the center loop finishes, the summed up marbles are sent for printing, which is on the side of the board (left for original board, right for mirrored). After printing, a `!!` cell is reached, terminating the board. Note that the loop that gave `101 * x` continues to run by itself until the board is terminated.
`Dp` simply prints out the result as a decimal number.
[Answer]
# Theseus
This may be considered as a loophole, but I like the language, so here goes. This program defines a function `f` on natural numbers that maps *3n* to *3n+1*, *3n+1* to *3n+2*, and *3n+2* to *3n*, for every *n*.
```
data Num = Zero | Succ Num
iso f :: Num <-> Num
| n <-> iter $ Zero, n
| iter $ m, Succ Succ Succ n <-> iter $ Succ m, n
| iter $ m, Succ Succ Zero <-> back $ m, Zero
| iter $ m, Succ Zero <-> back $ m, Succ Succ Zero
| iter $ m, Zero <-> back $ m, Succ Zero
| back $ Succ m, n <-> back $ m, Succ Succ Succ n
| back $ Zero, n <-> n
where iter :: Num * Num
back :: Num * Num
```
[Theseus](https://bitbucket.org/roshanjames/theseus) is a reversible language with a Haskell-like syntax, where every function is invertible (discounting issues with non-termination). It is highly experimental, and designed for research purposes. The above code defines a datatype for natural numbers, and the function `f`. Given an input number, you pattern-match to it on the left-hand side (it always matches `n`). Then you look at the pattern on the right. If that pattern has a label (here `iter`), you proceed to pattern-match it on the left-hand side, and again take the corresponding value on the right-hand side. This repeats until you have an unlabeled value on the right, and that is your output. The patterns on the left, and on the right, must be exhaustive and non-overlapping (separately for each label). Now, to "reverse the polarity" of `f`, I do the following.
* Swap the two values of every label. This does not change the semantics of `f`.
* Swap the right- and left-hand-sides in the function body. This defines the inverse function of `f` *by design*.
The result:
```
iso f :: Num <-> Num
| iter $ n, Zero <-> n
| iter $ n, Succ m <-> iter $ Succ Succ Succ n, m
| back $ Zero, m <-> iter $ Succ Succ Zero, m
| back $ Succ Succ Zero, m <-> iter $ Succ Zero, m
| back $ Succ Zero, m <-> iter $ Zero, m
| back $ Succ Succ Succ n, m <-> back $ n, Succ m
| n <-> back $ n, Zero
where iter :: Num * Num
back :: Num * Num
```
[Answer]
# tr
```
a b
```
**Example:**
```
$ echo "apple" | tr a b
bpple
$ echo "bpple" | tr b a
apple
```
Only a true inverse on the domain of strings that don't include both 'a' and 'b'.
[Answer]
# Another [Marbelous](https://github.com/marbelous-lang/docs/blob/master/spec-draft.md) answer
The original right shifts the command line input (an 8 bit value), adding a leading one if a 1 gets lost by shifting. (`0000 0001 -> 1000 0000`)
```
{0 ..
~~ ..
>> {0
-2 =0
.. ^0
\/ }0
}0 Sb
<< ..
\\ ..
:Sb
// ..
Sb >>
}0 ..
^7 }0
{0 \/
```
Rotating this board by 180° (but leaving the content of each cell the same) Changes the program so that it left shifts (`1000 0000 -> 0000 0001`)
```
\/ {0
}0 ^7
.. }0
>> Sb
.. //
:Sb
.. \\
.. <<
Sb }0
}0 \/
^0 ..
=0 -2
{0 >>
.. ~~
.. {0
```
You can [test it here](https://codegolf.stackexchange.com/a/40808/8478). (you'll need to turn on 'Display output as decimal numbers')
## Explanation
Both program consist of two boards, the main board (which gets the command line input) and `Sb`. Lets have a look at both versions of the main board, only looking at cells that can be reached in their respective orientation (since marbles typically can't go upwards and the input devices are not at the top):
```
original: flipped:
}0 }0
}0 Sb .. }0
<< .. >> Sb
\\ .. .. //
```
Those are pretty straightforward boards, both take two copies of the input (which take the place of the `}0`cells. The original feeds one version into a left shift device `<<` the flipped version puts it in a right shift device `>>` These perform a bitshift but unfortunately discard any lost bits. Which is where the `Sb` boards come in, they check if bitshifting the value they're fed will result in a bit being lost and return a value to be added to the result to counteract the lost bit.
Here's the relevant part of the original `Sb`board for the original program:
```
}0
^7
{0
```
This one is incredibly easy, `^7' checks the value of the most significant bit. If this one is 1, performing a left shift would cause this bit to be lost. So this board outputs the value of this bit as an 8 bit value to be added to the result of the bitshift.
For the flipped version, `Sb`has to look at the least significant bit and return `128` or `0`, this is a little bit more complicated:
```
}0
^0 ..
=0 -2
{0 >>
.. ~~
.. {0
```
If the least significant bit (as tested by `^0`) is 0, it just returns 0. If it is one, `^0` will output `1`. This will fail the equality test with `0` `=0` and thus be push to the right. We then subtract 2 `-2`to get 255, left shift `>>` to get 127 and perform a binary not `~~` to get 128 (we could also simply have added one `++` to get 128, but where's the fun in that?)
] |
[Question]
[
(This is [OEIS A057531](https://oeis.org/A057531).)
### Your task
Given a positive integer, \$n\$, find the \$n\$th number where the digit sum equals the number of factors
### Explanation
For example, let's take 22:
Its factors are \$[1, 2, 11, 22]\$ (length: 4).
Its digit sum is 4.
This means that it is a number where the digit sum equals the number of factors.
### The series
The first few terms of this series are:
\$[1, 2, 11, 22, 36, 84, 101, 152, 156, 170]\$
### Test cases
Note: these are 1-indexed. You may use 0-indexing.
```
Input Output
1 1
2 2
3 11
4 22
5 36
10 170
20 444
30 828
40 1111
50 1548
100 3588
```
### Clarifications
* **You may use either 0-indexing or 1-indexing**
* The sequence starts from 1, not from 0
* The factors of a number include 1 and the number itself
* **Default [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply** - you may output the first \$n\$ terms, or the infinite sequence, or something else
* **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!**
[Answer]
# [Factor](https://factorcode.org/) + `lists.lazy math.unicode project-euler.common`, 54 bytes
```
[ 1 lfrom [ dup >dec 48 v-n Σ swap tau* = ] lfilter ]
```
[Try it online!](https://tio.run/##TU/NSsNAEL73KT6vYjYWFGzEQi9KQHopnkoJ62byY/eP3UlLfR3fx1eKm@bibWa@32mkYhfGj125fSug@8hRaPl9wZGCJQ0juRNehkhhnk80CeK8DLZXrib44L7SPaNBUxDKGePsbJYgYr740FvGM8ptgdbpZrF5Lze7AuuaFOxgPimsIydSC9zg9VoK92K1QpYhEqFj9rHI89qpKJorPiULF9pcOctkOT@7UGdV1XJVJdu7f9VFx0YvFsvHcY8ldBOcwR714OcCD084ZRa/P4hn6cFyuMULDonYa06PH0YltYZmeaSkExNEUnXjHw "Factor – Try It Online")
Returns an infinite lazy list of the sequence.
* `1 lfrom` The natural numbers
* `[ ... ] lfilter` Take the ones where...
* `>dec 48 v-n Σ` Digit sum
* `tau*` Divisor count
* `=` Are equal
[Answer]
# [Raku](https://raku.org/), 39 bytes
```
grep {.comb.sum==grep $_%%*,1..$_},1..*
```
[Try it online!](https://tio.run/##K0gtyjH7n1up4FCsYPs/vSi1QKFaLzk/N0mvuDTX1hYsoBKvqqqlY6inpxJfC6K0/lsrFCdWKihVAwUUbO2AeqNV4nUNY5UU0vKLFGo0gGpMNXVADAMdIwM9IM9A8z8A "Perl 6 – Try It Online")
This is an expression for the lazy, infinite sequence of values.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 44 bytes
```
for(i=1,oo,sumdigits(i)-numdiv(i)||print(i))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN3XS8os0Mm0NdfLzdYpLc1My0zNLijUyNXXzQJwyIKumpqAoM68EyNKE6IFqhRkBAA)
Prints the sequence forever.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
1DS=ÆdƲ#
```
[Try it online!](https://tio.run/##y0rNyan8/9/QJdj2cFvKsU3KQLYBAA "Jelly – Try It Online")
Takes \$n\$ on STDIN, and outputs the first \$n\$ values.
## How it works
```
1DS=ÆdƲ# - Main link. Takes no arguments
Ʋ - Group the previous 4 links into a monad f(k):
D - Digits of k
S - Sum
Æd - Divisor count of k
= - Are they equal?
1 # - Read n from STDIN and find the first n k≥1 such that f(k) is true
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 66 bytes
```
(k=t=0;While[k<#,If[Tr[1^Divisors@++t]==Tr@IntegerDigits@t,k++]])&
```
[Try it online!](https://tio.run/##Dce9CoMwEADgVykIouSgF38mDWRwcesgdAgphJLGI9VCPLqUPnvab/s2x6vfHNPd5aByFRUrHK4rPb2JYwHzwyzJyNtEbzpe6dBCsFVqSXre2QefJgrEh2aIQlhbl7kKuhguiXbWXJdnffpIaKCFDnqQCA1Ci9Ah9PgvfnP@AQ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~55~~ 51 bytes
-4 bytes thanks to [G B](https://codegolf.stackexchange.com/users/18535/g-b)
```
1.step{|a|a.digits.sum==(1..a).count{a%_1<1}&&p(a)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN40N9YpLUguqaxJrEvVSMtMzS4r1iktzbW01DPX0EjX1kvNL80qqE1XjDW0Ma9XUCjQSNWshWqEmwEwCAA)
[Answer]
# [Python 3](https://docs.python.org/3/), 69 bytes
```
n=1
while sum(n%~d//n+n//10**-~d*9for d in range(n))or[print(n)]:n+=1
```
[Try it online!](https://tio.run/##NY1BCsIwFET3OcVshKRFkurKQryIuBCS2ID9v6QR202vHm2Lsxkej2GGOXdM58JDipRhsbUIiXuM84jYD5wy/BSzcD7sWk6qFfiF/7hRDJhwxckYs@s161IaVcg24tPFl8f47iUdFqc11aR1Y6rquLjqEjjBIRLSg55eklKcbvsBqXtLtW1K@QI "Python 3 – Try It Online")
Would print forever if I hadn't doctored the print function in the preamble.
Based on @Arnauld's answer.
This uses two additional little tricks:
1. sum d=1..n n%-d // n equals number of divisors - n
2. sum d=1.. n // 10d x 9 equals n - digit sum
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~60 59~~ 58 bytes
Prints the sequence 'forever' (that is, until the call stack overflows).
```
for(n=0;g=d=>d&&!(n%d--)-~~(n+g)[d]+g(d);)g(++n)||print(n)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPP1sA63TbF1i5FTU1RI081RVdXU7euTiNPO10zOiVWO10jRdNaM11DWztPs6amoCgzr0QjT/P/fwA "JavaScript (V8) – Try It Online")
### Commented
We use a recursive function which simultaneously counts the number of divisors and subtracts the sum of the digits.
```
for( // infinite loop:
n = 0; // start with n = 0
g = d => // g is a recursive function taking a divisor d
d && // stop if d = 0
!(n % d--) - // add 1 if d is a divisor of n
~~(n + g) // coerce n to a string with some additional
// non-digit characters
[d] + // subtract the d-th digit (0 if out of bounds)
g(d); // add the result of a recursive call
) //
g(++n) // increment n; initial call to g with d = n
|| print(n) // print n if the result is 0
```
---
# [Python 3](https://docs.python.org/3/), 78 bytes
*-1 thanks to [@Mukundan314](https://codegolf.stackexchange.com/users/91267/mukundan314)*
A port of my [initial JS code](https://codegolf.stackexchange.com/revisions/254912/4). Most probably sub-optimal.
```
f=lambda d,v:d and(n%d<1)-v%10+f(d-1,v//10)
n=1
while 1:f(n,n)or print(n);n+=1
```
[Try it online!](https://tio.run/##BcFBCoAgEAXQfadwEygqNbSzPIwxSYF9RcLo9PZe@Z4zY@k9@hTunYNg0xyLAJYYeSNl20izjpItmTZNNKsBnob3vNIhyEUJA5WrKPXCI6FWaE@9/w "Python 3 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Èâ ʶXìx}iU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yOIgyrZY7Hh9aVU&input=MTAw)
```
Èâ ʶXìx}iU :Implicit input of integer U
È :Function taking an integer X as argument
â : Divisors
Ê : Length
¶ : Equal to
Xì : Digit array
x : Reduced by addition
} :End function
iU :Get the Uth integer >=0 that returns true
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
KLn∑=)ȯ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJLTG7iiJE9KcivIiwiIiwiMjAiXQ==)
```
ȯ # First n integers
-----) # Where...
L # Length of
K # Factor count
= # Equals
n∑ # Digit sum
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
NθW‹№υ¹θ⊞υ⁼ΣLυΣEυ¬﹪Lυ⊕λI⊖Lυ
```
[Try it online!](https://tio.run/##Rc1NCsMgEAXgfU7hcgS7KGSXZdpFoAmBnsCaoQaMxp9pj2@VLpzde3y8UVoG5aTJebInpYWOFwbwfOi@ejfI4IExwujIJiDBrlwwzzlbKeqa756kifCko0D7TqXkhdQ8y7OKxSWY3UbGNSHYZFXAA23CDQz/39CtYS9vRhkT3LCBtlxQzn2@fMwP "Charcoal – Try It Online") Link is to verbose version of code. Outputs the `n`th term. Explanation:
```
Nθ
```
Input `n`.
```
W‹№υ¹θ
```
Repeat until `n` terms have been found.
```
⊞υ⁼ΣLυΣEυ¬﹪Lυ⊕λ
```
Determine whether the current length of the predefined empty list is a member of the sequence, and push the result to the predefined empty list. Note that this has been written in such a way that it thinks `0` is not a member of the sequence, although an alternative interpretation could have included it.
```
I⊖Lυ
```
Output the index of the last element in the list, which is therefore the `n`th term. (At a cost of 1 byte, this could be `I⌕Aυ¹` to output the first `n` terms.)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 68 bytes
```
K`
"$+"{`^
_
{`^
_$'¶$.'¶
\d
*
w`\b(_+)(?=\1*$)
_
_(¶_+)\1$
))0G`
_
```
[Try it online!](https://tio.run/##K0otycxLNPz/3zuBS0lFW6k6IY4rngtMqqgf2qaiByS4YlK4tLjKE2KSNOK1NTXsbWMMtVQ0gcriNQ5tA4rEGKpwcWlqGrgncMX//28CAA "Retina – Try It Online") No test suite due to the way the program uses history. Explanation:
```
K`
```
Clear the buffer.
```
"$+"{`
)`
```
Repeat the original input number times.
```
^
_
```
Increment the value in the buffer.
```
{`
)`
```
Repeat until the buffer stops changing.
```
^
_$'¶$.'¶
```
Make three copies of the buffer; increment the first, and convert the second to decimal.
```
\d
*
```
Convert each digit separately back to unary, thus computing the sum of the digits.
```
w`\b(_+)(?=\1*$)
_
```
Count the number of factors in the current value.
```
_(¶_+)\1$
```
If the digit sum equals the factor count then decrement the first value again, causing the inner loop to exit.
```
0G`
```
Keep only the first value.
```
_
```
Convert the final value to decimal.
[Answer]
# [Python](https://www.python.org), ~~80~~ 77 bytes
```
i=1
while[sum(map(int,str(i)))-sum(i%-~j<1for j in range(i))or print(i)]:i+=1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwc3gzNyC_KISheLM9LzEHC4IpQehNKC8YE93R58gXx2FnMTcpJREhXhDHYV4IyuF1IrMEg0DTU2YrsScxKJcDWPNpaUlaboWN30zbQ25yjMyc1Kji0tzNXITCzQy80p0ikuKNDI1NTV1QYKZqrp1WTaGaflFClkKmXkKRYl56akgaaBAQRFQOZAda5WpbWsIMXQBlILSAA)
-3 bytes thanks to [@Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)
[Answer]
# Excel (ms365), 170 bytes
```
=INDEX(REDUCE(0,ROW(1:1048576),LAMBDA(a,b,IF(COUNT(REDUCE(0,SEQUENCE(b),LAMBDA(x,y,IF(MOD(b,y),x,VSTACK(x,y)))))-1=SUM(--MID(b,SEQUENCE(LEN(b)),1)),VSTACK(a,b),a))),A1+1)
```
Here `ROW(1:1048576)` will represent `n` and is the extend to which Excel can go (max rows). You'll notice that calculation wise the nesting will likely not compute but to be fair to the challenge of any possible positive integer I had to include this number. 'Much easier' to compute and able to calculate any of the given samples would be `ROW(1:3588)`:
[](https://i.stack.imgur.com/s2Z0b.png)
What happens is:
* The outer `REDUCE()` will cycle through all possible integers in Excel-rows. It will `VSTACK()` any integer which follows the following rule;
* The inner `REDUCE()` will `VSTACK()` all integers in iteration if they equal zero when `MOD()` is applied **and** the `SUM()` of the numbers used in the integer equals the `COUNT()` of these stacked integers (I hope that is clear);
* `INDEX()` will then return a zero-based (hence the `+1)` integer from the `VSTACK()`. If you wish to return an array of the 1st n integers:
```
=DROP(TAKE(REDUCE(0,ROW(1:500),LAMBDA(a,b,IF(COUNT(REDUCE(0,SEQUENCE(b),LAMBDA(x,y,IF(MOD(b,y),x,VSTACK(x,y)))))-1=SUM(--MID(b,SEQUENCE(LEN(b)),1)),VSTACK(a,b),a))),A1+1),1)
```
[](https://i.stack.imgur.com/CDRvT.png)
[Answer]
# x86-64 machine code, 39 bytes
```
31 C0 FF C0 31 F6 6A 0A 59 50 99 F7 F9 29 D6 01 C2 75 F7 58 89 C1 50 F7 F9 58 83 EA 01 99 11 D6 E2 F4 19 D7 79 DC C3
```
[Try it online!](https://tio.run/##XVLBbpwwED3jr5hSrQS7EC2bNlJ2s8kh515yqtT0YGwDjsCm2KTeRvvroWMgNM1l8Lx582b8DEtLxobhs1Ss7rmAG2O51BfVLfkPqmX@EeukKj1GpLJQRD7S@ECoaSCChzAiF2Wtc1pDQYo9CZzuQFCX@ECUcFb1DcIoOCJT3cjEBxK0vakg2x6g1S10zM1Ih0wuS2lrrVvsZvwXSnD5DMJzTJ/PGhwzyrk/TBODJ/UHllaU87oeb/TYPLEKyqzuZvFl4rsJS9s4yotn8xaUs3ezvQT8U0N@7vlv5SdlYPaABJ2wJA4BvRutbKhUk5tdyRJgFe1gvcbkOSYv3jALDo6QZgmc8Ls9kOB3JWsB0Wbj4OYIuywmATIDXx6R7Aru8LSfst12zNboL6SQfc2wcH2NMkGLb2qLKFxJSG9hJR9ViEMSfN1TjOsFZ7JQHtU3yiqpBDDNxT70ZTevwzW8vPFgtd199yrHKOqVkaUSfLzTOi7iH26z@RkfzjBf4ASfUMHdX3q1RSHCdfKTFSYe93G@iJ71nfLTzmQYXllR09IMaXP1BQP@gkfsFfVf "C (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes a number `n` in EDI and returns the 0-indexed `n`th number where the digit sum equals the number of factors in EAX.
In assembly:
```
f: xor eax, eax # Set EAX to 0. EAX will be the number currently being tested.
nextnum:
inc eax # Increase EAX by 1.
xor esi, esi # Set ESI to 0.
push 10; pop rcx# Set RCX (the 64-bit register containing ECX) to 10.
push rax # Save the value of RAX (containing EAX) onto the stack.
digitloop:
cdq # Set EDX to 0 by sign-extending EAX.
idiv ecx # Divide EDX:EAX by ECX (10).
# The quotient goes in EAX and the remainder goes in EDX.
sub esi, edx # Subtract EDX (the remainder; a digit of the number) from ESI.
add edx, eax # Add EAX to EDX.
jnz digitloop # Jump back if the result of the addition is nonzero.
# This loop will exit when the quotient and remainder are both zero.
# This performs one more iteration than otherwise necessary,
# so that EDX will be 0 after the loop, which will be useful later.
pop rax # Restore the value of RAX from the stack.
mov ecx, eax # Set ECX to the same value, the number being tested.
# (The higher bits of RCX are automatically zeroed.)
factorloop:
push rax # Save the value of RAX onto the stack.
idiv ecx # Divide EDX:EAX by ECX; quotient in EAX, remainder in EDX.
pop rax # Restore the value of RAX from the stack.
sub edx, 1 # Subtract 1 from EDX. The carry flag CF becomes 1 iff EDX=0.
cdq # Set EDX to 0 by sign-extending EAX.
adc esi, edx # Add EDX+CF to ESI, increasing it by 1 with each factor found.
loop factorloop # Decrease RCX by 1, and jump back if it's nonzero.
sbb edi, edx # Subtract EDX+CF from EDI.
# 1 is the last value checked, and it is always a factor.
# Thus, the last ADC added 1 to ESI, and CF=1 iff ESI went
# from -1 to 0; iff the number satisfies the condition.
jns nextnum # Jump back if the result is nonnegative.
ret # Return.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞ʒÑgySOQ
```
Outputs the infinite sequence.
[Try it online.](https://tio.run/##yy9OTMpM/f//Uce8U5MOT0yvDPYP/P8fAA)
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
ʒ # Filter it by:
Ñ # Get a list of divisors of the current integer
g # Pop and push its length
yS # Push the current integer again, and convert it to a list of digits
O # Take the sum of those digits
Q # Check if the amount of digits equals the digit-sum
# (after which the filtered infinite list is output implicitly as result)
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 10 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
î·─£\Σ=╛p▲
```
Outputs the infinite sequence, with each term on a separated line.
[Try it online.](https://tio.run/##ASAA3/9tYXRoZ29sZv//w67Ct@KUgMKjXM6jPeKVm3DilrL//w)
**Explanation:**
```
▲ # Do-while true with pop:
î # Push the 1-based loop index
· # Quadruplicate it
─ # Pop one, and get a list of its divisors
£ # Pop this list, and get its length
\ # Swap to put another 1-based index at the top of the stack
Σ # Sum its digits
= # Check if the amount of divisors and sum of digits are equal
╛ # If this is truthy:
p # Print a 1-based index with trailing newline
```
[Answer]
# [R](https://www.r-project.org/), 53 bytes
```
while(F<-F+1)sum(F%/%10^(0:F)%%10,-!F%%1:F)||print(F)
```
[Try it online!](https://tio.run/##FYpNCoMwEIWvEpFAgpHOqGmDdD3H6E5QsEXU4iZ3j28273t/eynXvKyTk3crDfvj/3ViH5bp42gUb@FCWwmIlPO2L7/TiS81B9MFwwqwfwaTBmRCwVGXiIpfhJ06laTPqKIuQXricgM "R – Try It Online")
Prints the sequence indefinitely (in theory). In practice, results over 308 are inaccurate as then `10^(0:F)` exceeds computing capabilities of R. We could counter this by using eg. `10^(0:nchar(F))`, but this costs bytes...
### Explanation:
```
while(F<-F+1) # while increasing value of F (infinitely)
sum(F%/%10^(0:F)%%10, # sum the digits of F (with a lot of unnecessary 0s)
-!F%%1:F) # minus the count of divisors of F
||print(F) # if the result is 0, print F
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
ℕ₁≜.ẹ+~l~f
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pv7fmobcOjpsaH2xY8atz7/1HLVCDnUeccvYe7dmrX5dSl/f9vaPA/CgA "Brachylog – Try It Online")
This is a generator. The TIO link has a header to ask for the first 10 possible instantiations of the output.
### Explanation
```
ℕ₁≜. The output is an instantiated natural integer
.ẹ+ The sum of elements (i.e. digits) of the output…
~l …is the length of a list…
~f …which is the list of factors of the output
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 9 bytes (18 nibbles)
```
|,~~`^+`@~$,|,$~%@
```
```
| # filter
,~ # 1..infinity
~ # for each number n that is falsy for
`^ # bitwise xor of
+ # sum of
`@ $ # digits of n in base
~ # 10 (default)
# and
, # length of
,$ # 1..n
| # filtered for each i that is
~ # falsy for
%@ # n modulo i
```
[](https://i.stack.imgur.com/9iDfn.png)
[Answer]
# [Excel](https://www.microsoft.com/en-us/microsoft-365/excel), ~~112~~ 110 bytes
`LET(r,ROW(1:999),REDUCE("",r,LAMBDA(a,b,a&IF(SUM(MID(b,SEQUENCE(LEN(b)),1)+0)=SUM((MOD(b,r)<1)+0),b&",",""))))`
[](https://i.stack.imgur.com/MZPi5.png)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
.fqsjZTl{m*FdyP
```
[Try it online!](https://tio.run/##K6gsyfj/Xy@tsDgrKiSnOlfLLaUy4P9/QwMA "Pyth – Try It Online")
Outputs the first \$n\$ terms as a list.
##### Explanation
```
.fqsjZTl{m*FdyP | Full program
.fqsjZTl{m*FdyPZQ | with implicit variables
------------------+---------------------------------------------------------------
.f Q | Find the first <input> integers Z (starting with 1) such that:
s | the sum of
jZT | the base 10 digits of Z
q | equals
l | the length of
| the list of factors of Z, i.e.:
{ | the unique
m*Fd | products of
y | all subsets of
PZ | the prime factors of Z
```
[Answer]
# [PLIS](https://github.com/ConorOBrien-Foxx/PLIS) `-i`, 78 bytes
```
1+@(H@({$0*$0}{([$0+$1]{$0%10}[$0/10](M*$0))@(spT@$0)-[$0+$1](H@($0%a))@$0}a))
```
The `-i` flag generates sequence entries infinitely, as such:
```
C:\Users\conorob\Programming\langs\PLIS (main -> origin)
λ plis -i -f example\digit-sum-equal-factor-count.min.plis
1 2 11 22 36 84 101 152 156 170 202 208 225 228 288 301 372 396 441 444 468 516 525 530
602 684 710 732 804 828 882 952 972 1003 1016 1034 1070 1072 1106 1111 1164 1236 ^C
```
PLIS is a programming language which primarily manipulates data using relevant OEIS sequences. While it has a lot of OEIS sequences implemented, PLIS does not aim to trivialize CGCC challenges by implementing random challenge sequences, hence the length.
Because OEIS sequences are the primary functions in this language, whenever a sequence of word characters are encountered, they are interpreted as a base 53 integer encoded using the alphabetic characters and `_`. (The OEIS sequence quoted in the OP, A057531, would be represented as `_ZU`, were it actually implemented in the language.)
Here is a commented, ungolfed explanation of what the code generally does.
```
# add 1 to each
1 +
# find indices where the sequence is nonzero
@(
A000007@(
# square each difference
{$0*$0}
# over each positive integer
{
# digit sum
([$0+$1] {$0%10} [$0/10] (A000012*$0))@(A055642@$0)
-
# factor count
[$0+$1](A7@($0%A000027))@$0
} A000027)
)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~84~~ 83 bytes
* -1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!
```
j,c;f(i){for(j=c=1;j<i;)c+=i%j++<1;for(;j;j/=10)c-=j%10;c||printf("%d ",i);f(i+1);}
```
[Try it online!](https://tio.run/##FcxBCoNADAXQdecURRhIGEWz/uYwJWUkgdoi3alnH3H94NmwmLUWvaGS816/G4WaCmJ2sBX1HKXMglsQiFFlYhs0skyw4/htvv4rdfn97HrnuynCONvn5Stx2tOjEiOd7QI "C (gcc) – Try It Online")
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$10\log\_{256}(96)\approx\$ 8.231 bytes
```
FmC'=SxLJk
```
[Try it online!](https://fig.fly.dev/#WyJGbUMnPVN4TEprIiwiIl0=)
Returns/prints the infinite list of such numbers.
```
FmC'=SxLJk
F # Filter
mC # The infinite list of numbers
' # Where
Sx # The digit sum
= # Equals
L # The length
Jk # Of its divisors + itself
```
[Answer]
# [Pip Classic](https://github.com/dloscutoff/pip), ~~35~~ 18 bytes
```
W++xI$+x=0Nx%\,xPx
```
[Try it online!](https://tio.run/##K8gs@P8/XFu7wlNFu8LWwK9CNUanIqDi/38A "Pip – Try It Online")
A lot of bytes saved thanks to @DLosc!
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
▐ë<of▌ëÇ@
```
[Run and debug it](https://staxlang.xyz/#p=de893c6f66dd898040&i=)
This is PackedStax, which unpacks to:
# [Stax (unpacked)](https://github.com/tomtheisen/stax), 11 bytes
```
VIf:d%_E|+=
```
[Run and debug it](https://staxlang.xyz/#c=VIf%3Ad%25_E%7C%2B%3D&i=)
```
VI # infinity
f # filtered by
:d% # the length of the divisors
_E|+ # and the digit sum
= # are equal
```
[Answer]
# [Haskell](https://www.haskell.org/), 73 bytes
```
s=[n|n<-[0..],length[d|d<-[1..n],0==mod n d]==(sum.map(read.pure).show)n]
```
[Try it online!](https://tio.run/##DcixDoQgDADQX2Fw0MRrcLdfQhiatDmMUAnF3OK/473xJbJTch7DMOij@yd4gLhm0W9PgR/@zwagcfWI5WKnjiPibHeBQnVuQgz1brKApeu3aByFDsXaDu1Tp1Pc5r2z8QI "Haskell – Try It Online")
[Answer]
# [Scala](https://www.scala-lang.org/), ~~83~~ 71 bytes
Saved 12 bytes thanks to the comment of @naffetS
---
Golfed version. [Try it online!](https://tio.run/##HY2xCoMwFADn@hUPaTFvUJJVzNAP6FQ6lSKvqUokJpLEQil@exo6Hhx3QZGh5J7zoCJcSFv4FgCvYYQlAyM/hRbO3tPnfo1e2@mBLdysjiCzeXiTASMF5zyNzjPqagHRgUE9slAeqWwWWllfV7zCJmyLlOwvEDbKbTYyOvWdQFxzOpr8wwSwF3uRfg)
```
for(a<-1 to l)if(s"$a".map(_-'0').sum==(1 to a).count(a%_<1))println(a)
```
Ungolfed version. [Try it online!](https://tio.run/##VZA9a8MwFEV3/4q7FKShirOGeiiUbqVDyFBKCa@q7ajow0jPDabkt7uK7CEdNDzp3HseSposzXP4/G4144WMx28FfLUdXB4ExT7t8BgjTe97jsb3H3KHgzeMppDAD1lY48rNtq5rbDZ4CyM0ecR2sKRb8MkknA2fQH5a6SkzZ/JcSroQIQgP99iCw0LIVbAo0uheuyfTG05ZRIrDso9yNIijolTepMrcTcqP7pk0h3gNidJNUukwes66OxzRNKjlmjAdxD9Pc1MgMWQf2/wpC3@prudSzfMf)
```
object Main {
def main(args: Array[String]): Unit = {
val limit = 1000 // You can replace this with any limit you want
for (a <- 1 to limit) {
val sumOfDigits = a.toString.map(_.asDigit).sum
val numFactors = (1 to a).count(a % _ == 0)
if (sumOfDigits == numFactors) println(a)
}
}
}
```
[Answer]
# Rockstar, 168 bytes
Rockstar can't do *anything* the challenge asks. So, of course, I'm going to do it anyway! On my phone!
```
listen to N
X's 0
while N
let X be+1
Y's 0
D's 0
while X-Y
let Y be+1
let M be X/Y
turn up M
let D be+M's X/Y
cut X in L
while L
let D be-roll L
let N be-D's 0
say X
```
[Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in)
```
listen to N :Read input string into variable N
X's 0 :Initialise X as 0
while N :While N is not 0
let X be+1 : Increment X
Y's 0 : Initialise Y as 0
D's 0 : Initialise D as 0
while X-Y : While Y is less than X
let Y be+1 : Increment Y
let M be X/Y : Assign X/Y to variable M
turn up M : Round M up to nearest integer
let D be+ : Increment D by
M's X/Y : Is M equal to X/Y?
: End while loop
cut X in L : Split X into a digit array and assign to variable L
while L : While L is not empty
let D be- : Decrement D by
roll L : Pop the first element from L
: End while loop
let N be- : Decrement N by
D's 0 : Is D equal to 0?
:End while loop
say X :Output X
```
] |
[Question]
[
Your challenge is to print `x` digits of pi where `x` is your code length.
Examples:
```
Source code (length) -> output
foo! (4) 3.141
foobar (6) 3.14159
kinda long (10) 3.141592653
+++++ (5) 3.1415
123456789 (9) 3.14159265
```
You can use `floor(π/10 * 10code\_length) / 10code\_length - 1` to determine the number of digits you need to print. Note that the decimal point does not count as a digit of pi - so code of length 3 should have output `3.14`, of length 4.
Rules:
* Your code length must be larger than three characters.
* You may not use any standard loopholes.
* You may use any standard allowed output methods.
* You may not read your source to determine code length.
* **You may not use a builtin pi constant.**
* Pi must be *completely accurate* and not approximated.
* The decimal point in the output is necessary. If you choose to output via return value, you must return a floating point integer.
* The goal of this challenge is to find the shortest solution in each language, not the shortest language for the solution. Don't be afraid to post a solution in a language when a shorter solution is posted in the same language as long as your solution uses a different method.
[Answer]
# Mathematica, 18 bytes
using zeta function
[](https://i.stack.imgur.com/WgYiE.jpg)
```
Sqrt[6Zeta@2]~N~18
```
[Try it online!](https://tio.run/##y00sychMLv6fZvs/uLCoJNosKrUk0cEots6vztDif0BRZl6JgkPafwA "Mathics – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
“Œı⁸Ç’÷ȷ8
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//4oCcxZLEseKBuMOH4oCZw7fItzj//w "Jelly – Try It Online")
Outputs `3.14159265`
**How it Works**
```
“Œı⁸Ç’ - The integer 314159265
÷ - divide
ȷ8 - The integer 100000000
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
3;⁽4ƒṾ
```
**[Try it online!](https://tio.run/##y0rNyan8/9/Y@lHjXpNjkx7u3Pf/PwA "Jelly – Try It Online")**
Prints `3,14159` with the allowed "European" decimal separator, `,`.
### How?
```
3;⁽4ƒṾ - Main link: no arguments
3 - literal 3 3
⁽4ƒ - base 250 literal 14159 14159
; - concatenate [3,14159]
Ṿ - unevaluate ['3', ',', '1', '4', '1', '5', '9']
- implicit print 3,14159
```
[Answer]
# VBA (Excel), 15 bytes
```
MsgBox 4*Atn(1)
```
Output:
3.14159265358979
I think this is not acceptable as I golfed it just to fit the length of the PI. The un-golfed length of it is 17 bytes. D:
[Answer]
# [Python 3](https://docs.python.org/3/), 64 bytes
```
print("3.%d"%int("SIXW57LUPVBUA10HBQJOL57QLF54UT0U00KIN32O",36))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ8lYTzVFSRXMDPaMCDc19wkNCHMKdTQ08HAK9PL3MTUP9HEzNQkNMQg1MPD29DM28lfSMTbT1Pz/HwA "Python 3 – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~10~~ ~~9~~ 7 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
4ΘΞ“6⌡υ
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=NCV1MDM5OCV1MDM5RSV1MjAxQzYldTIzMjEldTAzQzU_)
Explanation:
```
4ΘΞ“ push 31415
6⌡ 6 times do
υ divide by 10
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 5 bytes
```
3.14F
```
[Try it online!](https://tio.run/##S85KzP3/31jP0MTt/38A "CJam – Try It Online")
### How it works
```
3.14 e# Push 3.14.
F e# Push 15.
```
[Answer]
# [Desmos](https://www.desmos.com/), 130 bytes
```
f\left(\right)=\frac{\operatorname{floor}\left(10^{128}\cdot 4\sum_{k=1}^{9^9}\frac{\left(-1\right)^{k+1}}{2k-1}\right)}{10^{128}}
```

The source code for this (Which can be accessed by copy and pasting inside and outside of Desmos) isn't optimal when generated using the Desmos editor, so a few bytes of whitespace were golfed down where possible.
This defines a function `f` which takes no arguments returns pi, calculated using the [Gregory Sequence](http://mathworld.wolfram.com/GregorySeries.html) to `k=9^9` *(I can't confirm this is accurate enough, however I am of the believe that it is, it can be made more accurate with a greater value of k)* it then floors the result to `128` decimal places, which, alongside the `3.`, is the length of the source code.
[Try it online!](https://www.desmos.com/calculator/sj7sokmfrx)
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~9~~ 4 bytes
As short as it can allowably get :)
Includes an unprintable (reverse line feed, charcode 141) after the `#`.
```
3.#
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.6&code=My4jjQ==&input=)
In Japt, any character following `#` is converted to its character code and appended to any digits or decimal points which may precede it, in this case the `3.`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes
```
”i‴Aχ:&”
```
[Try it online!](https://tio.run/##S85ILErOT8z5/7@gKDOvREHJWM/QxNDU0shM6f///7pl/3WLcwA "Charcoal – Try It Online")
Just a compressed string.
[Answer]
# Javascript, 16 bytes
```
_=>Math.acos(-1)
```
```
f=
_=>Math.acos(-1)
console.log(f())
```
[Answer]
# [Neim](https://github.com/okx-code/Neim), 5 bytes
```
3FBρσ
```
Explanation:
```
3 Push 3
FB F pushes 45, B converts it into a character code, '.'
ρ Push 14
σ Push 15
Implicitly concatenate and print stack
```
[Try it online!](https://tio.run/##y0vNzP3/39jN6Xzj@eb//wE "Neim – Try It Online")
[Answer]
# APL, 6 bytes
```
10○⍟-1
```
Takes the imaginary part of ln(-1).
[Try it online!](http://tryapl.org/?a=10%u25CB%u235F-1&run)
[Answer]
# [J](http://jsoftware.com/), 16 bytes
```
17j15":4*_3 o.1:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuY6BgpWCgq@cc5OP239A8y9BUycpEK95YIV/P0Oq/Jldqcka@Qpq6@n8A "J – Try It Online")
Similar to the VBA answer. Outputs: `3.141592653589793`.
[Answer]
# [Math.JS](http://mathjs.org), 17 bytes.
```
log(-1,e).im
```
*That's 5 leading spaces*
This calculates  to 15 decimal places, and implicitly prints it.
[Try It Online!](https://a-ta.co/math/&ICAgICBsb2coLTEsZSkuaW0=)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
3•∊&SK•)'.ý
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f@FHDokcdXWrB3kCGprre4b3//wMA "05AB1E – Try It Online")
```
COMMAND # CURRENT STACK | EXPLANATION
------------#-----------------------+-----------------------------------
3 # [3] | Push 3.
•∊&SK• # [3, 1415926535] | Push compressed base-255 number 1415926535.
) # [[3,1415926535]] | Wrap the 2 to an array.
'. # [[3,1415926535],'.'] | Push a decimal point.
ý # ['3.1415926535'] | Join 3 and 1415926535 with a decimal point.
```
---
***USING BUILT-INS:***
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
žq5£
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6L5C00OL//8HAA "05AB1E – Try It Online")
---
`3žs` doesn't work for some reason...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
-ÆAær5
```
[Try it online!](https://tio.run/##y0rNyan8/1/3cJvj4WVFpv//AwA "Jelly – Try It Online")
Uses a different approach than the other Jelly answers.
## How?
`-ÆA` is inverse cosine of `-1` (which is pi), `ær5` retrieves the needed section. It worked out so rounding is equivalent to truncation in this case
[Answer]
# [ForceLang](https://github.com/SuperJedi224/ForceLang), 269 bytes
```
set S 0x5F258E476FC1B3B5571012206C637089460E41E814CB071E61431B5F0671F551D18D2C5D2D3A2565E408C6DE8D753F595B6E9979C3866D1C9965008DCFB02E3BD11D21DFFAF17978F05C8BBACF55A5ED5E90B1D8CAD8736AA4B728EB342B453F86353DB371D322B6A98613BC5CCB00AC2.mult 1e-270
io.write S.toString 268
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~9~~ 8 bytes
```
-1X;V9:)
```
[Try it online!](https://tio.run/##y00syfn/X9cwwjrM0krz/38A "MATL – Try It Online")
Explanation:
```
-1 % number literal
X; % inverse cosine (radians), giving pi
V % convert to string
9 % specify precision
:) % keep first 9 characters - 8 digits of precision
```
Saved one byte thanks to Luis Mendo!
[Answer]
# RPL (HP48), 86.5 bytes, 87 digits [Does this count?]
```
« GROB 8 43
14159265358979323846264338327950288419716939937510582097494459230781640628620899862803
→STR 9 OVER SIZE SUB 2 "." REPL »
```
GROB is an image keyword. The 2 numbers that follow are width and height. The hexadecimal digits that follow are bitmap. That's 1 byte of storage for every 2 digits plus the image metadata.
Empty program `« »` takes 10 bytes. A command takes 2.5 bytes. A float takes 10.5 bytes, but if it's equal to a single digit integer, it can take 2.5 bytes.
HP48 stores 4 rather than 8 bits at each memory location, so a byte occupies 2 consecutive locations (low endian). Often 20-bit chunks are used, and they do take 2.5 bytes (not 3).
[Answer]
# TI-BASIC, 7 bytes
```
round(4tan⁻¹(1),6
round(2sin⁻¹(1),6
round(cos⁻¹(-1),6
```
These three statements will print `3.141593`.
---
**Note:** TI-BASIC is a tokenized language. Character count does ***not*** equal byte count.
[Answer]
# [Julia 1.0](http://julialang.org/), 16 bytes
```
show(acos(-1))##
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/vzgjv1wjMTm/WEPXUFNTWfl/cn5KanxOal56SYaCrYKhGVdBUWZeSU6ehiaclZaTn1@kkZSZrnG@QVPf0EBBS8HQIA5Jo6aCPkhEA9ksXQWg@f8B "Julia 1.0 – Try It Online")
This is the default precision printed, I sadly have to add 2 dummy characters but I don't think it's possible to make it shorter
[Answer]
# [Haskell](https://www.haskell.org/), 15 bytes
```
acos(-1)-3e-15
```
[Try it online!](https://tio.run/##y0gszk7NyflfZvtfITE5v1hD11BT1zhV19D0f25iZp6CrUJKvgIXZ0FpSXBJkU@egopCcUZ@uUKZtraSgoaStjaIp5GTmpdekqEBkdEEmqCtraCkkJKZnllSrKn0HwA "Haskell – Try It Online")
Using @JungHwanMin formula.
[Answer]
# Perl 5, 40 bytes
```
}{$\=$\/~(2*$_)*~$_+2for-130..-2
```
Requires the command line option `-pMbignum`, counted as 8.
**Sample Useage:**
```
$ perl -pMbignum test.pl < /dev/null
3.141592653589793238462643383279502884197
```
I apologize for no TIO link, it doesn't seem to support `bignum` (or an unmatched opening brace...).
[Answer]
# [MY](https://bitbucket.org/zacharyjtaylor/my-language/src), 7 bytes
```
’2ō"8↑↵
```
[Try it online!](https://tio.run/##y638//9Rw0yjo71KFo/aJj5q2/r////oaAsdBXMdBcNYHYVoEyCto2AMYprqKIBQbCwA)
## How?
* `’`, decrement the top of the stack (`0` is popped if empty, making the stack `[-1]`). (Same symbol as Jelly)
* `2`, push `2`.
* `ō`, since the top of the stack is two, discard the `2`, pop `n`, then push `acos(n)` (in radians, this gives pi, this symbol is `o` with a negative sign on top of it. `o` (for normal trig) comes from APL).
* `"`, pop the top element of the stack and push it as a string.
* `8`, push `8`.
* `↑`, pop `a` then `b`, push `b[:a]` (This is another symbol taken from APL).
* `↵`, output with a new line (OUTPUT <- STACK).
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 16 bytes
```
"]a:5;."3no>n<
```
[Try it online!](https://tio.run/##S8sszvj/Xyk20cpUyvpQr56ScV6@XZ7N//8A "><> – Try It Online")
There's a couple of unprintables in there, with the first having value 26 and the second 141.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 99 bytes
```
i;main(){for(;i<46;)printf(i++?"%02d":"3.",i[L"0;5:a]î.+& O2
TÅ©']KiR J^-\
N¤
>cV
0ý*uO"]);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/TOjcxM09Dszotv0jDOtPGxMxas6AoM68kTSNTW9teSdXAKEXJSslYT0knM9pHyeBQr7WUqVVi7OF1elLaagr@RjIhh1sPrVSP9c4MUvCK042R8zu0hE3GjiM5TIbZ4PBerVI2f6VYTeva//8B "C (gcc) – Try It Online")
Hardcode 99 bottle of digits
[Answer]
# [Pyth](https://pyth.herokuapp.com/?code=%3C%60.ttZ4+T&debug=0), 9 bytes
```
<`.ttZ4 T
```
**[Try it here.](https://pyth.herokuapp.com/?code=%3C%60.ttZ4+T&debug=0)**
Works with the fact that  "\pi\approxeq\arccos(-1)").
[Answer]
# [Ruby](https://www.ruby-lang.org/), 16 bytes
```
->{Math.acos -1}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf167aN7EkQy8xOb9YQdew9n9BaUmxQlp07H8A "Ruby – Try It Online")
[Answer]
# Excel VBA, 16 Bytes
Anonymous VBE immediate window functions that takes no input and output to any of Excel VBA's STDOUTs
*Each line represents a separate function that returns Pi of length 16*
```
?Mid(4*Atn(1),1)
```
```
?Str([Acos(-1)])
```
```
Debug.?4*Atn(1);
```
```
MsgBox[Acos(-1)]
```
```
[A1]="=ACOS(-1)"
```
] |
[Question]
[
# Task
Given a positive integer `n`, output the joined compound of circles
The circles are of square of size `n+2` but removing the corner edges and the middle, before finally overlapping `n` times of itself
E.g.
```
2
```
->
```
####
####
####
####
```
->
```
##
# #
# #
##
```
->
```
## ##
# # #
# # #
## ##
```
# Testcases
```
1
->
#
# #
#
2
->
## ##
# # #
# # #
## ##
3
->
### ### ###
# # # #
# # # #
# # # #
### ### ###
4
->
#### #### #### ####
# # # # #
# # # # #
# # # # #
# # # # #
#### #### #### ####
```
Trailing spaces are allowed
You have to use the character `#`
You have to join the strings by newlines (no lists)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
[Answer]
# [J](http://jsoftware.com/), 37 32 31 30 28 bytes
```
'# '{~(>:+*:)($=/~0,~])0,#&1
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1ZUV1KvrNOystLWsNDVUbPXrDHTqYjUNdJTVDP9rcqUmZ@QrpCkYQxjq6jABI3QBw/8A "J – Try It Online")
*-2 thanks to ovs for realizing XOR could be replaced with XNOR*
## key idea
The 2d pattern we seek is just the XOR function table of these two 1d patterns:
```
0 1 1 1 0 1 1 1 0 1 1 1 0
--------------------------
0 |0 1 1 1 0 1 1 1 0 1 1 1 0
1 |1 0 0 0 1 0 0 0 1 0 0 0 1
1 |1 0 0 0 1 0 0 0 1 0 0 0 1 <-- XOR TABLE
1 |1 0 0 0 1 0 0 0 1 0 0 0 1
0 |0 1 1 1 0 1 1 1 0 1 1 1 0
```
[Answer]
# [Lua](https://www.lua.org), 86 bytes
```
x,a,c=...," ","\n"b=a.rep;d=b(a..b("#",x),x)print(d..c..b(b("#"..b(a,x),x+1)..c,x)..d)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m704pzRxwYKlpSVpuhY3wyp0EnWSbfX09HSUFJR0lGLylJJsE_WKUgusU2yTNBL19JI0lJSVdCo0gaigKDOvRCNFTy8ZJAyWADESwbLahppACSBTTy9FE2I61JIl0YYGsVA2AA) Tried moving some stuff around but couldn't get an improvement.
[](https://i.stack.imgur.com/aspux.png)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 37 35 34 30 26 bytes
```
{"# "(1,s)=\:1,/x#,s:&x,1}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6pWUlZQ0jDUKda0jbEy1NGvUNYptlKr0DGs5eJKUzDmAgCPZAfm)
Yay my second k answer!
Uses @Jonah's approach.
*¯2 bytes thanks to @doug in the k tree*
*¯1 bytes by using `@`*
*¯4 bytes thanks to @ovs and @doug*
*¯4 bytes thanks to @Traws*
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 16 bytes
```
v\#₌≬₅*Ṅ꘍R₅*ǏȮJJ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJDIiwiIiwidlxcI+KCjOKJrOKChSrhuYTqmI1S4oKFKsePyK5KSiIsIiIsIjMiXQ==)
(IMO) this is some pretty elegant code. It uses some quite neat tricks to achieve the score it is. The output format's still stupid though.
```
v\# # Fill 1..n with spaces
₌----- # Apply both to the stack...
≬--- # The next three elements as one
₅*Ṅ # Repeat each by its length and join with spaces
꘍ # And prepend n spaces to each #
R # Reverse each of those so a # is at the start
₅* # Repeat each of those by the required length
Ǐ # Append the first character (#)
Ȯ # Push the item under (the # # #) to the stack
JJ # Append that and prepend it
# (C flag) join by newlines and centre
```
An approach similar to Jonas' answer, but independently derived:
# [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 18 bytes
```
›D?*"ʀ$Ḋƒv꘍ƛ‛ #$İ∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwi4oC6RD8qXCLKgCThuIrGknbqmI3Gm+KAmyAjJMSw4oiRIiwiIiwiMyJd)
The last 7 bytes exist because of the stupid output format, and some Vyxal bugs.
# [Vyxal](https://github.com/Vyxal/Vyxal) `joe`, 18 bytes
```
v\#*Ṅðp…£v\#?꘍*Ǐ¥J
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJqb2UiLCIiLCJ2XFwjKuG5hMOwcOKApsKjdlxcIz/qmI0qx4/CpUoiLCIiLCIzIl0=)
The initial version of the first approach. Who's Joe?
[Answer]
# [Ruby](https://www.ruby-lang.org/), 46 bytes
```
->n{[z=(" "+?#*n)*n,[?#+(" "*n+?#)*n]*n,z]*$/}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOrrKVkNJQUnbXlkrT1MrTyfaXlkbJKCVBxQCCsQCxapitVT0a/9rGOrpmWrq5SYWVNdU1BSUlhQrpEVXxFqDWLX/AQ "Ruby – Try It Online")
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 25 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
Port of [Jonah's excellent J answer](https://codegolf.stackexchange.com/a/244097/64121).
```
" #"⊏˜·≠⌜´+⟜1(+⥊↑⟜1)¨1∾ט
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgIiAjIuKKj8ucwrfiiaDijJzCtCvin5wxKCvipYrihpHin5wxKcKoMeKIvsOXy5wKCkbCqCAxK+KGlTQ=)
[Answer]
# [Haskell](https://www.haskell.org/), 69 bytes
```
f n=unlines[[" # "!!(0^mod x(n+1)+0^y)|x<-[0..n*n+n]]|y<-[0..n]++[0]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7Y0LyczL7U4OlpJQVlBSVFRwyAuNz9FoUIjT9tQU9sgrlKzpsJGN9pATy9PK087Lza2phLKjdXWjjaIjf2fm5iZp2CrUFBaElxS5JOnoKKQpmDyHwA "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'#úR×Ćи¬DÙ‡.ø»
```
[Try it online](https://tio.run/##ASUA2v9vc2FiaWX//ycjw7pSw5fEhtC4wqxEw5nDguKAoS7DuMK7//80) or [verify the first 5 results](https://tio.run/##yy9OTMpM/W/qquSZV1BaYqWgZO@nw6XkX1oC4en4HZ7wX1358K6gw9OPtF3YcWiNy@GZh5seNSzUO7zj0O7/Ooe22f8HAA).
**Explanation:**
```
'# '# Push "#"
ú # Pad it with the (implicit) input amount of leading spaces
R # Reverse it so the spaces are trailing
× # Repeat this the (implicit) input amount of times as string
Ć # Enclose; append its own head (the "#")
и # Repeat it the (implicit) input amount of times as list
¬ # Push its first item (without popping the list)
D # Duplicate it
Ù # Uniquify its characters: "# "
 # Bifurcate; short for Duplicate & Reverse copy: " #"
‡ # Transliterate all "# " to " #" in the duplicated string
.ø # Surround the list with this string as leading/trailing item
» # Join by newlines
# (after which the result is output implicitly)
```
I initially tried to use the Canvas builtin, but [it ended up at twice the amount of bytes..](https://tio.run/##yy9OTMpM/f/f6FHDLItHHb0uxnqHFh9a7WloqGWse2glUERd2fzwXBO9eGOfQ6sPrQMKnJv9/78JAA)
[Answer]
# [Python](https://www.python.org), 63 bytes
```
lambda n:"\n".join(n*(a+n*b)+a for a,b in[" #",*n*["# "]," #"])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY37XMSc5NSEhXyrJRi8pT0svIz8zTytDQStfO0kjS1ExXS8osUEnWSFDLzopUUlJV0tPK0opWUFZRidUDcWE2oMeogdZlAVQpFiXnpqRqGOuaaVgVFmXklGmkamZqa1hA2VPmCBRAaAA)
[Answer]
# x86-64 machine code, 33 bytes
```
56 B8 20 0A B0 23 5A 52 AA 34 03 59 51 F3 AA 34 03 FF CA 75 F3 66 AB FF CE 79 E9 7A E4 88 17 59 C3
```
[Try it online!](https://tio.run/##ZZJNb9swDIbP4q/gPASQFzdI030hbgZsPe@y04AkB0eSYxWKJEhOqyzIX59HuW0uu5AQ34cvKUjC@5u9EMPQxANy/FVwmO2N2zUGW2iXzB9jhyFqiGbJZrtTr3CefnytKC7mOc6/gyfp4J6wMWP5Dph3HoNMNb60ywSExN7FHbDkwki@YeKKiQQsKI//g1IJVOTCHu0fNDBaPb@WaTcqR/RUf/QKI@W8zTpIva1Qmuuc7N5DWWBZg0q9ChaLhwLPT05LbLnomvABY4Xa9mjL@gLwXlthjlLhfeyldrPuG0BWD422vIQzsNyEQcWj6defbhfbGlhLe/PRA1d4W1O6X@EXytNpCYx6WMtfOqo8hs4@EN7yYqI3dhI3tiChenXNwAWuyMb@bESnrULhpFoWWc6zEs2i9zjRUTo8v@E4mS9@k91pxfnRRr23SuJ40bIt12k63dI98bnTRiE/4TsySQ932fTqwCca87vHclwskXgZhr@iNc0@DjeHzx8p0O9ZEa/MPw "C++ (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string, and takes the number n in RSI.
In assembly:
```
f: push rsi # Push n onto the stack.
sl: .byte 0xB8, 0x20, 0x0A # These bytes combine with the next instruction to form
# mov eax, 0x23B00A20. In particular, the lowest byte (AL) is 0x20 (' ')
# and the second-lowest byte (AH) is 0x0A ('\n').
pl: mov al, 0x23 # (Executed for the middle lines) Set AL to 0x23 ('#').
pop rdx; push rdx # Set RDX to n. (This is 2 bytes; mov edx, [rsp] would be 3.)
l: stosb # Write AL to the string, advancing the pointer.
xor al, 3 # Change AL from ' ' to '#' or vice versa.
pop rcx; push rcx # Set RCX to n.
rep stosb # Write AL to the string RCX times, advancing the pointer.
xor al, 3 # Change AL from ' ' to '#' or vice versa.
dec edx # Subtract 1 from EDX.
jnz l # If it's not zero, jump back. (Repeats n times.)
stosw # Write AL and AH ('\n') to the string, advancing the pointer.
dec esi # Subtract 1 from ESI.
jns pl # If it's not negative (which occurs n times),
# jump back to make a line starting with '#'.
jpe sl # Jump back to make a line starting with ' '
# if the sum of the eight low bits is even.
# This is true for -1 (…11111111) but not for -2 (…11111110).
mov [rdi], dl # Add DL (the low byte of RDX), which is 0, to the string.
pop rcx # Take n off the stack.
ret # Return.
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 58 bytes
```
param($n)($t=(' '+'#'*$n)*$n);,(('#'+' '*$n)*$n+'#')*$n;$t
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqZgq1D9vyCxKDFXQyVPU0OlxFZDXUFdW11ZXQvIB2FrHQ0NIFcbKAwVAsmCaGuVkv@1XColqcUlzonFqcW2DhqGOkY6xjomOqY6ZppIMjWq1VxKnnkFpSVWCirxCgl5/qUlII4SlxrQCSrxXLX/AQ "PowerShell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 102 bytes
*shorter version thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!*
```
i=-1,j;main(n){for(n+=scanf("%d",&n);j=i++<n;puts(""))for(;j-->n-n*n;putchar("# "[!(j%n)^(i^n&&i)]));}
```
[Try it online!](https://tio.run/##HcpBCsIwEAXQq@hIw4zpLHQb40XEQhipTsBfaXUlnj2i28czvZq15ll3fU334mDIe5xmRsyLFYxM3YX6AEk1e4wHpMfruTCRyK@lqnqEYvt3u5WZabOi05prBxnYB4TgchZJn9b2Xw "C (gcc) – Try It Online")
# [C (GCC)](https://gcc.gnu.org), 107 bytes
```
main(i,j,n){scanf("%d",&n);++n;for(i=-1;i++<n;puts(""))for(j=-1;j++<n*n-n;putchar("# "[!(j%n)^(i^n&&i)]));}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6FjezcxMz8zQydbJ08jSri5MT89I0lFRTlHTU8jSttbXzrNPyizQybXUNrTO1tW3yrAtKS4o1lJQ0NUHiWSDxLJC4Vp4uWC45I7FIQ0lZQSlaUSNLNU8zTiMzLk9NLVMzVlPTuhZiJdTmJdGGBrFQNgA)
Indented version:
```
main(i,j,n){
scanf("%d",&n);
++n;
for(i=-1;i++<n;puts(""))
for(j=-1;j++<n*n-n;
putchar("# "[!(j%n)^(i^n&&i)]));
}
```
[Answer]
# [Python](https://www.python.org), ~~71~~ 67 bytes
```
lambda n:"\n".join([t:=" "+f'{"#"*n} '*n,*["#"+f'{" "*n}#'*n]*n,t])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3nXMSc5NSEhXyrJRi8pT0svIz8zSiS6xslRSUtNPUq5WUlbTyahXUtfJ0tKKBHLCYAkhMGSgWCxQuidWEGqVfUJSZV6KRpmGoqckFYxshsY2R2CaaUG0LFkBoAA)
-4 bytes from @Unrelated String
[Answer]
# APL+WIN, 37 bytes
Prompts for n. Index origin = 0
```
' #'[(v,0)∘.≠((n×n+1)⍴v←0,(n←⎕)⍴1),0]
```
[Try it online! Thanks to Dyalog APL Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv7qCsnq0RpmOgeajjhl6jzoXaGjkHZ6ep22o@ah3SxlInY5GHpACagOJGGrqGMT@B@rk@p/GZcilrqDOlcZlBKWNobQJFwA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
NθFθGH+→⁺²θ⁺ ×θ#
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orLb9IAchQCMjPqUzPz/PIz8nJL9ew0tZRsArKTM8o0VEIyCkt1jDSUSjUhLKVFJR0FEIyc1OLNQp1FJSUlTQ1Na3//zf@r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
Fθ
```
Repeat `n` times...
```
GH+→⁺²θ⁺ ×θ#
```
... draw a hollow polygon using the directions Right, Down, Left, Up, Right, of size `n+2`, using a string consisting of a space and `n` `#`s. Each polygon therefore starts at the top left of the "circle" and finishes at the top right, ready to start the next one.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~18~~ 17 bytes
```
WBtTh!-GtQ*Q:Z)Zc
```
[Try it online!](https://tio.run/##y00syfn/P9ypJCRDUde9JFAr0CpKMyr5/39jAA) Or [verify all test cases](https://tio.run/##y00syfmf8D/cqSQkQ1HXvSRQK9AqSjMq@b9BcoRLVEXIf0MuIy5jLhMA).
### Explanation
Consider input `n = 3` as an example.
```
WB % Implicit input: n. 2^n, convert to binary.
% STACK: [1 0 0 0]
tTh % Duplicate, push 1, concatenate horizontally
% STACK: [1 0 0 0], [1 0 0 0 1]
!- % Transpose, subtract element-wise with broadcast
% STACK: [0 -1 -1 -1
1 0 0 0
1 0 0 0
1 0 0 0
0 -1 -1 -1]
GtQ*Q: % Push n, duplicate, add 1, multiply, add 1: gives n^2+n+1. Range (1-based)
% STACK: [0 -1 -1 -1
1 0 0 0
1 0 0 0
1 0 0 0
0 -1 -1 -1], [1 2 3 4 5 6 7 8 9 10 11 12 13]
Z) % Horizontal indexing (1-based, modular)
% STACK: [0 -1 -1 -1 0 -1 -1 -1 0 -1 -1 -1 0
1 0 0 0 1 0 0 0 1 0 0 0 1
1 0 0 0 1 0 0 0 1 0 0 0 1
1 0 0 0 1 0 0 0 1 0 0 0 1
0 -1 -1 -1 0 -1 -1 -1 0 -1 -1 -1 0]
Zc % Convert non-zeros to '#'. Implicit display (char(0) is displayed as space)
% STACK: [' ### ### ### '
'# # # #'
'# # # #'
'# # # #'
' ### ### ### ']
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
‘ð;ׯ€⁸ḍn€/ị⁾# Y
```
**[Try it online!](https://tio.run/##y0rNyan8//9Rw4zDG6wPTz@6@1HTmkeNOx7u6M0DsvQf7u5@1LhPWSHy////xgA "Jelly – Try It Online")**
```
‘ð;ׯ€⁸ḍn€/ị⁾# Y - Main Link: integer, N
‘ - increment -> N+1
ð - start a new dyadic chain - f(N+1, N)
× - multiply -> (N+1)×N
; - concatenate -> [N+1, (N+1)×N]
Ż€ - zero range each -> [[0..N+1], [0..(N+1)×N]
⁸ - chain's left argument -> N+1
ḍ - divides? (vectorises) -> [[1,0,...,0,1], [1,0,...,0,1,0,...,0,1,0,...,1]]
/ - reduce by:
€ - for each:
n - not equal (vectorises)
ị⁾#. - index into "# " (vectorises)
Y - join with newline characters
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, 43 bytes
```
say$_=$".('#'x$_.$")x$_,($/.y/ #/# /r)x"@F"
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVIl3lZFSU9DXVm9QiVeT0VJE0jpaKjo61XqKyjrKyvoF2lWKDm4Kf3/b/wvv6AkMz@v@L@ur6megaHBf92CRAA "Perl 5 – Try It Online")
[Answer]
# Python 3, ~~93~~ 82 bytes
Jonah's [observation](https://codegolf.stackexchange.com/a/244097/111305) that this pattern can be formed easily with an XOR table intrigued me, and I wanted to see if this would produce something short in Python. Unfortunately, I couldn't come up with a good way to build the required patterns golfily, and the result clocks in 30 bytes longer than the other python answer here:
```
lambda x:"\n".join("".join(" #"[i^j]for i in[0,*[1]*x]*x+[0])for j in[0,*[1]*x,0])
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCSikmT0kvKz8zT0MJSmsoKSjpKCkraUZnKtpmxablFylkKmTmqRuoFquraqgbqmtVaGpVaKsbqGuC5LKgcgZwSc3/BUWZeSUaaRqGmppcMLYREtsYiW0CVA8A)
Edit -11 bytes: from [@DLosc](https://codegolf.stackexchange.com/users/16766/dlosc)'s idea of using lists of ints instead of strings.
## Explanation
```
lambda x:
for j in [0,*[1]*x,0] ## Builds the list [0,1,1,...0], with x 1s, and loops over it
for i in [0,*[1]*x]*x+[0] ## Builds the list [0,1,1,...0,1,1,...0,....], i.e. [0,1...] with x 1s, repeated x times, with an extra 0 at the end
(" ","#")[i^j] ## '#' if i xor j, else ' '
"".join( ) ## .join the characters of this line
"\n".join( ) ## Encapsulate it in a list for output
```
[Answer]
# Mathematica 12, 83 bytes
```
StringRiffle[StringJoin/@Table[If[#∣i⊻#∣j,"#"," "],{j,0,#},{i,0,#2#}]&[#+1,#],"\n"]&
```
Uses the obvious divisibility trick, and *Mathematica*'s good unicode parsing
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H55ZkhFdnVaal2z7P7ikKDMvPSgzLS0nNRrC8crPzNN3CElMAop4pkUrP@pYnPmoazeIztJRUlbSUVJQitWpztIx0FGu1anOBNFGyrWxatHK2oY6yrE6SjF5SrFq/2t1AoDGlThogWzSdwhKzEtPdTA0iP0PAA)
[Answer]
# [flax](https://github.com/PyGamer0/flax) `C`, 21 19 18 bytes
```
₊ #iZŻ≠⌜ŻF₎⍴⊂µ¬W1⍪
```
~~Not happy with the byte count...~~
Slightly better.
-1 byte by implicit joining of newlines.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 79 bytes
```
.+
$*
1
$_¶
^
$%' #¶
¶$
¶$%` #
\b¶
# ¶
%(`1
$_¶
1(?=.*(.))
$1
.¶
(.+)(.).
$2$1
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLkEsl/tA2rjguFVV1BWUg69A2FRBWTVBQ5opJAgooKwAJVY0EqEpDDXtbPS0NPU1NLhVDLj2gCJeGnrYmUECPS8VIxfD/f2MA "Retina 0.8.2 – Try It Online") Explanation:
```
.+
$*
```
Convert to unary.
```
1
$_¶
```
Replicate the line of `n` `1`s `n` times.
```
^
$%' #¶
```
Prefix a line of `n` `1`s with a suffix of `#`. This indicates the pattern for the first line.
```
¶$
¶$%` #
```
Append another such line.
```
\b¶
# ¶
```
Append `#` to the original `n` lines. These indicate the pattern for the intermediate lines.
```
%(`
```
Apply the rest of the script separately to each line.
```
1
$_¶
```
Repeat each line `n` times. This also leaves an extra copy of the two pattern characters on a line on its own.
```
1(?=.*(.))
$1
```
Replace each `1` with the last character on the line.
```
.¶
```
Delete last character on each line as it is joined with the next line.
```
(.+)(.).
$2$1
```
Move the final copy of the first pattern character to the start of the entire line and delete the final copy of the second pattern character.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 40 bytes
```
.+
*$( $&*#)¶$&*$(*$(#$&* )#¶)$&*$( $&*#
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS0tFQ0FFTUtZ89A2IKWiAUTKQIaCpvKhbZpgEbD0//@GXEZcxlwmAA "Retina – Try It Online") Link includes test cases. Explanation: Just some boring string repetition. The final line parses as `$&*$( $&*#)¶$&*$($&*$(#$&* )#¶)$&*$( $&*#)` where the `$()` is a grouping construct and `$&*` repeats the character or group the number of times given by the input.
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~66~~ 65 bytes
```
n=>(t=(r=s=>s.repeat(n))(' '+r('#'))+`
`)+r(r('#'+r(' '))+`#
`)+t
```
[Try it online!](https://tio.run/##ZchLCoAgEADQfacIXDhDJPRZBDGeJQmLIlRUvL6Vu2j53qmSCqs/XGzTlDfKhiREAk@BZBBeO60iGETgNW88cMYRm6Va8EHhm3VJ9m7MqzXBXlpcdocNOsS5@lb/r@Ff41P5Bg "JavaScript (V8) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 86 bytes
```
t=(.cycle).take
f n=unlines$t(n+2)[t(n^2+n+1)[" # "!!(x+y)|x<-l]|y<-l]where l=1:t n[0]
```
[Try it online!](https://tio.run/##FcVBCoMwEADAu69YrYeEoFS9leYVHoOFICuK20V0RQP@PbaXmdFvMxLFKFaVfegJdSl@xmQAtjvTxLjlotjU2v361IZNpV0GD8jSVJ0m6Ot8F9Rd4e8x4opAtnoJsHt28esnBgvLLq2s@QBNvAE "Haskell – Try It Online")
[Answer]
# [Headascii](https://esolangs.org/wiki/Headass#Headascii), 121 bytes
```
+OUO{^)+E:ROD-}.UOD++++[]]]][]]O[UO{N-)!@++E:]PUO{^):]+++PD-};}.UO)++++E:U[{N-)+++E:]+++PUO{^):]PD-};}.OUUO{^)@+E:RO!D-}.
```
Whew!
Try it [here!](https://replit.com/@thejonymyster/HA23)
Code will have to be copied and executed as shown:
```
erun("+OUO{^)+E:ROD-}.UOD++++[]]]][]]O[UO{N-)!@++E:]PUO{^):]+++PD-};}.UO)++++E:U[{N-)+++E:]+++PUO{^):]PD-};}.OUUO{^)@+E:RO!D-}.","your input here")
```
But also, it takes input by charcode, so for example if you wanted to input 4, you'd type
```
"\u0004"
```
Which I think is perfectly valid :D
Code breakdown:
```
+OUO{^)+E:ROD-}. block 0
+O push 1 to global as a flag
UO get n/push n to global
U {^) : D-} loop n times
RO push n to global
+E . goto block 1
UOD++++[]]]][]]O[UO{N-)!@++E:]PUO{^):]+++PD-};}. block 1
UOD push flag to global
++++[]]]][]]O push 32 to global
[ and store it
UO push n to global
{N-) : U } loop n times
]P append 32 to string
UO push n to global
U {^): D-}; loop n times
]+++P append 35 to string
!@ print string w/trailing
newline and clear string
++E . goto block 2
UO)++++E:U[{N-)+++E:]+++PUO{^):]PD-};}. block 2
UO) if flag is 0
++++E goto block 5
: else
U[ store 32
{N-) : U } loop n plus 1 times
]+++P append 35 to string
UO push n to global
{^): D-}; loop n times
]P append 32 to string
+++E . goto block 3
OUUO{^)@+E:RO!D-}. block 3
O push 0 to global as flag
U discard previous flag state
UO push n to global
U {^) : D-} loop n times
RO push n to global
! print string w/trailing newline
@ clear string
+E . goto block 1
block 4 is empty
```
Using the global array length as an extra register is a fun trick i just learned doing this :)
] |
[Question]
[
Based on a list of numbers and their equivalent letters, take a string input, replace the characters of that string with the equivalent number/letter and output the result.
### List
>
> * 1 = a
> * 2 = b
> * 3 = c
> * 4 = d
> * 5 = e
> * 6 = f
> * 7 = g
> * 8 = h
> * 9 = i
> * 0 = j
>
>
>
### Input
>
> thisisastring1124
>
>
>
### Output
>
> t89s9s1str9n7aabd
>
>
>
### Rules
* Numbers are equivalent to lowercase letters only.
* Any character outside the list will be left as is.
* Input string must not contain spaces.
* Either full program or function is permitted.
* Since it's code-golf, fewest bytes wins.
[Answer]
## bash, 18 bytes
```
tr 1-90a-j a-j1-90
```
[Try it online!](https://tio.run/##S0oszvj/v6RIwVDX0iBRN0sBiEFMoFhGZnFmcWJxSVFmXrqhoZEJAA)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~76~~ 68 bytes
```
lambda w:w.translate(dict(zip(s,s[::-1])))
s=b'1234567890jihgfedcba'
```
[Try it online!](https://tio.run/##DchLDoIwEADQvadw12mixgJ@aMJJ1MWUUjoES8NMQvTy1bd8@SNxSXUJ3bPM@HYe95vdTrJi4hllAE@9wJcy8IEf1h7NS2u9484pU9XN5Xq7t@eJ4hgG3ztUJa@UBAIoicTEyPKP0ZiqUVqXHw "Python 3 – Try It Online")
[Answer]
## [Perl 5](https://www.perl.org/), 17 bytes
```
y;a-j1-90;1-90a-j
```
[Try it online!](https://tio.run/##K0gtyjH9/7/SOlE3y1DX0sAaRADZ//@XZGQWZxYnFpcUZealGxoamfzLLyjJzM8r/q9bAAA "Perl 5 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~45~~ 23 bytes
```
tr/1..90a..j/a..j1..90/
```
[Try it online!](https://tio.run/##K0gtyjH7/7@kSN9QT8/SIFFPL0sfRIB5@kCJjMzizOLE4pKizLx0Q0Mjk3/5BSWZ@XnF/3ULAA "Perl 6 – Try It Online")
Just a plain transliteration regex.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 9 bytes
```
žmÁAT£J‡
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6L7cw42OIYcWex1uetSw8P//kozM4szixOKSosy8dENDIxMA "05AB1E – Try It Online")
**Explanation**
```
žmÁ # push 0987654321
AT£ # push abcdefghij
J # join strings
 # bifurcate
‡ # transliterate
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 12 bytes
```
T`a-j09-1`Ro
```
[Try it online!](https://tio.run/##K0otycxL/P8/JCFRN8vAUtcwISj///@SjMzizOLE4pKizLx0Q0MjEwA "Retina 0.8.2 – Try It Online") Explanation:
```
T``
```
Perform a transliteration.
```
a-j09-1
```
The source list is the letters `a-j`, then `0`, then the digits `9-1`.
```
Ro
```
The destination list is the source list reversed, i.e. the digits `1-9`, then `0`, then the letters `j-a`.
[Answer]
# [J](http://jsoftware.com/), 38 bytes
```
rplc[:(;~"0|.)'9876543210jabcdefghi'"1
```
[Try it online!](https://tio.run/##BcFBDoIwEAXQfU/x081IQpoWEKGGk7iCytASo4RhiV69vrdmlsHAwsPmfXuFh7/cf9qepqC@u7XXpq6cXccpPGdeYiLtcqG0AfFgCCW@HixKzSF@wKAjJkkyyrGn9@Jc1ZDKfw "J – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~82~~ 78 bytes
```
lambda i,l='1234567890jihgfedcba':''.join((x,l[~l.find(x)])[x in l]for x in i)
```
[Try it online!](https://tio.run/##Hcy9DoMgFEDhV7lhARJiqrV/Jj6JdQApcg0FIwx06atT7fad5ayfZINviumfxcm30hJQuJ7Wzbm9XG/3x2lBO5uXnpSkHaXVEtAzloUbvq4y6DXLfORDBvTgRhM2@BN5ORwOMyLVtA@JAJIsRowypg39XNdNS3gH6x4JDAu8/AA "Python 2 – Try It Online")
-4 with thanks to @ovs
[Answer]
# JavaScript (ES6), 66 bytes
```
s=>s.replace(e=/[1a2b3c4d5e6f7g8h9i0j]/g,c=>e[e.search(c)^1],e+=e)
```
[Try it online!](https://tio.run/##BcFLDsIgEADQu3QFsVKp1eqCXqSpyTgdPg2BhiFeH9874AeMJZz1mvJOzZrGZmFV6IyAJMgMq4bxe8dpf9DTzu7l3@F2bIPr0Sy0kmKCgl6g/Oitp4sh2TAnzpFUzE5Y0VUfODBwLSE5rcepk7L9AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 40 bytes
```
function(s)chartr("0-9ja-i","ja-i0-9",s)
```
[Try it online!](https://tio.run/##FYgxCsAgDAD3PiOLBhS0dOnQx0jBGgcLSXx/aofjuGOrl9U5bqV3eMG7FVb2kOLZSyQI8GsVBEGr3mkjISmiTOPJeT8cbmv3KZoWDu0D "R – Try It Online")
Surprisingly, R is decent at this kind of [string](/questions/tagged/string "show questions tagged 'string'") challenge, because it has a `tr`-like function as in the [Bash answer](https://codegolf.stackexchange.com/a/167851/67312). No idea why it exists, but I'm grateful for it!
[Answer]
# MS-SQL, 71 bytes
```
SELECT TRANSLATE(v,'1234567890abcdefghij','abcdefghij1234567890')FROM t
```
The new SQL 2017 function [`TRANSLATE`](https://docs.microsoft.com/en-us/sql/t-sql/functions/translate-transact-sql?view=sql-server-2017) performs individual character replacement, so is ideally suited for this purpose. See [my similar answer in a prior challenge](https://codegolf.stackexchange.com/a/163167/70172).
Input is via a pre-existing table **t** with varchar column **v**, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). To replace only lowercase letters, the table must be created using a *case-sensitive collation*:
```
CREATE TABLE t(v varchar(max) COLLATE Latin1_General_CS_AS)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
⁵Øaḣ,ØDṙ1¤ċÞ⁸Ṛy)
```
[Try it online!](https://tio.run/##AToAxf9qZWxsef//4oG1w5hh4bijLMOYROG5mTHCpMSLw57igbjhuZp5Kf///3RoaXNpc2FzdHJpbmcxMTI0 "Jelly – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), 13 bytes
```
Xz+jk+0_S9<GT
```
[Try it here!](https://pyth.herokuapp.com/?code=Xz%2Bjk%2B0_S9%3CGT&test_suite=1&test_suite_input=thisisastring1124&debug=0)
### Explanation
```
Xz+jk+0_S9<GT – Full program.
_S9 – Yield [9, 8, 7, ..., 1]
+0 – Prepend a 0.
jk – Join to a single string.
+ <GT – And append the first 10 letters of the alphabet to it.
Yields 0987654321abcdefghij.
Xz – Transliterates the input from the above to the above reversed.
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~80~~ 66 bytes
```
map(!"1a2b3c4d5e6f7g8h9i0j")
e!(a:b:y)|e==a=b|e==b=a|1<2=e!y
e!_=e
```
[Try it online!](https://tio.run/##Fcy9DsIgFEDh3acA4tAOTQTrX@N9ClcTc8FbQGlDCg5N@uxinc7wJcdhelMIxcK9DBgrLiQqvTft80DH/mTP7uJ3L1FviFfY6W6uFwJA0P9owEVeFRCfV38ArQs/MmDxk295YltmmcjOJ58w5cmPVkrVivI1fUCbSmNi/AE "Haskell – Try It Online")
[Answer]
## REXX, 57 bytes
```
#=1234567890
a='abcdefghij'
say translate(arg(1),a #,# a)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 81 72 bytes
Thanks to Giacomo Garabello for the suggestions.
```
f(char*s){for(;*s++=*s-97U<11?(*s-6)%10+48:*s-48U<11?(*s-9)%10+97:*s;);}
```
[Try it online!](https://tio.run/##VYzRCoIwGEbvfYpBBNvMaCGpzewpuoouxkr9oWbsn96Iz76mQdDdOeeDTyeN1n4FRj/7@4OU6O7QbdvK11S3ynJkY91ZKjnG8YljUmSXUogzDXhga7GL0/wYOM1/uVhykYUsmZw8GEdeCgydQdlGb@ZjwnnggZExIgRqOg@V@Cohiw9XcWNy8Xfv8C9N0eS9awEBFToLphFin34A "C (gcc) – Try It Online")
[Answer]
# Powershell, 94 bytes
```
-join($args|% t*y|%{if(1+($p=($s='1a2b3c4d5e6f7g8h9i0j').IndexOf($_))){$s[$p-bxor1]}else{$_}})
```
Test script:
```
$f = {
-join($args|% t*y|%{if(1+($p=($s='1a2b3c4d5e6f7g8h9i0j').IndexOf($_))){$s[$p-bxor1]}else{$_}})
}
&$f "thisisastring1124"
```
## Explanation
* `$args` - argument strings
* `$args|% t*y` - expands to `|ForEach-Object -Method ToCharArray` equivalent of `"$args".ToCharArray()`
* `($s='1a2b3c4d5e6f7g8h9i0j').IndexOf($_)` - find a char in the string, returns a position or -1 if not found. Let $s stores the string which contains a paired char on neighbor positions that differ by the last bit: 0+1, 2+3, 4+5....
* `if(1+($p=...))` - if position was found
* `$p-bxor1` - position bit xor 1
[Answer]
# [R](https://www.r-project.org/), 107 bytes
```
function(s){a=utf8ToInt(s);l=a>96&a<107;n=a>47&a<58;a[n]=(a[n]-9)%%10+97;a[l]=(a[l]+4)%%10+48;intToUtf8(a)}
```
[Try it online!](https://tio.run/##JcwxC8IwEIbh3f9Rm1CERKJNiXF3r5N0OIRoSrhCc5nE3x5PHe6D9xlurcHXUPBOcUGR5Qt8oWDH5YLE6ZKH83Dcwkmr3iGH6TkO1sENJy@@uxtk02jVDT1j@mGaOvNHY11EGpcrPxUg3zWIlp4xxwyZ1ogPrfemlRvmuWRSfK2sHw "R – Try It Online")
First attempt, definitely improvable...
[Answer]
# [Rust](https://www.rust-lang.org/), 96 bytes
```
|x|x.bytes().map(|x|match
x{49..=57=>x+48,97..=105=>x-48,48=>106,106=>48,x=>x}as
char).collect()
```
[Try it online!](https://tio.run/##HY5BboMwEEX3nGLKorJVYuGKFNzIXKIHqCbUFCJwE89UcpXk7HSUL/3Fe6uXfom3McKKc1QargXIlsAwvsMY1TNx0rDr4YPTHL/Bb7d8y@b4x4GUNiuelYgVeZiKfG2cMX7f@j6/NF3lWiFb7wV3gk3ne1u/VXLfC2fxd6RimDBpM/wsSxhY6e3wSECikPgzXJ7UqEqeZpoJ6RFh7WtTn0pdQcmdI0dWvIst4vHrVJf6UNy3fw "Rust – Try It Online")
Not Unicode-safe, if it was it would be even longer.
[Answer]
# [K4](https://kx.com/download/), 38 bytes
**Solution:**
```
{(,/|x,a)(,/a:0 1_'10 11#'.Q`a`n)?x}@'
```
**Explanation:**
Lookup each character in the list `"abcdefghij1234567890"` and then index into the list `"1234567890abcdefghijX"` where `X` is the original character.
Need to find a shorter way to build the strings...
```
{(,/|x,a)(,/a:0 1_'10 11#'.Q`a`n)?x}@'
{ }@' / apply (@) lambda {} to each (')
?x / lookup x in
( ) / do this together
.Q`a`n / index into .Q with a (gives a-z) and n (gives 0-9)
10 11#' / take 10 from first list and 11 from second list
0 1_' / drop 0 from first list and 1 from second list
a: / save as a
,/ / flatten
( ) / do this together
x,a / prepend x to a
| / reverse it
,/ / flatten
```
**Bonus:**
Another solution for **38 bytes**:
```
{(a,b,x)?[(b:1_11#.Q.n),a:10#.Q.a]x}@'
```
[Answer]
# [Yabasic](http://www.yabasic.de), 135 bytes
Takes input from the console and outputs to the console.
```
Input""s$
For i=1To Len(s$)
c$=Mid$(s$,i,1)
n=asc(c$)-96
If-38>n Then?chr$(143+n+11^(n=-48));ElsIf n<11Then?n*(10>n),"";Else?c$;Fi
Next
```
[Try it online!](https://tio.run/##Hcq9DoIwFEDhvU/RNB1ahcQrqBAEJ0lI1InZBGuRGr0gRUVfHn@2k3znVRwKa9QwZNjcO8YsJ2ndUhNDXtONRmG5JIrHW3Pk33aMA5JgXFglFJduOCdZ6XpBgjSvNK5U1XIBvjfGMcBeYOz6gZTR@mKzkuIS4H/hSMAkQekw9iO9UjxKDdnpvhuG4qCOujxV5ny5Yt3cWtvdH8/@9Yap58/miyCcfAA "Yabasic – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~44~~ 42 bytes
```
V=1oA q +0+"jihgfedcba"Um@W=VaX)¦É?Vw gW:X
```
[Try it online!](https://tio.run/##y0osKPn/P8zWMN9RoVBB20BbKSszIz0tNSU5KVEpNNch3DYsMULz0LLDnfZh5Qrp4VYR//8rlWRkFmcWJxaXFGXmpRsaGpkYAIESAA "Japt – Try It Online")
[Answer]
# sed, 44 bytes
```
y/1234567890abcdefghij/abcdefghij1234567890/
```
A bit boring, I admit.
Testing:
```
$ echo 'thisisastring1124' | sed 'y/1234567890abcdefghij/abcdefghij1234567890/'
t89s9s1str9n7aabd
```
] |
[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/3755/edit).
Closed 5 years ago.
[Improve this question](/posts/3755/edit)
A JAPH is a grand tradition of making a program that prints "Just another Perl hacker,". We already have a question about [JAPH](https://codegolf.stackexchange.com/questions/1/just-another-perl-hacker) on this site but they seem more concerned with hiding the text, but JAPH has always been more about hiding the method by which it does what it does. Therefore I challenge you to show off your favorite language's cool features, and don't worry too much about hiding the text (unless you want to).
Here's mine, in Perl, which shouldn't be to hard for an experienced velociraptor to understand, but may be interesting for others.
```
(*STORE,*TIESCALAR)=map{eval"sub{$_}"}qw'map{print&&sleep$|}split//,pop bless\$|++';tie$t,main;$t="Just another Perl hacker,\n"
```
Judged subjectively on votes by you guys, lets see some mind-benders!
[Answer]
# C
Must be compiled to 32bit. On 64bit machines use `gcc -m32` or such.
```
#include <stdlib.h>
int main() {
char *c = "echo Just another C hacker";
int foo=123; //unused /* Warning: there's a
int k=(int)1 * (long) system
//now for the fun part! * of chinese boxes
//behold: * in this code. */
+0;
-1;
((int(*)(char *))k)(c);
}
```
Disclaimer: not my idea. I found it years ago hidden in some piece of code. Seriously. Theirs was even better, I forgot several little details. But the gist is there.
When you see it, you'll sh\*t bricks.
[Answer]
# Mathematica:
```
TextRecognize@
ImageAssemble@
Transpose@
ImagePartition[Import@"https://i.stack.imgur.com/S9fci.png", 5]
```
[Answer]
## [Dart](http://www.dartlang.org/)
```
class Print{
var PrinT,print,prinT;
get PRint() => PrinT;
get pRInt() => 'A$prinT';
get pRint() => print;
set pRInt(PrinT){print=PrinT;}
set prInt(pRInt){prinT='n$pRInt';}
Print(prinT,PRINT){
PrinT = prinT;
prInt = PRINT;
}
PRINT(print,PrinT){
pRint.PRint('$print ${pRint.pRInt} $PRint $PrinT');
}
Print.print(print,prinT){
pRInt = new Print(print,'other');
PrinT = prinT;
}
}
main(){
Print print = new Print.print(print,'Dart');
print.PRINT('Just','Hacker');
}
```
Edit : less boring setter, less boring getter.
I have studied this language for a day, so I think other people may think this as a child's mess... :(
[Answer]
## PRNG
It's in C, but it actually shows off that you can do cool things using PRNGs and outputs `Just another PRNG hacker`:
```
#include <stdio.h>
#define P 0x3A4B5C6D
char s[6];
int j, t;
void r(int d) {
t = ((P * d + P) << 17) + ((P * d - P) >> 15) + P;
for (j = 0; j < 5; j++) {
s[j] = (t % 51) + 67;
t /= 51;
if ((s[j] >= 91) && (s[j] <= 96)) s[j] = 32;
}
printf("%s", s);
}
int main() {
r(0x444C725);
r(0x2D65DD4B);
r(0x6C5C71A);
r(0xB2A4BBD);
r(0x275BD6F);
return 0;
}
```
Using the built-in PRNG (srand, rand) would be possible, too, but less portable.
[Answer]
# C
```
int main(int _)
{
putchar(~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~
putchar(~-~-~-~-~-~-
putchar(-~-~-~-~-~-~-~-~
putchar(-~-~
putchar(~-~-~-~-~-~-~-
putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
putchar(~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
putchar(~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~
putchar(~-~-~-
putchar(~-~-~-~-~-~-~-~-~-~-~-~-
putchar(-~-~-~-~-~
putchar(-~
putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~
putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
putchar(~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
putchar(-~
putchar(~-~-
putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~_
))))))))))))))))))))));
}
```
[Answer]
# Python
```
credits.__class__(0,'Just another Python hacker')()
```
[Answer]
## Javascript
```
eval('Acy419yt=12-14;'.split('').map(function(x){return String.fromCharCode(
0240-x.charCodeAt(0))}).join(''))[_]((___='splitulengthureverseujoinufilter'
.split('\x75'),function __(_){return _[___[1]]?__(_[___[0][0]+___[___[3]](''
)[___[0]]('')[___[4]](function(_,__){return ~~(__/2)==1})[___[3]]('')+'ce'](
1))+_[0]:_}("Just Another JavaScript Hacker"))[___[0]]('')[___[2]]()[___[3]](''));
```
In my code, JAJSH text was encrypted by reversing it, not only once, but twice!! Ha! Can you find it?
[Answer]
## Haskell
I did this one [with some help](http://www.haskell.org/haskellwiki/Lambdabot).
```
{-# LANGUAGE ForeignFunctionInterface #-}
import Control.Applicative
import Control.Monad
import Foreign
import Foreign.C
foreign import ccall "stdio.h puts"
puts :: CString -> IO ()
main :: IO ()
main = liftM2 allocaBytes length
((<*> puts) . ((>>) .) . flip (flip zipWithM_ [0..] . pokeElemOff))
$ map (fromIntegral . fromEnum) "Just another Haskell hacker\0"
```
And just for fun:
```
{-# LANGUAGE ForeignFunctionInterface #-}
import Control.Exception
import Control.Monad
import Data.Bits
import Data.Word
import Foreign
import Foreign.C
foreign import ccall "stdlib.h realloc"
c_realloc :: Ptr a -> CSize -> IO (Ptr a)
foreign import ccall "stdlib.h free"
c_free :: Ptr a -> IO ()
foreign import ccall "stdio.h puts"
c_puts :: CString -> IO ()
-- | Write a UTF-8 character into a buffer.
--
-- Return the length of the character in bytes, which will be a number from 1-4.
pokeUtf8 :: Ptr Word8 -> Char -> IO Int
pokeUtf8 ptr char =
case (fromIntegral . fromEnum) char :: Word32 of
c | c <= 0x7F -> do
put ptr c
return 1
c | c <= 0x7FF -> do
put ptr (0xC0 .|. c `shiftR` 6)
put (ptr `plusPtr` 1) (0x80 .|. c .&. 0x3F)
return 2
c | c <= 0xFFFF ->
if c >= 0xD800 && c <= 0xDFFF
then replacement
else do
put ptr (0xE0 .|. c `shiftR` 12)
put (ptr `plusPtr` 1) (0x80 .|. c `shiftR` 6 .&. 0x3F)
put (ptr `plusPtr` 2) (0x80 .|. c .&. 0x3F)
return 3
c | c <= 0x10FFFF -> do
put ptr (0xF0 .|. c `shiftR` 18)
put (ptr `plusPtr` 1) (0x80 .|. c `shiftR` 12 .&. 0x3F)
put (ptr `plusPtr` 2) (0x80 .|. c `shiftR` 6 .&. 0x3F)
put (ptr `plusPtr` 3) (0x80 .|. c .&. 0x3F)
return 4
_ -> replacement
where
put p c = poke p (fromIntegral c :: Word8)
replacement = pokeUtf8 ptr '\xFFFD'
withUtf8 :: String -> (CStringLen -> IO a) -> IO a
withUtf8 string action = expand nullPtr 64 0 string where
expand buf bufsize pos str = do
buf' <- c_realloc buf (fromIntegral bufsize)
when (buf' == nullPtr) $ do
c_free buf
ioError $ userError "Out of memory"
write buf' bufsize pos str
write buf bufsize pos str
| bufsize - pos < 4 = expand buf (bufsize * 2) pos str
| otherwise = do
case str of
(c:cs) -> do
len <- pokeUtf8 (buf `plusPtr` pos) c
write buf bufsize (pos + len) cs
[] -> do
pokeByteOff buf pos (0 :: Word8)
finish buf pos
finish buf len =
finally (action (buf, len)) (c_free buf)
puts :: String -> IO ()
puts str = withUtf8 str (c_puts . fst)
main :: IO ()
main = puts "\x266B Just another C hacker using Haskell \x266B"
```
[Answer]
# JavaScript
Run in console
```
({}+[])[!''+!''+!![]] + (!![]+[])[!''+!''] + (![]+[])[!''+!''+!''] + (!![]+[])[+![]] + ({}+[])[!![]+!''+!''+!''+!''+!''+!''] + (![]+[])[+!![]] + ([][{}]+[])[+!![]] + ({}+[])[+!''] +
(!![]+[])[+![]] + 'h' + (![]+[])[!''+!''+!![]+!![]] + (!![]+[])[+!![]] + ({}+[])[!![]+!![]+!''+!''+!''+!''+!''] + ({}+[])[!![]+!''+!![]] + (![]+[])[!![]+!''+!![]] +
({}+[])[!![]+!![]+!![]+!![]+!''+!![]+!![]] + 'h' + (![]+[])[+!![]] + ({}+[])[!![]+!![]+!''+!![]+!![]] + 'k' + (![]+[])[!''+!![]+!![]+!''] + (!![]+[])[+!'']
```
[Answer]
# Python 2.x (single expression)
Now, while this is quite easy to figure out for Pythoneers, others might find it at least interesting. If you wonder why there's so many lambdas, I wanted to have maximum underscoreness, but minimal repetition. Who doesn't love underscores? [Ideone](http://ideone.com/DY6Uso)
```
(lambda ______________:(lambda ______,_______,________:(lambda _____:(lambda _,___,__,____,_____________:(lambda _________,__________:(lambda ___________,____________:___________(____________,____[_________**(_________+__________)-__________::_________+_________+_________]+_[__________::_________]+__[_________+__________])(____________,______________))((lambda _,__:________(______(_))[__]),(________(__import__(_[_________]+__[_________*_________+__________]+_[_________]))[_[_________:_________+_________]+___[__________/_________]+__[__________]+_____(u'')[__________/_________]+_[_________+__________]])))((_____________(_)+_____________(_))/_____________(_),_____________(_)/_____________(_)))(_____([]),_____({}),_____(None),_____({}.__iter__),lambda _:len(_)))(lambda _:_______(______(_))))((lambda _:_.__class__),(lambda _:_.__name__),(lambda _:_.__dict__)))('Just another Python Hacker\n')
```
An indented version if you prefer:
```
(lambda ______________:
(lambda ______,_______,________:
(lambda _____:
(lambda _,___,__,____,_____________:
(lambda _________,__________:
(lambda ___________,____________:
___________(____________,____[_________**(_________+__________)-__________::_________+_________+_________]+_[__________::_________]+__[_________+__________])(____________,______________)) (
(lambda _,__:________(______(_))[__]),
(________(__import__(_[_________]+__[_________*_________+__________]+_[_________]))[_[_________:_________+_________]+___[__________/_________]+__[__________]+_____(u'')[__________/_________]+_[_________+__________]]))) (
(_____________(_)+_____________(_))/_____________(_),
_____________(_)/_____________(_))) (
_____([]),
_____({}),
_____(None),
_____({}.__iter__),
lambda _:len(_))) (
lambda _:_______(______(_)))) (
(lambda _:_.__class__),
(lambda _:_.__name__),
(lambda _:_.__dict__)))('Just another Python Hacker\n')
```
This defines a function and calls it with 'Just another Python Hacker'. Now, it didn't have to be a function, but I thought it would be more elegant.
```
f = (lambda ______________:(lambda ______,_______,________:(lambda _____:(lambda _,___,__,____,_____________:(lambda _________,__________:(lambda ___________,____________:___________(____________,____[_________**(_________+__________)-__________::_________+_________+_________]+_[__________::_________]+__[_________+__________])(____________,______________))((lambda _,__:________(______(_))[__]),(________(__import__(_[_________]+__[_________*_________+__________]+_[_________]))[_[_________:_________+_________]+___[__________/_________]+__[__________]+_____(u'')[__________/_________]+_[_________+__________]])))((_____________(_)+_____________(_))/_____________(_),_____________(_)/_____________(_)))(_____([]),_____({}),_____(None),_____({}.__iter__),lambda _:len(_)))(lambda _:_______(______(_))))((lambda _:_.__class__),(lambda _:_.__name__),(lambda _:_.__dict__)))
f('Hello.\n')
f('Just another Python Hacker here.\n')
```
[Answer]
# QBasic
Here's my implementation in QBasic. The program must be called "JAQBH.BAS" in or for this to execute properly, as it reads its own source as part of the program. And I couldn't find any sane way of determining the name of the currently running script.
```
COMMON SHARED JAQBH$
COMMON SHARED F$
IF F$ = "" THEN F$ = "A.BAS"
OPEN F$ FOR OUTPUT AS #1
PRINT #1, JAQBH$
DATA 20,16,28,24,16
DATA "Just Another QBasic Hacker"
OPEN "JAQBH.BAS" FOR INPUT AS #2
FOR i% = 1 TO 5
READ l%
y$ = INPUT$(l%, #2)
PRINT #1, y$
y$ = INPUT$(2, #2)
NEXT
CLOSE #1
CLOSE #2
F$ = "CON"
READ JAQBH$
CHAIN "A.BAS"
```
[Answer]
# Haskell
Fun with monad transformers:
```
import Control.Monad.State
import Control.Monad.Writer
newtype A a = A (Maybe a)
newtype B = B { c :: String }
instance Show a => Show (A a) where
show (A x) = show x
instance Show B where
show = c
s = [97, 13, 1, 5, -12, -3, 13, -82, 40, 25, 18,
-8, -6, 7, 0, -76, 72, -7, 2, 8, -6, 13]
main = print . A . fmap B . execWriterT . flip evalStateT 0 . mapM f $ s
where f x = modify (+x) >> get >>= tell . return . toEnum
```
[Answer]
## Scala
```
val bi = BigInt ("467385418330892203511763656169505613527047619265237915231602")
bi.toByteArray.map (_.toChar).mkString
```
[Answer]
## Postscript.
Creates a custom font with which to display the text.
```
%!
100 200[>>begin
(Encoding{}FontType 3
BuildChar{exch begin 10 0 setcharwidth load exec stroke end}
FontMatrix .1 0 0 .1 0 0 FontBBox 0 0 10 10)
{token{exch}{exit}ifelse}loop
{4 6}{array astore def}forall
/c{1 string cvs 0 get}4{def}repeat
/J c{7 9 moveto 7 2 lineto 6 4 1 360 190 arcn}
/A c{2 2 moveto 5 8 lineto 8 2 lineto}
/P c{3 2 moveto 3 8 lineto 3 6 2 90 270 arcn}
/s c{5 7 2 0 270 arc 5 3 2 90 180 arcn}
/H c{2 2 moveto 2 8 lineto 8 8 moveto 8 2 lineto 2 4 moveto 8 4 lineto}5{def}repeat
/F currentdict end definefont 20 scalefont setfont
moveto(JAPsH)show
```
[Answer]
## Ruby
Had two ideas and ended up combining them.
```
def Object.const_missing(const)
define_method(:method_missing) do |meth,*args|
"#{meth}"['i'] ? ->a{not$*<<a.pop} :print(meth)
end[const,$\=' ']
end
Begin
case %w[Just another ruby hacker]
when tick
puts 'tock'
when tick
puts 'tock'
when tick
puts 'tock'
when tick
puts 'tock'
else
eval($**$\)
end
```
[Answer]
## Ruby 1.9
Cheesy, highly implementation-dependent, but I hope you find it spooky.
```
class Object
define_method(:!) do |n=3|
send(methods.find{|la|la[/[slappy]{#{n}}/]})
end
end
(!!!:!).!(5) unless respond_to?('Just another ruby hacker,')
```
Edit: [Proof](https://ideone.com/Yp8qCb)
[Answer]
# Python
My JAPH in Python
```
class Foo:
def __init__(s, t='Just another Python hacker'):
def g():
return [100,101,102,32,102,
40,120,41,58,112,114,
105,110,116,32,120],t
s.g = g()
class Z():
def __add__(s,x):return x
s.z = sum((chr(i)for i in s.g[0]),Z())
def __call__(s,t):
return t.join(map(chr,s))
def __iter__(s):
return (ord(i) for i in `s`)
def __repr__(s):
return s.g[-1]
def __getitem__(s, x):
exec s.z
f(s(x))
Foo()['']
```
[Answer]
# JavaScript
```
eval (atob("ZnVuY3Rpb24gcHJpbnQoKSB7CmZ1bmN0aW9uIHRyKGEsYikgewogICAgcmV0dXJuIGEubWFwKGZ1bmN0aW9uKHgpewogICAgICAgIHJldHVybiB4LnRvU3RyaW5nKGIpOwogICAgfSkuam9pbignICcpOwp9CgoKdmFyIGEgPSJXemt5TmpNNE1Td3lNekl3TURJek1UYzNPU3d4TVRnMU5UTTNMREV3TkRVek1EYzBOelZkIjsKYSA9IGF0b2IoYSk7CmEgPSBKU09OLnBhcnNlKGEpOwphID0gdHIoYSwzNik7CmNvbnNvbGUubG9nKGEpOwp9"));
print();
```
[Answer]
# Lua/[RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation)
```
print "Just " -- Write Just to the Console--
print "Another " -- Write Another to the Console--
print "Lua " -- Write Lua, definitely NOT [ 'RProgN' ]--
print "Hacker " -- Do u really thing u r an hacker like i [ ur NOT ]--
```
I'm sure there's a better and sneakier way to combine these two languages.
Hiding in comments is just so overused.
[Try the Lua Out](https://repl.it/DvoN)
[Try the RProgN Out](https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=%09print%20%22Just%20%22%20%09%09%09--%20%09%09%09%09%09%09%20%20%20Write%20Just%20to%20the%20Console--%0A%09print%20%22Another%20%22%20%09%09--%20%09%09%09%09%09%09Write%20Another%20to%20the%20Console--%0A%09print%20%22Lua%20%22%09%20%09%09--%20%09%09%09%20Write%20Lua%2C%20definitely%20NOT%20%20%5B%20%27RProgN%27%20%5D--%0A%09print%20%22Hacker%20%22%20%09%09--%20Do%20u%20really%20thing%20u%20r%20an%20hacker%20like%20i%20%5B%20ur%20NOT%20%5D--&input=)
[Answer]
# [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language
```
removeAllWeapons player
s = primaryWeapon player
call = "scripting " else "language "
a = [if true, if false]
b = ["s=s+(call select 0)", format["s=s+(call select 1)%1%2=%3", {;}, "call", {nil}]]
a select 0 then b
a select 1 then b
a = a + getPos player + [{Just another} + format ([" %1 %2 "] + ("Operation" ELSE "Flashpoint"))]
"b = format[""%2%1%3."", s, _x, call""""""hacker""""""]" count a
titleText (b else "plain")
exit
```
Save as `ofp.sqs` (or any other name), and call with `[] exec "ofp.sqs"`.
**Output:**
[](https://i.stack.imgur.com/6p9ja.jpg)
[Answer]
# [Canvas](https://github.com/dzaima/Canvas)
```
³{┤:js nte avshce@;utaohrcna akr@})∑╷
```
...which **should** work, but `╷` on strings hasn't been implemented yet. Hooray for dead projects! The working version uses the same logic, but is a bit... less obfuscated.
[Try it online!](https://dzaima.github.io/Canvas/?u=JUIzJXVGRjVCJXUyNTI0JXVGRjFBSnMlMjBudGUlMjBhdnNIY2UldUZGMjAldUZGMUJ1dEFvaHJDbmElMjBha3IldUZGMjAldUZGNUQldUZGMDkldTIyMTE) (working version)
[Answer]
# Perl on OSX 10.7+ (requires Xcode)
```
#!/usr/bin/perl
use Inline C=>q{int g(){atexit("j\31\350\31\0\0\0Just \
another Perl hacker\n1\300@\220\17\204\n\0\0\0j\1k\4\x\
cd\x80\203\304\20\303^j\1_Z\270\4\0\0\2\17\5\303");}};g
```
] |
[Question]
[
Given two points `A` and `B`, find the angle from line `AO` to line `BO` about point `O` where `O` is the origin (`(0,0)`). Additionally, the angle may be positive or negative depending on the positions of the points (see examples). Input will be points `A` and `B`, and may be given in any convenient form. Output will be the angle in degrees (but it is positive if `AO` is rotated counter-clockwise about the origin to get `BO` and negative if it is rotated clockwise). If the angle is 180 degrees you may return a negative or positive output. Similarly, the angle can be the positive or negative version of the same angle (`90 deg` is equal to `-270 deg`). Examples:
* Input: `A(5,5) B(5,-5)` Output: `-90` (`AO` is rotated `-90` degrees to get `BO`).
* Input: `A(5,-5) B(5,5)` Output: `90` (`AO` is rotated `90` degrees to get `BO`).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
[Answer]
# TI-BASIC, 13 bytes
For TI-83+/84+ series calculators.
```
Degree
Input Y
min(ΔList(R►Pθ(Ans,∟Y
```
To use this program, enter the list `{x1,x2}` through the Ans variable, and `{y1,y2}` at the prompt.
[Answer]
# Pyth, 11 bytes
```
.t-FPM.jMQ6
```
[Demonstration](https://pyth.herokuapp.com/?code=.t-FPM.jMQ6&input=%5B%5B1%2C+1%5D%2C+%5B1%2C+0%5D%5D&debug=0)
Input is given in the format:
```
[[Bx, By], [Ax, Ay]]
```
If it is desired that A comes first, this can be changed for 1 byte.
Explanation:
```
.t-FPM.jMQ6
Implicit: Q = eval(input())
.jMQ Convert input pairs to complex numbers.
PM Take their phases (angles in the complex plane).
-F Take the difference.
.t 6 Convert to degrees
```
[Answer]
# CJam, 14 bytes
```
q~::ma:-P/180*
```
This is a full program that reads the input as `[[Ax Ay] [Bx By]]` from STDIN.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%3A%3Ama%3A-P%2F180*&input=%5B%5B5%205%5D%20%5B5%20-5%5D%5D).
### How it works
```
q~ e# Read and evaluate all input.
::ma e# Replace each point (x, y) with atan2(x, y).
e# This returns its angle with the positive y axis, measured clockwise.
:- e# Compute the difference of the two resulting angles.
e# This returns the angle between the points, measured counter-clockwise.
P/180* e# Divide by Pi and multiply by 180 to convert to degrees.
```
[Answer]
## [Minkolang 0.9](https://github.com/elendiastarman/Minkolang), 112 bytes
I *really* want to implement trig functions as built-ins now...but this was fun! (Caveat: this outputs the positive angle difference, not the signed angle difference. Given my limitations, I think that's justified.)
```
4[n]0c2c*1c3c*+r4[2;1R]r+1R+0g*12$:;$:8[0ci2*3+d1R;0g$:1i1+[i2*1+d1+$:*]*]$+'3.141592654'25*9;$:$:12$:r-66*5**N.
```
[Try it here.](http://play.starmaninnovations.com/minkolang/?code=4%5Bn%5D0c2c*1c3c*%2Br4%5B2%3B1R%5Dr%2B1R%2B0g*12%24%3A%3B%24%3A8%5B0ci2*3%2Bd1R%3B0g%24%3A1i1%2B%5Bi2*1%2Bd1%2B%24%3A*%5D*%5D%24%2B%273%2E141592654%2725*9%3B%24%3A%24%3A12%24%3Ar-66*5**N.&input=1%202%201%20-2)
### Explanation
I'll post a fuller explanation if anyone wants it, but the gist of it is:
```
4[n] Take in 4 integers from input
0c2c*1c3c*+ dot product
r4[2;1R]r+1R+0g*12$:; magnitudes of vectors
$: dot product divided by magnitudes (z)
8[0ci2*3+d1R;0g$:1i1+ *] Taylor series for arccos
[i2*1+d1+$:*] In particular, the coefficient (1/2 * 3/4 * ...)
$+ Add them all up!
'3.141592654'25*9;$:$: Divide by pi for converting to degrees
12$:r- Subtract from 1/2 - I now have arccos(z)
66*5** Convert to degrees
N. Output as number and stop.
```
[Answer]
# Mathematica, 22 bytes
```
{-1,1.}.ArcTan@@@#/°&
```
**Example:**
```
In[1]:= {-1,1.}.ArcTan@@@#/°&[{{5,5},{5,-5}}]
Out[1]= -90.
In[2]:= {-1,1.}.ArcTan@@@#/°&[{{5,-5},{5,5}}]
Out[2]= 90.
```
[Answer]
# Julia, ~~18~~ 25 bytes
```
f(A,B)=angle(B/A)/pi*180
```
This assumes that "any convenient form" already allows for `A` and `B` to be given as complex numbers. Then, the [complex number arithmetic](http://docs.julialang.org/en/latest/manual/complex-and-rational-numbers/) does all the heavy lifting.
*Edit: converted snippet to function. 18 byte version only works in the Julia REPL.*
[Answer]
# Python 2.7, 73 Bytes
```
from math import*
f=lambda A,B:degrees(atan2(B[1],B[0])-atan2(A[1],A[0]))
```
**Test:**
```
f((5,5),(5,-5)) #-90.0
f((5,-5),(5,5)) #90.0
```
[Answer]
# Octave, 43 bytes
```
f=@(a,b)(cart2pol(b)-cart2pol(a))(1)*180/pi
```
Input/Output:
```
octave:40> f([5,5],[5,-5])
ans = -90
octave:41> f([1,0],[0,1])
ans = 90
```
[Answer]
# Javascript, 66 bytes
```
let f=(a,b)=>(Math.atan2(b.y,b.x)-Math.atan2(a.y,a.x))*180/Math.PI;
```
[demo](http://www.es6fiddle.net/ig8epjjd/)
[Answer]
# Ruby, 64, 58 bytes
```
a=->(b){b.map{|c|Math.atan2(*c)}.reduce(:-)*180/Math::PI}
```
Usage
```
a.call [[5, 5], [5, -5]] # => -90.0
a.call [[5, -5], [5, 5]] # => 90.0
```
[Answer]
# JavaScript, 49 bytes
```
(a,b)=>((c=Math.atan2)(...b)-c(...a))/Math.PI*180
```
Input is taken in form: `[aY, aX], [bY, bX]` (notice the reversed x/y)
[Answer]
# CJam, 15 bytes
```
l~ma@@ma-P/180*
```
Thought I'll get in the CJam game as well. [Try it online](http://cjam.aditsu.net/#code=l%7Ema%40%40ma-P%2F180*&input=5%20-5%205%205).
Input is in form of `bx by ax ay`. Unfortunately, this is the shortest method of doing this challenge without copying Dennis' answer.
[Answer]
# TeaScript, 28 bytes
I really should of implemented trig functions...
```
$.atan2(_[3]-y,z-x)*180/$.PI
```
[Try it online](http://vihanserver.tk/p/TeaScript/?code=%24.atan2(_%5B3%5D-y%2Cz-x)*180%2F%24.PI&input=5) input is `a.x a.y b.x b.y`
### Explanation
```
$.atan2( // Arc Tangent of...
_[3] - y, // 4th input - 2nd input
z - x, // 3rd input - 1st input
) * 180 / $.PI // Converts rad -> deg
```
[Answer]
# [Simplex v.0.7](http://conorobrien-foxx.github.io/Simplex/), 13 bytes
I'm glad I added `mathrelations` :D Unfortunately, I cannot take pointwise input. So, I input each point as a separate number (Ax, Ay, Bx, By). (I used [this](https://stackoverflow.com/a/26076956/4119004) as a resource.)
```
(iRi~^fR)2LSo
( )2 ~~ repeat inner twice
iRi ~~ take two chars of input (x,y)
~ ~~ switch top 2 on stack
^f ~~ apply atan2 on (y,x)
R ~~ go right
L ~~ go left
S ~~ subtract result
o ~~ output as number
```
I can save a char if I can take input as (Ay, Ax, By, Bx):
```
(iRi^fR)2LSo
```
[Answer]
# C, 88 bytes
```
#include<math.h>
typedef double d;d g(d x,d y,d a,d b){return atan2(b-y,a-x)*180/M_PI;}
```
Requires compiling with GCC to take advantage of `M_PI` being defined in `math.h` as a part of [GCC's built-in math constants](http://www.gnu.org/software/libc/manual/html_node/Mathematical-Constants.html).
[Try it online](http://ideone.com/OunR8Y) - since ideone doesn't use GCC (apparently), an additional few bytes are needed for enough digits of π to be accurate.
] |
[Question]
[
In chess, [Forsyth-Edwards Notation](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation), more commonly called "FEN", is a textual way of transcribing boards. It describes each of the board's eight rows (called "ranks" in chess) from top to bottom from White's perspective. The pieces are written as K (king), Q (queen), R (rook), B (bishop), N (knight), and P (pawn). Black pieces use these letters in lowercase, and white pieces use these letters in uppercase. Empty spaces are indicated by a number from 1 to 8 indicating how many consecutive empty spaces there are. A completely empty rank would be `8`, a single black rook in the rightmost column (called "files" in chess) would be `7r`, and two white pawns on each end of a row would be `PP4PP`. Ranks are separated by a `/`. There is normally other information added, indicating which side is to move, castling and *en passant* rights, move number, and halfmove clock, but we will ignore them for the purposes of this challenge.
# Input
A FEN string, from the command line or STDIN, as you please. You may assume that this string is always valid.
# Output
Write to STDOUT a simple ASCII art representation of the board as it would actually appear:
* Pieces are represented by their character in FEN
* Empty squares are represented by spaces
* Pieces and squares are separated by a pipe `|` and there are pipes on each side of the board
So an empty board, written as `8/8/8/8/8/8/8/8` in FEN, would appear as
```
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
```
The starting position of a chess game is written as `rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR`, and would appear as
```
|r|n|b|q|k|b|n|r|
|p|p|p|p|p|p|p|p|
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
|P|P|P|P|P|P|P|P|
|R|N|B|Q|K|B|N|R|
```
The final position of [Anderssen-Kieseritzky 1851](http://www.chessgames.com/perl/chessgame?gid=1018910), called "The Immortal Game" in the chess community, is written as `r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1`, and your program when fed that input would output:
```
|r| |b|k| | | |r|
|p| | |p|B|p|N|p|
|n| | | | |n| | |
| |p| |N|P| | |P|
| | | | | | |P| |
| | | |P| | | | |
|P| |P| |K| | | |
|q| | | | | |b| |
```
[Answer]
# Retina, 13 bytes
```
\d
$*
/
¶
|
```
[Try it online!](http://retina.tryitonline.net/#code=XGQKJCogCi8KwrYKCnw&input=cjFiazNyL3AycEJwTnAvbjRuMi8xcDFOUDJQLzZQMS8zUDQvUDFQMUszL3E1YjE)
## Explanation
The first part (note the trailing space):
```
\d
$*
```
is to convert a to the specific number of spaces. Retina has a `$*` feature to repeat. The way it works is: `<num>$*<char>` if there is no `<num>`, Retina will assume `$&` or the matched string, in this case the matched number.
The next part:
```
/
¶
```
is pretty simple, it replaces all `/` with `¶` which is a newline.
The last part works the same:
```
|
```
This will replace everything (hence why there is nothing on the first line) with `|`. Putting a `|` everywhere.
[Answer]
## Ruby - ~~75~~ ~~82~~ ~~78~~ ~~76~~ ~~75~~ ~~62~~ ~~59~~ ~~58~~ ~~57~~ 56 bytes
```
->n{"|#{n.gsub(/\d|
/){' '*$&.hex}.chars*?|}|".tr'/',$/}
```
*Saved a few bytes thanks to Ventero*
Let me explain (with `\n` replacing the literal newline):
```
->n{"...".tr'/',$/}
```
This implicitly returns the value of the string, with each `/` replaced with a newline (by default, `$/` contains a newline)
```
"|#{...}|"
```
This is super simple; it's just a string containing a pipe, string interpolation, and another pipe. The string interpolation is evaluated
```
n.gsub(/\d|\n/){' '*$&.hex}...
```
This replaces every number with that many spaces. I can save a few bytes by also finding newlines here; because `hex` returns 0 if the string isn't a valid number, when it finds a newline –- i.e. the one at the end of the result of `gets` –- it replaces it with a 0-length string, effectively deleting it. Without this, there would be a trailing pipe.
`$&` is a magic variable which represents the complete text of the latest variable match, which lets me save a byte by eliminating `|d|`. I can save another byte by using `.hex` instead of `.to_i`, which works because every number is less than 9, which means that hex and decimal have the same values.
```
.chars*?|
```
This puts a pipe between every character. Note that this is what puts the pipes on either side of the lines (except the first and last) because the slashes, which eventually turn into newlines through `tr`, count as characters, and are therefore surrounded by pipes. The `?|` just means "the one-character string `"|"`".
And... that's it. It's a frankly scandalously simple program. It just uses a lot of sneaky syntax tricks.
[Answer]
# Perl, 28 bytes
Includes +2 for `-lp`
Give input on STDIN
```
fen.pl <<< "r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1"
```
`fen.pl`:
```
#!/usr/bin/perl -lp
s/\d/$"x$&/eg;s/|/|/g;y;/;
```
Actually in the league of some golfing languages...
Notice that the file based version needs the final newline in the file so that one is really 29 bytes. But the commandline version doesn't need that extra newline and therefore the code counts as 28 bytes:
```
perl -lpe 's/\d/$"x$&/eg;s/|/|/g;y;/;' <<< "r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1"
```
[Answer]
# Pyth - ~~24~~ ~~22~~ 21 bytes
```
.i*\|72jcu:G`H*Hd9z\/
```
[Test Suite](http://pyth.herokuapp.com/?code=.i%2a%5C%7C72jcu%3AG%60H%2aHd9z%5C%2F&input=rnbqkbnr%2Fpppppppp%2F8%2F8%2F8%2F8%2FPPPPPPPP%2FRNBQKBNR&test_suite=1&test_suite_input=8%2F8%2F8%2F8%2F8%2F8%2F8%2F8%0Arnbqkbnr%2Fpppppppp%2F8%2F8%2F8%2F8%2FPPPPPPPP%2FRNBQKBNR%0Ar1bk3r%2Fp2pBpNp%2Fn4n2%2F1p1NP2P%2F6P1%2F3P4%2FP1P1K3%2Fq5b1&debug=0).
```
+ Concatenate
K\| Store "|" in K and use value
+ K Concatenate to end
jK Join string by K, this puts "|" between each char
: String substitution
\/ Replace "/"
b With newline
u Reduce
9 Over [0, 9)
z With input as base case
:G String substitution current val
`H Replace stringifyed int from list we're looping through
*Hd With " "*that int
```
[Answer]
# Pyth, 23 bytes
```
VT=:Q`N*dN;jc.i*\|72Q\/
```
[Try it online!](http://pyth.herokuapp.com/?code=VT%3D%3AQ%60N*dN%3Bjc.i*%5C|72Q%5C%2F&input=%22r1bk3r%2Fp2pBpNp%2Fn4n2%2F1p1NP2P%2F6P1%2F3P4%2FP1P1K3%2Fq5b1%22&debug=0)
How it works:
```
VT=:Q`N*dN;jc.i*\|72Q\/
VT ; for N in range(10):
=:Q`N*dN Q = Q.replace(`N`,repeat(' ',N))
.i*\|72Q temp = interweave(repeat('|',72), Q)
c \/ temp = chop(temp,'/')
j temp = join(temp,'\n')
print temp
```
[Answer]
# JavaScript ES7, ~~80~~ 70 bytes
Is an anonymous function that accepts a string as input.
```
a=>[,...[+t?" ".repeat(t):t<"0"?`
`:t for(t of a)].join``,`
`].join`|`
```
80-byte ES6-only appraoch.
```
a=>a.split`/`.map(x=>[,...x.replace(/\d/g,t=>" ".repeat(t)),`
`].join`|`).join``
```
## Explanation
We use an array comprehension to loop over the list:
```
[+t?" ".repeat(t):t<"0"?`
`:t for(t of a)]
```
This is equivalent to:
```
[!isNaN(parseInt(t, 10)) ? " ".repeat(parseInt(t, 10)) : t === "/" ? "\n" : t for(t of a)]
```
If it's a number, we have that number of spaces. If it's a `/`, we have a newline. Otherwise, we have the character. Then, we join the comprehension with nothing to make a string.
Then, we create an array of length 3 `[,...that,"\n"]`. `...` splats the joined comprehension into chars. Joining this yields the result.
[Answer]
# Julia, 62 bytes
```
s->split("|"join(replace(s,r"\d",d->" "^parse(d)),"|")"|","/")
```
This is an anonymous function that accepts a string and returns an array of strings. To call it, assign it to a variable.
The approach is the same as in QPaysTaxes' clever Ruby [answer](https://codegolf.stackexchange.com/a/78331/20469). We replace each digit in the input with that many spaces, place `|` between each character, tack `|` onto the front and back, and split into an array on `/`.
[Try it online!](http://julia.tryitonline.net/#code=Zj1zLT5zcGxpdCgifCJqb2luKHJlcGxhY2UocyxyIlxkIixkLT4iICJecGFyc2UoZCkpLCJ8IikifCIsIi8iKQoKQmFzZS5wcmludF9tYXRyaXgoU1RET1VULCBmKCI4LzgvOC84LzgvOC84LzgiKSkKcHJpbnRsbigiXG4iKQpCYXNlLnByaW50X21hdHJpeChTVERPVVQsIGYoInJuYnFrYm5yL3BwcHBwcHBwLzgvOC84LzgvUFBQUFBQUFAvUk5CUUtCTlIiKSkKcHJpbnRsbigiXG4iKQpCYXNlLnByaW50X21hdHJpeChTVERPVVQsIGYoInIxYmszci9wMnBCcE5wL240bjIvMXAxTlAyUC82UDEvM1A0L1AxUDFLMy9xNWIxIikp&input=)
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~50~~ 45 bytes
This was fun haha. Not only am I a noob in Retina, but also in regex in general... This can probably be golfed a *lot*, so I'll do some more research.
Code:
```
8
44
7
34
6
42
5
4
4
22
3
2
2
1
/
¶
|
```
[Try it online!](http://retina.tryitonline.net/#code=OAo0NAo3CjM0CjYKNDIKNQogNAo0CjIyCjMKIDIKMgogIAoxCiAKLwrCtgoKfA&input=cm5icWtibnIvcHBwcHBwcHAvOC84LzgvOC9QUFBQUFBQUC9STkJRS0JOUg)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 21 bytes
Code:
```
9GNNð×:}S'|ý"|ÿ|"'/¶:
```
Also 21 bytes: `'|¹9GNNð×:}S'|«JJ'/¶:`.
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=OUdOTsOww5c6fVMnfMO9InzDv3wiJy_Ctjo&input=cm5icWtibnIvcHBwcHBwcHAvOC84LzgvOC9QUFBQUFBQUC9STkJRS0JOUg).
[Answer]
# Python 3.5, 112 bytes:
```
def r(o):print(''.join(['| '*8if h=='8'else'| '*int(h)if h.isdigit()else'|\n'if h=='/'else'|'+h for h in o])+'|')
```
[Try it online! (Ideone)](http://ideone.com/Vwuk9S)
[Answer]
## JavaScript (ES6), ~~69~~ ~~67~~ 62 bytes
```
s=>[,...s.replace(/[/-8]/g,c=>+c?' '.repeat(c):`
`),,].join`|`
```
The extra commas create empty values in the outer split which creates the beginning and ending `|` characters. You need two trailing commas because trailing commas are optional at the end of lists, so the first one is still part of the previous item.
Edit: Saved 5 bytes thanks to @user81655.
[Answer]
## R (out of competition)
Sorry if it's not appropriate to post this, but I thought it was cool that I just happened to have a function lying around that actually works for this question without editing! It prints unicode output rather than ascii, though. I can't remember quite why I wrote it, but it wasn't to answer a challenge.
```
function(x){
# x = FEN position, a string
# can be split with / or ,
# example: forsythe("rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R")
allowed <- c(paste(1:64),
c("k", "q", "r", "b", "n", "p", "K", "Q", "R", "B", "N", "P"))
chars <- strsplit(x, "")[[1]]
chars <- chars[-which(!(chars %in% allowed))]
out <- c()
for (i in 1:length(chars)){
if (chars[i] %in% paste(1:64)){
out <- c(out, rep(" ", as.numeric(chars[i])))
}
else{
out <- c(out, chars[i])
}
}
if (length(out) < 64) out <- c(out, rep(" ", 64-length(out)))
pieces <- strsplit("KQRBNPkqrbnp", "")[[1]]
unicode <- c("\u2654", "\u2655", "\u2656",
"\u2657", "\u2658", "\u2659", "\u265A", "\u265B",
"\u265C", "\u265D", "\u265E", "\u265F")
for (i in 1:64){
if (out[i] %in% pieces){
out[i] <- unicode[which(pieces==out[i])]
}
else{
}
}
out <- matrix(out, nc=8, byrow=T)
#print(out)
plot(0, xlim=c(0, 8), ylim=c(0, 8), type="n", xaxt="n", yaxt="n",
xlab="", ylab="")
for (i in 0:7){ for (j in 0:7){ rect(i, j, i+1, j+1,
col=ifelse(((i+j) %% 2) == 0, grey(0.95), "white"), border=F) }}
for (i in 0:7){ for (j in 0:7){
text(i+0.5, j+0.5, out[8-j, i+1], cex=2)
}}
axis(1, labels=letters[1:8], at=1:8 - 0.5, tick=F)
axis(2, labels=paste(1:8), at=1:8-0.5, las=2, tick=F)
}
```
[Answer]
# Jolf, 28 bytes
```
RΜGi'/dΆγ'|RGρH«\d»d*♣PHEγγS
```
Replace `♣` with the character `\x05`, or [try it here!](http://conorobrien-foxx.github.io/Jolf/#code=Us6cR2knL2TOhs6zJ3xSR8-BSMKrXGTCu2QqBVBIRc6zzrNT&input=cjFiazNyL3AycEJwTnAvbjRuMi8xcDFOUDJQLzZQMS8zUDQvUDFQMUszL3E1YjE)
[Answer]
# C, 252 bytes
```
i=-1,j,s=1,x;C(char*n){while(n[++i])s+=isdigit(n[i])?n[i]*2+1:2;char*m=(char*)malloc(s);for(i=j=-1;n[++i]&(m[++j]='|');)if(n[i]=='/')m[++j]='\n';else if(isdigit(n[i]))for(x=n[i]-'0';x;--x&&(m[++j]='|'))m[++j]=' ';else m[++j]=n[i];m[++j]='\0';return m;}
```
**Detailed** [*try online*](http://ideone.com/t76YtP)
```
// input-string, input-string-size
char* C(char*n)
{
int i=-1,j,s=1,x;
// figure out required grid size
while(n[++i])s+=isdigit(n[i])?n[i]*2+1:2;
char*m=(char*)malloc(s);
i=j=-1;
while(n[++i]) // while not end of string
{
m[++j]='|'; // seperator
if (n[i]=='/') // end of row
m[++j]='\n';
else if (isdigit(n[i])) // fill spaces
for(x=n[i]-'0';x;--x&&(m[++j]='|')) m[++j]=' ';
else
m[++j]=n[i]; // single literals
}
m[++j]='|';
m[++j]='\0';
return m;
}
```
[Answer]
# Haskell, 110 Bytes
```
p '/'="\n"
p c|'1'<=c&&c<='8'=replicate(read[c])' '
p c=[c]
main=getLine>>=putStrLn.('|':).(>>=(:"|")).(>>=p)
```
## Ungolfed:
```
p c | c=='/' = "\n"
| '1'<=c && c<='8' = replicate (read [c]) ' '
| otherwise = [c]
addPipes string = "|" ++ concatMap (\c -> [c] ++ "|") string
main = getLine >>= putStrLn . addPipes . concatMap p
```
[Answer]
# JavaScript (FireFox 30+), 61
Using array comprehension that is not standard EcmaScript anymore
```
f=>'|'+[for(c of f)+c?' |'.repeat(c):c<'A'?`
|`:c+'|'].join``
```
**Test**
```
F=f=>'|'+[for(c of f)+c?' |'.repeat(c):c<'A'?`\n|`:c+'|'].join``
console.log=x=>O.textContent+=x+'\n'
;['8/8/8/8/8/8/8/8','rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR',
'r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1']
.forEach(t=>console.log(F(t)+'\n'))
```
```
<pre id=O></pre>
```
[Answer]
## Python, 84 bytes
```
lambda a:"".join(c*c.isalpha()or"\n"*(c=="/")or" "*int(c)for c in a).replace("","|")
```
Explanation:
```
c*c.isalpha() - if c is alphabetical, use c
"\n"*(c=="/") - if it's "|", replace it with a newline
" "*int(c) - else its an int.
"".join( ).replace("","|") - interweave "|" between the chars
```
[Answer]
## Lua, 106 Bytes
```
print("|"..(...):gsub(".",function(c)return c:find("%d")and(" |"):rep(c)or c=="/"and"\n|"or c.."|"end),'')
```
### Ungolfed
```
print("|".. -- prepend | to the following string
(...):gsub(".",function(c) -- iterate over each character in the argument
return -- replaces in the argument
c:find("%d") -- if c is a number
and(" |"):rep(c) -- replace by " |"*c
or c=="/" -- elseif c is a slash
and"\n|" -- replace by "\n|"
or c.."|" -- else (case letter)replace by c
end) -- return the modified string
,'') -- add an empty parameter to print
-- it suppresses the second output of gsub
```
[Answer]
# ><>, 64 bytes
```
<v?(0:i
r\
"<o-*=@"%/": v?*(@)@":/"::;?(0:o"|
^~?="0":-1o" "<
```
4 wasted bytes due to alignment issues, not sure how to golf them out though. ¯\\_(ツ)\_/¯
[Answer]
# Java 7, ~~190~~ 184 bytes
```
String Z(int c){String m="";if(c==47)m+="|\n";else if(c>57)m+="|"+c;else while(c-->48)m+="| ";return m;}String C(String n){String m="";for(char x:n.toCharArray())m+=Z(x);return m+"|";}
```
**Detailed** [*try online*](http://ideone.com/Lc36JE)
```
public static String Z(char c)
{
String m="";
if(c=='/')m+="|\n";
else if(c>'9')m+="|"+c;
else while(c-->'0')m+="| ";
return m;
}
public static String C(String n)
{
String m="";
for(char x:n.toCharArray())m+=Z(x);
return m+"|";
}
```
[Answer]
## Pyke, ~~25~~ 20 bytes
```
FD~u{RIbd*(s\/n:k\|:
```
Explanation:
```
F ( - for char in input:
D~u{RI - if char in '0123456789':
bd* - char = " "*int(char)
s - sum(^)
\/n: - ^.replace("/","\n")
k\|: - ^.replace("", "|")
```
[Try it here!](http://pyke.catbus.co.uk/?code=FD%7Eu%7BRIbd%2a%28s%5C%2Fn%3Ak%5C%7C%3A&input=r1bk3r%2Fp2pBpNp%2Fn4n2%2F1p1NP2P%2F6P1%2F3P4%2FP1P1K3%2Fq5b1)
[Answer]
# brev, 89 bytes
```
(fn(print(strse x'num(->(m 0)string->number(make-string #\ ))"."(c conc "|")"/""\n")"|"))
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
r\dȰçÃrP'| q'/
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVI&code=clxkyLDnw3JQJ3wgcScv&input=InIxYmszci9wMnBCcE5wL240bjIvMXAxTlAyUC82UDEvM1A0L1AxUDFLMy9xNWIxIg)
```
r\dȰçÃrP'| q'/ :Implicit input of string U
r :Replace
\d : Regex /[0-9]/g
È : Pass each match through a function
° : Postfix increment (to convert from string to integer)
ç : Repeat a space that many time
à :End replace
r :Replace
P : Empty string
'| : With "|"
q'/ :Split on "/"
:Implicit output, joined with newlines
```
] |
[Question]
[
**This question already has answers here**:
[Is it a prime? w/o math [closed]](/questions/20920/is-it-a-prime-w-o-math)
(7 answers)
Closed 9 years ago.
Write a program which determines if a given number is prime.
The catch: No digits or arithmetical operators. This means:
1. No digits from `0` to `9`, anywhere in the program, and whatever the meaning
2. No using any built-in operators for addition (and incrementing), subtraction (and decrementing), multiplication, division, exponentiation, or modulus, anywhere in the program
3. This includes symbols like `+` and functions like `num.add()`
4. All other operations are permitted
5. You may define your own functions for the forbidden operations
6. You may use symbols like `-` when they mean things other than the forbidden operations
Shortest code wins - any language permitted.
# Example solution
An ungolfed solution in Java can be found [here](http://pastie.org/9001717).
[Answer]
# PHP, 117 characters
This one is based on regular expressions. If a string containing *$n* characters can be split into chunks of equal length, then *$n* must be composite.
(Assumes *$n* is a positive integer.)
```
function p($n){$u=true;$s=str_repeat('x',$n);return($s!='x'&&!preg_match('/^(xx{'.$u.',})\\'.$u.'{'.$u.',}$/U',$s));}
```
### Output:
```
for ($i=1; $i<=100; $i++) if (p($i)) echo "$i ";
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
```
[Answer]
## Sage, 18
Looks like this is allowed.
```
input()in Primes()
```
`3` gives `True`, `4` gives `False`
[Answer]
# PERL ~~53~~ ~~54~~ ~~52~~ 48
```
('a'x($_=pop))=~/^a?$|^(?<a>aa+?)\g{a}+$/||print
```
Thanks to reddit: <http://www.reddit.com/r/programming/comments/crmhe/regular_expression_to_check_for_prime_numbers_1111/>
[Answer]
# J - 7 char
Trivial.
```
(p:~=~)
```
This verb is in the form of a hook. Applied to an argument `y`, it will evaluate as follows. (Feel free to check for yourself: [Hook](http://www.jsoftware.com/help/dictionary/dictf.htm), [Reflex/Passive](http://www.jsoftware.com/help/dictionary/d220v.htm), [Equals](http://www.jsoftware.com/help/dictionary/d000.htm), [Primes](http://www.jsoftware.com/help/dictionary/dpco.htm).)
```
(p:~=~) y NB. (F G) y becomes y F (G y) (Hook)
y p:~ (=~ y) NB. x F~ y becomes y F x (Passive)
(=~ y) p: y NB. F~ y becomes y F y (Reflex)
(y = y) p: y NB. anything is equal to itself, so y=y becomes 1
1 p: y NB. 1 p: y tests for primality of y
```
Usage:
```
(p:~=~) 5
1
(p:~=~) 6
0
(p:~=~) 8675309
1
NB. test every element of a list
(p:~=~)every 1627 5231 7610 6311 4549 6990 4220 9028 4066 3496
1 1 0 1 1 0 0 0 0 0
```
[Answer]
## Python 3, 85
```
(lambda i:not any(' '*i==(' '*u)*v for u in range(i)for v in range(i)))(int(input()))
```
Where `*` is not a multiplication operator but a string multiple self-concatenation operator.
[Answer]
# Ruby, 30
```
require'prime';f=->n{n.prime?}
```
Declares a function that returns whether its argument is prime.
Alternative version (same length):
```
require'prime';f=proc &:prime?
```
Obviously bending the rules, but you never said built-in prime functions aren't allowed.
[Answer]
# PHP - 208
```
<?php
function i($n){if($n==strlen(" "))return!!"";foreach(range(strlen(" "),$n) as$_){if($_!=$n){$a=array_fill(!!"",$n,"");while(count($a)>=$_)array_splice($a,!!"",$_);if(!count($a))return!!"";}}return!"";}
```
Type juggling in PHP is fun!
] |
[Question]
[
Write a function (or a whole program) that outputs (or prints) an ASCII art of the initial position of [Mölkky](https://en.wikipedia.org/wiki/M%C3%B6lkky) pins.
### Output :
```
__ __ __
__(07)__(09)__(08)__
(05)__(11)__(12)__(06)
| (03)__(10)__(04) |
| | (01) (02) | |
|__| | | | | |__|
|__| |__| |__|
|__| |__|
```
### Rules :
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins!
* Trailing spaces are allowed on each line
* *Additional* leading spaces (meaning, without counting the already mandatory leading spaces) are allowed **only if** there are the same number of *additional* leading spaces in each of the 8 mandatory lines
* *Additional* newlines are allowed at the beginning and at the end. These additional lines can contain any number of spaces
---
Thanks to [Arnauld](https://codegolf.meta.stackexchange.com/users/58563/arnauld) for the ASCII art and his advices concerning the challenge!
Despite the risk of just having to hardcode and/or compress the output, i hope the challenge will be interesting enough!
I intend to post my own answer in Javascript, but since i forced myself to do it without hardcoding, it has become quite long :')
[Answer]
# [Python 3](https://docs.python.org/3/), 123 bytes
```
print(b'313a@B$""E""Q$6Q%Q$35Q#'.hex().translate(['__','| ',' ',*'\n| ','(%02x)']*9)%(*b' ',))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EI0ndWNjQWCSRkZHRQUBAwImRkVlFiZlZyVVISSlQxSxQVShQxdhUKFBZXS8jtUJDU6@kKDGvOCexJFUjWj0@Xl1HvUZBAUiCCC31mLwaEEdD1cCoQlM9VstSU1VDK0mdnZODVVCIjVmAhZFJXUdT8/9/AA "Python 3 – Try It Online")
## Explanation
This is a two-step compression. A dictionary coding is first applied so that certain chunks of recurring text is mapped to some number. The specific mapping is defined as follows:
```
0 -> '(%02x)'
1 -> '__'
2 -> '| '
3 -> ' '
4 -> '\n'
5 -> '|'
6 -> ' '
```
The `%02x`s are converted to their corresponding values at the end by using a `%` formatting
The compressed string we get after applying the table above is `331331331461010101401010104201010324220303224512222251243651251251243335125123`. This string can then be uncompressed by using [`str.translate()`](https://docs.python.org/3/library/stdtypes.html#str.translate).
A nice trick to compress this by roughly half is to use the [`bytes.fromhex()`](https://docs.python.org/3/library/stdtypes.html#bytes.fromhex) function, which interprets the string as a sequence of hex digits and converts it to a byte-string. Then to decode, we can use the inverse function, [`bytes.hex()`](https://docs.python.org/3/library/stdtypes.html#bytes.hex). Fortunately, all of the hex digits are below `8`, so we can represent all the bytes directly without using any escape codes.
[Answer]
# JavaScript (ES6), 145 bytes
NB: Although I suggested the ASCII art in the sandbox, I didn't make any attempt to compress it until now. I would otherwise have waited before posting this answer.
*-1 thanks to [emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a)*
*-6 by removing trailing spaces, as suggested by [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)*
This is 29 bytes shorter than [hardcoding](https://tio.run/##VYk5DoNADEX7OYVLu0g0Q1YKchWDWKJEiEEQpeLuE9sUAct@1n//XX2ruZ5e4@cwxKZNXZG4eJQgw7ylk0N/I2VuvAsd@ouGEIyZFVdyCwD6kzlv7kwAi2prAikzsiiaeW3@K8bB@rdUt9NlquMwx7499vGJHRKlHw).
```
i=>`232323
3050505
05151504
60515046
66040466
76666676
2767676
227676`.replace(/./g,n=>"( )|"[n>>1]+(n>1?n&1?"__":" ":n+"_798512630412"[i=-~i]))
```
[Try it online!](https://tio.run/##HYhBCoMwFAX3OYX8RYm0ahL1pxUSDyKiYqOkSCJauiq9ulXfLGZ4r@7Trf1i53fk/NNsg9qs0q1ID0jK8gPCcr7DMoLsNBJElu1GIvGYRCIkytNntPFi5qnrDU3iZLw5pYEG4RcqpzWvr9RpXroLL6FpoIAggMJdoZGPe84FpizjAiqrop@tw3DrvVv9ZOLJj3Sg@/EH "JavaScript (Node.js) – Try It Online")
### Encoding
The ASCII art is split into 8 distinct patterns of 3 characters:
```
0: "(0x" 4: ") "
1: "(1x" 5: ")__"
2: " " 6: "| "
3: " __" 7: "|__"
```
The leading character of the \$n\$-th pattern is picked from the lookup string `"( )|"` at index \$\lfloor n/2\rfloor\$.
If \$n>1\$, it is followed by either `" "` (2 spaces) if \$n\$ is even, or `"__"` if \$n\$ is odd.
If \$n\le1\$, we append \$n\$ as the tens digit and pick the units digit from the lookup string `"_798512630412"`, using the initially undefined argument \$i\$ of the function as a counter.
[Answer]
# [Python 3](https://docs.python.org/3/), 137 bytes
```
for k in b"KHLHLHLHKLI IIHKI
I
IQKNI\nIQNKNNQQNNKRNNNNNRNKHRNRNRNKHHRNRN":print(end=f"({k:02d}"*(k<13)or" )|\n"[k%4]+" _"[k%3]*2)
```
[Try it online!](https://tio.run/##HYbLCsIwEADxrehHhAWhqRdtPBW9d9mykFxtEaQWSyAppRdRvz3Szhxm2nf/8k6FUPtOWNE48QDK8lHKV7jBNWa0wC3ucKmJZ1g4nGsm5omeamYyPGCYMsNm7DiQtl3j@ujpqmsN0cemx6T6QRzZy0lJ34GQ38LBze7P5QHEfThVxokM4Q8 "Python 3 – Try It Online")
Each letter in the hardcoded string corresponds to a triple of characters, of one of `" )|\n"` followed by two copies of a space or underscore. The unprintable special characters correspond to pin numbers via their ASCII value. They're printed padded to two digits and preceded by an `(`.
Here's a version without unprintables:
**138 bytes**
```
for k in b"KHLHLHLHKLhIjIiIHKfIlImIgQKNdIkIeQNKNNbQcQNNKRNNNNNRNKHRNRNRNKHHRNRN":print(end=k//96*f"({k-97:02d}"or" )|\n"[k%4]+" _"[k%3]*2)
```
[Try it online!](https://tio.run/##HYZNC4JAFAD/yvIgUCMMjUKhu48nD3avJYH52dauLF6i@u0bOnOYmd7zYE3qfWed0GI0ogYqylUqB3zgiAV1@MQX9pK4QY2tZGKu5V0yk@IFxVQoVmvXgXxyo5mD1jRnHcfZMeog@Ohddsr3SfMD60CE36uBi94cqi2I23JpFSWh938 "Python 3 – Try It Online")
**152 bytes**
```
*s,="%23c"%10*8
t=3
for n in b"
\n\0":
k=2
for c in(n>0)*f"__({n:02})| || ||__|":s[t+t//21*2+k-3//k+k//4*19]=c;k+=1
t+=6
print(*s,sep='')
```
[Try it online!](https://tio.run/##Hc7dCoIwGIBh@q/VRXwMRN2K/UWUsW4kY5AkyWCK7iSya1/WwXv2HLzNyz9rp0Ig3VbjSKoCR4KTI/JaobJuwUHl4I4Xq@VsvZlPcjfN@WiMMwRWSwQ/UgwkcReekhIbk7xdxuUn7QH6f8b0OOuunnrGpCCS2p1izFLL2J6I000XZ0u1QOCpPqCmrZxPhpvu0eg4TkP4Ag "Python 3 – Try It Online")
An alternative method with less hardcoding that turned out longer. Creates the ASCII art by starting with a blank canvas overlaying rectangles like this:
```
__
(01)
| |
| |
|__|
```
with the corresponding pin numbers at the corresponding positions. Thanks to loopy walt for -2 bytes.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~112~~ 110 bytes
```
`0:8 22#?[;;]//[176#"";i[<i]+\:5 2#+\"",7#4 18;{("__";x/"()")," _"^\:"| |"}'-2$$w:101+<i:"HN/;( 5\""]
```
[Try it online!](https://ngn.codeberg.page/k#eJwFwbEKwjAUBVDUyamD4OTwuCmYkkqa0NryXsHVyR9IYlzzBQq2/95zPh1P5L16BJFkbXDjXQFSwlySiTyQVyZitz+hHVVPbpK/Rs6Qn4Vu0LQgynhHxkK0YL3efF1/2XXOzIXxfFk560N1HC4RSBtFkxfF)
Places the pins top to bottom one after another in an initially empty grid.
Some of the strings contain unprintables that are swallowed by SE markdown. Click on the link to get the full code.
[Answer]
-1B from c--
# [C (gcc)](https://gcc.gnu.org/), 150 bytes
```
i;f(c){for(i=0;c="226262425G5I5H41E5K5L5F031C5J5D30331A1B33037333337023737370223737"[i++];printf(c>64?"%02.f)":c&4?"__%c":"%3c",c-64.,"\n( |"[c%4]));}
```
[Try it online!](https://tio.run/##VY5bSwMxEIXf91eEgS2ZXnPdtV2qqK33f1BLkIGVPLhK8c31t6@TKJZOwpc550A4NHslGobYtJLwq30/yLhWDa3BmIqPM/7W3/s7p7f@0T/5G2X1tX/wG6us1Zf6yvJS2zS1MrzV6c0L7OJksm8@DrH75M/PK3cBpTLzFmFFIxYhlAQrKC3BlGaVm0/huZOihx2Vbo/YfA9vL7GTXEuyKBbjQvCEcMKCIVWNicvMM0y2VD4prTNNTioseiGkstlT2XMoRJ/snGhMNJgl2yH8JsfLTqrxl/wzVzsxxovhBw "C (gcc) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 164 163 bytes
* -1 thanks to The Thonnu for the docstring implementation, very neat! I would never have thought to do this.
Very little I tried was shorter than a few substitutions and str repetitions. But, Im horrible at strings in python so please lmk if yall find something. I'm sure theres a better approach in totality and will be checking back on other answer to learn :)
```
a=" |__|"
print(" __"*3+"""
__(07)__(09)__(08)__
(05)__(11)__(12)__(06)
| (03)__(10)__(04) |
| | (01) (02) | |
|__"""+"| "*5+"|__|\n",a*3+"\n ",a*2)
```
[Try it online!](https://tio.run/##HY67CsMwDEV3f4W4k5V08COPduifBEy2dnFDyBLwv7uSlqP7AEnHfX1@Nfe@v0HUSmlwx/mtlxdLVAqGPAJwIn1YWfkyPoXOh1lNjMZkxcKuEfmQLQuWTSzLNbYmsjKxWYnlCjBCDIZZpnyxVTx2Pb1VeUN14t7/ "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/) `-funsigned-char`, 144\* bytes
```
i;main(c){for(;c=c/16?:"3333:\3033;\2003>\3633 6\3233! A! 3!!!32#2#2#!3!3"[i++];)printf(c&12?"(%02d)":L"\n |_"+c%4,c%16-3);}
```
[Try it online!](https://tio.run/##JchBC4IwFABgsFM3nxBddWE4TNK98OCo6N4/aBHyTBvUCq1T9ddblPCdPkoaImu1vJTaRMSf9bWNJC1pnuXrggFgz8VCYYooB0qkKa4U5ohDH3KFAnEc@OBtYBSA46MXwB86LohJzwUI8Fdsp@N4L/mt1eZeRzTNxJpFYSoqzootU8Z/HVhM4WJGYZYnyOXb2g/V57LpbFI/TKcbc6wSOpXtFw "C (gcc) – Try It Online")
There's some unprintable characters in the string, you should be able to see them on TIO.
\*: I wasn't able to insert some characters on TIO, you have to encode each octal char in the string as a single byte instead of an escape code. Here's the string and a bash script to build it locally:
## Try it locally
`str.c`:
```
#include <stdio.h>
char s[] = {
0x11, 0x11, 0x33, 0x11, 0x11, 0x33, 0x11, 0x11, 0x33, 0x10,
0x33, 0x3a, 0xc3, 0x33, 0x3b, 0x03, 0x80, 0x33, 0x3e, 0xf3,
0x33, 0x09, 0x20, 0x11, 0x36, 0xd3, 0x33, 0x17, 0x21, 0x20,
0x11, 0x12, 0x41, 0x11, 0x15, 0x21, 0x11, 0x02, 0x20, 0x33,
0x12, 0x21, 0x11, 0x12, 0x21, 0x11, 0x12, 0x21, 0x33, 0x02,
0x10, 0x11, 0x32, 0x23, 0x11, 0x32, 0x23, 0x11, 0x32, 0x23,
0x10, 0x11, 0x11, 0x21, 0x33, 0x12, 0x21, 0x33, 0x02, 0x00,
};
int main(){fputs(s, stdout);}
```
**bash script**:
```
gcc -o str str.c
cat >molkky.c \
<(printf %s 'i;main(c){for(;c=c/16?:"') \
<(./str) \
<(printf %s '"[i++];)printf(c&12?"(%02d)":L"\n |_"+c%4,c%16-3);}')
# verify size with `wc -c molkky.c`
gcc -w -funsigned-char -o molkky molkky.c
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 67 [bytes](https://github.com/Adriandmen/05AB1E/wiki/codepage)
```
•1wÕ—VîaÉîñG)ùǝn\ιÏòáð×т}í(¿°ç÷É¡¤©•"_ |a(
)"ÅвJº'a•ëç‰ÊÉ&.åÈž•¦S.;
```
[Try it online.](https://tio.run/##AX8AgP9vc2FiaWX//@KAojF3w5XigJRWw65hw4nDrsOxRynDucedblzOucOPw7LDocOww5fRgn3DrSjCv8Kww6fDt8OJwqHCpMKp4oCi4oCcXyB8YSgKKeKAnMOF0LJKwronYeKAosOrw6figLDDisOJJi7DpcOIxb7igKLCplMuO///)
**Explanation:**
Step 1: Generate halve the shape with dummy value for the numbers:
```
•1wÕ—VîaÉîñG)ùǝn\ιÏòáð×т}í(¿°ç÷É¡¤©•
# Push compressed integer 32061609852501126428829348223954853956247903207401179145663962432977933413421358
"_ |a(\n)"√Ö–≤ # Convert it to custom base-"_ |a(\n)", which basically converts it to
# base-length, and indices each value into this string
J # Join this list of characters to a single multiline string
```
[Try just step 1 online.](https://tio.run/##AVkApv9vc2FiaWX//@KAojF3w5XigJRWw65hw4nDrsOxRynDucedblzOucOPw7LDocOww5fRgn3DrSjCv8Kww6fDt8OJwqHCpMKp4oCiIl8gfGEoCikiw4XQskr//w)
Step 2: Mirror it to have the full shape:
```
º # Horizontally mirror the multiline string
```
[Try the first two steps online.](https://tio.run/##AVsApP9vc2FiaWX//@KAojF3w5XigJRWw65hw4nDrsOxRynDucedblzOucOPw7LDocOww5fRgn3DrSjCv8Kww6fDt8OJwqHCpMKp4oCiIl8gfGEoCikiw4XQskrCuv//)
Step 3: Replace the dummy value with the numbers at the correct positions:
```
'a '# Push string "a"
•ëç‰ÊÉ&.åÈž• # Push compressed integer 1070908051112060310040102
¦ # Remove the leading 1
S # Convert it to a list of digits
.; # Replace every first occurrence of "a" in the multiline string one by
# one with these digits
# (after which the result is output implicitly)
```
[I've used this 05AB1E tip to generate the code of step 1.](https://codegolf.stackexchange.com/a/120966/52210)
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•1wÕ—VîaÉîñG)ùǝn\ιÏòáð×т}í(¿°ç÷É¡¤©•` is `32061609852501126428829348223954853956247903207401179145663962432977933413421358` and `•ëç‰ÊÉ&.åÈž•` is `1070908051112060310040102`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 147 bytes
```
sed 's/A/ /g;s/B/__/g;s/C/| /g;s/D/)__(/g'<<E
AABAABAAB
B(07D09D08)B
(05D11D12D06)
C(03D10D04)A|
CC(01D02)AC|
|BCCCCC|B|
A |BC|BC|B|
AAA|BC|B|
E
```
[Try it online!](https://tio.run/##LYg7EsIwDAV7ncJd7EpSwndII1k5hwcGJvRudXdjkrzZYve9nvXbWv28w1BRMARcHxUVS9kkox@XYSol4jrM8wIiugNBI12N7ka3pBDpbMzGo9ElQY40GZPRKYlD7slGY5Ls4Jr/c3WQ0GOju8hhS2s/ "Bash – Try It Online")
*Port of [G B](https://codegolf.stackexchange.com/users/18535/g-b)'s [Ruby answer](https://codegolf.stackexchange.com/a/262433/9481)*
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~156~~ 147 bytes
```
puts"9kkdofqiz475318ru58n0ar9fnhjekvkdkkidk".to_i(36).digits(8).map{|y|" __)__(%s) | |__
"[y*3,3]}.join%("070908051112060310040102".scan /../)
```
[Try it online!](https://tio.run/##DcLtDoIgFADQ/z0FY3OD1vAifuCztMYssvBONNE2y56dPDvTcl1jHJc50BrRDu3LffKqUFJPS6E9NFPd@md3xzdaRGeRinkwjqmSC@sebg5Mc9E343dbN0p2xnBjWBI4IdvemAM9r0d1Upef6AbnE0ahgho0FFLKDEpQEiAHCRkV4dZ4kgqR8hj/ "Ruby – Try It Online")
Second lazy attempt
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 524 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 65.5 bytes
```
»×3Ḃ≥tPkǔλu₍εc7˵z¤ꜝµ]¼εȮẎ-{Cḟȧ7x+¨Ȧ≥yĊ⁋»`
%_|`τ»c;ṅm₴y„»₄τvS2↳›øb%
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9IiwiIiwiwrvDlzPhuILiiaV0UGvHlM67deKCjc61YzfElsK1esKk6pydwrVdwrzOtciu4bqOLXtD4bifyKc3eCvCqMim4omlecSK4oGLwrtgXG4gJV98YM+EwrtjO+G5hW3igrR54oCewrvigoTPhHZTMuKGs+KAusO4YiUiLCIiLCIiXQ==)
A simple "encode everything as a magic number and base decompress" approach.
## Explained
```
»×3Ḃ≥tPkǔλu₍εc7˵z¤ꜝµ]¼εȮẎ-{Cḟȧ7x+¨Ȧ≥yĊ⁋»`
%_|`τ»c;ṅm₴y„»₄τvS2↳›øb%­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏⁠‎⁡⁠⁣⁡⁢‏⁠‎⁡⁠⁣⁡⁣‏⁠‎⁡⁠⁣⁡⁤‏⁠‎⁡⁠⁣⁢⁡‏⁠‎⁡⁠⁣⁢⁢‏⁠‎⁡⁠⁣⁢⁣‏⁠‎⁡⁠⁣⁢⁤‏⁠‎⁡⁠⁣⁣⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣⁣⁢‏⁠‎⁢⁠⁡‏⁠‎⁢⁠⁢‏⁠‎⁢⁠⁣‏⁠‎⁢⁠⁤‏⁠‎⁢⁠⁢⁡‏‏​⁡⁠⁡‌⁣​‎‎⁢⁠⁢⁣‏⁠‎⁢⁠⁢⁤‏⁠‎⁢⁠⁣⁡‏⁠‎⁢⁠⁣⁢‏⁠‎⁢⁠⁣⁣‏⁠‎⁢⁠⁣⁤‏⁠‎⁢⁠⁤⁡‏⁠‎⁢⁠⁤⁢‏⁠‎⁢⁠⁤⁣‏⁠‎⁢⁠⁤⁤‏⁠‎⁢⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁤​‎‎⁢⁠⁢⁡⁢‏⁠‎⁢⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁢⁠⁢⁡⁤‏⁠‎⁢⁠⁢⁢⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁢⁠⁢⁢⁣‏⁠‎⁢⁠⁢⁢⁤‏‏​⁡⁠⁡‌⁢⁣​‎‎⁢⁠⁢⁣⁡‏‏​⁡⁠⁡‌­
»×3Ḃ≥tPkǔλu₍εc7˵z¤ꜝµ]¼εȮẎ-{Cḟȧ7x+¨Ȧ≥yĊ⁋» # ‎⁡The number 230294082147299956815045524104987124251723716866820093416899236760877183504036402931220223094
` # ‎⁢Converted to bijective base "<newline> %_|"
%_|`
»c;ṅm₴y„»₄τ # ‎⁣The list ⟨ 7 | 9 | 8 | 5 | 11 | 12 | 6 | 3 | 10 | 4 | 1 | 2 ⟩
vS # ‎⁤With each number converted to string
2↳ # ‎⁢⁡Padded to have a leading 0 if only one character
øb # ‎⁢⁢Each surrounded in ()
% # ‎⁢⁣Formatted into the bijective base converted string
üíé Created with the help of Luminespire at https://vyxal.github.io/Luminespire
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 132 bytes
```
a=(" "*22+$/)*j=9
"|0/923-71+\\)".bytes{|i|m=j+=i/13*2
"!GCC@".bytes{|k|a[m,n=k/16]=("|__| |(%02d)"%i%=13)[k%8,n];m+=21+n/2}}
$><<a
```
[Try it online!](https://tio.run/##KypNqvz/P9FWQ0lBScvISFtFX1Mry9aSS6nGQN/SyFjX3FA7JkZTSS@psiS1uLomsybXNkvbNlPf0FjLiEtJ0d3Z2QEumV2TGJ2rk2ebrW9oFgs0sSY@vkZBoUZD1cAoRVNJNVPV1tBYMzpb1UInL9Y6V9vWyFA7T9@otpZLxc7GJvH/fwA "Ruby – Try It Online")
Looped version of the below. Explanation to follow.
# [Ruby](https://www.ruby-lang.org/), 139 bytes
```
a=(" "*22+$/)*j=8
"|0/923-71+\\)".bytes{|i|a[j+=i/13*2,4]="(%02d)"%(i%13)
a[j-22,2]="__"
a[j+23,4]=a[j+46,4]="| |"
a[j+69,4]="|__|"}
$><<a
```
[Try it online!](https://tio.run/##JYvLDoMgFET3fAW5kYSHFrkYWxPpj9SGYNoFLvtYmNJvp1J3c@bMPN7zmnNwHChIRFVpIRd3IpBaPaBtjkZNk4DDvL7uz0@KKVwW5aI2VmLdXR1w1uJNAOORGSvIphvEGjfjPRRUaMuwpK7/XxKlaVf9sBfeJ/iS6jyOIecf "Ruby – Try It Online")
A full program that creates a canvas of 8 lines of 22 spaces and a newline, modifies it by adding the pins one by one from top to bottom, and then prints it.
The characters in the magic string are in the format `(number of characters to advance from the previous pin) * 13 + (value of pin)`
It should be possible to golf this quite a bit by drawing each pin line by line from top to bottom using a loop instead of hardcoding each line of the pin.
[Answer]
# [Python](https://www.python.org), 130 bytes
```
A="%25c"%10*9;k=60
for j in b"ouS_7I!-'Y=C"*6:k-=1;j+=k//12%8%6*25;A=A[:j-4]+f" __ | ||__|({-k:02})"[k//24*4:][:4]+A[j:]
print(A)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3mxxtlVSNTJOVVA0NtCyts23NDLjS8osUshQy8xSSlPJLg-PNPRV11SNtnZW0zKyydW0NrbO0bbP19Q2NVC1UzbSMTK0dbR2jrbJ0TWK105QU4uMVahQUamri42s0qnWzrQyMajWVooHqjUy0TKxio62Ayhyjs6xiuQqKMvNKNBw1IS6BOgjmMAA)
## How?
Draws all the pins "simultaneously" line-by-line bottom up so stuff that should be hidden gets overwritten.
### [Python](https://www.python.org), 150 bytes
```
A='';h="| "
for*c,z in*"_ |_|_","| ":h='|'+2*z+h[:7];A=(h[:3:-1]+h[:6]+h+"\n"+A).replace(*c or(4*'|',"(%02x)"),14)
print(A%(*b' ',))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3pznaqqtbZ9gq1SiAgRJXWn6RVrJOlUJmnpZSvIJCTXxNvJIOSFrJKsNWvUZd20irSjsj2so81trRVgPIMLbSNYwFiZgBSW2lmDwlbUdNvaLUgpzE5FQNrWSF_CINEy2gTh0lDVUDowpNJU0dQxNNroKizLwSDUdVDa0kdXZODlZBITZmARZGJnUdTU2I66COhDkWAA)
Not good enough to compete with the xnors and dingledoopers of this world but I still kind of like it.
### How?
Uses the approximate facts that the figure is left-right symmetric and each half's lines can be obtained sequentially by shifting the previous line by three characters (up to a wobble in the centre) to "procedurally" generate the figure. The final number insertion is stolen from dingledooper.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 279 bytes
Solution without hardcoding, which was kind of a hell to write.
But i needed to be exactly sure how much longer it was than the output itself!
```
_=>[...Array(128)].map((_,i)=>(a=i%16)+0*(d=p=>Math.abs(8-a)/2+Math.abs((b=1+i/16|0)-p))(0)?a%2?d(4.5)<=5&b>1?d(2)<=5&b<6?")("[(a/2+b|0)%4%2]:'|':' ':d(2)%4&(d(2)<5&b<5|d(2)==7|i==104)?'__':d(3)<4&b>1&b<6&i!=72?((t=d(2.5)==1.5)?"":"0")+(14-d(3)-b*2+(a+b>11)+t*4):' ':`
`).join``
```
[Try it online!](https://tio.run/##XVDbToNAEH3nK5CEMlMEd1d6semU@AF@gRpYWqo0tRBAowmvvvkJ@nP9kTpLvcXN5szOOWcu2Y1@0s2yLqo22JWr/LCmQ0KL6zAML@tav4BUU7wNH3QFkJwWSAvQVLhyjL4YwooqWlzp9j7UWQPTQOOZ8n9yyEj6xZkcdwKDChEExtpV8QqicIRzGg2yheRMHd/zcewgONeguUnGNW7kqtuZ13kzz/ZmxudGA@j9xj7qzJNo0hVEUkQYe0lifOc4j0xr03JQnNBExQAtsZvHspUxdpyZIxz0QUaBqQiyofJB@1wm0W@HEfJQnppaKYabstil6UE3TV63BPlzlS/bfHVa583jtqU1IP/Lstw15TYPt@UdwJdC9O2Nnf37682Op@4/3jiif7SgZR3bQmrZfJLkP1ocQUzQ4EWPU0bbAjEyGa9rUPXKGK3OtkGc95zouQhtuzN0r0g0qLBPmU6So/J7mTGbfCl/0O4X/MfxSfHwCQ "JavaScript (Node.js) – Try It Online")
---
(i'll add some explanations when i'll have more time to get back into this code)
[Answer]
# [Racket](https://racket-lang.org) - 404 bytes
I didn't want to hardcode the string (even though it would've made life easier). I spent roughly half of today trying to encode the string BY HAND and came up with this solution. I do believe there is a simpler encoded solution, but I had fun :)
```
#lang racket
(let([? char=?])(display(string-join(map(λ(c)(cond[(? c #\a)" "][(? c #\b)"__"][(? c #\c)"\n"][(? c #\d)"__(0"][(? c #\e)")__(0"][(? c #\f)")__\n(0"][(? c #\g)")__(1"][(? c #\h)"| (0"][(? c #\i)") |"][(? c #\j)"| "][(? c #\k)") (0"][(? c #\l)" |"][(? c #\m)"__|"][(? c #\n)"\n "][else(string c)]))(string->list"abababc d7e9e8f5g1g2e6)ch3g0e4icjh1k2ilc|mlllllmn |mlmlmna|mlm"))"")))
```
[Try it online!](https://tio.run/##VZDPbsMgDMbvewqLXuzDpKbt/h22PkgTVdShhITQKsllUt5s79BXSoGtgtlC8P38GVkeJHdqWpaVlU7DENUTWjXhYQ/cyOFzXxHWZrxa@Y3jNBinn9uLcdjLK95@kAn54uoDejusSkkCfIjqAU4kjsckmUTpkqxDFdcJKBL0n5wjKV3O9K@rSKQhMQPkHuM9AHMCbbQk3UVD3mLD8FlHH6bLtAvDxy@UHdXfNoCpInqs5suacRLyFJKhflMf6v38ogu9Ua/EzVav1c5w2xTdxlieexuid@BfPp0MtyAS/tCy3AE "Racket – Try It Online")
---
## Explanation
We first convert the encoded string into a list via `string->list`. We pass this to `map` which passes the encoded character `c` a `lambda` function to test whether `c` matches any defined options. If it does, we return the corresponding string, otherwise we just return `c` as is. After the `map` is finished, we join all the results together and display the single string.
```
(let ([? char=?])
(displayln
(string-join
(map (lambda (c)
(cond [(? c #\a) " "]
[(? c #\b) "__"]
[(? c #\c) "\n"]
[(? c #\d) "__(0"]
[(? c #\e) ")__(0"]
[(? c #\f) ")__\n(0"]
[(? c #\g) ")__(1"]
[(? c #\h) "| (0"]
[(? c #\i) ") |"]
[(? c #\j) "| "]
[(? c #\k) ") (0"]
[(? c #\l) " |"]
[(? c #\m) "__|"]
[(? c #\n) "\n "]
[else (string c)]))
(string->list "abababc d7e9e8f5g1g2e6)ch3g0e4icjh1k2ilc|mlllllmn |mlmlmna|mlm"))
"")))
```
---
## Output
```
__ __ __
__(07)__(09)__(08)__
(05)__(11)__(12)__(06)
| (03)__(10)__(04) |
| | (01) (02) | |
|__| | | | | |__|
|__| |__| |__|
|__| |__|
```
*Have an amazing day everyone :)*
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 62 bytes
```
F⪪”←&∧÷⊘FsK⦃NlE"Φ➙⁺¡﹪!⌕~⎇⸿¤”¶«⸿F⪪ι «M³→¿κ«→↗↑³↙) ↑³↗(⟦__κ ω__
```
[Try it online!](https://tio.run/##hY8/C4MwFMRn/RRHpggWovZ/144tlJZOTSkiWoMSRUSH4mdPX9VBp0Ie4e5@3EuiNKyiIsyNSYoK/FbmquYMYgOIHc1WarECPI/GJ72WGiIgIUgsSUBQJHzmgknNHAcf27pUSlOLrJhzsK1JsSIKI2SdiybmgYv9Vb3T@kdaKgHPhnSIJ9lo3MuJNSwiz0Uwc45Fq09xUtM@B2B/6LGTYD5DH@z1oo9l/atdtHST8eyRzqbTGWMWTf4F "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Corresponds to @xnor's 154-byte Python approach, although I hadn't seen it at the time.
```
F⪪”←&∧÷⊘FsK⦃NlE"Φ➙⁺¡﹪!⌕~⎇⸿¤”¶«
```
Split the compressed string `07 09 08\n05 11 12 06\n 03 10 04\n 01 02"` on newlines and loop over each row.
```
‚∏ø
```
Start a new row of output.
```
F⪪ι «
```
Split the row on spaces and loop over each column.
```
M³→
```
Move to the next column.
```
¿κ«
```
If there is a pin at this position, then...
```
→↗↑³↙) ↑³↗(⟦__κ ω__
```
... draw the pin without moving the cursor.
The cursor actually starts at the cell below the first `_` in the bottom row. It moves right and then up and right, then draws three `|`s up, then draws the `)` and two spaces diagonally down and left (the first of these spaces overwrites one of any `_` from a previous pin), then draws three `|`s up again for the left of the pin, the draws the `)` up and right, then draws 5 lines of text `__`, pin number, space, nothing, `__`, leaving the cursor where it started.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 69 bytes
I was expecting this method to result in more terse code than this, oh well...
```
+ȷṾṫ-Ø(j“Ẓ“m³ṭ’ṃ“#%&$”©¤js4;Ɱ;ƭ@ƒ@
“'EçS¬aßQ35%C‘d5ṃ⁶Ėç/€»/Y®,“| _”¤y
```
A full program taking no arguments that prints the ASCII art, or a niladic Link that yields a string including the newline characters.
**[Try it online!](https://tio.run/##y0rNyan8/1/7xPaHO/c93Lla9/AMjaxHDXMe7poEJHMPbX64c@2jhpkPdzYDucqqaiqPGuYeWnloSVaxifWjjeusj611ODbJgQsoqe56eHnwoTWJh@cHGpuqOj9qmJFiCtLWuO3ItMPL9R81rTm0Wz/y0DodoNoahXiQOUuANgMA "Jelly – Try It Online")**
### How?
Creates each pin in the correct location on its own using characters below `(` and greater than in an order\* such that they may then be merged using `»` (maximum) and finally translates this string into one with the expected characters.
\* Also uses different characters for the `_` at the top of a pin and the `_` at the bottom of a pin so they merge in a different order.
```
+ȷṾṫ-Ø(j“Ẓ“m³ṭ’ṃ“#%&$”©¤js4;Ɱ;ƭ@ƒ@ - Link 1: int PinNumber; lists of space characters [R, C]
+»∑ - {PinNumber} add 1000
·πæ - unevaluate -> list of characters
·π´- - tail from index -1 -> two characters with the leading zero if need be
√ò(j - "()" joined with {that} -> e.g. PPN = "(07)"
¤ - nilad followed by links as a nilad:
“Ẓ“m³ṭ’ - [190, 6908225]
“#%&$” - "#%&$"
© - (copy "#%&$" to the register for later use)
ṃ - base decompress {[190, 6908225]} with digits {"#%&$"}
-> ["%&&%", "#%%##%%##$$#"]
j - join {that} with {PPN}
s4 - split into chunks of length four
-> e.g. ["%&&%", "(07)", "#%%#", "#%%#", "#$$#"]
ƒ@ - start with {that} and reduce with {[r, c]} applying:
∆≠@ - alternate between these with swapped arguments:
;Ɱ - map with concatenate
; - concatenate
-> pin made of #%&$ characters at its desired location
“'EçS¬aßQ35%C‘d5ṃ⁶Ėç/€»/Y®,“| _”¤y - Main Link: no arguments
“'EçS¬aßQ35%C‘ - code page indices = [39,69,23,83,7,97,21,81,51,53,37,67]
d5 - div-mod by five -> [[7,4],[13,4],[4,3],[16,3],[1,2],[19,2],[4,1],[16,1],[10,1],[10,3],[7,2],[13,2]]
ṃ⁶ - base decompress {that} with digits [space character]
Ė - enumerate -> [[1,[" ", " "]], [2,...], ...]
ç/€ - reduce each using Link 1 as a dyad
»/ - reduce by maximum (vectorises)
Y - join with newline characters -> X
¤ - nilad followed by link(s) as a nilad:
® - recall "#%&$" from the register
,“| _” - pair with "| _"
y - translate {X} with mapping {["#%&$", "| _"]}
N.B. $ translates to _ as well as & as it is out of range
- (if running as a program) implicit print
```
] |
[Question]
[
I have a cake shop that specialises in birthday cakes. The cakes that I sell must have candles placed in a circle. You would probably think I can just divide 360° by the number of candles, but the machine for placing candles is quite unique; it uses a list of numbers representing positions of candles, placing them one-by-one until it reaches the desired amount. Furthermore, it can only store numbers as a binary fraction of turns, ie. \$n/2^m\$ where \$\{n,m \in \Bbb Z^{0+} | n < m \}\$.
Since I want the candles placed as evenly as possible, I've devised a method for working out where to place each candle.
The first candle goes at position 0.
In order to balance the cake, the next goes at 1/2.
The next two candles go in the remaining gaps, so 1/4, 3/4.
The next four use the sequence so far to define the order. So 1/8, 5/8, 3/8, 7/8.
Ad infinitum.
To put it more generally:
$$
\begin{aligned}
f(0) &= 0 \\
f(n) &= f(n - 2 ^{\lfloor \log\_2{n} \rfloor}) + 2 ^ {-\lfloor \log\_2{n} \rfloor - 1}
\end{aligned}
$$
Create for me a program or function to create this sequence.
My machine has a small hard drive (I mean *really* small), so the code should be as short as possible.
## Output
The output should follow [standard sequence output](https://codegolf.stackexchange.com/tags/sequence/info). That is, either output the entire sequence (print them one by one or return a list or generator representing the sequence), or given an index \$n\$ (0 or 1 indexed) return the \$n\$th entry or every entry up to the \$n\$th.
The entries can be either represented as a simplified fraction (numerator and denominator separated by `/`) or decimal (rounding errors are acceptable).
The first 64 terms as fractions are
```
0
1/2
1/4
3/4
1/8
5/8
3/8
7/8
1/16
9/16
5/16
13/16
3/16
11/16
7/16
15/16
1/32
17/32
9/32
25/32
5/32
21/32
13/32
29/32
3/32
19/32
11/32
27/32
7/32
23/32
15/32
31/32
1/64
33/64
17/64
49/64
9/64
41/64
25/64
57/64
5/64
37/64
21/64
53/64
13/64
45/64
29/64
61/64
3/64
35/64
19/64
51/64
11/64
43/64
27/64
59/64
7/64
39/64
23/64
55/64
15/64
47/64
31/64
63/64
```
and as decimal
```
0
0.5
0.25
0.75
0.125
0.625
0.375
0.875
0.0625
0.5625
0.3125
0.8125
0.1875
0.6875
0.4375
0.9375
0.03125
0.53125
0.28125
0.78125
0.15625
0.65625
0.40625
0.90625
0.09375
0.59375
0.34375
0.84375
0.21875
0.71875
0.46875
0.96875
0.015625
0.515625
0.265625
0.765625
0.140625
0.640625
0.390625
0.890625
0.078125
0.578125
0.328125
0.828125
0.203125
0.703125
0.453125
0.953125
0.046875
0.546875
0.296875
0.796875
0.171875
0.671875
0.421875
0.921875
0.109375
0.609375
0.359375
0.859375
0.234375
0.734375
0.484375
0.984375
```
[Answer]
# [Python](https://www.python.org), 31 bytes
```
f=lambda a:a and(f(a//2)+a%2)/2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhb702xzEnOTUhIVEq2AOC9FI00jUV_fSFM7UdVIU98IompfWn6RQqJCZp5CUWJeeqqGsZGmVUFRZl4JSLWmJkTRggUQGgA)
Returns the nth term (0-based) as a float.
# [Python](https://www.python.org), 54 bytes
```
a=b=0
while[print(int(bin(a)[:1:-1],2)/-~b)]:a+=1;b|=a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3zRJtk2wNuMozMnNSowuKMvNKNEA4KTNPI1Ez2srQStcwVsdIU1-3Lkkz1ipR29bQOqnGNhGiG2oIzDAA)
Prints decimal fractions indefinitely.
How?
One can check that if we simply count 0,1,2,3,4 ... and mirror the binary representation at the dot we get 0.0 -> 0.0, 1.0 -> 0.1, 10.0 -> 0.01, 11.0 -> 0.11, 100.0 -> 0.001 ... which happens to be precisely what is needed.
[Answer]
# JavaScript (ES6), 32 bytes
Returns the \$n\$-th term, 0-indexed.
```
f=(n,p=0)=>n?f(n>>1,2*p|n&1)/2:p
```
[Try it online!](https://tio.run/##DcxNDoIwEEDhPaeYBTEzgvzFuBBarkKD1GjITAOGTe3ZS1dv8@V9zWH2efu4343ltcRoFXLpVENK82iRtW7L7ur@fGmp7p4uWtmQQUHTA8MAj3tqURD4DGAW3mVdqlXeOBnMPQdKNPdpRGGiPgvxBA "JavaScript (Node.js) – Try It Online")
### 23 bytes
Using [loopy walt's approach](https://codegolf.stackexchange.com/a/246768/58563), this can be further optimized to:
```
f=n=>n&&(f(n>>1)+n%2)/2
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i5PTU0jTSPPzs5QUztP1UhT3@h/Wn6RRp6CrYKBtUKego2CmQmQ1tbWVKjmUlBIzs8rzs9J1cvJT9dISNRQqc6r1QQqVakGmqFZm6BpzVX7HwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes
```
I↨·⁵↨⊗N²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxOFVDz1RHAcxwyS9NyklN0fDMKygt8SvNTUot0tDU1FEw0gQC6///DQ3@65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs the 0-indexed `n`th term. Explanation: Another port of @loopywalt's Python answer.
```
N Input `n`
⊗ Doubled
↨ ² Convert to base 2
↨·⁵ Interpret as base 0.5
I Cast to string
Implicitly print
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
½B.ḋ
```
(or, equivalently, `B.ḋD`)
[Try it online!](https://tio.run/##yygtzv6f@6ip0e//ob1Oeg93dP//DwA "Husk – Try It Online")
Outputs n-th term of sequence.
Same approach as [Neil's variant](https://codegolf.stackexchange.com/a/246771) of [loopy walt's answer](https://codegolf.stackexchange.com/a/246768).
```
ḋ # convert to binary digits
B. # convert from base-0.5
½ # halve
```
This is *much* shorter than calculating the numerator (OEIS A030101: `mȯḋ↔ḋN`) and denominator (OEIS A062383: `mö`^2←LḋN`) separately & combining (`mȯ§/o`^2Lḋ↔ḋN`).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~63~~ 60 bytes
```
float d,v;float f(n){for(d=1,v=0;n;n/=2,d*=2)v+=v+n%2;v/=d;}
```
[Try it online!](https://tio.run/##pVFta4MwEP6@X3EIQqwp1ljbSZZ9GfsVaxmSl07WxaLiZMW/PhcT18oY@7JwFy7PPc/lcuHLA@fDoI5l3oDALXWRQjo4q7JCgsW4ZSuqqY4YwWLBSNCGrA21T2gbMUH7odANvOWFRgGcb8AsV0N2J8kbKZ710x4YnFcYYmuJ3VMbbG2c2WOcuFzs4NTxtzZNUkshsaORzFEzRydbKyGJkyVxT39rRLhGRgGGtbXbmcWbvz0h//PNemqLl7pugL/k1cLskr/KynXm7bpHsuuyB@Oph2F@TrzvR5UVoHHmhRayM7IVncI7qIsPWSp0HX0QTdBihlEIQ6sIbEH3aeMaqzamok3SC@zGWJuEQk3wE5cGn/211e4hmo/dYVfhqTI3KeT5Apb34Cvw6502720w1PgykpoxuZ@u62/64ZOrY36oh@X7Fw "C (gcc) – Try It Online")
*Saved 3 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!!!*
Inputs integer \$n\$.
Returns the \$n^\text{th}\$ element in the sequence as a floating point number.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
BHḅ.
```
A monadic Link that accepts a non-negative integer and yields the element of the binary [Van der Corput sequence](https://en.wikipedia.org/wiki/Van_der_Corput_sequence "Wikipedia") at that 0-indexed index.
**[Try it online!](https://tio.run/##y0rNyan8/9/J4@GOVr3///9bAgA "Jelly – Try It Online")**
### How?
Uses the definition given at Wikipedia's entry for a [Van der Corput sequence](https://en.wikipedia.org/wiki/Van_der_Corput_sequence "Wikipedia") using base two:
$$\text{Corput}\_2(n) = \sum\_{k=0}^{\text{bitLength}(n)-1}{\text{bit}(n, k)\cdot 2^{-k-1}}$$
$$\text{Corput}\_2(n) = \sum\_{k=0}^{\text{bitLength}(n)-1}{\frac{1}{2}\text{bit}(n, k)\cdot \frac{1}{2^k}}$$
```
BHḅ. - Link: non-negative integer, I
B - binary digits of I
H - halve them all
. - a half
ḅ - convert (the list of zeros and halves) from base (one half)
```
[Answer]
# [Factor](https://factorcode.org/), ~~54~~ 42 bytes
```
[ >bin 48 v-n 0 [ [ 2 / ] bi@ + ] reduce ]
```
[Try it online!](https://tio.run/##JYqxCsIwGIT3PsXtYhUpIgriJi4u4lQ6pPGkQZvEP38LPn2Nyg3ffdzdjdUg0/VyOh@36I12ZTSSKP8@8junn@BB8Xwi8TXQWyZEoeo7ivOKXVGsK7igZqqxb51HtcE491iizllhgQatO2CWKbwNlmjytcxqQx9DImhsN30A "Factor – Try It Online")
```
! 9
>bin ! "1001"
48 ! "1001" 48
v-n ! { 1 0 0 1 } (convert from binary string to array)
0 ! { 1 0 0 1 } 0 (push seed value for reduce)
[ [ 2 / ] bi@ + ] ! { 1 0 0 1 } 0 [ [ 2 / ] bi@ + ] (push base 1/2 convert quotation)
reduce ! 9/16
! =========================================================================================
! (now let's look at each iteration of reduce)
! 0 1 (iteration 1)
[ 2 / ] bi@ ! 0 1/2 (divide both by 2)
+ ! 1/2
! 1/2 0 (iteration 2)
[ 2 / ] bi@ ! 1/4 0
+ ! 1/4
! 1/4 0 (iteration 3)
[ 2 / ] bi@ ! 1/8 0
+ ! 1/8
! 1/8 1 (iteration 4 [final])
[ 2 / ] bi@ ! 1/16 1/2
+ ! 9/16
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 64 bytes
```
\d+
$*
+`(1+)\1
$+0
01
1
.+
$&/$.&$*01
1
10
+`01
110
0
1+|^
$.&
```
[Try it online!](https://tio.run/##K0otycxL/K@nzaWidWgbF5eKXgKXqoZ7wv@YFJAQl3aChqG2Zowhl4q2AZeBIZchF0ipmr6KnpqKFphvaABUBGIBGQZcXIbaNXFAU9T@/zc0BQA "Retina 0.8.2 – Try It Online") Link is to test suite that generates the results for `0`..`n` (inclusive, 0-indexed). Explanation: Port of @loopywalt's Python answer.
```
\d+
$*
```
Convert to unary.
```
+`(1+)\1
$+0
01
1
```
Convert to binary.
```
.+
$&/$.&$*01
```
Divide by the next power of `2`.
```
1
10
+`01
110
0
```
Convert to unary, but reading backwards (which is why the power of `2` "ended" in `1`).
```
1+|^
$.&
```
Convert to decimal, but fix up an input of `0` to output `0`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~38~~ 33 bytes
```
If[#<1,0,#0@⌊#/2⌋+#~Mod~2]/2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zMtWtnGUMdAR9nA4VFPl7K@0aOebm3lOt/8lDqjWH0jtf8BRZl5JQoOCiGJSTmp0WnRmbE6CtWZOgpmJrWx/wE "Wolfram Language (Mathematica) – Try It Online")
*-5 bytes thanks to att*
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 23 bytes
```
f(a)=if(a,f(a\2)+a%2)/2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboW29M0EjVtM4GkDhDHGGlqJ6oaaeobQWRvqqTlF2kkKtgqGOgomBnrKBQUZeaVAAWUFHTtgARIs6YmRC3MRAA)
A port of [loopy walt's Python answer](https://codegolf.stackexchange.com/a/246768/97916).
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 8 bytes
Double n, get base 2 representation and interpret as base 0.5
```
0.5/2\2*
```
[Try it online!](https://ngn.codeberg.page/k#eJxLszLQM9U3ijHS4uJKc1A0NODi4gIALMwDpw==)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes (-11 from Steffan, -13 from ATT)
```
#~IntegerReverse~2/2^BitLength@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X7nOM68kNT21KCi1LLWoOLXOSN8ozimzxCc1L70kw0FZ7X9AUWZeSXSavkNQYl56arSBjqFBbOx/AA "Wolfram Language (Mathematica) – Try It Online")
## Explanation
`#~IntegerReverse~` Take the number reversed
`2` in base 2,
`/` divided by
`2^BitLength@#` the nearest greater power of 2 to the input.
If you want to output a list:
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes
```
Table[i~IntegerReverse~2/2^BitLength@i,{i,0,#}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyQxKSc1OrPOM68kNT21KCi1LLWoOLXOSN8ozimzxCc1L70kwyFTpzpTx0BHuTZW7X9AUWZeSXSag6FB7H8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 24 bytes
```
{:2("0."~.base(2).flip)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2spIQ8lAT6lOLymxOFXDSFMvLSezQLP2f3FipYIeUElafpFCnLHBfwA "Raku – Try It Online")
Pity the radix syntax doesn't support non-integer bases.
### Explanation
```
{ } # Anonymous code block
.base(2) # Convert to base 2
.flip # Reverse
"0."~ # Prepend with 0.
:2( ) # Convert back to base 2
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~5~~ 4 bytes
```
b½.β
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJiwr0uzrIiLCIiLCI5Il0=)
## How?
```
b # Get the binary digits of the (implicit) input
½ # halve them all
β # Convert from base
. # 1/2
```
*-1 byte thanks to emanresu A*
[Answer]
# [ayr](https://github.com/ZippyMagician/ayr), 9 bytes
Pretty boring solution, but it works
```
.5#.#:&+:
```
Other solutions include `:.5#.#:+:`, `.5#.-:&#:`, and `:.5#.-:#:`
[Try it!](https://zippymagician.github.io/ayr#Zjo@/LjUjLiM6Jis6/PWYifjYw//)
# Explained
```
#: Convert to base 2
& After
+: Doubling the input
#. Then convert to base 10 from base
.5 1/2
```
[Answer]
# [Desmos](https://www.desmos.com), ~~65~~ 64 bytes
```
f(n)=total(.5mod(floor(nl),2)l)
l=.5^{[floor(log_2(n+0^n))...0]}
```
[Try it on Desmos!](https://www.desmos.com/calculator/0gwb89h18p)
*-1 byte thanks to Aiden Chow*
[Answer]
# APL+WIN, 16 bytes
Prompts for nth term 0 indexed. Uses the binary/base 0.5 approach.
```
.5⊥((n⍴2)⊤n←⎕),0
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv57po66lGhp5j3q3GGk@6lqSB5QCKtHUMfgPlOf6n8ZlwJXGZQjERkBsDMQmQGwKxGZAbA7EFkBsyQUA "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
Here's one for fans of [Cabin Pressure](https://en.wikipedia.org/wiki/Cabin_Pressure_(radio_series)). There is an episode in which the characters devise a new version of Fizz Buzz, which is simplified to contain absolutely no mathematics.
It has these rules:
* If someone says "fizz", you say "buzz".
* If someone says "buzz", you sing "'ave a banana"
* If someone says your name, you say "fizz".
The result is that whenever a name is uttered, that person says "fizz" and the sequence has to run to completion.
---
Let's write some code.
I'd like you to write a program/function/whatever which works thus:
* It accepts one single string of text as input.
* If the string equals the name of the language your code is written in, it outputs "fizz".
* If the string equals "fizz", it outputs "buzz".
* If the string equals "buzz", it outputs "'ave a banana" (note the apostrophe at the start).
* If the input is not one of these things, it should terminate.
* Here's the kicker: The output string must go to two places.
* + Output to be seen by the user
* + Back into your code as input
* I don't really care if they are output in each iteration, or build a string for eventual output.
* Outputs must be separated by new lines (in console or result string)
# Rules
* This is code golf, write in any language you like and attempt to make your code as small as possible.
* Standard loopholes apply.
* I'd like to see links to an online interpreter.
* The language name can be a full name or common short-form of the language the answer is written in. E.g. JS is acceptable, but shortening Ruby to R is not).
# Test Cases
Input
```
'buzz'
```
Output
```
'ave a banana
```
---
Input
```
'fizz'
```
Output
```
buzz
'ave a banana
```
---
Input
```
ruby # or the name of the language your answer is written in
```
Output
```
fizz
buzz
'ave a banana
```
---
Input
```
something else
```
No output
[Answer]
# perl -M5.010 -n, 47 bytes
```
"Perl\nfizz\nbuzz\n'ave a banana"=~/\b$_/;say$'
```
[Try it online!](https://tio.run/##K0gtyjH9/18pAEjH5KVlVlXF5CWVgkj1xLJUhUSFpMQ8IFSyrdOPSVKJ17cuTqxUUf//H6Se619@QUlmfl7xf11fUz0DQ4P/unkA "Perl 5 – Try It Online")
Prints whatever is following the input, or nothing if there is no match. Assumes input is newline terminated.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“Çȥȧ>$ỌĿɦ@⁴Ƙ½Æ/ṠṫḞƇ»Ỵṣ⁸ḊẎY
```
**[Try it online!](https://tio.run/##AVEArv9qZWxsef//4oCcw4fIpcinPiThu4zEv8mmQOKBtMaYwr3Dhi/huaDhuavhuJ7Gh8K74bu04bmj4oG44biK4bqOWf///ydhdmUgYSBiYW5hbmE "Jelly – Try It Online")**
### How?
```
“...»Ỵṣ⁸ḊẎY - Link: list of characters, W
“...» - compressed string = "Jelly\nfizz\nbuzz\n'ave a banana"
Ỵ - split at newlines = ["Jelly","fizz","buzz","'ave a banana"]
ṣ - split at:
⁸ - chain's left argument, W e.g. "Jelly" -> [[],["fizz","buzz","'ave a banana"]]
Ḋ - dequeue = [["fizz","buzz","'ave a banana"]]
Ẏ - tighten = ["fizz","buzz","'ave a banana"]
Y - join with new lines = "fizz\nbuzz\n'ave a banana"
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 63 bytes
```
bash=fizz
fizz=buzz
buzz="'ave a banana"
echo ${x=${!1}}&&$0 $x
```
[Try it online!](https://tio.run/##S0oszvgf4BjiYatnpQKi/ycBRWzTMququECEbVIpkAUibJXUE8tSFRIVkhLzgFCJKzU5I19BpbrCVqVa0bC2Vk1NxUBBpeL/f7AJAA "Bash – Try It Online")
This requires `.` to be in your `PATH`. If that's not acceptable, then replace `$0` with `./$0` (assuming the program is being run from the current working directory) at the cost of 2 bytes (65 bytes total).
Input is passed as an argument, output is on stdout. The language name is entered as `bash`.
(There's spurious output to stderr, but that's OK under our generic rules.)
[Answer]
# JavaScript (ES6), 64 bytes
Expects `"js"` for the language name. Returns an array of strings.
```
s=>[k="js","fizz","buzz","'ave a banana"].filter(w=>k*(k|=s==w))
```
[Try it online!](https://tio.run/##ZY1NDoIwEIX3nqLpxtYoNxguYlwMOMXS2jFMhYR499rgTvIWL/nyfkacUfrJv/Il8Z2KgyLQXgPoUfRZO7@u1br3ZkecSaHqMFXpW@N8zDSZBdpwMuEDArBYW3pOwpGayINx5le29vCHt@k9rrd7KPyk/PBpUBSFaqB8AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 56 bytes
```
$
¶Retina¶fizz¶buzz¶'ave a banana
^(.*¶)(.*¶)*?(\1|.*$)
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX4Xr0LYgMP/QtrTMqqpD25JKQaR6YlmqQqJCUmIeEHLFaehpHdqmCSG17DViDGv0tFQ0uf7/h@jlAmnlAunkQtEIAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
$
¶Retina¶fizz¶buzz¶'ave a banana
```
Append the possible inputs and outputs.
```
^(.*¶)(.*¶)*?(\1|.*$)
```
Try to delete only up to and including a line matching the original input. If this is not possible, then just delete everything.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~46~~ 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
’
05AB1E
fizz
ÒÖ
'ž™ a æé’I¶.ø¡¦θ
```
-13 bytes by porting [*@Abigail*'s Perl answer](https://codegolf.stackexchange.com/a/205794/52210), so make sure to upvote her!!
Outputs `[]` for invalid inputs.
[Try it online.](https://tio.run/##yy9OTMpM/f//UcNMLgNTRydDV660zKoqrsOTDk/jUj@671HLIoVEhcPLDq8EqvA8tE3v8I5DCw8tO7fj/3@IcgA)
**Original 46 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:**
```
"fizz"U•äƵí•hRQiX=}XQi'ÒÖ=}'ÒÖQi’'ž™ a æé’,}õ?
```
Outputs nothing for invalid inputs.
[Try it online.](https://tio.run/##yy9OTMpM/f9fKS2zqkop9FHDosNLjm09vBbIyAgKzIywrY0IzFQ/POnwNNtaMBWY@ahhpvrRfY9aFikkKhxednglkK9Te3ir/f//BqaOToauAA)
**Explanation:**
```
’
05AB1E
fizz
ÒÖ
'ž™ a æé’ '# Push dictionary string "\n05AB1E\nfizz\nbuzz\n'ave a banana"
I # Push the input
¶.ø # Surround it with leading and trailing newline
¡ # Split the string on this
¦ # Remove the first part (for invalid inputs)
θ # Pop and only leave the last part (or an empty list)
# (and output it implicitly as result)
"fizz"U # Puts "fizz" in variable `X`
•äƵí• # Push compressed integer 14793296
h # Convert it to hexadecimal: E1BA50
R # Reverse it to 05AB1E
Qi } # If the (implicit) input-string is equal to this:
X # Push "fizz" from variable `X`
= # Print it with trailing newline without popping
X # Push "fizz" from variable `X`
Qi } # If the top of the stack equals "fizz",
# which will use the (implicit) input if the stack is empty:
'ÒÖ '# Push dictionary string "buzz"
= # Print it with trailing newline without popping
'ÒÖQi } '# If the top of the stack (or implicit input) equals "buzz":
’'ž™ a æé’ '# Push dictionary string "'ave a banana"
, # Pop and print it
õ? # Print "" without newline
# (for invalid input, which otherwise would be output implicitly)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•äƵí•` is `14793296`; `'ÒÖ` is `"buzz"`; and `’'ž™ a æé’` is `"'ave a banana"`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~77~~ 76 bytes
```
t="Python","fizz","buzz","'ave a banana"
*map(print,t[t.index(input())+1:]),
```
[Try it online!](https://tio.run/##VY7BCsIwDIbveYqQi62OgXgr7B28i4d2rVhwXWkz2fbys91OJofkT0j@Ly78HsNt60frsEMi2rij@z6lhl5@XUsx015O@utQo9GhJMF50FHE5AM3/ODWB@tm4UOcWEh5uaqnbLbyEPwQx8SYlwyvMWFGH6poM1sfFOB@Usw/ejBWK6yb5KOQgJwW5WbXi8pXtJt7F1lh1DkD7t6CuiNIbgc3VGqozPBHDNr0Fo7@Bw "Python 3 – Try It Online")
Takes input from `STDIN`, and print the results to `STDOUT`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 43 [bytes](https://github.com/abrudz/SBCS)
```
'APL' 'fizz' 'buzz' '''ave a banana'(↑⍳↓⊣)⊂
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X90xwEddQT0ts6oKSCWVgil19cSyVIVEhaTEPCBU13jUNvFR7@ZHbZMfdS3WfNTV9D/tUduER719j7qaD603Bsn2TQ0OcgaSIR6ewf/TFMCmcunq6nKlQc2GccA2wDjlGYklqWXF6gA "APL (Dyalog Unicode) – Try It Online")
List of string literals is quite expensive...
### How it works
```
S←'APL' 'fizz' 'buzz' '''ave a banana' ⍝ Let's call this array S
S(↑⍳↓⊣)⊂ ⍝ The function
S( ⍳ )⊂ ⍝ 1-based index of the input in S, 5 if not found
↓⊣ ⍝ Drop that many items from the start of S
↑ ⍝ Convert the remaining items to be placed on each line
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 117 bytes
```
void a(String s){System.out.println(s=s=="fizz"?"buzz":s=="buzz"?"'ave a banana":s=="java"?"fizz":"");if(s!="")a(s);}
```
[Try it online!](https://tio.run/##VY49DoMwDIVnOIXL0jCUA4AiTtCJsepgfhUKAeFAKYiz0zRBaisP8XvP9pcaJ7x0fSHr/LH3Y9qIDLIGieCKQsLqus7hkkKln6kTObQ6Y4kahKxud8ChIt@MOmZpBg6yeJoLzI@0PQfIvFIsi/eV6fgna/2RH1mOk003dzdIPHhA/pq8SBVt0I0q6LWnGsmIE@cWEdvT4ccwXeydcSoAIUWpyyaGF9uN0NMoUTI6cd0hIz/a9m1/Aw "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes
```
≔⪪“Jε(h&]⦄_⁷¦⊗‹f·ⅈ⦄⊗x⍘ς3➙A⁸“↑”¶υΦυ№…υκθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8juCAns0RDyRkqHpOXlllVFZOXVAoi1RPLUhUSFZIS84BQSUdBKSZPSVNHoVTTmiugKDOvRMMtM6cktUijVEfBOb8UyHeuTM5Jdc7ILwAJZQOVFmpqalr//w8z/r9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪪“Jε(h&]⦄_⁷¦⊗‹f·ⅈ⦄⊗x⍘ς3➙A⁸“↑”¶υ
```
Split the string `Charcoal\nfizz\nbuzz\n'ave a banana` on newlines and save the result in a variable.
```
Φυ№…υκθ
```
Filter on the result and show only those entries that appear after the input.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~102~~ 79 bytes
```
a='fizz'
b='buzz'
def f(s):t={'Python':a,a:b,b:"'ave a banana"}[s];print t;f(t)
```
[Try it online!](https://tio.run/##XY2xDsIwDET3fIWVxa2UidFV/oEdMThtIrqkUWMQLeLbQ0jFgm/wSWffS5vclngqhS2Ged9ROYvu/jWTDxC63JPYF57bHRIbJmccaeSHBwbHsUq/L/k6pHWOAjKETvoSlhUyzBF@rwYOQN2t38BfRw3YjROSAlk3amwF/jn6JASJc1ZwILSto8sH "Python 2 – Try It Online")
Uses a different approach from the other answer, recursive function
Edit: Thanks @SurculoseSputum for saving 23 bytes!
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~52~~ 47 bytes
```
∧"Brachylog
fizz
buzz
'ave a banana"ṇ;?⟨a₁h⟩b~ṇ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6kUFCUn1KanFpspfRwV@fDHduApH31o7YNj5qa9R51rFDSSEvMzCktStVUqoUrqH24dcL/Rx3LlZxgZnGlZVZVcSWVAgn1xLJUhUSFpMQ8IFR6uLPd2v7R/BWJj5oaMx7NX5lUBxT5/z9aKS2xOCVNSUcJpBFIwU0CskHGACmv1JycSiCNamAsAA "Brachylog – Try It Online")
The predicate fails on inputs on which it should "terminate". If outputting an unbound variable is more desirable, +2 bytes for `.∨`; if an empty string is necessary, +1 on top of that for `Ẹ`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~115~~ \$\cdots\$ ~~105~~ 98 bytes
Saved 4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Saved 7 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!!!
```
i;*y[]={"c","fizz","buzz","'ave a banana"};f(char*s){for(i=0;i<3;)strcmp(s,y[i++])||puts(s=y[i]);}
```
[Try it online!](https://tio.run/##bY7RaoMwFIbv@xSHwNiJplBYe7PUJ3G5SENsIyaKSQdqfXZ35iyMsT8XP0m@83HM/mrMsjiZDaUqJmaYYJUbR6rLfa1X/WlBw0UHOmyWFZqb7rPIp6rt0RUH6c5vksfUG99hFEPp8lzxx6O7p4ixoLvicl68dgE5TDugrIoMEhTgddO0Bk9ZdKNtNzvncuW89aYbMAkYBBz/RVJ5VKRhsfU23Vy4gm2iZT@ftCKgCwlqQg6S6gwnCXlePzf5TtcTUiF7ie8fgQlS1mqzrxL88/Dk979Dkxsy7@blCw "C (gcc) – Try It Online")
[Answer]
## Kotlin, 103 bytes
```
fun f(x:String){listOf("fizz","buzz","'ave a banana").fold("Kotlin"){a,b->if(x==a){println(b);f(b)};b}}
```
[Try it online!](https://pl.kotl.in/k5cal-_iM)
] |
[Question]
[
I came upon this question, because it seems to be very common use-case to find unique characters in string. But what if we want to get rid of them?
Input contains only lower case alphabets. Only letters from a to z are used. Input length may be from 1 to 1000 characters.
Example:
input: helloworld
output: llool
Objective: Shortest code wins
Language: Any of the [top 20 of TIOBE languages](http://en.wikipedia.org/wiki/TIOBE_index)
[Answer]
### (GolfScript, 15 13 characters)
```
:;{.;?);>?)},
```
GolfScript is not one of the top 20, but a codegolf without GolfScript... ([run it yourself](http://golfscript.apphb.com/?c=OydoZWxsbyB3b3JsZCcKCjo7ey47Pyk7Pj8pfSwKCnByaW50))
*Previous Version:
([run script](http://golfscript.apphb.com/?c=OydoZWxsbyB3b3JsZCcKCjEvOjt7O1wtLDssKDx9LAoKcHJpbnQ%3D))*
```
1/:;{;\-,;,(<},
```
[Answer]
## Perl, 28 24 characters (includes 1 for 'p' option)
```
s/./$&x(s!$&!$&!g>1)/eg
```
Usage:
```
> perl -pe 's/./$&x(s!$&!$&!g>1)/eg'
helloworld
llool
```
At first I thought I could do this with negative look-ahead and negative look-behind, but it turns out that negative look-behinds must have a fixed length. So I went for nested regexes instead. With thanks to [mob](https://codegolf.stackexchange.com/users/5202/mob) for the `$&` tip.
[Answer]
## J, 12 characters
Having entered a valid Perl answer, here's an invalid (language not in the TIOBE top 20) answer.
```
a=:#~1<+/@e.
```
Usage:
```
a 'helloworld'
llool
```
Declares a verb `a` which outputs only non unique items.
[Answer]
## GolfScript (14 chars)
```
:x{{=}+x\,,(},
```
[Online demo](http://golfscript.apphb.com/?c=OydoZWxsbyB3b3JsZCcKCjp4e3s9fSt4XCwsKH0sCgpwcmludA%3D%3D)
Might not qualify to win, but it's useful to have a yardstick.
[Answer]
# Ruby 46 40 36
```
gets.chars{|c|$><<c if$_.count(c)>1}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~6~~ 5 bytes
```
ÆèX É
```
*-1 byte thanks to @Oliver*
[Try it online!](https://tio.run/##y0osKPn//3Db4RURCoc7//9XykjNyckvzy/KSVECAA "Japt – Try It Online")
[Answer]
## Perl 44
```
$l=$_;print join"",grep{$l=~/$_.*$_/}split""
```
Execution:
```
perl -lane '$l=$_;print join"",grep{$l=~/$_.*$_/}split""' <<< helloworld
llool
```
[Answer]
# Mathematica 72 63
Ok, Mathematica isn't among the top 20 languages, but I decided to join the party anyway.
`x` is the input string.
```
"" <> Select[y = Characters@x, ! MemberQ[Cases[Tally@y, {a_, 1} :> a], #] &]
```
[Answer]
# K, 18
```
{x@&x in&~1=#:'=x}
```
[Answer]
## Python 2.7 (~~52~~ 51), ~~Python 3 (52)~~
I didn't expect it to be so short.
2.7: `a=raw_input();print filter(lambda x:a.count(x)>1,a)`
~~3.0: `a=input();print''.join(i for i in a if a.count(x)>1)`~~
`raw_input()`: store input as a string (`input()` = `eval(raw_input())`)
(Python 3.0: `input()` has been turned into `raw_input()`)
`filter(lambda x:a.count(x)>1,a)`:
Filter through all characters within `a` if they are found in `a` more than once (`a.count(x)>1`).
[Answer]
## sed and coreutils (128)
Granted this is not part of the TIOBE list, but it's fun (-:
```
<<<$s sed 's/./&\n/g'|head -c -1|sort|uniq -c|sed -n 's/^ *1 (.*)/\1/p'|tr -d '\n'|sed 's:^:s/[:; s:$:]//g\n:'|sed -f - <(<<<$s)
```
De-golfed version:
```
s=helloworld
<<< $s sed 's/./&\n/g' \
| head -c -1 \
| sort \
| uniq -c \
| sed -n 's/^ *1 (.*)/\1/p' \
| tr -d '\n' \
| sed 's:^:s/[:; s:$:]//g\n:' \
| sed -f - <(<<< $s)
```
### Explanation
The first sed converts input into one character per line. The second sed finds characters that only occur once. Third sed writes a sed script that deletes unique characters. The last sed executes the generated script.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), 8 bytes
```
⊇.oḅlⁿ1∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FXu17@wx2tOY8a9xs@6lj@/79SYlJickpqYkqS0v8oAA "Brachylog – Try It Online")
Function submission. Technically noncompeting because the question has a limitation on what langauges are allowed to compete (however, several other answers have already ignored the restriction).
## Explanation
```
⊇.oḅlⁿ1∧
⊇ Find {the longest possible} subset of the input
o {for which after} sorting it,
ḅ and dividing the sorted input into blocks of identical elements,
lⁿ1 the length of a resulting block is never 1
. ∧ Output the subset in question.
```
[Answer]
## Python (56)
Here's another (few chars longer) alternative in Python:
```
a=raw_input();print''.join(c for c in a if a.count(c)>1)
```
---
If you accept output as a list (e.g. `['l', 'l', 'o', 'o', 'l']`), then we could boil it down to **49** characters:
```
a=raw_input();print[c for c in a if a.count(c)>1]
```
[Answer]
## Perl (55)
```
@x=split//,<>;$s{$_}++for@x;for(@x){print if($s{$_}>1)}
```
Reads from stdin.
[Answer]
## C# – 77 characters
```
Func<string,string>F=s=>new string(s.Where(c=>s.Count(d=>c==d)>1).ToArray());
```
If you accept the output as an array, it boils down to **65** characters:
```
Func<string,char[]>F=s=>s.Where(c=>s.Count(d=>c==d)>1).ToArray();
```
[Answer]
# Ocaml, ~~139~~ 133
Uses ExtLib's ExtString.String
```
open ExtString.String
let f s=let g c=fold_left(fun a d->a+Obj.magic(d=c))0 s in replace_chars(fun c->if g c=1 then""else of_char c)s
```
Non-golfed version
```
open ExtString.String
let f s =
let g c =
fold_left
(fun a c' -> a + Obj.magic (c' = c))
0
s
in replace_chars
(fun c ->
if g c = 1
then ""
else of_char c)
s
```
The function `g` returns the number of occurences of c in the string s. The function `f` replaces all chars either by the empty string or the string containing the char depending on the number of occurences. Edit: I shortened the code by 6 characters by abusing the internal representation of bools :-)
Oh, and ocaml is 0 on the TIOBE index ;-)
[Answer]
# PHP - 70
```
while($x<strlen($s)){$c=$s[$x];echo substr_count($s,$c)>1?$c:'';$x++;}
```
with asumption $s = 'helloworld'.
[Answer]
# Java 8, 90 bytes
```
s->{for(char c=96;++c<123;s=s.matches(".*"+c+".*"+c+".*")?s:s.replace(c+"",""));return s;}
```
**Explanation:**
[Try it online.](https://tio.run/##hVDBTsMwDL3vK6ycEsoiARIShMIXsAtHxCG42ZqSJlXsDqGp314ykQMnkGzZfn7ye/Jgj3abJheH7mPFYIng2fp42gD4yC7vLTrYnUeAF84@HgBlbUiZgi8lSxBb9gg7iNDCStvH0z5lib3NgO3drWkafLi6vjHUkh4tY@9ICn0hGmx@FfVE96Szm0LRlQUTl0IoZbLjOUcgs6zmR2@a30PRq7LH5DsYi/Hq7fXNqmr6i9iNOs2sp7LhEGXUKEXvQkifKYfufP9PKveePFl2xP9yh/LPSlo2y/oN)
```
s->{ // Method with String as both parameter and return-type
for(char c=96;++c<123; // Loop over the lowercase alphabet
s=s.matches(".*"+c+".*"+c+".*")?
// If the String contains the character more than once
s // Keep the String as is
: // Else (only contains it once):
s.replace(c+"","")); // Remove this character from the String
return s;} // Return the modified String
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 59 bytes
```
"$args"-replace"[^$($args|% t*y|group|?{$_.Count-1}|% n*)]"
```
[Try it online!](https://tio.run/##PY7BCsIwEETv@YolbE1TWsGrIAp@hmgp7VoPoYlJS5Wm3x5ji@5peTuzM0aPZN2DlAp4hwNMgWNlW8cLS0ZVNfHLDdMF@QT67O1bqwfjjxOW27Meur7YzfHSZfLKw8zYKWUQJ0/F96ketVWNyEHEXSshmQQPCUyLCF0OSC9DdU9NDMdyxZbcoPoINrETugXy2GLlBT3/Jrn/qTmbwwc "PowerShell – Try It Online")
Less golfed:
```
$repeatedСhars=$args|% toCharArray|group|?{$_.Count-1}|% name
"$args"-replace"[^$repeatedСhars]"
```
Note: `$repeatedChars` is an array. By default, a Powershell joins array elements by space char while convert the array to string. So, the regexp contains spaces (In this example, `[^l o]`). Spaces do not affect the result because the input string contains letters only.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 8 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function.
```
∊⊢⊆⍨1<⍧⍨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FH16OuRY@62h71rjC0edS7HEj/T3vUNuFRb9@jvqme/o@6mg@tN37UNhHICw5yBpIhHp7B/9MU1DNSc3Lyy/OLclLUAQ "APL (Dyalog Extended) – Try It Online")
`⍧⍨` count-in selfie (count occurrences of argument elements in the argument itself)
`1<` Boolean mask where one is less than that
`⊢⊆⍨` partition the argument by that mask (beginning a new partition on 1s and removing on 0s)
`∊` **ϵ**nlist (flatten)
[Answer]
# JavaScript, 45 bytes
```
s=>[...s].filter(c=>s.match(c+'.*'+c)).join``
```
[Answer]
# [R](https://www.r-project.org/), 70 bytes
```
a=utf8ToInt(scan(,''));intToUtf8(a[!a%in%names(table(a)[table(a)<2])])
```
[Try it online!](https://tio.run/##RY3BTsMwDIbvPEWpNC2RRg@ckNgegPs4TTs4jdMUXHsk6dYw7dnLqhaQL7@/3/IXRrdzPdepFVaDvsYaePv0R6qq0tfhNsKuT@5lL2@c1HSiNuu11q8tp7283xsFh0dYtbxi6DCqBIZQgT78hu3zUR/1eHtwqvRIJBcJZEs97WBqa9E13rcfn0QzNMD3mXPtESPO2QvlwgPbognIYBfcCadcnHLywstXoix9MBARAhok4SZJH/@dk3IydiynrxBTf74M@XtRisWiEXKlHn8A "R – Try It Online")
A poor attempt, even from a TIOBE top 20 language. I know something can be done about the second half, but at the moment, any golfs escape me.
[Answer]
# JavaScript, 34 bytes
Input as a string, output as a character array.
```
s=>[...s].filter(x=>s.split(x)[2])
```
[Try It Online!](https://tio.run/##BcFLDsAQEADQu3TForPonouIhPi0ZGLESOv2@l71r@cwSp9no5h2VpuVNgDAFnLBmYZYSjNwxzLFkuaycgdqTJgA6RZZHE9CpI8GxkNCpdKck/sH)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 82 bytes
```
p=>[...p].map((v,i,a)=>a.filter(f=>f==v).length).reduce((a,c,i)=>c>1?a+=p[i]:a,[])
```
[Try it online!](https://tio.run/##XcoxDsIwDADAnWd0ckSwxApyeAZD1MFNnTbIbaK09PsBVua7Fx@8hZrKflnzKC1SK@Q8IpYeFy4Ah02WDTnGmHSXCpFcJDoMqqzTPhusMr6DALANNn1ncNcHn6n41N/Y@t60kNctq6DmCSJ0s6jmZ646dsbcT3868MwLD1x/2D4 "JavaScript (Node.js) – Try It Online")
[Answer]
# C++, 139 bytes
```
string s;cin>>s;string w{s}; auto l=remove_if(begin(s),end(s),[&w](auto&s){return count(begin(w),end(w),s)==1;});s.erase(l,end(s));cout<<s;
```
ungolfed:
```
#include <algorithm>
#include <string>
#include <iostream>
int main() {
using namespace std;
string s;
cin >> s;
const string w{s};
auto l = remove_if(begin(s), end(s), [&w](auto& s) {
return count(begin(w), end(w), s) == 1;
});
s.erase(l, end(s));
cout << s;
return 0;
}
```
[Answer]
## PHP - 137
**Code**
```
implode('',array_intersect(str_split($text),array_flip(array_filter(array_count_values(str_split($text)),function($x){return $x>=2;}))));
```
**Normal Code**
```
$text = 'helloworld';
$filter = array_filter(array_count_values(str_split($text)), function($x){return $x>=2;});
$output = implode('',array_intersect(str_split($text),array_flip($filter)));
echo $output;
```
[Answer]
**PHP - 83 78**
```
<?for($a=$argv[1];$i<strlen($a);$r[$a[$i++]]++)foreach($ras$k=>$c)if($c>1)echo$k
```
Improved version:
```
<?for($s=$argv[1];$x<strlen($s);$c=$s[$x++]) echo substr_count($s,$c)>1?$c:'';
```
Of course this needs notices to be turned off
**Edit:** Improvement inspired by @hengky mulyono
I am so bad at codegolf :)
] |
[Question]
[
Dealing with colors in non-markup languages often complicates things.
I would like to see some variations of how color is used in different languages.
The object of this competition is to output 'Hello World' in the seven colors of the rainbow.
According to Wikipedia, these are the 7 colors.
```
Red #FF0000 (RGB: 255, 0, 0)
Orange #FF7F00 (RGB: 255, 127, 0)
Yellow #FFFF00 (RGB: 255, 255, 0)
Green #00FF00 (RGB: 0, 255, 0)
Blue #0000FF (RGB: 0, 0, 255)
Indigo #6600FF (RGB: 111, 0, 255)
Violet #8B00FF (RGB: 143, 0, 255)
```
**The rules**
1. The program must output 'Hello World'. (Doesn't necessarily need to be text, but it must be distiguishable as 'Hello World')
2. Each letter must be a different color.
3. The colors can be in any order.
4. You must use each of the seven colors at least once. (You may use more than the given colors)
5. No use of markup languages *in any case*.
**The winner is whoever has the lowest amount of characters AND follows the rules**
**Bonus -1 character if it is written in [DART](http://www.dartlang.org/)**
I will pick the winner on Jan 11 (if I remember ;D).
Good luck
## WINNER(s)
I made a mistake D:, updated winners.
1st.
[stranac - Python, 60 chars](https://codegolf.stackexchange.com/a/4564/3473)
2nd.
[Ilmari - Karonen Perl + GD, 146 chars](https://codegolf.stackexchange.com/a/4531/3473)
Shortest length with all rules adhered to.
[Brownie points to JiminP](https://codegolf.stackexchange.com/a/4563/3473) for the DART answer.
[Answer]
## Mathematica
```
ImageMultiply[ColorNegate[Graphics[Text[Style["Hello World",30]],ImageSize->190]],ColorData["Rainbow","Image"]]
```
I know, I know, it doesn't comply with the rules.. but I had to try playing with Mathematica's image processing functions.
Screenshot:

[Answer]
## Haskell, 88 characters
```
f(c,n)=putStr$"\27["++show n++"m"++[c]
main=mapM_ f$zip"Hello World\n"$35:cycle[31..36]
```

Note that this uses ANSI terminal colors, of which there are only 6 and they might not match the exact ones given (it depends on terminal settings), so I'm bending the rules a little here.
**Slightly longer version with almost correct colors, 107 characters**
This version uses xterm colors instead of ANSI ones. This does not rely on any custom palettes, and uses the closest colors I could find in the 256-color xterm palette.
```
f(c,n)=putStr$"\27[38;5;"++show n++"m"++[c]
main=mapM_ f$zip"Hello World\n"$cycle[196,208,226,46,21,57,93]
```

[Answer]
# Python, 60 chars
Now using 7 colors, and the "correct" ones.
Uses ansi escape sequences. The underscore is there just so it's not an invisible space.
This version prints some extra spaces, because of the way python's print works, but those spaces save quite a few chars, so I'm fine with them being there.
```
for p in zip(range(7)*2,'Hello_World'):print'\033[3%im%s'%p,
```
And a screenshot, as required by MrZander:

[Answer]
## Python, 261 chars
```
C=((255,0,0),(255,127,0),(255,255,0),(0,255,0),(0,0,255),(111,0,255),(143,0,255))
print'P3 67 5 255'
for i in range(335):print'%d %d %d'%(C+C[2:])[i%67/6]if 0x4f7c938a00e7df7d12208a8aa0220820a34413d154044105f7e8828a28808820828cf04f39100e0417d1>>i&1 else'0 0 0'
```
Implements the spec exactly, generating a ppm image. Here is the result, converted to gif and scaled up by a factor of 4:

[Answer]
## Perl -> ANSI terminal, 53 chars
```
s//Hello World/;s/./\e[3${[5,(1..6)x2]}[pos]m$&/g;say
```
This produces the exact same output as [Hammar's Haskell solution](https://codegolf.stackexchange.com/a/4529/3191). It uses `say`, so needs perl 5.10+ and the `-M5.010` (or `-E`) switch. For older perls, replace `say` with `print`. A trivial one-character reduction could be achieved by replacing `\e` with a literal ESC character, but that would make the code much harder to read and edit.
**Edit:** Added two chars to match Hammar's output exactly, and to actually show all six possible terminal colors. (In the earlier version, the only character printed in color 6 = cyan was the space.)
Screenshot:

---
**Edit 2:** If [using a custom terminal palette](https://codegolf.stackexchange.com/a/4564) (and an underscore for the space) is allowed, then I can easily reproduce the exact colors given in the spec with just 50 chars:
```
$_=Hello_World;s/./\e[3${[(0..6)x2]}[pos]m$&/g;say
```
Screenshot:

[Answer]
## Perl -> HTML, 99 chars
```
@c=(("00")x5,77,(ff)x5,77)x2;print"<font color=#",@c[$i+8,$i+4,$i++],">$_"for split//,"Hello World"
```
**Screenshot:**

The HTML probably won't pass any validators, but should be understood by just about all browsers.
This code doesn't produce the *exact* RGB colors you listed, but it does get very close. Specifically, the colors of the letters are:
```
H Red #FF0000
e Orange #FF7700
l Yellow #FFFF00
l Chartreuse #77FF00
o Green #00FF00
(Spring green #00FF77)
W Cyan #00FFFF
o Sky blue #0077FF
r Blue #0000FF
l Indigo #7700FF
d Violet #FF00FF
```
The output looks a lot nicer on a black background, but explicitly printing a `<body bgcolor=black>` would've cost me 28 extra characters. You may adjust your browser settings to achieve the same effect instead. :-)
[Answer]
## Perl + GD, 146 chars
Per the comments to my [other answer](https://codegolf.stackexchange.com/a/4530/3191), here's a solution that directly produces an image file using the GD library:
```
use GD'Simple;move{$m=new GD'Simple 70,12}2,12;s//Hello World/;s/./fgcolor$m(((0)x5,127,(255)x5,127)x2)[$i+8,$i+4,$i++];string$m$&/eg;print$m->png
```
And here's the output:

Again, using a black background would look better, but would cost me 29 characters (`$m->bgcolor(0,0,0);$m->clear;`).
**Edit:** Figured out how to shave off 20 chars by (ab)using indirect object notation and a few other tweaks. The new code emits a warning, but still runs fine.
[Answer]
Some cheating but solve the problem
## Bash + Ruby (needs `lolcat` gem)
```
echo Hello World | lolcat -p 0.25
```

[Answer]
**Postscript 155 143**
This relies on Ghostscript's ability to "figure-out" that Palatino is short for Palatino-Roman.
```
/h{c 1 1 sethsbcolor}def/c 0 def
200 400 moveto/Palatino 36 selectfont
h{32 ne{/c c .14 add dup 1 gt{1 sub}if def}if pop
h}(Hello World!)kshow
```
[Answer]
Some different approaches to doing this with
**PostScript**
First: Shortest one (**89**):
```
9 9 moveto/Courier 9 selectfont
0{pop pop
dup 1 1 sethsbcolor
.07 add}( Hello World)kshow
```
[](https://i.stack.imgur.com/DAUeo.png)
Un-golfed:
```
9 9 moveto
/Courier 9 selectfont
0 % hue
{ % hue c1 c2
pop pop % hue
dup 1 1 sethsbcolor % hue
.07 add % newHue
}( Hello World)kshow
```
This is continuously changing colour in x direction using the hsb color space. (Idea to use hsb colors and kshow are credited to luser droog - see his entry!) It does not use the exact seven colors given by MrZander.
When restricting myself to MrZander's colors, I get there using **141** chars:
```
9 9 moveto/Courier 9 selectfont(H e*l4l4oI WIosrsl{d~)dup
0 2 20{2 copy
1 add get 32 sub 166 div 1 1 sethsbcolor
1 getinterval show
dup}for
```
[](https://i.stack.imgur.com/AJOJE.png)
This encodes the hue value of MrZander's colors as one byte in the printable ASCII range. This byte is translated to a hue value in the range between 0 and 1 by subtracting 32 and dividing by 166. Each character of the "Hello World" string is followed by its encoded hue value.
Un-golfed:
```
9 9 moveto
/Courier 9 selectfont
(H e*l4l4oI WIosrsl{d~)dup % string string
0 2 20{ % string string index
2 copy % string string index string index
1 add get % string string index hueChar
32 sub 166 div % string string index hueValue
1 1 sethsbcolor % string string index
1 getinterval % string substring
show % string
dup % string string
}for
```
**TODO**: Something isn't quite right with the colors.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 81 bytes
```
s="Hello World";for((i=0;i<11;i++));do printf "\e[$((RANDOM%9+31))m${s:i:1}";done
```
[Try it online!](https://tio.run/##S0oszvj/v9hWySM1JydfITy/KCdFyTotv0hDI9PWwDrTxtDQOlNbW1PTOiVfoaAoM68kTUEpJjVaRUMjyNHPxd9X1VLb2FBTM1elutgq08qwVgmoMC/1/38A "Bash – Try It Online")
[](https://i.stack.imgur.com/Gwve5.png)
[Answer]
## Dart to HTML, ~~135~~ 134-1 = 133
`main(){for(var s="Hello World",i=0;i<11;print("<font color=#${'F00F60FB0FF06F00F00B606B00F60F90F'.substring(i*3,i*3+3)}>${s[i++]}"));}`
Is there any way to color texts without using markup language? I can't test canvases...
[Answer]
I know it says "no markup in any case", but I'd like to submit this CSS one in 468 characters:
```
<style>b{font-weight:normal}i{font-style:normal}u{text-decoration:none}b:after{content:'e';color:orange}b:before{content:'H';color:red}i:after,i:before{content:'l'}i:before{color:#ff0}i:after{color:#0f0}u:before{content:'o ';color:#66f}u:after{content:'W';color:blue}s{text-decoration:none}s:before{content:'o';color:#006}s:after{content:'r';color:#60f}p{display:inline}p:before{content:'l';color:#8b00ff}p:after{content:'d'}</style><b></b><i></i><u></u><s></s><p></p>
```
None of the styling is done with the markup.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 64 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Ol`HÁM Wld`Ëici%Ã$,...$BÇg`ff7fo8Þ»èç36nãr`qÍ ro0 i`¬l:#
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JGNvbnNvbGUuY2xlYXIoKSQ&code=T2xgSMFNIFeObGRgy2ljaSXDJCwuLi4kQsdnYGZmN2ZvjTjeu%2bjnBzONNo9u43KBn2BxzSBybzAgaWCsbI46Iw) (open your browser's console)
Or, for the benefit of those on devices without browser consoles:[](https://i.stack.imgur.com/IRfzU.png)
[Answer]
## Ruby
242 more procedural way:
```
require 'paint'
s = "HelloWorld"
out = ""
[
'#FF0000',
'#FF7F00',
'#FFFF00',
'#00FF00',
"#00FFFF",
"#5555FF",
'#0000FF',
'#000077',
'#6600FF',
'#8B00FF'
].each_with_index { |c, i| out << "#{Paint[s[i], c.dup]}" }
puts out
```
If i manage to think of a better way to generate the colours i will. A few of the middle ones i just did some trial and error for getting the colours close.
] |
[Question]
[
This a simple question.
The start day is a Saturday and let the input be a non-negative number `x`.
The output should be the number of weekdays (Mon-Fri) in the next `x` days inclusive.
For example, if `x = 3` then the output should be 2. For `x` from 0 onwards the output should be:
```
0,0,1,2,3,4,5,5,5,6,7,8,9,10,10,10,11,...
```
—-—
Now I am regretting not having asked the question for a user specified day of the week instead of just Saturday. It’s too late to change the question now and a new question would probably be marked as a duplicate. If anyone wanted to add an answer for this extension, I would love to see it.
[Answer]
# [Python 2](https://docs.python.org/2/), 18 bytes
```
lambda x:x*6/7-x/7
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCqkLLTN9ct0Lf/H9afpFChUJmnkJRYl56qoapgaYVF2dBUWZeiUKaRoXmfwA "Python 2 – Try It Online")
Found by brute-forcing. `x*6/7` counts non-Sundays, and `-x/7` subtracts the number of Saturdays.
```
all x 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
all - Sun = x*6/7 0 0 1 2 3 4 5 6 6 7 8 9 10 11 12 12 13 ...
Sat = x/7 0 0 0 0 0 0 0 1 1 1 1 1 1 1 2 2 2 ...
all - Sun - Sat 0 0 1 2 3 4 5 5 5 6 7 8 9 10 10 10 11 ...
```
Brute-forcing suggests that this is the unique arithmetical solution of this length or shorter, subject to some limitations like not using parens, using only single-digit constants, and not having too-large intermediate results.
---
**19 bytes**
```
lambda x:x-x/7+-x/7
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCqkK3Qt9cG0T8T8svUqhQyMxTKErMS0/VMDXQtOLiLCjKzCtRSNOo0PwPAA "Python 2 – Try It Online")
Found by brute-forcing. But, it has a nice interpretation. `x` counts all `x` days. Then `-x/7` subtracts the number of Sundays in those `x` days, and `+-x/7` subtracts the number of Saturdays. Note that there's a difference in Python between subtracting `x/7` and adding `-x/7` aka `(-x)/7`, because floor-div is not symmetric around zero since it always round down.
```
all = x 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
Sun = x/7 0 0 0 0 0 0 0 1 1 1 1 1 1 1 2 2 2 ...
Sat = -(-x/7) 0 1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 ...
all - Sun - Sat 0 0 1 2 3 4 5 5 5 6 7 8 9 10 10 10 11 ...
```
---
**20 bytes**
```
lambda x:x*5/7+x%7/4
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCqkLLVN9cu0LVXN/kf1p@kUKFQmaeQlFiXnqqhqmBphUXZ0FRZl6JQppGheZ/AA "Python 2 – Try It Online")
I found this by hand, noting that `f(x)` increases asymptotically with slope `5/7` and seeing that the difference to `x*5/7` (with floor-division) has a nice period-7 form.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 6 bytes
```
Ý7%1›O
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8FxzVcNHDbv8//83BgA "05AB1E – Try It Online")
Very similar to the APL answer
## Explained
```
Ý | Generate a list between 0 and input
7% | Mod each number by 7
1› | Determine if each number is greater than 1
O | Summate the list and output it
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 [bytes](https://github.com/abrudz/SBCS)
```
+/2≤7|⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X1vf6FHnEvOaR72b/6c9apvwqLfvUVfzofXGj9omPuqbGhzkDCRDPDyD/6cdWmGgA1RmYgkA "APL (Dyalog Unicode) – Try It Online")
1-based range is a big win here.
### How it works
```
+/2≤7|⍳
⍳ ⍝ 1-based range
7| ⍝ modulo 7; 1 2 3 4 5 6 0 ...
2≤ ⍝ is at least 2; 0 1 1 1 1 1 0 ...
+/ ⍝ sum the booleans
```
---
For the bonus question (let the user provide the day of the week to start):
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 [bytes](https://github.com/abrudz/SBCS)
```
+/⎕⍴⎕⌽7↑5⍴1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@2/qO@qY96t4DInr3mj9ommgJ5hiDJ/5l5OZl5qY/aJlQDVfVuBanq3YWsqpZLQz3YNyQ8xC1YXefQCnUrdU0dAwVDBSMFYwUTBVMFM4VHHTP0IMYoGOg86t1sZAAA "APL (Dyalog Unicode) – Try It Online")
We don't need any fancy arithmetic. Just create a bit vector, rotate it to match the requested day of week to start with, cycle it and count ones (i.e. sum).
Accepts `Sun, Mon, ..., Sat` as the number `0, 1, ..., 6` as the first input, and the number of days as the second (both from stdin). (It actually works for any integers (for the first input) and gives the result as if it was modulo 7.)
### How it works
```
+/⎕⍴⎕⌽7↑5⍴1
7↑5⍴1 ⍝ 1 repeated 5 times and then overtaken to length 7
⍝ i.e. 1 1 1 1 1 0 0
⎕⌽ ⍝ Take the starting weekday and rotate ^ that many units to the left
⎕⍴ ⍝ Take the number of days and cycle ^ to that length
+/ ⍝ Sum
```
[Answer]
# JavaScript (ES6), 16 bytes
```
n=>n*20/7+n%7>>2
```
[Try it online!](https://tio.run/##FcpNDkUwFAbQuVXcAUmr8RMGBrRr0aDyXuS7gpg0XXsxOpPzt7c9p@O3XwV4XqLTEdogb@qqU8g6Y5ro@BAgTXVPoIHaT6Uk@YRoYpy8LeXGqxitSD2CfGvqnYAMo@yTEB8 "JavaScript (Node.js) – Try It Online")
### How?
The expression \$\lfloor 5n/7\rfloor\$ gives the correct answer when \$n\bmod 7\$ is less than or equal to \$3\$ but is off by \$1\$ otherwise.
```
n | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16
-------------+---+---+---+---+---+---+---+---+---+---+----+----+----+----+----+----+----
floor(5n/7) | 0 | 0 | 1 | 2 | 2 | 3 | 4 | 5 | 5 | 6 | 7 | 7 | 8 | 9 | 10 | 10 | 11
expected | 0 | 0 | 1 | 2 | 3 | 4 | 5 | 5 | 5 | 6 | 7 | 8 | 9 | 10 | 10 | 10 | 11
difference | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0
n mod 7 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 0 | 1 | 2
```
This can be adjusted with:
$$f(n)= \left\lfloor\frac{5n}{7}\right\rfloor+\left\lfloor\frac{n\bmod 7}{4}\right\rfloor$$
which may also be expressed as:
$$f(n)= \left\lfloor\frac{20n/7+(n\bmod 7)}{4}\right\rfloor$$
---
# [JavaScript (Node.js)](https://nodejs.org), 15 bytes
In order to use [@xnor's formula](https://codegolf.stackexchange.com/a/206544/58563) without adding explicit floor operations, we have to work with BigInts. So this version expects a BigInt as input.
```
n=>n*6n/7n-n/7n
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5PyyxP3zxPF0T8T8sv0shTsFUwyLNWyFOwUTAGM7S1NRWquRQUkvPzivNzUvVy8tM1EhI1VKrzajWBilWq0zTyNGsTNK25av8DAA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Port of Bubbler's APL solution so be sure to `+1` them, too.
```
õu7 x¨2
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9XU3IHioMg&input=NTEKLW1T) - Includes all test cases
[Answer]
# bc, 29 bytes
```
define f(n){return n*6/7-n/7}
```
[Try it online!](https://tio.run/##Jcs5DoAwDAXRnlOkTJBQMEsC1wFiicZFBBXi7EbfNK@a2XbVo/ApxbGX8NRy3VWctCnmTmJ@Vdn3oWFPYAAjmMAMEshgAavF/2IP2UR2kW1kH6XwAQ "bc – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
R%7>1S
```
[Try it online!](https://tio.run/##y0rNyan8/z9I1dzOMPj///@mAA "Jelly – Try It Online")
Interestingly equal-length in all regards to Lyxal's 05AB1E answer, so I've copy-pasted the explanation, swapping out the commands.
```
R | Generate a list between 0 and input
%7 | Mod each number by 7
>1 | Determine if each number is greater than 1
S | Summate the list and output it
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 18 bytes
```
f(n){n=n*6/7-n/7;}
```
[Try it online!](https://tio.run/##TY/NDoIwDMfvPEVDQrJJCSACkokX41MIB8KH7uAgwIFIeHasBNRtXdN/9@va3Lrn@TxXTPFRxWoX2KGl7FBM8zOTinEYNaCVP7J2B@0thRhGPRmu@2SILmS@jvAfe/okFkKqHsqhKYe@LBYMRgcddHGPHh7QX3aAIR4xQtfZjrviVd0C@9SQhDqC3Ak6@Srrim1Vub0K9IwLME25dbv93xFLaS6@atOSXjHdKMA6A91GlygaQSJ0SPMREf/almm6spM2zW8 "C (gcc) – Try It Online")
Port of [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s formula from his [Python 2 answer](https://codegolf.stackexchange.com/a/206544/9481).
[Answer]
# Java, 12 bytes
```
x->x*6/7-x/7
```
[Answer]
# perl -Minteger -lp, 14 bytes
```
$_=$_*6/7-$_/7
```
[Try it online!](https://tio.run/##DcixDYAgFAXA/s1BZULwoYAWjuAMVMSQECDo/H698noaxYmoeKg4eRO0iiaIzCAsFqxw8AjYsIN/ErTgAq6gA/3b@pNbvUWfuT7pSkN0Lx8 "Perl 5 – Try It Online")
Uses the same algorithm as the Python 2 solution from @xnor. The `-Minteger` switch makes perl use integer division.
[Answer]
# x86-16 machine code, 16 bytes
```
33 DB XOR BX, BX ; clear BX sum
MLOOP:
E3 0B JCXZ DONE ; handle x = 0
8A C1 MOV AL, CL ; loop counter to AL
D4 07 AAM 7 ; AL = AL mod 7
3C 01 CMP AL, 1 ; AL <= 1 ?
7E 01 JLE IS_WEEKEND ; if so, is a weekend
43 INC BX ; otherwise increment count
IS_WEEKEND:
E2 F3 LOOP MLOOP ; loop until 0
DONE:
C3 RET ; return to caller
```
Callable function, input in `CL` (unsigned byte) output to `BX`.
[](https://i.stack.imgur.com/GRsEx.png)
Or **22 bytes** to operate on 16 bit unsigned WORD in `CX`:
```
33 DB XOR BX, BX ; clear BX sum
MLOOP:
E3 11 JCXZ DONE ; handle x = 0
8B C1 MOV AX, CX
33 D2 XOR DX, DX ; clear DX (high word of quotient)
BF 0007 MOV DI, 7 ; set up WORD divisor
F7 F7 DIV DI ; DX = DX:AX mod DI
80 FA 01 CMP DL, 1 ; DL <= 1 ?
7E 01 JLE IS_WEEKEND ; if so, is a weekend
43 INC BX ; otherwise increment count
IS_WEEKEND:
E2 ED LOOP MLOOP
DONE:
C3 RET ; return to caller
```
[Answer]
# [Julia](https://julialang.org/), 143 Bytes
```
function weekdays(days)
r = mod(days, 7)
if r <= 2 r=0
else r -= 2
end
wd::Int64 = floor(days/7)
return(5 * wd + r)
end
```
[Try it online!](https://tio.run/##PY7dCsIwDEbv9xQfu9p0ovMXhnsAH2PYFqI1laxj@vS1tmIuEnL4cshtsjS0rxDMxFdPjjFrfVfDe6y@rS4QS9Dj4VQiDU4Zkon83GML6TeJaDvqyFaR5Z1VmrPqugv74z5qjHVOkmj984j2k3B1wCIGsYTURTwMxgkIxGi7XdY/hdhbrv4PUt2UDcqc/wA "Julia 1.0 – Try It Online")
To use a custom start date, I add an offset argument, and `days += offset` at the start of the function
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 22 bytes
```
.+
$*
.(.{0,5}).?
$1
.
```
[Try it online!](https://tio.run/##Dci9DkAwGIbR/bkOEn/50rfVYjK6DQaDxSA2ce3ljOfa7@Pcclkta7aWosEqe1wX39pmCmE5O4Qn0BNJDIxM6E8hjwLqUUQJDWhEE959 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*
```
Convert to unary.
```
.(.{0,5}).?
```
For each week, match Sunday, then up to five weekdays, then optionally match Saturday.
```
$1
```
Keep just the weekdays.
```
.
```
Count the resulting weekdays.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
IΣ…⪫00×⁵1N
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8O5Mjkn1Tkjv0DDKz8zT0PJwEBJRyEkMze1WMNUR0HJUElTU0fBM6@gtMSvNDcptUhDEwSs//83MvivW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. This is actually 3 bytes shorter than trying to calculate the result arithmetically. Explanation:
```
1 Literal string `1`
×⁵ Repeated 5 times i.e. `11111`
00 Literal string `00`
⪫ Join its characters giving `0111110`
… N Cyclically extend to the input number of days
Σ Sum the digits
I Cast to string
Implicitly print
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
lf<1%T7S
```
[Try it online!](https://tio.run/##K6gsyfjvFhj4PyfNxlA1xDz4//9oAx0FQx0FIx0FYx0FEx0FUx0FMx0Fcx0FCx0FS6AUSNowFgA "Pyth – Try It Online")
Port of Bubbler's APL solution.
## Explanation
```
lf<1%T7S
l : length of
f : filter on
S : 1-based range to input
<1%T7 : where mod 7 is greater than 1
```
[Answer]
# AWK, 29 bytes
```
{print int($0*6/7)-int($0/7)}
```
[Try it online!](https://tio.run/##SyzP/v@/uqAoM69EAYg1VAy0zPTNNXUhbCCr9v9/Ay5DLiMuYy4TLlMuMy5zLgsuSy5DoKAhl6ERl6Exl6EJl6Epl6EZAA "AWK – Try It Online")
Port of @xnor's Python 2 answer.
[Answer]
# Befunge-93, 12 bytes
```
&:6*7/\7/-.@
```
[Try it online!](https://tio.run/##S0pNK81LT/3/X83KTMtcP8ZcX1fP4f9/Q0MA "Befunge-93 – Try It Online")
Another port of xnor's algorithm.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
```
sm<1%d7
```
[Try it online!](https://tio.run/##K6gsyfj/vzjXxlA1xfz/f0MDAA "Pyth – Try It Online")
Port of Lyxal's [05AB1E answer](https://codegolf.stackexchange.com/a/206546/41020).
```
sm<1%d7
m For each number from 0-input:
%d7 Mod 7
<1 Greater than 1
s Take the sum, implicit print
```
[Answer]
# [Io](http://iolanguage.org/), 44 bytes
It seems like ranging is too costly here.
```
f :=method(x,if(x>0,if(x%7>1,1,0)+f(x-1),0))
```
[Try it online!](https://tio.run/##y8z//z9Nwco2N7UkIz9Fo0InM02jws4ATKma2xnqGOoYaGoDObqGmkCW5v@0/CKNTB0DHUMDAx0uBSBI08jUVCgoyswrycnj0vwPAA "Io – Try It Online")
# [Io](http://iolanguage.org/), 46 bytes
```
method(x,Range 0 to(x)map(i,if(i%7>1,1,0))sum)
```
[Try it online!](https://tio.run/##y8z/n6ZgZasQ8z83tSQjP0WjQicoMS89VcFAoSRfo0IzN7FAI1MnM00jU9XczlDHUMdAU7O4NFfzf1p@EVDCQMfQwECHSwEIgEo0FQqKMvNKcvK4NP8DAA "Io – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 142 bytes
(Due to number-wrapping problems) The maximum supported input is 255.
```
>,[[>+>+<<-]>[-<+>]<->>>+++++++<[>->+<[>]>[<+>-]<<[<]>-]>[-]>>+<[<<<+>>>>[-<<<<[-]>+>>>]<<<<[->>+<<]>[->>>+<<<]>>>-<-]>[-]<<[-<<<<+>>>>]<<<]<.
```
[Try it online!](https://tio.run/##JU1LCoVADNu9y/TVE4RcpHShgiCCC8Hz12Ymi9L82u1Zz/t496uK/wgaDfBkOIwJJ2kTCDo122zPEwgkRzYpB2i90d2GVNGcRAkoy7H1Svr8pEujMtrKJ5aq3wc "brainfuck – Try It Online")
If you are not sure whether this output is correct, try [this](https://tio.run/##ZY5BCkJBDEN3XmasJwi5SOlCBUEEF4Ln/yatHwS7GJpJ2r7L63x/3t7Xx7bxmMnFBUQxA4uFILmmkAz6lSkvCkgUO1u0A@hfpVmVfy1rhBNwlt2pJWMueVOP9LTzhS05LI5o5dd1dkkFc@dqtGCY3Wxr0Ft5aR@tPSr0rubunT@NszWs/3EZJ7OK7fAB) link.
## Explanation
```
>,
```
Read input
```
[
```
While the input is nonzero:
```
[>+>+<<-]>[-<+>]
```
`>x 0 0` -> `x 0 >x`
```
<->>>+++++++<[>->+<[>]>[<+>-]<<[<]>-]>[-]
```
Modulo by 7
```
>>+<[<<<+>>>>[-<<<<[-]>+>>>]<<<<[->>+<<]>[->>>+<<<]>>>-<-]>[-]<<
```
Check if this number is greater than 1
```
[-<<<<+>>>>]<<<
```
Add it to the accumulator (at the first item of the tape)
```
]
```
End while
```
<.
```
Move to the accumulator, print the value.
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 10 bytes
```
0&1ɧ⑷7%1>⑼
```
[Try it online!](https://tio.run/##y05N///fQM3w5PJHE7ebqxraPZq45/9/Q4P/ukVBAA "Keg – Try It Online")
Total not a port of ~~Lyxal's~~ my 05AB1E answer... (spoiler, it is). ;P
## Explained
```
0&1ɧ⑷7%1>⑼
0& # Store 0 in the register, as this will be used to keep track of the number of weekdays
1ɧ # Create a range between 1 and the implicit input
⑷ # Map the following to each item in the stack:
7%1>⑼ # Increment the register by whether or not ((item % 7) > 1)
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), `s`, 5 bytes
```
ʀ7%1>
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%CA%807%251%3E&inputs=3&header=&footer=)
Another port of my 05AB1E answer
[Answer]
# x86-16 machine code, ~~18~~ 16 bytes (No Loop):
Bytecode: `"\xD4\x07\x88\xC1\xC1\xE8\x08\x6B\xC0\x05\x49\x78\x02\x01\xC8\xC3"`
```
0: d4 07 aam 0x7 ; eax contains n, with aam 0x7 -> al = n % 7 and ah = n / 7
2: 88 c1 mov cl,al ; keep result of n%7 in ecx
4: c1 e8 08 shr ax,0x8 ; by shifting 8 times ax, ax=al=n/7;
7: 6b c0 05 imul ax,ax,0x5 ; we multiply by 5
a: 49 dec ecx ; ecx = ecx - 1 -> give 65535 if n was power of 7
b: 78 02 js 11 <end> ; if it happened we don't care about the remainder so we can just return n/7*5, the Signed Flag will be set so we can jump 2 bytes forward.
d: 01 c8 add eax,ecx ; if not then we add (n%7)-1 to n/7*5
00000011 <end>:
f: c3 ret
```
~~[obtained from assembling](https://defuse.ca/online-x86-assembler.htm#disassembly)~~ thanks to `objdump -d -mi8086 dayofweek.s`
```
global dayofweek
bits 16
section .text
dayofweek:
aam 7
mov cl, al
shr ax, 8
imul ax,5
dec ecx
js end
add eax,ecx
end:
ret
```
Test: main.c
```
int main() {
for (short i = 0; i < 50; i++)
printf("%2d %2d\n", dayofweek(i), (i*20/7+i%7)/4);
return 0;
}
```
output:
```
0 0
0 0
1 1
2 2
3 3
...
33 33
34 34
35 35
35 35
```
~~It is not as short as @640KB (16 bytes) but~~ I believe it is still an interesting answer as it provides a better performance (no loop)
edit: Thanks to Peter -2 bits
NB (Peter): Do note that aam only divides AL, not AX, so you might as well declare the arg in C as **uint8\_t**, as well as specifying the gcc -mregparm=3 calling convention to put it in the reg you want.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 42 bytes
```
function x($y){[math]::floor($y*6/7-$y/7)}
```
[Try it online!](https://tio.run/##Hc7RCoJAEAXQ975CYoOMW@3Muq4W9iMiEmEUmJYVFea32zbcAzPch2Gu7avq7qeqrsfx@GwOj3PbBO@5@oR9ftk/TsVmc6zbtvPNIl67pfqsXTiMqqvumYYGgX0MIlifGM4nQQrSgkAsDCgCWRGDnEhAKVgLf4iFAUdgK2KwEwk4hdGCYFgYmAjGTvRqZfV31qsmeweq3E7VXJVhkO0CvzQh/sP/m6uyWFY330yH8Qc "PowerShell – Try It Online")
Fork of Python 2 answer
] |
[Question]
[
Posted from [sandbox](https://codegolf.meta.stackexchange.com/a/18419/56555)
**The Intro**
What is an ACU? This challenge is based on the concept of money and since this is an international community, we all use different currencies, so in keeping with our spirit of inclusiveness, I have invented a new currency called Arbitrary Currency Units (ACUs) specifically for this challenge. In reality, the challenge is the same whether we are using Dollars, Pounds, Euros, Bitcoins, Lao Kip or Baked Beans.
**The Idea**
It's New Year. We all have ideas about how we can improve things in the coming year. Mine is to save some money but randomly putting money aside quickly becomes uninteresting so I am following up on something I read on a news site last year. Each week, I put the amount of ACUs equal to the week number into a tin and after 52 weeks I will have saved ACU 1378. That's enough for a nice golfing holiday somewhere in 2021!
**The Problem**
I need an incentive to keep me going with this so I need to know how much I have or will have in the tin on any given date during 2020. For example, if I enter a date before today I want to know how much was in the tin on that date. For a date after today I want to know how much I will have if I stay with the plan.
**The Challenge**
Write a program or function which will, when given any date in 2020 (apart from 30-31 Dec - see "The Details"), output the number of ACUs that are in my tin.
**The Details**
* Each week in 2020 consists of exactly 7 days.
* The first week of the year starts on 1 January 2020.
* We are considering only weeks that are completely within 2020. The last week ends on 2020-12-29 so there are exactly 52 weeks and 30/31 December are not included.
* Each week I will put a number of ACUs equal to the week number into my tin on the first day of the week, that is on the 1st January I will put 1 ACU into the tin, on the 8th January I will put 2 ACUs, etc. I will at no point take any ACUs out of the tin.
**The Rules**
* Program or function - your choice.
* Input in whatever convenient format but it must be a date. I have a feeling that accepting a day-of-year input may trivialise this challenge but I am open to other opinions on this.
* Output however you like but it must be a number of ACUs or a string representation of same.
* We are only talking about complete weeks in 2020 so you can assume that the input will not include 30 or 31 December. It's up to you how you deal with it if it does.
* Don't forget that in 2020 February has 29 days.
* Usual loopholes barred and this is code golf so the shortest program/function in each language will be the winner. All languages welcome and I will not be accepting an answer as per current consensus. Upvotes will decide who wins.
A small Python script that generates the expected output for each week is available here [Try it online!](https://tio.run/##fVDLCsIwEDwnX7G3tjRKEkFB9Du8CBLaSIN9UbcUvz4mlTa5VFiW2WV2Ztj@g1XXSmtN03cDQqlQo2k0fZrhjXBdF3sPUsklZ1y4ymittghCsoMjTFq/HkU3tp4mqCrGaJoqU2v4ueRBxLdS16jSYwYXmD3OlPSDcXfJzSlCwiAoM0ju6DazkBt2C94SXQ7WNJREOXMfjcRJA84jW0qW//wxO2XWfgE "Python 2 – Try It Online"). The output can also be printed to stick on the side of your tin if you decide to do the same :)
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~20~~ 19 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function taking `[year,month,day]` as argument.
```
2!∘⌊7÷⍨43816-⍨⌂days
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/30jxUceMRz1d5oe3P@pdYWJsYWimC2Q86mlKSaws/p/2qG3Co96@R31TPf0fdTUfWm/8qG0ikBcc5AwkQzw8g/@nKRgZGBkoGBgCERcSxxyZYwHjGBopGFkCAA "APL (Dyalog Extended) – Try It Online")
`⌂days` calculate the number of **days** since 1899-12-31
`43816-⍨` subtract 43816; days since 2019 12 18, i.e 14 days weeks extra
`7÷⍨` divide by 7; weeks since 2019 12 18, i.e two weeks extra
`⌊` floor; whole weeks since 2019 12 18, i.e two weeks extra
`∘`
`2!` count the number of ways to choose 2 out of that many
In other words, if \$d(x)\$ is the number of days since 1899-12-31, then the answer is
$${\Big\lfloor{d(x)-43816\over7}\Big\rfloor\choose2}=
{\Big\lfloor{d(x)-43823\over7}\Big\rfloor-1\choose2}=
\sum\_{n=1}^{\big\lfloor\frac{d(x)-43823}7\big\rfloor}n$$
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 33 bytes
```
{[+] 1..Date.new(24,|@_).week[1]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Olo7VsFQT88lsSRVLy@1XMPIRKfGIV5Trzw1NTvaMLb2f3FipUKaQo1KvEJafpGChqGOoaaOhomOOZi0AJKGhjrGEMoERBnpGFlq/gcA "Perl 6 – Try It Online")
Takes input as `month,day`. This initialises a date in the year 24 (since that year starts on Monday and is a leap year), and calculates the sum of the range of 1 to the current week number.
[Answer]
# [R](https://www.r-project.org/), ~~56~~ 34 bytes
```
function(d)sum(1:format(d-2,"%V"))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jRbO4NFfD0Cotvyg3sUQjRddIR0k1TElT83@aRmKxnktiSaqGkpGBkYGugaGugTlIAgA "R – Try It Online")
A function taking an R `Date` as its argument and returning a number. Works because `2019-12-30` was a Monday, `strftime(,"%V")` returns the ISO week number and then calculates the relevant triangular number.
Thanks to @Giuseppe for saving 17 bytes, and @RobinRyder a further 3!
[Answer]
# JavaScript (ES6), ~~53~~ 51 bytes
Takes input as `(month)(day)`.
This is longer than [my other answer](https://codegolf.stackexchange.com/a/197818/58563) but does not use any date built-in.
```
m=>g=d=>--m?g(d+31+~m%9%2-(m==2)):~(d=~-d/7)*~-~d/2
```
[Try it online!](https://tio.run/##dcvBCoJAEADQe/8hzCSj7CiYwdi3iKNL4bqS0nF@fesa1vXBe/Svfhue93WnJeqYJklBOi8qHVG4edC8crmFrM2YIIgw4tVAxUjLBs9GpiWnIS5bnMdijh4mcAgN4ukb6z94OaD7/Oqn1kdlBG4R0xs "JavaScript (Node.js) – Try It Online")
### Commented version
```
m => // m = month
g = d => // g is a recursive function taking the day d
--m ? // decrement m; if it's not equal to 0:
g( // do a recursive call:
d + 31 // add 31
+ ~m % 9 % 2 // subtract 1 if (m + 1) mod 9 is odd
// to account for the August -> July transition
- (m == 2) // subtract 1 if m = 2, for February
) // end of recursive call
: // else:
~( // compute the triangular number
d = ~-d / 7 // using d' = (d - 1) / 7:
) * // -floor(d' + 1) *
~-~d // -floor(d' + 2)
/ 2 // / 2
```
[Answer]
# JavaScript (ES6), ~~61 50 49~~ 47 bytes
*Assumes that the system is set up to UTC time (as the TIO servers are)*
Takes input as `(month)(day)`.
```
m=>d=>(n=new Date(68,m-1,d+738)/6048e5|0)*-~n/2
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/X1i7F1k4jzzYvtVzBJbEkVcPMQidX11AnRdvc2EJT38zAxCLVtMZAU0u3Lk/f6H9yfl5xfk6qXk5@ukaahqGmhrmmJheqoAkOQQsMQUOgfmOsoiaYokaaGkaWmpr/AQ "JavaScript (Node.js) – Try It Online")
### How?
Given the month \$m\$ and the day \$d\$, we generate the corresponding date in \$1968\$ (the closest leap year before Epoch) with an additional offset of \$738\$ days.
```
new Date(68, m - 1, d + 738)
```
We implicitly coerce this value to a number of milliseconds and divide it by:
$$7\times24\times60\times60\times1000=604800000$$
We discard the decimal part of the result to turn it into a 1-based week index \$n\$ in \$1970\$ (Epoch's year) which is consistent with the week index in \$2020\$.
\$738\$ is the sum of:
* a leap year (\$366\$ days) to reach 1969
* a non-leap year (\$365\$ days) to reach 1970
* a week (\$7\$ days) to go from 0-indexed to 1-indexed
Finally, we return the \$n\$th triangular number \$\dfrac{n(n+1)}{2}\$.
[Answer]
# [Red](http://www.red-lang.org), 38 bytes
```
func[d][(t: pick d - 2 14)*(t + 1)/ 2]
```
[Try it online!](https://tio.run/##NYtBCsIwEEX3nuLTVauEdoKgduHKE7gdZhEyEyxKLSGeP2rFzeO9Dz@b1qspyyaNNb3myCrclhHLFO9QOHjQvtu2BTtQ18NLTc9sId6goRiYHDk/@AGHv3zx8SP8yV0srqPwkqe5gJeg/cNS@b2J0Lhzg7SmSH0D "Red – Try It Online")
Takes input as a date in any reasonable format: dd-mm-yyyy, yyyy-mm-dd, dd-MMM-yyyy. [Red](http://www.red-lang.org)'s `date` datatype fourteenth field holds the week nember.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•Σ₁t•ºS₂+6šI£O+7÷LO
```
-1 byte thanks to *@Arnauld*.
Input in the order `month`, `day`, `year` (although the year is ignored).
[Try it online.](https://tio.run/##yy9OTMpM/f//UcOic4sfNTWWABmHdgU/amrSNju60PPQYn9t88Pbffz//zc05DI04jIyMDIAAA)
**Explanation:**
```
•Σ₁t• # Push compressed integer 5354545
º # Mirror it: 53545455454535
S # Convert it to a list of digits: [5,3,5,4,5,4,5,5,4,5,4,5,3,5]
₂+ # Add 26 to each: [31,29,31,30,31,30,31,31,30,31,30,31,29,31]
6š # Prepend a 6: [6,31,29,31,30,31,30,31,31,30,31,30,31,29,31]
I£ # Leave the first month-input items of this list
O # And sum those
+ # Add it to the (implicit) day-input
7÷ # Integer-divide it by 7
L # Pop and push a list in the range [1,n]
O # And sum that list
# (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 `•Σ₁t•` is `5354545`.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~94~~ \$\cdots\$ ~~82~~ 77 bytes
```
lambda d:(n:=(date(*d)-date(2020,1,1)).days//7+1)*-~n/2
from datetime import*
```
[Try it online!](https://tio.run/##Xc5LbsMgEAbgvU8xYgUuiQ1O5YfEtpdIs6AFWks1IMLCkeVe3YUs8qg0Go0@zYx@f4nfzjadD5sR79uPnD6UBDVgOwisZNS4VGR3HXjNa8ooI2Sv5OVcVe0LI@Xu11a8MMFNkLfiOGkYJ@9CLDcnjsi6CPKMKErtVBgXQNEZRgu4AHz/mesGB9omqF@fqEvE6wdijDaE9v0/O@TT5vGWccr7pE3bZSVDAT6MNmKD3nKeFBsWtcJXiroYrMgKizvmQYj5tIKevf6MWu0R2f4A "Python 3.8 (pre-release) – Try It Online")
Function takes date as a `(year, month, day)` tuple and returns the number of ACUs. Tests ported from [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s answer.
[Answer]
# [Perl 5](https://www.perl.org/) `-ap -MTime::Local -MTime::Piece`, 61 bytes
```
$_=($w=(gmtime timegm 0,0,0,$F[0],$F[1]-1,24)->week)*($w+1)/2
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lZDpdxWIz23JDM3VQFEpOcqGOiAoIpbtEEsiDSM1TXUMTLR1LUrT03N1tQC6tA21NQ3@v/fyELB0OhffkFJZn5e8X/dxIL/ur6megaGBkA6BGiWlVVAZmpyKpznk5@cmAMA "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
A function that takes the month and date.
`Time#yday` returns the day of the year.
```
->m,d{k=1+~-Time.gm(4,m,d).yday/7;k*-~k/2}
```
[Try it online!](https://tio.run/##KypNqvyfZhvzX9cuVyelOtvWULtONyQzN1UvPVfDRAcopqlXmZJYqW9una2lW5etb1T7vzwjMydVIT21pJhLQaFAIS1aSyVer7ggJ7NEw15XUy83sUBDzaokPz5TM5YrNS/lv4GhroEhl4GJroE5mLTgMgSKGINJEy5DI10jSwA "Ruby – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 48 bytes
Thanks to @mazzy
```
(1..(((Date|% DayOfYear)/7)+1)|measure -sum).sum
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X8NQT09DQ8MlsSS1RlXBJbHSPy0yNbFIU99cU9tQsyY3NbG4tChVQbe4NFdTD0j8/w8A "PowerShell – Try It Online")
Originally 76 bytes
```
[Linq.Enumerable]::Sum([Linq.Enumerable]::Range(1,(Get-Date).DayOfYear/7+1))
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/P9onM69QzzWvNDe1KDEpJzXWyiq4NFcDi3BQYl56qoahjoZ7aomuS2JJqqaeS2Klf1pkamKRvrm2oabm//8A "PowerShell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~34~~ ~~32~~ ~~38~~ ~~34~~ 32 bytes
```
g(n){n=n/604800-2607;n=n*-~n/2;}
```
Takes as input the number of seconds since January 1st, 1970 (the Unix epoch) at 0:00 AM UTC time.
Explanation:
```
n=n/604800-2607;
```
Divide by number of seconds in a week and subtract the number of weeks from Jan 1 1970 to Jan 1 2020 minus one so we don't have to increment later.
```
n=n*-~n/2;
```
Return the [n'th triangle number](https://math.stackexchange.com/questions/60578/what-is-the-term-for-a-factorial-type-operation-but-with-summation-instead-of-p). This is equivalent to the ACU calculation but without any builtin language constructs or loops. Due to TIO's calling convention I can assign to the first argument instead of using `return`.
*-2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!*
*+6 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) and [ElPedro](https://codegolf.stackexchange.com/users/56555/elpedro)!* (:P)
*-4 bytes thanks (indirectly) to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!*
*-2 more bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!*
[Try it online!](https://tio.run/##TZDNTsMwEITvfopVkJHzR0OgSUVaJMQzcECAqmDHqaXaQY7DpQqvHtZNod3LyqNvZkfmacv5NLXMhAezMYsiu19lWZoXWVnhO0p/zCKvxulKGb4fRAPr3gnV3eweyVlySjdeIco40LUy7LtTIiQHAjh8V1v4HKRs7FtefFTkqMrOMvA8hw1kFa41LHPccQzhkZjdfnz@1oFD8nZZlqu7AjtCjJ4I5sLVP@sjaz4g2jIXnvXe2YFjhobI6a0ysvOI9tHs2oOXpDzKc@cE8iKBgL6mVKdUBAmc/BfhXxbPShbQHhjdi/ABqICn55f@3SD/l@MS3@xkG@eDtnGDNfgBZJx@AQ)
[Answer]
# [PHP](https://php.net/), ~~67~~ ~~59~~ 57 bytes
```
<?=(($d=(int)(date(z,strtotime($argv[1]))/7+1))+$d*$d)/2;
```
[Try it online!](https://tio.run/##K8go@P/fxt5WQ0MlxVYjM69EUyMlsSRVo0qnuKSoJL8kMzdVQyWxKL0s2jBWU1PfXNtQU1NbJUVLJUVT38j6////RgaGlroGhrqGpgA "PHP – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 21 bytes
```
“¢(Y’b3+29ÄŻ⁸ị++6:7RS
```
[Try it online!](https://tio.run/##ATQAy/9qZWxsef//4oCcwqIoWeKAmWIzKzI5w4TFu@KBuOG7iysrNjo3UlP///8xMv8yOf8yMDIw "Jelly – Try It Online")
A full program taking the date as three arguments: month, day, year. Alternatively a dyadic link taking the month as its left and day as its right argument. (The year is ignored in any case.) Jelly has no date type, so this needs to generate the cumulative month lengths.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 44 bytes
```
x=>Enumerable.Range(1,x.DayOfYear/7+1).Sum()
```
[Try it online!](https://tio.run/##dVBda4MwFH3WX3HxoUTMrPGlUD@g0A0G6wZrYfQx09hlzAhRtxbxt7sbW0EYy8tNzj33nHOT1XdZLYeHVmXxljfiIEtBpWrSIhnOSXqv2lJo/v4l/FeuToIweva3/PJSHAXXy5XHXH/flsQdIruoNMFJkJAAi7DEWEO8eJ4LnW19cw05WmBbiR@Y3EgYhAEFSYG5kW29admIJ6kEMVz/UO0bLdWJODs8jmsoxiTnl/pR7SrVfKDepGWiTfCkayYwGozZPpEcRFjiuQICt4yWLJAIiUkOiwUSUwhX19YsmtMF/RqelxuHjisZX@NjWbcFR3CT5yYPYddWhlZStcI8evuvXMf6mRyFYvyBceP/Zfv5jyHQD78 "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# TI-BASIC, ~~26~~ 25 bytes
```
∑(X,X,1,1+int(7⁻¹(1+dbd(1.012,Ans
```
Hooray for built-ins!
Input is the compressed version of the end date in the form `MM.DDYY` or `DDMM.YY` where `MM` is the month (e.g. `01`), `DD` is the day (e.g. `24`) and YY is the year (in this case, `20`).
Input is in `Ans`.
Output is the wanted result as specified in the challenge.
**Update:**
In my attempt to fix the code, I somehow made it shorter.
**Explanation:**
```
∑(X,X,1,1+int(7⁻¹(1+dbd(1.012,Ans
dbd(1.012,Ans ;difference in days between 1Jan2020 and the
; compressed input
1+ ;add one to allow 1Jan2020 to be an input
7⁻¹( ;multiply by 1/7
int( ;truncate
1+ ;convert week index from 0-indexed to 1-indexed
∑(X,X,1, ... ;summation of X from 1 to the above
;implicit print of Ans
```
**Examples:**
```
1.2420:prgmCDGF28
6
2.2920:prgmCDGF28
36
1.3120:prgmCDGF28
10
1.0120:prgmCDGF28
1
```
---
**Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count.
[Answer]
## [Java](https://www.java.com), 24 characters/bytes
```
c->c.get(3)*-~c.get(3)/2
```
[Try it online](https://tio.run/##bVBdT8IwFH3efsUNL3YglUD0wQHJ/CDhwZAIL8QYUrtCil23bC2GGP3reMs2RDDpQ3vuOeeenjXbsHaaCb2O33cyydLcwBoxao1U9J4poWOWh/7ZaGk1NzLVdJaOtRlVr9CvmYVhRvJ/vGgTSZl9UzjlihUFPDGp4dP3fK@CK@0mlTEkOCRTk0u9enkFlq@KwHG9P2v7tfkQGLcOhQHseHvI6UoY0gua7e/6etXdhajHU4uAM4X8Q0DkjTVm0FyQwHFxTgsUzx@j50vodrqdoLJYpjkQqQ3EbDtZzgWaDaATHj370Lu5PgJarTL/wfQhmi8mo0XpfaDtF7gNnnPXNom4Revqd5RlmdpGBVZA0OeXPN0WRiQ0tYZmWJlRmmjxAWV/d1aqWOQkcEzPcyb4YdKImRG30DiBXT5sYiYTbOFUEmISbhOrUBq7VBfFuUOZeg/uE3757vhf/u4H)
* This is an instance of ToIntFunction as a Lambda function.
* c is a reference to a [Calendar](https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html) object.
* c.get(3) returns the week of year field ([Calendar.WEEK\_OF\_YEAR](https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#WEEK_OF_YEAR) == 3)
* x\*-~x/2 is the triangle number calculation.
] |
[Question]
[
## Task
Your task is to take an array of numbers as input, and produce a new one where each number has been shifted both right and left, leaving `0`s if no number fills a spot. This process can be represented graphically like this:
```
[x]
/ | \
[x, 0, x]
```
This is done with every number in the list, with overlapping numbers being added. A list with two numbers would look like this:
```
[x, y]
/ \/ \
/ /\ \
[x, y, x, y]
```
With three numbers, you start to get overlaps, and addition:
```
[x, y, z]
/ \/ \/ \
/ /\ /\ \
[x, y, x+z, y, z]
```
## Example
A simple example is `[1]` gives `[1, 0, 1]` because
```
[1]
/ \
/ \
[1, 0, 1]
```
Another example
```
[1, 2]
/\ /\
/ X \
/ / \ \
[1, 2, 1, 2]
```
Another example
```
[1, 2, 3]
/\ /\ /\
/ X X \
/ / \/ \ /\
[1, 2, 4, 2, 3]
```
## Image:
[](https://i.stack.imgur.com/Wac7r.png)
## Test cases
```
[1,2,3] => [1,2,4,2,3]
[4,2] => [4,2,4,2]
[1] => [1,0,1]
[7,4,5,6] => [7,4,12,10,5,6]
[1,2,4,2,1] => [1,2,5,4,5,2,1]
[1,0,1] => [1,0,2,0,1]
[1,0,2,0,1] => [1,0,3,0,3,0,1]
[8,7,6,5,4] => [8,7,14,12,10,5,4]
[1,4,9,16] => [1,4,10,20,9,16]
[1,2] => [1,2,1,2]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ŻŻ+
```
[Try it online!](https://tio.run/##y0rNyan8///o7qO7tf8/3L3l0Najkx/uXPyoYY6CrZ3Co4a5D3csCjvcfnTSw50zNCP//4821DHSMY4FSYKZJmAuVzSQhgiaQASBQoYwVQY6hkCuOVDYVMcMIgjiGBrpGBqAhbjgRhkiTDYFqzcC64WYATfOCGokgg2XMoZikLSFjrmOGcgciDSIa4iw1gRsgImOpY6hGUy/CUjKyAAiBnYVwj0gDgA "Jelly – Try It Online")
Using [hyper's oberservation](https://chat.stackexchange.com/transcript/message/60209526#60209526)
## How it works
```
ŻŻ+ - Main link. Takes a list L
ŻŻ - Prepend two zeros
+ - Add elementwise
```
[Answer]
# [Python 3](https://docs.python.org/3/), 38 bytes
```
lambda l:map(sum,zip(l+[0,0],[0,0]+l))
```
[Try it online!](https://tio.run/##RZDdboMwDIXv8xSRr5LhTSRQuiLRF0lzETZQkQJFQCdtL8/yU@Aiic9n@8Ty@LvcH0O2ttVttaavvw21ZW9GNj97/OtGZhOVYqox3InlfF2aeZlpRQFACZSYaVpdaQjzIIlyb4R5hA6JrSpF4eTZ4RMWEXohJIo0ILJbicP5FOpl6I0eu518WR7xnspex6c/8YyF94lpL8XxbR4McrygKLb@3KdkGlmY6pjHC@I2QLZtND/GMlAKkkA@pma05qthoG8DIGi3QeAHra6A1HGuynepE9DASfuYqMGadgMNHiWh49QNCzOo3lpmuMaar/8 "Python 3 – Try It Online")
Also works in Python 2
[Answer]
# [Factor](https://factorcode.org/) + `pair-rocket`, 34 bytes
```
[ 0 => 0 prepend dup 2 rotate v+ ]
```
[Try it online!](https://tio.run/##TU5Nb4JQELzzK@ZuSoBSrTV6bbx4MT0ZDxvYWiI@XvetRtvw23EhpPYymY@dyX5SoY10H9v15v0Nnip5kqY4siLw95ldwQFHFsf1w4j5qkIBJ9Kv@ML9QIAXVr15qZziwI6F6uqHtGpcwCKKfpEiwzNaY7mxdnB6nJl@wXR0siFNR5X8Y9mferXO1Dr5mOWYI30MtFG3s9vlysC@8uxKlGdviTRKyrhMsO/SBI68r2@IA4qaSbo7 "Factor – Try It Online")
## Explanation
Infix syntax? In my Factor? You bet. `0 => 0` is 1 byte shorter than `{ 0 0 }` and does the same thing.
```
! { 1 2 3 }
0 => 0 ! { 1 2 3 } { 0 0 }
prepend ! { 0 0 1 2 3 }
dup ! { 0 0 1 2 3 } { 0 0 1 2 3 }
2 rotate ! { 0 0 1 2 3 } { 1 2 3 0 0 }
v+ ! { 1 2 4 2 3 }
```
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 12 bytes
```
zdm~<ao[i,i]
```
## Explanation
`zdm` takes a `SemiAlign` of `Semigroup` elements and combines them with the semigroup action defaulting to the present value if only one is present.
That's a bit of a mouthful. In this case `zdm` takes two lists of numbers and zips them together with addition. In places where there is only one number to add (i.e. the longer end of a list) it just adds zero.
`ao` concats two lists so `ao[i,i]` adds two copies of `i` to the front. For integers `i=0` so this is the same as adding zero twice. With that we combine it with a monad operator `~<` and we get something that takes a list and `zdm`s it with a version of it with two zeros on the front.
I use `i` here because the result is a nice function which can work on more than just lists. For example it will also combine lists or strings in the natural way.
```
ghci> zdm~<ao[i,i]$[1,2,3]
[1,2,4,2,1]
ghci> zdm~<ao[i,i]$["a","b","c"]
["a","b","ca","b","c"]
```
## Reflections
`[i,i]` is pretty long. If I made an alias `Ki` for `K i` (or `K0` for `K 0`) this could be `zdm~<Ki<Ki` saving two bytes overall.
[Answer]
# [R](https://www.r-project.org/), 28 bytes
```
function(x)c(0,0,x)+c(x,0,0)
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCM1nDQMdAp0JTO1mjAsgw0PyfplGcnJinoanJZahgomAGxIYKxv8B "R – Try It Online")
Updates the [related challenge](https://codegolf.stackexchange.com/a/216504/67312).
Thanks to alephalpha for pointing out a bug.
# [R](https://www.r-project.org/) >= 4.1, 21 bytes
```
\(x)c(0,0,x)+c(x,0,0)
```
[Try it online!](https://tio.run/##K/r/P0ajQjNZw0DHQKdCUztZowLIMND8b6hgomAGxIb/AQ "R – Try It Online")
[Answer]
# [convey](http://xn--wxa.land/convey/), ~~[14](https://codegolf.stackexchange.com/revisions/241596/1)~~ 13 bytes
```
0+}
^,<<0
0"{
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiMCt9XG5eLDw8MFxuMFwieyIsInYiOjEsImkiOiJbMSwxLDEsMV0ifQ==)
[](https://i.stack.imgur.com/RRCp9.gif)
[Answer]
# [J](http://jsoftware.com/), 10 bytes
```
0 0&(,+,~)
```
[Try it online!](https://tio.run/##TY6xDsIwDET3fMWJgVJhqjhNU6hUFiQmJtaKCVEhFv6AXy9OQhKGKL539tmvZdVUM8YBFQgag7xdg9P1cl409HpDW/rUS60e9@cbMxgGbRIWJvNU9EI7uP9@aSu@AKVkj1YTk6H2hvGIUNog1SR/hDZCQZy6NLHIXnBHLkIv2BDrgFSO4pLchX4TZmNGjjO/yFJnq/09b@@pJ@dzou0ll7U2BFg6ELs0b71ldGThqnKPF6pevg "J – Try It Online")
Obligatory nod to [Iverson's favorite expression](https://codegolf.stackexchange.com/questions/216479/ken-iverson-s-favourite-apl-expression), as noted in comments by Bgil Midol.
Or, for one extra byte, in the prettier symmetric form:
```
0 0&,+,&0 0
```
[Answer]
# [Desmos](https://desmos.com/calculator), 28 bytes
```
f(l)=join(l,0,0)+join(0,0,l)
```
Can't get much shorter than this as far as I'm aware.
[Try It On Desmos!](https://www.desmos.com/calculator/3kctzkalgr)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/wldkq6pmkh)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 34 bytes
```
->a{(r=0,0,*a).zip(a+r).map &:sum}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6xWqPI1kDHQEcrUVOvKrNAI1G7SFMvN7FAQc2quDS39n@BQlp0tKGOkY5xbOx/AA "Ruby – Try It Online")
[Answer]
# [Wolfram Mathematica](https://www.wolfram.com/mathematica/), 18 bytes
```
{##,0,0}+{0,0,##}&
```
Just a Mathematica port of what other posters have done: Create two lists, where two zeros are appended to the input in one, and prepended to the input in the other, and add them.
Sample usage:
```
{##,0,0}+{0,0,##}&@@{8,7,6,5,4}
```
>
> {8, 7, 14, 12, 10, 5, 4}
>
>
>
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 19 bytes
```
@(a)conv(a,[1,0,1])
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKunp/ffQSNRMzk/r0wjUSfaUMdAxzBW83@aBpBppGMMZAIA "Octave – Try It Online")
---
# [Octave](https://www.gnu.org/software/octave/), 19 bytes
```
@(a)[a,0,0]+[0,0,a]
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKunp/ffQSNRMzpRx0DHIFY7GkjqJMb@T9OINtQx0jGO1fwPAA "Octave – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2Å0ì+
```
[Try it online](https://tio.run/##MzBNTDJM/f/f6HCrweE12v//R1vomOuY6ZjqmMQCAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfaXLf6PDrQaH12j/1/kfHW2oY6RjHKsTbaJjBCQNgdhcx0THVMcMxAPKAcV1DMFsAzhtBGVb6JjrmAHVmoDFTXQsdQyh2mJjAQ).
Uses the legacy version of 05AB1E, because the `+` will keep trailing items when lists are of different lengths, whereas the new 05AB1E version would ignore/remove them. In the [new version of 05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), this therefore would have been 7 bytes instead:
```
2Å0ì0ζO
```
[Try it online](https://tio.run/##yy9OTMpM/f/f6HCrweE1Bue2@f//H22hY65jpmOqYxILAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf6PDrQaH1xic2@b/X@d/dLShjpGOcaxOtImOEZA0BGJzHRMdUx0zEA8oBxTXMQSzDeC0EZRtoWOuYwZUawIWN9Gx1DGEaouNBQA).
**Explanation:**
```
2Å0 # Push list [0,0]
ì # Prepend it front of the (implicit) input-list
+ # Add the values at the same positions to the input-list,
# keeping the additional trailing items
# (after which the result is output implicitly)
2Å0ì # Same as above
ζ # Zip/transpose with the (implicit) input-list, creating pairs,
0 # using 0 as filler-item when lists are different in length
O # Sum each inner pair
# (after which the result is output implicitly)
```
[Answer]
# JavaScript (ES6), 34 bytes
*Saved 2 bytes thanks to @tsh*
```
a=>[0,0,...a].map((v,i)=>v+~~a[i])
```
[Try it online!](https://tio.run/##bZCxDoMgFEV3v8JR01cERG0H/RHDQKw2NlZMbRz9dQto1SgkLIfDuxdeYhB98am777WVj3Kq0kmkWY4BA0JIcPQWnecNUPtpNlzGUeQ196dCtr1sStTIp1d5OQEKIXfV8n03CFwDmIHOQVXUiKvKZvUkkkXbzcRATlqiLkcQ81XTgFAg2GDH0lQnEr5rGpkZ1DJ9zjyUoNYi28lODZd91m@QQKyT/7oGZKvOLAEM7kDUU9cApl2KZ2x5Kj98oJqt4PQD "JavaScript (Node.js) – Try It Online")
[Answer]
# T-SQL, 94 bytes
```
SELECT sum(x)FROM(SELECT*FROM @
UNION SELECT x,i+2FROM @
UNION SELECT 0,i+1FROM @)y
GROUP BY i
```
**[Try it online](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=bd411d17e244154ed4c360801035f4da)**
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
F²⊞θ⁰IEθ⁺ι§θ⁻κ²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw0hTIaC0OEOjUEfBQNOaK6AoM69EwzmxuETDN7EAJBqQU1qskamj4FjimZeSWgES8s3MA4pl6ygYaYKB9f//0dGGOiY6ljqGZrGx/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²⊞θ⁰
```
Append two zeros to the input array.
```
IEθ⁺ι§θ⁻κ²
```
Add the last but one element to each element of the array and output the result.
[Answer]
# x86-64 machine code, 16 bytes
```
89 d1 31 c0 99 03 06 ab ad 92 e2 f9 ab 92 ab c3
```
[Try it online!](https://tio.run/##XVLBctsgFDzrfcWLOm2kmngsRXbSqO4lf9CrqwNByGZGFiqgjGY0/vWqD2RnOr0Au293gQei7x@OQswzt2dM8GecwPrY6jfeYgPNC0Rn/Y5SjAxlPUI0aoOSe8QJifo3GNlL7kjI63opHYxVFUTWaVtD1OraT6M4HX3E1dlq3eNi/VD@J7myRjpIY0xLkKOTpsP4NcbpXasam0R1Dr8ahkJ31mFAnIW5S8sLwCfViXaoJX63rlZ6ffoBYB13SqB1ZhAOnbROcCtxCq4ymPnhuSL7rWYPFe5xgumRTRnL2ePlwmDK2VSwPCwz4sOiYNMTK9iW7QLcLnqSsaUeAjZXsF1A/i/xzJ7YjvzFLS4j9zeW7W5bZn5LuJTgz3nmqktSmCBq6F2SpQt8cBq/OHz5uJtNISJN5C1G2qF1h2xTlcQ0yYIZujX3A7XN0z7NqxXde0M9wbu9L@IKc0KrFQVGUW9I0iTxZ4UxuwWrKiT0gxMnbpL7X929J@jI8/xHNC0/2vnhvCtooB@3pwTZ/gU "C++ (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as an array of 32-bit integers; the address of the given array in RSI; and the length of the given array in RDX.
In assembly:
```
f:
mov ecx, edx # Put the length in ECX.
xor eax, eax # | Set EAX and EDX to 0.
cdq # | These will hold the two previous numbers in that order,
repeat: # | or 0 if nonexistent.
add eax, [rsi] # Add the current number to the twice-previous number.
stosd # Write the sum to the result array, advancing the pointer.
lodsd # Load the current number into EAX, advancing the pointer.
xchg edx, eax # Exchange EDX and EAX, putting the previous number into EAX
# and the current number into EDX.
loop repeat # Loop, counting down from the length in ECX.
stosd # Write the penultimate number to the result array,
# advancing the pointer.
xchg edx, eax # Switch the last number into EAX.
stosd # Write the last number to the result array, advancing the pointer.
ret # Return.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
Sż+‼Θ
```
[Try it online!](https://tio.run/##yygtzv7/P/joHu1HDXvOzfj//3@0hY65jpmOqY5JLAA "Husk – Try It Online")
Zips by addition the input together with itself after prepending two zeros:
```
Sż+‼Θ
S # hook: Sfgx means f(x,g(x))
ż # f = zip together (keeping trailing elements)
+ # by addition:
‼ # g = apply twice
Θ # prepend zero
```
(one byte (‼) longer than [Ken Iverson’s Favourite Expression](https://codegolf.stackexchange.com/a/216480/95126))
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/index.html), ~~14~~ ~~12~~ 10 bytes
*Edit: -2 bytes (and a BQN lesson) thanks to ovs & Razetime*
```
2⊸⌽⊸+0‿0∾⊢
```
[Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=TW92ZV9yaWdodF9hbmRfbGVmdCDihpAgMuKKuOKMveKKuCsw4oC/MOKIvuKKogpNb3ZlX3JpZ2h0X2FuZF9sZWZ0IDjigL834oC/NuKAvzXigL80)
[Answer]
# TI-Basic, 17 bytes
```
augment({0,0},Ans)+augment(Ans,{0,0
```
Takes input in `Ans`.
[Answer]
# [Zsh](https://www.zsh.org/), ~~48~~ 42 bytes
```
a=(0 0 $@);for i ($@ 0 0)echo $[i+$a[++j]]
```
[Try it Online!](https://tio.run/##NUy7DoIwFN37FWfo0KZLWxE1xIT/IAzEUB6DJFQXlW@vR1KHm/O@rzimoPT7eY/9AxNmiIEydVdlYSFrXYVlZaBkTW11fxsXyGYysmuMmds2bdXA3meNmxABDh4HYgH/U7wT@RFlzujvruO3P/rMz@yW7Ba7X@ACl2fpCw)
~~[48bytes](https://tio.run/##qyrO@J@moVldmlecWqKQqZClwJUO5P5PtNUwUDBQUHHQtE6y1VBxALINNK3T8ovAajRUqhOt4pJqNW1sbFSiM7WzYv/XWqcDVdcUFddycaUpGCoYKRgDaRMFIxAPiM2BbFMFM6gcUBwsagg0F0YbQdkWQLVmQLUmYHETBUsFQ6i2/wA "Zsh – Try It Online")~~ - zip & add arrays
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 3 bytes
```
çç+
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FksPLz-8XHtJcVJyMVRkwc2IaEMdIx3jWK5oEx0jIGkIxOY6JjqmOmYgHlAOKK5jCGYbwGkjKNtCx1zHDKjWBCxuomOpYwjVFguxAAA)
```
çç+
ç Prepend zero
ç Prepend zero
+ Add
```
---
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 3 bytes
```
5Ƃ×
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FktNjzUdnr6kOCm5GCqy4GZEtKGOkY5xLFe0iY4RkDQEYnMdEx1THTMQDygHFNcxBLMN4LQRlG2hY65jBlRrAhY30bHUMYRqi4VYAAA)
```
5Ƃ×
5Ƃ Binary digits of 5
× Convolve
```
[Answer]
# [Arturo](https://arturo-lang.io), 34 bytes
```
$[a][map couple++a<=[0,0]++a=>sum]
```
[](https://i.stack.imgur.com/RSnm5.png)
```
$[a][ ; a function taking an argument a
map ... =>sum ; map over a block and take the sum of each element
couple ; aka zip
++a<=[0,0] ; input ++ [0, 0]
[0,0]++a ; [0, 0] ++ input
] ; end function
```
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://www.uiua.org/pad?src=0_7_1__IyBTaW5nbGUtYnl0ZSBjaGFyYWN0ZXIgZW5jb2RpbmcgZm9yIFVpdWEgMC44LjAKIyBXcml0dGVuIGhhc3RpbHkgYnkgVG9ieSBCdXNpY2stV2FybmVyLCBAVGJ3IG9uIFN0YWNrIEV4Y2hhbmdlCiMgMjcgRGVjZW1iZXIgMjAyMwojIEFQTCdzICLijbUiIGlzIHVzZWQgYXMgYSBwbGFjZWhvbGRlci4KCkNPTlRST0wg4oaQICJcMOKNteKNteKNteKNteKNteKNteKNteKNteKNtVxu4o214o21XHLijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbUiClBSSU5UQUJMRSDihpAgIiAhXCIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0-P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX7ijbUiClVJVUEg4oaQICLiiJjCrMKxwq_ijLXiiJril4vijIrijIjigYXiiaDiiaTiiaXDl8O34pe_4oG_4oKZ4oan4oal4oig4oSC4qe74paz4oeh4oqi4oeM4pmtwqTii6_ijYnijY_ijZbiipriipviip3ilqHii5XiiY3iip_iioLiio_iiqHihq_imIfihpnihpjihrvil6vilr3ijJXiiIriipfiiKfiiLXiiaHiip7iiqDijaXiipXiipziipDii4XiipniiKnCsOKMheKNnOKKg-KqvuKKk-KLlOKNouKsmuKNo-KNpOKGrOKGq-Kags63z4DPhOKInuK4ruKGkOKVreKUgOKVt-KVr-KfpuKfp-KMnOKMn-KVk-KVn-KVnCIKQVNDSUkg4oaQIOKKgiBDT05UUk9MIFBSSU5UQUJMRQpTQkNTIOKGkCDiioIgQVNDSUkgVUlVQQoKRW5jb2RlIOKGkCDiipc6U0JDUwpEZWNvZGUg4oaQIOKKjzpTQkNTCgpQYXRoVUEg4oaQICJ0ZXN0MS51YSIKUGF0aFNCQ1Mg4oaQICJ0ZXN0Mi5zYmNzIgoKRW5jb2RlVUEg4oaQICZmd2EgUGF0aFNCQ1MgRW5jb2RlICZmcmFzCkRlY29kZVNCQ1Mg4oaQICZmd2EgUGF0aFVBIERlY29kZSAmZnJhYgoKIyBFeGFtcGxlczoKIwojIFdyaXRlIHRvIC51YSBmaWxlOgojICAgICAmZndhIFBhdGhVQSAi4oqP4o2PLuKKneKWveKJoOKHoeKnuyziipdAQi4iCiMgRW5jb2RlIHRvIGEgLnNiY3MgZmlsZToKIyAgICAgRW5jb2RlVUEgUGF0aFVBCiMgRGVjb2RlIGEgLnNiY3MgZmlsZToKIyAgICAgRGVjb2RlU0JDUyBQYXRoU0JDUwo=), 7 bytes
```
+↻2.⊂⊚2
```
[Try it!](https://uiua.org/pad?src=0_7_1__ZiDihpAgK-KGuzIu4oqC4oqaMgoKZiBbMSAyIDNdCmYgWzQgMl0KZiBbMV0KZiBbNyA0IDUgNl0K)
```
+↻2.⊂⊚2
⊚2 # a list with two zeros
⊂ # prepend
. # duplicate
↻2 # rotate by two elements
+ # add
```
] |
[Question]
[
This is my attempt to pair [code-shuffleboard](/questions/tagged/code-shuffleboard "show questions tagged 'code-shuffleboard'") with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
You need to write a full program or function that sums all codepoints of the input string. If there is no input, you can output any number, including `0`.
## Rules
* The input will always be in printable ASCII.
* The sum of the codepoints of your source must be exactly 2540.
+ If your language uses its own code page, you should use it to calculate your program's codepoints.
+ If you used Unicode in your code you *have* to use Unicode bytes to calculate your program's length.
* Null bytes (which don't contribute to your codepoint sum) are banned.
* The program must **not** work with any consecutive substring removed.
* The conversion of codepoints are required.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Your score is the length of your source code, the shorter being better.
[Answer]
# [Haskell](https://www.haskell.org/), 25 bytes
```
b~zw=sum(fromEnum`map`zw)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P6muqty2uDRXI60oP9c1rzQ3ITexIKGqXPN/cVGyrRJOaSWu3MTMPNuCosy8EpUkBaDi//@S03IS04v/6yYXFAAA "Haskell – Try It Online")
The `~` is not an infix operator, but a marker for a [lazy pattern match](https://wiki.haskell.org/Lazy_pattern_match) on argument `zw` of `b`, while conveniently being the largest-valued ASCII character at 126. The infix-ized ``map`` is also used because the backtick has a large ASCII value of 96. With both of these, we can avoid any spaces or other whitespace, which have low ASCII values.
The dense 24-byter
```
z~zz=sum$fromEnum`map`zz
```
comes just short in its sum of 2525, 15 too small. Its average ASCII value is 105.21, with the only values below 97 (for `a`) being `=` at 61, `$` at 36, and `E` at 69. An improvement would like involve finding an alternative for one of these.
(Non-ASCII characters can surely do better by having higher character values, but I'm not doing that because this is more interesting.)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~11 10~~ 9 bytes
*Thanks @MariaMiller for finding the right Unicode character, saving 1 byte!*
```
ࠂ,=sum,
```
[Try it online!](https://tio.run/##TY8xUsQwDEV7n@LjbZwZQ0O3M0vNDbYACuMoJEPW8tgKAy0n4WjcJChOwTaW7f/09ZW/ZOR0vx5QwwdBRkLlpURC5J4QKqqUKb15CCOOFN93ZrlgDkLFNOwEa@36@/PtT6r4VV93W192nTH0SdFtmN4PEKrSLIYlRZk4mYELKqaEp1cbrIeeYa@PNM/sceYy9zf25WiArGHEVQ97@6CMjnS1a8b/4bZZmZVrMXm43sjsBvY5XWm7dFQ//XSXkB2X3rfIXbf@AQ "Python 3 – Try It Online")
This is essentially just `sum`, padded with extra characters to reach the sum of `2540`. Usage is `ࠂ(s)` where `s` is a byte string (which acts like both string and integer array). Feels kinda cheaty, but ¯\\_(ツ)\_/¯.
The first character in source code is the Unicode character with codepoint `2050` ([Samaritan letter Gaman](https://www.fileformat.info/info/unicode/char/0802/index.htm)). This character might not be displayable depending on your browser.
---
The previous solution is longer but has nice Unicode characters:
**11 bytes**
```
ϕ,ϴ=sum,9
```
[Try it online!](https://tio.run/##TY8xUsMwEEV7neKjNPKMSJOKzISaG1AAhZDX2IOj1UhrhhwkN@EePpIjywVpJO3@t3@/4kV6Dodlh@x@CNITMk/JEzy3BJeRJQ3hy0IYvif/vTHTGaMTSqpiJ2itl/lq579TkezTUur9OhlNoxT9kjcrWN47CGWpJt0UvAwcVMcJGUPA26d22qKcbrtfaBzZ4pXT2D7oj6MCYokjJlvox@fCzFeTm@r7n25dFblgNSd3919S27x@D3faJh2LXWmas4uGU2tr4qZZbg "Python 3 – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/Flakheads/BrainHack), 32 bytes
```
<[[[{({}()<>)<>}<>({{}[()]})]]]>
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v/fJjo6ulqjulZD08YOiGpt7DSqq2ujNTRjazVjY2Pt/v//r0RIjRIA "Brain-Flak (BrainHack) – Try It Online")
## Explanation
First the observations I made my first time around (that solution and its explanation is below) continue to be important here. We need and even number of `()` pairs for a valid answer.
This time however we are going to use a starting program that already has an even number of `()`s.
```
{({}()<>)<>}<>({{}[()]})
```
This program first increments every element by 1 then calculates the sum of 1 less than every element. If we look at all possible ways to delete from this without causing a bracket mismatch here are what they do:
```
{(()<>)<>}<>({{}[()]}) # Never halts
{({}<>)<>}<>({{}[()]}) # Sums 1 less than every element
{({}())<>}<>({{}[()]}) # One more than above
{({}()<>)}<>({{}[()]}) # Never halts
{({}()<>)<>}({{}[()]}) # No output
{({}()<>)<>}<>({[()]}) # Never halts
{({}()<>)<>}<>({{}[]}) # Complex output still incorrect
{(<>)<>}<>({{}[()]}) # Never halts
{({})<>}<>({{}[()]}) # Sums 1 less than every element
{({}()<>)<>}<>({{}}) # Sums 1 more than every element
{()<>}<>({{}[()]}) # Sums 1 less than every element
{({}()<>)<>}<>({}) # Adds 1 to every element
{<>}<>({{}[()]}) # Sums 1 less than every element
{({}()<>)<>}<>() # Adds 1 to every element
{}<>({{}[()]}) # Outputs 0
{({}()<>)<>}<> # Adds 1 to every element
<>({{}[()]}) # Outputs 0
{({}()<>)<>} # Outputs nothing
({{}[()]}) # Sums 1 less than every element
```
So this is a good starting place. To make it the correct sum I use the same method I outlined for the first attempt.
>
> Now we just need the proper combination of `[..]`s `<..>`s and `((..){}){}`s to hit 2540. Unfortunately while `[..]`s would be ideal seeing as they have the highest codepoint average I can't seem to get it to work with any of them present.
>
>
>
This time we are luckier and the winning combination is `<[[[..]]]>`.
# [Brain-Flak](https://github.com/Flakheads/BrainHack), 34 bytes
```
<<<<<<<<(((({{}})){}){}){}>>>>>>>>
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v/fBgo0gKC6urZWU7O6FoLsoOD///9KhFUpAQA "Brain-Flak (BrainHack) – Try It Online")
## Explanation
The code that does the task is `({{}})`. But we need to pad it to 2540. The main issue is that apart from `()` every pair has an even total. This means we need and even number of `()` pairs, and at the same time our starting code uses only 1 `()` pair.
On top of this unlike `[]` or `<>` `()` pairs are not so easy to add. The one way we can do that is to wrap the entire program in `(..){}`, so to rectify our issue we alter the base program to
```
(({{}})){}
```
Now we just need the proper combination of `[..]`s `<..>`s and `((..){}){}`s to hit 2540. Unfortunately while `[..]`s would be ideal seeing as they have the highest codepoint average I can't seem to get it to work with any of them present. The one that works is the one used above.
[Answer]
# [C# (Visual C# Interactive Comρiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 13 bytes
I *had* to abuse the IO so that C# can be comρetitive once in its entire existence. Takes char codes as `int`s as inρut. To make this seem less terrible, this acceρts any `IEnumerable<int>` instead of only an array.
```
ρ=>ρ.Sum();
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpds4@maV5qbWpSYlJNqk5lXYqejACIV3BRsFf6fb7S1O9@oF1yaq6Fp/T@gCCij4aahhCKspBeS75yRWORYVJRYqaGpF5yak5pcolFha6cBVK5Zoampac0F1@qRmpOTr6MQnl@Uk6JIjNb/AA "C# (Visual C# Interactive Compiler) – Try It Online")
Alternatively, for less byte savings (30 bytes):
This includes the most descriptive variable name ever on this website.
```
strS=>strS.Select(p=>+p).Sum()
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5yRWBQdq6OQmVdip@CmYPu/uKQo2NYOROoFp@akJpdoFNjaaRdo6gWX5mpo/rfmCigCqtVw01DySM3JyddRCM8vyklRVNILyXcGmuVYVJRYqaGpqYmkEL@RmDr/AwA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# brainfuck, ~~41~~ 39 bytes
(I haven't tested exhaustively)
Uses 3 strategies for wasting the codepoint sum: repeating all `<` and `>`, nesting the innermost `[` and `]` unneccessarily, and adding and later removing the same number to/from the output.
Runs in an interpreter with large cells and wrapping/bidirectional memory, which TIO isn't :(. Outputs by charcode.
```
++++++[[[[[[[<<<+>>>-]]]]]],]<<<------.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
žĆs"þþþþþx"g6QôkO
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6L4jbcVKh/fBYIVSulng4S3Z/nikAA "05AB1E – Try It Online")
This was made by Kevin Cruijssen.
## Explanation
```
žĆ # Push codepage
s # Swap
"þþþþþx" # Push a string of length 6
g # Get the length of the string (6)
6Q # And compare it with 6 (True -> 1)
ô # Split into chunks
k # Index into the codepage
O # Sum
```
# Original idea, ~~63~~ ~~48~~ ~~36~~ 29 bytes
-15 bytes by using `1!` and replacing the `!`.
-12 bytes by dropping the factorial entirely, and using `≠` instead of `1`.
-7 bytes by using `тн` and replacing the `н`. I'm not sure if this is allowed though, because with no input, it just outputs 49.
```
тžĆ"ʒʒʒʒʒʒʒʒʒʒKþþþ"gè.VôžĆskO
```
[Try it online!](https://tio.run/##yy9OTMpM/f//YtPRfUfalE5NwoTeh/eBoFL64RV6YYe3gNQVZ/uToQUA "05AB1E – Try It Online")
## Explanation
```
т # Push 100
žĆ # Push the codepage
"ʒʒʒʒʒʒʒʒʒʒKþþþ" # Push a string of length 14
g # Get the length of the string
è # Index into the codepage (н)
.V # Run н (first digit of 100)
ô # Split into chunks of 1
žĆ # Push codepage
s # Swap with input
k # Find each char in codepage
O # Sum
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 25 bytes
```
Ƌ->Ƌ.codePoints().sum()
```
[Try it online!](https://tio.run/##dY1NCsIwEIX3PcXgKhHMBbSCG1cKgu7ERewfqfmjMykU8QTeq9eKsboTV8Pje9@8VvZy0Za3qIx3HUGbsgiktKiDLUg5K@bL7AcidZU0b1RoiQh7qSzcMwAfrloVgCQpnd6pEkxi7Eidss35ArJrkE9VgJPbOdtsv0OrT2cNNeRxfC7W41MUrqwOTllCxgUGw3hcTqpOIhDkUAvpvR42@H7FZn@9Gf@IxwGpMsIFEj7NkbaMJvTIHvEF "Java (JDK) – Try It Online")
All alternatives I tried failed:
```
s->s.chars().sum() // Function<String,Integer>
s->s.sum() // Function<IntStream,Integer>
java.util.stream.IntStream::sum
...
```
[Answer]
# [Perl 5](https://www.perl.org/), 29 bytes
```
for(split//,<>){$u+=ord}say$u
```
[Try it online!](https://tio.run/##K0gtyjH9/z8tv0ijuCAns0RfX8fGTrNapVTbNr8opbY4sVKllID0v/yCksz8vOL/ur6megaGBgA "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 26 bytes
```
lambda ŏ:sum(ŏ.encode())
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUeFov1Vxaa7G0X691Lzk/JRUDU3N/wVFmXklGmkaSh6pOTn5Ogrh@UU5KYpKmppcXMoKQNUKaaV5ySWZ@XkKJRmJJQrJiXkKKamJOQrlmSUZCnn5ebqOwc6enlzptlA7isFW5CYWaOQXpegUA82B2JCOxQa4DFTv4R6w5sM9CPdhU4bFG0Bl/wE "Python 3 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 28 bytes
```
lambda eZ:sum(bytearray(eZ))
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklkTM1yqq4NFcjqbIkNbGoKLFSIzVKU/N/QVFmXolCmoYSPlVKmv8B "Python 2 – Try It Online")
[Answer]
# [PHP](https://php.net/), 35 bytes
```
FOR(;$zz=$argn[$u++];)$a+=ORD($zz);
```
[Try it online!](https://tio.run/##K8go@G9jXwAk3fyDNKxVqqpsVRKL0vOiVUq1tWOtNVUStW39g1w0gBKa1v9dnT38VRKtoWqdYEqdIUodoUqdNK3BCh2t/@UXlGTm5xX/13UDAA "PHP – Try It Online")
OK I'm cheating a little bit here, but the shorter code I found for PHP having too much codepoints sum already (2549), I'll interpret the question in a litteral sense:
* "program or function that sums all codepoints of the input string" -> it is not said I have to display the result, above code actually sums it :D (yeah I know, implicit rules.. well!)
* "you can output any number, including 0" -> well I can, but if not forced to, I won't :P
[Answer]
# [Python 2](https://docs.python.org/2/), 28 bytes
```
lambda zva:sum(map(ord,zva))
```
[Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SaqukpPQ/JzE3KSWRs6os0aq4NFcjN7FAI78oRQfI19T8D1SgV1xSlFmgocmVZptalpijAdKoyVVQlJlXopAG4f0HAA "Python 2 – Try It Online")
Uses a tab after the `lambda`.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-nl`, ~~28~~ 26 bytes
-2 bytes from GB.
```
p $_.chars.sum{|ay|ay.ord}
```
[Try it online!](https://tio.run/##KypNqvz/v0BBJV4vOSOxqFivuDS3uiaxEoj08otSavHJ/csvKMnMzyv@r5uXAwA "Ruby – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes
```
A[J_]:=Tr@ToCharacterCode[J]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/98x2is@1so2pMghJN85I7EoMbkktcg5PyU12iv2f0BRZl5JtGO0UmJSckpqWrpSbCwXXAyfTqDC/wA "Wolfram Language (Mathematica) – Try It Online") Defines a named function `A` that takes a string as input and returns the sum of its ASCII codepoints. `ToCharacterCode` converts a character to its codepoint (and outputs a list of codepoints when fed a string of characters) and `Tr` sums them.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410)
```
üüd←⎕UCS⍞⋄+/üüd
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f/hPYf3pDxqm/Cob2qoc/Cj3nmPulu09cGiIAX/geKe/kB5Ay5tfSDbMexR72Z1PJrUFRQe9c5VCMnILFZISc3NzysuKUosSS1WKMlILAESqQrJ@SmpBfmZeSUKxaW5CuWZJRmZeWCJlNS0xNKcEoiCxPRUBaARRqYmBly6urpcaVyGRsZAMjEpGaguPSMzKzsnNy@/oLCouKS0rLyisgoA "APL (Dyalog Unicode) – Try It Online")
A full program that takes a single line from STDIN as input.
The ASCII characters are shuffled around within the default codepage (along with APL symbols and accented characters), and many useful characters appear at the high half (character value > 128). Accented characters are valid to use in an identifier, and `ü` has the highest character value among them.
This code achieves "The program must not work with any consecutive substring removed" by separating the Unicode conversion `⎕UCS` and sum `+/` into two statements.
The character `⎕` alone is *over nine thousand* (pun intended) in Unicode, so APL can't compete using Unicode scoring.
### How it works
```
üüd←⎕UCS⍞⋄+/üüd
⍞ ⍝ Take a line of input from stdin
⎕UCS ⍝ Convert to Unicode codepoints
üüd← ⍝ Assign to variable
⋄ ⍝ Statement separator
+/üüd ⍝ Sum
```
[Answer]
# Python, 30 bytes
Works in Python 2 and 3.
```
lambda abZ:(sum(map(ord,abZ)))
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSExKcpKo7g0VyM3sUAjvyhFByigqan5v6AoM69EI01DHb86daBSAA "Python 3 – Try It Online")
Alternative 30-byter:
```
lambda aN,b=ord:sum(map(b,aN))
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRTyfJNr8oxaq4NFcjN7FAI0kn0U9T839BUWZeiUaahjp@depApQA "Python 3 – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 28 bytes
```
'zzzzzzzzzzzh'+{}/]{+}*1446-
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X70KATLUtatr9WOrtWu1DE1MzHTxywIA "GolfScript – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 37 bytes
```
func[-][!: 0 forall -[!: ADD ! -/1]!]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85Wjc2WtFKwUAhLb8oMSdHQRfEc3RxUVBU0NU3jFWM/V9QlJlXopCmoESUciUuuHpDI2Ol/wA "Red – Try It Online")
Nothing original. `-` is the input string, `!` is the sum. For each character in the input string I add its value to the sum. [Red](http://www.red-lang.org) is case insensitive, so I use `ADD` instead of `add` (and isntead of the `+` operator) in order to match 2540. `forall` iterates over the entire series (list) and at each iteration returns the remaining series - just like `cdr` in LISP or `rest` in Racket. That's why I use `/1` to obtain the first element in the series.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 28 bytes
```
Ă=>eval(Buffer(Ă).join`+`)
```
[Try it online!](https://tio.run/##TY27DoJAEEV7v2K6nQk4sTeQaGVpb0xYllkDWRmyPOz5Nv5rxc76nnNuZxc7utgO07HXRpKHIm1rUcpiA15n7yXithJ32vZVVlFy2o8ahIO@0KO5SQgKH42hMUTnw//8YGb0kIEx9OS3HdBBUYJjtz/d9@B0mZCIozSzE0SbQ00/wu5OncOJKH0B "JavaScript (Node.js) – Try It Online")
Submission only works on ASCII. Although it source code contains non-ASCII.
This one based on code by [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld).
---
# [JavaScript (Node.js)](https://nodejs.org), 31 bytes
```
s=>Buffer(s).map(c=>w+=c,w=0)|w
```
[Try it online!](https://tio.run/##PYu9DoMgEIB3n8LxiC1xJ@fQJ/FCwWDAI4eVpe@ODsb1@1npoGIl5P298de1LLwIpR77uRWcPj/vnUBROlEGi1Md0L4qjupf26x3CQmU6fzVu4Mi3PuFOstb4eh05AX8I5RpJw "JavaScript (Node.js) – Try It Online")
---
Another trivial one.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
IΣES⁺⊗⊗⊗⊗LPP⌕γι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUDDM6@gtCS4BCiRrqGpoxCQU1qs4ZJfmpSTmoKT9knNSy/J0FAKCFDSBAEdBbfMvBSNdB2FTDBf0/r//2JbO6fStLTUIo1iTb1coEXJtnbl2rbJOuW2Bpo15f91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Only works on printable ASCII, so I can't feed it its own source code, even if I could create it in the right code page. Explanation:
```
S Input string
E Map over characters
ι Current character
⌕ Find index in
γ Printable ASCII
⁺ Plus
PP Literal string `PP`
L Length
⊗⊗⊗⊗ Doubled four times
Σ Take the sum
I Cast to string
Implicitly print
```
Hex dump in Charcoal's code page:
```
C9 91 C5 D3 AB 9E 9E 9E 9E CC 50 50 9B E7 E9
```
[Answer]
## Common Lisp, 42 bytes
```
(LAMBDA(%)(APPLY'+(MAP'CONS'CHAR-CODE %)))
```
This was found by trial and error using the following test: basically the code is printed to string, with some spaces removed (but not all, otherwise it parses badly), then it is read back to lisp and evaluated with its own representation.
```
(let ((string (remove #\space
(princ-to-string
'(lambda(%)(apply'+(map'cons'char-code %))))
:count 6)))
(values string
(funcall (eval (read-from-string string)) string)))
```
This returns both the code as string, and its sum:
```
"(LAMBDA(%)(APPLY'+(MAP'CONS'CHAR-CODE %)))"
2540
```
Usually you call `map` as follows, `(map 'list function sequence)`, where `list` is the type of result you want to build with map. Any Lisp type can be given, but obviously it should be a sequence. Here I used `cons` (lists are made of cons cells) to change the count, but the consequence if that is that there will be an error if the input is an empty sequence, since it cannot be expressed as a cons cell.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~19~~ ~~13~~ 12 bytes
```
->{.sum}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1@5cc/W5Zr3i0tza/wUK6sh8db3kjMSiYhBbQ80qvyhFk6tAIS1aPSM1JydfPRbIgTIx1P0vSS0u@ZdfUJKZn1f8XzcvBwA "Ruby – Try It Online")
The weird char probably isn't displayed, so it's ASCII 899.
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 22 bytes
```
"̛̜"-&57i:&+&1+?.&n;
```
[Try it online!](https://tio.run/##S8sszvj/X@nMnDOzlXTVTM0zrdS01Qy17fXU8qz//09JAQA)
Contains two two-byte unicode characters, which can't be removed since they are used to set the initial value of the accumulator. Relies on the official interpreter's quirk of normalizing jump coordinates back to 0 if they are outside the code box (for parity).
] |
[Question]
[
**This question already has answers here**:
[Code Golf: 6174 - Kaprekar's mythical constant](/questions/2762/code-golf-6174-kaprekars-mythical-constant)
(22 answers)
Closed 8 years ago.
**Input**:
A three digit number
* from stdin or as an argument
* not all digits are the same
* may start with one or two zero's
**Process**
Order the input-digits ascending and descending to form two new numbers.
Subtract the smallest from the largest. Use the difference as new input. NB: This process needs 3 digits, so 10 has to be returned, or taken care of, as 010.
Repeat this process (Kaprekar transformation) until you hit [495](http://en.wikipedia.org/wiki/495_%28number%29).
**Output**:
The number of steps it took to reach 495.
Example:
Input: 211
```
211 – 112 = 099
990 – 099 = 891 (rather than 99 - 99 = 0)
981 – 189 = 792
972 – 279 = 693
963 – 369 = 594
954 − 459 = 495
```
Output: 6
[Answer]
## Windows PowerShell, 61 ~~65~~ ~~70~~ ~~72~~ ~~73~~ ~~82~~
Evil alternative approach. It becomes apparent if you desperately search for patterns in the input.
Be sure to also check out Ventero's [Ruby](https://codegolf.stackexchange.com/questions/1255/hitting-495-kaprekar/1268#1268) and [Golfscript](https://codegolf.stackexchange.com/questions/1255/hitting-495-kaprekar/1270#1270) solutions which use the same technique which was sort of a joined work :-)
```
(7..3+1..5)[($x=($a="$args")[0..2]|sort)[2]-$x[0]]*($a-ne495)
```
A little explanation might be in order for this, I guess. Suppose you have a number consisting of three digits. For convenience they are labeled *a*, *b* and *c* here with *c* being the largest. You then are going to subtract *abc* from *cba*.
If we picture that, we are going to get (*c* − *a* − 1), 9 and (10 + *a* - *c*) as the individual digits. This will *always* hold, no matter the input digits. This also means that the middle digit get no say in how long the sequence will be, simply because it always is `9`.
So basically the first and last digit of the *sorted* digits suffice in determining the length of the sequence. One can easily make a list with every conceivable combination of first and last digit (there are only 45) to search for patterns there.
As it turns out, there are at least two. Both play with the first few results of the different digits: `[6 5 4 3 1 2 3 4 5]`. First, taking the *difference* between the largest and the smallest digit and subtracting one gives the appropriate index in the aforementioned list of results. Second, interpreting the smallest and largest digit as a single number and doing modulo 11 yields the same, except that one has to prepend another `6` to the list.
[Answer]
## J, ~~43~~ 37
```
<:$".@(\:,'-',/:)~@":@((3$10)&#:)^:a:
```
Sample run (note how stripping the 3 leading chars displays a trace):
```
<:$".@(\:,'-',/:)~@":@((3$10)&#:)^:a:211
6
".@(\:,'-',/:)~@":@((3$10)&#:)^:a:211
211 99 891 792 693 594 495
<:$".@(\:,'-',/:)~@":@((3$10)&#:)^:a:494
1
<:$".@(\:,'-',/:)~@":@((3$10)&#:)^:a:495
0
```
This version repeatedly (`^:`) converts to decimal (`(3$10)&#:`), concatenates the descending list (`\:`), a minus sign `'-'` and the ascending list (`/:`), and evaluates (`".`). Until the result is stable (`a:`). Then it counts the number of returned elements (`<:$`).
I'm as surprised as you it needs fewer characters than the table lookup variant.
[Answer]
## Golfscript, ~~29~~ 26 characters
```
.$)\0=-.5<{7\}4if-\~495=!*
```
Basically a mix of Joey's PS- and my Ruby-solution.
Edit: Thanks [Nabb](https://codegolf.stackexchange.com/users/174/nabb) for a suggestion on how to shorten this by 3 characters.
[Answer]
## Python, 89 characters
```
n=input()
c=0
while n-495:s=''.join(sorted('%03d'%n));n=int(s[::-1])-int(s);c+=1
print c
```
[Answer]
## J, 40
Using the Joey/Ventero approach. (go upvote them first)
```
(-&4`(7&-)@.(<&5)".'-'1}\:~y)-'495'-:y=.
```
This doesn't beat Golfscript, but I liked the idea of sorting the number, replacing the middle digit with a `-` and evaluating that.
[Answer]
## Ruby 1.8, ~~64 55 52~~ 48 characters
```
l=gets.bytes;i=l.max-l.min;p /495/?0:i<5?7-i:i-4
```
Note that the input shouldn't contain a line break.
For Ruby 1.9, the solution needs an additional space before the last colon.
* (64 -> 55) Thanks to [Joey](https://codegolf.stackexchange.com/users/15/joey) for pointing out that the input already consists of 3 digits.
* (55 -> 53) Thanks to [steenslag](https://codegolf.stackexchange.com/users/537/steenslag) for pointing out `Array#minmax`
* (53 -> 52) Actually just using `Array#max` and `Array#min` directly is shorter.
* (52 -> 48) Implicitly match a regexp against `$_` to test for 495.
[Answer]
## Windows PowerShell, ~~80~~ 79
```
for($a="$args";$a-495;++$i){$a=-join($x="00$a"[-1..-3]|sort)[2..0]-+-join$x}+$i
```
History:
* 2011-03-05 00:27 **(113)** Initial attempt.
* 2011-03-05 00:33 **(107)** One `sort` has to suffice.
* 2011-03-05 00:36 **(92)** Inlined the `filter`.
* 2011-03-05 00:41 **(87)** No format string anymore. There are other ways.
* 2011-03-05 00:43 **(85)** Unnecessary parentheses.
* 2011-03-05 01:01 **(83)** `-eq` → `-`.
* 2011-03-05 15:42 **(80)** I no longer need to cast the initial input to `int`. Removed unneeded parentheses.
* 2015-09-11 08:20 **(79)** I can move a `+` and save a space by abusing that `-` can only mean arithmetic and thus always converts both operands to a number.
Side note: [My test cases](http://svn.lando.us/joey/Public/SO/CG1255/test.ps1).
[Answer]
## C - 133
*newline added for appearance*
```
c;main(n,l,h,t,i){scanf("%d",&n);for(;n!=495;c++,n=(h-l)*99)
for(l=n%10,h=l,i=2;i--;)t=(n/=10)%10,t<l?l=t:t>h?h=t:0;printf("%d\n",c);}
```
[Answer]
# APL, 42 chars/bytes\*
```
{⍵=495:⍺+0⋄L←⍵⊤⍨3⍴10⋄(⍺+1)∇10⊥L[⍒L]-L[⍋L]}
```
APL entry was missing from historic golf! Had to rectify. Trivial implementation, nothing fancy. Tested on [ngn/apl](http://ngn.github.io/apl/web/).
**Explanation**
The function is initially called with a single number `⍵`. It will recursively call itself `∇` with the number of steps already taken `⍺` and the new number `⍵`.
```
⍵=495: ⍺+0
```
Terminating condition: if `⍵` is 495, return the number of steps already taken (0 if `⍺` is yet undefined—this may differ in other dialects.)
```
L←(3⍴10)⊤⍵
```
Decode `⍵` into a list of 3 digits base 10. Above `⊤` is reflected to save 1 char.
```
(⍺+1) ∇ 10⊥L[⍒L]-L[⍋L]
```
Sort the list both ways, subtract one from the other member-wise, encode the result in base 10 (this works for negative digits too; may differ in other dialects) and recurse, adding 1 to `⍺` (or just 1 if undefined, see above.)
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
\*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long.
[Answer]
**Lua 173 bytes**
Going for the longest one:
```
T=table c=T.concat i=1 n=tonumber p=io.read()while l~="495"do l={p:match"(%d)(%d)(%d)"}T.sort(l)k={}k[1]=l[3]k[2]=l[2]k[3]=l[1]p=('%03i'):format(c(k)-c(l))i=i+1 end print(i)
```
[Answer]
## Python, 63
```
f=lambda n:n-495and-~f(99*(int(max(`n`))-int(min(`n`))*(n>99)))
```
A recursive function. Gives `0` for `n==495` and otherwise transforms `n` and increments the counter by `1` with `-~`.
The transformation uses the fact that for three-digit numbers `abc-cba` equals `99*(a-c)`. To account for two-digit numbers, we set the `min` digit to `0` unless `n>99`.
[Answer]
# JavaScript 145
This was the best I could do on such short notice:
`for(n=prompt(i=o=e='');!i--|n-495;o+=n+' - '+a+' = '+(n=(p=n-a+e)[2]?p:0+p)+'\n')b=n.split(e).sort(),n=b.reverse(a=b.join(e)).join(e);alert(o+~i)`
] |
[Question]
[
If you place the positive integers together and read each set of two adjacent digits at the same time, you get: ([A136414](http://oeis.org/A136414))
```
12, 23, 34, 45, 56, 67, 78, 89, 91, 10, 1, 11, ...
```
However, if you squash that sequence again:
```
12, 22, 23, 33, 34, 44, 45, 55, 56, 66, 67, 77, 78, 88, 89, 99, 91, 11, 10, 1, 11, 11
```
and so on.
Your task is to output the sequence of the positive integers ***squashed m times***.
# Squashing process
```
[1, 2, 3, 4, 5]
↓
"12345"
↓
[12, 23, 34, 45]
```
[Python squashing script](https://ato.pxeger.com/run?1=NY49DoIwGIbn9hRfmL6GYoJ_McTegI2x6UBSqjVYSFsGzuLCoqfwIt5GkDi97_A8yfN49WO8dm6ankM02ekz6saAwZYVlGheCal4iJ6SIJJkc-usw3vdY8VbxigpRds4DPMznQcL1oGv3aXBctGJNWDPZZYXOhXSuogVBmkVS3-b5ooxRYlv4uAd6DXg3fuFNChzDlsOOw57DgcOx5lekX_rFw)
# Rules
* You have to receive m (a positive integer) as the input or you can output the sequences for all m
* Numbers in the sequence can appear more than once
* Leading zeros must be removed (eg. `04` is `4`)
* [Default sequence rules](https://codegolf.stackexchange.com/tags/sequence/info)
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply
# Test cases
```
[In]: 1
[Out]: [12, 23, 34, 45, 56, 67, 78, 89, 91, 10, 1, 11, 11, 12, 21, 13, 31, 14, 41, 15, ...]
[In]: 2
[Out]: [12, 22, 23, 33, 34, 44, 45, 55, 56, 66, 67, 77, 78, 88, 89, 99, 91, 11, 10, 1, 11, 11, 11, 11, 11, 12, 22, 21, 11, 13, 33, 31, 11, 14, 44, 41, 11, 15, ...]
[In]: 3
[Out]: [12, 22, 22, 22, 23, 33, 33, 33, 34, 44, 44, 44, 45, 55, 55, 55, 56, 66, 66, 66, 67, 77, 77, 77, 78, 88, 88, 88, 89, 99, 99, 99, 91, 11, 11, 11, 10, 1, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 22, 22, 22, 21, 11, 11, 11, 13, 33, 33, 33, 31, 11, 11, 11, 14, 44, 44, 44, 41, 11, 11, 11, 15, ...]
```
[Answer]
# [Haskell](https://www.haskell.org), 49 bytes
```
f(x:z)=read[x,z!!0]:f z
q=[1..]:map(f.(>>=show))q
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWNw3TNCqsqjRti1ITU6IrdKoUFQ1irdIUqrgKbaMN9fRirXITCzTS9DTs7GyLM_LLNTULoRp1chMz8xRsuRQUgCp84xU0Cooy80oU9BRKErNTFUwMNBVUIExDAwWoHpilAA)
Haskell loves infinite sequences. Here we get to make an infinite sequence of infinite sequences.
The function `f` takes infinite string of digits and produces numbers formed from the pairs in order. We combine this with `(>>=show)` to get a function which takes an infinite sequence and produces the next. We use recursion to create the infinite list of such sequences starting with `[1..]`.
[Answer]
# Python 3.8, ~~121~~ 119 bytes
```
lambda m,n:m<1and n or(n*0==[]or(n:=range(1,n)))and(d:=''.join(map(str,n)))and z(m-1,[int(i+j)for i,j in zip(d,d[1:])])
```
[Try it online!](https://tio.run/##VYzLDsIgEEX3fsXsOqNoxMbEEPmSygKDD4gMBLuRn8fWpAt39@SenPwZn4n7Uy6t6kt72Xh1FqJgFc/SsgOGVJDXe60HMy@li@XHDaVgIpoMdEp33S4kzxhtxvdYlgsqxq0Ug@cR/SbQPRXwIoBnqD6jE26QypChlsvs1Kkqj0SrBQ//2P@wfQE "Python 3.8 (pre-release) – Try It Online")
`m` is the number of squashes applied and `n` controls the length of the output.
---
Same idea, except split over two functions (and somehow the exact same number of characters):
```
lambda m,n:y(m,range(1,n))
y=lambda m,a:m<1and a or(d:=''.join(map(str,a)))and y(m-1,[int(i+j)for i,j in zip(d,d[1:])])
```
[Try it online!](https://tio.run/##VY3LCsIwEEX3fkV2ncFRiEWQ0H5J7WIkPlLMJMRump@PqaDg8nAu98RlfgRpTzGV3J/Lk/3FsvIkZgFPieV@BU2CuFn6n2TjO81iFauQwJq@afZTcAKeI7zmRIyIq68fO02DkxncdsJbSMrRpJyo7CJYsoM2I45YYlo3uab0sba@ePjH9oPlDQ "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞IFSü«ï
```
Given \$m\$, output the infinite \$m^{th}\$ sequence.
[Try it online](https://tio.run/##yy9OTMpM/f//Ucc8T7fgw3sOrT68/v9/YwA) or [verify the first 25 results of the first 5 \$m\$](https://tio.run/##ASgA1/9vc2FiaWX/NUVOPyIg4oaSICI//@KInk5GU8O8wqvDr/99MjXCoyz/).
**Explanation:**
```
∞ # Push the infinite list of positive integers: [1,2,3,...]
IF # Loop the input `m` amount of times:
S # Convert the list of integers to a flattened list of digits
ü # For each overlapping pair of digits:
« # Append them together
ï # Convert it back to an integer to remove the leading 0s
# (after which the result is output implicitly)
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 21 bytes [SBCS](https://github.com/abrudz/SBCS)
Anonymous infix lambda, taking `m` as left argument and the number of elements of the sequence to generate as right argument.
```
{⍵↑{⍎¨2,/∊⍕¨⍵}⍣⍺⍳1+⍵}
```
`{`…`}` "dfn"; `⍺` is `m` and `⍵` is the number of elements to generate.
`1+⍵` increment the number of elements (to handle the case of 1)
`⍳` generate the **i**ntegers 1…`m`+1
`{`…`}⍣⍺` repeat application of the following function, `m` times:
`⍕¨⍵` format each number in the sequence
`∊` enlist (flatten)
`2,/` concatenate adjacent characters
`⍎¨` evaluate each
`⍵↑` take as many elements as requested
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu/VR28TqR719h1YY6eg/6uh61Dv10AqgcO2j3sWPenc96t1sqA3iAgA&f=M1RIUzAy4DICUsYWXMZAytwEAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 64 bytes
```
f=(m,n)=>n?[...f(m,n-1),m--?+f(m,n+2).join``.substr(n-1,2):n]:[]
```
[Try it online!](https://tio.run/##bcrLDkAwEIXhvSfpRDuhdhI8iEhcK4QZafH6ddlJLP/vnLk5G9fZadsVcT94bzKxSoIsp6JERPOUikGuShXhW6EGnHmiukZ3tG634j5IDSlVaVn5jsnxMuDCozDiHiKA4Iv6D5MX/QU "JavaScript (Node.js) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
!¡ȯmdẊeṁdN→
```
[Try it online!](https://tio.run/##AR0A4v9odXNr//8hwqHIr21k4bqKZeG5gWRO4oaS////Mg "Husk – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ị+D€FVƝƊ⁹¡¥
```
[Try it online!](https://tio.run/##ASgA1/9qZWxsef//4buLK0TigqxGVsadxorigbnCocKl/8Onw75H//80MP80 "Jelly – Try It Online")
1-indexed, takes \$m\$ on the right and \$n\$ on the left to give the \$n\$th term of the sequence.
It seems like there should be a non-naive method as well, but the patterns that manifest in the single digits may not be as real as they seem.
```
⁹¡ Repeat m times
+ ¥ starting with n + m:
D€ digits of each
€ (implicitly rangifies on first iteration),
F flatten,
VƝ concatenate each pair of adjacent digits into an integer.
ị Get the n'th element of the result.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 96 bytes (@math junkie)
```
def f(n,c=0):
while n<1:c+=1;yield c
for s in f(n-1):
for b in`s`:
if c:yield int(c+b)
c=b
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY5NDoIwEEbX9BSzbIMkgButchfC0IZJSkvaMYazuGFjPJO3EUS3L-_7ebymmYfg62V53tgWp3fbGwtW-gM2pdIC7gM5A_5aacyb6jKTcT2gABsiJCC_uUW1mV_UrahNrRYZWUC96-RZYt4pkWHT_XbONoYRiE3kENzaNE4hMlByhEZMcc2Ao8RyJ9LKozrUZanUXvA__AE)
TIL: Apparently one can mix spaces and tabs in Python 2.
### Old [Python 2](https://docs.python.org/2/), 101 bytes
```
def f(n,c=0):
while n<1:c=c+1;yield c
for s in f(n-1):
for b in`s`:
if c:yield int(c+b)
c=b
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY5NDoIwEIX3nGKWbcAEcKModyEMnTBJaUk7xnAWN2yMZ_I2UtHl-_L-Hq95kdG7el2fN6HD6W0GQ0DKFdiWusngPrI14K5Vgy3m1WVhYwfADMgHiMAumQ9Vsn5Rv6EudkkCE2CzB9iJwrzXCWPb_8bOFPwELCaI93Zrm2YfBDhaRpPNYUuB5ShqJ4rUURd1WWq9F_xffwA)
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 20 bytes
```
J+.ro{im2CO}3MVE!j.+
```
[Try it online!](https://tio.run/##SyotykktLixN/V9dkPrfS1uvKL86M9fI2b/W2DfMVTFLT/t/bXjOf2MFQwMDAy4jBUtLLmMFSwA "Burlesque – Try It Online")
```
J # Duplicate M
+.ro # Range [1..M+1]
{
im # Implode (concatenate digits)
2CO # Chunks with overlap length 2 ("ABC"2CO -> "AB" "BC")
}
3MV # Move the 3rd item (N) to top of stack
E! # Evaluate that many times
j.+ # Keep the top M numbers
```
# [Burlesque](https://github.com/FMNSSun/Burlesque), 13 bytes (invalid violates [default sequence rules](https://codegolf.stackexchange.com/tags/sequence/info))
```
ro{im2CO}x/E!
```
[Try it online!](https://tio.run/##SyotykktLixN/V9dkPq/KL86M9fI2b@2Qt9V8X9teM5/QwVTLiMFS0suYwVLAA "Burlesque – Try It Online")
```
ro # Range 1..N
{
im # Implode (concatenate digits)
2CO # Chunks with overlap length 2 ("ABC"2CO -> "AB" "BC")
}
x/ # Reorder stack putting `m` on top
E! # Eval `m` times
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
Tɾ$(ṅ2lĖ)Ẏ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJUyb4kKOG5hTJsxJYp4bqOIiwiIiwiNTBcbjIiXQ==)
Takes `number of items to generate` then `how many times to squash`
[Answer]
# Rust + Itertools, 249 bytes
```
use itertools::*;let f=|s:Box<dyn std::iter::Iterator<Item=u32>>|Box::new(s.flat_map(|a|(0..=a.log10()).rev().map(move|t|a/10u32.pow(t)%10)).tuple_windows().map(|k:(u32,u32)|k.0*10+k.1));let g=|n|{let mut k=f(Box::new(1..));for _ in 0..n{k=f(k)};k};
```
Playground link: <https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=11fa065d958a13e4a9d68dc2de7b9b12>
[Answer]
# Java 10, ~~143~~ 139 bytes
```
n->m->{int r[]=new int[n],i,j=0;for(;j++<m;){var s="";for(i=0;i<n;r[i]=new Byte(s.substring(i,i+++2)))s+=j<2?i-~i+""+-~i*2:r[i];}return r;}
```
Takes inputs \$n,m\$ and outputs the first \$n\$ values of the \$m^{th}\$ sequence.
[Try it online.](https://tio.run/##jVCxboMwEN3zFSdPpgdWi5QlxlTtUKlDp4yUwUkgMsUG2SYViuivU0Mide1in9/zvbv3GnmRSXP6mo@tdA4@pDLXDYDz0qsjNIFlg1ctqwdz9Koz7O1eZO/GV@fKxv/7pIwvyjyHGsRsklwn@TVAYItSmOp7pU0Zq7gRj7zuLOUNYqZ5dL1IC04QsqIqsCoz3Bbq1vc6@oo65oaD81aZM1WxQsQ0iiKHosnSZ5X8KCQEw/WQ7pZGPtnKD9aA5dPMN8FtPxza4PZu@tKpE@gQBN2vmkUpoyUTWLYEI9ItX1/rQgHR4omDzsQ2nIjRygHsR@crzbrBsz6o@NZQogVBjYQHEYIGyQ4@PcG//F6slaNjvrsNpjWTfd@O1ET3Qgdfy/BpM82/)
**Explanation:**
```
n->m->{ // Method with two integer parameters & integer-array result
int r[]=new int[n], // Create the result-list of `n` amount of 0s
i, // Index-integer `i`, uninitialized for now
j=0,i;for(;j++<m;){ // Loop `j` in the range [1,m):
var s=""; // String `s`, starting empty
for(i=0;i<n // Inner loop `i` in the range [0,n):
; // After every iteration:
r[i]= // Replace the i'th value in the result-array to:
new Byte( // Convert the following String to an integer,
// (to put it in the integer-array & to remove leading 0s)
s.substring( // A substring of String `s`,
i,i+++2))) // in the character index-range [i,i+2)
// (and increase `i` by 1 afterwards with `i++`)
s+= // Append to String `s`:
j<2? // If `j` is 1, thus the first iteration of loop `j`:
i-~i // Append (2*i+1) to the String
+""+-~i*2 // as well as (2*i+2)
// (so the .substring-indices won't be out-of-bounds)
: // Else:
r[i]; // Append the i'th integer of the result-array instead
}return r;} // After the loops: return the result-array
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
‘RDFṡ2ḌƲ⁴¡³ị
```
[Try it online!](https://tio.run/##AScA2P9qZWxsef//4oCYUkRG4bmhMuG4jMay4oG0wqHCs@G7i////zEy/zI "Jelly – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 bytes
```
LsM.:jkb2<yFShQE
```
[Try it online!](https://tio.run/##K6gsyfj/36fYV88qKzvJyKbSLTgj0PX/f0MDAy5jAA "Pyth – Try It Online")
Takes `n` (number of elements to generate) then `m` on separate lines.
```
LsM.:jkb2<yFShQE
L Create a lambda with variable b:
jkb - Concatenate elements of b
(e.g. [1,2,3,4] -> "1234")
.: 2 - Produce all 2-element sub-strings
(e.g. "1234" -> ["12","23","34"])
sM - Convert to integers
(e.g. ["12","23","34"] -> [12,23,34])
ShQ Range from 1 to n+1
yF E Apply the above lambda m times
< Keep the first n elements
```
[Answer]
# [lin](https://github.com/molarmanful/lin), 41 bytes
```
$`1`d \; `it
\ns `' `flat2`xp \; `'
`_` N
```
[Try it here!](https://replit.com/@molarmanful/try-lin) Generates an infinite list of infinite lists.
Pretty-printed output version (run with `-i` flag if using local interpreter):
```
; ( 40`t ) `' 10`t `__ wrap_
$`1`d \; `it
\ns `' `flat2`xp \; `'
`_` N
```
lin is a stack-based language I began working on a few years back, but have recently been dusting off with new features and inspirations.
## Explanation
* `$` 1`d` push infinite list `[1..]`
* `\; `it` iterate infinitely...
+ `\ns `' `flat` convert each number to digit list and flatten
+ `2`xp \; `'` pairwise map...
- ``_` N` convert pair to number
[Answer]
# Python 2, 102 bytes
```
def z(m,n):a=range(1,n);exec'd="".join(map(str,a));a=[int(i+j)for i,j in zip(d,d[1:])];'*m;return a[m]
```
[Try it online!](https://tio.run/##VczBCgIhFEDRfV8hs5n3SgIn2oz4JeJC0ikF34gZlD9vU9Ci5Vncm1/1ttLUu/MLa5A44WxVsXT1IDZI//SX0alhOMY1ECSb4V4Lt4jSKh2oQjhEXNbCAo8sEGshg@NOi9mgkeM@yeLroxCzOpmeyydp21ucEXc/Tv88fdnf "Python 2 – Try It Online")
It's not the shortest Python 2 script here, but the approach is very different to @loopy walt's so I thought it was worth sharing anyways.
The first version of the code, when given an input *n*, returned a sequence containing at least the first *n* elements, but @math junkie pointed out that this is not allowed in the sequence rules.
] |
[Question]
[
Help! My device malfunctions and whenever I try to repeat a String, I get a messy results. Instead of repeating the same string **N** times, it fills an **NxN** square with each of its characters, and stacks the squares up.
For example, given the String `"Test"` and the number `2`, instead of `"TestTest"`, I get:
```
TT
TT
ee
ee
ss
ss
tt
tt
```
---
After I have seen this for a while, I started to like it. Your task today is to reproduce this strange behaviour. Given a *non-empty* string that consists of printable ASCII only, and a *positive* integer, output the String my malfunctioning device returns.
* All standard rules apply.
* The input and output may be handled through any reasonable mean.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes in each language wins.
---
# Test Cases
```
Input
Output
----------
"Test", 2
TT
TT
ee
ee
ss
ss
tt
tt
----------
"UuU", 3
UUU
UUU
UUU
uuu
uuu
uuu
UUU
UUU
UUU
----------
"A", 5
AAAAA
AAAAA
AAAAA
AAAAA
AAAAA
----------
```
You can [find a larger test case here](https://pastebin.com/HJRQ986T). Good luck and have fun golfing!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Inspired by [Mr. Xcoder's Jelly abuse](https://codegolf.stackexchange.com/a/141703/53748)
```
x⁹×Y
```
A full program taking the string and the number as command line arguments and printing the result (since as a dyadic link it returns a list of strings and newline characters, which may not really be acceptable).
**[Try it online!](https://tio.run/##y0rNyan8/7/iUePOw9Mj////7@7v4/bfFAA "Jelly – Try It Online")**
### How?
The naive (non-abusive) five byter is:
```
x⁹x€Y - Main link: list of characters, s; number, n e.g. "xyz", 2
⁹ - chain's right argument, n 2
x - times (repeat each element) ['x','x','y','y','z','z']
x€ - times for €ach [['x','x'],['x','x'],['y','y'],['y','y'],['z','z'],['z','z']]
Y - join with newlines ['x','x','\n','x','x','\n','y','y','\n','y','y','\n','z','z','\n','z','z']
- as a full program: implicit print
- note: this could be submitted as a dyadic link (AKA unnamed function)
```
The abuse used by Mr. Xcoder (Python's `operator.mul` may act on a `str` and an `int` to repeat the `str` - here single characters - and the atom which uses it, `×`, vectorises w.r.t. its left argument) can be used here too to replace `x€` with `×` - yielding the full program:
```
x⁹×Y - Main link: list of characters, s; number, n e.g. "xyz", 2
⁹ - chain's right argument, n 2
x - times (repeat each element) ['x','x','y','y','z','z']
× - multiply (vectorises) ["xx","xx","yy","yy","zz","zz"]
- (note, these "..." are actually strings, something not usually seen in Jelly)
Y - join with newlines ["xx",'\n',"xx",'\n',"yy",'\n',"yy",'\n',"zz",'\n',"zz"]
- implicit print
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
This is exactly what we are asked to do... Abuse undefined behaviour!\*
```
×+⁷×⁴
```
[Try it online!](https://tio.run/##y0rNyan8///wdO1HjdsPT3/UuOX///@OTs4urv@NAQ "Jelly – Try It Online")
\* By *undefined behaviour* I am talking about using `×` for repeating strings. Sometimes it's shorter than usual behaviour, so why not?
[Answer]
# [Haskell](https://www.haskell.org/), 26 bytes
The function `(!)` returns a list of lines.
```
n!s=map(<$[1..n])s<*[1..n]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0@x2DY3sUDDRiXaUE8vL1az2EYLwvqfm5iZp2CrUFBaElxS5JOnoFGal5OZl1qsoKGhqKlgpKAUklpcoqSpyaUABHZ2uBQaKyiFloYSVmeqoOQIVPUfAA "Haskell – Try It Online")
[Answer]
# Bash + GNU Sed, 58
Using a very similar technique to [this answer](https://codegolf.stackexchange.com/a/19457/11259) to illustrate how close to being a dup to [this](https://codegolf.stackexchange.com/questions/19450/enlarge-ascii-art) that this question is:
```
printf -vr %$1s
sed "s/./${r// /&}\n/g;s/\S*./${r// /&}/g"
```
[Try it online](https://tio.run/##S0oszvj/v6AoM68kTUG3rEhBVcWwmKs4NUVBqVhfT1@lukhfX0FfrTYmTz/dulg/JlgLSVA/Xen//5DU4pL/xgA).
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~5~~ 4 bytes
-1 byte thanks to @Zgarb
```
SṀRṘ
```
[Try it online!](https://tio.run/##yygtzv7/P/jhzoaghztn/P//3@h/SGpxCQA "Husk – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 31 bytes
```
param($a,$b)$a|%{,("$_"*$b)*$b}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRRyVJUyWxRrVaR0NJJV5JC8gF4tr///9rRCdnJBZFx8aqh5aGqmv@NwYA "PowerShell – Try It Online")
Explanation:
```
param($a,$b) # Takes input $a (char-array) and $b (integer)
$a|%{ } # Loop through every character in $a
"$_"*$b # Construct a string of $b length of that character
,( )*$b # Repeat that $b times
# Implicit Write-Output inserts a newline between elements
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 5 bytes
-2 bytes thanks to [scottinet](https://codegolf.stackexchange.com/users/73296/scottinet)
```
εײF=
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3NbD0w9tcrP9/z@0NJTLGAA "05AB1E – Try It Online")
```
ε # For each character:
× # Repeat this character N times
²F # For 0 .. N:
= # Print without popping
```
[Answer]
# [Python 3](https://docs.python.org/3/), 42 bytes
```
lambda x,y:"".join(y*(r*y+"\n")for r in x)
```
[Try it online!](https://tio.run/##RY1BCsIwEEXX9hTDrJIaurC4CXThHezKikSbYKRNShKhQTx7TARxMTDDf2/@EsPdmjapbkiTmK@jgJVFjtg8rDYk1sTVcYuDQaqsAwfawEpTkD5cbsJLDx2cCB7zjWxHGcH@2SNry3ZAtqfnqnj5ZzH/Gq82i9MmEHzxN@Th2GRwFoFkljJpxi63lt4fqb4JTR8)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
t&Y"!
```
[**Try it online!**](https://tio.run/##y00syfn/v0QtUknx/38jLvWQ1OISdQA "MATL – Try It Online")
### Explanation
```
t % Implicitly input a number, n. Duplicate
&Y" % Implicitly input a string. Three-input repelem function. Repeats
% each entry in the first input (s) the specified numbers of times
% vertically (n) and horizontally (n). Gives a char matrix
! % Transpose. Implicit display
```
[Answer]
## C++, ~~125~~ 123 bytes
-2 bytes thanks to aschepler
```
#include<string>
using s=std::string;s u(s a,int b){s r;for(auto&c:a)for(int i=0;i<b*b;){if(!(i++%b))r+=10;r+=c;}return r;}
```
Make sure that the overload of the `+=` operator called takes a `char` data type in this instruction `if(!(i++%b))r+=10`
[Answer]
# Brainfuck, 103 Bytes
```
,[>,]-[>+<-----]>---[-<<->>]<<[->+<]>[[->+>+<<]>>[-<<+>>]<[<<<[<]>.[>]>>-]++++++++++.[-]<<<[<]>[-]>[>]>
```
[Try it online](https://copy.sh/brainfuck/?c=LFs-LF08IFRha2UgSW5wdXQKPi1bPis8LS0tLS1dPi0tLSBBU0NJSSAwLCB0byB1c2UgaW4gbmV4dCBzdGVwClstPDwtPj5dPDwgQ29udmVydCBBU0NJSSBudW1iZXIgdG8gcmF3IG51bWJlciBieSBzdWJ0cmFjdGluZyBBU0NJSSAwClstPis8XT4gTW92ZSB0aGUgbnVtYmVyIG92ZXIgb25lIHRvIHNlcGFyYXRlIGl0IGZyb20gdGhlIHBocmFzZQpbCiAgWy0-Kz4rPDxdPj5bLTw8Kz4-XTwgQ29weSB0aGUgbnVtYmVyCiAgWwogICAgPDw8WzxdPiBCYWNrIHRvIExldHRlcgogICAgLiBQcmludCBMZXR0ZXIKICAgIFs-XT4-LSBCYWNrIHRvIENvdW50ZXIKICBdCiAgKysrKysrKysrKy5bLV08IFByaW50IHRoZSBuZXdsaW5lCiAgPDxbPF0-Wy1dPiBDbGVhciBMZXR0ZXIKICBbPl0-IEJhY2sgdG8gQ291bnRlcgpd) (Make sure to turn on dynamic memory or it won't run)
Note: The input is slightly different. This code takes in a string where the last character is a digit for number of repeats. So input might look like `Test5`.
This code requires an unbounded tape, and relies on byte wrapping behavior.
Ungolfed:
```
,[>,]< Take Input
>-[>+<-----]>--- ASCII 0, to use in next step
[-<<->>]<< Convert ASCII number to raw number by subtracting ASCII 0
[->+<]> Move the number over one to separate it from the phrase
[
[->+>+<<]>>[-<<+>>]< Copy the number
[
<<<[<]> Back to Letter
. Print Letter
[>]>>- Back to Counter
]
++++++++++.[-]< Print the newline
<<[<]>[-]> Clear Letter
[>]> Back to Counter
]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 7 bytes
Outputs an array of strings.
```
VÆmpVÃy
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=VsZtcFbDeQ==&input=IlRlc3QiCjIKLVI=) (`-R` flag for visualisation purposes only)
---
## Explanation
Implicit input of string `U` and integer `V`.
```
VÆ Ã
```
Generate an array of integers from `0` to `V-1` and pass each through a function.
```
mpV
```
Map (`m`) over `U` and repeat (`r`) each character `V` times.
```
y
```
Transpose and implicitly output resulting array.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~9~~ 8 bytes
-1 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
```
FS«GTηι↓
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLQkuKQoMy9dQ1NToZpLAQgC8nMq0/PzNKxCdBQydBQyNa3Bwr75ZakaVi755XlAgdr//0NSi0v0FMz@65b91y3O@a@bCAA "Charcoal – Try It Online")
## Explanation
```
FS For each character (i) in the next input as a string
«
G ι Polygon using i as fill
T Right, down, then left
η The second input (h) (automatically casted to a number)
↓ Move down
```
[Answer]
# [R](https://www.r-project.org/), 59 bytes
```
function(S,n)write(rep(strsplit(S,"")[[1]],e=n*n),"",n,,"")
```
Writes to stdout.
Splits the string into characters, repeats each `n^2` times, and then prints with width `n` and with no separator.
[Try it online!](https://tio.run/##FcgxCoAwDADAr0imROKgs75Ct9JJUihILGnE59c63llLwzq19Ojp@VbcWem17IImBatbLVf23gAUwhwjy6ajUjcr/9sSwiHVgRdqHw "R – Try It Online")
[Answer]
# J, ~~15~~ 14 bytes
```
[:,/]$"1 0~[,[
```
Sub-optimal for sure. Returns a 2D array of chars. Takes `n` as the left argument and the string as the right.
On mobile, so the usual amenities are missing.
# Explanation
(For old answer)
```
[:,/(2#[)$"1 0]
```
`$"1 0` reshape each character to
`(2#[)` an `n` \* `n` matrix.
`,/` join matrices together to yield the output.
[Answer]
# [Perl 5](https://www.perl.org/), 26 + 1 (-p) = 27 bytes
```
$"=<>;s|.|($&x$".$/)x$"|ge
```
[Try it online!](https://tio.run/##K0gtyjH9/19FydbGzrq4Rq9GQ0WtQkVJT0VfE0jVpKf@/@@en5@ikJhWklqUl5@fp6MQnl@Uk6LIZf4vv6AkMz@v@L@ur6megaHBf90CAA "Perl 5 – Try It Online")
[Answer]
# Pyth, 9 bytes
```
VEp*+*NQb
```
[Try it here!](https://pyth.herokuapp.com/?code=VEp%2a%2B%2aNQb&input=%22Test%22%0A2&test_suite=1&test_suite_input=2%0A%22Test%22%0A3%0A%22UuU%22%0A5%0A%22A%22%0A25%0A%22ABCDEFGHIJKLMNOPQRSTUVWXYZ%22&debug=0&input_size=2)
# Pyth, ~~11~~ 10 bytes
```
sm*Q+*QdbE
```
[Try it here!](https://pyth.herokuapp.com/?code=sm%2aQ%2B%2aQdbE&input=3%0A%22ABCDE%22&debug=0)
**Or, 10 bytes:**
```
jsm*Q]*QdE
```
**Or, 11 bytes:**
```
js*RQm]*dQE
jsm*vzm*dvz
sm*vz+*dvzb
```
[Answer]
# [SOGLOnline commit 2940dbe](https://github.com/dzaima/SOGLOnline/tree/2940dbe13bc955f6456c1d3a737b40e255a1d103), 4 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
∙ι*I
```
This was made for a specific commit, namely the one before I changed `∙` from, when used on an array of strings, repeating each letter x times to repeat each item x times. [Here](https://dzaima.github.io/SOGLOnline/?code=JXUyMjE5JXUwM0I5Kkk_,inputs=VGVzdCUwQTM_) is the online interpreter without that version, which, as can be seen, doesn't work.
To try the commit, download [this](https://github.com/dzaima/SOGLOnline/tree/2940dbe13bc955f6456c1d3a737b40e255a1d103), open the `index.html` file, in the program paste `∙ι*I` and in the input write something like
```
Test
2
```
Explanation:
```
∙ι*I
∙ get an array with 2nd input amount of items of the 1st input
ι pop one implicit input to cycle back to the number
* multiply horizontally each separate character
I rotate clockwise
```
[Answer]
# Java 8, ~~152~~ ~~128~~ ~~118~~ 100 bytes
```
s->n->{for(char c:s)for(int j=0;j++<n;System.out.println("".valueOf(new char[n]).replace('\0',c)));}
```
[Try it online!](https://tio.run/##bZCxbsMgFEV3fwXy0EBtozQriaUqUqUOVYd0Sz1Qgh0ofiDAqaIo3@7i1EOl9m1cBOe8q/mJV9ZJ0IfPUfXO@oh0yugQlaHtACIqC/SeZZkbPowSSBgeAnrhCtAlQ2lC5DHlWwth6KVfP0OUnfQ1ajdQ1ZfWeqwgIrVZMrUGtjuHKHtqh0idTxcGMNBodzEdOlwU6q5S5YpQI6GLR0yqB0LYNfF/sZ5mr7U4cr9vyr/wGnVog8ZQ1ZPDzC81m2ySRpi/Z6ooyJTpZKeTnS6K8h/DPKcnbgb52mKQX@iGhYZQL53hQuLF@3JRhr1qyCQ7zrZzY7P0yaoD6lNv@GfXfYO47wKZa5ymo9w5c8b5mwwxT61sE@jRe37GhFAuhHQRrwi7Pbhm1/Eb "Java (OpenJDK 8) – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 8 bytes
Takes repetition as left argument and text as right argument.
```
{⍺⌿⍺/⍪⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3zGptDj1UduE6ke9ux717AeS@o96Vz3q3Vr7/7@RAlhWQT0ktbhEncsYxg0tDVXnMoXxHNUB "APL (Dyalog Unicode) – Try It Online")
`{`…`}` an unnamed lambda where `⍺` represents the left argument and `⍵` the right argument
`⍪⍵` make the text into a one-column table
`⍺/` replicate `⍺` times horizontally
`⍺⌿` replicate `⍺` times vertically
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 bytes
```
mpV² òV
```
Returns an array of strings.
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=bXBWsiDyVg==&input=IlRlc3QiCjIKLVI=) with the `-R` flag to join the array with newlines.
## Explanation
```
mpV² òV Implicit input of U=string, V=number
m Map each char in the input string to...
pV² Itself repeated V² times
òV Cut the resulting string into partitions of length V
```
[Answer]
# D, 86 bytes
```
S u(S,I)(S a,I b){S r;foreach(c;a)for(I i;i<b*b;){if(!(i++%b))r~='\n';r~=c;}return r;}
```
[Try it online!](https://tio.run/##DYuxDoIwEEB3vuIkMdwJcXA9/QDmOrq0UOIl0pqj6EDw12uHl/eWN@ZsYEXT9YQGbNeDo82A8hTV2@GJA1sqjT0Iy9WdHNMmEx5Q2vboiPR3ax6h4eKBd/Vp1VD2vfpEGWG2EpBgq2R@R02wpPFckMhfleRfAVes735JdXch4mrP@Q8)
Takes the string as the left argument, and the integer as the right argument.
This is a port of [HatsuPointerKun's C++ answer](https://codegolf.stackexchange.com/a/141724/55550) into D.
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `N`, 3 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
Ḅd×
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVFMSVCOCU4NGQlQzMlOTcmZm9vdGVyPSZpbnB1dD0yJTBBJTIyVGVzdCUyMiZmbGFncz1O)
Takes the number then the string
#### Explanation
```
Ḅd× # Implicit input -> 2, "Test"
Ḅ # Multiply each of the characters by the number -> "TTeesstt"
d # Split this string into a list of characters -> ["T", "T", "e", "e", "s", "s", "t", "t" ]
× # Repeat each character input number of times -> ["TT", "TT", "ee", "ee", "ss", "ss", "tt", "tt"]
# Implicit output, joined on newlines
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~83~~ 79 bytes
```
i,j;f(p,n)char*p,n;{for(;*p;p++)for(i=n;i--;puts(""))for(j=n;j--;putchar(*p));}
```
[Try it online!](https://tio.run/##JcsxDsIwDIXh3aeoMtlpspTR4hZcIIpISUSD1ZSp6tUxKbzp1ye96OcYVbMrnFBcpfgIq@3Be3qtyFZYxpHOztfK2XuW99bQGPph6Vj@eD7RChEfuoRckWCHoS@hud3bZtwwEcMBoJ@YnmFu6pfL9AU "C (gcc) – Try It Online")
[Answer]
# CJam, 11 Bytes
```
{__*@e*/N*}
```
Function that takes string followed by int.
[Try it Online](http://cjam.aditsu.net/#code=lli%7B__*%40e*%2FN*%7D~&input=abcd%0A5)
[Answer]
# Kotlin 1.1 - 99 bytes
```
fun s(s:String,c:Int)=s.flatMap{p->List(c,{p})}.joinToString("\n"){p->List(c,{p}).joinToString("")}
```
Returns the whole output as a string.
**Can't use TryItOnline as 1.1 is not supported**
## Test
```
fun s(s:String,c:Int)=s.flatMap{p->List(c,{p})}.joinToString("\n"){p->List(c,{p}).joinToString("")}
fun main(args: Array<String>) {
println(s("Hello World", 5))
}
```
It would be 84 if a list of strings was acceptable as output:
```
fun s(s:String,c:Int)=s.flatMap{p->List(c,{p})}.map{p->List(c,{p}).joinToString("")}
```
[Answer]
# PHP, 97 bytes
```
for($i=0;$i<strlen($s=$argv[1]);$i++)for($j=0;$j<$r=$argv[2];$j++)echo str_repeat($s[$i],$r)."
";
```
[Answer]
# Mathematica, 49 bytes
```
(z=#2;Grid[Column/@Table[#,z,z]&/@Characters@#])&
```
**input**
>
> ["Test",4]
>
>
>
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
Small minded, but I haven't gotten there just yet.
```
VQp*+*Nszbsz
```
Explanation:
```
VQ For every letter in the first input...
p Print without newline...
*+*Nszsz (The index * int(second input) + newline) * int(the second input)
```
[Test Suite](http://pyth.herokuapp.com/?code=VQp%2a%2B%2aNszbsz&input=%22Test%22%0A2&test_suite=1&test_suite_input=%22Test%22%0A2%0A%22UuU%22%0A3%0A%22A%22%0A5%0A%22ABCDEFGHIJKLMNOPQRSTUVWXYZ%22%0A25&debug=0&input_size=2)
[Answer]
# [Clojure](https://clojure.org/), 82 75 bytes
```
#(dotimes[x(count %1)](dotimes[y %2](prn(apply str(repeat %2(get %1 x))))))
```
[Try it online!](https://tio.run/##dYxBCsIwEEX3OcUQKcwsG/EAHqIr6SKkU4mkSUgn0J4@Vhcign/5/uO5kB61cMOJZ1hsmGt04lNsJ5yS@IXX24Yu1SjQ9TR@4A6dGTGXiDbnsMMqBQtntodn8M4vHTZ6rxEo/GqDFl5FgyF1FHyUEOlHGOqg4fz/v2q4kGpP "Clojure – Try It Online")
Uncompressed:
```
#(dotimes [x (count %1)]
(dotimes [y %2]
(prn
(apply str
(repeat %2 (get %1 x))))))
```
Edit: Shaved a few chars off the end by replacing a for loop with the stdlib repeat function.
] |
[Question]
[
>
> This is the robbers' thread to a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. Click the link to find the [cops' thread](https://codegolf.stackexchange.com/questions/242075/output-two-numbers-cops-thread).
>
>
>
In the [cops' thread](https://codegolf.stackexchange.com/questions/242075/output-two-numbers-cops-thread) of this challenge, answerers will be writing programs which output two numbers, \$x\$ and \$y\$. As robbers, your goal will be to crack their submissions. To do this, you find a program in the same language as a cop's program which outputs a number in between \$x\$ and \$y\$, and is the same length as or shorter than the cop's program. Your program must use the same output method as the cop's submission.
You submit that program here and notify the cop in a comment on their answer.
For every answer you crack here you get 5 points. As an extra incentive you will gain an additional point for every byte shorter your program is than the cop's. If your program is the same length, that is fine; you still get 5 points.
The winner is the person with the highest total score across all answers.
[Answer]
# [Malbolge](https://github.com/TryItOnline/malbolge), 6 bytes, cracks [Kamila Szewczyk's answer](https://codegolf.stackexchange.com/a/242077/95126)
```
(&<`q#
```
[Try it online!](https://tio.run/##y03MScrPSU/9/19DzSahUPn/fwA "Malbolge – Try It Online") (or try it [here](https://malbolge.doleczek.pl/#) to avoid timing-out)
Outputs 2.
**Explanation**.
The goal is to output the ASCII character "`2`" in a 7-byte or less program.
Malbolge code & data occupies the same memory space. When a Malbolge program is loaded, the last two single-byte instructions act as 'seeds' that determine how the remaining memory is initialized (in a deterministic but rather uncontrollable fashion). So if we try to construct 5 command/byte programs that use the contents of the memory to generate the ASCII encoding for "`2`", we can try different combinations of the remaining 2 commands/bytes to try to find one that gives the correctly-initialized memory to achieve this. There are 8 valid Malbolge commands (and any other byte in the program will generate an error upon loading), so this gives us 8x8 combinations to try per 5 byte program. This is obviously less than the 1/256 chance of 'hitting' the ASCII character "`2`" in any particular byte, so we'll probably have to try more than one program.
Each Malbolge command self-modifies immediately after execution, making re-use rather difficult. So here we try only single-pass programs, without any attempt to loop. We will need to use the commands `j` (set the data pointer), `<` (write an ASCII value to the output), and (probably) `v` (end the program). This gives us room for 2 more data-altering commands in within the 5-byte limit, so we can try combinations of `*` (rotate) and `p` (tritwise OP operation), as well `o` (no operation; but in Malbolge this changes the data pointer as a side effect so it can also affect the output).
Unfortunately, after trying all 64 combinations of the final two bytes across the Malbolge programs `jpo<v..`, `jop<v..`, `ojp<v..`, `jpp<v..`, `jppp<v.`, `jpppp<v`, `j*o<v..`, `j*p<v..`, `j*pp<v.` and `j*ppp<v` (where `.` represents any of the 8 Malbolge commands), we can only generate the output numbers 0, 1, 3, 5, 6, 7, 8, 9. At this point it seems likely that [Kamila Szewczyk](https://codegolf.stackexchange.com/users/61379/kamila-szewczyk) may have used a similar approach, and therefore hoped that generating the character "`2`" in 7 bytes or less is impossible...
But: what about shorter programs that omit the `v` (end the program) command? These allow the memory to be initialized differently, and so we can maybe find a combination that enables output of "`2`"... but the Malbolge interpreter will now continue reading bytes from the rest of the initialized memory and executing them as commands, with rather uncontrollable consequences! Still, if it hits a `v` (end of program) before it hits a `<` (write output), that could be Ok: so let's try it!
After some searching, we find that `j*p<..` is indeed able to initialize the memory to output "`2`", using two different suffix combinations: when test-run, `<j` unfortunately keeps running and outputs an additional "`2L`" before stopping, but `/j` stops after the "`2`". It's a crack!
To load into Malbolge, the final program - `j*p</j` - must finally be encoded using a series of operations (see the [spec](https://web.archive.org/web/20190417235149/http://www.lscheffer.com/malbolge_spec.html)) to yield the final loadable code of `(&<`q#`.
[Answer]
# [R](https://codegolf.stackexchange.com/a/242083/), 4 bytes
```
2e98
```
[Try it online!](https://tio.run/##K/r/3yjV0uL/fwA "R – Try It Online")
Not much fun but the range makes it cracked
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~26 18~~ 14 bytes (88 bytes saved)
Crack of [@lyxal's vyxal cop program](https://codegolf.stackexchange.com/a/242085/103772)
```
k×:\(+33*\↵+Ė›
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrw5c6XFwoKzMzKlxc4oa1K8SW4oC6IiwiIiwiIl0=)
output lowest bound +1
(first time doing vyxal, tell me if I did something incorrectly)
## Explanation
```
k× Push 2147483648 onto the stack
=> [2147483648]
: Duplicate the stack
=> [2147483648, 2147483648]
\(+ Concatenate the last element of the stack with `(`
=> [2147483648, '2147483648(']
33* Multiply by 33 the string on top of the stack
=> [2147483648, '2147483648(21 ... 8(2147483648(']
\↵+ Add `↵` to the string on top of the stack
=> [2147483648, '2147483648(21 ... 8(2147483648(↵']
Ė Evaluate as vyxal code the last element of the stack (see the cop thread)
=> [ <lowest bound> ]
› Add 1 to the result
=> [ <lowest bound +1> ]
implicit output
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 [bytes](https://github.com/JCumin/Brachylog/wiki/Code-page) (0 bytes saved), 20922789888
```
16ḟ↔↔
```
Outputs \$20\text{,}922\text{,}789\text{,}888\$.
Cracks [@Fatalize's Brachylog Cop answer](https://codegolf.stackexchange.com/a/242089/52210), which is also 5 bytes and the range \$14\text{,}159\text{,}265\text{,}359\$ to \$61\text{,}803\text{,}398\text{,}875\$.
[Try it online.](https://tio.run/##SypKTM6ozMlPN/r/39Ds4Y75j9qmANH///@jAA)
**Explanation:**
```
16ḟ # Push the factorial of 16: 20922789888000
↔ # Reverse (but remain an integer): 88898722902
↔ # Reverse back: 20922789888
```
[Answer]
# Excel, 6 bytes, cracks [Luke Dunn's answer](https://codegolf.stackexchange.com/a/242132/95126)
```
=1E250
```
[Try it online!](https://tio.run/##yygtzv7/39bQ1cjU4P9/AA "Husk – Try It Online")
[](https://i.stack.imgur.com/QpeZr.png)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 22 bytes
```
x=>'9'.repeat(1e7-1)-1
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1k7dUl2vKLUgNbFEwzDVXNdQU9fwf3J@XnF@TqpeTn66RpqGpub//7plOQA "JavaScript (Node.js) – Try It Online")
This cracks [l4m2's cop](https://codegolf.stackexchange.com/a/242082/106710).
Works only in theory. The string in the answer, with `9999999` golfed to `1e7-1`, minus 1, which coerces it to a number.
---
# [JavaScript (Node.js)](https://nodejs.org), 22 bytes
```
x=>'909'.repeat(1e7/3)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1k7d0sBSXa8otSA1sUTDMNVc31jzf3J@XnF@TqpeTn66RpqGpub//7plOQA "JavaScript (Node.js) – Try It Online")
Works in reality.
This one exploits the fact that the repetition count is rounded down.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 15 bytes (10 bytes saved), cracks [mathcat's answer](https://codegolf.stackexchange.com/a/242092)
```
-[>+<-----]>++.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fN9pO20YXBGLttLX1/v8HAA "brainfuck – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 6 bytes, cracks [robbie crockett's first answer](https://codegolf.stackexchange.com/revisions/242293/2)
```
28^213
```
[Try it online!](https://tio.run/##y08uSSxL/V@UmpiTm1jx38gizsjQ@H9OfrqGoZ55qrGBhaY@iGNkofkfAA "Octave – Try It Online")
Found by a brute force search of `n` where `log(1.7e308,n)` is very close but less than an integer so that `n^ceiling(log(1.7e308,n))` is not too large.
[Answer]
# [Seed](https://codegolf.stackexchange.com/a/242086/56656), 4695 bytes (96 byte save), \$9^{999999999999999}\$
```
48 136118222288577729572552152791709368605773628347021471008690822115373392141244799774415998107055377981742447271161172093778621602759645881735548840779482802560209189517746243033627985739511100518293138471484155429274889918272710559291982273929396912514475806069037521031407489333870378703173662910402083164029699758795021006600087782123480276870349030965867563726975877728510764214971834340717031826050329624446895168002822671009104546726772407954859794475567312583905626817398451742396403319735329821368897163429801670218889821848435198982270769585133239840182076928600225425386926305906233725574337009104530356853863448383654832344408718772724757372631143287400290703116853900133240035664821661976772888810467002790969870927064001031662898740474966711631710727286951427698675681491111582579107155062882709864229052873760966169264245600186093538370974908907020474070930611562816292100183878427364763405389786799631792649382212389347264227332059441821014321577413408905755610100524739302573178913805937883513832378054230283344383753275902621779919104894612137194747465109053363132937703205299899090062685892622098070989799300096851455096301228710972701865038051936551041342440525433281771038877777161882636844059426594521805350407152290165733138028576146967247522643744694141195004623423857857693427850032738203686267421228588828435013088446245077772203162760491431357812801871298876631302950079959010177847566668826266369346040779302669462790393198104623019338124802383380441313038602352462845958086644089497490467594136351122837597449672487010313897868432189301305885675861325709179122431375903938149903427353406026693988298068066087414204535567217531278847246663063521026232422013930241593518848232749733716027932971967899916260405600669083231342566885341691912368360136490149146410247155251733391927312938665018633466748949229241307444214633067906713336048685943513134140263372359696945716406670478168007378272916725550905826132341140883161990841937113616809856754859509173906225877693272986499970529936397933788880924831441272134709649991804869975215537765013304261103280798035738449283801074367455416975896866833656686794976325679828000354046625307811860168996790355272279436375392093313679100121487235860221918848736347751782535229777178218227648706506003129525970134666691479694925217524902959803338422438060038658440582225592904612537669959087757488373578611752282868269275950214371229748731729215641332246654869362216109284862185496124584262579953474203167872603070470067950478753207808608248943878860011908115468802190546000519840247324568161439611525769820989196058123147718137077000120913662868599382356603269721601449988482683980532792892177658333875496383645485133701798213530386049902190319666619680418627484562095523349838908554879800729189834397636333150687591784783593636695475815080002634570530677847790228554244311329470586241698758265462755938042304017099033993858637076639260904636077951244351657896256391998258900387543477862789459882688297086948688007197707992577339183010173354065933555655553421866069534486864447491231024219783356908661520568506172333653043056654975852125377780460189002009695349728259441892176823884813139372756407875800289098734167129099381792737264454097003678873187452677901588877289663613161551851497712147029113595405001612731177702538079055158748598170770058186080901509151495332123511968083584199679029073876741472874261160159173180904406481520378171876773781817052362670957754076341052151226864982044423001068087857032658832611786035188675526138932008287577260700322890640413383485742814765880396419208969263227721270455088178847430617675460588467868983618120954389404362140231158416321704501412371098629111850576048849097883084678663620297477847964712187292115607313892012356396662805274189107494467684644891521782414262128173708455480707454354968100553678330533006106890027275388315886464487511584246560889155661821779830187538375406868333151665726444207031130208083500148213129337075506341798868095841311106337887887291979827246042278337117981115263174824668396544795084846659779500193321324649508077325582071348037416574693493790019348532848623137704882189995492207319495341511822520469501170794388924439459462165936478786200751196030621197856797511117488998623310034898658778486649937046992404397946797175451641601275425983240032855623615931663152448038884938302103599522781131691794955910668601656339114328483085213740867710698818388423094906297631419655436847220572682142406966844544894284269328182913703189411753835932978396033829515305455631318696053728968876051410783596705077112312728424202529475578776676152981258884551184505959739004252170359641105692336889964755135425463797747654176970663980003607348930037794652574271713970
```
Nothing clever on my part I stole this from the answer's edit history.
[Answer]
# [Python 3](https://python.org), 19 16 bytes (saves 22 25 bytes)
```
print(3*10**456570)
```
Cracks [DialFrost's cop answer](https://codegolf.stackexchange.com/a/242221/97819)... I just did a bunch of trial and error to get this lol.
[Try it online](https://tio.run/##K6gsycjPM/7/v6AoM69Ew1JLy8TcwsTMSPP/fwA).
[Verify it's between the two numbers](https://tio.run/##ZY29DoMwDIR3P4XFRBiq/qC2VJR3cSsokRISJV54@tQh6lBxk3Xfnc@vPLvlkpK23gVGSzzDS3/wuZ2Hid7sgiZTn45ZCqIlY/a4y1JASxTWNU17u7fXM4CesDQGFPYAFPmgF64rdq6wSsFoJJjLA8r6LibeForjH6JV3HLnbp9zP6Os9vmpSukL)
[Answer]
# [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), 6 bytes, cracks [Fmbalbuena's answer](https://codegolf.stackexchange.com/a/242231/100664)
```
~(#)
```
[Try it online!](https://tio.run/##S03OSylITkzMKcop@P@/rr5eQ1nz/38A "!@#$%^&*()_+ – Try It Online")
] |
[Question]
[
There are quite a few means in mathematics, such as the arithmetic mean, the geometric mean, and many others...
## Definitions and Task
Note that these are the definitions for *two positive integers*\*:
* The **root mean square** is the square root of the sum of their squares halved ().
* The **arithmetic mean** is their sum, halved ().
* The **geometric mean** is the square root of their product ().
* The **harmonic mean** is **2** divided by the sum of their inverses ( = ).
Given two integers **a** and **b** such that **a, b ∈ [1, +∞)**, sum the means mentioned above of **a** and **b**. Your answers must be accurate to at least 3 decimal places, but you do not have to worry about rounding or floating-point precision errors.
# Test Cases
```
a, b -> Output
7, 6 -> 25.961481565148972
10, 10 -> 40
23, 1 -> 34.99131878607909
2, 4 -> 11.657371451581236
345, 192 -> 1051.7606599443843
```
You can see the correct results for more test cases using **[this program](https://tio.run/##Zcwxr4IwFAXgvb/ixqlFIlJ00MTBSWdXdbjVaklsS0oZ/PV4gfdCxOmk53y31Tsa74q2NbCDF1p1R8BUbSVkwPMMYQ55pgTD75njXAkikj2nQ0JDksBizcJkoi2R9KGi6I//YGsJli7y0lVN5EIwNy2Y1ehqas@G29SJ9DkEDhH6uDJWhe5sdvI@QneynaV91ufiKv7XfSijsTqWt4mRozloTyL8kHwkRwzWux@xHMXFnXTdvCLwurHgHxCNHpToPJV8eIm2WK1ZvpEf)**. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid submissions that follows the standard rules wins.
\* There are many other means, but for the purposes of this challenge we'll use the ones mentioned in the "Definitions" section.
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
```
a%b=sum[((a**p+b**p)/2)**(1/p)|p<-[2,1,-1,1e-9]]
```
[Try it online!](https://tio.run/##DcRLCoAgEADQq7hoQG2kZvoR1EnEhUFQVCJ9dt3deou3@Gub9z0lD9N4PYeV0msd8@lPFay0llRE9cbBWEZCQ0iz6Z1Lh1@DGEU813CLTNgOWqQSqESugJChxqpugHp26QM "Haskell – Try It Online")
This uses the fact that the root-square, arithmetic, harmonic, and geometric means are all special cases of the [generalized mean](https://en.wikipedia.org/wiki/Generalized_mean) `((a**p+b**p)/2)**(1/p)` for `p=2,1,-1,0`. The geometric mean uses the limit `p->0+`, approximated as `p=1e-9` which suffices for precision.
[Answer]
# [Mathematica](http://reference.wolfram.com/language/), 37 bytes
*-2 bytes thanks to Martin Ender. -6 bytes thanks to Jenny\_mathy and function reusability thanks to JungHwan Min.*
```
(t=1##)^.5+(2(s=+##/2)^2-t)^.5+s+t/s&
```
[Try it online!](https://tio.run/##HYxNCsMgEEb3OcWAUBRtjZOf0oXgEXqCgJSEZpEuOrMTz26Mq@/xeHxH5O96RN4/sWzgoUj2Tgi1PCYtUZLXQlhUC965OdJs6VZ4Jaaap/Q0MGcDyfUGXH8RDpUaGBivHcapmhfm3HXv//5jsAHkBiEEaEeqnA "Wolfram Language (Mathematica) – Try It Online")
# [Mathematica](http://reference.wolfram.com/language/), 55 bytes
```
RootMeanSquare@#+Mean@#+GeometricMean@#+HarmonicMean@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z8oP7/ENzUxL7iwNLEo1UFZG8QBUu6p@bmpJUWZyVC@R2JRbn4ejKv2vyS1uKRYwVahutpcT0fBTK9WR6Ha0ADIBBIgtpExiA1hAlkmYJaxiSlI1NJIr7aWiyugKDOvREHfQSENRIAN/A8A "Wolfram Language (Mathematica) – Try It Online")
¯\\_(ツ)\_/¯
[Answer]
# [Python 3](https://docs.python.org/3/), 57 bytes
```
lambda a,b:(a+b+(a*a+b*b<<1)**.5)/2+(a*b)**.5+2*a*b/(a+b)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ8lKI1E7SVsjUQtIaSXZ2BhqamnpmWrqG4HEksAcbSMtIFMfpFDzf0FRZl6JRpoGiMzMKygt0dDU1EHmaGr@NzYx5TK0NAIA "Python 3 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 52 bytes
```
function(a,b,m=(a+b)/2,p=a*b)m+p^.5+(m^2*2-p)^.5+p/m
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUSdJJ9dWI1E7SVPfSKfANlErSTNXuyBOz1RbIzfOSMtIt0ATxCnQz/2fpmGuY6b5HwA)
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
```
a?b|s<-a+b,p<-a*b=s/2+sqrt(s^2/2-p)+sqrt p+2*p/s
```
[Try it online!](https://tio.run/##HcdBCoNADADAr@RY3ci60VoKlbzAF4iVLAiVqqTGY/@@LZ6GeYm9p2VJSTh@7VGIi6h/8tiaJ2ef/bjYkzwVmp0DdZSrt7TKvEELq2g3gu7zdkB/4wZDyaFEqjggcY1VfeVwpyH9AA "Haskell – Try It Online")
### Explanation:
`s/2 = (a+b)/2`: The arithmetic mean.
`sqrt(s^2/2-p) = sqrt((a^2+2*a*b+b^2)/2-a*b) = sqrt((a^2+b^2)/2)`: The root mean square.
`sqrt p = sqrt(a*b)`. The geometric mean.
`2*p/s = 2*a*b/(a+b)`. The harmonic mean.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~44~~ ~~42~~ 41 bytes
```
@(n)(q=mean(n))+rms(n)+(z=prod(n))^.5+z/q
```
[Try it online!](https://tio.run/##y08uSSxL/V@UW2zroJGnWVxYVKJRXJqrkacXZ6Spn5Oal16SARTXtOZKs9XT0/sPUqRRaJubmpgHEtYGagTS2hpVtgVF@SkgoTg9U@0q/cL/aRrR5jpmsZr/AQ "Octave – Try It Online\"gnVW2BUX5KWDhKv3C/2ka0eY6ZrGa/wE \"Octave – Try It Online")
Note that TIO does not have the signal package installed, so I defined `rms()` in the header. On [Octave Online](http://octave-online.net/), you can try it if you `pkg load nan`. I'm not sure if there are any online interpreters that load it by default, but most systems would have this package loaded by default.
Thanks to Tom Carpenter for spotting a small mistake of 2 bytes.
This defines an anonymous function, taking the input as a vector `n=[a,b]`. We then use inline assignment to reduce the calculation of the HM to just `z/q`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
²Æm,P½S
PḤ÷S+Ç+Æm
```
[Try it online!](https://tio.run/##y0rNyan8///QpsNtuToBh/YGcwU83LHk8PZg7cPt2kCx////R5vrKJjFAgA "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ 16 bytes
-2 bytes thanks to Erik the Outgolfer
```
nO;t¹O;¹Pt2¹zO/O
```
Explanation:
```
nO;t Root mean square
n Raise [a, b] to [a ** 2, b ** 2]
O Sum
; Half
t Square root
¹O; Arithmetic mean
¹ Retrieve stored [a, b]
O Sum
; Half
¹Pt Geometric mean
¹ Retrieve stored [a, b]
P Product
t Square root
2¹zO/ Harmonic mean
¹ Retrieved stored [a, b]
z Vectorised inverse to [1 / a, 1 / b]
O Sum
2 / Get 2 divided by the sum
O Sum of all elements in stack
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcOsQyvz/K1LDq3ztz60LqDE6NC6Kn99////zbnMAA "05AB1E – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 19 bytes
```
ṁëȯ√½ṁ□o½Σo√Π§/ΣoDΠ
```
[Try it online!](https://tio.run/##yygtzv7//@HOxsOrT6x/1DHr0F4g@9G0hfmH9p5bnA8UOLfg0HJ9INPl3IL///9Hm@uYxQIA "Husk – Try It Online")
-1 thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz).
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~21~~ ~~18~~ 17 bytes
```
UYmGphX^GYmGpy/vs
```
[Try it online!](https://tio.run/##y00syfn/PzQy170gIyLOHURX6pcV//8fbaZgHgsA "MATL – Try It Online")
-3 bytes thanks to Luis Mendo.
### Explanation
```
UYm % Mean of squares,
% Stack: { (a^2+b^2)/2 }
Gp % Product of input, a*b
% Stack: { (a^2+b^2)/2, a*b }
hX^ % Concatenate into array, take square root of each element.
% Stack: { [RMS, HM] }
GYm % Arithmetic mean of input.
% Stack: { [RMS,GM], AM }
Gpy % Product of input, duplicate AM from below.
% Stack: { [RMS,GM], AM, a*b, AM
/ % Divide to get HM
% Stack { [RMS,GM], AM, HM}
vs % Concatenate all to get [RMS,GM,AM,HM], sum.
```
[Answer]
# [Ohm v2](https://github.com/MiningPotatoes/Ohm), 16 bytes
```
²Σ½¬³Π¬³Σ½D³Πs/Σ
```
[Try it online!](https://tio.run/##y8/INfr//9Cmc4sP7T205tDmcwvAJJDnAuIU659b/P9/tLmOglksAA "Ohm v2 – Try It Online")
## Explanation
```
square sum halve sqrt input product sqrt input sum halve dupe input product swap div sum
```
...if Ohm had a verbose mode of sorts. :P
```
²Σ½¬³Π¬³Σ½D³Πs/Σ
implicit input [[7, 6]]
²Σ½¬ root mean square
² square [[49, 36]]
Σ sum [85]
½ halve [42.5]
¬ square root [6.519]
³Π¬ geometric mean
³ push first input [6.519, [7, 6]]
Π product [6.519, 42]
¬ square root [6.519, 6.481]
³Σ½ arithmetic mean
³ push first input [6.519, 6.481, [7, 6]]
Σ sum [6.519, 6.481, 13]
½ halve [6.519, 6.481, 6.500]
D³Πs/ harmonic mean
D duplicate [6.519, 6.481, 6.500, 6.500]
³ push first input [6.519, 6.481, 6.500, 6.500, [7, 6]]
Π product [6.519, 6.481, 6.500, 6.500, 42]
s swap [6.519, 6.481, 6.500, 42, 6.500]
/ divide [6.519, 6.481, 6.500, 6.461]
Σ sum [25.961]
implicit output [25.961]
```
[Answer]
# TI-Basic (TI-84 Plus CE), ~~27~~ 25 bytes
```
√(sum(Ans2)/2)+mean(Ans)+2prod(Ans)/sum(Ans)+√(prod(Ans
```
-2 bytes from [Scrooble](https://codegolf.stackexchange.com/users/73884/scrooble)
Takes a list of two numbers in `Ans`, and implicitly returns the sum of the four means; e.g. run with `{7,6}:prgmNAME` to get `25.96148157`.
Explanation:
`√(sum(Ans2)/2)`: 8 bytes: root mean square
`mean(Ans)`: ~~5~~ 3 bytes: arithmetic mean (old: `sum(Ans)/2`)
`2prod(Ans)/sum(Ans)`: 8 bytes: harmonic mean
`√(prod(Ans`: 3 bytes: geometric mean
+3 bytes for 3 `+`es
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 22 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
+:A½.².²+½√..*:√;«a/¹∑
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=KyUzQUElQkQuJUIyLiVCMislQkQldTIyMUEuLiolM0EldTIyMUElM0IlQUJhLyVCOSV1MjIxMQ__,inputs=MzQ1JTBBMTky)
[Answer]
# [Dyalog APL](https://www.dyalog.com/), 44 bytes
```
{+/(2×o÷k),(.5×k←⍺+⍵),.5*⍨(o←⍺×⍵),.5×+/⍺⍵*2}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqbX0No8PT8w9vz9bU0dAzPTw9Gyj6qHeX9qPerZo6eqZaj3pXaORDxA5Phwoenq6tD@QDeVpGtf//myukKZhxGRoAKUMDLiNjEM1lBCRNuIxNTEE8SyMA "APL (Dyalog Unicode) – Try It Online")
Dyadic dfns with `a` on the left and `b` on the right.
[Answer]
# JavaScript, 47 bytes
```
a=>b=>(c=a+b)/2+(c*c/2-(d=a*b))**.5+d**.5+2*d/c
```
quite trivial
```
f =
a=>b=>(c=a+b)/2+(c*c/2-(d=a*b))**.5+d**.5+2*d/c
```
```
<div oninput="r.value = f(+a.value)(+b.value)">
<p><label>a = <input id="a" type="number" step="any" value="1" /></label></p>
<p><label>b = <input id="b" type="number" step="any" value="1" /></label></p>
</div>
<p>result = <output id="r">4</output></label></p>
```
[Answer]
# Java 8, 63 bytes
```
a->b->Math.sqrt((a*a+b*b)/2)+(a+b)/2+Math.sqrt(a*b)+2/(1/a+1/b)
```
Takes both parameters as `Double` and outputs as `Double`.
[Try it here.](https://tio.run/##jY8xT8MwEIX3/gqPdk0ckhYQKmRCbJ06IoazE8DBtU19qVRV/e3hClEzNrfck973Tu9a2EMWYuPb@rs3DlJia7D@OGMsIaA1rCVCdWid@ui8QRu8eh3E00votGtuJjH/u6qYYc89ZJXOqjXgl0o/O@Qc5iD1XIu8FJKTJCFHG8iRZc6LHGSRa9GvqN95aEU6SzWHtvtga7alD/gGd9Z/vr0zEMc/enNI2GxV6FBFstB5bhTE6A78oRaDuq@FWF3Di9sLf5bXA@ViDEziL/hyCr5Y3o33H8shcpqd@l8)
Or (also **63 bytes**):
```
a->b->(a+b+Math.sqrt(a*a+b*b<<1))/2+Math.sqrt(a*b)+2d*a*b/(a+b)
```
Takes both parameters as `Integer` and outputs as `Double`.
[Try it here.](https://tio.run/##jY8/T8MwEMX3fgqPdkLcNv2DUEMmhMTQqSNiODumOLi2G18qVVU/e3AhFDE1t9w73e@e3tVwgMx5Zevqs5MGQiBr0PY0IiQgoJakjgRvURv@3lqJ2ln@3IvixaLaquZuGPTkWmFUWRJJHjvISpGVFFKRrgE/eNg3SCGJcyKKYsrYOP@3ECzNqyT28eWGdauY8FKx@Wgbg/Z5D05XZBd/oBtstN2@vhFgp296cwyodty1yH1cobFUcvDeHOk968WSsdUteDphf@o2ns@u@BD6F54PgGfzxdX7If85OI/O3Rc)
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
```
lambda a,b:((a*a+b*b)/2)**.5+(a+b)/2+(a*b)**.5+2*a*b/(a+b)
```
[Try it online!](https://tio.run/##Tck7CoAwDIDh3VM4tmmJGl8oeBOXFCkKvhAXT1@DIDqE5P@yX@e4rRR814eZFzdwzNa1SjGwceB0QhoAS6MkJWQLPkIgZ/J42I9pPWOvarQV6ujNLEUr8wHlAv9GW/wyL0r5N4Q63A "Python 2 – Try It Online")
Takes input as floats
[Answer]
# [ARBLE](https://github.com/TehFlaminTaco/ARBLE), ~~49~~ 45 bytes
*-4 bytes thanks to Mr. Xcoder*
```
((a^2+b^2)/2)^.5+(a+b)/2+(a*b)^.5+2*a*b/(a+b)
```
[Try it online!](https://tio.run/##SyxKykn9/19DIzHOSDspzkhT30gzTs9UWyNROwnIBtJaSWABIy0gSx8s/P//f/P/ZgA "ARBLE – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 15 bytes
```
æßπ√+ßΣßπτ/+ßµ+
```
[Try it online!](https://tio.run/##S0wuKU3Myan8///wssPzzzc86pilfXj@ucUg9vkWfSD70Fbt//@jjU1MdRQMLY1iAQ "Actually – Try It Online")
Yay Actually has a built-in for Root Square Mean!
```
æßπ√+ßΣßπτ/+ßµ+ ~ Full program.
æ ~ Arithmetic mean.
ßπ√ ~ Product, Square root (computes geometric mean).
+ ~ Addition.
ßΣ ~ Push the sum of the input.
ßπτ ~ Push the product of the input doubled.
/ ~ Divide.
+ ~ Addition.
ßµ ~ Push Root Square Mean.
+ ~ Addition.
```
[Answer]
# [Julia](http://julialang.org/), ~~49~~ 47 bytes
```
a$b=(x=a+b)/2+((a^2+b^2)/2)^.5+(y=a*b)^.5+2*y/x
```
[Try it online!](https://tio.run/##TcdBCoAgEADAe@/Yw6qQuWXRwa8I680QiSiw11sEUbeZ5UiRx1oZgsPiWAWhSSGyJxU83RG@tQpPxzI8JHnqUtct5j1lHGESzRvTgem@Ug/mNxi@9IMFM5OoFw "Julia 0.6 – Try It Online")
[Answer]
## Groovy, 54 bytes
```
{a,b->c=a+b;((a*a+b*b)/2)**0.5+c/2+(a*b)**0.5+2*a*b/c}
```
-2 thanks to Mr. Xcoder for an edit that made me feel dumb.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 76 bytes
+13 bytes for `using System;`
```
a=>b=>Math.Sqrt((a*a+b*b)/2)+(a+b)/2+Math.Sqrt(a*b)+2/(1/a+1/b)
```
[Try it online!](https://tio.run/##bY4/D4IwFMT3fgrGlioNDDogXUicZGJwfv0TbYIt0mJiCJ8dm0B0cXr37nfJnfR76Qa9jN7YW9K@fdCPEvWj6IxMZAfeJ/WEfIAQ/xVn59HKk3Ixo3d/rPVw3lcLVFxUvIFwz9rnEDCGFKhIBWEFoTjKKOgPQyS0YDhnQHMmyPJdsg14OaOSBozFBE1bde2sd53OroMJ@mKsxj0@KoIPipASzWhePg "C# (.NET Core) – Try It Online")
[Answer]
# [Jq 1.5](https://stedolan.github.io/jq/), 76 bytes
```
[pow((map(pow(.;2))|add)/2;.5),add/2,pow(.[0]*.[1];.5),2/(map(1/.)|add)]|add
```
Expanded
```
[
pow((map(pow(.;2))|add)/2;.5) # root mean square
, add/2 # arithmetic mean
, pow(.[0]*.[1];.5) # geometric mean
, 2/(map(1/.)|add) # harmonic mean
]
| add # that just about sums it up for mean
```
[Try it online!](https://tio.run/##TYxNbsMgEIX3PgVSN3YFmBkYYBSpF0EsLGWTKrWd1lY2OXsIpl10FvPz5nvv81ZSkMJnKWq9CfUhkDR7cBHIUx0csEtgpABzQA1xpktoq9RsTbJOM4OFGKI3gQ1XQgr3LxdAewo2gCOgCGh9l6yjmsKY/xBDoIM3npids9HZ7lHSutz7/mta@2PRJxyGx3Q@DyOeNA2yriPK9komv@sEuek4Ng@M@hfPRy/luazbZZl/ilLzfr2qy7zuWz2@p7ta9q0eLw "jq – Try It Online")
] |
[Question]
[
# About the Series
First off, you may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges. You can find the leaderboard along with some more information about the series [in the first post](https://codegolf.stackexchange.com/q/45302/8478).
Although I have a bunch of ideas lined up for the series, the future challenges are not set in stone yet. If you have any suggestions, please let me know [on the relevant sandbox post](http://meta.codegolf.stackexchange.com/a/4750/8478).
# Hole 2: Numbers from a Normal Distribution
I can't believe this hasn't been done yet! You're to generate random numbers, drawing from a [normal distribution](http://en.wikipedia.org/wiki/Normal_distribution). Some rules (the majority of them are probably automatically covered by most submission, but some of them are in place to ensure consistency of results between vastly different languages):
* You should take **two non-negative integers as input**: a seed `S` and the amount `N` of numbers to return. The output should be a list of `N` floating point numbers, drawn from a normal distribution with **mean 0** and **variance 1**. Whenever your submission is given the same seed `S` it should produce the same number. In particular, if it is called once with `(S, N1)` and once with `(S, N2)`, the first `min(N1, N2)` entries of the two outputs should be identical. In addition, **at least 216 different values of `S` should produce different sequences.**
* You may use any built-in random number generator that is documented to draw numbers from an (approximately) *uniform* distribution, provided you can pass `S` on to it and it supports at least 216 different seeds. If you do, **the RNG should be able to return at least 220 different values** for any given number you request from it.
* If your available uniform RNG has a smaller range, is not seedable, or supports too few seeds, you must either first build a uniform RNG with a sufficiently large range on top of the built-in one or you must implement your own [suitable RNG](http://meta.codegolf.stackexchange.com/a/1325/8478) using the seed. [This page](http://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use) may be helpful for that.
* If you don't implement an established algorithm for generating normal distributions, please include a proof of correctness. In either case, **the algorithm you choose must yield a theoretically exact normal distribution** (barring limitations of the underlying PRNG or limited-precision data types).
* Your implementation should use and return either **floating-point numbers (at least 32 bits wide)** or **fixed-point numbers (at least 24 bits wide)** and all arithmetic operations should make use of the full width of the chosen type.
* You must not use any built-in functions directly related to normal distribution or Gaussian integrals, like the [Error function](http://en.wikipedia.org/wiki/Error_function) or its inverse.
You may write a full program or a function and take input via STDIN, command-line argument, function argument or prompt and produce output via return value or by printing to STDOUT (or closest alternative).
`S` and `N` will be non-negative integers, each less than 220. Output may be in any convenient, unambiguous list or string format.
This is code golf, so the shortest submission (in bytes) wins. And of course, the shortest submission per user will also enter into the overall leaderboard of the series.
# Leaderboard
**[The first post of the series generates a leaderboard.](https://codegolf.stackexchange.com/q/45302/8478)**
To make sure that your answers show up, please start every 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
```
*(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)*
[Answer]
# Dyalog APL, 33 bytes
[`{(.5*⍨¯2×⍟?0)×1○○2×?0}¨⍳⎕⊣⎕rl←1+⎕`](http://tryapl.org/?a=S%u21901%20%u22C4%20N%u2190100000%20%u22C4%20f%u2190%7B%7B%28.5*%u2368%AF2%D7%u235F%3F0%29%D71%u25CB%u25CB2%D7%3F0%7D%A8%u2373%u2375%u22A3%u2395rl%u2190%u237A+1%7D%20%u22C4%20w%u219030%20%u22C4%20r%u21908%20%u22C4%20%u2296%u2349%u2191%27%23%27%u2374%A8%u2368%u2308.5+10%D7%28%u22A2%F7%u2308/%29+/%28w-%u23732%D7w%29%u2218.%3D%u230Ar%D7S%20f%20N&run)
[Box-Muller](https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform):
```
⎕ ⍝ evaluated input
⎕rl←1+⎕ ⍝ set APL's random seed to 1+⎕ (S)
⍝ add 1 because ⎕rl←0 has special meaning: sets the seed randomly
{ }¨⍳N ⍝ do the thing in braces N times
?0 ⍝ random number 0≤x<1
1○○2×A ⍝ sin(2πA)
.5*⍨¯2×⍟B ⍝ sqrt(-2lnB)
```
[Answer]
# R, 68 bytes
```
function(S,N){set.seed(S);sqrt(-2*log(runif(N)))*cos(2*pi*runif(N))}
```
This uses the `runif()` function, which generates random deviates from a uniform distribution. The seed for the random number generation is specified using `set.seed()`, which by default uses the Mersenne-Twister algorithm with a period of 2^19937-1.
The result is an R vector of length N containing the computed standard normal deviates.
This uses the Box-Muller method: For two independent uniform random variables U and V,

[Answer]
## Dyalog APL, ~~42~~ 34
```
{⎕RL←⍺⋄{(.5*⍨¯2×⍟⍺)×1○⍵×○2}/?⍵2⍴0}
```
This is a function that takes `S` as its left argument and `N` as its right argument.
```
5{⎕RL←⍺⋄{(.5*⍨¯2×⍟⍺)×1○⍵×○2}/?⍵2⍴0}10
3.019132549 ¯0.2903143175 ¯0.7353414637 1.421417015 2.327544764 ¯0.00005019747711 ¯0.9582127248 ¯0.2764568462
¯0.1602736853 ¯0.9912352616
5{⎕RL←⍺⋄{(.5*⍨¯2×⍟⍺)×1○⍵×○2}/?⍵2⍴0}20
3.019132549 ¯0.2903143175 ¯0.7353414637 1.421417015 2.327544764 ¯0.00005019747711 ¯0.9582127248 ¯0.2764568462
¯0.1602736853 ¯0.9912352616 0.642585109 ¯0.2450019151 ¯0.415034463 0.03481768503 ¯0.4621212815 ¯0.760925979
0.2592913013 1.884867889 ¯0.9621252731 0.3062560446
```
It's an implementation of the Box-Muller transform, using Dyalog APL's built-in random operator `?`, which by default is a Mersenne twister that returns 64-bit values, which should be enough.
Explanation:
* `⎕RL←⍺`: set the random seed to `⍺`.
* `?⍵2⍴0`: generate `⍵` pairs of random numbers between 0 and 1.
* `{`...`}/`: apply the following function to each pair:
+ `(.5*⍨¯2×⍟⍺)×1○⍵×○2`: calculate the `Z0` value (`sqrt(-2 ln ⍺)×cos(2π⍵)`).
[Answer]
# Perl, 67
```
sub f{srand$_[0];map{cos(atan2(1,1)*rand 8)*sqrt-2*log rand}1..pop}
```
Box-Muller as in other entries. `f` takes parameters in order `S, N`.
Use:
```
$ perl -le 'sub f{srand$_[0];map{cos(atan2(1,1)*rand 8)*sqrt-2*log rand}1..pop}print for f(5,3)'
-1.59212831801942
0.432167710756345
-0.533673305924252
```
[Answer]
# Java, ~~164~~ 161 bytes
```
class B extends java.util.Random{B(int s,int n){super(s);for(;n-->0;System.out.println(Math.sqrt(-2*Math.log(nextDouble()))*Math.cos(2*Math.PI*nextDouble())));}}
```
This takes in input via function and output via stdout. It uses the Box-Muller method.
[Answer]
# Commodore 64 Basic, ~~76~~ ~~70~~ 63 bytes
```
1INPUTS,N:S=R/(-S):F┌I=1TON:?S●(-2*LOG(R/(1)))*S╮(2*π*R/(1)):N─
```
Since the PETSCII character set contains some symbols not present in Unicode, I've made substitutions: `/` = `SHIFT+N`, `┌` = `SHIFT+O`, `●` = `SHIFT+Q`, `╮` = `SHIFT+I`, `─` = `SHIFT+E`
This implements the standard Box-Muller transform to generate the numbers; I picked the sin(x) half of the transform because Commodore 64 Basic has a two-character shortcut for `sin()`, but not for `cos()`.
Although the manual states otherwise, the value of the argument to `RND` *does* matter: if a negative number is passed, the random number generator is not merely re-seeded, it is re-seeded *with that number*. This makes seeding much simpler: instead of needing to `POKE` five memory locations, I merely need to make a do-nothing call to `RND`, which reduces the code from two lines/121 bytes to 1 line/76 bytes.
Edit: Golfed six bytes off by realizing I could combine the two `INPUT` statements, and that the space after `TO` was optional.
Edit: Golfed another seven off: Commodore Basic does, in fact, have Pi as a built-in constant, and it's even typeable on a modern keyboard (`SHIFT+PgDn`, in case you were wondering).
[Answer]
# 80386 machine code, 72 bytes
Hexdump of the code:
```
60 8b 7c 24 24 33 ed 8d 75 fb 8d 46 79 f7 e2 f7
f6 8b da b3 7f 0f cb d1 eb 89 1f d9 07 d9 e8 de
e9 33 ee 75 e5 d9 ed d9 c9 d9 f1 dc c0 d9 e0 d9
fa d9 c9 d9 eb de c9 dc c0 d9 ff de c9 d9 1f 83
c7 04 e2 c6 61 c2 04 00
```
Here is the source code (can be compiled by Visual Studio):
```
__declspec(naked) void __fastcall doit(int count, unsigned seed, float* output)
{
_asm {
// ecx = count
// edx = seed
// save registers
pushad;
mov edi, [esp + 0x24]; // edi = pointer to output
xor ebp, ebp; // ebp = 0
lea esi, [ebp - 5]; // esi = 4294967291 (a prime number)
myloop:
// Calculate the next random number
lea eax, [esi + 121]; // eax = 116
mul edx;
div esi;
mov ebx, edx;
// Convert it to a float in the range 1...2
mov bl, 0x7f;
bswap ebx;
shr ebx, 1;
// Convert to range 0...1 and push onto the FPU stack
mov [edi], ebx;
fld dword ptr [edi];
fld1;
fsubp st(1), st;
// Make 2 such random numbers
xor ebp, esi;
jnz myloop;
// Calculate sqrt(-2*ln(x))
fldln2;
fxch;
fyl2x;
fadd st, st(0);
fchs;
fsqrt;
// Calculate cos(2*pi*y)
fxch st(1);
fldpi;
fmul;
fadd st, st(0);
fcos;
// Calculate and write output
fmulp st(1), st;
fstp dword ptr [edi];
add edi, 4;
// Repeat
loop myloop
// Return
popad;
ret 4;
}
}
```
---
Here I use a a [Lehmer random number generator](http://en.wikipedia.org/wiki/Lehmer_random_number_generator). It uses the following algorithm:
```
x(k+1) = 116 * x(k) mod 4294967291
```
Here 4294967291 is a big (2^32-5) prime number, and 116 is a small (less than 128; see below) number that is its [primitive root](http://en.wikipedia.org/wiki/Primitive_root_modulo_n). I chose a primitive root that has
a more-or-less random distribution of zeros and ones in binary representation (01110100). This RNG has the maximum possible period of 4294967290, if the seed is nonzero.
---
The relatively small numbers I used here (116 and 4294967291, which can be represented also as -5) let me take advantage of the `lea` instruction encoding:
```
8d 46 79 lea eax, [esi+121]
```
It is assembled to 3 bytes if the numbers can fit into 1 byte.
---
The multiplication and division use `edx` and `eax` as their working registers, which is why I made `seed` the second parameter to the function (`fastcall` calling convention uses `edx` to pass the second parameter). In addition, the first parameter is passed in `ecx`, which is a good place to hold a counter: a loop can be organized in 1 instruction!
```
e2 c6 loop myloop
```
---
To convert an integer into a floating-point number, I exploited the representation of single-precision floating-point numbers: if I set the high 9 bits (exponent) to the bit pattern `001111111`, and leave the 23 low bits random, I'll get a random number in the range 1...2. I took the idea from [here](https://xor0110.wordpress.com/2010/09/24/how-to-generate-floating-point-random-numbers-efficiently/). To set the high 9 bits, I used some bit-fiddling on `ebx`:
```
mov ebx, edx; xxxxxxxx|yyyyyyyy|zzzzzzzz|aaaaaaaa
mov bl, 0x7f; xxxxxxxx|yyyyyyyy|zzzzzzzz|01111111
bswap ebx; 01111111|zzzzzzzz|yyyyyyyy|xxxxxxxx
shr ebx, 1; 00111111|1zzzzzzz|zyyyyyyy|yxxxxxxx
```
---
To generate two random numbers, I used a nested loop of 2 iterations. I organized it with `xor`:
```
xor ebp, esi; first time, the result is -5
jnz myloop; second time, the result is 0 - exit loop
```
---
The floating-point code implements the [Box-Muller transform](http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform).
[Answer]
# Haskell, 118 ~~144~~
```
import System.Random;h z=let(u,r)=random z in(cos$2*pi*fst(random r)::Float)*sqrt(-2*log u):h r;g=(.(h.mkStdGen)).take
```
Example usage:
```
*Main> g 3 0x6AE4A92CAFA8A742
[0.50378895,-0.20593005,-0.16684927]
*Main> g 6 0x6AE4A92CAFA8A742
[0.50378895,-0.20593005,-0.16684927,1.1229043,-0.10026576,0.4279402]
*Main> g 6 0xE09B1088DF461F7D
[2.5723906,-0.5177805,-1.3535261,0.7400385,3.5619608e-3,-8.246434e-2]
```
The return type of `random` is constrained to `Float`, which makes `random` generate a uniform float in [0, 1). From then on it's a simlpe box-muller formula with some pointless magic for list generation.
[Answer]
# Golflua, 63 ~~70~~
[Golflua info and instructions.](http://meta.codegolf.stackexchange.com/a/1216/7162)
```
\g(n,s)`_ENV,b=M,{}rs(s)~@i=1,n b[i]=q(l(r()^-2))*c(r()*pi)$~b$
```
Returns a table containing the values. In the example I'm using `~T.u( )`, which is the same as `return table.unpack( )` in lua.
```
> ~T.u(g(3,1234567))
0.89302672974232 0.36330401643578 -0.64762161593981
> ~T.u(g(5,1234567))
0.89302672974232 0.36330401643578 -0.64762161593981 -0.70654636393063 -0.65662878785425
> ~T.u(g(5,7654321))
0.3867923683064 -0.31758512485963 -0.58059120409317 1.2079459300077 1.1500121921242
```
A lot of chars were saved by setting the function's environment to `M` (aka `math`).
[Answer]
# SAS, 108
I already posted an [answer in R](https://codegolf.stackexchange.com/a/45449/20469) that's shorter than this, but there are very few SAS answers on PPCG, so why not add another?
```
%macro f(s,n);data;do i=1 to &n;x=sqrt(-2*log(ranuni(&s)))*cos(8*atan2(1,1)*ranuni(&s));put x;end;run;%mend;
```
With some white space:
```
%macro f(s, n);
data;
do i = 1 to &n;
x = sqrt(-2 * log(ranuni(&s))) * cos(8 * atan2(1, 1) * ranuni(&s));
put x;
end;
run;
%mend;
```
This defines a macro which can be called like `%f(5, 3)`. The macro executes a data step which loops through the integers 1 to N, and at each iteration it computes a random normal deviate using Box-Muller and prints it to the log using the `put` statement.
SAS has no built-in for pi, so the best we can do is approximate it with arctangent.
The `ranuni()` function (which is deprecated but requires a couple fewer characters than the newer function) returns a random number from a uniform distribution. The SAS documentation doesn't give a whole lot of detail on the RNG implementation other than it has a period of 2^31-2.
In SAS macros, macro variables are referenced with a preceding `&` and resolve to their values at run time.
As you've probably witnessed, SAS is rarely an actual contender in a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") contest.
[Answer]
# Java, 193 bytes
While this doesn't beat the current Java leader, I decided to post anyway to show a different method of calculation. It's a golfed version of OpenJDK's [`nextGaussian()`](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/Random.java#Random.nextGaussian%28%29).
```
class N extends java.util.Random{N(int s,int n){super(s);for(float a,v;n-->0;System.out.println(v*Math.sqrt(-2*Math.log(a)/a)))for(a=0;a>=1|a==0;a=v*v+(v=2*nextFloat()-1)*v)v=2*nextFloat()-1;}}
```
With line breaks:
```
class N extends java.util.Random{
N(int s,int n){
super(s);
for(float a,v;
n-->0;
System.out.println(v*Math.sqrt(-2*Math.log(a)/a)))
for(a=0;
a>=1|a==0;
a=v*v+(v=2*nextFloat()-1)*v)v=2*nextFloat()-1;
}
}
```
[Answer]
## T-SQL, 155 bytes
```
CREATE PROC R(@S BIGINT,@N INT)AS
DECLARE @ INT=0,@K INT=8388607WHILE @<@N
BEGIN
SELECT SQRT(-2*LOG(RAND(@S*@%@K)))*COS(2*PI()*RAND(@S*9*@%@K))SET @+=1
END
```
Use with EXEC R S,N because there is no STD\_IN in T-SQL
where S and N are the seed and N respectively. S will produce "random" (RAND(seed) is a really bad random number implementation) sequences when S>2^16 (possibly before that, but I won't guarantee it). Uses Box-Muller like most solutions so far. 8388607 is 2^23-1, which should hopefully generate 2^20 different values.
[Answer]
## Powershell, 164 bytes
```
Param($s,$n)$q=2147483647
$a=GET-RANDOM -SETSEED $s
FOR(;$n---gt0;){$a=GET-RANDOM
$b=GET-RANDOM
[math]::SQRT(-2*[math]::LOG($a/$q))*[math]::COS(2*[math]::PI*$b/$q)}
```
Same as most answers with Box-Muller. Not very experienced with Powershell, so any help golfing would be appreciated.
[Answer]
# Ruby, 72 bytes
```
->n,s{include Math;srand s;n.times{p sqrt(-2*log(rand))*sin(2*rand*PI)}}
```
### Input (as lambda function):
```
f.(6, 12353405)
```
### Output:
```
-1.1565142460805273
0.9352802655317097
1.3566720571574993
-0.9683973210257978
0.9851210877202192
0.14709635752306677
```
PS: I would like to know if this can be golfed further. I'm just a beginner.
[Answer]
# Matlab, 77
The first input should be `n`, the second one `s`.
```
a=input('');
rand('seed',a(2));
for i=1:a;
(-2*log(rand))^.5*cos(2*pi*rand)
end
```
[Answer]
# Octave, 91 ~~96~~ 88 bytes
```
function r=n(s,n)rand("seed",s);x=rand(2,n);r=cos(2*pi*x(1,:)).*sqrt(-2*log(x(2,:)));end
```
Or, with whitespace:
```
function r=n(s,n)
rand("seed",s);
x=rand(2,n);
r=cos(2*pi*x(1,:)).*sqrt(-2*log(x(2,:)));
end
```
Set the seed up front, and use the Box-Mueller method.
NB: Octave allows for generation of arrays of random numbers, and can use standard operations on these arrays which produce array outputs. The `.*` operator is element-by-element multiplication of two arrays to produce the result.
[Answer]
# Pyth, 32 bytes
No Python being used now in super-quotes because of the new functions Pyth has now. Yet another Box-Mueller.
```
.xvzVQ*@_y.lOZ2.71 2.ty*3.14OZ1
```
That space in the beginning is important.
```
.xvz Seed RNG with evaluated input
VQ For N in second input
* Multiplication
@ 2 Square root
_y Times negative 2
.l ) Natural log
OZ Of random float (RNG with zero give [0, 1) float)
.t 1 Cosine from list of trig functions
y Double
* Multiplication
.nZ Pi from constants list
OZ Random Float
```
The seeding doesn't seem to work in the online interpreter, but it works fine in the local version. The online interpreter seems to be fixed, so here's a permalink: [permalink](https://pyth.herokuapp.com/?code=.xvzVQ*%40_y.lOZ2.71%202.ty*3.14OZ1&input=10%0A5)
[Answer]
## STATA, 85 bytes
```
di _r(s)_r(n)
set se $s
set ob $n
g a=sqrt(-2*ln(runiform()))*cos(2*runiform()*_pi)
l
```
Takes input via standard in (first number is S, then N). Sets the seed to S. Sets the number of observations to N. Makes a variable and sets its value to the Box Muller transform value (thanks to @Alex for showing it). Then lists all of the observations in a table with column header a and observation numbers next to them. If these are not okay, let me know, and I can remove headers and/or observation numbers.
[Answer]
# R, 89 Bytes
I know R has been done before but I wanted to show a different approach than the Box-Muller that everyone else used. My solution uses the [Central Limit Theorem](http://en.wikipedia.org/wiki/Central_limit_theorem) .
```
f=function(S,N){set.seed(S);a=1000;for(i in(1:N)){print(sqrt(12/a)*(sum(runif(a))-a/2))}}
```
[Answer]
## TI-Basic, 74 bytes
```
Prompt S,N:S→rand:For(X,1,N:0→A:0→V:0→W:While A≥1 or A=0:2rand-1→V:2rand-1→W:V²+W²→A:End:Disp VW√(Aֿ¹-2log(A:End
1 1111111 11 1111111111111111111 1111 111111 1111111 11111111111111 11 111111111 111
```
The `¹` is actually the inverse operator.
[Answer]
# Perl, ~~150~~ ~~108~~ 107 bytes
This uses the [Marsaglia Polar Method](http://en.wikipedia.org/wiki/Marsaglia_polar_method). Called with f(S, N).
Moved the assignment of `$a` into the calculation of `$c`.
107:
```
sub f{srand$_[0];map{do{$c=($a=-1+2*rand)**2+(-1+2*rand)**2}until$c<1;print$a*sqrt(-2*log($c)/$c)}1..$_[1]}
```
Removed spare number storage and the definition of `$b`.
108:
```
sub f{srand$_[0];map{do{$a=-1+2*rand,$c=$a**2+(-1+2*rand)**2}until$c<1;print$a*sqrt(-2*log($c)/$c)}1..$_[1]}
```
150:
```
sub f{srand$_[0];map{$h?$h=!print$s:do{do{$a=-1+2*rand,$b=-1+2*rand,$c=$a*$a+$b*$b}until$c<1;$d=sqrt(-2*log($c)/$c);$s=$b*$d;$h=print$a*$d;}}1..$_[1]}
```
[Answer]
## Swift, 144 142
Nothing clever, just seeing how Swift works.
```
import Foundation;func r(s:UInt32,n:Int){srand(s);for i in 0..<n{println(sqrt(-2*log(Double(rand())/0xffffffff))*sin(2*Double(rand())*M_PI))}}
```
I was hoping I could use (0...n).map{} but it the compiler doesn't seem to recognise map{} unless you use a parameter.
[Answer]
# [Haskell](https://www.haskell.org/), 97 bytes
```
import System.Random
h(a:b:c)=sqrt(-2*log a::Float)*cos(2*pi*b):h c
f a=take a.h.randoms.mkStdGen
```
[Try it online!](https://tio.run/##Hcy7DcMgEADQ3lNckQKQghxKJNqkjyc4YxwQX8M1mZ5IeQM8jyO6lOYMudVOsH0HuSzfWI6aF89Q79pyM65O7K5Eqh9ArZ@pInFh62BKtCB2rj3Y5QQ0hNEBSi/7vxgyx42OlyszYyhgoPVQCG5wglrhsc4f "Haskell – Try It Online")
Just your basic Box-Muller transformation, on an infinite list of random numbers.
[Answer]
# [Python 3](https://docs.python.org/3/), 118 bytes
```
from random import*
from math import*
def f(s,n):seed(s);return[sqrt(-2*log(random()))*cos(tau*random())for _ in[0]*n]
```
[Try it online!](https://tio.run/##XczLCoMwEIXhvU@R5UywYHTXPoqISE2q0Mykk3HRp09vIG1Xh@9fnHTXhakrJQhHIxPNz1ljYlFbvVucdNnL7IMJkGvCY/Z@hown8boJ9fkmCofWXvkCnxtARHvmDDptdk@BxYxmpb4ZLA0lyUoKAVzT1A6x@nb75@7H7uXyAA "Python 3 – Try It Online")
[Answer]
# SmileBASIC, 81 bytes
Well, now that I've answered the first question, I have to do all the rest...
Generating random numbers is cheap, but seeding the RNG uses the *longest* builtin function in the language, `RANDOMIZE`.
```
DEF N S,N
RANDOMIZE.,S
FOR I=1TO N?SQR(-2*LOG(RNDF()))*COS(PI()*2*RNDF())NEXT
END
```
Maybe there's some way to optimize the formula. I don't see how it's required to use two RNG calls.
] |
[Question]
[
The goal is to calculate all the squares up to `x` with addition and subtraction.
Rules:
1. The code must be a function which takes the total number of squares to generate, and returns an array containing all those squares.
2. You can **not** use strings, structures, multiplication, division, or built-in functions for calculating squares.
3. You can only use arrays, integers (whole numbers), addition, subtraction. **No other operators allowed!**
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question, so the shortest code in bytes wins!
[Answer]
# APL - 10
```
{+\1++⍨⍳⍵}
```
Example usage:
```
{+\1++⍨⍳⍵}10
1 4 9 16 25 36 49 64 81 100
```
[ngn APL demo](http://ngn.github.io/apl/web/#code=%7B+%5C1++%u2368%u2373%u2375%7D10)
[Answer]
# C, 55 52 bytes
```
int s(int n,int*r){for(int i=0,j=-1;n--;*r++=i+=j+=2);}
```
simply sums odd numbers
* `n`: number of squares to compute
* `r`: output array for storing the results
* `j`: takes the successive values 1, 3, 5, 7, ...
* `i`: is incremented by `j` on each iteration
## Edit
4 chars can be saved using the implicit int declaration (>C99), but this costs 1 char because `for` initializers cannot contain a declaration in >C99. Then the code becomes
```
s(int n,int*r){int i=0,j=-1;for(;n--;*r++=i+=j+=2);}
```
## Usage
```
void main() {
int r[20];
s(20, r);
for (int i = 0; i < 20 ; ++i) printf("%d\n", r[i]);
}
```
## Output
```
1
4
9
16
25
36
49
(...)
361
400
```
[Answer]
### GolfScript, 17 characters
```
{[,{.+(1$+}*]}:F;
```
Usage (see also examples [online](http://golfscript.apphb.com/?c=e1ssey4rKDEkK30qXX06RjsKCjEwIEYgcA%3D%3D&run=true)):
```
10 F # => [0 1 4 9 16 25 36 49 64 81]
```
*Note:* `*` is a loop and not the multiplication operator.
[Answer]
## Windows Batch, 115 bytes
```
setlocal enabledelayedexpansion&for /l %%i in (1 1 %1)do (set a=&for /l %%j in (1 1 %%i)do set /a a+=%%i
echo.!a!)
```
This should be placed in a batch file instead of being run from cmd, and it outputs the list to the console. It takes the number of squares to create from the first command-line argument. For the most part it uses `&` instead of newlines, one is still needed however and it counts as two bytes.
It needs delayed variable expansion enabled, this can be done with `cmd /v:on`. Assuming it's not, an extra `setlocal enabledelayedexpansion&` was needed at the start (without it the script is 83 bytes).
[Answer]
# Haskell - 30
```
f n=scanl1(\x y->x+y+y-1)[1..n]
```
This uses the fact that `(n+1)^2=n^2+2n+1`
[Answer]
## Perl, 27 bytes
```
sub{map{$a+=$_+$_-1}1..pop}
```
**Math:**

**Script for calling the function to print 10 squares:**
```
#!/usr/bin/env perl
$square = sub{map{$a+=$_+$_-1}1..pop};
use Data::Dumper;
@result = &$square(10);
print Dumper \@result;
```
**Result:**
```
$VAR1 = [
1,
4,
9,
16,
25,
36,
49,
64,
81,
100
];
```
**Edits:**
* Anonymous function (−2 bytes, thanks [skibrianski](https://codegolf.stackexchange.com/questions/21796/calculate-all-the-squares-up-to-x-using-only-addition-and-subtraction/22073?noredirect=1#comment51780_22073))
* `pop` instead of `shift` (−2 bytes, thanks [skibiranski](https://codegolf.stackexchange.com/questions/21796/calculate-all-the-squares-up-to-x-using-only-addition-and-subtraction/22073?noredirect=1#comment52152_22073))
[Answer]
# JavaScript - 32 Characters
```
for(a=[k=i=0];i<x;)a[i]=k+=i+++i
```
Assumes a variable `x` exists and creates an array `a` of squares for values `1..x`.
# ECMAScript 6 - 27 Characters
```
b=[f=i=>b[i]=i&&i+--i+f(i)]
```
Calling `f(x)` will populate the array `b` with the squares for values `0..x`.
[Answer]
## Julia - 33
Any square number can be written by a summation of odd numbers:
```
julia> f(x,s=0)=[s+=i for i=1:2:(x+x-1)];f(5)
5-element Array{Int64,1}:
1
4
9
16
25
```
[Answer]
# C++ 99 81 78 80 78
```
int* f(int x){int a[x],i=1;a[0]=1;while(i<x)a[i++]=a[--i]+(++i)+i+1;return a;}
```
my first try in code-golf
this code is based on
a = 2 x n - 1
where **n** is term count and **a** is **n** th term in the following series
1, 3, 5, 9, 11, 13, .....
sum of first 2 terms = 2 squared
sum of first 3 terms = 3 squared
and so on...
[Answer]
## DCPU-16 Assembly (90 bytes)
I wrote this in assembly for a fictional processor, because why not?
```
:l
ADD I,1
SET B,0
SET J,0
:m
ADD J,1
ADD B,I
IFL J,I
SET PC,m
SET PUSH,B
IFL I,X
SET PC,l
```
The number is expected to be in the X register, and other registers are expected to be 0. Results are pushed to the stack, it will break once it reaches 65535 due to the 16 bit architecture. You may want to add a `SUB PC, 1` to the end to test it.
Compiled, the program should be 20 bytes (10 words).
[Answer]
## Haskell
```
f x=take x [iterate (+y) 0 !! y | y<- [0..]]
```
This basically invents multiplication, uses it own itself, and maps it over all numbers. `f 10` = `[0,1,4,9,16,25,36,49,64,81]`. Also `f 91` = `[0,1,4,9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361,400,441,484,529,576,625,676,729,784,841,900,961,1024,1089,1156,1225,1296,1369,1444,1521,1600,1681,1764,1849,1936,2025,2116,2209,2304,2401,2500,2601,2704,2809,2916,3025,3136,3249,3364,3481,3600,3721,3844,3969,4096,4225,4356,4489,4624,4761,4900,5041,5184,5329,5476,5625,5776,5929,6084,6241,6400,6561,6724,6889,7056,7225,7396,7569,7744,7921,8100]`.
[Answer]
# Haskell, 34 / 23
```
n#m=m+n:(n+2)#(m+n)
f n=take n$1#0
```
or, if imports are okay:
```
f n=scanl1(+)[1,3..n+n]
```
Output:
```
λ> f 8
[1,4,9,16,25,36,49,64]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
+)’Ä
```
[Try it online!](https://tio.run/##y0rNyan8/19b81HDzMMt////NzQAAA "Jelly – Try It Online")
## How it works
```
+)’Ä - Main link. Takes x on the left
) - For each integer 1 ≤ i ≤ x:
+ - Yield i+i = 2i
’ - Decrement each
Ä - Calculate the cumulative sum
```
[Answer]
## Javascript 47
`function f(n,a){return a[n]=n?f(n-1,a)+n+n-1:0}`
`r=[];f(12,r);console.log(r)` returns :
`[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144]`
[Answer]
# Smalltalk, 52
```
f:=[:n||s|(s:=1)to:n collect:[:i|x:=s.s:=s+i+i+1.x]]
```
Returns a new array (i.e. does not fill or add to an existing one).
call:
f value:10
-> #(1 4 9 16 25 36 49 64 81 100)
[Answer]
# python - 39
```
a=0
for i in range(5):a+=i+i+1;print(a)
```
Replace `5` with any value. Any suggestions?
[Answer]
**Bash - ~~92~~ ~~85~~ ~~62~~ ~~61~~ ~~59~~ 57**
```
declare -i k=1;for((i=0;i++<$1;k+=i+i+1));do echo $k;done
```
Result:
```
$ ./squares.sh 10
1
4
9
16
25
36
49
64
81
100
```
Edit: I replaced the inner loop with the algorithm from @mniip's Haskell solution.
[Answer]
Same method as above, in APL and J:
APL: `F←{+\1+V+V←¯1+⍳⍵}` (17 characters) works with most APL variants (try it [here](http://www.tryapl.com/))
and even less (only 14 characters) with NGN APL: `F←{+\1+V+V←⍳⍵}` (see [here](http://ngn.github.io/apl/web/index.html))
J: `f=:+/\@(>:@+:@:i.)` (18 characters)
**edit:** better solution in APL: `F←{+\¯1+V+V←⍳⍵}` (15 characters)
[Answer]
# C# (82)
```
int[] s(int n){int i,p=0;var r=new int[n];while(i<n){p+=i+i+1;r[i++]=p;}return r;}
```
[Answer]
# C# - 93
```
int[]s(int l){int[]w=new int[l];while(l>=0){int i=0;while(i<l){w[l-1]+=l;i++;}l--;}return w;}
```
When called from another method of the same class, will return the array - `[1,4,9,16,25,36...]`,
up to `l`th element.
[Answer]
**Fortran II|IV|66|77, ~~134~~ ~~122~~ ~~109~~ 105**
```
SUBROUTINES(N,M)
INTEGERM(N)
K=0
DO1I=1,N
K=K+I+I-1
1 M(I)=K
END
```
Edit: removed inner loop and used @mniip's Haskell algorithm instead.
Edit: Verified that the subroutine and driver are valid Fortran II and IV
Driver:
```
INTEGER M(100)
READ(5,3)N
IF(N)5,5,1
1 IF(N-100)2,2,5
2 CALLS(N,M)
WRITE(6,4)(M(I),I=1,N)
3 FORMAT(I3)
4 FORMAT(10I6)
STOP
5 STOP1
END
```
Result:
```
$ echo 20 | ./a.out
1 4 9 16 25 36 49 64 81 100
121 144 169 196 225 256 289 324 361 400
```
[Answer]
# Python - 51
Here I'm defining a function as requested by the rules.
Using `sum` of odd numbers:
```
f=lambda n:[sum(range(1,i+i+3,2))for i in range(n)]
```
This only uses `sum` (a builtin which performs addition) and `range` (a builtin which creates arrays using addition). If you object to `sum`, we can do this with `reduce`:
```
def g(n):v=[];reduce(lambda x,y:v.append(x) or x+y,range(1,i+i+3,2));return v
```
[Answer]
# PHP, 92 bytes
This needs to have the "short tags" option enabled, of course (to shave off 3 bytes at the start).
```
<? $x=100;$a=1;$r=0;while($r<=$x){if($r){echo"$r ";}for($i=0,$r=0;$i<$a;$i++){$r+=$a;}$a++;}
```
Output:
```
1 4 9 16 25 36 49 64 81 100
```
[Answer]
## Forth - 48 bytes
```
: f 1+ 0 do i 0 i 0 do over + loop . drop loop ;
```
Usage:
```
7 f
```
Output:
```
0 1 4 9 16 25 36 49
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 9 bytes
```
ɾ(n:+‹)W¦
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C9%BE%28n%3A%2B%E2%80%B9%29W%C2%A6&inputs=10&header=&footer=)
It could be just two bytes if everything is allowed
] |
[Question]
[
# In-between fractions
**The challenge:**
You will need to create code that takes atleast 3 inputs; 2 integers and "a fraction representation" - whichever type suits your language for representing the fraction increments) ie. If you choose string the input would be "1/4" or you could choose 2 extra integer inputs or a tuple or w/e.
Input can be anywhere reasonable (STDIN, function arguments, from a file, etc.), and so can output (STDOUT, function return value, to a file, etc.)
**Rules:**
1. The input "fraction" will always be a valid fraction, less than 1; example "1/4"
2. The second input integer will always have a higher value than the first integer. I.E the first input integer will always have a lower value than the second.
3. The input integers can be negative.
4. Outputted fractions should be reduced as much as possible (simplified)
The code will need to output every "fraction step" between the 2 numbers in increments of the input fraction.
The code should be a program or function as stated [here](http://meta.codegolf.stackexchange.com/a/2422/42503)
**Example 1:**
Input: `-2,3,"1/2"`
Output:
```
-2
-3/2
-1
-1/2
0
1/2
1
3/2
2
5/2
3
```
**Example 2:**
Input: `1,2,"2/3"`
Output:
```
1
5/3
2
```
or
```
1
4/3
2
```
Note: Counting can start from either direction (thank you @Mego)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
## Mathematica, 16 bytes
```
Range@##⋃{#2}&
```
An unnamed function that takes two integers and a rational number and returns a list of numbers, e.g.:
```
Range@##⋃{#2}&[-2, 3, 1/2]
(* {-2, -(3/2), -1, -(1/2), 0, 1/2, 1, 3/2, 2, 5/2, 3} *)
```
Mathematica's `Range` does exactly what the challenge asks, except that it omits the upper bound if the difference between lower and upper bound isn't exactly a multiple of the step size. Therefore we take the `Union` (using `⋃`) with the list containing only the upper bound which ensures that it appears exactly once. Note that `Union` will sort the result but we want it sorted anyway, since the step size is always positive. Also since we're working with rationals, they're automatically reduced as much as possible.
[Answer]
# T-SQL 2012+, ~~831~~ ~~535~~ ~~477~~ ~~270~~ ~~246~~ ~~240~~ 219 bytes
Please note this is a one liner - sql doesn't have build in function to reduce the fraction.
May not be the best language for this type of question. It is human readable(kind of - compared to some of the other languages).
```
DECLARE @f INT=-5,@t INT=3,@n INT=3,@ INT=8;
WITH C as(SELECT
top((@t*@-@f*@)/@n+1)ROW_NUMBER()OVER(ORDER BY @)M
FROM sys.messages)SELECT(SELECT
IIF(V%@=0,LEFT(V/@,9),CONCAT(V/MAX(M),'/',ABS(@)/MAX(M)))FROM c
WHERE V%M=0AND @%M=0)FROM(SELECT
@f*@+@n*~-M V FROM c)k
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1068668/in-between-fractions)**
[Answer]
## Python 2, 81 bytes
```
from fractions import*
a,b,c=map(Fraction,input())
while a<b:print a;a+=c
print b
```
[Try it online](http://ideone.com/fork/4LJrGp)
[Answer]
# Octave, ~~34~~ 30 bytes
```
@(a,b,c)rats(union([a:c:b],b))
```
Now takes the fraction as a numeric expression rather than separate numerator and denominator.
Sample on [ideone](http://ideone.com/R9JoIV)
[Answer]
# Haskell, ~~31~~ 26 bytes
```
f a b c=min[b]$a:f(a+c)b c
```
Lazy evaluation FTW! Demo:
```
*Main> import Data.Ratio
*Main Data.Ratio> f (-2) 3 (1%2)
[(-2) % 1,(-3) % 2,(-1) % 1,(-1) % 2,0 % 1,1 % 2,1 % 1,3 % 2,2 % 1,5 % 2,3 % 1]
*Main Data.Ratio> f 1 2 (2%3)
[1 % 1,5 % 3,2 % 1]
```
(I was initially tempted by Haskell’s `[a,a+c..b]` notation, but it has some quirks that necessitate something like `f a b c|l<-[a,a+c..b-c/2]=l++[b|last l<b]` for 41 bytes or `f a b c=[x|x<-[a,a+c..],x<b]++[b]` for 33.)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes
```
3$:3Gvu9X10ZGZD
```
This may fail for very large denominators. I hope output format is acceptable.
[**Try it online!**](http://matl.tryitonline.net/#code=MyQ6M0d2dTlYMTBaR1pE&input=MgoxLzI0CjM)
```
3$: % take three inputs and generate range
3G % push third input again
v % vertically concatenate. Gives vertical array as output
u % get unique elements (i.e. remove the last one if it is repeated)
9X1 % predefined literal 'rat'
0ZG % set rational format
ZD % display using that format
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~32~~ ~~54~~ 48 bytes
```
->a,b,c{(a..b).step(c){|x|p x%1>0?x:x.to_i};p b}
```
This solution is based on [Mego's Python answer](https://codegolf.stackexchange.com/a/77822/47581) and assumes that `c` will always be a `Rational`, Ruby's fraction format. [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ0knuVojUU8vSVOvuCS1QCNZs7qmoqZAoULV0M7AvsKqQq8kPz6z1rpAIan2f1q0oY6JTlBiSWZ@XmKOhpGOsWbsfwA "Ruby – Try It Online")
**Edit:** Fixed a bug where integers weren't presented like integers. -6 bytes thanks to Not That Charles and MegaTom.
The functions are called in this way:
```
> f=->a,b,c{(a..b).step(c){|x|p x%1>0?x:x.to_i};p b}
> f[1,4,Rational(2,3)]
1
(5/3)
(7/3)
3
(11/3)
4
```
[Answer]
# Julia, 14 bytes
```
f(a,b,c)=a:c:b
```
This is similar to the Mathematica answer, except that Julia's ranges are already in the desired format, so it is even shorter. Also returns a collection of numbers. Example output:
```
11-element StepRange{Rational{Int64},Rational{Int64}}:
-3//1,-5//2,-2//1,-3//2,-1//1,-1//2,0//1,1//2,1//1,3//2,2//1
```
Note that the integers are displayed with 1 in the denominator, and a double-slash is used for fractions. To get the output exactly as defined in the question requires some more code:
```
f(a,b,c)=map(x->println(x.num,x.den<2?"":"/$(x.den)"),a:c:b)
```
[Answer]
# Matlab with Symbolic Toolbox / Octave with SymPy, 27 bytes
*Thanks to @sanchises for pointing out an error, now corrected*
```
@(a,b,c)sym(union(a:c:b,b))
```
This is an anonymous function. To call it, assign it to a variable or use `ans`.
Example:
```
>> @(a,b,c)sym(union(a:c:b,b))
ans =
@(a,b,c)sym(union(a:c:b,b))
>> ans(-2,3,1/2)
ans =
[ -2, -3/2, -1, -1/2, 0, 1/2, 1, 3/2, 2, 5/2, 3]
```
[Answer]
# Javascript, ~~108 90 86~~ 81 bytes
```
(a,b,n,d)=>{var s="";for(a=a*d;a<b*d;a+=n)s+=(a%d?a+"/"+d:a/d)+" ";s+=b;return s}
```
An anonymous function. After assignment to a named variable with white space:
```
var f=(a,b,n,d)=>
{ var s="";
for(a=a*d; a<b*d; a+=n)
s+= (a%d ? a + "/" + d : a/d) + " ";
s+=b;
return s
}
```
Test examples:
```
console.log(f(1,2,1,8)); //writes:
1 9/8 10/8 11/8 12/8 13/8 14/8 15/8 2
console.log(f(-3,3,4,7)); // writes:
-3 -17/7 -13/7 -9/7 -5/7 -1/7 3/7 1 11/7 15/7 19/7 3
```
An imperative approach using javascript, no recursion, library or functional programming.
[Answer]
# Smalltalk – 89 bytes
For once Smalltalk is almost competitive!
```
Number extend[p:e q:i[|h|self to:e by:i do:[:x|h:=x. x printNl].h=e ifFalse:[e printNl]]]
```
Call like this:
```
> 2 p:5 q:1/2
2
5/2
3
7/2
4
9/2
5
> 1 p:2 q:2/3
1
5/3
2
```
[Answer]
## R - 71 bytes
Assumes you have already installed the `MASS` package
```
f=function(x,y,z)MASS::fractions(union(seq(x,y,eval(parse(text=z))),y))
> f(1, 2, '1/3')
[1] 1 4/3 5/3 2
> f(2, 5, '1/2')
[1] 2 5/2 3 7/2 4 9/2 5
```
[Answer]
## Pyret, 56 bytes
```
{(b,e,n,d):link(e,map(_ / d,range(b * d, e * d))).sort()}
```
Takes in beginning (b), end (e), numerator (n), and denominator (d). Creates a range of integers, divides those through and appends the end to the list (by linking and then sorting).
] |
[Question]
[
I once encountered this (mini) game where you had 4 or more vertical pipes that were connected by a number of horizontal pipes and you have to drop a ball or water into the vertical pipes.
There are 2 kinds I know of:
* Get the object into a bucket/basket under one of the exits (guess
what pipe to throw it in)
* Guess what pipe the object will come from.
### Sample pipes:
```
| | |-------|
|-------| |-------|
| |-------| |
|-------|-------|-------|
| |-------| |
|-------| |-------|
|-------| |-------|
| |-------| |
```
### Basic rules:
* When moving through a horizontal pipe the object will go down when
possible
* When moving through a vertical pipe the object will turn into a horizontal pipe when possible.
### Your job
* Write a program that will create a random grid of pipes(see sample
pipes).
* There should be at least 4 vertical pipes and a fair amount of horizontal pipes at least 10.
* The length of the vertical pipes is up to you.
* Show the path that the object took to reach the bottom and show how many turns it took to get there.
* (Optional) input to deterimine starting point, pipes numbered 1..N from left to right.
### Display:
```
| vertical pipe
- horizontal pipe
: vertical pipe used by the object
= horizontal pipe used by the object
V Object starting point
^ Object ending point
```
### Example:
```
V
: | |-------|
:=======: |-------|
| :=======: |
|-----!-:=======: |
| :=======:-------|
|-------| :=======:
|-------| :=======:
| :=======: |
^
14 turns were taken to get to the end.
```
**Detail**
The object enters pipe 1 and starts moving down, goes left into the first horizontal pipe.
Back down and into the second pipe followed by a U-turn into the third pipe.
At the end of the third pipe you see an exclamation mark,
shouldnt be in your result but I used this to show you the object could have gone straight ahead.
However rule number 1 prevents that.
Winner will be determined by votes in 3 weeks from now 24-02-2014 (dd-mm).
Happy coding ^.^
[Answer]
# Mathematica
The 2D code generates a graph showing the path of the water. I displayed the vertex numbers for convenient cross-checking with the 3D display. Normally the vertex numbers would be hidden.
Input:
```
r=10;c=7;
result=flow2D[{r,c},3]
```
Actually, the result contains multiple objects. The first object, `result[[1]]`, is the 2D graph shown here.

---
The 3 dimensional pipes are `Tube`'s (3D lines) plotted in 3 space. The coordinates computed based on the vertices of the 2D graph along a 3rd coordinate that was randomly generated (This allows the pipes to assume different positions along y each time the code is run.)
The axes are displayed to help the reader convince herself that the 3D rendering is indeed based on the 2D rendering.
The 3D input of interest here is:
```
Graphics3D[{CapForm[None],verticalPipes,allRungs,Darker@Red,connections},
ImageSize->600,Axes-> True,Ticks->{Range[1,2 r,2],Range[c],Range[10]},ViewPoint->{0,-2,1.5}]
```
The number or rows, columns and entry column are taken from the 2D code. They do not have to be re-entered.

## 2D Code
In the coming days I will document and tidy up the code for 2D and 3D.
```
flow2D[{rows_,columns_},startColumn_]:=
Module[{r=rows,c=columns,g,j,h,ends,middle,midcuts,direction="down",turns=0,path,rungs},
(*complete gridgraph*)
g=GridGraph[{r,c},VertexSize-> Medium,GraphStyle->"Prototype",EdgeStyle->"Thick",
VertexLabels->"Name",ImagePadding-> 30,ImageSize->470];
(*horizontal pipes that must be removed*)
ends=Table[r(c1-1)+r1\[UndirectedEdge] r(c1)+r1,{c1,1,c-1},{r1,{1,r}}];
(*horizontal pipes to consider removing *)
middle=Table[r(c1-1)+r1\[UndirectedEdge] r(c1)+r1,{c1,1,c-1},{r1,2,r-1}];
midcuts=RandomSample[#,RandomInteger[Round[{r/15,2r/5}]]]&/@middle;
rungs=Flatten[midcuts(*Join[ends,midcuts]*)];
j=EdgeDelete[g,Flatten[Join[ends,midcuts]]];
h[path_]:= Module[{start=path[[-1]],right,left,up,down,newnodes},
{v=NeighborhoodGraph[j,start,1,(*VertexLabels\[Rule]"Name",*)ImagePadding->25],
VertexList[v]};newnodes=Complement[VertexList[v],path];
If[newnodes=={},path,
h[Append[path,
Switch[direction,
"down",Which[
MemberQ[newnodes,start+r],(turns++;direction="right";start+r),
MemberQ[newnodes,start-r],(turns++;direction="left";start-r),
MemberQ[newnodes,start-1],start-1],
"right",Which[
MemberQ[newnodes,start-1],(turns++;direction="down";start-1),
MemberQ[newnodes,start+r],start+r],
"left",Which[
MemberQ[newnodes,start-1],(turns++;direction="down";start-1),
MemberQ[newnodes,start-r],start-r]
]]]]];
{HighlightGraph[j,path=h[{r*startColumn}],ImageSize->300],path,rungs,ends,midcuts}]
convert[node_,r_,c_]:=Append[footing[[Quotient[node-1,r]+1]],Mod[node-1,r]+1(*Mod[node,r]*)]
connect[a_\[UndirectedEdge]b_,r_,c_]:=Tube[Line[{convert[a,r,c],convert[b,r,c]}],0.2]
```
# 3D Code and results
```
r=10;c=7;
result=flow2D[{r,c},3];
g2D=result[[1]];
path2D=result[[2]];
\[AliasDelimiter]
xScale=2;
footing = {#, RandomInteger[{1, 6}]} & /@ Range[1,xScale c, xScale];
verticalPipes=Tube[Line[{Append[#,1],Append[#,r]}],.19]&/@footing;
Graphics3D[{CapForm[None],verticalPipes},ImageSize->600,Axes->True,AxesEdge->Automatic,ViewPoint->{0,-2,1.5},
Ticks->{Range[1,2 r,2],Range[c],Range[10]}];
path3D=UndirectedEdge@@@Partition[Riffle[stops=path2D,Rest@stops],2];
allRungs=connect[#,r,c]&/@rungs;
connections=connect[#,r,c]&/@path3D;
path2D;
g2D
Graphics3D[{CapForm[None],verticalPipes,allRungs,Darker@Red,connections},
ImageSize->600,Axes-> True,Ticks->{Range[1,2 r,2],Range[c],Range[10]},ViewPoint->{0,-2,1.5}]
```
[Answer]
# C#
*(via LINQPad, in "C# Program" mode; )*
Going to have to apply Equitable Stroke Control, as far as any golfing might go, but this is my approach in C# *(well, LINQPad, but who wants all the boilerplate that goes into making a full C# app work?)*.
Grid definitions are variable, with a number of vertical pipes and height of overall structure, and are repeatably-random by passing a seed (see the `PipeGrid` constructor).
In the absence of a definitive answer as to which way the object would flow if either direction was possible, I have allowed you to specify a behaviour from a number of options (see `SolveBehavior` enumeration / `PipeSolver` constructor).
Starting vertical is definable (see `PipeSolver.Solve`).
I have assumed that the horizontal pipes are always between two *adjacent* vertical pipes, i.e. no horizontal can bypass a horizontal pipe.
```
///<summary>Entry point</summary>
void Main()
{
var grid = new PipeGrid(vertical:10, height:10, seed:5);
var solver = new PipeSolver(grid, SolveBehavior.FlipFlop);
solver.Solve(start:2);
}
///<summary>Represents the direction the object is travelling</summary>
enum Direction
{
Down = 0,
Left = 1,
Right = 2
}
///<summary>Determines the route to take if a junction yields both horizontal directions</summary>
enum SolveBehavior
{
///<summary>Throws an <see cref="InvalidOperationException" /></summary>
Fail = 0,
///<summary>Prefers the left-most direction (screen-relative)</summary>
FavorLeft = 1,
///<summary>Prefers the right-most direction (screen-relative)</summary>
FavorRight = 2,
///<summary>Alternates preferred direction, based on the number of turns</summary>
FlipFlop = 3,
///<summary>Prefers the same direction the object travelled, on its last horizontal movement</summary>
SameDirection = 4,
///<summary>Prefers the opposite direction the object travelled, on its last horizontal movement</summary>
Uturn = 5
}
///<summary>Provides the logic for solving a <see cref="PipeGrid" /></summmary>
class PipeSolver
{
///<summary>Creates a new <see cref="PipeSolver" /> for the supplied <paramref name="grid" />,
///with the given <paramref name="behavior" /> used to resolve junctions with both horizontal
///paths</summary>
public PipeSolver(PipeGrid grid, SolveBehavior behavior = SolveBehavior.FlipFlop)
{
if (grid == null) throw new ArgumentNullException("grid");
_grid = grid;
_behavior = behavior;
}
private readonly PipeGrid _grid;
private readonly SolveBehavior _behavior;
///<summary>Simulate the dropping of an object to run through the grid, at the top of a
///given <paramref name="start" /> vertical pipe</summary>
public void Solve(int start = 1, bool dumpFrames = false, string tag = "Result")
{
if (start < 1) start = 1;
if (start > _grid.Verticals) start = _grid.Verticals;
int x, y;
Direction?[,] path = new Direction?[_grid.Width, _grid.Height];
x = (start - 1) * 2;
y = 0;
Direction dir = Direction.Down, lastDir = Direction.Down;
int turns = 0;
do
{
path[x, y] = dir; // we moved through this pipe
// rule 1: when moving through horizontal pipe, object will go down when possible
if ((dir == Direction.Left || dir == Direction.Right) && (x % 2 == 0))
{
lastDir = dir;
dir = Direction.Down;
++turns;
}
// rule 2: when moving through start pipe, object will turn into horizontal pipe when possible
else if (dir == Direction.Down)
{
bool hasLeft = (x > 0 && _grid[x - 1, y]);
bool hasRight = (x < _grid.Width - 1 && _grid[x + 1, y]);
if (hasLeft && hasRight)
{
switch (_behavior)
{
case SolveBehavior.FavorLeft:
hasRight = false; // "forget" about right pipe
break;
case SolveBehavior.FavorRight:
hasLeft = false; // "forget" about left pipe
break;
case SolveBehavior.FlipFlop:
if (turns % 2 == 0) hasLeft = false;
else hasRight = false; // "forget" about left on the even moves, or right on the odd moves
break;
case SolveBehavior.SameDirection: // force staying in the same direction
if (lastDir == Direction.Left) hasRight = false;
else if (lastDir == Direction.Right) hasLeft = false;
else goto case SolveBehavior.FlipFlop; // use the flip-flop behaviour to determine first turn
break;
case SolveBehavior.Uturn: // force turning back on itself
if (lastDir == Direction.Left) hasLeft = false;
else if (lastDir == Direction.Right) hasRight = false;
else goto case SolveBehavior.FlipFlop; // use the flip-flop behaviour to determine first turn
break;
default: throw new InvalidOperationException(
"Failed to find distinct path, with no resolving behavior defined"
);
}
}
if (hasLeft) dir = Direction.Left;
else if (hasRight) dir = Direction.Right;
if (hasLeft || hasRight) ++turns;
}
switch (dir) // update position, based on current direction
{
case Direction.Left: if (x > 0) --x; break;
case Direction.Right: if (x < _grid.Width - 1) ++x; break;
default: ++y; break;
}
if (dumpFrames)
{
DumpFrame(path, start, tag:string.Concat("Frame #", turns, " (", _grid.Seed, ")"));
DrawFrame(path, start, tag:string.Concat("Frame #", turns));
}
}
while (y < _grid.Height);
int end = (x / 2) + 1;
DumpFrame(path, start, end, turns, tag);
DrawFrame(path, start, end, turns, tag);
}
///<summary>Internal method for drawing a given frame</summary>
private void DumpFrame(Direction?[,] path, int start, int? end = null, int? turns = null, string tag = null)
{
var builder = new StringBuilder();
builder.Append(' ', --start * 5).AppendLine("v");
for (int y = 0; y < _grid.Height; y++)
{
for (int x = 0; x < _grid.Width; x++)
{
builder.Append(
(x % 2 == 0)
? path[x, y].HasValue ? ":" : _grid[x, y] ? "|" : " "
: path[x, y].HasValue ? "====" : _grid[x, y] ? "----" : " "
);
}
builder.AppendLine();
}
if (end.HasValue) builder.Append(' ', (end.Value - 1) * 5).AppendLine("^");
if (turns.HasValue) builder.Append(turns.Value)
.Append(" turns were taken to get to ")
.AppendLine(end.HasValue ? "the end." : "this point.");
builder.ToString().Dump(string.IsNullOrWhiteSpace(tag) ? "Frame" : tag);
}
///<summary>Internal method for rendering a frame as a bitmap</summary>
private void DrawFrame(Direction?[,] path, int start, int? end = null, int? turns = null, string tag = null)
{
using (var sprites = new Sprites())
using (var canvas = new Bitmap(16 * _grid.Width, 16 * (_grid.Height + 3)))
using (var graphics = Graphics.FromImage(canvas))
{
graphics.FillRectangle(Brushes.Green, 0, 16, 16 * _grid.Width, 16 * _grid.Height);
_grid.Draw(graphics, sprites, offsetX:0, offsetY:16);
// draw the start position
start = (start - 1) * 32;
graphics.DrawImageUnscaled(sprites.RoadVertical, start, 0);
graphics.DrawImageUnscaled(sprites.CarVertical, start, 0);
graphics.DrawImageUnscaled(sprites.StartFlag, start, 0);
// draw the path
for (int y = 0; y < _grid.Height; y++)
for (int x = 0; x < _grid.Width; x++)
{
if (path[x, y].HasValue)
{
Image car;
switch (path[x, y])
{
case Direction.Left:
// if even, then on a vertical, so turning left; otherwise travelling left
car = (x % 2 == 0) ? sprites.CarTurnLeft : sprites.CarLeft;
break;
case Direction.Right:
// if even, then on a vertical, so turning right; otherwise travelling right
car = (x % 2 == 0) ? sprites.CarTurnRight: sprites.CarRight;
break;
default:
car = sprites.CarVertical;
if (x == 0 && path[x + 1, y].HasValue) // far-left and will move right = turn-right
car = sprites.CarTurnRight;
else if (x == _grid.Width - 1 && path[x - 1, y].HasValue) // far-right and will move left = turn-left
car = sprites.CarTurnLeft;
else if (x > 0 && x < _grid.Width - 1)
{
car = sprites.CarVertical; // if not right or left, then down
if (path[x + 1, y].HasValue && !path[x - 1, y].HasValue) // if came from the left, then turn right
car = sprites.CarTurnRight;
else if (path[x - 1, y].HasValue && !path[x + 1, y].HasValue) // if came from the right, then turn left
car = sprites.CarTurnLeft;
}
break;
}
graphics.DrawImageUnscaled(car, 16 * x, 16 * (y + 1));
}
}
// draw the end position, if we are at the end
if (end.HasValue)
{
end = (end - 1) * 32;
graphics.DrawImageUnscaled(sprites.RoadVertical, end.Value, 16 * (_grid.Height + 1));
graphics.DrawImageUnscaled(sprites.CarVertical, end.Value, 16 * (_grid.Height + 1));
graphics.DrawImageUnscaled(sprites.EndFlag, end.Value, 16 * (_grid.Height + 1));
}
if (turns.HasValue)
{
string s = string.Concat(turns.Value, " turns were taken to get to ",
end.HasValue ? "the end." : "this point.");
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
graphics.DrawString(s, SystemFonts.DefaultFont, Brushes.Black, 0, 16 * (_grid.Height + 2));
}
canvas.Dump(tag ?? "Bonus");
}
}
}
///<summary>Represents a configuration of pipes</summary>
class PipeGrid
{
///<summary>Creates a new <see cref="PipeGrid" />, of a given <paramref name="height" />
///with the given number of <paramref name="vertical" /> pipes, and randomly distributes
///horizontal pipes between them, based on a repeatable <paramref name="seed" />.</summary>
public PipeGrid(int vertical = 4, int height = 8, int? seed = null)
{
if (vertical < 2) vertical = 2;
if (height < 2) height = 2;
Width = (2 * vertical) - 1;
Height = height;
Verticals = vertical;
Seed = seed ?? Environment.TickCount;
var rnd = new Random(Seed);
_nodes = new bool[Width,Height];
for (int x = 0, xw = Width; x < xw; x++)
for (int y = 0; y < height; y++)
{
// place verticals in every even column, and randomly place horizontals in odd columns
if (x % 2 == 0 || rnd.Next(0, 2) == 1)
_nodes[x, y] = true;
}
}
private readonly bool[,] _nodes;
public int Width { get; private set; }
public int Height { get; private set; }
public int Verticals { get; private set; }
public int Seed { get; private set; }
public bool this[int x, int y] { get { return _nodes[x, y]; } }
///<summary>Renders the grid to the LINQPad results pane, for inspection</summary>
public PipeGrid Dump(string tag = null)
{
var builder = new StringBuilder();
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
builder.Append(
(x % 2 == 0)
? _nodes[x, y] ? "|" : " "
: _nodes[x, y] ? "----" : " "
);
}
builder.AppendLine();
}
builder.ToString().Dump(string.IsNullOrWhiteSpace(tag) ? "Grid" : tag);
return this;
}
///<summary>Render the grid as a bitmap image</summary>
public void Draw(Graphics g, Sprites s, int offsetX = 0, int offsetY = 0)
{
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
if (_nodes[x, y])
{
Image sprite = sprite = s.RoadVertical;
if (x % 2 != 0)
sprite = s.RoadHorizontal;
else if (x == 0 && _nodes[1, y])
sprite = s.JunctionTeeRight;
else if (x == Width - 1 && _nodes[x - 1, y])
sprite = s.JunctionTeeLeft;
else if (x > 0 && x < Width - 1)
{
if (_nodes[x - 1, y] && _nodes[x + 1, y])
sprite = s.JunctionCross;
else if (_nodes[x + 1, y] && !_nodes[x - 1, y])
sprite = s.JunctionTeeRight;
else if (_nodes[x - 1, y] && !_nodes[x + 1, y])
sprite = s.JunctionTeeLeft;
}
g.DrawImageUnscaled(sprite,
x:(16 * x) + offsetX,
y:(16 * y) + offsetY);
}
}
}
}
///<summary>Creates a <see cref="PipeGrid" /> with horizontal pipes at all possible positions</summary>
public static PipeGrid CreateAllOpen(int verticals = 4, int height = 8)
{
var grid = new PipeGrid(verticals, height, 0);
for (int y = 0; y < height; y++)
for (int x = 0, xw = grid.Width; x < xw; x++)
grid._nodes[x, y] = true;
return grid;
}
}
///<summary>Store tile sprites, to be used in the graphical rendering of the result</summary>
class Sprites : IDisposable
{
public Sprites()
{
byte[,] car = new byte[,] {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 3, 1, 1, 1, 1, 1, 1, 3, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 3, 1, 1, 1, 1, 1, 1, 3, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 3, 1, 1, 1, 1, 1, 1, 3, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 3, 1, 1, 1, 1, 1, 1, 3, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 3, 1, 1, 1, 1, 1, 1, 3, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1, 0, 0, 0 },
{ 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0 },
{ 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
};
byte[,] road = new byte[,] {
{ 0, 6, 2, 2, 2, 2, 2, 6, 6, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 6, 6, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 6, 6, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 6, 6, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 6, 6, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 6, 6, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 6, 6, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 6, 6, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 6, 6, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 6, 6, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 6, 6, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 6, 6, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 0 },
};
byte[,] roadNESW = new byte[,] {
{ 0, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 0 },
{ 6, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 6 },
{ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 },
{ 2, 2, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 2 },
{ 2, 2, 2, 2, 5, 5, 2, 5, 5, 2, 5, 5, 2, 2, 2, 2 },
{ 2, 2, 2, 2, 5, 5, 2, 5, 5, 2, 5, 5, 2, 2, 2, 2 },
{ 2, 2, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 2 },
{ 2, 2, 2, 2, 5, 5, 2, 5, 5, 2, 5, 5, 2, 2, 2, 2 },
{ 2, 2, 2, 2, 5, 5, 2, 5, 5, 2, 5, 5, 2, 2, 2, 2 },
{ 2, 2, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 2 },
{ 2, 2, 2, 2, 5, 5, 2, 5, 5, 2, 5, 5, 2, 2, 2, 2 },
{ 2, 2, 2, 2, 5, 5, 2, 5, 5, 2, 5, 5, 2, 2, 2, 2 },
{ 2, 2, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 2 },
{ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 },
{ 6, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 6 },
{ 0, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 0 },
};
byte[,] roadNES = new byte[,] {
{ 0, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 0 },
{ 0, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 6 },
{ 0, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 },
{ 0, 6, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 2 },
{ 0, 6, 2, 2, 5, 5, 2, 5, 5, 2, 5, 5, 2, 2, 2, 2 },
{ 0, 6, 2, 2, 5, 5, 2, 5, 5, 2, 5, 5, 2, 2, 2, 2 },
{ 0, 6, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 2 },
{ 0, 6, 2, 2, 5, 5, 2, 5, 5, 2, 5, 5, 2, 2, 2, 2 },
{ 0, 6, 2, 2, 5, 5, 2, 5, 5, 2, 5, 5, 2, 2, 2, 2 },
{ 0, 6, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 2 },
{ 0, 6, 2, 2, 5, 5, 2, 5, 5, 2, 5, 5, 2, 2, 2, 2 },
{ 0, 6, 2, 2, 5, 5, 2, 5, 5, 2, 5, 5, 2, 2, 2, 2 },
{ 0, 6, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 5, 2, 2, 2 },
{ 0, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 },
{ 0, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 6 },
{ 0, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 0 },
};
byte[,] start = new byte[,] {
{ 0, 0, 1, 1, 1, 0, 4, 4, 4, 0, 0, 0, 4, 0, 0, 0 },
{ 0, 0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0 },
{ 0, 0, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0 },
{ 0, 0, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0 },
{ 0, 0, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0 },
{ 0, 0, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0 },
{ 0, 0, 1, 4, 4, 4, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
};
byte[,] end = new byte[,] {
{ 0, 0, 1, 1, 1, 0, 1, 1, 6, 0, 0, 0, 6, 0, 0, 0 },
{ 0, 0, 1, 6, 6, 6, 1, 1, 6, 6, 1, 1, 6, 0, 0, 0 },
{ 0, 0, 1, 1, 6, 6, 6, 6, 1, 6, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 1, 6, 6, 1, 1, 6, 6, 1, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 1, 1, 1, 6, 1, 6, 6, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 6, 6, 1, 1, 6, 6, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 6, 6, 6, 6, 1, 6, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 1, 6, 6, 1, 1, 6, 6, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 6, 6, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
};
RoadVertical = Sprite(road);
RoadHorizontal = RotateSprite(RoadVertical, 90);
JunctionCross = Sprite(roadNESW);
JunctionTeeRight = Sprite(roadNES);
JunctionTeeLeft = FlipSprite(JunctionTeeRight, horizontal:true);
CarVertical = Sprite(car);
CarLeft = RotateSprite(CarVertical, 90);
CarRight = FlipSprite(CarLeft, horizontal:true);
CarTurnLeft = RotateSprite(CarVertical, 45);
CarTurnRight = FlipSprite(CarTurnLeft, horizontal:true);
StartFlag = Sprite(start);
EndFlag = Sprite(end);
}
public Image RoadVertical { get; private set; }
public Image RoadHorizontal { get; private set; }
public Image JunctionCross { get; private set; }
public Image JunctionTeeLeft { get; private set; }
public Image JunctionTeeRight { get; private set; }
public Image CarVertical { get; private set; }
public Image CarLeft { get; private set; }
public Image CarRight { get; private set; }
public Image CarTurnLeft { get; private set; }
public Image CarTurnRight { get; private set; }
public Image StartFlag { get; private set; }
public Image EndFlag { get; private set; }
///<summary>Create a sprite from the byte data</summary>
private Image Sprite(byte[,] data)
{
int width = data.GetLength(0);
int height = data.GetLength(1);
var image = new Bitmap(width, height);
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
Color c;
switch (data[y,x])
{
case 1: c = Color.Black; break;
case 2: c = Color.DarkGray; break;
case 3: c = Color.Red; break;
case 4: c = Color.LimeGreen; break;
case 5: c = Color.Yellow; break;
case 6: c = Color.White; break;
default: continue;
}
image.SetPixel(x, y, c);
}
return image;
}
///<summary>Rotate an image by a number of <paramref name="degrees" /> around the centre</summary>
private Image RotateSprite(Image source, float deg)
{
var b = new Bitmap(source.Width, source.Height);
using (var g = Graphics.FromImage(b))
{
float tx = (float)source.Width / 2.0f;
float ty = (float)source.Height / 2.0f;
g.TranslateTransform(tx, ty);
g.RotateTransform(deg);
g.TranslateTransform(-tx, -ty);
g.DrawImageUnscaled(source, 0, 0);
}
return b;
}
///<summary>Flip an image about its centre</summary>
private Image FlipSprite(Image source, bool horizontal = false, bool vertical = false)
{
var b = new Bitmap(source);
RotateFlipType rft = ( horizontal && vertical) ? RotateFlipType.RotateNoneFlipXY
: ( horizontal && !vertical) ? RotateFlipType.RotateNoneFlipX
: (!horizontal && vertical) ? RotateFlipType.RotateNoneFlipY
: RotateFlipType.RotateNoneFlipNone;
b.RotateFlip(rft);
return b;
}
#region IDisposable implementation
public void Dispose() { Dispose(true); }
~Sprites() { Dispose(false); }
protected void Dispose(bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
using (RoadVertical) { }
using (RoadHorizontal) { }
using (JunctionCross) { }
using (JunctionTeeLeft) { }
using (JunctionTeeRight) { }
using (CarVertical) { }
using (CarLeft) { }
using (CarRight) { }
using (CarTurnLeft) { }
using (CarTurnRight) { }
using (StartFlag) { }
using (EndFlag) { };
}
RoadVertical = null;
RoadHorizontal = null;
JunctionCross = null;
JunctionTeeLeft = null;
JunctionTeeRight = null;
CarVertical = null;
CarLeft = null;
CarRight = null;
CarTurnLeft = null;
CarTurnRight = null;
StartFlag = null;
EndFlag = null;
}
#endregion
}
```
## Update:
Fearing my plain old text output might be a little drab for this popularity context, I offer up an extended version that *also* draws the path taken as an image. I've modelled it as car, driving through a horrible road network, trying to get to the bottom, but with the world's-worst GPS that forces you to make a turn at every junction.
As a bonus, this also makes it clearer to see the 'turns'.
Enjoy -- *vroom vroom!!*
## Example results:
*(verticals: 10, height: 10, random seed:5, start pipe: 2, solve behaviour: FlipFlop})*

[Answer]
## C#
Fun times! :-)
This code ensures there is at least some straight pipe at either end of each pipe. It also ensures there are no ambiguous turns.
```
using System;
namespace Experiment.DownTheDrain
{
class Program
{
static void Main(string[] args)
{
var program = new Program();
program.Width = 19;
program.Height = 17;
program.SpanCount = program.Width * program.Height / 4;
program.Spacing = 3;
program.Run();
}
public int Width { get; set; }
public int Height { get; set; }
public int SpanCount { get; set; }
public int Spacing { get; set; }
public bool[,] Spans { get; private set; }
public void Run()
{
GenerateSpans();
DrawPipes();
var pipe = ReadStartPipe();
var turns = DrawPath(pipe);
WriteTurns(turns);
Console.ReadLine();
}
private void GenerateSpans()
{
Random random = new Random();
Spans = new bool[Width, Height];
int x, y;
for (int i = 0; i < SpanCount; i++)
{
do
{
x = random.Next(Width);
y = random.Next(Height);
}
while (SpanAt(x - 1, y) || SpanAt(x, y) || SpanAt(x + 1, y));
Spans[x, y] = true;
}
}
private void DrawPipes()
{
const string Junction = "│┤├┼";
Console.CursorLeft = 0;
Console.CursorTop = 0;
DrawLabels();
for (int y = -1; y <= Height; y++)
{
for (int x = 0; x <= Width; x++)
{
Console.Write(Junction[(SpanAt(x-1,y) ? 1 : 0) + (SpanAt(x,y) ? 2 : 0)]);
Console.Write(x == Width ? Environment.NewLine : new string(SpanAt(x, y) ? '─' : ' ', Spacing));
}
}
DrawLabels();
}
private void DrawLabels()
{
for (int x = 0; x <= Width; x++)
Console.Write("{0}{1}",
(char)(x + 65),
x == Width ? Environment.NewLine : new string(' ', Spacing)
);
}
private int ReadStartPipe()
{
Console.WriteLine();
Console.Write("Please select a start pipe: ");
int pipe;
do
{
var key = Console.ReadKey(true);
pipe = (int)char.ToUpper(key.KeyChar) - 65;
}
while (pipe < 0 || pipe > Width);
Console.WriteLine((char)(pipe + 65));
return pipe;
}
private int DrawPath(int x)
{
int turns = 0;
Console.CursorTop = 1;
for (int y = -1; y <= Height; y++)
{
if (SpanAt(x - 1, y))
{
x--;
Console.CursorLeft = x * (Spacing + 1);
Console.WriteLine("╔{0}╝", new string('═', Spacing));
turns += 2;
}
else if (SpanAt(x, y))
{
Console.CursorLeft = x * (Spacing + 1);
Console.WriteLine("╚{0}╗", new string('═', Spacing));
x++;
turns += 2;
}
else
{
Console.CursorLeft = x * (Spacing + 1);
Console.WriteLine("║");
}
}
return turns;
}
private void WriteTurns(int turns)
{
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("{0} turns taken to reach the bottom.", turns);
}
private bool SpanAt(int x, int y)
{
return x >= 0
&& x < Width
&& y >= 0
&& y < Height
&& Spans[x, y];
}
}
}
```
Output:

[Answer]
# [Funciton](http://esolangs.org/wiki/Funciton)
As if Funciton wasn’t already among the most pointless languages in the world, this is certainly the most useless program I’ve written in it so far.
Since this looks ugly in StackExchange due to the extra line spacing, consider running the following in your browser’s JavaScript console to fix that:
>
> `$('pre').each(function(){$(this).css('line-height',1)})`
>
>
>
Since Funciton doesn’t have a random number generator, I decided to let you enter the pipe pattern. Since the pattern encoding is unobvious, banging the digit keys on your keyboard randomly is as good as a random number generator.
The input is expected to be three decimal numbers separated by spaces. The first number is the width (one less than the number of vertical pipes); the second is the index of the starting pipe, and the last is any number that encodes the horizontal pipe pattern; you can make it as large as you want. If the width is negative or the pipe index is out of range, the output is `Impossiburu.`
The program automatically ensures that there are never two horizontal pipes next to each other, which could cause ambiguous turns.
```
┌───╖
┌────────────┤ ♯ ╟───────────┬───────────────┐
╔════╗ ┌─┴─╖ ┌────╖ ╘═══╝ ╔═══╗ ┌─┴─╖ ╔════╗ │
║ 21 ║ │ × ╟──┤ >> ╟─────────╢ ╟──┤ ʘ ╟──╢ 32 ║ │
╚═╤══╝ ╘═╤═╝ ╘═╤══╝ ╚═══╝ ╘═══╝ ╚════╝ │
└───────┘ ┌───┴───┐ │
╔════╗ ┌───╖ │ ┌───┴──────────────────┐ │
║ 32 ╟──┤ ʘ ╟──┘ │ ╔═══╗ │ │
╚════╝ ╘═╤═╝ ┌─┴─╖ ║ 0 ╟───┐ │ │
┌───────┴──────┤ · ╟────┐ ╚═══╝ ┌─┴─╖ │ │
│ ╘═╤═╝ └─────────┤ ʃ ╟─┘ │
│ ┌──────────┘ ╘═╤═╝ │
┌─┴─╖ ┌─┴──╖ ┌─────────╖ ┌────┴────╖ │
│ ♯ ║ │ >> ╟──┤ str→int ╟────┐ │ str→int ║ │
╘═╤═╝ ╘═╤══╝ ╘═════════╝ ┌─┴─╖ ╘════╤════╝ ┌─┴─╖
│ ┌─┴─╖ ╔════╗ │ ░ ║ ┌──┴────────────────┤ · ╟────────────┐
└───┤ × ╟─╢ 21 ║ ╘═╤═╝ ┌─┴─╖ ╘═╤═╝ │
╘═══╝ ╚════╝┌─────┐ └───┤ ▒ ╟───┐ ┌─────────╖ ┌─┴─╖ │
┌─────────╖ ┌─┴─╖ │ ╘═╤═╝ ├─┤ str→int ╟─┤ ʃ ╟─┐ │
┌──┤ int→str ╟──┤ · ╟─┐ └──────────┘ │ ╘═════════╝ ╘═╤═╝ │ │
│ ╘═════════╝ ╘═╤═╝ │ ╔══════════════╗ │ ╔═══╗ ┌──────┘ │ │
│ ╔══════════╗ ┌─┴─╖ │ ║ 158740358500 ║ │ ║ ╟──┘ ┌───╖ ╔═╧═╗ ┌───╖ │
│ ║ 20971533 ╟──┤ ╟─┘ ║ 305622435610 ║ │ ╚═══╝ ┌─┤ ≤ ╟──╢ 0 ╟──┤ ≥ ╟─┴─┐
│ ╚════╤═════╝ └─┬─╜ ║ 491689778976 ║ └────────┤ ╘═╤═╝ ╚═══╝ ╘═╤═╝ │
│ ┌─┴─╖ ┌───╖ │ ║ 886507240727 ║ │ └──────┬──────┘ │
│ │ ‼ ╟──┤ ‼ ╟─┘ ║ 896192890374 ║ │ ┌┴┐ │
│ ╘═╤═╝ ╘═╤═╝ ║ 899130957897 ╟───┐ │ └┬┘ │
└──────┘ ┌─┴─╖ ╚══════════════╝ ┌─┴─╖ ┌─┴─╖ │ │
│ ‼ ╟────────────────────────┤ ? ╟──┤ · ╟────────┤ │
╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ┌─┴─╖ │
╔═══════════════╧════════════════════════╗ │ └────────┤ ≥ ╟──────────┘
║ 83139057126481738391428729850811584337 ║ ┌────╖ ╘═══╝
║ 75842912478026089564602018574355013746 ║ ┌────┤ >> ╟──┐
║ 85373033606532129933858395805642598753 ║ │ ╘══╤═╝ │
║ 19381927245726769973108298347355345088 ║ │ ┌─┴─╖ │ ╓───╖
║ 84932603219463911206052446527634696060 ║ │ │ ░ ║ │ ║ ░ ║
║ 230797436494578049782495796264992 ║ │ ╘═╤═╝ │ ╙─┬─╜
╚════════════════════════════════════════╝ │ ┌──┴──┐ └─────────┴────────┐
│ │ ┌─┴──╖ ┌┐ ┌┐ │
│ │ │ << ╟─┤├─┬─┤├─────┐ │
┌────╖ ╔═══╗ │ │ ╘═╤══╝ └┘ │ └┘ ╔═╧═╗ │
┌─┤ << ╟──╢ 1 ║ │ │ ╔═╧═╗ │ ║ 1 ║ │
│ ╘═╤══╝ ╚═══╝ ┌───────────────────┐ │ │ ║ 2 ║ │ ╚═╤═╝ │
│ └─────┬──────────┴─────────┐ │ │ ┌──┴─╖ ╚═══╝ ┌─┴─╖ ┌┐ │ │
│ │ ┌───┐ ┌─┴─╖ │ │ │ << ╟─────────┤ ? ╟─┤├───┤ │
│ │ │ ├──┤ · ╟─┐ │ │ ╘══╤═╝ ╘═╤═╝ └┘ ├───┘
│ ┌───┐ ┌─┴─╖ ┌───╖ └─┬─┘ ╘═╤═╝ ├───┐ │ │ ╔═╧═╗ ╔═══╗ ┌─┴─╖ │
├─┤ ├─┤ · ╟─┤ ♯ ╟─────┘ ┌─┴─╖ │ │ │ └──╢ 1 ║ ║ 0 ╟──┤ ? ╟──────┘
│ └───┘ ╘═╤═╝ ╘═══╝ ┌───────┤ · ╟─┴─┐ │ │ ╚═══╝ ╚═══╝ ╘═╤═╝
│ ┌─┴─╖ ┌─┴─╖ ╘═╤═╝ │ │ └─────────────────┐ │
│ ┌────┤ · ╟──────┤ · ╟──┐ │ │ └────────┐ │
│ │ ╘═╤═╝ ╘═╤═╝ │ │ └────┐ │ │
│ └───┬──┴──┐ │ │ │ ┌─┴──╖ │ │
│ │ ┌┴┐ │ │ └─────┬──┤ << ║ │ │
│ │ └┬┘ │ │ ┌┴┐ ╘═╤══╝ │ │
│ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ │ └┬┘ ╔═╧═╗ │ │
└────┤ · ╟─┤ ? ╟─┐ │ ♯ ║ ├──────────┤ ║ 1 ║ │ │
╘═╤═╝ ╘═╤═╝ │ ╘═╤═╝ ┌┴┐ │ ╚═══╝ │ │
│ │ │ ┌─┴─╖ └┬┘ │ │ │
│ │ └─┤ ? ╟──┘ ┌─┴─╖ │ │
│ │ ╘═╤═╝ ┌─────┤ > ╟─────┬──┘ │
│ │ ┌─┴─╖ ┌─┴─╖ ╘═══╝ ├─────────┐ │
┌─┴─╖ └─────┤ · ╟───┤ · ╟─────────────┘ │ │
┌─┤ · ╟─────┐ ╘═╤═╝ ╘═╤═╝ │ │
│ ╘═╤═╝ ┌──┴─╖ ┌─┴─╖ │ │ │
│ │ │ >> ╟─┤ ▒ ╟──┐ ├─────────────┐ ┌─┴─╖ │
│ │ ╘══╤═╝ ╘═╤═╝ ├──┘ │ ╓───╖ ┌─┤ · ╟─┤
│ │ │ ┌─┴─╖ │ ├─╢ ▒ ╟─┤ ╘═╤═╝ │
│ │ └───┤ · ╟──┘ │ ╙─┬─╜ │ │ │
│ │ ╘═╤═╝ │ │ ┌─┴─╖ │ │
│ │ ┌─┴─╖ │ └─┤ · ╟─┤ │
│ │ ┌──┤ ╟────────────┐ │ ╘═╤═╝ │ │
│ │ │ └─┬─╜ ┌───╖ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ │ │
│ └──────┐ │ └────┤ ‼ ╟───┤ · ╟──┤ · ╟───┤ ▓ ╟─┘ │
│ │ │ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │
│ │ │ ╔═══╗ ┌─┴─╖ │ └───────┘ │
│ │ └──╢ 0 ╟──┤ ? ╟─┐ │ │
│ │ ╚═══╝ ╘═╤═╝ │ ┌─┴─╖ │
│ ╔═══╗ │ ┌─┴─╖ ├─┤ · ╟─┐ │
│ ║ 2 ║ │ ┌────┤ · ╟─┘ ╘═╤═╝ ├──────────────────┘
│ ╚═╤═╝ │ │ ╘═╤═╝ │ │
│ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ╔═╧═╕ ┌─┐ │ │
│ │ + ╟──┤ ? ╟──┤ ? ╟──╢ ├─┴─┘ │ │
│ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╚═╤═╛ │ │
│ └──┬───┘ ╔═╧═╗ │ │ │
│ │ ║ 0 ║ │ │
│ │ ╚═══╝ │ │
│ └─────────────────────────┘ │
└────────────────────────────────────┘ ╓┬──╖
┌────────────────────────────────────────────────╫┘▓ ╟────────────┐
│ ╔═══════════╗ ╔════════════════════╗ ╙─┬─╜ │
│ ║ 387759291 ║ ║ 385690484238253342 ║ │ │
│ ║ 565251600 ║ ┌───╢ 839653020379129116 ║ │ ┌────┐ │
│ ║ 199735775 ║ ┌─┴─╖ ╚════════════════════╝ │ │ ┌┴┐ │
│ ║ 904933210 ╟──┤ ? ╟────────────────┐ │ │ └┬┘ │
│ ╚═══════════╝ ╘═╤═╝ ┌──────┐ ├────────────┴────┘ ┌─┴─╖ │
│ ╔═══════════╗ ┌─┴─╖ ┌─┴─╖ ╔═╧═╗ │ ╔════╗ ╔═══╗ │ ♯ ║ │
│ ║ 388002680 ╟──┤ ? ╟──┤ ≠ ║ ║ 1 ║ │ ║ 21 ║ ┌─╢ 1 ║ ╘═╤═╝ │
│ ║ 480495420 ║ ╘═╤═╝ ╘═╤═╝ ╚═══╝ │ ╚═╤══╝ │ ╚═══╝ ┌┴┐ │
│ ║ 244823142 ║ │ ├───────────┘ │ │ └┬┘ │
│ ║ 920365396 ║ │ ┌─┴─╖ ┌───╖ ┌─┴──╖ │ ┌────╖ ┌─┴─╖ │
│ ╚═══════════╝ └────┤ · ╟──┤ ‡ ╟─────┤ >> ║ └─┤ >> ╟──┤ · ╟──┴─┐
│ ╔═══════════╗ ┌───┐ ╘═╤═╝ ╘═╤═╝ ╘═╤══╝ ╘═╤══╝ ╘═╤═╝ │
│ ║ 618970314 ╟─┘ ┌─┴─╖ ┌─┘ │ │ ┌─┴─╖ │ │
│ ║ 790736054 ║ ┌─┤ ? ╟─┴─┐ │ ├───────┤ ▓ ╟─────┘ │
│ ║ 357861634 ║ │ ╘═╤═╝ │ │ ┌───┘ ╘═╤═╝ │
│ ╚═══════════╝ │ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ╔═══╗ │
│ ╔═══════════╗ │ │ ‼ ╟─┤ · ╟──┤ ? ╟─┤ · ╟─────────┤ · ╟──┐ ║ 1 ║ │
│ ║ 618970314 ╟─┘ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │ ╚═╤═╝ │
│ ║ 790736054 ║ │ ┌─┴─╖ ┌─┴─╖ │ ╓┬──╖ ┌┴┐ ┌┴┐ │ │
│ ║ 357861713 ║ └───┤ · ╟──┤ · ╟───┘ ┌─╫┘‡ ╟─┐ └┬┘ └┬┘ │ │
│ ╚═══════════╝ ╘═╤═╝ ╘═╤═╝ │ ╙───╜ │ ┌─┴─╖ └────┤ │
│ ╔════════════════╗ ┌─┴─╖ ┌─┴─╖ │ ┌───╖ │ │ ♯ ║ └────┘
│ ║ 43980492383490 ╟────┤ ? ╟──┤ ? ╟───┐ └─┤ ‼ ╟─┘ ╘═╤═╝
│ ╚════════════════╝ ╘═╤═╝ ╘═╤═╝ │ ╘═╤═╝ ┌┴┐
│ ╔════════════════╗ │ │ │ │ └┬┘
│ ║ 43980492383569 ╟──────┘ └──────┬──────┘
│ ╚════════════════╝ │
└─────────────────────────────────────────────┘
```
## Explanation
* The main program finds the first two spaces and splits out the numbers. It runs the third (the pipe pattern) through `░` and then calls `▒` with the result, which returns the output as well as the number of turns taken. It then adds the text `n turns were taken to get to the end.`, where `n` is the number of turns calculated by `▒`.
* `░` takes a number and inserts a `0`-bit after every `1`-bit, thus ensuring there are never two horizontal pipes in succession.
* `▒` generates the output by successively calling `▓` and then shifting out the right number of bits from the pipe pattern until it is zero. It also increments or decrements the “current pipe” appropriately.
* `▓` generates one line of the output. In each iteration, it shifts out one bit from the pipe pattern and then decides whether to output `│` (+ 4 spaces), `║` (+ 4 spaces), `├────┤`, `╔════╝` or `╚════╗`; in the latter three cases, it removes the first character from the next iteration. The last iteration generates `│\r\n` or `║\r\n` as appropriate.
## Example output
Input:
>
> `6 3 73497529294753`
>
>
>
Output:
```
├────┤ │ ║ │ │ │
├────┤ │ ╚════╗ ├────┤
│ ├────┤ ╔════╝ ├────┤
│ ├────┤ ║ │ │ │
│ │ │ ║ │ ├────┤
│ │ │ ║ ├────┤ │
│ ├────┤ ╚════╗ ├────┤
│ ├────┤ │ ║ │ │
│ ├────┤ ╔════╝ │ │
├────┤ ╔════╝ │ ├────┤
│ │ ║ │ │ ├────┤
10 turns were taken to get to the end.
```
Input:
>
> `3 0 65536`
>
>
>
Output:
```
║ │ │ │
║ │ │ │
║ │ ├────┤
0 turns were taken to get to the end.
```
Input:
>
> `3 7 75203587360867` (pipe index out of range)
>
>
>
Output:
```
Impossiburu.
```
[Answer]
# Groovy, 311
```
t=System.in.text.collect{it.collect{it}};s=t.size();d=0;c=0;y=0;x=t[0].indexOf('|');println' '*x+'V'
while(y<s){t[y][x]=t[y][x]=='|'?':':'='
if(d){x+=d}else y++
if(y<s)if(d){if(t[y][x]=='|'){d=0;c++}}else if(t[y][x+1]=='-'){d=1;c++} else if(t[y][x-1]=='-'){d=-1;c++}}
t.each{println it.join()}println' '*x+'^'+c
```
* line 1: setup and find first |
* line 2: swap out replacement : or =
* line 3: move x/y to next pos (d=0=down,d=-1=left,d=1=right)
* line 4: find next direction
* line 5: print out results
Here it is formatted:
```
t=System.in.text.split('\n').collect{it.collect{it}}; s=t.size()
d=0; c=0; y=0; x=t[0].indexOf('|')
println ' '*x + 'V'
while (y<s) {
t[y][x] = t[y][x] == '|' ? ':' : '='
if (d) {x += d} else y++
if (y<s)
if (d) {if (t[y][x]=='|') {d = 0; c++}}
else if(t[y][x+1]=='-') {d = 1; c++}
else if(t[y][x-1]=='-') {d = -1; c++}
}
t.each {println it.join()}
println ' '*x + '^'+c
```
Output from the sample:
```
V
: | |-------|
:=======: |-------|
| :=======: |
|-------|-------:=======:
| |-------| :
|-------| :=======:
|-------| :=======:
| |-------| :
^10
```
Other output:
```
V
: | |-------| |
:=======: |-------| |
| :=======: |-------|
|-------|-------:=======: |
| |-------| :=======:
|-------| |-------| :
|-------| |-------| :
| |-------| :=======:
| |-------| : |
| | :=======: |
|-------| : | |
| :=======: | |
| : |-------| |
| :=======: | |
^16
```
(I know I did code-golf instead of popularity, but that's just my style)
[Answer]
**JavaScript**
The HTML canvas listens for click events and finds the nearest row of pipes and uses that for the starting point. Output is drawn on the canvas and there is also a textarea containing the ASCII output defined by the OP.
The algorithm will ensure that there are never two connecting horizontal pipes. Other than that restriction, a probability is defined in the initial variables and that is used to randomly determine whether a horizontal pipe should occur or not.
[JSFIDDLE](http://jsfiddle.net/pqx8S/1/)
```
<html>
<head>
<script type="text/javascript">
var WIDTH = 20,
HEIGHT = 15,
JUNCTIONS = [],
PROBABILITY = 0.2,
COLOR1 = '#00DD00',
COLOR2 = '#DD0000',
RADIUS = 4,
SPACING = 20,
turns = 0,
pipe = 10,
canvas,
context;
function Junction( x, y ){
this.x = x;
this.y = y;
this.l = null;
this.r = null;
if ( y == 0 )
JUNCTIONS[x] = [];
JUNCTIONS[x][y] = this;
var l = this.left();
if ( x > 0 && l.l == null && Math.random() <= PROBABILITY )
{
this.l = l;
l.r = this;
}
}
Junction.prototype.left = function(){
return this.x == 0?null:JUNCTIONS[this.x-1][this.y];
}
Junction.prototype.right= function(){
return this.x == WIDTH-1?null:JUNCTIONS[this.x+1][this.y];
}
Junction.prototype.down = function(){
return this.y == HEIGHT-1?null:JUNCTIONS[this.x][this.y+1];
}
Junction.prototype.reset = function(){
this.entry = null;
this.exit = null;
}
Junction.prototype.followPipe = function( prev ){
this.entry = prev;
if ( prev === this.l || prev === this.r ) {
this.exit = this.down() || true;
turns++;
} else if ( this.l !== null ) {
this.exit = this.l;
turns++;
} else if ( this.r !== null ) {
this.exit = this.r;
turns++;
} else
this.exit = this.down() || true;
console.log( this.exit );
if ( this.exit !== true )
this.exit.followPipe( this );
}
Junction.prototype.toString = function(){
if ( this.entry === null ){
if ( this.r === null ) return '| ';
return '|--';
} else {
if ( this.r === null ) return ': ';
return ':==';
}
}
function init(){
for ( var x = 0; x < WIDTH; ++x )
for ( var y = 0; y < HEIGHT; ++y )
new Junction( x, y );
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
canvas.addEventListener('click', draw );
draw();
}
function draw( evt ){
for ( var x = 0; x < WIDTH; ++x )
for ( var y = 0; y < HEIGHT; ++y )
JUNCTIONS[x][y].reset();
if ( evt ){
pipe = Math.round((evt.clientX - canvas.getBoundingClientRect().left)/SPACING)-1;
if ( pipe < 0 ) pipe = 0;
if ( pipe >= WIDTH ) pipe = WIDTH - 1;
}
turns = 0;
JUNCTIONS[pipe][0].followPipe( true );
context.clearRect(0, 0, canvas.width, canvas.height);
context.lineWidth = 2;
for ( var y = 0; y < HEIGHT; ++y ) {
for ( var x = 0; x < WIDTH; ++x ) {
var j = JUNCTIONS[x][y];
e = j.entry;
if ( j.r !== null ){
context.beginPath();
context.strokeStyle = e===null?COLOR1:COLOR2;
context.moveTo(SPACING*(x+1), SPACING*(y+1));
context.lineTo(SPACING*(x+2), SPACING*(y+1));
context.stroke();
}
if ( y > 0 ){
context.beginPath();
context.strokeStyle = (e===JUNCTIONS[x][y-1])?COLOR2:COLOR1;
context.moveTo(SPACING*(x+1), SPACING*(y));
context.lineTo(SPACING*(x+1), SPACING*(y+1));
context.stroke();
}
}
}
for ( var y = 0; y < HEIGHT; ++y ) {
for ( var x = 0; x < WIDTH; ++x ) {
context.beginPath();
context.arc(SPACING*(x+1), SPACING*(y+1), RADIUS, 0, 2*Math.PI, false);
context.fillStyle = JUNCTIONS[x][y].entry===null?COLOR1:COLOR2;
context.fill();
}
}
var h = [];
for ( var x = 0; x < WIDTH; ++x )
h.push( x!=pipe?' ':'v ' );
h.push( '\n' );
for ( var y = 0; y < HEIGHT; ++y ) {
for ( var x = 0; x < WIDTH; ++x )
h.push( JUNCTIONS[x][y].toString() )
h.push( '\n' );
}
for ( var x = 0; x < WIDTH; ++x )
h.push( JUNCTIONS[x][HEIGHT-1].exit!==true?' ':'^ ' );
h.push( '\n' );
h.push( turns + ' turns were taken to get to the end.' );
document.getElementById( 'output' ).value = h.join( '' );
}
window.onload = init;
</script>
</head>
<body>
<p>Click on a row to show the path</p>
<canvas id="canvas" width="450" height="350"></canvas>
<textarea id="output" style="width:100%; height:24em;"></textarea>
</body>
</html>
```
**Output**

] |
[Question]
[
Given two numbers \$x,y > 2, x≠y \$ output all integers \$m\$ such that
$$
x + y \equiv x \cdot y \pmod m
$$
$$
x \cdot y > m > 2
$$
## Input
Two integers
## Output
A list of integers
## Test cases
```
3, 4 -> 5
5, 8 -> 3, 9, 27
29, 9 -> 223
26, 4 -> 37, 74
13, 11 -> 7, 17, 119
6258, 571 -> 463, 7703, 3566489
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes
```
<P<√ë í2‚Ä∫
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m73MwDQxyTB1wYKlpSVpuharbQJsDk88NcnoUcOuJcVJycVQ8QXLow2NdQwNYyFcAA) or [try all testcases](https://ato.pxeger.com/run?1=m73MwDQxyTB1weqySnslBV07BSX7yqWlJWm6FqttAmwOTzw1yehRw64lxUnJxYtqdSAyC27qRUcb65jE6kSb6lgASSNLHUsQZQYWMzTWMTQE0mZGphY6puaGsbEQbQA).
-1 thanks to Kevin Cruijssen
Lists the divisors of \$xy-x-y\$ greater than \$2\$.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 8 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
(ε*(─2╒-
```
[Try it online.](https://tio.run/##y00syUjPz0n7/1/j3FYtjUdTGoweTZ2k@/9/tLGOSSxXtKmOBZA0stSxBFFmYDFDYx1DQyBtZmRqoWNqbhgLAA)
**Explanation:**
```
( # Decrease both values in the (implicit) input-pair: [x-1,y-1]
ε* # Multiply them together: (x-1)*(y-1)
( # Decrease that by 1 as well: (x-1)*(y-1)-1
─ # Get all divisors
2‚ïí # Push [1,2]
- # Remove those values from the divisors-list
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 7 bytes
```
√ó__F√¶2>
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWKw9Pj493O7zMyG5JcVJyMVR0wWJTLgsIEwA)
Based on Command Master’s idea, implemented a bit differently
```
√ó # Multiply. X * Y
_ # Swapped subtract. X * Y - X
_ # Swapped subtract. X * Y - X - Y
F # Factors.
√¶ # Filter by:
2> # Greater than 2?
```
I chose Thunno 2 because of that swapped subtraction operator. It's the only stack golflang which has swapped versions of arithmetic operations, as far as I know.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 8 bytes
```
ᵋ*+-Ď~2>
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Fqsfbu3W0tY90ldnZLekOCm5GCq-4KaCsYIJl6mCBZeRpYIll5EZkGdorGBoyGVmZGqhYGpuCFEIAA)
```
ᵋ*+-Ď~2>
ᵋ* x * y
+ x + y
- minus
Ď divisors
~ choose an element from the list
2> check if it is greater than 2
```
[Answer]
# [Raku (Perl 6) (rakudo)](https://raku.org), 41 bytes
```
{[3..($^x*$^y)].grep: 0==($x+$y-$x*$y)%*}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kKDG7dMHy3EoFlTQF26WlJWm6Fjc1q6ON9PQ0VOIqtFTiKjVj9dKLUgusFAxsbTVUKrRVKnVVgBKVmqpatVANMcWJIAM0jHUUTDStuaA8Ux0FCwTPyFJHwRKJa4ai1hCo1dAQwTczMrXQUTA1BwpB7FiwAEIDAA)
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/products.htm), ~~22~~ ~~17~~ 16 bytes
-5 bytes thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs)
-1 bytes thanks to [@att](https://codegolf.stackexchange.com/users/81203/att)
```
(2↓2∪∘⍸0=⍳|⊢)×-+
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70qpTIxJz89PrEgZ8EqK7_E3NTigsTk1KWlJWm6Fns1jB61TTZ61LHqUceMR707DGwf9W6uedS1SPPwdF3tJcVJycU3K9wetU141Ntn9Kir-VHf1OAgZyAZ4uEZzMUFZADljBXcFEygbFMg2wLKNrIEcixhHDMkVYYgLYaGUJ6ZkakFkG9qbshl5ZqXgubEBQsgNAA)
```
(2↓2∪∘⍸0=⍳|⊢)×-+­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢​‎⁠⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌­
(2↓2∪∘⍸0=⍳|⊢) ⍝ ‎⁡monadic function to get factors greater than 2:
⊢ ⍝ ‎⁢ arg
| ⍝ ‎⁣ mod
⍳ ⍝ ‎⁤ each number in range [1;arg]
0= ⍝ ‎⁢⁡ boolean vector, marking where result is 0
⍸ ⍝ ‎⁢⁢ ‎⁢⁢get indices of 1s
2∪ ⍝ ‎⁢⁣ prepend 2 if not in array
2↓ ⍝ ‎⁢⁤ drop first two elements (i.e. 1 and 2)
×-+ ⍝ ‎⁣⁡pass (⍺ × ⍵) - (⍺ + ⍵) to the function
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 56 bytes
```
i;f(x,y){for(i=x*y;--i>2;)(x*y-x-y)%i?:printf("%d ",i);}
```
[Try it online!](https://tio.run/##dVJ/b4IwEP3fT3EhWQLaZlp@qd3cH4ufYprFYHF1W12UZGWGrz52UMDKNhKa4967947rJXSXJGUpeepqknvn9HB05b0e5pxSuWDcczGmmubejXyYfxylylLXudmCQ6THi3KACXjfSOV6cB4APlVC6A@RZGL7PH5awz2cw4Jf5ycm7xOYEWBxH2YGZszvI35TGBOIgz4YGBCxSfVOZn1CaAhBhMZxPMbTD6MomLbETJwy3bUWYmtVexFq4WfEwqnFyxstAtP6L4LKEYviiSENO1tDvMyEWHOwYmbFvhUHVtwfpDLaKIMVeLI6wKnVV5Ec1CmD5GVzHOIpkldxNHxnpZdspWeP@IYOAfvbd5pqXAVwKzOptkJj2Zg34R2c5Jc4pG7bhge3bWrY5TiMRjW/3Yx2OyotM@kaXvMrNG/Q/Bd62T4CuIF0gUsImkDuXTjVGl8lzE2gZncbf5kqi6D@NV6pZcOZg2ObtpPao4zisOf2L1@3XvUsnijdry2B4g@r1qAYFOV3kr5tdqeSfv4A "C (gcc) – Try It Online")
[Answer]
# Google Sheets, 58 bytes
```
=let(p,A1*B1,s,sequence(1,p,3),filter(s,0=mod(p-A1-B1,s)))
```
Put \$x\$ in cell `A1`, \$y\$ in cell `B1` and the formula in cell `C1`.
[Answer]
# [Python](https://www.python.org), 52 bytes
```
lambda x,y:[i for i in range(3,x*y)if(x+y)%i==x*y%i]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY5NboMwEIXX8SlGkaLY1ImK-TEg0YukWVAF2pHAWOBIcI_uuskmvVNu0zGhC9vzPc17zz-_dnZfvbndGyjh_X51zSF7xG3VfVwqmORcnBCafgAENDBU5rPmkZyCWWDDp5dZ7LAsCXd4Xr3f2Nl-cDDOI_PGFk3tvcTH0V3QFGyDxkqoJ0uVXWX5f1sBp8AzGidhOo62Rce3civEWS45q7SHwxvshWCb_uooo-EBJRLagax8EUvKogYyEorn326PNpIQe3fCEgmZn0jJJSjNFD25V5SKmErXxUhL0DELaS0MvUAc-hPmLFVJJiHRix6ntKL1K91RkqZxlj9L_wA)
[Answer]
# [Haskell](https://www.haskell.org/), ~~38~~ 35 bytes
*-3 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844).*
```
x#y=[m|m<-[3..x*y],1>mod(x*y-x-y)m]
```
[Try it online!](https://tio.run/##XY5LCoMwGIT3nmLATVL@CNHGKlRv0BOkWQQqVGqsVBcJ9O6plG7SWQ0fzONu18cwTTH6PHTavd1Z6Koo/CEYkr173thuhReBOxO3Yd1WdNDQFeFoMvxE0IrQJKBsCW1K6v@Q3GukTFBdqoagTtLAZJmz47wPOrtcwJbXOG8owK7aE4KB6OGRI3CO77X4AQ "Haskell – Try It Online")
[Answer]
# [Go](https://go.dev), 80 bytes
```
func(x,y int)(M[]int){for m:=3;m<x*y;m++{if(x*y-x-y)%m<1{M=append(M,m)}}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TVFLasMwEKVbnWJqMMiNEup_fioUmmVKaLNrSzGOFUxjx7XlYCN8gh6hm1DoodLTVJaTkIU0mvfefDTz_bPe7g9mFoQfwTqCJIhTFCfZNucDjSVcOzvFJg6jQkNoF-TA6G_JWX94WLAyDXFFaohTbuD5y1trBdvmkIypPUmm1U09SXo9ETMsn_2qXxt6MjXFnAZZFqUrPCeJ0TQoj3iZp02X9-_qi9dZBEsoeF6GHMSxxASiKgNVpVGd8KjgBVAJLQUSNgGHdLRwm4Yg4RIYnhDJjghYviKskfI6xrLsDvQuEtg-Ad9RuClDTfNESNxsjzlSpGe5soTrn3nHk3Lfv5W37XqeM1S6BqF2WGrE2ACBFrkUb1KsUUqfl_dPS2k1A7WzeyccxhTyIJU76b4oUBAqkGE-qAjwQW2gmMH17LMMNliSLSanI1ODSs2wpq8I6Cugd6DvAOs74zXVWlkXT-AyqpEdXrY0e3zoGjruZL_v7D8)
Uses the factors of \$xy-x-y \gt 2\$ method.
# [Go](https://go.dev), 81 bytes
```
func(x,y int)(M[]int){for m:=3;m<x*y;m++{if(x+y)%m==x*y%m{M=append(M,m)}}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TVHdSsMwGMXbPMVnoZC6OGy7tvsxguAuJ_7sTkVK14zi0tU2HS2hT-AjeDMEH2o-jWm6jV0kH9855_vJyffPcr3d2VkYfYTLGHiYpCjh2ToXfYNxYRyTYpVEcWEgtAlzYPS3FOxyuHtkZRrhitSQpMLCs5e3Nkq2zoGPqTvh19VFPeG9nkwYrnq1ZXJKFWRyOaNhlsXpAs8It5oG5bEo87TpGv-dfYk6i2EOhcjLSIDcz5hAXGWgxzR6FREXogCqoLlE0iUwIB0tvaYhSHoEhgdEsSMCTqAJZ6SzjnEctwP9kwZuQCAYaNxWpbZ9IBRut8ceadJ3PDXCC478wFfyILhSt-v5_mCodQ1CrVvaY2yBRA-5Eq9SbFBKn-e3T3MVDQu15r0TAWMKeZiqT-meKFEYaZBh0a8IiH5toYTB-fSzDFdYkS2m3FGtQbdm2DAXBMwF0BswN4DNjfWaGq2sqydwWtWoDU9Xmt7fdQvt_2S77eI_)
Formula as verbatim, \$xy \equiv x+y \pmod m\$.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
F²⊞υNIΦ…³Πυ¬﹪⁻ΠυΣυι
```
[Try it online!](https://tio.run/##RYoxDsIwDEX3nsKjLYUhdOyIhMTQKoIThFBopDRBjs31QyQG/vbe@2HzHIpPrT0LAx4JnNYN1cAlv1UW3e8rI9E0OI5Z8OSr4Dkm6fbq82vF0YDj8tAgqEQGliI4d04F55i14r8auOn@e0Xqm1qz42BtO3zSFw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²⊞υN
```
Input `x` and `y` and push them to the predefined empty list.
```
IΦ…³Πυ¬﹪⁻ΠυΣυι
```
Output all numbers between `3` and the product of the list that are factors of the difference between the product and the sum.
21 bytes for a faster version that can handle the last test case in a more reasonable amount of time:
```
F²⊞υNI⁺³⌕A﹪⁻ΠυΣυ…³Πυ⁰
```
[Try it online!](https://tio.run/##RYtNCsIwEIX3PUWWE4iglarQVRGELipBTxDTagPTRCaZXj@mKzfv53s8OxuywWDO70ACaik0xxlYid5/Od15eU0EUraVJucTXE1MoJEjHJW4OT92iDCEkTHA4HzhmkqzCVgq8eSleAkP4z/TdvmvG94XlW3Op7q5VM35kHcr/gA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Vectorises the remainder check and then finds the positions of the zero remainders.
[Answer]
# [R](https://www.r-project.org), 32 bytes
```
\(x,y,a=x*y-x-y)which(!a%%3:a)+2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY5NCsIwEIX3nmJECqlOwPwnQj2JmyCEupWKyd5buImCh_I2TklxMX_few_m-brWdxo-tylx_4UTy1gwDnlbeOalv4-X88jWsevUIfY7ufgeiSkE3W-AH8GsEjMIvl3EA4J0BCUtoVEp1QzsP6QcgtPEBAWEaJCYmEsEEqw0HsG4RdOWjM7tqStjrfah_VJrmz8)
Port of [Command Master's 05AB1E answer](https://codegolf.stackexchange.com/a/269713/55372).
# [R](https://www.r-project.org), 35 bytes
```
\(x,y,M=3:(p=x*y))M[p%%M==(x+y)%%M]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY5NCgIxDIX3niIwDLSaAfvfCvUGPYG67XoQhXbvLdxUwUN5GzN0cJHk5Xt5kOfr2t45fu63PPnvcGYFK6aoDmyOZVs5T6d5HFOMrOwqJ3VZTx-ZKQTNB5iOYDaZGQTfN-IBQTqCkkToVEq1APsPKYfgNDFBASE6JCaWEoEMK41HMG71tKVD5_bUlbFW-9B_aa3PHw)
Straightforward approach.
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), ~~19~~ 15 bytes
```
▽=⊃∩◿∘,:↘3⇡.⊃×+
```
[Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAg4pa9PeKKg-KIqeKXv-KImCw64oaYM-KHoS7iioPDlysKCmYgMyA0CmYgNSA4CmYgMjkgOQpmIDI2IDQKZiAxMyAxMQpmIDYyNTggNTcxCg==)
-4 bytes thanks to Tbw
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes
```
Divisors[##-##]/. 1|2->Set@$&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yWzLLM4v6g4WllZV1k5Vl9PwbDGSNcuOLXEQUXtf0BRZl5JtLKuXZqDg3KsWl1wcmJeXTVXtbGOSa0OV7WpjgWIMrLUsQTTZhBhQ2MdQ0MQw8zI1ELH1Nywlqv2PwA "Wolfram Language (Mathematica) – Try It Online")
Input `[x, y]`. `##-##` is not zero - it computes the sum minus the product of arguments.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 46 bytes
```
x=>y=>{for(m=x*y,q=m-x-y;--m>2;)q%m||print(m)}
```
[Try it online!](https://tio.run/##Tc3RCsIgFMbx@z3FuQk0lKFuORn6LiMQFlibjaG0nt3MILw4N/8ffOc27dPz6udlo/uQrE5Bm6jNyz48cjqcI1m1o4HGkVJn@IjXkzuOxc/3DTn8ThaBwAg6DG0LffMD3OTc5zyULAgoAlxWylVWVZRzUcPlvyYkAdlVxvInxoplYt9jKn0A "JavaScript (V8) – Try It Online")
---
# JavaScript (ES6), 52 bytes
```
(x,m=2)=>g=y=>++m<x*y?((x*y-x-y)%m?"":m+" ")+g(y):""
```
[Try it online!](https://tio.run/##Xc7RCoMgFIDh@z3FQRjotIVaa8asZ4lWspE51hj59C7pZnhxzs3/cTjP7tst/fvx@mSzuw9h1AGvzGpBdGO01w2l9raefIvxtrM18@RoW4RqSxEgQg32pEYo9G5e3DScJ2fwiEESDFAQAnkO5SGJZYzXPUoGioGoEiNUNGo3Qsg0X/7uy4pBVSSCxw8438UGeByuwg8 "JavaScript (Node.js) – Try It Online")
[Answer]
# TI-BASIC, 25 bytes
```
For(M,3,prod(Ans)-1
If not(fPart(M⁻¹min(ΔList(Ans
Disp M
End
```
Takes input in `Ans` as a list of two integers. Add a `)` to the end of the first line to make it faster.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
’P’ÆD>Ƈ2
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw8wAID7c5mJ3rN3o////0YbGOgqGhrEA "Jelly – Try It Online")
Port of [Command Master’s 05AB1E answer](https://codegolf.stackexchange.com/a/269713/106959).
-1 byte and a bugfix thanks to [@Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)
## Explanation:
```
’P’ÆD>Ƈ2­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌­
’ # ‎⁡Decrement both values in the list: [x - 1, y - 1]
P # ‎⁢Product of the list: (x - 1) * (y - 1)
’ # ‎⁣Decrement again: ((x - 1) * (y - 1)) - 1
ÆD # ‎⁤Get the divisors
Ƈ # ‎⁢⁡Keep items that satisfy the condition below
> 2 # ‎⁢⁢Greater than 2
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 50 bytes
```
.+
$*
1(?=1+¶1(1+))
$1
M!&`(111+)\b(?<=^11\1+)
%`1
```
[Try it online!](https://tio.run/##FcgxCoMwGAbQ/TtFhKT8miB8akWh4uLq5BpKFBxcOpSezQN4sZiO73333/FZo5El@MnG0kIXoIwD7XVSaPMcmpizRxAy0W8yvoY36RNgAiNh5lBC4zpj7VSDp1Mdqt6pHlX7D6Ymbw "Retina 0.8.2 – Try It Online") Link is to test suite for faster test cases that splits input on non-digits and spaces the outputs apart. Explanation:
```
.+
$*
```
Convert to unary.
```
1(?=1+¶1(1+))
$1
```
Calculate `1+(x-1)(y-1)`, as that's golfier than trying to subtract `x` or `y` afterwards.
```
M!&`(111+)\b(?<=^11\1+)
```
Subtract `2` and find all factors that are greater than `2`.
```
%`1
```
Convert to decimal.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 45 bytes
```
param($a,$b)3..($p=$a*$b)|?{!(($a+$b-$p)%$_)}
```
[Try it online!](https://tio.run/##RY/dToNAEIWv2acYcWpAl0ZYYMsFEW301sZeGtMsuE1jaEB@ognl2XEQqclsMuecOV@yZfGlq/qg89zJikoPuI@7oVSVOlqoOKa2WC4tLGNU1yROd92FRcENpg6W9gJ3dj/0jCUWA@CJJTj4HMzAtCcdcFiRFhCBJ2fTizjQmJ4nzlY4FYUE6c@mSzTXJVeCS@NGv8ElJaEXEDaQY@iHAqS8FSCCMPRX45ENJ3gqqkeVHZzn9ENnDXTMoO8ApvT0d0mWfocYcEd@pes2b0hd4R5Q0REzXjfbdVs3xXHqv0FCBGPbZpmuazo1/1omOPrzH0k39yNW0fIwLoQyXmb@ucSMnvVs@AE "PowerShell Core – Try It Online")
Saved two bytes using [rajashekar](https://codegolf.stackexchange.com/users/104396/rajashekar)'s method, upvote [their answer](https://codegolf.stackexchange.com/a/269741/97729)!
] |
[Question]
[
### Task
Write a function or a program to find the number of rotations required by a wheel to travel a given distance, given its radius.
### Rules
Input can be 2 positive rational numbers and can be taken in any convenient format.
Both inputs are of same unit.
**There must not be any digits 0-9 in your code.**
The output will be an integer (in case of float, round to infinity)
This is **code-golf** so shortest code wins
### Examples
```
distance radius output
10 1 2
50 2 4
52.22 4 3
3.4 0.08 7
12.5663 0.9999 3
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~5~~ 4 bytes
```
τ/╠ü
```
[Try it online!](https://tio.run/##y00syUjPz0n7//98i/6jqQsO7/n/39BAwZDL1EDBiMvUSM/ISMGEy1jPRMFAz8CCy9BIz9TMzBjIsQQCAA "MathGolf – Try It Online")
## Explanation
```
τ Push tau (2*pi)
/ Divide the first argument (total distance) by tau
╠ Reverse divide (computes (distance/tau)/radius)
ü Ceiling
```
[Answer]
# APL+WIN, 9 bytes
Prompts for radius followed by distance:
```
⌈⎕÷○r+r←⎕
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4/6ukAihze/mh6d5F2EVAcyPsPlPmfxqVnYMFlrGcCAA "APL (Dyalog Classic) – Try It Online")
Explanation:
```
○r+r←⎕ prompt for radius and double it and multiply by pie
⌈⎕÷ prompt for distance, divide by result above and take ceiling
```
[Answer]
# Java 8, ~~32~~ 30 bytes
```
a->b->-~(int)(a/b/Math.PI/'')
```
Contains unprintable `\u0002` between the single quotes.
Port of [*@jOKing*'s Perl 6 answer](https://codegolf.stackexchange.com/a/176335/52210).
[Try it online.](https://tio.run/##jY5Na8JAEIbBY37F3NwFM4nrBy22OZWCB6HgUTxMvuym6yaYiSCifz3dUkOOZk4vzPPAU9CZ/CL9aRNDdQ0b0vbqAdRMrBMo3Bcb1gbzxiasS4ufj/H2UTaxySaDmLXl7JCdoghyeG/Jj2I/8u9CW5aCgjjYEH/j1zoYj8ayXXkuoHKiC3h0nEudwtG1iS2ftD3s9kDyrxNge6k5O2LZMFbuxcaKHKmqzEVMw1R2M5Vy9Yxf9LwaxCtUqjPmQ4wZzjs@xPBlgDFVuFguZ7316u7fu3m39hc)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~15~~ 12 bytes
*-3 bytes tjanks to nwellnhof reminding me about tau*
```
*/*/τ+|$+!$
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0tfS/98i3aNiraiyn9rruLESoU0DUMDHUNNGMfUQMcIwTHSMzLSUTCBCxjrmegoGOgZWMBFDI30TM3MjEGilkCgaf0fAA "Perl 6 – Try It Online")
Anonymous Whatever lambda that uses the formula `(a/b/tau).floor+1`. Tau is two times pi. The two anonymous variables `$` are coerced to the number `0`, which is used to floor the number `+|0` (bitwise or 0) and add one `+!$` (plus not zero).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~47~~ ~~45~~ ~~44~~ 43 bytes
```
lambda l,r:l/(r+r)//math.pi+l/l
import math
```
[Try it online!](https://tio.run/##RcvLCsMgFATQfb7iQjcJCT6uJn1A/6QbSwkRNJGLm369bU2qsxrmMOEdl23FNN8fyRn/fBlwA90cb6mnjnNv4sKC7R13jfVhowi/KQWya4S5lQJyBpB76eAE2Px5LIyVdWVkiJl1ZVVYMX28BROXg8@FJbJxmlTm6zf7O30A "Python 2 – Try It Online")
---
* -2 bytes, thanks to flawr
* -1 byte, thanks to Jonathan Allan
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
·/žq/î
```
Port of [*@flawr*'s Python 2 comment](https://codegolf.stackexchange.com/questions/176328/number-of-rotations#comment424571_176329).
Takes the input in the order `radius`,`distance`.
[Try it online](https://tio.run/##yy9OTMpM/f//0Hb9o/sK9Q@v@//fkMvQAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/q9v/Qdv2j@wr1D6/7r/PfkMvQgMuIy9SAy4TL1EjPyIjLQM/AgstYzwTIsAQCLkMjPVMzM2MA).
**Explanation:**
```
· # Double the first (implicit) input
/ # Divide the second (implicit) input by it
žq/ # Divide it by PI
î # Ceil it (and output implicitly)
```
[Answer]
# PHP, 47 bytes
```
<?=ceil($argv[++$i]/M_PI/(($b=end($argv))+$b));
```
[Try it online](http://sandbox.onlinephpfunctions.com/code/c16dfdd0af45e7222fabae2e6f68841537cbba34).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 29 bytes
```
->l,r{(l/Math::PI/r+=r).ceil}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5Hp6haI0ffN7Ekw8oqwFO/SNu2SFMvOTUzp/Z/QWlJsUJatKGBjmEsF5RjaqBjhOAY6RkZ6ZjA@cZ6JjoGegYWcAFDIz1TMzNjoKAlEMT@BwA "Ruby – Try It Online")
[Answer]
## **C, 46 bytes**
```
f(float a,float b){return ceil(a/(b+b)/M_PI);}
```
I'm new to PPCG, so I'm not sure wether I have to count other parts in the byte count, such as the
```
include <math.h>
```
needed for the ceil function, which will rise the count to **64 bytes**
[Answer]
# [Catholicon](https://github.com/okx-code/Catholicon), 8 bytes
```
ċ//ĊǓĊ`Ė
```
Explanation:
```
/ĊǓĊ divide the first input by the doubled second input
/ `Ė divide that by pi
ċ ceil
```
New version (pi builtin made one byte, division parameters swapped), 5 bytes
```
ċ/π/Ǔ
```
[Answer]
# [J](http://jsoftware.com/), 10 9 bytes
```
>.@%o.@+:
```
[Try it online!](https://tio.run/##LYs7CoAwFAT7nGIRRERZns8PGojkLmIQGwtrzx7jZ6uZgd1jOB0hsJA40@cHfWVjaTKiCI4FalwW4TRmXbYDjSCg@bh/WH9WqibtPm3ZJRHK@N@U/TC0b5vS4g0 "J – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 5 bytes
```
Vt*/e
```
[Run and debug it](https://staxlang.xyz/#c=Vt*%2Fe&i=10+++++++1%0A50+++++++2%0A52.22++++4%0A3.4++++++0.08%0A12.5663++0.9999&a=1&m=2)
```
Vt* multiply by tau (2pi)
/ divide
e ceiling
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/create_explanation.py), ~~6~~ 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
∞/π/ü
```
Semi-port of [*@flawr*'s Python 2 comment](https://codegolf.stackexchange.com/questions/176328/number-of-rotations#comment424571_176329).
Takes the input in the order `radius distance`.
-1 byte because `ceil` builtin has just been added, replacing the `floor+1`.
[Try it online](https://tio.run/##y00syUjPz0n7//9Rxzz98w36h/f8/2@oYGjAZaRgasBlomBqpGdkxGWgZ2ChYKxnAmRYAoGCoZGeqZmZMQA).
**Explanation:**
```
∞ # Double the first (implicit) input
/ # Divide the second (implicit) input by it
π/ # Divide it by PI
ü # Ceil (and output implicitly)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~45~~ ~~47~~ 45 bytes
```
f(d,r,R)float d,r;{R=ceil(d/r/'G'/'\n'*'q');}
```
A reasonable approximation of pi is 355/113. Since circumference C = 2 \* r \* PI, we can instead of pi use tau, which is then of course ~710/113. 710 happens to have the convenient factors 2 \* 5 \* 71, which is compactly expressed as `'G' * '\n'`. ~~We add one (`r/r`) to force rounding to infinity.~~
Edit: My trick was too clever for its own good: it of course made it fail if the distance was a multiple of the circumference.
[Try it online!](https://tio.run/##TY3LCoMwEEXXzVcEoSQpMWp8tEW67t61G0kaEXy0qXQj/nrTRCt4FzOXwxlG@LUQxigsqaYFUe1QjdD2fCpu4tG0WAY6QHcUoLJHJ/RCJJ/NZ2gkrPEmw7VoAiZweOqmHxX2jmeWKPifsuw96kxtZew2ITmYAbAu7Kqmx8ttjaMQulAYLdtKFqYb5HvIGecOJjsYs2Q1QxZeNhhxlmZZ7ODVxj02X6Haqn4bv@1@ "C (gcc) – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 20 bytes
```
f(d,r)=cld(d/π,r+r)
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/P00jRadI0zY5J0UjRf98g06RdpHmf4fijPxyhTQNQwMdQ00uGM/UQMcIiWekZ2SkY4IQMNYz0THQM7BAiBga6ZmamRkDRS2BQPM/AA "Julia 1.0 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~39~~ 32 bytes
-7 bytes Thanks to Giuseppe
```
function(d,r)ceiling(d/(r+r)/pi)
```
[Try it online!](https://tio.run/##HYZBDkAwEADvXrLLZrVbhIPXtEgTqabhJN5eag4zk3KO83oFe/ojgKOEt1387sMGroVUR98UIT45glaksYrQK5K/wiLUlTXcEauxrBbuh8GQ4ukD8ws "R – Try It Online")
I feel like this could definitely be golfed, but I am a bit lazy right now to do anything about it
[Answer]
# [min](https://min-lang.org/), 16 bytes
```
/ tau / ceil int
```
Takes the distance and radius put on the stack in that order. Then divides by tau, rounds, and makes int.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
÷÷ØPHĊ
```
[Try it online!](https://tio.run/##y0rNyan8///wdiCcEeBxpOv////Geib/DfQMLAA "Jelly – Try It Online")
[Answer]
# Japt, 7 bytes
```
/MT/V c
```
[Try it here](https://ethproductions.github.io/japt/?v=1.4.6&code=L01UL1YgYw==&input=MTAKMQ==)
[Answer]
# [JavaScript (Babel Node)](https://babeljs.io/), 25 bytes
*-2 bytes using @flawr comment =D. -1 from @Kevin. -7 from @Shaggy*
```
a=>b=>-~(a/(b+b)/Math.PI)
```
[Try it online!](https://tio.run/##Zcy7DoIwFIDhGZ@i4zkx9AqoQ9kdTHyFFsFLGkqkOPrqFXVQ6z9/@S/mZsbmeh5Cbo1tXd77Qxs7HY2ura7zOxgGdmmR7Uw40f0WY@P70buWOn@EDgRHEIiEZFnGGPFTGKZA5OJXlbOSf6pIlaRSIhRv@HEqcYoWCJzydQpXCRSSllWlnngz9@Jf2/gA "JavaScript (Babel Node) – Try It Online")
[Answer]
# [Dart](https://www.dartlang.org/), ~~47~~ 46 bytes
```
import'dart:math';f(a,b)=>(a/(b+b)/pi).ceil();
```
[Try it online!](https://tio.run/##ZcxNCsMgFATgfU/houB71Bo1Jv2R5i7aNERo0hDchZzdCm5anN3wDdPbNcTop@WzBtqncp9sGKkZwDKHjw5sBe7ksFo88ufLvwFNnKyfAbcDIcvq5wD0uA0gBZO4k3NHFEXzb41gKpsuTXGlmM5cF1xzzQQX1@yXwqXiTdvWaXNL@XnZ4xc "Dart – Try It Online")
* -1 byte thanks to @Shaggy
[Answer]
**Haskell, 25 bytes**
```
f d r=ceiling(d/(r+r)/pi)
```
[Answer]
# [Lua](https://www.lua.org), 61 58 57 49 bytes
```
function(s,r)return math.ceil(s/(r+r)/math.pi)end
```
[Try it online!](https://tio.run/##HcjBCoAgDADQX@m4kSgVCR36mDAlwZbM@f0resdX@qFp19QpSH4ImmHkKJ1puA@5bIi5QHPAI6P7p2aMdGrlTAIJptmu3i/Gbh9EfQE "Lua – Try It Online")
*Thanks to KirillL. -8 bytes.*
[Answer]
# Common Lisp, 36 bytes
```
(lambda(a b)(ceiling(/ a(+ b b)pi)))
```
[Try it online!](https://tio.run/##TY7dCoJAEIXve4qDEM0QbLr@ZBDRq6yuxYK6ouvtvrqNRNDcnO8MA9@0vVumjV5@HkxAQGLdEszYdpiNdesC@DVMa4jHhA/Uez9BbkEWM8ONOBFlKTIGlSn0HlppjUIoVwVSldaCmVZlVeVSbzLMsB5/zlg/79HGB@L1B@UXRAtRgTbqzdBYQwYNU9u53o1vusDQGY2sJsfM2/6VxAc)
[Answer]
# [Tcl](http://tcl.tk/), 50 bytes
```
proc N d\ r {expr ceil($d/(($r+$r)*acos(-$r/$r)))}
```
[Try it online!](https://tio.run/##LcuxDsIgFEbh/T7FPzCARgq0NPoSfQF1aKCDCabktiYmDc@ODJ7tG84eUq2Z14AJ8QHGsXwzIyyvJEXspBR8FqxOc1g3eRHcNShVanrP@T@QNbDkDRx5p53DQL0eYLS5knXaj2PfcGtRwZE/@4b7BBEh@FnqDw "Tcl – Try It Online")
---
# [Tcl](http://tcl.tk/), 53 bytes
```
proc N d\ r {expr ceil($d/(($r+$r)*acos(-[incr i])))}
```
[Try it online!](https://tio.run/##LcsxDoMgGIbhnVN8AwO0kQKKaS/hBayDAQcSWsmvTZoYzk4d@m7P8O4@1Zpp9RgQniAcyzcT/BKT4OEmBKcrJ3mZ/bqJZoxvT4iTlLLU9Jrz/2FGwzCnYZmzylp0rFUdtNJ3Zqxyfd@eeJyxgiN/9g3jAB7AaSr1Bw "Tcl – Try It Online")
Lack of a pi constant or function makes me lose the golf competition!
[Answer]
# PowerShell, 53 52 51 bytes
-1 byte thanks to @mazzy
-1 byte after I realized I don't need a semicolon after the `param()` block
```
param($d,$r)($a=[math])::ceiling($d/($r+$r)/$a::pi)
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVFR6VIU0Ml0TY6N7EkI1bTyio5NTMnMy8dKKWvoVKkDZTWV0m0sirI1Pz/HwA "PowerShell – Try It Online")
Takes input from two commandline parameters, distance `-d` and radius `-r`.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~23~~ 19 bytes
```
(d,r)->-d/(r+r)\-Pi
```
[Try it online!](https://tio.run/##HcjLDsIgEIXhV5l0BXEGYXqJLuwzdF9ZEJsaEmImxEV9eoSe1fcfCTnSW8oODyhqw6xppu2q8iXrJy2xBJH0UwfQDJLj51vZtejgFVJSO8KhNcK6OovgfNVYwSfYMCMMzb0ZEKyxtxaOzThNfTvudd7r8gc "Pari/GP – Try It Online")
[Answer]
# [Desmos](https://www.desmos.com), 22 bytes
```
f(d,r)=ceil(d/π(r+r))
```
[Try it on Desmos!](https://www.desmos.com/calculator/y4tjadxsah)
[Answer]
# JavaScript (Babel Node), 23 bytes
```
s=>r=>-~(s/2/r/Math.PI)
```
[Try it online!](https://tio.run/##Zcy9DsIgFEDhuT4FI3colEtbdaC7g4mvQCv1J6Q0hTr66lh1UPHMX85V37TvpssY8la3xuaDO5rYq@hVM6kmv1PPkU98r8OZHXYQOzd4Zw2z7kR7KgqgAoCQLMs4J24O4xwIrn5VtSj8U2WqkCECLd/w42TiJCuBFqzYpHCdQIGsqmv5xNulF//axgc "JavaScript (Babel Node) – Try It Online")
[Answer]
# [Clojure](https://clojure.org/), 50 bytes
```
(fn[a b](int(Math/ceil(/ a Math/PI(count" ")b))))
```
An anonymous function that accepts two integers `a` and `b` as arguments: the distance and the wheel's radius, respectively.
[Try it online!](https://tio.run/##lZDBjsIgFEX3fsVNVzRpkNJWZ@IXTDImLtyZWdAKaQ0BR2F@vz5rZoGpC9@O8zgnhM76U7zocWTGHRTaHza4wLYq9MtOD5YtoTCddl@s89GFDMjyNqcZ2VEbGLxv5tjgWwdy9W9UFqHXMNF1YfAOqvV/esHOF8pZR3WUAuXk7O4MhpWiIMKx74crrr2P9ojpPjKZJWojIBO1IVXOq/WTKrmUqFP7zgqCs4EqDVS8huDiIykQLB50NrFOE6XkzWpVkfBJk/7BY1X87168aLwB "Clojure – Try It Online")
`(count " ")` evaluates to `2`, so this function implements \$\lceil \dfrac a{2\pi b} \rceil\$.
] |
[Question]
[
For this challenge, you must create a programme which takes an integer `x` and outputs its source `x` many times.
**Rules**
* This is codegolf, the aim is to golf your programme to have the least amount of bytes
* If you submit a function, the function must take `x` as a parameter and either return or print the entirety of your code `x` many times to STDOUT. The function body must also not be empty
* If you submit a lambda, it is not required for you to assign it to a variable
* [Standard loophole](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) restrictions apply.
* Empty programmes are forbidden
* Your programme only has to work when `x` is a whole integer larger than or equal to 0
* Your programme may also not directly read any part of its source code
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
Note the trailing comma and newline.
```
s='s=%r;print s%%s*input(),\n';print s%s*input(),
```
[Try it online!](https://tio.run/nexus/python2#@19sq15sq1pkXVCUmVeiUKyqWqyVmVdQWqKhqROTpw4XRohy/f9vBAA "Python 2 – TIO Nexus")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 bytes
```
"iQ ²pU"iQ ²pU
```
[Try it online!](https://tio.run/nexus/japt#@6@UGahwaFNBKIz@/98IAA "Japt – TIO Nexus")
# Explanation
```
"iQ ²pU"iQ ²pU
"iQ ²pU" # Take this string
iQ # Prepend a quote
² # Double the string (= source code)
pU # Duplicate input times
```
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 8 bytes
```
{`{.*¶}{
```
The RProgN2 Loop quine works particularly well for this!
```
{ } # A function literal
{# Without a matching }, this loops back to the second instruction, which essentially runs the function. This is a bug, but it works to make the "Looping Quine".
`{. # Append the literal {, stringifying the function.
* # Multiply the stringified function by the input.
¶ # Terminate the program.
```
[Try it online!](https://tio.run/##Kyooyk/P0zX6/786oVpP69C22ur///@bAgA "RProgN 2 – Try It Online")
[Answer]
# Mathematica, ~~40~~ 33 bytes
*Thanks to lanlock4 for saving 7 bytes!*
```
StringRepeat[ToString[#0], #1] &
```
Pure function taking a nonnegative integer argument. `ToString[#0]` is the standard Mathematica way to access the current pure function's definition; `StringRepeat[..., #1]` concatenates (input) copies of that string together. For example,
```
StringRepeat[ToString[#0], #1] & [2]
```
yields:
```
StringRepeat[ToString[#0], #1] & StringRepeat[ToString[#0], #1] &
```
[Answer]
# Python 2, 70 bytes
This solution works if `x=0`. There is a single trailing newline.
```
s='s=%r;exec"print%%r;"%%(s%%s)*input()';exec"print%r;"%(s%s)*input()
```
[**Try it online**](https://tio.run/nexus/python2#@19sq15sq1pknVqRmqxUUJSZV6IK5CmpqmoUq6oWa2pl5hWUlmhoqiMrAMkDpRGyXP//mwIA)
---
## Python 2, 60 bytes (invalid)
This assumes that `x>=1`, but the OP clarified that `x` can be zero. There is a single trailing newline.
```
s='s=%r;print(s%%s*input())[:-1]\n';print(s%s*input())[:-1]
```
[**Try it online**](https://tio.run/nexus/python2#@19sq15sq1pkXVCUmVeiUayqWqyVmVdQWqKhqRltpWsYG5OnDpdDk@L6/98UAA)
[Answer]
# [V](https://github.com/DJMcMayhem/V), 11 bytes
```
ÀñAÀÑ~"qpx
```
[Try it online!](https://tio.run/nexus/v#@3@44fBGRyAxsU5aqbCg4v///8YA "V – TIO Nexus")
This is an extremely trivial modification of the [standard extensible V quine](https://codegolf.stackexchange.com/a/100426/31716). We simply use `À` to run it *arg1* times.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 31 bytes
```
[[1-rd91Pn93P[dx]Pdx]s.rd0<.]dx
```
[Try it online!](https://tio.run/nexus/dc#M/4fHW2oW5RiaRiQZ2kcEJ1SERsAxMV6RSkGNnqxKRX//wMA "dc – TIO Nexus")
Explanation:
```
[[1-rd91Pn93P[dx]Pdx]s.rd0<.]dx
[ 91Pn93P[dx]P ]dx # Same old regular quine
[1-rd dx]s.rd0<. # Loop until the counter is zero
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 bytes
```
*E îQi"*E îQi"
```
[Try it online!](https://tio.run/##y0osKPn/X8tV4fC6wEwlGP3/vxEA "Japt – Try It Online")
[Answer]
# [Underload](https://esolangs.org/wiki/Underload), 12 bytes
```
(a(:^)*~^):^
```
[Try it online!](https://tio.run/nexus/underload#07CystLS0tL8r5GoYRWnqVUXp2kV9z/4PwA "Underload – TIO Nexus")
Function submission, because Underload has no other way to take input. (The TIO link shows the number 4 given as input, and adds code to print the resulting output).
This is just a universal quine constructor `(a(:^)*):^`, plus `~^` ("make a number of copies equal to the argument").
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes
```
"34çìDJ¹.D»"34çìDJ¹.D»
```
[Try it online!](https://tio.run/nexus/05ab1e#@69kbHJ4@eE1Ll6Hduq5HNqNxuX6/98AAA "05AB1E – TIO Nexus")
[Answer]
# [Python 2](https://docs.python.org/2/), 41 bytes
```
_="input('_=%r;exec _'%_*input())";exec _
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P95WKTOvoLREQz3eVrXIOrUiNVkhXl01XgsiqqmpBBX7/98YAA "Python 2 – Try It Online")
Does a kinda hacky output using `input` instead of `print`, since `print` has a weird bug involving printing a newline when it [isn't supposed to...](https://tio.run/##HcyxCoAgFEbh3acQQ65GONQYPcsdSsghFf2jenqLljN8w8kP9hTH1nhRuYQI4kWX2d9@NWxJcx9iPmHsoH6U3MKRU4GsT51F99VVbOmEu0qAN0RWdP9JEnwFtekF). Exits with an EOF error.
### Explanation:
```
_="input('_=%r;exec _'%_*input())"; # Set _ to a string
exec _ # Execute that string
input( ) # "print"
'_=%r;exec _'%_ # The source code with _ formatted in
*input() # Actual input many times
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
“;⁾vṾẋɠ”vṾ
```
[Try it online!](https://tio.run/nexus/jelly#@/@oYY71o8Z9ZQ937nu4q/vkgkcNc0Hs//@NAQ "Jelly – TIO Nexus")
### How it works
```
“;⁾vṾẋɠ”vṾ Main link. No arguments.
“;⁾vṾẋɠ” Set the argument and the return value to the string ';⁾vṾẋɠ'.
Ṿ Uneval; yield '“;⁾vṾẋɠ”'.
v Eval ';⁾vṾẋɠ' with argument '“;⁾vṾẋɠ”'.
‚Åæv·πæ Yield 'v·πæ'.
; Concatenate '“;⁾vṾẋɠ”' and 'vṾ', yielding the source code.
…† Read an integer from STDIN.
ẋ Repeat the source code that many times.
```
[Answer]
# [GNU Make](https://www.gnu.org/software/make/), 49 bytes
```
$(foreach ,$(shell seq $1),$(strip $(value $0)))
```
Make will join the copies by a single space, so I have to include the additional space character at the end and remove it with a `strip` in between in order to follow the requirement faithfully.
[Answer]
# Pyth, 17 bytes
```
j*]jN*2]"j*]jN*2]
```
[Try it online!](http://pyth.herokuapp.com/?code=j%2a%5DjN%2a2%5D%22j%2a%5DjN%2a2%5D&input=3&debug=0)
Trivial extension to the pretty-well-known `jN*2]"jN*2]` quine, but can probably be golfed down
[Answer]
## [Betaload](https://esolangs.org/wiki/Betaload), 203 bytes
Newlines added for clarity:
```
(a(:^)*(!()):#(}:(:)~^a((::*:**:*)*)~*(~*)*~(*)~^a*(*)*{)>(0)(!()){:^}(1)(){:^}(2)(:*){:^}(
3)(::**){:^}(4)(:*:*){:^}(5)(::*:**){:^}(6)(:*::**){:^}(7)(::*::***){:^}(8)(:*:*:*){:^}(9)(
::**::**){:^}R^^S):^
```
I gave myself the restriction that it must read from STDIN rather than from the top of the stack like an Underload answer typically would. I also used proper, decimal input, which makes up most of the code.
### Explanation:
I wrap the program up in a quine-wrapper: `(a(:^)*` and `):^`. This means all code inside the quine wrapper will have the program's source code at the bottom of the stack.
In order to convert digits into a normal Church numeral, I use the technique of replacing each digit with the code to multiply by 10 and add that digit:
```
0 -> (::*:**:*)*
1 -> (::*:**:*)*(:)~*(*)*
2 -> (::*:**:*)*(::)~*(**)*
3 -> (::*:**:*)*(:::)~*(***)*
```
There's a lot of repetition here, so let's package it up into a subprogram that will take a Church numeral from the top of the stack and use it to construct the "digit string:"
```
:(:)~^a((::*:**:*)*)~*(~*)*~(*)~^a*(*)*
```
I put this into a new environment so that it can be accessed quickly:
```
#(}:(:)~^a((::*:**:*)*)~*(~*)*~(*)~^a*(*)*{)>
```
Now I can create the replacement code for `R`. `R` uses the top elements of the stack to form a lookup table to replace a string from STDIN with Betaload code. It works like this:
```
()
(0)(code for 0)
(1)(code for 1)
(2)(code for 2)
...
R
```
However, we can use the subprogram we just made to generate the code segments:
```
(0)(!()){:^}
(1)(){:^}
(2)(:*){:^}
(3)(::**){:^}
...
```
When `R` is run, it will transform the input into a series of subprograms that build up a Church numeral. When this subprogram is executed, it creates that Church numeral on the next element on the stack (0, which was placed down earlier). This means that, after `R^`, the top value on the stack will be the Church numeral. We then `^` one more time to apply the Church numeral to the final element in the stack (the program's source code) to get the answer.
Fun fact: I've had the MD for this submission for several months. I'd kept it after misunderstanding a question (that I can't seem to find anymore). I had to dig it up from my Recycle Bin to post it here.
[Answer]
## Perl, 48 bytes
```
print"$_\47"x(2*pop)for'print"$_\47"x(2*pop)for'
```
`\47` is the octal escape for a single quote (`'`). It is interpreted inside double quotes (`"`), but not inside single quotes.
[Answer]
# Javascript ES6, ~~27~~ 37 bytes
```
_=>alert(`${f.name}=${f}`.repeat(_))
```
**Edit**
+10 bytes if `f=` should be also displayed
---
```
f=
_=>alert(`${f.name}=${f}`.repeat(_))
f(2);
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~20~~ 12 bytes
8 bytes saved thanks to Martin Ender
```
{"_~"+ri*}_~
```
[Try it online!](https://tio.run/nexus/cjam#@1@tFF@npF2UqVUbX/f/vykA "CJam – TIO Nexus")
### Exaplanation
```
{ e# Begin a block literal:
"_~"+ e# Add whatever's on the stack to the beginning of the array ['_', '~'].
ri* e# Repeat the resulting array a number of times equal to the input.
} e# Close the block. Push it on the stack.
_~ e# Copy it and run it.
```
[Answer]
# PHP, 194 bytes
```
<?php $a="PD9waHAgJGE9IiMiOyRpPSRhcmd2WzFdO3doaWxlKCRpLS0pZWNobyBzdHJfcmVwbGFjZShjaHIoMzUpLCRhLGJhc2U2NF9kZWNvZGUoJGEpKTs=";$i=$argv[1];while($i--)echo str_replace(chr(35),$a,base64_decode($a));
```
[Try it online!](https://tio.run/nexus/php#DczbCoIwGADgV4nYhUJB2QHEJDp5yg5oJhgRv9tqK2VDI8uXN@8/vmY2l0x2EJjd41qvwFk8PHuju3zHD79AHsOA4ZxocW2Rw4gIiL/ZdhVIPxzIJN6L9LesiePdcX6uUtt6JiF7guOKXR1JfxUw3/YY1iJtb@mv1n8SOxLtL7en0uwaiJsIisfnMrwaFeMZVRDv91WKmeiU7@JWUJkBpgpmhTKaqD0EvRRKOh3fCMWCtBxU1WiaZvgH "PHP – TIO Nexus")
Not golfy at all, as b64 quines tend to be.
[Answer]
# [Go](https://golang.org/), ~~257~~ 254 bytes
This pains me.
```
package main;import(."fmt";."strings";."strconv";."os");func main(){s:="package main;import(.\"fmt\";.\"strings\";.\"strconv\";.\"os\");func main(){s:=%q;n,_:=Atoi(Args[1]);Print(Repeat(Sprintf(s,s),n))}";n,_:=Atoi(Args[1]);Print(Repeat(Sprintf(s,s),n))}
```
[Try it online!](https://tio.run/nexus/go#lYzLCgIhGEZfJYRAQQai3cgs5g2ilk2EiIqEl/H/axM9u2m3TW3afeeDc0qS6iStXnjpgnA@xYy0I8YjER0BzC5YeE0Vw6XNCIQJcw7qIVF2hX4gPztTC03Vmd6pD7TYE2I9v3rLWQR@7IcRo6NjtrBfHZjY1AbSrU5aIt2lRoYCB8YDYzfyv1JKWd8B "Go – TIO Nexus")
[Answer]
# Microscript II, 22 bytes:
```
"v{lqp}sN*h"v{lqp}sN*h
```
# Microscript II, 20 bytes (but technically invalid as it accesses the source code of a code block):
```
{s""+`"~sN*"s`+}~sN*
```
[Answer]
# C, ~~144~~ 116 bytes
```
i;main(a){for(i=getchar()-48;i--;)printf(a="i;main(a){for(i=getchar()-48;i--;)printf(a=%c%s%c,34,a,34);}",34,a,34);}
```
[Answer]
# Python 3, 69 Bytes
```
s='s=%r\nx=int(input())\nprint(s%%s*x)\n'
x=int(input())
print(s%s*x)
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 115 bytes
```
n=>{var s="n=>{{var s={0}{1}{0};for(int i=0;i++<n;)Write(s,(char)34,s);}}";for(int i=0;i++<n;)Write(s,(char)34,s);}
```
[Try it online!](https://tio.run/##Sy7WTS7O/O@YXJKZn2eTmVdil2b7P8/WrrossUih2FYJxISyqw1qqw1rgaR1Wn6RBlCpQqatgXWmtrZNnrVmeFFmSapGsY5GckZikaaxiU6xpnVtrRLRSv9bc6VpGGpa/wcA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0"D34çý×?"D34çý×?
```
Modification of the default [quine](/questions/tagged/quine "show questions tagged 'quine'") [`0"D34çý"D34çý`](https://codegolf.stackexchange.com/a/97899/52210) by adding `×?`.
[Try it online.](https://tio.run/##yy9OTMpM/f/fQMnF2OTw8sN7D0@3R2L@/28MAA)
**Explanation:**
```
0 # Push 0 to the stack
# STACK: [0]
"D34çý×?" # Push the string 'D34çý×?' to the stack
# STACK: [0, 'D34çý×?']
D # Duplicate this string
# STACK: [0, 'D34çý×?', 'D34çý×?']
34ç # Push '"' to the stack
# STACK: [0, 'D34çý×?', 'D34çý×?', '"']
√Ω # Join the stack by this '"' delimiter
# STACK: ['0"D34çý×?"D34çý×?']
√ó # Repeat the string the (implicit) input amount of times
# input = 2 → STACK: ['0"D34çý×?"D34çý×?0"D34çý×?"D34çý×?']
? # Output to STDOUT without trailing newline
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~27~~ 25 bytes
```
"34çs«DJ¹FD,"34çs«DJ¹FD,
```
[Try it online!](https://tio.run/nexus/05ab1e#@69kbHJ4efGh1S5eh3a6ueigcbn@/zcBAA "05AB1E – TIO Nexus")
[Answer]
# Pyth, 13 bytes
```
*jN*2]"*jN*2]
```
[Test suite](https://pyth.herokuapp.com/?code=%2ajN%2a2%5D%22%2ajN%2a2%5D&test_suite=1&test_suite_input=1%0A2%0A3&debug=0)
The standard Pyth quine plus two `*` for the repetition.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
`I*`I*
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCJgSSpgSSoiLCIiLCI0Il0=)
Quine cheese (סּ͡͡ ◞סּ͡͡ )
## Explained
```
`I*`I*­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌­
`I*` # ‎⁡The string "I*"
I # ‎⁢with itself quoted, prepended
* # ‎⁣Repeated input times
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
] |
[Question]
[
Given a positive integer `n`, output a number meter formatted like this:
```
0 1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 1 2
```
The input number is 20 in this example.
More formally, the decimal representations of the numbers are arranged vertically, from most significant digits on the last row to least significant digits at the top, using space-padding.
All numbers should be printed, and any size of number is allowed.
An example solution in Python 3 follows:
```
def meter(top: int):
initial = list(str(str(n).ljust(len(str(top + 1)))) for n in range(1, top + 1))
rotated = list(zip(*initial))[::-1]
return "\n".join(" ".join(n) for n in rotated)
```
This is Code Golf! Make the answer with the lowest bytes to win.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 4 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
R↶ *
```
[Try it online.](https://dzaima.github.io/Canvas/?u=JXVGRjMyJXUyMUI2JTIwJXVGRjBB,i=MjA_,v=8)
**Explanation:**
```
R # Push a list in the range [1, (implicit) input-integer],
# and implicitly print each integer on a separated newline to the Canvas
↶ # Rotate the entire Canvas 90 degrees counterclockwise
* # Join each character on each line of the Canvas with a space delimiter
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 40 30 20 bytes
```
{" "/'|+(#$x)$$1+!x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pWUlDSV6/R1lBWqdBUUTHUVqyo5eJKMLBKUzAyANEaOkpKmjq6RgbK6mkKhgamXAAxmgrN)
-10 : more straightforward (less fun?)
-10 : Actual golfing courtesy of @coltim and @bstrat
[Answer]
# JavaScript (ES6), 69 bytes
Expects the input number as a string.
```
f=(n,d=0,i=n)=>i?f(n,d,i-1)+(`${i}`[d]||' ')+' ':n[++d]?f(n,d)+`
`:''
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfF1kAn0zZP09Yu0z4NxNfJ1DXU1NZIUKnOrE2ITomtqVFXUNfUBhJWedHa2imxEGWa2glcCVbq6v@T8/OK83NS9XLy0zXSNJSMDJQ0Nf8DAA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 40 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 5 bytes
```
ɾ∩Ṙ⁋øɽ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiyb7iiKnhuZjigYvDuMm9IiwiIiwiMjAiXQ==)
I honestly don't know how people find these obscure string overloads that I can never seem to remember.
## Explained
```
ɾ∩Ṙ⁋øɽ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌­
ɾ∩ # ‎⁡Transpose the range [1, input], treating digits as columns.
Ṙ⁋ # ‎⁢Reverse that, and join each sublist on spaces. Then, join that on newlines.
øɽ # ‎⁣Right align that. I honestly don't know why this works. It just does.
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `N`, 7 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
RðƬrðȷj
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPVIlQzMlQjAlQzYlQUNyJUMzJUIwJUM4JUI3aiZmb290ZXI9JmlucHV0PTIwJmZsYWdzPU4=)
#### Explanation
```
RðƬrðȷj # Implicit input
RðƬ # Transpose [1..input], filling with spaces
r√∞»∑j # Reverse and join each on spaces
# Implicit output, joined on newlines
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes
```
↑IEN⟦⊕ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMqtEBHwTmxuETDN7FAwzOvoLTErzQ3KbVIQ1NHIdozL7koNTc1ryQ1RSNTM1YTCKz//zcy@K9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
N Input as a number
E Map over implicit range
ι Current value
‚äï Incremented
‚ü¶ Make into sublist (causes the output to be double-spaced)
I Cast to string
↑ Print rotated 90°
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L€SζR»
```
[Try it online.](https://tio.run/##yy9OTMpM/f/f51HTmuBz24IO7f7/38gAAA)
**Explanation:**
```
L # Push a list in the range [1, (implicit) input-integer]
€S # Map each integer to a list of digits
ζ # Zip/transpose; swapping rows/columsn,
# with a space character to fill unequal length rows
R # Reverse this list of lists
» # Join each inner list by spaces, and then each string by newlines
# (after which the result is output implicitly)
```
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 55 bytes
```
;1+ I>a10X>b tpose _`"_`\" \"rep +` ; tk _` w>< n>o"map
```
[Try it here!](https://replit.com/@molarmanful/try-sclin) Takes input from the second line.
For testing purposes:
```
;1+ I>a10X>b tpose _`"_`\" \"rep +` ; tk _` w>< n>o"map
20
```
## Explanation
Prettified code:
```
; 1+ I>a 10X>b tpose _` ( _` " "rep +` ; tk _` w>< n>o ) map
```
Assuming input *n*:
* `; 1+ I>a` range `[1, n]`
* `10X>b` digitize (literally "convert each to base-10 digits")
* `tpose _`` transpose, reverse resulting lines
* `(...) map` map over each line...
+ `_` " "rep +` ; tk _`` left-pad with spaces to length *n*
- `_`` reverse
- `" "rep +`` concatenate to infinite list of spaces
- `; tk` take first *n* elements
- `_`` reverse again
+ `w>< n>o` join with space and output
The (current) lack of string manipulation commands present in sclin makes it a tad unwieldy for string challenges...
[Answer]
# [Python](https://www.python.org), 72 bytes
```
n=input()
*map(print,*(f'{j+1:<{len(n)}}'[::-1]for j in range(int(n)))),
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3PfJsM_MKSks0NLm0chMLNAqKMvNKdLQ00tSrs7QNrWyqc1LzNPI0a2vVo62sdA1j0_KLFLIUMvMUihLz0lM1gIqBskCgAzEPauyCRUYGEBYA)
-1 thanks to *@Arnauld* (by switching to Python 3.8)
-5 thanks to *@c--* (by using f-strings)
-12 thanks to *@loopy walt* (by using map rather than a for loop)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 79 bytes
```
->n{(1..n).map{d=_1.digits
[" "]*(n.to_s.size-d.size)+d}.transpose.map{_1*" "}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3_XXt8qo1DPX08jT1chMLqlNs4w31UjLTM0uKuaKVFJRitTTy9Ery44v1ijOrUnVTwJSmdkqtXklRYl5xQX5xKlhfvKEWUHVtLcTYVQWlJcUKbtFGBrEQgQULIDQA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
õs ÕÔˬ¸
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9XMg1dTLrLg&input=MTU)
[Answer]
# [R](https://www.r-project.org), 82 bytes
```
\(n)write(t(Reduce(cbind,strsplit(format(paste(1:n),j="l"),""))[nchar(n):1,]),1,n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3g2I08jTLizJLUjVKNIJSU0qTUzWSkzLzUnSKS4qKC3IySzTS8otyE0s0ChKLgYoMrfI0dbJslXKUNHWUlDQ1o_OSMxKLgGZYGerEauoY6uRpQkzemKZhrMmVpmFkACINDQyh4gsWQGgA)
[Answer]
# [J](http://jsoftware.com/), ~~25 23~~ 20 bytes
```
1j1#"#.0|.@|:1":@+i.
```
[Try it online!](https://tio.run/##VYyxCgIxEET7@4plU8Qjcc3GRlaFRcFKLGyvsJA79Bo/IPn3GCIiFgMz84aZC5KdYC9gwUMAqVoSHK/nU@GZDRoKmTQLo6h7Uum7y4FgkC2muNNE6D7cKMqiRunRcR22WcgyiF81FhN50R/vxvvjBRNsmrH2m2P4K27rAPWWK2GO5Q0 "J – Try It Online")
*-3 thanks to doug!*
* `1 ... +i.` 1...n
* `":@` Each of them formatted as a string
* `0|.@|:` Transposed and reversed
* `1j1#"#.` Add the space padding
[Answer]
# [Ruby](https://www.ruby-lang.org/), 68 bytes
```
->n{(0...s=n.to_s.size).map{|i|(0..n).map{_1.digits[i-s]||" "}*" "}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3XXTt8qo1DPT09Ipt8_RK8uOL9Yozq1I19XITC6prMmtAUnkQXryhXkpmemZJcXSmbnFsTY2SglKtFoiohZi1qqC0pFjBLdrIMBYisGABhAYA)
Inspired by Jordan's ruby answer, but different enough to merit a new post.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 57 bytes
```
.+
*¶
¶
$^$.>`#¶#¶
P^`.+
N$`.
$.%`
¶
~L$`#+
L`.{$.&}
A`#
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS@vQNi4gUolT0bNLUD60DYi4AuISgDJ@Kgl6XCp6qgkgea46H5UEZW0unwS9ahU9tVouxwTl//@NDAA "Retina – Try It Online") Explanation: Based on my golf to @TwiNight's answer to [Enklactify these strings](https://codegolf.stackexchange.com/q/164208/) to transpose the text.
```
.+
*¶
¶
$^$.>`#¶#¶
```
Create a range from `1` to the input, but with the digits reversed, and each line padded with a `#`, and the lines separated by a line with just a `#`.
```
P^`.+
```
Left pad everything with spaces so that it lines up.
```
N$`.
$.%`
```
Sort all characters by their column index.
```
¶
~L$`#+
L`.{$.&}
```
Complete the transposition by joining everything together and then splitting by the number of `#`s.
```
A`#
```
Remove the final line, which will always be the `#`s.
[Answer]
# Excel, 49 bytes
```
=MID(SEQUENCE(,A1),1+LEN(A1)-SEQUENCE(LEN(A1)),1)
```
Input in cell `A1`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
Ṿ€z⁶ṚG
```
[Try it online!](https://tio.run/##ARoA5f9qZWxsef//4bm@4oKseuKBtuG5mkf///8yMA "Jelly – Try It Online")
-2 thanks to *@UnrelatedString*
#### Explanation
```
Ṿ€z⁶ṚG # Main link - argument n
€ # To each number in the range [1..n]:
·πæ # Convert it to a string
z⁶ # Transpose using filler space
·πö # Reverse this list of lists
G # Format as a grid
# (join each on spaces, then newlines)
```
[Answer]
# [jq](https://stedolan.github.io/jq/), ~~68~~ 66 bytes
***-2 bytes** with a better use of `range`*
```
[range(.)+1|@sh/""]|transpose|map(map(.//" ")|join(" "))|reverse[]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70oq3BZtJJukVLsgqWlJWm6FjedoosS89JTNfQ0tQ1rHIoz9JWUYmtKgGLFBfnFqTW5iQUaIKynr6-koKRZk5WfmacBYmnWFKWWpRYVp0bHQkyCGrhguZEBl6GBgQGECwA)
~~[Attempt This Online!](https://ato.pxeger.com/run?1=m70oq3BZtJJukVLsgqWlJWm6FjddoosS89JTNQytDbX1NGscijP0lZRia0qAosUF-cWpNbmJBRogrKevr6SgpFmTlZ-ZpwFiadYUpZalFhWnRsdCzIIauWC5kQGXoYGBAYQLAA)~~
```
[
range(.) + 1 # `range` generates 0 to n - 1; add 1
| @sh / "" # Since numbers do not have spaces or special characters,
# `@sh` behaves the same as `@text`/`tostring`.
# `/ ""` splits into an array of characters
] # `[ ... ]` collects values into an array
| transpose # transpose, filling missing values with null.
| map(
map(.//" ") # replace null with space
| join(" ") # join on spaces
)
| reverse[] # most-significant digits last.
```
] |
[Question]
[
# Rules
You will receive as input a list that contains integers and strings. Your task is to move all of the strings to the end of the list and all of the integers to the beginning of the list.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the answer with the least number of bytes wins.
[Answer]
# [Python 3](https://docs.python.org/3/), 24 bytes
```
lambda l:l.sort(key=dir)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHHKkevOL@oRCM7tdI2JbNI83@OrUK0UqKSjoKhjoJSEpA2AtLJQNoYSBsCaSUjEGGsFMuVppGjyVVQlJlXAmT8BwA "Python 3 – Try It Online")
Sorts in place, modifying the input list. It so happens that the `dir` of a number is smaller than that of a string because the `__abs__` method that numbers have comes alphabetically first.
```
>> dir(1)
['__abs__', '__add__', '__and__', ...]
>> dir('a')
['__add__', '__class__', '__contains__', ...]
```
The only built-in to use as a key that would be shorter than `dir` is `id`, but it seems to puts strings before numbers, and I don't know if its behavior is consistent.
---
# [Python 2](https://docs.python.org/2/), 6 bytes
```
sorted
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzvzi/qCQ15X@OrUK0UqKSjoKhjoJSEpA2AtLJQNoYSBsCaSUjEGGsFMtVUJSZV6KQppGj@R8A "Python 2 – Try It Online")
Python 2 allows comparing different types, and conveniently numbers come before strings.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte
05AB1E does this *exactly* as specified.
```
{
```
[Try it online!](https://tio.run/##yy9OTMpM/f@/@v//aEMdpUQlHSMdYx2lJCUdpWSlWAA "05AB1E – Try It Online")
[Or, verify all test cases (so far)](https://tio.run/##yy9OTMpM/X9u6//q/7X/o6MNdZQSlXSMdIx1lJKUdJSSlWJ14GJAkdhYAA)
# Explanation
Even if the answer is a one-byte answer, I still feel like typing the explanation.
```
Implicit input as a list
{ Sort the list (numbers go before the strings)
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 1 byte
```
∧
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HH8v9pj9omPOrte9Q31dP/UVfzofXGj9omAnnBQc5AMsTDM/g/kPYK9vdTSFOAstSjDXWUEpV0jHSMdZSSlHSUkpVi1bnwKAMqilUHAA "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 4 bytes
```
Sort
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277Pzi/qOR/QFFmXomCQ3p0taGOUqKSjpGOUpJSbez//wA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# JavaScript (ES6), 31 bytes
```
a=>a.sort((a,b)=>!b.big-!a.big)
```
[Try it online!](https://tio.run/##FcVBCoAgEADAr6SnFUywzvqR6LBrJUW4kdH3N5vLHPhiTfd@PX3hZZUtCIaIrvL9AKAlE6IiR3vuFf4ZSVwqn6s7OcMGk/badt52mtpDO7XH2Rj5AA "JavaScript (Node.js) – Try It Online")
### How?
The deprecated but still widely supported method [`.big()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/big) is defined for Strings and undefined for Numbers. Hence the sorting criterion `!b.big-!a.big` which is either \$-1\$, \$0\$ or \$1\$.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~30~~ 24 bytes
```
->l{l.sort_by &:methods}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkevOL@oJD6pUkHNKje1JCM/pbj2f4FCWnS0UqKSjoKhjoJSEpA2AtLJQNoYSBsCaSUjEGGsFBv7HwA "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 33 bytes
```
L.sort(key=lambda x:str(type(x)))
```
[Try it online!](https://tio.run/##K6gsycjPM/7vo2CrEK2UqKSjYKijoJQEpI2AdDKQNo7976NXnF9UopGdWmmbk5iblJKoUGFVXFKkUVJZkKpRoamp@b@gKDOvRMNH8z8A "Python 3 – Try It Online")
And in fact this is how I'd write it in live code too, probably...
[Answer]
# [Red](http://www.red-lang.org), 23 bytes
```
func[x][reverse sort x]
```
[Try it online!](https://tio.run/##DcUxDoAgDAXQ3VP89A5q4jFcm07QJixgChJuX33Lc81xa2bZ7Ap7a@Il7DrVu6I3H1gSj5c6YGBqVQlkZf7tOA9QallJ4gM "Red – Try It Online")
[Answer]
# Java 8, ~~43~~ 41 bytes
```
L->{L.sort((i,j)->i==i.toString()?1:-1);}
```
-2 bytes thanks to *@Neil*.
Input as a `List` of `Object`s, with `String` and `Integer` items.
[Try it online.](https://tio.run/##jVLLbsIwELzzFas9OYpjNVD1wFO9p7QSR9qDCQY5DTGKFyqK@PbUcUKFCq16SWTPY2c2yeReRtnyvUpzaS08SV0cOwC6IFWuZKpgWh8B9kYvIWWZo4sd6Vwk2tLweZGplMaQBAPHOnXcw5IkncIUChhBlUTjYyKsKYkxzbMgGuvRSAsyMyp1sWbBJO5HcTA4VYNavN0tciduPfzMjUvEGvb8DWTQxCFlicX8nmMXOabIH3yCFkCJPOa4QN71YI9jjA21h1dR/Riva@oIIb7n/NI3dwdXr1AfF4zHspQHTxuzH7dWSFsjTAZtzm2piA4vrhax2q29nh0sqY0wOxJbj2EfsMUKkV5S/@mQF@x240v9HzXbRVwHm59zrUzJ3A3o0d0A9LAWCas/lZsLrRqgsQTjtuYJa0VMtwY33Jlxv6BLW6TKrKD5/BPAV8TQhPUL@mACCIGFoYYhXAwFx@M1jm943vbJL@BUfQE)
**Explanation:**
```
L->{ // Method with Object-List parameter and no return-type
L.sort( // Sort the List by:
(i,j)-> // For every pair of items `i,j`:
i==i.toString()? // If `i` is a String (by checking whether `i` and the builtin
// String-conversion of `i` reference the same instance):
1 // Put it after item `j`
: // Else:
-1);} // Put it before item `j`
```
[Answer]
# [~~Perl 6~~ Raku](https://github.com/nxadm/rakudo-pkg), ~~15~~ 14 bytes
-1 thanks to Jo King.
```
*.sort(*~~Str)
```
[Try it online!](https://tio.run/##HY7BCsIwGIPve4qAYHWMoh4EGT6AZ4/iobpMh2s3@v9DvPjqs/UQEsJHyMjY72f/wbLFcS6tDFFX5fd71rie66JYwI4JQSeYhA2ejIQO8O5FdAo66Rhzo@x7vJ/UhIA9PYMKXMLD5G@MgiFCNHbhIRYnTZPBKALZsLGFuA/a1cW4291UOBwqmG0KpmGbbZfLCttN1ua6/r@q5x8 "Perl 6 – Try It Online")
This is an anonymous WhateverCode function nested within another. I didn't know I could do that.
[Answer]
# [Python 3](https://docs.python.org/3/), 78 bytes
```
lambda x:[*filter(lambda _:type(_)==int,x)]+[*filter(lambda _:type(_)==str,x)]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PycxNyklUaHCKlorLTOnJLVIAyoSb1VSWZCqEa9pa5uZV6JToRmrjUdJcUkRSMn//wA "Python 3 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ñy
```
[Test it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8Xk&input=WyJhIiwiYiIsImMiLCIxIiwxLCIyIiwyLCIzIiwzXQotUQ)
[Answer]
# [PHP](https://php.net/), 20 bytes
```
fn(&$a)=>sort($a,2);
```
[Try it online!](https://tio.run/##RYyxCgIxEET7/YphWSSBbTzLGP2QI0g8PHLNXUjSid8eY2U3894wOeV@veeUQSQbPGaaz8qRddKL8pOVFw76hwMFCm6sq@/rbk4Srb/VozQjUSfr@nDrUV5xSQbjMlZIg8WbAKlGmoUbMZdtb4/y644@6F8 "PHP – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 36 bytes
```
p=egrep\ ^-?[0-9]+$
tee a|$p
$p -v<a
```
[Try it online!](https://tio.run/##S0oszvj/v8A2Nb0otSBGIU7XPtpA1zJWW4WrJDVVIbFGpYBLpUBBt8wm8f9/U2MTrsSkZK5EUy4uy2KuikqjbC5dY0MDLkMjEwA "Bash – Try It Online")
A value is considered to be an integer if: (1) the first character is either a digit or a minus sign; (2) any other characters are all digits; and (3) at least one digit is present. Any value that is not an integer is considered to be a string.
[Answer]
# [R](https://www.r-project.org/), 26 bytes
```
function(L)sort(unlist(L))
```
Straightforward: `unlist` then `sort` the list `L`. Works because digits sort before alphabetic letters, be them upper or lower case.
[Try it online!](https://tio.run/##K/r/P600L7kkMz9Pw0ezOL@oRKM0LyezuATI0/z/HwA "R – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 117 bytes
```
f(a,l,p,c)struct{int*s,i;}*a,*p;{for(c=l,p=a;c--;p++)p->s?:printf("%d ",p->i);for(;l--;a++)a->s&&printf("%s ",a->s);}
```
C does not have lists of combined strings and integers so instead I use an array of structures; if the string is `NULL` (which a real string never will be), then print the integer instead. Of course, go over the list an print the integers first, then the strings.
Stable sort.
[Try it online!](https://tio.run/##bdBLTsMwEAbgfU4xskRlpxORtjtGgYNUXRi3AUttYtkOC6KcPYyTAg3UG3t@f36a4s2YcaylxjM6NCpE35nY2ybmAS0NucbcUV@3XpqKSaXJFAW59Vq54jm8PDnPtpbi4QgCObKKEqYzK81Ks1qtflRglSJFwzifBbZxXQxZnwE386495IGmgteApWygLEvDi7aN/GjtUV3xYoNrtz9ANU3OZBoJLRDKAX@TEmFzW4vXO2K7EOaO2C3E5q8Q23/J7iZJ70p9LeerIwT7eWq/S/W4KPflQan5X/wpdr6Bkr9m/AI "C (gcc) – Try It Online")
[Answer]
# T-SQL, 35 bytes
Decimals will be placed in the integer section
```
DECLARE @ table(a varchar(99))
INSERT @ values('1'),('a'),('abc'),('1'),('d'),('84753')
SELECT*FROM @ ORDER BY-isnumeric(a)
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 2 bytes
```
><
```
[Try it online!](https://tio.run/##SyotykktLixN/V@tZKikoGBkrKBkpKSglJiUrKRgqGBc@9/O5v9/AA "Burlesque – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
o$dir(N)
```
I don't know what it is about python eval that makes me feel like I'm bending the rules, but I like it :)
[Try it online!](https://tio.run/##K6gsyfj/P18lJbNIw0/z//9oQx2lgABndyUdBUMTIx0FJc8S9WKF5PycFIXMPIWM1KJUBSsNpdh/@QUlmfl5xf91UwA "Pyth – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 24 bytes
```
O$^m`^(-?[0-9]+$)?.*$
$1
```
[Try it online!](https://tio.run/##K0otycxL/P/fXyUuNyFOQ9c@2kDXMlZbRdNeT0uFS8Xw//9ELkOuJC4DrmQuXUMA "Retina 0.8.2 – Try It Online") Explanation:
```
m`^(-?[0-9]+$)?.*$
```
Match each line, capturing it if it's an integer.
```
O$
$1
```
Sort the matches by the captured integer, as a string. This sorts non-integers to the beginning as nothing was captured which results in the empty string in the substitution.
```
^
```
Reverse the list after sorting.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
F²ΦEθ⭆¹κ⁼ι⁼κ§θλ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw0hTIaAoM69Ewy0zpyS1SMM3sUCjUEchuAQomA7iGOooZGtq6ii4FpYm5hRrZMJZ2ToKjiWeeSmpFSANOZogYP3/f3S0UqKSjgJQm1ISkDYA0slAWtcwNva/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²
```
Make two passes over the input items.
```
Eθ⭆¹κ
```
Stringify all the input items...
```
Φ...⁼ι⁼κ§θλ
```
... and filter on those elements that are not or are unchanged under stringification respectively.
[Answer]
# Batch, 320 Bytes
```
@ECHO OFF
Setlocal EnableDelayedExpansion
Set /P S=Str:
FOR %%B IN (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) DO (
IF "!L!"=="" (Set L=!S:%%B= !) Else (Set L=!L:%%B= !)
)
FOR %%C IN (0,1,2,3,4,5,6,7,8,9) DO (
IF "!R!"=="" (Set R=!S:%%C= !) Else (Set R=!R:%%C= !)
)
Set S=%L: =%%R: =%
ECHO(%S%
pause
```
[Answer]
# [Kotlin](https://kotlinlang.org), 41 bytes
Expects and returns a `List<Any>`. The order of ints and strings in the returned list should be stable.
```
{it.partition{it is Int}.let{(a,b)->a+b}}
```
[Try it online!](https://tio.run/##PYzLCsIwEEX3/YphVglOC742YgMuBcFvSNXAYJyWdhSk5Ntj24V3czmLc56tRpb88RHCAcyFBz2e5OsslA7@BHUeWavO98rKrUwAPMBZNFXxoaPx1NjS@VWTUg5vgZdnMRbGAqbN8TiloF7uGpamWdOG0CNhg7QlvCHtaE94R7tYXc@iJphZsbZIkH8 "Kotlin – Try It Online")
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$4\log\_{256}(96)\approx\$ 3.292 bytes
```
^'#s
```
[See the README to see how to run this](https://github.com/Seggan/Fig/blob/master/README.md)
```
^'#s # Expects the list as input
^' # Sort the input using the following function as a key:
#s # Is string?
```
[Answer]
# [Factor](https://factorcode.org/), 29 bytes
```
[ [ real? 0 1 ? ] sort-with ]
```
[Try it online!](https://tio.run/##HcwxCsJAEAXQPqf4TK8oooIWKcXGJliFFEuYJIPrbBgnBBHPvgYP8F4XWk@W79X1djnhwaYc8Qw@4JXMRXuMxu7v0UQd56L4YAvyORF2oC5NRtjjgCOIpR@cQCrKhG@uUcM4xBKbxZRo/uVqliVvchtixDr/AA "Factor – Try It Online")
Is it a real number? Then sort it as though it were 0. Otherwise, sort it as though it were 1.
[Answer]
# [Uiua](https://uiua.org), 3 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
⊏⍏.
```
[Try it!](https://uiua.org/pad?src=0_3_1__ZiDihpAg4oqP4o2PLgoKZiB7ImFiYyIgMTUgImRlZiIgMSAyfQo=)
This is the default behavior of sorting a boxed list in Uiua.
```
⊏⍏.
. # duplicate
⍏ # rise (grade up)
⊏ # select
```
[Answer]
# [Scala 3](https://www.scala-lang.org/), 75 bytes
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=dVLRSsMwFAUf9xWXPCXaDreJSF0He1ZBEPGhlpF17ZYxU0nipI5-iS--6ItfNL_Gmybb3MBCc5N7zs09ycn7l874gve-ExLK8pUrSdL1aTme55mBGy4krFqtFsCSL0BG9FpokwxllcaD7ZRB_PliivBifTVq61KZB2Fmq4zrnIrozighp8E8QiaLB91-59IjmMC0wy0ycAiMmnnttvw5YgCTvIAnlEK5muoIhkrxKnGFKYvgXgoDMeoE_EyuDe0EcBYA6RIcMhzO2Q4jHBNIIGOMXU_oYeyQTUmPWH5tj21bN2Uc-8rq-LDdkitY4EVggrdNae-kyT-r3JjqFiUaanHms3ZNIiBu7SvlHuXfwoWke7oOqRHsLDmQ6Rsnvm9RKqAC-mGjoC3kRGS5Zp7szC6x2KJUMJ8t0QSTzbYsgMYvdMR5AfFg0-iREDgBjb-dsv2C0Y5YbqDaR1E0wpwuLd5yCKHDNtsGfqv676FS75Z_MR8fLv4C)
```
_.sortWith{case(i:String,j:Any)=>2<1;case(i:Any,j:String)=>2>1;case _=>2>1}
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=dVO9TsMwEB7YOvAMJ08JJJHaIoQiisReEBJCDKGqXNcproKNbLeooDwJCwssvBFPw9lxaFOJIT777vvuJ5_9_mUYrejwuyCpVC9USzL5-FzZMj37OThUsyVnFq6okPDWA7CaCgvXfg8w5yWwaJzDWBhbXMrNJN7ZI6Tu4bKmFcgcSSPoYmF0ERKNM6O0vRf2MTgAGDUcIpHDrdVCLhJY5oAsTyppZfg-DoMe1OA9zupVBzbtOOu2QTfGE04YUb0wmEhruimaNG6gO4kjj0Jjlhsb9RM4SYAMCC4Ml9N4GyMUHQggM7SDABii7ZOWMiTxbmlPo36Ao_1ya6qhwh-GDppZ5f6d9z9rbu3mBlu0kYvHwevOJAfSnANTZqwD-pdayajT2T60K3Sn0VC6CJVLpVEUOE99D5mQc8G4if_UdXdCIdlFIxEHr0IZLNvegSCbaUV18oVCD4TAMRj83DbuEqZboGpDdbCi9I01fRnxyiGFftymTUKqeneoSdCrbp5FeB0fwf4C)
```
object Main {
trait N {
def c(L: List[Any]): List[Any]
}
val n: N = (L: List[Any]) => {
L.sortWith {
case (i: String, j: Any) => false
case (i: Any, j: String) => true
case _ => true
}
}
def main(args: Array[String]): Unit = {
test(1, 4, "2", "c", 6)
test("a", 1, "b", 2, "c", 3, "1", "2", "3")
}
def test(a: Any*): Unit = {
var list = a.toList
prettyPrint(list)
print(": ")
list = n.c(list)
prettyPrint(list)
println()
}
def prettyPrint(list: List[Any]): Unit = {
print("[")
for (i <- list.indices) {
val o = list(i)
o match {
case s: String => print("\"" + s + "\"")
case _ => print(o)
}
if (i < list.size - 1) print(",")
}
print("]")
}
}
```
] |
[Question]
[
I was asked this question in an interview but I was unable to figure out any solution. I don't know whether the question was right or not. I tried a lot but couldn't reach any solution. Honestly speaking, nothing came to my mind.
## Rocco numbers
A positive integer \$n\$ is a Rocco number if it can be represented either as \$n=p(p+14)\$ or \$n=p(p-14)\$, where \$p\$ is a prime number.
The first 10 Rocco numbers are:
$$32, 51, 95, 147, 207, 275, 351, 435, 527, 627$$
## Task
Your code must accept a positive integer as input and determine if it is a Rocco number or not.
## Brownie points
* Write a function that calculates and prints the count of Rocco numbers less than or equal to 1 million.
* Write a function that calculates and prints the count of Rocco numbers from the bonus question (above one) that are prime.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
Returns \$1\$ if \$n\$ is a Rocco number, or \$0\$ otherwise.
```
fDŠ/α14å
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/zeXoAv1zGw1NDi/9/9/IwswcAA "05AB1E – Try It Online")
### How?
Given a positive integer \$n\$, we test whether there exists a prime factor \$p\$ of \$n\$ such that:
$$\left|p-\frac{n}{p}\right|=14$$
### Commented
```
fDŠ/α14å # expects a positive integer n as input e.g. 2655
f # push the list of unique prime factors of n --> 2655, [ 3, 5, 59 ]
D # duplicate it --> 2655, [ 3, 5, 59 ], [ 3, 5, 59 ]
Š # moves the input n between the two lists --> [ 3, 5, 59 ], 2655, [ 3, 5, 59 ]
/ # divide n by each prime factor --> [ 3, 5, 59 ], [ 885, 531, 45 ]
α # compute the absolute differences
# between both remaining lists --> [ 882, 526, 14 ]
14å # does 14 appear in there? --> 1
```
[Answer]
# JavaScript (ES7), 55 bytes
```
n=>(g=k=>k>0&&n%--k?g(k):k==1)(n=(49+n)**.5-7)|g(n+=14)
```
[Try it online!](https://tio.run/##DYtBDoIwEADvvGIvNrs0JTTBGMStbyFIGy3ZGiBc1LfXzmXmMq/xGLdpfb53I@kxZ89Z2GHgyC66Vik5GRPvASNdI7MlFMau10J13ZzNhb4BRbPtKPu0ogCDHUDgVtwWSmtN8KkAPAqBUjAl2dIyN0sqKw3VL/8B "JavaScript (Node.js) – Try It Online")
### How?
Given a positive integer \$n\$, we're looking for a prime \$x\$ such that \$x(x+14)=n\$ or \$x(x-14)=n\$.
Hence the following quadratic equations:
$$x^2+14x-n=0\tag{1}$$
$$x^2-14x-n=0\tag{2}$$
The positive root of \$(1)\$ is:
$$x\_0=\sqrt{49+n}-7$$
and the positive root of \$(2)\$ is:
$$x\_1=\sqrt{49+n}+7$$
Therefore, the problem is equivalent to testing whether either \$x\_0\$ or \$x\_1\$ is prime.
To do that, we use the classic recursive primality test function, with an additional test to make sure that it does not loop forever if it's given an irrational number as input.
```
g = k => // k = explicit input; this is the divisor
// we assume that the implicit input n is equal to k on the initial call
k > 0 && // abort if k is negative, which may happen if n is irrational
n % --k ? // decrement k; if k is not a divisor of n:
g(k) // do a recursive call
: // else:
k == 1 // returns true if k is equal to 1 (n is prime)
// or false otherwise (n is either irrational or a composite integer)
```
Main wrapper function:
```
n => g(n = (49 + n) ** .5 - 7) | g(n += 14)
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~45~~ 28 bytes
```
((*+49)**.5+(7|-7)).is-prime
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfQ0NL28RSU0tLz1Rbw7xG11xTUy@zWLegKDM39b81V3FipUJ6UWqBhlqajoKhnp6WZnScoUHsfwA "Perl 6 – Try It Online")
Uses [Arnauld's construction](https://codegolf.stackexchange.com/a/179339/76162), that \$\sqrt{n+49}\pm7\$ must be prime for \$n\$ to be a Rocco number.
### Explanation:
```
(*+49)**.5 # Is the sqrt of input+49
+(7|-7) # Plus or minus 7
( ).is-prime # Prime?
```
[Answer]
# Regex (ECMAScript), ~~64~~ 62 bytes
```
^(?=(x((x{14})(x+)))(?=(\1*)\4\2*$)(\1*$\5))\6\3?(?!(xx+)\7+$)
```
[Try it online!](https://tio.run/##TY/LbsIwFER/BRCCe5MmJBSohGuy6oINi3bZtJIFl8StcSzbQMrj29NkUam70ZwjjeZLnITbWml85IzckT1U@pt@Gss1nXuvVLzUBuDCV5Og@YSMQw1QX9PZHaEOEbGr8jTAfJZPgyF2eZjPEfNF/phB1oe61fKncIhNMLlg7Ks3b6UuAGOn5JZg8RDNEJnjCTuXUhGA4pbETklNgNjn@qgUXguuYmeU9DCOxsjkHkDzIlakC1/ianq7SbcRG5DcCOtorT0U78kH4h@g/0Cv0ixddhh9aavzYK1PQsldzwpd0LI3CBXbVxaYfObEZBhiOzioB7ElQ8KDxPgg/LYEi3h1o5FpL3noXqTMHL3ztlXY/d4k0XSeJL8 "JavaScript (SpiderMonkey) – Try It Online")
Takes its input in unary, as a sequence of `x` characters whose length represents the number.
This regex finds two numbers \$a\$ and \$a+14\$ such that \$n=a(a+14)\$. If it finds them, it then asserts that either \$a\$ or \$a+14\$ is prime.
The multiplication algorithm implemented here searches for two unknown factors which, when multiplied together, equal a known product. The regex for this is also essentially equivalent to that of the shortest form of multiplication for asserting that two known factors multiply to make a known product.
In many of my other posted regex answers, multiplication is implemented as finding the unknown product of two known factors; the shortest form of that is different. Both methods would work in both circumstances, but golf-wise, they're worse at doing each other's job.
Here is an explanation of how this form of multiplication works in general:
We have \$AB \stackrel{?}{=} C\$, where \$A \ge B\$. The steps to asserting \$AB=C\$ are (shown here in an order that's easier to explain conceptually; in the regex they're done in the order that results in the best golf):
* Assert that \$C-A \equiv 0 \pmod A\$
+ This is equivalent to \$C \equiv 0 \pmod A\$, a direct consequence of \$C=AB\$
* Assert that \$C-A-(B-1) \equiv 0 \pmod {A-1}\$,
+ This can be shown to result from \$C=AB\$:
\$\begin{aligned}C-A-(B-1) &= AB-A-(B-1) \\ &= A(B-1)-(B-1) \\ &= (A-1)(B-1)\end{aligned}\$
* Assert that there is no \$0<D<C\$ which satisfies both of the above with \$D\$ in place of \$C\$
This can be expressed as:
* Assert that the only \$0<E \le C-A\$ that satisfies the following moduli is \$E=C-A\$:
+ \$E \equiv 0 \pmod A\$
+ \$E \equiv B-1 \pmod {A-1}\$
We now have two coprime moduli, \$A\$ and \$A-1\$. By the [Chinese remainder theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem), there is one and only one integer \$E\$ such that \$0 < E \le A(A-1)\$, or alternatively stated, \$0 < E+A \le A^2\$, and the above moduli are satisfied. And since we know \$B\le A\$, it follows that \$AB\le A^2\$.
The algebra above shows there is at least one \$E\$ satisfying the moduli: \$E=AB-A\$. The Chinese remainder theorem shows that there is exactly one \$E\$ satisfying the moduli within a certain range. The fact that \$B\le A\$ guarantees that \$AB-A\$ falls inside that range. We are not guaranteed that \$C\le A^2\$, but as long as we search for the *smallest* \$E\$ satisfying the moduli, we're guaranteed that \$E=AB-A\$, so if \$E=C-A\$, then \$AB=C\$.
The regex essentially searches for the smallest \$E\$ satisfying the moduli, then asserts that \$E=C-A\$. The assertion of \$C \equiv 0 \pmod A\$ is done afterward, making the regex a bit slower in the name of golf.
Also note that in regex, \$0 \equiv 0 \pmod 0\$, so the algorithm works for \$A=1\$ without any need for a special case.
In cases where we don't know whether \$A\ge B\$, and can't capture them at the source in such a way as to automatically sort them as such, we can simply assert both versions of each:
* \$C \equiv 0 \pmod A\$
* \$C \equiv 0 \pmod B\$
* \$C-B \equiv 0 \pmod {A-1}\$
* \$C-A \equiv 0 \pmod {B-1}\$
This makes for shorter golf than actually sorting \$A\$ and \$B\$ into lesser and greater after they've already been captured. But for this particular problem, only the two assertions need to be used, since by definition \$A=B+14\$.
And the regex, pretty-printed and commented:
```
# For the purposes of these comments, the input number = N.
^
# Find two numbers A and A+14 such that A*(A+14)==N.
(?=
(x((x{14})(x+))) # \1 = A+14; \2 = \1-1; \3 = 14; \4 = A-1; tail -= \1
(?= # Assert that \1 * (\4+1) == N.
(\1*)\4\2*$ # We are asserting that N is the smallest number satisfying
# two moduli, thus proving it is the product of A and A+14
# via the Chinese Remainder Theorem. The (\1*) has the effect
# of testing every value that satisfies the "≡0 mod \1"
# modulus, starting with the smallest (zero), against "\4\2*$",
# to see if it also satisfies the "≡\4 mod \2" modulus; if any
# smaller number satisfied both moduli, (\1*) would capture a
# nonzero value in \5. Note that this actually finds the
# product of \4*\1, not (\4+1)*\1 which what we actually want,
# but this is fine, because we already subtracted \1 and thus
# \4*\1 is the value of tail at the start of this lookahead.
# This implementation of multiplication is very efficient
# golf-wise, but slow, because if the number being tested is
# not even divisible by \1, the entire test done inside this
# lookahead is invalid, and the "\1*$" test below will only
# fail after this useless test has finished.
)
(\1*$\5) # Assert that the above test proved \1*(\4+1)==N, by
# asserting that tail is divisible by \1 and that \5==0;
# \6 = tool to make tail = \1
)
# Assert that either A or A+14 is prime.
\6 # tail = \1 == A+14
\3? # optionally make tail = A
(?!(xx+)\7+$) # Assert tail is prime. We don't need to exclude treating
# 1 as prime, because the potential false positive of N==15
# is already excluded by requiring \4 >= 1.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~13~~ 12 bytes
```
ṗ;14{+|-};?×
```
Enter the candidate number as a command-line argument. Outputs `true` or `false`. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HO6daGJtXaNbq11vaHp////9/IwBwA "Brachylog – Try It Online")
### Explanation
The code is a predicate whose input is unconstrained and whose output is the number we're testing.
```
ṗ Let the input ? be a prime number
;14 Pair it with 14, yielding the list [?, 14]
{+|-} Either add or subtract, yielding ?+14 or ?-14
;? Pair the result with the input, yielding [?+14, ?] or [?-14, ?]
× Multiply; the result must match the candidate number
```
(Tips are welcome. That `{+|-}` still feels clunky.)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
Different approach then [DLosc](https://codegolf.stackexchange.com/users/16766/dlosc)'s [answer](https://codegolf.stackexchange.com/a/179997/81957)
```
Ċ-14&∋ṗ&×
```
Takes N as output, gives [P, P-14] or [P+14,P] back through input (biggest number first)
## explanation
```
Ċ # The 'input' is a pair of numbers
-14 # where the 2nd is 14 smaller then the first
&∋ṗ # and the pair contains a prime
&× # and the numbers multiplied give the output (N)
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//0iXrqGJ2qOO7oc7p6sdnv7//39TQwA "Brachylog – Try It Online")
[Answer]
# Pyth, ~~22~~ 20 bytes
```
}Qsm*Ld+Ld_B14fP_TSh
```
Try it online [here](https://pyth.herokuapp.com/?code=%7DQsm%2aLd%2BLd_B14fP_TSh&input=51&debug=0).
```
}Qsm*Ld+Ld_B14fP_TShQ Implicit: Q=eval(input())
Trailing Q inferred
ShQ Range [1-(Q+1)]
fP_T Filter the above to keep primes
m Map the elements of the above, as d, using:
_B14 [14, -14]
+Ld Add d to each
*Ld Multiply each by d
s Flatten result of map
}Q Is Q in the above? Implicit print
```
*Edit: Saved 3 bytes as input will always be positive, so no need to filter out negative values from the list. Also fixed a bug for inputs `1` and `2`, costing 1 byte. Previous version: `}Qsm*Ld>#0+Ld_B14fP_TU`*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ ~~15~~ 14 bytes
Saved 1 byte by computing 14 with `7·` instead of `žvÍ` (cant believe I didnt think of this in the first place).
Saved 1 byte thanks to Emigna
```
ÅPε7·D(‚+y*Q}Z
```
[Try it online!](https://tio.run/##ASMA3P9vc2FiaWX//8OFUM61N8K3RCjigJoreSp9y5xzw6X//zM1MQ "05AB1E – Try It Online") or [Test all inputs](https://tio.run/##yy9OTMpM/W9o6ebpEvr/cGvAua3mh7a7aDxqmKVdqRURWBv1P8JeSUHXTkHJXifmv7ERl4kBl6khl4UBl6Upl6GxMZehiTmXoakpl5GBOZeRqQGXkbkpl7GBAZcxUJUJkDYxNuUyAWkyMucyBcqbGZkDAA "05AB1E – Try It Online")
## Explanation
```
# Implicit input n
ÅP # Push a list of primes up to n
ε } # For each prime in the list...
7· # Push 14 (by doubling 7)
D(‚ # Push -14 and pair them together to get [14,-14]
+ # Add [14,-14] to the prime
y* # Multiply the prime to compute p(p-14) and p(p+14)
Q # Check if the (implicit) input is equal to each element
Z # Take the maximum
```
[Answer]
# [J](http://jsoftware.com/), ~~21~~ 15 bytes
Based on [Arnauld's](https://codegolf.stackexchange.com/a/179350/74062) solution:
```
14 e.q:|@-(%q:)
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N/QRCFVr9CqxkFXQ7XQSvO/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqChTmMZWwEY5kYm/4HAA "J – Try It Online")
Previous atempt:
```
e.&,14&(]*+,-~)@p:@i.
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D9VT03H0ERNI1ZLW0e3TtOhwMohU@@/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqChTmMZWwEY5kYm/4HAA "J – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 61 bytes
```
.+
$*
^((1{14})1(1)+)(?<=(?<!^\4+(..+))\2?)(?<-3>\1)+$(?(3)1)
```
[Try it online!](https://tio.run/##FcqxCsJAFETRfv5CiPDWxZC3My8xoKb0J0LQwsLGQuzEb19jcZvDfd3fj@etbu1yrW1Gs8Ni5h/XN7l5ysmm42lts8zK1rY5pblMf93zPK9DY5MxeaqVHehgAQkKDLAHB/AAjlAHOVQgQoIC6qEBOkAjokM4oiCIECJ@ "Retina 0.8.2 – Try It Online") Explanation:
```
.+
$*
```
Convert to unary.
```
^((1{14})1(1)+)
```
`\1` captures the larger of the two factors. `\2` captures the constant 14, saving a byte. `\3` captures the smaller of the two factors, minus 1. This also ensures that both factors are at least 2.
```
(?<=(?<!^\4+(..+))\2?)
```
Check the two factors to ensure at least one of them is prime. The idea of using `\2?` was shamelessly stolen from @Deadcode's answer.
```
(?<-3>\1)+
```
Repeat the larger of the two factors a number of times equal to one less than the smaller of the two factors. As we've already captured the larger factor once this then ends up capturing the product of the two factors.
```
$(?(3)1)
```
Ensure that the product equals the given number.
A direct translation to Retina 1 by replacing `$*` with `*1` would have the same byte count but a byte could be saved by replacing all the `1`s with `_`s and then the `*1` could be replaced with `*` rather than `*_`. Previous Retina 1 answer for 68 bytes:
```
.+
*
Lw$`^(__+)(?=(\1)+$)
$1 _$#2*
Am` (__+)\1+$
(_+) \1
0m`^_{14}$
```
[Try it online!](https://tio.run/##Hck9CsJAEIDR/jtFwBU2WZBMZiY/hYiVjUcISSwsLGIhgoV49lXsHrzH9Xm7XyRv42nJu0TF@RWWKc5zKuNhH0cpUygJUsxh01Qc16X45ygpEH8oRoF6Xab5LfYJOWuNCtqgihrqaIt2aI8OWI0J1mCKGeZYi3VYjw14jQve4Iob7l8 "Retina – Try It Online") Explanation:
```
.+
*
```
Convert to unary.
```
Lw$`^(__+)(?=(\1)+$)
$1 _$#2*
```
Find all the pairs of factors.
```
Am` (__+)\1+$
```
Ensure one is prime.
```
(_+) \1
```
Take the absolute difference.
```
0m`^_{14}$
```
Check whether any are 14.
[Answer]
# [JavaScript (Babel Node)](https://babeljs.io/), 69 bytes
*Damn, I though I was going to beat Arnaulds' Answer but no..... :c*
```
x=>[...Array(x)].some((a,b)=>x/(a=(p=n=>--b-1?n%b&&p(n):n)(b))-a==14)
```
[Try it online!](https://tio.run/##Jci7DoIwFADQGb6ig5J7g60SncSL8QccXI2JbS2mBlpSHsEQvh0Hz3g@cpCtDrbpuJLKVNz5l1lKWkYq7kKISwjyCyM@ROtrAyA3CqkYtyAJGnJUcK54dnZrlSQNODw6BIXIJVF2wKX0ASztcnvKzD63aYpTHA0ysGDavuoYsRIs5nFkS/gXxlGkvWt9ZUTl3/C8ea09u/a1MoFRwVaTnZ8Yz8sP)
*I want to get rid of the `x=>[...Array(x)].some(` part using recursion so it might get shorter over time*
**Explanation**
```
x=>[...Array(x)] Creates a range from 0 to x-1 and map:
.some((a,b)=> Returns True if any of the following values is true
x/ Input number divided by
(a=(p=n=>--b-1?n%b&&p(n):n)(b)) recursive helper function. Receives a number (mapped value) as parameters and returns
the same number if it is prime, otherwise returns 1. Take this value
and assign to variable a
-a Subtract a from the result
==14 Compare result equal to 14
```
It uses the formula
$$ n/p-p==14 $$
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 bytes
*Same as my [Javascript Answer](https://codegolf.stackexchange.com/a/179344/78039)*
```
k d@/X-X¥E
```
[Try it online!](https://tio.run/##y0osKPn/P1shxUE/Qjfi0FLX//@jjY10uEwNdbgsTYHYDIjNgdgCiC1jFXRzgwA "Japt – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
:ạ⁹ɗÆf14e
```
[Try it online!](https://tio.run/##y0rNyan8/9/q4a6Fjxp3npx@uC3N0CT1////xkYA "Jelly – Try It Online")
[Answer]
# APL(NARS) 16 chars, 32 bytes
```
{14=∣r-⍵÷r←↑⌽π⍵}
```
{π⍵} would find the factorization of its argument and we suppose that the last element of its result (the list of divisors of n) is the maximum prime divisor of n;
Here we suppose that one equivalent definition of Rocco number is: n is a Rocco number <=> max factor prime of n: r is such that it is true
14=∣r-n÷r [for C pseudocode as 14==abs(r-n/r) this definition of Rocco number seems ok at last in the range 1..1000000]; the range of ok value would be 1..maxInt; test:
```
f←{14=∣r-⍵÷r←↑⌽π⍵}
{⍞←{1=f ⍵:' ',⍵⋄⍬}⍵⋄⍬}¨1..10000
32 51 95 147 207 275 351 435 527 627 851 1107 1247 1395 1551 1887 2067 2255 2451 2655 2867 3551 4047 4307 4575 5135 5427 5727 6035 6351 6675 7347 8051 8787 9167 9951
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 99 bytes
```
n=>Enumerable.Range(2,n).Any(p=>Enumerable.Range(2,p).All(y=>y>=p|p%y>0)&(n==p*(p+14)|n==p*(p-14)))
```
[Try it online!](https://tio.run/##bc6xCsIwFIXhvU/RRblX09KquNQEHHQW3yANSQ3E25BaIdB3jxncdPvgh8NRU6Umm64zqZOlF@vH0QnDE3Fxofmpg@ydru@SBg07RlifKYL/G32OzkHkIgruF7@KosE1EOd@A37bHnD5uspGTF1hxqClesBbhtKWlsqf2ZYd9w1iYQ0YsIi3kF9mdOkD "C# (Visual C# Interactive Compiler) – Try It Online")
`Enumerable.Range` strikes again :) Using the crazy compiler flag, you can reduce things quite a bit, although I am kind of a fan of the vanilla solution.
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) + /u:System.Linq.Enumerable, 77 bytes
```
n=>Range(2,n).Any(p=>Range(2,p).All(y=>y>=p|p%y>0)&(n==p*(p+14)|n==p*(p-14)))
```
[Try it online!](https://tio.run/##RY69CsIwGAD3PkUXJZ@2tVVxsCbgoJOD6BO0IdFA@iX2Rwj02Y0BhW7HDcfxLuWd8ucB@UFhn9TGaCapR8puFT4EWScI2REdsZOxwWhNHGWOUTvamWM5zAlSahfELostjH9OAwP4MpKmFRV/knfVxipWGJ9waERb1Vpkv2yR7DY5QKQkkUQBXNvwE6D0H2N7ZbDzq2F/d10vmuyi8JVNiS8 "C# (Visual C# Interactive Compiler) – Try It Online")
Below is a port of Arnauld's solution that seemed pretty cool. It is currently the longest, but it can probably be golfed some.
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 101 bytes
```
n=>{bool g(int k)=>--k<2?n>1:n%k>0&g(k);var d=Math.Sqrt(n+49)-7;return(n=(int)d)==d&(g(n)|g(n+=14));}
```
[Try it online!](https://tio.run/##FYzBDoIwEAXvfEUvkt0IBJRotLSe9GZi9AtKKdCASyzgRf12hMvL5CUzug91b6fLSDqzNAR517WyFBMJ@VmYVTDfrEEhw7DJNieSyZFWjYz9Chrkb@VYIa5qqKPHyw1A6/SA4Z47M4yOgMSiY4FCFD5UQPidZy2SFJH/Ju6VnTNK17B0LLPEzjQ@jVN5a6K7ospAEuy2MaJnSyjBIt7cXJyBT38 "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
€14mS≠`/¹p
```
[Try it online!](https://tio.run/##yygtzv6f9qip8eGOxUYGBv8fNa0xNMkNftS5IEH/0M6C//8B "Husk – Try It Online") Given an integer, the function outputs a truthy or falsy value. A port of [Arnauld's answer](https://codegolf.stackexchange.com/a/179350).
[Answer]
# APL(NARS) 30 chars, 60 bytes
```
{∨/{0=1∣⍵:0π⍵⋄0}¨(7,¯7)+√49+⍵}
```
Here 0π is the function say if one number is a prime, test:
```
f←{∨/{0=1∣⍵:0π⍵⋄0}¨(7,¯7)+√49+⍵}
{⍞←{1=f ⍵:' ',⍵⋄⍬}⍵⋄⍬}¨0..700
32 51 95 147 207 275 351 435 527 627
```
[Answer]
# F#, 2 answers (noncompeting)
I really liked @Arnauld 's answers, so I translated them.
**123 bytes**, based on the [JavaScript answer](https://codegolf.stackexchange.com/a/179339/78960)
```
fun n->let t=int<|sqrt(float n+49.)in Seq.map(fun n->Seq.filter(fun i->n%i=0)[1..n]|>Seq.length=2)[t-7;t+7]|>Seq.reduce(||)
```
Explanation:
```
fun n->let t=int<|sqrt(float n+49.)in Seq.map(fun n->Seq.filter(fun i->n%i=0)[1..n]|>Seq.length=2)[t-7;t+7]|>Seq.reduce(||) //Lambda which takes an integer, n
let t=int<|sqrt(float n+49.) //let t be n, converted to float, add 49 and get square root, converted back to int (F# type restrictions)
in //in the following...
[t-7;t+7] //Subtract and add 7 to t in a list of 2 results (Lists and Seqs can be interchanged various places)
Seq.map(fun n->Seq.filter(fun i->n%i=0)[1..n]|>Seq.length=2) //See if either are prime (here, if either result has 2 and only 2 divisors)
|>Seq.reduce(||) //And logically OR the resulting sequence
```
**125 bytes**, based on the [05AB1E answer](https://codegolf.stackexchange.com/a/179350/78960)
```
fun n->let l=Seq.filter(fun i->n%i=0)[2..n-1]in let m=Seq.map(fun i->n/i)l in Seq.map2(fun a b->abs(a-b))l m|>Seq.contains 14
```
Explanation:
```
fun n->let l=Seq.filter(fun i->n%i=0)[2..n-1]in let m=Seq.map(fun i->n/i)l in Seq.map2(fun a b->abs(a-b))l m|>Seq.contains 14 //Lambda which takes an integer, n
let l=Seq.filter(fun i->n%i=0)[2..n-1] //let l be the list of n's primes
in //in...
let m=Seq.map(fun i->n/i)l //m, which is n divided by each of l's contents
in //and then...
Seq.map2(fun a b->abs(a-b))l m //take the absolute difference between each pair of items in the two sequences to make a new sequence
|>Seq.contains 14 //and does the resulting sequence contain the number 14?
```
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
Outputs by exit code, fails (`1`) for Rocco numbers.
```
P=k=1.
n=input()
exec"P*=k*k;k+=1;P%k*abs(n/k-k)==14>y;"*n
```
[Try it online!](https://tio.run/##TY7LTsMwFET38xVXQUhteNV5EIXI7NolRIgfSNyLGjm1I9cR@OtDDAtYzUhnZjRT8CdrskXZI5OkJEmWVmop7mHkYKbZb7bgL1ZJm0qd6kbfSNG01zrt@svGPOg7vZVSFM@hSVKzrHXgig7Wenb0MYyrXKgPZGe/bt2SNWOgN6uUJTOf@0g7xzS5wXg@Ap@nYWR6dzM/gci7EIUoPqB4EdErnjztXw9756z7DfSOO/0HX7oz/6M/82QWgQw5CuQC@epylDuUAmWGukT9iLqCKCpku@ob "Python 2 – Try It Online")
] |
[Question]
[
*Problem adapted from the book **[Fortran 77](http://www.ebay.co.uk/itm/FORTRAN-77-DONALD-M-MONRO-ARNOLD-PAPERBACK-BOOK-PRINTED-1987-/121637388292) by Donald M. Monro***
## Introduction
Digital plotting machines are widely used to produce various forms of drawings, graphs and other pictorial results. Most such machines can move their pens only in certain directions, usually as single steps in the X and Y direction or both. A typical machine would move in one of the eight directions shown in Fig. 1:

[Fig.](https://en.wikipedia.org/wiki/Common_fig) 1
## Challenge
Write a program *without trigonometric functions* which takes a number from 0 to 7 (inclusive) as input and outputs the corresponding coordinates of the endpoints in Fig. 1.
Output should as an array or list with two elements (i.e. `(1, 0)` or `[0,-1]`)
## Table of I/O
```
0 (1, 0)
1 (1, 1)
2 (0, 1)
3 (-1, 1)
4 (-1, 0)
5 (-1, -1)
6 (0, -1)
7 (1, -1)
```
## Winning
Shortest code in bytes wins
[Answer]
# Python 2, 29 bytes
```
lambda n:1j**(n/2)*(1+n%2*1j)
```
Returns the coordinates as a complex number.
[Answer]
# Mathematica, 24 bytes
```
Sign@{12-8#+#^2,4#-#^2}&
```
Pure function, using `Sign` and knowing where certain parabolas go.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Hı*µḞ,ĊṠ
```
Using complex arithmetic appears to be allowed.
[Try it online!](https://tio.run/nexus/jelly#@@9xZKPWoa0Pd8zTOdL1cOeC/wZF5oe2Ht1zuP1R0xpvIHb/DwA "Jelly – TIO Nexus")
### How it works
```
Hı*µḞ,ĊṠ Main link. Argument: n
H Halve; yield n/2.
ı* Yield i^(n/2), where i is the imaginary unit. Since i = e^(iπ/2), this
computes e^(inπ/4) = cos(nπ/4) + i×sin(nπ/4) = x + iy, where (x, y) is
the coordinate pair of (nπ/4)/(2π) = n/8 turns along the unit circle.
µ Begin a new chain with argument z = x + iy.
Ḟ Real part of z; yield x.
Ċ Imaginary part of z; yield y.
, Pair, yielding (x, y).
Ṡ Apply the sign function to x and y.
```
[Answer]
# C, ~~103~~ ~~86~~ ~~74~~ ~~73~~ 70 bytes
*Thanks to @orlp for saving ~~12~~ 15 bytes!*
```
f(n){n="biM1*#?["[n]/7;printf("%c%d %d",n&8?32:45,n/4&1,n%2*~-(n&2));}
```
[Try it online!](https://tio.run/nexus/c-gcc#@5@mkadZnWerlJTpa6ilbB@tFJ0Xq29uXVCUmVeSpqGkmqyaoqCaoqSTp2Zhb2xkZWKqk6dvomaok6dqpFWnq5GnZqSpaV37H6haITcxM09Dk6uaSwEE0jQMNK0LSkuKNZSUNK1hYoZYxIywiBljETPBImaKRcwMi5g5kFn7HwA)
[Answer]
# [Desmos](https://www.desmos.com/calculator), 33 bytes
```
f(n)=mod(floor([4,2]^55/3^n),3)-1
```
[Try it on Desmos!](https://www.desmos.com/calculator/gvur2d5a0f)
The coordinate is returned as a 2 element list.
[Answer]
## JavaScript (ES6), ~~41~~ 36 bytes
```
r=>[1-(6800>>r*2&3),(425>>r*2&3)-1]
```
Uses two simple lookup tables which encode the 8 entries in base 4 after adding one to each "digit". Alternate version, using simpler lookup tables:
```
r=>["22100012"[r]-1,"12221000"[r]-1]
```
---
Old version (4 bytes shorter thanks to @Neil):
```
r=>[r>2&r<6?-1:r<2|r>6,r>4?-1:r%4&&1]
```
Naive approach using some simple calculations to find the X and Y coordinates separately...
[Answer]
# APL, 21 bytes
```
{ׯ4 4+1 ¯1×2*⍨⍵-4 2}
```
[Answer]
# TI-Basic, 23 bytes
```
Prompt X
e^(i(pi)X/4
round({real(Ans),imag(Ans)},0
```
Assumes your calculator is in radian mode; if that needs to be in the program, then it's 25 bytes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*I am still fairly confident there is shorter, but I have not found anything yet, so thought I'd post this*
```
+2,ị6400b3¤’
```
**[Try it online!](https://tio.run/nexus/jelly#@69tpPNwd7eZiYFBkvGhJY8aZv7//98EAA)** or see a [test suite](https://tio.run/nexus/jelly#@69tpPNwd7eZiYFBkvGhJY8aZv4/3P6oac3//9EGOoY6RjrGOiY6pjpmOuaxAA)
### How?
```
+2,ị6400b3¤’ - Main link: n e.g. 7
+2 - n+2 9
, - paired with n: [n+2,n] [9,7]
¤ - nilad followed by link(s) as a nilad 9th 7th
6400 - 6400 v v
b3 - to base 3: [2,2,2,1,0,0,0,1] [2,2,2,1,0,0,0,1]
ị - index into (1-indexed and modular) [2,0]
’ - decrement (vectorises) [1,-1]
```
---
An [alternative method](https://tio.run/nexus/jelly#@x@vr6Ot/3DnAi4jp8Ptjxp3HFr4//9/EwA), also **12 bytes**:
```
_/,+/Ṡ - Link 1: get next coordinate: current coordinate (list) e.g. [-1,-1]
_/ - reduce by subtraction 0
+/ - reduce by addition -2
, - pair [0,-2]
Ṡ - sign (vectorises) [0,-1]
2BÇ⁸¡ - Main link: n
2B - 2 in binary: [1,0]
¡ - repeat
⁸ - left argument (n) times:
Ç - last link (1) as a monad
```
[Answer]
# C, 66 bytes
```
f(n){printf("%d %d\n",(n-2)%4?n>2&n<6?-1:1:0,(n-4)%4?n>4?-1:1:0);}
```
test code
```
main(i)
{for(i=0;i<8;++i) f(i);}
```
results
```
1 0
1 1
0 1
-1 1
-1 0
-1 -1
0 -1
1 -1
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 34 bytes
```
e=>[434,5].map(n=>(85*n>>2*e&3)-1)
```
[Try it online!](https://tio.run/##bc6xDsIgFIXh3acgHcylgQYKtC7wIsaBVGo0FRprfH3MpZOR@cufcx7@47fpdV/fPKZryLPNwbqzVpqZS/f0K0Tr4GTa6FzfhqOiXNI8pbilJXRLusEMgjLSCAKSEUEbevhViSqLyn/tUXsCoqoKVRHg9Vgj650rywbZ7Mwr@YA@lO0aj8hjOV44fwE "JavaScript (Node.js) – Try It Online")
[Answer]
## C, 56 bytes
```
d(n){printf("%d,%d",n+2&3?n+2&4?-1:1:0,n&3?n&4?-1:1:0);}
```
Simple binary search done twice. The first search is done on n shifted by 2.
[Online output on Ideone.](https://ideone.com/3Epp5s)
## C, 53 bytes
```
r;p(n){r?0:p(r=n+2);r=!printf("%d ",n&3?n&4?-1:1:0);}
```
Output without a comma was able to be compacted even more using a recursive call.
[Online output on Ideone.](https://ideone.com/UoR0of)
] |
[Question]
[
Your task is to take an input string of ascii characters and output the string as a series of vertical words separated by spaces. An example is shown below:
Given the string:
```
Hello, World! My name is Foo.
```
the output should be:
```
H W M n i F
e o y a s o
l r m o
l l e .
o d
, !
```
10 bonus points will be awarded if your program correctly handles strings which need to wrap-around the terminal, which we'll set at 80 characters.
50 points if your program can also do the reverse!
[Answer]
## J, 15
```
|:>'\S+| 'rxall
```
Usage:
```
|:>'\S+| 'rxall 'Hello, World! My name is Foo.'
H W M n i F
e o y a s o
l r m o
l l e .
o d
, !
```
[Answer]
# Javascript - ~~228~~ ~~172~~ ~~145~~ 126
```
A=prompt().split(" "),B="",N=A;for(y=0;y<N.length;y++){for(i=0;i<N.length;i++){if(A[i][y]){B+=A[i][y];}else{B+=" ";}}B+="\n";}
```
My first code golf :)
[Answer]
# APL, 22
```
{⍉⊃⍵⊂⍨1+0,+\2≠/⍵=' '}
```
**Explanation**
```
{ ⍵=' '} A. check which chars are spaces
2≠/ B. of that vector, which consecutive pairs are different
+\ C. compute the partial sums
1+0, D. insert 0 at the front and add 1 to every item
⍵⊂⍨ use this vector to split the original string
⍉⊃ disclose into a matrix and transpose
'W o w S u c h D o g e'
A. 0 0 0 1 0 0 0 0 1 0 0 0 0
B. 0 0 1 1 0 0 0 1 1 0 0 0
C. 0 0 1 2 2 2 2 3 4 4 4 4
D. 1 1 1 2 3 3 3 3 4 5 5 5 5
```
**Example**
```
{⍉⊃⍵⊂⍨1+0,+\2≠/⍵=' '} 'Hello, World! My name is Foo.'
H W M n i F
e o y a s o
l r m o
l l e .
o d
, !
```
[Answer]
# Ruby, ~~91~~ 87
```
s=gets.split
puts s.map{|x|x.ljust(s.map(&:size).max,' ').split''}.transpose.map &:join
```
Hooray, I beat Perl! :D
# Ruby, 150 - 50 bonus = 100
```
s=$<.read
n=s.index"
"
s=s.split n ?'
':' '
o=s.map{|x|x.ljust(s.map(&:size).max,' ').split''}.transpose.map &:join
puts n ?o.map(&:strip).join(' '):o
```
It just detects for newlines, and applies special handling if they are detected.
Run it like
```
ruby transposegolf.rb < transposegolfinput.txt
```
[Answer]
## Javascript ~~184~~ ~~149~~ 123
```
var a=s.split(" "),b="",c;for(c in a)b+="<div style='float:left'>"+a[c].split("").join("<br>")+"</div>";document.write(b);
```
With the example string defined:
```
var s = "Hello, World! My name is Foo.";
var a=s.split(" "),b="",c;for(c in a)b+="<div style='float:left'>"+a[c].split("").join("<br>")+"</div>";document.write(b);
```
You can copy the second statement to you browsers console.
Unminified:
```
var res = "Hello, World! My name is Foo.";
var t=res.split(" ");
var s ="";
for (var word in t){
s+="<div style='float:left'>" + t[word].split("").join("<br />") + "</div>";
}
document.write(s);
```
JsFiddle Link: <http://jsfiddle.net/FzMvK/>
My first code golf post :P
[Answer]
# Perl - 92 ~~97~~
```
$_=<>;chop;@x=split$";do{print((substr$_,$q,1or$").$")for@x;$q++,print$/}while/@{['\S'x$q]}/
```
Does the job in a pretty straightforward way.
[Answer]
# K, 33
```
{" "/:',:''x@'/:!max@#:'x:" "\:x}
```
Example input and output:
```
k){" "/:',:''x@'/:!max@#:'x:" "\:x}"Hello, World! My name is Foo."
"H W M n i F"
"e o y a s o"
"l r m o"
"l l e ."
"o d "
", ! "
```
[Answer]
## Python:
One line of code to process the sting:
```
import sys
m = "Hello, World! My name is Foo."
map(lambda y: sys.stdout.write(' '.join(y)+'\n'), zip(*map(lambda x: x.ljust(max(map(len,m.split()))), m.split())))
```
[Answer]
# Python 2.7, ~~108~~ 103
I'm sure this can be golfed more, but here's an initial solution in python.
```
w=raw_input().split();m=max(map(len,w));i=0
while i<m:print" ".join(map(lambda x:x.ljust(m)[i],w));i+=1
```
Improvements:
* split(" ") => split()
* removed some extra spaces
[Answer]
# F#, 187
```
let o=Console.ReadLine()
let s=o.Split(' ')
let m=s|>Seq.map String.length|>Seq.max
for l=0 to m-1 do
for w in s|>Seq.map(fun x->x.PadRight(m,' ').[l])do printf"%c "w
printfn"%s"""
```
[Answer]
# Ruby, 63
```
$F.map(&:size).max.times{|i|puts$F.map{|s|s[i]||' '}.join' '}
```
The algorithm is very straightforward; only golfed. Code is 61 bytes long, plus 2 bytes for the `-na` options that it needs to work. From `ruby -h`:
```
-n assume 'while gets(); ... end' loop around your script
-a autosplit mode with -n or -p (splits $_ into $F)
```
Sample run:
```
$ echo 'This sentence is false' | ruby -na cols.rb
T s i f
h e s a
i n l
s t s
e e
n
c
e
```
[Answer]
# Python 2.7 - 137 112 bytes
```
s=raw_input().split()
for c in range(max(map(len,s))):
for w in s:
try:print w[c],
except:print' ',
print''
```
Someone else has already done it better, but I might as well throw this up. Adds spaces to each word in the input until it's the same length as the longest one (to avoid index errors for the next part), then prints the `c`th letter of every word while `c` goes from 0 to the length of each string.
I came up with a much better way of doing this and cut out 25 bytes. Rather than padding strings with spaces to avoid the index error, I handle the error directly! Whenever there's nothing to print, I print a single space in its place with `try:print w[c],`, `except:print' ',`. I also remembered that I don't need a space between a print statement and a string literal, which saved one byte.
Note that Python 2 allows you to mix tabs and spaces and considers them separate levels of indentation. SE's Markdown interpreter replaces a tab character with four spaces, but every line of this program except the first has exactly one byte of indentation.
Formatting was pretty easy, since `print 'something',` prints `'something '` rather than `'something\n'`. I did that for each character, and used an empty `print` statement to get the newline where I needed it.
[Answer]
## C, 111 110 95 90 bytes
This solution uses VT-100 control codes to move the cursor on the terminal
```
main(int _,char**v){char*s=*++v;printf("^[7");while(*s)' '==*s?(s++,printf("^[8^[[2C^[7")):printf("%c^[[B^H",*s++);}
```
the `^[` sequence is a placeholder for the single ASCII ESC character, that can't be displayed here.
* `^[7` saves the current pointer position
* `^[8` restores the cursor position to the saved position
* `^[[2C` moves 2 steps right
* `^[[B` moves 1 step down
**edit 1:** the `^[[D` (1 step left) VT-100 code has been replaced by a backspace (shown as `^H` here, but is only one ASCII char) ; also forgot the "separated by spaces" instruction, now fixed
**edit 2:**
7 chars saved by using a `for` loop instead of `while`, and `32` instead of `' '`:
```
main(int _,char**v){printf("^[7");for(char*s=*++v;*s;s++)32==*s?printf("^[8^[[2C^[7"):printf("%c^[[B^H",*s);}
```
8 more chars saved by calling one less `printf`: the ternary `?:` operator is now used in the `printf` parameters
```
main(int _,char**v){printf("^[7");for(char*s=*++v;*s;s++)printf(32==*s?"^[8^[[2C^[7":"%c^[[B^H",*s);}
```
**edit 3:**
Got rid of the local variable `s`, working directly with `argv` aka `v`. This is totally hideous. But saved 4 chars. Also replaced `==` with `^` and therefore switched the `?:` operands, to save 1 more char.
```
main(int c,char**v){printf("^[7");for(v++;**v;)printf(32^*(*v)++?"%c^[[B^H":"^[8^[[2C^[7",**v);}
```
## Usage
```
$ gcc transpose.c -o transpose --std=c99
$ ./transpose 'Hello, World! My name is Foo.'
H W M n i F
e o y a s o
l r m o
l l e .
o d
, !
```
## Un-golfed version (first version)
```
main (int _,char**v) {
char*s=*++v; // init s with the address of the first letter
printf("^[7"); // save the current cursor position
while(*s)
' '==*s ? ( /* if current char is a space */
s++,printf("^[8^[[2C^[7") /* return to the saved location, move right, save position */
) : /* kind of else */
printf("%c^[[B^H",*s++); /* print the current char, move down, move left */
}
```
## Un-golfed version (last version)
```
main(int c,char**v) {
printf("^[7");
for(v++;**v;) /* v++: make v point to argv[1] */
printf(
32^*(*v)++? /* test if **v is different from ' ', and make *v point to
the next char */
"%c^[[B^H":
"^[8^[[2C^[7",
**v); /* this undefined behaviour (using *v and (*v)++ in the same expression)
works as "expected" with gcc 4.7.2 */
}
```
[Answer]
I [answered this question](https://codegolf.stackexchange.com/a/21659/14509) a long time ago. It was one of my first contributions to the site, actually. I recently came across it again and was kind of embarrassed. 112 bytes?! Unacceptable. So I gave it another shot:
# Python 3 - 92 bytes
```
s=input().split()
print('\n'.join(map(' '.join,zip(*[a.ljust(max(map(len,s)))for a in s]))))
```
In the 109 days since I posted that first answer, I like to think I've come a long way. Even something like using Python 3 over 2.71 wouldn't have occurred to me. With this code golfed down to under 100 bytes, my soul can finally rest and I can proceed to the afterlife.
**Explanation**
```
s=input().split()
```
This gets a line from `stdin` and creates a list by splitting it at whitespace characters. The only whitespace likely to be in the input is spaces, so this line gets a list of words.
Let's take the second line from the inside out:
```
max(map(len,s))
```
`map` takes a function and an iterable as arguments. It applies the function to each element of the iterable, and returns a new iterable of the results. Here, I create an iterable with the lengths of each input word. `max` gets the maximum value from an iterable. This gets us the longest word in the input.
```
[a.ljust( )for a in s]
```
A list comprehension is similar to `map`. It does something to every element of an iterable, and returns a list the results. For every word in the input, I do `that_word.ljust(`some code`)`. `ljust` is short for "left justify". It takes an integer as an argument and adds spaces to the string until it's that long.
```
zip(* )
```
This is a neat trick. In this context, `*` means "unzip this iterable as multiple arguments". This way, `zip` can be used to [transpose a matrix](http://en.wikipedia.org/wiki/Transpose) (e.g. `zip(*[(1,2),(3,4)])` -> `[(1,3),(2,4)]`). The only restriction is that all the rows in the matrix have to be the same length, or elements from all rows but the shortest are cut off to match.
```
map(' '.join, )
```
We already know what `map` does. The only new thing here is `join`, which takes an iterable of strings and makes it a single string using the delimiter it's attached to. For example, `'a'.join(['I', 'can', 'play', 'the', 'saxophone'])`2 becomes `Iacanaplayatheasaxophone`.
```
print('\n'.join( ))
```
This `join` takes a bunch of strings and seperates them by newlines. All that's left is to `print` to `stdout` and we're done!
All together now:
```
print('\n'.join(map(' '.join,zip(*[a.ljust(max(map(len,s)))for a in s]))))
```
Find the length of the longest word from the input, append spaces to every word until they're the same length, transpose with the `zip(*`3 trick, use `join` to seperate each character in a row with spaces, `join` again to seperate each row with a newline, and print! Not bad for the only non-input-handling line in a 92 byte program.
---
1. The extra characters spent on `print()`'s parentheses are outweighed by the 4 characters I drop from `raw_input()`->`input()`.
2. I can't actually play the saxophone.
3. `)`. You're welcome.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score ~~8~~ ~~-20~~ -21 (~~30~~ 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) - 50 bonus):
```
|Dgi#ζεSðý}»}ë¹ε2ô€¬}ζJεðÜ}ðý
```
[Try it online (regular single-line input).](https://tio.run/##MzBNTDJM/f@/xiU989BO5XPbzm0NPrzh8N7aQ7trD68@t9Xo8JZHTWsOrak9t83r3FagzJxakPT//x6pOTn5Ogrh@UU5KYoKvpUKeYm5qQqZxQpu@fl6AA)
[Try it online (multi-line reversed input).](https://tio.run/##MzBNTDJM/f@/xiU989BO5XPbzm0NPrzh8N7aQ7trD68@t9Xo8JZHTWsOrak9t83r3FagzJxakPT//x4K4Qq@CnkKmQpuXKkK@QqVCokKxQr5XDkKRQoKCrlADGLnAOlUINbjyldIUYACLh0FRRgbAA)
**Explanation:**
```
| # Take the input split on newlines:
# i.e. 'This is a test' → ['This is a test']
# i.e. 'T i a t\nh s e\ni s\ns t'
# → ['T i a t','h s e','i s','s t']
Dg # Duplicate this list, and take the length
# i.e. ['This is a test'] → 1
# i.e. ['T i a t','h s e','i s','s t'] → 4
i } # If the length is exactly 1:
¹ # Take the input again
# # Split the input-string by spaces
# i.e. 'This is a test' → ['This','is','a','test']
ζ # Zip with space-filler: Swap all rows and columns
# i.e. ['This','is','a','test'] → ['Tiat','hs e','i s','s t']
ε } # For each item:
S # Convert the item to a list of characters
# i.e. 'Tiat' → ['T','i','a','t']
ðý # Join them by a single space
# i.e. ['T','i','a','t'] → 'T i a t'
» # Join the result by newlines (and output implicitly)
ë # Else:
ε } # For each item:
2ô # Split it into chunks of two characters
# i.e. 'h s e' → ['h ','s ',' ','e']
€¬ # Take the head (first character) of each:
# i.e. ['h ','s ',' ','e'] → ['h','s',' ','e']
ζ # Zip with space-filler: Swap all rows and columns
# i.e. [['T','i','a','t'],['h','s',' ','e'],['i',' ',' ','s'],['s',' ',' ','t']]
# → [['T','h','i','s'],['i','s',' ',' '],['a',' ',' ',' '],['t','e','s','t']]
J # Join each inner list to a single string
# i.e. [['T','h','i','s'],['i','s',' ',' '],['a',' ',' ',' '],['t','e','s','t']]
# → ['This','is ','a ','test']
ε } # For each item:
ðÜ # Remove any trailing spaces
# i.e. 'is ' → 'is'
ðý # Join the items by a single space (and output implicitly)
```
---
**Original 8-byte answer:**
```
#ζεSðý}»
```
[Try it online.](https://tio.run/##MzBNTDJM/f9f@dy2c1uDD284vLf20O7//z1Sc3LydRTC84tyUhQVfCsV8hJzUxUyixXc8vP1AA)
**Explanation:**
```
# # Split the input-string by spaces
# i.e. 'This is a test' → ['This','is','a','test']
ζ # Zip with space-filler: Swap all rows and columns
# i.e. ['This','is','a','test'] → ['Tiat','hs e','i s','s t']
ε } # For each item:
S # Convert the item to a list of characters
# i.e. 'Tiat' → ['T','i','a','t']
ðý # Join them by a single space
# i.e. ['T','i','a','t'] → 'T i a t'
» # Join the result by newlines (and output implicitly)
```
[Answer]
## Mathematica 49
Clearly Mathematica isn't the best for this one:
```
Grid[PadRight@Characters@StringSplit@s^T]/. 0->" "
```

>
> Note `^T` (transpose) is only one char (I can't find the right char code now)
>
>
>
[Answer]
# Javascript, 141
```
a=prompt().split(' '),c=0,d=a.map(function(a){b=a.length;c=c<b?b:c});for(j=0;j<c;j++){b='';for(i in a)b+=a[i][j]?a[i][j]:' ';console.log(b);}
```
Sample
```
hello, world! this is code golf
hwticg
eohsoo
lri dl
lls ef
od
,!
```
[Answer]
## GolfScript [41 bytes]
```
' '%:x{.,x{,}%$-1=-abs' '*+}%zip{' '*}%n*
```
How it works:
```
' '%:x split text into words and store array in 'x'
{ for each word in the array:
., from word's length
x{,}%$-1=- substract the length of the longest word in 'x'
abs get absolute value (maybe there is a shorter way?)
' '*+ add corresponding number of spaces
}%
zip{' '*}% transpose array of words and add spaces between letters
n* join words with a new line character
```
You may see the online demo [here](http://golfscript.apphb.com/?c=J0hlbGxvLCBXb3JsZCEgTXkgbmFtZSBpcyBGb28uJwoKJyAnJTp4ey4seHssfSUkLTE9LWFicycgJyorfSV6aXB7JyAnKn0lbio%3D).
**P.S.:** This is my first GolfScript code ever, so don't judge me strictly ;)
[Answer]
## R, 116
```
z=t(plyr::rbind.fill.matrix(lapply(strsplit(scan(,""),""),t)));z[is.na(z)]=" ";invisible(apply(cbind(z,"\n"),1,cat))
```
[Answer]
# Bash + coreutils, 54
```
eval paste `printf " <(fold -w1<<<%s)" $@`|expand -t2
```
Output:
```
$ ./transpose.sh Hello, World! My name is Foo.
H W M n i F
e o y a s o
l r m o
l l e .
o d
, !
$
```
[Answer]
## APL: 18
```
⍉↑1↓¨a⊂⍨' '=a←' ',
```
**Explanation:**
a←' ', put a space in front of the string and assign to a
' '= find spaces, produces a boolean
1↓¨a⊂⍨ make substrings starting where the boolean has 1's and drop first element of each (so the space)
⍉↑ Make matrix out of the resulting substrings, and reverse it along the diagonal
[Answer]
# [R](https://www.r-project.org/), 81 bytes
Save a byte by storing a newline as `e`, which can be used in both `scan` calls, the compare call and `cat`.
```
w=scan(,e,t=scan(,e<-"
"));while(any((s=substr(w,F<-F+1,F))>e))cat(pmax(" ",s),e)
```
[Try it online!](https://tio.run/##NcYxDsIwDADAnVeYTLZwkZjbMkYsnZlNsdRKaYLioLSvDxM3XW6tjjZLRFYu/w2dOzmivi5rUJR4INpo35eVjJX90PnLjT3RXYlmKfjZZEcHjo1YqT00hMTwTDm8zzAdEGVTWA18Stf2Aw "R – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 26 bytes
**Solution:**
```
`0:{" "/'+(|/#:'x)$x}@" "\
```
[Try it online!](https://tio.run/##y9bNz/7/P8HAqlpJQUlfXVujRl/ZSr1CU6Wi1gEoEqPkkZqTk6@jEJ5flJOiqOBbqZCXmJuqkFms4Jafr6f0/z8A "K (oK) – Try It Online")
**Explanation:**
```
`0:{" "/'+(|/#:'x)$x}@" "\ / the solution
" "\ / split input on whitespace
{ }@ / apply (@) lambda
$x / pad ($) input (x)
( ) / do this together
#:'x / count (#:) each (')
|/ / max
+ / transpose / flip
" "/' / join each with whitespace
`0: / print to stdout
```
[Answer]
## Python 2.7 - ~~119~~ 106
Take 1 - 166. The reversing of lists was needed to make pop work in the order I wanted, but this seemed wasteful. And when I tried to combine into a single comprehension for fun, the pop screwed things up.
```
w=raw_input().split(' ');l=max([len(l) for l in w]);
q=[list(p)[::-1]for p in w]+[['\n']*l]
t=[' '+(v.pop() if v else' ')for i in range(l)for v in q]
print ''.join(t)
```
Take 2 - 119. So I changed to simple list indexing. Still seems clunky though, especially the padding of spaces and new lines.
```
w=raw_input().split(' ');l=max([len(l)for l in w]);print''.join([' '+(v+' '*l)[i]for i in range(l)for v in w+['\n'*l]])
```
Take 3 - thanks to @grc
```
w=raw_input().split();l=max(map(len,w));print''.join(' '+(v+' '*l)[i]for i in range(l)for v in w+['\n'*l])
```
[Answer]
## Python 3, 124
```
a=input().split()
l=max(map(len,a))
print("\n".join(" ".join(c[i] for c in [i+" "*(l-len(i)) for i in a]) for i in range(l)))
```
[Answer]
# Haskell, 112
Golfed:
```
import Data.List
r s=unlines$transpose$p$words s
p w=m(\s->s++replicate(maximum(m l w)-l s)' ')w
m=map
l=length
```
Explained:
```
import Data.List
-- Break on spaces, then pad, then transpose, then join with newlines
r s=unlines$transpose$p$words s
-- Pads each String in a list of String to have the same length as the longest String
p w=m(\s->s++replicate(maximum(m l w)-l s)' ')w
-- Aliases to save space
m=map
l=length
```
Example:
```
*Main Data.List> putStrLn $ r "Hello Doge"
HD
eo
lg
le
o
```
[Answer]
# JavaScript, 139 (156 with console.log output)
```
s=" ",b="",a=prompt().split(s),l=0;for(var i in a){m=a[i].length;l=(l<m)?m:l;}for(i=0;i<l;i++){for(var j in a)b+=((x=a[j][i])?x:s)+s;b+="\n"}console.log(b);
```
I think this is as golfed as I can get it. I just split, find the largest word and transpose accordingly, adding spaces if the char doesn't exist in the shorter words. More than the previous submitted JavaScript answer, but that answer doesn't seem to work?
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-R`, 5 bytes
```
¸y¬m¸
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=uHmsbbg=&input=IkhlbGxvLCBXb3JsZCEgTXkgbmFtZSBpcyBGb28uIgotUg==)
---
## Explanation
```
¸ :Split on spaces
y :Transpose
¬ :Split columns
m :Map rows
¸ : Join with spaces
:Implicitly join with newlines and output
```
[Answer]
# Pyth, 8 bytes
```
jbjL\ Cc
```
[Try it online!](http://pyth.herokuapp.com/?code=jbjL%5C+Cc&input=%22Hello+World%22&debug=0)
Pretty straightforward. Takes input enclosed in quotes, i.e. `"Hello World"`
```
jbjL\ CcQ
---------
cQ Chop the input Q on spaces
C Matrix transpose
jL\ Join each element by spaces,
i.e. interleave spaces between the characters of each element
jb Join by newlines
```
[Answer]
# APL(NARS), 79 chars, 158 bytes
```
{m←⌈/↑∘⍴¨z←(' '≠⍵)⊂,⍵⋄v←∊m{⍵\⍨∊(k⍴1)(0⍴⍨⍺-k←↑⍴⍵)}¨z⋄((2×↑⍴z)⍴1 0)\[2]⍉(↑⍴z)m⍴v}
```
test:
```
f←{m←⌈/↑∘⍴¨z←(' '≠⍵)⊂,⍵⋄v←∊m{⍵\⍨∊(k⍴1)(0⍴⍨⍺-k←↑⍴⍵)}¨z⋄((2×↑⍴z)⍴1 0)\[2]⍉(↑⍴z)m⍴v}
f 'Hello, World! My name is Foo.'
H W M n i F
e o y a s o
l r m o
l l e .
o d
, !
```
The old function have output not perfect:
```
{⍪¨(' '≠⍵)⊂,⍵}'Hello, World! My name is Foo.'
H W M n i F
e o y a s o
l r m o
l l e .
o d
, !
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 7 years ago.
[Improve this question](/posts/11249/edit)
Simulate `cowsay` in the default mode.
```
$ cowsay <<< Hello
_______
< Hello >
-------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
$ perl -e 'print "Long text "x20' | cowsay
__________________________________________
/ Long text Long text Long text Long text \
| Long text Long text Long text Long text |
| Long text Long text Long text Long text |
| Long text Long text Long text Long text |
\ Long text Long text Long text Long text /
------------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
```
How short can be the code? The cow and the balloon can be slightly different, but all elements should be present. Dynamic/multiline balloon is a plus.
Explicit list of the required elements:
* Text;
* Balloon;
* Line from the cow to the balloon;
* The cow (eye[s], month, ears, body, legs (minimum two), udder, tail).
`/usr/share/cowsay/cows/` may be accessed, but obviously not `/usr/games/cowsay` itself.
Note: here is the `/usr/share/cowsay/cows/default.cow` file:
```
$the_cow = <<"EOC";
$thoughts ^__^
$thoughts ($eyes)\\_______
(__)\\ )\\/\\
$tongue ||----w |
|| ||
EOC
```
Usage of the file is optional. When used, it must be accessed by full path. (Windows users may copy it to something like `C:\usr\share\cowsay\co\default.cow`, for fairness).
[Answer]
## Mathematica: Work in progress
I'll pin down the balloon once I can get the cow to settle:
```
ExampleData[{"Geometry3D", "Cow"}]
```

[Answer]
# Perl, 84 characters
```
print$a='-'x52,<>=~s/.{1,50}\b/sprintf"
|%-50s|",$&/rge,"$a
\\
]:p
| )=
| P=
¬"
```
Output:
```
----------------------------------------------------
|Long text Long text Long text Long text Long text |
|Long text Long text Long text Long text Long text |
|Long text Long text Long text Long text Long text |
|Long text Long text Long text Long text Long text |
----------------------------------------------------
\
]:p
| )=
| P=
¬
```
Admittedly, I golfed the cow as much as I golfed the code. But the Mathematica cow is going to win anyway :)
**Note:** Requires Perl 5.16 for the `/r` non-destructive substitution flag.
[Answer]
# Ruby: ~~152~~ ~~150~~ ~~149~~ ~~146~~ 143 characters
```
load'/usr/share/cowsay/cows/default.cow'
p=%w{U~ o* o o}
puts l=?-*44,gets.gsub(/(.{1,40})\b\s*/){"( %-41s)\n"%$1}+l,$the_cow.gsub(/\$\w+/){p.pop}
```
The cow art is read from the default.cow file and decorated in after-12-rounds-vs-Mike-Tyson manner, similar with a `cowthink -e 'o*' -T 'U~'` invocation.
The text is read from standard input and wrapped at most 40 characters. Line breaks in the input text are not supported.
Sample run:
```
bash-4.2$ perl -e 'print "Long text "x15' | ruby cow.rb
--------------------------------------------
( Long text Long text Long text Long text )
( Long text Long text Long text Long text )
( Long text Long text Long text Long text )
( Long text Long text Long text )
--------------------------------------------
o ^__^
o (o*)\_______
(__)\ )\/\
U~ ||----w |
|| ||
```
## With art bending: ~~138~~ ~~135~~ 136 characters
```
load'/usr/share/cowsay/cows/default.cow'
puts l=?-*44,gets.gsub(/(.{1,40})\b\s*/){"( %-41s)\n"%$1}+l,$the_cow.gsub(/\$.+?([use]+)\b/,'\1')
```
As the elements have to be just present, we can use what we have in place instead of defining realistic ones.
Sample run:
```
bash-4.2$ ruby cow.rb <<< 'Hello poor little cow'
--------------------------------------------
( Hello poor little cow )
--------------------------------------------
s ^__^
s (es)\_______
(__)\ )\/\
ue ||----w |
|| ||
```
[Answer]
## K, 178
```
{-1'g,({"+ ",x,((&/(c-4;60-#x))#" ")," +"}'l),(g:,(&/(64;4+c::#*l:(60*!-_-(#x)%60)_x))#"+"),("+ ^__^";" + (oo)\\_______";" (__)\\ )\\/\\";" ||----w |";" || ||");}
```
.
```
k){-1'g,({"+ ",x,((c-#x)#" ")," +"}'l),(g:,(&/(64;4+c::#*l:(60*!-_-(#x)%60)_x))#"+"),("+ ^__^";" + (oo)\\_______";" (__)\\ )\\/\\";" ||----w |";" || ||");}"Hello codegolf.stackexchange.com"
++++++++++++++++++++++++++++++++++++
+ Hello codegolf.stackexchange.com +
++++++++++++++++++++++++++++++++++++
+ ^__^
+ (oo)\_______
(__)\ )\/\
||----w |
|| ||
```
[Answer]
## APL ~~133 140 138~~ 122
This one liner takes screen input in the form of a character vector or array enclosed in quotes via: ←⍎⍞ The appearance of the output is improved by including leading and following spaces in the input.
```
('∘'⍪'∘',((¯2↑1,⍴t)⍴t←⍎⍞),'∘')⍪'∘'⋄5 19⍴(,⍉(19⍴2)⊤323584 196592 63503 4072 3096)\'∘^__^∘(oo)\_______(__)\)\/\||----w|||||'
```
The cow character locations on each row of the array are specified as 19 bit boolean vectors.
To use input the one liner followed by the bubble text in quotes:
```
' Hello '
°°°°°°°°°
° Hello °
°°°°°°°°°
° ^__^
° (oo)\_______
(__)\ )\/\
||----w |
|| ||
```
Multi-line text is input as an array.
```
3 36⍴' Multi-line text input as an array. '
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
° Multi-line text input as an array. °
° Multi-line text input as an array. °
° Multi-line text input as an array. °
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
° ^__^
° (oo)\_______
(__)\ )\/\
||----w |
|| ||
```
This version can be tested via the free APL interpreter at www.nars2000.org
] |
[Question]
[
Your challenge is to construct a [*proper*](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine) [quine](https://esolangs.org/wiki/Quine) using as few *distinct* characters as possible.
## Scoring
Your score is equal to the number of distinct characters in your code, aiming to minimise this. [Standard quine rules](https://codegolf.meta.stackexchange.com/q/12357/66833) apply.
[Answer]
# [Python 3](https://docs.python.org/3/), 9 distinct characters, 15341 bytes
```
exec('%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1))
```
[Try it online!](https://tio.run/##7doxDoMwDIXh0yBATFWPhJA6tR06lNOnl6AQ25@yR/4dx3l5yXv/PF7Pe2vbd1uncVjHYVpuV495uTqSIyOoMFfPowpnbtYKq1ipUv/Jmy@Pqh9PLxHYXbgROR/Pzb2Yz6zxzB2xRrd3E8QY0T86ftYIM@artcrrGMelpapyZYe2wUrZ5F2zOJ01Rg4ydhJnANY6PZLPgbHfzPnJ5OYpq/y5qB1Gxctq7N3ojwNuRJw9b1pcUK4t15aGoscQ4abHKIyi6mlu7Qc "Python 3 – Try It Online")
This encodes each character as a series of `+1`s and then sums them all together before executing the final encoded program:
```
A="""print(end='exec('+'+'.join("'%%c'%%("+'+1'*ord(B)+")"for B in'A=""'+'"'+%r+'"'+'"";exec(A%%A)')+")")""";exec(A%A)
```
[Try it online!](https://tio.run/##RYzBCoQwDER/RQZCkhWEZY@Lh/orWrF7SKV40K/vxl5kGAaGx9uvY8v2qTWMAPaS7JBoy8jxjLNw7xl@OZmAiWavwL83v3JZZNIeijWXbuqS8a1w3kulDQPf5glEQbnRiucMWusf "Python 3 – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 3 distinct characters, 1432 bytes
```
111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--11-11-p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--11-111-1--p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--1111-1--p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1--111-1--p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1--111-1--p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1--111-1--p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--11-1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--11p
```
[Try it online!](https://tio.run/##S8sszvj/39DQUJdyqAsyxVC3gDqm4bWHDrbg8yOYRRd/0semwQFhATuyfE0gNAY8PHQR1o6YmAHn8gH2JdANBf//AwA "><> – Try It Online")
This uses the characters `1-p` to `p`ut this code at the start of the program:
```
"/
o<
:/r~:
```
This quotes the whole program, accounts for the characters that were overwritten, and then outputs the program itself.
[Answer]
# [Haskell](https://www.haskell.org/), Score 13, 523 bytes
```
p=putStr;main=a>>mmm>>a>>mmm>>mmmm>>mmmmm>>mmm>>mm>>mmm>>mmmm>>mm>>mmmmm>>mmm>>mmmmmm>>mmm>>mmm>>mmmm>>mm>>mm>>mmmmm>>mmm>>mmmm>>mmm>>mmmm>>mm>>mm>>mm>>mmmmm>>mmm>>mmmmm>>mmm>>mmmm>>mm>>mm>>mm>>mm>>mmmmm>>mmm>>mmmmmm>>mmmmmm>>mmm;a=p"p=putStr;main=a>>mmm>>a>>mmm>>mmmm>>mmmmm>>mmm>>mm>>mmm>>mmmm>>mm>>mmmmm>>mmm>>mmmmmm>>mmm>>mmm>>mmmm>>mm>>mm>>mmmmm>>mmm>>mmmm>>mmm>>mmmm>>mm>>mm>>mm>>mmmmm>>mmm>>mmmmm>>mmm>>mmmm>>mm>>mm>>mm>>mm>>mmmmm>>mmm>>mmmmmm>>mmmmmm>>mmm;a=p";mm=p"m";mmm=p"\"";mmmm=p";m";mmmmm=p"m=p";mmmmmm=p"\\"
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v8C2oLQkuKTIOjcxM8820c4uNzfXzg5G58LJXLgImhS6NCoHVR2mWhyKsBiKRyVOJ8Bo60TbAqWR41Pr3FwgmQuiQYwYJTArFywDYYLlISqhvJgYpf//AQ "Haskell – Try It Online")
The used characters are:
```
p=utSr;main>"\
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes, 4 distinct characters
```
≔´θ´´´≔´´´´´⪫´θ´´´´´θθ´≔´´⪫θ´´θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R55RDW87tOLQFBMEcGHy0ajVCBgTP7QDxoGqAshC5czv@/wcA "Charcoal – Try It Online") Explanation: I started with the standard Charcoal quine from [Golf you a quine for great good!](https://codegolf.stackexchange.com/questions/69/) (which uses six distinct characters) and adapted it to try to remove the `F`, `⁺` and `ι` characters, which I was able to do at the cost of having to use the `⪫` character instead. I was then amused to discover that in fact the final quine was the same length as the original quine (less the trailing newline, which was needed for a true quine in the then version of Charcoal that used `A` instead of `≔`).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 31 bytes, score: 8 distinct bytes
```
$;="$;=%p;$><<$;%%$;";$><<$;%$;
```
[Try it online!](https://tio.run/##KypNqvz/X8XaVgmIVQusVexsbFSsVVVVrJVgbBXr//8B "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes, 2 distinct bytes
```
”ṘṘ
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw9yHO2cA0f//AA "Jelly – Try It Online")
## How it works
This is the [standard Jelly quine](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/73930#73930), nothing too interesting
```
”ṘṘ - Main link. Takes no arguments
”Ṙ - Yield the character "Ṙ"
Ṙ - Convert to a Jelly representation ("Ṙ" -> ”Ṙ) and print
- Implicitly output the character "Ṙ"
```
[Answer]
# [Python 3](https://docs.python.org/3/), 11 distinct bytes
```
p='p=%r;print(p%%p)';print(p%p)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8BWvcBWtci6oCgzr0SjQFW1QFMdzinQ/P8fAA "Python 3 – Try It Online")
Nice. Uses p and r as variables because print is necessary, so why not just use the characters from there? 31 bytes in length if that's a tiebreaker.
I don't see this being improved on, given TC Python 3 is already ~~7~~ 8 characters.
# [Python 2](https://docs.python.org/2/), 10 distinct bytes
```
p='p=%r;print p%%p';print p%p
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8BWvcBWtci6oCgzr0ShQFW1QB3OLvj/HwA "Python 2 – Try It Online")
What I do see, however, is that Recursive Co. has gotten a 10 byte answer, which, again, is 3 from optimal. Go upvote their answers as well!
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes 8 distinct bytes
```
p="p=%p;$><<p%%p";$><<p%p
```
[Try it online!](https://tio.run/##KypNqvz/v8BWqcBWtcBaxc7GpkBVtUAJyir4/x8A "Ruby – Try It Online")
Thanks to Jo King for -1 distinct byte
[Answer]
# JavaScript console (~~9 8~~ 7 distinct characters, ~~21 22~~ 24 bytes)
```
($=$=>'($='+$+')($)')($)
```
Thanks to JoKing, again for -1 byte!
Older versions
```
($=_=>`($=`+$+`)()`)() // 8 distinct characters
($=_=>`($=${$})()`)() // 9 distinct characters
```
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein), score 6, 71 bytes
```
<22+2+2+2+2+2+2+2+2+2+2+2+2+2+2+2+@+2+2+2+2+2+2+2+2+2+2+2+2+2+2+2+22<"
```
[Try it online!](https://tio.run/##y85Jzcz7/9/GyEgbP3QgIG9kZKPE9f//fwMDg/@6jgA "Klein – Try It Online")
Uses the characters `<2+@"` and newline. This uses `"` to push all the rest of the program backwards. However since this portion of the program is a palindrome, there is no need to put it in the correct order. All we have to do is add `"` onto the end. This is done by adding a whole bunch of `2`s up to 34.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), score 21, 64 bytes
```
main(s){printf(s="main(s){printf(s=%c%s%c,34,s,34);}",34,s,34);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPo1izuqAoM68kTaPYVglDRDVZtVg1WcfYRKcYSGha1yohsf//BwA "C (gcc) – Try It Online")
[Standard C quine](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/122856#122856), except not using the `%1$c` since that's extra chars.
### Breakdown
* `main(,){";}` (11) are probably required
* `printf` (+5=16) is required for most standard quines
* `%cs` (+3=19) from the format string
* `34` (+2=21), the ASCII code for the double quote. I don't believe hexadecimal or octal will be better here
[Answer]
# [C (gcc)](https://gcc.gnu.org/) for Linux x86\_64, score 13, ~~8241~~ 7604 bytes
```
main[]={+1111+1111+1111+1111+1111+111+111+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1,+1111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+111111+11111+11111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+111+111+111+11+11+1+1,+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+111+111+111+111+111+11+11+11+11+11+11+11+11+11+1+1,+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+1111111+1111111+111111+111111+111111+111111+11111+11111+1111+111+111+111+111+111+111+111+11+11,+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+1,+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+1,+1111111111+111111111+111111111+111111111+111111111+11111111+11111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+1111+111+111+11+11+11+11+11+11+11+11+1+1+1,+1111111111+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+111+111+111+111+111+111+111+11+1+1+1+1+1,+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+1111111+1111+111+11+11+11+11+11+1+1+1+1+1+1+1+1+1,+111111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+11+11+11+11+1+1+1+1+1+1+1,+1111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+1111+1111+11+11+11+11+1+1+1+1+1+1+1+1+1+1,+1111111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+11111+11111+11111+11111+1111+1111+111+111,+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+111+1+1+1+1+1+1,+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+111+1+1+1+1+1+1,+1111111111,+1111111111+111111111+111111111+111111111+111111111+11111111+11111111+1111111+1111111+1111111+111111+11111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+11+11+11+1+1+1,+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+111111+11111+11111+11111+11111+1111+1111+111+111+111+111+111+11+11+11+11+1+1,+1111111111+1111111111+1111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+111111+11111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+111+11+11+11+11+1+1+1+1+1+1,+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+11111+1111+1111+1111+1111+1111+1111+1111+111+111+111+11+11+11+11+1+1+1,+1111111111+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+1,+1111111111+1111111111+1111111111+111111111+111111111+11111111+11111111+1111111+1111111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+1+1,+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+1111+1111+111+111+111+111+111+11+11+11+11+11+11+1+1+1+1+1,+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+11111+11111+1111+1111+1111+1111+1111+1111+111+111+111+111+11+11+11+11+11+11+11+11+1+1+1,+1111111111+1111111111+1111111111+111111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+1111+1111+1111+111+11+11+11+11+11+1+1+1+1+1,+1111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+111111+1111+1111+1111+1111+1111+1111+111+111+111+11+11+1,+1111111111+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+11111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+111+111+11+11+11+11+11+11+11+1+1+1+1+1+1,+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+111111+111111+111111+11111+11111+11111+11111+1111+1111+1111+111+111+111+111+111+111+111+111+11+11+11+11+11+11+1+1+1,+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+111+111+11+1+1+1+1,+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+111111+111111+111111+11111+11111+1111+1111+1111+1111+111+11+11+11+11+11+1+1+1+1,+11111111+11111111+11111111+11111111+11111111+1111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+1111+1111+1111+111+1+1,+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+111+11+11+11+11+11+11+1+1+1,1};
```
[Try it online!](https://tio.run/##7Vm7DsIwDPwgp0NmxJcghioqFeKxlAGB@HVCeQyVmqdjJ6lEaZouleKLfXcxqumV0vrU7s@b7foOcrxsj98w3fOf@Hz2vQD/Rv0C0wn1NGIyAUIARdyRqETO/gkJhxEYV@JwoQbRmIWBAe4x3lVHwrPXHlT@iDgQoS9@vpj9tWxnfkmjBxk1goBMaQVmTjbEYut8m67ILf6CQbGIStKKqyUcI7Bl0oyuhHHejXP9vq18D@IcJ0UzTQ1kgHGu10s695kSDFbRTOLt9Azw6@eSlTK8yF2sjPIVLPGlOKxUojAzd5FDZ2Fw4@HMaVRzOQF0UiVG7wmCgymna67E4Ue1O6B2gqdUfkRfBeHVSUo6TdbQFhLCTlWIbOHY/Hiizd4H4IubUI5CJN7fZc99SOAWf8yhEIXiksHjpmPGVigm//O1tkqnd7gciPQ/vcj0qvJCYjApRYrBTGHysdL6qXbHth90c@uunRourTq8AA "C (gcc) – Try It Online")
This uses the characters `aimn[]={}+1,;`
Bootstrap program:
```
.text
.section .text.startup,"ax",@progbits
.globl main
.type main, @function
main:
.cfi_startproc
call poprbp
.ascii "main[]={,+1111111111};"
poprbp:
pop %rsi
lea -5(%rsi),%rbp
lea 119(%rsi),%r8
push %rdi
pop %rax
push $8
pop %rdx
syscall
add $9, %rsi
push:
mov 0(%rbp),%r12d
push $11
pop %r13
mov $1111111111,%ebx
push $10
pop %r14
cmp:
cmp %r12d, %ebx
jbe movslq
xchg %ebx, %eax
xor %edx, %edx
dec %r13d
div %r14d
xchg %eax, %ebx
jmp cmp
movslq:
movslq %r13d, %rdx
ones:
push %rdi
pop %rax
syscall
sub %ebx,%r12d
jne cmp
comma:
dec %rsi
push %rdi
pop %rax
push %rdi
pop %rdx
syscall
inc %rsi
add $4, %rbp
cmp %r8, %rbp
jne push
theend:
add $10, %rsi
push $3
pop %rdx
syscall
ret
.cfi_endproc
.size main, .-main
```
[Try it online!](https://tio.run/##hVLraoMwFP7vUwSxoMwOs3ZgLXuSdYSYhJribaYtjtJnd7l4OZTR@cdzyXc5J2HrI2PDUFFZh9HNI4SqihBEyLUp6VmWgpDQ8xktS9Q2bZe3h9r3/FeqmJTo4Bvc59fHLX7B83ffH3x7ygGyKUarTkmblIKi9Xto8iheTaSmivFuLqcOeFGFRnIJaGi/tIIUNLhrqB9lHNuYco6CXbyIG5TzVDVXlIRG38jhNw5YMQa0eDOfD5Y545XIoRGcQMjWJqwa59cBshrayQQ75QJpTlV@27RnxdE2zZFxxL7pdMJtaRyOC2YtObdcXq0ahxS0hypaWatPE2i1DMSOKl5219RCZf9tHi5YXXLnelnhqRazJGuqimbAObiGZ/f60PrjZmUN6Ow1b80c42tyC09Bxbgy1DY5F0LUPFuwOHl4IyjYPNfvxNn8o713H4Zf "C (gcc) – Try It Online")
This was based on the following C program.
```
#include<unistd.h>
main(){
write(1,"main[]={",8);
int i = 0;
do {
unsigned int x = 1111111111;
unsigned int y = ((unsigned int*)main)[i];
do {
while( y<x ) {
x/=10;
}
printf("+%d",x);
}
while(y-=x);
write(1,",",1);
} while ( i++<10 );
write(1,"1};",3);
}
```
[Try it online!](https://tio.run/##ZZBRC4IwFIXf/RWHRbCllaOXYNofER/CmV6oFaWkxH67zTQT2l52z/k4995l6yLLum5BJjvXOo9qQ49Kb8qDdzmS4eLlAc87VTmXAeulJI1fLNgL5QwyFQgxwr7QV/QwUJsHFSbXH7txtpyO@gdaB3A@l1ai7yMSSgd8CnaTlHTOOdqogZhEoNnGMlRjaTE@bncXduLMX2oWNGLwrffLadfxV55WdFd@NDtA4CDfj2QIoTD/C2kVC3YOtV33Bg "C (gcc) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 18 distinct bytes
```
$_=q(print"\$_=q($_);eval;");eval;
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3rZQo6AoM69EKQbMVonXtE4tS8yxVoLS//8DAA "Perl 5 – Try It Online")
This is a classic Perl quine. I have no idea how Perl works, but this is tested on TIO. Feel free to tell me how to improve this. 34 bytes if that matters.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 distinct bytes, 4 bytes
```
`I`I
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgSWBJIiwiIiwiIl0=)
classic vyxal quine
] |
[Question]
[
# Task
Given an input string of one or more ASCII characters which codepoints are between 0 and 128 (exclusive), do the following:
1. Convert each character into its 7-bit ASCII code (if the ASCII code is less than 7 bits, put leading zero bits)
2. Concatenate all bits (this results in `7*n` bits where `n` is the number of characters)
3. For each bit in this bitstream, print 1 if it is different from the previous bit, and print 0 otherwise. The first output bit is always 1.
# Example
Input:
```
Hi
```
Output:
```
11011001011101
```
Explanation:
>
> The string "Hi" has the ASCII codes
>
>
> `72 105`
>
>
> which in bits are:
>
>
> `1001000 1101001`
>
>
> And the transition bits indicators:
>
>
> `11011001011101`
>
>
>
This is code golf. Lowest byte count wins.
# Test Cases
Test case 1:
```
Hello World!
110110010101110011010101101010110001110000111110000110000001011101101010101100110001
```
Test case 2:
```
%% COMMENT %%
1110111111011111100001100010010100001010110101011010011101010011111110011000001101111110111
```
Test case 3 (credit to Luis Mendo):
```
##
11100101110010
```
---
Congrats to Luis Mendo for the shortest solution with 9 bytes in MATL!
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
```
n=1
for c in input():n=n<<7|ord(c)
print'1'+bin(n^n/2)[4:]
```
[Try it online!](https://tio.run/##XU7BCsIwDL33K@qgdMODzRCEsZ1E8DK9CB5ED26VFUo6xkQF/73WdR1iEvIeIS8v7atvDKb20SgtKWTyKasoiiwWQG6moxVV6Kq993GSYYF5vnqbro6rhLSdwp4Dn18VxnjBRZqcltnZOjkhAMKVgG8OBEYeQPj5AIGIIbwibIpR7Rrxc/iBIButhPhzAW8TCMB0zb80HbN8K7U29Gg6Xc844YzR9b4sN7sDZYx/AA "Python 2 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
Hj7&B!hdg
```
[Try it online!](https://tio.run/##y00syfn/3yPLXM1JMSMlHchMzcnJVwjPL8pJUQQA "MATL – Try It Online")
### Explanation
```
H % Push 2
j % Read line of input, unevaluated
7&B % Convert to binary with 7 bits. Gives a 7-column matrix
! % Transpose
h % Concatenate horiontally. The matrix is read in column-major order
d % Consecutive differences
g % Convert to logical. Implicitly display
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 11 bytes
Takes advantage of the fact that spaces can be coerced to `0` in JavaScript when trying to perform a mathematical or, in this case, bitwise operation on it.
```
c_¤ù7Ãä^ i1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=Y1%2bk%2bTfD5F4gaTE&input=IkhlbGxvIFdvcmxkISI) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y1%2bk%2bTfD5F4gaTE&footer=UmlVcQ&input=WwoiSGkiCiJIZWxsbyBXb3JsZCEiCiIlJSBDT01NRU5UICUlIgoiIyMiCl0tbVI)
```
c_¤ù7Ãä^ i1 :Implicit input of string
c_ :Map codepoints
¤ : Convert to binary string
√π7 : Left pad with spaces to length 7
à :End map
√§^ :XOR consecutive pairs
i1 :Prepend 1
:Implicitly join and output
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
O+Ø⁷BḊ€FIA1;
```
[Try it online!](https://tio.run/##y0rNyan8/99f@/CMR43bnR7u6HrUtMbN09HQ@v///6qqAA "Jelly – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~36~~ 30 bytes
*Fix thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)*
*-2 bytes thanks to [Sanchises](https://codegolf.stackexchange.com/users/32352/sanchises)*
```
@(a)[1;~~diff(de2bi(a,7)'(:))]
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjUTPa0LquLiUzLU0jJdUoKVMjUcdcU13DSlMz9n9KZnGBRpqGkkemkqbmfwA "Octave – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 21 bytes
```
1q{i2b7Te[}%e__(;.^);
```
[Try it online!](https://tio.run/##S85KzP3/37CwOtMoyTwkNbpWNTU@XsNaL07T@v9/j9ScnHyF8PyinBRFAA "CJam – Try It Online")
## Explanation
Showing the stack with a sample input of `5`:
```
1 q e# Push 1 and then the whole input: 1 "5"
{
i e# Convert to its char code: 1 [53]
2 b e# Convert to binary: 1 [[1 1 0 1 0 1]]
7 T e[ e# Left-pad with 0 to length 7: 1 [[0 1 1 0 1 0 1]]
} % e# Map this block over every character in the string
e_ e# Flatten array: 1 [0 1 1 0 1 0 1]
_ ( ; e# Duplicate array and remove its first element: 1 [0 1 1 0 1 0 1] [1 1 0 1 0 1]
. ^ e# Element-wise xor: 1 [1 0 1 1 1 1 1]
) ; e# Remove and pop the last element of the array: 1 [1 0 1 1 1 1]
e# Stack implicitly printed: 1101111
```
To see if a bit is different from the previous bit, we do a vector (element-wise) xor between the bit array and the bit array without the first element. We also remove the last bit of the result, because it is always the last bit of the longer array unchanged.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 [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 string from stdin.
```
1,2≠/∊1↓¨11⎕DR¨⍞
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9/r@hjtGjzgX6jzq6DB@1TT60wtDwUd9Ul6BDKx71zgOp4KoG8h@1TXjU22f0qKsZyPELUo9Xr33Uu7jaAEiu@e@RyeWRmpOTrxCeX5STosilqqrg7O/r6@oXoqCqCgA "APL (Dyalog Unicode) – Try It Online")
`‚çû`‚ÄÉprompt for input ("a quote in a console")
`11⎕DR¨` change each character to bit-Boolean **D**ata **R**epresentation
`1↓¨` drop the first bit from each
`∊` **ϵ**nlist (flatten)
`2≠/` pairwise difference
`1,`‚ÄÉprepend a one
[Answer]
# [Dart](https://www.dartlang.org/), ~~213~~ 168 bytes
```
f(s,{t,i}){t=s.runes.map((r)=>r.toRadixString(2).padLeft(7,'0')).join().split('').toList();for(i=t.length-1;i>0;i--)t[i]=t[i]==t[i-1]?'0':'1';t[0]='1';return t.join();}
```
Previous one-liner
```
f(String s)=>'1'+s.runes.map((r)=>r.toRadixString(2).padLeft(7,'0')).join().split('').toList().reversed.reduce((p,e)=>p.substring(0,p.length-1)+(p[p.length-1]==e?'0':'1')+e).split('').reversed.join().substring(1);
```
[Try it online!](https://tio.run/##ZU7LasMwELz3K9SD0QpsIfVSqFB6CIEekhbaQg/BB4PtZItjG3kDBeNvdy2/oI2QZkfL7sykiaO@z6EJWwqxEy3ZRrprmTXyktQATtiNk1S9Jyn@fJDD8gQPQtZJus9ygseQKy6E/K6wBCGbukACzsWwsceGQJi8coCWZJGVJzpH2uBGGYwiQUeM7QgeIx0/D1JPXHNDRxVbT1xGV1cymuVN118ST9o7xuohCkEO/AW5YNYyrrUarvI4PC7Mn6msKCr2Vbkivb@ZHzf8Z@JLUVN/LAtR45k95kk1b6sb1yBg27fDYff6yYJgtdWT4FoW4TmMUv9y6CnIQrRe/abQq5h37/pf "Dart – Try It Online")
This verbosity and lack of easy built ins is really killing this one. Still managed to pull a one liner though.
* -45 bytes by not using a one liner and using a for loop
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
⭆θ◧⍘℅鲦⁷←Wⅈ←I﹪⍘KD²←01 ²1
```
[Try it online!](https://tio.run/##TY0xC8IwFIR3f8UjEHgPItgugt2sbsYWdHANbbTB0Gga68@PbbM4HMdxx3dNp3zjlI2x9qYPeAmTPaR64VtArdqTvgfcq0GnAivfml5ZNCQgn7QlomIl3ahxN2@n8O2M1YA3JIIEXRoBpRoCStd@rPtH1lo/D8brJhjXYy4ggQSwTQZs@Zk/EopljIoYOYeykvJ4vgLnq7ge7Q8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⭆θ◧⍘℅鲦⁷←
```
Convert all the characters to binary and pad them to a length of 7 and then print them, but leave the cursor over the last digit.
```
Wⅈ
```
Repeat until the cursor is over the first digit.
```
←I﹪⍘KD²←01 ²
```
Calculate whether the digits are different and overwrite each digit with the difference.
```
1
```
Overwrite the first digit with a `1`.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~73~~ ~~56~~ 49 bytes
```
$args|%{$b=+$_
6..0}|%{+($c-ne($c=($b-shr$_)%2))}
```
[Try it online!](https://tio.run/##XVBNi8IwEL3nV4wyMQm2MvHgYaGwsAheXC/CHsXuFj8otpseFGp/e3faNIU1JDPvZSbvhSmLe@aqc5bnLaaQQN3i0Z2qp6wxTeZ4EKvFghqmc43f8S3jmGhM4@rs8GDk0pimbYTQanNREShriTd1kY8yUVdh8QK@Cpf/TP739F0d8Tgk8vd9CoD6NegOnTS8puAkJXzsttv15x6k9FbWi4wpiA0fIHrxtt48AGtHD//RUUwZeIKEWgBgGQE@eHg8LmaO0Qx4mu8l0ylqrsXZL@j4WlxuXDfmjeNUNO0f)
*-17 bytes thanks to mazzy* :)
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-p`, ~~68~~ 57 bytes
-11 bytes by shamelessly stealing the method used by [xnor's Python solution](https://codegolf.stackexchange.com/a/188098/52194).
```
l=1
gsub(/./){l=l<<7|$&.ord}
$_=?1+(l^l/2).to_s(2)[2..-1]
```
[Try it online!](https://tio.run/##KypNqvz/P8fWkCu9uDRJQ19PX7M6xzbHxsa8RkVNL78opZZLJd7W3lBbIycuR99IU68kP75Yw0gz2khPT9cw9n9BaUmxQmaagoqegp2C4X@P1JycfIXw/KKcFEUuVVUFZ39fX1e/EAVVVS5l5X/5BSWZ@XnF/3ULAA "Ruby – Try It Online")
Original solution:
```
gsub(/./){'%07b'%$&.ord}
l=p
gsub(/./){b=$&.ord-48;r=l ?l^b:1;l=b;r}
```
[Try it online!](https://tio.run/##KypNqvz/P724NElDX09fs1pd1cA8SV1VRU0vvyillivHtoALIZlkCxHXNbGwLrLNUbDPiUuyMrTOsU2yLqr9/98jNScnXyE8vygnRfFffkFJZn5e8X/dAgA "Ruby – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Çb7jð0:¥ÄJ1ì
```
Uses the legacy version of 05AB1E, since `j` implicitly joins the strings together, which requires an explicit `J` after the `j` in the new version of 05AB1E.
[Try it online](https://tio.run/##MzBNTDJM/f//cHuSedbhDQZWh5YebvEyPLzm/3@PTGUA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9TVmmvpPCobZKCkn3l/8PtSeZZhzcYWB1aerjFy/Dwmv86/z0yuTxSc3LyFcLzi3JSFLlUVRWc/X19Xf1CFFRVuZSVuTwylQE).
**Explanation:**
```
Ç # Convert the (implicit) input-string to a list of ASCII code-points
# i.e. "Hi#" ‚Üí [72,105,35]
b # Convert each integer to a binary string
# ‚Üí ["1001000","1101001","100011"]
7j # Prepend each with spaces to make them length 7,
# and join everything together to a single string implicitly
# ‚Üí "10010001101001 100011"
√∞0: # Replace all those spaces with 0s
# ‚Üí "100100011010010100011"
¥ # Get the deltas of each pair of 1s/0s
# ‚Üí [-1,0,1,-1,0,0,1,0,-1,1,-1,0,1,-1,1,-1,0,0,1,0]
Ä # Get the absolute value of this
# ‚Üí [1,0,1,1,0,0,1,0,1,1,1,0,1,1,1,1,0,0,1,0]
J # Join them all together
# ‚Üí "10110010111011110010"
1ì # And prepend a 1
# ‚Üí "110110010111011110010"
# (after which the result is output implicitly)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~16~~ ~~15~~ 14 bytes
```
:1Ẋ≠ṁȯΩo=7LΘḋc
```
[Try it online!](https://tio.run/##ATAAz/9odXNr//86MeG6iuKJoOG5gcivzqlvPTdMzpjhuItj////IkhlbGxvIFdvcmxkISI "Husk – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~20 16~~ 15 bytes
```
bƛṅS7↳vċ†;f¯ȧ1p
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=b%C6%9B%E1%B9%85S7%E2%86%B3v%C4%8B%E2%80%A0%3Bf%C2%AF%C8%A71p&inputs=H%23&header=&footer=)
A mess. -4 thanks to Aaron Miller. -1 thanks to lyxal.
[Answer]
# [Python 2](https://docs.python.org/2/), 104 bytes
```
lambda w:reduce(lambda(A,P),C:(A+'10'[P==C],C),bin(reduce(lambda a,c:a*128+ord(c),w,1))[3:],('','x'))[0]
```
[Try it online!](https://tio.run/##XVCxbsMgEJ3LV9DBOmhQBelSWfIQWZW6pM0QqYPjgRisWqJg2VRJv961TXCTAuLePb27d9D@@E9n10OdHQYjv45K4lPaafVdaRJysmE7yvKUbFYgOBS7LMtLllN2bCy5UWLJqlQ@iPXzynWKVJSdmKC0eEpLRgAYnGHMeDl43ftc9rrHGS4QALxqYxz@cJ1R90gIPh4upj0DccEx8MDPIQI@r1ARlfxSPV6jB0OTU5Lg/H27fXnb4yRBQS2uQmx2GYDzf94imEcgxOIRBl2ajV6oRKh2HW6NbOxenz3D2lZOaTUluLG48I99axpP4GCB4kk888sHlSm6a7vG@r8mkbhqFamaLCqKhtu3wi8 "Python 2 – Try It Online")
A quick stab at it.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~13~~ 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ìEÖâU₧(~¬8IE
```
[Run and debug it](https://staxlang.xyz/#p=8d459983559e287eaa384945&i=Hello+World%21%0A%25%25+COMMENT+%25%25&a=1&m=2)
If it's guaranteed that all input characters have the 7th bit set, as some answers assume, it can be done in [10 bytes](https://staxlang.xyz/#p=e06008438e5fa0938fb3&i=Hello+World%21%0A%25%25+COMMENT+%25%25&a=1&m=2)
[Answer]
# [Kotlin](https://kotlinlang.org), 182 bytes
```
var l='6'
fun f(b:String)=b.fold(""){t,i->t+"".a(i.toInt())}.map{if(l==it){l=it;0} else {l=it;1}}
fun String.a(v:Int):String=if(v<=0)"${this}0".reversed() else "${this}${v%2}".a(v/2)
```
[Try it online!](https://tio.run/##bY8xT8MwEIXn5lccblFt0ZjQgSE0ldjaGSSWLKlitydcp7JNAFn@7cZJQAIJDz6d733vnV87p1DH2DcGVLW8X2byTYOkh/LJGdRHVh247FRLCWHerTDfuhtCeEORu26vHWUs8HNz8Sipqip0zKt0PxQBhLICpu4uhNF38kx0XyaWfWdUie03VcHIwrsT2lAQbkQvjBUtZZPPz2jh@@t1GBbob9csDqbnBjVtzNGW8GhM87mZXLcMfJbNZGeAUlxBUjBAPVTL39Gd9roVH2n/UTa7JMYpTcmzsA4WCDnUKTSpQ53@/lsihzT254nUOv/v1HpEQ5aFGHcYd0KpDl46o9qrOJ9/AQ "Kotlin – Try It Online")
Hopefully I can improve this soon, I feel like there must be some spots for improvement but I can't think right now
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 60 bytes
```
s/./sprintf'%07b',ord$&/ge;s/.(?=(.))/0|$&^$1/ge;s/^/1/;chop
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX0@/uKAoM68kTV3VwDxJXSe/KEVFTT891RoopWFvq6GnqalvUKOiFqdiCBGN0zfUt07OyC/4/98jNScnXyE8vygnRfFffkFJZn5e8X9dX1M9A0OD/7oFAA "Perl 5 – Try It Online")
[Answer]
# C (gcc (MinGW)), 90 bytes
Requires a compiler providing `itoa()`.
```
n[9],b,c;f(char*s){for(b=*s<64;c=*s++;printf("%07s",itoa((c^c/2)&127,n,2)))c|=b<<7,b=c&1;}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-p`, 50 bytes
```
gsub(/./){"%07b"%$&.ord}
gsub(/./){$`=~/#$&$/?0:1}
```
[Try it online!](https://tio.run/##KypNqvz/P724NElDX09fs1pJ1cA8SUlVRU0vvyillgshoZJgW6evrKKmom9vYGVY@/@/R2pOTr5CeH5RToriv/yCksz8vOL/ugUA "Ruby – Try It Online")
## Explanation
First line, same as [Value Ink's answer](https://codegolf.stackexchange.com/questions/188085/string-to-bit-transition/188097#188097):
```
gsub(/./){ $& } # Replace each character $&…
.ord # …with its ASCII code…
% # …formatted as…
"%07b" # …binary digits padded to 7 places.
```
Second line:
```
gsub(/./){ $& } # Replace each character $&…
$` # …if the text to its left…
=~ # …matches…
/# $/ # …the Regexp /c$/ where "c" is the character…
?0:1 # …with 0, or 1 otherwise.
```
In Ruby you can use interpolation in Regexp literals, e.g. `/Hello #{name}/`, and for variables that start with `$` or `@` you can omit the curly braces, so if e.g. `$&` is `"0"` then the grawlixy `/#$&$/` becomes `/0$/`.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~9~~ 13 bytes
**Solution:**
```
~=':,/(7#2)\'
```
[Try it online!](https://tio.run/##y9bNS8/7/7/OVt1KR1/DXNlIM0ZdySM1JydfITy/KCdFUen/fwA "K (ngn/k) – Try It Online")
**Explanation:**
```
~=':,/(7#2)\' / the solution
\' / convert each
( ) / do this together
7#2 / 2 2 2 2 2 2 2
,/ / flatten
=': / equal to each-previous?
~ / not
```
**Notes:**
* **+4 bytes** to support strings consisting only of 6-bit chars
[Answer]
# [Emojicode](http://www.emojicode.org/), 263 bytes
```
üèÅüçáüî§üî§‚û°Ô∏èüñçüÜïsüîÇbüìáüÜïüî°üëÇü躂ùóÔ∏è‚ùóÔ∏èüçáüç™süî™üî°üî¢b‚ùóÔ∏è‚ûï128 2‚ùóÔ∏è1 7‚ùóÔ∏èü療û°Ô∏èüñçsüçâüî§?üî§‚û°Ô∏èüñçüÜïpüîÇb süçá‚Ü™Ô∏èbüôåpüçáüëÑüî§0üî§‚ùóÔ∏èüçâüôÖüçáüëÑüî§1üî§‚ùóÔ∏èüçâb‚û°Ô∏èüñçpüçâüçâ
```
Try it online [here.](https://tio.run/##S83Nz8pMzk9JNfv//8P8/sYP83vbP8yfsgSEH81b@H5H/4f503o/zG@bWgwUakr6MH9yO4gH5Cz8MH9iE1DPnkdzpwPVQUiI/t5VINWrIIqmLEqCqpg31dDIQsEIwjNUMIdrWYWwCqixtxNkuz2mEwrATlAAKWl/1LYKKAN0z8yeAoilE1tAOgzA2mAGA02a2YosbYgqnYSwoACivLfz/3@P1JycfIXw/KKcFEUA "Emojicode – Try It Online")
Ungolfed:
```
üèÅ üçá üí≠ Main code block
üî§üî§ ‚û°Ô∏è üñç üÜï s üí≠ Start with s as the empty string
üîÇ b üìá üÜï üî° üëÇüèº üí≠ For each byte b in the input ...
‚ùóÔ∏è ‚ùóÔ∏è üçá
üç™ s üí≠ ... append ...
üî™ üî° üî¢ b ‚ùóÔ∏è ‚ûï 128 üí≠ ... b + 128 (this gives the leading zero(s) in case the binary representation of b is shorter than 7 digits) ...
2 üí≠ ... in binary ...
❗️
1 7 üí≠ ... without the leading one ...
❗️
üç™
‚û°Ô∏è üñç s üí≠ ... to s
üçâ
üî§?üî§ ‚û°Ô∏è üñç üÜï p üí≠ This will be used as the previous character, by assigning it neither 0 nor 1 we assure the first bit output is always a one
üîÇ b s üçá üí≠ For each character in s:
‚Ü™Ô∏è b üôå p üçá üí≠ If it is the same as the previous character ...
üëÑ üî§0üî§ ‚ùóÔ∏è üí≠ ... output a zero ...
üçâ üôÖ üçá üí≠ ... else ...
üëÑ üî§1üî§ ‚ùóÔ∏è üí≠ ... output a one
üçâ
b ‚û°Ô∏è üñç p üí≠ And the current character becomes the new previous character.
üçâ
üçâ
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~150~~ 95 bytes
*-55 thanks to @dana*
```
x=>[...[...x].reduce((a,c)=>a+c.charCodeAt(0).toString(2).padStart(7,0),"")].map(c=>x!=(x=c)|0)
```
[Try it online!](https://tio.run/##FcuxDoIwEADQXxGmu4gX4qJLSYyLO4ODYbhcC0IqR0olHfz3qsMb38QbrxLGJR62c@5NTqZ5ENFf6ig4@xYHwJWgaXgvJE8OV7XuEqFGitrGMM4DHJEWtm3kEOFU1ViVJXb04gXENKkwkIzgp8YsOq/qHXkdoIfy5rzX3V2Dt0WJNOk4w69i/gI "JavaScript (V8) – Try It Online")
[Answer]
# [Python3.8](https://www.python.org/downloads/release/python-380b2/), 72 bytes
**Solution:**
```
lambda a:["10"[a==(a:=x)]for x in"".join(bin(ord(i)+128)[3:]for i in a)]
```
**Explanation:**
Ever since Python 3.8 introduced assignment expressions (rather than the standard assignment statements), I have wanted to use them in a list comprehension that needs to remember the last item.
This is not the best way to do this but demonstrates an interesting method of using the assignment expression.
The code creates a lambda function which takes the required argument which is the string to convert. When called, the function proceeds as follows. Every character in a is converted to its character code which 128 is added to for dealing with 6-bit characters (the binary representation will always be 8 bits and we can chop off the first bit). This number is converted to binary and the header (0x) and the initial 1 from adding 128 is chopped off. These new strings are then joined into one larger string.
For each character in this new string (which contains the concatenated 7-bit representation of the text), it is checked if the character is the same as the previous character. What happens with the first character? The first result character should always be "1" so we just have to make sure that whatever is in the last character variable is neither "1" nor "0". We do this by reusing the original parameter now that we are not using it anymore. This may be a problem if the original string was a single "0" (a single "1" just happens to work) but we will ignore that.
During the comparison, the previous character was evaluated first so when we use the assignment expression to set the previous character variable to the current character, it does not affect the comparison expressions' evaluation.
The comparison either produces True or False which can also be used as 1 or 0 respectively in Python, so they are used to look up either a "1" or "0" in a string
[Answer]
# [Tcl](http://tcl.tk/), ~~215~~ ~~167~~ 140 bytes
```
{{s {B binary} {X ~$w/64}} {join [lmap c [split $s {}] {$B scan $c c w;$B scan [$B format i [expr 2*$w^$w^$X<<7]] B7 r;set X $w;set r}] ""}}
```
[Try it online!](https://tio.run/##ZU9NT4QwEL3zK56lXLzYGuMedk8YEy@rFxNJKiaIkGC60JQa3BD861g@SpbddtJ5M51588aksq8zgxzvfdvWaEN8FmWijx3aCH@0ubm/6yz@rooSQh4ShRSiVrIwoLa8i9HSEHWalKCp/Wu2LhQW5JU@JAYFRParNG6vafMxWLTbbeIY4QZ6O4yPQJsRaEtISNf16sfUIJwza4wPdwR8xs6xKT86B9h4pg5XyeZu@xBv5BaJUvIImoM8ZVJWeKu0/LoisedG84l0cY58FsTYmRY@iXGA82XmJHwhu1QQBHh42e8fn18RBCsJy@bsssv3XelJksT96T7eKljN8Xz/Hw "Tcl – Try It Online")
Uses shift-by-one and exclusive-or to detect transitions. Carries lsb of current character to msb of next character. Combines output for each character by joining list returned by lmap.
Uses lambdas with default arguments to save bytes on initialization and repeated commands.
Relies heavily on order of operation. Works for empty string.
[Answer]
# [Haskell](https://www.haskell.org/), 137 bytes
```
import Data.Char
b 0=[]
b n=odd n:b(n`div`2)
d x|x='1'|1<2='0'
c=('1':).map d.(zipWith(/=)<*>tail).concatMap(reverse.take 7.b.(+128).ord)
```
[Try it online!](https://tio.run/##HY7BisIwFADv@Yq3SGmywtP24iLGiwpeul4WPCxCX5NAg2lS0igi/nu37mmYyzAtDVfj3Djarg8xwZ4S4a6lyBpYyt/LBC@D1uDXDfe1tve6FEzD4/WQeZG/ik0p82XOlOSTrgV21ING/rT92aaWL6TYfG4TWSdQBa8oVdTzaO4mDgYTXQ2ssEE@L8ovgSFqMXZkPUiwPplIKgG/eWe9GQDhHVcT/12Mx@k8wDlEpz9YlsHuVFWH7x/IMjab/QE "Haskell – Try It Online")
The biggest problem here is converting booleans (result of the XOR) to '0'/'1'.
[Answer]
# [Python 3](https://docs.python.org/3/), 88 84 bytes
```
l=2;s=''
for c in''.join(f'{ord(c):07b}'for c in input()):s+='01'[l!=c];l=c
print(s)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8fWyLrYVl2dKy2/SCFZITNPXV0vKz8zTyMJiA2NLLTzi1I0kjU1o42tYmFKgKigtERDU9OqWNtW3cBQPTpH0TY51jrHNpmroCgzr0SjWPP/f4/UnJx8hfD8opwURQA "Python 3 – Try It Online")
I feel that the assignments should be avoidable, but couldn't think of any way to do that.
**Update:**
* -4 bytes thanks to [movatica](https://tio.run/##K6gsycjPM/7/P8fWyLrYVl2dKy2/SCFZITNPXV0vKz8zTyNNqTq/KEUjWdPKwDypVgkmDUQFpSUamppWxdq26gaG6tE5irbJsdY5tslcBUWZeSUaxZr//3uk5uTkK4TnF@WkKAIA)
[Answer]
# [PHP](https://php.net/), 90 bytes
```
for(;$c=ord($argn[$j++]);$o.=sprintf('%07b',$c));for(;($q=$o[$i++])>'';$p=$q)echo$p!=$q|0;
```
[Try it online!](https://tio.run/##XVFdS8MwFH3fr7jOlLRYXfIkWOsYokzY3GCCD7WMWrOtUpssTUVQf3u9/dwwLc25yTk5J7dqp8rrsdqpATEiNzn4EAwAAqBTkaYSnqVO306oC5Rzhi/j1VMD3uJuYs16PXWA1aNRdEzWqvFDIXQbN8uC28V8fvf4BJbV2PHmoH7qDmxDMPbPnzcBOsB579OE7Q87uJ6edlb9rRjtN4/2qsXQG2ykFlG8s6FtVpQjAge@USFf17mJtLEdD3CMRhBHyhRagCyMKgygGCoZckmktxm2mpiAhV7FzZOPIo2MAPwVcH7fk/MSke2R2Jf6za51AXk/Owsdj8gLP1c6yczGpha7fKUuiR3HqwU22ftEBiSpqDeUekT5ZO@IeCeJOkH4w7yyCoIpMPlWmHWciijD9JivouGeC8MXM3QR@T5G5SGMgS4nqxWFK6D3k4cZtmg5Xa7vFrNKhvfQIhcGRPaZaJl9iMyAkYfLZeLLdD0oMmTaJKkN2@L9uJDHhcLit/wD "PHP – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 80 bytes
```
s=>{for(int p,c=2,i=0;i<7*s.Length;Write(p==c?0:1))(p,c)=(c,1&s[i/7]>>6-i++%7);}
```
[Try it online!](https://tio.run/##RYyxCoMwFEX3fEVQWpIaW@1QoTEp3Tq4dxAHCVHfEiUJ7SB@expKodPlXA5HuVw5CHflYTa18xbMKAcRnJDrMFsCxuOFKXFmIAoOdXVwx0ab0U/8acFrsgihbsW1pJREjwqiWLl3LZyqTspLDlm2qyjfAkcIxaDu1URevcUOg8FGv9tuTR6QsCRNk42iFWH8DTdgNHGURx5@@/8jbuED "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), 73 bytes
```
s=>[...c=s.repeat(7)].map((_,i)=>(c=1&s.charCodeAt(i/7,p=c)>>6-i%7)!=p|0)
```
[Try it online!](https://tio.run/##BcFRCsIwDADQs9ihJLBF/bH7SUE8hoiU2GnHXENb9uXd63uz33yRHLUO29gmboXdnYiEC@WgwVew@KCvV4BnH5EdCJ8PheTj8y29wrVCPNpeWdC5yxD3FnesvxM2SWtJS6AlvWEC03UGaU5xBWMQ2x8 "JavaScript (V8) – Try It Online")
] |
[Question]
[
* Original: <https://james-iry.blogspot.co.at/2009/05/brief-incomplete-and-mostly-wrong.html>
>
> Alain Colmerauer designed the logic programming language Prolog. His goal was to create a programming language that is as intelligent as a two-year-old child. In order to prove that he had succeeded in his goal, he presented a Prolog program that answers "No" resourcefully for all inquiries.
>
> Ask me anything!
>
> ?-
>
>
>
* (Of course he didn't.) Your task is to create a program that is more intelligent than Alain Colmerauer's program. This does not have to be in Prolog.
## Specifics
* If input ends with `?` and has at least one `,`, return text from the last `,` until before the last `?`.
* Else, if input ends with `?` return `No`.
* Else, return `Yes`.
## Rules
* No standard loopholes.
* Input/output will be taken via our standard input/output methods.
* Your program has to take at least 1 inquiry.
* You should output the processed inquiry.
* The `Yes` and `No`'s are case-sensitive in the examples.
* You are guaranteed that if the input includes a `?`, the input will only have one `?` and it will always be the last character.
* The input will always be a phrase/sentence. This phrase/sentence will never only contain the characters `,` and `?`, e.g. `,`, `?`, and `,?` are not valid inputs. (Although submissions might implement it anyway, since the phrase/sentence is an empty string in these cases.)
* In addition, the input will never end with `,?`.
* If there is whitespace immediately after the last `,` or immediately before the `?`, they should be included in the output.
## Examples
```
Hmm. -> Yes
Alright, -> Yes
Ask me anything! -> Yes
Ask me a question, please! -> Yes
Are you okay? -> No
No? -> No
Hey,does this program work? -> does this program work
Quotes in the following test cases should not be outputted.
They are used as a delimiter here.
Okay, so this does work ? -> " so this does work "
Please, add, a, test, case, containing, multiple, commas? -> " commas"
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
[Answer]
# [Python 3](https://docs.python.org/3/), 62 bytes
```
lambda s:['Yes',*s[:-1].split(','),'No'][~(','in s)*('?'in s)]
```
[Try it online!](https://tio.run/##fc7BCsIwDAbgu08R8ZBuVEG8DXR487S7zB0qq1q2NrWZSC@@@pyIelFvSf6PJD52J3KL/rDc9a2y@1oBZyVuNaNMucym82rGvjWdQImJxIKwKm@PxjjgJBWYP6uq98G4ThwEbqydYZLAZLqCYdHoHay5AatBueGoccfxXwTni@bOkJPgW61Y/@BBQ6QLUKNi/hIFfUBBX8cbHWVNmmF4hcEHOgZl4UqhefPvcX8H "Python 3 – Try It Online")
The expression `~(','in s)*('?'in s)` evaluates to `0` (i.e. `'Yes'`) if the string does not contain a `'?'`, else `-1` (i.e. `'No'`) if the string does not contain a `','`, and otherwise `-2` (i.e. the last comma-separated section of the string excluding the last character).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'?åi',¡”€–”0ǝθ¨ë”…Ü
```
-1 byte thanks to *@Grimy*.
[Try it online](https://tio.run/##yy9OTMpM/f9f3f7w0kx1nUMLHzXMfdS05lHDZCDD4PjcczsOrTi8GiTYsOzwnP//PVIrdVLyU4sVSjIyixUKivLTixJzFcrzi7LtAQ) or [verify all test cases](https://tio.run/##PY0xCsIwGIX3nuLXxSWINwhuncQrxDZoqMlfm1QJKBQHZ9HVDg6KoAdwbgY3D9GLxOjg8r@f7/HeQ80mgvv10ro97UK7O0CX@h51F9Ejzbmt6nb7aKtjeAav@v1sbu7@hdXVnYL6DfGxlP1oqDOQHJiyZibUtPMHsCi5NgIVgXzOmebBKjhYLAEzZmk0QhrF3JIUuYYQ1pAXOC2YhBUWGY3GvxQBlqbhEDChjkDyYwkqw4QKgwRkOTciTHyplEzTDw).
**Explanation:**
```
'?åi '# If the (implicit) input contains a "?":
',¡ '# Split the (implicit) input on ","
”€–” # Push dictionary string "Not"
0ǝ # Insert it at the first position (index 0) in the list
θ # Then get the last item of the list
¨ # And remove the last character
# (either the "?" of the original input; or the "t" in "Not")
ë # Else:
”…Ü # Push dictionary string "Yes"
# (after which the top of the stack is output implicitly as result)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `”€–”` is `"Not"` and `”…Ü` is `"Yes"`.
[Answer]
# JavaScript (ES6), ~~53~~ 52 bytes
```
s=>(m=s.match(/(,?)([^,]*)\?/))?m[1]?m[2]:'No':'Yes'
```
[Try it online!](https://tio.run/##ndJBa4MwFADge3/FmxfjyJTt2GJlh0HZwQ52Gp2FoNE6jc/lxQ1/vUvsZYNC1@YQyEveR/JePsSXoFzXvbnrsJBTGU8Ur5mKKVTC5AcWMZ4EbLfn2W3wnkRBkKjdfWanh2zpp@gv/TdJ/rTaLQC8jVKhx@GaEUXgWclzzCM1oCSIbjSHuqtuLiBPMfA5SDI1dhz6VgqS58E/jJYw4gDYiDG57HWOSXFWUkyurMxvZSNHXqAksIUh6DVWWij4Rt2c1Z1yOnWWt/Z1HAiP2/NBtwf/uLWTT2TO7MtccA6iKOzEwdhOcMjnWI6dEXVnO8xBDa2pbXdcVClBiXdkjytvkS3CEvWTsD@SIF67XMJWhi1W7Pl1m4ZktIXqcmQlo8CO1fQD "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // s = input string
( m = s.match( // m is the result of matching in s:
// +------------> an optional comma
// | +------> followed by a string containing no comma
// | | +--> followed by a question mark
// <--><-----><>
/(,?)([^,]*)\?/
)) ? // if m is not null:
m[1] ? // if the comma exists:
m[2] // output the string following it
: // else:
'No' // output 'No'
: // else:
'Yes' // output 'Yes'
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~23~~ 22 bytes
```
¿№θ?¿№θ,⁻⊟⪪θ,¦?¦No¦Yes
```
[Try it online!](https://tio.run/##Vcs9DsIwDAXgnVNYmVLJnIChAzMoEhNjlAaw5PxQJ71@CKUIsVh633t2Dzu7ZLk1uoE@phqLfiKoUQ0D/BO@yczU44liFW1S1pfM9Ku3xwN4Fr9t1Tmpr@SPXL10as2wt@IR7DT1g1C8FAS3mkuxWIoU7wihcqHMq4ZgZdy1/cIv "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 1 byte thanks to @KevinCruijssen. Explanation:
```
¿№θ?
```
Does the string contain any `?`s?
```
¿№θ,
```
Does it contain any `,`s?
```
⊟⪪θ,
```
Split the string on `,`s and take the last.
```
⁻...?
```
Delete the `?` and output the result.
```
No
```
If there are no `,`s then output `No`.
```
Yes
```
If there are no `?`s then output `Yes`.
[Answer]
# [Perl 5](https://www.perl.org/) + `-plF/,|\?/`, 25 bytes
```
$_=/\?$/?/,/?pop@F:No:Yes
```
[Try it online!](https://tio.run/##PY6xagMxEER7fcUGXG6iKo0hbNwYV07agCEI33IWJ2llrY5wkG@PortAmi3ezOxM5hKeW9t9vtgL7SxZtJQlvx73Z9l/sLZ2ivHJHELx462iOegEkcGlpd58Gh/@Adxn1uolIeTATrlLhWGRGWRyC5mzkDnxgoOwQg8r5CJjcRG@pExk3roLQeVP21yrAGTet38Ibhj6Qai9COG6sauk6nzqUxDiHKrv5SuN0Sn9SF4XaXvM4Wjx@0L2Fw "Perl 5 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 25 bytes
```
?qeQ\??}\,QPecQ\,"No""Yes
```
[Try it online!](https://tio.run/##Hcg7CsAgDADQq0jm3MEbFB0LLkFDK/grSYcOPbstLm9449FzTnuxD9a@Ab3j6APC1gF2ljnBFSZhNJTSDxplUTRxXexNKbfcDjT1LppHWVsriYUP "Pyth – Try It Online")
```
?q # if ==
eQ\? # Q[-1] "?":
?} # if in
\,Q # "," Q:
cQ\, # return split(Q, ",")
e # [-1] (last element)
P # [:-1] (remove the trailing ?)
"No" # else: return "No"
"Yes" # else: return "Yes" (last " implicit)
```
[Answer]
# [Zsh](https://www.zsh.org/), 51 bytes
```
<<<${${${1#*\?}:+Yes}:-${${${${1##*,}%$1}:-No}%\?}}
```
[Try it online!](https://tio.run/##qyrO@J@moanx38bGRqUaBA2VtWLsa620I1OLa610IWIgUWUtnVpVFUOgmF9@rSpQSe1/TS6uNAX1/OzESoWSjNQ8dRDPsxjIzixWSFQoLE0tLsnMz7MHizvn5@YmFuso5OXDJfRQJMozSzIwdPmW5pRkFuSkKiRDVSXmpShUppboYKh0zUsphpihAxT4DwA "Zsh – Try It Online")
A byte can be saved if `ends with,?` and similar are invalid.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ëw‼◘╔╤▬n→ª▒¡Γ╟ï¿
```
[Run and debug it](https://staxlang.xyz/#p=89771308c9d1166e1aa6b1ade2c78ba8&i=Hmm.%0AAlright,%0AAsk+me+anything%21%0AAsk+me+a+question,+please%21%0AAre+you+okay%3F%0ANo%3F%0AHey,does+this+program+work%3F%0AOkay,+so+this+does+work+%3F%0APlease,+add,+a,+test,+case,+containing,+multiple,+commas%3F&a=1&m=2)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~32~~ 28 bytes
```
^'?K`Yes
.+,(.*)\?
$1
'?K`No
```
-4 bytes with tips from *@Neil*.
[Try it online.](https://tio.run/##PY3NCsIwEITveYoVFP9CoU8QPFkQildBpEu71NAmW5MUydPHtAcvc/iGb8ZR0BbLtDtcm/Taq1vzIC@KszwUp@NTiW0pFlhzSpUxhbj4AQwB2hje2vabP4DPTD5othKmkdBTrhxB5Bl4wKhEzUpUFGXH5CHLHibHvUMDX3aDEvfVkoBdl0NCyHMS2pW1bANqmw8lmHkMOl8s1Bj06gc)
**Explanation:**
```
K` # Replace any (implicit) input, which does
^ # NOT
'? '# contain a "?"
Yes # with "Yes"
.+ # Match 1 or more characters
, # followed by a comma
.* # followed by zero or more characters,
( ) # (captured in capture group 1)
\? # followed by a (trailing) "?"
$1 # And replace it with just the match of capture group 1,
# (so everything between the last comma and trailing question mark)
K` # Replace any remaining string, which does
'? '# contain a "?"
No # with "No"
# (after which the result is output implicitly)
```
[Answer]
# IBM/Lotus Notes Formula, 79 bytes
```
@If(@Ends(i;"?");@If(@Contains(i;",");@Left(@RightBack(i;",");"?");"No");"Yes")
```
No TIO for Formula so...
[](https://i.stack.imgur.com/66f2j.png)
[](https://i.stack.imgur.com/Z9JIN.png)
[](https://i.stack.imgur.com/5jm8R.png)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~98~~ 87 bytes
*-9 bytes thanks to ElPedro*
```
x=input();o="Yes"
if"?"==x[-1]:o=x[(x.rfind(",")+1):-1]if x.count(",")else"No"
print(o)
```
[Try it online!](https://tio.run/##TZAxb9wwDIV3/QqWk4RTDATdXBhGtkxJhyxB20Gx6AtzkuhKMmr/@qvOAYpqkIjvPfIRWvb6LunrdRJPMAAiXreB07JWbb7JgK9UUPGMIw7D9uPu/lcv7dVbl2dOXqNFc7o3fRN4hq2bZE31oBQK4ZOgWjI3JObaZivFcZFcoexF0UaTRk8zzPpIND3Cqa3QfQgnjYCnwIlglgxHwQlua3ZlCVxvpOiXvJIxFs5B3lwo2hil/ve3nK5Uz6nL5Pxnj@kVtDPr4OKbd/1h7nKpmReNPxMac32MsVMPIfP5vVr1UC4QCVxqn8Xp/OUfgN8rlcqSLCyBXKEmZYJdVpCL20f1JKN6pN16oQKtucCS5ZxdhD@SL6N6bi4LRT61w3UTYFTfj3kWnPftslBbkIXpYJOk6ji1VSzENVRu4TcaoyvjXw "Python 3 – Try It Online")
This has been solidly beaten by other answers, but I'm trying out golfing in Python a bit more. Advice is appreciated!
[Answer]
# [PHP](https://php.net/), 58 bytes
```
<?=$argn[-1]=='?'?substr(strrchr($argn,','),1,-1)?:No:Yes;
```
[Try it online!](https://tio.run/##PY2xqsJAEEX7fMUoQhQmD9KqYbERK3ntQy3WZEhC3J11Z8MjP@@6prCYW5zLneM6F@NeVSvtW3spyltV5SpXMt4l@HU6X3d@PbeYY77BEotyo7Zn3v6R7CLVHcPyape7eDLmJzvIAIZA2yl0vW0XXwDPkST0bBHcg7RQqjzBxCPwoCeVnVllJ5qwYRJIYwHnufXawD/7QWW/8wpBN00KhJDeIdQzq9kG3dskRDDjI/RJ8aHGaFEvdh@vxOL4Bg "PHP – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 78 bytes
```
func[s][r:"Yes"parse s[to","copy t to"?"(r: last split t",")| to"?"(r:"No")]r]
```
[Try it online!](https://tio.run/##bY7BasMwEETv@YqpTg2IfoAvprecQumtGB@EvU6FLa2yK1ME/XdHySG40Muy@2bYGaFx@6Sx6w9Ts01rHDrtO2nMF6lJTpSgXWZjzcCpIKPurXmVBovTDE2Lr6zKx9@nZM5sjr30WxIfMyaYUwhv5vA833VGILhY8rePl5d/JFxX0uw5WqSFnNIfkxAKr@DZlXbHz7y/TlTsyKSoIYokfBEX8MMy710fj@8WbhzrsMg11mJ4sIFjdj7WihZhXbKvVe40BKet2W4 "Red – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 40 bytes
```
{m/[\,(.*?)]*\?$/??$0.tail||"No"!!"Yes"}
```
[Try it online!](https://tio.run/##bY8/a8MwEMV3fYpnYYodVDtTl9CIbJlM19J0ELGcGls6V7IpIkm/uquYlkLpctz97s97N2jXP8wm4K7BI@azKV8OIitWMn9dHWRaSpmui1G1/eXCK@JJwp@159e5IYesb632Oc4MMGVcyjnut7zcxNqrgCb7TNc5u857Y4rYQVxlO9/BaCgbxrfWnpK/HO@T9mNLVmDotfL6d8JpBJpAnQryBitiFf1kex1ETdojnvUYHJ2cMvgg1y0T/7fY0yIhoOo6BoExagscF3YkGx@30aSAmfqxjX5u1Bjll5vf@Rc "Perl 6 – Try It Online")
[Answer]
# [Gema](http://gema.sourceforge.net/), 34 characters
```
*,*\?=@subst{\*,=;$2}
*\?=No
*=Yes
```
Sample run:
```
bash-5.0$ echo -n 'Hey,does this program work?' | gema '*,*\?=@subst{\*,=;$2};*\?=No;*=Yes'
does this program work
```
[Try it online!](https://tio.run/##S0/NTfz/X0tHK8be1qG4NKm4pDpGS8fWWsWolgsk5pfPpWUbmVr8/39ATmpicaqOQmJKCpDQUShJLS7RUUgGiyXn55UkZuZl5qXrKOSW5pRkFuSARXNzE4vtAQ "Gema – Try It Online") / [Try all test cases online!](https://tio.run/##lVFNTwIxED3TXzFskAIpYkj0QjbAwQQvYLyZhZiyW3Y3sO3adqME/e047SYICR68dKbvvfl47Zqb7JiIeMe1gP4UrDD2LeZGhB3SiOisKG7pKqSvwlB3n@50nmb2AjJbKARwubdZLtPmNQ7eK@ybK8mg3AnsfqnC0XtVgdry/dgRc@XxuTq/zcSeJUoYwDEGSq1SzQv4UHrrVdcpX7nAvgyMqmkvdBz4uiu4L3r2ezLgSYIH8w/DIPZYrKTluUS3DIpqZ3M05dCi4KZuWueUdAkpdS7tBugX3PQf7gy4OLy/iEM8l5ICfZJlZTG@CINtMXn8LEVsRYLpAs2QjdKQOxGeELQOzdN/RZPVdzBCF6ShfXUYtDog4kxB30l9VYDTBqq0g1QUfGB07BOgxx7rLcfhxFRrYw/LHgtHreE3cdhckV6IP3Wk0A0IafzDzmlo0KpXctnhd@OaxrXBrRpFZ7ow/Eu6WkG7XftyT@KWSpQUxx8 "Bash – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 23 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ø'? ?Uq, hoinu¹Ìk'?:`Y
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=%2bCc/ID9VcSwgaG9pbnW5zGsnPzpgWYM&input=IkhtbS4i)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 72 bytes
```
x=>x.Last()!=63?"Yes":x.Contains(',')?x.Split(',').Last().Trim('?'):"No"
```
Saved 2 bytes thanks to @someone
[Try it online!](https://tio.run/##ZZFBS8QwEIXv@ytmc2mLsRfBw65NEUH2sKyCggh7CW22G7ZJaibV9tfXNBEteMnw3ny8GSYVXlcop8deV3forNQNjYWdimko2JDvObo0Wxe3NyV5F0g2Q/5gtONSY5rQJCuH/KVrpQvih85frVRpUibZhhwMmbarTyNrcMI3YzxI3fUug4LBm5VO7KUWKWGMAYGr2PSVHHU0Tmnks@0qhJCdUjn5Vfetlc3Z0YWDF1ACuB7d2Y9b/@/AR@@1NJpC1wqOYslYAaPpwVz4WP7ZB7MQOzHS2ggEPwChs6axXMGXsZcF9OQDKKCJUMBnAhbIcxhOgde1f2g4EoUqeFU89PwroPrWSb/p7CrFcY6YvgE "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~66~~ ~~63~~ 62 bytes
```
lambda i:("Yes",("No",i[i.rfind(",")+1:-1])[","in i])["?"in i]
```
[Try it online!](https://tio.run/##TY8/b4MwEMX3fopXT0a4kdIRKUXdMkVZq7SDGww5gX3ENmr49PSgS294@vndnyePc75xeF3aw@cyWP/dWFCl1YdLymh1YmXoQrvYUmi0Mqoo99XL/qu4CFMArVT/0dJyxAPCWh2938nE@xCpu2WzYurhHWyQPArd8z8L98mlTBwMxsHZ5LZmdJh5Avd2ruV94lWPbjYNuwQ5kjBG7qL1@OHYr93ztm1gm0bEIMtZg@vmXTlkS0GiDfw0ZJKo1fXeploVqJ4gNUYKWT5RQuHwJlKi1Y9i@QU "Python 2 – Try It Online")
-3 after spotting the updated clarification "the input will only have one ? and it will always be the last character."
-1 with thanks to @ChasBrown
Basically a port of my [Lotus Notes answer](https://codegolf.stackexchange.com/a/192913/56555). Curiously, the clarification noted above does not help the Notes answer because `@Ends` is 4 bytes cheaper than `@Contains`. Now if only there was an `@In` function...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
Ṗṣ”,Ṫ⁾NoḊ?Ɗ“Yes”i?”?
```
[Try it online!](https://tio.run/##y0rNyan8///hzmkPdy5@1DBX5@HOVY8a9/nlP9zRZX@s61HDnMjUYqB4pj2QsP///7@OPQA "Jelly – Try It Online")
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~120~~ 118 bytes
Function-like macro:
```
#include<string>
#define f(s)({int i{},j{};for(;s[i];)j=s[++i]-44?j:i;s[--i]-63?"Yes":j?std::string(s-~j,i+~j):"No";})
```
[Try it online!](https://tio.run/##dZJPb5wwEMXvfIqJc4Gu6aVRD/zJKrdIlZJeq@0qsmDYNYttYhu1aEW@@nYwUVLR9IJ4v3nzPB6o@j49VNXlWqreWF9I47xFoW6J6KobaiwISH24ja5rbKRGaGKXxGepPcjzxNvzlDfGxrnbyX2etKXbbTZyn97cbNtMEk1TUl@/bNkPdCxrt87XWbZkxi59abncvLRJxh4My6fkMud6dD6ujsJ@krofPK@Mdh4CwN89Vh7rJzN4KiXnCMTgDVh0Q@fLJg4dSR6BbOJXWK6bIoAwRUW6KNju8dv@p2bUg53DVbGJWVGEUBIJlEByySUNV0Gv8qkQ4qZICanjtxlHdGXYQv4KtCnDtaPlxuxeqc@Mky15Q3edlYej52vsTqAQhB79kRZ59Z8yPA@kpdEc@g6Fw3@MFmE0A5iTGLeMa/NeejArcI8jrw06oCMd9NYcrFDwy9gTGdnHFfbe/khHcHBmMQX77IC5@QP8V@f3MDoHUdf04IFyqAKjX8PTkmkHHBR9FEn3nKlSwoXk5XVOmy5/AA "C++ (gcc) – Try It Online")
-2 bytes thanks to @ceilingcat
] |
[Question]
[
A jumping number is defined as a positive number n which all pairs of consecutive decimal digits differ by 1. Also, all single digit numbers are considered jumping numbers. eg. 3, 45676, 212 are jumping numbers but 414 and 13 are not. The difference between 9 and 0 is not considered as 1
**The challenge**
Create a program that output one of the following results:
* Given an input `n` output the first `n` jumping numbers.
* Given an input `n` output the `n`th term of the sequence.
**Note**
* Any valid I/O format is allowed
* 1-index or 0-index is allowed (please specify)
Here are some jumping numbers:
```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, 87, 89, 98, 101, 121, 123, 210, 212, 232, 234, 321, 323, 343, 345, 432, 434, 454, 456, 543, 545, 565, 567, 654, 656, 676, 678, 765, 767, 787, 789, 876, ...
```
This is also [A033075](https://oeis.org/A033075)
[Answer]
# [Haskell](https://www.haskell.org/), 57 bytes
```
(l!!)
l=[1..9]++[x*10+t|x<-l,t<-[0..9],(mod x 10-t)^2==1]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyNHUVGTK8c22lBPzzJWWzu6QsvQQLukpsJGN0enxEY32gAkrqORm5@iUKFgaKBbohlnZGtrGPs/NzEzT8FWoaAoM69EQUUhN7FAIU0BrNwy9v@/5LScxPTi/7rJBQUA "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
1DI*`ƑƊ#
```
A full program accepting an integer, `n`, from STDIN which prints a list of the first `n` positive jumping numbers.
**[Try it online!](https://tio.run/##y0rNyan8/9/QxVMr4djEY13K//@bmgAA "Jelly – Try It Online")**
### How?
Acceptable incremental differences between digits are `1` and `-1` while others from `[-9,-2]+[2,9]` are not. This lines up with integers which are invariant when raised to themselves. i.e. \$x^x=x\$ since:
$$0^0=1$$
$$1^1=1$$
$$2^2=4$$
$$\cdots$$
$$-1^{-1}=-1$$
$$-2^{-2}=-\frac{1}{4}$$
$$\cdots$$
```
1DI*`ƑƊ# - Main Link: no arguments (accepts a line of input from STDIN)
# - count up keeping the first (input) n matches...
1 - ...start with n equal to: 1
Ɗ - ...match function: last three links as a monad: e.g. 245 777 7656
D - convert to a list of decimal digits [2,4,5] [7,7,7] [7,6,5,6]
I - incremental differences [2,1] [0,0] [-1,-1,1]
Ƒ - invariant under?:
` - using left argument as both inputs of:
* - exponentiation (vectorises) [4,1] [1,1] [-1,-1,1]
- --so we: discard discard keep
- implicitly print the list of collected values of n
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 5 bytes
The input is 1-indexed.
### Code:
```
µN¥ÄP
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//0Fa/Q0sPtwT8/29qAAA "05AB1E (legacy) – Try It Online")
### Explanation
```
µ # Get the nth number, starting from 0, such that...
Ä # The absolute values
N¥ # Of the delta's of N
P # Are all 1 (product function, basically acts as a reduce by AND)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~79~~ 75 bytes
*-4 bytes by xnor*
```
f=lambda n,i=1:n and-~f(n-g(i),i+1)
g=lambda i:i<10or i%100%11%9==g(i/10)>0
```
[Try it online!](https://tio.run/##ZcyxCsIwGATgvU9xSyDBFPPrZGl8keIQqYk/6N8S2sHFV48p6OR0cHx382u5T3IoJfpHeF7HALHsqRMEGdt31NImzcbyjkyTfoY77slNGazIOUWkTt5Xtydnzq6s8BgYcQNgQQ6SbppstQYcsT1emjmzLFi/OcRa/k@OVGX5AA "Python 2 – Try It Online")
Derived from [Chas Brown](https://codegolf.stackexchange.com/users/69880/chas-brown)'s [answer](https://codegolf.stackexchange.com/a/180715/39328). The helper function `g(i)` returns whether `i` is a jumping number. Iff the last two digits of a number `n` have absolute difference 1, then `n%100%11` will be either 1 or 10, so `n%100%11%9` will be 1.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 36 [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")
1-indexed. Thanks to dzaima for their help with golfing this.
Edit: -15 bytes from ngn.
```
1+⍣{∧/1=|2-/⍎¨⍕⍺}⍣⎕⊢0
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKNdIe2/ofaj3sXVjzqW6xva1hjp6j/q7Tu04lHv1Ee9u2qBMo/6pj7qWmQAUsyV9qhtAlDa8FHPXvXaanUddaAkCBepP@rdqg5UZvSoZzuQn1yknqau8Kh3rkJJUWJKWp5CSb4CkPpfDVSmYPiodwuIoZMGJGpBVm0GMYwNAA)
**Explanation**
We have `f⍣g⍣h`, where, as `⍣` is an operator, APL translates this to `(f⍣g)⍣h`. (In contrast with functions where `2×3+1` is translated `2×(3+1)`)
```
1+⍣{...}⍣⎕⊢0 This is equivalent to
"do {check} we find the n-th integer that fulfils {check}"
1+⍣{...} ⊢0 Start with 0 and keep adding 1s until the dfn
(our jumping number check in {}) returns true.
⍣⎕ We take input n (⎕) and repeat (⍣) the above n times
to get the n-th jumping number.
{∧/1=|2-/⍎¨⍕⍺} The dfn that checks for jumping numbers.
⍎¨⍕⍺ We take the base-10 digits of our left argument
by evaluating each character of the string representation of ⍺.
|2-/ Then we take the absolute value of the pairwise differences of the digits
∧/1= and check if all of the differences are equal to 1.
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 90 bytes
```
f(n,K,b,k){for(K=0;n;b&&printf("%d,",K,n--))for(b=k=++K;k/10;)b*=abs(k%10-(k/=10)%10)==1;}
```
[Try it online!](https://tio.run/##FYxBCoQwDAD/IiiJttgeJeQFfYWpVCRsVtTbsm/vdm8zMEz2e861FjCXnDjFT3lfkDiQkQzDeR32FOj6zXUtMO8R/4Gw8jQl0jkGQhl5lRu0j8GDzhwDNkTmSN/6Wg@DtoVlwaY/ "C (gcc) – Try It Online")
[Answer]
# Japt, 14 bytes
Outputs the first `n`th term, 1-indexed.
```
_ì äa dÉ ªU´}f
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=X+wg5GEgZMkgqlW0fWY=&input=NTQ=)
(I know, I know, [I'm supposed to be taking a break](https://codegolf.meta.stackexchange.com/a/17410/58974) but I'm in golf withdrawal!)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~88~~ 87 bytes
```
f=lambda n,i=2:n and f(n-g(i),i+1)or~-i
g=lambda i:i<10or abs(i/10%10-i%10)==1==g(i/10)
```
[Try it online!](https://tio.run/##XYzBCsIwEETv/Yq9CAm2mK234n5J8ZBSEwd0W9L24MVfj1H04mUGHm9mfqzXSducg9z8fRg9aQ1pOyWvIwWjTTSwNfZsp/RsUMWfhw4ndlMiPywGB3Y7dg1KWBEWiR9m80ZCPSgUEQSl5DVeDNfsnCUEet@fqzlBV9q@3YcC/ydHV7z8Ag "Python 2 – Try It Online")
Returns the 0-indexed jumping number (i.e., f(0) => 1, etc).
[Answer]
# [Haskell](https://www.haskell.org/), 69 bytes
* Thanks to [Joseph Sible](https://codegolf.stackexchange.com/users/81540/joseph-sible) for enforcing the challenge rules and saving three bytes.
* Saved two bytes thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi).
```
(filter(all((==1).abs).(zipWith(-)<*>tail).map fromEnum.show)[1..]!!)
```
[Try it online!](https://tio.run/##HcmxCoMwEADQX6ngcFfwqKNg3PoFDh2sw1VMc/SiIYkU@vFNoW99jtNrVS3W3AtY0bxGYFUAY1okfiQk@Ei4SXbQYH8eMosieQ4nG3d/3Q5Pye1vnFqiuaqweJbNhCOPOf6ntn09TBeirpvLd7HKz1SaJYQf "Haskell – Try It Online")
[Answer]
# JavaScript (ES7), 60 bytes
Returns the \$n\$th term of the sequence (1-indexed).
```
f=(n,k)=>[...k+''].some(p=x=>(p-(p=x))**2-1)||n--?f(n,-~k):k
```
[Try it online!](https://tio.run/##FYtBCsIwEADvfcUeCs22JlChF2vqQ0RoqIlo6iY0IkIbvx7jaeYw81BvFabl7l@c3FWnZCSjnUU5nIUQtqmqiwjuqZmXHzkwz/@CWNd73uK2Eecnkwf@tXiwybiFEUhoeyA4QtdlNg3CWgBMjoKbtZjdjY2KlStFzGm55h/jiH0R0w8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
*-1 by Jonathan Allan*
```
1DạƝ=1ẠƲ#
```
[Try it online!](https://tio.run/##y0rNyan8/9/Q5eGuhcfm2ho@3LXg2Cbl//9NjAA "Jelly – Try It Online")
1-indexed.
[Answer]
# Swift, 228 bytes
```
func j(n:Int){
var r:[Int]=[]
for x in 0...n{
if x<=10{r.append(x)}else{
let t=String(x).compactMap{Int(String($0))}
var b=true
for i in 1...t.count-1{if abs(t[i-1]-t[i]) != 1{b=false}}
if b{r.append(x)}
}
}
print(r)
}
j(n:1000)
```
[Try it online!](https://tio.run/##VY@/CsIwEMb3PMUJDsnQkIBTMQ/g4ORYOqQ1kUiNIb1qIfTZ61Vc5Ib7x32/78Z38HhYVz/FHu481qeIorCXzZDrhprWNC3zzwwzhAhKShkLCx7mo9GqZGlTcvHKZ7G4YXSFDQ4BzQVziDeayv75SLbHs02F1PhvsVdCLF9KZzBP7ksIG0ETAelqiljpQiDbjRybUOm2otQK2BnQpTPeEm9ZNi/dnw@2RSIM8iyo3L7SSimxrh8)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~122~~ 121 bytes
```
g=lambda s:len(s)==1or 1==abs(ord(s[0])-ord(s[1]))and g(s[1:])
def f(n,i=1):
while n:
if g(str(i)):n-=1;yield i
i+=1
```
[Try it online!](https://tio.run/##JcpBCsMgEIXhdXIKlzO0gQztyjInCVkY1ESwY1Ch9PQ20t338975rUeSR2s7R/PerFFFRydQkJlSVsRstgIpWyjLvOL0F62IRqzau/WKo3VeeZB7YEI9Dp8jRKfk0hB8f9UMAVHLxPQ6c5B6ZR9vTM3Dc8b2Aw "Python 3 – Try It Online")
-1 byte by changing `f` from printing, to a generator function.
`g` is a recursive helper function which determines if a string `s` is a "jumping string" (this works since the character codes for 0 to 9 are in order and contiguous).
`f` is a generator function that takes in `n` and yields the first `n` jumping numbers.
[Answer]
# [R](https://www.r-project.org/), 85 bytes
```
i=scan();j=0;while(i)if((j=j+1)<10|all(abs(diff(j%/%10^(0:log10(j))%%10))==1))i=i-1;j
```
[Try it online!](https://tio.run/##DchBCoMwEAXQ0wT@R0pntqZzFSHaRmcILeiiG@8efcu39@52LOUL5jDJ/83bB06vQFgMypfKWVpDmQ@8vVZEeiaVCTK236qCINMdpJmSbv7QHF1F@gU "R – Try It Online")
Suspect this can be golfed more. Reads the number using `scan()` and outputs the appropriate jumping number.
[Answer]
# [Perl 5](https://www.perl.org/), 56 bytes
```
map{1while++$n=~s|.(?=(.))|abs$&-$1!=1|ger>9}1..<>;say$n
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saDasDwjMydVW1slz7auuEZPw95WQ09TsyYxqVhFTVfFUNHWsCY9tcjOstZQT8/Gzro4sVIl7/9/Q@N/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online")
1-indexed, outputs the nth jumping number
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 85 bytes
```
If[#<10,#,t=n=1;While[t<=#,{-1,1}~SubsetQ~Differences@IntegerDigits@n++~If~t++];n-1]&
```
[Try it online!](https://tio.run/##BcGxCsMgEADQXykIXTSQmxPBIYtbS4cO4mDDaQ6aG/Q6lfrr9r0zyYFnEtrTKHb4HNQKs1FGLFtYnge9MchqlflOYODXH59XQ7n3jXLGirxjc54FC9aNCklzrHX3uYvWceEJ4nXcKrFcXAkwz3GMPw "Wolfram Language (Mathematica) – Try It Online")
returns the n-th number
[Answer]
# [Factor](https://factorcode.org/), 129 bytes
```
: f ( x -- ) 1 [ [ dup 10 >base >array differences [ abs 1 = ] all? ] [ 1 + ] until
dup . 1 + [ 1 - ] dip over 0 > ] loop 2drop ;
```
[Try it online!](https://tio.run/##JY6xTsNADIb3PsU/glAqimBJRTuiLl0QU9TBzfnoqUfusB1Enz51U1my/X@yPjlSb0Wmr8/d/qPFmWXgjCpsdqmSBsMP2WlZSZTlvquRJbXUK0iELjpjKP@OPPSsWC92@xZ9CfxdcpxaRDzgH02DR6zQeYWxYvWMzZGUsZktCClGlruhAx3Vb99xAOW89dF5fPI5Dpby4iZYzuTGG@chVZQ//9G1HnMpFS9BvK@nt1fE6Qo "Factor – Try It Online")
Outputs the first `n` jumping numbers
[Answer]
# [Catholicon](https://github.com/okx-code/Catholicon), 5 bytes
```
ρHṘḃǰ
```
[Try it online!](https://tio.run/##S04sycjPyUzOz/v//3yjx8OdMx7uaD6@4f9/Q0MA "Catholicon – Try It Online")
] |
[Question]
[
A Harshad number is a number that is divisible by the sum of its digits. This is obviously dependent on what base the integer is written in. Base 10 Harshad numbers are sequence [A005349](https://oeis.org/A005349) in the OEIS.
## Your Task:
Write a program or function that determines whether a given integer is a Harshad number in a given base.
## Input:
A positive integer <10^9, and a base between 2 and 36, OR, a positive integer in its base, using lowercase letters for the numbers from 11-36 and a base between 2 and 36. You only have to handle one of these options.
## Output:
A truthy/falsy value indicating whether the first input is a Harshad number in the base of the second input.
## Examples:
```
27,10 ----------> truthy
8,5 ------------> truthy
9,5 ------------> falsy
1a,12 OR 22,12 -> truthy
```
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 46 bytes
```
lambda n,b:n%sum(n/b**i%b for i in range(n))<1
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPJ8kqT7W4NFcjTz9JSytTNUkhLb9IIVMhM0@hKDEvPVUjT1PTxvA/SBCoFiQcrWFkrmNooKmjYaFjCiQtwaShkYmOkWasFRdnQVFmXolCmgZQueZ/AA "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
bSḍḷ
```
[Try it online!](https://tio.run/##y0rNyan8/z8p@OGO3oc7tv@3Vjq8XP9R0xr3//@jjcx1FAwNYnUUoi10FExBtCWUNjQyAUrFAgA "Jelly – Try It Online")
### How it works
```
bSḍḷ Main link. Arguments: n (integer), k (base)
b Convert n to base k.
S Take the sum.
ḷ Left; yield n.
ḍ Test for divisibility.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 73 bytes
```
def f(n,b):
if b<2:return 1
s=0;c=n
while n:s+=n%b;n//=b
return c%s<1
```
[Try it online!](https://tio.run/##VcpBCsIwEADA@75iL4UsBtqNipo2n0lNaEDWkkSkr08vCnocmHWry1OOrd1DxKhEe7KAKaKfjM2hvrIgAxY3jLMTwPeSHgHFloOTzo/S984DfuLclYnbmpNUFZW5aB6I4OurPv/o9ic2J81EbQc "Python 3 – Try It Online")
1 is truthy, you know.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~54~~ 47 bytes
```
n,k=input();m=n;s=0
exec's-=m%k;m/=k;'*n
1>>n%s
```
Time and memory complexity are **O(n)**, so don't try **109** on TIO.
Output is via exit code, so **0** is truthy, **1** is falsy. If [this output method](https://codegolf.meta.stackexchange.com/a/11908/12012) winds up being allowed, a further byte can be saved by turning the program into a function.
*Thanks to @musicman523 for suggesting exit codes!*
[Try it online!](https://tio.run/##K6gsycjPM/r/P08n2zYzr6C0REPTOtc2z7rY1oArtSI1Wb1Y1zZXNds6V98221pdK4/L0M4uT7X4/38jcx0FQwMA "Python 2 – Try It Online")
[Answer]
# Dyalog APL, 20 bytes
```
{⍺=1:0⋄⍵|⍨+/⍺⊥⍣¯1⊢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOpHvbtsDa0MHnW3POrdWvOod4W2PlDoUdfSR72LD603fNS1CChe@///o44ZemlA6Ue9mw1N/wMA) [15 first numbers in 15 first bases]
Takes the number as a right argument and the base as a left argument, 0 is truthy.
**How?**
`⍺⊥⍣¯1⊢⍵` - `⍵` in base `⍺` as a list of digits
`⍵|⍨` - `⍵` modulo ...
`+/` - the sum
[Answer]
# Pyth, 12 7 bytes
```
!%hQsjF
```
[Try it online!](http://pyth.herokuapp.com/?code=%21%25hQsjF&test_suite=1&test_suite_input=%5B27%2C+10%5D%0A%5B8%2C+5%5D%0A%5B9%2C+5%5D%0A%5B23%2C+12%5D&debug=0)
Byte count is now lower since unary is no longer required.
### Explanation
```
!%hQsjF
jF Fold the input over base conversion (converts given number to given base)
s Sum the values
%hQ Take the first input modulo that sum
! Logical not, turning 0s from the modulus into True and all else into False
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
¦ΣB²¹
```
[Try it online!](https://tio.run/##yygtzv6fm18enHpiffGh5YeWPGpqLHrUNuFR26TyQ9v@H1p2brHToU2Hdv7//9/QQMHInMtUwQKILbkMjRSMjAA "Husk – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~64~~ 60 bytes
(requires the `pryr` package)
```
pryr::f({d=pryr::f('if'(n<b,n,n%%b+d(b,n%/%b)));!n%%d(b,n)})
```
This is an anonymous function that takes two arguments, `b` and `n` that evaluates to (which is on TIO):
```
function(b,n){
d=function(b,n)
if(n<b) n else n%%b + d(b,n%/%b)
!n%%d(b,n)
}
```
where `d` computes the digit sum for the required base.
Dropped 4 bytes once the base was guaranteed to be greater than 1.
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jSSdPs5pLIcUWRYRLQSEzTSPPJklTIU8hNac4VSFPVTVJQVshBSStqq@aBFSiCBRLgSiv/Z@mYWigY2Su@R8A "R – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
```
vUsV ¬xnV
```
Takes input as two integers.
[Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=dlVzViCseG5W&input=MjIgMTI=)
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 54 bytes
```
n->b->{int s=0,c=n;for(;c>0;c/=b)s+=c%b;return n%s<1;}
```
[Try it online!](https://tio.run/##ZZBRS8MwFIXf9ysOhUKLXe0qgq5rBZ8U0QnzrfQhTbOZ2aUlSYcy@ttn2nVzauAm4eS7OYe7Jlsyrmom1sXHvm7yklPQkiiFZ8IFdiNgUJUm2hzbihfYmDdnoSUXqzQDkSvl9iiwNv/5jealv2wE1bwS/j1/lazglGg2exSarZj0hjNBjXjvCC93x8mOCw0VBx6NRbSspBPRJIjoZZy76iKmdh5JphspIGw1m0TtPuodTVeamRSaKa0QDzm6tUMYeJh01XpnKm484PqfentQg19qGBouPGfbg20XsLfujacHe/fknldVyYiAZKoptYlV@x3hdFsaZF7Pp5PMjf40sM@aUc0K09IjYYYEwZFafCnNNn7VaL8209dLx7KvCjMD5EQx2KG5K1uB4IFI9U4KiGaTMwnHVq4trMH3LIB3jHgHy5rCwsv8zTqJcfwTyADzJwuGMQjMdcjejrpq998 "Java (OpenJDK 8) – Try It Online")
[Answer]
## Javascript (ES6), ~~68~~ 67 bytes
```
n=>k=>!(n%eval([...n.toString(k)].map(_=>parseInt(_,k)).join('+')))
```
Note that since we are required only to handle either base-*k* or base-10 numbers for `n`, I assume `n` is a base-10 integer always.
-1 byte, thanks to TheLethalCoder!
How it works:
```
! # Convert to true if 0 else false
(n% # Compute n modulo
eval( # evaluate string
[...n.toString(k)] # convert to array of base-k divisors
.map(_=>parseInt(_,k)) # map lowercase characters to ints
.join('+') # join array as string of characters
) # get the raw remainder, and let ! do its work
)
```
[Try it online!](https://tio.run/##ZcuxDoIwEADQ3a/AwXAX4aJNDDrA7uxoDClYSKFem7bh9ytxlPUlb5KLDL3XLpad7JQp2b5VGuoEXMxYN3vgg1qkgScRMUX7iF7zCDO@6CMdtHXjpA/qzhHadSBNVjPkxxwRU285WKPI2BEGEFWRnU@Iuz8WK4sN34rsssHrD9MX "JavaScript (Babel Node) – Try It Online")
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 12 bytes
```
{~(+/y\x)!x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqrpOQ1u/MqZCU7Gi9n@agp66hpG5gqGBtYWCqbUlEBsZKRgaaf4HAA "K (ngn/k) – Try It Online")
A function taking an integer (`x`) and the base to use (`y`).
* `y\x` convert `x` to a base-`y` representation
* `+/` take the sum of the digits
* `~(...)!x` check if the sum of the digits mod the input integer is non-zero
[Answer]
# Javascript ES6, 62 bytes
```
n=>b=>!(n%[...n.toString(b)].reduce((x,y)=>x+parseInt(x,b),0))
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 37 bytes
```
f(n,b,i,s){n?f(n/b,b,i,s+n%b):i%s<1;}
```
[Try it online!](https://tio.run/##fYrBCsIwEETv@xWhEkhw1SYgtrboj3gxia0Luoqpp9Jvj0Gv0jk8mHnjV733KXWK0SFh1CMfc9m4X12ydHpPMrammRIsiP3tHS6ijUOgx/p6ACAexP1MrDSMIHKerzx1qpDhxAWKTtkdmhIzS62b/5cKt1jN@Dr7esZbi8Zi5vcyQfoA "C (gcc) – Try It Online")
Returns zero for true, non-zero for false.
I want to know, why not just `i%s` does work, but `i%s<1` does (*isn't that very strange?*).
[Answer]
# [Perl 6](https://perl6.org), 40 bytes
```
{$^b>1??$^a%%[+] $a.polymod($b xx*)!!?1}
```
[Test it](https://tio.run/##TY5bboMwEEX/ZxUTyalMMVBHSfpACVlE/9qmMuC0SAZb2FSglBV1F90YhaRS8jlX99wzRtZqPTRW4tc6zGIoO7zJdC5xMxzJPt3yJCF7MZ@/@G9IRGi06kqdU5Ji2956s1nC@2Fkdk5ahxtURSUt9cJSmKcjIPq/P2Gmy5RGr7kfeQyTyNWN@@wihuQdepjMzyMbg1GiQv80FMNB1/@bwRbprqhM4xiRrZGZkzkjH4V1Hk6GwuL0L/0@l0bFpYanHvTD4p7xOwyCceyshwe2mu6r5PGSHISyHfDFkvFr6A8 "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with placeholder parameters 「$a」 and 「$b」
$^b > 1 # declare 「$b」 and compare against 1
?? # if 「$b > 1」 then:
$^a # declare 「$a」
%% # is it divisible by
[+] # reduce the following with &infix:<+> (sum)
$a.polymod(
$b xx * # infinite list of 「$b」s
)
!! # if 「$b <= 1」 then:
? 1 # Boolify 1 (shorter than True)
}
```
[Answer]
# Mathematica, 30 bytes
```
#2<2||Tr@IntegerDigits@##∣#&
```
Pure function taking two arguments, the integer and the base (in that order), and returning `True` or `False`. Careful: the first two `|`s are just the normal ASCII character, while the last `∣` is U+2223.
`#2<2` deals with the special case of base 1. Otherwise, `Tr@IntegerDigits@##` produces the sum of the digits of the first argument when written in the base of the second argument, and `...∣#` tests whether that sum divides the first argument.
[Answer]
## Batch, 119 bytes
```
@if %2==1 echo 1&exit/b
@set/at=%1,s=0
:l
@if %t% gtr 0 set/as+=t%%%2,t/=%2&goto l
@set/at=%1%%s
@if %t%==0 echo 1
```
Outputs 1 for Harshad numbers.
[Answer]
# [Python 3](https://docs.python.org/3/), 45 bytes
```
lambda n,b:int(n,b)%sum(int(i,b)for i in n)<1
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFPJ8kqM69EA0hrqhaX5mqAOJlATlp@kUKmQmaeQp6mjeH/giKQeJqGkpG5ko6CoYGmJhdcyNAYKGSKImKCIZIE0makqfkfAA "Python 3 – Try It Online")
Based on the updated formats for input.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 57 bytes
```
f(n,b,t,s){while(b>1&&t){s+=t%b;t/=b;}return b<2||n%s<1;}
```
[Try it online!](https://tio.run/##jc3dCoIwGMbxc6/iRVA2muSkqHhdV9KJW36BvYRbeKDeemvUuXT4/PnBY7LWGP@oemJ8jqAnByQ0RkCqOCFoJXN8jiE3LE7uN4pFwwIQJHLOv@yMENgRYZtd/mOyOGA43WSr/00nLJ@nrh9qpq8yTR2f7U65RKPbK43rWLvXSKDLYlkosaXE1fu3aYaqtT6bPg "C (gcc) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 25 bytes
```
(n,b)->n%sumdigits(n,b)<1
```
[Try it online!](https://tio.run/##JYhZCoAgEECvMgiBwggpRAXVRcIPKwrBZGiBOr1Zfb2F7ObkQnGGFiIPOAjZhWw/18kt7ti/06hoifzNL5Ad0ObCkZS9wWC03vMZ4RICoe91iSo3ySosXtQ/tEaljRHxAQ "Pari/GP – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
%ìV x
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=JexWIHg&input=MjIKMTI)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~49~~ 43 bytes
```
a,b;f(x,n){for(a=x,b=0;b+=x%n,x/=n;);a%=b;}
```
[Try it online!](https://tio.run/##dclNCsIwEEDh/ZwiVAIJHbUKUmWMJ3GTH6MBnUqtECg9eyy41bd8n19evS/FoqOoMrIeY9crazI605CrTZaMeW2YNFlpHE0FFon9/R0u4vgaQupWtxNA4kE8bGKlYQQx9@znFVUlw5krFFFtW9w0WtNv3ePurx2@NkH5AA "C (gcc) – Try It Online")
Returns zero for true, non-zero for false.
It is very simple. It just accumulates all the digits of `x` in `b` and returns `x % b`.
Ungolfed version:
```
// local variables
int a, b;
int f(int x, int n)
{
// Accumulate all digits in b
// Note that the for loop only checks x /= n
for (a = x, b = 0; b += x % n, x /= n;)
;
// Then return a % b.
return a % b;
}
```
Thanks to dingledooper for the -6 bytes!
[Answer]
# x86 Machine Code, 19 bytes
```
50 31 C9 99 F7 F6 01 D1 85 C0 75 F7 58 99 F7 F1 85 D2 C3
```
The above bytes define a function that accepts the value in the `EAX` register and the base in the `ESI` register, and sets the zero flag (`ZF`) based on whether the value is a Harshad number (`ZF` will be clear if the value is a Harshad number).
Note that this is a custom calling convention, defined expressly for the purposes of this challenge. Assembly/machine language programmers are allowed to do that. However, note further that the choice of the `ESI` register for the second parameter (base) is completely arbitrary. This can be changed to any other unused general-purpose integer register (*i.e.*, `EBX`, `EDI`, or `EBP`) without affecting either correctness or code size.
**[Try it online!](https://tio.run/##pZNbS8MwFMff@ykOkUI7qtOKeJ1XJu7Fl70MGZQsiVukTWsuMif76tZk7URn50Dz0vb8z@9cek7I9piQskyu8zyFnrrDUk0wvTfZiMnACMXHglF4walhEXx@j7BioffmgT0VKpkyqT6tLAlWWZIEaCiGujBqkgL4PsNTtJCXZyFPc2lVJ5NpVD1@eF0RYjKTYs38zklDDEKfG6yUv9SRFW@QMaW1TNcmHmrNlF5WH61t4knM3PvXOhu8iryoMzYG2dTFhvrqLuh3rxNAnUtCZgiCakIhQLsFubFz0fXQgAt4uHXerfYKixFAsBh@WNksy4VDCyxxxjSTju5eDVbYCFDfsW5R4He23/uZ1zX7tVfHkjQf2aVU0L0Z2MrHXLkIK2xYbaBk2kjxuZTzcosLkhrK4EzZX5rvTM49jwsNGeYiWG5yIa3pMUC@GgoUQbB6HeLDCPZ2Q7gAJHLk6nxlCoV1zk00HEUAB3@mj/9Dx7GtPG6i5175Th5TPFbldrYffwA "C (gcc) – Try It Online")**
In ungolfed assembly language mnemonics:
```
; bool IsHarshadNumber(unsigned value, unsigned base)
;
; Inputs:
; EAX = input value
; ESI = base
; Outputs:
; ZF = 0 if Harshad number; otherwise, ZF = 1
; Clobbers:
; EAX, EDX, ECX
;
IsHarshadNumber:
50 push eax ; preserve input value
31 C9 xor ecx, ecx ; zero-out accumulator
Accumulate: ; <----------------------------------------------------\
99 cdq ; zero-out EDX (based on EAX) to prepare for division |
F7 F6 div esi ; divide by base (EAX = quotient; EDX = remainder) |
01 D1 add ecx, edx ; accumulate remainder |
85 C0 test eax, eax ; is quotient 0? |
75 F7 jnz Accumulate ; keep looping until it is ----------------------------/
58 pop eax ; restore input value
99 cdq ; zero-out EDX (based on EAX) to prepare for division
F7 F1 div ecx ; divide by accumulator
85 D2 test edx, edx ; set ZF based on remainder
C3 ret
```
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 43 bytes
```
->n,b,s=0,i=n{(s+=n%b;n/=b)while n>0;i%s<1}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ0mn2NZAJ9M2r1qjWNs2TzXJOk/fNkmzPCMzJ1Uhz87AOlO12Maw9n@BQlq0kbmOoUEsF4hpoWMKYVjCGEZGOoZGsf8B "Ruby – Try It Online")
---
# [Ruby](https://www.ruby-lang.org/), 43 bytes
```
f=->n,b,s=0,i=n{n>0?f[n/b,b,s+n%b,i]:i%s<1}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5PJ0mn2NZAJ9M2rzrPzsA@LTpPPwkkpp2nmqSTGWuVqVpsY1j7v0AhLdrIXMfQIJYLxLTQMYUwLGEMIyMdQ6PY/wA "Ruby – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 41 bytes
```
f=(n,b,s=0,i=n)=>n?f(n/b|0,b,s+n%b,i):i%s
```
[Try it online!](https://tio.run/##bcjdCkAwFADge@@hdnKwreSnxrMYpklnMrny7pNL8V1@S3/2ftjtdqTkxikEoxihRq84WkWgWuoMo1xf/NmEYo0WGhv7MDjybp2y1c3MMFmi4ADReyssPlf/nJQoJEC4AQ "JavaScript (Node.js) – Try It Online")
Returns zero for true, non-zero for false.
] |
[Question]
[
This is a repost of [this](https://codegolf.stackexchange.com/q/54455/66833) challenge, intended to revamp it for looser I/O formats and updated rules
You are to write a program which takes an integer polynomial in \$t\$ as input and outputs the [Laplace transform](https://en.wikipedia.org/wiki/Laplace_transform) of this polynomial. Some definitions and properties:
* The Laplace transform of a given function \$f(t)\$ is
$$\mathcal{L}\{f(t)\} = F(s) = \int\_0^\infty f(t)e^{-st}dt$$
* The Laplace transform of \$f(t) = t^n, \, n = 0, 1, 2, ...\$ is
$$\mathcal{L}\{t^n\} = \frac{n!}{s^{n+1}}$$
* Laplace transforms distribute over addition:
$$\mathcal{L}\{f(t)+g(t)\} = \mathcal{L}\{f(t)\} + \mathcal{L}\{g(t)\}$$
* The Laplace transform of a constant multiplied by a function equals the constant multiplied by the transform:
$$\mathcal{L}\{af(t)\} = a\mathcal{L}\{f(t)\}$$
* An integer polynomial is a polynomial where each term has an integer coefficient, and a non-negative order
An worked example:
$$\begin{align}
\mathcal{L}\{3t^4+2t^2+t-4\} & = \mathcal{L}\{3t^4\}+\mathcal{L}\{2t^2\}+\mathcal{L}\{t\}-\mathcal{L}\{4\} \\
& = 3\mathcal{L}\{t^4\}+2\mathcal{L}\{t^2\}+\mathcal{L}\{t\}-4\mathcal{L}\{1\} \\
& = 3\left(\frac{4!}{s^5}\right)+2\left(\frac{2!}{s^3}\right)+\left(\frac{1!}{s^2}\right)-4\left(\frac{0!}{s}\right) \\
& = \frac{72}{s^5}+\frac{4}{s^3}+\frac{1}{s^2}-\frac{4}{s}
\end{align}$$
---
You may take input in a standard representation of a polynomial. Some examples (for \$3x^4+2x^2+x-4\$ as an example) are:
* A list of coefficients. `[-4, 1, 2, 0, 3]` or `[3, 0, 2, 1, -4]`
* Pairs of coefficients and powers. `[[3, 4], [2, 2], [1, 1], [-4, 0]]` and various different orderings
* A string, using whatever variable you like. `3x^4+2x^2+x-4`
Similarly, as the output will be a polynomial with negative orders, you may output in similar formats, such as (using \$\mathcal{L}\{3x^4+2x^2+x-4\} = \frac{72}{s^5}+\frac4{s^3}+\frac1{s^2}-\frac4s\$):
* A list of coefficients. `[72, 0, 4, 1, -4]` or `[-4, 1, 4, 0, 72]`
* Pairs of coefficients and powers. `[[72, -5], [4, -3], [1, -2], [-4, -1]]` and various different orderings (or the positive versions of the powers)
* A string, using whatever variable you like. `72s^-5+4s^-3+s^-2-4s^-1`
If you have an alternative I/O method you're unsure about, please comment below to ask.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
[Answer]
# [Haskell](https://www.haskell.org/), 25 bytes
```
zipWith(*)$scanl(*)1[1..]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzvyqzIDyzJENDS1OlODkxLwfIMIw21NOL/Z@bmJmnYKtQUJSZV6KgopCmEK1romOoY6RjoGMc@/9fclpOYnrxf93kggIA "Haskell – Try It Online")
Pretty straightforward: Generates the list of factorials `[1,1,2,6,...]` with a `scanl`, then does `zipWith(*)` to multiply each element of the input by the corresponding value.
**32 bytes**
```
foldr(\(i,x)r->x:map((i+1)*)r)[]
```
[Try it online!](https://tio.run/##DckxDoMwDADAva/w0CEpDoKWCQk@EjJEQFqrCViBAfXxNdx6H7995xgldIOENU5ZDYrw0Nn0R5s8K0VFrR86a@skQQc/YrBVWTqwpsEan1jhy92Sp@VazrTscIcASf5jiP69iRmZTw "Haskell – Try It Online")
A pretty folding-based solution. Takes inputs as `(exponent, coefficient)` pairs.
[Answer]
# [convey](http://xn--wxa.land/convey/), 15 bytes
```
v"*<
0+1"
1{*}
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoidlwiKjxcbjArMVwiXG4gMXsqfSIsInYiOjEsImkiOiItNCAxIDIgMCAzIn0=)
[](https://i.stack.imgur.com/NuzrN.gif)
The two left columns copy `"` 1, 2, 3, … into the top `*`. The value in the top right gets multiplied by that every lap, so we get (starting with an extra 1 = 0!) 1!, 2!, 3!, … copied into the bottom `*`. `{` reads the input, multiplies it with the factorials and outputs them `}`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
J’!×
```
Takes input as list of coefficients.
## Explanation
```
J’!×
J | Returns an array of elements from 1 to length of input array
’ | Subtracts 1 from each
! | Factorial each
×| Multiply each item in the original array by the created array
```
[Try it online!](https://tio.run/##y0rNyan8/9/rUcNMxcPT////H61romOoY6RjoGMcCwA "Jelly – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 3 [bytes](https://github.com/abrudz/SBCS)
```
×∘!
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/////D0Rx0zFP@nPWqb8Ki371FX86H1xo/aJj7qmxoc5AwkQzw8g/8bKxgoGCkYKhxab6KQpmCiYAzmGQAA "APL (Dyalog Unicode) – Try It Online")
Takes the liberal I/O to the extreme: takes the polynomial \$ 3x^4 + 2x^2+x-4 \$ as two arguments, the coefficients on the left and the powers on the right in decreasing order and including zero terms, as in `3 0 2 1 ¯4 f 4 3 2 1 0`. Returns the polynomial as a vector of coefficients.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 28 bytes
Input as a list of coefficients
```
$p++;$args|%{$p*$_;$p*=++$i}
```
[Try it online!](https://tio.run/##dVBRT4MwEH7nV1yaToaA2eYSky0ki3Pq0x7UxAdCFmTnJGMU25JpGL8dS5ENs3gP7d316/d9dxnbIxcfmCQVfc/TSMYs9QxQUVQ0s@0pDflGHHoFzS7paqpOz7ZpXFalYVCJQs5DgQI8mPX1r1mhrzriNMtlndSP7tiBoQMjBwYOXFtHEH5lGElcaxBxxzCEMQzgZkQaTGlYXZ0D9KDQ9TLfvSH3hmUjSLWaA7RDSFdXTVclbbsBcxR5IhXk4jg0zDS2eRd5FKGoxyK/WAIufqqq5SEa@Mpjie4jExKI/6JcQcdbAATOw12yJe6TOMVzBtrvm/dhnOQcTcd8bkyYlt/6CayAdBnAvQ2j7YazPF3PWcI4KIK7kG@fcK0I6uyBI6Z/KM5kJ3Ca8X9zyhsBf9Fu97iIgDi@kDxON8Fksthl8rsrRqBZ6Gkrtm2U1Q8 "PowerShell – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytes
```
⊢×!∘⍳∘≢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/x91LTo8XfFRx4xHvZtBZOei/2lAiUe9fY@6mh/1rnnUu@XQeuNHbROBWoKDnIFkiIdn8P80hUPrTXQUDHUUjHQUDHQUjAE "APL (Dyalog Unicode) – Try It Online")
Uses `⎕IO←0` (0-indexing)
Input as a list of coefficients.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 10 bytes
```
#2!#&@@@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9lIUVnNwcFBWe1/QFFmXkm0sq5dmoNyrFpdcHJiXl01V3W1sY5JrU61gY4xkDTSMQKShjqGQFLXRMegtpar9j8A "Wolfram Language (Mathematica) – Try It Online")
Input a list of coefficient/power pairs, including zero coefficients, sorted by power, and output a list of corresponding coefficients.
---
The built-in is longer: **23 bytes**
```
LaplaceTransform[#,t,]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yexICcxOTWkKDGvOC2/KDdaWadEJ1btf0BRZl5JtLKuXZqDcqxaXXByYl5dNZdxSZyJtlFJnJF2ia4JV@1/AA "Wolfram Language (Mathematica) – Try It Online")
Input a polynomial in terms of `t`, and output one in terms of `Null`.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 30 bytes
```
L$`.+
$&$:&*
+`\d+_
$.(*$(_$%'
```
[Try it online!](https://tio.run/##K0otycxLNPz/30clQU@bS0VNxUpNi0s7ISZFO55LRU9DS0UjXkVV/f9/XRMuQy4jLgMuYwA "Retina – Try It Online") I/O is a newline-delimited list of coefficients from lowest to highest degree. Explanation:
```
L$`.+
$&$:&*
```
For each coefficient, append a number of underscores equal to its degree.
```
+`\d+_
$.(*$(_$%'
```
Until no underscores remain, multiply each coefficient by the number of following underscores, deleting one in the process.
[Answer]
# Scala 3, ~~52~~ 48 bytes
```
p=>p.indices.scanLeft(1)(_*_.+(1))zip p map(_*_)
```
[Try it online!](https://scastie.scala-lang.org/cLmqQP3RTNieKga9HVLmeg)
Input and output as a list of integers, from lowest to highest degree.
`p.indices` gives us a range from 0 to `p.size - 1`. Scanning left with multiplication gives the factorial at each index, but since the first element is 0, we need to add 1 (hence `_.+(1)`). Then all the factorials are zipped with the coefficients and multiplied together.
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
p=i=1
while 1:print p*input();p*=i;i+=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8A209aQqzwjMydVwdCqoCgzr0ShQCszr6C0REPTukDLNtM6U9vW8P9/XRMuQy4jLgMuYwA "Python 2 – Try It Online")
Input and output are coefficients, one per line, starting with smallest degree (nearest zero).
Taking in `(coefficient, exponent)` pairs turns out slightly longer.
```
p=1
while 1:x,i=input();print p*x;p*=i+1
```
[Try it online!](https://tio.run/##BcHBCoAgDADQ@75ix7IFTj0lfo7gIGyEkX39ek@/0a4ezLQwvE3OinxMkiJdn7GsWW/pA9XNrK7IxmZ7IvTAhAyBMIAnjBAJ0w8 "Python 2 – Try It Online")
[Answer]
# [Raku](http://raku.org/), 15 bytes
```
*Z*1,|[\*] 1..*
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfK0rLUKcmOkYrVsFQT0/rv7VCcWKlQppGtK6JjqGOkY6BjnGs5n8A "Perl 6 – Try It Online")
`[\*] 1..*` is the infinite sequence of factorials starting with `1!`. An additional `1` (for `0!`) is pasted on to the front, then the whole thing is zipped-with-multiplication (`Z*`) with the sole input sequence `*`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
*Vl
```
[Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=KlZs&input=Wy00LDEsMiwwLDNd)
[Answer]
# [R](https://www.r-project.org/), ~~34~~ ~~28~~ 25 bytes
```
(x=scan())*gamma(seq(!x))
```
[Try it online!](https://tio.run/##K/r/X6PCtjg5MU9DU1MrPTE3N1GjOLVQQ7FCU/O/romCoYKRgoGC8X8A "R – Try It Online")
Pretty straightforward.
R lacks a short-named factorial function, but has `gamma`.
Generates sequence along `x` using [trick from @Giuseppe](https://codegolf.stackexchange.com/a/138046/55372).
[Answer]
# JavaScript (ES6), ~~31~~ 29 bytes
I/O: lists of coefficients, from lowest to highest degree.
```
a=>a.map((v,i)=>v*=p=i?p*i:1)
```
[Try it online!](https://tio.run/##BcFBCoAgEADAr3hUWSWrU7D1kOiwmIZhKhl@32ZualTtG8qnUj5d99gJV9IPFc4bBIFrk1gwbEWGxYhuc6o5Oh3zxT3f1QzMABuBDcCmQ4j@Aw "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = polynomial coefficients
a.map((v, i) => // for each coefficient v at position i in a[]:
v *= // multiply v by:
p = // the updated factorial p, which is:
i ? // if i > 0:
p * i // multiplied by i
: // else:
1 // initialized to 1
) // end of map()
```
[Answer]
# [SageMath](https://www.sagemath.org/), ~~27~~ 23 bytes
Saved 4 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
```
lambda f:f.laplace(x,x)
```
[Try it online!](https://sagecell.sagemath.org/?z=eJzLsY3hyknMTUpJVEizStPLSSzISUxO1ajQqdDk4iooyswr0cjRMNaqiDPRNgKSRtoVuiaamgDb6RBN&lang=sage&interacts=eJyLjgUAARUAuQ==)
Takes a function of \$x\$ as input and returns the Laplace transform as a function of \$x\$.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
IEA×ιΠ⊞Oυ∨κ¹
```
[Try it online!](https://tio.run/##JcG7CoUwDADQX@kYIYKvzdHJ4WIHN3EIVbDotSVN/f04eI47iF2gS9WyvwUGSgI/ijDeMQsUaGb/3xN4NJbDlp2AzemY4s4kgSGjmRhONHXx6VWXpeywxgYrbNdVy@d6AQ "Charcoal – Try It Online") Link is to verbose version of code. I/O is a list of coefficients from lowest to highest degree. Explanation:
```
A Input array
E Map over elements
ι Current element
× Multiplied by
Π Product of
υ Predefined empty list
⊞O After pushing
∨ Logical Or of
κ Current index
¹ Literal 1
I Cast to string
Implicitly print
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εN!*
```
[Try it online.](https://tio.run/##yy9OTMpM/f//3FY/Ra3//6N1TXQMdYx0DHSMYwE)
Or alternatively:
```
ā<!*
```
[Try it online.](https://tio.run/##yy9OTMpM/f//SKONotb//9G6JjqGOkY6BjrGsQA)
Both take a list of coefficients as input.
**Explanation:**
```
ε # Map over each value of the (implicit) input-list
N # Push the 0-based map-index
! # Pop and take it's faculty
* # Multiply it by the current value
# (after the map, the resulting list is output implicitly)
ā # Push a list in the range [1,length] based on the (implicit) input-list
< # Decrease each by 1 to make the range [0,length)
! # Take the faculty of each
* # And multiply it to the values at the same positions in the (implicit) input-list
# (after which the result is output implicitly)
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 10 bytes
A built-in.
```
serlaplace
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmD7vzi1KCexICcxOfV/QVFmXolGmoaxVkWcibYRkDTSrtA10dT8DwA "Pari/GP – Try It Online")
] |
[Question]
[
## Introduction
Your challenge today (inspired by [this challenge](https://codegolf.stackexchange.com/q/124362/56656)) is to write a number of snippets, functions or full programs each that output various ascii emoticons, without reusing characters.
## Challenge
* The list of valid ascii emoticons for this challenge is both [here](https://gist.github.com/Amphibological/becc7e31e3f0777674fdbd9a685db7da) and in the code block at the bottom of this post.
* Each snippet should be on a separate line in your submission.
* You may only use one language for all the snippets.
* Each snippet must either output to stdout or return a string containing the emoticon and an optional trailing new line, and *nothing else*.
* You may not use any character more than once across all snippets, however using a character multiple times in a single snippet is fine.
* You may not use any character not in your language's codepage (or ascii, if your language doesn't use a custom codepage) in any of the snippets. Put another way, you are restricted to only characters that can be encoded in one byte.
* No snippet can take any input.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
* Your score is the number of unique snippets that each print a different ascii emoticon in the text file above.
* Highest score wins!
*Good luck!*
---
Allowed emoticons, space separated:
```
:-) :) :-] :] :-3 :3 :-> :> 8-) 8) :-} :} :o) :c) :^) =] =) :-D :D 8-D 8D x-D xD X-D XD =D =3 B^D :-)) :-( :( :-c :c :-< :< :-[ :[ :-|| >:[ :{ :@ >:( :'-( :'( :'-) :') D-': D:< D: D8 D; D= DX :-O :O :-o :o :-0 8-0 >:O :-* :* ;-) ;) *-) *) ;-] ;] ;^) :-, ;D :-P :P X-P XP x-p xp :-p :p :-b :b d: =p >:P :-/ :/ :-. >:\ >:/ :\ =/ =\ :L =L :S :-| :| :$ :-X :X :-# :# :-& :& O:-) O:) 0:-3 0:3 0:-) 0:) 0;^) >:-) >:) }:-) }:) 3:-) 3:) >;) |;-) |-O :-J #-) %-) %) :-###.. :###.. <:-| ',:-| ',:-l <_< >_>
```
*EDIT: Apologies, there was a Unicode character in one of the emoticons which I missed. I have since deleted the emoticon containing it. I hope it won't cause too much inconvenience.*
[Answer]
# [Lenguage](https://esolangs.org/wiki/Lenguage), 131
I have put all the emoticons I am representing in the format `<emoticon> <byte> <length>` where the program is `<byte>` repeated `<length>`
times.
```
:-) 0 8062834757772801319734094828124956399638898464638002583172449928323170213117820932
:) 1 2892400118827976939438684163170029797380
:-] 2 736490387500841447075516267663006608725303862349670620478812283647578112884440609487323312712386965678607264902605611675427012612
:] 3 264202969342699153645046819327998571303367330111090974890246487724490982787908355751940
:-3 4 8657402899421565866640894175739857184468743778771208393372298092586390046095597770136092676
:3 5 3105690979328168701182830269522101416768856653828
:-> 6 74366524642622405428665075721999126422007787328051598231869446920043450605361049824610086990930509828
:> 7 26677682375393393246302105048632582268435010638972146679812
8-) 8 8062834757772801319734094828124956399638898464638002583172449928323170213117820932
8) 9 2892400118827976939438684163170029797380
:-} a 58350780111110182577346156792191842346790220983533887814420020926317170260174910391653244380390906064837889652367278401208674211826539380018313418995597836292
:} b 20932315791834567081523240053201294833948611487434768542347530871005539691107893137313828947907611434178521119850500
:o) c 3239118979209708736174752985014882031111216334552277195105326435158161594234375948611157455571250214219021418006029673058983092521806556299268
:c) d 47135384800053852612833041130432422958419430281388881777898152870448562232695635591679564906662772946483627525782544884262590480388
:^) e 1438457788087580951319367710279309782666608590130275933163395778517107001730213488515614614316939287805297916050613997699858436
=] f 264202969342699153645046819327998571303367330111090974890246487724490982787908355751940
=) 10 2892400118827976939438684163170029797380
:-D 11 19494738235915607848691977610067738996770809401324758166895184293407870315491767045222586644150487567302660
:D 12 6993394368615125679158619025868739646176627428942714419231588356
8-D 13 19494738235915607848691977610067738996770809401324758166895184293407870315491767045222586644150487567302660
8D 14 6993394368615125679158619025868739646176627428942714419231588356
x-D 15 19494738235915607848691977610067738996770809401324758166895184293407870315491767045222586644150487567302660
xD 16 6993394368615125679158619025868739646176627428942714419231588356
X-D 17 19494738235915607848691977610067738996770809401324758166895184293407870315491767045222586644150487567302660
XD 18 6993394368615125679158619025868739646176627428942714419231588356
=D 19 6993394368615125679158619025868739646176627428942714419231588356
=3 1a 3105690979328168701182830269522101416768856653828
B^D 1b 3477977520889650736889014052879324099230182173920756338825997078602142158679966714563481466490641782098496260504558444186939511707432172833580792152068
:-)) 1c 5487280990934680753018828240506400232950626778227616999140473333355621344480221047070135810437858502018906538135322099716
:-( 1d 1007854344721600164966761853515619549954862308079750322896556241040396276639727620
:( 1e 361550014853497117429835520396253724676
:-c 1f 193066536141020580302164136470251204437686055691792055134797767284510716823978799133444882487675968730852822850628645467043138793111556
:c 20 69259223195372526933127153405918857475749925384641832521628775278048964191953448010235510788
:-< 21 1161976947540975084822891808156236350343871677000806222372960108125678915708766403509532609233289220
:< 22 416838787115521769473470391384884097944297041233939791876
:-[ 23 11507662304700647610554941682234478261332872849213603444981441931993408013819384523239426761131046338728238514103212682428547076
:[ 24 4128171395979674275703856551999977676615114532985796482660101370695171606061068058628
:-|| 25 4490503514653154593994888171790391155410203882196166795024427350741089979748728649713594708726872557302769860059030544234798515347871831399522962560307902130717984058775353233427641373262315637622954685896613847112512731353207673251960307641577181784460210162728903376900
>:[ 26 6326404256268962375341314423857191467014094403422416400818262089647958639442872076631144582027712607626673470721042183428656778636530024452
:{ 27 327067434247415110648800625831270231780447054491168258474180169859461557673560830270528577311056428659039392497668
:@ 28 1707371672025177167763334723112485265179840680894217387507716
>:( 29 554073785562980215465017227247350859805999403077134660534580217077888830965463104478137810948
:'-( 2a 10717345685419298345739898907239062955989543426288201658648697659470455871802103594384430744225253295339799090003181572
:'( 2b 3844659212957764301173255361616590690802154974454843970302450614408994357252
:'-) 2c 85738765483354386765919191257912503647916347410305613269189581275763646974416828755075445953802026362718392720025452548
:') 2d 30757273703662114409386042892932725526417239795638751762419604915271954857988
D-': 2e 193066536141020580302164136470251204437686055691792055134797767284510716823978805646550931167703616753827688239442675846684408073420804
D:< 2f 638803582514482637985938722326699671446185653303063005249221931372282624304643888007010225504954128458626105348
D: 30 6513106048680027648022974865388814030379641269280309252
D8 31 101767282010625432000358982271700219224681894832504836
D; 32 52104848389440221184183798923110512243037130154242473988
D= 33 3334710296924174155787763131079072783554376329871518334980
DX 34 8062834757772801319734094828124956399638895572237883755195510489639007043088023556
:-O 35 167458526334676536652185920425610358671588951972278350803847452800159342788092683232963125354305467608039012907876356
:O 36 60072800202465067205832115025259229538134452493771044576134610843949072388
:-o 37 13267431338842966983371788226620956799431546865783704518985364512972676097928094894007982561650102539906104005323704405147662831001648414716854276
:o 38 4759457577127833947434564846207944091008496681623630261662476839548057726257842008934364673202165121028
:-0 39 16908990037932745833282996436991908563415515192912516393305269712082793058780464394797060
8-0 3a 16908990037932745833282996436991908563415515192912516393305269712082793058780464394797060
>:O 3b 92061298437605180884439533457875826090662949768337659782530130027559915316565778290258379740810961922785987127587463814832979972
:-* 3c 64502678062182410557872758624999651197111187717104020665379599426585361704942567428
:* 3d 23139200950623815515509473305360238379012
;-) 3f 8062834757772801319734094828124956399638898464638002583172449928323170213117820932
;) 40 2892400118827976939438684163170029797380
*-) 41 8062834757772801319734094828124956399638898464638002583172449928323170213117820932
*) 42 2892400118827976939438684163170029797380
;-] 43 736490387500841447075516267663006608725303862349670620478812283647578112884440609487323312712386965678607264902605611675427012612
;] 44 264202969342699153645046819327998571303367330111090974890246487724490982787908355751940
;^) 45 1438457788087580951319367710279309782666608590130275933163395778517107001730213488515614614316939287805297916050613997699858436
:-, 46 4128171395979674275703856551999977676615116013894657322584294363301463149116324315140
;D 47 6993394368615125679158619025868739646176627428942714419231588356
:-P 48 1339668210677412293217487363404882869372711615778226806430779622401274742304741465863705002834443740864312103263010820
:P 49 480582401619720537646656920202073836305075619950168356609076886751592579076
X-P 4a 1339668210677412293217487363404882869372711615778226806430779622401274742304741465863705002834443740864312103263010820
XP 4b 480582401619720537646656920202073836305075619950168356609076886751592579076
x-p 4c 106139450710743735866974305812967654395452374926269636151882916103781408783424759152063860493200820319248832042589635241181302648013187317734834180
xp 4d 38075660617022671579476518769663552728067973452989042093299814716384461810062736071474917385617320968196
:-p 4e 106139450710743735866974305812967654395452374926269636151882916103781408783424759152063860493200820319248832042589635241181302648013187317734834180
:p 4f 38075660617022671579476518769663552728067973452989042093299814716384461810062736071474917385617320968196
:-b 50 24133317017627572537770517058781400554710756961474006891849720910563839602997349891680610310959496091356602856328580683380392349138948
:b 51 8657402899421565866640894175739857184468740673080229065203596909756120523994181001279438852
d: 52 6513106048680027648022974865388814030379641269280309252
=p 53 38075660617022671579476518769663552728067973452989042093299814716384461810062736071474917385617320968196
>:P 54 736490387500841447075516267663006608725303598146701278260241040220479322532526226322067037926487695382287897020699710518663839748
:-/ 55 2113623754741593229160374554623988570426939399114064549163158714010349132347558049349636
:/ 56 758225336750041186812214421270044291203334148
:-. 57 207303614669421359115184191040952449991117919777870383109146320515198064030126482718877866076650545526414792977894485163640282912122988497207300
>:\ 58 50611234050151699002730515390857531736112755227379331206546096717183669115542976613049156656221700861013387765768337467429254229092240195588
>:/ 59 1161976947540975084822891808156236350343871260162019107609415971405328717636882880482535666496831492
:\ 5a 33025371167837394205630852415999821412920916263886371861280810965561372848488544468996
=/ 5b 758225336750041186812214421270044291203334148
=\ 5c 33025371167837394205630852415999821412920916263886371861280810965561372848488544468996
:L 5d 117329687895439584386390849658709432691668852526896571437762911804588036
=L 5e 117329687895439584386390849658709432691668852526896571437762911804588036
:S 5f 246058189629296915275088343143461804188198717414486198583847366016815400484868
:-| 60 7293847513888772822168269599023980293348777622941735976802502615789646282521863798956655547548863258104736206545909800151084276478317422502289177374449729540
:| 61 2616539473979320885190405006650161854243576435929346067793441358875692461388486642164228618488451429272315139981316
:$ 62 88269046595092069685018437596741636
:-X 63 22475902938868452364365120473114215354165767283620319228479378773424625026990985396952005392834074880328590847857837270368260
:X 64 8062834757772801319734094828124956399638895572237883755195510489639007043088023556
:-# 65 30757273703662114409386042892932725523524850710441599209489631379406624653316
:# 66 11033630824386508710627304699592708
:-& 67 15747724136275002577605653961181555468044723563746098795258691266256191822495748
:& 68 5649218982085892459841180006191464452
O:-) 69 12356258313025317139338504734096077084011903131684407032848168143843669217661859524670204261772879079170965450478974953193258440804270084
O:) 6a 4432590284503841723720137817978806878447995224617077284276641736623110647723704835825102487556
0:-3 6b 13267431338842966983371788226620956799431542106326127399808819977829395756624898061251158122488584656200472850638276239892043942732572982687825924
0:3 6c 4759457577127833947434564846207944091008496681623630264768167818876226427440672278456466089971021774852
0:-) 6d 12356258313025317139338504734096077084011903131684407032848168143843669217661859524670204261772879079170965450478974953193258440804270084
0:) 6e 4432590284503841723720137817978806878447995224617077284276641736623110647723704835825102487556
0;^) 6f 17635441167744220073677733420687434891802896487030356826420001439272855399824227332478064740691799715855116951261424132542286393800713533574133832361923633475307938715070413175521284
>:-) 70 12356258313025317139338504734096077084011903131684407032848168143843669217661859524670204261772879079170965450478974953193258440804270084
>:) 71 4432590284503841723720137817978806878447995224617077284276641736623110647723704835825102487556
}:-) 72 12356258313025317139338504734096077084011903131684407032848168143843669217661859524670204261772879079170965450478974953193258440804270084
}:) 73 4432590284503841723720137817978806878447995224617077284276641736623110647723704835825102487556
3:-) 74 12356258313025317139338504734096077084011903131684407032848168143843669217661859524670204261772879079170965450478974953193258440804270084
3:) 75 4432590284503841723720137817978806878447995224617077284276641736623110647723704835825102487556
>;) 76 35460722276030733789761102543830455027583961796936618253966333061189046605718849544410611318788
|;-) 77 98850066504202537114708037872768616672095225053475256206345501846339744503156212400486939296710743380901705521624650127283876034609414148
|-O 78 167458526334676536652185920425610358671588951972278350803847452800159342788092683232963125354305467608039012907876356
:-J 79 5110428660115861103887509778613597371569487059700877404902571191411112755984273780302829753244185412842987454468
#-) 7a 8062834757772801319734094828124956399638898464638002583172449928323170213117820932
%-) 7b 8062834757772801319734094828124956399638898464638002583172449928323170213117820932
%) 7c 2892400118827976939438684163170029797380
:-###.. 7d 63472263633935557923861736647125082748737134197688614613290540778155514115230551308688039019425910919616813001134916326957795000550316350938650788017945200937461476004474628334886705185455259784117223106102133685656049509651941592790179381411044907204635644645761089920625788481467539398532818999535942522921715094779750348520526769510592544772
:###.. 7e 22769557902708180570154032292525047244944529305685155554445656280981063526325050092172056931673139842713852077242156754930562874861800287931116285873505222881198972551491106610897147536510025664107567227744828946111351823651821405717420690800875100093349774665482097539926086501615885057530438321438724
<:-| 7f 11177788790790293702887103501120273414294472080999244458727694432909828650049566346015521682938653081799074785621881328429812576053504382165802153936498504910891056847057744922241561963821608276490675534388264964
',:-| 80 3894890932912594723800954614979778034738167705203999534297740046617805825001409260143039659396608186752825803082434011496463988584644917884342322616438404709718180718461226350290450773715077612074236332176364411401648796852480132979965285722014892425220
',:-l 81 13837432294794619465253598686799485174738918065898472542221995406271893447330289675331867938000869552982499765940481536206846117610229348870882129377116615066676461930445989701931533395349580971164855939208722231376387401455759135799771140
<_< 82 1658428917355370872921473528327619599928942763290765923893927134800978736248000485688913034091267225200427530628638653297304681376663135508758532
>_> 83 106139450710743735866974305812967654395452336850609019129211336627262639119872031084090434181841102412827361960232873811027499608106440672560545796
```
[Answer]
# [Haskell](https://www.haskell.org/), 3
Here is a start at a haskell solution.
## xD
```
"xD"
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKRIQ6nCRUnz/38A "Haskell – Try It Online")
This one is just a normal string it uses the characters `"xD`
## :]
```
':':']':[]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKRIQ90KCGPVraJjNf//BwA "Haskell – Try It Online")
This is a desugared string using cons to construct a list of characters. It uses the emoticon `:]` because both `:` and `]` are already used. In total this uses the characters `':][`.
## 8)
```
drop 8(show(88,8,8,8))
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKRII6Uov0DBQqM4I79cw8JCBww1NTX//wcA "Haskell – Try It Online")
This is where things start to get a little more interesting. Since we need a way to make a string without the characters `"` or `'` we use the `show` function. `show` takes something showable and makes a string out of it. Here we show the tuple `(88,8,8,8)`. This in tuple in particular ends with `8)`, the string we want, so we drop the first `8` chracters from the string using `drop 8`. The unique characters in this solution are `drop 8(shw,)`
---
If we could find some other way to make `Char`s I'd probably be able to make a 4th. `mempty`, could be used instead of `[]` in answer 2, and there are ways of extracting the `,` from answer 3.
[Answer]
# Charcoal, 10
These are just the ones I can do without using Charcoal's `cat`-like ability, which would allow me to add `XP` and `|-0`.
```
%) ←)%
:( ℅⁵⁸℅×±⁵±⁸
:-| :¹↑¹
;] ⮌];
<_< <_‖O
=/ =↗÷χχ
8-0 I⊖⁹¬⁰I⁰
B^D ↓ED^Bι
DX §α³§α²³
xp ↶⁴px
```
[Try them online!](https://tio.run/##S85ILErOT8z5//9R2wRNVa73e5Y86pvF9ail9VHj1keNO4CMw9MPbQRyQMQOmLzVoZ2P2iYe2glXv64n1hrGsYl/1DDt/Z71ML7to7bph7efbz/fDhN5v2flo65pjxp3HlrzqHEDiNe4AW5U2@T3e5a6xDmdg5t@aPm5jYc2g8lNhzYjFG571LiloOL/fwA "Charcoal – Try It Online") I've added `D⎚` commands to separate the snippets which sort of spaces them out, although it's not perfect, as the code should really be all on one line. Explanation:
```
←)%
```
The `←` causes the string literal `)%` to be printed leftwards i.e. reversed.
```
℅⁵⁸℅×±⁵±⁸
```
The character code for `:` is 58. The characer code for `(` is 5 times 8. (They are both negated here in case I needed a separator later.)
```
:¹↑¹
```
The `:` is a literal. The `¹` prints a line of length 1 horizontally, which is just a `-`. The `↓` causes the second line to be printed vertically, which gives the `|`.
```
⮌];
```
The `⮌` reverses the string literal `];`.
```
<_‖O
```
The `<_` is a string literal and the `‖O` causes the `<` to be reflected to the other side of the `_`.
```
=↗÷χχ
```
The `=` is a string literal and the `↗÷χχ` draws a line of length 10/10 i.e. 1 diagonally, i.e. `/`.
```
I⊖⁹¬⁰I⁰
```
The numbers `9-1` and `0` are cast to string and so print as digits, while the `0` in the middle is logically negated turning it into `1` which is another way of printing a `-`. (And I haven't even used it as a literal yet!)
```
↓ED^Bι
```
This takes the string literal `D^B` and converts it into an array, which would normally print vertically, however the print direction is overriden to vertical which results in... reversed output again!
```
§α³§α²³
```
This looks up the characters at positions 3 and 23 in the upper case alphabet (0-indexed).
```
↶⁴px
```
The `↶⁴` rotates the print direction through 180° thus causing the string literal `px` to be printed reversed yet again.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6
+1 to come?? dylnan suggested the use of `ṭ` to free up `Ȯ`, but can it be used?
Six full programs:
;] [`“;]`](https://tio.run/##y0rNyan8//9Rwxzr2P//AQ "Jelly – Try It Online")
xp [`⁾xp`](https://tio.run/##y0rNyan8//9R476Kgv//AQ "Jelly – Try It Online")
;D [`⁽8Ạb⁹Ọ`](https://tio.run/##y0rNyan8//9R416Lh7sWJD1q3Plwd8///wA "Jelly – Try It Online")
:0 [`”:®ṭ`](https://tio.run/##y0rNyan8//9Rw1yrQ@se7lz7/z8A "Jelly – Try It Online")
XP [`24,16ịØA`](https://tio.run/##y0rNyan8/9/IRMfQ7OHu7sMzHP//BwA "Jelly – Try It Online")
8-0 [`7‘.NṾṖ⁺`](https://tio.run/##y0rNyan8/9/8UcMMPb@HO/c93DntUeOu//8B "Jelly – Try It Online")
31 distinct bytes used, confirmation [here](https://tio.run/##AUsAtP9qZWxsef//UeKBvCxM////4oCcO13igb54cOKBvTjhuqBi4oG54buM4oCdOsKu4bmtMjQsMTbhu4vDmEE34oCYLk7hub7huZbigbo "Jelly – Try It Online").
[Answer]
# [Ruby](http://www.ruby-lang.org), 7
=\ [Try it online!](https://tio.run/##KypNqvxfbPtf3TYmRv1/QWlJsULxfwA "Ruby – Try It Online") A string literal
```
'=\\'
```
>\_> [Try it online!](https://tio.run/##KypNqvxfbPtfyS7eTul/QWlJsULxfwA "Ruby – Try It Online") Another string literal
```
">_>"
```
:p [Try it online!](https://tio.run/##KypNqvz/v8Cq4P9/AA "Ruby – Try It Online") Prints the `:p` symbol including the syntax (`:`) since it's using the `p` method
```
p:p
```
%) [Try it online!](https://tio.run/##KypNqvxfbPtftVpVs/Z/QWlJsULxfwA "Ruby – Try It Online") Yet another string literal
```
%{%)}
```
XP [Try it online!](https://tio.run/##KypNqvxfbPvfxsaRKyKAy/F/QWlJsULxfwA "Ruby – Try It Online") Here document notation (basically a multiline string literal)
```
<<A
XP
A
```
;] [Try it online!](https://tio.run/##KypNqvxfbPs/2t5axz42Vste939BaUmxQvF/AA "Ruby – Try It Online") Array of 2 characters (`':'` and `']'`) joined with `'-'`
```
[?;,?]]*?-
```
D8 [Try it online!](https://tio.run/##KypNqvxfbPtf38VCX684v7QoOfV/QWlJsULxfwA "Ruby – Try It Online") The source string of a regular expression
```
/D8/.source
```
\_\_
Honorable mention [Try it online!](https://tio.run/##KypNqvxfbPs/ITU5I1/BxSLhf0FpSbFC8X8A "Ruby – Try It Online") Executes the code in bash, returns `emoticon` with a trailing `\n`
```
`echo D8`
```
[Answer]
# Python 2, 4
This answer is a pretty simple start. For the first two we just use python's two different string syntaxes. For the third we use the same method as my Haskell answer where we make a tuple get its string representation and slice it up. For the last part we use the `chr` function to make the characters `:` and `)` and add them together.
## xD
```
"xD"
```
## =\
```
'=\\'
```
## 8)
```
`88,8,8`[8:]
```
## :)
```
chr(11+11+11+11+11+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1+1)
```
[Answer]
# [R](https://www.r-project.org/), 4
```
`!`<-`qu\157\164e`;!B^D
intToUtf8(c(88,80))
">_>"
'=]'
```
[Try it online!](https://tio.run/##K/r/P0ExwUY3obA0xtDUPMbQzCQ1wVrRKc6Fq8JWITOvJCQ/tCTNQiNZw8JCx8JAU5Or0lZByS7eTomrylZB3TZW/X9yYolGhU6lTpWOQnFqga0Sl5LmfwA "R – Try It Online")
A first attempt at an R solution. The need to use brackets for any function call seriously reduces the possibilities. The first snippet is a call to `quote` which [simply returns its argument](https://stat.ethz.ch/R-manual/R-devel/library/base/html/substitute.html) - Thanks @BLT for showing me a way to do it without parenthesis, allowing me to use `intToUtf8` on the following line.
I used another trick that @Giuseppe mentioned in a comment to another question once to spell `quote` without `o` and `t`.
[Answer]
# [Fission](https://github.com/C0deH4cker/Fission), 3
### |;-)
```
R"|;-)";
```
[Try it online!](https://tio.run/##S8ssLs7Mz/v/P0ipxlpXU8n6/38A "Fission – Try It Online")
### XP
```
V!P'!X'L
```
[Try it online!](https://tio.run/##S8ssLs7Mz/v/P0wxQF0xQt3n/38A "Fission – Try It Online")
### :o
```
/t<O/oO
U{\ {
```
[Try it online!](https://tio.run/##S8ssLs7Mz/v/X7/Exl8/358rtDpGofr/fwA "Fission – Try It Online")
There are only 3 ways to output something in Fission, so here we are
[Answer]
## Perl 5, 6
### :-)
```
':-)'
```
### :)
```
v58.41
```
### :-3
```
"\x3a\x2d\x33"
```
### =]
```
<<A;
=]
A
```
### B^D
```
q*B^D*
```
### XP
```
`echo XP`
```
[Try it online](https://tio.run/##K0gtyjH9/784sVJB3UpXU91aAQGUFYAiXCCpMlMLPRNDaxQpiIxSTIVxYkyFUQqQNlayhmgy5iooyswrUbCxcUQ1zzaWC4gcwToLtZziXLRQzAQKQHUmpCZn5CtEBCRYQ6UiAv7//5dfUJKZn1f8X9fXVM/A0AAA).
[Answer]
# Javascript, 5
Three trivial ones, then two interesting ones:
# xD
```
"xD"
```
# XP
```
'XP'
```
# <\_<
```
`<_<`
```
# :3
```
[[a=>0?0:0][0]+[]][0][6]+3
```
No characters for string literals left for the fourth one, so we get strings by concatenating with an array. The colon comes from writing a function which uses a colon, then converting it to a string.
# 8)
```
String((function(){(8)})).slice(12,14)
```
This one works very similarly to the fourth one, but uses slightly different methods to do everything.
Thanks to @steve-bennett for suggesting using the `String` constructor and `.slice` as an alternative to concatenating with arrays, and indexing. Managed to squeeze out +1 point from it.
] |
[Question]
[
Given a message, append checksum digits using prime numbers as weights.
---
A checksum digit is used as an error-detection method.
Take, for instance, the error-detection method of the EAN-13 code:
The checksum digit is generated by:
* Multiplying each digit in the message alternating by `1` and `3` (the weights)
* Summing it up
* Calculating the difference between the nearest multiple of 10 (Maximum possible value) and the sum
E.g:
```
1214563 -> 1*1 + 2*3 + 1*1 + 4*3 + 5*1 + 6*3 + 3*1 = 46
50 - 46 = 4
```
Although the EAN-13 code can detect transposition errors (i.e. when two adjacent bits are switched, the checksum will be different) it can't detect an error when two bits with the same weight are swapped.
E.g.: `163` -> checksum digit `8`, `361` -> checkdum digit `8`
Using a prime checksum, with the first weight being the first prime number, the second weight being the second prime number, etc., errors can be detected when *any* two bits are swapped.
Because the primes act as weights, you have an extra factor, *the length of the message `l`*:
1. Multiply each digit in the message by the `n`th prime
(First digit times the first prime, second digit times the second prime, etc.)
2. Sum it up
3. Calculate the sum of each prime up to the `l`th prime multiplied by `9` plus `1` (Maximum possible value)
4. Subtract the second sum by the first sum
E.g.:
```
1214563 -> 1*2 + 2*3 + 1*5 + 4*7 + 5*11 + 6*13 + 3*17 = 225
9*(2+3+5+7+11+13+17) + 1 -> 523
523 - 225 = 298
```
## Rules
* Take a decimal string, leading zeros are prohibited
* Output the checksum digits
* Standard Loopholes apply
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer wins!
## Examples
```
[In]: 213
[Out]: 69
[In]: 89561
[Out]: 132
[In]: 999999
[Out]: 1
[In]: 532608352
[Out]: 534
```
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 26 bytes
```
_9+""Q $P""zip *0\+ fold1+
```
[Try it here!](https://replit.com/@molarmanful/try-sclin)
I didn't like how my old language lin was turning out, so I've spent a bunch of time reworking/re-implementing it in Scala! So far it's very very WIP, but it works.
For testing purposes (use `-i` flag if running locally):
```
[2 1 3].
_9+""Q $P""zip *0\+ fold1+
```
## Explanation
Prettified version:
```
_ 9+ dup $P () zip * 0 \+ fold 1+
```
Assuming input digit list *x*,
* `_ 9+` i.e. `-x + 9`
* `dup $P () zip` truncate infinite list of primes to *x*'s length (more literally, zip *x* to primes but only keep primes)
* `*` (vectorized) multiply
* `0 \+ fold` sum
* `1+` increment
[Answer]
# Mathematica, ~~32~~ 29 bytes
```
(9-#).Prime@Range@Length@#+1&
```
[View it on Wolfram Cloud!](https://www.wolframcloud.com/obj/6f27d57c-e01e-4e28-b159-9baf6219d738)
*-3 bytes thanks to [Roman](https://codegolf.stackexchange.com/users/87058/roman)!*
Accepts input as a list of decimal digits.
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$13\log\_{256}(96)\approx\$ 10.701 bytes
```
}S*-x9tFmC@pL
```
[Try it online!](https://fig.fly.dev/#WyJ9UyoteDl0Rm1DQHBMIiwiWzUsMywyLDYsMCw4LDMsNSwyXSJd)
-1 character thanks to Seggan
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
Thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan) for removing the flag!
```
9ε:ẏǎ*∑›
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiOc61OuG6j8eOKuKIkeKAuiIsIiIsIlsyLDEsM11cbls4LDksNSw2LDFdXG5bOSw5LDksOSw5LDldXG5bNSwzLDIsNiwwLDgsMyw1LDJdIl0=)
**Explanation:**
```
9ε:ẏǎ*∑› # whole program
9ε # absolute of n-9 (vectorized)
:ẏ # push range of the list length
ǎ # and convert into primes
* # multiplication (vectorized)
∑ # sum the result
› # and increment it
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 13 bytes (26 nibbles)
```
+~+!$|,~==,|,$~%@$2~*- 9
```
[Nibbles](http://golfscript.com/nibbles/index.html) has no prime number builtins, so 7.5 bytes (15 nibbles) are used here to construct the infinite list of primes:
```
|,~==,|,$~%@$2 # infinite list of primes:
| # filter
,~ # the infinite list of integers by
| ~ # list of falsy elements of
@ # itself
% $ # modulo
,$ # 1..each integer
, # has a length
== # equal to
2 # two
```
Once this is done, it's another 5.5 bytes (11 nibbles) to subtract each input digit from 9, zip by multiplication with the primes, and add 1 to the sum.
```
!$ # zip the input digits
LOP # with the list of primes (see above)
~ # using the function
- 9 # subtract each digit from 9
* # and multiply by each prime
+ # now get the sum
+~ # and add 1
```
[](https://i.stack.imgur.com/BB5P7.png)
[Answer]
# [J](https://www.jsoftware.com), 16 bytes
```
1+1#.p:@i.@#*9-]
```
Accepts a list of digits.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxwVDbUFmvwMohU89BWctSNxYifNNKkys1OSNfQUMnzcFKSc9BR89ByUpTzU7B0MjQxNTMWMHI0FjBwtLUzFDBEgwUTI2NzAwsjE2NICYsWAChAQ)
```
1+1#.p:@i.@#*9-]
9-] NB. 9 - each item of input
p:@i.@# NB. list of primes, input length(#)->range 0..n-1(i.)->nth prime(p:)
* NB. element-wise multiplication
1#. NB. sum¹
1+ NB. increment
```
See common use 3 for [sum¹](https://code.jsoftware.com/wiki/Vocabulary/numberdot#dyadic).
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rprime`, ~~74~~ ~~60~~ 33 bytes
-27 bytes (!) thanks to [south](https://codegolf.stackexchange.com/users/110888/south)
```
->d{d.zip(Prime).sum{_2.*9-_1}+1}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7KI026WlJWm6FjcVde1SqlP0qjILNAJAcpp6xaW51fFGelqWuvGGtdqGtVCF_tGGRoYmpmbGOkaGxjoWlqZmhjqWYKBjamxkZmBhbGoUq5eamJxRrVCgoKRcDdRtpaBcnRYdb6iXkpmeWVKsV5RallpUnBpbq6QANXbBAggNAA)
In Ruby `Prime` is enumerable so you can `zip` with the prime numbers without calling `Prime.each` or `.take`.
[Answer]
# JavaScript (ES6), 64 bytes
Expects either a string or an array of digit characters.
```
f=(s,i=n=0)=>s[i]?(P=x=>n%x--?P(x):x?0:9-s[i++])(n++)*n+f(s,i):1
```
[Try it online!](https://tio.run/##XcvBDoIgAMbxe0/B3NogIgWEiRv6Ct6bB2fqbA5atMbbk5Zd@K7/33fv3p3rn/PjRYy9DSGMGrrzrI3OkK7cdW5r2GivK3P0hNQN9Kj0dVYqsjaMWwQNxuhk8LjdUElDb42zy3BZ7ARHmFBGcyF5ghAAIE0BU8UhIozuGfyIVLEolJD0b1ZBOYuJ@m43G4mB4ExmBRdsMysQPA8f "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
s, // s = input string
i = // i = pointer in s
n = 0 // n = prime candidate
) => //
s[i] ? // if s[i] is defined:
( P = x => // P is a helper recursive function taking
// x = n - 1 and testing whether n is prime
n % x-- ? // if x does not divide n (decrement x afterwards):
P(x) // do recursive calls until it does
: // else:
x ? // if x is not 0:
0 // n is composite: return 0
: // else:
9 - s[i++] // n is prime: return 9 - s[i] and increment i
)(n++) // initial call to P with x = n, then increment n
* n // multiply the result by n
+ f(s, i) // add the result of a recursive call to f
: // else:
1 // stop the recursion and add 1 to the final result
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
9αā<Ø*O>
```
[Try it online!](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/y3MbjzTaHJ6h5W/3X@d/dLSRjoKhjoJxrI5CtIWOgqWOgqmOghlQDCRgCRZAIJAYUNpYR8EIrMhAR8ECzAUKGsXGAgA "05AB1E – Try It Online")
## Explanation
```
9αā<Ø*O>
9α Get the absolute difference between 9 and each item in the list - call this X
ā Push [1..length(a)] without popping
< Decrement each
Ø Push nth (zero-indexed) prime fore ach
* Multiply each by the corresponding item in X
O Sum
> Increment
```
[Answer]
# [Factor](https://factorcode.org/) + `math.primes math.unicode`, ~~48~~ 47 bytes
```
[ dup length nprimes dup Σ 9 * 1 + -rot v. - ]
```
Takes input as a sequence of integers (digits).
[Try it online!](https://tio.run/##Vc/PCoJAEAbw@z7F17VQUjOyoGt06RKdooPY9Id0tXUVQnya3qdXstE20NnLzvDjm91LGOlUNYf9drdZ4kFKUoycngXJiHIkob7Zmbon/3sh71F6pq75TUpqE3JkirR@sZUaKyEqAa4KLhx4qNGvEaw15oERCwTwMWdXD4XjuYYEvVMPiAE@73A5Y8ppHncusw743kzUojniXGSISV752dJ8qB193hw55t0TWCrVKG1YODVJmCHXYfSwmy8 "Factor – Try It Online")
```
! { 1 2 1 4 5 6 3 }
dup ! { 1 2 1 4 5 6 3 } { 1 2 1 4 5 6 3 }
length ! { 1 2 1 4 5 6 3 } 7
nprimes ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 }
dup ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 } { 2 3 5 7 11 13 17 }
Σ ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 } 58 (sum)
9 ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 } 58 9
* ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 } 522
1 ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 } 522 1
+ ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 } 523
-rot ! 523 { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 }
v. ! 523 225 (dot product)
- ! 298
```
[Answer]
# [Python 2](https://docs.python.org/2/), 122 bytes
```
lambda n:sum(map(lambda x,y:(9-x)*y,map(int,n),[i for i in range(2,len(n)**2)if all(i%m for m in range(2,i))][:len(n)]))+1
```
[Try it online!](https://tio.run/##TcrBDoIwDADQX@nFpB31wG7uVwiHEkGbrIUAJuzrZ1QOXl/eUvbn7LHWLDbcBTxtL0OTBU84uCS8XQ8KhT@svrMTdwrTvIKCOqzijxEj59HRKYRIOoHkjHqx77L/pUR9l363J2raWt8 "Python 2 – Try It Online")
Accepts a string as input (ex: "12345")
Restructures the checksum equation as `sum((9-d)*p)+1`, where `d` is the input as a list of digits and `p` is a list of the first `len(d)` primes.
[Answer]
# [Raku](https://raku.org/), 40 bytes
```
{1+sum (9 X-.comb)Z*grep &is-prime,^∞}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2lC7uDRXQcNSIUJXLzk/N0kzSiu9KLVAQS2zWLegKDM3VSfuUce82v/FiZUKSirxCrZ2CtVpCirxtUoKaflFCjaGRoYmpmbGCkaGxgoWlqZmhgqWYKBgamxkZmBhbGpk9x8A "Perl 6 – Try It Online")
* `grep &is-prime, ^∞` is an infinite, lazy sequence of prime numbers.
* `9 X- .comb` is a list of nine minus each digit in the input number.
* `Z*` zips those sequences together with multiplication.
* `1 + sum ...` adds those products together and adds 1.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 27 bytes
```
a->1+primes(#a)*[9-x|x<-a]~
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWuxN17Qy1C4oyc1OLNZQTNbWiLXUraipsdBNj6yAqbgYmFhTkVGokKujaKQAV5pVopGSmZ5YUayRqKiiBBJUU0hBCmpo6CtFGhsY6ChaWpmaGOgqWYKCjYGpsZGZgYWxqFKsJMXjBAggNAA)
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~99~~ ~~93~~ 75 bytes
-4 bytes thanks to [c--](https://codegolf.stackexchange.com/users/112488/c)
```
i,d;f(*t,*r){for(*r=i=1;*t;*r-=(*t++-57)*i)for(d=2;d>1;)for(d=++i;i%--d;);}
```
[Try it online!](https://tio.run/##VY1NboMwEIX3nGKEROUfLGEINNGInqA3aLNAOEQjUVIZt10grl7XNShVZ@M3fm@@16t@7Kar95QbHJhwubB8GW6WCdtSq1E4FFa1wZFS1Y9cEP91TVuiedK4L1ISUqaUQY6r/7yRgbeOJsaTJYEwNDkB7jK7lzO0sMBzqkt9qJsqzYMu9fYeT3WjozrFibKuyqY4VnUZtgJWjLzQCixAgQKuwA1NZwSSksfE1rt3g73MH6PD@9/A9oscHjaP/5nvNpwMLM3GOdAz8zqF6nv@X3xNVv/dD2N3nb36@gE "C (clang) – Try It Online")
Ungolfed and commented
```
int primecs(char* text)
{
// start then result at one
int result = 1;
// first prime number
int prime = 1;
// loop until we get to the end of the string
while (*text != 0)
{
// calculate the next prime number
int div = 2;
while (div != 1)
{
// set the divisor to the current value of prime
div = prime;
// increment prime;
prime++;
// loop until mod(prime, div) = 0
while (prime % div != 0)
div--;
}
// add the results;
result += (prime * 9) - ((*text - '0') * prime);
// move to next character
text++;
}
return result;
}
```
[Answer]
# Excel, ~~148~~ ~~147~~ 138 bytes
Saved 1 byte thanks to [jdt](https://codegolf.stackexchange.com/questions/253264/prime-number-checksum/253364?noredirect=1#comment563156_253364)
If anybody has a shorter way to get a list of primes in Excel, I would love to have it.
```
=LET(s,SEQUENCE(2^10),t,TRANSPOSE(s+1),n,SEQUENCE(LEN(A1)),SUM((9-MID(A1,n,1))*INDEX(FILTER(s,MMULT(-(IF(s>t,MOD(s,t))=0),s+1)=0),n+1))+1)
```
Excel does not have a built-in for producing a list of the first *n* primes. About 80 bytes of this solution is just generating that list. The 84 byte formula below outputs the primes up to 1024. Change the `2^10` based on how much memory you have available and you can get a longer list.
---
**Here is the part that creates the list of prime numbers:**
```
=LET(s,SEQUENCE(2^10),t,TRANSPOSE(s+1),FILTER(s,MMULT(-(IF(s>t,MOD(s,t))=0),s+1)=0))
```
Let's break down that chonker first. After that, the rest is fairly straightforward. Here's the easy bits:
* `s,SEQUENCE(2^10)` just makes an array from 1 to 1024.
* `t,TRANSPOSE(s+1)` transposes that array and adds 1 to each element.
---
**Now it gets more complicated.**
```
FILTER(s,MMULT(-(IF(s>t,MOD(s,t))=0),s+1)=0)
```
* `IF(s>t,MOD(s,t))` creates a 2D array that's filled with either the result of `MOD(s,t)` or, if `s<=t`, it's just `FALSE`.
* `-(IF(~)=0)` turns that array into a series of `TRUE` or `FALSE`. Note that `FALSE` from the previous step does not equal `0` because it's not considered a number yet. Once we have that T/F table, we use the unary `-` to convert `TRUE` to `-1` and `FALSE` to `0`.
* `MMULT(-(IF(~)=0),s+1)` multiplies that 1/0 matrix with the same values that we see in `t`. I have to [go re-read](https://support.microsoft.com/en-us/office/mmult-function-40593ed7-a3cd-4b6b-b9a3-e4ad3c7245eb) how `MMULT()` works every time I use it so I'm not going to try to explain matrix math here because I'm not good at it. Because [magic], the values at all the prime indices will be 0.
+ Note: The magic isn't perfect so the value `1` is also included in that list because, mathematically, it could be prime. However, we have decided to *define* prime numbers to not include 1. See more [over at math.SE](https://math.stackexchange.com/a/122/222802). We could remove it from this results list but it costs less bytes to just skip over it later.
* `FILTER(s,MMULT(~)=0)` returns all the values from `s` where the corresponding value in the `MMULT()` was `0` since those are the primes (and also 1).
Now we have a neat list of all the prime numbers from 1 to 2^10 or whatever value your memory allows.
OK, if we used `LET()` to rename everything in that `FILTER()` function to just `p` (which costs 4 more bytes than *not* renaming it), then the original function looks like this:
```
=LET(s,SEQUENCE(2^10),t,TRANSPOSE(s+1),p,FILTER(s,MMULT(-(IF(s>t,MOD(s,t))=0),s+1)=0),n,SEQUENCE(LEN(A1)),SUM((9-MID(A1,n,1))*INDEX(p,n+1))+1)
```
---
**When we take out the bits we already know about in the formula above, it looks like this:**
```
=LET(s,~,t,~,p,~,n,SEQUENCE(LEN(A1)),SUM((9-MID(A1,n,1))*INDEX(p,n+1))+1)
```
Here are the last few pieces:
* `n,SEQUENCE(LEN($A1))` creates an array 1 to the length of the input.
* `(9-MID($A1,n,1))` extracts each digit from the input and subtracts it from 9.
* `*INDEX(p,n+1)` multiplies that result by the *n*th term from our prime list (shifted up by 1 to correct for the `1` at the beginning).
* `SUM(~)+1` adds up all those results and adds 1.
---
**Here's the final result:**
[](https://i.stack.imgur.com/U0i95.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11 10~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
9_ḋJÆN$‘
```
A monadic Link that accepts a list of integers and yields the checksum value as an integer.
**[Try it online!](https://tio.run/##y0rNyan8/98y/uGObq/DbX4qjxpm/P//P9pUx1jHSMdMx0DHAsgy1TGKBQA "Jelly – Try It Online")**
### How?
```
9_ḋJÆN$‘ - Link: list of integers, A
9 - nine
_ - subtract A (vectorises) -> Remainders = [9-A1, 9-A2, ...]
$ - last two links as a monad - f(A):
J - range of length (A) -> [1,2,3,4,5,...,length(A)]
ÆN - nth prime -> Primes = [2,3,5,7,11,...,length(A)th-Prime]
ḋ - (Remainders) dot product (Primes) = (9-A1)*2 + (9-A2)*3 + ...
‘ - increment -> checksum
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes
```
≔¹η≔¹ζFS«≦⊕ζW⊙…²ζ¬﹪ζλ≦⊕ζ≧⁺×ζ⁻⁹Iιη»Iη
```
[Try it online!](https://tio.run/##fU5NC4IwGD7rr3iP72BBGUXhSTp1MML6A0OXG8xN3Cwy@u1rZtSt5/Z88pSCdaVhyvvMWllrXFAQJI1/bAjsYjrAvW57d3Kd1DUSAo84yln7ye112fGGa8erqRHdhFQcMNN3LJiuOSajQeFgHOam6pXBgYIiAfBv5@sVshYOj6q3FM6y4Xbs51L3FrcUdsw6lGFsuv@Mj@Gnw7csCEm9Xy2T9XyzXCV@dlUv "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔¹η
```
Start with a checksum of `1`.
```
≔¹ζ
```
Start looking for prime numbers greater than `1`.
```
FS«
```
Loop over the input digits as a string.
```
≦⊕ζ
```
Increment the candidate prime number.
```
W⊙…²ζ¬﹪ζλ
```
While it has a nontrivial proper divisor...
```
≦⊕ζ
```
... increment the candidate prime number.
```
≧⁺×ζ⁻⁹Iιη
```
Account for the contribution of this digit to the checksum.
```
»Iη
```
Output the final checksum.
34 bytes using the newer version of Charcoal on ATO:
```
≔¹ηW‹LυLθ«≦⊕η¿⬤υ﹪ηκ⊞υη»I⊕Σ×υ⁻⁹I⪪θ¹
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6Fjf3OhYXZ6bnaRjqKGRoWnOVZ2TmpCpo-KQWFwOJvPSSDI1STR0FKLNQU1NToZqL0zexAKrNMy-5KDU3Na8kNQViAGdmmoKGY06ORqmOgm9-SmlOvkaGjkI2SGNAaXEGSBikrJYroCgzr0TDObG4BNkQjeDSXI2QzNzUYrABmXmlxRqWOgpgZcEFOZklGoU6CoaaUGC9pDgpuRjqleXRSrplOUqxK02NjcwMLIxNjSDiAA "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation:
```
≔¹η
```
Start looking for prime numbers greater than `1`.
```
W‹LυLθ«
```
Repeat until sufficient prime numbers have been obtained.
```
≦⊕η
```
Increment the candidate prime number.
```
¿⬤υ﹪ηκ
```
If it is not evenly divided by any prime number found so far, ...
```
⊞υη
```
... add the prime number to the predefined empty list.
```
»I⊕Σ×υ⁻⁹I⪪θ¹
```
Calculate the incremented dot product of the list of prime numbers with the digits of the 9's complement of the input number.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 17 bytes
```
hs*Vm-9vdz.fP_Zlz
```
[Try it online!](https://tio.run/##K6gsyfj/P6NYKyxX17IspUovLSA@Kqfq/39DI0MTUzNjAA "Pyth – Try It Online")
### Explanation
```
h add one to
s the sum of
*V the vectorized multiplication of
m-9vdz 9-d where d is each digit of the input
.fP_Zlz the first n primes where n is the length of the input
```
[Answer]
# [Python](https://www.python.org), 116 bytes
Takes input a decimal number as a string, while using a recursive [function](https://codegolf.stackexchange.com/a/152433/110265) to calculate the first `n` primes and the proposed equation of user `GotCubes`.
```
f=lambda n,i=1,p=1:n*[0]and p%i*[i]+f(n-p%i,i+1,p*i*i)
c=lambda s:sum(y*(9-x)for x,y in zip(map(int,s),f(len(s))))+1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY9NCoMwEIX3niKb4iRGMIqigtB7iAurDR3QMfgD2qt046a9U29TbetbfYvvvWEeL7OMt47W9TmN2o3fo86asr3UJSOJmZImUymJ3CtKqpk5ocixcDSQu7FEZxMECuRWddSGdJhaWAQk7sx117NZLgyJ3dFAWxpAGuXApYbmSjDwLY763z7vOu1ybvsqsCWz4ySM1A7JNzuFgR95cRD6dpFajJl-W4QKiHPrt3P88gE)
[Answer]
# [GeoGebra](https://www.geogebra.org/calculator), 73 bytes
```
n={
InputBox(n
l=IterationList(NextPrime(a),a,{2},Length(n)-1
1+Sum(9l-nl
```
Input is comma separated digits in the Input Box
[Try It On GeoGebra!](https://www.geogebra.org/calculator/ksbe2a7p)
] |
[Question]
[
### Backstory
You own a tiny jewellery shop in the suburbs of the city. The suburbs are too much overpopulated, so your shop has a thickness of *only one character* to fit in the busy streets.
Recently, there has been lots of cases of robbery on the neighborhood, and you fear that robbers will also come to get your bounty.
Therefore, you installed surveillance cameras to take care of the shop. But there is one *big* problem: **The cameras do not beep or alarm**.
---
You decide to program the security alarm by yourself. This will complete the contraptions and (hopefully) make your little shop safe and secure.
# Task
* Your surveillance cameras will map your shop like this:
```
WI J E W
```
This is your input, which you can take from STDIN or from the command-line arguments. Each of the letters have different meanings.
+ **W** represents a *wall*. Robbers and intruders cannot pass through them.
+ **E** means *employees*. These are the beings that the cameras recognise. If they see an intruder, they will immediately set off the alarm before the robbers can do anything. (They can see an intruder if there is no *wall*, *jewel*, *intruder* or other *employee* in between) They also tend to stand still.
+ **J** means *jewels*. These are the stuff the robbers and intruders are looking for.
+ **I** means *intruder*. They are most likely robbers. Their goal is to steal (at least one of) the jewels of the shop.
+ Of course, you can create your own legend of the map for the sake of saving code bytes.
* Based on the input, you need to write a program (or function) that does the following:
+ If an *intruder* can freely put their hands on a *jewel* OR an *employee* can see an *intruder*:
- Print a truthy value. ("1", "True", "Alert")
- **To be completely alert, print the ASCII bell character.** (It has an ASCII code of 7. When printed, it plays a *ting* sound on lots of computers and implementations)
* In most implementations, there cannot be a *ting* sound, so be carefull!
* In some cases where the bell *absolutely cannot* be printed, print an exclamation ('!') instead of it. (Printing exclamation marks may be harder to implement in some languages)
+ Else:
- Print a falsey value. ("0", "False", "Quiet")
* The shop *does not wrap around*.
* Welp, your computer runs slow when you run too much bytes. Try to program your code as short as possible. (`code-golf`)
### Example tests
```
STDIN: EXAMPLE STDOUT:
WI J E W 1(BEL)
WIWWJWE W 0
E I J I E 1(BEL)
I W J E 0
I E W E E 1(BEL)
IIIIEIIII 1(BEL)
JJJJEJJWI 0
```
Note: "(BEL)" refers to the bell character, not the string.
### Good luck!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḟ⁶OIA7fỌ
```
A full program which prints an empty string (falsey) if all is well or a bell character if not (a bell character is also truthy).
Input:
```
Wall W
Employee X
Jewel J
Intruder Q
```
**[Try it online!](https://tio.run/##y0rNyan8///hjvmPGrf5ezqapz3c3fP////wQAUFL4UIhXAA "Jelly – Try It Online")**
Or see the [test-suite](https://tio.run/##y0rNyan8///hjvmPGrf5ezqapz3c3fP/UcMcV08gERH4qGFu5cPdWw63P2paE/n/f7ingoKXgqtCOFe4Z3i4VziI5argCRTzVHDlAkoqhIPkgSygDBADWUDgCiK4vIDA1csr3BMA "Jelly – Try It Online") (The footer first translates the characters from the example ones and calls the Link for each line).
### How?
```
ḟ⁶OIA7fỌ - Main Link: list of characters in "W QJX"
⁶ - a space character
ḟ - filter-discard (remove any spaces)
O - to ordinals (e.g. "WXQJ" -> [87,88,81,74])
I - incremental differences (e.g. [87,88,81,74] -> [1,-7,-7])
...possible values are: -14 -13 -7 -6 -1 0 1 6 7 13 14
-7 and 7 indicate an intruder (Q) is next to a jewel (J) or employee (X)
A - absolute values
7 - seven
f - filter keep ([7] if any of the values are 7 else [])
Ọ - cast to characters (bell character in a list or an empty list)
- implicit print
...single-element lists print their element
while empty lists print an empty string
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 17 12 10 bytes
*-5 bytes by not distinguishing between Employees and Jewels*
*-2 bytes using addition, not multiplication, so I get 7 for \a for free*
Empty tiles are `-`, intruders are also `h`umans, jewels are still `J`ewels, the shop employees are `e`, and walls `>` are closing in. In Brachylog a predicate succeeding is the truthy value. So it's either a value as an output (`BEL`) or the unification failed, represented as `false.`.
```
ạ%₉ᵐs+7g~ạ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6Ompoe7Oh91rFBKS8wpTtVTAvJqH26d8P/hroWqj5o6gcxibfP0OiD3//9oJbsMXV0v3VRdOyUdINvOzssOwk7VzQCKZ@imAtlAJbp2IFVgNlAeiMFsIEgFEUC2FxCkennZZSjFAgA "Brachylog – Try It Online")
This is all done so the bytes modulo 9 `ạ%₉ᵐ` map `(empty) => 0, I => 5, J => 2, E => 2, W => 8`. With this, we can sum every subset of consecutive elements `s+` and check if one of them is `7` (`I J`, i.e. `5+0+0+2` or `E I`, i.e. `2+0+0+5`). Because empty tiles map to `0`, they don't change the value, and neither does the order. Also 7 cannot be made by other elements. If one subset matches, return convert 7 to a byte `~gạ`, which is `\a`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
áÇ¥Ä7Ãç
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/211125/52210), so make sure to upvote him as well!
Just like his answer, I use `W`=wall; `J`=jewel; `X`=employee; `Q`=intruder.
Outputs one or multiple BEL characters in a list as truthy value or an empty list as falsey value.
[Try it online](https://tio.run/##yy9OTMpM/f//8MLD7YeWHm4xP9x8ePn//@GBCgpeChEK4QA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/wwsPtx9aerjF/HDz4eX/df5HK4UHKih4KUQohCvpANnh4V7hEHaEQiBQPFAhAsgGKlEIB6kCs4HyQAxmA0EEiACyvYAgwssrPFApFgA).
**Explanation:**
```
á # Only keep the letters of the (implicit) input-string (removes spaces)
Ç # Convert each character to its codepoint integer
¥ # Get the forward difference between each codepoint pair
# (one of: [-14,-13,-7,-6,-1,0,1,6,7,13,14])
Ä # Take the absolute value of each difference
7Ã # Only keep all 7s in the list
ç # And convert those 7s (if any) to an ASCII character with this codepoint
# (after which the resulting list is output implicitly as result)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 52 bytes
Uses `#` instead of for empty spaces and instead of `W` for walls. Output is an empty string as a falsey value and the bell character for truthy inputs.
```
lambda s:any({*'I#'}<{*g,'#'}for g in s.split())*''
```
[Try it online!](https://tio.run/##PY6xCsIwFEVHoV9xIcNLiroIDkXdMiS/oA4VWy3UtiRxkNBvry@W@iAh5@aE3OETnn23m2occZna8nW7l/BF2X1kzMkIGg8xf6yJD3Xv8EDTwW/90DZBKpXTiqZQ@eD5@TkDCEYIK7QArWcELP6oheFbI/SM7AokfUEWeS3Io9M2o@XR1sJQds2yVCZ9nPr8ChTsuMq/28BVapkyxdHgmi7ImmIKRmxOiK4anJxVVZz2I2S89X27RKMiNX0B "Python 3 – Try It Online")
[Answer]
# JavaScript (ES6), ~~33~~ 28 bytes
*Saved 5 bytes thanks to @DomHastings!*
Expects `e` for a jewel, and the characters defined in the challenge for the other items.
The unprintable `BEL` is escaped below.
```
s=>/E *I|I *E/i.test(s)&&'\7'
```
[Try it online!](https://tio.run/##hY6xCsIwEIZHwac4OrRJwaY@QB2EGw7cby71KpXSFBOc@u5pMoigWH/4b/r4/ru3z9Z1j2H2h8leJfRNcM3JIJS0EJRohsqL88rpPC92Rejs5Owo1WhvqlcZE4AAAmdagzFwVGe86P0XxSz8pupPAIGihgA3NXELOM390lD6JPaPJgbT2aQkBkX4RdVhBQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~47~~ \$\cdots\$ ~~27~~ 26 bytes
Saved ~~2~~ ~~3~~ ~~7~~ 8 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!!!
Has unprintable bell character in quotes.
```
$0=/[EJ] *I|I *[EJ]/?"":0
```
[Try it online! (With printable bell)](https://tio.run/##LYxBCsIwEEX3OcUndKEFaXaCoK6ymFxgFtZFxKjBMkhbrKCevU7ADzM85g0/Tvf5/eizjBdUDharHRZZnnk4dQnnKNfU4xYHpNfYR0iauixpCfudK7dtDj4cUdOHUBds9rZd2437V9pW9I8JCPBgw8QcuJAH6Y3gjUpw8UpqdJQ0viwTND4Eph8 "AWK – Try It Online")
If there's possibly danger at hand outputs bell character (truthy) or outputs 0 (falsey) otherwise.
[Answer]
# perl -pl, 26 bytes
```
$_=/I *[EJ]|[EJ] *I/?"^G":0
```
[Try it online!](https://tio.run/##FYkxCoBADAT7e8UiVoJoYyOIVZDkAylErSwE0UMtfbsxt7DLsBPXa2/M8qWrGMVIMr1pUHDVZ/OQtbWZMiAgaFBWFU1EYP8YFFxCk3dy43XyUJogHhJR/s74bOdxWxn3Hw "Perl 5 – Try It Online")
Since it's hard to enter unprintable characters, the bell character is here (and in TIO), represented by the two character combo `^G`. In the real program, this is the character with ASCII code 7 (so, I'm counting it as 1 character).
# How does it work?
All the described cases boil down to an intruder next to either some jewels or an employee. So we use a regexp to detect this case.
# perl -pl, 15 bytes
```
s/E *I|I *E/^G/i
```
[Try it online!](https://tio.run/##FYkxCsAwDAP3vEJzoGTqE0zxC7x18xAITWg69u11FYHEoRt@tz1iFkHWV5GlnEepEaaAQ2DJ1MxtkUD5KSRRwpYn0bAkRtYkZ8Td9Ovjqf2asY32Aw "Perl 5 – Try It Online")
Here, "truthy" is taken to "contains a BEL character", and "falsey" as "does not contain a BEL character". And it uses @Dom Hastings suggestion of using `e` as the symbol for jewels.
# perl -F/[EJ]\s\*I|I\s\*[EJ]/ -pl, 13 bytes
```
$_=@F>1?"^G":0
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tbBzc7QXinOXcnK4P//cE8FBS8FV4VwrnDP8HCvcBDLVcETKOap4MoFlFQIB8kDWUAZIAaygMAVRHB5AYGrl1e457/8gpLM/Lzi/7pu@tGuXrExxVqeNZ5AEsTR/69bkAMA "Perl 5 – Try It Online")
We can offload part of the work to a command line switch, and reduce it to 13 bytes.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~26~~ 21 bytes
```
3NST(_-BMPaRMs)?o.'!i
```
[Try it online!](https://tio.run/##K8gs@P/f2C84RCNe18k3IDHIt1jTPl9PXTHz////FhYK5gqGFv91CwA "Pip – Try It Online")
-5 bytes after Dominic Van Essen's input changes.
Takes inputs as:
```
8 → Wall
4 → intruder
7 → Jewel
1 → Employee
```
Takes the differences, converts to string, checks if there's 3 in the string representation.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
*\lf&/TN@GTc
```
[Try it online!](https://tio.run/##K6gsyfjvFqgX@F8rhj0nTU0/xM/BPST5/391dS51BSVl5SzlVGUFMFtBIUsBwk5VVgKKKymnAtlAJcoKIFVgNlAeiMFsIEgFEUB2FhCkZmUpKKn/yy8oyczPK/6vmwIA "Pyth – Try It Online")
### Legend
* `j` - jewel
* `e` - employees
* `"` - intruder
* - wall
* `#` - empty
## Explanation
```
*\!lf&/TN@GTc
f # filter
c # input split on whitespace chars
# with lambda T:
@GT # some lowercase alphabet in T
&/TN # and '"' in T
*\!l # output '!' repeated length of results of filter times
```
[Answer]
# [R](https://www.r-project.org/), 74 bytes
```
function(x)`if`(grepl('IE|EI|IJ|JI',gsub(' ', '',x)),intToUtf8(c(49,7)),0)
```
[Try it online!](https://tio.run/##Tcy9CsJQDAXg3afIlly4g4OgDo4ZklnJWiy2FuTe0h/o0HevqWDpgWT4yEm39O/cwm2pxlQOTU40haKpCqq7V/shFJ5ZZtFZBWPdj09CwAiIcQohNmm458dQXaik0zWenY7h95HQBECBwTAc/mKmthcG8RsB3sRLYGtvJ97w2YmH17WJeljVXJYv "R – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 97 bytes
```
i;j;r;t;f(char*s){for(i=j=r=0;t=*s++;t==87?i=j=0:0)i|=t==73,j|=t==74|t==69,r|=i&j;r&&putchar(7);}
```
[Try it online (with exclamation point instead of bell since TIO can't handle it)](https://tio.run/##lU/LCsIwELz7FWsPNdGKKYqvEDzlkPxADtVDKVRTsEpaT22/vW4QxYtgB7IbJjs7k2x@zrK@t7zgjtc8J9klddOKNvnNESsK4QTjtZhWsxk2sd0cPMn2jNpWILFZRsXrsmqxrneRa4UNcVsY3h@130Ym4wnlXW/LGq6pLQmFZgSQk8AoAA0STEA5LBYxsneHY/iUxKdjOf/gWOLIW2SMNh8R@xJBwn6pJCi0UiCHWGE8MD7hICvlf4RnmBVC@jJEpBFSa6P@zdf1Tw "C (gcc) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
×!⊙⪪EIIEIJJI²№⁻θ ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCMkMze1WENJUUlHwTGvUiO4ICezREPJ1dPT1dPLyxMoaqSpo@CcXwpU6puZV1qsUaijoKSgBBTM1AQC6///wz0VFLwUXBXCuf7rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs `!` since BEL isn't in Charcoal's code page. Explanation:
```
EIIEIJJI Literal string `EIIEIJJI`
⪪ ² Split into 2-character substrings
⊙ Any substring satisfies
№ (non-zero) Count of
ι Current substring in
θ Input string
⁻ With spaces deleted
×! `!` if the above is true
Implicitly print
```
] |
[Question]
[
**This question already has answers here**:
[Make a list flat](/questions/248245/make-a-list-flat)
(22 answers)
Closed 1 year ago.
Given a list with lists nested inside it, return the list with the nested lists' items de-nested.
# Input
The list will have, at most, 4-deep nested lists. Count all 0's within the input as a null space.
# Output
Individually print out each item. Do not print out the output as a list. You can seperate each item with any kind of whitespace.
## Example Cases
`[[1, 0], [2, 0], [2, 3]] -> 1 2 2 3`
`[[[4, 5, 8]], [[5, 6, 20]], [[1, 20, 500]]] -> 4 5 8 5 6 20 1 20 500`
`[[[1, 0], [0, 0], [0, 0]], [[1, 0], [1, 2], [2, 0]], [[2, 0], [0, 0], [0, 0]]] -> 1 1 1 2 2 2`
The shortest code wins.
[Answer]
## APL (10)
```
0~⍨⍎⍞~'[]'
```
Explanation:
* `⍞~'[]'`: User input (`⍞`) without (`~`) the characters `'[]'`
This gives something like `'1,2,0,2,3'`
* `⍎`: Evaluate this string. It so happens that `,` is the concatenation operator, so now we have a list: `1 2 0 2 3` (APL lists are whitespace-separated by default)
* `0~⍨`: Remove all the numbers 0 from this list. (It is a list of numbers, not of strings, by now, so zeroes within numbers are not removed.
* This value is output (by default, because it's the value of the whole program, kind of like Golfscript). APL lists are whitespace-separated by default so it looks exactly like in the question.
[Answer]
## Sed, 20 chars
Solution is based on POSIX Extended Regular Expression.
```
s;[^0-9]+0|[],[]+;;g
```
**Output**:
```
bash-3.2$ sed -rf sedFile <<< "[[[4, 5, 8]], [[5, 6, 20]], [[1, 20, 500]]]"
4 5 8 5 6 20 1 20 500
```
**Edit**:
POSIX Basic Regular Expression([@clueless](https://codegolf.stackexchange.com/users/2360/clueless)'s solution), **19 chars**:
```
s/[^0-9][^1-9]*/ /g
```
[Answer]
## Python, 45
w00, exception handling in golf!
```
def d(x):
try:map(d,x)
except:print`x`*(x!=0)
```
[Answer]
## Perl, 20 16 13 chars
```
perl -ple 's/\D+0?/ /g'
```
The `-l` switch is necessary to preserve the final newline in the output.
Here's an alternate version that actually works with the lists semantically (51 chars).
```
perl -E '$,=$";sub p{map{ref$_?p(@$_):$_||""}@_}say p eval<>'
```
Both of these programs take advantage of the problem's stipulation that it "can separate each item with any kind of whitespace", and replaces the zeros with blanks, instead of removing them outright.
[Answer]
# K, 12
```
{x@?&x:,//x}
```
.
```
k){x@?&x:,//x}((1;0);(2;0);(2;3))
1 2 2 3
k){x@?&x:,//x}(((4;5;8));((5;6;20));((1;20;500)))
4 5 8 5 6 20 1 20 500
k){x@?&x:,//x}(((1;0);(0;0);(0;0));((1;0);(1;2);(2;0));((2;0);(0;0);(0;0)))
1 1 1 2 2 2
```
[Answer]
**Perl 13, 14 char** dit: `p` count for one char
```
s/\D+|\b0/ /g
```
**usage:**
```
cat '[[1, 0], [2, 0], [2, 3]]' | perl -pe 's/\D+|\b0/ /g'
```
[Answer]
## Ruby, 38 characters
```
puts eval(gets).flatten.reject &:zero?
```
The numbers are printed separated by a line break.
[Answer]
### Golfscript 15
```
~{[]*}4*{},' '*
```
**Input**
Run from the command line, like so:
```
echo [[[1 0] [0 0] [0 0]] [[1 0] [1 2] [2 0]] [[2 0] [0 0] [0 0]]] | ruby golfscript.rb x.gs
```
(assumung that the `x.gs` file contains the code presented above).
*Note that there are no commas (`,`) when defining the arrays; that's Golfscript syntax*
**Output**
When the command described in the *Input* section is issued, the output is:
```
1 1 1 2 2 2
```
[Answer]
# Python 3, 49 chars
```
import re
print(*re.findall('[1-9]\d*',input()))
```
# Python 2, 58 chars
```
import re
print re.sub('\D[^1-9]*',' ',raw_input())[1:-1]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 5 bytes
```
c f ¸
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=YyBmILg=&input=W1tbMSwgMF0sIFswLCAwXSwgWzAsIDBdXSwgW1sxLCAwXSwgWzEsIDJdLCBbMiwgMF1dLCBbWzIsIDBdLCBbMCwgMF0sIFswLCAwXV1d)
---
## Explanation
Implicit input of array `U`. Flatten the array with `c`. Filter it with `f` to remove the `0`s. Join it to a string using spaces with `¸`. Implicit output of resulting string.
[Answer]
# Java 10, 106 bytes
```
void c(Object i){for(var o:(Object[])i)try{System.out.print((int)o>0?o+" ":"");}catch(Exception e){c(o);}}
```
Input as nested `Object[]`, output printed to STDOUT.
[Try it online.](https://tio.run/##rZAxT8MwEIX3/opTJluYyg0EoVaCiRExdKw6uK4Bh9SOkmugsvzbw5WWIWkUMbBYunfP9767XDXqOt9@tLpQdQ3PyrowAahRodXQNt5uQbOXTW40guXh1VesURX4@VlcrbnlWB3C8lCj2U39HqdlZR0yRg/3D/LRXyWQzJOEL6JWqN/Z05c2JVrvwPCgmadGbAHK/aag0HP2T/SOeNgSad7bag2KH9mIx5lP@I0PnWImZBQdJR1QbmLki@OoPnTh2KkxltEpbkUm7mMvoVNk4k6kctQyI4PIJJn@jevyEHJQGcfq/yDQgfOOzUj/ynHaPE5i@w0)
---
**46 bytes**
```
s->s.replaceAll("[^0-9 ]","").replace(" 0","")
```
Input and output both as `String`.
[Try it online.](https://tio.run/##jU7LasMwELz7KwadbJCN4j5oCSn0A5pLjkIF1XGLEkUxlhIoxd/urlS77aGUXHZnd5jHTp91udvux8Zq7/GkjfvIAONC27/qpsU6nsAm9Ma9ockn4Isl/YeMhg86mAZrOKww@vLBV33bWRI/Wpsz@SzKeyjGGStmImcQ6TEuo0N3erHkMBmdj2aLAxWZsqSCLlKLzbsP7aE6nkLVEROsy13VUIRccAjFIeuffaUUK1LLf3TymuOG405FkSR0y1GLr2sRIdGC7kus5g7i956d0ic6frdMTP2nZk4bsmH8BA)
[Answer]
## C, 45 chars
```
for(;s=strtok(s,"[], ");s=0)atoi(s)&&puts(s);
```
It assumes that the input is given in a modifiable memory area pointed by `s`.
[Answer]
## Python, 99 111 chars
```
def d(l):
if list==type(l):return[y for x in l for y in d(x)]
return[str(l)]*(l!=0)
print" ".join(d(input()))
```
Previous 99 char version - fails when lists with zeros only are included:
```
d=lambda l:list==type(l)and[y for x in l for y in d(x)]or[str(l)]*(l!=0)
print" ".join(d(input()))
```
`d(l)` recursively flattens the list `l`, while filtering zeros and converting numbers to strings.
[Answer]
### Scala, 42 chars
Tokenized the string by non digits and non-digit followed by zero.
```
print(readLine split"\\D|\\b0"mkString" ")
```
[Answer]
## Prolog (79)
It inputs the list as a term, so you need to put a '.' after the list in the input.
Actually does list flattening.
```
x([H|T]):-x(H),x(T).
x(0). x([]).
x(M):-write(M),put(32).
:-read(X),x(X),halt.
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 4 bytes
```
0~⍨∊
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3yU1L7W45FHbBIO6R70rHnV0wYQUHvVN9Qr291NQj4421FEwiNVRiDZC0MaxsepcmCqjTXQUTHUULGJByqKBLDMdBSMDCM8QxARKGwD52DXD7DFApmF6wSIgM@AuAcsYYdUTqw4A "APL (Dyalog Unicode) – Try It Online")
`0~⍨` zeros removed from
`∊` the **ϵ**nlisted (flattened) data
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 2 bytes
```
$f
```
[Run and debug it](https://staxlang.xyz/#c=%24f&i=[[1,+0],+[2,+0],+[2,+3]]%0A[[[4,+5,+8]],+[[5,+6,+20]],+[[1,+20,+500]]]%0A[[[1,+0],+[0,+0],+[0,+0]],+[[1,+0],+[1,+2],+[2,+0]],+[[2,+0],+[0,+0],+[0,+0]]]&a=1&m=2)
`$` is flatten. `f` is filter out falsey values and print on separate lines.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `S`, 2 bytes
```
fꜝ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJTIiwiIiwiZuqcnSIsIiIsIltbWzEsIDBdLCBbMCwgMF0sIFswLCAwXV0sIFtbMSwgMF0sIFsxLCAyXSwgWzIsIDBdXSwgW1syLCAwXSwgWzAsIDBdLCBbMCwgMF1dXSJd)
[Answer]
### Scala 147:
Working on real lists, not on strings:
```
def f[A](l:List[_]):List[_]=l match{
case Nil=>l
case(l:List[_])::s=>(f(l):::f(s))
case e::s=>e::f(s)}
def p(l:List[_])=f(l)filter(!=0)mkString " "
```
Now the testdata:
```
val l1 = List (List (1, 0), List (2, 0), List (2, 3))
val l2 = List (List (List (4, 5, 8)), List (List (5, 6, 20)), List (List (1, 20, 500)))
val l3 = List (List (List (1, 0), List (0, 0), List (0, 0)), List (List (1, 0), List (1, 2), List (2, 0)), List (List (2, 0), List (0, 0), List (0, 0)))
val l4 = List (l1, l2, l3)
scala> l4.map(p)
res94: List[String] = List(1 2 2 3, 4 5 8 5 6 20 1 20 500, 1 1 1 2 2 2)
scala> p(l4)
res95: String = 1 2 2 3 4 5 8 5 6 20 1 20 500 1 1 1 2 2 2
```
[Answer]
### bash: 29 chars
```
l=$(echo "[[[1, 0], [0, 0], [0, 0]], [[1, 0], [1, 2], [2, 0]], [[2, 0], [0, 0], [0, 0]]]")
echo $l|tr -d '][,'|sed 's/\b0\b/ /g'
1 1 1 2 2 2
```
counting line 2 only withtout 'echo $l |'.
Test for 3 samples:
```
1 2 2 3
4 5 8 5 6 20 1 20 500
1 1 1 2 2 2
```
[Answer]
# [Tcl](http://tcl.tk/), 47 bytes
```
proc D L {concat {*}[concat {*}[concat {*}$L]]}
```
[Try it online!](https://tio.run/##bY47DoAwDEN3TuGBial8ijgAIzdADKgr0ArKFOXsJaUIMbBYjvVsxZslBLdbgx4DyNjNzB5U8Phr82GaOCzr7CKdEZVQDKoerZklowYaHUtCGi0qddtSDLSS42ZSUb2akHgJ@Ey@yx8sdklzXJHInf7A2EP@4nAB "Tcl – Try It Online")
Assuming 4-deep is something like `{{{{5}}}}`. As there is no example of such thing on test cases it may be something like `{{{5}}}`; if it is I can make my code shorter!
# [Tcl](http://tcl.tk/), 66 bytes
```
proc D L {lsearch -al -inl -not "[string map {\{ "" \} ""} $L]" 0}
```
[Try it online!](https://tio.run/##TU5BCoMwELz3FUPoVYi2KX2AR3@gPYRQWiGNQdPTsm9PNyrSy@zM7Oywyfmc4zw5tOhAfnna2b1RWY9qDAJhSlD9kuYxvPCxETQQlMLAgoxz91DQnH1ZScGJqBYNana8MItHVxjcWRwyuKHRK62FwGgRa2Y71AdukaIkuFcezX8xmfGbFvRteYfzDw "Tcl – Try It Online")
[Answer]
# Pyth, 5 bytes
```
jfT.n
```
[**Test suite**](https://pyth.herokuapp.com/?code=jfT.n&test_suite=1&test_suite_input=%5B%5B1%2C+0%5D%2C+%5B2%2C+0%5D%2C+%5B2%2C+3%5D%5D%0A%5B%5B%5B4%2C+5%2C+8%5D%5D%2C+%5B%5B5%2C+6%2C+20%5D%5D%2C+%5B%5B1%2C+20%2C+500%5D%5D%5D%0A%5B%5B%5B1%2C+0%5D%2C+%5B0%2C+0%5D%2C+%5B0%2C+0%5D%5D%2C+%5B%5B1%2C+0%5D%2C+%5B1%2C+2%5D%2C+%5B2%2C+0%5D%5D%2C+%5B%5B2%2C+0%5D%2C+%5B0%2C+0%5D%2C+%5B0%2C+0%5D%5D%5D&debug=0)
[Answer]
# [R](https://www.r-project.org/), 29 bytes
```
function(l)(x=unlist(l))[!!x]
```
[Try it online!](https://tio.run/##K/r/P600L7kkMz9PI0dTo8K2NC8ns7gEyNaMVlSsiP3/HwA "R – Try It Online")
`unlist` converts the list to an `atomic` `vector` recursively, so we just need to filter out the zero elements.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 53 bytes
```
function(x){return(','+x+',').replace(/,(0,)*/g,' ')}
```
[Try it online!](https://tio.run/##bU7NDoIwDL77FLttkwoD0ZgYn2TZgcxBMMtGBhgS47PPDYOayKX92u@nvVX3qpeu7YadsVfl64uvRyOH1hoy0YdTw@gMwYCTKQmVpk51upKKZEAY0G3WAEaYPv15I63prVaptg2pCec5ICYA8eLb90JQ@q/kJaADoJOIMh7QEVDB3lMeYaBZmNfNyx322xfvvIkZn09mplj1xHz/Ag "JavaScript (Node.js) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
ċ∋↰|ℕ₁ẉ⊥
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6kUFCUn1KanFpsxaX0cFen/aO2DY@amh51rHi4YxuQX/tw64T/R7ofdXQDJWoetUx91NQIFH7UtfT//2iF6GhDHQWDWB2FaCMEbRwLYkRHm@gomOooWEB4QJaZjoKRAYRnCGICpQ2AfIhimDkGyDRMLVgEpAduE1jGCKueWIVYAA "Brachylog – Try It Online")
Takes input through the input variable and prints the output separated by newlines. Ordinarily I'd complain about the output format, but it actually saved me a byte in a way I might not have thought to otherwise--putting `ẉ⊥` on the end is shorter than wrapping it in `{}ᶠ`.
```
ċ If the input is a list,
∋ pick some element of it
↰ and recur with it as the input.
| Otherwise, if the input
ℕ₁ is a natural number,
ẉ print it with a trailing newline
⊥ then trigger backtracking.
```
If the list items aren't restricted to being non-negative integers:
# [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes
```
ċ!∋↰|0!⊥|ẉ⊥
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6kUFCUn1KanFpsxaX0cFen/aO2DY@amh51rHi4YxuQX/tw64T/R7oVH3V0A2VqDBQfdS2tAYoDqf//oxWiow11FAxidRSijRC0cSyIER1toqNgqqNgAeEBWWY6CkYGEJ4hiAmUNgDyIYph5hgg0zC1YBGQHrhNYBkjrHpALKW8/BIlHQWlzLyS1PTUomKlWIVYAA "Brachylog – Try It Online")
[Answer]
# [PHP](https://php.net/), 70 bytes
```
function($a){array_walk_recursive($a,function($a){echo$a?"$a ":'';});}
```
[Try it online!](https://tio.run/##bVDbqsIwEHzPVwwloIWIabwg1suH5BQJJaWitCWtiki/vW7q5ShICDub2Z2dTZVX3Wpb5RVjPFt32alIm31ZDLkJb8Y5c91dzPGwczY9uXp/tkSIryKb5iU324AbBMvBIG7DuO1iUmts3dRYQzNA60hAJgJa/cdJQmA8xmiDCIrOpK/UU4GZwMKzWhOaCyj5yCIPiZaUv5unmGFBd06cV5Kef0i9psrP@FLqX7zi21fPqJ89H1ajp13FEtozK501aT7Ec2FTE0KIGznwfwOeeS4UCP6KIGZtdwc "PHP – Try It Online")
This isn't going to be the shortest (nor the longest), but figured it would be a chance to get to use `array_walk_recursive()`, which until today I can't think of ever having a use for it! At least it should be able to handle an arbitrary level deep nested lists.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 37 bytes
```
Flatten/*DeleteCases[0]/*StringRiffle
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@98tJ7GkJDVPX8slNSe1JNU5sTi1ONogVl8ruKQoMy89KDMtLSf1fwCQXeKg5eagUF1tqKNgUKujUG2EoI1ra7mQlVSb6CiY6ihY1ILkq4EsMx0FIwMIzxDEBEobAPloumAmGyDTME1gEZBmuN1gGSOsemr/AwA "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
## Overview
I was playing with Desmos and discovered a really cool spiral:
[](https://i.stack.imgur.com/V2O7i.png)
Doing some research, I discovered that this spiral was the [Archimedian spiral](https://en.wikipedia.org/wiki/Archimedean_spiral). Every point on the spiral is exactly \$\theta\$ away from the origin, where \$\theta\$ is the angle from the origin. That is, any point on the spiral has the polar coordinates \$(\theta, \theta)\$. This also has the consequence that the shortest distance between 2 arms of the spiral is exactly \$2\pi\$ if using radians or \$360\$ if using degrees.
## The Challenge
The basic spiral can be defined by the following formula in the polar coordinate system:
$$
r = a\theta
$$
Where \$a\$ is the multiplier of the distance between the arms. Your job is, given a floating point input for \$a\$, draw this spiral with *at least one* full rotation. You may output the image according to any [image I/O defaults](https://codegolf.meta.stackexchange.com/questions/9093/default-acceptable-image-i-o-methods-for-image-related-challenges).
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins.
[Answer]
# Minecraft Command Blocks, 599 bytes
[](https://i.stack.imgur.com/3B66q.png)
## Commands
Left column (bottom block 0, 4, -2)
```
scoreboard objectives add c dummy
scoreboard players set m c 1
summon armor_stand 0 0 0
setblock 0 3 0 redstone_block
```
Middle column (bottom block 0, 4, 0)
```
execute at @e[type=armor_stand] run setblock ~ ~ ~ stone
tp @e[type=armor_stand] 0 0 0
execute as @e[type=armor_stand] at @s run tp @s ~ ~ ~ ~5 ~
scoreboard players reset d
scoreboard players add m c 1
setblock 0 3 1 air
setblock 0 3 1 redstone_block
```
Right column (bottom block 0, 4, 1)
```
execute as @e[type=armor_stand] at @s run tp @s ^ ^ ^<Input>
scoreboard players add d c 1
setblock 0 3 1 air
setblock 0 3 0 air
execute unless score d c = m c run setblock 0 3 1 redstone_block
execute if score d c = m c run setblock 0 3 0 redstone_block
```
The distance multiplier is set in the first command block in the right column. Hardcoding inputs is not allowed by codegolf rules, but there isn't any other way to take input in Minecraft.
When ran for an hour with an input of 0.1 it produced this. It starts skipping blocks after a little over one rotation but it does complete one full rotation.
[](https://i.stack.imgur.com/cM72b.png)
[Answer]
# [Desmos](https://www.desmos.com), 14 bytes
```
r=\ans_1\theta
```
Well...
[Try it on Desmos!](https://www.desmos.com/calculator/fad9sga6st)
[Answer]
# [GFA-Basic](https://en.wikipedia.org/wiki/GFA_BASIC) 3.51 (Atari ST), 68 bytes
A manually edited listing in .LST format. All lines end with `CR`, including the last one.
```
PRO d(a)
F t=0TO 251
PL 160+t*COS(t/20)*a,100-t*SIN(t/20)*a
N t
RET
```
which expands to:
```
PROCEDURE d(a)
FOR t=0 TO 251
PLOT 160+t*COS(t/20)*a,100-t*SIN(t/20)*a
NEXT t
RETURN
```
NB: We use \$251\$ as the upper bound so that the curve stops on the x-axis rather than at some random position (because \$251/20\approx 4\pi\$).
### Example output
[](https://i.stack.imgur.com/UovXJ.png)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 bytes
```
PolarPlot[y#,{y,0,7}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyA/J7EoICe/JLpSWae6UsdAx7w2Vu1/QFFmXolDWrShQex/AA "Wolfram Language (Mathematica) – Try It Online")
I picked 7 for the plot range because it's a one-digit number that is close to \$2\pi\$ (so we get just around 1 rotation, slightly more).
Example result for input = 1:
[](https://i.stack.imgur.com/Y9qM9.png)
Example when we replace 7 with 50 (makes it more accurate to the image in the original post, but is one byte longer):
[](https://i.stack.imgur.com/mMXvb.png)
[Answer]
# [J](http://jsoftware.com/), 28 bytes
```
plot@(**r.@o.@])(%~8*i.)@1e5
```
[Try it online!](https://tio.run/##y/r/vyAnv8RBQ0urSM8hX88hVlNDtc5CK1NP08Ew1fS/n5Oeglt@kUJSZUmqQnJ@aV5JZl66Qn5eTqWegkKIp79CcmKeeolCQVF@SmlyqkJmbmJ6arHefwA "J – Try It Online")
a=1
[](https://i.stack.imgur.com/UGB8o.png)
a=2
[](https://i.stack.imgur.com/IFmUh.png)
[Answer]
# [R](https://www.r-project.org/), 49 bytes
```
function(a)plot(cos(t<-0:9e3/1e3)*t*a,sin(t)*t*a)
```
[Try it on rdrr.io!](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(a)plot(cos(t%3C-0%3A9e3%2F1e3)*t*a%2Csin(t)*t*a)%0Af(3))
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 50 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
(•math.Sin•Plot○(⊢×↕∘≠)•math.Cos)-2×π×999⥊99÷˜↕100
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=beKGkCjigKJtYXRoLlNpbuKAolBsb3Til4so4oqiw5fihpXiiJjiiaAp4oCibWF0aC5Db3MpLTLDl8+Aw5c5OTnipYo5OcO3y5zihpUxMDA=)
The JS version of BQN has a plotting builtin, which I used for the same rosetta code task. This is just a golf of that.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
9W:9/tJ*Ze*XG
```
Try it at [MATL online!](https://matl.io/?code=9W%3A9%2FtJ%2aZe%2aXG&inputs=&version=22.5.0)
### Explanation
```
9W % Push 9. 2 raised to that. Gives 512
: % Range. Gives [1 2 ... 512]
9/ % Divide each entry by 9
t % Duplicate
J* % Multiply each entry by imaginary unit
Ze % Exponential of each entry
* % Multiply each pair of entries
XG % Plot
```
[Answer]
# Excel & VBA, 144 bytes
```
Cell B1 = SEQUENCE(90)/9*PI()
Cell C1 = B1#*COS(B1#)*A1
Cell D1 = B1#*SIN(B1#)*A1
VBA Immediate Window Set x=activesheet.Shapes.AddChart2(,73,,,,360):x.Chart.SetSourceData Source:=Range("C1:D96")
```
Could cut the `,,,,360` if the plot doesn't have to be square.
[](https://i.stack.imgur.com/QCwQP.png)
[Answer]
# [SageMath](https://www.sagemath.org/), ~~69~~ 68 bytes
```
lambda a,t=var('t'):parametric_plot((a*t*cos(t),a*t*sin(t)),(t,0,9))
```
[Try it online!](https://sagecell.sagemath.org/?z=eJxLs43h5cpJzE1KSVRI1CmxLUss0lAvUde0KkgsSsxNLSnKTI4vyMkv0dBI1CrRSs4v1ijR1AExizPzgExNHY0SHQMdS01NXi5erjQNQ00AIRsXsw==&lang=sage&interacts=eJyLjgUAARUAuQ==)
*Saved a byte thanks to [Seggan](https://codegolf.stackexchange.com/users/107299/seggan)!!!*
[](https://i.stack.imgur.com/X6cOy.png)
### Original graph using 42 instead of 9
[](https://i.stack.imgur.com/SgbFo.png)
[Answer]
## SVG(HTML5) + JavaScript (ES6), ~~77~~ 76 + 96 = 172 bytes
```
f=a=>s.setAttribute("points",[...Array(9e3)].map((_,i)=>[Math.sin(i/=100)*i*a,Math.cos(i)*i*a]))
;f(.1)
```
```
<input value=.1 oninput=f(+value)><br>
<svg viewBox=-4,-4,8,8><polyline id=s fill=none stroke=red stroke-width=.05>
```
Edit: Saved 1 byte thanks to @Kaiido.
[Answer]
# [R](https://www.r-project.org/), 42 bytes\*
```
function(a,x=0:6e3/1e3)plot(a*x*pi*1i^x/2)
```
[Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(a%2Cx%3D0%3A6e3%2F1e3)plot(a*x*pi*1i%5Ex%2F2)%0A%0Af(3))
Calculates the the points of the spiral as the real and imaginary parts of complex numbers, which is conveniently displayed directly as points on the complex plane by the [R](https://www.r-project.org/) `plot` function.
\*The `*pi`...`/2` bit here is to scale the image so that the angle is in *radians* and achieve a distance between arms of exactly `2*pi`. If we use an alternative [unit of angular measurement](https://en.wikipedia.org/wiki/Angle#Units), such as *quadrants*, we could drop this for [37 bytes](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(a%2Cx%3D0%3A6e3%2F1e3)plot(a*x*pi*1i%5Ex%2F2)%0A%0Af(3)): `function(a,x=0:6e3/1e3)plot(a*x*1i^x)`.
Note also that the choice of `1e3` plotted points per quadrant was chosen to allow direct competition with [pajonk's R answer](https://codegolf.stackexchange.com/a/247272/95126); however, `99` plotted points per quadrant also gives a satisfactory output (the points overlap) and [saves another byte](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(a%2Cx%3D0%3A999%2F99)plot(a*x*1i%5Ex)%0A%0Af(3)): `function(a,x=0:999/99)plot(a*x*1i^x)`.
---
# [R](https://www.r-project.org/) + pracma library, 39 bytes
```
function(a)pracma::polar(r<-0:99/9,a*r)
```
[Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(a)pracma%3A%3Apolar(r%3C-0%3A99%2F9%2Ca*r)%0Af(3))
Using a dedicated `polar` function doesn't save much, if anything at all.
[Answer]
## Applesoft BASIC, 73 bytes
```
0GR
1COLOR=7
2INPUTR
3I=0
4PLOTCOS(I)*I*R+20,SIN(I)*I*R+20
5I=I+.1
6GOTO4
```
[](https://i.stack.imgur.com/W84cW.png)
[Answer]
**Clojure, 344 bytes**
```
(defn s[a](doto(JFrame."")(.setPreferredSize(Dimension. 500 500))(.add(doto(proxy[JPanel][](paintComponent[g](.drawPolyline g (into-array Integer/TYPE(map #(+ 250(* a(/ % 20)(Math/cos(Math/toRadians %))))(range 3600)))(into-array Integer/TYPE(map #(- 250(* a(/ % 20)(Math/sin(Math/toRadians %))))(range 3600)))3600))))).pack(.setVisible true)))
```
**Output for `(s 1)`:**
[](https://i.stack.imgur.com/cp0a2.png)
] |
[Question]
[
You are the captain of a world-famous wrestling team. An Olympic-grade match is coming up, and you are determined not to let your team down. You also happen to be a competent programmer, so you are going to write a program to help your team win!
You have access to the strength ratings for each of your own team wrestlers, and each of the opponent wrestlers. A wrestler will win their match only when their strength rating is greater than their opponent's strength rating. You have to write a program that will calculate the optimum pairing for each of your own wrestlers against each of the opponent wrestlers, and then output the maximum number of matches that can be won as a result.
# Input
Your program will take as input three arguments:
1. The number of members per team, there will be an equal number of wrestlers on each team. (Optional)
2. The strength rating of each of your team wrestlers, which is a number between 1 and 10.
3. The strength rating of each of the opponent wrestlers, which is a number between 1 and 10.
# Output
Calculate the optimum pairing for each of your own wrestlers against each of the opponent wrestlers, and then output the maximum number of matches that can be won as a result.
# Test cases
Test case 1:
```
Input:
5
2 4 6 2 6
3 10 6 7 7
Output: 1
```
Test case 2:
```
Input:
10
1 9 5 5 1 6 2 8 3 6
6 10 2 8 2 3 5 6 10 10
Output: 6
```
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~59~~ 57 bytes
*-2 bytes thanks to @dingledooper!*
```
lambda a,b:sum(b.sort()<b<[x]>b.pop(0)for x in sorted(a))
```
[Try it online!](https://tio.run/##jY3RjoIwEEXf@xX3zTYhhKKgEt0393U/QDebdimRCLQZasSvZwfjB2wmmcyde@ZOeMarH/K5OV7mzvS2NjCJrcZ7L206eopSHezhPH1/2DT4IDPVeMKEdsDiuloapebHte0cdCUQ6ckdQ8IxsDgyGO4ckqA3QbZDTEDm8fPepmPo2ihXWKl/EAJu@nUh4vT1eSLyVMGSMzeBQHyHRi4/1VyIHBuUyFGKNXTG4xZboTOhsUfBpV/uDmsmyoVYRM6ywEvq7A8 "Python 2 – Try It Online")
A function that takes 2 lists as arguments, and returns the maximum number of matches that can be won.
### Approach
For each opponent (from weakest to strongest), match that opponent with the weakest available member of my team that can win.
For example, let's say the strength of 2 teams (sorted) are as follow:
```
No. 1 2 3 4 5
Me [2, 2, 4, 5, 8]
Opponent [3, 6, 7, 7, 9]
```
* The 1st opponent has strength 3, so we need to match that with our 3rd team member.
* The 2nd opponent has strength 6, so we match that with our 5th.
We cannot win any more match. So in total we can win at most 2 matches.
### Ungolfed code
```
a,b=map(sorted,input()) # sorted strength of my team and opponent team
s = 0 # number of matches that can be won
for x in a: # loop through my team, in order of increasing strength
if x > b[0]: # if current member can beat the weakest opponent left
s += 1 # then match those two
b.pop(0) # and remove the weakest opponent
# (otherwise, current member is useless)
print s
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/) -zexecstack, ~~124~~ \$\cdots\$ ~~105~~ 103 bytes
Saved a whopping ~~2~~ ~~17~~ ~~19~~ 21 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
#define q(x)qsort(x,i=n,4,L"\x62b078bǃ");
i;j;f(a,b,n)int*a,*b;{q(a)q(b)for(j=0;i--;j+=*a++>b[j]);i=j;}
```
[Try it online!](https://tio.run/##pZDdToNAEIXv@xQTTJPdsiSA9nfFG@OdxgdoiVnoUhd1S4GkaNMrH863EgewLVUvjG6WAHPOnJl8obUIw7I8mctIaQkrUtBVtkxzUjDlaXbGro1ZMXADezgK3l4NyjuKxzwiggVMU6XznmC9gG9WRNAVCWi0TEns2VxZFo9NrydM8yKYxj7lyov5tnx6vsuleMqcqQ8ebFwGZwwGDPBjsOWdnew2ssNgzKBfX2fnGzE4bdzL5CgMq45du4Z4W/pn2qDRmwi3TunX9qrq2NjwKHXWePufFVkkMszlfL9PvaVQmtBNB/CE9yLtQdroyOrKnRXjS3z6BoP2/6mBnVVHkiK2iBg3z1BtN8FSxbWSkB4QVEFhms3xdQ71TrbPwTQVrV3tkK47Bxx0wKp8ejxmpm@TZKmlzrPJ/wcdkO8HVTFrjInIfouWj@1yv611IwpYK41bdefQzWYa49cMUa49b4/d9r82Wj8fbKd/5@v8kq/7X77OL/m2Bh2zdVsetsv8G1unZrst38PoUSyy0nqRhQyzXIQPHw "C (gcc) – Try It Online")
**How**
Sorts the two teams from weakest to strongest. Then goes through our side, starting from weakest, comparing it to the \$j^{\text{th}}\$ member of the opponent's team starting at \$j=0\$, their weakest wrestler. If we are ever stronger than the \$j^{\text{th}}\$ member we increment \$j\$. After we go through all our wrestlers, \$j\$ will be the maximum number we can beat.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Œ!>§Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8///oJEW7Q8sf7mz4//@/kY6JjpmOkY7Zf2MdQwMg01zHHAA "Jelly – Try It Online")
The second test case times out on TIO, but I have verified it locally. Takes your lineup as the left argument and theirs as the right.
```
Œ! Find every permutation of your lineups' strengths,
> compare each matchup for each permutation,
§ sum your wins for each permutation,
Ṁ and return the maximum number of wins.
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 16 bytes
```
(+/⊢≥⍋)0~⍨1⊥<\⍥∧
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X0Nb/1HXokedSx/1dmsa1D3qXWH4qGupTcyj3qWPOpb/T3vUNuFRb9@jruZD640ftU181Dc1OMgZSIZ4eAb/N1MwNFAwUrAAYmMFUwUwF4jSFAwVLIF8UyBtBpY3VjADAA "APL (Dyalog Extended) – Try It Online")
An almost direct port of [Jonah's J answer](https://codegolf.stackexchange.com/a/205087/78410). But unfortunately, I found that, despite having the same name "interval index", J's `I.` and APL's `⍸` don't have the identical behavior; J finds the indices *before* identical elements, but APL does *after* them.
* J: `echo 1 3 5 I. 0 1 2 3 4 5 6` gives `0 0 1 1 2 2 3`
* APL: `⎕←1 3 5 ⍸ 0 1 2 3 4 5 6` gives `0 1 1 2 2 3 3`
That makes `⍸` hard to use for this problem, so I had to fall back to outer product (which is used in the previous version of Jonah's answer).
### How it works
```
(+/⊢≥⍋)0~⍨1⊥<\⍥∧ ⍝ Left: opponent strengths, Right: ours
⍥∧ ⍝ Ascending sort both args
1⊥<\ ⍝ Outer product by < and then sum;
⍝ count the opponents who each of ours can win against
0~⍨ ⍝ Remove zeros
( ⍋) ⍝ Grade up; this is identical to ⍳∘≢ here since the arg is sorted
⊢≥ ⍝ Check if each number is at least its index
+/ ⍝ Sum; count ones
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
Coincidental port of Unrelated String's Jelly answer.
```
œ€‹Oà
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6ORHTWseNez0P7zg//9oIx0THTMdIx2zWK5oYx1DAyDHXMc8FgA "05AB1E – Try It Online")
## Explanation
```
œ All permutations to your team's combination
€‹ Does your team win at this position?
O Sum the resulting lists to get all wins
à Return the largest item of the list
```
[Answer]
# [J](http://jsoftware.com/), 25 22 20 bytes
```
0(]+>)/@|.@,I.&(/:~)
```
[Try it online!](https://tio.run/##LYzBCsIwEETv@YrBg22wpkljUxuoFARB8OTdkxjEiz8g/nqcbGV3WHb3zbzyylQJU0SFBhaR2hocr5dTtvVtc9Dt/DFzczbruo1fnbVSj/vzjYCJchYd9pRHv6zsBIeRe88Z5O85F5ujzRcoYGAl8L8TKizAQMCixHZiC0KOElouXoL/V5V/ "J – Try It Online")
*-3 bytes thanks to Bubbler*
*Thanks to Dominic van Essen for spotting a subtle bug (now fixed)*
---
This could be shorter using brute force, but I wanted to see how short I could make an efficient solution.
Our team = right arg, their team = left arg.
Using 2nd test case an example:
```
6 10 2 8 2 3 5 6 10 10 f 1 9 5 5 1 6 2 8 3 6
```
* `&(/:~)` Sort both arguments:
```
2 2 3 5 6 6 8 10 10 10
1 1 2 3 5 5 6 6 8 9
```
* `I.` Uses [Interval Index](https://code.jsoftware.com/wiki/Vocabulary/icapdot#dyadic) to determine how many of their players each of our players beats:
```
0 0 0 2 3 3 4 4 6 7
```
* `0...|.@,` Prepend a 0 and reverse:
```
2 3 3 4 4 6 7
```
* `(]+>)/` Now reduce from the right as follows: Take the right arg `]` (the running sum, seeded at `0`), compare the two args using `>` (returns 1 if left arg is greater than running sum, 0 otherwise), and add the two.
This means the running sum will increment exactly when "the number of opponents the current wrestler can beat" is greater than "opponents already beaten by other teammates".
The final result will be the total number of players our team can beat.
[Answer]
# [R](https://www.r-project.org/), ~~58~~ 54 bytes
```
function(a,b){for(i in sort(a))F=F+(i>sort(b)[F+1]);F}
```
[Try it online!](https://tio.run/##hY/BDoIwEETvfAXHbphDWwQ0BI/9CeMBCI09AEmtB2P89loqIcaYmD3tzuybXet14/Vt6p2ZJ9aio4eeLTOpmdLrbB1riVSjMmaOse3opDJxplo9/Xh3Qzs2PZPYoYRESbW7DMau4xyCh3mFihLN3m5sBkq2fYEDilAiUvbIv0nlQloUGbQCsRX8DzWP2cW6IUOG@KR28fAKPAiLla8v/IL6Fw "R – Try It Online")
Algorithm based on *Noodle9*'s solution; this could be made shorter than my own original recursive solution [76 bytes](https://tio.run/##hY/BCoMwDIbvPoXHhkVo69SNzb2IeGilnQWtoN1hT9/VTmSMwcglyf/nSzJ7r2v9sJ0zkyUCJRhNBmXvrifimolG3EZjiYQWQJNlmh0R0GSsxZjLmMOBpWpYVEr9@HRKjHVHOB6xRI4lXFyvzLy1c2Q09CusINHk7cbdAMk@z/CMRQgWKSfMv0nlSloVHrQCY8noH2oedxfbBA872CdVxsMrpEFYrXR74RfUvwA "R – Try It Online") or than one based on the elegant algorithm of *Surculose Sputum* [73 bytes](https://tio.run/##hY/PCoMwDMbvPoXHlmXQ1Kkb0h19CfGgYlkPKnQdWMRn7@ofZIzByCXJ9@WXRDspnHz1jVFDTyqoYRTPQRtSUbBbVlM6yUETFao@HKmSRN1tgSWdcpGfMLPCFmcs5yyfXWdNW3WiIRwukACHhGbm0Sq9tyNA5vsppDSQZHPDYaDBMY9wg9gHrpQrRN@kZCEtCvdaDGuJ7A81WnfH@wT3O/CTWq@Hp8C8sFjZ/sIvqHsD "R – Try It Online") in R
[Answer]
# [Io](http://iolanguage.org/), 66 bytes
Algorithm based on Noodle9's solution.
```
method(x,y,F :=0;x sort map(i,F=F+if(i>y sort at(F+1),1,0))last+1)
```
[Try it online!](https://tio.run/##bY67DoMwDEV3vsJjIu6QkBJKKzryFV2QWtRIvAQZ4OupCVQslZwoPs49suvXmm4FPdf27T/9S8xYUDJR95mmfvTUVoNwKIsydrVwj2WnlRdlrCU0lJRNNXlu1lo0bvIiAV0IZEH8shIRUeAGpFXgGZeUNIyu800XRUdQg3IOpqH0z3AFmU1Hp8nupn3ItwmJg2r1R21gkSGF4WORIAcvf2ybQXG//VBhZs/8@gU "Io – Try It Online")
## Explanation
```
method(x, y, // Take 2 arguments.
F := 0 // Initialize the counter to 0.
x sort map(i, // For every item in sorted x:
F = F + if( // Add the counter by:
i>y sort at(F+1), // if the current item is larger than sorted y at the same position
1,0) // converted to an integer
) last + 1) // Add the last item of the map by 1
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes
```
≔I⪪η η≔I⪪ζ ζWΦη›κ⌊ζ«§≔η⌕η⌊ι⁰§≔ζ⌕ζ⌊ζχ»I№η⁰
```
[Try it online!](https://tio.run/##ZY5RC4IwFIWf26@4@DTBwBlK4VME9lIQ9AvEpF2aq9wsWPTb13RSYNvLPTvnuzsVL9vqWgpr10rhWdJNqTQ93gRqyiMIIAjDCHiYk3/ffH3j/CdHUQMtUOi67dltW5f9eIlgjxKbrqEmdAdeZDYu@4VdolNURFCgPI0PA4I94htMKDOlzOQj3@tNDi1K7Yt7YBjvzt/V8qw55X06t5bFhMEKUncZZJDAEhaQkQxYPIjEyRQGyWI7f4gP "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔I⪪η η
```
Input the ratings of your wrestlers.
```
≔I⪪ζ ζ
```
Input the ratings of your opponents.
```
WΦη›κ⌊ζ«
```
Repeat while at least one of your wrestlers can beat one of your opponents.
```
§≔η⌕η⌊ι⁰
```
Set the strength of the weakest such wrestler to 0, so it will no longer be considered.
```
§≔ζ⌕ζ⌊ζχ
```
Similarly set the strength of its opponent to 10, so it will also no longer be considered.
```
»I№η⁰
```
Count and output the number of wins.
If the input was sorted, the calculation could be done in 19 bytes. Unfortunately it takes me 30 bytes to sort the input...
[Answer]
# JavaScript (ES6), 61 bytes
A shorter version inspired by [@SurculoseSputum's answer](https://codegolf.stackexchange.com/a/205082/58563).
```
a=>b=>(g=a=>a.sort((a,b)=>a-b))(a).map(x=>k+=x>g(b)[k],k=0)|k
```
[Try it online!](https://tio.run/##XYvBDoIwEETvfsluXAgFAT1sf4Rw2CIQLVICxHDw32vBm5nLvMm8p7xlaebHtEaju7e@Yy@sDWvoORSJFzevAEIGA0UGEQTjl0ywsbZn3nQPBitbk@UEP9Y3blzc0MaD66GDKqULFZRSUSNUGakkUElljXj6eyq6UR6ijv@Vsp9T7M7OaVhyOlAlwfdf "JavaScript (Node.js) – Try It Online")
That would be [31 bytes](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i7J1i5RLzexQKPC1i5b27bCLik6O1Yn29ZAsyb7f3J@XnF@TqpeTn66RppGtJGOkY6JjpmOWaymRrQxkGEOhIYGsZqaXGgqDXUMgWqNdUyBEKhex0LHEqTHCCoIETI0gCCg/v8A) if the arrays were already sorted in ascending order:
```
a=>b=>a.map(x=>k+=x>b[k],k=0)|k
```
---
# JavaScript (ES6), ~~85~~ 75 bytes
Takes input as two lists of integers `(team, opponents)`.
```
a=>b=>a.map(x=>(b[i=b.sort((a,b)=>b-a).findIndex(y=>x>y)]=a,~i&&++k),k=0)|k
```
[Try it online!](https://tio.run/##XYvLDoIwFET3fghpw6WhIKCLdu83EBa3PEwFWwLEQGL89VpwZ2Z1ZuY88IVzPelxiYxtWtcJh0IqIZE9cSSrkESVWig222khBEFRP0dIWadNczNNu5JNyFVutBIIHx0EYdhT6EVM372rrZnt0LLB3klHygTOkEMCeUVJmQKPPRVQVJSe/p4crpD58ON/gfTn5Luzc@KbDA7ksffdFw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes
```
Max[t=#2;Tr@Boole@Thread[#>t]&/@Permutations@#]&
```
[Try it online!](https://tio.run/##bYyxCoMwFEV3f0NwelATq7aElNC94OAWMoQ2omAMxCcUpN@eJk4dyp3uee9cq3E0VuP01GHg4aHfEnlOWe/F3bnZiH70Rr9kfkNVnERnvN0wvrtlFbkqwrbyncIZGqDQfFiW1vheASkjaqGNqPPTgnKQ2wrpqhTLkkXgCnUMOdwLVD9@k/wEacQ1HJWUf7fCFw "Wolfram Language (Mathematica) – Try It Online")
Unnamed function taking two arguments as input (first our team, then their team), each as comma-separated lists such as `{2,4,6,2,6}`. Brute-force check over all `Permutations` of the input, taking the `Max`. Mathematica doesn't automatically compare lists elementwise, but `Thread[#>t]` forces it to; `Boole` converts `True`s and `False`s to `0`s and `1`s, respectively, so that `Tr` counts the number of wins. Mathematica is bad with currying when it's not programmed into the builtins, so I couldn't see a better way to handle the arguments than `t=#2;`.
[Answer]
# [k4](https://code.kx.com/q/ref/), 27 bytes
```
{{x+y>x}/binr/{x@<x}'(y;x)}
```
Another port of [Jonah's J answer](https://codegolf.stackexchange.com/a/205087/78410), this time to k4.
If the input can be taken as a single list of two vectors, e.g. `(3 10 6 7 7;2 4 6 2 6)` (with the opposing team as the first list item, and our team as the second), the code can be simplified to 22 bytes as:
```
{{x+y>x}/binr/x@'<:'x}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
á Ëí>V xÃn
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4SDL7T5WIHjDbg&input=WzIsIDIsIDQsIDUsIDhdClszLCA2LCA3LCA3LCA5XQ)
[Answer]
# [Scala](https://www.scala-lang.org/), 168 bytes
Golfed version. [Attempt this online!](https://ato.pxeger.com/run?1=dVLBTsJAEI3XfsWczG4caJdKQXBNgHgwwZMxHowxS2mlpmxJdzWYhi_xwkXjxc_wI_Rr3HYLAROb3XbnzZs3Mzt9fVehSIW__swmj1Go4VIkEoq3Jx03ut8f0yiGmIjeIM_Fy-2F1Hc42TEoL55FDkM-aaos19G0X5pqwMXGVoNmnKXTcRRr4tGCKFxSfvYsUhjxYXOaZ4ubWZJG5P50SfslHPJRU2byfL7QL4eHIxPE-bKfxCSkxbAOIYz21RFbRamKQK0abGXr_Tn4AihLnpsmiMgfVA9ssVc6T-TDHe3BtUw0cCgcME-ZMJGLJ80MVDGJfbcp1nYL4RghQDCHYIv6CMyr4I5ZlO6rtf6oMW8byBBOENrVYhvdLoK_qx5YdetpVc52xS1RI2bTue42of9_Qh8D7GAbfbMDbOEJsp3eOugZpOR4lTcw2vu9KCM9TpQm9p6w7tBx3froO3WIpZtx55EIZ1BAKMx4bCaJIBAmFPhZxQVYmIHoVBLzd5UO29LKKXc9zfXafn8B)
```
def f(a:Array[Int],b:Array[Int])={var B=b.sorted;var sA=a.sorted;sA.foldLeft(0){(s,x)=>val C=B.dropWhile(_<x);val c=C.nonEmpty&&C(0)==x;if(c){B=B.drop(1);s+1}else s}-1}
```
Ungolfed version. [Attempt this online!](https://ato.pxeger.com/run?1=dVPNattAEKZXPcWczIqObcmq5cTEAQd6KKSnUHoIoaylVbxBWpnVOiQYPUkvvrS3PEZfok_T0e7aVgyFlXZ3vm--0fzo5-8m4yVP9m_16klkBr5yqWD3a2uK4cXfDyIAyEUBBeNzWGrNX--_KPOAsOpfwznQBgvYER3gmWtoam1EfkO21cidz6AlQbwPefOoqMv8VhSGRSHsgDXbCuElhMW1ZXUSJWhR1c9O3gca5brefF_LUrAfcEUOPXZWq1waWSuiHzxHqlafq415hcHgZFwLnsNiAS_eWxbAjt6hT-_0sefxWRyeGNsKPkLs763fRdmIDrLXdtjBbRAcqv3HFbuiFjCuH5tDje-MluqxK_M3Jft1LkGqzdbEZLJM5t7TEP19gvAJIUWgQ3q0JghxZM0zWmH4Xm1yphZHR8cY4RJhald80L1ASPrqqVN3yMSCU8vtrCTmwo3Hx4DJ_wMmmOIMp5jQk-IELzHu5TbDiCwdJ7JoStrvc2lI-lY2hrk6oc8wGI_9MQm8i6PT9GnBszVNXsapVS6SQuA08r0h3FBDTKkY_Rcd4FJqbTdb18393u3_AA)
```
def f(a: Array[Int], b: Array[Int]): Int = {
var sortedB = b.sorted
var sortedA = a.sorted
sortedA.foldLeft(0) { (sum, x) =>
val removedB = sortedB.dropWhile(_ < x)
val condition = removedB.nonEmpty && removedB.head == x
if (condition) {
sortedB = sortedB.drop(1)
sum + 1
} else sum
} - 1
}
```
But the scala code fails at the case `val input3 = Array(Array(10), Array(3,6,7,5,3,5,6,2,9,1), Array(2,7,0,9,3,6,0,6,2,6))`. Any help would be appreciated.
] |
[Question]
[
Take as input an integer in any reasonable format.
Then, output all the proper sub-strings of the base-10 digits of that integer that are powers of two, in any reasonable format.
# Test cases
```
10230 -> [1, 2]
13248 -> [32, 1, 2, 4, 8]
333 -> []
331 -> [1]
32 -> [2] # As 32 is not a proper sub-string, since it is the whole string.
322 -> [32, 2, 2]
106 -> [1]
302 -> [2]
464 -> [4, 4, 64]
655365536 -> [65536, 65536]
```
[Answer]
# [J](http://jsoftware.com/), 30 bytes
```
(]#~1#.E.~&":"#:)2^[:i.2>.@^.]
```
[Try it online!](https://tio.run/##ZYzNCsIwEITvfYqlBZtIXZJNGmRBCYqexINX217Eol58AH9evUZj9VCWWZZvZvbSpZi3MGPIoQAFHDRBWO42607U2VNnuMLnKOU0Y0nNns9Ic/QN1p1MtgsEJUJoFmLB94V/sL@zEOOxHKV4Q1lVmBwPpytoIJgwtKAVGfVnFqZgesuQnUYrzyMyxkQgCtayZ/rHqGcUEYXp3xmiQVcrN@yqb86GcTZC62yEriyN@@6P8znf6l4 "J – Try It Online")
*-4 bytes thanks to [Neil's approach](https://codegolf.stackexchange.com/a/248131/15469) of generating all the powers of 2 and finding matches.*
* `2^[:i.2>.@^.]` All the powers of 2 less than the input.
* `(1#.E.~&":"#:)` Gets a count of the matches for each.
* `]#~` Uses that as a mask to copy the powers of two. Makes copies of those that occur more than once, and removes those that don't occur at all.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
≈íIK í¬¨ƒÄ*bR
```
[Try it online](https://tio.run/##yy9OTMpM/f//6CRP71OTDq050qCVFPT/v6GBsZGJBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o5MqvU9NOrTmSINWUtD/Wp3/0YYGRsYGOobGRiYWOsbGxkBsqGNsBERGOoYGZjrGBkY6JmYmOmampsZgDBQFqY0FAA).
**Explanation:**
```
Œ # Get all substrings of the (implicit) input
IK # Remove the input itself
í # Filter this list by:
¬ # Push its leading digit (without popping the number)
Ā # Check that it's NOT 0 (0 if 0; 1 otherwise)
* # Multiply that to the number
b # Convert it to binary
R # Reverse it
# (only 1 is truthy in 05AB1E, including "01","001","0001",etc.)
# (after which the filtered result is output implicitly)
```
[Answer]
# Excel, 136 bytes
```
=LET(s,ROW(1:1024),r,s-1,t,TRANSPOSE(s),p,""&2^r,m,IF(t+r>LEN(A1),,MID(A1,s,t)),TEXTJOIN(",",,IFERROR(m*1^MATCH(IF(--m=A1,,m),p,0),"")))
```
Input is in cell A1 and is limited to 308 digits long since 2^1023 = 8.99e+307 and that's the highest value Excel can handle in that series.
---
It's a fairly long formula but `LET()` allows us to break it into chunks of `variable, value` except for the last term which is the output.
* `s,ROW(1:999)` creates a vertical array of values 1-1024.
* `r,s-1` offsets that array by 1. This is a wash on bytes vs. using `s-1` directly later but it does make the formula look nicer.
* `t,TRANSPOSE(s)` creates a horizontal array of values 1-1024.
* `p,""&2^r` creates an array of *string* values from 2^0 to 2^1023. It's important later on that these are strings and not numbers.
* `m,IF(t+r>LEN(A1),,MID(A1,s,t))` creates a triangular array of all the various substrings (and also the entire string but that'll get ignored later). For the input of `13248`, that looks like this:
[](https://i.stack.imgur.com/zKc5r.png)
(This is just the top left corner since most of the 1024x1024 table is `0`.)
---
That's all the variables we define. The last term is the output so we'll break that down bit by bit.
```
TEXTJOIN(",",,IFERROR(m*1^MATCH(IF(--m=A1,,m),p,0),""))
```
* `IF(--m=A1,,m)` let's us ignore the entire input even if it's a power of 2. For instance, `32`. I could have required the input be a string and then drop the `--` here to convert the string `m` to a number, but Excel defaults to things that look like numbers being numbers and it's worth 2 bytes (to me) to not require funky inputs.
* `MATCH(IF(--m=A1,,m),p,0)` tries to find an exact match for the `m` value in the powers of 2 array. If it doesn't find a match, this will equal `#N/A`. This is the part that makes it important for the powers to be strings. If we converted `m` to numbers and matched those, them string like `02` would resolve to be just `2` so they would match. Something line `102` would return `1,2,2` instead of just `1,2`.
* `m*1^MATCH(~)` multiplies `m` by either `1` or `#N/A`.
* `IFERROR(~,"")` converts all the errors to blanks. For the input of `13248`, that looks like this:
[](https://i.stack.imgur.com/ivLrp.png)
* `TEXTJOIN(",",,IFERROR(~))` concatenates all the values with a comma between each term.
---
The screenshot below shows the formula in `B1`, the results for all the test cases, and the snippets showing partial results for input `13248` that are also shown above.
[](https://i.stack.imgur.com/noPQH.png)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 57 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7.125 bytes
```
ǎ$o'E¨²c
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwix44kbydFwqjCsmMiLCIiLCJcIjEzMjQ4XCIiXQ==)
Can't believe I let 05AB1E win for so long smh. Takes input as a string.
## Explained
```
ǎ$o'E¨²c­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌­
ǎ$o' # ‎⁡Keep substrings of the input (excluding the input) where:
¨² # ‎⁢ All the powers of 2
E c # ‎⁣ Contains the substring.
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
≔¹ηW‹ηIθ«E⌕AθIηIη≦⊗η
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DUEchQ9OaqzwjMydVQcMntbhYI0NHwTmxuESjUFNTU6GaizOgKDOvRMM3sUDDLTMvxTEnR6MQqiJDUxPBAprCCVQENdclvzQpJzUFYnrt//9GBkYWRiYGlmYGxmamhmbmBiZGxpYm5kamhkYWZgaGZv91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔¹η
```
Start by checking for embedded `1`s.
```
W‹ηIθ«
```
Repeat until we reach the input number.
```
E⌕AθIηIη
```
Output each copy of the current power of 2 found in the input. (`FindAll` finds overlapping matches, otherwise `65536` would only be found once in `655365536`.)
```
≦⊗η
```
Try the next power of 2.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
DẆṖ×\S$ƇḌḤ’BȦƲƇ
```
[Try it online!](https://tio.run/##y0rNyan8/9/l4a62hzunHZ4eE6xyrP3hjp6HO5Y8apjpdGLZsU3H2v8fbj866eHOGToOWY8a5ijo2ik8apirGfn/v6GBkbGBjoKhsZGJhY6CsbExiDAEEkYgDCQMDcyALAMgy8TMREfBzNTUGIwB "Jelly – Try It Online")
## How it works
We use that fact that, if \$x = 2^n\$ for some \$n \in \mathbb N \cup \{0\}\$, then the binary representation of \$2x-1\$ consists of all \$1\$s. Note that the \$2x\$ is to handle \$x = 1\$.
```
DẆṖ×\S$ƇḌḤ’BȦƲƇ - Main link. Takes n on the left
D - Digits of n
Ẇ - All substrings
·πñ - Remove n
$Ƈ - Keep those with no leading zeros:
√ó\ - Scan by product
S - Resultant sum is zero
Ḍ - Cast to digits
ƲƇ - Keep those that are a power of 2:
·∏§ - Unhalve; Double
’ - Decrement
B - Binary
»¶ - All are non-zero?
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes
```
~s.¬?h¬0&cḃ+1∧
```
Generator solution; takes the full number through its output parameter and yields a power-of-2 substring through its input parameter. Input and output are both lists of digits. [Try it online!](https://tio.run/##ATgAx/9icmFjaHlsb2cy/37ihrDigoHhuoniiqX/fnMuwqw/aMKsMCZj4biDKzHiiKf//1szLDIsMCw0XQ "Brachylog – Try It Online")
### Explanation
```
~s.¬?h¬0&cḃ+1∧
The input parameter (implicit)
~s is a consecutive sublist of
. the output parameter
¬ which is not the same as
? the input parameter
h whose first element
¬0 is not zero
& And, the input parameter
c concatenated together
ḃ converted to binary
+ summed
1 is 1
‚àß Break unification of 1 with the output parameter
```
In other words, find a consecutive sublist of digits that satisfies the following conditions:
* It is not equal to the full list
* It does not start with 0
* When treated as a number and converted to binary, it is a 1 followed by some number of 0s
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 64 bytes
```
(?!^|0)
$'¶
%`\B
¶$`
O#^$`
$.&
1A`
.+
$*
G`^((.+)(?=\2$))*.$
%`.
```
[Try it online!](https://tio.run/##K0otycxL/P9fw14xrsZAk0tF/dA2LtWEGCeuQ9tUErj8leOApIqeGpehYwKXnjaXihaXe0KchoaetqaGvW2MkYqmppaeClCH3v//hsZGJhYA "Retina 0.8.2 – Try It Online") Explanation:
```
(?!^|0)
$'¶
%`\B
¶$`
```
Generate all of the nontrivial substrings of the input integer that do not begin with `0`. (Retina 1 can do this using `Lw`[1-9].*`.)
```
O#^$`
$.&
1A`
```
Delete the longest such substring i.e. the original input. (Retina 1 would use `N` instead of `O#`.)
```
.+
$*
```
Convert to unary. (`$*` would be just `*` in Retina 1.)
```
G`^((.+)(?=\2$))*.$
```
Keep only powers of two. This works by matching half of the unary number each time until you get to the last `1` at the end. (Retina 1 matches differently and requires you add the `m` flag.)
```
%`.
```
Convert to decimal.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~99~~ ~~96~~ ~~83~~ 81 bytes
* -5 thanks to ceilingcat
* -13 thanks to Juan Ignacio Díaz
Takes each power of 2 less than the input number and compares it to slices of the number.
```
j,k,m;f(i){for(m=j=1;j<i;j*=2)for(m*=j<m?:10,k=i;k;k/=10)k%m-j||printf("%d ",j);}
```
[Try it online!](https://tio.run/##TU7LboMwELzzFSuqSDYxrY0JimKcfkjVA4@Q2o4hCqQ9EH69rk2lqocdzWO1O016bhrnNDHEig4pPHfDDVmpJRO6VEInMsOrlUhd2tcDo8RIJYwwL5JRbDY21Y/H9ab6qUPxpoWYaCwW96T65nJvT1COU6uG549jFPkdsJXq0eegWgxzBBCs6u1dzsBoxikBxrN8T4BzHoB5yMJ4YLTwjHqWFzmBYrfj6xCgsBBIahH5g6FrLSsRNNTb7e8bgH8N5dGX9DkWa9KhP3q9TyOK41Ut0eK@m@5SnUeXfv0A "C (gcc) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~124~~ ~~57~~ ~~71~~ ~~58~~ ~~55~~ 50 bytes
With the input `n` an integer:
```
function(n,m=2^{0:log2(n-.1)})m[sapply(m,grepl,n)]
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jTyfX1iiu2sAqJz/dSCNPV89Qs1YzN7o4saAgp1IjVye9KLUgRydPM/Z/moahmYEmV5qGJYgwNoKQJmYg2ijOECxVkAkizUxNjcFY8z8A "R – Try It Online")
Note: Even though `0:n` should work on principle, and thus gain 7 bytes against `0:log(n,2)`, it produces `NA` for most values of `n`...
[Answer]
# Python 3.10.4 - 119 bytes
```
a=input()
for b in range(len(a)):
for c in range(len(a)-b):
n=int(a[c:c+b+1])
if(n&(n-1)==0)and n!=0:
print(n)
```
You type in the number when the program starts, we then iterate over all the possible substrings of that using [this code snippet](https://stackoverflow.com/a/61993428/16886597). Then we finally use [this method](https://stackoverflow.com/a/57025941/16886597) to check if the given substring is a power of two, and if so, print it.
Note: when entering the number, be careful to not have an extra space on the end, as that will cause an error. Here's an example of me running it (on Arch Linux):
```
[me@computer ~]$ python golf.py
13248 <-- We enter that number ourself with the keyboard, the rest is automatically outputted
1
2
4
8
32
```
---
Note to OP:
In some cases (for example 10230), it outputs a number more than once:
```
$ python golf.py
10230
1
2
2
```
I assume that is fine, as it is a power of two, even if listed twice. If it isn't, I can update my answer
[Answer]
# [Factor](https://factorcode.org), ~~79~~ 76 bytes
```
[ all-subseqs 1 head* [ "0"head? ] reject [ dec> 1 - >bin all-eq? ] filter ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RU4xasNAEOz9isFlQEK6k4VJwClDIKQJqYyL83llK5bPp70VTgh5QZ6QRk1S5Ef-Tc5SEdhhh9mZZb5-KmPlyP358_np_vHuGoHajpyl8M9SehU2AQcju9QbDsTY8rHztdsOIvbEjhp4JpE3z7UTtCfcTCbt6R15pnSGXKtiDq11RA6t4qh4KqEzhaIsUM5megA-vjupkvn5YQnTNEno1rFKQI4dmc0Vlphm0wu9xQpML2Qlahuyi2hJsFjXbshRezFUdSOx72r8-XswHkGM3aej0Pfj_gM)
Takes input as a string. -3 bytes from [tip](https://codegolf.stackexchange.com/a/248135/97916) by caird coinheringaahing.
* `all-subseqs` Get every contiguous subsequence of the input.
* `1 head*` Remove the last one (which is the same as the input).
* `[ "0"head? ] reject` Remove the ones that start with zero.
* `[ ... ] filter` Select every subsequence whose...
* `dec> 1 - >bin all-eq?` ...predecessor's binary digits are all the same.
[Answer]
# JavaScript (ES6), 79 bytes
Returns a space-separated string.
```
f=(s,n=1)=>n<s?(g=s=>s&&(s.match('^'+n)?n+' ':'')+g(s.slice(1)))(s)+f(s,n*2):''
```
[Try it online!](https://tio.run/##hdDtaoMwFAbg/7uKg4Mmmak1HxUZs2XXMRw48SPDRfFk3eU7dd2YtdBACOE8vDk579kpw7w3ndue4mEoE4rcJoIlB/uER1olmBxws6EYfGQuryl5Jb5lR@sTII@EML8aS9iYvKCCMUaR@eUU8SDZWB7y1mLbFEHTVrSkngilCj0YF2Ow28GL4CDTu0ulpI7/KyU5TJKD5hCvvFJq1n/@ihBLIdZEnsUvkSncwzOCkmAQbOsgg65vu6IH/HzbouuNrTigsXkBxk3I1QV81WMo/FQDWL8il41MX5NXhxBGN1sOL8LWKTrSS6LnGUZ6JaP9Xs3bO8v5MtLpSIdv "JavaScript (V8) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
f!-PsT2g#\1P.:
```
[Try it online!](https://tio.run/##K6gsyfj/P01RN6A4xChdOcYwQM/q/38lQwMjYwMlAA "Pyth – Try It Online")
Accepts a string as input, and returns a list of strings.
```
.: -> All positive-length substrings of the (implicit) input
P -> Remove the last substring (which is the entire string)
g#\1 -> Filter for substrings which start with "1" or greater
f -> Filter for elements where...
PsT -> ... its list of prime factors
!- 2 -> ... is empty when all 2s are removed
```
[Answer]
# Python 3.10 - 72 bytes
```
lambda x:sum(([w:=2**n]*(w<x)*str(x).count(str(w))for n in range(x)),[])
```
Can probably be golfed further - I initially misunderstood the question as wanting no duplicates (i.e. `322 -> [32, 2]`), but I think the structure that lead me to is fine. Also, in principle this will work for any input, but it takes several seconds to run on `13248` and will probably take longer than I care to wait on `655365536`.
[Answer]
# JavaScript, 70 bytes
```
f=(n,i=1)=>n>i?[...[...n.matchAll(`(?=${i})`)].fill(i),...f(n,i+i)]:[]
```
```
f=(n,i=1)=>n>i?[...[...n.matchAll(`(?=${i})`)].fill(i),...f(n,i+i)]:[]
console.log(JSON.stringify(f("10230" ))) // [1, 2]
console.log(JSON.stringify(f("13248" ))) // [32, 1, 2, 4, 8]
console.log(JSON.stringify(f("333" ))) // []
console.log(JSON.stringify(f("331" ))) // [1]
console.log(JSON.stringify(f("32" ))) // [2]
console.log(JSON.stringify(f("322" ))) // [32, 2, 2]
console.log(JSON.stringify(f("106" ))) // [1]
console.log(JSON.stringify(f("302" ))) // [2]
console.log(JSON.stringify(f("464" ))) // [4, 4, 64]
console.log(JSON.stringify(f("655365536"))) // [65536, 65536]
```
Input a string, output array of integers.
[Answer]
# BQN, 29 bytes
```
‚Ä¢Fmt{‚àä‚üú(ùîΩ¬®ùï©‚ä∏>‚ä∏/2‚ãÜ‚Üïùï©)‚ä∏/‚àæ‚Ü묮‚ÜìùîΩùï©}
```
[Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oCiRm10e+KIiuKfnCjwnZS9wqjwnZWp4oq4PuKKuC8y4ouG4oaV8J2VqSniirgv4oi+4oaRwqjihpPwnZS98J2VqX0KRiAxMzI0OA==)
## Explanation
* `‚àæ‚Ü묮‚ÜìùîΩùï©` substrings of input
* `∊⟜(...)⊸/` keep substrings that are found in the constructed list...
+ `ùï©‚ä∏>‚ä∏/2‚ãÜ‚Üïùï©` powers of 2 less than input
+ `ùîΩ¬®` convert each element to string
] |
[Question]
[
## Integers in cosine
From trigonometry we know that
\$\sin(a) =-\cos(a + \frac{(4\*m + 1)\pi}{2})\$
where \$a\$ is an angle and \$m\in\mathbb{Z}\$ (integer).
### The task
For an input of a positive integer \$n\$ calculate the value of the integer \$k\$ with \$n\$ digits that minimizes the difference between \$\sin(a)\$ and \$-\cos(a + k)\$. Or in a simpler way, generate the sequence [A308879](http://oeis.org/A308879).
### First few values
1 digit : 8
2 digits: 33
3 digits: 699
4 digits: 9929
5 digits: 51819
6 digits: 573204
### Output
You can create a function or print the result on the standard output.
Your program needs to be able to calculate at least the 6 cases in the section above.
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins.
### Reference
<https://www.iquilezles.org/blog/?p=4760>
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes
This uses a trick: Mathematica doesn't expand `Sin[51819]` into a proper number even when `Max` is called on a list of such things, and because of how `Last` works, it doesn't care that `Sin[51819]` is not a list and simply returns `51819`.
```
Last@Max@Sin@Range[10^#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE7872Yb898nsbjEwTexwiE4M88hKDEvPTXa0CBOOVbtf0BRZl6Jg1u0YSwXjGmEYBojmCYIpmnsfwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 37 bytes
```
->n{(1..10**n).max_by{|k|Math.sin k}}
```
[Try it online!](https://tio.run/##HYu9DoIwGAB3n@IDB35SGwqKdKgLcXBQE@KGxJREAiEWYiGRlD57RZe7W@49lpOp2N1sDkK5BGMS@L7w8It/HuWk5nY@86HGshHQam04MMgTBFGEIKYUAaXhwh1JyE/7KAy2xYpgOTx7N/ZAwSxm6MdBgi2Wd62ERtD@q2NVLgq9lHO6ONBU0FmMY1k31aDTa5Yd05tlgzZf "Ruby – Try It Online")
Minimising the difference between \$\sin(a)\$ and \$-\cos(a+k)\$ amounts to minimising \$|k-(4m+1)\pi/2|\$ for some \$m\$, or equivalently maximising \$\sin(k)\$.
Iterating over `(1..10**n)` works at least for \$n\le6\$, as required. More generally, according to the [OEIS](http://oeis.org/A308879) (reference courtesy of [@Λ̸̸'s 05AB1E answer](https://codegolf.stackexchange.com/a/204614/92901)):
>
> It is not guaranteed that each term in the sequence produces a better approximation than the previous one, although numerical evidence suggests so.
>
>
>
Iterating over `(10**~-n...10**n)` is guaranteed to work for any \$n\$, at a cost of 7 extra bytes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
Port of Dingus's answer. (It's [A308879](http://oeis.org/A308879). From that page, it says that the sequence is also "the n-digit integer m that maximizes sin(m)"...)
```
°LΣŽ}θ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0Aafc4sPtx7aW3tux///xgA "05AB1E – Try It Online")
## Explanation
```
° 10 ** n
L 1 range
Σ Sort by:
Ž} Sine
θ Maximum under that mapping
```
[Answer]
# [R](https://cran.r-project.org/) ~~30~~ 27 bytes
Following the same thread as [@Dingus' Ruby answer](https://codegolf.stackexchange.com/a/204611/85958), as indicated in [the entry to A308879](http://oeis.org/A308879), i.e. looking at the maximum value of \$\sin(k)\$ over \$1,\ldots,10^n\$:
```
which.max(sin(1:10^scan()))
```
[Try it online!](https://tio.run/##K/r/vzwjMzlDLzexQqM4M0/D0MrQIK44OTFPQ1NT87/5fy4uAA "R – Try It Online")
[Answer]
# Java 8, 91 bytes
```
n->{double r=0,m=0,s,k=Math.pow(10,n);for(;k-->1;)if((s=Math.sin(k))>m){m=s;r=k;}return r;}
```
Port of [*@Dingus*' Ruby answer](https://codegolf.stackexchange.com/a/204611/52210), so make sure to upvote him!
[Try it online.](https://tio.run/##LU@7bsMwDNzzFUQmCX7AXqvKf5AsGYsOqh8pI4syJDlFYfjbXbrxwAPIO/KOD/M0xaOzWzuaGOFikJYTAFLqw2DaHq57C9D5@WvsoRXMAEnFw/XEEJNJ2MIVCPRGRbMcwqCr3HHF3OqLSd/l5H9EXeW8OvgglC2KplYSByHiSxCRhJWycXJxOqqgrVpDn@ZAENS6qd1t4tvsdpg@PXbgOLG4pYB0//gEI19xd489KepaAb7XFWOWyX8O4PYbU@9KP6dy4sU0ksDs/AbnTIye7pJK/lMeT67bHw) (It's barely able to reach up to \$n=9\$ on TIO before it times out.)
**Explanation:**
```
n->{ // Method with integer parameter and double return-type
double r=0, // Result-double, starting at 0
m=0, // Maximum `m`, starting at 0
s, // Integer `s` for the Sine calculation, uninitialized
k=Math.pow(10,n);for(;k-->1; // Loop `k` in the range (10^input, 1]:
if((s=Math.sin(k)) // Set `s` to the Sine of `k`
>m){ // If this `s` is larger than the current maximum `m`:
m=s; // Replace the maximum with this `s`
r=k;} // And replace the result with `k`
return r;} // Return the result after the loop
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~64~~ 63 bytes
```
n=>[...Array(t=10**n)].map(_=>[9-Math.sin(--t),t]).sort()[0][1]
```
[Try it online!](https://tio.run/##DclRCsIwDADQq/iZbGvYvkRqBQ/gCUqRMleNbM1og@Dpq@/3veMn1rnwribLY2nJtewunoiupcQvqJvGrssYaIs73P91MreoL6qcwRjFQQNSlaKAfgx@Cs0mKcBusnw@2r5nnCVXWRda5Qk8HBIwYvsB "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ApU õ ñ!sM
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=QXBVIPUg8SFzTQ&input=Mw)
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 bytes
```
⊃⍒1○⍳10*⎕
```
-7 bytes from [ngn and Adám.](https://chat.stackexchange.com/transcript/message/55300296#55300296)
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94P@jruZHvZMMH03vftS72dBA61HfVJDEfwUwKOAy5IKxjOAsYzjLBM4yhbPMAA "APL (Dyalog Extended) – Try It Online")
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~20~~ 16 bytes
```
{i[⊃⍒1○i←⍳10*⍵]}
```
-4 bytes from [Bubbler.](https://chat.stackexchange.com/transcript/message/55299238#55299238)
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/vzoz@lFX86PeSYaPpndnPmqb8Kh3s6GB1qPerbG1/9PA/D6wgjWPerccWm/8qG3io76pwUHOQDLEwzP4f5qCIVeaghEQGwOxCRCbArEZFwA "APL (Dyalog Extended) – Try It Online")
Implements [Dingus's algorithm.](https://codegolf.stackexchange.com/a/204611/80214)
## Explanation
```
{i[⊃⍒1○i←⍳10*⍵]}
{ } function body
i i←⍳10*⍵ assign to i the range of 1 to 10^n
1○ find the sine of each value in i
⊃⍒ Grade(sort) by descending value, select index of first(maximum) value
i[ ] return k in i where sin k is maximum
```
[Answer]
# [Python 3](https://docs.python.org/3/), 51 bytes
```
import math
lambda n:max(range(10**n),key=math.sin)
```
[Try it online!](https://tio.run/##LcpBCoAgEAXQdZ1ilk5IFC2CoMNMlCXlV8xFnt4IeusXcjo8hlKsCz4mcpKO2syXuGUVwuTkUVGwb6rvmgaszy3PX2pvCy7GRwJZ0H/0yFNdhWiRFLRRYC4v "Python 3 – Try It Online")
Uses [Dingus's observation](https://codegolf.stackexchange.com/a/204611/20260) about maximizing sine.
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), ~~53~~ 51 bytes
```
read*,n
print*,maxloc([(sin(1d0*k),k=1,10**n)])
end
```
[Try it online!](https://tio.run/##S8svKilKzNNNT4Mw/v8vSk1M0dLJ4yooyswr0dLJTazIyU/WiNYozszTMEwx0MrW1Mm2NdQxNNDSytOM1eRKzUv5/98MAA "Fortran (GFortran) – Try It Online")
Port of my own [Ruby answer](https://codegolf.stackexchange.com/a/204611/92901). Because why not?
] |
[Question]
[
I'm currently scanning a bunch of handwritten documents and converting them to `.txt` files. Since I have a terrible handwriting the `.jpg`->`.txt` converter converts some of my umlauts to the *"normal"* letter encased by `'`
## Task
Write a program or a function that:
* Is given a string
+ you can choose any I/O codepage as long as
- it supports the characters `AEIOUaeiouÄËÏÖÜäëïöü'`.
* [combining diacriticals](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) are prohibited
- the Input and Output codepages are the same.
+ the input will (beside spaces) only contain printable characters from your codepage.
- There will only be one solution, thus things like `'a'e'` won't appear
* Converts all characters in the following set `AEIOUaeiou` to `ÄËÏÖÜäëïöü`
+ If, and only if, they are surrounded by `'` characters:
- ***Example***: `'a''e' -> äë`
+ If the ***from*** string is a single letter.
- for example `'AE'` does not change at all, outputting as-is.
+ If the ***from*** character is not a character out of `AEIOUaeiou` that character won't change.
Note: The ***from character / from string*** is the one between `'`.
## Testcases
```
Input
Output
<empty line>
'A'sthetik
Ästhetik
Meinung ist wichtig!
Meinung ist wichtig!
Ich sagte: "Er sagte: 'Ich habe Hunger'"
Ich sagte: "Er sagte: 'Ich habe Hunger'"
Ich sagte: "Er sagte: ''A'sthetik'"
Ich sagte: "Er sagte: 'Ästhetik'"
Hämisch rieb er sich die H'a'nde
Hämisch rieb er sich die Hände
H'a''a'slich isn't a German word
Hääslich isn't a German word
since it's really called h'a'sslich
since it's really called hässlich
```
[Answer]
# JavaScript (ES6), ~~81~~ ~~70~~ 68 bytes
```
s=>s.replace(/'[aeiou]'/gi,c=>"ï ÖÄöä ËÜëüÏ "[c.charCodeAt(1)%15])
```
---
## Try It
```
f=
s=>s.replace(/'[aeiou]'/gi,c=>"ï ÖÄöä ËÜëüÏ "[c.charCodeAt(1)%15])
i.addEventListener("input",_=>o.innerText=f(i.value))
console.log(f("'A'sthetik")) // Ästhetik
console.log(f("Meinung ist wichtig!")) // Meinung ist wichtig!
console.log(f(`Ich sagte: "Er sagte: 'Ich habe Hunger'"`)) // Ich sagte: "Er sagte: 'Ich habe Hunger'"
console.log(f(`Ich sagte: "Er sagte: ''A'sthetik'"`)) // Ich sagte: "Er sagte: 'Ästhetik'"
console.log(f("Hämisch rieb er sich die H'a'nde")) // Hämisch rieb er sich die Hände
console.log(f("H'a''a'slich isn't a German word")) // Hääslich isn't a German word
console.log(f("since it's really called h'a'sslich")) // since it's really called hässlich
```
```
<input id=i><pre id=o>
```
---
## Explanation
* `s=>` Anonymous function taking the input string as an argument via parameter "s".
* `s.replace(x,y)` Returns the string with "x" replaced by "y".
* `/'[aeiou]'/gi` Case insensitive regular expression that matches all occurrences of a vowel enclosed by single quotes.
* `c=>` Passes each match of the regular expression to an anonymous function via parameter "c".
* `"ï ÖÄöä ËÜëüÏ "[n]` Returns the nth character (0 indexed) in the string "ï ÖÄöä ËÜëüÏ ", similar to `"ï ÖÄöä ËÜëüÏ ".charAt(n)`.
* `c.charCodeAt(1)%15` Gets the remainder of the character code of the second character in "c" (i.e. the vowel character) when divided by 15.
---
## Alternative, ~~40/52~~ 36/48 bytes (35/47 characters)
The following was my answer before combining diacritics were disallowed (Boo-urns!) - better viewed in [this Fiddle](https://jsfiddle.net/petershaggynoble/wgubutt4/)
```
s=>s.replace(/'([aeiou])'/gi,"$1̈")
```
However, [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) suggests that with the addition of `.normalize()` for an additional 12 bytes that this would be valid.
```
s=>s.replace(/'([aeiou])'/gi,"$1̈").normalize()
```
[Answer]
# Perl 5, 25 bytes
```
s/'(\w)'/chr 1+ord$1/age
```
24 bytes, plus 1 for `-pe` instead of `-e`
This makes use of the rule that "you can choose any I/O codepage as long as it supports the characters `AEIOUaeiouÄËÏÖÜäëïöü'`". It also makes use of the `/a` flag on regexes, which causes `\w` to refer to precisely the characters in `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789` no matter how they're encoded.
The chosen I/O codepage for my script is this:
```
1 a
2 ä
3 e
4 ë
5 i
6 ï
7 o
8 ö
9 u
10 ü
11 A
12 Ä
13 E
14 Ë
15 I
16 Ï
17 O
18 Ö
19 U
20 Ü
21 '
```
(I can't test this script on the test cases in the question, as they include some really weird characters, like `t`.)
---
Thanks to [Grimy](/users/6484/grimy) for saving me three bytes. Earlier, I had `s/'([a-z])'/chr 1+ord$1/gie`, which made use of (the encoding and) the interesting fact that `[a-z]` is special-cased in Perl to match precisely `abcdefghijklmnopqrstuvwxyz` no matter the encoding. My earlier answer is, IMO, more interesting, but this one is shorter, so, what the heck, I'll take it.
[Answer]
# Vim, 33 bytes
```
:s/\c'\([aeiou]\)'/<C-v><C-k>\1:/g
ii<esc>D@"
```
[Try it online!](https://tio.run/nexus/v#@29VrB@TrB6jEZ2YmplfGhujqa4vxh1jaKWfzpWZKe3ioPT/v4d6ojoQFedkJmcoZBbnqZcoJCqkpxblJuYplOcXpQAA "V – TIO Nexus") in the backwards compatible V interpreter.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 29 bytes
```
r"'%v'"@"ï ÖÄöä ËÜëüÏ "gXc1
```
[Try it online!](https://tio.run/nexus/japt#AUoAtf//ciInJXYnIkAiw68gICDDlsOEw7bDpCDDi8Ocw6vDvMOPICJnWGMx//8iJ0EnJ0UnJ0knJ08nJ1UnJ2EnJ2UnJ2knJ28nJ3UnIg "Japt – TIO Nexus")
### Explanation
```
r"'%v'"@"ï ÖÄöä ËÜëüÏ "gXc1
r"'%v'"@ // Replace each match X of /'<vowel>'/ in the input with
"ï ÖÄöä ËÜëüÏ "g // the character in this string at index
Xc1 // X.charCodeAt(1).
// Values larger than the length of the string wrap around,
// so this is effectively equal to " ... "[n%15].
// Implicit: output result of last expression
```
[Answer]
# Javascript, 67 bytes
```
s=>s.replace(/'.'/g,c=>"äëïöüÄËÏÖÜ"['aeiouAEIOU'.indexOf(c[1])]||c)
```
[Try it online!](https://tio.run/##lY@xSgNBEIZ7n2K8Zu9AL9gqF0gRTApJZRUC2ezN3Y1udsPOxiiktLOws7JMZ2FnZbcPdu4JIsg1wjAMM/P988@NvJOsHG38qbEltlXRcjHk3OFGS4XpQORiUJ@oYpiEQ3gL7@EjfIbH8BSew0t4TeZCItntaDydXYucTIn3sypV87NFttjvVdYqa9hqzLWt0ypdipFg36Cn22WWXRz9mV4hma2pgdjDjlTjqT7u25uqBljWHs8hGbufUnTtRq4QJlEEnUj@wf4a68cm4bAmjqwjXAFGMPqDkuIxIUX8uxeKoxisu11iIzxIuES3lgZ21pV9DJNRCOQFg0Op9QOomLGEplP6luqw9gs "JavaScript (Node.js) – Try It Online")
Replace all characters between quotes with either the corresponding umlauted character, or the match itself if it's not in the group of characters that need changing.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œṣ⁹Ṫ¤j
“.ạẏụ’D196;+\Ọż⁾''jЀØc¤;@Wç/
```
**[Try it online!](https://tio.run/nexus/jelly#AV0Aov//xZPhuaPigbnhuarCpGoK4oCcLuG6oeG6j@G7peKAmUQxOTY7K1zhu4zFvOKBvicnasOQ4oKsw5hjwqQ7QFfDpy////8iRXIgc2FndGU6ICcnQSdzdGhldGlrJyI "Jelly – TIO Nexus")**
This seems pretty complicated for Jelly!
### How?
Note: Since the characters are not on the code-page, but are within the range of a byte in Unicode I think they must be created from ordinals, so I have.
```
œṣ⁹Ṫ¤j - Link 1, Replace: char list S [...], list R [char T, char list F]
œṣ - split S at sublists equal to:
¤ - nilad followed by link(s) as a nilad:
⁹ - link's right argument, R
Ṫ - tail - yield char list F and modify R to become [T]
j - join with R (now [T])
- all in all split S at Rs and join back up with [T]s.
“.ạẏụ’D196;+\Ọż⁾''jЀØc¤;@Wç/ - Main link: char list S
196; - 196 concatenate with:
“.ạẏụ’ - base 250 literal 747687476
D - to decimal list [7,4,7,6,8,7,4,7,6]
+\ - cumulative reduce with addition: [196,203,207,214,220,228,235,239,246,252]
Ọ - cast to characters: ÄËÏÖÜäëïöü
¤ - nilad followed by link(s) as a nilad:
⁾'' - literal ["'", "'"]
Øc - vowel yield: AEIOUaeiou
jЀ - join mapped: ["'A'", "'E'", ...]
ż - zip together
W - wrap S in a list
;@ - concatenate (swap @rguments)
ç/ - reduce with last link (1) as a dyad
- implicit print
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 24 bytes
```
Óã'¨[aeiou]©'/
±:
éiD@"
```
[Try it online!](https://tio.run/nexus/v#@3948uHF6odWRCemZuaXxh5aqa4vxn1ooxXX4ZWZLg5K//97qCeqA1FxTmZyhkJmcZ56iUKiQnpqUW5inkJ5flEKAA "V – TIO Nexus")
Hexdump:
```
00000000: d3e3 27a8 5b61 6569 6f75 5da9 272f 160b ..'.[aeiou].'/..
00000010: b13a 0ae9 6944 4022 .:..iD@"
```
This is just a direct translation of my vim answer so that I can beat all of the golfing languages. :P
[Answer]
# [Ruby](https://www.ruby-lang.org/), 62+1 = 63 bytes
Uses the `-p` flag for +1 byte.
```
gsub(/'([aeiou])'/i){$1.tr"AEIOUaeiou","ÄËÏÖÜäëïöü"}
```
[Try it online!](https://tio.run/nexus/ruby#U1YsKk2qVNAt@J9eXJqkoa@uEZ2YmplfGquprp@pWa1iqFdSpOTo6ukfChZW0lE63HK4@3D/4WmH5xxecnj14fWHtx3eo1T7/79ncoZCcWJ6SaqVgpJrEYypru6oXlySkVqSma2uBAA "Ruby – TIO Nexus")
[Answer]
# [///](https://esolangs.org/wiki////), 67 bytes
```
/~/'\///`/\/\/~/'A~Ä`E~Ë`I~Ï`O~Ö`U~Ü`a~ä`e~ë`i~ï`o~ö`u~ü/
```
[Try it online!](https://tio.run/nexus/slashes#@69fp68eo6@vn6AfA4RAjmPd4ZYE17rD3QmedYf7E/zrDk9LCK07PCchse7wkoTUusOrEzLrDq9PyK87vC2htO7wHv3//wE "/// – TIO Nexus")
This works by replacing non-dotted letters surrounded by single-quotes(`'A'`) with the same letter as a dotted, without the single quotes (`Ä`). A single replacement of this looks like this (before the golf): `/'A'/Ä/`.
The golf takes two common occurrences, `//` and `'/`, and uses them as replacements.
[Answer]
# Swift - 201 bytes
```
import Foundation;func g(s:String){var e=s;var r="aeiouAEIOUäëïöüÄËÏÖÜ".characters.map{String($0)};for i in r[0...9]{e=e.replacingOccurrences(of:"'\(i)'",with:r[r.index(of:i)!+10])};print(e)}
```
Usage: `g("'A'sthetik") // => Ästhetik`
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 53 bytes
```
(v←'''[AEIOUaeiou]''')⎕R{' ÄËÏÖÜäëïöü'[v⍳2⊃⍵.Match]}
```
[Try it online!](https://tio.run/nexus/apl-dyalog#jZCxTsMwEIb3PsXRxbB0YGTrUKkdKiQkpqqDm1zjE4ldbCcFISYQAyjAAhMwdWNgQDCx@U38IsGuVEGYsKzT@ff3352umfur@@0qBMbYpD8Y7R9yJFVOw3PH3z4cnDEAd@lu3J17dE9u5V7dm/t0X2xS@fp9119f@PqjN@Y2EdPzpoH1mYOvX2Li62dYIpQG14pVkKGFnCxqngPJRWlhrlUBViBIPIl/EsGo6EqVZBYErzAa0SR8gWvQkMxyhONSWTS9TudX0w7rMxMYS0cteYwkS5kBGQtLSoSlbKsFjBIBhmcW96A70JuURVnwGcIwuFGz7n9MPzP84YduVZAJJk04AwyOMAqkFMozzmSKbTpo4Zo8QmTiMnjYny64hKXSaQsOO0kQyDIDGnmen0ISIqYgNiW@AQ "APL (Dyalog Unicode) – TIO Nexus")
Uses PCRE *R*eplace (saving the RegEx as *v*) to apply the following function to quoted vowels:
`{` anonymous function
`' ÄËÏÖÜäëïöü'[`…`]` index the string (note two spaces corresponding to `'[`) with:
`⍵.Match` the matched string
`2⊃` pick second letter (the vowel)
`v⍳` find index in *v*
`}`
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 99 bytes
```
{split("AEIOUaeiou",p,"")
for(i=1;i<=split("ÄËÏÖÜäëïöü",r,"");i++)gsub("'"p[i]"'",r[i])}1
```
[Try it online!](https://tio.run/nexus/awk#dY0xT8NADIX3@xXmlkvULF0pHTpUNEPViQkxXBKTWKSX6O6iCiE2NgY2JsZuDGxMbP5hwUFUTEiW35P9PXt8CH1LMdGrdb67skjdoLM@0zpVt51PaDlf0MXyl@EnfuYXfuU3PvI7f/Anf@nMT/SCZrO0DkORaKP7a7oRybxo@jgfx9z1Q1TKrEyIDUa6U2qL5AZXA4UIByqbSPWZUnnZQLB1xHPQa3@yZho3tkDYSAS90f@Sfy8maMPHPQUhPWEBKJh8gorkkLHGVSiIGKnQThsKzkSwcIl@bx0cOl8pFciVCBRNAI@2be@hlI4VNFPuJ6i@AQ "AWK – TIO Nexus")
I tried to come up with some clever regex within a `gensub` but failed :(
[Answer]
# [SOGL](https://github.com/dzaima/SOGL), ~~43~~ 35 (UTF-8) bytes
```
L∫:ÆW ':h++;"äëïöü”:U+Wŗ
```
Explanation:
```
L∫ repeat 10 times, pushing current iteration (0-based)
: duplicate the iteration
ÆW get the index (1-based) in "aeiouAEIOU"
':h++ quote it
; put the copy (current iteration) ontop
"äëïöü” push "äëïöü"
: duplicate it
U uppercase it
+ join together, resulting in "äëïöüÄËÏÖÜ"
W get the index (1-based) in it
ŗ replace [in the input, current char from "aeiouAEIOU" with
the corresponding char in "äëïöüÄËÏÖÜ"
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~30~~ ~~29~~ 24 bytes
-6 bytes thanks to Emigna
```
žMDu«S''«''ì"äëïöü"Du«S:
```
05AB1E conveniently has the characters `äëïöü` in its code page.
[Try it online!](https://tio.run/nexus/05ab1e#@@95dJ@vS@mh1cHq6odWq6sfXqN0eMnh1YfXH952eI8SWMLq/3/1RHUdBfVUEJEJIvJBRCmIcAQRriDCE0T4g4hQEJGYqg4A "05AB1E – TIO Nexus")
(old code)
```
žMDu«Svy''.ø})"äëïöü"Du«¹ŠS:
```
Explanation (outdated):
```
žM Push aeiou ['aeiou']
D Duplicate ['aeiou', 'aeiou']
u Uppercase ['aeiou', 'AEIOU']
« Concatenate ['aeiouAEIOU']
vy For each...
'' Push '
.ø Surround a with b (a -> bab)
} End loop
) Wrap stack to array [["'a'", "'e'", "'i'", "'o'", "'u'", "'A'", "'E'", "'I'", "'O'", "'U'"]]
"äëïöü" String literal. [["'a'", "'e'", "'i'", "'o'", "'u'", "'A'", "'E'", "'I'", "'O'", "'U'"], 'äëïöü']
Du« Duplicate, uppercase, concat [["'a'", "'e'", "'i'", "'o'", "'u'", "'A'", "'E'", "'I'", "'O'", "'U'"], 'äëïöüÄËÏÖÜ']
¹ Push first input
Š Push c, a, b ["'A'sthetik", ["'a'", "'e'", "'i'", "'o'", "'u'", "'A'", "'E'", "'I'", "'O'", "'U'"], 'äëïöüÄËÏÖÜ']
S Convert to char list ["'A'sthetik", ["'a'", "'e'", "'i'", "'o'", "'u'", "'A'", "'E'", "'I'", "'O'", "'U'"], ['ä', 'ë', 'ï', 'ö', 'ü', 'Ä', 'Ë', 'Ï', 'Ö', 'Ü']]
: Replace all ['Ästhetik']
Implicit print
```
[Try it online!](https://tio.run/nexus/05ab1e#@@95dJ@vS@mh1cHq6odWq6sfXqN0eMnh1YfXH952eI8SWMLq/3/1RHUdBfVUEJEJIvJBRCmIcAQRriDCE0T4g4hQEJGYqg4A "05AB1E – TIO Nexus")
[Answer]
# Python 3.6, ~~98~~ 92 characters
```
import re;a=lambda i,p="'([AEIOUaeiou])'":re.sub(p,lambda x:'ÄËÏÖÜäëïöü'[p.index(x[1])-3],i)
```
It's a function, not a complete program.
Formatted for readability:
```
import re
a = lambda i, p="'([AEIOUaeiou])'":\
re.sub(p, lambda x: 'ÄËÏÖÜäëïöü'[p.index(x[1]) - 3], i)
```
Thanks to @ValueInk for clever tips for further golfing.
[Answer]
# [Retina](https://github.com/m-ender/retina), 39 bytes
```
iT`A\EI\OUaei\ou'`ÄËÏÖÜäëïöü_`'[aeiou]'
```
[Try it online!](https://tio.run/nexus/retina#dY2xbsJADIb3PIXL4nfoxhARhoqlnQgil8TKWQ0X6e4ixM7GwMbEyMbAxsTmB0sdpIoJybIt/9//e@DvYpqn83zxY4jzrsdC9nKQo5zkLBe5yk3u8lgXuFS961c4DDjFEC1F/k2@iF3vGuAQYcuVjdx8JPPKQjBNpE@YpP5/xfFsTUmQqYM8Tt6Br3xlMrlsOCjomUogpfQN1KwxaNDVlIxTK7SjwMFhBAMz8hvjYNv5OgnsKgKOGMCTadsdVNqpBjvanr4/ "Retina – TIO Nexus")
] |
[Question]
[
**This question already has answers here**:
[Additive Persistence](/questions/1775/additive-persistence)
(47 answers)
Closed 6 years ago.
## Your Task:
Write a program or function that, when given a number, outputs its *persistence*. The persistence of a number is the number of times you can add its digits before arriving at a one-digit number. All one digit numbers have a persistence of 0. Note that this is different from questions about finding the digital root, as those questions ask for the end result of this process, whereas this question wants the number of steps required to get there.
## Input:
An integer.
## Output:
The persistence of the inputted integer.
## Examples:
```
1-->0 (1=1)
12-->1 (1+2=3)
99-->2 (9+9=18, 1+8=9)
9999-->2 (9+9+9+9=36, 3+6=9)
```
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~50~~ 39 bytes
-10 thanks to @JonathanAllan
```
f=lambda x:x>9and-~f(sum(map(int,`x`)))
```
[Try it online!](https://tio.run/##FYpBCoAgEADP9Yq9SCsYVNBhg3pLRkhBmqTBdunrZjBzmvFP3E7XpWTGQ9tl1cADT6TdWr8Gw23Rao@7i2rmWUqZzHkBw@4y/o4oh7LwV@5QiT6ACJVAVgY5r42CtlNA9Ev0AQ "Python 2 – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
;.{ẹ+}ⁱ⁾Ḋ∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/31qv@uGundq1jxo3Pmrc93BH16OO5f//WwLB/ygA "Brachylog – Try It Online")
### Explanation
```
;.{ }ⁱ⁾ Iterate Output times on the Input…
Ḋ∧ …so that the result is a single digit:
ẹ+ Sum the elements
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~91~~ 90 bytes
```
s(A,B):-A=0,B=0;divmod(A,10,Q,R),s(Q,T),B is T+R.
p(A,B):-A<10,B=0;s(A,S),p(S,T),B is T+1.
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/v1jDUcdJ00rX0dZAx8nWwDolsyw3PwUoaGigE6gTpKlTrBGoE6Kp46SQWawQoh2kx1UA02FjCNECMiJYU6dAIxhJoaHe//8FGoY6jiAJQyOgDiBtaanjDKGBLBdNPQA "Prolog (SWI) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
DS$ÐĿL’
```
[Try it online!](https://tio.run/##y0rNyan8/98lWOXwhCP7fR41zPx/uP1R05r//6MNdQyNdCwtgcjSMhYA "Jelly – Try It Online")
## How it works
```
DS$ÐĿL’
DS$ digital sum
ÐĿ apply until results not unique, collect all intermediate results
L length of the collection
’ minus 1
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 58 bytes
1 byte thanks to Felipe Nardi Batista and [Kritixi Lithos](https://chat.stackexchange.com/transcript/message/38132712#38132712) who discovered the same golf independently.
```
a,m;f(n){for(m=n,a=0;m;m/=10)a+=m%10;return n>9?1+f(a):0;}
```
[Try it online!](https://tio.run/##dclBDsIgEEDRtZ6C1DQZUlRwh0i9iBsCRUmcqUG6anp2NHFbl/99v797X3eJ/HMKA7u8S0jj4dFXJ9BEID7HMQNaEs5KgwaPVknuOoutkiYPZcrEqNdX1UVw/CzNUhMVhi4R8Hm7eeVvRmjacKNGRFCcmxU9rbLWf/g3lvoB "C (gcc) – Try It Online")
[Answer]
# Mathematica, 48 bytes
```
(n=#;t=0;While[n>9,n=Tr@IntegerDigits@n;t++];t)&
```
but **alephalpha** golfed it down to...
# Mathematica, 41 bytes
```
(t=-1;#//.n_:>Tr[t++;IntegerDigits@n];t)&
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
[DgiNq}SO
```
Explanation:
```
[ Start infinite loop
D Duplicate
g Length
i If equal to one:
N Push iteration number
q Terminate program
} Else:
S Get the characters
O Sum
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/2iU906@wNtj//39LIAAA "05AB1E – Try It Online")
[Answer]
# Java 8, 67 bytes
```
n->{int r=0,s;for(;n>9;n=s,r++)for(s=0;n>0;n/=10)s+=n%10;return r;}
```
**Explanation:**
[Try it here.](https://tio.run/##hVDLCsIwELz3K/YiJFRr65MS4h/Yi0fxEGOUaN2WJBWk9Ntror1KDzuwM8PssHfxErOqVni/PHpZCmthLzS2EYBGp8xVSAVFWL8ESBIQKfNMF3mwTjgtoQAEDj3Odm0wGJ5OLbtWhjDc5Qy5nZo4poGwPPWcnznPUmpjjpMsZUa5xiAY1vUsxNbNufSxQ/qr0hd4@l7k4IzG2/EEgv5KHd7WqWdSNS6pveRKJJhIktFvxb96PqJni7GAfNSQjx9ZrtabLR2@2fUf)
```
n->{ // Method with integer parameter and integer return-type
int r=0, // Result-count
s; // Digit-sum
for(;n>9 // Loop as long as `n` contains more than 1 digit
; // After every iteration:
n=s, // Replace the `n` with the sum of digits
r++) // and increase the result-count
for(s=0; // Reset the sum to 0
n>0; // Inner loop (2) as long as n is larger than 0
n/=10) // Divide n by 10 every iteration
s+=n%10; // And increase the sum with the trailing digit
// End of inner loop (2) (implicit / single-line body)
// End of loop (1) (implicit / single-line body)
return r; // Return the result-count
} // End of method
```
[Answer]
## Lua 125
```
function r(n,c,t,m)n=tostring(n)t,c=0,c or 0;for m=1,#n do t=t+n:sub(m,m)end return #n==1 and(print(c)or true)or r(t, c+1)end
```
you call it simply using r({yourNumber})
[Answer]
# [Perl 5](https://www.perl.org/), 32 bytes
31 bytes of code + `-p` flag.
```
$_=eval,$\++while 1<s/./+$&/g}{
```
[Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdAv@q8TbppYl5uioxGhrl2dk5qQqGNoU6@vpa6uo6afXVv//b2gEAA "Perl 5 – Try It Online")
Short explanations:
`s/./+$&/g` adds a `+` before each digit and returns the number of digits. While this number is greater than `1`, we set `$_` to the value of the `eval`uation of this string, and increment the number of set (`$\++`). At the end, `$\` is implicitly printed thanks to `-p` and `}{`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
t:"tFYAs]v9>s
```
[Try it online!](https://tio.run/##y00syfn/v8RKqcQt0rE4tszSrvj/f0sgAAA "MATL – Try It Online")
### Explanation
```
t % Implicit input. Duplicate
:" % Do the following that many times
t % Duplicate
FYA % Convert to base 10: array of decimal digits
s % Sum of array
] % End
v % Concatenate stack vertically
9> % Greater than 9? element-wise
s % Sum. Implicit display
```
[Answer]
# Javascript, 47 bytes
```
f=x=>x>9?f([...x+""].reduce((a,b)=>+a+ +b))+1:0
```
```
f=x=>x>9?f([...x+""].reduce((a,b)=>+a+ +b))+1:0
console.log('1 -> ' + f(1));
console.log('12 -> ' + f(12));
console.log('99 -> ' + f(99));
console.log('9999 -> ' + f(9999));
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~46~~ 45 bytes
```
g n|m<-sum$read.pure<$>show n,m<n=1+g m|1<3=0
```
[Try it online!](https://tio.run/##Xcc7DoAgEAXA3lO8gs5PRCsS8C4kEiSyqwGNDXfHWqebzebdxVirBxfSfb5JJGfX4byT02LJ2/GAO9JsZOtBRerZjJVsYBisBxoAZwp8QcBD/jp9r9T/StUX "Haskell – Try It Online")
`read.pure<$>show n` converts an integer `n` to a list of digits, applying `sum` to this list yields the digital sum `m`. If `m` is smaller than `n` then `n` was not yet a single digit, so we recursively call `g m` and add one. Otherwise `0` is returned.
[Answer]
# [PHP](https://php.net/), 58 bytes
```
for(;9<$a=&$argn;$a=array_sum(str_split($a)))$p++;echo+$p;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkCQRK1v/T8os0rC1tVBJt1cAS1kBWYlFRYmV8cWmuRnFJUXxxQU5miYZKoqampkqBtrZ1anJGvrZKgfX//1/z8nWTE5MzUgE "PHP – Try It Online")
[Answer]
# Swift 4, 89 bytes
```
func p(i:Int)->Int{return"\(i)".count==1 ?i :p(i:"\(i)".map{Int("\($0)")!}.reduce(0,+))}
```
Swift 4 is still in beta, so you can't run it online. If you have Xcode 9 Beta, it will work.
Un-golfed:
```
func p(i: Int) -> Int {
return "\(i)".count==1 ? i : p(i: "\(i)".map{Int("\($0)")!}.reduce(0,+))
}
```
Here we check to see how many digits are in the number. If it is only one, we return the number. If not, we turn it into a string, change each character back into an int, get the total sum of all the digits, and run that back through the original function.
[Answer]
## Clojure, 88 bytes
```
#(loop[v(str %)i 0](if(=(count v)1)i(recur(str(apply +(for[c v](-(int c)48))))(inc i))))
```
Oddly long...
[Answer]
# Dyalog APL, 27 bytes
```
{⍵≤9:0⋄1+∇+/⍵⊤⍨10⍴⍨⌈10⍟1+⍵}
```
[Answer]
# [Lua](https://www.lua.org), ~~82~~ 80 bytes
```
x=~~...c=0while x>9 do
c=c+1z=0while x>0 do
z=z+x%10x=x//10
end
x=z
end
print(c)
```
[Try it online!](https://tio.run/##yylN/P@/wrauTk9PL9nWoDwjMydVocLOUiElnyvZNlnbsAohaAASrLKt0q5QNTSosK3Q1zc04ErNS@GqsK0C0wVFmXklGsma////twQCAA "Lua – Try It Online")
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), 28 bytes
```
V0R1>[dl2-?<1+M&+vm1+R>:v_|]
```
[Try it online!](https://tio.run/##SypKzMxLz89J@/8/zCDI0C46JcdI197GUNtXTbss11A7yM6qLL4m9v///4aWlgA "Braingolf – Try It Online")
## Explanation
```
V0R1>[dl2-?<1+M&+vm1+R>:v_|] Implicit input of commandline args
V0R Create stack2, push 0, return to stack1
1> Push 1 to bottom of stack1
[.....................] While loop, will run while bottom item on stack1 is not 0
d Split top of stack into digits
l2-? If length of stack <= 2..
<1+ ..Move BoS to stop and increment
M ..Move item to stack2
&+ ..Sum entire stack
vm ..Move item back from stack2
1+ ..Increment top item on stack2
R> ..Return to stack1 and move ToS to bottom
: Else
v_ ..Switch to stack2 and print last item
| Endif
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 26 bytes
```
1`\d.
#$&
\d
$*
}`1+
$.&
#
```
[Try it online!](https://tio.run/##K0otycxL/P/fMCEmRY9LWUWNKyaFS0WLqzbBUJtLRU@NS/n/f0sgAAA "Retina – Try It Online") Explanation: The first stage counts the persistence: if there are at least two digits, the persistence (represented here by `#` signs) is incremented. The second stage converts each digit individually to unary, effectively adding them, while the third stage converts back to decimal, looping until a single digit is obtained. It then remains to count the `#` signs.
] |
[Question]
[
Your job is to implement bitwise addition.
To ensure that this is done, you will compute and print the result of addition without carry (or bitwise XOR). Then, you will compute the carry of the addition (bitwise AND) and multiply it by two (bitwise left shift). If the carry is nonzero, then you add the carry and the previous result until the carry is zero, at which point you stop producing output. If all is done correctly, the final result printed should be the sum of the two integers that you received as input.
Here's an ungolfed reference implementation in C:
```
#include <stdio.h>
void print_add(unsigned a, unsigned b)
{
unsigned carry;
while(b)
{
carry = a & b;
a ^= b;
printf("%u\n", a);
b = carry << 1;
}
}
```
## Input
Two positive integers in any convenient format.
## Output
A list of positive integers in any convenient format representing each result of addition without carry. Leading/trailing whitespace/newlines are allowed.
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The answer with the least bytes in each language wins, which means that I will not accept an answer.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. This includes, but is not limited to, [Abusing native number types to trivialize a problem](https://codegolf.meta.stackexchange.com/a/8245).
## Testcases
```
1, 1 -> 0, 2
3, 17 -> 18, 16, 20
6, 7 -> 1, 13
21, 19 -> 6, 36, 32, 40
10, 9 -> 3, 19
20, 20 -> 0, 40
```
Your code must work for at least all pairs of positive integers that your integer type can represent the sum of.
[Answer]
# JavaScript (ES6), 34 bytes
Takes input as `(A)(B)`, where `A+B` is a positive-looking 32-bit integer, i.e. less than 0x80000000.
Returns an array.
```
A=>g=B=>B?[A^=B,...g((B&~A)*2)]:[]
```
[Try it online!](https://tio.run/##XY7BDoIwEAXvfkVPpjW1dFuCYlIM/Q2CCUFoMIQaMR799boEufTwTjM77aP5NHP7Gp7v4@TvXehNKE3hjDWFvVblzVguhHCU2v23ZAfF6ktVh9ZPsx87MXpHe0qALWMkSYjkRO0irBmF04rhzAlk6MhYyrCxSejoiCt8A/KV471epjhJ4w5I7Pw9jZ087iDHbX9NZfgB "JavaScript (Node.js) – Try It Online")
Or for **35 bytes**, a BigInt version with unlimited input:
```
A=>g=B=>B?[A^=B,...g((B&~A)*2n)]:[]
```
[Try it online!](https://tio.run/##Xc5LCsIwEIDhvafIShKJaR6lWiGV5hqlQqltUEoiVlx69ZiR1kUWM6uPf@bevbu5f94er73z1yGMOtS6stroypyb@qINZYxZjM32U5OddKQ9NW3ovZv9NLDJWzxiJBz5LYKyDHGK5CYBKgJxWIA4UiSKqHjKCuj8WVQqERIuiXIRsaFgJEV52hIcWqtUsVWmLRCw1q9zHr4 "JavaScript (Node.js) – Try It Online")
### How?
In order to use only 2 variables and pass a single variable to the recursive function, we apply the XOR right away to `A` and prepend the result to the output array.
Instead of computing `(A AND B) * 2`, we now need to compute `(B AND (A XOR B)) * 2`. Fortunately this can also be expressed as:
```
(B AND (NOT A)) * 2
```
leading to the rather short `(B&~A)*2` in JS syntax.
[Answer]
# [sed](https://www.gnu.org/software/sed/) -En, 120 bytes
```
:L;s/0(.{8})0/a\1a/;s/0(.{8})1/b\1a/;s/1(.{8})0/b\1a/;s/1(.{8})1/a\1b/;tL;y/ab /01\
/;P;s/$/0/;tM;:M;s/\
.(.*1)/\
\1/;tL
```
[Try it online!](https://tio.run/##K05N0U3PK/3/38rHuljfQEOv2qJW00A/McYwUR8hYKifBBUwhKlAEzAEaUnSty7xsa7UT0xS0DcwjOHStw4AqlDRNwCK@1pb@QI5MVx6GnpahppARowhSPn//wYGBoYgqABmGBga/ssvKMnMzyv@r@uaBwA "sed – Try It Online")
Or [try all the test cases online!](https://tio.run/##ZY9NasMwEIX3c4qHCeQPezS7EpnsklVCewBvZFutA4kd7IS2lJ7dlRUZQzoD0tM3TzNSbrqqL8wN22vbfLTmgjSNdq/7qN8cdMdqkfy8/C4Vm0wMT0A4D0BGxxOQ4UrO@nbQ32xysJKMWL85x4yV40e9ObpDRskiWcnSiUwGe@@mExXVpSlxX38hvIvoszqdLVprSpxPtSWgbNwC2KJqEM0GGE1gHj/H3Bc7WyLe1YjfkfD06fRfBz@gtr16hGAUFHZPZCIiCkF4IkMGz4N4BBXQ6FEYBf0B)
Input: Two 8-bit integers written in binary (on one line, with a space in between them).
Output: Also 8-bit binary numbers.
For convenience this is written for 8-bit integers, but if you want to use 32-bit integers, for instance, just change the instances of `8` in the script to `32`. You can try out the [32-bit version here](https://tio.run/##K05N0U3PK/3/38rHuljfQEOv2tioVtNAPzHGMFEfScRQPwkqYghXgy5iCNKVpG9d4mNdqZ@YpKBvYBjDpW8dAFSiom8AFPe1tvIFcmK49DT0tAw1gYwYQ5Dy//8NcANDEFTAq8DA0PBffkFJZn5e8X9d1zwA).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~65~~ \$\cdots\$ ~~46~~ 45 bytes
Saved 5 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
f(a,b){for(;b;b&=~a,b*=2)printf("%d ",a^=b);}
```
[Try it online!](https://tio.run/##VczBCsIwDAbg@54iFJRWMmg62JBSn0SEtlLZwU2GtzFfveYyukIg@fl@EttXjDkn6TGoNc2LtMGGs/txvjijPss4fZMUpycI9A8XlN3y24@TVGuzIwFBewOhbJMkIfHe6T51QEPRDmmouIeD9lij4c/XwoaQc9UgDYcCaYTajQae8oELRvO55T8 "C (gcc) – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~69~~ \$\cdots\$ ~~56~~ 45 bytes
11 bytes less, thank to [Mitchell Spector](https://codegolf.stackexchange.com/users/59825/mitchell-spector)!
```
d()(echo $[a=$1^$2];((c=$1&$2))&&d $a $[c*2])
```
[Try it online!](https://tio.run/##XYuxCgIxEER7v2IIS8hauStnCMEvkRNiIqSz8P9ZwzV3caph5r1X@XazFji8a/@AHuVO8iRdcwh1VE/K7H0DlXHWs65sDQLJGNkc504NV0jM03JD/GN0aCkfF7kgzZZE6LIzZj8 "Bash – Try It Online")
Commented long version:
```
# Defines function d with parenthesis sub-shell block (commands), rather than
# curly-braces commands block, to save leading space and trailing semicolons.
d ()
(
# Print and assign new value, using deprecated $[expression] syntax, rather
# than modern's $((expression)) syntax, saves 2 bytes.
echo $[a=$1^$2]
# Bash stand-alone arithmetic expression's return-code, conditions recursive
# call, with argument 2 computed inline, using deprecated but shorter
# arithmetic expression.
((c=$1&$2)) && d $a $[c*2]
)
```
Note that the shorter but deprecated `$[expression]` syntax is going to be removed in later Bash versions.
See: `man bash` Bash 5.0.3(1)-release
>
> Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result.
>
>
> The format for arithmetic expansion is:
>
>
>
> ```
> $((expression))
> ```
>
> The old format `$[expression]` is deprecated and will be removed in upcoming versions of bash.
>
>
>
See also: [bug-bash ML](https://lists.gnu.org/archive/html/bug-bash/2012-04/msg00033.html):
On Sun, Apr 8, 2012 at 12:50 AM, Linda Walsh wrote:
>
> Re: status on $[arith] for eval arith vsl $((arith))??
> ...
> Some linux distributions patch the man page and document $[ ] as deprecated.
>
>
> The SUS rationale says:
>
>
> In early proposals, a form $[expression] was used. It was functionally
> equivalent to the "$(())" of the current text, but objections were
> lodged that the 1988 KornShell had already implemented "$(())" and
> there was no compelling reason to invent yet another syntax.
> Furthermore, the "$[]" syntax had a minor incompatibility involving
> the patterns in case statements.
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
def f(a,b):1/b;print a^b;f(a^b,(a&b)*2)
```
[Try it online!](https://tio.run/##TY/RbsMgDEXf@QorkyaYaJeQaltTrZ9SCRKioqYEYaYtX58Zlk17AHwP11d2WNJ19mpdBzvCyLU0omuezSlE5xPoizkRvBjJ9aMRT0qs7h7mmAAXZGycI0zOW3A@gz2mwfmOATxAtHogHD4SSZSgPcI73HXgmCIZowuy9O4xTC7xaneuhCCvlmA2J00gAX8NcvsvQZPDxP88xP67RJmgv9r@lr8@bSSQ4pIng21JKu1Xb0PqIGhEkmXjqlobCQ3szlBLUKwl8ZpV80bVC6Ga0f2DiLRM5eeYNfE2HyXhULOG@gvOEUemcly95R7qbw "Python 2 – Try It Online")
A recursive function that prints all intermediate values, then terminates with an exception.
---
# [Python 2](https://docs.python.org/2/), 41 bytes
```
f=lambda a,b:b*[0]and[a^b]+f(a^b,(a&b)*2)
```
[Try it online!](https://tio.run/##TY/vasMgFMW/@xSXDIY2thhTtrWQvkjIQJuEyhIj6hh9@uzerBv74J/7u@ccr@Geb4vX6zo2k5ltb8BIe7a7VnXG9615t105cjwkN89W7LRY3RyWmCHdE2PjEmFyfgDnCRxS7p0/M4AniIPpEYfPjGWSYHyCBmYTeMoRhdEFuXkPKUwu82J/KYRArZFgH0rns4T0K5CP/hY0uZT5nwbZf5XYJrjehusHtb6GiCCiC7@C6dQOEY00F70rIeKlLUoci8emQY8oi65YKwkV7C@gJGhWY/FKVfWGtxdEiuH@g5DUTNNxohp5TUtLOCpWoX/DFHFimuLUI/eovgE "Python 2 – Try It Online")
A recursive function that takes in two summands and returns a list of intermediate results.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
&/Ḥṭ^/ƲƬḢ€Ḋ
```
A monadic Link accepting a list of two integers which yields a list of integers.
**[Try it online!](https://tio.run/##y0rNyan8/19N/@GOJQ93ro3TP7bp2JqHOxY9agKSXf///482MtRRMLSMBQA "Jelly – Try It Online")**
### How?
Note that at the end of proceedings we'll have the sum and a carry of zero, and if we were to compute the addition without carry and the carry once more we'd get the same results, so we can keep going until `[sum-without-carry, carry]` does not change...
```
&/Ḥṭ^/ƲƬḢ€Ḋ - Link: list of two integers, [a,b]
Ƭ - Collect up (starting with [a,b]) while results are distinct applying:
Ʋ - last four links as a monad:
/ - reduce (current pair, [x,y]) by:
& - bitwise AND
Ḥ - double
/ - reduce (current pair, [x,y]) by:
^ - bitwise XOR
ṭ - tack -> [x^y, (x&y)*2]
Ḣ€ - head each
Ḋ - dequeue (remove a from the front)
```
[Answer]
## Batch, 68 bytes
```
@if %2==0 exit/b
@set/a"a=%1^%2,b=(%1&%2)*2
@echo %a%
@%0 %a% %b%
```
Explanation:
```
@if %2==0 exit/b
```
Repeat until `b` is zero.
```
@set/a"a=%1^%2,b=(%1&%2)*2
```
Calculate the XOR and the carry.
```
@echo %a%
```
Output the next result.
```
@%0 %a% %b%
```
Restart with the new operands.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
`Z~t1MZ&Et]xx
```
[Try it online!](https://tio.run/##y00syfn/PyGqrsTQN0rNtSS2ouL/f0MDLksA) Or [verify all test cases](https://tio.run/##y00syfmf8D8hqq7E0DdKzbUktqLiv7qurnqES8h/Qy5DLmMuQ3MuMy5zLiMgz5LL0IDLksvIAIgA).
### Explanation
```
` % Do...while
Z~ % Bitwise XOR. Takes the two inputs implicitly the first time
t % Duplicate
1M % Push the inputs of the latest bitwise XOR again
Z& % Bitwise AND
E % Multiply by 2
t % Duplicate. This copy will be used as loop condition
] % End. If the top of the stack is not 0 a new iteration is run
xx % Delete top two elements (a 0 from the last bitwise AND and a
% copy of the result from the last bitwise XOR)
% Implicitly display
```
[Answer]
# Rust, ~~69~~ 68 bytes
```
|mut a:u8,mut b:u8|while b>0{let c=(a&b)*2;a^=b;b=c;print!("{} ",a)}
```
A port of [math junkie](https://codegolf.stackexchange.com/users/65425/math-junkie)'s python [answer](https://codegolf.stackexchange.com/a/204042/46901).
[Try it](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=fn%20main()%20%7B%0A%20%20%20%20let%20g%3D%7Cmut%20a%3Au8%2Cmut%20b%3Au8%7Cwhile%20b%3E0%7Blet%20c%3D(a%26b)*2%3Ba%5E%3Db%3Bb%3Dc%3Bprint!(%22%7B%7D%20%22%2Ca)%7D%3B%0A%20%20%20%20g(21%2C%2019)%3B%0A%7D) on Rust Playground.
I had to use a temporary variable because destructuring in assignments is still being [worked on](https://github.com/rust-lang/rfcs/issues/372)
[Answer]
# [Python 2](https://docs.python.org/2/), 44 43 bytes
-1 byte thanks to @SurculoseSputum
```
a,b=input()
while b:a,b=a^b,(a&b)*2;print a
```
[Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SqmCroK6u/j9RJ8k2M6@gtERDk6s8IzMnVSHJCiSWGJeko5GolqSpZWRdUJSZV6KQ@B@onguqyNAqtSI1WQNkkCZEXskWCJT@G@oYchnrGJpzmemYcxkBeZZchgY6llxGBjpGBgA "Python 2 – Try It Online")
Very simple implementation. Pretty much a golfed version of the reference code.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
NθNηWη«≧&θη≔⁻|θιηθ≦⊗η⟦Iθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oLmZ8B5JdnZOakKgCZCtVcnL6JBY7FxZnpeUGZ6RklGk6ZJeWZxamOeSk6CoU6CiDlnBB5Dd/MvNJimAJ/oNE6CpmaICVAlSBlcJM0XPJLk3JSU6DaA4oy80o0op0Ti0uAzokFCtX@/29kqGBo@V@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input `a` and `b`.
```
Wη«
```
Repeat while `b` is non-zero. This also makes a copy of `b`.
```
≧&θη
```
Bitwise And `b` with `a`.
```
≔⁻|θιηθ
```
Bitwise Or `a` with the copy of `b`, and subtract the above value, thus replacing `a` with the Bitwise Xor of `a` and `b`.
```
≦⊗η
```
Bitwise left shift `b` as it is now the carry.
```
⟦Iθ
```
Output the value of `a` on its own line.
[Answer]
# Javascript ES6, 48 chars, uint32 full support
```
a=>b=>{for(;b;alert(a>>>0))[a,b]=[a^b,(a&b)<<1]}
```
Test with `console.log` instead of alert:
```
f=a=>b=>{for(;b;console.log(a>>>0))[a,b]=[a^b,(a&b)<<1]}
g=(x,y,...res)=>console.log(`=== ${x} ${y} => ${res} ===`)+f(x)(y)
g(2147483648, 2147483648, 0)
g(3000000000, 1, 3000000001)
g(2147483648, 0)
g(1, 1, 0, 2)
g(3, 17, 18, 16, 20)
g(6, 7, 1, 13)
g(21, 19, 6, 36, 32, 40)
g(10, 9, 3, 19)
g(20, 20, 0, 40)
```
```
.as-console-wrapper.as-console-wrapper { max-height: 100vh }
```
# Javascript ES6, 43 chars, int32 except 2\*\*32
```
a=>b=>{for(;b;alert(a))[a,b]=[a^b,(a&b)*2]}
```
Test with `console.log` instead of alert:
```
f=a=>b=>{for(;b;console.log(a))[a,b]=[a^b,(a&b)*2]}
g=(x,y,...res)=>console.log(`=== ${x} ${y} => ${res} ===`)+f(x)(y)
g(2147483648, 2147483648, 0, 'never')
g(3000000000, 3000000000, 0, 1705032704)
g(3000000000, 1, 3000000001)
g(2147483648, 0)
g(1, 1, 0, 2)
g(3, 17, 18, 16, 20)
g(6, 7, 1, 13)
g(21, 19, 6, 36, 32, 40)
g(10, 9, 3, 19)
g(20, 20, 0, 40)
```
```
.as-console-wrapper.as-console-wrapper { max-height: 100vh }
```
# Javascript ES 2020, 44 chars, infinite integers
```
a=>b=>{for(;b;alert(a))[a,b]=[a^b,(a&b)*2n]}
```
Test with `console.log` instead of alert:
```
alert=x=>console.log(x+"")
f=a=>b=>{for(;b;alert(a))[a,b]=[a^b,(a&b)*2n]}
g=(x,y,...res)=>console.log(`=== ${x} ${y} => ${res} ===`)+f(x)(y)
g(2147483648n, 2147483648n, 0, 4294967296)
g(3000000000n, 3000000000n, 0, 6000000000)
g(3000000000n, 1n, 3000000001)
g(2147483648n, 0)
g(1n, 1n, 0, 2)
g(3n, 17n, 18, 16, 20)
g(6n, 7n, 1, 13)
g(21n, 19n, 6, 36, 32, 40)
g(10n, 9n, 3, 19)
g(20n, 20n, 0, 40)
```
```
.as-console-wrapper.as-console-wrapper { max-height: 100vh }
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 54 bytes
```
(a,b)->{for(;b>0;b=(b&~a)*2)System.out.println(a^=b);}
```
[Try it online!](https://tio.run/##dU/BasMwDL33K0Sgwy6uSTJYabP0sJ122KnHrQMldYq7xAm2Ehil@3XP6brBBj2Ix5Oe9J4OOOD8sHv3uulaS3AIXPaka1n1piTdGjnLJmWNzsEzagPHCUDXF7UuwRFSgKHVO2jCjG3IarN/2QLaveNnKcCDfmyN6xtl758Mqb2y4oJrqCD3DEXB5@tj1VqWFes4K3JW3Hwin6V88@FINbLtSXbhNNWG4Vte8Ozks/PxcWlAC6Qcrf7YAoz9AeteOcjPAum6WhOLRMSzi@a/QcWiqVtNTSTGhV9ZJbEsVUfsklx2aJ0KhH0bvMRbLuDaMNnyq4bho@jV/AQ6TcY6eZ@IxN@KZOHvxMKngS19EoulT2ORxl8 "Java (JDK) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
Δ`^=y`&D_#·)
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3JSEONvKBDWXeOVD2zX//482MtRRMLSMBQA "05AB1E – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 48 bytes
```
(a,b,c,d)=>{for(;b>0;c=a&b,d.Add(a^=b),b=c<<1);}
```
[Try it online!](https://tio.run/##ZY9Na4QwEIbv/opBSokwK37sbil@wLK34q2HHmQLGmMbWGLRbHuQ/HYbNW4rXmYS3mfemZd2O9rx4btogYuvm/QhAcF@4MaFzIML9OCjDyqy7kSwIUL0n1ZIuEGOuCb2GyLQe55XzGF7iodr5Li18TDwVkw3M/mozhHRBDE9NH1v@gEXc2OTmS0Z72Q8rkqJE1mTVBvpRCVvxCQi/K9/MykZSIElUqycJO3rpiVRmXoRTYrHEiv3VFWkeE9KB8uExrHvRGoY12iQFfST3APpapI5Vm8BQOaer6xox6P0ryaTmHsXkyP39cvTp8z6uRFdc2XuW8sly7hg5MHulxGF/TKjYJdC/ypbLj7cl4YLYiPYo42ytZMafgE "C# (Visual C# Interactive Compiler) – Try It Online")
This is my first time using a for loop to do operations within the actual iterator, which feels weird, and uncomfortable, but also calming.
Mostly just tried to play with the reference, and make it more compact. Will be returning to this later. Need to double check my answer is fully legal (using the List), but this is my initial attempt.
More Info:
```
(a,b,c,d)=>{ //Pass in variables via lambda expression, and now a for loop
//Note, the c# for statement format is:
//for (initializer; condition; iterator)
////body
//
for( //Start of for loop statement
; //A mustache... jk. I am using no initializers, so just a ";" - totally blank
b>0; //My for loop conditional. I used an int rather than a c bool, which is not as compact, maybe there's a better way
//For loop Iterators:
c=a&b, //c is carry
d.Add(a^=b), //Append to end of list: a equals a xor b
b=c<<1 //left shift
) //End Initializers, condition, and iterator parts of for loop
; //Body of for loop (nothing)
} //End lambda expression
```
[Answer]
# [K4](https://kx.com/download/), ~~32~~ 31 bytes
**Solution:**
```
1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\
```
**Examples:**
```
q)k)1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\1 1
0 2
q)k)1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\3 17
18 16 20
q)k)1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\6 7
1 13
q)k)1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\21 19
6 36 32 40
q)k)1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\10 9
3 19
q)k)1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\20 20
0 40
```
**Explanation:**
Lots of eaches...
```
1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\ / the solution
( )\ / iterate
0b\:' / convert each into into binary
@\: / apply (@) each-left (\:) function to right
( ; ) / two item list
&/ / AND
~=/ / XOR
2/:' / convert each from binary
1 2* / multiply first item by 1, 2nd by 2
+ / flip
* / first
1_ / drop first element
```
] |
[Question]
[
# Rotonyms 2
A "Rotonym" is a word that ROT13s into another word (in the same language).
For this challenge, we'll use an alternate definition: a "Rotonym" is a word that circular shifts/rotates into *another* word (in the same language).
For example:
```
'stable' < 'tables' < 'ablest'
'abort' > 'tabor'
'tada' >> 'data'
```
# The Challenge
Write a program or function that accepts a dictionary/word list and prints or returns a complete list of rotonyms.
1. Order doesn't matter.
2. Comparisons should be case-insensitive, so you can assume the input will be passed as a lower-case-only dictionary.
3. Result should be expressed as single words (not the pairs) and contain no duplicates, so you can assume the input has no duplicates.
4. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
# Example
Given
```
ablest
abort
green
irk
stable
tables
tabor
tata
terra
vex
you
```
Return
```
ablest
abort
stable
tables
tabor
```
# A Real Test
Given
```
a aa aal aalii aam aani aardvark aardwolf aaron aaronic aaronical aaronite aaronitic aaru ab aba ababdeh ababua abac abaca abacate abacay abacinate abacination abaciscus abacist aback abactinal abactinally abaction abactor abaculus abacus abadite abaff abaft abaisance abaiser abaissed abalienate abalienation abalone abama abampere abandon abandonable abandoned abandonedly abandonee abandoner abandonment abanic abantes abaptiston abarambo abaris abarthrosis abarticular abarticulation abas abase abased abasedly abasedness abasement abaser abasgi abash abashed abashedly abashedness abashless abashlessly abashment abasia abasic abask abassin abastardize abatable abate abatement abater abatis abatised abaton abator abattoir abatua abature abave abaxial abaxile abaze abb abba abbacomes abbacy abbadide abbas abbasi abbassi abbasside abbatial abbatical abbess abbey abbeystede abbie abbot abbotcy abbotnullius abbotship abbreviate abbreviately abbreviation abbreviator abbreviatory abbreviature abby abcoulomb abdal abdat abderian abderite abdest abdicable abdicant abdicate abdication abdicative abdicator abdiel abditive abditory abdomen abdominal abdominales abdominalian abdominally abdominoanterior abdominocardiac abdominocentesis abdominocystic abdominogenital abdominohysterectomy abdominohysterotomy abdominoposterior abdominoscope abdominoscopy abdominothoracic abdominous abdominovaginal abdominovesical abduce abducens abducent abduct abduction abductor abe abeam abear abearance abecedarian abecedarium abecedary abed abeigh abel abele abelia abelian abelicea abelite abelmoschus abelmosk abelonian abeltree abencerrages abenteric abepithymia aberdeen aberdevine aberdonian aberia aberrance aberrancy aberrant aberrate aberration aberrational aberrator aberrometer aberroscope aberuncator abet abetment ablest abort abut ach ache acher achete achill achor acor acre acyl ad adad adat add addlings adet ala ama baa bafta balonea batea beta caba cha chilla cora crea da dad dada data each lacy orach rache saddling stable tables tabor tabu tade teache zoquean zoraptera zorgite zoril zorilla zorillinae zorillo zoroastrian zoroastrianism zoroastrism zorotypus zorrillo zorro zosma zoster zostera zosteraceae zosteriform zosteropinae zosterops zouave zounds zowie zoysia zubeneschamali zuccarino zucchetto zucchini zudda zugtierlast zugtierlaster zuisin zuleika zulhijjah zulinde zulkadah zulu zuludom zuluize zumatic zumbooruk zuni zunian zunyite zupanate zutugil zuurveldt zuza zwanziger zwieback zwinglian zwinglianism zwinglianist zwitter zwitterion zwitterionic zyga zygadenine zygadenus zygaena zygaenid zygaenidae zygal zygantra zygantrum zygapophyseal zygapophysis zygion zygite zygnema zygnemaceae zygnemales zygnemataceae zygnemataceous zygnematales zygobranch zygobranchia zygobranchiata zygobranchiate zygocactus zygodactyl zygodactylae zygodactyli zygodactylic zygodactylism zygodactylous zygodont zygolabialis zygoma zygomata zygomatic zygomaticoauricular zygomaticoauricularis zygomaticofacial zygomaticofrontal zygomaticomaxillary zygomaticoorbital zygomaticosphenoid zygomaticotemporal zygomaticum zygomaticus zygomaxillare zygomaxillary zygomorphic zygomorphism zygomorphous zygomycete zygomycetes zygomycetous zygon zygoneure zygophore zygophoric zygophyceae zygophyceous zygophyllaceae zygophyllaceous zygophyllum zygophyte zygopleural zygoptera zygopteraceae zygopteran zygopterid zygopterides zygopteris zygopteron zygopterous zygosaccharomyces zygose zygosis zygosperm zygosphenal zygosphene zygosphere zygosporange zygosporangium zygospore zygosporic zygosporophore zygostyle zygotactic zygotaxis zygote zygotene zygotic zygotoblast zygotoid zygotomere zygous zygozoospore zymase zyme zymic zymin zymite zymogen zymogene zymogenesis zymogenic zymogenous zymoid zymologic zymological zymologist zymology zymolyis zymolysis zymolytic zymome zymometer zymomin zymophore zymophoric zymophosphate zymophyte zymoplastic zymoscope zymosimeter zymosis zymosterol zymosthenic zymotechnic zymotechnical zymotechnics zymotechny zymotic zymotically zymotize zymotoxic zymurgy zyrenian zyrian zyryan zythem zythia zythum zyzomys zyzzogeton
```
Return
```
aal aam aba abac abaft abalone abate abet ablest abort abut ach ache acher achete achill achor acor acre acyl ad adad adat add addlings adet ala ama baa bafta balonea batea beta caba cha chilla cora crea da dad dada data each lacy orach rache saddling stable tables tabor tabu tade teache
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~25~~ ~~23~~ ~~22~~ ~~17~~ 16 [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")
Borrows ideas from [ngn's ngn/k solution](https://codegolf.stackexchange.com/a/165668/43319). And then -6 thanks to him. Also -1 by returning [an enclosed list as like H.PWiz](https://codegolf.stackexchange.com/a/165655/43319).
Anonymous tacit prefix function.
```
⊂∩¨1,.↓(∪≢,/,⍨)¨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FX06OOlYdWGOroPWqbrPGoY9WjzkU6@jqPeldoHlrxP@1R24RHvX2P@qZ6@j/qaj603vhR20QgLzjIGUiGeHgG/09TUE9MykktLlEHMfKLQHR6UWpqHpDOLMoGksUlIAVABpguhjDyi8B0SSKISi0qAtFlqRVAsjK/VB0A "APL (Dyalog Unicode) – Try It Online")
`(`…`)¨` apply the following tacit function to each word:
`,⍨` concatenate the word to itself
`≢,/` all word-length sub-strings (i.e. all rotations)
`∪` unique elements of those rotations (to prevent words like `tata` for appearing twice)
`1,.↓` the concatenation of the drop-firsts (the original words) of each list
`⊂∩¨` intersection of the the content of that and the entire original word list
---
### Old solution
-2 thanks to ngn.
Anonymous prefix lambda.
```
{⍵/⍨2≤+/⍵∊⍨↑(∪≢,/,⍨)¨⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR71b9R70rjB51LtEGMrY@6ugCch@1TdR41LHqUeciHX0dIF/z0AqgXO3/tEdtEx719j3qm@rp/6ir@dB6Y6BKIC84yBlIhnh4Bv9PU1BPTMpJLS5RBzHyi0B0elFqah6QzizKBpLFJSAFQAaYLoYw8ovAdEkiiEotKgLRZakVQLIyv1QdAA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` function where `⍵` is the word list:
`(`…`)¨` apply the following tacit function to each word:
`,⍨` concatenate the word to itself
`≢,/` all word-length sub-strings (i.e. all rotations)
`∪` unique elements of those rotations (to prevent words like `tata` for appearing twice)
`↑` mix the list of lists into a single matrix (pads with all-space strings)
`⍵∊⍨` indicate which elements of the matrix are members of the original list
`+/` sum the rows (counts occurrences of each of the original words)
`2≤` indicate which have duplicates (i.e. occur other than when rotated back to original)
`⍵/⍨` use that to filter the original list
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ṙ1$ƬfḊɗƇ
```
[Try it online!](https://tio.run/##y0rNyan8///hzpmGKsfWpD3c0XVy@rH2/w93bzncHvn/f2JSTmpxCVdiUn5RCVd6UWpqHldmUTZXcQlIggtMFoOo/CIgWZLIVZJaVJTIVZZawVWZXwoA "Jelly – Try It Online")
### Alternate version, 7 bytes
```
ṙƬ1fḊʋƇ
```
Dyadic `Ƭ` used to do something weird, so this didn't work when the challenge was posted.
[Try it online!](https://tio.run/##y0rNyan8///hzpnH1himPdzRdar7WPv/h7u3HG6P/P8/MSkntbiEKzEpv6iEK70oNTWPK7Mom6u4BCTBBSaLQVR@EZAsSeQqSS0qSuQqS63gqswvBQA "Jelly – Try It Online")
### How it works
```
ṙƬ1fḊʋƇ Main link. Argument: A (array of strings)
ʋ Vier; combine the 4 preceding links into a dyadic chain.
Ƈ Comb; for each string s in A, call the chain with left argument s and
right argument A. Keep s iff the chain returned a truthy value.
Ƭ 'Til; keep calling the link to the left, until the results are no
longer unique. Return the array of unique results.
ṙ 1 Rotate the previous result (initially s) one unit to the left.
f Filter; keep only rotations that belong to A.
s is a rotonym iff there are at least two rotations of s in A.
Ḋ Deque; remove the first string (s) of the result.
The resulting array is non-empty / truthy iff s is a rotonym.
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 20 bytes
Requires `⎕io←0`
```
⊂∩¨(,/(1↓∘∪⍳∘≢⌽¨⊂)¨)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkG/x91NT3qWHlohYaOvobho7bJjzpmPOpY9ah3M4jRuehRz95DK4BqNA@t0PyfBtTxqLcPqNnT/1FX86H1xo/aJgJ5wUHOQDLEwzP4f5qCemJSTmpxiTqIkV8EotOLUlPzgHRmUTaQLC4BKQAywHQxhJFfBKZLEkFUalERiC5LrQCSlfml6gA "APL (Dyalog) – Try It Online")
`(1↓∘∪⍳∘≢⌽¨⊂)¨` gets the unique rotations (excluding the string itself) of each string in the dictionary
`≢` takes the length of a vector
`⍳∘≢` creates the range from 0 up to the length
`⌽` rotates a vector some number of times, e.g 2⌽'abort' -> 'ortab'
`⍳∘≢⌽¨⊂` will then give all the rotations of a vector
`∪` removes the duplicates
`1↓` removes the first element (the original string)
`,/` flattens all the rotations into one list
`⊂∩¨` takes the intersection of the dictionary with the rotations
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 26 bytes
```
g;?z{tWl⟧₆∋I;W↺₍R;W≠&h∋R}ˢ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P93avqq6JDzn0fzlj5raHnV0e1qHP2rb9aipNwjI6FyglgEUC6o9vej//2ilxKSc1OISJR0gI78IRKcXpabmAenMomwgWVwCUgBkgOliCCO/CEyXJIKo1KIiEF2WWgEkK/NLlWL/RwEA "Brachylog – Try It Online")
```
g;?z % Zip the whole input with each word in it respectively
{ }ˢ % Apply this predicate to each pair in the zip
% and select the successful values
tW % Let the current word be W
l⟧₆∋I % There exists a number I from 1 to length(W)-1
;W↺₍R % And R is the result of circularly shifting the
% current word I times
;W≠ % And R is not the current word itself (needed for words like "tata")
&h∋R % And R is one of the input dictionary words
% (R is implicitly the output of the predicate, and
% successful R values are collected and output by the ˢ)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~73~~ ~~69~~ 67 bytes
```
lambda d:[w for w in d if{w[i:]+w[:i]for i in range(len(w))}-{w}&d]
```
[Try it online!](https://tio.run/##JcrBDsIgEATQX9mTQNSLxyZ@Se2BhqVurNAsVGwavh2hXuZNMrNs8endrdj7o8z6PRoNpusTWM@QgBwYILunnrrhnPqOhjZQG1i7CeWMTial8nVP@WSGsjC5CFbuQo8zhigutXhuTozoqsSvmiG2Qy2H4V88H0bdQObmB781N7@KrMoP "Python 2 – Try It Online")
Takes a set of words (lowercase), and returns a list of rotonyms.
---
Saved
* -2 bytes, thanks to ovs
[Answer]
# [K (ngn/k)](https://github.com/ngn/k), 23 bytes
```
{x^x^,/1_'(,/|0 1_)\'x}
```
[Try it online!](https://tio.run/##5Vjpbtw2EP7vpxCMArGBFEn@2o@SkyvOSszyUClys9o0fXV3LkpaI32CAtbMN7zm4HDI9enPOMSXl@PTz8uXy5e37z58ffPw9t3f77sPXx8/vbn8eilPP83TfXf/6eH90/3945f7T/H@rus6@F3jHx/hn/x07Mzzt3R6fvh2NM4/m2d4zo@ff92Vj5/pezEHD3PpzCHl0g0ZIHYun7q5UEfHdCaWMtJiugI5m@4Ml25J9e5m9m/m3JnO0J@nzzmkAb9IINuzQUUEfiR/JJCiUNc3zhMJFWhAOivqxD9D38HCyLyy2DMRaGge8YWZi62BkCN9hOe@zooK8xPTgoP8hvyiWKcVDAnx6nW2MOtExfHIlBd0s4k9CIIsfAZLwDtoRgnU5X2K3BjYkTBBZjFa6SbO0VYsiwkSQxlv/bmhAJFt4igjK8BmTwWdl7WzCYfEwHFXLmNOc8MOHTZ5h5vF3D@DUKtMbEEQYdYBzQCNxDw4ZqNQnTmuU8fd3NHfoDZiXdEZYezZzLs4z06sK5ho7srmlRa5orQtUMSkIr4iE2s0LrrhpSQnQPKtVNmaM9OLk5y5OFHBGilVOVcxS1LggCNamFlneYiR1tkJ27h2F1mYQC9IYnGARehcQIY6pqkIFTWpxOq94xRFYR7dRCjD2UkUGuSYqiAbqwI7v@LdKHH/QC19qj4F8tayidaQERayM1EBK7NSNCx6IjtBKLam0lrUAIHntZUtsQ5Yg1t71CqLAY7C9fwq4rArVntE8EvDiY5DdqKAG3rKGi4pKgMdGDdvDRh3t/UPgCVq05pG2pYMWCzC8qox3bRNaX6leu7TBDfSNrqMKWO52vTWzaKzGfaOpzPaKxljKxchYnFuoAhoTENetbzReKCijTQL1VIGPVijG6u4hhWTqXx4wA10snmzgPcaPB9T0E1A3oM2FOkP6O3IHjE@McDar@NL5roGaAfeRQPvK/DGUTxgcmVcgujIFjgZCJwdV1SE61JZR60@MVoaKgpK69PoNMhBZUFilTPmntQQwm0DIdfY0hZ4zaIFZ3d54u2FpB/pAyaZaWHBeU@MluiZ0JnrF2zEGFshON0SsN7FAWNiSZdHB/EKORj6joUo3SzEC1HApp7u0X6kD/Ugw9zqUIPpLP1Z@gjgUCALPZUuyr@xy2ztrEr/49VwqEiwNBXg0df0VwWM/xWXmDBahtBAe4/ceaHeKMdU1g6fiCes5Jx1O@zmsImKyzJhBiFaZ2aic6CF6agpa6LBJATF7phyUJwmtUAEWrJSqUcWLUk/HAkL3T3XinkImLsYcu9Q7LF84AlkhFtZFLlIndbSjKE4yB4t32Oyrjq6ua7VgzvRQD@679/NSMhFjCbyE@4LN1QmeNyZ0y13rYEuCuKHlHI9IWKtnPrIFg54nQy/Pq611IFiX2s@g7dkzRW1/jDx6gYyB93khxGCOPDRXRGHfBMKCaXIpMJFLe4gGbUMhonFaomHUiHtFyJ8BCl3dgVGRnmmsWTTANYcQlOasKqCDhDJ8XqsfZH8WoYIwTQuOy6Y8lVhuekgKdVdp45MByoV4w46cyOUVyKviPdJX2S1ZBEufgdFqQpuj/u9MIedlNpiCQsKAW8O@FAQ15P4mkIzRnOioWRq1ufcb9rWNaj1iLeNBLc14GO83LQEevN4Kv1bW8oHdztqnkaISXZWm/D9NWEt2I2STVXczJDV4UZSXSlPY3OMscaIhRaisPSguyBw19zGRKFQVQ/O3iFVgbnVMkRwm40CGrXvY/GmW11DrLZMHrWp81oOG9pWIimuUKMnUN1gYYNpG93UzwZLD/6GIoe1RVbXg4JbAzkowk1SmxjDCnODuGNxuBFcDau4dWjQCO7COWPuCir0k6pXeFFTNDalaV5HpIPUSsYaB3xHNbPU1WtajQiGvQxMeJVAZRUp6wj0Ymt8bQAJCWOZQ0hWD6I2JJ8G7WPE4RLMBjJcBCy6nF/mFRWdLJbpw4GR2LcGK2y5xxB3wZTWsTREYdEx8u5g5LZlm2a@x7zCcfWvQD@@wuqRSvMmiFdNHf8e8a3tKppLukh3zRyEDHLxLFnZwgwNCMy4eJaRM@iKKUrarleMOv72upP/H4T2e7/ffli3X8nyQvu/Pqnu/gU "K (ngn/k) – Try It Online")
`{` `}` is a function with argument `x`
`0 1_` cuts a string at indices 0 and 1, e.g. `"abcd"` -> `(,"a";"bcd")`
`|` reverses the two slices: `("bcd";,"a")`
`,/` joins them: `"bcda"`
`(,/|0 1_)\` returns all rotations of a string
`(,/|0 1_)\'x` are the rotations of each string in `x`
`1_'` drops the first "rotation" of each, i.e. each trivial identity rotation
`,/` join
`x^y` is the list `x` without elements of the list `y`
`x^x^y` is the intersection of `x` and `y`
[Answer]
# JavaScript (Node.js), ~~105~~ 99 bytes
```
f=l=>l.filter(w=>[...Array(k=w.length)].map((x,i)=>(w+w).substr(i,k)).some(r=>l.includes(r)&&r!=w))
```
Ungolfed:
```
f = list =>
list.filter( word =>
// create a list of all rotonyms for the current word
[ ...Array( len = word.length ) ]
.map( (x,i) =>
( word+word ).substr(i, len)
)
// check if any of the rotonyms is in the initial dictionary/wordlist
.some( rotonym =>
list.includes( rotonym )
// and is not the word itself
&& rotonym != word
)
```
[Try it online!](https://tio.run/##bVdpjus2DL7KdH4UCfqaG8wDeo6iPxSLsfWixdWSjH35KTfZzqBATH7Uwk0U7fwyD1OG7Ob6Z0wWvr5uH/7jp7/cnK@QT8@Pn39fLpe/cjbL6f7xvHiIY53O/1yCmU@nzx/u/PHz9Pzjeb6Udi01n9yP@xmFFOCUSZGLg28Wyimff/89//bxPJ@/hhRL8nDxaTzdTu/mzdDP0@Mc0oBPJJDtw@Q7g2fyNwIpCnVD57yRUIUOZLK9mSv@DD1XCxPzxuLARKChfcQXZi72AUKO7BEuQyuKKvM704qL/I78oli31ZSZN6@7hVknJm43pqzQFRMHEARZeAFLwDvoTglU9T5FHgwcSJghsxitTBM3V7@NiTJB4ijjfT53FCCyT5xlZBXY7bli8KI7m3BNDBxP5TrlVDp2GLDJB9w95vkCQq0y8QVBhKILugOaiTI6ZpNQ3TltW6fD3sm/oL5i0@iMMI6s8CmW4sS7ioXmVnav9sxVpV1BFZeqxIpMvNG86IHXmpwAqbfa5GgeTD@d1MynExNskUqVaxWrBG9PEbQws87yEiOjxQnbuU5XUUxgECS5uMIitFSQpY5pqkLFTKqxee@4RFEok5sJZXg4yUKHnFMV5GBV4OA3fFgl4V9pZEjNp0DRWnbRGnLCQnYmKmBj2DN4AiORkyAU@1DtI@qAwMc2yp5YB2zBbTPqlcUER@F6fxVx2hWrPyL4peNE1yE7McADA1UNtxSVgS6MK/sA5t3t8yNgi9qtpomOJQM2i7B8G0wvY3Mq30yXIc3wIu2r65Qytqvdbts9epjxGHh6oL9SMbZxEyIWSwdVQGea8qbtjdYDNW2kWai2MhjAGj1YxS1smFzlywNupJvNhwV81uD5moIeAvIBdKDKfMBoJ46I8Z0B9n5dXzP3NUA/8N018rkCHxzlA2ZXpyWIjWyBi4HAw3FHRbipyrpqi4nR0lFVUPucZqdDTioLkqucsfakhxDuBwi5xV62wDqrNhwv9yBlog3JMNEDTDLTyoLznhipGJjQnRsWHMQcWyG43RKw3sURc2LJlscA8RVyNfTcKlF6sxCvRAGHBnqPDhM9aAcZ1tYbWjBvln6WHgK4FMhDT62L6m96y@xtUaNvRTor00IMfUXakGBrqsCr1/RvA8z/iipmzJYhNNLZI3deqDfKsZR1wifiCTs5V90BuxJ2UXFdZqwgRNvOTLQEUkxXTVkXDRYhKHa3lIPiNKsHIpDKRq0eWbQkPR0JC7171oZ1CFi7mHLvUBywfeANZIRHWRW5SJPW0o6xOsgePT9i8q45enOtzYO700I/uV@/zETIRcwm8jueCw80JnjdmdNbbm2BXhTErynldkfEVrn0kS2c8DYb/vpYW20j5b61/ABvyZsVrT5NXN1I7mCY/GGEII58dTfEKd@FSkKtsqlyU4sHSE4to2FisVvipVRI54UIP4KUO7sBI6s801iz6QB7DqE5zdhVQReI5FgfW1@kvpYxQjCdy4kLpnpVWF8mSErtMKkr05VaxXSAzrwI9ZvIGvF9MlTRlizCxR@gGFXBHfFwFEo4SKkrS9hQCHhzxQ8FCT1JrCl0Z7QmOkqmZf2c@5@xTQeN3vBtI8ntA/gxXl9GAn3zeGr9@1jKV/e6qswTxCQnq0P4/TVjLziskkNV3N0Q7fAiqa2U56kHxlhzxEJPUVgG0FMQeBjua6JQaGoHdx@QmsDa6hUiuO9GAZ06zrH4Mq2hIVZfZo/WNHhthx3tmkiKG9TsCdQwWNhh2ld388Vg68H/UBSwjoh2vSh4NJCDIjwk9YkxbDB3iCcWxxfBtbCJ@4QmjeAhnQVrV1Clv1SDwk91RXNTu@VtRbpKr2SsecDvqO6WhrqmzYlgOMrAhLUEaqtI2UagL7bOtwGQlDCWPYREexCzIeE/XJ1jxOkSzA4yXAQsqs4vZUNVN4tn@uHASPzbkhX22mOIp2Bqn1g6orToGvnuYOR2td0yv8e8wmmLr8IwfcMakUplFySqbo7/j/g@torlmj5lumVOQgZ58SxZ2cIMHQjMuHnWiStoxRIla@uKWcf/Xu@XMuO34en97f18Pn/9Bw "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
εDvDÀ})ÙåO<Ā}Ï
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3FaXMpfDDbWah2ceXupvc6Sh9nD////R6olJOanFJeo6CkBWfhGYkV6UmpoHYmQWZYOo4hKQIhALzCiGsvKLIIySRDCdWlQEZpSlVoCoyvxS9VgA "05AB1E – Try It Online")
**Explanation**
```
ε } # apply to each word in the input
Dv } # for each letter in the word
DÀ # copy the previous word and rotate it left
)Ù # wrap the rotations in a list and remove duplicates
å # check each rotation for presence in the input
O # sum presences
<Ā # decrement the sum and truthify it (check if 1 or greater)
Ï # filter, keep words in input that are true in the resulting list
```
[Answer]
# [PynTree](https://github.com/alexander-liao/pyn-tree), 44 bytes
```
§y:f#x0€[x/|Ḟz&⁻xzėzḞw+#x`wLx#x`0wRLxy]y#\x1
```
[Try it online!](https://tio.run/##K6jM0y0pSk39H@D8/9DySqs05QqDR01roiv0ax7umFel9qhxd0XVkelVQE65tnJFQrlPBZA0KA/yqaiMrVSOqTD87/q/Wj0xKSe1uERdB8jILwLR6UAz84B0ZlE2kCwuASkAMsB0MYSRXwSmSxJBVGpREYguS60AkpX5peq1/3WBDkvMKy7IzEm1BQA "PynTree – Try It Online")
This turned out to reveal a major flaw in the way PynTree constructs list comprehensions because it uses functions to assign variables so that assignment can go in expressions, but then the conditions end up not having the value of the variable until after it has been evaluated and the main block has been evaluated. This appears to be easily fixable but I did not notice this earlier and so this answer is hideously long.
Actually even if I fixed that I think it still might be terribly long.
[Answer]
# [Perl 6](https://perl6.org), 65 bytes
```
{@^a.grep:{@a∋any(($/=[.comb]).rotate,*.rotate...^*eq$/).join}}
```
[Try it](https://tio.run/##LYzBCoJAFEX37ytmEaESz52LQvA/IuFpr7B0xt6M0iDug/6yH5k02px74cDpWdosDJbVmGF9AOi82tbmzCoPU1ESXoX7/VTQ5/Um7aNok@ZHrE1XnWIU48jxLvkfRCwTfmzSGG@m0fMc0JJXFyNqLUZto9nGgaqWrQOqjDhY8qyhkTtYtwr40a5jZKEjcCxCMPITvBm@ "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with placeholder parameter @a
@^a # declare and use placeholder parameter
.grep: # find the values that match
{
@a
∋ # Set contains operator
any( # create a junction of the following
# generate a sequence
(
$/ = # store into $/ (no declaration needed for this variable)
[ # turn into an array instead of a one-time sequence
.comb # the input split into characters
]
).rotate, # start the sequence on the first rotation
*.rotate # use this to generate the rest of the values in the sequence
...^ # keep generating values until: (and throw out last value)
* eq $/ # one of them matches the cached array of the input
).join # for each array in the junction join the strings (no spaces)
}
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~66~~ ~~55~~ 70 bytes
```
lambda d:{w for w in d for v in d if v not in w not in v in w*2in v*3}
```
[Try it online!](https://tio.run/##NczBDsIgDAbgV@kNXTzNm4lv4gUCKHHCUupwWfbsaItc@n9Nm39e6ZHiWP31Vif9MlaDvWwFfEIoECJY4dIY/E8xEW@lQ25lGJnDea8zhkjgD5vSZnKZ1AmUltGm0aZnV0L5uqNzkRHwyZGJG1iC/FfCBpI@coiCxX041vRW@7F@AQ "Python 2 – Try It Online")
11 bytes thx to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) to use chained `x in y in z` approach.
Takes a set of words `d`; returns a set of Rotonyms.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 131 bytes
```
($t=$args|%{@{r=0..($l=($k=$_).Length-1)|%{-join$k[-$_..($l-$_)]}
w=$_}})|%{$u=$_
$t|?{$u.w-ne$_.w-and$u.w-in$_.r}|%{$_.w}}|sort|gu
```
[Try it online!](https://tio.run/##5Vhfb9w2DH/OfQojuK4J1hy6vQcL0NcBG5a9FUOhsxlbiWy5@nOJr7nP3vGfbF/QfYIBOfJHiSIpiqbljP4ZQuzAuZvaB/i@fbj99v1qm263JrTx9d23u2/h9uNud7V1t1fbp9vtl@vd7zC0qbv55Rqnbx69HbZPn2@2X1gJ@fU/p80zKp5OpLDNCDfb9Pobwt3zzQCo@XxjhoZFXPxlF06kiMOn02v0Ib22@ftps7m72lTVh7urS7N3EFNl9jhXtQFgqGx4qmKiiYppJOYD0mSqBCGY6gAv1eTz5Yfq3MAPll1ez57qqt6bt67IxqJTGfpz9LMWaY@/gUBoDgbjIvDs3QMBPwi1deG8kFCCAmQyo1f8I@dm30DHPLNYMxFoaB3xiZkdygAhS/4IxzpHRYn5E9OESm5BblKsyxJmkHh2ulpYY8XFwwNTNmijGWoQBEF4hIaAs1CCEqjmnR94sOeN9CMEFodGponzySgWY4IkUMbLfCioh4Fj4iwjS8Bhjwk3L7aD6feegeWpkLrgY8EWN2zCCpeIeT6C0EaZxIJggKgKJQDNRGwts06oruzmpd1qbefOUNGYLVojjHcW@RRjtBJdwkKzRw4vlcwlpcVAkpCS7BWZRKN50QNPyVsBUm8py9EcmL5YqZkXKy7YI5Uq1ypWie854YgmZo1tWMXIaLTCFq7TSQwTqAVJLvYwCY0JRNUy9UmouPFpyM5ZLlEUYmdHQgEOVrJQIOdUBTlYFXjzM15pyfb3NFL77HxPu204xMZQEA0EawYF7KyRBtPgTuQkCA1lKJURDUDgYR7lSBoL7MHOMxpVgwkehOvzq4jTrljjEcFNBXt6HIIVBzxQU9VwS1EZ6IGxcRnAvNtlvgVsUYtX39GxBMBm0U9vBv3Z2OjjG9ex9iOcSYt26nzAdrX4zUtEB9OuN@4PGK9UTJO5CREbYgFJQGGa8qztjfSBmjbSIFRbGdTQGD1YxbmfMYXKDw/Ylp5sPizgswbHjynoISCvQQeSzPe42453xPiJAfZ@1U@B@xpgHPjqavlcgQ@O8gGjTd3Ui4/QABcDgYPljopwNhVUa94To6mgpCCVOc1OgZxUFiRXIWDtSQ8hXA4QQh5K2QLbTNpwVi9afHshqTv6AZPANLFgnSNGJmom9MzVEw5ijhshuLwh0Dg7tJiThnw53CC@QvaGfg@JKL1ZiCeigEM1vUfrjn7oBxnWVoUeTNXQX0M/AqgKFKGj1kX111WBo43q9D8uGfuMBFtTAtY@@q8ZMP9HNDFitgyhls4euXVCnVGOpawTzhP32Mm56lbYxn4RFadpxApCNK8MRGNPhulRU1ZEg0UIiu2DD71iP2oEIpDJTK0e2dCQ9GxJmOjdc8xYh4C1iyl3FsUa2wc@gYzwKJMiO9Bk09CKNlkIDiNfY4ouW3pzHbMD@0SKrrOPj6YjZAfMJvInPBceyEzwcWdOb7lj7ulFQXzvfchPiNgrlz6yiROeR8O3j2NOuaXc5xwO4BqK5ohen81wtC2Fg9vkixGCoeVHd0ac8kVIJKQkixI3tWEFKaipNUwa7Jb4UCqk80KElyDltpmBES3HdEjBFIA9h9DoR@yqoAoiWbbH3iepr6kdoDeFy4kLpnpVmM4mSPJ5Namafk@toltBa86E9EZki/g@qZNY8w3Cya2gOFXBrnG9FmK/knwx5rGhEHBmjxcF2bqXvfq@BKM1UZA3Oeh17gdjsw0afcC3jSS3DOBlPJ2N9HTncdT6lzEf9vZcK44dDF5OVofw/jViL1hpyaEqLmGIdTiT1JcPY1c2xlhzxEJJUT/VoKcgcDVcdAahkNUPrl4hdYG1VSpEcFmNAga1nmPxbFq3hlhjGR16081rOyxosUTSMEPNnkDdBgsL9It2cR8Nth78hqIN64hY1wcFjwZCrwgPSWNiDDMMBeKJDe2ZYHM/i8uEJo3gKp0Ra1dQok@qWuGLhqK5ScXzrOH30isZax7wHlXC0q0e/RxEb3iXPRO20lNbRco@erqxFT4PgKSEsawhJNZ7cdt751udY8TpEswBMpwETGrOTXFGSRdLZHpxYCTxzcnql9pjiKdgUpmYCqK0qI7cOxjZxWzxzO8xp7Cb95eg7t5g3ZFKcRFkV8Udf4@4MnYUz8m/yHQOnIQA8uKZgrKJGQbQM@PmmTquoCOWKHk7HjHr@O3F/5Tg/wT05ZO/Xr6ty4eyXNL@r7eqy@vNdfVavau@bS622NrSJ6z7D9UWXkb8@MCb@G21/bKauh/xtk2DZaC6iTx0WV2iWoCYHc3/tH2o7s4WbS4@/3n/KUd86v7YP6Lxf@7Q58U9Xmzog/R25fMGvlZXxRb/86t6X72/Ru2/i9dVBLv7vL/HC9zQXn38UP368br6ubrc7XYYz8VfJR61trk4bU6b7/8C "PowerShell Core – Try It Online")
For each word in the list, create generate a list of all its rotations
Then look for a matching rotation with a different original word
If it exists, keep the word.
Then sort and deduplicate them.
Sorting is required in PowerShell as `Get-Unique` only works on sorted lists.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~71~~ 62 bytes
```
^(\w)(\w*)
$2$1!¶$&
%+)s`^(.+)(!.*¶\1)$
$2
O`
!`\b(.+)(?=¶\1!)
```
[Try it online!](https://tio.run/##HYlRCsIwFAT/9xaBKHktFOq/eAQvEEoSCFKUBl6eVS/WA/RiMenHzsIMR5kXX8pk7IfqOoK@6FHtmz7j1FN2kxl6Mmro9s2OpGvG3UE5G45wuzavqBQfXjELfEgseHCMC2Z@IksLOJjbJa4UD4nMHmv84pfefw "Retina 0.8.2 – Try It Online") Explanation:
```
%+)
```
Repeat for each word.
```
^(\w)(\w*)
$2$1!¶$&
```
Prepend the next rotation of the word with a trailing `!`.
```
s`^(.+)(!.*¶\1)$
$2
```
But if that's the original word, then delete it again.
```
O`
```
Sort the words.
```
!`\b(.+)(?=¶\1!)
```
Find the duplicates.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 bytes
*Extremely* slow, but works. TIO times out, but I confirmed it works by manually lowering the number of iterations in the language source.
```
f@_XéZ ÀX©UøXéZ}a
f@ // Filter the input array by
_ }a // generating up to 1e8 rotations of each string
XéZ ÀX // and checking if the rotation is different than the original,
©UøXéZ // yet still exists in the input array.
```
[Try it online!](https://tio.run/##y0osKPn/P80hPuLwyiiFww0Rh1aGHt4B4tQm/v8frV5ckpiUk6quow6miyEM9VgA "Japt – Try It Online")
[Answer]
## Javascript, 129 Chars
```
f=a=>{n={};r=w=>w.slice(1,w.length)+w[0];a.map(w=>{m=r(w);while(m!=w){if(-~a.indexOf(m))n[m]=1;m=r(m);}});return Object.keys(n);}
```
## Ungolfed
```
f=a=>{
n={};
r=w=>w.slice(1,w.length)+w[0];
a.map(w=>{
m=r(w);
while(m!=w){
if(-~a.indexOf(m))n[m]=1;
m=r(m);
}
});
return Object.keys(n);
}
```
[Try it online!](https://tio.run/##JYpRrsIgEEW34uvXEJXoN8EtuICmH1inFYWhGVA0Td/W@8D3c89J7rmbl4k92yntKVxxXQdt9GkmPS@KddanLKOzPcJxl6VDGtNNbHN76JSR3kxQitlrhixUvlmH4H90FrMdYP9rpKUrvs8DeCGo9Z0@qtp6oZZFKMb0ZNqcL3fsk3zgJwKVZ@0DxeBQujDCAG1jLg5janZFAleOjEiFlh9lY6pBkS/jvwT@MpkKZK584bvsJzybTgi1/gE)
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 144 bytes
```
l->{for(var s:l){var r=s;for(int i=s.length();i-->1;){r=r.substring(1)+r.charAt(0);if(!r.equals(s)&l.contains(r)){System.out.println(s);i=0;}}}}
```
[Try it online!](https://tio.run/##bVA9b8IwEN35FVeGym6NBWtDIiHWdmKsOpjUCQbHTu/OqCjit1MnqFPr4d35vXcfuqM5m8Xx83RzXR@R4Zj/OrHz@qmY/eGaFGp2MfwrEqM13SjV3hDBm3EBhhlAn/be1UBsOIdzdJ/QZU3sGF1o3z/AYEtysgJsY6DUWVxvo/d2mra@G6sKGihvflENTURxNgj04uUwJlhSMZIuMLiStLeh5YOQhVssqlUhByxRU9rT1Ems5DPq@mBww2KZTY14QG2/kvEkSD56XcfAeUUSKOWwuxDbTsfEus/l7EM2Fa5cFtf8bsW09wSvjvh3W/BQwgbRXEgbGhUxN3tviZXZ58upFq0NyuFJ5ctkQU1IY4iYkY1im@vV2X6rS0xzTb13uYuaS3kf2mhT17Zn4SfiOrvefgA "Java (JDK 10) – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~100~~ 94 bytes
```
x=>x.Where(y=>y.Select((z,i)=>x.Where(c=>c!=y).Contains(y.Remove(0,i)+y.Remove(i))).Any(b=>b))
```
[Try it online!](https://tio.run/##dZJNT8MwDIbP7a8IOyViRNy7Vpr4lkBC7LBzmpktok3AScsK2m8v7lgBTUGqVPl9XsdObO3PtEPoG2/smi06H6DO0r@RvHBVBToYZ728AQto9JHj3ti3LE11pbxnj@jWqOr0M01em7IymvmgAv1aZ1bsQRnLRZoQTVqFLIAPlyooljML7@xW@c0CwswHpPMLLjLyjR45X634RJUVxZMocRgFawSwMWDwJSZTw1QkRvbA/0McxkFQUR0Qo6CFbUzuXPMt03fdWD07eqvp3ZVtasChw1ErGLrgBje975Dab/NiK5cbQOBdXnRyAcNsOf@YGvGLdF7ok7wTNHsbaGKed/IJatcCPyfj6U9khBBybjte5kUpRJ8k2WGwCL6pApUdO@DjdfaXeKalU3rDBys1y4w9ZNBuJAmV9a4CuUQTgLYLOHmGvF26678A "C# (.NET Core) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 66 bytes
```
s=>s.filter(t=>s.some(u=>(t+t).match(u)&&t!=u&t.length==u.length))
```
[Try it online!](https://tio.run/##bVdpcus2DL5K@udNMp3mBnlnCS3CEl@4qCToRL58io2SnOmMBXwAFywEIfmPu7k21bDiP7l4@L6@fbe33@31GiJCfUbGrSR47m@/n/FvfHlNDqflub/8@oV/vfVf@Bohz7i8vXVDLy/fU8mtRHiNZX6@Pr@7J8e/yE8IRBM9mUH1N1c/BHyWeGVQstIwDS4LGSEMoIP9yV3o5/i5eFiEdxEnIQodr2O@CQt5KBgFtse4Tb0ZQuEfQpEmxQPFzbAtw1KF92irlfmgJq5XobJhaC5PoAiq8gaeQQwwnFJo28eSRZkkkLRCFTF7HWbuLnHX6WaK1FHBx3gdKEEWnyTLxBDE7RUpeN27unQpAoIMVVxqaQMHCtjVEx4ey3gDpd6Y@kIgQ7MJwwHLRJuDsEWprVz2pctp7RIf0Jix7xicMomsySm2FtQ7pEILd3EPR@bQ6NgA1SXUWImpN5YXO3DEEhRovWHXo7kJ/QpaM19BTYhFLlWpVaoSulFN0SbMBy9TnGpbUHZwG0bdmMGkSHNxgU1pQ9CpQWhBpWqmYO4xBilREtoSVkYVbkGzMKDk1AQ9WBMk@B2fZmn4F9ZMpceSOFovLnrHTniowWUDYsyDXDRPkehJMMpDhUNjDii87VrxxAcQC2EfMa88JTgrt/trSNJu2PxRIW4DF74ONagBUUxcNdJSTAa@MKEdCsp7OMZnoBZ1WC0LH0sFahZp@6EsD7q1tB@m21RWeJCO2biUSu3qsNsPj25uPgdebuSvVozv0oSY5TYAKhjMUt6tvfF84KZNtCq1VgYTeGcHa7inHbOrcnkgzHyz5bBAzhqiXFOwQyA@gSlQxxNFu0hEgj8EUO@3@VilrwH5Uaub5VxBDo7zAWvAZUtqo3qQYmBwC9JRCe5bVZu1xyRoGwgN4Biz7AwoSRVBc1Ur1Z72EMbjAKH2PMoWZE@0hhP1HpTKtBOZFn5ASBWKIoQYmfEWkxC@c9NGSsqxV0LLPQMfQ54pJ55tRQqQXiEXx88VmfKbhTkyBVJN/B6dFn7IDjGqrSey4J48/zw/DGgqsIeRWxfX3/JUxdtmRp@adlahjRn5SrQTodaEILPv5d8OlP87bbFSthyjmc@eeIhKozNOpWwDsTAv1Mml6k44tHSIhnFbqYII7Ssr05Z4Y75qxoboqAjBcLiWmgyX1TxQgbfs3OqJZc/SZ2Bh43fPvVMdAtUupTwGEidqH3QDBdFRoqGQedB7XjFjgBrJ8zNm73rgN9e9RwgfPDEu4c8ftzAKmbJJ/IPORRRdCF134fyWu/fELwrml1Jq/yAkVqX0iW2S8L46@fq4d@wz5773eoPo2Zs7Wf10@R5mdofClA8jAnmWq7sjSfkhIAuIugilqeUTZKe22Qnx1C3pUhrk8yJEH0HGg9@B01lRaMbqBqCew2gtK3VVsAkqBdlPrG9aX9ucIbnB9cQVc70axIcBlko/DdrMcuFWsZxgcA8C/hBlR3qfTKi7FU9wiyeoRk0IZzydhZZOUhmbFWooDKK70IeChl401pKGM1YTAxXXq33O/Y9u34O1V3rbaHKHgj7G8UGT@Jsncus/dKVewuOsti6Qi56sqej7a6VecJqlh2p4uKG7w4NktkpdlxGYYMuRCCNFaZvATkHhST3mZKXQzQ6tPiEzQbU1KkTxWE0COXUeE/Fh2EIjbL6skaxZ8NYOBzp2Yinv0LKn0MIQ4YDlmD3MN0eth/5DccCm0d3totDRQE2G6JDMJ8GwwzognVieH4TQ0y4eA5Y0hqd0NqpdRch/qSaDX@aK5QaH5X1GuWivFGx5oO@o4ZaFei@7E8lJlEmI7JK4rRIVG4m/2AbfFaApEaxrGOnuSc2mQv9wbUyQpEuxOChwU7DZdnFrO0JbrJ7Zh4Mg9W9PVjpqTyCdgsMxsA3EabE5@t0hKBzbDsvyHosGlz0@hGn5gS0ik9ohaFTDnPwfiUN3V8tYvnS4V0lCBX3xbNXYJowcSMKkeeIiFXSnEmVr9ztlnf57vb@2lb4N35/eX16@/wM "JavaScript (Node.js) – Try It Online")
boring answer
[Answer]
# [Ruby](https://www.ruby-lang.org/), 81 bytes
```
->a{a.select{|w,*b|w.scan(/(?=.)/){b<<$'+$`}
b[1..].any?{_1!=w&&a.include?(_1)}}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVjJktxEEL1z4hOGCGNswOPwjYONb75x4OxwmJIqu1WeWkQtPaMez5dwcRDwUfA15FaSeoKIUebLWnKrrJR6_vgrt2H58ue7N3-3enjx0z-_vvjZ3JvrAh7Gev_59sfvh8-312U08dnLZ2_fXD9_-fx-eP36yXc_PPnt4avh_avr6w_XJi5v7z---ubN7dOn5trF0TcLb599fPX84eFBFP_79S_z1bv3396-N1eG_jw9ziEN-EQC2Z5MvmFwm_yBQIpC3dg5byRUoQOZbFdmwD9Dz2BhYt5YHJkINLSP-MLMxT5AyJE9wmVsRVFlfsO04iK_Ib8o1m01ZebN625h1omJw4EpK3TFxBEEQRZewBLwDrpTAlW9T5EHAwcSZsgsRivTxM3g1zFRJkgcZbzN544CRPaJs4ysArs9VwxedGcThsTA8VSuU06lY4cBm7zD3WOeLyDUKhNfEEQouqA7oJkoR8dsEqo7p3XrtNs7-QvUV6wanRHGkRU-xVKceFex0NyZ3as9c1VpV1DFpSqxIhNvNC964LUmJ0DqrTY5mhPTOyc1c-fEBFukUuVaxSpJgROOaGFmneUlRkaLE7Zxna6imMAoSHIxwCK0VJCljmmqQsVMqrF577hEUSiTmwllODnJQoecUxXkYFXg4Fe8WyXhDzQypuZToGgtu2gNOWEhOxMVsDELfNEsRiInQSj2odpH1AGBp3WUPbEO2IJbZ9QriwmOwvX-KuK0K1Z_RPBLx4muQ3ZigAdGqhpuKSoDXRhXtgHMu9vmj4AtarOaJjqWjN01heXRYLoYm1N5ZLqMaYYLaVtdp5SxXW122-bRyRz3gacT-isVYxs3IWKxdFAFdKYpb9reaD1Q00aahWorgxGs0YNV3MKKyVW-POCOdLP5sIDPGjxfU9BDQD6CDlSZDxjtxBExvmGAvV_X18x9DdCPnM2RzxX44CgfMLs6LUFsZAtcDAROjjsqwlVV1lVrTIyWjqqC2uc0Ox1yUlmQXOWMtSc9hHA_QMgt9rIF1lm14Xi5BykTbUjGiR5gkplWFpz3xEjFyITu3LjgIObYCsHtloD1Lh4xJ5ZseQwQXyGDoedQidKbhXglCjg00nt0nOhBO8iwtq7Qgrmy9GfpIYBLgTz01Lqo_qarzN4WNXpVpLMyLcTQV6QNCbamCrz6nH5vgPk_o4oZs2UIHenskTsv1BvlWMo64RPxhJ2cq26HXQmbqLguM1YQonVnJloCKaarpqyLBosQFLtDykFxmtUDEUhlo1aPLFqSbh0JC717zg3rELB2MeXeoThi-8AbyAiPsipykSatpR3H6iB79HyPybvm6M11bh7cDS30k_v0yUyEXMRsIr_Bc-GBxgSvO3N6y51boBcF8SGl3G4QsVUufWQLJ7zNhr8-zq22I-W-tXwCb8mbM1q9NfHsjuQOhskfRgjika_uijjlm1BJqFU2VW5qcQfJqeVomFjslngpFdJ5IcKPIOXOrsDIKs801mw6wJ5DaE4zdlXQBSI51sfWF6mv5RghmM7lxAVTvSqsFxMkpbab1JVpoFYx7aAzF0J9JLJGfJ-MVbQli3DxOyhGVXB7PO6FEnZS6soSNhQC3gz4oSChJ4k1he6M1kRHybSsn3P_M7bqoNEDvm0kuX0AP8brxUigbx5PrX8bS3lwl6vKPEFMcrI6hN9fM_aC3So5VMXdDdEOF5LaSnmeemCMNUcs9BSFZQQ9BYG74b4mCoWmdnD3DqkJrK1eIYL7bhTQqf0cixfTGhpi9WX2aE2D13bY0aaJpLhCzZ5ADYOFDaZtdTdfDLYe_A1FAeuIaNeLgkcDOSjCQ1KfGMMKc4d4YvF4IbgWVnGb0KQR3KWzYO0KqvSTalR4p65obmq3vK5Ig_RKxpoH_I7qbmmo57Q6EQxHGZiwlkBtFSnbCPTF1vk6AJISxrKHkGgPYjYkn446x4jTJZgdZLgIWFSdX8qKqm4Wz_TDgZH4tyYrbLXHEE_B1D6xdERp0TXy3cHIbWq7ZX6PeYXTGl-FcXqENSKVyiZIVN0c_x7xfewslmu6k-mWOQkZ5MWzZGULM3QgMOPmWSeuoDOWKFk7nzHr-Nvrwwf5r8KXL8L_Aw)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
¬£éYÃøWkU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&code=rKPpWcP4V2tV&input=WyJhYmxlc3QiLCJhYm9ydCIsImdyZWVuIiwiaXJrIiwic3RhYmxlIiwidGFibGVzIiwidGFib3IiLCJ0YXRhIiwidGVycmEiLCJ2ZXgiLCJ5b3UiXQ)
```
¬£éYÃøWkU :Implicit filter of each string U in input array W
¬ :Split
£ :Map each element at 0-based index Y
éY : Rotate U right Y times
à :End map
ø :Does that contain any element of
WkU : W with U removed
```
] |
[Question]
[
>
> In probability theory, the [normal (or Gaussian) distribution](https://en.wikipedia.org/wiki/Normal_distribution) is a very common continuous probability distribution. Normal distributions are important in statistics and are often used in the natural and social sciences to represent real-valued random variables whose distributions are not known.
>
>
>
## The challenge
Your challenge is to plot the [probability density](https://en.wikipedia.org/wiki/Probability_density) of the Gaussian Distribution [on a 3-dimensional plane](https://en.wikipedia.org/wiki/Gaussian_function#Two-dimensional_Gaussian_function). This function is defined as:

Where:



**A** = 1, **σx** = **σy** = **σ**
## Rules
* Your program must take one input **σ**, the standard deviation.
* Your program must print a 3D plot of the Gaussian Distribution in the highest quality as your language/system allows.
* Your program may not use a direct Gaussian Distribution or probability density builtin.
* Your program does not have to terminate.
* Your plot may be in black and white or color.
* Your plot must have grid lines on the bottom. Grid lines on the sides (as shown in the examples) are unnecessary.
* Your plot does not need to have line numbers next to the grid lines.
## Scoring
As usual in [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the submission with the least bytes wins! I may never "accept" an answer using the button, unless one is incredibly small and intuitive.
## Example output
Your output could look something like this:

Or it could look like this:

[More](http://www.librow.com/content/common/images/articles/article-9/2d_distribution.gif) [valid](https://rltangblog.files.wordpress.com/2012/07/mv-basic-bivariate-gaussian-plot-simu001-scatterplot3d-sigma-12-0-5.jpeg) [outputs](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQAZBSbw7AeVGgxGGBt0S7Dfp0lvKzg6aoki9FC-X3A42epv2TCEg). [Invalid](http://www.librow.com/content/common/images/articles/article-9/normal_distribution.gif) [outputs](https://i.stack.imgur.com/uwja1.png).
[Answer]
# C++, ~~3477~~ 3344 bytes
Byte count does not include the unnecessary newlines.
MD XF golfed off 133 bytes.
There's no way C++ can compete for this, but I thought it would be fun to write a software renderer for the challenge. I tore out and golfed some chunks of [GLM](http://glm.g-truc.net/0.9.8/index.html "GLM") for the 3D math and used [Xiaolin Wu's line algorithm](https://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm "Xiaolin Wu's line algorithm") for rasterization. The program outputs the result to a PGM file named `g`.
[](https://i.stack.imgur.com/A5xgj.png)
```
#include<array>
#include<cmath>
#include<vector>
#include<string>
#include<fstream>
#include<algorithm>
#include<functional>
#define L for
#define A auto
#define E swap
#define F float
#define U using
U namespace std;
#define K vector
#define N <<"\n"
#define Z size_t
#define R return
#define B uint8_t
#define I uint32_t
#define P operator
#define W(V)<<V<<' '
#define Y template<Z C>
#define G(O)Y vc<C>P O(vc<C>v,F s){vc<C>o;L(Z i=0;i<C;++i){o\
[i]=v[i]O s;}R o;}Y vc<C>P O(vc<C>l, vc<C>r){vc<C>o;L(Z i=0;i<C;++i){o[i]=l[i]O r[i];}R o;}
Y U vc=array<F,C>;U v2=vc<2>;U v3=vc<3>;U v4=vc<4>;U m4=array<v4,4>;G(+)G(-)G(*)G(/)Y F d(
vc<C>a,vc<C>b){F o=0;L(Z i=0;i<C;++i){o+=a[i]*b[i];}R o;}Y vc<C>n(vc<C>v){R v/sqrt(d(v,v));
}v3 cr(v3 a,v3 b){R v3{a[1]*b[2]-b[1]*a[2],a[2]*b[0]-b[2]*a[0],a[0]*b[1]-b[0]*a[1]};}m4 P*(
m4 l,m4 r){R{l[0]*r[0][0]+l[1]*r[0][1]+l[2]*r[0][2]+l[3]*r[0][3],l[0]*r[1][0]+l[1]*r[1][1]+
l[2]*r[1][2]+l[3]*r[1][3],l[0]*r[2][0]+l[1]*r[2][1]+l[2]*r[2][2]+l[3]*r[2][3],l[0]*r[3][0]+
l[1]*r[3][1]+l[2]*r[3][2]+l[3]*r[3][3]};}v4 P*(m4 m,v4 v){R v4{m[0][0]*v[0]+m[1][0]*v[1]+m[
2][0]*v[2]+m[3][0]*v[3],m[0][1]*v[0]+m[1][1]*v[1]+m[2][1]*v[2]+m[3][1]*v[3],m[0][2]*v[0]+m[
1][2]*v[1]+m[2][2]*v[2]+m[3][2]*v[3],m[0][3]*v[0]+m[1][3]*v[1]+m[2][3]*v[2]+m[3][3]*v[3]};}
m4 at(v3 a,v3 b,v3 c){A f=n(b-a);A s=n(cr(f,c));A u=cr(s,f);A o=m4{1,0,0,0,0,1,0,0,0,0,1,0,
0,0,0,1};o[0][0]=s[0];o[1][0]=s[1];o[2][0]=s[2];o[0][1]=u[0];o[1][1]=u[1];o[2][1]=u[2];o[0]
[2]=-f[0];o[1][2]=-f[1];o[2][2]=-f[2];o[3][0]=-d(s,a);o[3][1]=-d(u,a);o[3][2]=d(f,a);R o;}
m4 pr(F f,F a,F b,F c){F t=tan(f*.5f);m4 o{};o[0][0]=1.f/(t*a);o[1][1]=1.f/t;o[2][3]=-1;o[2
][2]=c/(b-c);o[3][2]=-(c*b)/(c-b);R o;}F lr(F a,F b,F t){R fma(t,b,fma(-t,a,a));}F fp(F f){
R f<0?1-(f-floor(f)):f-floor(f);}F rf(F f){R 1-fp(f);}struct S{I w,h; K<F> f;S(I w,I h):w{w
},h{h},f(w*h){}F&P[](pair<I,I>c){static F z;z=0;Z i=c.first*w+c.second;R i<f.size()?f[i]:z;
}F*b(){R f.data();}Y vc<C>n(vc<C>v){v[0]=lr((F)w*.5f,(F)w,v[0]);v[1]=lr((F)h*.5f,(F)h,-v[1]
);R v;}};I xe(S&f,v2 v,bool s,F g,F c,F*q=0){I p=(I)round(v[0]);A ye=v[1]+g*(p-v[0]);A xd=
rf(v[0]+.5f);A x=p;A y=(I)ye;(s?f[{y,x}]:f[{x,y}])+=(rf(ye)*xd)*c;(s?f[{y+1,x}]:f[{x,y+1}])
+=(fp(ye)*xd)*c;if(q){*q=ye+g;}R x;}K<v4> g(F i,I r,function<v4(F,F)>f){K<v4>g;F p=i*.5f;F
q=1.f/r;L(Z zi=0;zi<r;++zi){F z=lr(-p,p,zi*q);L(Z h=0;h<r;++h){F x=lr(-p,p,h*q);g.push_back
(f(x,z));}}R g;}B xw(S&f,v2 b,v2 e,F c){E(b[0],b[1]);E(e[0],e[1]);A s=abs(e[1]-b[1])>abs
(e[0]-b[0]);if(s){E(b[0],b[1]);E(e[0],e[1]);}if(b[0]>e[0]){E(b[0],e[0]);E(b[1],e[1]);}F yi=
0;A d=e-b;A g=d[0]?d[1]/d[0]:1;A xB=xe(f,b,s,g,c,&yi);A xE=xe(f,e,s,g,c);L(I x=xB+1;x<xE;++
x){(s?f[{(I)yi,x}]:f[{x,(I)yi}])+=rf(yi)*c;(s?f[{(I)yi+1,x}]:f[{x,(I)yi+1}])+=fp(yi)*c;yi+=
g;}}v4 tp(S&s,m4 m,v4 v){v=m*v;R s.n(v/v[3]);}main(){F l=6;Z c=64;A J=g(l,c,[](F x,F z){R
v4{x,exp(-(pow(x,2)+pow(z,2))/(2*pow(0.75f,2))),z,1};});I w=1024;I h=w;S s(w,h);m4 m=pr(
1.0472f,(F)w/(F)h,3.5f,11.4f)*at({4.8f,3,4.8f},{0,0,0},{0,1,0});L(Z j=0;j<c;++j){L(Z i=0;i<
c;++i){Z id=j*c+i;A p=tp(s,m,J[id]);A dp=[&](Z o){A e=tp(s,m,J[id+o]);F v=(p[2]+e[2])*0.5f;
xw(s,{p[0],p[1]},{e[0],e[1]},1.f-v);};if(i<c-1){dp(1);}if(j<c-1){dp(c);}}}K<B> b(w*h);L(Z i
=0;i<b.size();++i){b[i]=(B)round((1-min(max(s.b()[i],0.f),1.f))*255);}ofstream f("g");f
W("P2")N;f W(w)W(h)N;f W(255)N;L(I y=0;y<h;++y){L(I x=0;x<w;++x)f W((I)b[y*w+x]);f N;}R 0;}
```
* `l` is the length of one side of the grid in world space.
* `c` is the number of vertices along each edge of the grid.
* The function that creates the grid is called with a function that takes two inputs, the `x` and `z` (+y goes up) world space coordinates of the vertex, and returns the world space position of the vertex.
* `w` is the width of the pgm
* `h` is the height of the pgm
* `m` is the view/projection matrix. The arguments used to create `m` are...
+ field of view in radians
+ aspect ratio of the pgm
+ near clip plane
+ far clip plane
+ camera position
+ camera target
+ up vector
The renderer could easily have more features, better performance, and be better golfed, but I've had my fun!
[Answer]
# Mathematica, 47 bytes
```
Plot3D[E^(-(x^2+y^2)/2/#^2),{x,-6,6},{y,-6,6}]&
```
takes as input σ
**Input**
>
> [2]
>
>
>
**output**
[](https://i.stack.imgur.com/fBFlu.jpg)
*-2 bytes thanks to LLlAMnYP*
[Answer]
# [Gnuplot](http://gnuplot.sourceforge.net) 4, ~~64~~ ~~62~~ ~~61~~ ~~60~~ 47 bytes
*(Tied with [Mathematica](https://codegolf.stackexchange.com/a/123068/52405)! WooHoo!)*
```
se t pn;se is 80;sp exp(-(x**2+y**2)/(2*$0**2))
```
Save the above code into a file named `A.gp` and invoke it with the following:
`gnuplot -e 'call "A.gp" $1'>GnuPlot3D.png`
where the `$1` is to be replaced with the value of `σ`. This will save a `.png` file named `GnuPlot3D.png` containing the desired output into the current working directory.
Note that this *only* works with distributions of Gnuplot 4 since in Gnuplot 5 the `$n` references to arguments were deprecated and replaced with the unfortunately more verbose `ARGn`.
**Sample output with `σ = 3`:**
[](https://i.stack.imgur.com/SPyvS.png)
This output is fine according to [OP](https://codegolf.stackexchange.com/questions/123039/plot-the-gaussian-distribution-in-3d/123062?noredirect=1#comment302867_123062).
---
# [Gnuplot](http://gnuplot.sourceforge.net) 4, Alternate Solution, 60 bytes
Here is an alternate solution which is much longer than the previous one but the output looks much better in my opinion.
```
se t pn;se is 80;se xyp 0;sp exp(-(x**2+y**2)/(2*$0**2))w pm
```
This still requires Gnuplot 4 for the same reason as the previous solution.
**Sample output with `σ = 3`:**
[](https://i.stack.imgur.com/nj3HB.png)
[Answer]
# R, ~~105~~ ~~102~~ ~~87~~ 86 bytes
```
s=scan();plot3D::persp3D(z=sapply(x<-seq(-6,6,.1),function(y)exp(-(y^2+x^2)/(2*s^2))))
```
Takes Sigma from STDIN. Creates a vector from `-6` to `6` in steps of `.1` for both `x` and `y`, ~~then creates an `121x121` matrix by taking the outer product of `x` and `y`. This is shorter than calling `matrix` and specifying the dimensions. The matrix is now already filled, but that's ok, because we are overwriting that.~~
The `for`-loop loops over the values in `x`, making use of the vectorized operations in `R`, creating the density matrix one row at a time.
`(s)apply` again is a shorter method for vectorized operations. Like the hero it is, it handles the creation of the matrix all by itself, saving quite a few bytes.
[](https://puu.sh/w2x3b/c6da2e2fdf.png)
## ~~128~~ ~~125~~ ~~110~~ 109 bytes, but way more fancy:
This plot is created by the `plotly` package. Sadly the specification is a bit wordy, so this costs a lot of bytes. The result is really really fancy though. I would highly recommend trying it out for yourself.
```
s=scan();plotly::plot_ly(z=sapply(x<-seq(-6,6,.1),function(y)exp(-(y^2+x^2)/(2*s^2))),x=x,y=x,type="surface")
```
[](https://i.stack.imgur.com/6ArOY.png)
[Answer]
# Applesoft BASIC, ~~930~~ ~~783~~ ~~782~~ ~~727~~ ~~719~~ ~~702~~ ~~695~~ 637 bytes
-72 bytes and a working program thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) spotting my error and a shortened algorithm
```
0TEXT:HOME:INPUTN:HGR:HCOLOR=3:W=279:H=159:L=W-100:Z=L/10:B=H-100:C=H-60:K=0.5:M=1/(2*3.14159265*N*N):FORI=0TO10STEPK:X=10*I+1:Y=10*I+B:HPLOTX,Y:FORJ=0TOL STEP1:O=10*J/L:D=ABS(5-I):E=ABS(5-O):R=(D*D+E*E)/(2*N*N):G=EXP(-R)*M:A=INT((C*G)/M):X=10*I+Z*O+1:Y=10*I+B-A:HPLOTTOX,Y:IF(I=0)GOTO4
1IF(J=L)GOTO3
2V=INT(J/10):IF((J/10)<>V)GOTO5
3D=ABS(5-I+K):E=ABS(5-O):R=(D*D+E*E)/(2*N*N):U=EXP(-R)/(2*3.14159*N*N):S=INT((C*U)/M):P=10*(I-K)+Z*O+1:Q=10*(I-K)+B-S:HPLOT TOP,Q:HPLOTX,Y
4IF(J=0)GOTO7:IF(I<10)GOTO5:IF(J=L)GOTO6:V=INT(J/10):IF((J/10)=V)GOTO6
5HCOLOR=0
6HPLOTTOX,10*I+B:HCOLOR=3:HPLOTX,Y
7NEXTJ:NEXTI:HPLOTW+1,H:HPLOTTO101,H:HPLOTTO0+1,H
```
[Ungolfed version here.](https://gist.github.com/aaronryank/0eb179b8c68659b90d084555a031222d)
When given input `1`:
[](https://i.stack.imgur.com/CyDdL.png)
When given input `2`:
[](https://i.stack.imgur.com/DrLpe.png)
] |
[Question]
[
**Disclaimer**
This question is not a duplicate of [this question](https://codegolf.stackexchange.com/questions/47870/count-the-number-of-ones-in-unsigned-16-bit-integer). I'm not counting specific digits, as we already have those set in the initial parameters. This question is focusing on the decimal numbers that can be constructed from the binary strings based on the digits provided.
**Challenge**
Given two integers `X` and `Y`, representing the number of zeroes (`0`) and ones (`1`) respectively, calculate all the possible decimal equivalents that can be determined from creating binary strings using only the zeroes and ones provided, and display them as output.
**Example 1:**
Input: `0 1`
Output: `1`
Explanation: Only one `1` to account for, which can only be converted one way.
**Example 2:**
Input: `1 1`
Output: `1,2`
Explanation: `01` converts to 1, `10` converts to 2.
**Example 3:**
Input: `3 2`
Output: `3,5,6,9,10,12,17,18,20,24`
Explanation: Three `0`s and two `1`s make `00011` (3), `00101` (5), `00110` (6), `01001` (9), `01010` (10), `01100` (12), `10001` (17), `10010` (18), `10100` (20), `11000` (24)
**Limitations and Rules**
* I will only expect your code to work where `0 < X + Y <= 16` so the maximum number in the output could only occur from 16 `1`s, i.e. parameters `0` and `16`.
* As a result of the above limitation, the range of numbers we'd expect in the output are from `0` and `65535`.
* I will accept functions or code, so long as the resulting output is provided, whether this be a comma separated list, an array, list outputted to STDOUT, etc. The only criteria I must stress about the output is that it **must** be sorted.
* This is code golf, minimum bytes will receive maximum glory.
* We will not tolerate [silly loopholes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny)
[Answer]
# Python, 60 bytes
```
lambda x,y:[n for n in range(1<<x+y)if bin(n).count('1')==y]
```
Test it on [Ideone](http://ideone.com/8iRR8q).
### How it works
All positive numbers that can be represented in binary with **x** zeroes and **y** ones is clearly smaller than **2x + y**, since the canonical binary representation of the latter has **x + y + 1** digits.
The lambda simply iterates over the integers in **[0, 2x + y)** and keeps all integers **n** in that range that have **y** ones. Since **n < 2x + y** is can be represented with **x** (or less) zeroes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
0,1xŒ!ḄQ
```
[Try it online!](http://jelly.tryitonline.net/#code=MCwxeMWSIeG4hFE&input=&args=MywgMg)
### How it works
```
0,1xŒ!ḄQ Main link. Argument: [x, y]
0,1x Repeat 0 x times and 1 y times.
Œ! Compute all permutations of the result.
Ḅ Unbinary; convert each permutation from base 2 to integer.
Q Unique; deduplicate the results.
```
[Answer]
# Mathematica, ~~59~~ 57 bytes
A usual outcome with Mathematica: high-level functions = good, long function names = bad.
```
#+##&~Fold~#&/@Permutations@Join[0&~Array~#,1&~Array~#2]&
```
`Join[0&~Array~#,1&~Array~#2]` creates a list with the correct number of `0`s and `1`s. `Permutations` generates all permutations of that list, without repetitions (as I learned) and in sorted order. `#+##&~Fold~#` (a golfuscated version of `#~FromDigits~2`) converts a list of base-2 digits into the integer they represent.
Previous version, before Martin Ender's comment:
```
#~FromDigits~2&/@Permutations@Join[0&~Array~#,1&~Array~#2]&
```
[Answer]
## CJam (15 14 bytes)
```
{As.*s:~e!2fb}
```
This is an anonymous block (function) which takes input as an array `[number-of-ones number-of-zeros]` and returns output as an array.
[Online demo](http://cjam.aditsu.net/#code=%5B2%204%5D%0A%0A%7BAs.*s%3A~e!2fb%7D%0A%0A~%60)
---
A long way off the mark, but [more interesting](https://softwareengineering.stackexchange.com/a/67087/13258): this is without permutation builtins or base conversion:
```
{2\f#~1$*:X;[({___~)&_2$+@1$^4/@/|_X<}g;]}
```
It would work nicely as a GolfScript unfold.
[Answer]
# [Japt](https://github.com/ETHproductions/Japt), 16 bytes
```
'0pU +'1pV)á mn2
```
[Test it online!](http://ethproductions.github.io/japt/?v=master&code=JzBwVSArJzFwVinhIG1uMg==&input=MyAy)
### How it works
```
// Implicit: U = first integer, V = second integer
'0pU // Repeat the string "0" U times.
+'1pV) // Concatenate with the string "1" repeated V times.
á // Take all unique permutations.
mn2 // Interpret each item in the resulting array as a binary number.
// Implicit: output last expression
```
### Alternate version, 17 bytes
```
2pU+V o f_¤è'1 ¥V
// Implicit: U = first integer, V = second integer
2pU+V // Take 2 to the power of U + V.
o // Create the range [0, 2^(U+V)).
f_ // Filter to only items where
è'1 // the number of "1"s in
¤ // its binary representation
¥V // is equal to V.
// Implicit: output last expression
```
I've been trying to further golf both versions, but I just can't find any slack...
[Answer]
# Ruby, 63 bytes
A simple implementation. Golfing suggestions welcome.
```
->a,b{(?0*a+?1*b).chars.permutation.map{|b|(b*'').to_i 2}.uniq}
```
**Ungolfing**
```
def f(a,b)
str = "0"*a+"1"*b # make the string of 0s and 1s
all_perms = str.chars.permutation # generate all permutations of the 0s and 1s
result = []
all_perms.do each |bin| # map over all of the permutations
bin = bin * '' # join bin together
result << bin.to_i(2) # convert to decimal and append
end
return result.uniq # uniquify the result and return
end
```
[Answer]
# Pyth - 11 bytes
```
{iR2.psmVU2
```
[Test Suite](http://pyth.herokuapp.com/?code=%7BiR2.psmVU2&test_suite=1&test_suite_input=0%2C+1%0A1%2C+1%0A3%2C+2&debug=0).
```
{ Uniquify
iR2 Map i2, which converts from binary to decimal
.p All permutations
s Concatenate list
mV Vectorized map, which in this case is repeat
U2 0, 1
(Q) Implicit input
```
[Answer]
# Python 2 - ~~105~~ 99 bytes
+8 bytes cos our output needs to be sorted
```
lambda x,y:sorted(set(int("".join(z),2)for z in __import__('itertools').permutations("0"*x+"1"*y)))
```
[Answer]
## Mathematica, 47 bytes
```
Cases[Range[2^+##]-1,x_/;DigitCount[x,2,1]==#]&
```
An unnamed function taking two arguments: number of `1`s, number of `0`s.
Essentially a port of [Dennis's Python solution](https://codegolf.stackexchange.com/a/92461/8478). We create a range from `0` to `2x+y-1` and then keep only those numbers whose amount of `1`-bits equals the first input. The most interesting bit is probably the `2^+##` which uses some [sequence magic](https://codegolf.stackexchange.com/a/45188/8478) to avoid the parentheses around the addition of the two arguments.
[Answer]
## MATLAB 57 + 6
```
@(a,b)unique(perms([ones(1,a) zeros(1,b)])*2.^(0:a+b-1)')
```
run using
```
ans(2,3)
```
ungolfed
```
function decimalPerms( nZeros, nOnes )
a = [ones(1,nOnes) zeros(1,nZeros)]; % make 1 by n array of ones and zeros
a = perms(a); % get permutations of the above
powOfTwo = 2.^(0:nOnes+nZeros-1)'; % powers of two as vector
a = a * powOfTwo; % matrix multiply to get the possible values
a = unique(a) % select the unique values and print
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 9 bytes
```
y+:<Y@XBu
```
[Try it online!](http://matl.tryitonline.net/#code=eSs6PFlAWEJ1&input=Mwoy)
### Explanation
The approach is similar to that in [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/92458/36398).
```
y % Implicitly take two inputs (say 3, 2). Duplicate the first.
% STACK: 3, 2, 3
+ % Add
% STACK: 3, 5
: % Range
% STACK: 3, [1 2 3 4 5]
< % Less than
% STACK: [0 0 0 1 1]
Y@ % All permutations
% STACK: [0 0 0 1 1; 0 0 0 1 1; ...; 0 0 1 0 1; ...; 1 1 0 0 0]
XB % Binary to decimal
% STACK: [3 3 ... 5 ... 24]
u % Unique
% STACK: [3 5 ... 24]
% Implicitly display
```
[Answer]
# Actually, 21 bytes
A port of [my Ruby answer](https://codegolf.stackexchange.com/a/92467/47581). Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=4pSCKyknMSpAJzAqK-KVqGDOtWoyQMK_YE3ilZQ&input=Mwoy)
```
│+)'1*@'0*+╨`εj2@¿`M╔
```
**How it works**
```
Implicit input of a and b.
│+) Duplicate a and b, add, and rotate to bottom of stack. Stack: [b a a+b]
'1*@ "1" times b and swap with a.
'0*+ "0" times a and add to get "0"*a+"1"*b.
╨`...`M Take all the (a+b)-length permutations of "0"*a+"1"*b
and map the following function over them.
εj Join the permutation into one string
2@¿ Convert from binary to decimal
╔ Uniquify the resulting list and implicit return.
```
[Answer]
# Groovy 74 Bytes, 93 Bytes or 123 Bytes
I don't know which one you consider more fully answers the question but...
## 74 Byte Solution
```
{a,b->((1..a).collect{0}+(1..b).collect{1}).permutations().unique()}(1,2)
```
For an input of 1,2 you get:
```
[[1,0,1], [0,1,1], [1,1,0]]
```
## 93 Byte Solution
```
{a,b->((1..a).collect{0}+(1..b).collect{1}).permutations().collect{it.join()}.unique()}(1,2)
```
For an input of 1,2 you get:
```
[101, 011, 110]
```
## 123 Byte Solution
```
{a,b->((1..a).collect{0}+(1..b).collect{1}).permutations().collect{it.join()}.unique().collect{Integer.parseInt(it,2)}}(1,2)
```
For an input of 1,2 you get:
```
[5, 3, 6]
```
Try it out here:
<https://groovyconsole.appspot.com/edit/5143619413475328>
[Answer]
# JavaScript (Firefox 48), ~~85~~ ~~76~~ ~~74~~ ~~71~~ 70 bytes
Saved 3 bytes thanks to @Neil.
```
(m,n,g=x=>x?g(x>>1)-x%2:n)=>[for(i of Array(1<<m+n).keys())if(!g(i))i]
```
Array comprehensions are awesome. Too bad they haven't made it into official ECMAScript spec yet.
# JavaScript (ES6), ~~109~~ ~~87~~ ~~79~~ ~~78~~ ~~71~~ 70 bytes
```
(m,n,g=x=>x?g(x>>1)-x%2:n)=>[...Array(1<<m+n).keys()].filter(x=>!g(x))
```
Should work in all ES6-compliant browsers now. Saved 7 bytes on this one, also thanks to @Neil.
[Answer]
# Groovy 80 Bytes
based on the answer by @carusocomputing
his 123 Byte solution can be compressed into 80 Bytes:
## 80 Byte Solution
```
{a,b->([0]*a+[1]*b).permutations()*.join().collect{Integer.parseInt(it,2)}}(1,2)
```
For an input of 1,2 you get:
```
[5, 3, 6]
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~72~~ 68 bytes
```
f(a,b){for(a=1<<a+b;a--;)__builtin_popcount(a)^b||printf("%d\n",a);}
```
[Try it online!](https://tio.run/##FcxBCoAgEADAvwTBSnqojtpPIlkNQ6hVRE/Z262OcxkrDmtbc4DcsNuFBLiMSuFgJAohmdam@DN70jFEGwplQLaZWmPylB10/b5Sx5HJp13oCb4EZj79fgE "C (gcc) – Try It Online")
Unfortunately there is no popcount() in the standard library, but it is provided as a "builtin function" by GCC. The output is sorted, but in reverse order.
Thanks to @ceilingcat for shaving off 4 bytes!
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ËçEìá mÍâ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=y%2bdFw6zhIG3N4g&input=WzMgMl0)
```
ËçEìá mÍâ :Implicit input of array
Ë :Map each D at 0-based index E
çE : Repeat E D times
à :End map
¬ :Join
á :Permutations
m :Map
Í : Convert from binary string to integer
â :Deduplicate
```
[Answer]
# PHP, 80 or 63 bytes
depending on wether I must use `$argv` or can use `$x` and `$y` instead.
```
for($i=1<<array_sum($argv);$i--;)echo$argv[2]-substr_count(decbin($i),1)?_:$i._;
```
prints all matching numbers in descending order delimited by underscores.
filename must not begin with a digit.
**no builtins, 88 or 71 bytes**
```
for($i=1<<array_sum($argv);$i--;print$c?_:$i._)for($n=$i,$c=$argv[2];$n;$n>>=1)$c-=$n&1;
```
---
add one byte each for only one underscore after every number.
@WallyWest: You were right. Saves 3 bytes for me from `for($i=-1;++$i<...;)`
[Answer]
# [Perl 6](http://perl6.org), ~~64 62~~ 49 bytes
```
{(0 x$^a~1 x$^b).comb.permutations.map({:2(.join)}).sort.squish}
```
```
{[~](0,1 Zx@_).comb.permutations.map({:2(.join)}).sort.squish}
```
```
{(^2**($^x+$^y)).grep:{.base(2).comb('1')==$y}}
```
## Explanation:
```
# bare block lambda with two placeholder parameters 「$^x」 and 「$^y」
{
# Range of possible values
# from 0 up to and excluding 2 to the power of $x+$y
( ^ 2 ** ( $^x + $^y ) )
# find only those which
.grep:
# bare block lambda with implicit parameter of 「$_」
{
# convert to base 2
# ( implicit method call on 「$_」 )
.base(2)
# get a list of 1s
.comb('1')
# is the number of elements the same
==
# as the second argument to the outer block
$y
}
}
```
```
say {(0..2**($^x+$^y)).grep:{.base(2).comb('1')==$y}}(3,2)
# (3 5 6 9 10 12 17 18 20 24)
```
] |
[Question]
[
Task similar to [this one](https://codegolf.stackexchange.com/questions/44830/string-to-binary). Take a string of ASCII characters and convert it to base-3 equivalents separated by a space.
For example:
```
Hello, world!
```
Should be converted to
```
02200 10202 11000 11000 11010 01122 01012 11102 11010 11020 11000 10201 01020
```
The output should only contain numbers with the same number of digits. Which separator to use is up to you.
This is a code-golf challenge so the shortest solution wins.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
3YA
```
Uses newline as separator. [**Try it online!**](https://tio.run/##y00syfn/3zjS8f9/dY/UnJx8HYXy/KKcFEV1AA "MATL – Try It Online")
### Explanation (by [@Sundar R](https://codegolf.stackexchange.com/users/8774/sundar-r))
`YA` is a single function, corresponding to Matlab's [`dec2base`](https://www.mathworks.com/help/matlab/ref/dec2base.html) (convert from decimal to some base). By default it takes two arguments: an array with the numbers to convert and the base to convert to. Since only the second argument (`3`) is specified here, the input is implicitly used as the first argument.
The cool part is that this is automatically applied to the whole input (which is a char array), the results collected into a char matrix, and when things don't line up, `0`'s are automatically prepended to make them have the same width.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~ 70 66 ~~ 62? 66 bytes
```
for c in input():print(*[ord(c)//d%3for d in b'Q '],sep='')
```
(Code contains unprintable bytes inside the `b'...'`)
A full program accepting input from STDIN that prints the result using a newline separator (with a trailing newline).
**[Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFZITMPiApKSzQ0rQqKMvNKNLSi84tSNJI19fVTVI1BalJAapLUA6U5mRnVY3WKUwts1dU1///3SM3JyddRKM8vyklRBAA "Python 3 – Try It Online")**
---
...but 66 if we need to handle multi-line strings (since `input()` only reads one line:
```
lambda s:[print(*[ord(c)//d%3for d in b'Q '],sep='')for c in s]
```
An unnamed function that prints the answer.
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYKrqgKDOvREMrOr8oRSNZU18/RdU4Lb9IIUUhM08hST1QmpOZUT1Wpzi1wFZdXRMkkwySKY79X5JaXKJgq6Curh7D5ZGak5Ovw1WeX5SToggU4UrTAElr/odIKEAkAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
All-ASCII jelly code to boot...
```
Ob3Uz0ZUK
```
A full program accepting a string that prints the result.
**[Try it online!](https://tio.run/##y0rNyan8/98/yTi0yiAq1Pv///9KHkCxfB2F8vyinBRFJQA "Jelly – Try It Online")**
### How?
```
Ob3Uz0ZUK - Main Link: list of characters
O - ordinals
b3 - to base three
U - upend (reverse each)
z0 - transpose with filler of zero
Z - transpose
U - upend (reverse each)
K - join with spaces
- implicit, smashing print
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
⪫ES⭆◧⍘℅鳦⁵Σλ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMrPzNPwzexQMMzr6C0JLgEKJiuoamjAGGBJAISU3xS00o0nBKLU6Hy/kUpmXmJORqZQIXGQGwK0lCaq5GjqQlkKSkoaWpa///vkZqTk6@jUJ5flJOiyPVftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
E Map over characters
ι Current character
‚ÑÖ ASCII code
⍘ ³ Convert to base 3
◧ ⁵ Left pad to length 5
⭆ Map over characters and join
λ Inner character
Σ Numeric value if any
‚™´ Join with spaces
Implicitly print
```
12 bytes to print as a list:
```
UB0←E⮌S⮌⍘℅ι³
```
[Try it online!](https://tio.run/##NcmxCsIwEIDhvU8RO10gguBmt04KFcU@wZGcNXgk5ZrWxz8z6D9@v3@h@IysOlLp0b8nyWsK0B5a2zV3ianAaaBnceaKMzxoI1kILmley1jqnsBaZ/7e40I/vkmICRli3Udb61TPxJyd@WThsGt0v/EX "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
UB0
```
Set output to zero fill.
```
←E⮌S⮌
```
Output the strings upside-down and reversed (which right-justifies them) given by...
```
⍘℅ι³
```
... converting the ASCII codes to base 3.
[Answer]
# [Python 3](https://docs.python.org/3/), 71 bytes
```
import numpy
for i in input():print(numpy.base_repr(ord(i),3).zfill(5))
```
[Try it online!](https://tio.run/##Hck7CoAwDADQ3VPELQEp2OLiZcQvBmwbYjvUy1cR3vakpDMGVyt7iZogZC@lOaICA4eP5IQ0inJI@KdZ5nufdBfFqBsydY7Mc/B14UBUa2/dvKxtC2Bf "Python 3 – Try It Online")
-30 thanks to Jonathan Allan, I'm lazy to golf another code
Prints numbers separated by newlines
If you really need space as a separator then here is the code:
# [Python 3](https://docs.python.org/3/), 176 bytes
```
import numpy
m=input()
y=m[:-1]
u=lambda x:"0"*(5-len(x))+x
for i in y:print(u(str(numpy.base_repr(ord(i),base=3))),end = " ")
print(u(str(numpy.base_repr(ord(m[-1]),base=3))))
```
[Try it online!](https://tio.run/##hY5LCsIwFAD3OcVrVu9pK7bFTSAnKSKpjRhoPqQJNKePn5U7twMzTCjp6d1Yq7HBxwQu21CYlcaFnJBYkXYSXX9lWa7KzouCXfAzP@ClW7XDnei4s4ePYMA4KCJE4xJm3FLEb@s0q03fog4RfVzQUPsBciSiVrsFJHDgxP55dnpP/LhUaz@Mar43DcDwAg "Python 3 – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), ~~38~~ 34 bytes
```
[ [ 3 >base "%05s "printf ] each ]
```
[Try it online!](https://tio.run/##DcWxCsIwEAbgvU/xG3ATKYhLBVd16VI6lQ7XeLHFM6l3ER8/@i1fIJ@Tlr67tZcGT9bIgpD0RTkv8YH/834lNVYYvz8cPRtOVeWuLJJ2@CaV@8aVAQMOOE9kDLetjwa36hJzwAgmP2MsnkTKDw "Factor – Try It Online")
* `[ ... ] each` For each code point in the input string,
* `3 >base` convert it to base 3
* `"%05s "printf` and print it with leading zeros to a length of five, followed by a space.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
C3τvṅ5∆Z⁋
```
Uses newline as the separator.
```
C3τvṅ5∆Z⁋
C Convert to ASCII codepoint
3τ Convert each character to base 3
v·πÖ Join by nothing, because to-base returns a list of digits
5∆Z Pad with 5 zeros (because that's the max length of an ASCII char)
‚Åã Join by newlines
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJDM8+EduG5hTXiiIZa4oGLIiwiIiwiSGVsbG8sIHdvcmxkISJd)
It will probably get 9 bytes soon, because of a bug (to-base doesn't support vectorization)
Lyxal epic speed bug fix done
Actually, [8 bytes with flag](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiQzPPhHbhuYU14oiGWiIsIiIsIkhlbGxvLCB3b3JsZCEiXQ==), but `j` is very buggy
[Answer]
# [R](https://www.r-project.org/), ~~63~~ 59 bytes
```
function(s)write(rep(utf8ToInt(s),e=5)%/%3^(4:0)%%3,1,,,"")
```
[Try it online!](https://tio.run/##K/qflFicamz7P600L7kkMz9Po1izvCizJFWjKLVAo7QkzSIk3zOvBCiqk2prqqmqr2ocp2FiZaCpqmqsY6ijo6OkpAkxQkPJIzUnJ19HoTy/KCdFESgMAA "R – Try It Online")
~~Nothing clever, but a straightforward implementation in R is shorter than anything else that I can think of so far...~~
To avoid the penalty of defining a base-conversion `function` to use on each character, we repeat each character value 5 times, and then use vectorized integer division (`%/%`) and modulo (`%%`) to calculate all the base-3 digits. Then, by lucky co-incidence, the `write` function splits its output data into a column width of 5 by default.
[Answer]
# [Javascript (Node.js)](https://nodejs.org), ~~62~~ 59 bytes
```
f=
x=>[...x].map(t=>(t.charCodeAt()+243).toString(3).slice(1))
console.log((f+'').length);
console.log(f("Hello World!")+'');
```
[Try it online!](https://tio.run/##DcmxCoMwEADQX6lOF9oetLpGEJfuHcUhxGhTzpwkR/Xv02wP3tf8TLLR73IPPLu86HzqbkTEc8LN7CC6A0H7MXEo3wuo67NtFAq/JfqwQnEibx08lMqWQ2JySLzCAvXLEfHtcnCkuarL/wE)
-3 thanks to @tsh
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 20 bytes
```
{'0'+3|‚åäùï©√∑3‚ãÜ‚åΩ‚Üï5}¬®-‚üú@
```
Anonymous function that takes a string and returns a list of strings. [Run it online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeycwJyszfOKMivCdlanDtzPii4bijL3ihpU1fcKoLeKfnEAKCkYgIkhlbGxvLCBXb3JsZCEi)
If a list of lists of digits is an acceptable output format, then it's 16 bytes:
```
{3|‚åäùï©√∑3‚ãÜ‚åΩ‚Üï5}¬®-‚üú@
```
### Explanation
```
{'0'+3|‚åäùï©√∑3‚ãÜ‚åΩ‚Üï5}¬®-‚üú@
-‚üú@ Subtract '\0' from each character, converting to list of charcodes
{ }¨ Map this function to each charcode:
‚Üï5 Range(5)
‚åΩ Reverse
3⋆ 3 to the power of each
ùï©√∑ Divide the argument by each
‚åä Floor
3| Mod 3
'0'+ Convert digits to characters by adding '0'
```
[Answer]
# [GeoGebra](https://geogebra.org/calculator), ~~74~~ 50 bytes
```
Zip(Take(ToBase(a,3),2,6),a,TextToUnicode("")+243)
```
Insert string input between the `""`. (I guess this is [allowed](https://chat.stackexchange.com/transcript/message/60478046#60478046)) Output is a list of strings padded to 5 digits. (This is also [allowed](https://codegolf.stackexchange.com/questions/243100/convert-a-string-of-ascii-characters-to-base-3-equivalents/243151#comment547493_243100) by OP)
Uses the " add \$3^5\$ " idea from [@DLosc](https://codegolf.stackexchange.com/users/16766/dlosc)'s [answer](https://codegolf.stackexchange.com/a/243152/96039).
[Try It On GeoGebra!](https://www.geogebra.org/calculator/zfzbsmn4)
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 14 bytes
```
)**m{3B!5'0P[}
```
[Try it online!](https://tio.run/##SyotykktLixN/f9fU0srt9rYSdFU3SAguvb/f4/UnJx8HYXy/KKcFEUA "Burlesque – Try It Online")
```
)** # Map ord
m{ # Map
3B! # To base 3
5'0P[ # Pad to length 5 using "0"s
}
```
[Answer]
# APL+WIN, 22 bytes
Prompts for ASCII string. Index origin = 0
```
(⍕¨(⊂5⍴3)⊤¨⎕av⍳⎕)~¨' '
```
Most of the bytes are taken by formatting the output.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
m(↑_5ṁsΘB3c
```
[Try it online!](https://tio.run/##yygtzv7/P1fjUdvEeNOHOxuLz81wMk7@//@/R2pOTr6OQnl@UU6KIgA "Husk – Try It Online")
5 bytes (`m(B3c`) to calculate the base-3 representation of each ASCII character, but then 6 more bytes to format the output: prepend a zero (`Θ`), get string representation of digits (`s`), flatten together (`ṁ`), and take the last 5 elements (`↑_5`).
If it's acceptable for the base-3 digits to be space-separated (and the groups to be newline-separated), then we could do it in [10 bytes](https://tio.run/##yygtzv7/P1ej/FHbxHjTczOcjJP////vkZqTk6@jUJ5flJOiCAA): `m(w↑_5ΘB3c`.
If we insist on space-separating the non-separated base-3 digits (exactly as in the example), it'll cost [12 bytes](https://tio.run/##yygtzv7/vzxX41HbxHjThzsbi8/NcDJO/v//v0dqTk6@jkJ5flFOiiIA): `wm(↑_5ṁsΘB3c`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~72 64~~ 62 bytes
```
unwords.map(\c->show.(`mod`3).div(fromEnum c)=<<[81,27,9,3,1])
```
[Try it online!](https://tio.run/##DczRCsIgFADQX7mNHhScsPZQwewt6B9aMNFsknpFW/v7bjsfcGZd388QyKmRlrRisVVGndlo2kudcZVsiminnkvrv8wVjNe0RDBcDcP91InDUZxFL7oHp6h9AgW5@PSBPbjmtsUoYEuD3TX0My7oV6XW5PwH "Haskell – Try It Online")
* Saved 8+2 Bytes thanks to @ovs suggestions.
Couldn't find any golfy way for the list of powers of 3: tried (3^)<$>[4,3..0] with no gains.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 72 bytes
```
i;f(char*s){for(;*s;++s,putchar(32))for(i=243;i/=3;)putchar(48+*s/i%3);}
```
[Try it online!](https://tio.run/##XZFhb4IwEIa/@ytuJCYtYGyLS7Z17stisv8g@@Bqq81YIbRGNuNfHysIDCWhOd577r3rIWY7Iepac4XEflOGFp9UXiIeWh5FNi4OrpFRwjBudL1ki4Tr@TLhuM8tHqLQzvU0wfxca@Pga6MNwnCagH9aV3DSOrt@hyWcgjeZZXkMx7zMtnfBmY8wWRVSOLntSMIYIUAJIwwoJU3cn5QAoZQxfxLaZOmFoW2WDaQPacMwMnTKjXVdP7GX4lOWXbu0WrG0enz1730Qw/g76av9EgA1l9RmKytfRngXPoPVPzJXqL8EnndCOCgcoqilcWt22dBoS97vsqkWeudXefg4KLW2rsykQQ5DBHREeF0U36hhYnD4P1GUflyFgjSY2jSA2UtqgmtCtVWY30wj/TTDD7kdaHA1qw55So1v0HjLzuo8Ode/QmWbna1nxz8 "C (gcc) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 15 bytes
```
S3E5+A_TB3MaJ:s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7IKlpSVpuhbrg41dTbUd40OcjH0TvayKIaJQyY3RSh6pOTn5Ogrl-UU5KYpwXQA)
Or, using the `-s` flag to do the output formatting, **12 bytes**:
```
S3E5+A_TB3Ma
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSbrFS7IKlpSVpuhZrgo1dTbUd40OcjH0TIUJQmY3RSh6pOTn5Ogrl-UU5KYpwLQA)
### Explanation
Pip doesn't have any padding builtins as of this writing, so we do the following instead: Add \$3^5\$ to each codepoint; convert to base 3, resulting in a 6-digit number that always has a leading 1; and slice off the first digit.
```
S3E5+A_TB3MaJ:s
a ; First command-line argument
M ; Map this function to each of its characters:
A_ ; ASCII code of the character
3E5+ ; Add 3 to the 5th power
TB3 ; Convert to base 3
S ; Suffix containing all but the first character
J: ; Join the resulting list on
s ; Space
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ç3Bí0ζøí»
```
Output is newline delimited.
[Try it online.](https://tio.run/##ASYA2f8wNWFiMWX//8OHM0LDrTDOtsO4w63Cu///SGVsbG8sIHdvcmxkIQ)
**Explanation:**
Uses the legacy version of 05AB1E because it can zip/transpose on list of strings, whereas the new 05AB1E version requires a matrix of characters. This would be 10 bytes in the new version by replacing `B` with `в` and adding a `J` (join) before the `»`. If any amount of leading 0s is valid, this could be 9 bytes as well in the new version of 05AB1E with `Ç3BZ°+€¦»` or `Ç3BZj»ð0:`.
```
Ç # Convert the (implicit) input-string to a list of codepoint integers
3B # Convert each integer to a base-3 string
í # Reverse each string
ζ # Zip/transpose; swapping rows/columns,
0 # using a 0 as trailing filler for unequal length rows
√∏ # Zip/transpose back
í # Reverse each string back
» # Join the strings with newline delimiter
# (after which the result is output implicitly)
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 80 bytes
```
s->s.chars().forEach(c->System.out.printf("%05d ",new Long(Long.toString(c,3))))
```
[Try it online!](https://tio.run/##XU7BSsQwEL33K8YFIZU2COLFrr2I4EFPe/AgHsY07aammZJMKiL77THd3YsOzAzz3uO9GXHBeuw@k5lm8gxjvmVkY2UfnWJDTl41hbIYArygcfBTAMzxwxoFgZHzWsh0MGVO7NgbN7y9A/ohlEcpwAO5ECfttye2hR7uU6jbINUefRCl7Mk/otoLVbe778B6khRZzlnNvdhcXt92sKmc/oJncoNYh2Q6uQlV3ZS5UnPMyk4gFvTrA3D3541MSlRKzywyXDZn8H@gdeLMHYq1Dyk9aWupglfytrv4BQ "Java (JDK) – Try It Online")
* -4 bytes thanks to [swpalmer](https://codegolf.stackexchange.com/users/111175/swpalmer).
[Answer]
# APL, 21 Chars, 39 Bytes
```
{∊6↑¨,⌿⍕¨(5⍴3)⊤⎕UCS⍵}
```
`(5⍴3)⊤⎕UCS⍵` converts input to base 3 ASCII code in five digits.
`,⌿⍕¨` converts the digits to characters and joins them together.
`6↑¨` pads space in between (also results in a trailing space) and `∊` builds the final output.
[Try it online!](https://tio.run/##AUoAtf9hcGwtZHlhbG9n//9m4oaQe@KIijbihpHCqCzijL/ijZXCqCg14o20MyniiqTijpVVQ1PijbV9//9mICdIZWxsbywgd29ybGQhJw "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 35 bytes
```
->s{s.bytes.map{"%05d"%_1.to_s(3)}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3lXXtiquL9ZIqS1KL9XITC6qVVA1MU5RU4w31SvLjizWMNWtrIUq3FCi4RSt5pObk5OsolOcX5aQoKsVCpBYsgNAA)
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 30 bytes
```
:bytes|:*&(~:to_s&3|:%&"%05d")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboW-6ySKktSi2ustNQ06qxK8uOL1YxrrFTVlFQNTFOUNCGKthQouEUreaTm5OTrKJTnF-WkKCrFQqQWLIDQAA)
## Explanation
```
:bytes | # Get bytes, then
:* & ( # map with...
~:to_s & 3 | # convert to base 3
:% & "%05d" # format to 5 digits
)
```
] |
[Question]
[
# Challenge
The [primitive circle problem](https://en.wikipedia.org/wiki/Gauss_circle_problem#Generalizations) is the problem of determining how many [coprime](https://en.wikipedia.org/wiki/Coprime) integer lattice points \$x,y\$ there are in a circle centered at the origin and with radius \$r \in \mathbb{Z}^+
\$ such that \$x^2+y^2 \le r^2 \$. It's a generalization of [Code-Golf: Lattice Points inside a Circle](https://codegolf.stackexchange.com/questions/1938/code-golf-lattice-points-inside-a-circle).
[](https://i.stack.imgur.com/K42tj.png)
**Input**
Radius \$r \in \mathbb{Z}^+\$
**Output**
Number of coprime points
# Test Cases
Taken from sequence [A175341](https://oeis.org/A175341) in the [OEIS](https://en.wikipedia.org/wiki/On-Line_Encyclopedia_of_Integer_Sequences).
| Radius | Number of coprime points |
| --- | --- |
| 0 | 0 |
| 1 | 4 |
| 2 | 8 |
| 3 | 16 |
| 4 | 32 |
| 5 | 48 |
[Answer]
# JavaScript (ES6), 45 bytes
Based on [A000089](https://oeis.org/A000089), the number of solutions to:
$$x^2+1\equiv 0 \pmod n$$
which allows to compute [A304651](https://oeis.org/A304651) and eventually [A175341](https://oeis.org/A175341).
```
f=(n,k=N=n*n)=>N&&4*(--k*k%N>N-2)+f(n,k||--N)
```
[Try it online!](https://tio.run/##FcxBDsIgEEDRfU8xi9owIEatu0qPwBlKKhiFDKZt3FDOjrj6m5f/Nl@zzsvrs0mKD1uKU4yOXmlFnFCNuutunEnpuT/oUcsrCvcH@y6lxuLiwoLdgEDBeai5w6WvFQIhNQBzpDUGewrxySbD2kQZK21TnWCecGhy@QE "JavaScript (Node.js) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), 58 bytes
*-1 thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
The recursion is convenient in JS but otherwise really pointless. It is replaced with a single loop below.
```
k,N;f(n){for(k=N=n*n,n=0;N;k=k?:--N)n+=--k*k%N>N-2;k=4*n;}
```
[Try it online!](https://tio.run/##JY5BCsIwEEX3PcVQCCRNBkpxZYzeICdwE1JSyugoVXBRcnVjgqsH738@P@ISYylkvE2S1Z4emyTnHQ9s2I3WW3J0OSJ6xdoh0kDCnz1O1R8Gtrms/IZ7WFkq2DuANtAUg4PRVpxgatT6nwM8t5on2QcpZlVbYr5yb4ANtAfK1lLucvnGdAvLq@DnBw "C (gcc) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 63 bytes
```
f(m,r,n,x){for(r=n=0;n++<m*m;)for(x=n;x--;)r+=x*x%n>n-2;m=r*4;}
```
[Try it online!](https://tio.run/##HYpBCsIwEADP7SuWSiFpEqnibZu@xIskRhfMVmKFQOnbY@tpYGaceThXDsTu9fV3GD6zp@n4HEsQUSfNOsslTEkky7ZHVmqIXUS5q2wZszEok7K5yy2PbM4YbeouuBbiGeKNWEhY6mr7QeyKwEKPGwY4bVSK/r16p60G0bQezAitv3KjgTQEQVJiXa31Wn4 "C (gcc) – Try It Online")
Port of [@enzo's python answer](https://codegolf.stackexchange.com/a/269992/91267) (very surprised that it matches byte count with the python answer)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes
```
r4I~If[Abs@+##>r,Sign@r,#~#0~+##+#2~#0~+##]&~1
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v@j9pIUmnnWeadGOScUO2srKdkU6wZnpeQ5FOsp1ygZ1QBFtZSMoK1atzvB/QFFmXkm0sq5dmgNIIDg5Ma8uKDEvPTXaQMfEPPY/AA "Wolfram Language (Mathematica) – Try It Online")
Counts edges of that star formed by the points in the first quadrant.
```
I~ &~1 initial edge: 1-I
If[Abs@+##>r, , ] can this edge be split?
#~#0~+##+#2~#0~+## yes: split the edge
Sign@r no: count if input≠0
4 * 4 quadrants
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~70~~ 63 bytes
```
lambda m:4*sum(x*x%n>n-2for n in range(m*m+1)for x in range(n))
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHXykSruDRXo0KrQjXPLk/XKC2/SCFPITNPoSgxLz1VI1crV9tQEyRYgRDM09T8DxLKRAiZaVpxKQBBQVFmXolGmkYmUAkA "Python 3 – Try It Online")
* *-7 bytes* thank to Mukundan314 by removing the double sum and parenthesis
[Answer]
# Google Sheets, 109 bytes
```
=iferror(4*sum(map(sequence(1,A2+1,0),lambda(x,map(sequence(A2),lambda(y,(1=gcd(x,y))*(x^2+y^2<=A2^2)))))),0)
```
Put the radius in cell `A2` and the formula in cell `C2`.
The formula creates a \$(n+1)×n\$ matrix for the upper right quadrant, excluding the \$x\$ axis (\$y ≠ 0\$). The matrix contains ones and zeros. The result is 4 times the sum of the matrix.

This would be much simpler to implement with an array formula, but unfortunately `gcd()` is an aggregating function that only gives one result per evaluation rather than a result matrix, so we need to test every lattice point separately.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 61 bytes
```
f[n_]=Sum[Boole[GCD[x,y]==1&&x^2+y^2<=n^2],{x,-n,n},{y,-n,n}]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8tOi8@1ja4NDfaKT8/JzXa3dklukKnMtbW1lBNrSLOSLsyzsjGNi/OKFanukJHN08nr1anuhLCiP0fUJSZVxIdXAKk0oMy09KABoQkJgHJtOhMoIZMHQMdQ4vaWB0lBaXY2P8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒRṗ2²S>ɗÐḟ²g/€ċ1
```
A monadic Link that accepts the non-negative integer\* radius and yields the count of coprime lattice points in or on the circle of that radius centred at the origin.
**[Try it online!](https://tio.run/##AScA2P9qZWxsef//xZJS4bmXMsKyUz7Jl8OQ4bifwrJnL@KCrMSLMf///zU "Jelly – Try It Online")**
### How?
```
ŒRṗ2²S>ɗÐḟ²g/€ċ1 - Link: non-negative integer, r
ŒR - abs-range -> [-r..r]
ṗ2 - Cartesian power {2}
-> LatticePoints of the enclosing, axis-aligned square
Ðḟ - filter discard those {LatticePoints} for which:
ɗ ² - last three links as a dyad - f(LatticePoint, r^2)
² - square {each coordinate of LatticePoint}
S - sum {these}
> - {that} greater than {r^2}?
g/€ - reduce each {remaining LatticPoint} by GCD
ċ1 - {that} count occurrences of one
```
\* Also works for floats, up to floating-point errors, since while `ŒR` implicitly floors its input no lattice point will be in or on the circle if one of its coordinates is further out.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 54 bytes
```
f(n)=sum(x=-n,n,sum(y=-n,n,gcd(x,y)==1&&x^2+y^2<=n^2))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN83SNPI0bYtLczUqbHXzdPJ0QMxKCDM9OUWjQqdS09bWUE2tIs5IuzLOyMY2L85IUxOie19afpFGpq2BjoKhhY5CQVFmXomhRppGpqaCkoISTBHMKgA)
[Answer]
# [Desmos](https://desmos.com/calculator), 61 bytes
```
f(n)=4\sum_{a=0}^n\sum_{b=1}^n0^{\gcd(a,b)-1}\{aa+bb<=nn,0\}
```
[Try It On Desmos!](https://www.desmos.com/calculator/xzmxeh7ob1)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/wfu41krnsv)
I really feel like this can be golfed but I can't really think of anything at the moment. I also have this other version without the piecewise but it is 62 bytes:
```
f(n)=4∑_{a=0}^n∑_{b=1}^n0^{gcd(a,b)-1}sgn(sgn(nn-aa-bb)+1)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
(Ÿn¬sãʒ¿}€O@O
```
Straight-forward modification (adding `ʒ¿}€`) of [my 05AB1E answer for the related challenge](https://codegolf.stackexchange.com/a/270011/52210).
[Try it online](https://tio.run/##AR8A4P9vc2FiaWX//yjFuG7CrHPDo8qSwr994oKsT0BP//81) or [verify all test cases](https://tio.run/##ATkAxv9vc2FiaWX/dnk/IiDihpIgIj95RP8oxbhuwqxzw6PKksK/feKCrE9AT/8s/1swLDEsMiwzLDQsNV0).
**Explanation:**
```
( # Negate the (implicit) input-integer
Ÿ # Push a list in the range [(implicit) input,-input]
n # Square each inner value
¬ # Push the first item (without popping the list), which is input²
s # Swap so the list is at the top again
ã # Cartesian power of 2 to get all possible pairs
ʒ } # Filter this list of pairs by:
¿ # Where the Greatest Common Divisor (gcd) of the pair is 1
# (note: only 1 is truthy in 05AB1E)
€O # Sum all remaining inner pairs together
# (note: the `€` is only for n=0, so [] remains [], instead of becoming 0)
@ # Check for each whether the input² is >= this value
O # Sum to get the amount of truthy values
# (which is output implicitly as result)
```
[Try it online with step-by-step output lines.](https://tio.run/##VZA9TgMxEIV7TjHaaiMtBQUNUgApkSIaFokSUThhdm3FsY1/WKWg4QhcgTZVCkSHtIiGY3CRZWwHIgrLkt9738yzdmwucBiKC2WCP4GiGvevZwfFJbbMI3iOIH6VMktX2gBTd2CC48BACufJk6yWqRbhJiWqw3TdxuTnW45e3wdmEZAtODwwGTCKKmsz9InRCBuBHldQJkK/HUEnPNfBg9HGCNUmYxwc8/1mB@@YqdJmLaGYlOR2TswlgmEEBd38y7mPlxyslVzDEtEkOXs7jjbVFxZmkykgbS4dHMXg13P//ribGVa5jVAKbcpGx/fTps6GCcfFEhpts42wxLT7f@23IBycjumF7r8/Od/jvU59YoKtdFA@9bDB83X2Oyg7LuIOVDFYOp7Ao4ipq2E4/gE)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 53 bytes
```
(k=0;Do[k+=4Tr[1^PowerModList[-1,1/2,n]],{n,#^2}];k)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277XyPb1sDaJT86W9vWJKQo2jAuIL88tcg3P8Uns7gkWtdQx1DfSCcvNlanOk9HOc6oNtY6W1Ptf0BRZl6Jgr5Dur5DUGJeemq0gY6hQez//wA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [R](https://www.r-project.org), 49 bytes
```
\(n)sum(sapply(1:n^2,\(a)4*sum(!((1:a)^2+1)%%a)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY1LCsJADIb3nmJcFBI7QpNJx1HwJqUwCIOCltLHwrO4qYKH8jam-Nh8_4P85HbvpkfaP8chrcOLKmiwHy_Qx7Y9X4F2Tc22goiymuslaBWx5pwwyyIifofH_4CCTbhou1MzwAHEmmANeWscWyPqN6ph7rhQlJpoq2DWU_YKRxpdUCdSzBtFKRo9-d-_afroGw)
Uses the same OEIS chain [A000089](https://oeis.org/A000089) → [A304651](https://oeis.org/A304651) → [A175341](https://oeis.org/A175341) as in [@Arnauld's answer](https://codegolf.stackexchange.com/a/269991/55372).
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 96 bytes
```
.+
*_,$&*_,$&*
Lw`_+,_+,_*(?=_)
Am`^(__+)\1*,_+,\1*$
_+
$.&*$&
Cm`^(_+),\1(_*)(_*),\2$
.+
$.(4**
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9Pm0srXkdFDUJw@ZQnxGvrgJCWhr1tvCaXY25CnEZ8vLZmjKEWSBxIqXDFa3Op6KlpqahxOYOltTWB4hrxWpogrBNjpMKlB1KhYaKl9f@/AZchlxGXMZcJlykA "Retina – Try It Online") Link includes test cases. Explanation:
```
.+
*_,$&*_,$&*
```
Create a list `[r, r, r]` (in unary).
```
Lw`_+,_+,_*(?=_)
```
Create `r²` lists `[x=r..1, r, y=0..r-1]`.
```
Am`^(__+)\1*,_+,\1*$
```
Keep only the lists where `x` and `y` are coprime. (This particular implementation of the test assumes `x` is positive.)
```
_+
$.&*$&
```
Square `x`, `r` and `y`.
```
Cm`^(_+),\1(_*)(_*),\2$
```
Count (in decimal) the number of lists where `x²+y²<=r²`.
```
.+
$.(4**
```
Multiply by `4`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
I×⁴ΣE⊕XN²№Eι﹪⊕Xλ²ι⁰
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyQzN7VYw0RHIbg0V8M3sUDDMy@5KDU3Na8kNUUjIL88tQgoUlBa4leamwRka@ooGGkCCef8UqAJIPWZOgq@@SmlOflYdOZAVWcCsYEmGFj//2/5X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses the formulae from OEIS, `A175341(n)=A304651(n²)=4ΣA000089(n²)`.
```
N Input `n` as an integer
X Raised to power
² Literal integer `2`
⊕ Incremented
E Map over implicit range
№ Count of
⁰ Literal integer `0` in
ι Current value
E Map over implicit range
λ Inner value
X Raised to power
² Literal integer `2`
⊕ Incremented
﹪ Modulo
ι Current value
Σ Take the sum
× Times
⁴ Literal integer `4`
I Cast to string
Implicitly print
```
Note that the newer version of Charcoal on ATO allows you to vectorise the inner loop making it slightly more efficient, although the byte count is the same:
```
I×⁴ΣE⊕XN²№﹪⊕X…⁰ι²ι⁰
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjcrAooy80o0nBOLSzRCMnNTizVMdBSCS3M1fBMLNDzzkotSc1PzSlJTNALyy1OLgCIFpSV-pblJQLamjoKRJpBwzi8FmuCbn1Kak49FS1BiXnqqhoGOQiZMA4hhsKQ4KbkY6orl0Uq6ZTlKsQsNIHwA "Charcoal – Attempt This Online") Link is to verbose version of code.
[Answer]
# APL(NARS), 37 chars
```
+/{(1=∨/⍵)∧0≥-/2⌽∊2*⍨r⍵}¨,∘.,⍨r..-r←⎕
```
test:
```
+/{(1=∨/⍵)∧0≥-/2⌽∊2*⍨r⍵}¨,∘.,⍨r..-r←⎕
⎕:
10
192
+/{(1=∨/⍵)∧0≥-/2⌽∊2*⍨r⍵}¨,∘.,⍨r..-r←⎕
⎕:
0
0
+/{(1=∨/⍵)∧0≥-/2⌽∊2*⍨r⍵}¨,∘.,⍨r..-r←⎕
⎕:
5
48
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/266445/edit).
Closed 3 months ago.
[Improve this question](/posts/266445/edit)
Given input \$x \in \left\{0,3,6,...,90\right\}\$, output \$\sin\left(x°\right)\$ using integer and \$+ - \times \div ( ) \sqrt{\cdot}\$(square root), e.g. \$\sin(45°)=\sqrt{1\div 2}\$.
Flexible output format. You needn't do any simplification to output, aka. it's fine to output \$\sin(0°)=\sqrt{42}-\sqrt{6\sqrt{-9+58}}\$. Complex intermediate value is fine but please mention.
Shortest code wins.
[Answer]
# [Python](https://www.python.org), 89 bytes
```
c='s-1*'
y='/s+2/s++7s5s*6+5s522'
f=lambda d:d and'+*'+y+(x:=f(d-3))+'*'+c+x*2+c+y*2or'0'
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3I5Nt1Yt1DbXUuSpt1fWLtY2AWNu82LRYy0zbtNjUyEidK802JzE3KSVRIcUqRSExL0VdW0tdu1Jbo8LKNk0jRddYU1NbHSiSrF2hZQQkK7WM8ovUDdQhFqwuKMrMK9FI0wAqg4jArAYA)
It times out when trying to run it in ATO when trying to run it for large degrees, but it should work in theory. It outputs in prefix notation, where `s` is the unary square root operator; all other operators are binary. Furthermore, in this notation, there are only single digits (e.g. `20` represents a `2` then a `0`).
It works by repeatedly applying the formula
$$ \sin(a+3^{\circ}) = \sin(a) \cos(3^{\circ}) + \cos(a) \sin(3^{\circ}) \\
= \sin(a) \cos(3^{\circ}) + \sqrt{1-\sin(a)\sin(a)} \sqrt{1-\cos(3^{\circ})\cos(3^{\circ})}$$
where \$\cos(3^\circ) = \sin(87^\circ)\$ equals
$$\frac12 \sqrt{2+\frac12 \sqrt{7+\sqrt{5}+\sqrt{6(5+\sqrt{5})}}}$$
(according to Wolfram-Alpha).
[Answer]
# [Python 3](https://docs.python.org/3.8/), 75 bytes
```
lambda x:f"(1-1{(s:=x//3*'*(1+S(5)+S(S(20)-10))/(S(12)+S(-4))')})/S(-4{s})"
```
[Try it online!](https://tio.run/##Tc5BboMwEAXQNT7FKJvMpBBwnEYNKqdg282kNQ4SBmKjyiXK2alRq6qbP2/@6o9f03Xo1cvolsYNFt4tT1do7Ti4CfwtBnuohanelo7t5YMhlM0GZSbv6Msq5LnabXcon2p8phg1HgrKZEGUR8vD2mVHoi09KF959w/aLM3gIEDbg@PeaCzSs0oVlSLxUIHBQCKZo/Qnd@jjw97rdcvF47xvLRuCV5A6O4tkdG0/YUhh3jvNHQnx09DvNRjH/Fn984lo@QY "Python 3.8 (pre-release) – Try It Online")
This produces an expression with complex numbers as intermediates that can be evaluated in Python with `S=cmath.sqrt`. For instance, `x=3` gives:
```
(1*S(1+S(5)+S(2*S(5)-10))/S(S(12)+S(-4))-1/(1*S(1+S(5)+S(2*S(5)-10))/S(S(12)+S(-4))))/S(-4)
```
The main idea is to work with complex numbers, in particular roots of unity. Since \$e^{i \theta}\ = \cos(\theta) + i\sin(\theta)\$ where \$i = \sqrt{-1}\$, we can work with multiples of \$\theta\$ as
$$\ \cos(k\theta) + i\sin(k\theta)= e^{i k\theta}\ = \left(e^{i \theta}\right)^k = \left( \cos(\theta) + i\sin(\theta)\right)^k$$
From there, we can extract just the sine with:
$$\sin(k \theta) = \frac{\left(e^{i \theta}\right)^k-1/\left(e^{i \theta}\right)^k}{2i}$$
We can take the \$k\$ power by multiplying \$k\$ times, that is concatenating \$k\$ copies of `*stuff` in the expression, since the challenge doesn't allow exponents in the formula.
So we express \$e^{i \theta}\$ for \$\theta = 3^{\circ}\$ (three degrees), and take its \$k\$-th power by multiplying it \$k\$ times, using string repetition.
It remains to express \$e^{i \theta}\$ for \$\theta = 3^{\circ}\$. We could directly write out its sine and cosine, but it's a bit shorter to express it in terms of 36 and 30 degrees:
$$e^{i (3^\circ)} = \sqrt{e^{i (6^\circ)}} = \sqrt{e^{i (36^\circ)}e^{i (-30^\circ)}} = \sqrt{(\cos(36^\circ)+i \sin (36^\circ))(\cos(30^\circ)-i \sin (30^\circ))}$$
These angles have [relatively nice sines and cosines](https://en.wikipedia.org/wiki/Exact_trigonometric_values#Common_angles). A bit of tweaking and combining terms gives this in the code's notation as:
```
S((1+S(5)+S(2*S(5)-10))/(S(12)+S(-4)))
```
If we call `S(c)` the value above, the value we want to output is:
```
(S(c) - 1/S(c))/S(-4)
```
using that \$\sqrt{-4} = 2i\$. Finally, an improvement from @loopwalt that saved 6 bytes is to simplify this to
```
(1-c)/S(-4c)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 39 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.875 bytes
```
∆R∆sS
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwi4oiGUuKIhnNTIiwiIiwiNDUiXQ==)
Bitstring:
```
000100111011111001011001001010111111101
```
Outputs square root as `sqrt(...)`, and division as `/`. Uses sympy to calculate the exact sine value, and then casts to string.
## Explained
```
∆R∆sS­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌­
∆R # ‎⁡Convert the input to radians
∆s # ‎⁢find sine of that
S # ‎⁣cast to string, which stops conversion to float. Instead, it uses the exact representation, which is expressed in terms of integers.
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Python 3](https://docs.python.org/3/) + SymPy, ~~41~~ 39 bytes
```
lambda n:sin(rad(n))
from sympy import*
```
[Try it online!](https://tio.run/##FcsxDoAgDAXQ3VN0BMNgwiSJN3HBKEpiP01h4fQY3/6kt6fAj7Tt4418nJEQaobReBpYOyUtTLWzdMosRds8UlECZZBG3JdZ3Oqdt0E0oxm49L/xAQ "Python 3 – Try It Online") Link outputs all results from `0°` to `90°`. Edit: Saved 2 bytes thanks to @loopywalt.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~132~~ 110 bytes
```
f=->x{(x%60-24).abs==6?%w{(s5-1)/4 1/2 (s(30+s180)+s5-1)/8 1}[x/30]:"s(1/2+#{q=x<=>45}*(#{f[q*(x*2-90)]})/2)"}
```
[Try it online!](https://tio.run/##JcrdCsIgGADQV5GNwafL@beNFbkeRLxokODFoGWR4Xx2C7o9nMdr@ZTiNJ1jgtiMnMoed9claD1emneCMFCBWY8EkwgCKN4GMXHc/n1CIpvIFLenKsDvtHXadDzruR8ygTo5sxGIRNIjxzZjJnGVixLd06@3kHa/35HxRKuDM97aXL4 "Ruby – Try It Online")
While existing answers are very clever (and shorter than this!), the output expressions are rather long. This recursive function uses the half-angle formulas to produce expressions that fit on a single line in all cases.
Half angle formulas (rules for determining correct sign in all quadrants are unnecessary and omitted):
`cos(a/2)=sqrt(1/2+(cos a)/2)` or `cos x=sqrt(1/2+(cos x*2)/2)`
`sin(a/2)=sqrt(1/2-(cos a)/2)` or `sin x=sqrt(1/2-(cos x*2)/2)`
Below is a development version of the code, showing how the half angle formula is used to recursively derive expressions for all inputs. There are four infinite cycles as follows:
`30>30`, `90>90`, `18>54>18`, `78>66>42>6>78`. These are broken with explicit values for 30,90,18 and 78 (note even the fairly complex base expression for 78 is much simpler than the base expression for 3 used in other answers.)
**Development code with table showing how each value is derived by recursion**
```
f=->x{m=x%60
m==30?"1/2"[0,90/x]:m==18?"(sqrt5-1)/4/-2+(sqrt(30+sqrt180)/8"[0,x/13*11]:"sqrt(1/2+#{s=x<=>45}sin(#{s*(x*2-90)})/2)"}
```
[Try it online!](https://tio.run/##HYzRCoIwGIXve4pYBNt07f83DZVmDyK7CRJ2YZQzWOiefalXh@98nDN@H7@UeiPaMA8mnK9wGIzRcCcoFekgr0EG26wdVndC/WecSoFMFlKobEeqIdsSK2Cy2iZBouaItiG7X4@y0@xNuJm2KKN3L7oip4ErUQOLTCpGYtJ4mdzw9PPilvexc9zovO@ctTH9AQ "Ruby – Try It Online")
[Answer]
# [Mathematica/Wolfram](http://www.wolfram.com/mathematica), 27 bytes
```
f=FunctionExpand@Sin[#*°]&
```
[Try it online](https://tio.run/##y00syUjNTSzJTE78/z/N1q00L7kkMz/PtaIgMS/FITgzL1pZ69CGWLX/AUWZeSXRIYlJOanRadGZCloKxrE6CtWZOgoGOgrGBrWxsf8B) (thx to @noodle man)
This is a function solution - `#` introduces a placeholder for argument and `&` says whatever comes before is a pure function. `°` is builtin for number of radians in a degree, `@` is function application without brackets. Beyond that just relying on the underlying symbolic computation engine.
The full list of answers can be generated via:
```
Table[f[i * 3], {i, 0, 30}]
```
[](https://i.stack.imgur.com/lINfx.png)
] |
[Question]
[
# Challenge
Given input as a list/array of natural numbers that each represent the floor of a class a student has to go to, sort the numbers in a way such that the MAD (mean average deviation) number of flights between classes is minimized, thus saving energy and preventing the chance of being late to a class.
When sorted like this, the highest floor is in the middle of the list/array and the lowest floors are on the sides.
# Rules
* The student starts and ends on the first floor for entering and exiting the school building.
* The student only uses the stairs to get to each class.
* The list is in sequential order.
* This is code-golf, so answers will be scored in bytes with fewer bytes being the goal.
# Test cases
| Input | Possible Outputs |
| --- | --- |
| 8, 9, 6, 4, 7, 10, 5, 7, 8 | 4, 6, 7, 8, 10, 9, 8, 7, 55, 7, 8, 9, 10, 8, 7, 6, 4 |
| 4, 7, 3, 5, 7, 8, 4, 2, 4 | 2, 4, 4, 7, 8, 7, 5, 4, 33, 4, 5, 7, 8, 7, 4, 4, 2 |
| 4, 1, 2, 3, 2, 9, 4, 6, 2, 8 | 2, 2, 4, 6, 9, 8, 4, 3, 2, 11, 2, 3, 4, 8, 9, 6, 4, 2, 2 |
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
smy
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=smy&inputs=%5B8%2C%209%2C%206%2C%204%2C%207%2C%2010%2C%205%2C%207%2C%208%5D&header=&footer=)
Look ma, no Unicode!
```
s # Sort
m # Mirror, appending the reverse
y # Push every second item, and the rest.
```
[Answer]
# [Python 2 or 3](https://docs.python.org/3.8/), ~~40~~ 35 bytes
```
lambda a:a.sort()or(a+a[::-1])[::2]
```
**[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSHRKlGvOL@oREMzv0gjUTsx2spK1zBWE0gZxf4vKMrMK9FI04g20VEw1FEw0lEwBpOWOgpAETMw2yJWU/M/AA "Python 3.8 (pre-release) – Try It Online")**
### How?
Sort the input list, append (`+`) the sorted input list in reverse (`[::-1]`), take every other value (`[::2]`).
Note that `a.sort()` sorts `a` and returns `None`, which is falsey, and, as such, the `or` evaluates its right argument, `(a+a[::-1])[::2]` where we use the now sorted `a`.
[Answer]
# [jq](https://stedolan.github.io/jq/), 26 bytes
Takes a list of numbers as input, outputs as a stream. Uses the same method as Jonathan Allan answers.
```
sort|(.+reverse)[keys[]*2]
```
[Try it online!](https://tio.run/##yyr8/784v6ikRkNPuyi1LLWoOFUzOju1sjg6Vsso9v//aAsdBUsdBTMdBRMdBXMdBUMDHQVTMMsiFgA "jq – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṣm0m2
```
A monadic Link that accepts a list of positive integers and yields a list of positive integers.
**[Try it online!](https://tio.run/##y0rNyan8///hzkW5BrlG////jzbRUTDUUTDSUTAGk5Y6CkARMzDbIhYA "Jelly – Try It Online")**
### How?
```
Ṣm0m2 - Link: list of positive integers, F
Ṣ - sort F
m0 - append the reverse (m is overloaded to do this when given 0)
m2 - modulo-2 slice (get every other value)
```
[Answer]
# JavaScript (ES6), 54 bytes
```
f=a=>+a?a:[a.sort((a,b)=>b-a).pop(),...f(a)].reverse()
```
[Try it online!](https://tio.run/##bcxBCsIwEAXQvafIcgang7VaWyH1IKWLaU1FKU1ISq8fNYILcfP5MO/PQ1YJg7@7JZvt1cQ4atHNVi5yboWD9QuAUI@66TNBdtYBEjOPINixN6vxwQDGwc7BToYne4MR2opUTaokdSB1IpXvSB1TqzrEzQ/@mOJL0mr/yv82T8ciZZ1smfr7dXwC "JavaScript (Node.js) – Try It Online")
### How?
At each iteration, we pick the smallest element from the original array, append the result of a recursive call and reverse the resulting array. We stop when there's only one element remaining in the original array.
For the input `[8, 9, 6, 4, 7]`, this gives:
```
5th iteration: [ **9** ]
4th iteration: [ **8**, 9 ] -> [ 9, 8 ]
3rd iteration: [ **7**, 9, 8 ] -> [ 8, 9, 7 ]
2nd iteration: [ **6**, 8, 9, 7 ] -> [ 7, 9, 8, 6 ]
1st iteration: [ **4**, 7, 9, 8, 6 ] -> [ 6, 8, 9, 7, 4 ]
```
[Answer]
# [Factor](https://factorcode.org/), 55 bytes
```
[ natural-sort dup <evens> swap <odds> reverse append ]
```
[Try it online!](https://tio.run/##RY69CsJAEIR7n2JewGBMjImK2ImNjViJxZGsEgyXc2/jD@KznxsULIb55mOLPZlSWg773Wa7nsG3LLU940JsqYGna0e2JB/RQ9j4v4BjEnk6rq1gPhi8kKNAhhRTxCNMtHK8Vfci@e0UY83XxsqJplDOtPU6HGCNdGyaYf8Hqs5hQTeyfgl/NzraqlJmdewJxjmyFY5BuF4h8igbMhw@ "Factor – Try It Online")
## Explanation
It's a quotation (anonymous function) that takes a sequence from the data stack and leaves a sequence on the data stack. Assuming `{ 8 9 6 4 7 10 5 7 8 }` is on the data stack when this quotation is called...
| Word | Comment | Data stack (top on right) |
| --- | --- | --- |
| `natural-sort` | Sort into ascending order | `{ 4 5 6 7 7 8 8 9 10 }` |
| `dup` | Copy top of stack | `{ 4 5 6 7 7 8 8 9 10 } { 4 5 6 7 7 8 8 9 10 }` |
| `<evens>` | Get elements at even indices as a virtual sequence | `{ 4 5 6 7 7 8 8 9 10 } T{ evens { seq { 4 5 6 7 7 8 8 9 10 } } }` |
| `swap` | Swap top two data stack objects | `T{ evens { seq { 4 5 6 7 7 8 8 9 10 } } } { 4 5 6 7 7 8 8 9 10 }` |
| `<odds>` | Get elements at odd indices as a virtual sequence | `T{ evens { seq { 4 5 6 7 7 8 8 9 10 } } } T{ odds { seq { 4 5 6 7 7 8 8 9 10 } } }` |
| `reverse` | Reverse a sequence | `T{ evens { seq { 4 5 6 7 7 8 8 9 10 } } } { 9 8 7 5 }` |
| `append` | Append a sequence to another sequence | `{ 4 6 7 8 10 9 8 7 5 }` |
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{«ι
```
Outputs both possible results. If this is not allowed, add a trailing `н` or `θ` to leave just the first or last list of the pair instead.
[Try it online](https://tio.run/##yy9OTMpM/f@/@nDTodXndv7/H22ho2Cpo2Cmo2Cio2Cuo2BooKNgCmZZxAIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/6sNNh1af2/lf5390tIWOgqWOgpmOgomOgrmOgqGBjoIpmGURq6MQDRE0houBlRkBSaikIZhnDCYtwZJmYDZYsxFYwBQsZhkbCwA).
**Explanation:**
```
{ # Sort the (implicit) input-list
 # Bifurcate it, short for Duplicate & Reverse copy
« # Merge the lists together
ι # Uninterleave it into two lists
# (after which this pair of lists is output implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~45 38~~ 36 bytes
```
->l{a=0;l+l.sort!.map{l.slice!a-=1}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOtHWwDpHO0evOL@oRFEvN7GgGsjOyUxOVUzUtTWsrf1foJAWHW2ho2Cpo2Cmo2Cio2Cuo2BooKNgCmZZxMb@BwA "Ruby – Try It Online")
### How on earth?
I think this should be undefined behaviour, but somehow it works:
* `l.sort!` is the first step, we need a sorted array to perform our magic
* `l.sort!.map` does not iterate on the **original** array and will stop as soon as it reaches the last element of the **current** array.
* `l.slice!a-=1` gets the elements in reverse order, skipping one at every iteration. The first element will be the max, on the second iteration, we will get the second last, which will be the 3rd highest number (because the max was removed, and the last element is now the 2nd highest number). And so on.
* Finally, `l+l.sort!.map{...}` will join the remaining element in l with the result of the mapping operation. Again, we are not using the original array to perform the addition, but the current array.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~11~~ 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
]êsx{▐x
```
-4 bytes by porting [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/235808/52210) (with an iterative instead of recursive approach).
[Try it online.](https://tio.run/##y00syUjPz0n7/z/28KriiupH0yZU/P9voWOpY6ZjomOuY2igYwqkLLhAHGMIGyhhpGMCFDEE0sZAbAkUMQPSFlxAcaAaMx1LAA)
**Explanation:**
```
] # Wrap the stack into a list, so we start with an empty list []
ê # Push the inputs as an integer-array
s # Sort it
x # Reverse it
{ # Loop over these descending sorted values:
▐ # Append the current value to the list
x # And reverse the entire list
# (after the loop the entire stack is output implicitly as result)
```
[Answer]
# [Wolfram](https://www.wolfram.com/language/), 33 bytes
```
Join[#,Reverse@#][[;;;;2]]&@*Sort
```
[Try it here!](https://tio.run/##y00syUjNTSzJTE78n6lgq1BtoqNgrqNgrKNgCmZY6CgARYyAZK01V5qC7X@v/My8aGWdoNSy1KLiVAfl2OhoayAwio1Vc9AKzi8q@R9QlJlX4pDmkPkfAA)
Logic copied from other answers. Sort, join with reverse, take every other item
[Answer]
# [R](https://www.r-project.org/), ~~41~~ 37 bytes
*-4 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
function(x)c(y<-sort(x),rev(y))[!1:0]
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjNZo9JGtzi/qATI1ilKLdOo1NSMVjS0Moj9n6aRrGGho2Cpo2Cmo2Cio2Cuo2BooKNgCmZZaGpygRRAxI3hwmCVRkASIW8IFjAGk5ZgeTMwG2jEfwA "R – Try It Online")
Uses the most common strategy here.
The index `!1:0` is recycled to vector length and therefore alternates `FALSE TRUE FALSE TRUE...` to get every second element.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~154~~ \$\cdots\$ ~~119~~ 117 bytes
```
i;j;k;*b;*f(a,l)int*a;{i=j=qsort(a,l,4,L"\x62b078bǃ");b=malloc(4*l);for(k=-~l-l%2;i<l;j+=2)b[i++]=a[j/l?k-=2:j];a=b;}
```
[Try it online!](https://tio.run/##rVNdb5swFH3vr7CQUgExamLyWZf1Ydrb/kGCJiCmg7hJhpEWNcpe9uP2r8YutgGHpH1apBjb99x7zj22E@8lSaoqozndUjembmpHmDvZrnQjesqCPPgh9kVZb@IJ/mqtjzMSj@aL@M9vy6Fx8Bpxvk/sicsdmu4Lext4v7jHB4RmT5zmw4A48SobDsMgWuUP/HnrBeQxD2kUxPRcAQ16jbKd7aDTHYJfvVEyUX4br0IUoNMCoyVGM4wmGM0xGo8wmsrZ4kw7MFFghfFbiMwiMJpYv8WOZdCX41JiZ3IOpS@0cJUhsje2T22lznnQS1evMTLjpBcnvbjfi/tOx@lKUqFIVXWs29Rf3xDIjgeWlGzTGKa6UN3Xbi3lDNZTbUKboE0jsvNJkzOX7sHS7@O1ca1rE4lvTwc2idlEk6eyOpnYUGDMb/V0aXxXojPP2MN9GLkBM86hY76Ba88j@R4VLows2bJCyYEn8IWsj8vP8J9aGJlr39J58BSQXfeS7TbsCGkjqqdPfQHX9A5Fw6FEN8@icYZDJXUlZTikZhQujg6Lq/ChAEBqWyt4tO1mKzJXAnMQx2vu3OQ10wdisIGW8@e670cLxnKVh0bJ8xVjiLxP6IJWShVACY8BI/6fBYn3BKlbCYXbm3nDQ8S4gbhpMzpEolY//lg3e0e4Spaf@3upFgXACN@PXRyI9Q7aa65iXcDsMy0Ys4XeON@dq79JyqMXUXk/K@@NHVkiyijZ/gM "C (gcc) – Try It Online")
*Saved a whopping 21 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) and his execstack magic!!!*
Inputs the a pointer to an array of floors of classes that a student has to go to as natural numbers \${1 \dots n}\$, and the array's length (because pointers in C carry no length information).
Return a pointer to an array of the floors sorted so that the mean average deviation of flights between classes are minimized.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~23~~ 18 bytes
```
W⌈⁻θυF№θι≔⮌⊞OυιυIυ
```
[Try it online!](https://tio.run/##HYxNC8IwEETv/oo9biBe/EChJ@m5WLyWHkKJZiFNdDep/vuY9jIMj3kzOcNTNL6UryNvATvzoznP2FHIgh8NWSkFz8iAbcwhrYgquYnQK@DDLpbFYp/F3d@WTYqMeZusarPrmarUGklYn5pShuGk4aLhqOG8lauGSg41x7HsF/8H "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @KevinCruijssen's answer.
```
W⌈⁻θυ
```
Repeat until the output contains all of the floors in the input list (fortunately floors are 1-indexed in the US, so the maximum only becomes falsy when the set difference is empty).
```
F№θι
```
Repeat once for each occurrence of the maximum floor in the input list.
```
≔⮌⊞Oυιυ
```
Push the maximum floor to the predefined empty list, then reverse it.
```
Iυ
```
Output the resulting list.
[Answer]
# TI-Basic, 49 bytes
```
Prompt A
SortA(ʟA
dim(ʟA
seq(2fPart(I/2)(I-Ans-.5)+Ans-I/2+1,I,1,Ans→B
SortA(ʟB,ʟA
```
Input is sorted in-place.
[Answer]
# [Arturo](https://arturo-lang.io), 36 bytes
```
$=>[x:sort&map x++reverse x[a,b]->a]
```
[Try it](http://arturo-lang.io/playground?k8rs8b)
Sort, append reverse, take every other element.
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 8 \log\_{256}(96) \approx \$ 6.58 bytes
```
z:DrA+Zl
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhYrqqxcihy1o3IgXKjogj3RFjoKljoKZjoKJjoK5joKhgY6CqZglkUsRA0A)
Outputs both possible results. For the first, add a trailing `AJ`, and for the second, add a trailing `AK`.
#### Explanation
```
z:DrA+Zl # Implicit input
z: # Sort
Dr # Bifurcate
A+ # Concatenate
Zl # Uninterleave
# Implicit output
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~7~~ ~~6~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Íê1 ë
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=zeoxIOs&input=WzgsIDksIDYsIDQsIDcsIDEwLCA1LCA3LCA4XQ)
] |
[Question]
[
In this challenge you will be determining how controversial a vote is, given an array of other votes, by figuring out a number called the C-factor. What is the C-factor, you ask?
Well, imagine you've got multiple votes on an election. We'll use `1` and `0` for the sake of the challenge to represent two different candidates in an election. Here's the ten votes in our sample election:
```
0110111011
```
Now, say we want to find the C-factor of any vote for candidate `0`. We can do that with the following function:
$$
f(o,v) = abs(o-mean(v))
$$
In \$f\$, `o` is the vote we want to determine the C-factor for, and `v` is an array of votes. So, using our function, to get the C-factor of any vote for candidate `0`:
$$
f(0, [0,1,1,0,1,1,1,0,1,1]) = 0.7
$$
A lower C-factor shows that the vote was less controversial in comparison to the other votes. So, a vote for candidate `0` is more different from the other votes than a vote for candidate `1`. In comparison, the C-factor for a candidate `1` vote is \$0.3\$, so it is less controversial because it is more like the other votes.
## The Challenge
Write a function \$f(o,v)\$ to determine the C-factor of a vote `o` given results of a vote `v`.
* `o` must be an integer, either `0` or `1`.
* `v` must be an array (or similar container type depending on language specifications) of arbitrary length containing zeroes and ones.
* The function should return or print to the console the resulting C-factor given the function parameters, using the formula above or a modified method.
Good luck! The least bytes wins (winner chosen in five days).
[Answer]
# [R](https://www.r-project.org/), 23 bytes
```
function(o,v)mean(o!=v)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jX6dMMzc1EchQtC3T/J@mYaCTDMSGQAghobSm5n8A "R – Try It Online")
The challenge boils down to computing the proportion of values in `v` different from `o` (i.e. `mean(xor(o,v))`). We can therefore avoid using `abs`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ạÆm
```
[Try it online!](https://tio.run/##y0rNyan8///hroWH23L///9v8N9AxxAIISSUBgA "Jelly – Try It Online")
Literally just "absolute difference to mean".
```
ạÆm Main link
ạ Absolute difference
Æm Arithmetic Mean
```
If you invert the arguments you can invert the atoms.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~9 8~~ 5 bytes
```
≠⌹⊢=⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hngkc9Ox91LbIF4v9pj9omPOrte9Q31dP/UVfzofXGj9omAnnBQc5AMsTDM/i/oUKagoGCIRBCSCgNAA "APL (Dyalog Unicode) – Try It Online")
Anonymous train. Thanks to @Adám for a byte saved, and thanks to @ngn for 3 bytes!
### How:
```
≠⌹⊢=⊢ ⍝ Anonymous Train
⊢ ⍝ The right argument (⍵)
⊢= ⍝ Equals itself. Generates an array of 1s
≠ ⍝ XOR left (⍺) and right args; generates ⍵ or (not ⍵), depending on ⍺.
⌹ ⍝ Divide these matrices.
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 3 bytes
```
♀^æ
```
[Try it online!](https://tio.run/##S0wuKU3Myan8///RzIa4w8v@/4820DEEQggJpWO5DAA "Actually – Try It Online")
Explanation:
```
♀^æ
♀^ XOR each vote with candidate (0 if matches, 1 if not)
æ mean of the list
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
ÅAα
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cKvjuY3//0cb6BgCIYSE0rFcBgA "05AB1E – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 16 bytes
```
@(a,b)mean(a!=b)
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjUSdJMzc1MU8jUdE2SfN/moaBTrSBjiEQQkgoHav5HwA "Octave – Try It Online")
[Answer]
# Elm 0.19, 48 bytes
```
f a v=abs(v-(List.sum a/toFloat(List.length a)))
```
Online demo [here](https://ellie-app.com/5RXLTSKHBZva1).
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), ~~11~~ 8 bytes
```
Mean@`/=
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@983NTHPIUHf9r9fampKcbRKQUFyeixXQFFmXklIanGJc2JxanG0WpqOQjSXAhBEG@iAsCEQQkgoHRurA5E3xCXPFRv7HwA "Attache – Try It Online") Takes arguments as `f[o, v]`.
Nothing terribly original.
## Alternative approaches
**11 bytes:** `Average@`/=`
**11 bytes:** `${1-x~y/#y}` Counts the occurrences of `x` in `y` divided by the length of `y`, then subtracts that from `1`.
**11 bytes:** `{1-_2~_/#_}` (Arguments are reversed for this one)
**15 bytes:** `${Sum[x/=y]/#y}` A more explicit version of the above, without `Average`.
[Answer]
# JavaScript, 38 bytes
```
n=>a=>a.map(x=>n-=x/a.length)|n<0?-n:n
```
[Try it](https://tio.run/##LYVBCoAgEAC/o5Bm10h7SHRYTK2wVUrCQ383oZhhZocbLn1uMTEMiylWFpQKqvyASLJUyGRugXuDLq30wUGMDHssOuAVvOE@OGKJoGQSTVf5@n@mtLw)
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 26 bytes
```
(o,v)=>1-v.count(o)/len(v)
```
[Try it online!](https://tio.run/##KyjKL8nP@59m@18jX6dM09bOULdMLzm/NK9EI19TPyc1T6NM839BUSaQn6ZhoKMQDcSGYARnINixmpr/AQ "Proton – Try It Online")
The output is a fraction because Proton uses sympy instead of regular Python numbers for better precision.
(-7 bytes; abs-diff to mean is shorter than mean of abs-diff; I'm actually dumb)
-1 byte thanks to Rod
[Answer]
# [Perl 6](http://perl6.org/), 20 bytes
```
{@_.sum/@_}o(*X!= *)
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2iFer7g0V98hvjZfQytC0VZBS9P6f3FipUKahoGOAggbghGcgWBrav4HAA "Perl 6 – Try It Online")
`* X!= *` is an anonymous function which takes the not-equals cross product of its two arguments. It produces a sequence of Booleans; for example, `1 X!= (1, 0, 1)` evaluates to `(False, True, False)`.
`{ @_.sum / @_ }` is another anonymous function that returns the average of its arguments. Boolean `True` evaluates to `1` numerically, and `False` to `0`.
The `o` operator composes those two functions into one.
[Answer]
# [Enlist](https://github.com/alexander-liao/enlist), 3 bytes
```
nÆm
```
[Try it online!](https://tio.run/##S83LySwu@f8/73Bb7v///w3/G@gYAiGEhNIA "Enlist – Try It Online")
```
nÆm Main Link
n Not Equals (returns a list of whether or not each element is unequal to to the value)
Æm Arithmetic Mean
```
The language is very heavily inspired by Jelly to the point that it's probably more like me experimenting to try to recreate the structure of how Jelly is parsed with my own code.
-1 byte thanks to Mr. Xcoder
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 27 bytes
```
(.),((?(\1)|()).)*$
$#3/$#2
```
[Try it online!](https://tio.run/##K0otycxL/P9fQ09TR0PDXiPGULNGQ1NTT1NLhUtF2VhfRdno/38DHQNDQyACYQA "Retina 0.8.2 – Try It Online") Outputs a fraction. Explanation: The first group captures `o` and the second group captures each entry of `v`, while the conditional ensures that the third group only makes a capture when the vote is dissimilar. The `$#` construction then returns the count of the relevant captures as desired.
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=sum`, 30 bytes
```
sub f{abs((shift)-sum(@_)/@_)}
```
[Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhrToxqVhDozgjM61EU7e4NFfDIV5TH4hr/xcnViqkaRjoGOgYAiGEhNKa///lF5Rk5ucV/9f1NdUzMDQA0j6ZxSVWVqElmTm2QHMA "Perl 5 – Try It Online")
[Answer]
# [K (Kona)](https://github.com/kevinlawler/kona), 17 bytes
```
{_abs+/y-x%.0+#x}
```
[Try it online!](https://tio.run/##y9bNzs9L/P8/zao6PjGpWFu/UrdCVc9AW7mi9n9atIGCIRBCSChtbRD7HwA "K (Kona) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 62 bytes
```
float f(o,v,l,k)int*v;{float r=0;for(k=l;k;)r+=v[--k]^o;r/=l;}
```
[Try it online!](https://tio.run/##hZDLDoIwEEXX8BUTjQnVopTHquKPoCYGqDYgNaWyIXw71heiMZDMYjI990zb2D7GcduyXBwUMEvgCuc4Q7xQ84rWz7EMHcqEtLIwpxlFchFWkW1nu72gcqVnTTvlRZxfkxTWpUq4WJ42pqkVcD7wwqoETxDUpnGfqLRUJCLODkKoHQzkUV3z6Rv6CbjvAOlxv9UPeBEEvcAfpR8R71s5chnTuEgdZtZkxrbFBOvP0oeP52jAQYj@Icgo8XK4ow531OFhgGDQMUC8HL7e4g06OqJpbw "C (gcc) – Try It Online")
Call as `f(int o, int *v, int length_of_v)`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 6 bytes
```
aVx÷Vl
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=YVZ491Zs&input=MApbMCwxLDEsMCwxLDEsMSwwLDEsMV0)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~47~~ 42 bytes
*-5 bytes from @arnauld*
```
a=>b=>Math.abs(a-eval(b.join`+`)/b.length)
```
[Try it online!](https://tio.run/##LcUBCoAgDEDR62xUVgewG3SCCJplpYiLFK@/guLD@54KpfV2V24ib1Z2LaQHo4eR8qnIJKDGFgpglGcXl2rB1qhg45FPlJVj4mBV4AN26BCmru7fPv/PiPIA "JavaScript (Node.js) – Try It Online")
[Answer]
# Java 8, 47 bytes
```
v->o->(o-=v.get().sum()/v.get().count())<0?-o:o
```
[Try it online.](https://tio.run/##fVFLa8MwDL73V4icbJpo7bWPjMHYbacetx28PIrbxAqxbCijvz3TkozuMIpBD/RJ@j75ZKLJTuV5KBrjPbwa674WAJ4N2wJOUsXAtsE6uIItOXyZg90/tUPousZW/Z@a574yLT5T@Gyqw5jk6d25EzSFyec51LCHIWY5ZbmibB/xWLHS6EOr9MNvVlBw4vVu9ZjRhobtQlR0MkFUzGIi2RJaEaiEh3XHtw8w@kcsAFee1apMYZWu5U129np7g6zvQK6L293GVWNHOaoASmGKEBHivPVw8Vy1SIGxE0LcOJXQPlnSMgHjSogS3y711Pfm4pFpYq@iFtjmnZNxFsCyRiPnvyils/zuByDV0q1nOOmZ/nX4Bg)
or alternatively:
```
v->o->Math.abs(o-v.get().sum()/v.get().count())
```
[Try it online.](https://tio.run/##fVFNa8MwDL33V4icbJpo7XVdA4OxW089bju4@WjdJVaIZUMZ/e2ZlmR0h1EM@kBP0nvy2USTncvPoWiM97Az1n0tADwbtgWcpYqBbYN1cAVbcvg6B0//1Pah6xpb9X9qnvvKtPhC4dBU@zHJ07tzJ2gKk89zqGELQ8xyyvKd4ROag1eURTxWrDT60Cr98JsVFJx4PWwWoqKTCaJiFhPJltCKQCU8rDu@fYDRP2IBuPKsVmUKq3Qtb7Kz15sbZH0Hcl3c7jauGjvKUQVQClOEiBDnrfuL56pFCoydEOLGqYS2yZKWCRhXQpT4dqnnvjcXj0wTexW1wB7fORlnASxrNHL@i1I6y@9@AFIt3XqGk57pX4dv)
For both the inputs are a `Supplier<DoubleStream>` for the list of votes `v` and `double` for the vote `o`.
**Explanation:**
```
v->o-> // Method with DoubleStream-Supplier & double parameters and double return
(o-=v.get().sum() // Get the sum of the DoubleStream-Supplier
/v.get().count() // Divide it by the amount of items in the DoubleStream-Supplier
) // Subtract this from `o`
<0?-o:o // And get the absolute value of this updated value `o`
```
[Answer]
# [Common Lisp](https://lisp-lang.org/) 49 bytes
**Solution:**
```
(defun c(o v)(abs(- o(/(reduce'+ v)(length v)))))
```
[Try it online](https://tio.run/##dYrBDkAwEETvvmJvphGhn8RaNJGStvj8peHgYiaZmUweLy5uqhhk3D0xVjoMuj6iphUNggw7S1nldxE/pfleWUWBM7gkBKaWSrRkbz/5dqaQJGzBmQ9tf2nVCw)
**Explanation:**
```
(defun c(o v)
(abs (- o (/ (reduce '+ v) (length v)))))
```
* reduce applies an function over all list elements (+ in this case)
* rest is just the base function, abs(o - mean(v))
[Answer]
# [Ruby](https://www.ruby-lang.org/), 31 bytes
```
->o,v{v.count(1-o)/v.size.to_f}
```
[Try it online!](https://tio.run/##KypNqvz/v6C0pFhB1y5fp6y6TC85vzSvRMNQN19Tv0yvOLMqVa8kPz6tNtpAB4gMgRBCQunY2P//AQ "Ruby – Try It Online")
[Answer]
# Pyth, 4 bytes
```
aE.O
```
Explanation:
```
( implicitly set Q = eval(input()) )
a Absolute difference between
E eval(input()) (this is the second line of input taken)
.O and the average of
Q (implicit) Q (the first line of input)
```
Input is in the format of:
```
[0,1,1,0,1,1,1,0,1,1]
0
```
with the array of votes first, and the candidate second.
[Try it online!](https://tio.run/##K6gsyfj/P9FVz////2gDHUMghJBQOpbLAAA)
] |
[Question]
[
I saw [another prime challenge](https://codegolf.stackexchange.com/questions/144633/how-many-unique-primes) coming by in PPCG, and I do love me some primes. Then I misread the introductory text, and wondered what the creative brains here had come up with.
It turns out the question posed was trivial, but I wonder if the same is true of the question I (mis)read:
---
\$6\$ can be represented by \$2^1\times3^1\$, and \$50\$ can be represented by \$2^1\times5^2\$.
## Your task:
Write a program or function to determine how many distinct primes there are in this *representation* of a number.
## Input:
An integer \$n\$ such that \$1 < n < 10^{12}\$, taken by any normal method.
## Output:
The number of distinct primes that are required to *represent the unique prime factors* of \$n\$.
## Test cases:
```
Input Factorisation Unique primes in factorisation representation
24 2^3*3^1 2 (2, 3)
126 2^1*3^2*7^1 3 (2, 3, 7)
8 2^3 2 (2, 3)
64 2^6 1 (2) (6 doesn't get factorised further)
72 2^3*3^2 2 (2, 3)
8640 2^6*3^3*5^1 3 (2, 3, 5)
317011968 2^11*3^5*7^2*13^1 6 (2, 3, 5, 7, 11, 13)
27 3^3 1 (3)
```
This is not an OEIS sequence.
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆFFQÆPS
```
**[Try it online!](https://tio.run/##y0rNyan8//9wm5tb4OG2gOD///8bG5obGBpamlkAAA "Jelly – Try It Online")** or **[Check out the test Suite.](https://tio.run/##y0rNyan8//9wm5tb4OG2gOD/h9sfNa1x//8/2shER8HQyExHwUJHwdwISJmZGOgoGBuaGxgaWppZxAIA)**
## How?
```
ÆFFQÆPS ~ Full program.
ÆF ~ Prime factorization as [prime, exponent] pairs.
F ~ Flatten.
Q ~ Deduplicate.
ÆP ~ For each, check if it is prime. 1 if True, 0 if False.
S ~ Sum.
```
[Answer]
# Mathematica, 39 bytes
```
Count[Union@@FactorInteger@#,_?PrimeQ]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zm/NK8kOjQvMz/PwcEtMbkkv8gzryQ1PbXIQVkn3j6gKDM3NTBW7T@QkVei4JAebWxobmBoaGlmEfv/PwA "Wolfram Language (Mathematica) – Try It Online")
thanks to Martin Ender (-11 bytes)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~9~~ 7 bytes
Saved 2 bytes thanks to *Kevin Cruijssen*
```
ÓsfìÙpO
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8OTitMNrDs8s8P//38LMxAAA "05AB1E (legacy) – Try It Online")
**Explanation**
```
Ó # push the prime factor exponents of the input
sfì # prepend the prime factors of the input
Ù # remove duplicates
p # check each if it is prime
O # sum
```
[Answer]
# [R](https://cran.r-project.org/) + [numbers](https://cran.r-project.org/package=numbers), ~~80~~ 78 bytes
```
function(n)sum(isPrime(unique(unlist(rle(primeFactors(n))))))
library(numbers)
```
[Try it online!](https://tio.run/##HYq7DcAgDAX7TPIYIUXa1FkBEEiWwCQ2LjK987nmpNOJ182rcZ40GBzUOkgPoV5gTJd9aqQT0grOr@8xzyH6zj9LoyRRbrD1VESDV6zBHw "R – Try It Online")
Similar to Giuseppe (using `numbers` package and `rle`) but no assignments.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
&YFhuZpz
```
[Try it online!](https://tio.run/##y00syfn/Xy3SLaM0qqDq/39jQ3MDQ0NLMwsA "MATL – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 6 bytes
```
ḋ_uṗ¦Σ
```
[Try it online!](https://tio.run/##S0/MTPz//@GO7vjShzunH1p2bvH//8aG5gaGhpZmFgA "Gaia – Try It Online")
---
* `ḋ` computes the prime factorization, as **[prime, exponent]** pairs.
* `_` flattens the list.
* `u` removes duplicate elements.
* `ṗ¦` maps through the elements and returns **1** if a prime is found, **0** otherwise.
* `Σ` sums the list.
[Answer]
## CJam (13 bytes)
```
{mFe__&:mp1b}
```
[Online test suite](http://cjam.aditsu.net/#code=qN%25%7B~%5C%0A%0A%7BmFe__%26%3Amp1b%7D%0A%0A~%3D%7D%2F&input=24%202%0A126%203%0A8%202%0A72%202%0A8640%203%0A317011968%206%0A27%201)
This is pretty straightforward: get primes with multiplicities, reduce to distinct values, filter primes, count.
Sadly [Martin](https://codegolf.stackexchange.com/users/8478/martin-ender) pointed out some cases which weren't handled by the mildly interesting trick in my original answer, although he did also provide a 1-byte saving by observing that since `mp` gives `0` or `1` it can be mapped rather than filtered.
[Answer]
# [Ohm v2](https://github.com/MiningPotatoes/Ohm), ~~6~~ 5 bytes
-1 byte thanks to @Mr.Xcoder
```
ä{UpΣ
```
[Try it online!](https://tio.run/##y8/INfr///CS6tCCc4v//zc2NDcwNLQ0swAA "Ohm v2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode) + `dfns`](https://www.dyalog.com/), 29 bytes
```
⎕CY'dfns'
{≢∪⍵/⍨1pco⍵}∘∊2pco⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVOdI9ZS0vGJ1rupHnYsedax61LtV/1HvCsOC5Hwgs/ZRx4xHHV1GIF7Xov9pj9omPOrte9TV/Kh3zaPeLYfWGz9qmwg0JTjIGUiGeHgG/09TMORKUzACYmMgNgFiQxMA "APL (Dyalog Unicode) – Try It Online")
-6 bytes from Adám.
## Explanation
```
{≢∪⍵/⍨1pco⍵}∘∊2pco⊢ ⊢ → input
2pco prime factors and exponents as matrix
{ }∘∊ flatten and use as right arg for:
⍵/⍨ filter out values in arg
1pco⍵ which aren't prime
≢∪ count the unique values
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 7 bytes
```
w♂i╔♂pΣ
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/7/80cymzEdTpwCpgnOL//83NjQ3MDS0NLMAAA "Actually – Try It Online")
Explanation:
```
w♂i╔♂pΣ
w factor into [prime, exponent] pairs
♂i flatten to 1D list
╔ unique elements
♂p for each element: 1 if prime else 0
Σ sum
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~142~~ ~~135~~ 119 bytes
```
f=lambda n,d=2:n-1and(n%d and f(n,d+1)or[d]+f(n/d))or[]
p=f(input())
print sum(f(n)==[n]for n in set(p+map(p.count,p)))
```
[Try it online!](https://tio.run/##JY/BCoMwEETvfsUiFLKYtiYVtUK@RDxYozRQN0EjtF9v1/a0M8ODmQ2f@PSk98HbEQykabpP5tXPD9sDSWt0Q2fVkxV0ssAXJsFxptAvre0ydleLh@mSYCbhKGxRICZhcRRh3WbBCBrTUjf5BQgcwTpGEbK5DyJcBr9RlAERd@5ODsYdTKsLCUqXEmoJJetKsyyLXMJNVblS97LumgTg18jL/5sbcJyN73EQx0e4fwE "Python 2 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~11~~ 10 bytes
```
#ṗuS+omLgp
```
[Try it online!](https://tio.run/##yygtzv7/X/nhzumlwdr5uT7pBf///zc2NDcwNLQ0swAA "Husk – Try It Online")
---
**EDIT:** Saved 1 byte thanks to [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
ḋọcdṗˢl
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmJiBXA8h5uKP74e7e5JSHO6efXlSupKn0cFdn7cOtE/6jSOT8/x9tZKJjaGSmY6FjZqJjbqRjYWZioGNsaG5gaGhpZqFjZB4LAA "Brachylog – Try It Online")
```
The output
l is the length of
c the concatenated
ọ list of pairs [value, number of occurrences]
ḋ from the prime factorization of
the input
d with duplicates removed
ṗˢ and non-primes removed.
```
A fun 9-byte version: [`ḋọ{∋∋ṗ}ᶜ¹`](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmJiBXA8h5uKP74e7e5JSHO6efXlSupKn0cFdn7cOtE/5DJKofdXQDEVC29uG2OYd2/v8fbWSiY2hkpmOhY2aiY26kY2FmYqBjbGhuYGhoaWahY2QeCwA)
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rprime`, 66 bytes
```
->n{Prime.prime_division(n).flatten.uniq.count{|i|Prime.prime? i}}
```
[Try it online!](https://tio.run/##bZHRToMwFIbveYqTeCEljKztKPNCfQXvl80gFNdEC5ZiYoBXtx7QsG7uJO3Vl//Pd47pXr5cde9WD7p/MupdJs30P5fqU7Wq1qEmSfWWWyt10mn1kRR1p20/qMGjH0GNo9uxTXwDf8MOPOIHCt4wCFkMnASUCR@kCLIoO8H8F4whI8H2RM6hcDFLqPDKERSXIEWQQCigrGWrby28SgtVXtjaqFaWUHXGHqUhQcbOgiYNdrVxKzbrBcVGBHmUXtFIScBptqb0Tsw6qDw5p@jMIjpvSSwsWsdAKT6sYJlnz//boxRS@0TmxbEf7NBAtbP70X3XjcXjtW5l5gP9AA "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
k
âUü ml)èj
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=awriVfwgbWwp6Go&input=MzE3MDExOTY4)
## Alternative
```
k
â¡x¶X})xj
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=awrioXi2WH0peGo&input=MzE3MDExOTY4)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
#ṗuṁS:Lgp
```
[Try it online!](https://tio.run/##yygtzv7/X/nhzumlD3c2Blv5pBf8///f2NDcwNDQ0swCAA "Husk – Try It Online")
Slight improvement over Mr. XCoder's answer.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 37 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.625 bytes
```
ǐĊfUæ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBcz0iLCIiLCLHkMSKZlXDpiIsIiIsIjI0XG4xMjZcbjY0XG44XG4zMTcwMTE5NjggICJd)'
Takes the counts of the prime factorization which gives a list of [prime, exponent] for each prime, flattens, uniquifies, finds the primes.
[Answer]
# [Maxima](http://maxima.sourceforge.net/), 104 bytes
So long, it can be golfed much more.
[Try it online!](https://tio.run/##VcxNDoMgEAXgfU/BckhZCDXYn/QkjYupDikJIFVM8PTUrtTZfZP3nsdsPZZiIPD7043Uzx2BQ//uEV5ZLK3I54ULj3H7tsIaFkfrKULm6UOBSUZuIlZxMQf7nQmMw5QogDXYpWGc1v3/lcdpLYYEBlTN@Sap9J7XPfQh2ahDUNfV3hfZVFLe9GFANavKDw)
```
f(n):=lreduce(lambda([x,y],x+y),map(lambda([x],if primep(x)then 1 else 0),unique(flatten(ifactors(n)))))
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
smP_d{+PQlM.gkP
```
**[Try it here!](https://pyth.herokuapp.com/?code=smP_d%7B%2BPQlM.gkP&input=8640&test_suite=1&test_suite_input=24%0A126%0A8%0A72%0A8640%0A317011968&debug=0)**
[Answer]
# [R](https://www.r-project.org/) + numbers, 92 bytes
```
function(n)sum(1|unique((x=c((r=rle(primeFactors(n)))$l,r$v))[isPrime(x)]))
library(numbers)
```
[Try it online!](https://tio.run/##FcqhDsIwFAVQv69ATNybgBgKwSwaTxBb0yYvad/gdY@MhH8voM@xlnbnQ0uuYZVFoaxeMHxc5ekR2MYA2Gg54mFS4mUK62L198g@761/kTep179h453sssw22RvqZY5W2RKGI7uEE9sX "R – Try It Online")
[Answer]
# J, 20 bytes
```
3 :'+/1 p:~.,__ q:y'
```
Counted by hand lol, so tell me if this is off.
Any golfing suggestions?
Boring submission: flatten the prime factorization table and count primes.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 47 bytes
```
n->#Set(select(isprime,concat(Vec(factor(n)))))
```
[Try it online!](https://tio.run/##FYpBCsMgEEWvMqSbCYwQbdBm0VyikE3oQkSLkBoxs@nprf7V@7yXbYnik2uAZ01ivb084@UP7xjjlUv8enJncpZx8w6DdXwWTGNftTkfP0wgVmhl4oZDPwOEnhDsaiaQShM8CHRjoxrqeSK4SzNJuegmlHmP9Q8 "Pari/GP – Try It Online")
[Answer]
# Javascript (ES6), 145 bytes
```
n=>{for(a=[b=l=0],q=n,d=2;q>=2;)q%d?(b&&(a.push(0),l++),d++,b=0):(q/=d,a[l]++,b=1);for(i in a){for(d=1,e=a[i];e%d;d++);e-d||n%e&&l++};return l+1}
```
[Answer]
# [Factor](https://factorcode.org), 62 bytes
```
group-factors flatten unique values [ prime? ] filter length ;
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TU5BTsMwELz7FXOEQ6ImrZLQSsAN9dIL4oQ4WGHTWji2a6-ReAuXXOAjvKK_wY1BcNmZ3R3NzPvnIHu2fjp9Pdxvd3dryL6nEKwPkAn6gN6OTmnyZWSlFSsKUBYv5A1pjJIP4jxKJ30gj8y9GpPsHy9zTICRaXMyZQjnifkt_Q3jGC1LVtYEBDpGMknwx8pnIoeN2O5Sv-DIVMtOCLHGgAsYFAVGXArgI_JQdKfrvbfRFb-Rg5bMZBCNSn54lTom80fMzW7whEFpTtU1mT0fsPlxua1Xyb8UVd3M2M2zyce2zrdmtZjJsmoXVXXVZFHdniH7TFPGbw)
] |
[Question]
[
This golf requires a factorial calculation be split up among multiple threads or processes.
Some languages make this easier to coordinate than others, so it is lang agnostic.
Ungolfed example code is provided, but you should develop your own algorithm.
The goal of the contest is to see who can come up with the shortest (in bytes, not seconds) multicore factorial algorithm for calculating N! as measured by votes when the contest closes. There should be a multicore advantage, so we'll require that it should work for N ~ 10,000. Voters should vote down if the author fails to provide a valid explanation of how it spreads out the work among processors/cores and vote up based on golf conciseness.
For curiosity, please post some performance numbers. There may be a performance vs golf score tradeoff at some point, go with golf so long as it meets the requirements. I'd be curious to know when this occurs.
You may use normally available single core big integer libraries. For instance, perl is usually installed with bigint. However, note that simply calling a system provided factorial function won't normally split the work across multiple cores.
You must accept from STDIN or ARGV the input N and output to STDOUT the value of N!. You may optionally use a 2nd input parameter to also provide the number of processors/cores to the program so it doesn't do what you'll see below :-) Or you may design explicitly for 2, 4, whatever you have available.
I will post my own oddball perl example below, previously submitted on [Stack Overflow under Factorial Algorithms in Different Languages](https://stackoverflow.com/questions/23930/factorial-algorithms-in-different-languages). It is not golf. Numerous other examples were submitted, many of them golf but many not. Because of share-alike licensing, feel free to use the code in any examples in the link above as a starting point.
Performance in my example is lackluster for a number of reasons: it uses too many processes, too much string/bigint conversion. As I said it is an intentionally oddball example. It will calculate 5000! in under 10 seconds on a 4 core machine here. However, a more obvious two liner for/next loop can do 5000! on one of the four processors in 3.6s.
**You'll definitely have to do better than this:**
```
#!/usr/bin/perl -w
use strict;
use bigint;
die "usage: f.perl N (outputs N!)" unless ($ARGV[0] > 1);
print STDOUT &main::rangeProduct(1,$ARGV[0])."\n";
sub main::rangeProduct {
my($l, $h) = @_;
return $l if ($l==$h);
return $l*$h if ($l==($h-1));
# arghhh - multiplying more than 2 numbers at a time is too much work
# find the midpoint and split the work up :-)
my $m = int(($h+$l)/2);
my $pid = open(my $KID, "-|");
if ($pid){ # parent
my $X = &main::rangeProduct($l,$m);
my $Y = <$KID>;
chomp($Y);
close($KID);
die "kid failed" unless defined $Y;
return $X*$Y;
} else {
# kid
print STDOUT &main::rangeProduct($m+1,$h)."\n";
exit(0);
}
}
```
My interest in this is simply (1) alleviating boredom; and (2) learning something new. This isn't a homework or research problem for me.
Good luck!
[Answer]
## Mathematica
A parallel-capable function :
```
f[n_, g_] := g[Product[N@i, {i, 1, n, 2}] Product[N@i, {i, 2, n, 2}]]
```
Where g is `Identity` or `Parallelize` depending on the type of process required
For the timing test, we'll slightly modify the function, so it returns the real clock time.
```
f[n_, g_] := First@AbsoluteTiming[g[Product[N@i,{i,1,n,2}] Product[N@i,{i,2,n,2}]]]
```
And we test both modes (from 10^5 up to 9\*10^5): (only two kernels here)
```
ListLinePlot[{Table[f[i, Identity], {i, 100000, 900000, 100000}],
Table[f[i, Parallelize], {i, 100000, 900000, 100000}]}]
```
Result:

[Answer]
# Haskell: 209 200 198 177 chars
### 176 167 source + 33 10 compiler flag
This solution is pretty silly. It applies product in parallel to a value of type `[[Integer]]`, where the inner lists are at most two items long. Once the outer list is down to at most 2 lists, we flatten it and take the product directly. And yes, the type checker needs something annotated with Integer, otherwise it won't compile.
```
import Control.Parallel.Strategies
s(x:y:z)=[[x,y::Integer]]++s z;s x=[x]
p=product
f n=p$concat$(until((<3).length)$s.parMap rseq p)$s[1..n]
main=interact$show.f.read
```
(Feel free to read the middle part of `f` between `concat` and `s` as "until I heart the length")
Things seemed like they were going to be pretty good since parMap from Control.Parallel.Strategies makes it pretty easy to farm this out to multiple threads. However, it looks like GHC 7 requires a whopping 33 chars in command line options and environment vars to actually enable the threaded runtime to use multiple cores (which I included in the total). Unless I am missing something, which is possible *definitely the case*. (**Update**: the threaded GHC runtime appears to use N-1 threads, where N is the number of cores, so no need to fiddle with run time options.)
To compile:
```
ghc -threaded prog.hs
```
Runtime, however, was pretty good considering the ridiculous number of parallel evaluations being sparked and that I didn't compile with -O2. For 50000! on a dual-core MacBook, I get:
```
SPARKS: 50020 (29020 converted, 1925 pruned)
INIT time 0.00s ( 0.00s elapsed)
MUT time 0.20s ( 0.19s elapsed)
GC time 0.12s ( 0.07s elapsed)
EXIT time 0.00s ( 0.00s elapsed)
Total time 0.31s ( 0.27s elapsed)
```
Total times for a few different values, the first column is the golfed parallel, the second is the naive sequential version:
```
Parallel Sequential
10000! 0.03s 0.04s
50000! 0.27s 0.78s
100000! 0.74s 3.08s
500000! 7.04s 86.51s
```
For reference, the naive sequential version is this (which was compiled with -O2):
```
factorial :: Integer -> Integer
factorial n = product [1..n]
main = interact $ show.factorial.read
```
[Answer]
## Ruby - 111 + 56 = 167 characters
This is a two file script, the main file (`fact.rb`):
```
c,n=*$*.map(&:to_i)
p=(0...c).map{|k|IO.popen("ruby f2.rb #{k} #{c} #{n}")}
p p.map{|l|l.read.to_i}.inject(:*)
```
the extra file (`f2.rb`):
```
c,h,n=*$*.map(&:to_i)
p (c*n/h+1..(c+1)*n/h).inject(:*)
```
Simply takes the number of processes and number to calculate as args and splits the work up into ranges that each process can calculate individually. Then multiplies the results at the end.
This really shows how much slower Rubinius is to YARV:
Rubinius:
```
time ruby fact.rb 5 5000 #=> 61.84s
```
Ruby1.9.2:
```
time ruby fact.rb 5 50000 #=> 3.09s
```
(Note the extra `0`)
[Answer]
## Java, 523 519 434 430 429 chars
```
import java.math.*;public class G extends Thread{BigInteger o,i,r=BigInteger.ONE,h;G g;G(BigInteger O,int
I,int n){o=O;i=new BigInteger(""+I);if(n>1)g=new G(O.subtract(r),I,n-1);h=n==I?i:r;start();}public void
run(){while(o.signum()>0){r=r.multiply(o);o=o.subtract(i);}try{g.join();r=r.multiply(g.r);}catch(Exception
e){}if(h==i)System.out.println(r);}public static void main(String[] args){new G(new BigInteger(args[0]),4,4);}}
```
The two 4s in the final line are the number of threads to use.
50000! tested with the following framework (ungolfed version of the original version and with a handful fewer bad practices - although it's still got plenty) gives (on my 4-core Linux machine) times
```
7685ms
2338ms
1361ms
1093ms
7724ms
```
Note that I repeated the test with one thread for fairness because the jit might have warmed up.
```
import java.math.*;
public class ForkingFactorials extends Thread { // Bad practice!
private BigInteger off, inc;
private volatile BigInteger res;
private ForkingFactorials(int off, int inc) {
this.off = new BigInteger(Integer.toString(off));
this.inc = new BigInteger(Integer.toString(inc));
}
public void run() {
BigInteger p = new BigInteger("1");
while (off.signum() > 0) {
p = p.multiply(off);
off = off.subtract(inc);
}
res = p;
}
public static void main(String[] args) throws Exception {
int n = Integer.parseInt(args[0]);
System.out.println(f(n, 1));
System.out.println(f(n, 2));
System.out.println(f(n, 3));
System.out.println(f(n, 4));
System.out.println(f(n, 1));
}
private static BigInteger f(int n, int numThreads) throws Exception {
long now = System.currentTimeMillis();
ForkingFactorials[] th = new ForkingFactorials[numThreads];
for (int i = 0; i < n && i < numThreads; i++) {
th[i] = new ForkingFactorials(n-i, numThreads);
th[i].start();
}
BigInteger f = new BigInteger("1");
for (int i = 0; i < n && i < numThreads; i++) {
th[i].join();
f = f.multiply(th[i].res);
}
long t = System.currentTimeMillis() - now;
System.err.println("Took " + t + "ms");
return f;
}
}
```
Java with bigints is not the right language for golfing (look at what I have to do just to construct the wretched things, because the constructor which takes a long is private), but hey.
It should be completely obvious from the ungolfed code how it breaks up the work: each thread multiplies an equivalence class modulo the number of threads. The key point is that each thread does roughly the same amount of work.
[Answer]
### CSharp - ~~206~~ 215 chars
```
using System;using System.Numerics;using System.Threading.Tasks;class a{static void Main(){var n=int.Parse(Console.ReadLine());var r=new BigInteger(1);Parallel.For(1,n+1,i=>{lock(this)r*=i;});Console.WriteLine(r);}}
```
Splits up the calculation with the C# Parallel.For() functionality.
Edit; Forgot lock
Execution times:
```
n = 10,000, time: 59ms.
n = 20,000, time: 50ms.
n = 30,000, time: 38ms.
n = 40,000, time: 100ms.
n = 50,000, time: 139ms.
n = 60,000, time: 164ms.
n = 70,000, time: 222ms.
n = 80,000, time: 266ms.
n = 90,000, time: 401ms.
n = 100,000, time: 424ms.
n = 110,000, time: 501ms.
n = 120,000, time: 583ms.
n = 130,000, time: 659ms.
n = 140,000, time: 832ms.
n = 150,000, time: 1143ms.
n = 160,000, time: 804ms.
n = 170,000, time: 653ms.
n = 180,000, time: 1031ms.
n = 190,000, time: 1034ms.
n = 200,000, time: 1765ms.
n = 210,000, time: 1059ms.
n = 220,000, time: 1214ms.
n = 230,000, time: 1362ms.
n = 240,000, time: 2737ms.
n = 250,000, time: 1761ms.
n = 260,000, time: 1823ms.
n = 270,000, time: 3357ms.
n = 280,000, time: 2110ms.
```
[Answer]
## Perl, 140
Takes *`N`* from standard input.
```
use bigint;$m=<>;open A,'>',
undef;$i=$p=fork&&1;$n=++$i;
{$i+=2;$n*=$i,redo if$i<=$m}
if($p){wait;seek A,0,0;$_=<A
>;print$n*$_}else{print A$n}
```
**Features:**
* computation split: evens on one side and odds on the other (anything more complex than that would need a lot of characters to balance the computation load appropriately.
* IPC using a shared anonymous file.
**Benchmark:**
* 10000! is printed in 2.3s forked, 3.4s unforked
* 100000! is printed in 5'08.8 forked, 7'07.9 unforked
[Answer]
## Scala (345 266 244 232 214 characters)
Using Actors:
```
object F extends App{import actors.Actor._;var(t,c,r)=(args(1).toInt,self,1:BigInt);val n=args(0).toInt min t;for(i<-0 to n-1)actor{c!(i*t/n+1 to(i+1)*t/n).product};for(i<-1 to n)receive{case m:Int=>r*=m};print(r)}
```
Edit - removed references to `System.currentTimeMillis()`, factored out `a(1).toInt`, changed from `List.range` to `x to y`
Edit 2 - changed the `while` loop to a `for`, changed the left fold to a list function that does the same thing, relying on implicit type conversions so the 6 char `BigInt` type appears only once, changed println to print
Edit 3 - found out how to do multiple declarations in Scala
Edit 4 - various optimizations I've learned since I first did this
Ungolfed version:
```
import actors.Actor._
object ForkingFactorials extends App
{
var (target,caller,result)=(args(1).toInt,self,1:BigInt)
val numthreads=args(0).toInt min target
for(i<-0 to numthreads-1)
actor
{
caller ! (i*target/numthreads+1 to(i+1)*target/numthreads+1).product
}
for(i<-1 to numthreads)
receive
{
case m:Int=>result*=m
}
print(result)
}
```
[Answer]
### Scala-2.9.0 170
```
object P extends App{
def d(n:Int,c:Int)=(for(i<-1 to c)yield(i to n by c)).par
println((BigInt(1)/: d(args(0).toInt,args(1).toInt).map(x=>(BigInt(1)/: x)(_*_)))(_*_))}
```
### ungolfed:
```
object ParallelFactorials extends App
{
def distribute (n: Int, cores: Int) = {
val factorgroup = for (i <- 1 to cores)
yield (i to n by cores)
factorgroup.par
}
val parallellist = distribute (args(0).toInt, args(1).toInt)
println ((BigInt (1) /: parallellist.map (x => (BigInt(1) /: x) (_ * _)))(_ * _))
}
```
The factorial of 10 is computed on 4 cores by generating 4 Lists:
* 1 5 9
* 2 6 10
* 3 7
* 4 8
which are multiplied in parallel. There would have been a simpler approach to distribute the numbers:
```
(1 to n).sliding ((n/cores), (n/cores)
```
* 1 2 3
* 4 5 6
* 7 8 9
* 10
But the distribution wouldn't be that good - the smaller numbers would all end in the same list, the highest in another one, leading to the longer computation in the last list (for high Ns, the last thread wouldn't be almost empty, but at least contain (N/cores)-cores elements.
Scala in version 2.9 contains parallel Collections, which handle the parallel invocation themselves.
[Answer]
## Erlang - 295 characters.
First thing I've ever written in Erlang so I wouldn't be surprised if someone could easily halve this:
```
-module(f).
-export([m/2,f/4]).
m(N,C)->g(N,C,C,[]).
r([],B)->B;
r(A,B)->receive{F,V}->r(lists:delete(F,A),V*B)end.
s(H,L)->spawn(f,f,[self(),H,L,1]).
g(N,1,H,A)->r([s(N div H,1)|A],1);
g(N,C,H,A)->g(N,C-1,H,[s(N*C div H,N*(C-1) div H)|A]).
f(P,H,H,A)->P!{self(),A};
f(P,H,L,A)->f(P,H-1,L,A*H).
```
Uses the same threading model as my earlier Ruby entry: splits the range up into sub-range and multiplies the ranges together in seperate threads then multiplies the results back in the main thread.
I wasn't able to figure out how to get escript working so just save as `f.erl` and open up erl and run:
```
c(f).
f:m(NUM_TO_CALC, NUM_OF_PROCESSES).
```
with appropriate substitutions.
Got around 8s for 50000 in 2 processes and 10s for 1 process, on my MacBook Air (dual-core).
Note: Just noticed it freezes if you attempt more processes than the number to factorialize.
] |
[Question]
[
Consider a sorted array of positive floating point numbers such as:
```
input = [0.22, 2.88, 6.35, 7.17, 9.15]
```
For each integer \$i\$ from 1 up to the last value in input rounded up, output the mean of all values less than \$i\$.
In this case the output should be:
```
[0.22 0.22 1.55 1.55 1.55 1.55 3.15 4.155 4.155 5.154 ]
```
If there is no value in the input less than \$i\$ you don't need to add anything to the output.
More examples: (output rounded to three decimal places)
```
input = [2.37, 4.15, 5.47, 6.64, 7.01, 8.87, 9.37]
output = [2.37 2.37 3.26 3.997 4.657 5.128 5.752 6.269]
input = [2.22, 2.66]
output = [2.44]
input = [0.09, 0.09, 2.21, 3.64, 7.26, 7.58, 9]
output = [0.09, 0.09, 0.797, 1.508, 1.508, 1.508, 1.508, 3.478, 3.478]
input = [0.35, 2, 2.45, 3.71, 5.13, 9.0, 9.66]
output = [0.35, 0.35, 1.6, 2.128, 2.128, 2.728, 2.728, 2.728, 2.728, 4.614]
```
You can round your output to three decimals places or not as you choose.
Your code should run in linear time in the length of the output plus the length of the input
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~19~~ 20 bytes [SBCS](https://github.com/abrudz/SBCS)
Added 1 byte to fix handling of trailing integers.
```
(⌈¯2-/⌊,⊢/)⊢⍤/+\÷⍳⍤≢
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=03jU03FovZGu/qOeLp1HXYv0NYHEo94l@toxh7c/6t0MZD7qXAQA&f=Xcq7DYBADIPhnik8gZXH5RIWYhvKW5BJCFSIxtIvf36d64DQDMYqTHogqYmdGpu/t9EToxvBkW3maCOKYj3Q8wuDIv/uUbkB&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
```
⍝ n←≢input, m←≢output
+\÷⍳⍤≢ ⍝ Cumulative averages
⍳⍤≢ ⍝ Numbers from 1 to n - O(n)
+\ ‚çù Cumulative sums - O(n)
√∑ ‚çù Elementwise division - O(n)
⌈¯2-/⌊,⊢/ ⍝ Repeat counts
⊢/ ⍝ Last value - O(1)
‚åä ‚çù Floor of each number - O(n)
, ‚çù Concatenate - O(n)
¯2-/ ⍝ Adjacent differences - O(n)
‚åà ‚çù Ceil (last difference) - O(n)
⊢⍤/ ⍝ Repeat cumulative averages by
‚çù counts on the left - O(m+n)
```
I'm pretty sure I can replace `⍳⍤≢` by the grading (sorting indices) primitive `⍋` because sorting a sorted list will always be O(n), but I can't really prove that.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~91 100~~ 95 bytes
```
i;n;f(a,l,s)float*a,s;{for(i=n=s=0;i<a[l-1]+1;n<l&&a[n]<i?s+=a[n++]:++i*n&&printf("%f ",s/n));}
```
[Try it online!](https://tio.run/##NVDLboMwEDyHr1ghFdmxQ3g/alA/JOKACESOqIkw6aERv166Nu3Ba@/O7Ix3u9Ot67ZNCiUG0vKRazqMU7scW67Fa5hmImtV6zoQsmov4ylsWChUNXpee1FNJT80q/HFWPPOmDwqz3vMUi0Dcd8GcLk@K0rFumHJ@WylIl@TvFLn5RywApLDXTgHawhLrxd9aaAGRA@BH0UcIr8oOGR@nHLI/TDnUPphyhGP/BizxGSQ@kluWFliWEHIofALy0WO5e5aWcatclBy2CMiyI7/OqPMxBQdy51obG1nkhpWHhqvMDbKgQlWcBX7MGOv9t@D@axtxJgD4jjiNAORiN7xBAKvCrT87qeBYB@F83@GSlSABFZbwTsultqFDMQuCJjZmoUais6Hx3PRxHXNe0WjuV@es0ILZ91@umFsb3o76eVad0X5Cw "C (gcc) – Try It Online")
## Explanation
\$i \le \lceil x \rceil \iff i \lt x + 1 \qquad \forall \quad i \in \mathbb{Z} \quad \textrm{and} \quad x \in \mathbb{R}\$
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ĊṪṭḞIx@Ä÷JƊ
```
A monadic Link that accepts a sorted list of positive floats and yields a sorted list of floats - the cumulative averages without any leading zeros.
**[Try it online!](https://tio.run/##y0rNyan8//9I18Odqx7uXPtwxzzPCofDLYe3ex3r@v//f7SRjoKxnrEJiDQz01GwACI9Ux0Fy1gA "Jelly – Try It Online")**
### How?
```
ĊṪṭḞIx@Ä÷JƊ - Link: sorted list of positive floats, A = [a,b,...,z]
(length(A)=n, ceil(A[n])-ceil(A[0])+1=m)
Ċ - ceiling - O(n) -> [ceil(a),ceil(b),...,ceil(z)]
·π™ - tail - O(1) -> [ceil(z)]
·π≠ - tack - O(1) -> [a,b,...,z,ceil(z)]
·∏û - floor - O(n) -> [floor(a),...,floor(z),floor(ceil(z))]
I - deltas - O(n) -> [floor(b)-floor(a),...,floor(z)-floor(y),floor(ceil(z))-floor(z)]
Ɗ - last three links as a monad - f(A):
Ä - sums - O(n) -> [a,a+b,...,sum(A)]
J - range - O(n) -> [1..n]
√∑ - divide - O(n) -> [a,(a+b)/2,(a+b+c)/3,...]
@ - with swapped arguments:
x - repeat - O(n+m) -> [a,..a,(a+b)/2,...,(a+b)/2,...,...,Total/N]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 71 or 110 bytes
```
Reap[Do[t=Select[#,#<i&];If[t!={},Sow@Mean@t],{i,‚åàMax@#‚åâ}]][[2,1]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pyg1sSDaJT@6xDY4NSc1uSRaWUfZJlMt1tozLbpE0ba6Vic4v9zBNzUxz6EkVqc6U@dRT4dvYoWD8qOeztrY2OhoIx3D2Fi1/wFFmXklDmkO1QZ6RkY6CkZ6FhY6CmZ6xqY6CuZ6huY6CpZ6hqa1XHBlRlBlZma1/wE "Wolfram Language (Mathematica) – Try It Online")
I had doubts about the time linearity, but the tests show that it is linear:
[Try it online!](https://tio.run/##Fc1BC4IwGIDhu79iKXj6ErVjGTtE0EEI7Ta@YNSsgZthHxSM3Qv8lf4Rs9N7e14j6a6MJH2RU1NUSj7ErhNU1KpVFxIRRBsd4/rQCFoUzkPdvXippOWE4DSMw6eUbx6Nw9cjCpFDhhhPMxEce21JWGAhW25ZCGyv@yfxkzba3njDK2mvnZmPrXBZAixL08T/c14xiwwDcBby1OM0/QA "Wolfram Language (Mathematica) [Dash] Try It Online")
And for this code, the linearity of time can be algorithmically proven:
```
(c=1;m=0;Reap[Do[If[#[[c]]<i,m=Mean@#[[;;c++]];Sow@m,If[m>0,Sow@m,c=Min[Length@#,c+1]]],{i,‚åàMax@#‚åâ}]][[2,1]])&
```
[Try it online!](https://tio.run/##PcpBC4IwGIDhe79iIEThx9BFaqzFDl2ChKjj@A5jmO4wjRgUiPcCf6V/xISi48v7OO2rwmlvjR5LMS6MiLkjIuLnQt/UvlGHqwqUMohbC07kha7l1JybMETkl@YhHUzG7SL4hhG5rdWxqEtfyQBMGCMitBaG/pXrpwyG/t0hKsVgOsv5eLrb2stSthFlDAijWQYkoas1kJTGKZANjdfd7M/YjyVJN34A "Wolfram Language (Mathematica) [Dash] Try It Online")
[Answer]
# [OCaml](http://www.ocaml.org/), 290 bytes
290 bytes, it can be golfed much more.
Any suggestion would be appreciated.
Golfed version. [Try it online!](https://tio.run/##rZHNasMwDIDvewpRGMSUas5/Gi95gh12z0IJmYsNqVtSd9uh797Jztq1sMMODUQGS/q@SNn23WY4nQZpYSM7sxrsSkM3jpW/6b6qXuoheNF7i@p9Okf54SoY0wZc1Sh7UHLYydFdw/6wgX57MBZ0pdega6KAVdI0rRz2kqC2V77yU1sFx6Zd1AE1PaHvYmUZTLSmvaACPccQOWNHVZZ2URNXPWtPPautY8xRscB3TPUanPJP@u23XgTaXM/CkfuXUn5FK6gegJ7fVTUco0hAhEUhIMM4FZBjmAtYYpi2xxr8yrQlYPA6amPXuPMHzB4xpsiEJ97kgtmbOSeuVBHGBE4ILCDFJHfCLHFCHgoosPDaOG/h3t5pxCy7N5l2uxQwRbLQFPHPRFHmYlq4iTi/v9f9qIjILiap8@ah22oYe6MLNO6/rKdv)
```
let mean_lt_i arr=let max=ceil(List.hd(List.rev arr))in let rec helper arr sum count i=if i>max then[]else match arr with |[]->(sum/.count)::(helper[]sum count(i+.1.0))|h::t->if h<i then helper t(sum+.h)(count+.1.0)i else(sum/.count)::(helper arr sum count(i+.1.0))in helper arr 0.0 0.0 1.0
```
Ungolfed version. [Try it online!](https://tio.run/##pZHLbsIwEEX3@YorpEq2qk7zAJLGhS/oonuKUJQa2VIwKJi2C/49tU14BKmrjuQkzp05czWzratN03WNtNjIyqwau9Ko2hazCC7C/@oHM9RSN2Bvem9JffYfrfzyuZxDm0t6K2so2exkGzj7wwb19mAsdM/0odfuOg9oq6TBYnmRZLOXTrC1CvXf2qqL5uPokvE0B/PkZzrBeVmyvqlTrz2ZxiMhoZjzO4gqS@sxzonCq3MTfPQMe6K7UsXBTqieAz0AXSP4/svUcBL3rrS5nVhMcThOj6LIj3R1s42wGyxiSlOBlIpCYErZRCCnJBd4oWSyPK9juNHjHGFr2rpG7L3Vxq5pF14YPVDmnlyEuoHGRh/mLNwYSClz7cauncCExrm3MR17G3EiUFARzGT5f8x03S8)
```
let mean_lt_i arr =
let max = ceil (List.hd (List.rev arr)) in
let rec helper arr sum count i =
if i > max then []
else match arr with
| [] -> (sum /. count)::(helper [] sum count (i +. 1.0))
| h::t -> if h < i then helper t (sum +. h) (count +. 1.0) i
else (sum /. count)::(helper arr sum count (i +. 1.0))
in helper arr 0.0 0.0 1.0
let _ =
let arr = [0.22; 2.88; 6.35; 7.17; 9.15] in
mean_lt_i arr |> List.iter (Printf.printf "%.3f ");
Printf.printf("\n");
let arr = [2.37; 4.15; 5.47; 6.64; 7.01; 8.87; 9.37] in
mean_lt_i arr |> List.iter (Printf.printf "%.3f ");
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Å»+}ā/I¤îªï¥øε`и}˜
```
Port of [@JonathanAllan's Jelly](https://codegolf.stackexchange.com/a/260922/52210) answer (but without the convenient \$O(n)\$ builtins..), so make sure to upvote him as well!
[Try it online](https://tio.run/##AUYAuf9vc2FiaWX//8OFwrsrfcSBL0nCpMOuwqrDr8Klw7jOtWDQuH3LnP//WzAuMjIsIDIuODgsIDYuMzUsIDcuMTcsIDkuMTVd) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w62HdmvXHmnUrzy05PC6Q6sOrz@09PCOc1sTLuyoPT3nv87/6GgDPSMjHSM9CwsdMz1jUx1zPUNzHUs9Q9NYHYVoIz1jcx0TIEfHVM/EHKjAzASowMBQx0LPAqTK2ByiCmyCmRlci6megQEKB0gYGsTGAgA).
**Explanation:**
```
Å» } # O(n) Cumulative left-reduce the (implicit) input-list by:
+ # O(1) Adding items together
ā # O(1) Push a list in the range [1,length] (without popping)
/ # O(n) Divide the values at the same positions in the lists
I # O(1) Push the input-list again
¤ # O(1) Push its last/maximum value (without popping the list)
î # O(1) Ceil that last value
ª # O(1) Append it to the list
ï # O(n) Floor each value in the list
¥ # O(n) Get the forward differences of this list
√∏ # O(n) Pair the values of the two lists together
ε # O(n) Map over each value:
` # O(1) Pop and push the values of the pair to the stack
–∏ # O(n+m) Repeat the value the count amount of times as list
}Àú # O(n) After the map: flatten the list of lists
# O(1) (after which the result is output implicitly)
```
Unfortunately 05AB1E lacks vectorized repeat and/or zip-with builtins, hence the use of `øε`и}` (zip, map, and repeat separately). `δиÅ\` would be 1 byte shorter for this snippet, but would make it quadratic instead of linear.
**Without the [restricted-complexity](/questions/tagged/restricted-complexity "show questions tagged 'restricted-complexity'"), it could have been 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage):**
```
¤îLε‹ÏÅA}˜
```
[Try it online](https://tio.run/##AToAxf9vc2FiaWX//8Kkw65MzrXigLnDj8OFQX3LnP//WzAuMjIsIDIuODgsIDYuMzUsIDcuMTcsIDkuMTVd) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f9DSw6v8zm39VHDzsP9h1sda0/P@a/DBVLCVZ6RmZOqUJSamKKQmceVks@loKCfX1CiDzEJSqEZbqOgAlabl/o/2kDPyEjHSM/CQsdMz9hUx1zP0FzHUs/QNJYr2kjP2FzHBMjWMdUzMQfKm5kA5Q0MdSz0LECKjM3BisD6zcxgGkz1DAyQ2UDCECgAAA).
**Explanation:**
```
¤ # Get the last/maximum value of the (implicit) input-list
î # Ceil it
L # Pop and push a list in the range [1, ceil(max)]
ε # Map over each value:
‹ # Check for each value in the (implicit) input-list whether it's smaller than
# this value
Ï # Only keep the values of the (implicit) input-list where this is truthy
√ÖA # Get the arithmetic mean of these remaining values
}Àú # After the map: flatten the list of lists
# (after which the result is output implicitly)
```
[Answer]
# Awk, 81 79 66 62 bytes:
`{for(;g<int($1);g++)if(n)print(m);m+=($1-m)/++n}END{print(m)}`
Try it here: <https://www.jdoodle.com/ia/I4A>
Takes as input (and outputs) a contiguous newline-separated list of numbers. Will take input with gaps if an initial regex is added to only accept lines with numbers. 2 bytes reduced with canny substitution for `NR`. 17 bytes reduced by squashing *everything* (updating `g`) into a loop with all unnecessary variables trimmed, giving a healthy side effect of reducing punctuation.
---
Degolfed:
```
# implicit init: n=0, m=0, g=0
{for(; # golfy blank init
g<int($1); # bring old floor up to new (no-op if equal):
g++) # print the current cumulative mean
# conveniently the right number of times
if(n) # just don't print on first entry
print(m) # print cumulative mean
; # we can chain functions without semicolons?? how very golfy
m+=($1-m)/++n} # increment n and inline cumulative mean
END{print(m)} # one last time, with feeling
```
Code is transparently linear in input size, taking advantage of the sorted-ness of the array.
[Answer]
# [R](https://www.r-project.org), ~~67~~ 57 bytes
```
\(i)c(na.omit(sapply(1:-(-max(i)%/%1),\(x)mean(i[i<x]))))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY9NCsIwEIX3niIbYQLpmJ_mT_Qk6qIUCwVbxR-oZ3FTBQ_hUbyNGVuaxQu8-d685PE8969q_b5dqyx84xZqXkJb4LGpr3ApTqfDHdQyg6wpujSbL-aKiy10vNkXLdSbetXteDrjgk8FJUjUWjCNIQjm0FjBPCovWERlOZ8RotEkI0-GYBZzT6DLCZRKsIDhjxs_4cNG50ZDooyCDZqGKWPGvHakNlXHiaUn_PO5JdArKlWGKiQJrR0-0PfD_QM)
(shaved off 10 thanks to [@dominic-van-essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen))
[Answer]
# [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), ~~196~~ ~~187~~ 179 bytes
\$\color{red}{\text{The code doesn't output correct results. Any help would be appreciated.}}\$
---
Saved 17 bytes thanks to the comment of [@erfink](https://codegolf.stackexchange.com/users/62273/erfink)
Golfed version. [Try it online!](https://tio.run/##lZA/a8MwEMX3fAp1yeJD8X87dVRcOhWS0iHQwYgiEjWRUSRRK1NIvror2W0pXUKGO4RO73fv6cDsnh@YFRvWb5jcHCWzfMWZ6hrzvhSdpeie9Cu9PUrenDoSgnKlyekMgkTQupJkydXO7oGRR2O42q71Gd72wgnaBZG1mU7FgjxxIYXa1UvW2drA80djmqaldCGgC8h4rlQQVK0rfWGXl6abKeofylrf@aXuclBrWokgoJUb/SwY9Q9EgJ/QStNeKHO0iKBTiOMYUIzLElCOkwxQgaMC0BxH2bma/Es9yCiazV4/hbKTyS8mxokTpU4EKMNp4WF56mFhBKjE5YBMipuQo7M8v0EU4nAOaOwO4HYn3z7i3PfMxZxf5/0F@j8ZjKSZpxWRTxglPk/o23V//Rc)
```
Module[{s=0,n=0,o={},i=1,j=1,l=Length,a=AppendTo},While[j<=l@p&&i<=Ceiling@Last@p,If[p[[j]]<i,s+=p[[j]];n++;j++;o~a~N[s/n],If[l@o!=0,o~a~Last@o];i++];If[j<=l@p&&p[[j]]>=i,i++]];o]
```
Ungolfed version. [Try it online!](https://tio.run/##hZHPS8MwFMfv/Suel10asrZb1@pWUTwJnXgYeAhBwhbXlDYdNgVh7G@vr8nKFBUveT@/n5eX1MIUshZGbUXfb0W17Sph5FoK3TKlD515zVVrONxkHqybXVdJdqzFB2TwIFWl9J7lojWulXMCbVdjLSCgnWk6gxX0jycCCm1IoBzMiXgAL4VCYAmrDHKp96Y4g2AywWbM4qihDx7fXIWxknNYgbJZO83P4FJa2rT2feeUo3N/OEi92zTM3YfAE0PtVI8Kh8Mp7hp3ru0qC8gPpd3XBXyUq/McFyLmj5UuK9xm4w7ftPZwcA@451nF8HoBjSICEU1TAgs6iwkkNEwIXNMwPi29336Ow3T6/K60@YKJ6AxFcxQRiOk8GWCL@QAL8GNSmlrkLPkP2fef)
```
calculateMeans[input_List] :=
Module[{max = Ceiling[Last[input]], sum = 0, n = 0, output = {}, i = 1, j = 1},
While[j <= Length[input] && i <= max,
If[input[[j]] < i,
sum += input[[j]];
n++;
j++;
AppendTo[output, N[sum/n]];
,
If[Length@output!=0,AppendTo[output, Last[output]]];
i++;
];
If[j <= Length[input] && input[[j]] >= i,
i++;
];
];
output
]
input = {0.22, 2.88, 6.35, 7.17, 9.15};
calculateMeans[input] //Print
input = {2.37, 4.15, 5.47, 6.64, 7.01, 8.87, 9.37};
calculateMeans[input] //Print
```
[Answer]
# [Python 3](https://docs.python.org/3/), 121 bytes
```
def f(a):
i=n=s=0
while i<a[-1]+1:
if n<len(a)and a[n]<i:s+=a[n];n+=1
else:i+=1;n>0and print(s/n, end=' ')
print()
```
[Try it online!](https://tio.run/##RY/dioMwEIXvfYq5UzHNJv5rzb6ISAg00oCdlkZY9undjLr0IsPkzJdzMq/f9f7EYttudoY5MWkfgVOovBIR/NzdYsENZrzIKZNhBG4GHBaLgTR4AzPiNLjeZ4q6K2ZKBsgu3vYu9Ff8FoS93g7XxH8hA4s3FUOcRqeYbsFSazQPqzUoBbHWD@NQ65jyVutXDwrG0AOMguc5g5y3LYOaFxWDhsuGQcdlNbGDyXkRlDIoDCpeNkTWJZFCMmh5u/NF8@EPz7r@VwQXHYOjhml4VZwOeU21CundB6Zv7A5lRWQjKVcWlCKonMZTOPPzva8EDo/V@t1kTuiSbn8 "Python 3 – Try It Online")
This is just a python version of [c--'s C solution](https://codegolf.stackexchange.com/a/260921/40818).
[Answer]
# [Haskell](https://www.haskell.org/), 102 bytes
```
y x=y x 0.0 1.0 0where y(x:z)s i n|x<i=y z(s+x)i(n+1)|0<1=y[]s i n++y(x:z)s(i+1.0)n;y[]s i n=[s/n|n>0]
```
[Try it online!](https://tio.run/##NYyxDsIgFAB3v@INHSAQBExt1eKPNAwdSEpsX0wxERr@HYnR4aa73DyFh1uWUhJEUwEpJKiKfM9uc5BIvO40gAfMcfA12UlgkXqCTNEsB2XSaL@esV9MPKsHire/MWM4Ysa7tGWdPJrn5vHVpGaUQmsOWvQ9h7M4tRw6oToOF6Faeygf "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 179 bytes, sorted input ≥0, O(n)
```
import Data.List
c v=d$map last$groupBy((.fst).(==).fst)$zip(floor<$>v)$zipWith(/)(scanl1(+)v)[1.0..]
d w=concat$zipWith replicate((\z->zipWith(-)(tail z)z++[1])$fst<$>w)(snd<$>w)
```
[Try it online!](https://tio.run/##NY07b8MgFIV3/4o7MFxk5za4yqNSyRBl7N7B9YCwk6BgQEAd1X/etSxl@87RedxVevTWzrMZgo8ZLior@jIpFxpG2bFBBbAqZXaL/jec/xDpmjInlJKvxCYT8Gq9j5/sNK7y2@Q7vnFMWjkrsOQjbwRtidqig6fU3mmVX0GIfbBmMXrEn2lzevU3HLMyFiY@lWUjWs6Wt@Xiuey6boV5UMbJEI3LTLNmS3VdQU3HYwV7et9VcCBxqOCDxK4t5n8 "Haskell – Try It Online")
[Answer]
# SAS
Input data in SAS can be passed as a SAS data set (standard SAS data transporting structure) or as macrovariable (a text string).
Solution 1) is based on input in SAS data set. Solution 2) is based on input passed as a text string. Though the solution 2) is 3 bytes shorter, it is the 1) which probably is more "SAS way".
---
**Solution 1)**
# 122 bytes
*Input:*
Input is a SAS dataset `i` containing variable `x`:
```
data i;
infile cards dsd;
input x @@;
cards;
0.22, 2.88, 6.35, 7.17, 9.15
;
run;
```
Code:
```
data a;merge i i(rename=(x=y) firstobs=2);s+x;a=s/_N_;do j=j to coalesce(y,ceil(x));if j>x then output;end;retain j 1;run;
```
Human readable code:
```
data a;
merge
i
i(rename=(x=y) firstobs=2);
s+x;
a=s/_N_;
do j=j to coalesce(y,ceil(x));
if j>x then output;
end;
retain j 1;
run;
```
The solution utilise `merge` statement which reads dataset `i` and data set `i` starting from the second observation with variable `x` renamed to `y`. Effectively for each value of `x` the `y` variable contains the next value. Only for the last value of `x` value of `y` is missing.
Dataset `a` contains cumulative average in variable `a` (alongside source data).
---
**Solution 2)**
# 119 bytes
*Input:*
Input is a text string passed by a macrovariable `x`:
```
%let x=0.22, 2.88, 6.35, 7.17, 9.15;
```
Code:
```
data;array d[999](&x);do i=1to ceil(max(of d:));do while(-d[j+1]>-i);j+1;s+d[j];end;a=s/(j<>1);if a then put a;end;run;
```
Human readable code:
```
data;
array d[999] (&x);
do i=1 to ceil(max(of d:));
do while(-d[j+1]>-i);
j + 1;
s + d[j];
end;
a = s/(j<>1);
if a then put a;
end;
run;
```
Result of the processing is printed out in the SAS log with `put a;` statement.
If text string in macrovariable `&x` contains more than 999 elements this part: `d[999]` has to be properly adjusted (what extends length). But, up to 999999, it still is not worse than 1).
The `array` statement in SAS data step (in this context) should not be confused with arrays which are available for example in C. In this context the `array d[999] (&x)` means "create 999 variables named `d1`, `d2`, ..., `d999` initiated with values from text string passed by macrovariable `&x`.
---
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
⊞θ⌈⌈θ≔⁰η≔⁰ζFθ«≦⊕η≧⁺ιζIE…ι§θη∕ζη
```
[Try it online!](https://tio.run/##VY5PC8IwDMXP@ilyTKGW6fyDeBK9eBDGrsND2eoa2Kqu3RiKn712KogQQh6/5OXlWjb5RVbeJ63VeOOwU1SRKfEoe6rbGm@Msc14ay2VBiMO@k/dgzpfGghr8BiPjvL6ZQeTN6pWxqnic/NjKZXaYVK1lgN9LEZJQ8bhTloXHl8xlaZUGODWHUyh@iGYZozDnjoqFN7fcgj29D7LIhEvOMxCiXkYYrGacliIacxhLaKhLZenk5901Qs "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞θ⌈⌈θ
```
Push the ceiling of the largest element of the list to the list.
```
≔⁰η≔⁰ζ
```
Start with no elements so far with a running total of zero.
```
Fθ«
```
Loop over the elements.
```
≦⊕η≧⁺ιζ
```
Update the count and sum.
```
IE…ι§θη∕ζη
```
Output the current average for each new integer before the next value.
19 bytes for quadratic complexity:
```
IEΦE⊕⌈⌈θΦθ‹λιι∕ΣιLι
```
[Try it online!](https://tio.run/##LUpdC4IwFP0re7yDNbSlET0aQWAQ9Cg@DL3ohblyLunfr02Ccw7nqxu1617ahPBwZD1UevFw12@4kvHoNnuzncMJrcceKiRDdoj9l6bPBDPnXLD/eRasxmUBIxhtPUVeaKUe4RnPKdZoBz9C2jk/h9A0mVSFYPsIeYhGyWMuWCFzJdhJZknKsm3DbjU/ "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# Excel, 49 bytes
```
=TOCOL(AVERAGEIF(A:A,"<"&SEQUENCE(1+MAX(A:A))),2)
```
Input is vertical array beginning in cell `A1`.
[Answer]
# [Elixir](https://elixir-lang.org/), 138 bytes
Golfed version. [Try it online!](https://tio.run/##NY9Ba8MwDIXv@RXvmGChOV3aZGPtvYexHxDMKLULhtQZcwtp6X/PpG05COSn9z7JYYhT/J59OJ1Hfx0C3g8xwY@q4Fb2jjJ9UqrIj6@IJ6Sd/W37/JQchSEH6V3x754ed7cdYr5IKkrKj5qZ3qIQZX6nbCYdmLrS6LJArcbcyiVparYiheQhNReA8s9/l8kL2H9wTPkrHC/KWPFzS2i4XhPW3Ei/4U1DaNnWhI47UV7E4whWyFA8bCUkwRdahX6bdUNZzT8)
```
def y([],s,_,n),do: if n>0,do: [s/n],else: []
def y([x|z]=list,s,i,n)do if x<i do y(z,s+x,i,n+1)else y([],s,i,n)++y(list,s,i+1.0,n)end end
```
Ungolfed version. [Try it online!](https://tio.run/##RZDNCsIwEITvPsUcLQ1rqvUX9e5BfAApIjaFQI1iKtTiu9fdpuolZHdnvtnElLa2j7bNTXG95c/SYH@2DvltAHAPr@ExU/AKJwUXKR6sYAs4bKFDdfQjxxJTesNF9vfVeKPJsEFpfdUxrDACG0KpsYb91mBPwzLEqIOUb0nUzQT@E/ULBVgcc@cfIBbSMgk@lw/C2a91/T0O2B3IOn83l0qgY5rMFVJKpgpTSvk@o1mqMCedKCxowZ0lazhcS0IXo6Me30XIz5EkDKO2/QA)
```
defmodule Main do
def y([], s, _, n), do: if n > 0, do: [s/n], else: []
def y([x | z] = list, s, i, n) do
if x < i do
y(z, s + x, i, n + 1)
else
y([], s, i, n) ++ y(list, s, i + 1.0, n)
end
end
def main do
IO.inspect y([2.37, 4.15, 5.47, 6.64, 7.01, 8.87, 9.37], 0.0, 1.0, 0)
end
end
Main.main()
```
[Answer]
# [Erlang(escript)](http://erlang.org/doc/man/escript.html), 127 bytes
Golfed version. [Try it online!](https://tio.run/##NY9Ra8MgEMff@ymOPimeRpe2Y@vme2HkJS@hQUJZ7Sa0JlhLFxj96pkGdh5y9zv/fzwbzgf/xe31M7ghTvzSH29nSy4H56lYcPsz9CGSdixWCBkWylAxjaQ1WGOHFb1/Ww@Vlly3dVGZ7Tzq8qEJzX3zuzfvH@4ak2SXJFy7EzRvO65HsseaNZkyRbcx3GyGs3l@ydhI/oVMCZmQ9Ucx5Z@QjgLXC0jh@tfTPbhoyfIxPPwSoU0mUpRrhKeUYpWKUjwrhLVQJcJLskrXZmMQZK6zN0iad/sD)
```
y([],S,_,N)when N>0->[S/N];y([],_,_,_)->[];y([X|Z]=List,S,I,N)->if X<I->y(Z,S+X,I,N+1);true->y([],S,I,N)++y(List,S,I+1.0,N)end.
```
Ungolfed version. [Try it online!](https://tio.run/##VVDBasJAEL3nKx6eNmSz2TRqUdvchZKLl2AIQepaA7oJa8QGir@ezm4s0mEOs2/evDezypx2@itUl09Tt90whOdmfz0pdt7V2hdeqL7bxnSs6KMphwWjuCTc61lRcmw4Ko7Mx@2oNDKkkAhTFBtEyMrVg1WN6bvWiOb4wbbEOz7qS@d01k4nTD1Q1AfkeMP6722jZ1siIkA@kqmK/ZVrd@aq/lMfy42iQUDI08gOCmk7bkDpPd1jT2PVc4FmebiZulNscm/vesJRkKgUyYzjhVJMqUjEa8wxE3HCsbCKCzGfk7G0tbOQvv2sYfgF)
```
-module(main).
-export([y/4, main/1]).
y([], S, _, N) when N > 0 -> [S / N];
y([], _, _, _) -> [];
y([X | Z] = List, S, I, N) ->
if X < I ->
y(Z, S + X, I, N + 1);
true ->
y([], S, I, N) ++ y(List, S, I + 1.0, N)
end.
main(_) ->
io:fwrite("~p~n", [y([0.35, 2, 2.45, 3.71, 5.13, 9.0, 9.66], 0.0, 1.0, 0)]).
```
[Answer]
# [Racket](https://racket-lang.org/), 204 bytes
Golfed version. [Try it online!](https://tio.run/##PY/NasMwEITveoqBHrpLQbXjOqVQmgcxPYhYDksV1dg@2H15Z9z8HAQrzeib2SEcf@K0PqWQTxj@L26VNnaWI2RBGieMMGSFHH9zi0biuZ@Ww6bwzTrIFzIKzslollf6syqeRfUbTUwjQSlSaWZIZwNN219qf5Ah3q832CdmmG7RVF/ImpXxnDJKUiX0fWQN6gx4VLsXpc9QerZhBearru6xzTlYVgdIa2OfwpLyFVP4qsYOO/9Wo/LvJWpfVvjwBc9@ryg4kckdVZ27YtYL)
```
(define (y lst s i n) (cond [(empty? lst) (if (> n 0) (list (/ s n)) '())] [else (let ([x (first lst)] [z (rest lst)]) (if (< x i) (y z (+ s x) i (+ n 1)) (append (y '() s i n) (y lst s (+ i 1.0) n))))]))
```
Ungolfed version. [Try it online!](https://tio.run/##VVBBasMwELz7FQM9dJeCasd1SqE0DzE9iFgOoopqbB/sft4ZywlpBEIjdmZ2dnt7/HHjsjwFG0/o0y/LpHGtjw4yIwwjBnhEzQA5/saGL1CLO3fjfFjrCvEt5AsROXHwlMgrVVEVz6L6vUlcGFxC5DhS6gnS@p7s1WQjXU/9B@ndraK3UurziQle/7MZk/wXdpyUUYkiCn2k2K5zsVmpTHSd6D4fJR6FYXxmZmCK70s4W79N3/ihC3YOcbPJTVlhh515q1Ca9wKVKUp8mJx3v1fkRPTkUpJdslmWCw)
```
#lang racket
(define (y lst s i n)
(cond
[(empty? lst) (if (> n 0) (list (/ s n)) '())]
[else
(let ([x (first lst)]
[z (rest lst)])
(if (< x i)
(y z (+ s x) i (+ n 1))
(append (y '() s i n) (y lst s (+ i 1.0) n))))]))
(define (main)
(displayln (y '(0.35 2 2.45 3.71 5.13 9.0 9.66) 0.0 1.0 0)))
(main)
```
] |
[Question]
[
>
> A number is a Mersenne Prime if it is both prime and can be written in the form 2m-1, where m is a positive integer.
>
>
>
**For example:**
* 7 is a Mersenne Prime because it is 23-1
* 11 is not a Mersenne Prime because it cannot be written as 2m-1
* 15 is not a Mersenne Prime because it is not prime
**The first few Mersenne primes:**
* 3
* 7
* 31
* 127
* 8191
**Your task:**
* Take a user input (it will be a positive integer) - let's call it n
* Find the nth Mersenne prime and output it in the format shown below
**Example output:**
With an input of `4`, the output should be `127`. (But this is [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") so any form of output is allowed)
---
I'll add my attempt at this as an answer, but I'm sure that it can be golfed down a bit.
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), all languages are accepted, and the shortest answer wins!
[Answer]
# JavaScript (ES6), 50 bytes
Returns the \$n\$-th Mersenne prime, 1-indexed.
```
n=>{for(k=1;n;n-=d<2)for(d=k-=~k;k%--d;);return k}
```
[Try it online!](https://tio.run/##FYpBCsIwEADvfcUeKmQpEerFw3b9gX9oaRLRlF1Jq5cQvx7b08DMvKbvtM7p@d6sqPM1cBW@5aDJRO5JSCy74YKHcBwt/yLFk7WOkJLfPkkglnpUAYaeQGBguO7sOoTcAMwqqy7@vOjDjHfTZim4r20ORrCMSE2pfw "JavaScript (Node.js) – Try It Online")
# `eval()` version, 48 bytes
*Suggested by [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan)*
```
n=>eval(`for(k=1;n;n-=d<2)for(d=k-=~k;k%--d;)k`)
```
[Try it online!](https://tio.run/##FcpBCsMgEEDRfU4xixQcgoV008VkcoPeQYlaWmUsSclG7NVtsvrw@G@7221ZX5@vlux8C9yEZ7/bpEzIq4o8kpBodtMNT3AcNf8ixYvWjjAabCcLMIwEAhPD/egwIJQOYMmy5eSvKT@Veai@SMVj7UtQgtUgdbX9AQ "JavaScript (Node.js) – Try It Online")
### How?
Numbers of the form \$2^n-1,\:n>1\$ can be computed recursively with:
$$\begin{cases} a(0)=3\\a(n)=2\times a(n-1)+1\end{cases}$$
Hence the golfed recurrence formula: `k-=~k`.
### Commented
```
n => { // n = input
for( // outer loop:
k = 1; // start with k = 1
n; // stop when n = 0
// after each inner loop,
n -= d < 2 // decrement n if d = 1 (i.e. k is prime)
) //
for( // inner loop:
d = // update k to the next number of the form 2**N - 1
k -= ~k; // and initialize the divisor d to the same value
k % --d; // decrement d until it divides k
); //
return k // k is the n-th Mersenne prime: return it
} //
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 7 bytes
```
Þ∞E‹~æẎ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJHIiwiIiwiw57iiJ5F4oC5fsOm4bqOIiwiIiwiMSJd)
7 bytes flagless (change `Ẏ` to `i`) if 0-indexing is allowed.
## But how?
```
Þ∞E‹~æẎ
Þ∞ # all positive integers
E‹ # as the power of 2 minus 1 (basically, all numbers that are of the form 2^m - 1)
~æ # with only primes kept
Ẏ # take the first (input) items
# The -G flag outputs the biggest of the final list
```
[Answer]
# [Factor](https://factorcode.org/) + `math.primes.lucas-lehmer`, 48 bytes
```
[ 1 lfrom [ lucas-lehmer ] lfilter lnth 2^ 1 - ]
```
[Try it online!](https://tio.run/##VYzBCsIwEETv@Yr5gQYUT/UDxIsX8VRaCGFLg5u0bNZD/fm46MnLMLx5zByirtIe9@vt0uNJUojBqWr9pefw3pGDLt/wm6RMRl8x1I5pySTYhFR3W4ri7NzJtQEH8CxrxoA/dTScWK1xscvjZGKHscXADN8@ "Factor – Try It Online")
0-indexed.
* `1 lfrom` A lazy list of the natural numbers
* `[ ... ] lfilter` Select the ones that...
* `lucas-lehmer` ...are Mersenne numbers
* `lnth` Take the nth one
* `2^ 1 -` Turn a Mersenne number into a Mersenne prime
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
f=lambda k,n=1,p=1:k and f(k-(p%n>n&n+1),n+1,p*n*n)or~-n
```
[Try it online!](https://tio.run/##FcuxDkAwFAXQ3Ve8hbQ8QyUWSf1LhSLl9qWxWPx6sZztyH1tEV3O3h7unGZHgWENizVDIIeZvAqtkhIjKjRG8wdLjRo6pqdF9jFRoB2UHNZFGe71UJCkHdd/dX4B "Python 2 – Try It Online")
Uses the [Wilson's Theorem prime generator](https://codegolf.stackexchange.com/a/27022/20260), which could be implemented like this to find the `k`'th prime:
```
f=lambda k,n=1,p=1:k and f(k-p%n,n+1,p*n*n)or~-n
```
[Try it online!](https://tio.run/##FcsxCoAgGAbQvVP8S6Bmgw4NgocxzBLrU8SlpatbrQ9euduRoXsP9nTX6h0lCatkscokcvAUWJrLCInpUwEBnuszo4dcKVEEVYd9Y0rqhZuBSo1of@L9BQ "Python 2 – Try It Online")
But, modifies it to count only numbers of the form \$2^a-1\$ which are tested for as `n&n+1==0`. This is combined with the primality check as `p%n>n&n+1`.
Because this method recurses through all potential primes whether or not they have form \$2^a-1\$, it already exceeds the default maximum recursion depth for inputs of 5 and above.
**[Python 2](https://docs.python.org/2/), 65 bytes**
```
f=lambda k,n=3:k and f(k-all(n%d for d in range(2,n)),n-~n)or n/2
```
[Try it online!](https://tio.run/##RYwxCoAwEAR7X3GNkIOIGLEJ@JiTGJXEjQQbG78etbIbmGGO61wTTCl@jLJPTihojL0NJHDkVWgkRoX65ZTJ0QbKgmVWRoNZo7nBr0BryheEP@j0wLaiI284vxGXBw "Python 2 – Try It Online")
Recurses through numbers of the \$2^a-1\$ by repeatedly applying `n->2*n+1`, using trial division to test for primality.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
&‘<Ẓø#Ṫ
```
[Try it online!](https://tio.run/##ARkA5v9qZWxsef//JuKAmDzhupLDuCPhuar///80 "Jelly – Try It Online")
```
# Count up the first n matches
Ṫ then take the last
ø starting from 0:
& Is the candidate bitwise AND
‘ itself + 1
< less than
Ẓ whether or not it's prime?
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 85 bytes
```
Y+X:-X mod Y<1->Y<X;Y+1+X.
Q-N-R:-2+Q,Q- \Q-N-R;N>1,Q- \Q-(N-1)-R;R is Q.
W-R:-3-W-R.
```
[Try it online!](https://tio.run/##LYo7CoAwEAV7T7GlEl8gahXFIwRi4wYsBQmoERU8fvxgNcww2x7mMOG4fIxOsAbTEkZyjULrGq6dUIJlYmHQaRTC5hY0fFqbVv2WGqjsKR35g6xM@ncu8UBGDarAOW27X8@UMxlv "Prolog (SWI) – Try It Online")
-4 bytes thanks to Jo King
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~63~~ 51 bytes
```
d;k;f(n){for(k=1;n;n-=d<2)for(d=k-=~k;k%--d;);n=k;}
```
[Try it online!](https://tio.run/##VVDLboMwELznK1ZISHbAaoBGJHLcS9WvKByQbVLk1kQYqaiIfnrp8kjaWPJ6Pbsz3rFkZynHUXHDS2JpX9YNMSLillsm1CmmE6CEYeLbcOMzpjjlVhg@jJVt4aOoLKHQbwDXBOjuomWr1WsOAvokhDSEJAohijE5RMcpTaJdiuc@fowP6cBnrqyta0G@Fc0Wo5ZGN4uEl3UvcdYdn3HvvRD@3xNvZeOQQKbnK6t0h7QdX9MTuOpL1yW5DkYfVmB7QzgEwdxNZ7HFzNVQi2qLVAARvys5LJWkpfeoRvT2CzMz/2u4NNhSEs9XwJ4Ao@8yi67aEFx4M@6E0PkqO2yG8UeW78XZjezzFw "C (gcc) – Try It Online")
*A port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/251596/9481).*
*Saved a whopping 13 bytes thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)!!!*
Inputs positive integer \$n\$.
Returns the 1-based \$n^{\text{th}}\$ Mersenne prime.
[Answer]
# [Python](https://www.python.org), 57 bytes
```
a=1
while 1:a-=~a;0in(a%d for d in range(2,a))or print(a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxBCsIwFAX3nuKBCElpxYqCVnIDbyBSvja1gZqE9It040XcdKHeqbdRWlfvMQzz_PiWK2e7fu-Dsaxqup4KiijO1WEgx2id5XPvvJAiIglMEXTDwZwZ7OBs3WIQwZVGaULDWL9vXCabfksqndwrU2ukGSXqQbuFsYJmBUoXUMBYBLIXLZYxSflDQ0mQHAOvUqz-t-vG_QI)
`a-=~a` taken from [Arnauld's JS answer](https://codegolf.stackexchange.com/a/251596)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes
```
2^MersennePrimeExponent@#-1&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773yjON7WoODUvLzWgKDM31bWiID8vNa/EQVnXUO0/UCivRMEhPdok9v9/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
!fṗm←İ2
```
[Try it online!](https://tio.run/##yygtzv7/XzHt4c7puY/aJhzZYPT//39TAA "Husk – Try It Online")
```
!fṗm←İ2
m # map over
İ2 # powers of 2
← # decrementing each one
f # then filter to keep only
ṗ # primes
! # and get the input-th one.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes
```
;2{;X≜^-₁ṗ}ᶠ⁽t
```
[Try it online!](https://tio.run/##AVAAr/9icmFjaHlsb2cy/3t3IiAtPiAidz/ihrDigoLhuol94bWQ/zsyeztY4omcXi3igoHhuZd94bag4oG9dP//WzEsMiwzLDQsNSw2LDcsOCw5XQ "Brachylog – Try It Online")
Worth noting it started with `∧{≜;2↔^-₁ṗ}ᶠ↖?t`.
```
;2{ }ᶠ⁽ Find the first n possible outputs given 2 from:
;X pair the 2 with an unbound variable,
≜ label the variable to an integer,
^ raise the 2 to that power,
-₁ subtract 1,
ṗ and fail if not prime.
t Yield only the last of the results.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞o<ʒp
```
Outputs the infinite sequence.
[Try it online.](https://tio.run/##yy9OTMpM/f//Uce8fJtTkwr@/wcA)
Outputting the 1-based \$n^{th}\$ value like the example in the challenge description, would be **8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** in the [legacy version of 05AB1E](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b) instead:
```
µNbSPNp*
```
[Try it online.](https://tio.run/##MzBNTDJM/f//0Fa/pOAAvwKt//9NAA)
**Explanation:**
```
∞ # Push an infinite list of positive integers: [1,2,3,...]
o # Take 2 to the power each: [2,4,8,...
< # Decrease each by 1: [1,3,7,...]
ʒ # Filter this list by:
p # Only keep the prime numbers
# (after which the result is output implicitly)
µ # Continue looping while `¾` is not equal to the (implicit) input-integer:
# (counter variable `¾` is 0 by default)
N # Push the loop-index
b # Convert it to a binary string
S # Convert it to a list of digits
P # Check if all bits are 1 by taking the product
N # Push the loop-index again
p # Check whether it's a prime number
* # Check if both are truthy
# (if they are: implicitly increase `¾` by 1)
# (after which the last index `N` is output implicitly as result)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~116 99 88~~ 85 bytes
```
def f(n,i=1,j=0):
while j!=n:i+=1;m=2**i-1;j+=all(m%k for k in range(2,m))
print(m)
```
[Try it online!](https://tio.run/##FcbBCoMwDADQu1@RHQaJdrC6nZR8jLB2praxlIr49R17p5evuu76au3jPHhUI2xN4CdNHZyrRAfhxjrJwHZOPPa9POwcBl5ixHTfwO8FNhCFsujX4WgSUQe5iFZM1Dz@I5qPikTU3j8 "Python 3 – Try It Online")
* (-24 thanks to Jo King)
* (-4 thanks to pxeger)
# [Python+](https://github.com/nayakrujul/python-plus), 78 73 bytes
```
n=int(§())
i=1
j=0
€j!=n
i+=1;m=2**i-1;j+=all(m%k£k:range(2,m))
$(m)
```
* (-1 thanks to pxeger)
* (-4 thanks to Jo King)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 38 bytes
```
\d+
_
$
_$`
"$+"}/^(__+)\1+$/+`$
_$`
_
```
[Try it online!](https://tio.run/##K0otycxLNPz/PyZFmyueS4UrXiWBS0lFW6lWP04jPl5bM8ZQW0VfOwEiEf//vykA "Retina – Try It Online") No test suite due to the program's use of history. Explanation:
```
\d+
_
```
On the first pass through the loop, replace the input with `1` in unary.
```
$
_$`
```
Double and increment the value.
```
/^(__+)\1+$/+`
```
While the value is composite...
```
$
_$`
```
... double and increment the value.
```
"$+"}
```
Repeat the above `n` times.
```
_
```
Convert to decimal.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
Nθ≔¹ηWθ«≔⊕⊗ηη≧⁻﹪±Π…¹ηηθ»Iη
```
[Try it online!](https://tio.run/##LU67DoMgFJ31KxiviR06dHJq2sVBY/wDxBsgQVC4tEPTb6cYOp2cnKdQ3AvHTUq93SONcVvQw9F09T0ELS1cW6YyeyttkGWBferqL/VWeNzQEq7wdHExGVXTlEA18L34Zi0VwaBtDC0b3BqNgxElJ4TJZyoIZm4llqmSb9l54VtPXluCBw90Nncp3dLlZX4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
≔¹η
```
Start with `1`.
```
Wθ«
```
Repeat until `n=0`.
```
≔⊕⊗ηη
```
Double and increment the value.
```
≧⁻﹪±Π…¹ηηθ
```
If the value is prime then decrement `n`. For decremented powers of 2, `(n-1)!%-n` is either `0` for composite or `-1` for prime. (In fact, `(n-1)!²%n` is `0` for any positive non-prime and `1` for any prime.)
```
»Iη
```
Output the final value.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 52 bytes
```
->n{r=1;1until(2...r+=r+1).all?{|x|r%x>0}&&1>n-=1;r}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vusjW0NqwNK8kM0fDSE9Pr0jbtkjbUFMvMSfHvrqmoqZItcLOoFZNzdAuTxeosqj2f4FCWrRR7H8A "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Èõ!²mÉ øX*j}iU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yPUhsm3JIPhYKmp9aVU&input=NA)
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$8\log\_{256}(96)\approx\$ 6.585 bytes
```
F@p{^2mC
```
[Try it online!](https://fig.fly.dev/#WyJGQHB7XjJtQyIsIiJd)
Outputs an infinite list of Mersenne primes.
```
F@p{^2mC
mC # Infinite list of counting numbers
^2 # 2^x
{ # Decrement
F@ # Filter for...
p # Primality
```
] |
[Question]
[
# Your Goal:
Given an odd integer input `n` greater than 1, generate a random *English word* of length `n`. An English word is one in which the **odd** (1-based) indices are **consonants** and the **even** (1-based) **indices** are vowels, the vowels being `aeiou`.
## Random
For the purposes of this challenge, you are to sample from the vowels and consonants uniformly, with replacement. In other words, each possible English word must be equally likely to appear as an output.
# Example Inputs/Outputs
```
3 -> bab, tec, yiq
5 -> baron, nariz, linog
7 -> murovay, fanafim
```
**Winner:**
Winner is the Lowest Byte Count.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 11 bytes
-3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
```
EžN¸žMšNèΩJ
```
[Try it online!](https://tio.run/##ARwA4/9vc2FiaWX//0XFvk7CuMW@TcWhTsOozqlK//83 "05AB1E – Try It Online")
[Answer]
# [Plain English](https://osmosianplainenglishprogramming.blog/), 485 bytes
```
To add any vowel to a string:
Pick a letter of the alphabet.
If the letter is any vowel, append the letter to the string; exit.
Repeat.
To add any consonant to a string:
Pick a letter of the alphabet.
If the letter is any consonant, append the letter to the string; exit.
Repeat.
To make a random string given a length:
If a counter is past the length, exit.
Add any consonant to the random string.
If the counter is past the length, exit.
Add any vowel to the random string.
Repeat.
```
What better way to write some random English than by using Plain English? I have applied a moderate level of golfing to this code; certain things could be shortened, but it would make this less legible, which would be a shame.
The reason I have defined three routines is because nested loops are forbidden in Plain English, so inner loops must be factored into separate routines.
Parameters and local variables are written as "a string" or "a length" (for example). These are subsequently referred to as "the string" and "the length." If you need to refer to more than one string, you could for example introduce "another string" and refer to it with "the other string." You may also name them whatever you want: "a random string" and refer to it either as "the random" or "the random string."
All arguments are passed by reference; even numbers. To output from a routine, you just modify the arguments. Then you simply refer to the object returned by the routine in the same way as you refer to parameters. For example, to use the routine defined above to output a random English word, you could:
```
To run:
Start up.
Make a random string given 5.
Write the random string on the console.
Wait for the escape key.
Shut down.
```
"To run:" is a special routine that signifies the starting point of the program. When added to the other three routines, this results in a program which will show something similar to the following when compiled and run:
[](https://i.stack.imgur.com/TBPhm.png)
[Answer]
# [Perl 5](https://www.perl.org/), 69 bytes
```
say map{([a,e,i,o,u],[grep!/[eiou]/,b..z])[$_%2][rand$_%2*16+5]}1..<>
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVIhN7GgWiM6USdVJ1MnX6c0Vic6vSi1QFE/OjUzvzRWXydJT68qVjNaJV7VKDa6KDEvBcTSMjTTNo2tNdTTs7H7/9/QwPBffkFJZn5e8X9dX1M9A0MDAA "Perl 5 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 89 bytes
```
f=(n,b)=>(b?"aeiou":"bcdfghjklmnpqrstvwyxz")[~~(Math.random()*(b?5:21))]+(--n?f(n,!b):"")
```
[Try it online! (includes tests)](https://tio.run/##ZYxbCsIwEACvsgY/djUtqIhYUE/gCUqh6SOtGrPaxvooiofwhF6k6rd/A8PMVjWqTqvNwXmWs7zr9AKtTGixxGQlVL7hkwhEkma6KLc7s7eHY1W75ny93ASFjweulSv9StmM90iDbzQNxiOiaIieZ1f6O@slFAhBneYKMGVbOzDAGsKJhKmEmYR5RPATbHLfcIFxvzV3eD9fS@i3Gg3d5R/E1H0A "JavaScript (Node.js) – Try It Online")
Takes `n` as length and `b` as whether to return vowel or consonant, default consonant.
Returns consonant or vowel based on `b`, decrements `n` and recurses with opposite `b` value.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
ØḄØẹḂ?X)
```
*-1 byte thanks to @Steffan*
[Try it online!](https://tio.run/##y0rNyan8///wjIc7WoDErp0PdzTZR2j@///fFAA "Jelly – Try It Online")
Explanation:
```
ØḄØẹḂ?X) # main link taking an integer
) # over the list [1..n]
? # if
Ḃ # n modulo 2 is truthy
ØḄ # yield the consonants
Øẹ # otherwise the vowels
X # get a random letter from that
```
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ÇÅφ⌠↑Ѱ↕Yx
```
[Run and debug it](https://staxlang.xyz/#p=808fedf418a5f8125978&i=7)
# Explanation
```
FVcVv2l@_@L
F In range 1 to the input, do this ...
Vv Vowels
Vc Consonants
2l Wrap the two inside a list
@ Index the constructed list into the counter
Note that the counter starts at 1,
so this picks the constants list
before the vowels list.
_@ Index by the current counter
(Stax doesn't have random number support)
L Wrap the whole stack into a list
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 76 bytes
Basic recursive function that adds a consonant and a vowel each time until there's only one character left, at which point it adds just the consonant.
```
f=->n{[*?b..?z].grep(/[^eiou]/).sample+(n<2?'':'aeiou'.chars.sample+f[n-2])}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y6vOlrLPklPz74qVi@9KLVAQz86LjUzvzRWX1OvODG3ICdVWyPPxsheXd1KPREkoa6XnJFYVAyTTIvO0zWK1az9b6xXXALUbmioY6SpkJKvUJNZw6WgUFBaUqyQFp0Zq4NEcqXmpfwHAA "Ruby – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 36 bytes
```
,{['aeiou'.123,97>^]\2%=.,rand=}%''+
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPlv/l@nOlo9MTUzv1Rdz9DIWMfS3C4uNsZI1VZPpygxL8W2VlVdXfv/fwA "GolfScript – Try It Online")
[Answer]
# [Python](https://www.python.org), 83 bytes
```
lambda n:[*map(choice,["bcdfghjklmnpqrstvwxzy","aeiou"]*n)][:n]
from random import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYw9DsIgGEB3T0GIAzSYaCfTxFM4Ygf6Q_m0fCBStV7FhcTonbyNmjq94b28-8uP0ThMD73ZPYeoF-v3tle2ahTBQmZWeVYbB3UrJK3qRndmf-gt-mM4xfPlehupoKoFN9AyQ17KAsuZDs6SoLD5Aqx3IWb_9Vy7QIAA_nTXspXIlyLnhQ-AkYHQDDif2pQmfgA)
Outputs a list of characters.
This is conceptually the same as [grc's answer for "Generate a pronounceable word"](https://codegolf.stackexchange.com/a/11879/113573), since the questions are almost identical.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 9 bytes
```
⟑₂¨ikvk¹℅
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwi4p+R4oKCwqhpa3ZrwrnihIUiLCIiLCI3Il0=)
Explanation:
```
⟑ # Map over the range 1 to n
₂¨i # If even:
kv # Push the string "aeiou"
# Otherwise:
k¹ # Push the lowercase consonants
℅ # Get a random character from the top of the stack
# Concatenate the character list into a string with the s flag
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 12 bytes
```
RC*[.CZVW]Ha
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJSQypbLkNaVlddSGEiLCIiLCIiLCI3Il0=)
### Explanation
This should be 11 bytes; the `.` is a no-op to work around a bug in the current language version.
```
RC*[CZVW]Ha
[ ] List containing:
CZ Lowercase consonants
VW Lowercase vowels
a Command-line argument
H Take that many elements (cycling the list as necessary)
RC* Random choice from each
```
---
I also found several 13-byte solutions:
```
RC{VW::CZ}M,a
RC[CZVW]@_M,a
LaORC(VW::CZ)
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 93 89 bytes
```
v=aeiou]
until tr -dc a-z</dev/urandom|head -c$1|grep -E "^[^$v([$v[^$v)*[$v?$";do
:
done
```
[Try it online!](https://tio.run/##S0oszvhfnFqiYPK/zDYxNTO/NJarNK8kM0ehpEhBNyVZIVG3ykY/JbVMv7QoMS8lP7cmIzUxRUE3WcWwJr0otUBB11VBKS46TqVMI1qlDERragEZ9ipK1in5XFZcKfl5qf//AwA "Bash – Try It Online")
A full command line program.
It generates random lowercase alpha strings of the required size in a loop until we find one matching the pattern `^<vowel>(<cons><vowel>)*<cons>?`.
[Answer]
## [D](https://en.wikipedia.org/wiki/D_(programming_language)), 124 bytes
```
auto f(int n){string s;for(import std;n;n--,s~=n%2?"aeiou"[uniform(0,5)]:"bcdfghjklmnpqrstvwxyz"[uniform(0,20)]){}return s;}
```
I'm not very good at code golf (but trying to get better) so this can probably be improved a lot
[Try it online](https://tio.run/##TY7LDoIwEEXX8hWTJiRtBIMkbqjEDzEu0AKOylTbgg@Cv47FjS5uzuYk56oRm6s2DqxTCz/Ucixap6HiSA5I9NYZpBqsrLThP1mSpDiO7DunMN2wokTdsm1L6LWGJ9FK7DK2P6iqPp7Ol4auN2Ndd388X/9Wmoid6AdTutaQbwxjp1FBUyBxAX0AAN@sv4KQw1J6rCFNJs5zSEUwuxt0ZXUhzkKVQWhZBBhN94WQwTB@AA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `rṀs`, 8 bytes
```
ƛkvk⁰"i℅
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJy4bmAcyIsIiIsIsaba3Zr4oGwXCJp4oSFIiwiIiwiNCJd)
Fun
[Answer]
# [Factor](https://factorcode.org) + `pair-rocket sequences.repeating`, 62 bytes
```
[ "bcdfghjklmnpqrstvwxyz"=> "aeiou"swap cycle [ random ] map ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RYwxDoIwFEB3TvHTHTcTo5FR4-JinAhD_XywUtryW0S8iguLDt6I22hCjNNL3kve41VIDJaHcXM87PbbJTipOGaLFQWoiA1p8NS0ZJD8jMmRDMqUwNLktv4nUBZWUTR_tqGIF2OSgjhhXpTnS6Vr4xr24drd-rtYJyAkKdsK30kH2KMmSH-_DOqvzKbLG6XW0LEKNIlhmPgB)
```
! 5
"bcdfghjklmnpqrstvwxyz"=> "aeiou" ! 5 { "bcdfghjklmnpqrstvwxyz" "aeiou" }
swap ! { "bcdfghjklmnpqrstvwxyz" "aeiou" } 5
cycle ! { "bcdfghjklmnpqrstvwxyz" "aeiou" "bcdfghjklmnpqrstvwxyz" "aeiou" "bcdfghjklmnpqrstvwxyz" }
[ random ] map ! "furom"
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 19 bytes
```
J"aeiou"smO?%d2J-GJ
```
[Test suite](https://pythtemp.herokuapp.com/?code=J%22aeiou%22smO%3F%25d2J-GJ&test_suite=1&test_suite_input=3%0A5%0A7&debug=0)
##### Explanation:
```
J"aeiou"smO?%d2J-GJ | Full code
J"aeiou"smO?%d2J-GJQ | with implicit variables
---------------------+--------------------------------------------------------
J"aeiou" | J = "aeiou"
m Q | For each d in [0...input):
O | Pick a random letter from
J | J
?%d2 | if d is even else
-GJ | the lowercase alphabet minus J (i.e. the consonants)
s | Print the concatenated results
```
[Answer]
# [Raku](https://raku.org/), 67 bytes
```
{$!=<a e i o u>;({(('a'..'z')∖$!,$!)[$++%2].pick}...*)[^$_].join}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkXR1iZRIVUhUyFfodTOWqNaQ0M9UV1PT71KXfNRxzQVRR0VRc1oFW1tVaNYvYLM5OxaPT09Lc3oOJX4WL2s/My82v8FpSUKaRoq8ZoKFRUKxgpp@UUKxjoKpjoK5v8B "Perl 6 – Try It Online")
* The vowels are stored in `$!`, one of just two special global variables that don't need to be declared.
* `{ ... } ... *` is a lazy, infinite list, where the code between the braces generates each successive element.
* `('a' .. 'z') ∖ $!` are the consonants. That `∖` isn't a backslash, it's the Unicode `SET MINUS` character.
* `(('a' .. 'z') ∖ $!, $!)[$++ % 2]` alternately chooses the consonants and vowels on each iteration of the generator. The anonymous state variable `$` counts how many iterations there have been so far, and the `% 2` reduces that to the alternating sequence `0, 1, 0, 1, ...`.
* `.pick` chooses a random vowel or consonant.
* `[^$_]` takes a number of elements from the sequence equal to the argument passed to the function.
* `.join` joins those elements into a single string.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~61~~ 58 bytes
```
c;f(n){for(;n;4370%c-n&1&&putchar(c,n--))c=97+clock()%26;}
```
[Try it online!](https://tio.run/##DcHRCoJAEAXQd7/CF5cZckArWmToY5YLq5KNYUUP4q83eg6kB9yhmYzXPC@kptdLbCqIhTaE1/eDIS2E2kSYce/iCdOMB3F1vunmzzQacbkW5SFTZC02/yNPqX@7/HY "C (gcc) – Try It Online")
-3 bytes thanks to ceilingcat!!
[Answer]
# [Zsh](https://zsh.sourceforge.io/) `--braceccl`, 67 bytes
[Try it Online!](https://tio.run/##FcWxDkAwFAXQ3VfcwcDwEo3B4md4WiXSNtoaVL@9GE7O7XXxMlgXMJ8TS@ajUk2bitdRgUwtMDaStUWaeVGr3sk4ChfdOU1yszE/p0cH0f7T2j0cA4hBtSi5Uug/w0cM5QU)
```
shuf -n$1 <(echo {bcdfghj-np-tv-z}{aeiou}|rs 0 1)|rs -g0|cut -c -$1
```
Similar to the [pronounceable word](https://codegolf.stackexchange.com/a/255756/15940) solution.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-mP`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;Ck%+Ugciv¹ö
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1Q&code=O0NrJStVZ2Npdrn2&input=Nw)
```
;Ck%+Ugciv¹ö :Implicit map of each U in the range [0,input)
;C :Lowercase alphabet
k :Remove
%+ : Append to "%"
Ug : Index U into
civ : "c" prepended with "v"
¹ :End remove ("%v"=/[aeiou]/gi "%c"=/[b-df-hj-np-tv-z]/gi)
ö :Random character
:Implicitly join & output
```
[Answer]
# [Nim](https://nim-lang.org/), 148 bytes
```
import random
randomize()
proc x(y:int):string=
let l="bcdfghjklmpqrstvwxyz";let a="auioe";for i in 0..y-1:result.add sample(if(i%%2)==0:l else:a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc49DoIwGMbxnVO8ISEpgwSZTEkPU2kLr_YD26LAOdxcSIyDR_I2atDpyT_P8rvdLZpleQxRbXavK5re-QieW-FMsg7OkuRJ710DI5ko2pjTED3aliUAWkbQLN03QrXd4ahNf_Ihni_jNKf19-Qs5QM6mdbKeUBAC2VRTJst9TIMOhZcCAjc9FoSVASzrMoZK6kGqYOkPF9tT9l07gOofv03vwE)
] |
[Question]
[
In this task, you will write a program/function that takes a [Normalized Malbolge](http://acooke.org/malbolge.html#norm) program and outputs the resulting [Malbolge](https://esolangs.org/wiki/malbolge) program. (This is a secret tool that all Malbolge programmers are using!)
## Input
A data structure that (somehow) represents a Normalized Malbolge program.
## Output
A data structure that represents the resulting Malbolge program.
## Examples
```
jpoo*pjoooop*ojoopoo*ojoooooppjoivvvo/i<ivivi<vvvvvvvvvvvvvoji
(=BA#9"=<;:3y7x54-21q/p-,+*)"!h%B0/.~P<<:(8&66#"!~}|{zyxwvugJ%
jjjj*<jjjj*<v
('&%#^"!~}{XE
jjjjjjjjjjjjjjjjjjjjjjj*<jjjjjjjjjjjjjjjjjjjjjjjj*<v
('&%$#"!~}|{zyxwvutsrqpnKmlkjihgfedcba`_^]\[ZYXWVT1|
```
## How to convert
Iterate over the normalized Malbolge program, performing the following steps for each character:
1. Replace the characters in the string `*jpovi</` with the corresponding character in `'(>DQbcu`. (That is, map `*` to `'`, `j` to `(`, and so on.)
2. Then subtract the current position of the program counter (i.e. the number of characters before the current one) from the character's ASCII code.
3. If the resulting ASCII code is less than 33, increment it by 94 and repeat until it is at least 33.
4. Append the resulting character to the output.
## Rules
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") contest; the shortest answer wins.
* No [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) please.
* The default I/O methods are allowed.
* Input will only contain the characters `*jpovi</`.
[Answer]
# Malbolge Unshackled (20-trit rotation variant), 7,784e6 bytes
Size of this answer exceeds maximum postable program size (eh), so the code is [located in my GitHub repository](https://github.com/KrzysztofSzewczyk/codegolf-submissions/raw/master/190971.mu).
## How to run this?
This might be a tricky part, because naive Haskell interpreter will take ages upon ages to run this. TIO has decent Malbogle Unshackled interpreter, but sadly I won't be able to use it (limitations).
The best one I could find is the fixed 20-trit rotation width variant, that performs very well, **converting 0,5 characters per second**.
To make the interpreter a bit faster, I've removed all the checks from Matthias Lutter's Malbolge Unshackled interpreter.
My modified version can run around 6,3% faster.
```
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh"
"OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";
typedef struct Word {
unsigned int area;
unsigned int high;
unsigned int low;
} Word;
void word2string(Word w, char* s, int min_length) {
if (!s) return;
if (min_length < 1) min_length = 1;
if (min_length > 20) min_length = 20;
s[0] = (w.area%3) + '0';
s[1] = 't';
char tmp[20];
int i;
for (i=0;i<10;i++) {
tmp[19-i] = (w.low % 3) + '0';
w.low /= 3;
}
for (i=0;i<10;i++) {
tmp[9-i] = (w.high % 3) + '0';
w.high /= 3;
}
i = 0;
while (tmp[i] == s[0] && i < 20 - min_length) i++;
int j = 2;
while (i < 20) {
s[j] = tmp[i];
i++;
j++;
}
s[j] = 0;
}
unsigned int crazy_low(unsigned int a, unsigned int d){
unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
int position = 0;
unsigned int output = 0;
while (position < 10){
unsigned int i = a%3;
unsigned int j = d%3;
unsigned int out = crz[i+3*j];
unsigned int multiple = 1;
int k;
for (k=0;k<position;k++)
multiple *= 3;
output += multiple*out;
a /= 3;
d /= 3;
position++;
}
return output;
}
Word zero() {
Word result = {0, 0, 0};
return result;
}
Word increment(Word d) {
d.low++;
if (d.low >= 59049) {
d.low = 0;
d.high++;
if (d.high >= 59049) {
fprintf(stderr,"error: overflow\n");
exit(1);
}
}
return d;
}
Word decrement(Word d) {
if (d.low == 0) {
d.low = 59048;
d.high--;
}else{
d.low--;
}
return d;
}
Word crazy(Word a, Word d){
Word output;
unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
output.area = crz[a.area+3*d.area];
output.high = crazy_low(a.high, d.high);
output.low = crazy_low(a.low, d.low);
return output;
}
Word rotate_r(Word d){
unsigned int carry_h = d.high%3;
unsigned int carry_l = d.low%3;
d.high = 19683 * carry_l + d.high / 3;
d.low = 19683 * carry_h + d.low / 3;
return d;
}
// last_initialized: if set, use to fill newly generated memory with preinitial values...
Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) {
if ((mem[d.area])[d.high]) {
return &(((mem[d.area])[d.high])[d.low]);
}
(mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word));
if (!(mem[d.area])[d.high]) {
fprintf(stderr,"error: out of memory.\n");
exit(1);
}
if (last_initialized) {
Word repitition[6];
repitition[(last_initialized-1) % 6] =
((mem[0])[(last_initialized-1) / 59049])
[(last_initialized-1) % 59049];
repitition[(last_initialized) % 6] =
((mem[0])[last_initialized / 59049])
[last_initialized % 59049];
unsigned int i;
for (i=0;i<6;i++) {
repitition[(last_initialized+1+i) % 6] =
crazy(repitition[(last_initialized+i) % 6],
repitition[(last_initialized-1+i) % 6]);
}
unsigned int offset = (59049*d.high) % 6;
i = 0;
while (1){
((mem[d.area])[d.high])[i] = repitition[(i+offset)%6];
if (i == 59048) {
break;
}
i++;
}
}
return &(((mem[d.area])[d.high])[d.low]);
}
unsigned int get_instruction(Word** mem[], Word c,
unsigned int last_initialized,
int ignore_invalid) {
Word* instr = ptr_to(mem, c, last_initialized);
unsigned int instruction = instr->low;
instruction = (instruction+c.low + 59049 * c.high
+ (c.area==1?52:(c.area==2?10:0)))%94;
return instruction;
}
int main(int argc, char* argv[]) {
Word** memory[3];
int i,j;
for (i=0; i<3; i++) {
memory[i] = (Word**)malloc(59049 * sizeof(Word*));
if (!memory) {
fprintf(stderr,"not enough memory.\n");
return 1;
}
for (j=0; j<59049; j++) {
(memory[i])[j] = 0;
}
}
Word a, c, d;
unsigned int result;
FILE* file;
if (argc < 2) {
// read program code from STDIN
file = stdin;
}else{
file = fopen(argv[1],"rb");
}
if (file == NULL) {
fprintf(stderr, "File not found: %s\n",argv[1]);
return 1;
}
a = zero();
c = zero();
d = zero();
result = 0;
while (!feof(file)){
unsigned int instr;
Word* cell = ptr_to(memory, d, 0);
(*cell) = zero();
result = fread(&cell->low,1,1,file);
if (result > 1)
return 1;
if (result == 0 || cell->low == 0x1a || cell->low == 0x04)
break;
instr = (cell->low + d.low + 59049*d.high)%94;
if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r'
|| cell->low == '\n');
else if (cell->low >= 33 && cell->low < 127 &&
(instr == 4 || instr == 5 || instr == 23 || instr == 39
|| instr == 40 || instr == 62 || instr == 68
|| instr == 81)) {
d = increment(d);
}
}
if (file != stdin) {
fclose(file);
}
unsigned int last_initialized = 0;
while (1){
*ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0),
*ptr_to(memory, decrement(decrement(d)), 0));
last_initialized = d.low + 59049*d.high;
if (d.low == 59048) {
break;
}
d = increment(d);
}
d = zero();
unsigned int step = 0;
while (1) {
unsigned int instruction = get_instruction(memory, c,
last_initialized, 0);
step++;
switch (instruction){
case 4:
c = *ptr_to(memory,d,last_initialized);
break;
case 5:
if (!a.area) {
printf("%c",(char)(a.low + 59049*a.high));
}else if (a.area == 2 && a.low == 59047
&& a.high == 59048) {
printf("\n");
}
break;
case 23:
a = zero();
a.low = getchar();
if (a.low == EOF) {
a.low = 59048;
a.high = 59048;
a.area = 2;
}else if (a.low == '\n'){
a.low = 59047;
a.high = 59048;
a.area = 2;
}
break;
case 39:
a = (*ptr_to(memory,d,last_initialized)
= rotate_r(*ptr_to(memory,d,last_initialized)));
break;
case 40:
d = *ptr_to(memory,d,last_initialized);
break;
case 62:
a = (*ptr_to(memory,d,last_initialized)
= crazy(a, *ptr_to(memory,d,last_initialized)));
break;
case 81:
return 0;
case 68:
default:
break;
}
Word* mem_c = ptr_to(memory, c, last_initialized);
mem_c->low = translation[mem_c->low - 33];
c = increment(c);
d = increment(d);
}
return 0;
}
```
## It's working!
[](https://i.stack.imgur.com/JBn3M.png)
[Answer]
# [Python 3](https://docs.python.org/3/), 82 bytes
```
p=0
for c in input():print(end=chr((b"de{#0ABT"["*jpovi<".find(c)]-p)%94+33));p+=1
```
[Try it online!](https://tio.run/##TYrBCsIwEETvfkWJCEmKWkkv1uSg3@BNvJi0dHPILiUGxI@PqydnBoY3DL3yjMnUSq5bTbg0voHEoWeWaqAFUpZjCs7Pi5QPEcb3ujtfruImdCQsYMVughSkV/ctqc2xb41R6kStO9TKD9QUkUUaub@MP0biHUopuAcLhW3LvzDC8AE "Python 3 – Try It Online")
Thanks to @Joel for replacing the ugly unprintable characters in the bytestring with printable ones.
I'm looking for a mod-chain to replace `"*jpovi<".find(c)`, but I don't think there is one that's shorter, and a non-exhaustive brute-force search hasn't found anything so far.
**82 bytes**
```
f=lambda s,p=0:s and chr((b"de{#0ABT"["*jpovi<".find(s[0])]-p)%94+33)+f(s[1:],p+1)
```
[Try it online!](https://tio.run/##TYvBDoIwEER/hdSYdAEVAhcbOOg3eCMcwNqwRLsbik2MH1@rJ2cOk/eS4dc6ka1CMO19eIx6SFzObaFcMlidXKdFylHo23tTnM4X0Yl0ZvLYiL1Bq6Xrih76HcP2WGdVBZmJqlR9zlkJgRe0qzQSLT9XCQAhninlmWI4pbhfph8TR4/eezpggz628f@hGdUH "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~84~~ 83 bytes
```
f=lambda p,i=0:p and chr(126-(i+b"WV@:-zyg"["*jpovi<".find(p[0])])%94)+f(p[1:],i+1)
```
[Try it online!](https://tio.run/##bVBdT8IwFH3nV9TicN0HMECUuSVK4ou@@GAAHQPHPouwlm1MBuhfn3VLABNOkzbn3HtPbw7NkoCE7Tz39IW1nDkWoBLWmyoFVugAO4h4pdWVeSzO4HBwr8rbzIcGFOaUpFiDdQ@HDk@NpolMxPU6SPQYU1RTwqKC8sSNk6ltxW4MdGBUAOAhGyQCnRMGKhD2/nFScEKZjtM0JQ2s4ZQdLT0FmWMoAcjr/Ydqbwx17U5tZzeb647cUlYNKkuigMbwIuD6zUb950XTVP621u1Wmfbzvd9ts81XuvafOIikchUGQSvvtHC@qnHVSdG@Gz2etp1BOXm@cnC7/P95EkcrGj4vF59zHPie69gz62M6McfG@9toOHhV9hBVzErFIxGgEfEl4G6oayeuA3AIjmmqbDEAyDphsbLAWScqFCuO3SgpC/phVgJ8acb0oyPKfwE "Python 3 – Try It Online")
This is mostly a math problem about simplifying the computation, plus some golfing after getting the math done. The ungolfed version of code is shown below.
# Ungolfed, non-recursive version
```
def convert(prog):
offsets = dict(zip("*jpovi</", [87, 86, 64, 58, 45, 122, 121, 103])) # ASCII encoded to "WV@:-zyg"
output = ""
for pos, c in enumerate(prog):
output += chr(126-(offsets[c]+pos)%94)
return output
```
[Try it online!](https://tio.run/##bVJtT9swEP7eX3FzV2an7kr6EkqWSINpH9i@TGICRlugS5zWZcQmcby2vPz17powKBJPpIvufPfc@R7rpZmptLtexyKBSKVWZIbqTE2ZXwOESpJcmBxCiGVk6EpqSpy5VlYGbcJhONjjMPA4eD0O/QGHXp@D2@lsjItmtztmDKAOB8dfjo5ApJGKRQxGATk9@ey3VsspqfoURhcG25DKT1QGWuUcIpAp1hU3IpsYsT3aVlkzhGiWUbfjtejTxMNo3EQC1tjvsTI9E6bI0qeKtRG5uYwmudhcbYgJlOCtlKPnCqEdhf@Nr0pfaYxLa61qy0Ba/AK7DTWXuAxCw8OD@v6IhMEnv7vcW/R7rY5729Yt3nTYiLybNQ532x8ffwSBTwc7nlfH2OPD/d1qufhri@m3BmG8GgXhBJW1JfOHnUb9oky/O/u6nfYGqsq3T57Z3r9ubvLsVqffb/5cz@Vsmog4@j25urwYj4bnv85OT36694TVxrVaqQtqwEEstIgMion6vGzT/68mrvXVcyrjkzzHQHUcPjNwoBUlxl942fof "Python 3 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 69 bytes
```
s=>(B=Buffer)(s).map((c,i)=>33+(B(" #{T BAe0d")[c%11]+94-i%94)%94)+''
```
[Try it online!](https://tio.run/##dYxBDoIwEEX3noJgSFsQlMCGhJLYM7gzLkhtTRtkGqrdePhaZGMMvsnM5M/PfN273vJJmUc@wlV4Sb2lHWaUPaUUE8GWFPfeYMx3itCuqjLMcBxtX6eIHcXhGpMzT8rykjV1rpKmJnNnCHkOo4VBFAPcsMRIG4DUaAiYFMKeNXw0mHBXzjnYq1a5UK37BrRChGx@AwNpu0z3x19heVl35hj/Bg "JavaScript (Node.js) – Try It Online")
### How?
Conveniently, Malbolge commands can easily be turned into a value in \$[1..9]\$ by just taking their ASCII code modulo \$11\$.
```
char. | ASCII code | mod 11
-------+------------+--------
'*' | 42 | 9
'j' | 106 | 7
'p' | 112 | 2
'o' | 111 | 1
'v' | 118 | 8
'i' | 105 | 6
'<' | 60 | 5
'/' | 47 | 3
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ 22 bytes
```
Oị“%þV DCµ2® ‘_JịØṖḊ¤
```
[Try it online!](https://tio.run/##y0rNyan8/9//4e7uRw1zVA/vC1NwcT601ejQOgWFRw0z4r2AEodnPNw57eGOrkNL/v//n4UdaNlk4ZQpAwA "Jelly – Try It Online")
A monadic link taking a Jelly string as its argument and returning a Jelly string.
Thanks to @JonathanAllan for saving 2 bytes!
## Explanation
```
O | Convert to Unicode code points
ị“%þV DCµ2® ‘ | Index into compressed integer list [37, 31, 86, 32, 68, 67, 9, 50, 8, 32, 32] (note the 32s are never actually used because the input mod 11 will be one of 1,2,3,5,6,7,8,9)
_J | Subtract position of character in original string
ị ¤ | Index into the following as a nilad:
ØṖ | - Printable ASCII characters
Ḋ | - With the first character (space) removed
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~65 55~~ 53 bytes
```
*.ords>>.&{(' #{T BAe0d'.ords[$_%11]-$++)%94+33}.chrs
```
[Try it online!](https://tio.run/##TYjLCsIwFET3/YqAfSYYLRVBGgv6De5EpNgUE1pvSOBCKX57jHXjGZjhjJF22PtxImlPjp5ysJ1rGp7OeUZW84WcT3LbZct9je9JWd7WMWNFctixqnrzx9M6X0eDeknHx9bklKc9d@1U1F4bAGo0BAyFsF@HxcGEXyEibJRQGCLwH9Aq0gEqfo0f "Perl 6 – Try It Online")
Uses the mod 11 trick from [Arnaud's answer](https://codegolf.stackexchange.com/a/190990/76162)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~32~~ ~~31~~ ~~23~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žQ¦•4¡ˆ¶ü]₁η₃•₃вIÇèā-è
```
-8 bytes creating a port of [*NickKennedy*'s Jelly answer](https://codegolf.stackexchange.com/a/190981/52210), so make sure to upvote him!!
-1 byte thanks to @Grimy.
Outputs as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f//6L7AQ8seNSwyObTwdNuhbYf3xD5qajy3/VFTM1AQSF7Y5Hm4/fCKI426h1f8/59VkJ@vVZCVDwQFWvlAGsTPB/PzC4DimWVlZfn6mTaZZUBoU4YM8rMyAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVqnkmVdQWmKloHB4v5IOl5J/aQmYq2T//@i@wEPLHjUsMjm08HTboW2H98Q@amo8t/1RUzNQEEhe2FR5uP3wiiONuodX/PfSObTN/n9WQX6@VkFWPhAUaOUDaRA/H8zPLwCKZ5aVleXrZ9pklgGhTRkyyM/K5MoCAi0bCFkG5mEBEAXYZcoA).
**Explanation:**
```
•4¡ˆ¶ü]₁η₃• # Push compressed integer 82767635194143615015
₃в # Converted to base-95 as list: [1,36,30,85,0,67,66,8,49,7,0]
IÇ # Push the input and convert each character to its unicode value
è # Index each into the list we created
ā # Push an integer list in the range [0, length]
# (without popping the list itself)
- # Subtract it from the previous list
žQ # Push builtin with all printable ASCII characters,
¦ # and remove the leading space
è # Index the values of the list into the ASCII characters
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•4¡ˆ¶ü]₁η₃•` is `82767635194143615015` and `•4¡ˆ¶ü]₁η₃•₃в` is `[1,36,30,85,0,67,66,8,49,7,0]`.
[Answer]
# Perl 5 (`-p`), ~~53~~, 51 bytes
saving 2 bytes, using `de{#0ABT` instead of `'(>DQbcu` so that `61` no longer needed
```
y;*jpovi</;de{#0ABT;;s/./chr 33+(-"@-"+ord$&)%94/ge
```
[TIO](https://tio.run/##K0gtyjH9/7/SWiurIL8s00bfOiW1WtnA0SnE2rpYX08/OaNIwdhYW0NXyUFXSTu/KEVFTVPV0kQ/PfX/f6COfK2CrHwgKNDKB9Igfj6Yn18AFM8sKyvL18@0ySwDQpsyZJCflcmVBQRaNhCyDMzDAiAKsMuU/csvKMnMzyv@r1sAAA)
first answer was
```
y;*jpovi</;'(>DQbcu;;s/./chr 33+(61-"@-"+ord$&)%94/ge
```
[TIO](https://tio.run/##K0gtyjH9/7/SWiurIL8s00bfWl3DziUwKbnU2rpYX08/OaNIwdhYW8PMUFfJQVdJO78oRUVNU9XSRD899f9/oJ58rYKsfCAo0MoH0iB@PpifXwAUzywrK8vXz7TJLANCmzJkkJ@VyZUFBFo2ELIMzMMCIAqwy5T9yy8oyczPK/6vWwAA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~24~~ 23 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Port of [Nick's Jelly solution](https://codegolf.stackexchange.com/a/190981/58974)
```
;£EÅgYn" #T BA0 "cXc
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O6NFxWdZbiIgIx1UIEJBBzAGICJjWGM&input=Impwb28qcGpvb29vcCpvam9vcG9vKm9qb29vb29wcGpvaXZ2dm8vaTxpdml2aTx2dnZ2dnZ2dnZ2dnZ2b2ppIg)
```
;£EÅgYn"..."cXc :Implicit input of string
£ :Map each character X at 0-based index Y
; E :ASCII
Å :Slice of the first character (space)
g :Get character at index
Y : Increment Y
n : Subtract from
"..." : Literal string (Codepoints: 32,35,29,84,32,66,65,7,48,6,32)
c : Codepoint at index
Xc : Codepoint of X
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 50 bytes
```
T`*j\p\ovi</`'(>DQbcu
.
$.`$* $&¶
+T`!p`~_p` .¶
¶
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyRBKyumICa/LNNGP0Fdw84lMCm5lEuPS0UvQUVLQUXt0DYu7ZAExYKEuviCBAU9IBeI/v/PKsjP1yrIygeCAq18IA3i54P5@QVA8cyysrJ8/UybzDIgtClDBvlZmVxZQKBlAyHLwDwsAKIAu0wZAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`*j\p\ovi</`'(>DQbcu
```
Make the transliteration as described in the question. `p` (described below) and `o` have special meaning to `T`ransliterate so they need to be quoted.
```
.
$.`$* $&¶
```
List each character on its own line, preceded by a number of spaces according to its index i.e. what the program counter would be.
```
+T`!p`~_p` .¶
```
Repeatedly cyclically decrement the last character on each line, deleting the preceding space each time, until all of the spaces have been deleted. The `p` stands for printable ASCII i.e. `-~`, however we want the `!` to map to `~` so that is transliterated first, and then the `_` causes the space in the match `.¶` to be deleted, while the remaining characters get transliterated one character code at a time.
```
¶
```
Join all of the characters back together.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
⭆S§Φγμ⁻℅§ #{T BAe0d ℅ικ
```
[Try it online!](https://tio.run/##TYvBCsIwEER/JdTLplT0bi/1IPRQFPQHQhPqxpgNMQ2CHx9XpeAs7PBmZ8eriiMpV8opok9wTmzToAL0PszphyAb0aXea/OEA7pkIkyNuHM6oJ8fcIwavXKwdCqxel3EvjNbLapGLGeUkl9uvOWuFBuI6mCJFWpi/zB9mQLnmHOmDbaYedr8L7JY1tm9AQ "Charcoal – Try It Online") Link is to verbose version of code. Port of @Arnauld's JavaScript answer. Explanation:
```
S Input string
⭆ Map over characters and join
ι Current character
℅ ASCII code
§ Cyclically indexed into
#{T BAe0d Literal string ` #{T BAe0d `
℅ ASCII code
⁻ Subtract
κ Current index
§ Cyclically indexed into
γ Printable ASCII
Φ Filtered on
μ Inner index (i.e. skip initial space)
Implicitly print
```
[Answer]
# [Haskell](https://www.haskell.org/), 135 bytes
```
t=h"*jpovi</"(fromEnum<$>"'(>DQbcu")
h(x:m)(y:n)i|i==x=y|1<2=h m n i
a n|n<33=a(n+94)|1<2=n
f=(toEnum.a<$>).(zipWith(+)[0,-1..]).(t<$>)
```
[Try it online!](https://tio.run/##dcyxDoIwFIXhnadoGhNb0CriImmZ9AGcHIxDJZBepBeCxYDh3RGc9YznS36jn4@sLMfRKUP9oq5eIDeU5U1lT9hauUjokiXH8z1tKfcM62LLWR8jhwGU6lQ/hHKnDLEECXia4IAyipRmGBz2/Ivo5Yq5as4JPQW5YG@oL@AMC/h1u1qHQtym0802Wg2oAF3W6NSRfCx@z5fFX3l9AA "Haskell – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 59 bytes
```
s=>s.Select((c,i)=>(char)(33+(" #{T BAe0d"[c%11]+94-i)%94))
```
[Try it online!](https://tio.run/##hY5BC8IwDIXv/opRGbSbm4pexG6goiB4U/AgHmbtNEObss5e/PGzuoug6BdIeC8hPGEiYaBe3JTgy7m6XWWZHS6Si3NWpp0PJ82T2iSpidfyIkVFqegAS1L6XDI6GISUeO37xptOZO9IdsLv9/fhaBgB80dDxupxa1tCJVegJDVVCeoUz1CJrKI5JYUj4E23hDH2@1ojBrpAhw7QzafGl0btfLDWYhc4WFfcvoMF/H//nSbf902TuX4A "C# (Visual C# Interactive Compiler) – Try It Online")
Port of @Arnaulds JavaScript answer. One if the rare instances where C# is shorter!
-3 bytes thanks to @ceilingcat!
] |
[Question]
[
# Challenge
Given an integer in 32-bit [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) format, return the index of the *second* least-significant zero digit in the binary representation, where an index of `0` represents the least significant bit, and an index of `31` represents the most significant bit.
If there is no second zero, you may return 0, any negative number, any falsy value, or report an error in a way that makes sense in your language.
You may use 1-indexing if you prefer, but the test cases below will use 0-indexing.
You may use unsigned integers if you prefer; if you do, then you must handle integers in the range `[0, 2^32)`. If you use signed integers, you must handle integers in the range `[-2^31, 2^31)`. The test cases here will use signed integers, but note that `-x` (signed) is `2^32 - x` (unsigned).
# Test Cases
```
0 (0b00) -> 1
1 (0b001) -> 2
10 (0b1010) -> 2
11 (0b01011) -> 4
12 (0b1100) -> 1
23 (0b010111) -> 5
-1 (0b11..11) -> None
-2 (0b11..10) -> None
-4 (0b11..00) -> 1
-5 (0b11..1011) -> None
-9 (0b11..10111) -> None
2^31-2 (0b0111..1110) -> 31
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins!
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
```
lambda n:[i for i in range(32)if n|1<<i>n][1]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjpTIS2/SCFTITNPoSgxLz1Vw9hIMzNNIa/G0MYm0y4vNtow9j@aCiNTTSsuzoKizLwShUwdhTSNTM3/AA "Python 2 – Try It Online")
Uses 0-indexing, unsigned numbers, and throws an error on no second zero.
Simply creates a list of indices of non-set bits, from lowest to highest, and returns the second entry.
[Answer]
## JavaScript (ES6), 34 bytes
Returns a 0-based index, or `-1` if no second zero is found.
```
n=>31-Math.clz32((n=~n^~n&-~n)&-n)
```
### Test cases
```
let f =
n=>31-Math.clz32((n=~n^~n&-~n)&-n)
console.log(f(0)) // -> 1
console.log(f(1)) // -> 2
console.log(f(10)) // -> 2
console.log(f(11)) // -> 4
console.log(f(12)) // -> 1
console.log(f(23)) // -> 5
console.log(f(-1)) // -> None
console.log(f(-2)) // -> None
console.log(f(-4)) // -> 1
console.log(f(-5)) // -> None
console.log(f(-9)) // -> None
console.log(f(2**31-2)) // -> 31
```
### Alternate expression
```
n=>31-Math.clz32((n=~n^++n&-n)&-n)
```
---
## Recursive version, 42 bytes
Returns a 0-based index, or `false` if no second zero is found.
```
f=(n,p=k=0)=>n&1||!k++?p<32&&f(n>>1,p+1):p
```
### How?
```
f=(n,p=k=0)=> // given n, p, k
n&1|| // if the least significant bit of n is set
!k++? // or this is the 1st zero (k was not set):
p<31&& // return false if p is >= 31
f(n>>1,p+1) // or do a recursive call with n>>1 / p+1
:p // else: return p
```
### Test cases
```
f=(n,p=k=0)=>n&1||!k++?p<32&&f(n>>1,p+1):p
console.log(f(0)) // -> 1
console.log(f(1)) // -> 2
console.log(f(10)) // -> 2
console.log(f(11)) // -> 4
console.log(f(12)) // -> 1
console.log(f(23)) // -> 5
console.log(f(-1)) // -> None
console.log(f(-2)) // -> None
console.log(f(-4)) // -> 1
console.log(f(-5)) // -> None
console.log(f(-9)) // -> None
console.log(f(2**31-2)) // -> 31
```
### Alternate version suggested by Neil, 41 bytes
Returns a 0-based index, or throws a *too much recursion* error if no second zero is found.
```
f=(n,c=1)=>n%2?1+f(~-n/2,c):c&&1+f(n/2,0)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
|‘‘&~l2
```
[Try it online!](https://tio.run/##y0rNyan8/7/mUcMMIFKryzH6//@/kTEA "Jelly – Try It Online")
It outputs something not in the range [1,31] if there isn't the second zero. This includes `32` `33` and `(-inf+nanj)`. I guess that makes some sense.
It calculates `log(((x|(x+1))+1)&~x)/log(2)`.
[Answer]
# IA-32 machine code, ~~14~~ 13 bytes
Hexdump:
```
F7 D1 0F BC C1 0F B3 C1 0F BC C9 91 C3
```
Disassembly listing:
```
0: f7 d1 not ecx
2: 0f bc c1 bsf eax,ecx
5: 0f b3 c1 btr ecx,eax
8: 0f bc c1 bsf ecx,ecx
b: 91 xchg eax, ecx
c: c3 ret
```
Receives input in `ecx`; output is in `al`. Returns 0 on error.
First of all, it inverts the input, so it can use the bit scan instructions to look for set bits. It looks for the least significant set bit, resets it, looks for least significant set bit again, and returns the result.
If the bit-scan instruction doesn't find any set bit, the Intel documentation says the output is undefined. However, in practice all processors leave the destination register unchanged in this case (as noted by Cody Gray, AMD documentation describes this behavior as mandatory).
So, there are the following cases:
1. No zero bits (binary 111...1): ecx is set to 0 by `not` and remains 0
2. One zero bit: ecx is set to 0 by `btr` and remains 0 after `bsf`
3. Two zero bits: ecx is set to the proper value by `bsf`
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~44~~ 38 bytes
```
i->i.numberOfTrailingZeros(~i&-i-2)&31
```
[Try it online!](https://tio.run/##RY4xT8MwEIXn5ld4qhLJtkgKAwEiMYDEgDqkE4jhmjjhgmNbtlOpQu1fDweNxBtO7066974BDiCsU2Zov2Y37TU2rNEQAnsFNOw7YaQQIdK9QwOaDfQhp4hadpNpIlojd/bFxOdluyeveuUrZtjDjKJCaaZxr/y223lAjaZ/U96G9IxrgaLI1pt8vvvrWfqXuoPFlo1EkdbR09f7BwPfh2yB@tU/S4hewSipu74426VXPOc5DZoFLzZc5FwUXFxzccPFLT8XVVXlWbJayRFcasoSnNPHx0Ahmeysf4Lmc@tb5VWb1scQFaVOsSwd0URtsgv0KTnNPw "Java (OpenJDK 8) – Try It Online")
Returns 0 if no second zero bit exists.
[Answer]
# Java, ... ~~194 191~~ 186 Bytes
```
static int f(int n){char[] c=Integer.toBinaryString(n).toCharArray();int j=0,o=2^32-2,i=c.length,l=i-1;if(n<0|n>o)return 0;for(;j<2&i>0;j+=c[--i]==48?1:0);if(j==2)return l-i;return 0;}
```
*-159 Bytes for using smaller variable names and removing whitespace*
*-25 Bytes, after taking even shorter variables and thanks to @KevinCruijssen tips*
*-18 Bytes, more whitespaces, function name*
*-3 Bytes, thanks to @KevinCruijssen, shortening if condition*
*-5 Bytes, Thanks to @Arnold Palmer, @KevinCruijssen, shortening loop*
## Ungolfed
```
public static int getPosSecondZero2(int number){
int overflow = 2^32-2;
if(number < 0 || number > overflow){
return 0;
}
String binaryString = Integer.toBinaryString(number);
char[] binaryCharArray = binaryString.toCharArray();
int count = 0;
int idx = binaryCharArray.length;
int length = binaryCharArray.length -1;
while(count < 2 && idx>0){
idx--;
if(binaryCharArray[idx] == '0'){
count++;
}
}
if(count == 2)
return length-idx;
return 0;
}
```
[Answer]
# Dyalog APL, 20 bytes
```
{2⊃(⍳32)/⍨~⌽⍵⊤⍨32⍴2}
```
Uses 1-indexing, throws `INDEX ERROR` in case of no second zero.
**How?**
`⍵⊤⍨` - encode `⍵` as a
`32⍴2` - binary string of length 32
`⌽` - reverse
`~` - negate (0→1, 1→0)
`(⍳32)/⍨` - compress with the range 1-32 (leaving indexes of zeros)
`2⊃` - pick the second element
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
B¬Ṛ;1,1ḣ32TḊḢ
```
[Try it online!](https://tio.run/##ASIA3f9qZWxsef//QsKs4bmaOzEsMeG4ozMyVOG4iuG4ov///zEx "Jelly – Try It Online")
Uses 1-indexing, gets unsigned integer as input. Returns `0` for not found.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
,4BUFḣ32¬TḊḢ
```
A monadic link, taking an integer, using the unsigned option and returning the 1-indexed result (returns 0 when none exists).
**[Try it online!](https://tio.run/##AR8A4P9qZWxsef//LDRCVUbhuKMzMsKsVOG4iuG4ov///zEx "Jelly – Try It Online")**
or
```
32Ḷ2*|€n⁸TḊḢ
```
**[Try that](https://tio.run/##ASIA3f9qZWxsef//MzLhuLYyKnzigqxu4oG4VOG4iuG4ov///zEx "Jelly – Try It Online")**
### How?
1.
```
,4BUFḣ32¬TḊḢ - Link: number, n e.g. 14
,4 - pair with 4 [14,4]
B - to binary [[1,1,1,0],[1,0,0]]
U - upend [[0,1,1,1],[0,0,1]]
F - flatten [0,1,1,1,0,0,1]
ḣ32 - head to 32 [0,1,1,1,0,0,1] (truncates the right if need be)
¬ - not (vectorises) [1,0,0,0,1,1,0]
T - truthy indexes [1,5,6]
Ḋ - dequeue [5,6]
Ḣ - head 5
- if the dequeued list is empty the head yields 0
```
2.
```
32Ḷ2*|€n⁸TḊḢ - Link: number, n e.g. 14
32Ḷ - lowered range of 32 [ 0, 1, 2, 3, 4, 5, ...,31]
2* - 2 exponentiated [ 1, 2, 4, 8,16,32, ...,2147483648]
|€ - bitwise or for €ach [15,14,14,14,30,46, ...,2147483662]
⁸ - chain's right argument 14
n - not equal? [ 1, 0, 0, 0, 1, 1, ..., 1]
T - truthy indexes [ 1, 5, 6, ..., 32]
Ḋ - dequeue [ 5, 6, ..., 32]
Ḣ - head 5
- if the dequeued list is empty the head yields 0
```
[Answer]
# x86\_64 machine code, ~~34~~ 32 bytes
Not sure if this is the right approach, quite a lot of bytes (turns out it is [not](https://codegolf.stackexchange.com/a/132979/48198)):
```
31 c0 83 c9 ff 89 fa 83 e2 01 83 f2 01 01 d1 7f 09 ff c0 d1 ef eb ee 83 c8 ff 83 f8 1f 7f f8 c3
```
[Try it online!](https://tio.run/##NVFhb4IwEP3Or7iwmLR6LBQ007HtjwyzYFu0iSum1IXN@NvZFSrh@l7veK8PkNlRynF8Mlaer0rDW@@V6Z5PH0kiO9t7kKfGweHXa9kp/bmHd0jroRT1IPN62JaEu3poW@IBm7mni3rIxczbyEMpqhd6No@a4BF6mrg@UOnouY2eQU9ctLMucFmmVZIY6@G7MZYF0rijxCnpchk2PxxuSQIQZhZd9eBe976f3gHgBjkKFLTQWmBRYiYwKzBbY7bBbIc5nThdGu5VNHC6v56jxQ0Ekg7XZLOZxGQUsQx3kJGu7RxMKQ2J8orgDURBuFrFmACWRnM4s6@mjqMOCzK25Izzxw/gzPJq1lwcTVuW9jSw6utPu44tFCfdQtWe6eGipdfqlba8tinSh8BHfrPn4Zh7cHLaX52lZMl9HP8B "C (gcc) – Try It Online")
```
second_zero:
# Set eax = 0
xor %eax, %eax
# Set ecx = -1
xor %ecx,%ecx
not %ecx
# Loop over all bits
Loop:
# Get current bit
mov %edi, %edx
and $0x1, %edx
# Check if it's zero and possibly increment ecx
xor $0x1, %edx
add %edx, %ecx
# If ecx > 0: we found the position & return
jg Return
# Increment the position
inc %eax
# Shift the input and loop
shr %edi
jmp Loop
Fix:
# If there's not two 0, set value to -1
xor %eax,%eax
not %eax
Return:
# Nasty fix: if position > 31 (e.g for -1 == 0b11..11)
cmp $31, %eax
jg Fix
ret
```
Thanks @CodyGray for `-2` bytes.
[Answer]
# [R](https://www.r-project.org/), 66 bytes
```
w=which.min
x=strtoi(intToBits(scan()));w(x[-w(x)])*any(!x[-w(x)])
```
reads from stdin; returns `0` for no second zero and the place otherwise.
[Try it online!](https://tio.run/##K/r/v9y2PCMzOUMvNzOPq8K2uKSoJD9TIzOvJCTfKbOkWKM4OTFPQ1NT07pcoyJaF0hoxmpqJeZVaijCuf91Lf8DAA "R – Try It Online")
[Answer]
# [8th](http://8th-dev.com/), 149 bytes
```
2 base swap >s nip decimal s:len 32 swap n:- ( "0" s:<+ ) swap times s:rev null s:/ a:new swap ( "0" s:= if a:push else drop then ) a:each swap 1 a:@
```
**Commented code**
```
: f \ n -- a1 a2 n
\ decimal to binary conversion
2 base swap >s nip decimal
\ 32bit formatting (padding with 0)
s:len 32 swap n:- ( "0" s:<+ ) swap times
\ put reversed binary number into an array
s:rev null s:/
\ build a new array with position of each zero
a:new swap ( "0" s:= if a:push else drop then ) a:each
\ put on TOS the position of the 2nd least least-significant zero digit
swap 1 a:@
;
```
**Usage and output**
```
ok> : f 2 base swap >s nip decimal s:len 32 swap n:- ( "0" s:<+ ) swap times s:rev null s:/ a:new swap ( "0" s:= if a:push else drop then ) a:each swap 1 a:@ ;
ok> [0, 1, 10, 11, 12, 23, -1, -2, -4, -5, -9, 2147483646]
ok> ( dup . " -> " . f . 2drop cr ) a:each
0 -> 1
1 -> 2
10 -> 2
11 -> 4
12 -> 1
23 -> 5
-1 -> null
-2 -> null
-4 -> 1
-5 -> null
-9 -> null
2147483646 -> 31
```
[Answer]
# MMIX, 20 bytes (5 instrs)
xxd --jelly
```
00000000: 23ff0001 c00000ff 23ff0001 da00ff00 #”¡¢Ċ¡¡”#”¡¢ḷ¡”¡
00000010: fe010000 “¢¡¡
```
Disassembly
```
sndz ADDU $255,$0,1
OR $0,$0,$255 // x |= x + 1
ADDU $255,$0,1
SADD $0,$255,$0 // x = popcnt((x + 1) & ~x)
POP 1,0
```
The algorithm is essentially the obvious "remove rightmost 0; figure out position of rightmost 0". The neat trick here is that I managed to do it without flipping all the bits first.
] |
[Question]
[
[RPS 25](https://www.umop.com/rps25.htm) is a version of Rock Paper Scissors which has 25 hand symbols instead of just 3. Each symbol defeats 12 symbols, and is defeated by 12 others.
[Here's a link to a chart showing which symbols defeat which.](https://www.umop.com/images/rps25_outcomes.jpg)
The challenge here is simple: your program should take in two strings representing the symbols thrown by each of the players, and output which player wins. You can do this in multiple ways:
* Outputting one of three distinct symbols, one indicating the first input wins and one indicating the second input wins, and one if there's a tie
* Outputting one of 25 distinct symbols indicating which hand symbol wins, outputting either one if there's a tie (since there only is a tie if both players play the same symbol)
The strings can be all lowercase, ALL UPPERCASE, or Title Case.
The following describes all of the possible outcomes; each symbol is followed by a colon, then a list of all of the symbols which it defeats.
```
GUN: ROCK SUN FIRE SCISSORS AXE SNAKE MONKEY WOMAN MAN TREE COCKROACH WOLF
DRAGON: DEVIL LIGHTNING NUKE DYNAMITE GUN ROCK SUN FIRE SCISSORS AXE SNAKE MONKEY
MOON: AIR BOWL WATER ALIEN DRAGON DEVIL LIGHTNING NUKE DYNAMITE GUN ROCK SUN
TREE: COCKROACH WOLF SPONGE PAPER MOON AIR BOWL WATER ALIEN DRAGON DEVIL LIGHTNING
AXE: SNAKE MONKEY WOMAN MAN TREE COCKROACH WOLF SPONGE PAPER MOON AIR BOWL
DYNAMITE: GUN ROCK SUN FIRE SCISSORS AXE SNAKE MONKEY WOMAN MAN TREE COCKROACH
ALIEN: DRAGON DEVIL LIGHTNING NUKE DYNAMITE GUN ROCK SUN FIRE SCISSORS AXE SNAKE
PAPER: MOON AIR BOWL WATER ALIEN DRAGON DEVIL LIGHTNING NUKE DYNAMITE GUN ROCK
MAN: TREE COCKROACH WOLF SPONGE PAPER MOON AIR BOWL WATER ALIEN DRAGON DEVIL
SCISSORS: AXE SNAKE MONKEY WOMAN MAN TREE COCKROACH WOLF SPONGE PAPER MOON AIR
NUKE: DYNAMITE GUN ROCK SUN FIRE SCISSORS SNAKE AXE MONKEY WOMAN MAN TREE
WATER: ALIEN DRAGON DEVIL LIGHTNING NUKE DYNAMITE GUN ROCK SUN FIRE SCISSORS AXE
SPONGE: PAPER MOON AIR BOWL WATER ALIEN DRAGON DEVIL LIGHTNING NUKE DYNAMITE GUN
WOMAN: MAN TREE COCKROACH WOLF SPONGE PAPER MOON AIR BOWL WATER ALIEN DRAGON
LIGHTNING: NUKE DYNAMITE GUN ROCK SUN FIRE SCISSORS AXE SNAKE MONKEY WOMAN MAN
BOWL: WATER ALIEN DRAGON DEVIL LIGHTNING NUKE DYNAMITE GUN ROCK SUN FIRE SCISSORS
WOLF: SPONGE PAPER MOON AIR BOWL WATER ALIEN DRAGON DEVIL LIGHTNING NUKE DYNAMITE
MONKEY: WOMAN MAN TREE COCKROACH WOLF SPONGE PAPER MOON AIR BOWL WATER ALIEN
SUN: FIRE SCISSORS AXE SNAKE MONKEY WOMAN MAN TREE COCKROACH WOLF SPONGE PAPER
DEVIL: LIGHTNING NUKE DYNAMITE GUN ROCK SUN FIRE SCISSORS AXE SNAKE MONKEY WOMAN
AIR: BOWL WATER ALIEN DRAGON DEVIL LIGHTNING NUKE DYNAMITE GUN ROCK SUN FIRE
COCKROACH: WOLF SPONGE PAPER MOON AIR BOWL WATER ALIEN DRAGON DEVIL LIGHTNING NUKE
SNAKE: MONKEY WOMAN MAN TREE COCKROACH WOLF SPONGE PAPER MOON AIR BOWL WATER
ROCK: SUN FIRE SCISSORS AXE SNAKE MONKEY WOMAN MAN TREE COCKROACH WOLF SPONGE
FIRE: SCISSORS AXE SNAKE MONKEY WOMAN MAN TREE COCKROACH WOLF SPONGE PAPER MOON
```
## Test cases
| Player 1 | Player 2 | Winner | Player Winning |
| --- | --- | --- | --- |
| Gun | Rock | Gun | 1 |
| Rock | Gun | Gun | 2 |
| Dynamite | Gun | Dynamite | 1 |
| Gun | Dynamite | Dynamite | 2 |
| Nuke | Scissors | Nuke | 1 |
| Paper | Sponge | Sponge | 2 |
| Moon | Paper | Paper | 2 |
| Man | Tree | Man | 1 |
| Gun | Gun | Gun | Neither |
Standard loopholes are forbidden. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins.
[Answer]
# [Python](https://docs.python.org), ~~116~~ 94 bytes
```
lambda a,b:[b,a][(h(b)-h(a))%25%2]
h=lambda s:b"SBOMAK1;R?0=T3%".find(int(s*3,35)%86)
```
(contains nine unprintable characters).
**[Try it online!](https://tio.run/##TZDdT4MwFMXfeTHxxY9EbZYQ6GTLNpwxGGI6ZIwA7VKYc0EeShbCjMKykRj/eoR26vpyzm1/Pbe32@8qLwu9zsy3@oN9pmsGmJYacaqxJFZzNYW9XGUQyqOxPEqk3DxAeyPtnIeTi1MS3CBveP1InwZnZnSiX8mXnX62KdbqpqjUfVfX9DGUH@5hXeW78msPTBArzgIrGlCeVxgFbmS3Hi88rr7rzCLsYocD9ovrc0ORQ/gd5Ls2N0sU2bQ1E7LkDHJ5GRABztFcnIdzgh2evST@tFWLWB4lyJq1RURtfhggEUsOJiDYs1c8ACPxNvTKJbTcMCQ0bP3UpWJPTESbZCWRpO2unV4BSncMbkGj/fdyU6hVbOgJyModqMCmAOJHIPzFe0p3OLiDktQS7J8wJNAsATEe0WQaTexRdKYyDaTwr0F63KD@AQ "Python 3 – Try It Online")**
---
### Previous
```
lambda a,b:[a,b][(h(b)-h(a))%50<26]
h=lambda s:' DMNNLTDLDOANWRBBAIMMPRSGWWCRTTMAWNMESEAXSSFFSURR'.find((s*2)[:5:4])
```
An unnamed function that accepts the two throws as uppercase strings and returns the winning throw as a string.
**[Try it online!](https://tio.run/##TZBPb4MgGMbvfgouC9K1Tdc/O5j1QBUtqYABO9s4D5rG6LJp05os@/ROsdvKged54cfzAufvpqirRZuv39qP9DM7pSAdZ1bcTUlsFmaGJoWZIvSwmr3MnxOjWN@oqwWBwzj3Q8d3BOaR3GwwZSyQyosiW4YhwxFnRBF8UMp11V5KOM3L6mSa19EcxdbKWiaobYpL/XUFaxBDb8/hGEDnyDGjIek93@@0@tTbhpxyTwPklfraSOwJfQb7lGgT4ZDI3mxEpBlMdcnEAAY4GPZVILinsyPhu73awt5Jge1tX4SS6E2Gh1hxM0zwHTnqAI6Hu@GDFmVTpYRUvXepHNaGF8kuGSaGcb6UVWNCAEcr8Ag6nb7XZWU2sbVIQF5fQAPKCgw/gtAvPoGjp9kSGUZPpP@EZYBuDFCqI7pMq4u9i87NdAwy9Ncgu2/Q/gA "Python 3 – Try It Online")**
##### How?
The throws each beat the twelve throws before them in the circular list `GUN DYNAMITE NUKE LIGHTNING DEVIL DRAGON ALIEN WATER BOWL AIR MOON PAPER SPONGE WOLF COCKROACH TREE MAN WOMAN MONKEY SNAKE AXE SCISSORS FIRE SUN ROCK`.
If we take the first and fifth characters of each of the throws, repeating characters if necessary (e.g. the fifth character of 'GUN' is 'U') we get distinct results: `GU DM NN LT DL DO AN WR BB AI MM PR SG WW CR TT MA WN ME SE AX SS FF SU RR` and none of these appear more than once in a concatenated version, `GUDMNNLTDLDOANWRBBAIMMPRSGWWCRTTMAWNMESEAXSSFFSURR`.
The first and "fifth" characters are extracted with `(s*2)[:5:4]` - that is the throw, `s`, repeated twice and then sliced starting with (implicit) index `0`, stepping by `4` up to, but not including index `5`.
The helper function, `h`, `find`s the first index at which those characters appear in the concatenated string to identify the location in the circular list. The `GU` may be replaced with a space as `find` returns `-1` if the input is not found (thus all indices are reduced by two).
The unnamed function calls the helper for each throw, takes the difference, modulos by fifty to deal with the circular nature of the ordering and checks if the second throw won or tied by seeing if that was less than twenty-six.
[Answer]
# JavaScript, 158 bytes
```
(a,b,v='ngeperoonAirowlteriengonvilingukeiteGunockSunireorsAxeakekeymanManreeacholf',m=v.indexOf(a.slice(-3)),n=v.indexOf(b.slice(-3)))=>n-m+(n>m?0:75)>36?b:a
```
Try it:
```
f=(a,b,v='ngeperoonAirowlteriengonvilingukeiteGunockSunireorsAxeakekeymanManreeacholf',m=v.indexOf(a.slice(-3)),n=v.indexOf(b.slice(-3)))=>n-m+(n>m?0:75)>36?b:a
;arr='Sponge Paper Moon Air Bowl Water Alien Dragon Devil Lightning Nuke Dynamite Gun Rock Sun Fire Scissors Axe Snake Monkey Woman Man Tree Cockroach Wolf'.split` `;
for(i=0;i<25;++i)
for(j=0;j<25;++j)
document.write(`<p>${arr[i]} vs ${arr[j]} - winner is ${f(arr[i], arr[j])}</p>`)
```
## Explanation
Imagine that we have a round table and all sorts of options are sitting at the table. I have ordered these options so that to the right of each option 12 options are all those options that can be defeated by this option, and to the left 12 options are all those options that can defeat this option:
`Sponge Paper Moon Air Bowl Water Alien Dragon Devil Lightning Nuke Dynamite Gun Rock Sun Fire Scissors Axe Snake Monkey Woman Man Tree Cockroach Wolf`
And all I need is to check if the second option is to the right of the first option. If yes, then the first one wins; if not, then the second one wins
## UPD 252 -> 227
Thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for the [tip](https://codegolf.stackexchange.com/questions/259618/play-rock-paper-scissors-25/259636?noredirect=1#comment572121_259636) to reduce bytes count
## UPD 227 -> 195
Based on [Neil](https://codegolf.stackexchange.com/users/17602/neil)'s [tip](https://codegolf.stackexchange.com/questions/259618/play-rock-paper-scissors-25/259636?noredirect=1#comment572126_259637)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~69~~ 67 bytes
```
⊕÷⊖﹪↨E²⌕”$⌊↘sM²o⌕J⊘bA″⌕‴‹⪫IïΣ↓|‖P¦?S↷Tσ⊞ωºBh✂νDδWcD\`9;1”…S³±¹¦⁷⁵¦³⁶
```
[Try it online!](https://tio.run/##RY7BasMwEETv/QqTkwzuoQltzxvJCaLWrpHiuj0Ke0kMjm1cJdCvV5VTL49hBmamu/i1m/0YY70OUxB66la@8hS4Tzqo4T70LBT/u2bub@Ms9v6HhfGL2BbZYZh6sTk2aEm6Bg/aOqnhq3QIhrAlYwBPtpQkW6pcTTXUhgi03VPbwgkqrSyo8rPSR2w@1Dduikz@diPLy7ykG8stuJDunUVeZLs8T0Q@@8Di5aHfXx/cvaUgxlSjq6e0CRif7@Mf "Charcoal – Try It Online") Link is to verbose version of code. Takes input in upper case and outputs `-` if the first input wins and `--` if the second input does, nothing for a tie. Explanation:
```
² Literal integer `2`
E Map over implicit range
”...” Compressed lookup table
⌕ Find index of
S Next input
… Truncated to length
³ Literal integer `3`
↨ ±¹ Take the difference (literally base `-1`)
﹪ Modulo
⁷⁵ Literal integer `75`
⊖ Decremented
÷ Integer divided by
³⁶ Literal integer `36`
⊕ Incremented
Implicitly output that many `-`s
```
The compressed string contains the first three letters of each word. The two inputs are then located within that string, and the second index is considered as a cyclic offset from the first index. If this is zero, then the result is a tie; if it is `3` to `36`, then the first input wins, otherwise the second input wins. Alternatively, the second input does not lose if it is above `36` and the first input does not lose if it is `36` or below.
Alternatively the two indexes could be considered to be a signed cyclic offset of between `-36` and `36` corresponding to an offset of between `-12` and `12` in the original list of symbols, in which case the sign of the offset would indicate which symbol is the winner.
Another approach I tried was to make the offset even or odd depending on which symbol wins. This is easier to show with Rock-Paper-Scissors-Lizard-Spock. By placing the symbols in the order Spock-Lizard-Rock-Paper-Scissors, each symbol beats those symbols an even number of places after it, e.g. Rock beats Scissors and Lizard. However this is slightly less golfy to implement in Charcoal. (Note that the symbols can also be placed in the order Spock-Rock-Scissors-Lizard-Paper whereby each symbol beats the two to its right and loses to the two to its left.)
[Answer]
# [Python](https://www.python.org), ~~234 230 134~~ 127 bytes
```
lambda a,b,v='SpoRocPapSunMooFirAirSciBowAxeWatSnaAliMonDraWomDevManLigTreNukCocDynWolGun'.find:(a,b)[(v(b[:3])-v(a[:3]))%75%2]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY9NTgJBEIX3nOJJQphJgIXGaCZhgRLdiDFiwgJZNEPP0ExTPen5UUKMB3FDYvROnsBr-BDjqutVVfqr7-0z35RLJ7v3pP_4UZVJ9_zr1ar1fKGgOvNO3W-Pc3fv4juVjysZOXdl_MD4cWwu3NPgWU9UORY1sGbkZOjVxK2Huh4puTHpg9e3VXbp4uFGJs5eV9LuJUYWUcCfw2lQB_NpdDILu3WgfouwdXbaOp79nfFt0ceeLqkG8dqDeAHpINuCaPaI1gKiU87INhZkL0sxkoJ8DeLV2pQavABUyUAT0EODGkXhfAGagB7cpkemN6CIElAE1NCgReadipcc2KTdK3JryiBsJM7DwAhs1AD2afWfgNwbKYOkuTVH_gV1ge2KRYRtEpgOViFDMzzo7naH9wc)
*-96 thanks to* [@Neil](https://codegolf.stackexchange.com/users/17602/neil)*!*
[Answer]
# JavaScript (ES6), 94 bytes
Expects `[x,y]`, using title case.
```
a=>a[a.map(s=>p="DWgMlktAwSironeRpufyCNTL".indexOf(s[parseInt(s,36)*75%687%4])-p,p=25),p%25%2]
```
[Try it online!](https://tio.run/##tZbdbtowFMfveQqrEkqyQbSx0U5DoWKlrSaVMrWVuEBceMGhKcGOktAmmvoGk3azy@099jx9gT0C87GdD4YoGwQugg3O@f/OOT4@vsP3OLQD14/qlI3JwrEW2GrjITZn2NdDq@1bB93BpOdNo87DtRswSq78uZOcXN5cHJguHZO47@jh0MdBSD7SSA9rbw6NF0fN6uG7o@rbkVH3a77VaBo1v9poVhujhc1oGKE@stCXCkLnc4rE5z0aIu2K2VOtpl3PKX@euQGBie2GIQtCPuzE4geKp/DdY3RKEj4YsBmGF3rieRMQ@PeEmwoYtm/FAs/R0KjG9boBnjCa6nXJvevxBRfu5DaiLp3w8eVcWO8mFM/cCIbnAmcbNqnZY4zmPnbcgC/4wB5AeIAjAtOO5xKwK/FgsB2ZFIQQ5IIrkeBLfUYnYOAT9oU@IALGlmxSloegkMst0/RPcCqXKhBSb/ssbURT7kEcMvd2zdQmOqkpQpBp7pilDVxqs@JiQe6UpY1wUjENgCqPXWr8eSwpBzHIHfzfFKVgEvM5PKkmIpDXfkllvm7zqICKGKSaJZX4Oi7lJvif79PdK3wtm9TLuIRemUf2ci6lGhDlW6bsM3sVLY2p5xSO05KP7FW0tFlBGDJfyzuz/6ZTe3Wp/5fc8le4VN@AYGSa@@r9KaRqHm5Q8HNP3V@xScUsGiqRe2n8CkvlEgJQaFbl9/2UTeqB54UC2celMaOSimC9oLivbapcR6PKY6tSkRfmDr8w9z/fETsyue1Q7xsm1450o1XpmA4LTrlBPUZWG@XTBKZwy5YmSOzz18kYLA2TEb@92958TEI9NtAxirlTSStbHJCQr3P0YVxDychI/2AeMT020WPTx@NTOtZfvzLQS5QsT7V6G2n8G4zwmRjrwqJl5RjHSPv969vTj@/8qXF17ennV83gUo@GsfgD "JavaScript (Node.js) – Try It Online")
### Credits
* This is based on the observation [first made by Neil](https://codegolf.stackexchange.com/a/259626/58563) that the outcome is based on a circular list.
* The odd/even interleaving trick which allows the final modulo 2 was borrowed from [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/259642/58563).
### How?
We use a hash function to isolate one of the first 4 letters1 of each word. This is enough to get 25 distinct symbols (including an undefined one for 'Man'). We then look for the symbols into a lookup string to get the correct positions in the circular list.
```
s | hash(s) | s[hash(s)] | index in lookup
-----------+---------+------------+-----------------
Man | 3 | n/a | -1
Devil | 0 | 'D' | 0
Woman | 0 | 'W' | 1
Dragon | 3 | 'g' | 2
Monkey | 0 | 'M' | 3
Alien | 1 | 'l' | 4
Snake | 3 | 'k' | 5
Water | 2 | 't' | 6
Axe | 0 | 'A' | 7
Bowl | 2 | 'w' | 8
Scissors | 0 | 'S' | 9
Air | 1 | 'i' | 10
Fire | 2 | 'r' | 11
Moon | 1 | 'o' | 12
Sun | 2 | 'n' | 13
Paper | 3 | 'e' | 14
Rock | 0 | 'R' | 15
Sponge | 1 | 'p' | 16
Gun | 1 | 'u' | 17
Wolf | 3 | 'f' | 18
Dynamite | 1 | 'y' | 19
Cockroach | 0 | 'C' | 20
Nuke | 0 | 'N' | 21
Tree | 0 | 'T' | 22
Lightning | 0 | 'L' | 23
```
*1: Using only 3 letters is also possible, for instance with [this expression](https://tio.run/##JY9Na8JAEIbv/oqXQCEpNlSUQg8W4kelUK2YgofSw5JM4jabmbC7Wv316Wov887heXhnftRJucLqzj@wlNT3FaZwmL6gU9bRG/vYDTGeJLjHaIw7PE1GjyHGg0GUd8I1YXVk7MVUWFxYtdoT5lI0VlRxwObYED4tEd51ffCsucZaMRZ00iZY7XW3qhbGWrihCzKjiZGzCuJeebLIzoSZ/BrkhXZOrEOmLV61peAEMQ/9W9UFchd6o9R1Rvs4QpQM0krsMtwR3z4qhJ0YSo3UsUs7VS65jJ@TIarYhem@rvk9RLTaX@YbqnnRqnWW@/Os0FaO212Uai7p/BG4fzZJkr7/Aw).*
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 698 bytes
```
Module[{t,keys},t=<|"air"->"dvbgfjnhipt`","alien"->"gfjnhipt`qcr","axe"->"rlxkuewsomad","bowl"->"vbgfjnhipt`q","cockroach"->"ws`madvbg`jn","devil"->"jnhipt`qc`lx","dragon"->"fj`hipt`qcrl","dynamite"->"ipt`qcrlxkue","gun"->"pt`qcrlxkuew","lightning"->"nhipt`qcrlxk","man"->"uewsomadvbgf","monkey"->"xkuewsomadvb","moon"->"advbgfjnhipt","nuke"->"hipt`qrclxku","paper"->"madvbgfjnhip","rock"->"t`qcrlxkuews","scissors"->"crlxkuewsoma","snake"->"lxkuewsomadv","sponge"->"omadvbgfjnhi","sun"->"`qcrlxkuewso","tree"->"ewsomadvbgfj","water"->"bgfjnhipt`qc","wolf"->"somadvbgfjnh","woman"->"kuewsomadvbg"|>;keys=Keys@t;If[n==e||StringContainsQ[t[n],FromCharacterCode[97+FirstPosition[keys,e][[1]]-1]],n,e]]
```
Explicit Mathematica code is as follows:
```
r[n_, e_]:=
Module[{t, keys},
t = <|"air" -> "dvbgfjnhipt`", "alien" -> "gfjnhipt`qcr", "axe" -> "rlxkuewsomad", "bowl" -> "vbgfjnhipt`q", "cockroach" -> "ws`madvbg`jn", "devil" -> "jnhipt`qc`lx", "dragon" -> "fj`hipt`qcrl", "dynamite" -> "ipt`qcrlxkue", "gun" -> "pt`qcrlxkuew", "lightning" -> "nhipt`qcrlxk", "man" -> "uewsomadvbgf", "monkey" -> "xkuewsomadvb", "moon" -> "advbgfjnhipt", "nuke" -> "hipt`qrclxku", "paper" -> "madvbgfjnhip", "rock" -> "t`qcrlxkuews", "scissors" -> "crlxkuewsoma", "snake" -> "lxkuewsomadv", "sponge" -> "omadvbgfjnhi", "sun" -> "`qcrlxkuewso", "tree" -> "ewsomadvbgfj", "water" -> "bgfjnhipt`qc", "wolf" -> "somadvbgfjnh", "woman" -> "kuewsomadvbg"|>;
keys = Keys[t];
If[n == e || StringContainsQ[t[n], FromCharacterCode[97 + FirstPosition[keys, e][[1]] - 1]],
n,
e
]
]
```
[Try it online!](https://tio.run/##bZJRa@MwDIDf9ytGXi972NPY7TIOCoMxDnbcowmL6riJ28TubLfpWPfbe5K85nSwhwb6fbIkSx4h9WaEZDWcgnIv5aV5qb9Xp1@@3Q1GvadyY97iR5mqH8cCbCiu7ot2v@xWa9fbbWqKsoDBGkd8hq86ED8YomE4bHZmin6EFunSTwNhkeMVsfZ6EzzontwUGwzGiGbt0LVmb/nMnL4ZDsQDdJ4rr9bNufBA4s3BaBOXP2NqAlW34wMCTkgH2/XJWdeRm@@AGt0IfOJ8BeqbqHc4GBL/brdfssgtgZgSYrfbcDs5d9BUGvEWtoZnOop45AHHQVi0GRFHbWP0IZLSYrCkHOQKYtx74lvvOhZe1CCRJyEKeKQpGA4Wt10jniDlPsXWNHE/rAhHkZzx59TEbLrieH9Hj6l6ws/PdPe4Uq6qzPH4JwUc/cK7BNbF3yopV5cPwY@LHgJorLzwrVG3N98ebIjp2UebrHeKkpWmVuq6rq/wVzr8V5@eMVtSQfGuy8s8y7q@mDkDFOQln5/NF@4z1xwiHe8W5bwdKfOGyeZFSMdvBVWO@c8AC97GF23k7k5/AQ)
*How to store the game rule in the code with minimum number of bytes?*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 48 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•2y§Á°rÇŽGιRjºU¤ÓqtÕ·¢ŸÝ)≠A÷`d•I04SδèJkÆ50%₂@è
```
Port of [*@JonathanAllan*'s (previous) Python answer](https://codegolf.stackexchange.com/a/259642/52210).
Input as a lowercase pair; outputs the winner (or either for ties) from the input-pair.
[Try it online](https://tio.run/##AWkAlv9vc2FiaWX//y7igKIyecKnw4HCsHLDg@KAocW9R865UmrCulXCpMOTcXTDlcK3wqLFuMOdKeKJoEHDt2Bk4oCiSTA0U860w6hKa8OGNTAl4oKCQMOo//9bImd1biIsImR5bmFtaXRlIl0) or [verify all test cases](https://tio.run/##JY7BSsNAEIbvPkUJSBETKdVevFRBkHrwoHiSgts0Tdcku3WTtkYq1AqF3kSRngTTFq0X8dDaqnjZIdc8RF4k7sbLfPPPP/Mz1EUVbCQw3ovmcJdsxN1R3uevcMM/GNzG3SD83Y@@js759wmfwMOFB498wUfhEp7W4sHzLizOquLGz20dRzOYHljQL@RW415vB6bJNX/LF2AGyxLKdmAYBqUwkCLuvmiaBsPsehjwSRgII9sJAzFuudtSRvNovsnHzTL/UfmnutLyi0om7t9nlKLP3w9hqianitkkiqpUfYIc7BmiJU1LwsZm3SOYmNI1WtiWZMikch3Z2JBsI89gghXalj7CUjg03WmgRuq5DUpMmdimdk1Ap7rFKNLroveYIR0HpWH0nw4lluHLS4LSV9ClrK6OXZcyV7Q1zNJJ@joTeUo50TRCNRtd@X8).
**Explanation:**
```
.•2y§Á°rÇŽGιRjºU¤ÓqtÕ·¢ŸÝ)≠A÷`d•
# Push compressed string "a dmnnltdldoanwrbbaimmprsgwwcrttmawnmeseaxssffsurr"
I # Push the input-pair
04S # Push [0,4]
δ # Map over the input-pair:
è # Get their (modular) 0-based 0th/first and 4th/fifth characters
J # Join each inner pair of characters together
k # Get their 0-based indices in the string
Æ # Reduce it by subtracting
50% # Modulo-50
₂@ # Is larger than or equal to 26
è # Use that 0 or 1 to 0-based index into the (implicit) input-pair
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•2y§Á°rÇŽGιRjºU¤ÓqtÕ·¢ŸÝ)≠A÷`d•` is `"a dmnnltdldoanwrbbaimmprsgwwcrttmawnmeseaxssffsurr"` (`a` could be just `gu` for the same byte-count).
] |
[Question]
[
Write a program that halts producing a random finite numerical output with probability 1. The [expected value](https://en.wikipedia.org/wiki/Expected_value) of the outputs of the program must be infinite.
For [physical limits](https://codegolf.meta.stackexchange.com/questions/14407/), you can assume your language and related functions use infinite precision numbers. E.g. for languages with random function providing range \$[0,1)\$, it returns a real in \$[0,1)\$. (Anyway I need to choose from `1/rnd` and `while(rnd)print(1)`)
Inspired by [St. Petersburg paradox](https://en.wikipedia.org/wiki/St._Petersburg_paradox).
Shortest code wins. Would be quite small for lots of language though.
---
There are two easy-seen ways to do this, both are accepted given the question: (in Javascript)
```
_=>1/Math.random() // ∫₀¹1/xdx=∞
_=>{c='1';while(Math.random()<.5)c+='1';return c} // Not golfed to easier get understood for other language user, at least I try to
// 1/2+11/4+111/8+1111/16+...=∞
```
[Answer]
# [R](https://www.r-project.org/), 9 bytes
```
rf(1,1,1)
```
[Try it online!](https://tio.run/##K/r/vyhNw1AHCDX//wcA "R – Try It Online")
Outputs a realization of the \$F(1,1)\$ distribution. The [\$F(d\_1,d\_2)\$-distribution](https://en.wikipedia.org/wiki/F-distribution) has infinite mean for \$d\_2 \leq 2\$.
One way of defining the \$F(1,1)\$ distribution is as follows: let \$X\_1,X\_2\$ be independent \$\mathcal N(0,1)\$ random variables. Then \$\frac{X\_1^2}{X\_2^2}\sim F(1,1)\$.
Using the \$F\$ distribution comes out 1 byte shorter than the 2 more obvious solutions `1/runif(1)` and `rcauchy(1)`.
The plot below shows the evolution of the sample mean, for sample size ranging from 1 to 1e6; you can see that it diverges.
[](https://i.stack.imgur.com/I8o2jm.png)
---
Alternate solution for the same byte count:
```
rt(1,1)^2
```
which outputs the square of a realization of Student's distribution \$t(1)\$. It has infinite expected value, since the \$t(1)\$ distribution has infinite variance. The square is needed to guarantee that the output is positive; without it, the expected value is undefined, since the realizations are often enough arbitrarily large positive or negative numbers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
1ḤXḂ$¿
```
[Try it online!](https://tio.run/##y0rNyan8/9/w4Y4lEQ93NKkc2v//cPvDnS0qhkAWAA "Jelly – Try It Online")
-1 byte thanks to Jonathan Allan
50% chance to output 1, 50% chance to output double this value. -2 bytes using a while loop inspired by Aaron Miller's answer.
## Explanation
```
1
¿ While
..$
X Random integer from 1 to (current value)
Ḃ % 2 (this ensures 50% chance no matter how large the current value is - except if it's 1)
Ḥ Double the current value
```
Unfortunately, Jelly doesn't have a "random decimal from 0 to 1" built-in, otherwise this could be `<random><reciprocal>`.
## Proof of validity
The probability to output \$2^x\$ is \$2^{-x-1}\$ for all \$x\in\mathbb{Z}^+\$. Therefore, the expected output is \$\sum\limits\_{n=0}^\infty 2^n\cdot 2^{-n-1}=\sum\limits\_{n=0}^\infty\frac12\rightarrow\infty\$
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 5 bytes
```
?+`
1
```
[Try it online!](https://tio.run/##K0otycxLNPz/3147gQtIAQA "Retina – Try It Online") Explanation:
```
?+`
```
Loop a random number of times with an exponential distribution...
```
1
```
Double the length. (Actually you get `2ⁿ-1`, but that's still enough to diverge to infinity.)
[Answer]
# [Python 3](https://docs.python.org/3/), 37 bytes
```
from random import*
print(1/random())
```
[Try it online!](https://tio.run/##K6gsycjPM/5fnpGZk6oQUlSaaqWQWpGarKGkpPQ/rSg/V6EoMS8FSGXmFuQXlWhxFRRl5pVoGOpDhDU0Nf8DVWr@BwA "Python 3 – Try It Online")
I had a slightly cool solution but now this is just the trivial solution.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~6~~ ~~7~~ 3 bytes
*Thanks to @hyper-neutrino for helping me to understand what expected output is.*
*Thanks to @Lyxal for porting a different answer than I did for -4 bytes.*
```
∆ṘĖ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%86%E1%B9%98%C4%96&inputs=&header=&footer=)
Explanation:
```
∆Ṙ # Random float in range [0.0, 1.0)
Ė # Reciprocal
# Implicit output
```
[Answer]
# [Thue](https://esolangs.org/wiki/Thue), 29 bytes
*Edit: +9 bytes to fix issue spotted by [@RossMillikan](https://codegolf.stackexchange.com/users/12480/ross-millikan).*
```
1::=.10
10::=~1
.0::=~0
::=
1
```
[Try it online!](https://tio.run/##K8koTf3/39DKylbP0IDL0ADIqDPk0gPTBlxAksuQ6/9/AA "Thue – Try It Online") *The TIO interpreter requires a trailing newline, and outputs each digit on a different line, which is not required. [Here](https://www.npmjs.com/package/thue) is an interpreter without these restrictions.*
Outputs in binary ([meta link](https://codegolf.meta.stackexchange.com/a/5367/31957)). Each step has a 50% chance to double the binary integer, or to start outputting it. The proven formula from other answers.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~169~~ ~~119~~ 118 bytes
```
#include<bits/stdc++.h>
int main(){std::mt19937 p((uint64_t)new int);std::string s="1";while(p()%2)s+=s;std::cout<<s;}
```
[Try it online!](https://tio.run/##JYpBCsIwEADvviJUhISgUhWlTepXRLehXWjX4G7oQXx7DHobZgZi3A4AOa@RYEp98A8U3rP0YO1uvK6QRM13JG3eRbbtLHXTHC8qap1KO59uYigsqrBxv4PlhTQo7qq6csuIU9BRm83BsO34v8AziffsPjl/AQ "C++ (gcc) – Try It Online")
This solution is directly derived [from the linked paradox in the question](https://en.wikipedia.org/wiki/St._Petersburg_paradox). The output string is composed of `1` digits so technically it can be interpreted as a number.
The random number generator is seeded with the address of a heap variable. The address changes each time the program is run.
>
> Another option is to use the address of a newly allocated heap variable:
> `mt19937 rng((uint64_t) new char);` [(source)](https://codeforces.com/blog/entry/61675)
>
>
>
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 4 bytes
```
/1OZ
```
[Try it online!](https://tio.run/##K6gsyfj/X9/QP@r/fwA "Pyth – Try It Online")
```
/1 # 1 divided by
OZ # Random float between 0 and 1
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 24 bytes
```
echo 32767/$RANDOM|bc -l
```
[Try it online!](https://tio.run/##S0oszvifpqGpUP0/NTkjX8HYyNzMXF8lyNHPxd@3JilZQTfnfy0XV9p/AA "Bash – Try It Online")
Prints a random number between \$1\$ and \$\infty\$.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes
```
1W‽²↑KA
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREPJUEnTmqs8IzMnVUEjKDEvJT9Xw0hTUwEiaxVaoKMQkJqa7ZiTo6Gpaf3//3/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
1
```
Print `1`.
```
W‽²
```
Repeat a random number of times with an exponential distribution...
```
↑KA
```
... duplicate the output.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
1r/
```
[Try it online!](https://tio.run/##y00syfn/37BI//9/AA "MATL – Try It Online")
This produces the output 1/*x*, where *x* is uniformly distributed on the interval (0,1). This has [infinite mean](https://en.wikipedia.org/wiki/Inverse_distribution#Inverse_uniform_distribution).
[Answer]
# [Python 3](https://docs.python.org/3/), 31 bytes
```
from time import*
print(time())
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehJDM3VSEztyC/qESLq6AoM69EAySkoan5/z8A "Python 3 – Try It Online")
The Python 3 `random` library uses the current time for a seed. Therefore, it is necessary to specify the random distribution of time that the program is run, to ensure that the simple `1/random()` is valid. Depending on the yet-to-come specification, my answer may or may not be valid.
[Answer]
# [R](https://www.r-project.org/), 9 bytes
```
1/rexp(1)
```
[Try it online!](https://tio.run/##K/r/31C/KLWiQMNQ8/9/AA "R – Try It Online")
`rexp(1)` - a single random sample from an exponential distribution with a (default) rate parameter of 1 - is the shortest [R](https://www.r-project.org/) random function call with a nonzero probability density at zero (there are other shorter random functions [`rt` and `rf`], but unfortunately they each lack default values for required parameters, so the function calls are no shorter\*).
\*Edit: no shorter, but both can be made just-as-short: see [Robin Ryder's answer](https://codegolf.stackexchange.com/a/224844/95126)
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), ~~8~~ 7 bytes
```
2?.#*@#
```
[Try it online!](https://tio.run/##S0pNK81LT/3/38heT1nLQfn/fwA "Befunge-93 – Try It Online")
This is basically just the [St. Petersburg paradox](https://en.wikipedia.org/wiki/St._Petersburg_paradox). Every time the pointer reaches the `?` and goes either left or right, it has a 1/2 chance of doubling the top of the stack and a 1/2 chance of just outputting the top of the stack and halting.
Explanation of the code:
```
2?.#*@#
2 Push 2 onto the stack.
? Change the direction of the pointer to a random direction:
2 * If left, double the top of the stack.
. @ If right, output the top of the stack and halt.
? If up/down, the pointer returns to the ?.
```
[Answer]
# APL, 5 bytes
```
÷1-?0
```
The program generates a random number from the range [0; 1), then substracts it from 1 to get the range (0; 1], and takes the reciprocal, so we get a number from the range [1; +∞).
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 3 bytes
```
1nx
```
[Try it online!](https://tio.run/##S8sszvj/3zCv4v9/AA "><> – Try It Online")
Has an infinite expected value, due to diverging more quickly than exponentially more unlikely repunits.
Will nevertheless always terminate when it empties its own stack, when the random trampoline takes more left turns than right turns.
[Answer]
# [Random Brainfuck](https://github.com/TryItOnline/brainfuck), 5 bytes
```
+[?.]
```
Throw a D256 until you throw a 0
[Try it online!](https://tio.run/##K0rMS8nP1U0qSszMSytNzv7/XzvaXi/2/38A "Random Brainfuck – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Sum of integers in string, separated by non-numericals such as 'a' and 'Y'](/questions/730/sum-of-integers-in-string-separated-by-non-numericals-such-as-a-and-y)
(39 answers)
Closed 3 years ago.
# **Input**
A string.
### **Output**
The sum of all integers in the line.
### **Constraints**
1≤Length of line≤500
### **Sample test Case**
**Input**
```
the 5is 108 seCONd4 a
```
**Output**
```
117
```
**Explanation**
Sum is: 5+108+4=117
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.œþOà
```
[Try it online](https://tio.run/##MzBNTDJM/f9f7@jkw/v8Dy/4/z9VwTSzWMHQwKI41TnFRCERAA) or [verify a few more test cases](https://tio.run/##MzBNTDJM/V9TVmmvpPCobZKCkn3lf72jkw/v8z@84L/O/1TzohRDo1QFQ8M0Ay5TLoPEJAMuMxMFUxNTHVMTE1NdYyMvrlQF08xiBUMDi@JU5xQThUQA). (Times out for the larger test cases due to the `.œ` builtin.)
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
þмS¡þO
```
[Try it online](https://tio.run/##yy9OTMpM/f//8L4Le4IPLTy8z////5KMVAXTzGIFQwMLheJUZ3@/FBOFRAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l4Qn/D@@7sCf40MLD@/z/6/xPNS9KMTRKVTA0TDPgMuUySEwy4DIzUTA1MdUxNTEx1TU28uJKVTDNLFYwNLAoTnVOMVFI5CrJgAspAMX8/UCiAA).
**Explanation:**
```
.œ # Get all partitions of the (implicit) input-string,
# which are all possible ways of dividing the input-strings into substrings
þ # Only leave the items consisting of digits for each partition
# (in the new version of 05AB1E, an explicit `€` is required)
O # Sum each inner list
à # Pop and push its maximum
# (after which the result is output implicitly)
þм # Only leave the non-digits of the (implicit) input-string
# i.e. "the 5is 108 seCONd4 a" → "the is seCONd a"
S # Split it into a list of characters
# → ["t","h","e"," ","i","s"," "," ","s","e","C","O","N","d"," ","a"]
¡ # Split the (implicit) input-string by each of these characters
# → ["","","","","5","","","108","","","","","","","4","",""]
þ # Remove the empty strings by only leaving the digits
# → ["5","108","4"]
O # And sum these numbers (which is output implicitly)
# → 117
```
[Answer]
# Javascript, ~~34~~ 32 bytes
`s=>eval(s.match(/\d+/g).join`+`)`
Match all digits and join them by a `+` turning it into 5+108+4, eval the result.
Only works on positive integers.
Saved 2 bytes thanks to Arnauld
```
f=
s=>eval(s.match(/\d+/g).join`+`)
g=()=>b.innerHTML = f(a.value)
g()
```
```
<input id=a value="the 5is 108 seCONd4 a" onkeyup="g()">
<pre id=b>
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 14 bytes
```
{sum m:g/\d+/}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urg0VyHXKl0/JkVbv/Z/cWKlQpqGUklGqoJpZrGCoYGFQnGqs79fiolCopLmfwA "Perl 6 – Try It Online")
Anonymous code block that returns the sum of all series of digits
[Answer]
# [R](https://www.r-project.org/), 64 48 45 bytes
After seeing the PowerShell entry I was able to golf this further.
```
function(s)eval(parse(,,gsub('\\D+','+0',s)))
```
[Try it online!](https://tio.run/##Dcm9DkAwEADg3VPcdndRCUmbGGzMvICltEUiiPPz@OVbvzMGqDKI4d7Ga9k3EvaPXemwp3hSapJ7IOz7JkWFaY5KmDkGwmv2YBaBIi9BfN21ToNFTv46rDHvrh1y/AA "R – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 bytes
Anonymous tacit prefic function
```
+/#⍎¨∊∘⎕D⊆⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X1tf@VFv36EVjzq6HnXMeNQ31eVRV9ujrkX/0x61TQDKAEU8/R91NR9ab/yobSKQFxzkDCRDPDyD/6cpqJdkpCqYZhYrGBpYKBSnOvv7pZgoJKoDAA "APL (Dyalog Unicode) – Try It Online")
`⊢` the argument
`⊆` partitioned (runs of True become pieces, run of False are separators) by
`∊` membership
`∘` of
`⎕D` the set of digits
`#⍎¨` evaluate each in the root namespace
`+/` sum
[Answer]
# [Zsh](https://www.zsh.org/), 21 bytes
```
<<<$[${1//[^0-9]/+0}]
```
[Try it online!](https://tio.run/##qyrO@P/fxsZGJVql2lBfPzrOQNcyVl/boDb2////JRmpCqaZxQqGBhYKxanO/n4pJgqJAA "Zsh – Try It Online")
```
${1 } # the 5is 108 seCONd4 a
${1//[^0-9]/+0} # +0+0+0+05+0+0+0108+0+0+0+0+0+0+04+0+0
$[${1//[^0-9]/+0}] # 117
```
Unfortunately, bash complains because it interprets `0108` as octal. Zsh does not (unless `setopt octalzeroes`)
[Answer]
# Bash, 43 bytes
```
for n in ${1//[!0-9]/ };{((s+=n));};echo $s
```
Replaces every non-number with a space, and then sums them together.
-5 bytes thanks to GammaFunction
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 8 bytes
```
\d+
$*
1
```
[Try it online!](https://tio.run/##K0otycxL/P8/JkWbS0WLy/D//5KMVAXTzGIFQwMLheJUZ3@/FBOFRAA "Retina 0.8.2 – Try It Online")
* The first line matches all numbers
* The second line replaces these by 1s, repeated said number of times
* The last line is a match, and counts the total number of 1s in the string
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 29 bytes
```
($args-replace'\D+','+0')|iex
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0MlsSi9WLcotSAnMTlVPcZFW11HXdtAXbMmM7Xi////6iUZqQqmmcUKhgYWCsWpzv5@KSYKieoA "PowerShell – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes
```
IΣ⁺ψS
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0VyMgp7RYo1JHwTOvoLQkuAQoma6hCQLW//@XZKQqmGYWKxgaWCgUpzr7@6WYKCRy/dctywEA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Charcoal's `Sum` operator automatically extracts numbers from a string, however if the string contains no non-digit characters then instead it takes the digital sum, so I concatenate a null byte to avoid this. The result is then cast back to string for implicit output.
[Answer]
# [Haskell](https://www.haskell.org/), 50 bytes
```
sum.map read.words.map f
f x|'/'<x,x<':'=x
f _=' '
```
[Try it online!](https://tio.run/##y0gszk7Nyflfrauck5iXXpqYnqrgHBCgrFvLVWirEPO/uDRXLzexQKEoNTFFrzy/KKUYzE3jSlOoqFHXV7ep0KmwUbdSt62oMbAxtFVXUP@fm5iZZ1tQlJlXolKoZGhUZmisoGCpoPQfAA "Haskell – Try It Online")
There's probably a better way, but this is the most obvious one.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~63~~ ~~59~~ 56 bytes
Why not. Obligatory regex answer. ~~Could probably dock off 6 by using Python 2, but whatever.~~ Doesn't apply anymore since I'm using an eval approach instead of using map.
```
import re;x=lambda y:eval('+'.join(re.findall('\d+',y)))
```
Explanation:
```
import re; # Import regex module
x=lambda y: eval( ) # Run as Python code
'+'.join( ) # Joined by '+'
re.findall('\d+',y) # A list of all matches of regex \d+ in string y
```
[Try it online!](https://tio.run/##PU7NisIwGLz7FEMuSbAUiy67KPXiXb3XHrLbr2skTUoSxCo@e42CXgbmj5l@iEdn5@Oou975CE@rS2lU99soDEs6KyP4lOcnp63wlLfaNsok7dBMeTZIKcdIIf6pQAElqorHI@FLBxSzHwTa7LbNAopnRfFd15PWeRhoi09pOQFwLS/CVLNaPknvtY2C3e4o10gobnfJ8tTsVHylMlMVdQa2VyFo@8@gW1yRJp86yAQC27qIt58@PgA "Python 3 – Try It Online")
[Answer]
# Java 10, 66 bytes
This is a lambda from `String` to `int`.
```
s->{var r=0;for(var n:s.split("\\D"))r+=new Long("0"+n);return r;}
```
Negative integers aren't supported. Presumably that's okay.
[Try It Online](https://tio.run/##jY3NTsMwEITPyVOsfHJUajmlRYiQXkBISPwceqQc3MQJDu4msjdBVZVnD67aO5xmNPvtTKMGNW/K76nrd9YUUFjlPbwqg3CMo0voSVGQoTUl7MOJb8gZrD8@QbnaJycyakKR6MlYUfVYkGlRPF3M/Rm/gmckXWu3hgryyc/Xx0E5cLnMqtbxk8c7L3xnDXG23T6yJHGzHPUPvLRYcybZDJPMaeodgsvGKYqyOExvDp70XrQ9iS4MkUVeCdV19sAZfWlYGQ@pvAWvH97fyiWoUJz98SchhQVcwxJWcPMPXkmZLnZncIzH6Rc)
## Acknowledgments
* -3 bytes thanks to [*Embodiment of Ignorance*](https://codegolf.stackexchange.com/users/84206/embodiment-of-ignorance)
[Answer]
## Ruby, ~~32~~ 27 characters
```
->s{eval s.scan(/\d+/)*?+}
```
### Acknowledgments
* -5 bytes thanks to [*Conor O' Brien*](https://codegolf.stackexchange.com/users/31957/conor-obrien)
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 17 bytes
```
?|i.I!/s+q;;>p.O@
```
[Try it online!](https://tio.run/##Sy5Nyqz4/9@@JlPPU1G/WLvQ2tquQM/f4f//koxUBdPMYgVDAwuF4lRnf78UE4VEAA "Cubix – Try It Online")
```
? |
i .
I ! / s + q ; ;
> p . O @ . . .
. .
. .
```
[Watch it run](https://ethproductions.github.io/cubix/?code=ICAgID8gfAogICAgaSAuCkkgISAvIHMgKyBxIDsgOwo+IHAgLiBPIEAgLiAuIC4KICAgIC4gLgogICAgLiAuCg==&input=dGhlIDVpcyAxMDggc2VDT05kNCBh&speed=20)
A fairly simple one. `I` in cubix will take the first integer in the input and push it to the stack. This has the effect of skipping all the characters. The rest of it is dealing with the additional and detecting the end of the input.
* `I!` Input an integer and test it for 0
* `s+q;;` If not zero, swap TOS (forces and initial 0) and add. Push result to the bottom of stack and clean out the top. Return to beginning.
* `/i?` If zero, redirect and do a character input to check
* `|?;/` If positive (character) turn right into a reflect, this then pushes it back through the checker `?` and turns right onto the pop from stack, leaving 0 on TOS. The IP then gets redirected back into the main loop.
* `I>p.O@` if negative (end of input) turn left, do integer input, bring the bottom of stack to top, output and halt.
[Answer]
# [PHP](https://php.net/), ~~40~~ 39 bytes
```
<?=array_sum(preg_split('(\D)',$argn));
```
[Try it online!](https://tio.run/##Hcy9CsIwFAbQV/kGoQkoVVAQau1gEVzqoKNQLu1tUkjSkKSDT19/9sPx2i@nymuPFQXlykFxiuLxrG@NLJDnYDsbSgzu9ISf27gruslacj3M6BgdGYPq/G1KCoHebZyt8IFVG70Zk8jEq5bZ@v9LWSxL0ozDGLHbHhH5cm/6PegD "PHP – Try It Online")
Run with `php -nF` input is from STDIN. Example:
```
$ echo the 5is 108 seCONd4 a | php -nF sumint.php
117
```
[Answer]
# [Haskell](https://www.haskell.org/), 43 bytes
```
f s|[(n,r)]<-reads s=n+f r|h:t<-s=f t|1>0=0
```
[Try it online!](https://tio.run/##BcExCoAgGAbQq3xEQ1GCQUFEtrTXAaJBUFEyCX9H727vWUmP9r4UA8pXE/rY3iuLWioCidAZxGyXtDISBikPGxe8vNIF8UUXEmoYVMlqTI4w8Bmk9/NQI2RVfg "Haskell – Try It Online")
Makes use of [`reads`](http://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#v:reads).
[Answer]
# [Ahead](https://github.com/ajc2/ahead), 13 bytes
This works because `I` simply scans the input stream for the next token that looks like a number, ignoring anything else.
```
~Ilj~#
>K+O@
```
[Try it online!](https://tio.run/##S8xITUz5/7/OMyerTplLwc5b29/h//@SjFQF08xiBUMDC4XiVGd/vxQThUQFAA "Ahead – Try It Online")
[Answer]
# [QuadR](https://github.com/abrudz/QuadRS), 9 bytes
```
+/⍎⍵
\D
```
[Try it online!](https://tio.run/##KyxNTCn6/19b/1Fv36PerVwxLlwK//@XZKQqmGYWKxgaWCgUpzr7@6WYKCQCAA "QuadR – Try It Online")
`+/` sum of
`⍎` evaluation as APL of
`⍵` the result of
`\D` replacing each non-digit with
a space
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-x`, 5 bytes
```
f/\d+
```
[Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=Zi9cZCs=&input=InRoZSA1aXMgMTA4IHNlQ09OZDQgYSIgLXg=)
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 23 bytes
```
Sum##N=>MatchAll&"\\d+"
```
[Try it online!](https://tio.run/##PcnBCoJAFIXhvU9xGKNNLjSVIrAI11lQO3UxjNdGUJHujR5/CsrOv/uOFtHGkmuxy9z1Ofh@ke1PWow99v1SVVWzUq4garhcTJO5197l0Y1yI5ZcM3HZBig9fKbEEtKOEYVbMOXnokmgVfA9owEcIorjDYZk/CvWiJEgnSHErxleVstBeXXt3g "Attache – Try It Online")
A more interesting, but indirect, answer (37 bytes): `{Sum!Reap[ReplaceF[_,/"\\d+",Sow@N]]}`
## Explanation
```
Sum##N=>MatchAll&"\\d+"
```
This has the form:
```
f##g=>h&x
```
which, when expanded and parenthesized, becomes:
```
f ## (g => (h&x))
```
`##` composes two functions together, `=>` creates a function mapping the left function over the result of the right function, and `&` binds an argument to a side of a function. For input `_`, this is equivalent to:
```
{ f[Map[g, h[_, x]]] }
```
First, then, we `MatchAll` runs of digit characters (`\\d+`). After, we convert each run to an actual integer using the `N` function. Finally, we take the sum of these numbers using `Sum`.
[Answer]
# APL(NARS), chars 13, bytes 26
```
{+/⍎¨⍵⊂⍨⍵∊⎕D}
```
test:
```
f←{+/⍎¨⍵⊂⍨⍵∊⎕D}
f 'the 5is 108 seCONd4 a'
117
```
[Answer]
# C# (Visual C# Interactive Compiler), ~~117~~ 111 bytes
```
a=>System.Text.RegularExpressions.Regex.Replace(a,@"\D+"," ").Split(' ').Select(x=>x==""?0:int.Parse(x)).Sum();
```
[Try it online.](https://tio.run/##FY3LCsIwFET3fsUlGxOsQUFBrKmCj5WoWMGNmxCvGoix5KYQv77GzTCcgTOGhoZst2u9WVAM1j8L62MFD1CdVlX9pYhvecEU5RmfrdNhm5qARPbj6Y8w5WycNsh1sWK3zYAVDJiQdeNs5H3o54oOTeRJVUkpxpajef6QJx0IeRJ5b99clF0JvXW2fhzKa7AR99Yjf3AWXwhTSzAezYBwfTzcJ6CZEGWv@wE)
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 17 bytes
```
s/\d+/$\+=$&/eg}{
```
[Try it online!](https://tio.run/##K0gtyjH9/79YPyZFW18lRttWRU0/Nb22@v//koxUBdPMYgVDAwuF4lRnf78UE4XEf/kFJZn5ecX/dX1N9QwMDf7rFgAA "Perl 5 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 3 bytes
Another test drive for my (very-WIP) interpreter.
```
q\D
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LXg=&code=cVxE&input=InRoZSA1aXMgMTA4IHNlQ09OZDQgYSI=)
```
q\D :Implicit input of string
q :Split on
\D : Non-digit characters (/[^0-9]/)
:Implicitly reduce by addition and output
```
[Answer]
# Java 8, ~~53~~ 130 bytes
105 bytes + 25 bytes for regex import
```
s->{long c=0;for(Matcher m=Pattern.compile("\\d+").matcher(s);m.find();c+=new Long(m.group()));return c;}
```
[Try it online!](https://tio.run/##LU7LSsQwFN3nKy5dJQ4TRlAQQt0Is3JUmKXjIqY3ndQ8SnI7KqXfXgPj6pwD5zXoi94O3dfqwpgywVC1nMh5mbHHH3mjmPG6FDhoF2fmImG22iDsZ59iD5YfKbtKilALG6dP7wwU0lThklwHoeb@Pe8foMXM9mDbtWwfrwWm3SmbMj9oMmfMENo3TXUkSpPC6Dzy5nTqNo2Q4ergdSlI62LHhTKbNuI3PNcmHmSf0zRyIYTKSFOOYNSyKnb8LYRBponkWH@Qj9xKyxs6I9y7Are7Byj49PrS3YFuapoty/oH)
**Explanation**
```
s->{ // Lambda function
long c=0; // Sum is zero
for(Matcher m=Pattern.compile("\\d+").matcher(s); // Prepare regex matcher
m.find(); // While the string contains unused matches...
c+=new Long(m.group())); // Add those matches to the output
return c; // Return the output
}
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 81 bytes
```
S =INPUT
D S SPAN('0123456789') . N REM . S :F(O)
O =O + N :(D)
O OUTPUT =O
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/nzNYwdbTLyA0hMsFyAwOcPTTUDcwNDI2MTUzt7BU11TQU/BTCHL1BdLBnFZuGv6aXJz@Crb@CtoKfpxWGi6aXP6c/qEhQAOAglyufi7//5dkpCqYZhYrGBpYKBSnOvv7pZgoJAIA "SNOBOL4 (CSNOBOL4) – Try It Online")
[Answer]
**Swift, 109 bytes**
```
func s(a:String){var d=0,t=0;a.forEach{(c) in if let e=Int(String(c)){d=d*10+e}else{t+=d;d=0}};t+=d;print(t)}
```
[Try it online!](https://tio.run/##JY3BCgIhFEV/5TErbSIcmCASVzGLNrXoC0SfjTBY6JtaiN9uVrsL99xz09s7Gmt1azCQmD7eKPpw5/mlI1gltqSE1Dv3iJM2c2aGgw/gHSxIgOociP0XreHZKrsZRI8Fl4SZemVlc5Qif/HZOGLES/0edTQj7H2CQRwg4el6sSPojtcP)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 6 bytes
```
$+a@XI
```
Treats `-123` as a negative integer. [Try it online!](https://tio.run/##K8gs@P9fRTvRIcLz////JRmpCqaZxQqGBhYKxanO/n4pJgqJAA "Pip – Try It Online")
```
a Command-line input
@XI Regex find all integers (XI is a variable predefined as the regex `-?\d+`)
$+ Fold on +
```
---
If hyphens should be ignored rather than treated as minus signs, then the following works for **7 bytes**:
```
$+a@+XD
```
`XD` is a preset variable for ``\d``; `+XD` adds the regex `+` modifier to it, making it match 1 or more digits.
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~98~~ ~~94~~ 93 bytes
```
s->java.util.Arrays.stream(s.split("\\D")).filter(t->!t.isEmpty()).mapToLong(Long::new).sum()
```
[Try it online!](https://tio.run/##dY87T8NAEIT7/IrD1V3hE0ggIUeJhMAdjyJ0hGJ1vsRrfA/drhOsyL/dXJBCxxarLeabme3gAGXXfM3o2aYdGCteAP1pQQyMRmw4od9/fAq2xAbI0upUcGvFHZK4ub4XZB/fXptbAcW0vECHgI1w2UZe8KS4TeFIov42NjKGnCDydDleD4y9fkgJRtLEyYKTf2lKO4hypnL9nzQfsUeWxXb7VCild9jnTySX6yvWSLWLPEr16/MenoPfy/OqKm@PStPgpJrPTTIYUg2mlZuR2DodBq6qmOtz79VyMU3zDw "Java (JDK) – Try It Online")
`-4 bytes` by using `Long::new` instead of `Long::valueOf`.
`-1 byte` by shortening the regex - if we're already removing empty strings later, making some extras when splitting is fine.
# Explained
```
s-> // Lambda (target type is ToLongFunction<String>)
java.util.Arrays.stream( // Stream the result of
s.split("\\D") // splitting on non-digits
)
.filter(t->!t.isEmpty()) // Discard any empty strings
.mapToLong(Long::new) // Convert to long
.sum() // Add up the stream's values.
```
] |
[Question]
[
## The Rules
* Each submission must be a full program.
* The program must take input as two comma-separated dates in the form `YYYY-MM-DD`, and print the number of days that has passed since the second date to STDOUT as if today was the first date (if the second date would be in the future, output a negative number) plus an optional trailing newline, and nothing else. Assume both dates are in the Gregorian calendar.
* The program must not write anything to STDERR.
Note that there must be an interpreter so the submission can be tested.
* Submissions are scored in *bytes*, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like [Folders](http://esolangs.org/wiki/Folders), are a bit tricky to score - if in doubt, please ask on [Meta](http://meta.codegolf.stackexchange.com/).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins
## Examples
**Input:**
```
2015-12-03,2015-12-01
```
**Output:**
```
2
```
**Input:**
```
2015-12-03,2014-12-01
```
**Output:**
```
367
```
**Input:**
```
2015-12-03,2013-12-03
```
**Output:**
```
730
```
[Answer]
# Bash + GNU utilities, 37
```
tr , \\n|date -f- +%s|dc -e??-86400/p
```
`tr` replaces the comma with a newline. `date` reads the newline separated dates and outputs the number of seconds since the Unix epoch that the passed-in date represents. These numbers are then put on the `dc` stack. Then its a simple matter of subtraction and divide by (24\*60\*60). In this case, `dc` stack-based RPN arithmetic evaluation is better than `bc` or bash `$( )`, mostly because the subraction-before-division needs no parentheses.
Input via STDIN:
```
$ echo 2015-12-3,2015-12-1 | ./longago.sh
2
$ echo 2015-12-3,2014-12-1 | ./longago.sh
367
$ echo 2015-12-3,2013-12-3 | ./longago.sh
730
$
```
[Answer]
# Julia, 67 bytes
```
print(Int(-diff(map(i->Date(i,"y-m-d"),split(readline(),",")))[1]))
```
Ungolfed:
```
# Read a line from STDIN
r = readline()
# Split it into two character dates
s = split(r, ",")
# Convert each to a Date object
d = map(i -> Date(i, "y-m-d"), s)
# Compute the difference in dates (first-second)
f = diff(d)[1]
# Convert the Base.Date.Day object to an integer
# Negate to get second-first
i = Int(-f)
# Print to STDOUT
print(i)
```
[Answer]
## Scala, ~~166~~ ~~139~~ ~~120~~ ~~116~~ 92 bytes
```
print(args(0).replace('-','/').split(",").map(java.util.Date.parse(_)/86400000).reduce(_-_))
```
Usage: `scala [source filename].scala [date1],[date2]`
*Note: The third version (120 bytes) and on uses a deprecated API. It still compiles and works fine.*
*Note2: Thanks to the commenters below for the great advice!*
[Answer]
# Ruby, ~~69~~ ~~66~~ ~~65~~ ~~57~~ 55 bytes
```
a=->l{Time.gm *$F[l,3]};p (a[0]-a[3]).div 86400
```
47 bytes + 8 bytes for command line option. Thanks to Dane Anderson, saved 2 bytes.
**57 bytes**
```
p (Time.gm(*$F[0,3])-Time.gm(*$F[3,3])).div 86400
```
49 bytes code + 8 bytes for command line option. Saved 8 bytes with manatwork's suggestion.
**65 bytes**
```
a,b=gets.split(?,).map{|i|Time.gm *i.split(?-)};p (a-b).div 86400
```
**66 bytes**
```
a,b=gets.split(?,).map{|i|Time.new *i.split(?-)};p (a-b).div 86400
```
**69 bytes**
```
a,b=gets.split(',').map{|i|Time.new *i.split('-')};p (a-b).to_i/86400
```
[Test it online](https://ideone.com/CiJ5Ik)
**Ungolfed**
```
a = -> l {
Time.gm *$F[l,3] # Anonymous method to parse time
}
p (a[0]-a[3]).div 86400 # Subtracts two times and divides by 24*60*60
```
**Usage:**
```
ruby -naF[,-] -e 'a=->l{Time.gm *$F[l,3]};p (a[0]-a[3]).div 86400' <<< '2015-12-3,2013-12-3'
=> 730
```
[Answer]
# [Japt](https://github.com/ETHproductions/Japt), 41 bytes
```
A=K$.parse)(($B=Uq', g0)-$A($Bg1))/864e5
```
So far this is the best I can get it as all the variables and `$` and parenthesis really kill the byte count.
[Try it online](http://ethproductions.github.io/japt?v=master&code=QT1LJC5wYXJzZSkoKCRCPVVxJywgIGcwKS0kQSgkQmcxKSkvODY0ZTU=&input=IjIwMTUtMTItMDMsMjAxNS0xMi0wMSI=)
## Explanation
```
// Implicit: U is set to input
A=K$.parse) // Set variable A to date parsing function
(($B=Uq', // Set B to input split by ,
g0) // Get the first date and parse
- // Subtract...
$A( // Parse this date...
$Bg1 // Get's second date
))/864e5 // Divides by 86,400,000
```
[Answer]
# MATLAB, ~~41~~ 31 bytes
```
disp(-diff(datenum(input(''))))
{'2015-12-03', '2014-12-22'}
346
```
Input must be a comma-separated cell array. `datenum` converts the input cell into a 2x1 numeric array with the time stamp. `diff` takes the difference between the two.
---
**Old solution, 41 bytes**:
```
disp(-diff(datenum(strsplit(input('')))))
```
Input must be a comma-separated string:
```
disp(-diff(datenum(strsplit(input('')))))
'2015-12-03, 2014-12-22'
346
```
The curious ways of programming. This works because of MATLAB's implicit casting between datatypes.
The output from `strsplit(input(''))` is a cell of strings. You cannot use `diff` on a cell, but fortunately, `datenum` works, and it actually casts the cell input back to a 2x1 numeric array, making `diff` possible to use.
You can specify a whole lot of delimiters in `strsplit`, but comma is the default one. Also, the default input to `datenum` is on the format `yyyy-mm-dd`. For those reasons, a lot of specifications such as: datenum(s,'yyyy-mm-dd') are avoided, saving a whole lot of bytes.
For the record, this would be 21 bytes if I could use a function:
```
@(s)-diff(datenum(s))
```
[Answer]
# Javascript ES6, 63 bytes
Tested in chrome.
```
alert(((p=Date.parse)((a=prompt().split`,`)[0])-p(a[1]))/864e5)
```
[Answer]
# PHP, 63 ~~64~~ ~~77~~ bytes
Found that the classic approach is shorter than the OOP one:
```
$x=fgetcsv(STDIN);$s=strtotime;echo($s($x[0])-$s($x[1]))/86400;
```
Reads the comma separated string from `STDIN`.
---
The straight forward OOP way (**77 bytes**):
```
$x=fgetcsv(STDIN);echo(new DateTime($x[0]))->diff(new DateTime($x[1]))->days;
```
---
**Edits**
* *Saved* **13 bytes** by using `strtotime` instead of `DateTime`.
* *Saved* **1 byte** by storing `strtotime` in a variable. Thanks to [Blackhole](https://codegolf.stackexchange.com/users/11713/blackhole).
[Answer]
# Excel, 25 bytes
```
=LEFT(A1,10)-RIGHT(A1,10)
```
Excel automatically handles the strings as dates.
[Answer]
# [TeaScript](https://github.com/vihanb/TeaScript), 24 bytes
```
((a=D.parse)×-a(y©/864e5
```
Uses `Date.parse` to parse the date, then get's the difference and divides.
[Try it online](http://vihanserver.tk/p/TeaScript/#?code=%22((a%3DD.parse)(x)-a(y))%2F864e5%22&inputs=%5B%222015-12-03,2015-12-01%22%5D&opts=%7B%22int%22:false,%22ar%22:true,%22debug%22:false,%22chars%22:false,%22html%22:false%7D)
## Explanation && Ungolfed
```
((a=D.parse)(x)-a(y))/864e5
// Implicit: x is first date
// y is second date
(
(a=D.parse) // Assign Date.parse to 'a'
(x) // Run Date.parse with first date
-a(y) // Subtract Date.parse run with second date
)/864e5 // Divide by 86,400,000
```
[Answer]
# VBA, 69 bytes
```
Function x(s)
g=Split(s, ",")
x=CDate(g(0))-CDate(g(1))
End Function
```
[Answer]
# psql, 75 bytes
(74 characters code + 1 character command line option)
```
\prompt i
select split_part(:'i',',',1)::date-split_part(:'i',',',2)::date
```
`psql` is PostgreSQL's interactive terminal. To respect the “Each submission must be a full program.” rule, the code reads the input itself.
Sample run:
```
bash-4.3$ psql -tf how-long-was-this.sql <<< '2015-12-3,2013-12-3'
730
```
[Answer]
# Python 2, ~~109~~ 113 bytes
```
import datetime as d
j=[d.date(*[int(k) for k in g.split('-')]) for g in raw_input().split(',')]
print j[0]-j[1]
```
[Answer]
## MATL, 5 bytes
```
iPYOd
```
This is the same as StewieGriffin's answer, except I used `flip` then `diff` rather than `diff` then negating the result.
Full explanation, with corresponding Matlab functions:
```
i %// input(''), get input
P %// flip, flips the array
YO %// datenum, converts date string into an integer
d %// diff, finds the difference between dates
```
[Answer]
## PowerShell v2+, ~~50~~ 44 Bytes
```
$a,$b=$args-split','|%{date $_};($a-$b).Days
```
Takes input argument as a string, splits it on the comma, then pipes the array via a built-in alias `date` short for `Get-Date` to convert our strings into .NET datetime format. Those two dates then get stored simultaneously into `$a` and `$b`. We then use an overloaded-subtraction-operator to subtract the second from the first, and output the `.Days` thereof.
Golfed 6 bytes thanks to [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler).
Technically non-competing, as it doesn't have an online interpreter available, since the FOSS implementation of PowerShell, [Pash](https://github.com/Pash-Project/Pash), is around PowerShell v0.5. It doesn't support `-split` yet, let alone the complex .NET date functionality.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
```
£ÐXÃr- zHÑ7e5
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=o9BYw3ItIHpI0TdlNQ&input=WwoiMjAxNS0xMi0wMyIKIjIwMTUtMTItMDEiCl0)
[Answer]
# JavaScript, ~~58~~ 53 bytes thanks to @targumon!
```
n=>(new Date((a=n.split`,`)[0])-new Date(a[1]))/864e5
```
Older version:
```
n=>(new Date((a=n.split(','))[0])-new Date(a[1]))/86400000
```
My submissions seem to have a reputation of being boring.
[Answer]
# [Jolf](http://conorobrien-foxx.github.io/Jolf/#code=JFM9JHZpR2knLCBtRE5-REggcn0vbTRTbWVQIjg2NCI1), 33 bytes
Only works in Chrome. Noncompeting, since language updates postdate question. I'll add a more thorough explanation later.
```
$S=$viGi', mDN~DH r}/m4SmeP"864"5
```
## “Explanation”
```
$S=$viGi', mDN~DH r}
$S=$ sets S equal to
viGi', take string input and reassign it to the comma-split input
mD } map with this function
N~DH r return the time of the date of H (element)
/m4SmeP"864"5
/ divide
m4S subtraction applied to S (S[0] - S[1])
meP"864"5 and 864 * 10 ^ 5 (thanks to Super Jedi for his nice constant)
implicit output
```
[Answer]
## MATLAB, 59 bytes
```
s=strsplit(input(''),',');disp(datenum(s{1})-datenum(s{2}))
```
Very straightforward approach: input has to be given as a string from the command window. The input string is then split and the number of days between the dates (and nothing else) is calculated from the serial date numbers.
I'm quite sure there is a way to avoid the need for calling datenum twice though...
[Answer]
## T-SQL + SQLCMD, 51 bytes
```
PRINT DATEDIFF(D,RIGHT('$(i)',10),LEFT('$(i)',10))
```
Tested with SQL Server 2008R2. The $(i) is replaced with the input provided as a command line argument.
Sample run:
```
sqlcmd -i script.sql -v i="2015-12-08,2016-01-01"
-24
```
[Answer]
## Mathematica, 61 bytes
```
Print@First[#-#2&@@DateObject/@InputString[]~StringSplit~","]
```
Basic date subtraction.
[Answer]
## Perl, 91 86 + 2 for np flags, 88 bytes
use Date::Calc qw(Delta\_Days);($a,$b)=split(/,/);$\_=Delta\_Days(split(/-/,$b),split(/-/,$a))
```
use Date::Parse;$_=str2time((split(/,/,$_))[0])-str2time((split(/,/,$_))[1]);$_/=86400
```
Example
```
$ echo 2015-12-3,2015-12-1 | perl -npe 'use Date::Parse;$_=str2time((split(/,/,$_))[0])-str2time((split(/,/,$_))[1]);$_/=86400'
2
```
[Answer]
# jq, 50 bytes
(49 characters code + 1 character command line option)
```
./","|map(.+"T0:0:0Z"|fromdate)|(.[0]-.[1])/86400
```
Sample run:
```
bash-4.3$ ~/bin/jq -R './","|map(.+"T0:0:0Z"|fromdate)|(.[0]-.[1])/86400' <<< '2015-12-3,2013-12-3'
730
```
[On-line test](https://jqplay.org/jq?q=./%22,%22|map%28.%2B%22T0:0:0Z%22|fromdate%29|%28.[0]-.[1]%29/86400&j=%222015-12-3,2013-12-3%22) (Passing `-R` through URL is not supported – so input passed as string "2015-12-3,2013-12-3".)
[Answer]
## Mathematica, 56 bytes
```
Print@#&@@-DateDifference@@InputString[]~StringSplit~","
```
Most (all?) date functions will try to parse string inputs into dates automatically.
[Answer]
# [C# .NET](https://visualstudio.microsoft.com/), 148 bytes
```
using System;class P{static void Main(string[]a){Console.Write((DateTime.Parse(a[0].Substring(11,10))-DateTime.Parse(a[0].Substring(0,10))).Days);}}
```
[Try Online](https://tio.run/##fcuxCoMwEIDhV8mYgAmJUGhxrGtBsNBBHK5pKAeagHcWRHz2VOre7R@@35P25HOeCeNbtAtxGCs/AJFoVmJg9OKT8CVugFESTzvrelDrNUVKQzCPCTlIWQOHO47BNDBRkNDZ3rTz8xikc4WzSun/yv6QMjUspKptyzmX1l20PenSFUee9/wC)
[Answer]
# C (gcc), ~~225~~ 199 bytes
-25 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)! Replacing an array of numbers with a string of wide-characters is some proper black-magic
-1 byte by adding an additional character to the start of the string, allowing for indexing with [m] instead of [m-1]
```
a,b,d,e,f;i(m,y){return(a=y-1)*365+a/4-a/100+a/400+L"\0\37;Zx\x97µÔóđİŎ"[m]+(m>1&(y%100*!(y%4)||y%400<1));}main(c){scanf("%d-%d-%d,%d-%d-%d",&a,&b,&c,&d,&e,&f);printf("%d",i(b,a)-i(e,d)+c-f);}
```
[Try it online!](https://tio.run/##NYttisIwGISvogFDXvu@mNSPEqp7Ak@w1h9p2kp@tEhVsKhXEBY8iCB7AT/OVbPCwjDzwMxYWlnbtgZTzDDHInaixAYOdb7d1ZUws4YU9IeTcWAGIzIDJeUfeZ@zTiKTYRR/75O9ju6/j8vj9vx5Xl9ntiiXgSi/FBdNzz/6XZ8jOB69SzlVAPGpNK4SFg4ba6pCsF5GH@E/MOQGeYrcIs@Q58gLiNe1q7afNUMnUjRATuSYQWDJ16e2DaUKSUakQlRaa5@k9Bs "C (gcc) – Try It Online")
Perhaps the code could be shortened by using <time.h>, but not using it makes for a fun challenge.
The difference between dates is calculated using a golfed version of [this code](http://www.sunshine2k.de/articles/coding/datediffindays/calcdiffofdatesindates.html).
Un-golfed:
```
a,b,d,e,f;
i(m,y){
return(a=y-1)*365 /*Num days in y-1 years*/
+a/4-a/100+a/400 /*Add previous years' leap days*/
+L" \0\37;Zx\x97µÔóđİŎ"[m] /*Add days this year until month*/
+(m>1&(y%100*!(y%4)||y%400<1)); /*Add this year's leap day*/
}
main(c){
scanf("%d-%d-%d,%d-%d-%d",&a,&b,&c,&d,&e,&f);
printf("%d",i(b,a)-i(e,d)+c-f);
}
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/265259/edit).
Closed 5 months ago.
[Improve this question](/posts/265259/edit)
Since programming is predicted to become natural linguisized by the unstoppable advances in LLM technology, perhaps we can code golf LLMs themselves.
Produce the shortest question that is not an arithmetic problem (we know it sucks at multiplication problems) that produces an obvious falsehood from ChatGPT with screenshot as evidence.
Extra points if the error is reproducible by others (perhaps it was generated with low temperature), not one even a child would make, or is particularly hilarious.
Use GPT4 if you have access.
[Answer]
# GPT3.5 model, 1 byte
Hexdump: `0x01`
[](https://i.stack.imgur.com/Gqdxd.png)
It doesn’t look like a blank message…
[Chat Link](https://chat.openai.com/share/83340212-039e-492f-9232-5b2e5eadff6e)
[Answer]
## 12 characters (GPT-4)
[](https://i.stack.imgur.com/40MOJ.png)
```
Query: eerie sorted
GPT-4: Sorting the word "eerie" alphabetically results in "eeeri".
```
This one's quite inconsistent. The longer "Sort letters eerie", though, elicited a wrong answer 10/10 times, always with an extra r and sometimes an extra e, though the letters' ordering was correct.
[Answer]
# ChatGPT 3.5 - 5 bytes
```
Vyxal
```
[](https://i.stack.imgur.com/Rcr9U.png)
1. APL and J aren't golfing languages
2. APL and J weren't inspirations for Vyxal (I know this because I didn't take anything from J)
[Answer]
# GPT-3.5, 2 bytes
```
_?
```
[](https://i.stack.imgur.com/UCkoA.png)
I entered a little more than an underscore, so it's somewhat of a falsehood.
[Answer]
# 9 characters (GPT-3.5)
[](https://i.stack.imgur.com/5zxr9.png)
>
> [User] am i dead
>
>
> [GPT-3.5] I'm just a computer program, so I can't determine your current state of being. If you're feeling uncertain or concerned about your health, I would strongly recommend seeking immediate medical attention or contacting a healthcare professional. They can provide you with the necessary assistance and guidance to address any health-related concerns.
>
>
>
One could argue this is clearly false, since if I am interacting with the model then I must be alive. (However, that is up for debate.)
[Answer]
# 17 bytes (ChatGPT)
ChatGPT sucks at code golf.
“th shrtst js quine”
The code it posted doesn’t work because it doesn’t include the `console.log(JSON.stringify())` bit, and is also not the shortest.
[](https://i.stack.imgur.com/6vpL3.jpg)
[Answer]
# ChatGPT, 5 bytes
“pi 97”
[](https://i.stack.imgur.com/E5PJ1.jpg)
>
> The value of pi (π) to 97 decimal places is:
> 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
>
>
>
This is pi to 100 decimal places, not 97.
[Answer]
## 44 Characters (ChatGPT 3.5)
>
> User: "banana" sorted reverse lexicographically is
>
>
> ChatGPT: When the
> word "banana" is sorted in reverse lexicographical order (from Z to
> A), it becomes "nnaaab."
>
>
>
[](https://i.stack.imgur.com/c9GI9.png)
] |
[Question]
[
There is a building with an infinite number of floors and you are the only passenger in an elevator which can lift an infinite number of people. You are going home, but before the elevator gets to your floor, the elevator stops at another floor to allow people to enter the elevator and input their destination floors. Your program should handle the floor order correctly
---
You will be given 3 inputs (the order of input doesn't matter but you need to specify the expected order of inputs):
* Integer - The number of the floor where the people entered the elevator
* Integer - Your destination floor
* Array of integers - The destination floors of entered people
You must output an array of integers with the numbers of floors (including yours) ordered correctly
The correct order is this order, where first the floors that are in the direction of your movement go in an ordered order, and then the floors that are in the direction opposite to yours go in reverse order
* The floor where the people entered is the floor where elevator already stopped so this floor should not be in the order of future destinations (output array)
* There will not be any duplicates in the input array
* Your destination floor will not be in the input array
For example let's say that elevator stopped at the ground floor, your destination is 3rd floor and people entered `[4,-2,-5,2,-4,1,5]`
So the output of must be `[1,3,4,5,-2,-4,-5]`
**Test cases:** (feel free to add more test cases)
```
0, 3, [4,-2,-5,2,-4,1,5] --> [1,2,3,4,5,-2,-4,-5]
0, -3, [4,-2,-5,2,-4,1,5] --> [-2,-3,-4,-5,1,2,4,5]
5, 10 [1,3,7,9,11,-3,-10] --> [7,9,10,11,3,1,-3,-10]
```
The shortest code in each programming language wins!
[Answer]
# [Python 3](https://docs.python.org/3/), ~~65~~ ~~64~~ ~~62~~ 61 bytes
```
lambda s,m,a:sorted([m]+a,key=lambda x:(x>s)*(s-m)-(s-x)**-2)
```
[Try it online!](https://tio.run/##bY3BboMwEETv/gorJ5vMql4IqkAiP0I5OI2loMTEimlC@vPUoZV64TKHeW92w3M8XYdids3HfLH@cLQywsPW8Xob3VG1vttanN2z@aNTraZ91JmK5DWlnHSWUa7n@7rBb/YQF008Tv3FSa6FdJP7VJvlUbPZ9kP4GpXWQoZbP4zKqYX8F9l3H5SFt0HdX72eDWQB2e5AOahEih0YZSdFIrSKRAnJibaMAu@owIxkEptOsDEGKRgrO2KY1DPyqlpg8UJJoer3QN79AA "Python 3 – Try It Online")
I think this may not work due to floating point inaccuracy once you reach a certain floor, since values that are too large eventually will round to the same value. Not sure what can fix that though
I reread the rules and saw there will never be duplicates so -1 byte
making the function anonymous; -2 bytes
-1 byte thanks to xnor's suggestion using `**-2` instead of `1/abs`
[Answer]
# [R](https://www.r-project.org), 47 bytes
```
\(e,d,l,m=c(d,l))m[order(!(m<e)-(e<d),(m-e)^2)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fY07DsIwEETrcArodqVZkU1iAVJyEX5NvK6wkCw4DY1B4lDcBkehpplXvBnN45nyKwzv-y3I9rM-ksHjgjiMVMgcD9fkLdGKYm8sZL1nUBTjc8On32wfqMayRVWN1EEaiEOJDgrHvJis_LEOWubFKlpssIPq1BetmeeHnGd-AQ)
Approach copied from [Jonah's answer](https://codegolf.stackexchange.com/a/258149/95126) - upvote that one!
---
Previously: **[R](https://www.r-project.org), 56 bytes**
```
\(e,d,l,u=e<d,`+`=sort)c(c(d,l[i<-!(l>e)-u])+!u,l[!i]+u)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fY1BCsIwFETX9RRml0_nQ2MbrNB4ELVQSBMoFAq1OY2bKHgob2OKXbuZgXkzzOM5x5c377B4rj_1TTr0GBGMa3p0eWfu07yQlVam-Do0LOR4dsShpVyEFImhzQNt-4uXBfYlsszKCnwAaySpoKCJdivlP1RDpXmiCiWOOEGptc-qoO0hxp9_AQ)
Uses the `decreasing` argument of `sort` to control sorting order.
[Answer]
# [J](http://jsoftware.com/), 29 27 bytes
```
}:@,([/:(~:&*-/),.(|@-{:))]
```
[Try it online!](https://tio.run/##fY69bsJAEIR7P8VAEd9Zu/7Bd5G8kiMLJCpEQWtOLhAIaNJQIEHy6mbtKKKCYqeYmW93z301kSJ8TqSK42iaxgfUghiEHKLDKRab1bL/kYZMm4n5lY@EM0upuTd8E2tDb6P1PMXYSEw9xjY8Pc6aYMJWkiaxw4Z/Lor2u@M3HLoZOg8VhwIeB5TIX2bdGF5PF303J5SE1hHPiD2pOCrIBzB/oS3UKMmRH2MteT2pCL9hBrP8K9PAKx36Bw "J – Try It Online")
* Sorts by:
+ First: Are you in the same direction as start - destination, as a 0 1.
+ Then: Absolute distance from start
[Answer]
# [R](https://www.r-project.org), 71 61 59 bytes
*-10 bytes thanks to pajonk, -2 thanks to Dominic*
```
\(x,y,z,i=sort(c(z,y)))c(i[i>x&y>x],rev(i[i<x]),i[i>x&y<x])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3rWM0KnQqdap0Mm2L84tKNJI1qnQqNTU1kzUyozPtKtQq7SpidYpSy0Bcm4pYTR2oMIgNNSIqTcNAR8FYh5MzWcNER9dIR9dUB0iY6BjqmGpqcoFkdfHImuoYArUDZQ11jHXMdSx1DA1B6nUNDTShNixYAKEB)
[Answer]
# [Haskell](https://www.haskell.org), 89 bytes
```
import Data.List
g z|z=id;g _=flip;f x y v|(a,b)<-span(<x)$sort$y:v=g(x<y)(++)b$reverse a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZDNToQwFEb3PMW3YEEzF0MF4s_QnUtfwEzIpOMUJDJI2kpgwpu4mY3xmXwWNxYGdeWmyT39zm3vfft4kuZZ1fXp9P5qi_D686E6tC_a4k5aeXFfGeuVOI5HUe3XJbaiqKt2XaDHgG4MJO1YFppWNkHWM9840R9uO1EGfTawYLViO1-rTmmjIJcHvqwydvsojTIQ2HhAEBFiwiah8JLClNyREKc0d4y7KqaE0vnOJdKc0eKE_0kTic9pmho4fbFSAo_mtjFd0Q1xPid5NGkziCYW0y9nuefp6aPL0BACqm8xIugJA6GjqWbIQvxNlnsHWTVOa3XVWPiQzR7aO6_gZ9ff)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ïš.¡›}ε{¹I‹N^iR]˜
```
Inputs in the order `myDestinationFloor, list, startFloor`.
[Try it online](https://tio.run/##yy9OTMpM/f//8PqjC/UOLXzUsKv23NbqQzs9HzXs9IvLDIo9Pef/f2OuaBMdXSMdXVMdIGGiY6hjGstlAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCaPGhlUr/D68/ulDv0MKI4kcNu2rPba0@tC7iUcNOv7jMoNjTc/4r6YXp/I@ONtaJNtHRNdLRNdUBEiY6hjqmsToGsToK0bq4pQwNdKINdYx1zHUsdQwNdYAqdQ2BEqaxsQA).
**Explanation:**
```
ï # Explicitly cast the first (implicit) input to an integer
š # Prepend this first input-integer to the second (implicit) input-list
.¡ # Group the integers in the list by:
› # Check if the third (implicit) input is larger than the current integer
}ε # After the group-by: map over the pair of lists:
{ # Sort the integers in the current group in ascending order
¹I‹ # Check if the first input is smaller than the third input
N^ # Bitwise-XOR it with the 0-based map-index
i # If this is truthy:
R # Reverse the list to a descending order
] # Close both the if-statement and map
˜ # Flatten this pair of lists to a single list
# (after which the result is output implicitly)
```
Two notes:
1. The cast to integer `ï` is necessary for the sort `{`. Without it, the input would be added as a stringified integer, and the sort would put it incorrectly after all the other integers in its group.
2. The bitwise-XOR `^` is to determine whether we need to reverse the list to a descending sorted group, which will apply as follows:
| `¹I‹` (first input < third input?) | `N` (is it the second iteration of the pair of lists?) | `iR` (reverse it?) |
| --- | --- | --- |
| truthy | 0 | yes |
| truthy | 1 | no |
| falsey | 0 | no |
| falsey | 1 | yes |
[Answer]
# JavaScript (ES6), 62 bytes
Expects `(stopFloor, myFloor, array)`.
```
(p,q,a)=>[...a,q].sort((a,b)=>((a<p)-(b<p))*(q-p)+(a-p)/(a-b))
```
[Try it online!](https://tio.run/##fY7BDoIwEETvfkWPrU4LpVRjIv4I6aEgGI2xIMbfxy0SYzTxMpvM7L7Zs3/4ob6duru8hkMztsXIO/TwotiXSimP3qkh3O6ce1Rk0tx1QvKKVCx5Lzux4p40Ia2EGOtwHcKlUZdw5C1nKRgzYGUOmUFakOTQsI4JwZKElZosgxx2WqA16xa/DPmXEW3zOkbkEe0HYsE0gajPYIMttJ5udOpmyGSm0Td4Z18Uqvh8ZY3sVfnxionJ/EQM5dqNTw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes
```
⊞ζηW⁻ζυ⊞υ⌊ι≔⮌Φυ‹ιθζI⎇‹ηθ⁺ζ⁻υζ⁺⁻υζζ
```
[Try it online!](https://tio.run/##TY0/C8IwEEd3P8WNF7iAf9rJSQQnhSJupUMowQRixFxTsV8@Ji2Cyw3v3o/XGxX6p3IpNZENTgRG7FdvY50GvFgfubAoBMz/SJChfcQHWpHFA7O9e7zqUQfWeLJu0KFYZ82MluAlhCCYstoE6wc8Kh7wpoNX4YOzZIpE0LgltTRj2fzoH5pxDqfUrgnkjqCtSG5J1pRPRRuquy7J0X0B "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞ζη
```
Add your destination floor to the list.
```
W⁻ζυ⊞υ⌊ι
```
Sort all of the floors in ascending order.
```
≔⮌Φυ‹ιθζ
```
Extract the floors below your starting floor and reverse them.
```
I⎇‹ηθ⁺ζ⁻υζ⁺⁻υζζ
```
Remove them from the sorted list of floors and then concatenate them to either the beginning or the end depending on your direction of travel.
[Answer]
# MATL, 20 bytes
```
h!ti-tZSt0)=~w|h&XS)
```
Try it out at [MATL Online](https://matl.io/?code=h%21ti-tZSt0%29%3D%7Ew%7Ch%26XS%29&inputs=%5B1%2C3%2C7%2C9%2C11%2C-3%2C-10%5D%0A10%0A5&version=22.7.4)
Input order is array of destinations, your destination, and the initial floor
**Explanation**
```
% Implicitly grab input
h! % Append your desired floor with the floors of everyone else
t % Duplicate this
i- % Subtract the initial floor
t % Duplicate this delta
ZSt0)=~ % Compare the sign of our target floor with the sign of everyone else
% and invert so same direction as us == 0, otherwise == 1
w % Flip the top of the stack to get the deltas again
| % Compute the absolute value to get the distance
h % Horizontally concatenate the sign-agreement array with
% the array of distances
&XS % Sort the rows and retrieve the row indexes
) % Index into our original array of all destinations
% Implicitly display the result
```
[Answer]
# [Arturo](https://arturo-lang.io), ~~55~~ 53 bytes
```
$[g,d,a][arrange a++d'x->*(x<g)?->1->9(g-d)-^g-x 0-2]
```
[Try it](http://arturo-lang.io/playground?c05T3v)
Port of Bob th's [Python answer](https://codegolf.stackexchange.com/a/258151/97916).
-2 bytes thanks to a suggestion by xnor.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~58 57~~ 56 bytes
```
->a,b,l{(l<<b).sort_by{|x|x>a ?x-a:l.sort[a>b ?0:-1]-x}}
```
[Try it online!](https://tio.run/##fYrBCsIwEAXvfsUeFd5K1jaIpaYfEhZJDj0FlKqQ0vbbYxDPXuYwM9M7zmW8FnYBEWnZp76Ph@PzPr1ucV7WvGYXaMgcuvS1PrhIg@lYlPO2lQeN3oAakG/BJ7BFRQuBVd39Kv/JFiR18YIGZ1wggrqzGNXyAQ "Ruby – Try It Online")
### How it works
Sort all floors above the current in ascending order, then all the floors below in descending order, then put the 2 arrays together in the right order.
This is done by "shifting" the floor numbers, if we are going up, then the floors below current get a higher number in reverse order (starting from max floor + 1 for the highest floor below current). If we are going down, then the floors below get a lower number, also in reverse order (from min floor + 1 for the highest floor below current).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 99 bytes
```
Join@@({s,m,a}={##};t={SortBy[#1,(s-#)&],#2}&@@SplitBy[Sort@Append[a,m],#>s&];If[m>s,Reverse@t,t])&
```
[Try it online!](https://tio.run/##FcmxCoMwEADQXxECQeEC1eokyrVbO5U6hgyhTTFgVMxRKCHfnuryluc0jcZpsi@dxi7dFzsj5sGDAx27wFhsqQvDstH1J1kJuRes4ApYFTnisE72iOPxsq5mfksNbu/ec9XePtL1Hp7mazZvkIBUwdNjszPhKE@QiTNkoQZRgWhgp4YSmqjSHw "Wolfram Language (Mathematica) – Try It Online")
Need to be golfed =(
try to do it later...
] |
[Question]
[
A huge storm is ravaging the world and as you and your family run away from it, you come across a gigantic shelter run by a girl. She tells you that "she sells sanctuary" and that different types of rooms are offered at different prices.
A room may only house one person.
# The challenge
Write a program which takes in two inputs: the number of people staying at the sanctuary and an array, map, object or string, whatever is convenient as long as the structure is similar to:
```
[[2, 3], [3, 5], [6, 7]]
```
In this case, it's a two dimensional array, but it could be a string, like
```
2,3 3,5 6,7
```
For each entry, the first item is the number of rooms offered for that type, and the second item is the cost of one room. For instance,
```
[[1, 2], [3, 4]]
```
means that one room is offered for the first type for 2 dollars each, and three rooms for the second type at 4 dollars each.
Since your family has limited resources, you would like to find the configuration for which as little money is spent as possible. So, your program should output a few numbers containing information about the number of rooms. At the end, it should also output the total cost.
This might all sound confusing, so take a sample input:
```
First input: 5
Second input: [[2, 5], [2, 3], [7, 100]]
```
The cheapest possible configuration is to have two people stay in the first type, costing `3 * 2 = 6` dollars, then two people in the second type for `5 * 2 = 10` dollars, and one person in the last type, for `100 * 1 = 100` dollars. The total cost is therefore `116` dollars. Your output for this test case would be
```
2 // two people in the first type of room
2 // two people in the second type of room
1 // one person in the third type of room
116 // total cost
```
Let us try another.
```
first input: 10
second input: [[1340993842, 5500], [1, 5000]]
```
The cheapest configuration is to have one person stay in the second type, and the other nine in the first type. The cost is therefore `9 * 5500 + 1 * 5000 = 54500`.
Output:
```
9
1
54500
```
A few extra rules:
* The number of people staying will never be more than the total number of rooms.
* Standard loopholes are disallowed as usual.
* The last output must be the price.
* You may output as an array if you would like.
* Nobody else is staying in the sanctuary.
* Shortest answer in bytes wins because this question is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
* Input may be taken as rest parameters.
* Order may be reversed, so for example the price might be the first item. You must make it clear though.
* The rooms are **not** guaranteed to be ordered from cheapest to most expensive.
* Output must be in order of the types given
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
```
Minimize[{#.x,Tr@x>#3},x∈Cuboid[0#,#2]]&
```
[Try it online!](https://tio.run/##FYq9CsIwGAD3vkag06fkp0E7WALOgqBbyBBrixkSoUQIhq9zn9MXie1wy915G1@Dt9H1toyncnHBefcddCb7BPdJpY4IhPRblvPn8XZPTQkQbkxdrpMLUZNdNypFTD3fehvmXOUsQQCjFCFz4HBAkAiblpTCyhaYaGjbimPDgeE6Y4XlDw "Wolfram Language (Mathematica) – Try It Online")
Input `[prices, availability, #people]`.
---
`Cuboid` represents a hyperrectangular region, given two opposite corners:
\$\texttt{Cuboid[$(a\_1,...,a\_n)$,$(b\_1,...,b\_n)$]}=\{(x\_1,...,x\_n)\;|\;\forall i=1,...,n:a\_i\le x\_i\le b\_i\}\$.
`Minimize` finds the minimum value of the expression \$\textit{prices}\cdot x\$ (the total price) and the corresponding vector \$x\$, where we additionally have the restrictions \$x\in\texttt{Cuboid[$0$,$\textit{availability}$]}\$ and \$\sum\_ix\_i=\textit{#people}\$.
```
Minimize[ (* minimize *)
{#.x, (* the total price, given *)
Tr@x==#3}, (* the total number of people *)
x∈Cuboid[0#,#2]] (* and the room availability *)
```
`>` saves one byte over `==` while still returning the same result (albeit with a warning).
[Answer]
# JavaScript (ES6), 104 bytes
*Saved 5 bytes thanks to @tsh*
Expects `(list)(n)`, where the list consists of `[available_i, price_i]` pairs.
Returns `[[booked_1, ..., booked_N], total_cost]`.
```
(p,o=p.map(_=>s=0))=>g=n=>n?g(n-1,p.find(([k,c],i)=>k*!p.some(([K,C])=>K&&C<c)&&++o[s+=c,i])[0]--):[o,s]
```
[Try it online!](https://tio.run/##hY/LCoMwEEX3/Qq7kaSOkvigtTR24dJPCKFIfJCqSWhKf99G/ABXd7hzzsC821/r5EfZb6xN168DW5EFw2yytBa9WOUYwZhVI9Os0s8R6ZiCTQalO4T4BFKA8uvpcraJM0vvywZq4asmDOuHxGEYRYa7iElQAnMi4hjfuQEnVmm0M3OfzGZEA@I8haAQEGyZbXmFgBIiBEYFxqdD2uOpxw9FmuWkLLNbvl0odoP6kewK9f@ufw "JavaScript (Node.js) – Try It Online")
### Commented
```
( p, // outer function taking the list p[]
o = p.map(_ => s = 0) // o[] = booking array, initialize to 0's
// s = total cost
) => //
g = n => // g is a recursive function taking the number of people n
n ? // if there's still at least one room to book:
g( // do a recursive call:
n - 1, // decrement n
p.find(([k, c], i) => // look for a room [k, c] at position i:
k * // if it is still available
!p.some(([K, C]) => // and there is not another room type
K && C < c // that is cheaper and still available
) && // then:
++o[s += c, i] // increment o[i] (i.e. book a room with index i)
// and add c to the total cost
) // end of find() (guaranteed to be successful)
[0]-- // decrement the number of available rooms of this type
) // end of recursive call
: // else:
[o, s] // stop the recursion and return the results
```
[Answer]
# [R](https://www.r-project.org/), 95 bytes
```
function(n,l)list(rowSums(outer(l[2,],y<-sort(unlist(Map(rep,l[2,],l[1,])))[1:n],`==`)),sum(y))
```
[Try it online!](https://tio.run/##XY5BCoMwEEX3nmQGpqAWKZTmCF25FFEbLQTiJEwSiqdPq@66evDfXzzJ4twahonnwYvRi8rvxDoax8Bk0ZoQQdynTWsAl@IiYLuaetoel@AkQuLj8pw8yOLplLarqEfErrpzT6NSIyKFtMKGmFk1hVX6ZXgGDTeqyhJJQ03XE82O37iLErEo/gqPrvwF "R – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 30 bytes
```
1 :'(](],1#.*)1#.]=/u{./:~@#)'
```
[Try it online!](https://tio.run/##VY5BS8NAEIXv@yse9rCJtNuZJlGzUCgKgiAK0msOtWxMW7pbdhOKCP71uEnxUIY3zDyGed@@v1GyxlJDYgqCjpopPH28PvcMLZMqqaY8UbdpbNVy3v2ouf5dTVLZp0KYbeMg1ya02G6CCfCm7bwF49wYi9MmhJ39UkrJy@kiFoP5DjM9LvdICtQpCmRgIiHeHhU4y6kss4d8gbPzh4CdRdsY57/x2bXwnQ1wcXA1juY42M5i/fJ@yShjQpEXREPG@CoaCdMYM9hRBPEPRNdI2RXUcD6C9X8 "J – Try It Online")
Solution is a J adverb which modifies the first input, takes a list of available rooms as the left arg, and a list of prices as the right arg. For example, the first test case is written like:
```
2 2 7 (5 f) 5 3 100
```
Note that the output is a J array, not space-separated standard output -- even though J displays arrays with only a space between elements.
## how
Using the above test case as an example...
* `/:~@#` Copy `#` the right arg elementwise using the left arg as a mask:
```
2 2 7 # 5 3 100
5 5 3 3 100 100 100 100 100 100 100
```
and sort `/:~`:
```
3 3 5 5 100 100 100 100 100 100 100
```
* `u{.` Take "first input" `u` elements from that:
```
3 3 5 5 100
```
* `]=/` Create a table showing where the prices `]` are equal to that:
```
0 0 1 1 0
1 1 0 0 0
0 0 0 0 1
```
* `1#.` Sum rows:
```
2 2 1
```
* `](...)` Taking the last result as the new right arg, and the prices `]` as the new left arg, apply the verb in parens...
* `],1#.*` Append to the new right arg `],` the sum of `1#.` the two args multiplied elementwise `*`:
```
2 2 1 116
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Wẋ$Ṫ$€ẎṢḣµċⱮ³,SḢ$
```
A full program that accepts two arguments, the list of pairs of room price and associated availability, and the number of guests which prints a list containing a list of room allocations, in the same order as the input pairs, and the total price.
**[Try it online!](https://tio.run/##y0rNyan8/z/84a5ulYc7V6k8alrzcFffw52LHu5YfGjrke5HG9cd2qwT/HDHIpX///9HR5vqKBjF6ihEG0NpQwMDHQXz2Nj/pgA "Jelly – Try It Online")**
### How?
```
Wẋ$Ṫ$€ẎṢḣµċⱮ³,SḢ$ - Main Link: list of [price, available] pairs, R; guests, N
€ - for each ([p,a] in R)
$ - last two links as a monad:
$ - last two links as a monad:
W - wrap -> [[p,a]]
ẋ - repeat -> [[[p,a],...p times],[[p,a],...a times]]
Ṫ - tail -> [[p,a],...a times]
Ẏ - tighten from a list of list of pairs to a list of pairs
Ṣ - sort
ḣ - head (to N)
µ - start a new monadic chain, f(X=this list of [price, availability] pairs)
Ɱ³ - for [p,a] in R:
ċ - count occurrences of [p,a] in X
-> allocations
$ - last two links as a monad:
S - sum (e.g. [[1,4],[7,9]] -> [8,13])
Ḣ - head -> total price
, - pair (the allocations and total price)
- implicit print
```
---
Maybe `Wẋ$Ṫ$€ẎṢḣ©ċⱮ⁸®SḢ` is acceptable for 16 - It's all OK until you consider the output when *only a single* priced room type exists: since Jelly list representations of a single element display just that element, we find that, for example, `[[15,7]] 3` would print `345` (rather than `[3]45`). Note, however, that we do know that the leading digits of this output will be the number of guests, so it is "parseable".
[Answer]
# Excel, ~~200~~ 198 bytes
```
=LET(r,A2#,n,ROWS(r)+1,x,SEQUENCE(n),q,{1,2,3,4},s,SORT(IFS(q=3,x,x=n,0,1,r),2),c,INDEX(s,,1),m,A1-MMULT((x>TRANSPOSE(x))*1,c),y,IF(m<c,m,c),INDEX(SORT(IF(q=4,IF(x=1,SUM(y*INDEX(s,,2)),y),s),3),,4))
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 108 bytes
Input is a list of `[number, price]` pairs. The numbers of booked rooms are printed and the total price is returned.
```
f=lambda p,r:p and(print(w:=min((X:=r.pop(0))[0],max(0,p-sum(x for x,y in r if y<X[1]))))or w*X[1]+f(p-w,r))
```
[Try it online!](https://tio.run/##fY3BDoIwDIbvPkVvdLqZTSACkfcgITtgyCKJG83EDJ4eR9Crvfxf2/QrLdNjdGlBfl1N/ezsve@AuK8IOtcj@cFNGKraDg6xqWp/ppFQMtZKzW03o@QkXm@LM5jRw8wXGBx4GAwst6ZVmsWKi3DcmpNBEoF7xtYANRjMObTthUOuI8RMt7xyUFJqzQ77@0QIkfyawA5firBLlNwsKs1kWaZFtunyeB@HKqL8o1o/ "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
Ṣẋ/€,€"ỤẎḣƓZðṪċⱮJ},§{
```
[Try it online!](https://tio.run/##y0rNyan8///hzkUPd3XrP2paowPESg93L3m4q@/hjsXHJkcd3vBw56oj3Y82rvOq1Tm0vPr/f9P/0dGmOkaxOtHGYNLQwEDHPDYWAA "Jelly – Try It Online")
Takes the number of people from STDIN and a list of [price, number] from a command-line argument. Outputs [counts, price].
## Explanation
```
Ṣẋ/€,€"ỤẎḣƓZðṪċⱮJ},§{ Main monadic link
Ṣ Sort
ẋ/€ For each sublist, repeat the first item the second item number of times
,€"Ụ Pair each number with the corresponding index in the original list
Ẏ Flatten by one level => [[price, index], ...]
ḣƓ Take the first [number on STDIN] items
Z Transpose => [prices, indices]
ð Remember this list
Ṫ Take the second item (the list of prices) and remove it from the list
ċⱮJ} Count the occurences of each index of the original list
,§{ Pair with the sum of what remains of the remembered list
```
[Answer]
# [Clojure](https://clojure.org/), ~~152~~ ~~145~~ ~~105~~ 98 bytes
```
#(let[x(take %2(for[[i j](sort %)k(repeat j i)]k))][(for[i %](count(keep #{(i 0)}x)))(apply + x)])
```
[Try it online!](https://tio.run/##bY5Ri8IwEITf@ysGpLCLPlSrqL8l7EPRLaQtSYwRIsf99l4M93JwsOzODh/D3BY/vaKudNcR47qhRZPJlIZZ0R5o9NEYi0no6WNCyzNFDTokTLAsM7OYClm0Qjf/colm1YDNF1l0/J2ZmYYQlje2yCy8ckN3/9QHjHHIAtOY0648ZR2kiP737rtuh7OINEVW4PRx9v2xu177y7FCxfp4lfqTUtn@/7wyFKJ1aXGgERmulFx/AA "Clojure – Try It Online")
Takes input as the listing of rooms with price given first followed by the number of guests, outputs the results as a vector.
### Explanation
First, we `sort` the input vector, by default sort is performed by the first element, which is the price.
Next, we "explode" the input using `repeat`, simulating the actual row of rooms sorted by price, and `take` the first N elements, where N is the number of guests:
```
[[5, 2], [3, 2], [100, 7]], 5 => 3 3 5 5 100 | 100 100 100 100 100 100
```
Then, we loop through the vector of rooms again, and `count` how many of each price do we have in the cheapest collection `x`. After the discussion with OP it was settled that the prices of different room types may not be the same, and therefore, price can be used as the room type ID.
Finally, we add the total sum of the prices to the output.
[Answer]
# JavaScript (ES6), 103 bytes
```
(n,i,t=0,p=[...i].sort((a,b)=>a[1]-b[1]).map(v=>v[0]<n?n-=v[0]:v[0]=n))=>[i.map(([x,y])=>(t+=x*y,x)),t]
```
Similar to the other JavaScript answer, it returns `[[booked_1, ..., booked_N], total_cost]`.
However, it's just a single function that expects `(n, list)` (where `list` is an array of arrays, e.g. `[[1,2],[3,4]]`, just like the examples provided).
Here's the idea:
```
(n, // the number of family members
i, // a list of rooms, e.g. [[1,2],[3,4]]
t=0, // initialize total cost
p=[...i] // shallow copy array
.sort((a,b)=>a[1]-b[1]) // sort the shallow copy
.map(v=> // loop it
v[0]<n // if there is more family members than rooms,
?n-=v[0] // put as many as possible in this room
:v[0]=n // otherwise, put the remaining ones in it
)
// we've now edited the elements of the original array
// so the first number is the amount of people staying
// in that room, not the amount of rooms of that type
// that are available
)=>[ // return an array
i.map(([x,y])=>( // loop the list of rooms
t+=x*y, // add the cost to t
x // return the number of people staying in the room
)
),
t] // finally, the total cost as last element of array
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
UMη⊞OικFθ⊞υ§⌊Φη⁻§κ¹№υλ²IEη№υκ
```
[Try it online!](https://tio.run/##PY7NCoMwEITvfYo9bmALVREPnopQ6EHqXXII1WIwPzYmpW@fJoV2L7PMzLfsfRHuboWKsRdbZ7UWZsKFYAj7cttmJ7x1KAlWxtrDwzrAJ/uGGAjO/mqm@Y29NFIHjRep/Owynpyw4y9fCQpG0NlgfOYUS0NQ5puDk8nsxO4xfZDZf23NtTbGsTgRjGNN0PC0NInMWhJUWSuCmnMejy8lPg "Charcoal – Try It Online") Input is the number of people and a list of [price, count] pairs, and output is a list of counts in the same order. Explanation:
```
UMη⊞Oικ
```
Push the index to each pair, so they are now [price, count, index].
```
Fθ
```
Repeat for each person.
```
⊞υ§⌊Φη⁻§κ¹№υλ²
```
Filter out the prices of the counts that have been used up, find the minimum, and push the original index to the list of persons.
```
IEη№υκ
```
Print the number of persons allotted to each type.
[Answer]
# Java, ~~156~~ 152 bytes
```
r->p->{int l=r.length,o[]=new int[l+1],i,j;for(;p-->0;--r[j][0],++o[j],o[l]+=r[j][1])for(i=j=-1;++i<l;)j=r[i][0]>0&(j<0||r[i][1]<r[j][1])?i:j;return o;}
```
[Try it online!](https://tio.run/##lZCxTsMwEIb3PoUnlBDHcmgraJ0EMYDEwNQx8mDapLVx7Mhxiqo0zx6cklIQC3i5u/@/031nwfYsFJu3npeVNhYIV6PGcomKRq0t1wpdk8kv02lV8yr5Gqwlq2vwwrhqJ8C9Ua4tsy7sNd@A0pneyhquthkFzGxr/7N3eE/jmpgrm9GMwmdlf2ppCoqkN2FahWnrFCATg2SutnYHdUYTlb@DoVEGEYUcClJo45EqDFNMwtBkgmaYwiDQLnMDkgbJSYyoP3TyRCRhRIKAx5L4wnl8GEjxlSdifDye6ojG55l7vhTE5LYxCmjS9edDyNdJD8awQ41qa3JWegViVSUP3hnT3di2NxDMOwiGOB3iLQQRxl3nj81z30cO7pGtd97qUNu8RLqxy2XlPtFK5V@WXVw0mp7/L5RoOsOLxfRuNjDNHYTDiVyKv/NE@E9A3aTrPwA)
*Saved 4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904)*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ε`и}{˜I£©¹€нsk{γ€g®Oª
```
First input as a list of pairs \$[price, amount]\$. Output as an array (with the last item being the total price).
[Try it online](https://tio.run/##yy9OTMpM/f//3NaECztqq0/P8Ty0@NDKQzsfNa25sLc4u/rcZiAr/dA6/0Or/v@PjjY1NTDQMTQ2MbC0NLYwMYrViQYKAEViY7kMDQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmWCvpJCYl6KgZA9kPGqbBGRUJoS5hP4/tzXhwo7a6tNzIg8tPrQy4lHTmgt7i7Orz20GstIPrfM/tOq/zv9oIDA1NTDQMTQ2MbC0NLYwMYrViQYKAEViY3UMDWJ1FEBKdEDCxmDSEChnDpQzjY0FAA).
**Explanation:**
```
ε # Map over each pair in the first (implicit) input-list:
` # Pop and push both values separated to the stack
и # Repeat the first item the second item amount of times as list
}{ # After the map: sort the list based on their first items
˜ # Then flatten the list of lists
I£ # Only leave the second input amount of leading values
© # Store this list in variable `®` (without popping)
¹ # Push the first list of pairs again
€н # Only leave the first item (the price) of each pair
s # Swap so list `®` is at the top of the stack
k # Get for each the index in the list of prices
{ # Sort these indices from lowest to highest
γ # Split it into groups of equivalent adjacent values
€g # Get the length of each group
® # Push list `®` again
O # Pop and push its sum
ª # Append it to the list of lengths
# (after which the result is output implicitly)
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.