text
stringlengths 180
608k
|
---|
[Question]
[
Note: this challenge has been posted [on the sandbox](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/14028#14028).
# Introduction
This challenge is inspired by [2009 Putnam B1](https://artofproblemsolving.com/community/c7h316672p1703568), a problem in an undergraduate mathematics competition. The problem is as follows:
>
> Show that every positive rational number can be written as a quotient of products of factorials of (not necessarily distinct) primes. For example,
>
>
> [](https://i.stack.imgur.com/ykS4p.png)
>
>
>
# Challenge
Your challenge is to take a pair of relatively prime positive integers, representing the numerator and denominator of a positive rational number (or just the rational number itself) as input, and output two lists (or arrays, etc.) of prime numbers so that the inputted rational number is equal to the ratio of the product of the factorials of the primes in the first list to the product of the factorials of the primes in the second list.
### Notes
* There may not be any primes that contained both in the first list and in the second list; however, a prime may appear as many times as one wishes in either list.
* The inputs can be assumed to each be (nonstrictly) between 1 and 65535; however, it cannot be assumed that the factorials of the numbers you will need to output will be in this range.
# Example Input and Output
Here are examples of legal inputs and outputs.
```
input=>output
10,9 => [2,5],[3,3,3]
2,1 => [2],[]
3,1 => [3],[2]
1,5 => [2,3,2],[5] (elements of a list may be in any order)
3,2 => [3],[2,2]
6,1 => [3],[]
```
The inputs (2,2), (0,3), (3,0), (3,6) and (1,65536) are illegal inputs (i.e. your program doesn't need to behave in any particular way on them). Here are some examples of illegal outputs:
```
1,2 => [2],[2,2] (2 is in both returned lists)
5,2 => [5],[2,4] (4 is not prime)
2,1 => [2],[1] (1 is not prime either)
3,2 => [3],[2] (3!/2! = 3, not 3/2)
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score in bytes wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~54~~ ~~53~~ ~~48~~ ~~46~~ ~~40~~ ~~35~~ ~~33~~ ~~32~~ 28 bytes
```
[D¿÷Z#DÓ€gZD<ØŠQ*DˆR!*]¯øεʒĀ
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/2uXQ/sPbo5RdDk9@1LQmPcrm8IziqEAtl9NtQYpasYfWH95xbuupSUcagCotdRQMDWIB "05AB1E – Try It Online") Edit: Saved 2 bytes thanks to @ASCII-only. Saved ~~1~~ ~~2~~ ~~3~~ 4 bytes thanks to @Emigna. (I only need to save one more and I'm down to half my original byte count!) Explanation:
```
[ Begin an infinite loop
D¿÷ Reduce to lowest terms
Z# Exit the loop if the (largest) value is 1
DÓ€g Find the index of the largest prime factor of each value
Z Take the maximum
D<ØŠ Convert index back to prime and save for later
Q Convert to an pair of which value had the largest prime factor
* Convert to an pair with that prime factor and zero
Dˆ Save the pair in the global array for later
R!* Multiply the other input value by the factorial of the prime
] End of infinite loop
¯ø Collect all the saved primes
εʒĀ Forget all the saved 0s
```
[Answer]
# Mathematica, ~~175~~ ~~177~~ ~~169~~ ~~154~~ 108 bytes
```
Join@@@Table[x[[1]],{s,{1,-1}},{x,r@#},x[[2]]s]&@*(If[#==1,1,{p,e}=Last@(r=FactorInteger)@#;p^e#0[p!^-e#]]&)
```
[Try it online!](https://tio.run/##Dc5BC4IwGIDhv7IYhMYnNkFLYvBBEBgdOnQbE5bMEnLKnCCM/Xbz9B6ey9sr99W9cl2j1nY2fL0PnUHEl3r/tFiEYFKCn8AzSFgI4BewSANskkk5yT0eoqoVlHMGDPwIOvCHmhxGlt9U4wZbGac/2sZIL2Ot6VGMuzrRVMp9vD5tZxxeh9/cm9tge7EtkBSJZ8e0BFKe0vOWDAhLCyBFnmcsyPUP "Wolfram Language (Mathematica) – Try It Online")
### How it works
This is the composition of two functions. The first, which ungolfs to
```
If[# == 1,
1,
{p,e} = Last[FactorInteger[#]];
p^e * #0[p!^-e * #]
]&
```
is a recursive function for actually computing the desired factorization. Specifically, given a rational input `x`, we compute the primes whose factorials should be in the numerator and denominator, and return the fraction with all of those primes multiplied together. (For example, on input `10/9 = 2!*5!/(3!*3!*3!)`, we return `10/27 = 2*5/(3*3*3)`.)
We do this by dealing with the largest prime factor at every step: if pe occurs in the factorization of x, we make sure p!e occurs in the factorial-factorization, and recurse on x divided by p!e.
(Earlier, I had a more clever strategy that avoids large numbers by looking at the previous prime number before p, but Mathematica can handle numbers as big as 65521! easily, so there's no point. The old version you can find in the history is much faster: on my computer, it took 0.05 seconds on inputs that this version handles in 1.6 seconds.)
The second function turns the output of the first function into lists of primes.
```
Join @@@
Table[x[[1]],
{s,{1,-1}},
{x,FactorInteger[#]},
x[[2]]*s
]&
```
For `s=1` (positive powers) and `s=-1` (negative powers), and for each term `{prime,exponent}` in the factorization `r@#`, we repeat the prime number `prime` `exponent*s` many times.
# Noncompeting version with ~~109~~ 62 bytes
```
If[#==1,∇1=1,{p,e}=Last@FactorInteger@#;(∇p)^e#0[p!^-e#]]&
```
Same as above, but instead of giving output as a list, gives output as an expression, using the ∇ operator (because it has no built-in meaning) as a stand-in for factorials. Thus, an input of `10/9` gives an output of `(∇2*∇5)/(∇3)^3` to represent `(2!*5!)/(3!)^3`.
This is shorter because we skip the second part of the function.
---
*+2 bytes: the assignment `f=First` has to be done in the right place to keep Mathematica from getting upset.*
*-8 bytes: fixed a bug for integer outputs, which actually made the code shorter.*
*-15 bytes: `FactorInteger` returns sorted output, which we can take advantage of.*
*-46 bytes: we don't actually need to be clever.*
[Answer]
## Python 2, ~~220~~ ~~202~~ ~~195~~ 183 bytes
```
g=lambda a,b:a and g(b%a,a)or b;n,d=input();m=c=()
while n+d>2:
t=n*d;f=p=2
while t>p:
if t%p:p+=1;f*=p
else:t/=p
if n%p:c+=p,;n*=f
else:m+=p,;d*=f
t=g(n,d);n/=t;d/=t
print m,c
```
[Try it online!](https://tio.run/##JY3LCoMwEEXX5itmI/gIWN01YfyXaHwEzDjYKaVfnwa7OVzOWVz@yn7SkNKGh4uTd@D0ZDLJw1ZNpdOuPi@YLGmPgfgtVW0jzljV6rOHYwFq/TgYBYLUeLsi46Dgn2Rko4qwgpRsuMXerg2yKpbjtRjp8oQcKce5RdaWGlwV3DXewt9CcKvyfW2pQ7E@Q/EVSCDqOaWnhv7xAw "Python 2 – Try It Online") Edit: Saved ~~18~~ 25 bytes thanks to @Mr.Xcoder. Saved 12 bytes thanks to @JonathanFrech.
] |
[Question]
[
The card game [War](https://en.wikipedia.org/wiki/War_(card_game)) is interesting in that the final outcome is entirely determined by the initial arrangement of the deck, so long as certain rules are followed for the order in which cards are picked up from the playing field and moved to decks. In this challenge, there will only be 2 players, simplifying things greatly.
## The Game
1. Each player is dealt a deck of 26 cards.
2. Each player places the top card in their deck face-up. The player with the higher-ranking card (`Ace > King > Queen > Jack > 10 > 9 > 8 > 7 > 6 > 5 > 4 > 3 > 2`) wins the round, and places their card on top of their opponent's card, flips them over, and adds them to the bottom of their deck (so their winning card is on the bottom of the deck, and the other player's losing card is just above it). This is done until one of the players runs out of cards.
* If the cards are of equal rank, then each player places the top 2 cards of their deck face-up on top of their previous card (so that the card that was on top of the deck is the second card in the stack, and the card that was second-from-top is on top). Then, the ranks (of the top card of each stack) are compared again, and the winner places their entire stack on top of the loser's entire stack, turns the stack upside-down, and places it on the bottom of their deck. If there is another tie, more cards are played in the same way, until a winner is chosen or one player runs out of cards.
If at any point one of the players needs to draw a card from their deck, but their deck is empty, they immediately lose the game.
## The Challenge
Given two lists of cards in the players' decks, in any convenient format, output a truthy value if Player 1 wins, and a falsey value if Player 2 wins.
For convenience, a 10 card will be represented with a `T`, and face cards will be abbreviated (`Ace -> A, King -> K, Queen -> Q, Jack -> J`), so that all cards are one character long. Alternatively, ranks may be represented with decimal integers 2-14 (`Jack -> 11, Queen -> 12, King -> 13, Ace -> 14`) or hex digits 2-E (`10 -> A, Jack -> B, Queen -> C, King -> D, Ace -> E`). Since suits don't matter, suit information will not be given.
* You may assume that all games will terminate at some point (though it may take a very long time), and one player will always run out of cards before the other.
* Each player places cards simultaneously, and one card at a time, so there is never any ambiguity about which player ran out of cards first.
## Test Cases
The test cases use `23456789ABCDE` to represent the ranks (in ascending order).
```
D58B35926B92C7C4C7E8D3DAA2, 8E47C38A2DEA43467EB9566B95 -> False
669D9D846D4B3BA52452C2EDEB, E747CA988CC76723935A3B8EA5 -> False
5744B95ECDC6D325B28A782A72, 68394D9DA96EBBA8533EE7C6C4 -> True
87DB6C7EBC6C8D722389923DC6, E28435DBEBEA543AA47956594A -> False
589EAB9DCD43E9EC264A5726A8, 48DC2577BD68AB9335263B7EC4 -> True
E3698D7C46A739AE5BE2C49286, BB54B7D78954ED526A83C3CDA2 -> True
32298B5E785DC394467D5C9CB2, 5ED6AAD93E873EA628B6A4BC47 -> True
B4AB985B34756C624C92DE5E97, 3EDD5BA2A68397C26CE837AD48 -> False
9A6D9A5457BB6ACBC5E8D7D4A9, 73E658CE2C3E289B837422D463 -> True
96E64D226BC8B7D6C5974BAE32, 58DC7A8C543E35978AEBA34D29 -> True
C2978A35E74D7652BA9762C458, 9A9BB332BE8C8DD44CE3DE66A5 -> False
BEDB44E947693CD284923CEA82, 8CC3B75756255A683A6AB9E7DD -> False
EEDDCCBBAA8877665544332299, EEDDCCBBAA9988776655443322 -> False
EEDDCCBBAA9988776655443322, DDCCBBAA9988776655443E3E22 -> True
```
## Reference Implementation
This reference implementation is written in Python 3, and takes input in the same format as the test cases (except separated by a newline instead of a comma and a space).
```
#!/usr/bin/env python3
from collections import deque
p1, p2 = [deque(s) for s in (input(),input())]
print(''.join(p1))
print(''.join(p2))
try:
while p1 and p2:
p1s = [p1.popleft()]
p2s = [p2.popleft()]
while p1s[-1] == p2s[-1]:
p1s.append(p1.popleft())
p2s.append(p2.popleft())
p1s.append(p1.popleft())
p2s.append(p2.popleft())
if p1s[-1] > p2s[-1]:
p1.extend(p2s+p1s)
else:
p2.extend(p1s+p2s)
except IndexError:
pass
finally:
print(len(p1) > 0)
```
[Answer]
## JavaScript (ES6), 134 bytes
```
f=([p,...r],[q,...s],t=[],u=[],v)=>!q||p&&(v|p==q?f(r,s,[...t,p],[...u,q],!v):p>q?f([...r,...u,q,...t,p],s):f(r,[...s,...t,p,...u,q]))
```
```
<div oninput=o.checked=f(p.value,q.value)>
Player 1's cards: <input id=p><br>
Player 2's cards: <input id=q><br>
<input id=o type="checkbox"> Player 2 loses
```
Return `undefined` if Player 2 wins, `true` otherwise. Accepts comparable iterators, usually arrays of integers or strings of hex characters. Answer is composed of over 22% of `.` characters, which I think must be a record for me.
[Answer]
# Python, 160 (155?) bytes
```
f=lambda x,y,z=1:f(*((x,y,z+2),(x[z:]+y[:z]+x[:z],y[z:]),(x[z:],y[z:]+x[:z]+y[:z]))[(x[z-1]>y[z-1])+(x[z-1]<y[z-1])*2])if len(y)>z<len(x)else len(x)>len(y)
```
This solution is theoretically valid, but it require the default python maximum recursion depth to be increased for some of the test cases.
The second solution is 5 bytes longer, but work for all the test cases.
```
f=lambda x,y,z=1:(f(x,y,z+2)if x[z-1]==y[z-1]else f(x[z:]+y[:z]+x[:z],y[z:])if x[z-1]>y[z-1]else f(x[z:],y[z:]+x[:z]+y[:z]))if len(y)>z<len(x)else len(x)>len(y)
```
Edit: Ungolfed solution 1:
```
def f(x,y,z=1):
if len(y)<z>len(x):
return len(x)>len(y)
else:
return f(*(
(x,y,z+2),
(x[z:],y[z:]+x[:z]+y[:z]),
(x[z:]+y[:z]+x[:z],y[z:])
)[(x[z-1]>y[z-1])+(x[z-1]<y[z-1])*2])
```
[Answer]
# Python, 261 to 265 bytes
```
def f(a,b):
if a==""or b=="":return b==""
p=a[0];q=b[0];a=a[1:];b=b[1:]
if p>q:a+=q+p
if p<q:b+=p+q
while p[-1]==q[-1]:
if len(a)<2 or len(b)<2:return len(b)<2
v=a[1];w=b[1];p+=a[0:2];q+=b[0:2];a=a[2:];b=b[2:]
if v>w:a+=q+p
if v<w:b+=p+q
return f(a,b)
```
As posted, this is 265 bytes and it works in both Python 2 and Python 3. You can save 4 bytes in Python 2 by replacing the spaces with a single tab in the while loop.
[Try it online](https://repl.it/CZFD)
[Answer]
# Haskell, 372
My first Haskell Program
(It's my first functional programming, too...)
```
w[]_=False
w _[]=True
w a b=if length j==0 then a>b else w (drop(d$head j)a++fst(head j))(drop(d$head j)b++snd(head j))where j=p a b
d(a,b)=quot(maximum[length a,length b])2
f (Just a)=a
p a b=map f$filter(/=Nothing)[t(a!!x,take(x+1)a,b!!x,take(x+1)b)|x<-[0,2..minimum[length a,length b]-1]]
t(a,b,c,d)=if a==c then Nothing else if a>c then Just(d++b,[])else Just([],b++d)
```
I'd love to have tips on how to improve.
Usage:
```
w "D58B35926B92C7C4C7E8D3DAA2" "8E47C38A2DEA43467EB9566B95"
w "669D9D846D4B3BA52452C2EDEB" "E747CA988CC76723935A3B8EA5"
w "5744B95ECDC6D325B28A782A72" "68394D9DA96EBBA8533EE7C6C4"
w "87DB6C7EBC6C8D722389923DC6" "E28435DBEBEA543AA47956594A"
w "589EAB9DCD43E9EC264A5726A8" "48DC2577BD68AB9335263B7EC4"
w "E3698D7C46A739AE5BE2C49286" "BB54B7D78954ED526A83C3CDA2"
w "32298B5E785DC394467D5C9CB2" "5ED6AAD93E873EA628B6A4BC47"
w "B4AB985B34756C624C92DE5E97" "3EDD5BA2A68397C26CE837AD48"
w "9A6D9A5457BB6ACBC5E8D7D4A9" "73E658CE2C3E289B837422D463"
w "96E64D226BC8B7D6C5974BAE32" "58DC7A8C543E35978AEBA34D29"
w "C2978A35E74D7652BA9762C458" "9A9BB332BE8C8DD44CE3DE66A5"
w "BEDB44E947693CD284923CEA82" "8CC3B75756255A683A6AB9E7DD"
w "EEDDCCBBAA8877665544332299" "EEDDCCBBAA9988776655443322"
w "EEDDCCBBAA9988776655443322" "DDCCBBAA9988776655443E3E22"
```
Haskell is quick... :)
```
real 0m0.039s
user 0m0.022s
sys 0m0.005s
```
] |
[Question]
[
The challenge is to identify the missing number in a string of undelimited integers.
You are given a string of digits (valid input will match the regular expression `^[1-9][0-9]+$`). The string represents a sequence of integers. For example, `1234567891011`. All numbers in the sequence are in the range from `1` and `2147483647` inclusive.
The sequence is a series of numbers where each number is one greater than its predecessor. However, this sequence *may* contain one and only one missing number from the sequence. It is possible that a given string also contains no missing numbers from the sequence. The string will always contain at least two numbers from the sequence.
The code must output or return the missing value, or `0` (this is a `0` - not a falsy value) in the event that the no missing values were found.
The following are valid inputs and their output/return:
```
input output actual sequence (for refrence)
123467 5 1 2 3 4 _ 6 7
911 10 9 __ 11
123125126 124 123 ___ 125 126
8632456863245786324598632460 8632458 8632456 8632457 _______ 8632459 8632460
123 0 1 2 3
8632456863245786324588632459 0 8632456 8632457 8632458 8632459
```
While all of this is described as a 'string' as input, if the language is capable of handling arbitrarily large numbers (`dc` and `mathematica`, I'm looking at you two) the input may be an arbitrarily large number instead of a string if that makes the code easier.
For reference, this was inspired by the Programmers.SE question: [Find missing number in sequence in string](https://softwareengineering.stackexchange.com/q/310242/40980)
[Answer]
## Haskell, ~~115~~ 112 bytes
```
g b|a<-[b!!0..last b]=last$0:[c|c<-a,b==filter(/=c)a]
maximum.map(g.map read.words.concat).mapM(\c->[[c],c:" "])
```
The first line is a helper function definition, the second is the main anonymous function.
[Verify test cases](http://ideone.com/CrtKf2) (I had to run shorter tests because of time restrictions).
## Explanation
This is a brute force solution: split the string into words in all possible ways, parse the words to integers, see whether it's a range with one element missing (returning that element, and `0` otherwise), and take the maximum over all splittings.
The range-with-missing-element check is done in the helper function `g`, which takes a list `b` and returns the sole element in the range `[head of b..last of b]` that's not in `b`, or `0` if one doesn't exist.
```
g b| -- Define g b
a<-[b!!0..last b]= -- (with a as the range [head of b..last of b]) as:
last$0:[...] -- the last element of this list, or 0 if it's empty:
c|c<-a, -- those elements c of a for which
b==filter(/=c)a -- removing c from a results in b.
mapM(\c->[[c],c:" "]) -- Main function: Replace each char c in input with "c" or "c "
map(...) -- For each resulting list of strings:
g.map read.words.concat -- concatenate, split at spaces, parse to list of ints, apply g
maximum -- Maximum of results (the missing element, if exists)
```
[Answer]
# JavaScript (ES6), 117 bytes
```
s=>eval(`for(i=l=0;s[i];)for(n=s.slice(x=i=m=0,++l);s[i]&&!x|!m;x=s.slice(x?i:i+=(n+"").length).search(++n))m=x?n:m`)
```
## Explanation
Fairly efficient approach. Finishes instantly for all test cases.
Gets each substring from the beginning of the input string as a number `n` and initialises the missing number `m` to `0`. It then repeatedly removes `n` from the start of the string, increments `n` and searches the string for it. If `index of n != 0`, it checks `m`. If `m == 0`, set `m = n` and continue, if not, there are multiple missing numbers so stop checking from this substring. This process continues until the entire string has been removed.
```
var solution =
s=>
eval(` // use eval to use for loops without writing {} or return
for(
i= // i = index of next substring the check
l=0; // l = length of initial substring n
s[i]; // if it completed successfully i would equal s.length
)
for(
n=s.slice( // n = current number to search for, initialise to subtring l
x= // x = index of n relative to the end of the previous n
i= // set i to the beginning of the string
m=0, // m = missing number, initialise to 0
++l // increment initial substring length
);
s[i]&& // stop if we have successfully reached the end of the string
!x|!m; // stop if there are multiple missing numbers
x= // get index of ++n
s.slice( // search a substring that starts from the end of the previous
// number so that we avoid matching numbers before here
x?i: // if the previous n was missing, don't increment i
i+=(n+"").length // move i to the end of the previous number
)
.search(++n) // increment n and search the substring for it's index
)
m=x?n:m // if the previous number was missing, set m to it
`) // implicit: return m
```
```
<input type="text" id="input" value="8632456863245786324598632460" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# JavaScript (ES6) 114
```
s=>eval("for(d=0,n=-9,z=s;z=z.slice((n+'').length);z.search(++n)?z.search(++n)?n=(z=s).slice(x=0,++d):x=n-1:0);x")
```
**Less golfed** and explained
```
f=s=>{
d = 0 // initial digit number, will be increased to 1 at first loop
n = -9 // initial value, can not be found
z = s // initializa z to the whole input string
// at each iteration, remove the first chars of z that are 'n'
// 'd' instead of 'length' would be shorter, but the length can change passing from 9 to 10
for(; z=z.slice((n+'').length); )
{
++n; // n is the next number expected in sequence
if (z.search(n) != 0)
{
// number not found at position 0
// this could be the hole
// try to find the next number
++n;
if (z.search(n) != 0)
{
// nope, this is not the correct sequence, start again
z = s; // start to look at the whole string again
x = 0; // maybe I had a candidate result in xm but now must forget it
++d; // try a sequence starting with a number with 1 more digit
n = z.slice(0,d) // first number of sequence
}
else
{
// I found a hole, store a result in x but check the rest of the string
x = n-1
}
}
}
return x // if no hole found x is 0
}
```
**Test**
```
F=s=>eval("for(d=0,n=-9,z=s;z=z.slice((n+'').length);z.search(++n)?z.search(++n)?n=(z=s).slice(x=0,++d):x=n-1:0);x")
console.log=x=>O.textContent+=x+'\n'
elab=x=>console.log(x+' -> '+F(x))
function test(){ elab(I.value) }
;['123467','911','123125126','8632456863245786324598632460',
'123','124125127','8632456863245786324588632459']
.forEach(t=>elab(t))
```
```
<input id=I><button onclick='test()'>Try your sequence</button>
<pre id=O></pre>
```
[Answer]
# C, ~~183~~ ~~168~~ ~~166~~ 163 bytes
```
n,l,c,d,b[9];main(s,v,p)char**v,*p;{for(;s>1;)for(d=s=0,n=atoi(strncpy(b,p=v[1],++l)),p+=l;*p&&s<2;)p+=memcmp(p,b,c=sprintf(b,"%d",++n))?d=n,s++:c;printf("%d",d);}
```
## Ungolfed
```
n,l,c,d,b[9];
main(s,v,p)char**v,*p;
{
/* Start at length 1, counting upwards, while we haven't
found a proper number of missing numbers (0 or 1) */
for(;s>1;)
/* Start at the beginning of the string, convert the
first l chars to an integer... */
for(d=s=0,n=atoi(strncpy(b,p=v[1],++l)),p+=l;*p&&s<2;)
/* If the next number is missing, then skip, otherwise
move forward in the string.... */
p+=memcmp(p,b,c=sprintf(b,"%d",++n))?d=n,s++:c;
printf("%d",d); /* print the missing number */
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
ŒṖḌI’ḂƑƊƇḢ.ịr/ḟƲ
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7pz3c0eP5qGHmwx1NxyYe6zrW/nDHIr2Hu7uL9B/umH9s03@Xw@2PmtaAVM74/9/QyNjEzFxHwdLQUEcByDE0MjU0MgMzAQ "Jelly – Try It Online")
Input as a list of digits. Outputs a singleton list `[a]` containing the missing element, or `[]` if there isn't one. [+1 byte](https://tio.run/##y0rNyan8///opIc7pz3c0eP5qGHmwx1NxyYe6zrW/nDHIr2Hu7uL9B/umH9sE5D33@Vw@6OmNSDFM/7/NzQyNjEz11GwNDTUUQByDI1MDY3MwEwA) to output `0` instead, and [+1 byte](https://tio.run/##y0rNyan8/9/l6KSHO6c93NHj@ahh5sMdTccmHus61v5wxyK9h7u7i/Qf7ph/bBOQ9/9w@6OmNSC1M/7/NzQyNjEz11GwNDTUUQByDI1MDY3MwEwA) to input as a single integer.
## How it works
```
ŒṖḌI’ḂƑƊƇḢ.ịr/ḟƲ - Main link. Takes a list of digits D on the left
ŒṖ - All partitions of D
Ḍ - Convert back to integers
ƊƇ - Keep those for which the following is true:
I - Forward differences
’ - Decrement
ḂƑ - This list is invariant under bit i.e. all 1 or 0
Ḣ - Take the first, R
Ʋ - Over R:
.ị - Take the first and last elements
r/ - Yield a range between them
ḟ - Remove the elements that are in R
This returns the single element that is in the range but not R
```
] |
[Question]
[
In [this challenge](https://codegolf.stackexchange.com/q/50240/32700) posed by xnor, we were asked to implement XOR multiplication. In this challenge the goal is to find the first `n` XOR primes. XOR primes are very similar to regular primes as you can see by the following definitions:
**Definition of Prime Number:** A positive number greater than 1 which cannot be formed through multiplication of two numbers except through the multiplication of 1 and itself.
**Definition of XOR Prime:** A positive number greater than 1 which cannot be formed through XOR multiplication of two numbers except through the XOR multiplication of 1 and itself. Note that the XOR primes compose oeis sequence [A014580](https://oeis.org/A014580).
XOR multiplication is defined as binary long multiplication without carrying. You can find more information about XOR multiplication in [xnor's challenge](https://codegolf.stackexchange.com/q/50240/32700).
## Input:
An integer `n`.
## Output:
The first `n` XOR primes.
### Here are the XOR primes under 500:
```
2 3 7 11 13 19 25 31 37 41 47 55 59 61 67 73 87 91 97 103 109 115 117 131 137 143 145 157 167 171 185 191 193 203 211 213 229 239 241 247 253 283 285 299 301 313 319 333 351 355 357 361 369 375 379 391 395 397 415 419 425 433 445 451 463 471 477 487 499
```
[Answer]
# Pyth, 26 bytes
```
.fq2/muxyG*Hhdjed2 0^SZ2ZQ
```
[Demonstration](https://pyth.herokuapp.com/?code=.fq2%2FmuxyG%2aHhdjed2+0%5ESZ2ZQ&input=10&debug=0)
To test whether a number is a XOR-prime, we generate the complete multiplication table up to that number using the algorithm from [here](https://codegolf.stackexchange.com/a/50245/20080), and then count how many times that number appears. If it's exactly 2, the number is prime.
Then, `.f` returns the first n primes.
[Answer]
## Ceylon, 166 bytes
Of course this can't compete with Pyth & Co ...
```
{Integer*}p(Integer n)=>loop(2)(1.plus).filter((m)=>{for(i in 2:m-2)for(j in 2:m-2)if(m==[for(k in 0:64)if(j.get(k))i*2^k].fold(0)((y,z)=>y.xor(z)))i}.empty).take(n);
```
Formatted:
```
{Integer*} p(Integer n) =>
loop(2)(1.plus).filter((m) => {
for (i in 2 : m-2)
for (j in 2 : m-2)
if (m == [
for (k in 0:64)
if (j.get(k))
i * 2^k
].fold(0)((y, z) => y.xor(z))) i
}.empty).take(n);
```
This creates an infinite iterable of integers (starting with 2), filters it by checking if a number is an XOR-prime, and takes the first `n` elements of that.
This filtering works by looping over all elements from 2 to m-1 (which are m-2 ones), and checking each pair if the xor-product give `m`. If the iterable created by that is empty, `m` is an xor-prime, and therefore included.
The xor-product itself is calculated using the same algorithm (and almost the same code) as in [my answer for the XOR product calculation](https://codegolf.stackexchange.com/a/66942/2338).
[Answer]
# Mathematica, ~~100~~ 99 bytes
As noted by xnor, XOR multiplication is just multiplication in the polynomial ring \$\mathbb{F}\_2[x]\$.
```
For[p=i=0,i<#,If[IrreduciblePolynomialQ[++p~IntegerDigits~2~FromDigits~x,Modulus->2],Print@p;i++]]&
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 74 bytes
Saved 4 bytes thanks to [Charles](https://codegolf.stackexchange.com/users/2605/charles).
As noted by xnor, XOR multiplication is just multiplication in the polynomial ring \$\mathbb{F}\_2[x]\$.
```
n->p=0;while(n,if(polisirreducible(Mod(Pol(binary(p++)),2)),print(p);n--))
```
[Try it online!](https://tio.run/##JchLCoAwDADRq7hMsIXqVuoNBK/grxooaYiKePpacDGLNzIp2V1yqHyV2fbiXfccFDdgQwEkRTpJdVvvheZyh7TCmCLMxJO@IHWNaNqSKPEFgh1bi5h/BmicK/oA "Pari/GP – Try It Online")
Basically the same as [my Mathematica answer](https://codegolf.stackexchange.com/a/67005/9288), but PARI/GP has shorter function names.
[Answer]
# Julia, 116 bytes
```
f(a,b)=b%2*a$(b>0&&f(2a,b÷2))
n->(A=[i=2];while endof(A)<n i+=1;i∈[f(a,b)for a=2:i-1,b=2:i-1]||push!(A,i)end;A[n])
```
The primary function is the anonymous function on the second line. It calls a helper function `f` (which is incidentally my submission for xnor's challenge).
Ungolfed:
```
function xor_mult(a::Integer, b::Integer)
return b % 2 * a $ (b > 0 && f(2a, b÷2))
end
function xor_prime(n::Integer)
# Initialize an array to hold the generated XOR primes as well as
# an index at which to start the search
A = [i = 2]
# Loop while we've generated fewer than n XOR primes
while endof(A) < n
# Increment the prime candidate
i += 1
# If the number does not appear in the XOR multiplication
# table of all numbers from 2 to n-1, it's an XOR prime
i ∈ [xor_mult(a, b) for a in 2:i-1, b in 2:i-1] || push!(A, i)
end
# Return the nth XOR prime
return A[n]
end
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
BJ’2*U×B{×^/ðþFċ=2
ÇƇ
```
[Try it online!](https://tio.run/##ASsA1P9qZWxsef//QkrigJkyKlXDl0J7w5deL8Oww75GxIs9MgrDh8aH////MTAw "Jelly – Try It Online")
## How it works
```
ÇƇ - Main link. Takes an integer n on the left
Ƈ - Yield the range [1, 2, ..., n] and filter on:
Ç - The helper function
BJ’2*U×B{×^/ðþFċ=2 - Help function. Takes an integer k on the left
ð - Define a dyadic link f(i, j):
B - Convert i to binary
J - Replace with their indices
’ - Decrement each
2* - 2 to the power of each
U - Reverse
B{ - Yield i in binary
× - Multiply the powers by the bits
× - Multiply by j
^/ - Reduce by XOR
þ - Yield the range [1, 2, ..., k] and create a multiplication table using f(i, j)
F - Flatten
ċ - Count the occurrences of k
=2 - Does this equal 2?
```
[Answer]
# [R](https://www.r-project.org/), 138 bytes
```
function(n,f=function(x,y)`if`(y,bitwXor(x*y%%2,2*f(x,y%/%2)),0)){while(n)if(sum(outer(1:(T=T+1),1:T,Vectorize(f))==T)<3)F[1+(n=n-1)]=T;F}
```
[Try it online!](https://tio.run/##Vc5BCsIwEEDR0wRm2ogm4qY6254giCDSYklwwCaSpjRVPHvFjeDy8zY/Lr7JITaPyL0daHGj7xIHD146@kWWM7bsWpjlldN0ChFyMQuhpS7cV8VaaES5QXxNN75b8MgOhrGHMCYbQVVgyJQKpaqMPNouhchPCw6RyOBhi/VZleDJrxReyOzr998Y6B0uHw "R – Try It Online")
Outputs the first `n` XOR primes in reverse order.
Sequentially tests each integer `T` (starting at 2) for XOR primality by checking whether the results of all values of 1..`T` XOR multiplied (using [helper function `f`](https://codegolf.stackexchange.com/a/218243/95126)) by 1..`T` contain only 2 instances of `T`.
] |
[Question]
[
A grid-filling meander is a closed path that visits every cell of a square \$N \times N\$ grid at least once, never crossing any edge between adjacent cells more than once and never crossing itself. For example:

Once filled, each cell of the grid can be represented by one of the following 8 tiles:

Numbered this way, the tiles of the above meander can be represented by this matrix:
```
5 6 5 6
4 8 3 2
5 7 6 2
4 3 4 3
```
Your task is to complete a grid-filling meander given an incomplete set of tiles. For example, the incomplete meander:

...which can be represented using `0`s for missing tiles:
```
5 0 0 0 6
0 0 7 0 0
0 0 0 0 3
2 4 0 0 0
0 0 3 0 0
```
...could be completed like this:

...i.e.:
```
5 6 5 1 6
4 8 7 6 2
5 7 7 7 3
2 4 8 8 6
4 1 3 4 3
```
### Specifications
* The input will always have at least \$1\$ and at most \$N^2\$ (non-empty) tiles, where \$2 \le N \le 7\$.
* You may use any set of values to represent the tiles, as long as it's specified in your answer.
* Your input and output may be in any format and order, as long as it's specified in your answer.
* At least one valid solution will exist for all inputs (i.e. you don't need to handle invalid input).
* [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods "Default for Code Golf: Input/Output methods") apply.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default "Loopholes that are forbidden by default") are forbidden.
* Explanations, even for "practical" languages, are encouraged.
### Test cases
>
> Input ([Θ](https://observablehq.com/@jrunning/grid-filling-meanders#0,6,0,0)):
>
>
>
> ```
> 0 6
> 0 0
>
> ```
>
> Output ([Θ](https://observablehq.com/@jrunning/grid-filling-meanders#5,6,4,3)):
>
>
>
> ```
> 5 6
> 4 3
>
> ```
>
>
>
> Input ([Θ](https://observablehq.com/@jrunning/grid-filling-meanders#5,6,5,6,4,0,3,2,5,7,6,2,4,3,4,3)):
>
>
>
> ```
> 5 6 5 6
> 4 0 3 2
> 5 7 6 2
> 4 3 4 3
>
> ```
>
> Output ([Θ](https://observablehq.com/@jrunning/grid-filling-meanders#5,6,5,6,4,8,3,2,5,7,6,2,4,3,4,3)):
>
>
>
> ```
> 5 6 5 6
> 4 8 3 2
> 5 7 6 2
> 4 3 4 3
>
> ```
>
>
>
> Input ([Θ](https://observablehq.com/@jrunning/grid-filling-meanders#5,0,0,0,6,0,0,7,0,0,0,0,0,0,3,2,4,0,0,0,0,0,3,0,0)):
>
>
>
> ```
> 5 0 0 0 6
> 0 0 7 0 0
> 0 0 0 0 3
> 2 4 0 0 0
> 0 0 3 0 0
>
> ```
>
> Output ([Θ](https://observablehq.com/@jrunning/grid-filling-meanders#5,6,5,1,6,4,8,7,6,2,5,7,7,7,3,2,4,8,8,6,4,1,3,4,3)):
>
>
>
> ```
> 5 6 5 1 6
> 4 8 7 6 2
> 5 7 7 7 3
> 2 4 8 8 6
> 4 1 3 4 3
>
> ```
>
>
[Answer]
# JavaScript (ES7), ~~236 ... 193~~ 185 bytes
Outputs by modifying the input matrix.
```
m=>(g=(d,x,y,v,r=m[y],h=_=>++r[x]<9?g(d,x,y,v)||h():r[x]=0)=>r&&1/(n=r[x])?x|y|!v?n?g(d='21100--13203-32-21030321'[n*28+d*3+7&31],x+--d%2,y+--d%2,v+=n<7||.5):h():!m[v**.5|0]:0)(0,0,0,0)
```
[Try it online!](https://tio.run/##ZU/bboMwDH3nK9KHlQQMC0lpt66hT/sKFk2o0JuaUEGFQMu@nZHRrpUmy4p9LrZzzJqs3lSH8yXQZV70W9ErkeCdwDm00EEDlVBpJ2EvPkXi@1XaytXrenejiTF7TJYWFpSIpJpOo2eshQXIujWdmTRrbfXCZVFEaRBEnFEecBawiHLKWeSm2mMvfu5xfzHlkYTWD4L8iUF3fRtf6NXCmDAmS7ttotLG88LYULmkBFP4DdJfivqCBFJIJOgLbUpdl6ciPJU7vMWKkDeUuh/aBeSCK8NtWb1nmz2ui7PVP6pVqLIzrixchcfyoPHgIGQsBz1BPrKT7Mhvx7FrceoglFKYSxgLKh1JHqgY5hDf6NlwLwc2NjEsBo7dGA5D/jOPf7xPHzx2x19rg48tg9kI3FkO14P6Hw "JavaScript (Node.js) – Try It Online")
(includes some post-processing code to print the result both as a matrix and as a flat list compatible with the [visualization tool](https://observablehq.com/@jrunning/grid-filling-meanders) provided by the OP)
## Results
* [Test case #1](https://observablehq.com/@jrunning/grid-filling-meanders#5,6,4,3)
* [Test case #2](https://observablehq.com/@jrunning/grid-filling-meanders#5,6,5,6,4,8,3,2,5,7,6,2,4,3,4,3)
* [Test case #3](https://observablehq.com/@jrunning/grid-filling-meanders#5,1,6,5,6,2,5,7,3,2,2,2,2,5,3,2,4,7,8,6,4,1,3,4,3)
## How?
### Variables
\$g\$ is a recursive function taking the current direction \$d\$, the current coordinates \$(x,y)\$ and the number of visited cells \$v\$.
The following variables are also defined in the scope of \$g\$:
* \$r\$ is the current row of the matrix.
```
r = m[y]
```
* \$h\$ is a helper function that tries all values from \$1\$ to \$8\$ for the current cell and invokes \$g\$ with each of them. It either stops as soon as \$g\$ succeeds or sets the current cell back to \$0\$ if we need to backtrack.
```
h = _ => ++r[x] < 9 ? g(d, x, y, v) || h() : r[x] = 0
```
### Initial checks
We first make sure that our current location is valid and we load the value of the current cell into \$n\$:
```
r && 1 / (n = r[x]) ? ... ok ... : ... failed ...
```
We test whether we're back to our starting position, i.e. we're located at \$(0,0)\$ and we've visited at least a few cells (\$v>0\$):
```
x | y | !v ? ... no ... : ... yes ...
```
For now, let's assume that we're not back to the starting point.
### Looking for a path
If \$n\$ is equal to \$0\$, we invoke \$h\$ to try all possible values for this tile.
If \$n\$ is not equal to \$0\$, we try to move to the next tile.
The tile connections are encoded in a lookup table, whose index is computed with \$n\$ and \$d\$, and whose valid entries represent the new values of \$d\$.
```
d = '21100--13203-32-21030321'[n * 28 + d * 3 + 7 & 31]
```
The last 8 entries are invalid and omitted. The other 4 invalid entries are explicitly marked with hyphens.
For reference, below are the decoded table, the compass and the tile-set provided in the challenge:
```
| 1 2 3 4 5 6 7 8
---+-----------------
0 | 0 - - 1 3 - 3 1 1
1 | - 1 - - 2 0 2 0 0 + 2
2 | 2 - 1 - - 3 1 3 3
3 | - 3 0 2 - - 0 2
```

We do a recursive call to \$g\$ with the new direction and the new coordinates. We add \$1/2\$ to \$v\$ if we were on a tile of type \$7\$ or \$8\$, or \$1\$ otherwise (see the next paragraph).
```
g(d, x + --d % 2, y + --d % 2, v += n < 7 || .5)
```
If \$d\$ is invalid, \$x\$ and \$y\$ will be set to *NaN*, forcing the next iteration to fail immediately.
### Validating the path
Finally, when we're back to \$(0,0)\$ with \$v>0\$, it doesn't necessarily mean that we've found a valid path, as we may have taken a shortcut. We need to check if we've visited the correct number of cells.
Each tile must be visited once, except tiles \$7\$ and \$8\$ that must be visited twice. This is why we add only \$1/2\$ to \$v\$ when such a tile is visited.
In the end, we must have \$v = N^2\$. But it's also worth noting that we can't possibly have \$v > N^2\$. So, it's enough to test that we don't have \$v < N^2\$, or that the \$k\$th row of the matrix (0-indexed) does not exist, where \$k=\lfloor\sqrt{v}\rfloor\$.
Hence the JS code:
```
!m[v ** .5 | 0]
```
### Formatted source
```
m => (
g = (
d,
x, y,
v,
r = m[y],
h = _ => ++r[x] < 9 ? g(d, x, y, v) || h() : r[x] = 0
) =>
r && 1 / (n = r[x]) ?
x | y | !v ?
n ?
g(
d = '21100--13203-32-21030321'[n * 28 + d * 3 + 7 & 31],
x + --d % 2,
y + --d % 2,
v += n < 7 || .5
)
:
h()
:
!m[v ** .5 | 0]
:
0
)(0, 0, 0, 0)
```
] |
[Question]
[
Steganography hides a given message inside a given carrier, producing a package that does not look suspicious. For this challenge, you will write a program that takes an ASCII message and an ASCII carrier as input, and return or print a package that is identical to the carrier except characters corresponding to the message are doubled, in the same order that they appear in the message.
Rules:
1. If the carrier already contains sequences of the same character more than once, and they are not used to encode a character of the message, the program will reduce them to a single character.
2. If the carrier does not contain the message characters in the right order, the program may return nothing, the carrier itself, or an error.
3. You may assume that the message and carrier are non-empty ASCII strings.
4. Capitalization matters: A is not equivalent to a.
5. When more than one package is valid, your program may output any or all of them.
6. Space is a character like any other character.
Test cases:
```
Message Carrier Package
"hi" "has it arrived?" "hhas iit arived?" OR "hhas it ariived?"
"sir" "has it arrived?" "hass iit arrived?"
"foo" "has it arrived?" "" OR "has it arrived?" OR an error.
"Car" "Cats are cool." "CCaats arre col."
"car" "Cats are cool." "" OR "Cats are cool." OR an error.
"Couch" "Couch" "CCoouucchh"
"oo" "oooooooooo" "oooo"
"o o" "oooo oooa" "oo ooa"
```
This is code golf, so fewest bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ẹⱮŒp<ƝẠ$ƇṪ
nƝ+çṬ¥a⁸ḟ0Ḥç¦ð¹ç?
```
A full program taking `carrier` and `message` as command line arguments which prints the result
(For a non-packable `message` prints the unchanged `carrier`).
**[Try it online!](https://tio.run/##AVgAp/9qZWxsef//4bq54rGuxZJwPMad4bqgJMaH4bmqCm7GnSvDp@G5rMKlYeKBuOG4nzDhuKTDp8Kmw7DCucOnP////yJoYXMgaXQgYXJyaXZlZD8i/yJzaXIi "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hrp2PNq47OqnA5tjch7sWqBxrf7hzFVfesbnah5c/3Lnm0NLER407Hu6Yb/Bwx5LDyw8tO7zh0M7Dy@3/H16u/6hpTeT//9HRShmJxQqZJQqJRUWZZakp9ko6CkoZmUqxOlwKWOWKM4twS6bl50MlnRNLioFSqQrJ@fk5eiA558QinHLJCLn80uQMsHIwAyKYDwcgGbgdIAEFIE4EiyoAhWMB "Jelly – Try It Online").
### How?
```
ẹⱮŒp<ƝẠ$ƇṪ - Link 1, helper function to find the indices to double: carrier, message
- e.g. "programming", "rom"
Ɱ - map across message with:
ẹ - indices of [[2,5], [3], [7,8]]
Œp - Cartesian product [[2,3,7],[2,3,8],[5,3,7],[5,3,8]]
Ƈ - filter keep if:
$ - last two links as a monad:
Ɲ - for neighbours:
< - less than? [1,1] [1,1] [0,1] [0,1]
Ạ - all truthy? 1 1 0 0
- [[2,3,7],[2,3,8]]
Ṫ - tail (if empty yields 0) [2,3,8]
nƝ+çṬ¥a⁸ḟ0Ḥç¦ð¹ç? - Main Link: carrier, message
? - if...
ç - ...condition: last Link (the helper function) as a dyad
ð - ...then: perform the dyadic chain to the left (described below)
¹ - ...else: do nothing (yields carrier)
- (the then clause:)
Ɲ - for neighbours in the carrier
n - not equal?
¥ - last two links as a dyad:
ç - call last Link (the helper function) as a dyad
Ṭ - untruth (e.g. [2,5] -> [0,1,0,0,1])
+ - add (vectorises)
a⁸ - logical AND with carrier
ḟ0 - filter out zeros
¦ - sparse application...
ç - ...to indices: call last Link (the helper function) as a dyad
Ḥ - ...do: double (e.g. 'x' -> 'xx')
```
[Answer]
# JavaScript (ES6), 71 bytes
Takes input as `(message)(carrier)`.
```
s=>g=([c,...C],p)=>c?(c==s[0]?(s=s.slice(1),c)+c:p==c?'':c)+g(C,c):s&&X
```
[Try it online!](https://tio.run/##fZAxa8MwEIX3/IpDQywRV2lXB8WD6RzwVAgZxEWxXdwo6JRAKfntrmzLpQltDiyk7969Z@ldXzSha07@6Wj3pjuojtS6UnyLqZSy2KUnodaYc1SKts@7nJMiSW2Dhr@IFMUCs5NSmCdJFg4VLwLLaD5/67whDwo4pYAC1Bq@wLvPsKI9km2NbG3FD5wERyFWcAXUHmtuxJ0keS3LTZlBAgsw8sMQ6SqIrnCdzfoMzuqGpRCK1Zqg8aCday5mnzMBy2WgAx74iGFTTnSAI41m1LjB7T8zTZOZu5k7WPtoLobe9Xqoj2Ccs05Go0LHHyi0pyA14TVsKxmMRkWhRz40Ao9j@HhszL/v/RVvz1gHp7iBn5rirT2fEet6Co73hrCZiv0aGM6TFOIb9RDCpxncSAF61n0D "JavaScript (Node.js) – Try It Online")
---
# Alternate version, 66 bytes
If we can take the message as an array of characters:
```
s=>g=([c,...C],p)=>c?(c==s[0]?s.shift()+c:p==c?'':c)+g(C,c):s+s&&X
```
[Try it online!](https://tio.run/##fZAxa8MwEIX3/IrDQyxhV@nsongwnQOeCiGDuMiWSxoFnRIoJb/dlW25NKHNgYz03bv3ZL2riyJ03ck/He1e943sSa5bybaYCyGqXX7ico0lQylp@7wrSZDpGs94hsVJSizTtECetazKkReU0XL51ntNHiQwygE5yDV8gXef4Yv2SPagxcG2rGHbkEA7zpDzF7gCKo@GaX6nS1/relMXkEIGWnxoItUG0RWui8UQxBLTJTmESowi6Dwo57qL3pcJh9Uq0BGPfMKwqWc6wolGM@rc6PafmaLZzN3MNdY@mouhd70BqiNo56wT0ahS8QKV8hSkOryGPYgEJqOqUhMfG4HHMXw8NuXf9/6Kt2c0wSlu4KfmeGvPZ0Rj5uD43xA2cyW/BsbzLIX4RgOEsFQCN1KAgfXf "JavaScript (Node.js) – Try It Online")
---
***Edit**: Thanks to @tsh for noticing that I forgot to remove some code when switching from non-recursive to recursive versions.*
[Answer]
## Haskell, ~~124~~ ~~121~~ ~~107~~ ~~101~~ ~~97~~ ~~95~~ 90 bytes
```
(#).(++"ü")
"ü"#[]=[]
p@(m:n)#e@(c:d)|m/=c=c:p#snd(span(==c)d)|m==n!!0=m:m:n#d|1<2=m:n#e
```
Raises the "Non-exhaustive patterns" exception if the carrier does not contain the message.
[Try it online!](https://tio.run/##jc6/bsMgEAbw3U9xgQ6gqOmf0eqpkbJm65hkOAGOUW1Axs7kR@vW9yoxlbzEGYLEdyd9PyFqit@maVKFxyS43Ij1mv3@MFnk5IcTHk5F2Iq2dJKbrVCllmP7ggpVGXh0WsRATiAqmQtEt1q9YltOnuvx7eMd82ZSS9YBgvYFAISh/@q7vYMnqIDVlk1BEWwP1HX2YvQnW7Jou4fcjrLbUR8nZUB532zuMT@oms1z2XvPcsznnoCZwHSJFUtS/b9y@@f0p6qGzjE9qxCu "Haskell – Try It Online")
Edit: -5 bytes thanks to @Laikoni.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 67 bytes
```
+`(.)(\1*)\1*(.*¶)(?(\1)(\1(\2)))(.*)$(?!¶)
$1$4$5¶$3$6
M!s`.*¶$
¶
```
[Try it online!](https://tio.run/##K0otycxL/P9fO0FDT1MjxlBLE4g19LQObdPUsAfyQWIaMUaamppAQU0VDXtFoAyXiqGKiYrpoW0qxipmXL6KxQkgDSpch7Zx/f@fkViskFmikFhUlFmWmmLPlZEJAA "Retina 0.8.2 – Try It Online") Takes the carrier on the first line and the message on the second line. Explanation:
```
+`(.)(\1*)\1*(.*¶)(?(\1)(\1(\2)))(.*)$(?!¶)
$1$4$5¶$3$6
```
Process runs of 1 or more identical characters of the carrier. If there is also a run of 1 or more of the same characters in the message, then append the shorter of the two runs to the output in duplicate, otherwise append a single character of the carrier to the output. Each run of output characters is terminated with a newline to distinguish it from the input. The `(?!¶)` at the end prevents the regex from thinking the carrier is the message once the message is exhausted, as normally `$` is allowed to match where `¶$` would match.
```
M!s`.*¶$
```
Delete everything if the message wasn't completely encoded.
```
¶
```
Remove the newlines from the output.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 118 bytes
```
import StdEnv,StdLib
$[][]=[]
$[u:v]b#(_,w)=span((==)u)v
|b%(0,0)==[u]=[u,u: $if(v%(0,0)<>b%(1,1))w v(tl b)]=[u: $w b]
```
[Try it online!](https://tio.run/##PY5LC8IwEITv/RUBK00g0vZajCc9CL31GIIkfUggj2KbFMHfbozUupfZnflgtlU9N0HbzqkeaC5NkHq0jxk0c3cxHkeppUhSyigjlMXFVZ6JHbzhBZFp5AZCQpBDPnmJPSxwgQihLrIOuwqkcoB@tY@nmJe4RGgBHs4KCPSlIrMAwUIz89hKQApoZm3GNsnzn7XNPwrvdlD8PoXDtQ7np@FatuuxPv0B "Clean – Try It Online")
Takes the carrier first, then the message.
Errors with `Run time error, rule '$;2' in module 'main' does not match` if message won't fit.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 73 bytes
```
f=->m,c,b=p{x,*c=c;x ?(x==m[0]?x+m.shift: x==b ?'':x)+f[m,c,x]:m[0]?x:''}
```
[Try it online!](https://tio.run/##jZLRaoMwFIbv@xRnbuC2ZrJrh/XCBxjsVryIZ5EItZFER0bbZ3fHpFltx6ABkXz/@f9zOESP9fc0NdnLpmPI6qzfW/aMGb5ZyB9tlnXla5XbdZcY2TZDCoRqyOM4tU/rppw9tkp9URrHx6lclZFsIwbhRJIbaAfgWrdf4jOPKnbvuROc4gV4/wjUQU8pz7T6HPh/HjchT/9aG6VusJ5aX6kz5DsQWiudUFbBl2MUfDBUKwCV2iYhinjBveIkUsiJNzn9FFfqnyHUiDKEnW4h4bzzolBqHBGlnNsvdwB0C@fC6LirhuXKZgr08csuxAFmuqoSwVHuD/QUDj3Qk0hQcm0Y@n@lhcFRQP9wd5x@AA "Ruby – Try It Online")
Recursive function, takes inputs as array of characters.
For once I was hoping to make use of Ruby's built-in `squeeze` method that contracts consecutive runs of the same character to a single instance. But unfortunately, nope - the last two test cases screwed everything so badly, that I had to resort to a completely different approach, and this turned out to be basically a port of [Arnauld's answer](https://codegolf.stackexchange.com/a/177217/78274).
[Answer]
# Powershell, 134 bytes
```
param($m,$c)$c-csplit"([$m])"|%{$i+=$o=$_-ceq$m[+$i]
if($o-or$_-cne"`0$h"[-1]){$h+=($_-replace'(.)(?=\1)')*($o+1)}}
$h*!($i-$m.Length)
```
The script returns the `empty string` if the carrier does not contain the message characters in the right order.
Less golfed test script:
```
$f = {
param($message,$carrier)
$carrier-csplit"([$message])"|%{ # split by chars of the message, chars itself included ([])
$offset=$_-ceq$message[+$i] # 0 or 1 if current substring is a current message char (case-sensitive equality)
$i+=$offset # move to next message char if need it
if($offset-or$_-cne"`0$h"[-1]){ # condition to remove redundant doubles after message char: arrrived -> arrived, ooo -> oo, etc
# `0 to avoid exception error if $h is empty
$h+=($_-replace'(.)(?=\1)')*($offset+1) # accumulate a double message char or a single substring without inner doubles: arried -> arived, anna -> ana, etc
}
}
$h*!($i-$message.Length) # repeat 0 or 1 times to return '' if the carrier does not contain the message characters in the right order
}
@(
,('hi' ,'has it arrived?' ,'hhas iit arived?', 'hhas it ariived?')
,('hi?' ,'has it arrived?' ,'hhas iit arived??', 'hhas it ariived??')
,('sir' ,'has it arrived?' ,'hass iit arrived?')
,('foo' ,'has it arrived?' ,'')
,('Car' ,'Cats are cool.' ,'CCaats arre col.')
,('car' ,'Cats are cool.' ,'')
,('Couch' ,'Couch' ,'CCoouucchh')
,('oo' ,'oooooooooo' ,'oooo')
,('o o' ,'oooo oooa' ,'oo ooa')
,('er' ,'error' ,'eerorr', 'eerror')
,('a+b' ,'anna+bob' ,'aana++bbob')
) | % {
$message,$carrier,$expected = $_
$result = &$f $message $carrier
"$($result-in$expected): $result"
}
```
Output:
```
True: hhas iit arived?
True: hhas iit arived??
True: hass iit arrived?
True:
True: CCaats arre col.
True:
True: CCoouucchh
True: oooo
True: oo ooa
True: eerror
True: aana++bbob
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 69+12 = 81 bytes
```
g(char*m,char*_){for(;*_;++_)*m-*_?_[-1]-*_&&p*_):p p*m++));*m&&0/0;}
```
Compile with (12 bytes)
```
-Dp=putchar(
```
[Try it online!](https://tio.run/##hZJNboMwEIX3nGLEAtn8pEmWRVEW9BZNhSw3YEsBIwPdRLl66XgCKahJMxKY4c379GyQSSnlMJRMKmHDKqYl5@fCWJaGeRpFOQ@rJMz3@Xuy@cCHIGhw4LWBJqyiiPM0rIJg/bJOL0MldM04nD1dd3C01tgN7GAde4BF/db1qeeVzFfaj30lWtAdCGv11/Fz7/PUa/quZf6hVqSRSBoAUzpeGvihdhaHa7V9whPtxBuBDD0PgLoAdt0AbgcQXxjzP56mYV4MPXfxcKHEmXCJM9G1KB9BGnNazYlZJq4aiacVEtESLw1/Am/HwPIJ/U5e@YA@5TW9VI5J6yKoMX0vpVI3FM3EdJ99IzpDc6s5w/WwjIOn9zs7p8CEAbzEkgL4TiwocMXQ7Ei5DN@yOImyHZK3Zodm99ezHw "C (gcc) – Try It Online")
```
g(char*m,char*_){
for(;*_;++_) //step through _
*m-*_? //check if character should be encoded
_[-1]-*_&& //no? skip duplicates
p*_) // print non-duplicates
:p p*m++)); //print encoded character twice
*m&&0/0; //if m is not fully encoded, exit via Floating point exception
}
```
] |
[Question]
[
# Background
This challenge is inspired by [this](http://datagenetics.com/blog/april22013/index.html) website, which published the following diagram:
[](https://i.stack.imgur.com/Xl3tg.png)
This diagram shows us that the longest Roman Numeral expression under 250 is that of 188, which requires 9 numerals to express.
# Challenge
The standard symbols used to express most Roman Numerals are the following: {`I`, `V`, `X`, `L`, `C`, `D`, `M`}, where the characters' numeric values are `M`=1000, `D`=500, `C`=100, `L`=50, `X`=10, `V`=5, `I`=1.
In this challenge, your goal is to, given an positive integer *n*, compute the number of valid Roman Numeral representations that can be composed through concatenating *n* of the standard symbols.
Then, your program must output the result of this computation!
**Input**: A positive integer *n*.
**Output**: The number of valid roman numeral expressions of length *n*.
# Rules for Roman Numeral Expressions
Roman Numerals originally only had "additive" pairing, meaning that numerals were always written in descending order, and the sum of the values of all the numerals was the value of the number.
Later on, subtractive pairing, the use of placing a smaller numeral in front of a larger in order to subtract the smaller from the larger, became commonplace to shorten Roman Numeral expressions. Subtractive pairs cannot be chained, like in the following invalid expression: `IXL`.
The following are the modern day rules for additive and subtractive pairing.
1. Only one I, X, and C can be used as the leading numeral in part of a subtractive pair.
2. I can only be placed before V or X in a subtractive pair.
3. X can only be placed before L or C in a subtractive pair.
4. C can only be placed before D or M in a subtractive pair.
5. Other than subtractive pairs, numerals must be in descending order (meaning that if you drop the leading numeral of each subtractive pair, then the numerals will be in descending order).
6. M, C, and X cannot be equalled or exceeded by smaller denominations.
7. D, L, and V can each only appear once.
8. Only M can be repeated 4 or more times.
# Further Notes
* We will not be using the *bar* notation; rather, we will simply add more *M*s to express any number.
* These are the **only** rules that we will follow for our roman numerals. That means that odd expressions, such as `IVI`, will also be considered valid in our system.
* Also remember that we are not counting the number of numbers that have expressions of length *n*, since some numbers have multiple expressions. Instead, we are solely counting the number of valid expressions.
# Test Cases
`1` → `7`
`2` → `31`
`3` → `105`
I checked the above by hand, so please make sure to double check the test cases, and add more if you can!
# Winning Criteria
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so have fun! I will only accept solutions that can handle at least inputs from 1 through 9. Any more is bonus!
# Edit
As requested by commenters, find below, or at this pastebin link, the 105 combos I counted for *n*=3
>
> III
> IVI
> IXI
> IXV
> IXX
> VII
> XII
> XIV
> XIX
> XVI
> XXI
> XXV
> XXX
> XLI
> XLV
> XLX
> XCI
> XCV
> XCX
> XCL
> XCC
> LII
> LIV
> LIX
> LVI
> LXI
> LXV
> LXX
> CII
> CIV
> CIX
> CVI
> CXI
> CXV
> CXX
> CXL
> CXC
> CLI
> CLV
> CLX
> CCI
> CCV
> CCX
> CCL
> CCC
> CDI
> CDV
> CDX
> CDL
> CDC
> CMI
> CMV
> CMX
> CML
> CMC
> CMD
> CMM
> DII
> DIV
> DIX
> DVI
> DXI
> DXV
> DXX
> DXL
> DXC
> DLI
> DLV
> DLX
> DCI
> DCV
> DCX
> DCL
> DCC
> MII
> MIV
> MIX
> MVI
> MXI
> MXV
> MXX
> MXL
> MXC
> MLI
> MLV
> MLX
> MCI
> MCV
> MCX
> MCL
> MCC
> MCD
> MCM
> MDI
> MDV
> MDX
> MDL
> MDC
> MMI
> MMV
> MMX
> MML
> MMC
> MMD
> MMM
>
>
>
# Edit 2:
Use the following non-golfed [code](https://tio.run/##jVPRatswFH2evuIuUCxjJ@BubGBwH5a0EEgIZJkJtHlQbKXVsCUjy6PZz6eSrLieS5vpQfjK59x77rlSdVRPgl@fTgcpSmCKSiVEUQMrKyEVVFLkTaYQyukBJNXf9FdVUTklNV2LknCs6LPyYwR6HYQExnP6HAImIex9HQHlTUklURT/ZZVFh2D2@yje@Y5oFjsACfaGgb156oXgzbdm3y7sPjX7dGb3pdfjmSWpaiRv08ZWwQ6CNrRREJn4XfkOdK0FoUE61Hb@hxQs1z2837uRz4/2ZJKJhiuc@XADkTUlM22NZot05IMOuVBAigK3x/N0u5jOlqNXZC9tT84dKWrq9JlG8o2GQfLBVCy4tb@Y85xljNaacN@VnNjGjdKudi/37tzYWS@BmwT2FmvGa@BmpoMK4bDkedKf3jTiTBvi2Q4@J/BN/8uhoBzXVL3FxCz4qtNCkjiTmZVP@CPFhjQg@DCGL/7HrtqDjWyom7p5DamZ/MBcnf5RPfUuvatVGwXuxeDO5FBnrihRyT80s1Q7QM@b/BasU1z7/Tdx@ead15HRIneX9m69WoawWensUQjfETIq2/qvLnWgACKXq5KMKwcMoW5K3HprlWriBUd8hNLb9Y/Vz1td2BqpO3An/QLeAx@Pxw/c6xz8D209@lUde3DlSMOf4Oy8qHXA89Dp9AI), as courtesy of Jonathan Allan to check your results.
# Edit 3:
I apologize for all of the errors in this challenge. I'll make sure to do a better job next time!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~177 168~~ 162 bytes
```
import re,itertools as q
f=lambda n:sum(None!=re.match("^M*(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$",(''.join(m)))for m in q.product('MDCLXVI',repeat=n))
```
[Try it online!](https://tio.run/##LcrLisIwFADQ9fgV1yL0RkLRcSeULtJNoXVZshKiTccMzcPbuBgmfntFZpYHTviJN@8@l8XY4CkCaW6ipuj9NIOa4b4ay0nZy6DAHeeHxZN3el2SLqyK1xtm526LokuiTnUlfnf88GQoRZJtaiv570ampk991fx5k3HM8@LbG4eWMTZ6AgvGwb0I5IfHNWLe1aKVfZNz0kGrWDrGlvcz70fKfWnAPd/v2HH1Eci4CCMatrwA "Python 2 – Try It Online")
I'm pretty new, help me golf this! This checks for actual roman numerals, the regex needs to be adjusted to account for the odd cases such as `IVI`
**-9 bytes** thanks to @Dead Possum!
**-6 bytes** thanks to @ovs
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 111 bytes
```
~(`.+
*$(CM)CDXCXCXCXLIXIXIXIVII
.(.)
.+¶$$&$¶$$&$1$¶$$&$&¶L`.{0,$+}\b¶D`¶
¶$
¶.+¶$$&$¶$$&I¶L`[A-Z]{$+}\b¶D`¶.+
```
[Try it online!](https://tio.run/##K0otycxLNPz/v04jQU@bS0tFw9lX09klwhkMfTwjwDDM05NLT0NPk0tP@9A2FRU1FQhpCKXVDm3zSdCrNtBR0a6NSTq0zSXh0DYuoBQQo2jwBKmLdtSNiq1GUqmn/f@/MQA "Retina – Try It Online") This is a complete rewrite as I misunderstood rule 1. to mean that you could only use one each of subtractive `I`, `X` and `C`. Explanation: The first part of the script expands the input into a string of `CM` pairs followed by the other possible subtractive pairs. Each pair is optional, and the first character of each pair is also optional within the pair. The third stage then expands the list of pairs into a list of Retina commands that take the input and create three copies with the option of the second or both characters from the pair, then trims and deduplicates the results. The final stage then appends code to perform the final tasks: first to expand the input to possibly add a final `I`, then to filter out results of the wrong length, then to deduplicate the results, and finally to count the results. The resulting Retina script is then evaluated.
Note: In theory 15 bytes could be saved from the end of the 4th line but this makes the script too slow to demonstrate on TIO even for `n=1`.
[Answer]
# JavaScript (ES7), 133 bytes
***Edit**: Fixed to match the results returned by [Jonathan Allan's code](https://tio.run/##jVPRatswFH2evuIuUCxjJ@BubGBwH5a0EEgIZJkJtHlQbKXVsCUjy6PZz6eSrLieS5vpQfjK59x77rlSdVRPgl@fTgcpSmCKSiVEUQMrKyEVVFLkTaYQyukBJNXf9FdVUTklNV2LknCs6LPyYwR6HYQExnP6HAImIex9HQHlTUklURT/ZZVFh2D2@yje@Y5oFjsACfaGgb156oXgzbdm3y7sPjX7dGb3pdfjmSWpaiRv08ZWwQ6CNrRREJn4XfkOdK0FoUE61Hb@hxQs1z2837uRz4/2ZJKJhiuc@XADkTUlM22NZot05IMOuVBAigK3x/N0u5jOlqNXZC9tT84dKWrq9JlG8o2GQfLBVCy4tb@Y85xljNaacN@VnNjGjdKudi/37tzYWS@BmwT2FmvGa@BmpoMK4bDkedKf3jTiTBvi2Q4@J/BN/8uhoBzXVL3FxCz4qtNCkjiTmZVP@CPFhjQg@DCGL/7HrtqDjWyom7p5DamZ/MBcnf5RPfUuvatVGwXuxeDO5FBnrihRyT80s1Q7QM@b/BasU1z7/Tdx@ead15HRIneX9m69WoawWensUQjfETIq2/qvLnWgACKXq5KMKwcMoW5K3HprlWriBUd8hNLb9Y/Vz1td2BqpO3An/QLeAx@Pxw/c6xz8D209@lUde3DlSMOf4Oy8qHXA89Dp9AI), which was given as a reference implementation by the OP.*
---
```
n=>[...Array(m=k=7**n)].reduce(s=>s+/^1*5?4{0,3}3?2{0,3}6?0{0,3}$/.test((--k+m).toString(7).replace(/0[62]|2[34]|4[51]/g,s=>s[1])),0)
```
[Try it online!](https://tio.run/##HczNisIwGIXhvVfxLYTJ1zTprzowkxavwWWIUGpaHGsiSUYQ9dprdHOezeH9666d793xEpixBz0PYjaikZzzrXPdjZzFSWySxKDiTh/@e028aDzN9kWyaut7nlbPqi0/rtv84zLjQftACGMnekYe7C64oxnJBmPjMnUxkuVyXapHKataPWq5KlQ2pu@yLBRimuM8WEcMCCh@wMAvfEcoRbgvAHprvJ00n@wYLxS@gLEmLoWBGMTFc34B "JavaScript (Node.js) – Try It Online")
### How?
1) We generate all numbers of \$N\$ digits in base 7 with an extra leading \$1\$:
```
[...Array(m = k = 7 ** n)].reduce(s => … (--k + m).toString(7) …, 0)
```
From now on, each digit will be interpreted as a Roman numeral symbol:
$$\begin{array}{}0\longleftrightarrow \text{I}, & 1\longleftrightarrow \text{M}, & 2\longleftrightarrow \text{X}, & 3\longleftrightarrow \text{L},\\
4\longleftrightarrow \text{C}, & 5\longleftrightarrow \text{D}, & 6\longleftrightarrow \text{V}
\end{array}$$
2) We replace all valid subtractive pairs of the form `AB` with `B`:
```
.replace(/0[62]|2[34]|4[51]/g, s => s[1])) // in the code
.replace(/I[VX]|X[LC]|C[DM]/g, s => s[1])) // with Roman symbols
```
**Examples:**
* `XLIXIV` becomes `LXV`
* `XIIV` becomes `XIV`, leaving a `I` that will make the next test fail
* `IC` remains unchanged, which also leaves an invalid `I` in place
3) We check that the remaining symbols are in the correct order and do not appear more times than they're allowed to:
```
/^1*5?4{0,3}3?2{0,3}6?0{0,3}$/.test(…) // in the code
/^M*D?C{0,3}L?X{0,3}V?I{0,3}$/.test(…) // with Roman symbols
```
[Answer]
# C, 150 123 bytes
I didn't read the description closely enough, so this produces the number of standard Roman numerals (where expressions like `IVI` aren't counted). Since I put some effort into it, I thought I would share anyway.
```
#define F(X) for(X=10;X--;)
x[]={0,1,2,3,2,1,2,3,4,2};f(i,o,a,b,c){for(i++;i--;)F(a)F(b)F(c)o+=i==x[a]+x[b]+x[c];return o;}
```
Original (150 bytes):
```
#define F(X) for(X=10;X--;)
i,o,a,b,c,x[]={0,1,2,3,2,1,2,3,4,2};main(){scanf("%i",&i);for(i++;i--;)F(a)F(b)F(c)o+=i==x[a]+x[b]+x[c];printf("%i\n",o);}
```
] |
[Question]
[
Sometimes when you're playing Wordle, you get to your fifth guess and you can't figure out the word any more, so you start mentally running through the list of remaining iterations, both sensical and nonsensical trying to figure out what those last few letters are.
The task here is to create all permutations of a final Wordle guess to save me from having to do it in my head, with the following rules:
### General rules:
* Wordle rules apply (similar to codebreaker game).
+ Guess an unknown five-letter word.
+ Guesses will return an indication of whether the letter is in the word such that:
- If a letter is in the correct position, it will be green
- If a letter appears in the word but is not in the correct position, it will be yellow
- If a letter does not appear in the word, it will be black.
- Letters can appear more than once in the solution (provided the solution is still a valid word)
- If a letter is guessed twice in the same guess (such as "guess") but is in the correct word fewer times than guessed, only the number of the repeated letters will be green or yellow. If the position is correct for one of the placements, that will appear green, regardless of the position in the sequence. If the positions are all wrong, the earliest occurence/s will be marked yellow and the following one/s black.
* Inputs should be solvable, even if no solutions are "real" words.
* Since Wordle only uses valid English words, only letters that appear on a standard English keyboard (a-z) need to be tested. **However, you should include all valid permutations, not just valid English words, in your output**.
* Solution is case insensitive.
### Input:
* A list of letters and indices (0 or 1 indexed, your choice), indicating the location of confirmed/green letters - **indicate the index you chose**;
* A list of letters and indices (consistently indexed), indicating yellow letters (i.e. the letter is known to not be at that index);
* A list/string of letters that are yet to be guessed.
Note, **green and yellow letters may still appear in more than the known positions**. For example, if the input for green is `[('E', 1)]`, there may still be an `E` in an index other than `1` as well.
### Output:
All potential "words" of exactly 5 letters, such that the green letters are in the indicated indexes, the yellow letters are not in the indicated indexes (but must appear at least once in the output), and the words consist of only the green, yellow, and remaining letters. The output may be in any order.
What's the shortest way to solve this problem? You may take input and output in any [convenient method or format](https://codegolf.meta.stackexchange.com/q/2447), and the shortest code in bytes wins.
---
### Example:
1. **Green Guesses** (1 indexed): O=2, E=4, N=5
2. **Yellow Guesses**: N!=3 (E!=5 is excluded because we know N=5)
3. **Unguessed Letters**: Q, W, I, P, F, J, K, X, B
All other letters (A, C, D, F, G, H, L, M, R, S, T, U, V, Y, Z) have been guessed and cannot occur in the result.
Output would be a list of all possible permutations given the known information, such as:
```
["BOBEN", "BOEEN", "BOFEN", "BOIEN", "BOJEN", "BOKEN", "BOOEN", "BOPEN", "BOQEN", "BOWEN", "BOXEN", "EOBEN", "EOEEN", "EOFEN", "EOIEN", "EOJEN", "EOKEN", "EOOEN", "EOPEN", "EOQEN", "EOWEN", "EOXEN", "FOBEN", "FOEEN", "FOFEN", "FOIEN", "FOJEN", "FOKEN", "FOOEN", "FOPEN", "FOQEN", "FOWEN", "FOXEN", "IOBEN", "IOEEN", "IOFEN", "IOIEN", "IOJEN", "IOKEN", "IOOEN", "IOPEN", "IOQEN", "IOWEN", "IOXEN", "JOBEN", "JOEEN", "JOFEN", "JOIEN", "JOJEN", "JOKEN", "JOOEN", "JOPEN", "JOQEN", "JOWEN", "JOXEN", "KOBEN", "KOEEN", "KOFEN", "KOIEN", "KOJEN", "KOKEN", "KOOEN", "KOPEN", "KOQEN", "KOWEN", "KOXEN", "NOBEN", "NOEEN", "NOFEN", "NOIEN", "NOJEN", "NOKEN", "NOOEN", "NOPEN", "NOQEN", "NOWEN", "NOXEN", "OOBEN", "OOEEN", "OOFEN", "OOIEN", "OOJEN", "OOKEN", "OOOEN", "OOPEN", "OOQEN", "OOWEN", "OOXEN", "POBEN", "POEEN", "POFEN", "POIEN", "POJEN", "POKEN", "POOEN", "POPEN", "POQEN", "POWEN", "POXEN", "QOBEN", "QOEEN", "QOFEN", "QOIEN", "QOJEN", "QOKEN", "QOOEN", "QOPEN", "QOQEN", "QOWEN", "QOXEN", "WOBEN", "WOEEN", "WOFEN", "WOIEN", "WOJEN", "WOKEN", "WOOEN", "WOPEN", "WOQEN", "WOWEN", "WOXEN", "XOBEN", "XOEEN", "XOFEN", "XOIEN", "XOJEN", "XOKEN", "XOOEN", "XOPEN", "XOQEN", "XOWEN", "XOXEN"]
```
Output may be in any order.
In this case:
* There are 12 possibilities for the first letter (any of "BEFIJKNOPQWX")
* There is 1 possibility for the second letter ("O")
* There are 11 possibilities for the third letter (any of "BEFIJKOPQWX", excluding N)
* There is 1 possibility for the fourth letter ("E")
* There is 1 possibility for the fifth letter ("N")
So the result should contain a total of 12 \* 1 \* 11 \* 1 \* 1 = 132 items.
In code terms, the inputs may be given as:
* `[['O', 2], ['E', 4], ['N', 5]]` or `[["O", "E", "N"], [2, 4, 5]]` or similar
* `[['N', 3]]` or `[["N"], [3]]` or similar
* `"QWIPFJKXB"` or `["Q","W","I","P","F","J","K","X","B"]` or similar
and the output as:
```
['BOBEN', 'EOBEN', 'FOBEN', 'IOBEN', 'JOBEN', 'KOBEN', 'NOBEN', 'OOBEN', 'POBEN', 'QOBEN', 'WOBEN', 'XOBEN', 'BOEEN', 'EOEEN', 'FOEEN', 'IOEEN', 'JOEEN', 'KOEEN', 'NOEEN', 'OOEEN', 'POEEN', 'QOEEN', 'WOEEN', 'XOEEN', 'BOFEN', 'EOFEN', 'FOFEN', 'IOFEN', 'JOFEN', 'KOFEN', 'NOFEN', 'OOFEN', 'POFEN', 'QOFEN', 'WOFEN', 'XOFEN', 'BOIEN', 'EOIEN', 'FOIEN', 'IOIEN', 'JOIEN', 'KOIEN', 'NOIEN', 'OOIEN', 'POIEN', 'QOIEN', 'WOIEN', 'XOIEN', 'BOJEN', 'EOJEN', 'FOJEN', 'IOJEN', 'JOJEN', 'KOJEN', 'NOJEN', 'OOJEN', 'POJEN', 'QOJEN', 'WOJEN', 'XOJEN', 'BOKEN', 'EOKEN', 'FOKEN', 'IOKEN', 'JOKEN', 'KOKEN', 'NOKEN', 'OOKEN', 'POKEN', 'QOKEN', 'WOKEN', 'XOKEN', 'BOOEN', 'EOOEN', 'FOOEN', 'IOOEN', 'JOOEN', 'KOOEN', 'NOOEN', 'OOOEN', 'POOEN', 'QOOEN', 'WOOEN', 'XOOEN', 'BOPEN', 'EOPEN', 'FOPEN', 'IOPEN', 'JOPEN', 'KOPEN', 'NOPEN', 'OOPEN', 'POPEN', 'QOPEN', 'WOPEN', 'XOPEN', 'BOQEN', 'EOQEN', 'FOQEN', 'IOQEN', 'JOQEN', 'KOQEN', 'NOQEN', 'OOQEN', 'POQEN', 'QOQEN', 'WOQEN', 'XOQEN', 'BOWEN', 'EOWEN', 'FOWEN', 'IOWEN', 'JOWEN', 'KOWEN', 'NOWEN', 'OOWEN', 'POWEN', 'QOWEN', 'WOWEN', 'XOWEN', 'BOXEN', 'EOXEN', 'FOXEN', 'IOXEN', 'JOXEN', 'KOXEN', 'NOXEN', 'OOXEN', 'POXEN', 'QOXEN', 'WOXEN', 'XOXEN']
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~198 176 205 166 152~~ 138 bytes
```
lambda g,y,u:{m for m in product(*[x or u+''.join(g+[a for a,b in y])for x in g])if all(m[q]!=p in m for p,q in y)}
from itertools import*
```
### [Try it online!](https://tio.run/##TY1Pi8IwEMXvforxNIkNe1hvQi@Cggru7mmF2EO0TY00f0xTsIifvSZdDzswj3mPH/NcHy7WzAeZH4dG6FMpoGY96xYPDdJ60KAMOG/L7hzIjN8hZl2G@HG1ypA642LEBDslsC9ocvd01wVVEkTTEM1vxTR3Kfx76thtpOlzIr2NFaHywdqmBaWd9WE2OK9M7GujqUoygXEk4YgM8CtJ2lWSPRbsDQBwEj2DT/ovw5/fzfd6uzsskb5DyqCtXI5Hg3R4AQ "Python 3 – Try It Online")
* -22, -39, -14 thanks to Steffan
* Thanks to Kamil Drakari for pointing out some bugs in the code
So, it didn't work before. I've now fixed it (I think).
Other test cases [here](https://tio.run/##TY3NasMwEITvfortaSVH9JDeCr4UGkgCTdJLC7IPSm05CtZPZBliSp/dlVwfurDDzsew48ZwseZpkkU5dUKfawEtG9nw/K1BWg8alAHnbT18BZLzO0Q2rBAfr1YZ0q64mGOCnVNwrGhy93S3FVUSRNcRzW/VQ@ES/Hvq2G1O059MehsrQuODtV0PSjvrQz45r0zs66NpapLBPJJwRAZ4SJL2NckbVmwJAHCC7xGu6T@Gp4/tcbPbf74gXSBl0DeuwNIgnX4B), [here](https://tio.run/##TY1Pa8MwDMXv/RTqSXZrxmhvhRzWw2DbYRustODm4C5x5hH/ieNAQulnT@20hwr0kJ5@6Lkh/FmzHmV2HGuhT4WAig2s25w1SOtBgzLgvC2630AWvIfodUvEp3@rDKmWXEyYYKcEDjlNW5/mKqdKgqhronmTzzOXzNtTx5qJppeZ9DZGhNIHa@sWlHbWh8XovDIxr41LWZAZTCUJR2SA2ySpd0l@MGd3AIAT/IzmM2VA8CVOK/pwxe/929fr@8dhi/RuRrAtXYZHg3S8Ag) and [here](https://tio.run/##TY1PawIxEMXvforxNImGUuxN2EM9FGwPbaFSIe4hdjfbyOaP2Sy4lH72NYkiDszw3psfM24Iv9Y8jbLYja3Q@0pAwwbWL/80SOtBgzLgvK36n0Bm/AQx6@eIDwerDGnmXGRMsH0Ch5Imd0q6KamSINqWaH4sp4VL4eWoY8dM0/@J9Da@CLUP1rYdKO2sD7PReWXivy6auiITyCUJR2Rw600aX1iy6x6AE3yP4SNlQPA5qkVWq6zuOPz8Xn@8vL5tV0ivYQS72hW4M0jHMw).
# [Python 3](https://docs.python.org/3/) + [`golfing-shortcuts`](https://github.com/nayakrujul/golfing-shortcuts), ~~131~~ 121 bytes
```
lambda G,Y,U:{M for M in Ip(*[X or U+sj('',G+[A for A,B in Y])for X in G])if j(M[Q]!=P in M for P,Q in Y)}
from s import*
```
* -10 thanks to Steffan
---
**Input:**
* `g`: The green letters, as a list, e.g. `['', 'O', '', 'E', 'N']`
* `y`: The yellow letters, in tuples with their positions, e.g. `[('N', 2)]`
* `u`: The unguessed letters, as a string: e.g. `'QWIPFJKXB'`
**Output:**
As letter tuples, e.g. `('Q', 'O', 'Q', 'E', 'N')`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes
```
UMθ∨ι⁻⪪α¹⁺⪪§ηκ¹⁻⪪α¹⁺θ⪪⁺ζΣη¹ΦEΠEθLι⭆θ§λ÷ιΠ∨E…θμLν¹⬤Ση№ιλ
```
[Try it online!](https://tio.run/##dY7LSgMxFIb3PkXI6gSOC9dd6WhhtHVGulAoXYSZ0ATPJDVmivryMZe2uDGQcC75P75BSz84STGu5aFx0yTtCB/IOg8G2drY@RM2BzIBJLIbgayny@Q2tHZUX6CRvYu6/S@QiHVYup/UzRNoUVL1LK56b2yApaGgPCQb6L0b5yGUOgFWyu6DBiNybBPS7/1pcxYhZK0N9@ZoRpX1z4Cu8prvgVSjXclM4kK0fzwSjAiqHbLGzUkpkagoxrjdco6Md/nJ9yE/z3yHrC5qeyrymL@8tv3y8entju/i9ZF@AQ "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the `["", "O", "", "E", "N"]`, `["", "", "N", "", ""]`, `"QWIPFJKXB"` formats, i.e. multiple letters unguessed or in a given yellow position should be concatenated into a string rather than being a subarray. Explanation:
```
UMθ∨ι⁻⪪α¹⁺⪪§ηκ¹⁻⪪α¹⁺θ⪪⁺ζΣη¹
```
Fill in the gaps in the green guesses by taking the set union of all of the input and subtracting the yellow guesses for that position. (Charcoal doesn't actually do set union so I have to fake it by set difference with the whole alphabet twice.)
```
EΠEθLι⭆θ§λ÷ιΠ∨E…θμLν¹⬤Ση№ιλ
```
Calculate the number of potential words and map each to a string by mixed base conversion using the lists of possible letters (which again Charcoal has to emulate, although at least it has cyclic indexing to help). Ensure those words contain at least one of all of the yellow guesses.
50 bytes using the newer version of Charcoal on ATO that can take the product of an empty list and flatten a list of lists:
```
UMθ∨ι⁻⪪α¹⁺§ηκ⁻⪪α¹⁺Σθ⁺ζΣηΦEΠEθLι⭆θ§λ÷ιΠE…θμLν⬤Ση№ιλ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVA9T8MwEBUrEv_B8nSR3IENiQkClQK0DeoAkpUhJCGxuNhtYlfAX2HpAIK_BL8Gn5tGLHh49_Xu3ZPfvoom7wqT43b74ezj5OTn4GiWr2LTtrkuYS3YogMl2Exp18NyhcpCLthxJFiKvnNmE11Wz9AI9hT9T1u6Ftb74lUwqptoeKeHaae0halCW3Xgz0PamdIVNuTew02la9uA8mS_az27Hib7-yhYou2F2qiyIr9_BeKXAqu4MWGhjUY5Pdz3KoiwsyRYbJz34iUweHvvH4p--JtPyScb5Nl3LaXMBJN8wSmE9DKkfM4zinLsz0dKGPBbLhi_I0gIUoIpwRXBNcE9wbkX2p39BQ "Charcoal – Attempt This Online") Link is to verbose version of code. Takes input in the `["", "O", "", "E", "N"]`, `[[], [], ["N"], [], []]`, `["Q", "W", "I", "P", "F", "J", "K", "X", "B"]` formats, i.e. letters unguessed or in a given yellow position need to be a subarray (both formats work for the green letters).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 38 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
5ÆgX ªNc kVgX)fÃrÈï[Y]c '+Ãf@Vc e!øXÃâ
```
[Try the original test case](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=NcZnWCCqTmMga1ZnWClmw3LI71tZXWMgJyvDZkBWYyBlIfhYw%2bI&input=WyIiICJPIiAiIiAiRSIgIk4iXSBbW10gW10gWyJOIl0gW10gW11dIFsiUSIsIlciLCJJIiwiUCIsIkYiLCJKIiwiSyIsIlgiLCJCIl0tUg), or [check that it's right](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=NcZnWCCqTmMga1ZnWClmw3LI71tZXWMgJyvDZkBWYyBlIfhYw%2bI&footer=8SBlWyJCT0JFTiIiRU9CRU4iIkZPQkVOIiJJT0JFTiIiSk9CRU4iIktPQkVOIiJOT0JFTiIiT09CRU4iIlBPQkVOIiJRT0JFTiIiV09CRU4iIlhPQkVOIiJCT0VFTiIiRU9FRU4iIkZPRUVOIiJJT0VFTiIiSk9FRU4iIktPRUVOIiJOT0VFTiIiT09FRU4iIlBPRUVOIiJRT0VFTiIiV09FRU4iIlhPRUVOIiJCT0ZFTiIiRU9GRU4iIkZPRkVOIiJJT0ZFTiIiSk9GRU4iIktPRkVOIiJOT0ZFTiIiT09GRU4iIlBPRkVOIiJRT0ZFTiIiV09GRU4iIlhPRkVOIiJCT0lFTiIiRU9JRU4iIkZPSUVOIiJJT0lFTiIiSk9JRU4iIktPSUVOIiJOT0lFTiIiT09JRU4iIlBPSUVOIiJRT0lFTiIiV09JRU4iIlhPSUVOIiJCT0pFTiIiRU9KRU4iIkZPSkVOIiJJT0pFTiIiSk9KRU4iIktPSkVOIiJOT0pFTiIiT09KRU4iIlBPSkVOIiJRT0pFTiIiV09KRU4iIlhPSkVOIiJCT0tFTiIiRU9LRU4iIkZPS0VOIiJJT0tFTiIiSk9LRU4iIktPS0VOIiJOT0tFTiIiT09LRU4iIlBPS0VOIiJRT0tFTiIiV09LRU4iIlhPS0VOIiJCT09FTiIiRU9PRU4iIkZPT0VOIiJJT09FTiIiSk9PRU4iIktPT0VOIiJOT09FTiIiT09PRU4iIlBPT0VOIiJRT09FTiIiV09PRU4iIlhPT0VOIiJCT1BFTiIiRU9QRU4iIkZPUEVOIiJJT1BFTiIiSk9QRU4iIktPUEVOIiJOT1BFTiIiT09QRU4iIlBPUEVOIiJRT1BFTiIiV09QRU4iIlhPUEVOIiJCT1FFTiIiRU9RRU4iIkZPUUVOIiJJT1FFTiIiSk9RRU4iIktPUUVOIiJOT1FFTiIiT09RRU4iIlBPUUVOIiJRT1FFTiIiV09RRU4iIlhPUUVOIiJCT1dFTiIiRU9XRU4iIkZPV0VOIiJJT1dFTiIiSk9XRU4iIktPV0VOIiJOT1dFTiIiT09XRU4iIlBPV0VOIiJRT1dFTiIiV09XRU4iIlhPV0VOIiJCT1hFTiIiRU9YRU4iIkZPWEVOIiJJT1hFTiIiSk9YRU4iIktPWEVOIiJOT1hFTiIiT09YRU4iIlBPWEVOIiJRT1hFTiIiV09YRU4iIlhPWEVOIl3x&input=WyIiICJPIiAiIiAiRSIgIk4iXSBbW10gW10gWyJOIl0gW10gW11dIFsiUSIsIlciLCJJIiwiUCIsIkYiLCJKIiwiSyIsIlgiLCJCIl0tUQ)
[Try my proposed test case](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=NcZnWCCqTmMga1ZnWClmw3LI71tZXWMgJyvDZkBWYyBlIfhYw%2bI&input=WyIiICJCIiAiIiAiVSIgIlQiXSBbWyJPIl0gW10gWyJBIl0gW10gW11dIFsiUSIsIlciLCJJIiwiUCIsIkYiLCJKIiwiSyIsIlgiXS1S)
[Try another case demonstrating multiple yellow letters in the same position](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=NcZnWCCqTmMga1ZnWClmw3LI71tZXWMgJyvDZkBWYyBlIfhYw%2bI&input=WyIiICIiICIiICJVIiAiVCJdIFtbIk8iXSBbIiJdIFsiQSIiQiJdIFsiIl0gWyIiXV0gWyJRIiwiVyIsIkkiLCJQIiwiRiIsIkoiLCJLIiwiWCJdLVI)
[Try a fourth test case with a yellow letter in the same position as a green letter](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=NcZnWCCqTmMga1ZnWClmw3LI71tZXWMgJyvDZkBWYyBlIfhYw%2bI&input=WyIiICJPIiAiIiAiRSIgIk4iXSBbW10gW10gWyJOIl0gWyJUIl0gW11dIFsiUSIsIlciLCJJIiwiUCIsIkYiLCJKIiwiSyIsIlgiLCJCIl0tUg)
Input format in order:
* Green letters as an array with `""` for unkown, e.g. `["", "O", "", "E", "N"]`
* Yellow letters as an array of arrays of letters for each position, e.g. `[[], [], ["N"], [], []]`
* Unguessed letters as an array of letters, e.g. `["Q","W","I","P","F","J","K","X","B"]`
High-level explanation:
```
5ÆgX ªNc kVgX)fÃrÈï[Y]c '+Ãf@Vc e!øXÃâ
5ÆgX ªNc kVgX)fà # Find the valid letters for each position
rÈï[Y]c '+Ã # Generate words from the possible letters
f@Vc e!øXÃ # Ensure that all yellow letters are used
â # Remove duplicates
```
Details:
```
5ÆgX ªNc kVgX)fÃ
5Æ Ã # For each X in range [0...4]:
gX # Return the green letter at index X if possible
ª # Otherwise
Nc # Get all letters from the three inputs
k ) # Remove:
VgX # The yellow letters at index X
f # Remove empty strings
rÈï[Y]c '+Ã
r à # Reduce the array of valid letters in steps:
È # Current array of prefixes
[Y]c # Possible next letters (converted to array if needed)
ï # Cross product of those two arrays
'+ # Concatenate each prefix and letter
f@Vc e!øXÃ
f@ Ã # Remove any word X where this is false:
Vc # Flatten yellow letters to a single array
e # Return true only if every letter:
!øX # is contained in X
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 117 bytes
```
->g,y,u{a,*b=g.map{|x|(x>''?x:u+(g+y.map{_1[0]})*'').chars};a.product(*b).select{|m|y.all?{m[_2]!=_1&&m!=m-[_1]}}|[]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3S3Xt0nUqdUqrE3W0kmzT9XITC6prKmo0KuzU1e0rrEq1NdK1K8Gi8YbRBrG1mlrq6pp6yRmJRcW11ol6BUX5KaXJJRpaSZp6xak5qckl1TW5NZV6iTk59tW50fFGsYq28YZqarmKtrm60fGGsbW1NdGxtVDLIwtKS4oV0qKj1dV1FNT9QQQIu4IIP_VYHS4FKACq8AMKGsUiiakHhnsGuHl5Rzipx-oV5xeVgFypoWaVlZ-ZpwmxYMECCA0A)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~26~~ 24 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as 3 arrays of character strings, or empty strings for blanks, in the order: yellow, green, unguessed. Outputs an array of character arrays
```
c@NcfÃá5 £VíªXÃâ fÈíÀU e
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TmNmIOE1IKNW7apYw%2bIgZsjtwFUgZQ&footer=bazN&input=WyIiLCIiLCJOIiwiIiwiIl0KWyIiLCJPIiwiIiwiRSIsIk4iXQpbIlEiLCJXIiwiSSIsIlAiLCJGIiwiSiIsIksiLCJYIiwiQiJd) - modified to run in a reasonable amount of time without crashing your browser by not allowing letters to be used more than once in each guess.
```
c@NcfÃá5 £VíªXÃâ fÈíÀU e :Implicit input of arrays U=yellow, V=green & W=unguessed
c :Flat map U by
@ :Passing each element through the following function
N : Array of all inputs
c : Flat map
f : Filter empty strings
à :End map
á5 :Permutations of length 5
£ :Map each X
Ví X : Interleave V with X
ª : Reducing each pair by Logical OR
à :End map
â :Deduplicate
f :Filter by
È :Passing each through the following function
í U : Interleave with U
À : Reducing each pair by testing for inequality
e : All true?
```
] |
[Question]
[
[Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) is a stack-based esoteric language with eight commands:
```
() Evaluates to 1
<> Switch active stack; evaluates to 0
[] Evaluates to height of current stack
{} Pop current stack; evaluates to the popped number
(...) Execute block and push the result; evaluates as result
<...> Execute block; evaluates as 0
[...] Execute block; evaluates as negation of result
{...} While top of active stack is nonzero, execute block
```
Write a program or function to detect and remove one common type of [push-pop redundancy](https://codegolf.stackexchange.com/a/95404/69059) that often occurs when writing Brain-Flak code.
# Finding Redundancy
To determine whether a push and pop are truly redundant, we must understand which scopes use the return value of instructions:
* The return value of any top-level instruction is ignored.
* `(...)` will always use the return values of its children.
* `<...>` will always ignore the top-level instruction of its children.
* `{...}` will pass the return values of its children to the enclosing scope; that is, their return values will be used if and only if `{...}` itself is in a scope that uses its return value.
* `[...]` theoretically works like `{...}` in this sense; however, you may assume that `[...]` is always in a scope that cares about return value, thus treating it like `(...)`.
The type of redundancy we are interested in occurs in any substring of the form `(A)B{}` satisfying the following:
* `A` is a balanced string; that is, the parentheses around `A` are matched.
* `(A)` is in a scope that ignores its return value.
* `B` does not contain `[]`, `<>`, or either half of the `{...}` monad.
* The `{}` immediately following `B` pops the value pushed by `(A)`. That is, `B` has an equal number of `{}` and `...)`, and no prefix of `B` has more `{}` than `...)`.
Note that `B` is typically not a balanced string.
# Removing Redundancy
To remove this redundancy, we temporarily introduce a symbol `0` to the language, which evaluates to 0. With this symbol, a redundant string `(A)B{}` can be safely replaced by `0BA`. Since Brain-Flak does not have a `0` symbol, we must make simplifications to remove it:
* A `0` with a sibling can be removed entirely, as can any top-level `0`s. (If there are two `0`s as the only children of a monad, only one of them can be removed.)
* `[0]` and `<0>` can be simplified to `0`.
* If you encounter a `(0)`, find the matching `{}`; replace the `(0)` and matching `{}` with `0`s.
* `{0}` will never happen. If I'm wrong about this, you may have undefined behavior in this case.
# Rules
* Input is a string taken by any reasonable method.
* Input is guaranteed to be valid Brain-Flak code consisting only of brackets.
* Any `[...]` monads in the input will be in scopes that do not ignore their return values.
* Output is a semantically equivalent Brain-Flak program with no push-pop redundancies as defined above.
* The output program must not be longer than the result of the algorithm described above.
* The input might not contain any redundancy; in that case, the input program should be output unchanged.
* If your solution is in Brain-Flak, it should hopefully not detect any redundancy in its own code.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program (in bytes) in each language wins.
# Test cases
With redundancy (with redundant push and pop marked):
```
Shortest redundancy
({}){} -> {}
^ ^^^
First example from tips post
({}<>)({}()) -> ({}<>())
^ ^ ^^
Second example from tips post
({}<({}<>)><>)(<((()()()){}[((){}{})])>) -> (<((()()()){}[((){}<({}<>)><>{})])>)
^ ^ ^^
Inside the zero monad
({}<({}{})>{}) -> ({}{}{})
^ ^ ^^
Inside a loop
{({}{})([{}])} -> {([{}{}])}
^ ^ ^^
Stack height pushed
([][]())({}()) -> ([][]()())
^ ^ ^^
Loop result pushed
({({}[()])}{})(({})) -> (({({}[()])}{}))
^ ^ ^^
Two redundancies
({}<({}{})>)({}{}) -> ({}{}{})
^ ^ ^ ^ ^^^^
Discovered redundancy
(({})){}({}()) -> ({}())
^^ ^^^^ ^^
Chained redundancy
(<(()()())>)(({}){}{}({})) -> (()()()({}))
^ ^ ^^
```
No redundancy (output should be the same as input):
```
-empty string-
(({}<>)({}())) - unlike the second test case, the pushed value is used again
(({}){}) - standard code for doubling the top value on the stack
({}{})<>{} - push and pop not on same stack
(()){{}{}} - loop starts between push and pop
({(({}[()]))}{})([]{}) - stack height is used after push
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~995~~ ~~973~~ 873 bytes
*Nitrodon saved me 22 bytes with a way around the monomorphism restriction*
Not *well* golfed, but golfed a bit.
I implement my own parsing library here. Not a wise idea for golf. If I really wanted to make this short I would probably just use an off the shelf one like `parsec`.
I also lose a ton of bytes to the type and instance declarations. This could definitely be done without them and it would probably save bytes.
```
import Control.Monad
newtype P b a=P{h::b->[(b,a)]}
instance Functor(P b)where fmap f(P p)=P$map(f?)?p
instance Applicative(P b)where pure x=P(\y->[(y,x)]);(<*>)=ap
instance Monad(P b)where P p>>=f=P$(>>=uncurry(flip$h.f)).p
f?x=f<$>x
l=s"("
k=s"()"
o=s")"
w=words
p x=pure x
e=P$p[]
x%y=liftM2(++)x y
P p#P q=P$p%q
b q=P(\x->[(b,a)|a:b<-[x],q a])
t=p?b(p$1>0)
s=mapM$b.(==)
a=foldr(#)e
n p=P(\x->[(x,())|[]==h p x])
v=a[s[x]%c%s[y]%c|[x,y]<-w"() <> {} []"]#s"0"
c=v#s""
d 0=a[n(a$s?w"<> [] { } )")*>a[k,n k*>t]%d 0,o%d 1,p""]
d x=a[n(s"<>"#s"[]")*>k#(p?b(`elem`"(<>[]"))%d x,s"{}"%d(x-1),o%d(x+1)]
f z=a[a[p""|z],(s"{"#s"[")%f z,l%f(0>1),s"<"%f(1>0),v%f z]
m=p""#(t%m)<*q
q=P(\x->[([],"")|[]==x])
z=a[s"0"*>p"",(s"["#s"<")*>z<*(s"]"#s">"),l%z%o*>p"<(0)>"]
r=a[n z*>t%r,z%r,q]
u x=head$(u.snd<$>((>>=h r.snd).h(do x<-f$1>0;l;i<-v;o;y<-d 0;s"{}";((x++'0':y++i)++)?m))x)++[x]
```
[Try it online!](https://tio.run/##ZVRRj9owDH7Pr7AC1cVQELfHIwmaJu1pJyHtsRdtgbaiorSlLZDC8dtvDmwHd3toEn/25882FivbrJM8f3vLNlVZt/CtLNq6zMfPZWFjViSHtqsSmMMCrJqfVk9Pi5GOxCK0aM4sK5rWFssEvu@KZVvWguLwsErqBNKNrSAloEI175Mh0hnOqhvla1Xl2dK22T65o1U7Opyai5fO63ShQ4NTIQcalb1jX8q745GO1iolKUE3VbOr606keVb1V@MUcVyxdOZUKvvasVw1XHC29hdyVtJN10EdyjpuWEX61zJYQvmqyDAXdCrP0vb5ixgO0UHHSK83h633B1u28C/x4v6N5tU@LeQocibcgjXIWlXNFqLqP@oJskbRNJ77i7FQCplVaZnHtehhwgqo3tO4UCC@RkapFVBFlGSvbNRQzmAZNFFH12vkws7I0YG6AKnhdIbIcNNr@ISzpdrTg7MYJsQrhO03swOnqMjACc6AHAfaRuuwgPVAtyagwLCk8zGsODfEcxdeQxxOmSgzEdY94Tv5neTJ5jcXUnsYieXChp/OPIiFGz2iTyTc8BENS@FIeWxESV@PJqR8p0s6jgG5wjxIxUQTg3Q4vf2Ewr13GbZRROqJNtigHGzZbcSRCTm/DscPxgv4ngea4r1C5BWkr/coB2Qbb2uOpHYMSh8mxQQ1dVn7HuFIAwjq8Ejf1rAddb5KbNwXu3FTxLQxwu/UCmpv4ngl4hKcHKX@55zm00yO9tNy2skRjXB6GcNUUPfDh8nDUzccZkg7M9sgOnrQ7/e2sVkBCuKSAfhV@AXiBRyMNG1/@7OtfxRk6TtLUEl4Q4C/FByJDBFweTpLKejQqLWmB60N974QOFlI1fy1fBRqcYfQIAkSAonj8Q@ez4iHPiHSY/oCftB8//zxkSMvaqSnr17vvERxdpdA6nuZS3PXzvAexY@y//FI2qM35ORZkaB/FPTR1/Zv8e8dvmMngVf1fy2Ytz8 "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), Ungolfed
Here's what this looks like ungolfed.
```
balanced :: Parser String
balanced =
( choice
[ string [x]
<> balanced
<> string [y]
<> balanced
| [x, y] <- ["()", "<>", "{}", "[]"]
]
) <|> string ""
<|> string "0"
getBetween :: Int -> Parser String
getBetween pushes
| pushes > 0 =
choice
[ do
notAhead $ string "<>"
notAhead $ string "[]"
start <- string "()" <|> fmap pure (charBy (`notElem` "{})"))
rest <- getBetween pushes
pure $ start ++ rest
, do
string "{}"
rest <- getBetween (pushes - 1)
return $ "{}" ++ rest
, do
string ")"
rest <- getBetween (pushes + 1)
return $ ')' : rest
]
| pushes == 0 =
choice
[ do
notAhead $ string "<>"
notAhead $ string "[]"
notAhead $ char '{'
notAhead $ char '{'
notAhead $ char ')'
start <- choice
[ string "()"
, do
notAhead $ string "()"
chr <-charBy $ const True
return [chr]
]
rest <- getBetween pushes
pure $ start ++ rest
, do
string ")"
rest <- getBetween (pushes + 1)
return $ ')' : rest
, pure ""
]
getBefore :: Bool -> Parser String
getBefore zeroed
| zeroed
=
choice
[ pure ""
, do
next <- choice $ map char "<{["
rest <- getBefore zeroed
return $ next : rest
, do
char '('
rest <- getBefore False
return $ '(' : rest
, do
prefix <- balanced
guard $ prefix /= ""
rest <- getBefore zeroed
return $ prefix ++ rest
]
| otherwise
=
choice
[ do
next <- choice $ map char "({["
rest <- getBefore zeroed
return $ next : rest
, do
char '<'
rest <- getBefore True
return $ '<' : rest
, do
prefix <- balanced
guard $ prefix /= ""
rest <- getBefore zeroed
return $ prefix ++ rest
]
mainParser :: Parser String
mainParser =
do
before <- getBefore True
char '('
inside <- balanced
guard $ inside /= ""
char ')'
between <- getBetween 0
string "{}"
after <- many $ charBy $ const True
end
return $ before ++ "0" ++ between ++ inside ++ after
zero :: Parser String
zero =
choice
[ char '0' *> pure ""
, choice
[ char x *> zero <* char y
| [x, y] <- ["[]", "<>"]
]
, do
char '('
zero
char ')'
return $ "<(0)>"
]
removeZeros :: Parser String
removeZeros =
choice
[ do
notAhead zero
chr <- charBy $ const True
rest <- removeZeros
return $ chr : rest
, zero <> removeZeros
, end *> pure ""
]
run :: String -> String
run input =
case
map snd $ apply (compose mainParser removeZeros) input
of
[] ->
input
x ->
head $ map run x
```
[Try it online!](https://tio.run/##zVfdb9s2EH/XX3FwA5hsnS7xYyELSLsVKNACA7anuUJKx3QsTJYESU7sJfnbszvyKJGy3bXYCuwhjnT3u@8PUmvV/Knz/Pnh/AV8VMXtVt1qeJ/rXbbI9YeiaVVxoxt4cf4UZZuqrFv4tdb5dqlhnS2z4jYCEKAWDf6XDvGuLNq6zF9fVVWe3ag2u9MGlmer9mqKjxO4yltdF4YF4vVreUz8U1mopRG8K7OlEUP36qWP/Vm1ioAWIEDEiTzgv1ur2nCz5iqv1soAokLft/tKw6@qbnQNCmZI5xfxW1tjcHCewJyfJ6BkimIKg9rDmze9HIJOwBksGFpJaIyVCv9HUcbZhffb4qYta6fxfq1rSthqoypYIc9XQOKdm2cWI8xPB5cSKk@7V4WhhWpba9iFOgV8hsYLp@FwdjKlrAFXEVa9V5eyf56GLppHGChdlkxGRq03lxOodYNK4nPUxbgAMTWIqUVMgWQ6fq3bbV042MqosmiGSC8XpqWGWXCuQ5LMUMG/cn/oPTfAiiGe575b/jQMnNObqt0fVujaFIcqAuCFcAnxY9K9TYfdEsbR5RpevSIwv/iOCTta2MswS4BfXK2R6Lzc@G6arrIUYmEKdLFkHjcPE6PoBkfzrRknQVNKbr0ty1zSA5sx08u4qtZL6mXtD@st1cN5AvgKQsEbWLhOBJiDWNBAwqOnQUHq8JjIDppap8gl59HQER4Z9knsZjPMGWcPxfplwIKW4BAk2tbqTiPP6CCDZYbZRtm5y23qySsHINFVmS@xB7DO0jZHFFF6@4UkZOTy7SfIT9EwaAxbzNMJisq0B1z7fExLUbZXa62Ww@XX2@0QlSV5PkRujrKi2rYoxqpvVKMH08LCBsiscuV50gtbzw0wcB7MfPggy8Ey3ZR4MDTai@GgXCpMPQtYry75/9SL7VRo/p64NkvC7Ag/yMsgyjABtOcadvt5oXIayOWB31HHmZkjznZKZLueO26@c4mJE3D4nuJQ@1OoR9QwgX1K3s9HQo4mMIoT@n14ot95OrKi9CvNCmKdo5Gh@5SLURTd6vatbu@1LiieD0V7OCwepNo2a5OJR36EBC54Ar1gu3R3XXjWGUVvTzPRfWbi1sM7A0bpWBircd6crWavCTf1X1DTL7nefKEsyJF0xw0Wzag4FkC3Hc/YFC5ewhvWpI/Amcf0ntYqOBnncNnbNmfhmZH8J@XyG3S/OqJ7LMe4XTvNqV@Y2ewHVcZjmg08fhh/P0eOh3X23AwmhgrfUSf@JB/100dT7DXq5j5B2yWepvB7vdUehrM5R2y/tNIf0EL/UZUn1ijPc8ojvCprs0npyD4xwgbyl65Ls0se@0d7tgQFmAdGBokv9M4rGXpII2nqOoof5iPvPujFGVofhGg0ejEODNqeEeOvaH6vcu/06nMnxl/RizeQVbYjRYNVDPbzBhUw5KdZn4vvCYzF/c5wc1q2eAm4z4zXRyvwbRkXPzDj8dcyHoxRn/D4f5nwaKOygmfi4Nz2eFQI9ndhDR2POehIvKNnS30QlYuI2X1EwQpc8AYI98FFdOzwUSv8OCHkRhV73qXHFhvd54OscCyYFTz06Z@zio/sHj4Z9VFEqT1MkqEenCc2lIsxvEyCjTEZNjNf1hFmFMUvLWXPgPBeg4eNvdekkb@OvVYabATSGXC686U/h2NxIZNuaUYRfgCWd/oPlGwOo/WZ33CIBvZrO6mnzhzXy56Joa@kI9j4NmfJgcyESj3MPUZXb4vw88eFhXR7NTZBuQs/bZOmoF7lj2R30/YmwzMtu6syfwz4HwL9LXrXE/mQJjvkwu6ZFMPMZhKpn65BfDYCGEmLzn5EECTemzBysqfB6HMxMmflnI6dpzgW@JPIJEnwAb9ATDImtCCfJA8QNRW9JsKj4OcWkoSQKEP0gDOkEGlAiYmWGGJgs/ujn1AmNtbQXmK5xDSoUeQpiBPfjAnORiZ9qgzNHsihaaL2lAeSmguJgRDaht/juwg72oOQ1roLIX3@Gw "Haskell – Try It Online")
[Answer]
# JavaScript, ~~449~~ ~~600~~ 580 bytes
*-13 bytes thanks emanresu A*
(@WheatWizard wrote their answer first, causing me to look at this challenge; this answer is not intended to steal their glory)
```
x=>{for([...x].reduce((_,b)=>"({[<".includes(b)?(y.unshift([b,--i+"#"]),y[1].push(y[0])):(b==")"&&y[0][2]&&j.push(y[0][1]),x=y.shift()).push(b!="}"|x[3]?b:b+(j.pop()||"-0#")),y=[[]],i=0,j=[]),y=y[0].reduce(g=(a,b)=>b[3]?a+b[0]+b[1]+b.slice(2,-1).reduce(g,"")+b[1]+b.pop():a+b[0]+b[2],"");x!=y;)y=(x=y).replace(/(((<-\d+#|^)([<[({]((-\d+#).+\5)?[\])}>]|X)*)(({-\d+#|^)([<[({]((-\d+#).+\11)?[\])}>]|X)*)*)\((-\d+#)(.*)\12\)(((?!\[\]|<>|\{-|#}).)*){}\12|\((-\d+#)(X)\16\)(((?!\[\]|<>|\{-|#}).)*){}\16|\[-\d+#X-\d+#\]|<-\d+#X-\d+#>/,"$1X$18$17$14$13");return y.replace(/-\d+#|X/g,"")}
```
[Try it online!](https://tio.run/##fZH/bpswEMdfZXFQdFfAidOtq1JMXgPJeBNOaEuEQgShAmGePTsTpen@2GTprPP3cz99yD6yZlcXp3P48XzZVcemKnNeVm8Al07Gw2tVg@Kcd5rX@b7d5QC/A4MyZjCoiPHiuCvbfd6AwS30vD0278XrGZQJwrDw2ZxpDHolND@1zTv0aqURN2CkZMgWC@ertV4sDnedYAw62fNrJsSrZGaSjcx26lFvzcb4QCHVCdBaFq7mDKmMVErroJCr4CCVqytdvlvfbxKyqXPjUmS@IY2MIMObsiBiHYQCP/GAMbzpU6XNZ8xaO/Glm8n@BXsJ1K2LO5UZBS4BIArTvT@3vxBUpGDQANMDcj/9gVuVahxjbRN8QIDh36wQf8MPmN5U4OSIdUoJYDtLibJRbNMhtPMROZHDSLK98wnhT//Hn2yqJjqZrGO@uPEyYJ5IPPHsiZ@e@O6JR9pBnZ/b@vitv49/HSdZTgscLwgMIgB0B2M370jFhtHdSN92@QM "JavaScript (V8) – Try It Online")
A horrific solution that uses string manipulation.
First, it recursively parses the program and adds annotations:
```
original:
(<(()()())>)(({}){}{}({}))
annotated:
(-1#<-2#(-3#()()()-3#)-2#>-1#)(-7#(-8#{}-1#-8#){}-8#{}-3#(-12#{}-0#-12#)-7#)
```
The `-N%`s inside brackets denote matching brackets. Additionally, `{}`s are annotated with the `-N#` of the `()` they pop.
Then, regex substitutions are repeatedly applied until it stabilizes (`X` is used instead of `0`):
(this is an explanation of the old regex; the new one that accounts for more cases is beyond explanation)
```
/\((-\d+#)(.*)\1\)(((?!\[\]|<>|\{-|#}).)*){}\1/X$3$2
\( literal open paren
(-\d+#) group 1, matches a -N#
(.*) group 2, this is A
\1\) matching close paren
(((?!\[\]|<>|\{-|#}).)*) group 3, this is B
(?!\[\]|<>|\{-|#}) there can be no [], <>, {-, or #}
{}\1 the {} that pops (A)
X$3$2 replace with X, followed by groups 2 and 3
/\[-\d+#X-\d+#\]/X replace [-N#X-N#] with X
/<-\d+#X-\d+#>/X replace <-N#X-N#> with X
```
In the actual implementation, these are all combined into a single unioned regex.
The `(0)` case from the original algorithm is just a special case of the `(A)B{}` -> `0BA` transformation, so no special casing is needed for it.
Once it stabilizes, all `X`s (these must be have a sibling) and `-N#`s are removed, and the resulting string is returned.
] |
[Question]
[
The sound of the [theremin](http://en.wikipedia.org/wiki/Theremin) has been immortalized in [The Beach Boys song *Good Vibrations*](https://www.youtube.com/watch?v=QSLMWasU0rM&feature=kp). Many also associate its sound with the theme for the original series of *Star Trek*, though [apparently it was a soprano's emulation](http://tvtropes.org/pmwiki/pmwiki.php/Main/Theremin).
This challenge requires you to implement a [theremin](http://en.wikipedia.org/wiki/Theremin).
# Input
* Take 2 dimensional input from a mouse or other input device (e.g. you could use a joystick), which will produce a tone from an audio output device as follows:
+ increasing x will increase the frequency of the tone. Note that frequency increases exponentially with musical note, so you must implement a linear relationship between mouse x position and the musical note, and
+ increasing y will increase the volume of the tone.
* There appears to be [confusion regarding the waveform produced by a real theremin](http://csound.1045644.n5.nabble.com/Theremin-sound-td1110719.html), so for simplicity, a sine wave (or close approximation thereof) must be used.
# Rules
* The tone produced must have at least a 2-octave range. More range is acceptable. A-440 must lie within the range.
* In order to create the audible appearance of continuously variable frequency and amplitude, the range of values considered in both dimensions from the input device must be at least 500 Implementations may open a window (at least 500x500 pixels) to read input from mouse cursor position. Or without opening a window, coordinates may be read directly from the mouse or other input device.
* There must be a simple means to stop the program - key-combination, mouse-click or other common input device. CTRL-c is sufficient.
* Any standard libraries may be used, as long as they do not totally implement the solution with no other work required.
* Standard rules for [Code Golf](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and [I/O](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* You may stop by having the mouse or input device lose focus on the input box.
## Notes
* Because the output tone is dynamically-generated, care must be take to ensure the tone is a continuous waveform; that is there are no audible clicks or pops caused by sudden changes of phase or amplitude.
* You may limit the input size zone to 500 by 500 but it may be bigger.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in any language wins.
## Special thanks
Special thanks to Digital Trauma for making this challenge and posting it in the Secret Santa's Sandbox. I have made a few edits and [here](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/1389#1389) is the original post.
[Answer]
# JavaScript ES6, ~~215~~ 188 bytes
This seems to work well in Chrome and Edge. Firefox and Safari not so much.
```
with(new AudioContext)o=createOscillator(onmousemove=e=>{o.frequency.value=9/innerWidth*e.x**2,v.gain.value=1-e.y/innerHeight}),v=createGain(),v.connect(destination),o.start(),o.connect(v)
```
Saved 27 bytes thanks to [@darrylyeo](https://codegolf.stackexchange.com/users/47097/darrylyeo)
### Try it online!
```
with(new AudioContext)o=createOscillator(onmousemove=e=>{o.frequency.value=9/innerWidth*e.x**2,v.gain.value=1-e.y/innerHeight}),v=createGain(),v.connect(destination),o.start(),o.connect(v)
```
```
<button onClick="o.stop()">Stop</button>
```
] |
[Question]
[
## Background
I wanted to make a pretty word cloud, like this:
```
these are
words
floating
```
I computed the `(x,y)`-coordinates of the first letter of each word, plugged them into my word cloud generator, and let it do its job.
However, I accidentally used `(y,x)`-coordinates, so the result looks like this:
```
these
floating
words
are
```
Since I'm too lazy to re-compute the coordinates, I need you to transpose the word cloud for me.
## Input
Your input is a rectangular grid of lowercase ASCII letters and spaces.
This means that every row is padded with spaces to have the same length.
The input can be taken as a multi-line string or an array of strings.
A *word* is a horizontal segment of letters, and its *position* is the `(x,y)`-coordinates of its leftmost letter, the upper left corner of the grid being `(0,0)`.
There will always be at least one word, and there are no trailing rows or columns of spaces.
However, leading rows or columns of spaces may be present.
## Output
Your output is another rectangular grid of characters, obtained by moving every word with position `(x,y)` to position `(y,x)`.
Your output **must not contain** extra trailing rows or columns of spaces.
Leading rows and columns must be preserved, and the output **must be rectangular**.
You may assume that this transformation does not create overlapping words, and does not merge several words into one.
This means that running the program on the output should produce the original input.
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
## Test cases
For clarity (and since Stack Exchange dislikes space-only lines), every row ends in a pipe character `|`.
**These are not part of the actual input or output**, and you should remove them.
Note again that running the program on each output should also produce the corresponding input.
```
Input:
oneword|
Output:
oneword|
Input:
spaces|
Output:
|
|
spaces|
Input:
|
row|
Output:
row|
Input:
these are|
words |
|
floating |
Output:
these |
|
floating|
|
words |
|
|
|
are |
Input:
same|
the |
|
same |
Output:
same|
the |
|
same |
Input:
some |
words k|
|
|
|
still|
Output:
words |
|
some still|
|
|
|
k |
Input:
hello |
world hey|
what up |
Output:
what|
|
world|
hello |
|
|
|
up |
hey |
Input:
a b a d cc|
g h huh nng|
ye dunnn |
dud yo |
wha g |
huh heh hah|
Output:
|
g wha |
a ye huh|
h |
b dud |
dunnn |
huh heh|
a g |
|
d yo |
nng hah|
cc |
```
[Answer]
# Perl, 58 bytes
Added +2 for `-lp`
Give input on STDIN, run as `perl -lp wordcloud.pl`
`wordcloud.pl`:
```
s/\w+/$l|=$a[pos]|=$"x~-$..$&/eg}for(@a){$_|=$l=~y// /cr
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 107 bytes
```
{x←' '⍴⍨×⍨2/⌈/⍴⍵⋄(⌈⌿↑⍸' '≠x)↑x⊣{x⊢←(⊃⍵)@((⊃⌽⍵)∘+¨↓0,⍪1-⍨⍳≢⊃⍵)⊢x}¨↓(⊃,/' '(≠⊆⊢)¨↓⍵),⍪⌽¨⍸2{1 0≡' '=⍺⍵}/' ',⍵}
```
[Try it online!](https://tio.run/##bVBNSwJRFN37K97uKSl@RBSBELipbbVp@XLGmeg1I42SIq6KQc0nRUgt@9hIBC5KiCAC@yf3j9i5zyKDHsx79557zrn3jqrqjNNUOvRmNBiW9oR0KkEkE9SJS4LiC9Ei81acjvPruqwiV5CZtGetBipSSDIvZEaf17gKWep3shaY0PlZEhn1Pyi@JPPKzO5tI4WsQb0HqHv3MEhS7xTs1EbSRv13TqhzszQdUXyVS5N5zGdgTeaZuvffZEgbbUtgUToL7yTMqRejkrIFprEYjsjNa6GVFznq3oFaxDK8AcvSdpUKBiEzsO5PGH86XuahB8Od7RLu3c2tnZkHTgsJnpVcVmYkFqzYP5HwRF6sQibDwD0Jjx1pkTVGhIiqquxGDMFS1nwX/w9HHbtozxErIrw2rehQ1Q4CD@m3ApVIHVkyxD88exBxSSySoxAACnPXwz/k/6OodqD1Qjff1Tr8KcJGO4CabOmrGvB6dbGfEvt8OaJcZoEnfDjUfREEnjVousKpB0Hw29epO4DDeQ5PQN7vNKz1XXzKl18 "APL (Dyalog Unicode) – Try It Online")
Makes an over-big matrix of spaces, and adds in the required words using `@`. Then, crops back to the required size.
] |
[Question]
[
>
> **Edit:** Bounty puzzle at the end of the question.
>
>
>
Given a set of 1-digit numbers, you should determine how tall a tower they can construct.
The digits live on a horizontal plane with a ground level where they can stand. No digit wants to be confused with a multi-digit number, so they always have an empty space on both of their sides.
```
4 2 1 9 6 8
```
A digit can be on top of another one:
```
2
6
```
or can be supported by two other diagonally below it:
```
9
5 8
```
The bottom one(s) have to support the weight the upper one supports (if there is any), plus the upper one's weight **which is always 1**. If there are two supporters, they split the upper one's total weight evenly (50%-50%).
*The weight of every digit is 1 independent of it's value.*
If one digit supports two others it has to be able to support the sum of their corresponding weight. **A digit can support at most its numerical value.**
Some valid towers (with heights `4`, `3` and `5`):
```
0
7 1
5 1 1 1 9 supports a total weight of 1.5 = (1+1/2)/2 + (1+1/2)/2
2 5 4 5 5
3 5 9 5 5 6 3 6 supports a total weight of 3 = 1.5 + 1.5 = (2*1+(2*1/2))/2 + (2*1+(2*1/2))/2
```
Some invalid towers:
```
1 5 The problems with the towers are (from left to right):
1 12 2 3 8 1 can't support 1+1; no space between 1 and 2;
1 5 6 1 1 1 9 1 can't support 1.5 = (1+1/2)/2 + (1+1/2)/2; 8 isn't properly supported (digits at both bottom diagonals or exactly below the 8)
```
You should write a program or function which given a list of digits as input outputs or returns the height of the highest tower constructable by using some (maybe all) of those digit.
## Input
* A list of non-negative single-digit numbers with at least one element.
## Output
* A single positive integer, the height of the highest constructable tower.
* Your solution has to solve any example test case under a minute on my computer (I will only test close cases. I have a below-average PC.).
## Examples
Format is `Input list => Output number` with a possible tower on the next lines which is not part of the output.
```
[0] => 1
0
[0, 1, 1, 1, 1, 1] => 3
0
1
1 1
[1, 1, 1, 1, 1, 2, 2] => 4
1
1
1 1
1 2 2
[0, 0, 2, 2, 2, 2, 2, 5, 5, 5, 7, 7, 9] => 9
0
2
2
5
5
5
7
7
9
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5] => 9
1
2
2
3
4
5
3 3
4 4 4
5 5 5 5
[0, 0, 0, 0, 0, 1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 7, 7, 9] => 11
0
1
2
3
4
5
3 3
4 5
5 5
3 7 3
2 7 9 2
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9] => 12
0
1
2
3
4
5
6
7
4 5
6 7
8 8
9 9
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9] => 18
0
1
2
3
4
5
6
7
8
9
5 5
6 6
7 7
4 8 4
3 7 7 3
2 6 8 6 2
2 5 8 8 5 2
3 9 9 9 9 3
```
This is code-golf, so the shortest entry wins.
## Bounty
I will award **100 reputation bounty** (unrelated to the already awarded one) for solving the extended problem below in polynomial time (in regard to the length of the input list) or proving that it isn't possible (assuming P!=NP). Details of the extended problem:
* input numbers can be any non-negative integers not just digits
* multi-digit numbers take up take same place as single-digit numbers
* multi-digit numbers can support they numerical value e.g. `24` can support `24`
The bounty offer has no expiry date. I will add and reward the bounty if a proof appears.
[Answer]
# Python 2 - 326
Runs easily under the time limit for all the examples given, though I did sacrifice some efficiency for size, which would probably be noticeable given much larger inputs. Now that I think about it though, since only single digits numbers are allowed the largest possible tower may not be very big, and I wonder what the maximum is.
```
def S(u,c=0,w=[]):
for(s,e)in[(len(w),lambda w,i:w[i]),(len(w)+1,lambda w,i:.5*sum(([0]+w+[0])[i:i+2]))]:
m=u[:];l=[-1]*s
for n in u:
for i in range(s):
if 0>l[i]and n>=e(w,i):m.remove(n);l[i]=n;break
if([]==l or-1in l)==0:
for r in S(m,c+1,[1+e(w,i)for i in range(s)]):yield r
yield c
print max(S(sorted(input())))
```
] |
[Question]
[
A [magic square](https://en.wikipedia.org/wiki/Magic_square) is an **n-by-n** square grid, filled with distinct positive integers in the range **1,2,...n^2**, such that each cell contains a different integer and the sum of the integers in each row, column and diagonal is equal.
Your task is to take an **n-by-n** matrix consisting of positive numbers, and a placeholder character for empty cells (I'll use **0**, but you can use any non-numeric character or datatype you like), and determine if it's possible to make a magic square by filling in the missing numbers
The matrix will be at least **2-by-2**, and at most **10-by-10**. The smallest possible non-trivial magic square is **3-by-3**. The numbers in the input matrix might be higher than **n^2**, and it's possible that all cells are filled.
## Test cases:
```
2 2
2 0
False
8 0 6
0 5 0
0 9 2
True
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
True
10 0 1
0 5 9
3 7 5
False
99 40 74 8 15 51 0 67 0 1
0 41 55 14 0 57 64 0 98 0
81 47 56 20 22 63 70 54 0 88
0 28 0 21 0 69 71 60 85 19
0 34 0 2 9 75 52 61 0 25
24 65 49 0 90 26 33 42 17 76
0 0 30 89 91 0 39 48 0 82
6 72 31 95 0 38 45 29 0 13
12 53 0 96 78 0 0 0 10 94
18 59 43 77 0 0 27 36 0 100
True
```
[Answer]
## JavaScript (ES6), ~~270~~ 268 bytes
Takes the matrix as a 2D array. Returns `0` or `1`.
```
a=>(g=(x,y=0,w=a.length,p,R=a[y])=>[0,1,2,3].some(d=>a.some((r,y)=>(p=s)^(s=r.reduce((p,v,x)=>(o|=1<<(v=[v,(b=a[x])[y],b[x++],b[w-x]][d]),p+v),0))&&p),s=o=0)||o/2+1!=1<<w*w?R&&[...Array(w*w)].map((_,n)=>(p=R[x])==++n|!p&&(R[x]=n,g(z=(x+1)%w,y+!z),R[x]=p)):r=1)(r=0)&&r
```
### Test cases
This is definitely too slow for the last test case. :-(
```
let f =
a=>(g=(x,y=0,w=a.length,p,R=a[y])=>[0,1,2,3].some(d=>a.some((r,y)=>(p=s)^(s=r.reduce((p,v,x)=>(o|=1<<(v=[v,(b=a[x])[y],b[x++],b[w-x]][d]),p+v),0))&&p),s=o=0)||o/2+1!=1<<w*w?R&&[...Array(w*w)].map((_,n)=>(p=R[x])==++n|!p&&(R[x]=n,g(z=(x+1)%w,y+!z),R[x]=p)):r=1)(r=0)&&r
console.log(f([
[ 2, 2 ],
[ 2, 0 ]
]));
console.log(f([
[ 8, 0, 6 ],
[ 0, 5, 0 ],
[ 0, 9, 2 ]
]));
console.log(f([
[ 16, 2, 3, 13 ],
[ 5, 11, 10, 8 ],
[ 9, 7, 6, 12 ],
[ 4, 14, 15, 1 ]
]));
console.log(f([
[ 10, 0, 1 ],
[ 0, 5, 9 ],
[ 3, 7, 5 ]
]));
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~45~~ 38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
gn¹à@¹˜āsKœ0ªεΘr.;¹gôD©ø®Å\®Å/)O˜Ë}à*
```
Also uses \$0\$ as placeholder. The more \$0\$s in the input, the slower the program is. Size of the matrix doesn't matter that much (a 10x10 matrix with three \$0\$s runs quite a bit faster than a 3x3 matrix with seven \$0\$s).
Could have been 4 bytes less, but there is currently a bug in the builtin `.;` with 2D lists. `:` and `.:` work as expected, but `.;` doesn't do anything on 2D lists right now.. hence the work-around of `˜` and `¹gô` to flatten the matrix; use `.;` on the list; and transform it back into a matrix again.
[Try it online](https://tio.run/##FY8hT0RBDIR/D@QLbNvd7ttgEDgEP@A4AQkhGEg4jUCgSDDYE2dBoCDh7FtQl/CXHn1JUzEznZnerS4ub66m6fp23PbN8bjdrX8eV6e/r2l8//vqL7v1/cHRuL3unyfjW/8eP/rT@bwO98526/780Df707RYmFAdMcwZBBnQRs2ILFmokhMlsEouuKEJGygepAdGDrHSSHgh1DUIS9SCKKbUimQsUxsyX6lgjVJRIwuloYVs@JznTqADHhGUsImhaDCJISFxNVANiRYWmVJmRydnXJGGhTx6RC/FU5BVCK@wj4/IjjecIsvlPw) or [verify some more test cases](https://tio.run/##dZG9SgRBEIRf5bhMKXS6528HAw0uMzASDtYLFERMFBQEAwMDTcw0NTDVwEjB@FYjwYfwRc7q2VMQFJbd2Z7pqq96Do@3d/Z3Zyenq8PB5@X1YLh6Otqc7R2Mu7u18fvt6/nx@tuNmz58PDv@Hi2tjPe6p9H0vnuZPnYXW/ZaXth4v@2uzrq7xRlmbdsqdAK@3WSCQds2cEgsOESW7Ft4oG5JgsJDPMsRIhCHhuuCjAQxmQDhw82fDvd/h/ujwbFB5vaFX8@Tsd@zLfeLzH1D0yKbUGBZlNKFZlw3ZijUsHpkn0LS3MmbUwPNxqW9YECNW@pIKKRiqkp5Ro@GY3EiPOcQetUMTdWlWIxvLqUzMbyf8wlyMhCf0Ei15QhCD6mKwEwVJUQkTxr4BtGuIbGGwMNKMN6MRQi5J8kcmxpLruGNqFg@Sgp8QcyGHgSRgSKCRzK/RC6EBokWiJRxNmOt5I2zSZI@ewvl65AsOEOGgKSW0/M4OcjFUVviLKAW5ZkIISEVZo@80skX). (NOTE: Last test case of the challenge description is not included, because it has way too many 0s..)
**Explanation:**
```
g # Get the length of the (implicit) input-matrix (amount of rows)
# i.e. [[8,0,6],[0,5,0],[0,0,2]] → 3
n # Square it
# → 9
¹ # Push the input-matrix again
à # Pop and push its flattened maximum
# → 8
@ # Check if the squared matrix-dimension is >= this maximum
# → 9 => 8 → 1 (truthy)
¹ # Push the input-matrix again
˜ # Flatten it
# → [8,0,6,0,5,0,0,0,2]
ā # Push a list in the range [1,length] (without popping)
# → [1,2,3,4,5,6,7,8,9]
s # Swap so the flattened input is at the top of the stack again
K # Remove all these numbers from the ranged list
# → [1,3,4,7,9]
œ # Get all possible permutations of the remaining numbers
# (this part is the main bottleneck of the program;
# the more 0s and too high numbers, the more permutations)
# i.e. [1,3,4,7,9] → [[1,3,4,7,9],[1,3,4,9,7],...,[9,7,4,1,3],[9,7,4,3,1]]
0ª # Add an item 0 to the list (workaround for inputs without any 0s)
# i.e. [[1,3,4,7,9],[1,3,4,9,7],...,[9,7,4,1,3],[9,7,4,3,1]]
# → [[1,3,4,7,9],[1,3,4,9,7],...,[9,7,4,1,3],[9,7,4,3,1],"0"]
ε # Map each permutation to:
Î # Push 0 and the input-matrix
˜ # Flatten the matrix again
r # Reverse the items on the stack, so the order is [flat_input, 0, curr_perm]
.; # Replace all 0s with the numbers in the permutation one by one
# i.e. [8,0,6,0,5,0,0,0,2] and [1,3,4,7,9]
# → [8,1,6,3,5,4,7,9,2]
¹g # Push the input-dimension again
ô # And split the flattened list into parts of that size,
# basically transforming it back into a matrix
# i.e. [8,1,6,3,5,4,7,9,2] and 3 → [[8,1,6],[3,5,4],[7,9,2]]
D # Duplicate the current matrix with all 0s filled in
© # Store it in variable `®` (without popping)
ø # Zip/transpose; swapping rows/columns of the top matrix
# → [[8,3,7],[1,5,9],[6,4,2]]
®Å\ # Get the top-left to bottom-right main diagonal of `®`
# i.e. [[8,1,6],[3,5,4],[7,9,2]] → [8,5,2]
®Å/ # Get the top-right to bottom-left main diagonal of `®`
# i.e. [[8,1,6],[3,5,4],[7,9,2]] → [6,5,7]
) # Wrap everything on the stack into a list
# → [[[8,1,6],[3,5,4],[7,9,2]],
# [[8,3,7],[1,5,9],[6,4,2]],
# [8,5,2],
# [6,5,7]]
O # Sum each inner list
# → [[15,12,18],[18,15,12],15,18]
˜ # Flatten it
# → [15,12,18,18,15,12,15,18]
Ë # Check if all values are the same
# → 0 (falsey)
}à # After the map: Check if any are truthy by taking the maximum
# → 1 (truthy)
* # And multiply it to the check we did at the start to verify both are truthy
# → 1 (truthy)
# (after which the result is output implicitly)
```
The part `D©ø®Å\®Å/)O˜Ë` is also used in [my 05AB1E answer for the *Verify Magic Square* challenge](https://codegolf.stackexchange.com/a/178959/52210), so see that answer for a more in-depth explanation about that part of the code.
] |
[Question]
[
## Task
Given a matrix, your program/function should output a [row-equivalent](https://en.wikipedia.org/wiki/Row_equivalence) matrix in checkerboard form ( \$A\_{ij}=0\$ if and only if \$i+j\$ is odd).
Two matrices are defined to be row-equivalent if and only if one can be obtained from the other by a sequence of elementary row operations (EROs), where each ERO consists of performing one of the following moves:
1. Swapping two rows
2. Multiplying one row by a nonzero rational constant
3. Adding a rational multiple of one row to another row
Since there are multiple possible outputs for each input, please include a way to verify that the output is row-equivalent to the input, or explain enough of your algorithm for it to be clear that the output is valid.
## Example
Input:
```
2 4 6 8
0 2 0 4
1 2 5 4
```
Subtracting row 2 from row 3 yields
```
2 4 6 8
0 2 0 4
1 0 5 0
```
Subtracting double row 2 from row 1 yields
```
2 0 6 0
0 2 0 4
1 0 5 0
```
That is one possible output. Another possible matrix output is
```
1 0 3 0
0 1 0 2
1 0 4 0,
```
which is also row-equivalent to the given matrix and is also in checkerboard form.
## Constraints
* The given matrix will have at least as many columns as rows and contain only integers (your output *may* use rational numbers, but this is not strictly necessary since you can multiply by a constant to obtain only integers in the output).
* You may assume that the rows of the matrix are linearly independent
* You may assume that it is possible to express the given matrix in checkerboard form
Input and output may be in any reasonable format that unambiguously represents an `m×n` matrix.
## Sample Test Cases
Each input is followed by a possible output.
```
1 2 3
4 5 5
6 5 4
1 0 1
0 1 0
1 0 2
1 2 3
4 5 5
2 0 -1
1 0 1
0 1 0
1 0 2
2 4 6 8
0 2 0 4
1 2 5 4
1 0 3 0
0 1 0 2
1 0 4 0
1 2 3 2 5
6 7 6 7 6
1 2 1 2 1
1 0 1 0 1
0 1 0 1 0
1 0 2 0 3
3 2 1 10 4 18
24 31 72 31 60 19
6 8 18 9 15 7
8 4 8 20 13 36
3 0 1 0 4 0
0 1 0 5 0 9
2 0 6 0 5 0
0 8 0 9 0 7
3 2 1 10 4 18
24 31 72 31 60 19
0 4 16 -11 7 -29
8 4 8 20 13 36
3 0 1 0 4 0
0 1 0 5 0 9
2 0 6 0 5 0
0 8 0 9 0 7
1 0 0 0 -2
0 1 0 1 0
0 0 1 0 2
3 0 1 0 -4
0 2 0 2 0
5 0 3 0 -4
```
Related:
* [Create a checkerboard matrix](https://codegolf.stackexchange.com/questions/126699/create-a-checkerboard-matrix)
* [Reduced Row-Echelon Form of a Matrix](https://codegolf.stackexchange.com/questions/59307/reduced-row-echelon-form-of-a-matrix)
[Answer]
# MATLAB - ~~114~~ 129 bytes
```
function n=c(m)
n=rref(m);l=size(n,1);for i=1:l
e=1.5+.5*(-1)^i:2:l;N=n(e,:);n(e,:)=N+repmat(n(i,:),length(e),1).*max(N).^2;end
```
[Try it online](https://tio.run/##lU/baoQwEH33K@Yx6eri5KKrIV9StrDY2AbcWKztQ3/eziTPCy1yJnPmXMB12m/f4TjmrzTtcU2Q/CTuskp@28JMm1v8Z/wJItUo3bxuED2OSxU8nu3pbJ9Eg/IljmpcXBKhHqUvz2kLH/fbLpKIxOolpLf9XQTJNSG9ZhyTeFZgoIOLgxYUwThAWiyYq6xIZqIdeSxYR8YHAkcbLMpfGvnAdX1BsWQUkwba6QBIBTSpTRnQCL3i2bWAA@fhwiIMNC30jqnJR0UODbr7T12bw9jRn5ACjRoeFiKZ@WsUx7DA5RMTdZXHLw)
For a given nxm matrix, there are three forms of the rref of the matrix.
1. The identity matrix (with optional all-zero columns) (m>=n)
2. Full rank matrix where columns that do not contain a row-leading 1 can have any value (m>n)
3. Identity matrix with zero rows on the bottom (m<n)
1 and 3 are easily made into a checkerboard by looping through each row and adding every odd/even row (which would have the 1s in the appropriate places)
for 2, however, it is impossible to make a checkerboard matrix unless the matrix is already a checkerboard. This is because the columns that have nonzero values can never be reduced because there is no column with a row-leading 1, and any ERO would add a value in another space that would ruin the checkerboard pattern. I'm certain there's a more rigorous explanation but linear algebra is not easy.
[Answer]
# Python3, 941 bytes:
```
from math import*
E=enumerate
Z=zip
T=lambda x:[i>0 for i in x]
lcm=lambda a,b:abs((a*b)//gcd(a,b))
U=lambda i,r,m:m[:i]+[r]+m[i+1:]
G=lambda r:all(r[i+1]for i,a in E(r)if a==0 and i+1<len(r))
v=lambda m:all(not any(r[not i%2::2])and all(r[i%2::2])for i,r in E(m))
S=lambda m:sum(sum(not i for i in b)for b in m)
def f(m):
q,Q=[m],0
while q:
if v(m:=q.pop(0)):return m
for x,a in E(m):
for y,b in E(m):
if x<y:
if all(j.count(0)==len(j)//2 and G(j)for j in m):q+=[m[:x]+[b]+m[x+1:y]+[a]+m[y+1:]]
for c in[1,-1]:
if 0 in(R:=[j+k*c for j,k in Z(a,b)]):
if T(b)!=T(R):q+=[U(y,R,m)]
if T(a)!=T(R):q+=[U(x,R,m)]
for j,k in Z(a,b):
if j and k:
L=lcm(j,k);A=[i*(L//j)for i in a];B=[i*(L//k)for i in b]
if 0 in(R:=[J+K*c for J,K in Z(A,B)])and T(b)!=T(R):
if(n:=S(u:=U(y,R,m)))>Q:Q=n;q+=[u]
if 0 in R and T(a)!=T(R):
if(n:=S(u:=U(x,R,m)))>Q:Q=n;q+=[u]
```
[Try it online!](https://tio.run/##jVNbT9swFH6ef8UZ04TdBkjSGxiMBBJCAjSJUl7Ioslp0@FSJ2mSsnZ/vjt22kJHq02RE/u72eckyeblc5o0jrN8sRjmqQYty2dQOkvzskauRJxMdZzLMiZP4rfKSE@MpY4GEmY8UOcuDNMcFKgEZiEZ9/WKlU7EZVRQKmsROzr62R9QhBgjjyuFcnJHcx1wFdaDPKzrQNU9HpLrlSDncjymuYFDu4sjzT5XNGdqCFIIF2QyAKTPxnGCKCOvK6@23iQtUTLHDDNTX33O/ZAZ0zJ5iVTpeZWuMefhLaeYamqGTXirNrKmyEw1I4N4CEN0cgIT514EOnRcAr@e1TiGCYKAB36lmovJYZZm1GWM53E5zdGMpEmarYqzIRU2d6INzKTMzubV3CxMFaPDfjpNSswUwrRhhN32bWOucW5iRtUh@aSOBwv4DNsdmXbPsN1zXEizmJveh1WyMfXRFHjOgRcutzP7uQjSLhfBqP5S61vdyHkx8U/27YZsJTbqHo3YZ9Gj3WrrRzp3uo5m4YZEbkpmG5IPG7yPH9kiX9YQ3An8/ijq2emFCFSN3h0dVR2wb0yGp5cr@OUNjtbn2ajwpn67rPDGua0OcOFcsurreVfZ2oxumnDxQKdcrEpl7Pye34vk1BQ3/bARdKFKk/9Im21LWxRib2/Phya04Zi44GNmk3j4bEETGVJ4RmCABmki2CLtNeX/TRn3gWe5huHIjmBiJc213aCY2wE7rMoOK2sZWQNwjSB4GIP3Y@I3oeFBxzf3tgveCQbAsaHgBO8t6BBcNS3mI9@ARtvmtf83z7V2r40lIQEH/smOxE5ViGuvAx@NZoGDuNUTfKMz/3eZ/ohSmQ9oge/p0/L3DYKalhlVSemAOiyysSopY@H66xqqcRnn9FuaxA4US8H@92QfRSTL0UeH9F0yY463BfcMAdsYfyfT2Mk0dzKtJfPlI9W21H7vWRVQxkUJpdJxAem03N8S1KmCFn8A)
A breadth-first, basic brute force approach.
] |
[Question]
[
In a desolate, war-torn world, where cities have been overrun by thugs and thieves, civilization has reinvented itself in the form of small, isolated, industrial cooperatives, scattered throughout the previously uninhabited landscape. The existence of these communities is reliant on teams of mercenary workers called "scrappers", who search the untamed territory for valuable materials to sell to the coops. As these materials have grown more scarce, scrapping has become an ever more difficult and dangerous profession. Fragile human workers have mostly been replaced with remote robotic stand-ins, called “bots”, and a typical mercenary is more likely to be a skilled programmer than an armed welder. As the human presence in scrapping has declined, so too has the respect between mercenary groups for one another. Bots are equipped not only to collect scrap, but to defend it, and in some cases take it by force. Bot programmers work tirelessly devising new strategies to outsmart rival scrappers, resulting in increasingly aggressive bots, and yet another danger for humans who venture outside the walls of their communities.
[](https://i.stack.imgur.com/6kPlm.gif)
*(yeah, the logo gets cropped hilariously)*
# Welcome to Scrappers!
*This is an early version of Scrappers in which scrap collection and factories have not been implemented. It’s basically a “shoot ‘em up”.*
You are a mercenary programmer tasked with creating a program to remotely conduct your bots to victory over rival scrapper groups. Your bots are spider-like machines consisting of power and shield generators at their core, surrounded by many appendages equipped with gripping, cutting, and attacking implements. The power generator is capable of producing 12 power units (pu) per tick (a scrapper's unit of time). You are in control of how this power is distributed amongst a bot's three primary needs: movement, shields, and firepower.
Scrapper bots are exceptionally agile machines, and can easily move over, under, and around any obstacles they encounter. Thus, collision is not something that your program needs take into consideration. You are free to allocate all, some, or none of the 12pu available to your bot for movement, as long as you deal in whole numbers. Allocating 0pu to a bot's movement functions would render it immobile. Allocating 2pu would enable a bot to move 2 distance units (du) per tick, 5pu would result in 5du/tick, 11pu would result in 11du/tick, and so on.
Your bots’ shield generators project a bubble of deflective energy around their body. A shield can deflect up to 1 damage before popping, thus leaving your bot exposed until it's shield generator builds enough power to snap the shield back into place. You are free to allocate all, some, or none of the 12pu available to your bot towards it’s shield. Allocating 0pu to a bot's shield means that it will never generate a shield. Allocating 2pu would allow a bot to generate a new shield 2 out of 12 ticks, or once every 6 ticks. 5pu would result in shield regeneration 5 out of every 12 ticks, and so on.
By building up a charge in their welding lasers, your bots can fire damaging beams over short distances with fair accuracy. Like shield generation, your bots’ rate of fire depends on the power allocated to their lasers. Allocating 0pu to a bot's lasers means that it will never fire. Allocating 2pu would allow a bot to fire 2 out of every 12 ticks, and so on. A bot’s laser will travel until it encounters an object or disperses into uselessness, so be mindful of friendly fire. Although your bots are quite accurate, they aren’t perfect. You should expect +/- 2.5 degrees of variance in accuracy. As the laser beam travels, its particles are incrementally deflected by the atmosphere until the beam becomes effectively harmless with enough distance. A laser does 1 damage at point blank range, and 2.5% less damage every bot-length it travels. In other words, the closer you are to your target, the more likely you are to hit it, and the more damage you will cause.
Scrapper bots are autonomous enough to handle basic functions, but rely on you, their programmer, to make them useful as a group. As a programmer, you may issue the following commands for each individual bot:
* MOVE: Specify coordinates towards which a bot will move.
* TARGET: Identify a bot to aim at and fire at when power allocation allows.
* POWER: Redistribute power between movement, shields, and firepower.
# Technical Game Details
There are three programs that you'll need to be familiar with. The [Game Engine](https://github.com/ScrappersIO/Game-Engine/releases/latest) is the heavy lifter and provides a TCP API that the player programs connect to. The player program is what you'll write, and I've provided some [examples with binaries here](https://github.com/ScrappersIO/Player-Samples). Finally, the [Renderer](https://github.com/ScrappersIO/Renderer) processes the output from the Game Engine to produce a GIF of the battle.
## The Game Engine
You can [download the game engine from here](https://github.com/ScrappersIO/Game-Engine/releases/latest). When the game is launched, it will begin listening on port 50000 (currently not configurable) for player connections. Once it receives two player connections, it sends the READY message to the players and begins the game. Player programs send commands to the game via the TCP API. When the game is over, a JSON file named scrappers.json (also, currently not configurable) is created. This is what the renderer uses to create a GIF of the game.
## The TCP API
Player programs and the game engine communicate by passing newline-terminated JSON strings back and fourth over a TCP connection. There are just five different JSON messages that can be sent or received.
### Ready Message
The READY message is sent from the game to the player programs and is only sent once. This message tells the player program what its player ID (PID) is and provides a list of all the bots in the game. The PID is the only way to determine which Bots are friendly vs enemy. More info on the bot fields below.
```
{
"Type":"READY", // Message type
"PID":1, // Player ID
"Bots":[ // Array of bots
{
"Type":"BOT",
"PID":1,
"BID":1,
"X":-592,
...
},
...
]
}
```
### Bot Message
The BOT message is sent from the game to the player programs and is sent when a bot's attributes change. For instance, when shields are projected, or health changes, a BOT message is sent. The Bot ID (BID) is only unique within a particular player.
```
{
"Type":"BOT", // Message type
"PID":1, // Player ID
"BID":1, // Bot ID
"X":-592, // Current X position
"Y":-706, // Current Y position
"Health":12, // Current health out of 12
"Fired":false, // If the Bot fired this tick
"HitX":0, // X position of where the shot landed
"HitY":0, // Y position of where the shot landed
"Scrap":0, // Future use. Ignore.
"Shield":false // If the Bot is currently shielded.
}
```
### Move Message
The MOVE message is a command from the player program to the game (but think of it as a command to a bot). Simply identify the bot you want to move, and the coordinates. It's assumed that you are commanding your own bot, so no PID is necessary.
```
{
"Cmd":"MOVE",
"BID":1, // Bot ID
"X":-592, // Destination X coordinate
"Y":-706, // Destination Y coordinate
}
```
### Target Message
The TARGET message tells one of your bots to target some other bot.
```
{
"Cmd":"TARGET",
"BID":1, // Bot ID
"TPID":0, // The PID of the bot being targeted
"TBID":0, // The BID of the bot being targeted
}
```
### Power Message
The POWER message reallocates the 12pu available to your bot between movement, firepower, and shields.
```
{
"Cmd":"POWER",
"BID":1, // Bot ID
"FPow":4, // Set fire power
"MPow":4, // Set move power
"SPow":4, // Set shield power
}
```
# The Competition
If you're brave enough to explore the untamed lands, you'll be entered into a double-elimination tournament against your mercenary peers. Please create an answer for your submission and either paste your code or provide a link to a git repo, gist, etc. Any language is acceptable, but you should assume I know nothing about the language and include instructions for running your program. Create as many submissions as you like, and be sure to give them names!
The [sample player programs](https://github.com/ScrappersIO/Player-Samples) will be included in the tournament, so I highly recommend testing your bot against them. The tournament will commence roughly two weeks after we get four unique program submissions. Good luck!
```
--- Winner's Bracket ---
** Contestants will be randomly seeded **
__________________
|___________
__________________| |
|___________
__________________ | |
|___________| |
__________________| |
|________________
__________________ | |
|___________ | |
__________________| | | |
|___________| |
__________________ | |
|___________| |
__________________| |
|
--- Loser's Bracket --- |___________
|
___________ |
|___________ |
___________| |___________ |
| | |
___________| | |
|___________ |
___________ | | |
|___________ | |___________|
___________| |___________| |
| |
___________| ___________|
```
# Other Important Info
* The game runs at 12 ticks/second, so you will not receive messages more frequently than every 83 milliseconds or so.
* Each bot is 60du in diameter. The shield takes up no additional space. With the +/- 2.5% accuracy, the odds of hitting a bot at a certain distance are represented by this graph:
[](https://i.stack.imgur.com/AJ1ag.png)
* The decay of laser damage over distance is represented by this graph:
[](https://i.stack.imgur.com/ufPDN.png)
* A bot's accuracy and laser decay combine to calculate its average damage per shot. That is, the average damage a bot will cause when it fires from a certain distance. Damage per shot is represented by this graph:
[](https://i.stack.imgur.com/n0XjN.png)
* A bot's laser originates half way between the bot's center and its edge. Thus, stacking your bots will result in friendly fire.
* Enemy bots spawn roughly 1440du apart.
* The game ends if 120 ticks (10 seconds) pass without any damage dealt.
* The winner is the player with the most bots, then the most health when the game ends.
# Understanding the Rendered Image
* Player 1 is represented by circles and player 2 by hexagons.
* The color of a bot represents its power allocation. More red means more power has been allocated to firing. More blue means more shield. More green means more movement.
* The "hole" in a bot's body represents damage. The larger the hole, the more damage has been taken.
* The white circles surrounding a bot are it's shield. If a bot has a shield at the end of the turn, it is shown. If the shield was popped by taking damage, it is not shown.
* The red lines between bots represent shots taken.
* When a bot is killed, a large red "explosion" is shown.
[Answer]
# Extremist (Python 3)
This bot will always devote all of its power to one thing: shielding if it isn't shielded, moving if it is out of position, and firing otherwise. Beats all of the sample bots except death-dish.
```
import socket, sys, json
from types import SimpleNamespace
s=socket.socket()
s.connect(("localhost",50000))
f=s.makefile()
bots={1:{},2:{}}
def hook(obj):
if "BID" in obj:
try:
bot = bots[obj["PID"]][obj["BID"]]
except KeyError:
bot = SimpleNamespace(**obj)
bots[bot.PID][bot.BID] = bot
else:
bot.__dict__.update(obj)
return bot
return SimpleNamespace(**obj)
decoder = json.JSONDecoder(object_hook=hook)
PID = decoder.decode(f.readline()).PID
#side effect: .decode fills bots dictionary
def turtle(bot):
send({"Cmd":"POWER","BID":bot.BID,"FPow":0,"MPow":0,"SPow":12})
bot.firing = bot.moving = False
def send(msg):
s.send(json.dumps(msg).encode("ascii")+b"\n")
for bot in bots[PID].values():
turtle(bot)
target_bot = None
def calc_target_bot():
ok_bots = []
for bot2 in bots[(2-PID)+1].values():
if bot2.Health < 12:
ok_bots.append(bot2)
best_bot = (None,2147483647)
for bot2 in (ok_bots or bots[(2-PID)+1].values()):
dist = bot_dist(bot, bot2)
if dist < best_bot[1]:
best_bot = bot2, dist
return best_bot[0]
def bot_dist(bot, bot2):
if isinstance(bot, tuple):
bot=SimpleNamespace(X=bot[0],Y=bot[1])
if isinstance(bot2, tuple):
bot=SimpleNamespace(X=bot[0],Y=bot[1])
distx = bot2.X - bot.X
disty = bot2.Y - bot.Y
return (distx**2+disty**2)**.5
LENGTH_Y = -80
LENGTH_X = 80
line = None
def move(bot, pos):
bot.firing = False
bot.moving = True
send({"Cmd":"POWER","BID":bot.BID,"FPow":0,"MPow":12,"SPow":0})
send({"Cmd":"MOVE","BID": bot.BID,"X":pos[0],"Y":pos[1]})
def go(bot, line):
if line != None:
position = (line[0]+LENGTH_X*(bot.BID-6),line[1]+LENGTH_Y*(bot.BID-6))
if not close_pos(bot, position, 1.5):
return True, position
return False, None
def close_pos(bot, pos, f):
if abs(bot.X - pos[0]) <= abs(LENGTH_X*f) or \
abs(bot.Y - pos[1]) <= abs(LENGTH_Y*f):
return True
def set_line(bot):
global line
newline = bot.X - LENGTH_X*(bot.BID - 6), bot.Y - LENGTH_Y*(bot.BID - 6)
if line == None or bot_dist(line, target_bot) < (bot_dist(newline, target_bot) - 100):
line = newline
def move_or_fire(bot):
global target_bot, line
if not target_bot:
target_bot = calc_target_bot()
followline, place = go(bot, line)
if not target_bot:
#Game should be over, but just in case ...
return turtle(bot)
elif bot_dist(bot, target_bot) > 2000:
line = None
position = (target_bot.X, target_bot.Y)
position = (position[0]+LENGTH_X*(bot.BID-6),position[1]+LENGTH_Y*(bot.BID-6))
move(bot, position)
elif followline:
set_line(bot)
move(bot, place)
elif any(close_pos(bot, (bot2.X, bot2.Y), .6) for bot2 in bots[PID].values() if bot != bot2):
try:
move(bot, place)
except TypeError:
turtle(bot)
set_line(bot)
#Let the conflicting bots resolve
else:
set_line(bot)
bot.firing = True
bot.moving = False
send({"Cmd":"POWER","BID":bot.BID,"FPow":12,"MPow":0,"SPow":0})
send({"Cmd":"TARGET","BID": bot.BID,
"TPID":target_bot.PID,"TBID":target_bot.BID})
def dead(bot):
del bots[bot.PID][bot.BID]
def parse_message():
global target_bot
line = f.readline()
if not line:
return False
bot = decoder.decode(line)
assert bot.Type == "BOT"
del bot.Type
if bot.PID == PID:
if bot.Health <= 0:
dead(bot)
elif not bot.Shield:
turtle(bot)
else:
move_or_fire(bot)
elif target_bot and (bot.BID == target_bot.BID):
target_bot = bot
if target_bot.Health <= 0:
target_bot = None
dead(bot)
for bot in bots[PID].values():
if bot.firing or bot.moving:
move_or_fire(bot)
elif bot.Health <= 0:
dead(bot)
assert bot.Health > 0 or bot.BID not in bots[bot.PID]
return True
while parse_message():
pass
```
[Answer]
# Less Reckless ([Go](https://golang.org/))
```
go run main.go
```
Originally, I planned to slightly modify the Reckless Abandon sample program so that bots would not fire if a friendly bot was in the way. I ended up with bots that pick new targets when a friend is in the way, which I guess is better. It'll beat the first two programs.
The code isn't perfect. The logic to determine if a shot is clear uses some pretty random guesswork.
There doesn't seem to be a mechanism to target "nobody". That might be a good feature to add.
The TCP API is nice in that any language can play, but it also means a lot of boilerplate code. If I wasn't familiar with the language the sample bots were written in, I probably wouldn't have been motivated to play around with this. A collection of boilerplate samples in various languages would be a great addition to your other git repos.
( most of the following code is copy/paste from one of the sample bots )
```
package main
import (
"bufio"
"encoding/json"
"flag"
"io"
"log"
"math"
"math/rand"
"net"
"time"
)
const (
MaxHealth int = 12
BotSize float64 = 60
)
var (
// TCP connection to game.
gameConn net.Conn
// Queue of incoming messages
msgQueue chan MsgQueueItem
)
// MsgQueueItem is a simple vehicle for TCP
// data on the incoming message queue.
type MsgQueueItem struct {
Msg string
Err error
}
// Command contains all the fields that a player might
// pass as part of a command. Fill in the fields that
// matter, then marshal into JSON and send.
type Command struct {
Cmd string
BID int
X int
Y int
TPID int
TBID int
FPow int
MPow int
SPow int
}
// Msg is used to unmarshal every message in order
// to check what type of message it is.
type Msg struct {
Type string
}
// BotMsg is used to unmarshal a BOT representation
// sent from the game.
type BotMsg struct {
PID, BID int
X, Y int
Health int
Fired bool
HitX, HitY int
Scrap int
Shield bool
}
// ReadyMsg is used to unmarshal the READY
// message sent from the game.
type ReadyMsg struct {
PID int
Bots []BotMsg
}
// Create our game data storage location
var gdb GameDatabase
func main() {
var err error
gdb = GameDatabase{}
msgQueue = make(chan MsgQueueItem, 1200)
// What port should we connect to?
var port string
flag.StringVar(&port, "port", "50000", "Port that Scrappers game is listening on.")
flag.Parse()
// Connect to the game
gameConn, err = net.Dial("tcp", ":"+port)
if err != nil {
log.Fatalf("Failed to connect to game: %v\n", err)
}
defer gameConn.Close()
// Process messages off the incoming message queue
go processMsgs()
// Listen for message from the game, exit if connection
// closes, add message to message queue.
reader := bufio.NewReader(gameConn)
for {
msg, err := reader.ReadString('\n')
if err == io.EOF {
log.Println("Game over (connection closed).")
return
}
msgQueue <- MsgQueueItem{msg, err}
}
}
func runStrategy() {
// LESS RECKLESS ABANDON
// - For three seconds, all bots move as fast as possible in a random direction.
// - After three seconds, split power between speed and firepower.
// - Loop...
// - Identify the enemy bot with the lowest health.
// - If a friendly bot is in the way, pick someone else.
// - If there's a tie, pick the one closest to the group.
// - Everybody moves towards and targets the bot.
var myBots []*GDBBot
// Move quickly in random direction.
// Also, might as well get a shield.
myBots = gdb.MyBots()
for _, bot := range myBots {
send(bot.Power(0, 11, 1))
radians := 2.0 * math.Pi * rand.Float64()
x := bot.X + int(math.Cos(radians)*999)
y := bot.Y + int(math.Sin(radians)*999)
send(bot.Move(x, y))
}
// Wait three seconds
time.Sleep(3 * time.Second)
// Split power between speed and fire
for _, bot := range myBots {
send(bot.Power(6, 6, 0))
}
for { // Loop indefinitely
// Find a target
candidates := gdb.TheirBots()
// Order by health
reordered := true
for reordered {
reordered = false
for n:=1; n<len(candidates); n++ {
if candidates[n].Health < candidates[n-1].Health {
temp := candidates[n-1]
candidates[n-1] = candidates[n]
candidates[n] = temp
reordered = true
}
}
}
// Order by closeness
// My swarm position is...
ttlX, ttlY := 0, 0
myBots = gdb.MyBots() // Refresh friendly bot list
for _, bot := range myBots {
ttlX += bot.X
ttlY += bot.Y
}
avgX := ttlX / len(myBots)
avgY := ttlY / len(myBots)
// Sort
reordered = true
for reordered {
reordered = false
for n:=1; n<len(candidates); n++ {
thisDist := distance(avgX, avgY, candidates[n].X, candidates[n].Y)
lastDist := distance(avgX, avgY, candidates[n-1].X, candidates[n-1].Y)
if thisDist < lastDist {
temp := candidates[n-1]
candidates[n-1] = candidates[n]
candidates[n] = temp
reordered = true
}
}
}
// For all my bots, try to find the weakest enemy that my bot has a clear shot at
myBots = gdb.MyBots()
for _, bot := range myBots {
for _, enemy := range candidates {
clear := clearShot(bot, enemy)
if clear {
// Target and move towards
send(bot.Target(enemy))
send(bot.Follow(enemy))
break
}
log.Println("NO CLEAR SHOT")
}
}
time.Sleep(time.Second / 24)
}
}
func clearShot(bot, enemy *GDBBot) bool {
deg45rad := math.Pi*45/180
deg30rad := math.Pi*30/180
deg15rad := math.Pi*15/180
deg5rad := math.Pi*5/180
myBots := gdb.MyBots()
enmyAngle := math.Atan2(float64(enemy.Y-bot.Y), float64(enemy.X-bot.X))
for _, friend := range myBots {
dist := distance(bot.X, bot.Y, friend.X, friend.Y)
angle := math.Atan2(float64(friend.Y-bot.Y), float64(friend.X-bot.X))
safeAngle := angle
if dist < BotSize*3 {
safeAngle = deg45rad/2
} else if dist < BotSize*6 {
safeAngle = deg30rad/2
} else if dist < BotSize*9 {
safeAngle = deg15rad/2
} else {
safeAngle = deg5rad/2
}
if angle <= enmyAngle+safeAngle && angle >= enmyAngle-safeAngle {
return false
}
}
return true
}
func processMsgs() {
for {
queueItem := <-msgQueue
jsonmsg := queueItem.Msg
err := queueItem.Err
if err != nil {
log.Printf("Unknown error reading from connection: %v", err)
continue
}
// Determine the type of message first
var msg Msg
err = json.Unmarshal([]byte(jsonmsg), &msg)
if err != nil {
log.Printf("Failed to marshal json message %v: %v\n", jsonmsg, err)
return
}
// Handle the message type
// The READY message should be the first we get. We
// process all the data, then kick off our strategy.
if msg.Type == "READY" {
// Unmarshal the data
var ready ReadyMsg
err = json.Unmarshal([]byte(jsonmsg), &ready)
if err != nil {
log.Printf("Failed to marshal json message %v: %v\n", jsonmsg, err)
}
// Save our player ID
gdb.PID = ready.PID
log.Printf("My player ID is %v.\n", gdb.PID)
// Save the bots
for _, bot := range ready.Bots {
gdb.InsertUpdateBot(bot)
}
// Kick off our strategy
go runStrategy()
continue
}
// The BOT message is sent when something about a bot changes.
if msg.Type == "BOT" {
// Unmarshal the data
var bot BotMsg
err = json.Unmarshal([]byte(jsonmsg), &bot)
if err != nil {
log.Printf("Failed to marshal json message %v: %v\n", jsonmsg, err)
}
// Update or add the bot
gdb.InsertUpdateBot(bot)
continue
}
// If we've gotten to this point, then we
// were sent a message we don't understand.
log.Printf("Recieved unknown message type \"%v\".", msg.Type)
}
}
///////////////////
// GAME DATABASE //
///////////////////
// GameDatabase stores all the data
// sent to us by the game.
type GameDatabase struct {
Bots []GDBBot
PID int
}
// GDBBot is the Bot struct for the Game Database.
type GDBBot struct {
BID, PID int
X, Y int
Health int
}
// InserUpdateBot either updates a bot's info,
// deletes a dead bot, or adds a new bot.
func (gdb *GameDatabase) InsertUpdateBot(b BotMsg) {
// If this is a dead bot, remove and ignore
if b.Health <= 0 {
for i := 0; i < len(gdb.Bots); i++ {
if gdb.Bots[i].BID == b.BID && gdb.Bots[i].PID == b.PID {
gdb.Bots = append(gdb.Bots[:i], gdb.Bots[i+1:]...)
return
}
}
return
}
// Otherwise, update...
for i, bot := range gdb.Bots {
if b.BID == bot.BID && b.PID == bot.PID {
gdb.Bots[i].X = b.X
gdb.Bots[i].Y = b.Y
gdb.Bots[i].Health = b.Health
return
}
}
// ... or Add
bot := GDBBot{}
bot.PID = b.PID
bot.BID = b.BID
bot.X = b.X
bot.Y = b.Y
bot.Health = b.Health
gdb.Bots = append(gdb.Bots, bot)
}
// MyBots returns a pointer array of GDBBots owned by us.
func (gdb *GameDatabase) MyBots() []*GDBBot {
bots := make([]*GDBBot, 0)
for i, bot := range gdb.Bots {
if bot.PID == gdb.PID {
bots = append(bots, &gdb.Bots[i])
}
}
return bots
}
// TheirBots returns a pointer array of GDBBots NOT owned by us.
func (gdb *GameDatabase) TheirBots() []*GDBBot {
bots := make([]*GDBBot, 0)
for i, bot := range gdb.Bots {
if bot.PID != gdb.PID {
bots = append(bots, &gdb.Bots[i])
}
}
return bots
}
// Move returns a command struct for movement.
func (b *GDBBot) Move(x, y int) Command {
cmd := Command{}
cmd.Cmd = "MOVE"
cmd.BID = b.BID
cmd.X = x
cmd.Y = y
return cmd
}
// Follow is a convenience function which returns a
// command stuct for movement using a bot as a destination.
func (b *GDBBot) Follow(bot *GDBBot) Command {
cmd := Command{}
cmd.Cmd = "MOVE"
cmd.BID = b.BID
cmd.X = bot.X
cmd.Y = bot.Y
return cmd
}
// Target returns a command struct for targeting a bot.
func (b *GDBBot) Target(bot *GDBBot) Command {
cmd := Command{}
cmd.Cmd = "TARGET"
cmd.BID = b.BID
cmd.TPID = bot.PID
cmd.TBID = bot.BID
return cmd
}
// Power returns a command struct for seting the power of a bot.
func (b *GDBBot) Power(fire, move, shield int) Command {
cmd := Command{}
cmd.Cmd = "POWER"
cmd.BID = b.BID
cmd.FPow = fire
cmd.MPow = move
cmd.SPow = shield
return cmd
}
////////////////////
// MISC FUNCTIONS //
////////////////////
// Send marshals a command to JSON and sends to the game.
func send(cmd Command) {
bytes, err := json.Marshal(cmd)
if err != nil {
log.Fatalf("Failed to mashal command into JSON: %v\n", err)
}
bytes = append(bytes, []byte("\n")...)
gameConn.Write(bytes)
}
// Distance calculates the distance between two points.
func distance(xa, ya, xb, yb int) float64 {
xdist := float64(xb - xa)
ydist := float64(yb - ya)
return math.Sqrt(math.Pow(xdist, 2) + math.Pow(ydist, 2))
}
```
[Answer]
**Trigger Happy - Java 8**
Trigger Happy is a simple evolution of my original, but no longer viable, Bombard bot. It is a very simple bot that will simply fire on the currently targeted enemy if there is a clear shot, otherwise performs a random walk to try to get into a better position. All the time attempting to have a shield.
However, for all its simplicity it is very effective. And will readily destroy the sample bots.
Note, there are multiple bugs with the bot such as will sometimes fire even when not a clear shot and may not maintain a shield... but it is still effective so will just submit this entry as-is
[](https://i.stack.imgur.com/b6Ujj.gif)
Death-dish vs Trigger Happy
Code as follows:
```
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
//import visual.Viewer;
public class TriggerHappy {
static final int BOT_RADIUS = 30;
private static final double WALK_MAX_DIRECTION_CHANGE = Math.PI/3;
static Bot targetedBot;
enum BotState
{
INIT,
RANDOM_WALK,
FIRING,
SHIELDING,
DEAD,
END
}
enum Power
{
MOVE,
FIRE,
SHIELD
}
private static PrintStream out;
private static List<Bot> enemyBots;
private static List<Bot> myBots;
//private static Viewer viewer;
public static void main(String[] args) throws Exception
{
InetAddress localhost = Inet4Address.getLocalHost();
Socket socket = new Socket(localhost, 50000);
InputStream is = socket.getInputStream();
out = new PrintStream(socket.getOutputStream());
// read in the game configuration
String line = readLine(is);
Configuration config = new Configuration(line);
// viewer = new Viewer(line);
myBots = config.bots.values().stream().filter(b->b.playerId==config.playerId).collect(Collectors.toList());
enemyBots = config.bots.values().stream().filter(b->b.playerId!=config.playerId).collect(Collectors.toList());
// set initial target
targetedBot = enemyBots.get(enemyBots.size()/2);
myBots.forEach(bot->target(bot,targetedBot));
for (line = readLine(is);line!=null;line = readLine(is))
{
// viewer.update(line);
// read in next bot update message from server
Bot updatedBot = new Bot(line);
Bot currentBot = config.bots.get(updatedBot.uniqueId);
currentBot.update(updatedBot);
// check for bot health
if (currentBot.health<1)
{
// remove dead bots from lists
currentBot.state=BotState.DEAD;
if (currentBot.playerId == config.playerId)
{
myBots.remove(currentBot);
}
else
{
enemyBots.remove(currentBot);
// change target if the targetted bot is dead
if (currentBot == targetedBot)
{
if (enemyBots.size()>0)
{
targetedBot = enemyBots.get(enemyBots.size()/2);
myBots.forEach(bot->target(bot,targetedBot));
}
// no more enemies... set bots to end state
else
{
myBots.forEach(bot->bot.state = BotState.END);
}
}
}
}
else
{
// ensure our first priority is shielding
if (!currentBot.shield && currentBot.state!=BotState.SHIELDING)
{
currentBot.state=BotState.SHIELDING;
shield(currentBot);
}
else
{
// not game end...
if (currentBot.state != BotState.END)
{
// command to fire if we have a clear shot
if (clearShot(currentBot))
{
currentBot.state=BotState.FIRING;
fire(currentBot);
}
// randomly walk to try and get into a better position to fire
else
{
currentBot.state=BotState.RANDOM_WALK;
currentBot.dir+=Math.random()*WALK_MAX_DIRECTION_CHANGE - WALK_MAX_DIRECTION_CHANGE/2;
move(currentBot, (int)(currentBot.x+Math.cos(currentBot.dir)*100), (int) (currentBot.y+Math.sin(currentBot.dir)*100));
}
}
}
}
}
is.close();
socket.close();
}
// returns true if there are no friendly bots in firing line... mostly
private static boolean clearShot(Bot originBot)
{
double originToTargetDistance = originBot.distanceFrom(targetedBot);
for (Bot bot : myBots)
{
if (bot != originBot)
{
double x1 = originBot.x - bot.x;
double x2 = targetedBot.x - bot.x;
double y1 = originBot.y - bot.y;
double y2 = targetedBot.y - bot.y;
double dx = x2-x1;
double dy = y2-y1;
double dsquared = dx*dx + dy*dy;
double D = x1*y2 - x2*y1;
if (1.5*BOT_RADIUS * 1.5*BOT_RADIUS * dsquared > D * D && bot.distanceFrom(targetedBot) < originToTargetDistance)
{
return false;
}
}
}
return true;
}
static class Bot
{
int playerId;
int botId;
int x;
int y;
int health;
boolean fired;
int hitX;
int hitY;
double dir = Math.PI*2*Math.random();
boolean shield;
int uniqueId;
BotState state = BotState.INIT;
Power power = Power.SHIELD;
Bot(String line)
{
String[] tokens = line.split(",");
playerId = extractInt(tokens[1]);
botId = extractInt(tokens[2]);
x = extractInt(tokens[3]);
y = extractInt(tokens[4]);
health = extractInt(tokens[5]);
fired = extractBoolean(tokens[6]);
hitX = extractInt(tokens[7]);
hitY = extractInt(tokens[8]);
shield = extractBoolean(tokens[10]);
uniqueId = playerId*10000+botId;
}
Bot()
{
}
double distanceFrom(Bot other)
{
return distanceFrom(new Point(other.x,other.y));
}
double distanceFrom(Point other)
{
double deltaX = x - other.x;
double deltaY = y - other.y;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
}
void update(Bot other)
{
x = other.x;
y = other.y;
health = other.health;
fired = other.fired;
hitX = other.hitX;
hitY = other.hitY;
shield = other.shield;
}
}
static class Configuration
{
BotState groupState = BotState.INIT;
HashMap<Integer,Bot> bots = new HashMap<>();
boolean isOpponentInitiated;
int playerId;
Configuration(String line) throws Exception
{
String[] tokens = line.split("\\[");
playerId = extractInt(tokens[0].split(",")[1]);
for (String token : tokens[1].split("\\|"))
{
Bot bot = new Bot(token);
bots.put(bot.uniqueId,bot);
}
}
}
/**
* Reads a line of text from the input stream. Blocks until a new line character is read.
* NOTE: This method should be used in favor of BufferedReader.readLine(...) as BufferedReader buffers data before performing
* text line tokenization. This means that BufferedReader.readLine() will block until many game frames have been received.
* @param in a InputStream, nominally System.in
* @return a line of text or null if end of stream.
* @throws IOException
*/
static String readLine(InputStream in) throws IOException
{
StringBuilder sb = new StringBuilder();
int readByte = in.read();
while (readByte>-1 && readByte!= '\n')
{
sb.append((char) readByte);
readByte = in.read();
}
return readByte==-1?null:sb.toString().replace(",{", "|").replaceAll("}", "");
}
final static class Point
{
public Point(int x2, int y2) {
x=x2;
y=y2;
}
int x;
int y;
}
public static int extractInt(String token)
{
return Integer.parseInt(token.split(":")[1]);
}
public static boolean extractBoolean(String token)
{
return Boolean.parseBoolean(token.split(":")[1]);
}
static void distributePower(Bot bot, int fire, int move, int shield)
{
out.println("{\"Cmd\":\"POWER\",\"BID\":"+bot.botId+",\"FPow\":"+fire+",\"MPow\":"+move+",\"SPow\":"+shield+"}");
// viewer.distributePower(bot.botId, fire, move, shield);
}
static void shield(Bot bot)
{
distributePower(bot,0,0,12);
bot.power=Power.SHIELD;
}
static void move(Bot bot, int x, int y)
{
distributePower(bot,0,12,0);
out.println("{\"Cmd\":\"MOVE\",\"BID\":"+bot.botId+",\"X\":"+x+",\"Y\":"+y+"}");
}
static void target(Bot bot, Bot target)
{
out.println("{\"Cmd\":\"TARGET\",\"BID\":"+bot.botId+",\"TPID\":"+target.playerId+",\"TBID\":"+target.botId+"}");
}
static void fire(Bot bot)
{
distributePower(bot,12,0,0);
bot.power=Power.FIRE;
}
}
```
To compile:
javac TriggerHappy.java
To run:
java TriggerHappy
] |
[Question]
[
Ice mazes have been one of my favorite staples of [Pokémon](https://en.wikipedia.org/wiki/Pok%C3%A9mon) games since their debut in Pokémon Gold and Silver. Your task will be to make a program that solves these types of problems.
Ice mazes primarily consist of, as the name suggests, ice. Once the player moves in a direction on ice they will continue to move in that direction until they collide with some obstacle. There is also soil which can be moved across freely and will stop any player moving across it. The last obstacle is stone. Stone cannot occupy the same space as the player and if the player attempts to move into it they will stop moving before they can.
You will receive a two dimensional container of values, such as an list of lists or a string separated by newlines, containing 3 distinct values for each of the 3 types of flooring (Ice, Soil, and Stone). You will also receive two pairs (or other equivalent two value containers) that indicate a start and goal coordinate in the maze. These may be zero or one indexed.
You must output a list of moves (4 distinct values with a bijection onto N,E,S,W) that would cause the player to arrive at the end when carried out.
Input will always have a closed perimeter of stone around the maze so you do not have to worry about the player exiting the maze
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the fewest bytes wins
## Test Cases
Here `.` will represent ice, `~` will represent soil, and `O` will represent a stone. Coordinates are 1 indexed. Each letter in the solution represents the direction beginning with that letter (e.g. `N`= North)
---
### Input
```
OOOOO
OO.OO
O...O
OOOOO
Start : 3,3
End : 3,2
```
### Output
```
N
```
---
### Input
```
OOOOOOOOOOOOOOOOO
O........O.....OO
O...O..........OO
O.........O....OO
O.O............OO
OO.......O.....OO
O.............OOO
O......O.......~O
O..O...........~O
O.............OOO
O.......O......OO
O.....O...O....OO
O..............OO
OOOOOOOOOOOOOO~~O
OOOOOOOOOOOOOOOOO
Start : 15,12
End : 16,8
```
### Output
```
N,W,N,E,N,E,S,W,N,W,S,E,S,E,N,E,N
```
---
### Input
```
OOOOOOOOOOOOOOOO
O~~~~~OOOOO~~~~O
O~~O~OOOOOOO~~OO
O...O..........O
O........O.....O
O..............O
OO.............O
O.............OO
O....~....O....O
O..............O
O..............O
OOOOOOOOOOOOOOOO
Start : 2,2
End : 14,3
```
### Output
```
E,S,S,W,N,E,N
```
---
### Input
```
OOOOOOOOOOOOOOOOOOO
O~~~~~~~OOOOOOOOOOO
O~~~~...OOOOOOOOOOO
OO~O~..OOOOOOOOOOOO
O..OO.............O
O..............O..O
O....O............O
O.O............~..O
O........OOOO.....O
O.......OOOOO.....O
O.......O~~~O.....O
O.......~~~~~.....O
O.......~~~~~.....O
O..........O......O
O..O..~...........O
O...............O.O
O.....O...........O
O.................O
OOOOOOOOOOOOOOOOOOO
Start : 2,2
End : 11,11
```
### Output
```
E,E,E,E,E,S,S,E,N,W,S,E,N,N,N
```
[Answer]
## Mathematica, 247 bytes
```
(p=x#[[##&@@x]];m={c,v}Switch[p[c+v],0,m[c+v,v],1,c+v,_,c];g=Cases[Array[List,Dimensions@#],c_/;p@c<2,{2}];a=cm[c,#]&/@{{1,0},{-1,0},{0,1},{0,-1}};e=Flatten[Table[#->c,{c,a@#}]&/@g,1];Normalize/@Differences@FindPath[Graph[e],#2,#3][[1]])&
```
With line breaks:
```
(
p=x#[[##&@@x]];
m={c,v}Switch[p[c+v],0,m[c+v,v],1,c+v,_,c];
g=Cases[Array[List,Dimensions@#],c_/;p@c<2,{2}];
a=cm[c,#]&/@{{1,0},{-1,0},{0,1},{0,-1}};
e=Flatten[Table[#->c,{c,a@#}]&/@g,1];
Normalize/@Differences@FindPath[Graph[e],#2,#3][[1]]
)&
```
My immediate idea was to represent the ice and soil positions as nodes in a graph with directed edges corresponding to legal moves, then use `FindPath`. One might think that determining the legal moves would be the easy part and finding the solution would be the hard part. For me, it was the opposite. Open to suggestions on how to compute the edges.
First argument `#` is a 2D array where `0` represents ice, `1` represents soil, and `2` represents stone.
Second argument `#2` and third argument `#3` are the starting and ending points, respectively, in the form `{row,column}`.
`` is the 3 byte private use character `U+F4A1` representing `\[Function]`.
## Explanation
```
p=x#[[##&@@x]];
```
Defines a function `p` which takes a list `x` of the form `{row,column}` and outputs `#[[row,column]]`; i.e., the ice/soil/stone value at that coordinate.
```
m={c,v}Switch[p[c+v],0,m[c+v,v],1,c+v,_,c]
```
Defines a function `m` which takes a starting position `c` and direction vector `v` and recursively determines where you would end up. If `c+v` is ice, then we continue sliding from that point, so it returns `m[c+v,v]`. If `c+v` is soil, then we move to `c+v` and stop. Otherwise (if `c+v` is stone or out of bounds), you don't move. Note that this is only intended to be called on ice or soil positions.
```
g=Cases[Array[List,Dimensions@#],c_/;p@c<2,{2}];
```
Defines the list `g` of ice and soil positions (`p` value less than `2`).
```
a=cm[c,#]&/@{{1,0},{-1,0},{0,1},{0,-1}};
```
Defines a function `a` which takes a starting position `c` and returns the results of moving in the `{1,0}`, `{-1,0}`, `{0,1}`, and `{0,-1}` directions. There may be some redundancy. Again, this assumes that `c` corresponds to ice or soil.
```
e=Flatten[Table[#->c,{c,a@#}]&/@g,1];
```
Defines the list `e` of directed edges representing legal moves. For each position `#` in `g`, compute the table of edges `#->c` for each `c` in `a@#`. Then since we'll end up with a sublist for each position `#`, I flatten the first level. There may be some loops and multiple edges.
```
Normalize/@Differences@FindPath[Graph[e],#2,#3][[1]]
```
`Graph[e]` is the graph where the nodes are the legal positions (ice or soil) and the edges represent legal moves (possibly bumping into a stone and not moving). We then use `FindPath` to find a path from `#2` to `#3` represented as a list of nodes. Since `FindPath` can take additional arguments to find more than one path, the result will actually be a list containing a single path, so I take the first element using `[[1]]`. Then I take the successive `Differences` of the coordinates and `Normalize` them. Thus up is `{-1,0}`, down is `{1,0}`, right is `{0,1}` and left is `{0,-1}`.
## Test cases
[](https://i.stack.imgur.com/eKivw.png)
[](https://i.stack.imgur.com/p2SiD.png)
[](https://i.stack.imgur.com/nhBPX.png)
[](https://i.stack.imgur.com/JFq5g.png)
[](https://i.stack.imgur.com/JphWv.png)
[Answer]
# JavaScript (ES6) 180 ~~183~~
```
(m,[x,y],[t,u],o=~m.search`
`,s=[[x-y*o,[]]],k=[])=>eval("for(i=0;[p,l]=s[i++],k[p]=t-u*o-p;)[-1,o,1,-o].map(d=>k[q=(M=p=>+m[p+=d]?m[p]<8?M(p):p:p-d)(p)]||s.push([q,[...l,d]]));l")
```
Using a [BFS](https://en.wikipedia.org/wiki/Breadth-first_search), like I did to solve [this related challenge](https://codegolf.stackexchange.com/a/50077/21348)
**Input**
The maze map is a multiline string, using `O` or `0` for stone, `8` for soil and any nonzero digit less than 8 for ice (`7` look good).
Start and end position are zero based.
**Output**
A list of offset, where -1 is `W`, 1 is `E`, negative less than -1 is `N` and a positive greater than 1 is `S`
*Less golfed*
```
(m,[x,y],[t,u])=>{
o=~m.search`\n`
s=[[x-y*o,[]]]
k=[]
for(i=0; [p,l]=s[i++], k[p]=1, t-u*o != p;)
{
[-1,o,1,-o].map(d=>(
M=p=>+m[p+=d] ? m[p]<8 ? M(p) : p : p-d,
q=M(p),
k[q]||s.push([q,[...l,d]])
))
}
return l
}
```
**Test**
```
Solve=
(m,[x,y],[t,u],o=~m.search`
`,s=[[x-y*o,[]]],k=[])=>eval("for(i=0;[p,l]=s[i++],k[p]=t-u*o-p;)[-1,o,1,-o].map(d=>k[q=(M=p=>+m[p+=d]?m[p]<8?M(p):p:p-d)(p)]||s.push([q,[...l,d]]));l")
function Go(maze) {
var map = maze.textContent;
var [sx,sy, dx,dy] = map.match(/\d+/g)
--sx, --sy // zero based
--dx, --dy // zero based
map = map.split('\n').slice(1).join('\n') // remove first line
var result = Solve(map.replace(/\./g, 7).replace(/~/g, 8), [sx,sy], [dx,dy])
S.textContent = result
Animate(maze, map, result, sx, sy)
}
function Display(maze, map, pos) {
var row0 = maze.textContent.split('\n')[0]
map = [...map]
map[pos] = '☻'
maze.textContent = row0+'\n'+map.join('')
}
function Animate(maze, map, moves, x, y) {
console.log('A',moves)
var offset = map.search('\n')+1
var curPos = x + offset * y
var curMove = 0
var step = _ => {
Display(maze, map, curPos)
if (curMove < moves.length)
{
curPos += moves[curMove]
if (map[curPos] == 'O')
{
curPos -= moves[curMove]
++curMove
}
else
{
if (map[curPos] == '~') {
++curMove
}
}
setTimeout(step, 100)
}
else
setTimeout(_=>Display(maze,map,-1),500)
}
step()
}
```
```
td {
border: 1px solid #888;
}
```
```
Select maze<pre id=S></pre>
<table cellspacing=5><tr>
<td valign=top><input type=radio name=R onclick='Go(M1)'><br>
<pre id=M1>3,3 to 3,2
OOOOO
OO.OO
O...O
OOOOO</pre></td>
<td valign=top><input type=radio name=R onclick='Go(M2)'><br>
<pre id=M2>15,12 to 16,8
OOOOOOOOOOOOOOOOO
O........O.....OO
O...O..........OO
O.........O....OO
O.O............OO
OO.......O.....OO
O.............OOO
O......O.......~O
O..O...........~O
O.............OOO
O.......O......OO
O.....O...O....OO
O..............OO
OOOOOOOOOOOOOO~~O
OOOOOOOOOOOOOOOOO</pre></td>
<td valign=top><input type=radio name=R onclick='Go(M3)'><br>
<pre id=M3>2,2 to 14,3
OOOOOOOOOOOOOOOO
O~~~~~OOOOO~~~~O
O~~O~OOOOOOO~~OO
O...O..........O
O........O.....O
O..............O
OO.............O
O.............OO
O....~....O....O
O..............O
O..............O
OOOOOOOOOOOOOOOO</pre></td>
<td valign=top><input type=radio name=R onclick='Go(M4)'><br>
<pre id=M4>2,2 to 11,11
OOOOOOOOOOOOOOOOOOO
O~~~~~~~OOOOOOOOOOO
O~~~~...OOOOOOOOOOO
OO~O~..OOOOOOOOOOOO
O..OO.............O
O..............O..O
O....O............O
O.O............~..O
O........OOOO.....O
O.......OOOOO.....O
O.......O~~~O.....O
O.......~~~~~.....O
O.......~~~~~.....O
O..........O......O
O..O..~...........O
O...............O.O
O.....O...........O
O.................O
OOOOOOOOOOOOOOOOOOO</pre></td>
</tr></table>
```
] |
[Question]
[
A [stem and leaf plot](https://en.wikipedia.org/wiki/Stem-and-leaf_display) displays a bunch of numerical values in groups, which are determined by all but the last digit. For example, suppose we have this set of data:
```
0, 2, 12, 13, 13, 15, 16, 20, 29, 43, 49, 101
```
We could produce this stem and leaf plot:
```
0|02
1|23356
2|09
3|
4|39
5|
6|
7|
8|
9|
10|1
```
The first row's stem is 0, so its "leaves" - the digits after the `|` - represent the values between 0 inclusive and 10 exclusive. The leaves on each stem are sorted. Stems with no leaves (like 3) still appear in the plot. The value of 101 is between 100 inclusive and 110 exclusive, so its stem is 10 (100 divided by 10).
**Your challenge** is to check whether a piece of text is a valid stem and leaf plot. A valid plot satisfies these rules:
* Has exactly one row for every stem (i.e. 10-wide group) in the range of the data (including stems in the middle of the range with no leaves)
* Has no stems outside the range
* All leaves are sorted ascending to the right
* All stems are sorted ascending down
* Has only numeric characters (besides the separator `|`)
You do not have to deal with numbers that have fractional parts. You may approve or reject extra leading zeros in the stems, but a blank stem is not allowed. There will be at least one value. You may only assume extra spaces after the leaves on each row. You may assume a leading and/or trailing newline. All characters will be printable ASCII.
Your function or program should return or output (to screen or the standard output) a truthy value for a valid plot, or a falsy value for an invalid plot. You may take input from the standard input, from a file, as one big string, as an array of strings - whatever is most convenient.
Here are some **test cases** that are valid plots (separated by blank lines):
```
2|00003457
3|35
4|799
5|3
99|3
100|0556
101|
102|
103|8
0|0
```
Here are some **test cases** that are invalid plots, with commentary to the right:
```
|0 Blank stem
5|347 Missing a stem (6) in the range
7|9
4| Has a stem (4) outside the range
5|26
6|7
11|432 Leaves aren't sorted correctly
12|9989
5|357 Stems aren't sorted correctly
4|002
6|1
4|5 Duplicate stem
4|6
4|6
5|1
51114 No stem and leaf separator
609
1|2|03 Multiple separators
2|779|
4|8abcdefg9 Invalid characters
5|1,2,3
75 | 4 6 Invalid characters (spaces)
76 | 2 8 8 9
```
This is code golf, so the shortest code wins! Standard loopholes are disallowed.
[Answer]
# Perl, 47 bytes
Includes +2 for `-0p`
Give input on STDIN
`stem.pl`:
```
#!/usr/bin/perl -0p
$"="*";$_=/^((??{$_+$n++})\|@{[0..9,"
"]})+$/
```
[Answer]
## [Pip](http://github.com/dloscutoff/pip), ~~60~~ 58 + 1 = 59 bytes
First stab at the problem, probably could use more golfing. Uses the `-r` flag to read lines of input from stdin. Truthy output is `1`, falsy output is `0` or empty string.
```
g=a+,#g&a@vNE'|NEg@v@v&$&{Y(a^'|1)a@`^\d+\|\d*$`&SNy=^y}Mg
```
Explanation and test suite pending, but in the meantime: [Try it online!](http://pip.tryitonline.net/#code=Zz1nQDArLCNnJmFAdk5FJ3xORWdAdkB2JiQme1koYV4nfDEpYUBgXlxkK1x8XGQqJGAmU055PV55fU1n&input=OTl8MwoxMDB8MDU1NgoxMDF8CjEwMnwKMTAzfDg&args=LXI)
[Answer]
# JavaScript, 189 bytes
```
(x,y=x.split`
`.map(a=>a.split`|`),z=y.map(a=>a[0]))=>!(/[^0-9|\n]|^\|/m.exec(x)||/^\d+\|\n|\|$/.exec(x)||y.some((c,i,a)=>c.length!=2||c[1]!=[...c[1]].sort().join``)||z!=z.sort((a,b)=>a-b))
```
Same length alternate solution:
```
(x,y=x.split`
`.map(a=>a.split`|`),z=y.map(a=>a[0]))=>!(/[^0-9|\n]|^\||^.*\|.*\|.*$/m.exec(x)||/^\d+\|\n|\|$/.exec(x)||y.some((c,i,a)=>c[1]!=[...c[1]].sort().join``)||z!=z.sort((a,b)=>a-b))
```
Defines an anonymous function that takes input as a multiline string.
I'm sure there's more to golf, so let me know if you see any possible improvements.
### Explanation:
The function checks for a number of bad things, and if any of those are true, it returns false (using logical ORs and a NOT)
```
(x,y=x.split("\n").map(a=>a.split`|`), //y is input in pairs of stem and leaves
z=y.map(a=>a[0])) //z is stems
=> //defines function
!( //logical not
/[^0-9|\n]|^\|/m.exec(x) //checks for invalid chars and blank stems
||/^\d+\|\n|\|$/.exec(x) //checks for stems out of range
||y.some((c,i,a)=>c.length!=2 //checks for multiple |s in a line
||c[1]!=[...c[1]].sort().join``)) //checks if leaves are in wrong order
||z!=z.sort((a,b)=>a-b)) //checks for stems in wrong order
```
In the alternate solution, checking for multiple `|`s in a line is done as part of the first regex instead.
[Answer]
## Batch, 409 bytes
```
echo off
set/pp=||exit/b1
set t=
set i=%p:|=&set t=%
if "%t%"=="" exit/b1
for /f "delims=0123456789" %%s in ("%i%")do exit/b1
:l
set t=-
set s=%p:|=&set t=%
if "%s%"=="" exit/b1
if not "%s%"=="%i%" exit/b1
set/ai+=1
for /f "delims=0123456789" %%s in ("%t%")do exit/b1
:m
if "%t:~1,1%"=="" goto n
if %t:~0,1% gtr %t:~1,1% exit/b1
set t=%t:~1%
goto m
:n
set/pp=&&goto l
if "%t%"=="" exit/b1
```
Takes input on STDIN, but exits as soon as it sees an error.
] |
[Question]
[
## Introduction
In this challenge, your task is to write a program that decides whether two given trees are isomorphic.
A tree means a directed acyclic graph where every node has exactly one outgoing edge, except the root, which has none.
Two trees are isomorphic if one can be transformed into the other by renaming the nodes.
For example, the two trees (where every edge points up)
```
0 0
/|\ /|\
1 3 4 1 2 5
|\ /|
2 5 3 4
```
are easily seen to be isomorphic.
We encode a tree as a list `L` of nonnegative integers in the following way.
The root of the tree has label `0`, and it also has nodes `1,2,...,length(L)`.
Each node `i > 0` has an outgoing edge to `L[i]` (using 1-based indexing).
For example, the list (with the indices given under the elements)
```
[0,0,1,3,2,2,5,0]
1 2 3 4 5 6 7 8
```
encodes the tree
```
0
/|\
1 2 8
| |\
3 5 6
| |
4 7
```
## Input
Your inputs are two lists of nonnegative integers, given in the native format or your language.
They encode two trees in the manner specified above.
You can assume the following conditions about them:
1. They are not empty.
2. They have the same length.
3. Each list `L` satisfies `L[i] < i` for all (1-based) indices `i`.
## Output
Your output shall be a truthy value if the trees are isomorphic, and a falsy value if not.
## Rules and scoring
You can write either a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
There are no time restrictions, but built-ins that decide tree or graph isomorphism are disallowed.
## Test cases
Truthy instances
```
[0] [0]
[0,1,2,1] [0,1,1,3]
[0,1,1,3,3] [0,1,2,2,1]
[0,1,0,1,2,3,3,0] [0,0,2,1,0,4,2,1]
[0,1,2,3,1,2,3,0,8] [0,1,0,3,3,4,4,7,7]
```
Falsy instances
```
[0,0] [0,1]
[0,1,2,0,3,3,4] [0,1,2,3,0,4,3]
[0,1,0,1,2,3,3,0] [0,0,2,1,0,5,2,1]
[0,1,1,0,1,3,2,1,5] [0,1,0,3,3,3,2,5,2]
[0,1,2,3,1,2,3,0,8] [0,1,0,1,4,4,5,6,6]
[0,1,0,2,0,3,0,4,0,5] [0,0,2,1,0,3,4,0,0,9]
```
[Answer]
# Python, 83
The anonymous function on the 2nd line is my solution.
```
f=lambda l,i=0:sorted(f(l,j+1)for j,e in enumerate(l)if e==i)
lambda a,b:f(a)==f(b)
```
`f` returns a canonized form of a subtree which is a sorted list of its canonized children. Then we must simply check if the canonized forms of each tree are equal.
[Answer]
# Mathematica, 48 bytes
```
SameQ@@(Sort//@(0(0//.PositionIndex@#))&/@{##})&
```
It's even shorter than the solution that uses `IsomorphicGraphQ`:
```
IsomorphicGraphQ@@(Graph@*MapIndexed[#->Tr@#2&]/@{##})&
```
] |
[Question]
[
Modern mathematics has been formalised using set theory by various systems of axioms. [Zermelo Frankel set theory with the axiom of choice](https://en.wikipedia.org/wiki/Zermelo%E2%80%93Fraenkel_set_theory) (ZFC) forms an intuitive set of axioms and is hence most popular, though stronger choices exist.
Inspiration: [A Relatively Small Turing Machine Whose Behavior Is Independent
of Set Theory](http://www.scottaaronson.com/busybeaver.pdf) by Adam Yedidia and Scott Aaronson
In this paper, a 7918-state Turing machine has been discovered that "checks" the consistency of ZFC. More specifically, it has been proven impossible to prove the machine as either halting or non-halting within ZFC. Note that if the program actually halts in a finite number of steps, its behaviour is also provably halting in any reasonable axiomatic system since we can enumerate this finite number of steps explicitly. Therefore halting can only mean an inconsistency in ZFC itself.
A 1919-state TM was also discovered subsequently
The method they've used (for the 8000 state machine) is to identify a mathematical statement whose truth has been proven to imply the consistency of ZFC, in this case Friedman's mathematical statement on graphs (section 3.1 of the paper), then written a program in a higher level language to check that, then converted it to a Turing machine
Your task: **Write a program in any accepted language on this site (not necessarily a Turing machine) which cannot be proven as halting or non-halting within ZFC.** This is code golf, so shortest program wins.
Your program must be deterministic, it cannot use "random" numbers or take external "random" input.
Likely method to go about this would be to identify a mathematical statement which is already known to be independent of ZFC or a stronger system, and check that - though this is by no means the only way to go about it. Here's a [list](https://en.wikipedia.org/wiki/List_of_statements_independent_of_ZFC) of such statements to get you started.
Related: [Analogous challenge for Peano arithmetic](https://codegolf.stackexchange.com/q/79470/40929)
[Answer]
# NQL: 335 characters
In [*The Busy Beaver Frontier*](https://www.scottaaronson.com/blog/?p=4916) page 12, Scott Aaronson mentions that Stefan O'Rear found a 748-state Turing machine that halts iff ZF is inconsistent. [Here](https://github.com/sorear/metamath-turing-machines/blob/master/riemann-matiyasevich-aaronson.nql) is the code that compiles to that Turing machine from a higher-level programming language called **NQL**, based on Laconic. I'm not very familiar with this language, but applying basic golfing techniques yields **397 characters**:
```
global x;global lcm;global l;global num;global denom;global i;global a;global b;global c;global d;proc main(){lcm=1;while(true){x=x+1;l=lcm;while(lcm!=(lcm/l)*l||lcm!=(lcm/x)*x){lcm=lcm+1;}if(x>253){num=0;denom=1;i=1;while(i<=lcm){num=num*i+denom;denom=denom*i;i=i+1;}a=num-denom*x;a=a*a;b=denom*denom;c=0;d=1;i=1;while(i<=x){c=c*i+d;d=d*i;i=i+1;}c=c*c;c=c*c*x;d=d*d;d=d*d;if(a*d>b*c){return;}}}}
```
I confirmed that the same output is produced as the original program with
```
diff <(python3 nqlaconic.py --print-tm riemann-matiyasevich-aaronson.nql) \
<(python3 nqlaconic.py --print-tm riemann-matiyasevich-aaronson-golfed.nql)
```
Applying variable name shortening (this changes the output) yields **335 characters**:
```
global x;global v;global l;global z;global y;global i;global a;global b;global c;global d;proc main(){v=1;while(true){x=x+1;l=v;while(v!=(v/l)*l||v!=(v/x)*x){v=v+1;}if(x>253){z=0;y=1;i=1;while(i<=v){z=z*i+y;y=y*i;i=i+1;}a=z-y*x;a=a*a;b=y*y;c=0;d=1;i=1;while(i<=x){c=c*i+d;d=d*i;i=i+1;}c=c*c;c=c*c*x;d=d*d;d=d*d;if(a*d>b*c){return;}}}}
```
Given its C-like syntax, I imagine the code could be easily adapted to other languages and shortened further.
] |
[Question]
[
In the decimal representation of every rational number `p/q`, you have a periodic tail, a non-periodic head, and a section before the decimal point in the following format:
```
(before decimal point).(non-periodic)(periodic)
```
Some examples include:
```
1/70 = 0.0142857... = (0).(0)(142857)
10/7 = 1.428571... = (1).()(428571) ## no non-periodic part
1/13 = 0.076923... = (0).()(076923)
3/40 = 0.075 = (0).(075)() ## no periodic part
-2/15 = -0.13... = -(0).(1)(3) ## negative
75/38 = 1.9736842105263157894... = (1).(9)(736842105263157894)
## periodic part longer than float can handle
25/168 = 0.148809523... = (0).(148)(809523)
120/99 = 40/33 = 1.212121... = (1).()(21)
2/1 = 2 = (2).()() ## no periodic, no non-periodic
0/1 = 0 = (0).()()
0/2 = 0 = (0).()()
299/792 = 0.37752... = (0).(377)(52)
95/-14 = -6.7857142... = -(6).(7)(857142)
-95/-14 = 6.7857142... = (6).(7)(857142)
```
The challenge is to swap the periodic and non-periodic parts, leaving the `before decimal point` alone, to create a new number. For example:
```
25/168 = 0.148809523... = (0).(148)(809523)
=> (0).(809523)(148) = 0.809523148148... = 870397/1080000
```
If a number has no periodic part like `0.25` turn that number into a new periodic number, and vice versa.
```
1/4 = 0.25 = (0).(25)() => (0).()(25) = 0.252525... = 25/99
4/9 = 0.444444... = (0).()(4) => (0).(4)() = 0.4 = 2/5
5/1 = 5 = (5).()() => (5).()() = 5 = 5/1
```
**The challenge**
* Take a fraction `x` as input, as a string, two inputs, a rational number, or whatever method suits your language.
* **Swap** the periodic and non-periodic parts of the decimal representation of `x` to create a new number, leaving the part before the decimal alone. The periodic part always starts as soon as possible so that the non-periodic part is as short as possible. Examples are below.
* Return the swapped number as a new fraction. The input is not necessarily reduced though the output should be. Input format is allowed to differ from output format.
* The numerator `p` of `x` will be an integer with absolute value of one million or less and the denominator `q` of `x` will be a **non-zero** integer with absolute value of one million or less.
* The numerator `r` and denominator `s` of the result is not guaranteed to be less than one million. Given the length of the periodic parts of these numbers, it is recommended that you avoid directly converting to floats.
* This is code golf. Shortest answer in bytes wins.
**Examples**
```
1/70 = (0).(0)(142857) => (0).(142857)(0) = (0).(142857)() = 0.142857 = 142857/1000000
10/7 = (1).()(428571) => (1).(428571)() = 1.428571 = 1428571/1000000
1/13 = (0).()(076923) => (0).(076923)() = 0.076293 = 76923/1000000
3/40 = (0).(075)() => (0).()(075) = 0.075075... = 75/999 = 25/333
-2/15 = -(0).(1)(3) => -(0).(3)(1) = -0.311111... = -28/90 = -14/45
75/38 = (1).(9)(736842105263157894)
=> (1).(736842105263157894)(9) = (1).(736842105263157895)() ## since 0.999... = 1
= 1.736842105263157895 = 1736842105263157895/1000000000000000000
= 347368421052631579/200000000000000000
25/168 = (0).(148)(809523) => (0).(809523)(148) = 0.809523148148... = 870397/1080000
120/99 = (1).()(21) => (1).(21)() = 1.21 = 121/100
2/1 = (2).()() => (2).()() = 2 = 2/1
0/1 = (0).()() => (0).()() = 0 = 0/1
0/2 = (0).()() => (0).()() = 0 = 0/1
299/792 = (0).(377)(52) => (0).(52)(377) = 0.52377377... = 2093/3996
95/-14 = -(6).(7)(857142) => -(6).(857142)(7) = -6.857142777... = -12342857/1800000
-95/-14 = (6).(7)(857142) => (6).(857142)(7) = 6.857142777... = 12342857/1800000
```
[Answer]
# Python 2, 292 bytes
```
def x(n,d):
L=len;s=cmp(n*d,0);n*=s;b=p=`n/d`;a={};n%=d
while not n in a:
a[n]=p;q=n/d;n=n%d
if q==0:n*=10;p+=' '
p=p[:-1]+`q`
p=p[L(a[n]):];a=a[n][L(b):]
if n==0:p=''
n=int(b+p+a);d=10**L(p+a)
if a!='':n-=int(b+p);d-=10**L(p)
import fractions as f;g=f.gcd(n,d);return(n/g*s,d/g)
```
Ungolfed version, works in both python 2&3. Also prints decimal representation.
```
def x(n,d):
# sign handling
s=n*d>0-n*d<0
n*=s
# b, a, p: BEFORE decimal, AFTER decimal, PERIODIC part
b=p=str(n//d)
a={}
n%=d
# long division
while not n in a:
a[n]=p
q=n//d
n=n%d
if q==0:
n*=10
p+=' '
p=p[:-1]+str(q)
# a/p still contain b/ba as prefixes, remove them
p=p[len(a[n]):]
a=a[n][len(b):]
if n==0: p=''
# print decimal representation
print("(" + b + ").(" + a + ")(" + p + ")")
# reassemble fraction (with a and p exchanged)
n=int(b+p+a)
d=10**len(p+a)
if a!='':
n-=int(b+p)
d-=10**len(p)
# reduce output
from fractions import gcd
g=gcd(n,d)
return(n//g*s,d//g)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~102~~ ~~101~~ ~~89~~ ~~87~~ ~~83~~ ~~81~~ ~~79~~ ~~78~~ ~~77~~ 74 bytes
This took way to long to write, way too long to debug, and definitely needs a lot of golfing (~~eight seven six~~ ~~five~~ four links, holy cow), but it is, to the best of my knowledge, correct. Many, many thanks to Dennis for his help here, especially with the first two links. Many thanks to Rainer P. as well, as I ended up borrowing a lot of the algorithm in their Python answer.
**Golfing edits:** -1 byte thanks to Xanderhall. Bug fix from not using the correct logical NOT builtin. -13 bytes from golfing the numerator links. +1 byte from fixing a bug for negative `d` with thanks to Dennis. Restructured the links so that the numerator generation is all in one link. -2 bytes from combining the second and third links. -4 bytes from moving some common elements of the third and fourth links to the second link and the main link. -2 bytes from removing some superfluous chain operators. -2 bytes from rearranging the numerator link. -1 byte from moving `Ḣ€` to end of the second link. Fixed a bug in the main link. -1 byte from changing `Ṫ ... ,Ḣ` to `Ḣ ... ṭ`. -3 bytes from moving the numerator link into the main link.
Golfing suggestions welcome! [Try it online!](https://tio.run/nexus/jelly#@2/0cHf34emPGremPGrcwnW4/fCEhzu26YDoI/sf7pjvEHNo68Mdix7uaD08Ie3Ixoc710L5XTDmo6Y1QHRoq5sOkBMINMEHJNK4VYvr8PSHOxccWvmoccfh6aqHth7arAO0wtFK3/rwBKASI5D5PYenH1oHtC1eH2yGVbr@////jUz@6xqaWQAA "Jelly – TIO Nexus")
```
2ị×⁵d⁴
ÇÐḶ,ÇÐĿḟ@\µḢḅÐfıṭµḢḊṭµḢ€€µF,ḢQ
ÇL€⁵*
×Ṡ©⁸×%µ³,⁴A:/;Ѐ2ĿḌ×®,Ç_/€µ:g/
```
**Explanation**
First, I'll explain the **main link**, which calls the other links.
```
×Ṡ©⁸×%µ³,⁴A:/;Ѐ2ĿḌ×®,Ç_/€µ:g/ Main link. Left argument: n (int), right argument: d (int)
Split into three chains.
×Ṡ©⁸×% First chain
× Multiply n by d.
Ṡ© Yield sign(n*d) and save it to the register.
⁸× Multiply by n.
% Yield n*sgn(n*d) modulo d.
µ³,⁴A:/;Ѐ2ĿḌ×®,Ç_/€ Second chain
What follows is the formula for the numerator.
(+) means combining the digits of two numbers into one number.
( `integer (+) periodic (+) non-periodic` - `integer (+) periodic` )
µ Start a new monadic chain with n*sgn(n*d)%d.
³,⁴ Pair the original two arguments as a nilad.
A Get their absolute values.
:/ Integer divide to get the integer part of abs(n)/abs(d).
2Ŀ Yield the results of the second link.
;Ѐ Append the integer part to each item in the right argument.
This appends to both lists from the second link.
Ḍ Convert each list from decimal to integer.
×® Multiply by sign(n*d) retrieved from the register.
;Ç Concatenate with the result of the third link (our new denominator).
_/€ Reduced subtract over each list.
Yields the proper numerator and denominator.
µ:g/ Third chain
µ Start a new monadic chain with [numerator, denominator].
g/ Yield gcd(numerator, denominator).
: Divide [numerator, denominator] by the gcd.
Return this as our new fraction.
```
Then, the **first link** that gets the digits.
```
2ị×⁵d⁴ First link: Gets the decimal digits one at a time in the format:
[digit, remainder to use in the next iteration]
2ị Gets the second index (the remainder).
×⁵ Multiply by 10.
d⁴ Divmod with d.
```
Now, the **second link** that gets the periodic and non-periodic parts of `n/d`, and a lot of other heavy lifting.
```
ÇÐḶ,ÇÐĿḟ@\µḢḅÐfıṭµḢḊṭµḢ€€µF,ḢQ Second link: Loops the first link,
separates the periodic digits and non-periodic digits,
removes the extras to get only the decimal digits,
and prepares for the third and fourth links.
Split into five chains.
ÇÐḶ,ÇÐĿḟ@\ First chain
ÇÐḶ Loop and collect the intermediate results **in the loop**.
ÇÐĿ Loop and collect **all** of the intermediate results.
, Pair into one list.
ḟ@\ Filter the loop results out the list of all results,
leaving only [[periodic part], [non-periodic part]].
µḢḅÐfıṭµḢḊṭ Second and third chains
µ Start a new monadic chain.
Ḣ Get the head [periodic part].
Ðf Filter out any [0, 0] lists from a non-periodic number,
ḅ ı by converting to a complex number before filtering.
Only removes 0+0j. This removes extra zeroes at the end.
ṭ Tack the result onto the left argument again.
µ Start a new monadic chain.
Ḣ Get the head [non-periodic and extra baggage].
Ḋ Dequeue the extra baggage.
ṭ Tack the result onto the left argument again.
µḢ€€µF,ḢQ Fourth and fifth chains
µ Start a new monadic chain with the processed periodic and non-periodic parts.
Ḣ€€ Get the head of each list (the digits)
in both the periodic and non-periodic parts.
µ Start a new monadic chain with these lists of digits.
F Left argument flattened.
Ḣ Head of the left argument.
, Pair the flattened list and the head into one list.
Q Uniquify this list. (Only removes if non-periodic part is empty)
Removes any duplicates resulting from a purely periodic n/d.
```
The **third link**, which yields our new denominator.
```
ÇL€⁵* Third link: Generate the denominator.
What follows is the formula for the denominator.
( 10**(num_digits) - ( 10**(num_periodic_digits) if len(non-periodic) else 0 ) )
Ç Yield the results of the second link.
L€ Get the length of each item in the list.
The number of digits in total and the number of digits in the periodic part.
⁵* 10 to the power of each number of digits.
```
] |
[Question]
[
>
> This is an [*Irregular Webcomic!*](http://www.irregularwebcomic.net/) themed task.\*
>
>
>
[**Death**](http://www.irregularwebcomic.net/cast/death.html) is a rather extensive orginization, and, although Head Death has had no trouble telling his employees apart, certain other entities connected to the orginization have had trouble keeping track of them all.
Thus, your task here is to, given the title of one of the various Deaths, generate the corresponding 32x32 pixel image of that Death.
Furthermore, as Head Death is rather bureaucratic (and a little bit stingy), the shortest program (after a few bonuses have been taken into account) will be the one chosen for official use.
Input must be case-insensitive. Additionally, the prefixes `Death Of`, `Death By`, and `The Death Of` should be treated as equivalent.
The output image may be saved to a file (in any lossless bitmap image format) or displayed on the screen.
The following are the **EXACT** RGB values to be used:
```
White 255 255 255
Black 0 0 0
Dark Gray 125 125 125
Bone Gray 170 170 170
Purple 60 0 140
Brown 120 40 0
Blue 0 80 200
Green 0 100 0
Neon Green 100 255 0
Red 0 255 0
```
(Note that no one Death uses all of those colors, and the only color which is common to all of them is bone gray)
Each output image shown here is shown first at actual size and then at 3x close-up.
# You are required to support the following Deaths:
**The Death of Insanely Overpowered Fireballs**
[](https://i.stack.imgur.com/PfBbD.png) [](https://i.stack.imgur.com/ZyeMM.png)
**The Death of Choking On A Giant Frog**
[](https://i.stack.imgur.com/QolxS.png) [](https://i.stack.imgur.com/tiIPY.png)
**Head Death**
[](https://i.stack.imgur.com/5w9To.png) [](https://i.stack.imgur.com/nMMY9.png)
**The Death of Being Wrestled To Death By Steve**
[](https://i.stack.imgur.com/XUAPl.png) [](https://i.stack.imgur.com/y5BLN.png)
**The Death of Inhaling Hatmaking Chemicals**
[](https://i.stack.imgur.com/qauom.png) [](https://i.stack.imgur.com/HhqAI.png)
**Charon**
[](https://i.stack.imgur.com/TmZDs.png) [](https://i.stack.imgur.com/YhU5f.png)
(Note that Charon's exact role in the organization is unknown)
# You are not required to support the following Deaths, but may do so for various bonuses
[**Death by Having Your Pelvis Crushed**](http://www.irregularwebcomic.net/342.html) (-8% bonus)
[](https://i.stack.imgur.com/3VX8a.png) [](https://i.stack.imgur.com/cC8h1.png)
**The Death of Being Ground By A Mars Rover Rock Abrasion Tool** (-10% bonus)
[](https://i.stack.imgur.com/OCMzS.png) [](https://i.stack.imgur.com/Hs7ip.png)
**The Death of Drowning in a Reactor Pool** (-10% bonus)
[](https://i.stack.imgur.com/F3gaL.png) [](https://i.stack.imgur.com/Am4uL.png)
[**The Death of Being Impaled By A Javelin**](http://www.irregularwebcomic.net/399.html) (-8% bonus)
[](https://i.stack.imgur.com/AIM7N.png) [](https://i.stack.imgur.com/kFUEc.png)
[**The Death of Being Stabbed By A Cutlass**](http://www.irregularwebcomic.net/495.html) (-9% bonus)
[](https://i.stack.imgur.com/OCcz3.png) [](https://i.stack.imgur.com/psMD6.png)
[**The Death of Bad Pizza Deliveries**](http://www.irregularwebcomic.net/1048.html) (-7% bonus)
[](https://i.stack.imgur.com/fRWxp.png) [](https://i.stack.imgur.com/kJ61Q.png)
(Probably the only Death not to wear a cape. Don't ask me why.)
If you add include all of them, the final multiplier is `0.92*0.9*0.9*0.92*0.91*0.93≈0.58`.
# Additional Bonus
If you use an RGBA format and replace the white background with transparency, save an extra 12%.
>
> `*` *Irregular Webcomic!* is ©2002-Present David Morgan-Mar. CC BY-NC-SA.
>
>
>
[Answer]
# JavaScript (ES6), ~~714~~ ~~677.97~~ ~~651.76~~ ~~634.36~~ ~~545.76~~ 1063 - (8% \* 10% \* 10% \* 8% \* 9% \* 7% \* 12%) = 542.75
```
e=>(e=e.slice(-4,-2),c=document.createElement("canvas"),c.width=c.height=32,t=(r="000")=>(o=c.getContext("2d")).fillStyle="#"+r,r=(r,t,l=1,e=1)=>o.fillRect(r,t,l,e),u=12,i="7d7d7d",t(),r(l=13,8,3),(n=!/ea|te|ca|ri|Po/.test(e))&&(r(l,6,3,5),r(u,7,5,3)),"ca"==e&&(r(l,3,3,3),r(u,6,5)),"ri"!=e&&(t("ea"==e?"3C008C":/te|Po/.test(e)?"006400":""),r(10,l,9,15+("ea"==e)),r(11,u,7),r(u,11,5)),"te"==e&&(t("782800"),r(u,6,5),r(l,5),r(15,5)),"ri"==e&&(t("f00"),r(l,5,3,2),r(16,6)),t("aaa"),r(l,7,3),r(l,9,3),r(m=14,8),r(m,u,1,u),r(u,u,5),r(l,m,3),r(l,16,3),r(l,18,3),r(l,20,3),r(l,24,3),r(u,25),r(16,25),r(11,26,1,6),r(17,26,1,6),r(17,l,1,8),n||r(m,10,1,2),/al|ar|sh|el|To/.test(e)?(r(8,u,4),t(),r(7,9,1,23),"al"==e&&(r(3,9,4,2),r(2,10,1,2)),"sh"==e&&r(2,8,6,4),"el"==e&&(r(6,6,3,4),r(7,4,1,2),r(5,8,5)),"To"==e&&(r(6,8,3,23),r(4,m,2,3),r(3,m),r(l,9,3),t("fff"),r(6,9),r(5,15),t("0050c8"),r(l,7,3,2),r(m,9))):"la"==e?(r(11,u),r(10,l),r(9,15,1,2),t(i),r(9,17,1,12),r(8,17),r(7,18),r(8,19)):r(11,l,1,8),"Po"==e&&(t(i),r(l,10,3),t("64ff00"),r(u,7,5,3),r(l,6,3)),c.toDataURL())
```
Generates a data-url to a png of the image, and covers all of the bonuses.
EDIT: Just realized the bonus that a transparent background knocks off another 12%, which also reduces my byte count!
] |
[Question]
[
Imagine a ***W*** by ***H*** grid of squares that wraps toroidally. Items are placed onto the grid as follows.
The first item can be placed on any square, but subsequent items must not be within a [Manhattan distance](http://en.wikipedia.org/wiki/Taxicab_geometry "Wikipedia article") ***R*** of any previous item (also known as a [Von Neumann neighbourhood of range ***R***](http://en.wikipedia.org/wiki/Von_Neumann_neighborhood#von_Neumann_neighborhood_of_range_r "Wikipedia article")). Carefully choosing the positions allows fitting a large number of items onto the grid before there are no more valid positions. However, instead consider the opposite aim: What is the lowest number of items that can be placed and leave no further valid positions?
Here is a radius 5 exclusion zone:

Here is another radius 5 exclusion zone, this time near the edges so the wrapping behaviour is apparent:

### Input
Three integers:
* ***W***: width of grid *(positive integer)*
* ***H***: height of grid *(positive integer)*
* ***R***: radius of exclusion zone *(non-negative integer)*
### Output
An integer ***N***, which is the smallest number of items that can be placed preventing any further valid placements.
### Details
* A radius of zero gives an exclusion zone of 1 square (the one the item was placed on).
* A radius of N excludes the zone that can be reached in N orthogonal steps (remember the edges wrap toroidally).
Your code must work for the trivial case of ***R*** = 0, but does not need to work for ***W*** = 0 or ***H*** = 0.
Your code must also deal with the case where ***R*** > ***W*** or ***R*** > ***H***.
# Time limit and test cases
Your code must be able to deal with all of the test cases, and each test case must complete within 5 minutes. This should be easy (the example JavaScript solution takes a few seconds for each test case). The time limit is mainly to exclude the extreme brute force approach. The example approach is still fairly brute force.
If your code completes within 5 minutes on one machine but not on another that will be close enough.
**Test cases** in the form inputs: output as `W H R : N`
```
5 4 4 : 1
5 4 3 : 2
5 4 2 : 2
5 4 1 : 5
7 5 5 : 1
7 5 4 : 2
7 5 3 : 2
7 5 2 : 4
8 8 8 : 1
8 8 7 : 2
8 8 6 : 2
8 8 5 : 2
8 8 4 : 2
8 8 3 : 4
7 6 4 : 2
7 6 2 : 4
11 7 4 : 3
11 9 4 : 4
13 13 6 : 3
11 11 5 : 3
15 14 7 : 2
16 16 8 : 2
```
# Snippet to help visualise and play around with ideas
```
canvas = document.getElementById('gridCanvas');ctx = canvas.getContext('2d');widthSelector = document.getElementById('width');heightSelector = document.getElementById('height');radiusSelector = document.getElementById('radius');itemCount = document.getElementById('itemCount');canvasMaxWidth = canvas.width;canvasMaxHeight = canvas.height;gridlineColour = '#888';emptyColour = '#ddd';itemColour = '#420';hoverCellColour = '#840';exclusionColour = '#d22';validColour = '#8f7';invalidColour = '#fbb';overlapColour = '#600';resetGrid();x = -1;y = -1;function resetGrid() {gridWidth = widthSelector.value;gridHeight = heightSelector.value;radius = radiusSelector.value;numberOfItems = 0;itemCount.value = numberOfItems + ' items placed.';cells = [gridWidth * gridHeight];for (i=0; i<gridWidth*gridHeight; i++) {cells[i] = '#ddd';}cellSize = Math.min(Math.floor(canvasMaxWidth/gridWidth), Math.floor(canvasMaxHeight/gridHeight));pixelWidth = gridWidth * cellSize + 1;canvas.width = pixelWidth;pixelHeight = gridHeight * cellSize + 1;canvas.height = pixelHeight;leaveCanvas();}function checkPosition(event) {bound = canvas.getBoundingClientRect();canvasX = event.clientX - bound.left;canvasY = event.clientY - bound.top;newX = Math.min(Math.floor(canvasX / cellSize), gridWidth-1);newY = Math.min(Math.floor(canvasY / cellSize), gridHeight-1);if (newX != x || newY != y) {x = newX;y = newY;drawGrid();}}function leaveCanvas() {x = -1;y = -1;drawGrid();}function drawGrid() {ctx.fillStyle = gridlineColour;ctx.fillRect(0, 0, pixelWidth, pixelHeight);cellColour = cells[x + gridWidth * y];if (cellColour == itemColour || cellColour == exclusionColour) {zoneColour = invalidColour;} else {zoneColour = validColour;}for (gridX=0; gridX<gridWidth; gridX++) {for (gridY=0; gridY<gridHeight; gridY++) {colour = (cells[gridX + gridWidth * gridY]);if (x >= 0 && y >= 0) {if (x == gridX && y == gridY) {colour = hoverCellColour;} else if (manhattanDistance(x, y, gridX, gridY) <= radius) {if (colour == exclusionColour) {colour = overlapColour;} else if (colour != itemColour) {colour = zoneColour;}}}ctx.fillStyle = colour;ctx.fillRect(gridX * cellSize + 1, gridY * cellSize + 1, cellSize - 1, cellSize - 1);}}}function manhattanDistance(a, b, c, d) {horizontal = Math.min(Math.abs((gridWidth + c - a) % gridWidth), Math.abs((gridWidth + a - c) % gridWidth));vertical = Math.min(Math.abs((gridHeight + d - b) % gridHeight), Math.abs((gridHeight + b - d) % gridHeight));return vertical + horizontal;}function placeItem(event) {bound = canvas.getBoundingClientRect();canvasX = event.clientX - bound.left;canvasY = event.clientY - bound.top;attemptX = Math.min(Math.floor(canvasX / cellSize), gridWidth-1);attemptY = Math.min(Math.floor(canvasY / cellSize), gridHeight-1);colour = cells[attemptX + gridWidth * attemptY];if (colour != itemColour && colour != exclusionColour) {for (a=0; a<gridWidth; a++) {for (b=0; b<gridHeight; b++) {if (manhattanDistance(a, b, attemptX, attemptY) <= radius) {cells[a + gridWidth * b] = exclusionColour;}}}cells[attemptX + gridWidth * attemptY] = itemColour;drawGrid();numberOfItems++;itemCount.value = numberOfItems + ' items placed.';}}
```
```
<canvas id='gridCanvas' width='500' height='300' style='border:none' onmousemove='checkPosition(event)' onmouseleave='leaveCanvas()' onclick='placeItem(event)'></canvas><br><textarea id='itemCount' readonly></textarea><br><button id='reset' onclick='resetGrid()'>Reset</button> with the following values:<br>Width:<input id='width' type='number' value='20' min='1' max='50' maxlength='2' step='1'><br>Height:<input id='height' type='number' value='13' min='1' max='30' maxlength='2' step='1'><br>Radius:<input id='radius' type='number' value='5' min='0' max='60' maxlength='2' step='1'>
```
# Example (ungolfed) solution
*Just an example for small outputs (resulting from radius not much smaller than the width and height). Can handle any of the test cases but will time out and give up for most larger cases.*
```
itemCount = document.getElementById('itemCount')
calculateButton = document.getElementById('calculate')
widthSelector = document.getElementById('width')
heightSelector = document.getElementById('height')
radiusSelector = document.getElementById('radius')
function calculate() {
calculateButton.disabled = true
widthSelector.disabled = true
heightSelector.disabled = true
radiusSelector.disabled = true
itemCount.value = 'Calculating...'
setTimeout(delayedCalculate, 100)
}
function delayedCalculate() {
gridWidth = widthSelector.value
gridHeight = heightSelector.value
radius = radiusSelector.value
startingMin = gridWidth*gridHeight + 1
var cells = [gridWidth * gridHeight]
for (i=0; i<gridWidth*gridHeight; i++) {
cells[i] = 0
}
var gridState = gridWithItemAdded(cells, 0, 0)
var minimum = minFromHere(gridState) + 1
itemCount.value = 'Minimum ' + minimum + ' items required.'
calculateButton.disabled = false
widthSelector.disabled = false
heightSelector.disabled = false
radiusSelector.disabled = false
}
function minFromHere(gridState) {
var x
var y
var newGridState
var noCells = true
var min = startingMin
for (x=0; x<gridWidth; x++) {
for (y=0; y<gridHeight; y++) {
if (gridState[x + gridWidth * y] == 0) {
noCells = false
newGridState = gridWithItemAdded(gridState, x, y)
m = minFromHere(newGridState)
if (m < min) {
min = m
}
}
}
}
if (noCells) return 0
return min + 1
}
function gridWithItemAdded(gridState, x, y) {
var a
var b
var grid = gridState.slice()
for (a=0; a<gridWidth; a++) {
for (b=0; b<gridHeight; b++) {
if (manhattanDistance(a, b, x, y) <= radius) {
grid[a + gridWidth * b] = 1
}
}
}
return grid
}
function manhattanDistance(a, b, c, d) {
horizontal = Math.min(Math.abs((gridWidth + c - a) % gridWidth), Math.abs((gridWidth + a - c) % gridWidth))
vertical = Math.min(Math.abs((gridHeight + d - b) % gridHeight), Math.abs((gridHeight + b - d) % gridHeight))
return vertical + horizontal
}
```
```
<textarea id='itemCount' readonly></textarea>
<br>
<button id='calculate' onclick='calculate()'>Calculate</button> with the following values:
<br>
Width:<input id='width' type='number' value='5' min='1' max='50' maxlength='2' step='1'>
<br>
Height:<input id='height' type='number' value='4' min='1' max='30' maxlength='2' step='1'>
<br>
Radius:<input id='radius' type='number' value='1' min='0' max='60' maxlength='2' step='1'>
```
[Answer]
# Python 2, ~~216~~ 182 bytes
```
def f(W,H,R):L={(i%W,i/W)for i in range(W*H)};M={(x,y)for x,y in L if min(x,W-x)+min(y,H-y)>R};g=lambda s:min([1+g(s-{((a+x)%W,(b+y)%H)for x,y in L-M})for a,b in s]or[1]);return g(M)
```
Input like `f(16,16,8)`. Uses pretty much the same algorithm as [@trichoplax's sample](https://codegolf.stackexchange.com/a/51611/21487), but with sets. Initially I didn't place the first item at `(0, 0)`, but this made it choke on the last few cases.
All cases above complete within 10 seconds, well under the limit. In fact, the cases are small enough that I had a little room to be less efficient, allowing me to remove a check which checked for duplicate states.
*(Thanks to @trichoplax for golfing help)*
**Expanded:**
```
def f(W,H,R):
# All cells
L={(i%W,i/W)for i in range(W*H)}
# Mask: Complement of exclusion zone around (0, 0)
M={(x,y)for x,y in L if min(x,W-x)+min(y,H-y)>R}
# Place recursively
g=lambda s:min([1+g(s-{((a+x)%W,(b+y)%H)for x,y in L-M})for a,b in s]or[1])
return g(M)
```
[Answer]
# Python 3, ~~270~~ ~~262~~ ~~260~~ ~~251~~ ~~246~~ 226
*(Thanks to Sp3000 for:*
* `-~` *instead of* `+1`, *which lets me lose a space after* `return` *on the last line.*
* *losing superfluous parentheses around* `W*H`.
* *lambdas...*
* *putting everything on one line.*
* *python modulo `%` gives positive result for negative numbers, to save another 20 bytes)*
This is the JavaScript example answer from the question ported into Python 3.
To avoid having to pass so many function arguments around, I've moved the two supporting functions inside the calculate function so that they share its scope. I've also condensed each of these functions into a single line to avoid the cost of indentation.
### Explanation
This fairly brute force approach places the first item at (0, 0), and then marks all the excluded squares. It then recursively places an item at all remaining valid squares until all squares are excluded, and returns the minimum number of items required.
### Golfed code:
```
def C(W,H,R):r=range;M=lambda g:min([M(G(g,x,y))for x in r(W)for y in r(H)if g[x+W*y]]or[-1])+1;G=lambda g,x,y:[g[a+W*b]if min((x-a)%W,(a-x)%W)+min((y-b)%H,(b-y)%H)>R else 0for b in r(H)for a in r(W)];return-~M(G([1]*W*H,0,0))
```
### Ungolfed code:
```
def calculate(W, H, R):
starting_min = W * H + 1
cells = [0] * (W * H)
grid_state = grid_with_item_added(cells, 0, 0, W, H, R)
return min_from_here(grid_state, starting_min, W, H, R) + 1
def min_from_here(grid_state, starting_min, W, H, R):
no_cells = True
min = starting_min
for x in range(W):
for y in range(H):
if grid_state[x + W * y] == 0:
no_cells = False
new_grid_state = grid_with_item_added(grid_state, x, y, W, H, R)
m = min_from_here(new_grid_state, starting_min, W, H, R)
if m < min:
min = m
if no_cells:
return 0
else:
return min + 1
def grid_with_item_added(grid_state, x, y, W, H, R):
grid = grid_state[:]
for a in range(W):
for b in range(H):
if manhattan_distance(a, b, x, y, W, H) <= R:
grid[a + W * b] = 1
return grid
def manhattan_distance(a, b, c, d, W, H):
horizontal = min(abs(W + c - a) % W, abs(W + a - c) % W)
vertical = min(abs(H + d - b) % H, abs(H + b - d) % H)
return horizontal + vertical
if __name__ == '__main__':
import sys
arguments = sys.argv[1:]
if len(arguments) < 3:
print('3 arguments required: width, height and radius')
else:
print(calculate(int(arguments[0]), int(arguments[1]), int(arguments[2])))
```
The ungolfed code defines a function and also includes code to allow it to be called from the command line. The golfed code just defines the function, which is [sufficient for standard code golf questions](http://meta.codegolf.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet).
If you would like to test the golfed code from the command line, here it is with the command line handling included (but not golfed):
### Command line testable golfed code
```
def C(W,H,R):r=range;M=lambda g:min([M(G(g,x,y))for x in r(W)for y in r(H)if g[x+W*y]]or[-1])+1;G=lambda g,x,y:[g[a+W*b]if min((x-a)%W,(a-x)%W)+min((y-b)%H,(b-y)%H)>R else 0for b in r(H)for a in r(W)];return-~M(G([1]*W*H,0,0))
if __name__ == '__main__':
import sys
arguments = sys.argv[1:]
if len(arguments) < 3:
print('3 arguments required: width, height and radius')
else:
print(C(int(arguments[0]), int(arguments[1]), int(arguments[2])))
```
] |
[Question]
[
The goal of this challenge is to check and extend the OEIS sequence [A334248](http://oeis.org/A334248): Number of distinct acyclic orientations of the edges of an n-dimensional cube.
Take an n-dimensional cube (if n=1, this is a line; if n=2, a square; if n=3, a cube; if n=4, a hypercube/tesseract; etc), and give a direction to all of its edges so that no cycles are formed. The terms of the sequence are the number of (rotationally and reflectively) distinct orientations that can be obtained.
## Example
For n=2, there are 14 ways to assign directions to the edges of a square with no cycles formed:

However, only three of these are distinct if they are rotated and reflected:

So when n=2, the answer is 3.
---
The winner of this [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge will be the program that calculates the most terms when run on my computer (Ubuntu, 64GB RAM) in one hour. If there is a tie, the program that computes the terms in the shortest time will be the winner.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), n = 4, <1 second on my computer
```
(* Elements of the hyperoctahedral group,represented by matrices *)
HyperoctahedralGroup[n_] :=
Join @@ Table[
Permute[IdentityMatrix@n, perm]*sign, {perm,
Permutations@Range@n}, {sign, Tuples[{1, -1}, n]}];
(* Action of group elements on a vertex of the hypercube,
where each vertex is represented by an integer from 1 to 2^n *)
ActOn[n_, g_, v_] :=
FromDigits[(1 + (IntegerDigits[v - 1, 2, n]*2 - 1) . g)/2, 2] + 1;
(* Orbits of vertices under such action *)
Orbits[n_, g_] :=
ConnectedComponents@Table[v <-> ActOn[n, g, v], {v, 2^n}];
(* Whether any orbit contains adjacent vertices *)
OrbitConatinsAdjacentVertices[edges_, orbits_] :=
Or @@ Or @@@ Outer[SubsetQ, orbits, edges, 1];
(* Merging vertices in each orbit into a single vertex *)
MergeVertices[edges_, orbits_] :=
Graph@DeleteDuplicates[
Sort /@ (edges /. (Alternatives@##2 -> #1 & @@@ orbits))];
(* Number of acyclic orientations fixed by some group element *)
InvariantAcyclicOrientations[n_, edges_, g_] :=
With[{orbits = Orbits[n, g]},
If[OrbitConatinsAdjacentVertices[edges, orbits], 0,
Abs[ChromaticPolynomial[MergeVertices[edges, orbits], -1]]]];
(* OEIS sequence A334248 *)
A334248[n_] :=
With[{edges = List @@@ EdgeList@HypercubeGraph@n},
Sum[InvariantAcyclicOrientations[n, edges, g], {g,
HyperoctahedralGroup[n]}]/(2^n*n!)];
Do[Print[n -> A334248[n]], {n, 1, 4}]
```
[Try it online!](https://tio.run/##jVRfb9MwEH/vpzg0CbUlXUm3BwRsSrUOVsTooBN7sAJy02tilNjFdsKqqZ@9nOOk29AEVGqbOHeX3z@74DbDgluR8N2u24fzHAuU1oBaAT2BbLNGrRLLM1xqnkOqVbkONK41GqrDJSw2QP1aJGig3@tcPG547@qZ/B7D6xPoAHxQQkIUwTVf5MhoAeAKdVFaZNMlDRR2c@mm3UYyAJpUxH0jUrq@czcB1B1NC6FW0kRfuEwxkluq8aXX5TpHw@7CAAYhLct4G7/pdIjdOHEtjlvNA3DPVgKHCrXF20fMk3KBQedXhhoBeZK1NcLAHxpwCYKuU9Sw0qqAEKyC0TfpNKHXziSJEEBK32ovxjsqnIhUWMO6IbyA7tRPaNYqGABxGDkG/ZG76cEhpL0hrYxiqg89q5leCO@YQ1cbUcolATElIeaeM8HwdQ2OFsOZkhITInGmirWSTo3Im1PB28EpNNiphZDHpHEVOFqtojcZklia6G9AufmQKGm5kAb48gdPaN49qhYDvZO8k2bcVHxtChguUzQEr55k9hhn2kWm/qU/yopm83Jh0H5uSwOoWwMIG1yXqFMh0/t3U@xqAz1IskqR44ZKcmxNJXiuDf8F573m6yyaUHgsTihrtHcsVdfRnCttYRhBt@6F4SF0xzkBdoQrNNHBARl5CgchPK/Z@NG9XgP7U1ksSE2ykiebhCZTgSCFfNRhJW592owq8HGGHfqprLgWXNqxb5496K1tbwnd238jbMbuPAo4gTYiVBJv/W6brth/mNaKRAl52ezS8cKws4wi7k6XK5VvpCoEz9kTGj/oHoQxfZpgn0/nYPBniTJBGB8dHY@OX9Ubyl8@OFc8Dy/6CXwUxtbyntOCu4ku2t3szZMNuXlZsL@rtk9W6sKfticQPH3O0Ukz7NL26MtntaUTxa40hY1J5/oeduxm0Wja3cfbeLf7DQ "Wolfram Language (Mathematica) – Try It Online")
Not really optimized. Takes less than 1 seconds on my computer to calculate the first four terms, but takes forever for the fifth term. It seems that Mathematica cannot compute the chromatic polynomial of `HypercubeGraph[5]` in a reasonable time.
Based on Peter Kagey's deleted answer (which did not consider rotations and reflections), and uses Burnside's lemma.
] |
[Question]
[
Related: [Program my microwave oven](https://codegolf.stackexchange.com/q/8791/43319) and [Generate lazy values](https://codegolf.stackexchange.com/q/73916/43319).
My colleague is so lazy that he doesn't even bother to move his finger when programming the microwave oven. (This is actually true!)
Help him find the microwave input that gives the time closest to what he wants, but where all digits are the same. If two inputs result in the same time difference from the desired time, choose the one with fewer digits. If both have the same number of digits, choose the lesser – so he doesn't have to wait so long.
Input is the integer that a perfectionist would enter, e.g. `430` is 4 minutes and 30 seconds while `100` and `60` each is 1 minute. It will be greater than 0 and will not exceed 9999.
Output must an integer, e.g. `444` is 4 minutes and 44 seconds and `55` is 55 seconds.
Both input and output may only be in simple seconds (no minutes) if the total time is below 1 minute and 40 seconds.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so your code must be as short as possible.
## Test cases:
```
30 → 33
60 → 55
70 → 111
90 → 88
100 → 55
101 → 66
120 → 77
130 → 88
200 → 99
201 → 222
500 → 444
700 → 666
1000 → 888
1055 → 999
1056 → 1111
1090 → 1111
```
[Answer]
# Jelly, 26 bytes
```
bȷ2ḅ60
³ÇạÇ,
9Rẋ€4R¤ḌFÇ€ṂṪ
```
Explanation:
```
bȷ2ḅ60 f(x) = x tobase 100 frombase 60
³ÇạÇ, g(x) = (abs(f(arg) - f(x)), x)
9Rẋ€4R¤ main(arg) = [1..9] repeat each with [1..4],
ḌF then get digits and flatten,
Ç€ then map g,
Ṃ then minimum,
Ṫ then last element.
```
[Try it online!](http://jelly.tryitonline.net/#code=Ysi3MuG4hTYwCsKzw4fhuqHDhywKOVLhuovigqw0UsKk4biMRsOH4oKs4bmC4bmq&input=&args=NzA)
[Answer]
## JavaScript (ES6), 112 bytes
```
n=>{c=n=>n*3+n%100*2;d=n=c(n);for(r=i=0;i<1e4;i++)/^(.)\1*$/.test(i)&(m=c(i)-n,m<0?m=-m:m)<d&&(d=m,r=i);return r}
```
Uses a helper function `c` which calculates five times the actual number of elapsed seconds.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 37 bytes
```
{⍵⊃⍨⊃⍋⊃|-/(60⊥0 100∘⊤)¨⎕⍵}⍎¨,⎕D∘./⍨⍳4
```
`⍳4` 1 2 3 4
`⎕D` "0123456789"
`∘./⍨` repetition table (like a multiplication table, but where each cell contains B repetitions of A instead of A×B)
`,` make table into list of strings
`⍎¨` make each string into number (Now we have a list off all possible results.)
`{`…`}` function where the argument is represented by `⍵`
`⎕⍵` precede argument with prompted input
`(`…`)¨` apply to each of the two (the argument and the list)...
`0 100∘⊤` convert to base-100
`60⊥` convert from base-60
`-/` calculate the difference between the two
`|` absolute value
`⊃` extract list (because `-/` encapsulated its result)
`⍋` sort order (Does not sort, only returns the order in which to place the arguments to achieve ascending order. If two elements are equal, they stay in current order. Since our list has elements of increasing length, this takes care of ties.)
`⊃` the first one, i.e. the one with smallest absolute difference from the input
`⍵⊃⍨` take that element from the argument list (the list of possible results)
Thanks to the colleague in question for shaving off one byte.
---
Note: I did not have any solution at the time of posting the OP.
] |
[Question]
[
## Background
Imagine for a moment that you have a mind-numbingly boring job.
Every morning, you are given a collection of tasks that you should work on that day.
Each task has a certain duration, and once started, it must be completed in one go.
Your boss will not tolerate idling, so if there are tasks that you could still complete before going home, you must work on one of them (you can choose which one).
Conversely, if all remaining tasks would require you to work overtime, you get to go home early!
Thus your goal is to minimize the length of your workday by clever scheduling.
Fun fact: this is one variant of the *lazy bureaucrat scheduling problem*, and it is NP-hard ([source](http://link.springer.com/article/10.1007%2Fs10878-007-9076-2)).
## Input
You have two inputs: the number of "time units" in your workday (a positive integer `L`), and the collection of tasks (a non-empty array of positive integers `T`, representing task durations).
They can be taken in any order, and in any reasonable format.
The array `T` may contain tasks with duration more than `L`, but it is guaranteed to contain at least one task with duration at most `L`.
## Output
A *valid schedule* is a subset of tasks `S ⊆ T` such that `sum(S) ≤ L`, and every task not in `S` (counting multiplicities) has duration strictly more than `L - sum(S)`.
Your output shall be the smallest possible sum of a valid schedule.
In other words, you shall output the minimal number of time units you must work today.
## Example
Consider the inputs
```
L = 9
T = [3,4,4,4,2,5]
```
One way of scheduling your day is `[4,4]`: you finish two tasks in 8 time units, and have 1 unit left.
Since no 1-unit tasks are available, you can go home.
However, the schedule `[2,5]` is even better: you work for 7 time units, and then all remaining tasks would take 3 or more time units.
The schedule `[2,4]` is not valid, since after working for 6 time units, you'd still have enough time to finish the 3-unit task.
7 units turns out to be optimal, so the correct output is `7`.
## Rules and scoring
You can write either a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
There is no time bound, so brute forcing is perfectly acceptable.
## Test cases
These are given in the format `L T -> output`.
```
1 [1,2] -> 1
6 [4,1] -> 5
7 [7,7,9] -> 7
9 [3,4,4,4,2,5] -> 7
20 [6,2,3,12,7,31] -> 17
42 [7,7,7,7,8,8,8] -> 36
42 [7,7,7,7,7,8,8,8] -> 35
42 [7,7,7,7,7,7,8,8,8] -> 36
16 [1,2,3,4,5,6,7,8,9,10] -> 13
37 [15,27,4,1,19,16,20,26,29,18] -> 23
22 [24,20,8,8,29,16,5,5,16,18,4,9] -> 18
80 [10,22,11,2,28,20,27,6,24,9,10,6,27,2,15,29,27] -> 71
59 [26,28,5,4,7,23,5,1,9,3,7,15,4,23,7,19,16,25,26] -> 52
```
[Answer]
# Jelly, 20 bytes
```
³œ-;⁴Ṃ;¹S>⁴
ŒPÇÐfS€Ṃ
```
[Try it online!](http://jelly.tryitonline.net/#code=wrPFky074oG04bmCO8K5Uz7igbQKxZJQw4fDkGZT4oKs4bmC&input=&args=WzI0LDIwLDgsOCwyOSwxNiw1LDUsMTYsMTgsNCw5XQ+MjI)
TIO is fast enough to finish the last test cases within its 60 second time limit, even if just barely.
### Background
The algorithm is both simple and inefficient:
1. We generate all subsets of **T**, counting multiplicities.
2. We filter the the subsets, keeping only those those subsets S that satisfy one of the following criteria:
* **S** is different from **T**, and the sum of the elements of **S** and the minimal element *not* in **S** is larger than **L**.
* **S** and **T** are identical.The filtered **T** (let's call it **T'**) now contains all lists of task that do just enough work (or even some overtime).
3. Of all **S** in **T'**, pick the one with the lowest sum.
### How it works
```
ŒPÇÐfS€Ṃ Main link. Left input: T (list). Right input: L (integer).
ŒP Powerset; generate all subsets of T.
Ðf Filter them...
Ç applying the helper link.
S€ Compute the sum of each kept subset.
Ṃ Take the minimum.
³œ-;⁴Ṃ;¹S>⁴ Helper link. Input: A (subset of T)
³œ- Multiset subtraction; remove the elements of A from T, counting
multiplicities.
;⁴ Append L to the resulting list.
Ṃ Take the minimum.
If S == T, the difference was empty and the minimum is L.
;¹ Prepend the minimum to A.
S Compute the sum.
>⁴ Compare it with L.
If S == T, the comparison will return 1.
```
[Answer]
# Pyth, ~~26~~ 25 bytes
```
JEhSsMf&gJsT>hS.-QT-JsTyQ
```
[Try it online.](http://pyth.herokuapp.com/?code=JEhSsMf%26gJsT%3EhS.-QT-JsTyQ&input=%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%5D%0A16&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=JEhSsMf%26gJsT%3EhS.-QT-JsTyQ&test_suite_input=%5B1%2C2%5D%0A1%0A%5B4%2C1%5D%0A6%0A%5B7%2C7%2C9%5D%0A7%0A%5B3%2C4%2C4%2C4%2C2%2C5%5D%0A9%0A%5B6%2C2%2C3%2C12%2C7%2C31%5D%0A20%0A%5B7%2C7%2C7%2C7%2C8%2C8%2C8%5D%0A42%0A%5B7%2C7%2C7%2C7%2C7%2C8%2C8%2C8%5D%0A42%0A%5B7%2C7%2C7%2C7%2C7%2C7%2C8%2C8%2C8%5D%0A42%0A%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%5D%0A16%0A%5B15%2C27%2C4%2C1%2C19%2C16%2C20%2C26%2C29%2C18%5D%0A37%0A%5B24%2C20%2C8%2C8%2C29%2C16%2C5%2C5%2C16%2C18%2C4%2C9%5D%0A22%0A%5B10%2C22%2C11%2C2%2C28%2C20%2C27%2C6%2C24%2C9%2C10%2C6%2C27%2C2%2C15%2C29%2C27%5Dh%0A80%0A%5B26%2C28%2C5%2C4%2C7%2C23%2C5%2C1%2C9%2C3%2C7%2C15%2C4%2C23%2C7%2C19%2C16%2C25%2C26%5Dh%0A59&debug=0&input_size=2)
I haven't been able to run the last two test cases (they time out online, I assume), but all the others work. This is just a basic brute force solution.
[Answer]
# Ruby, 124 bytes
```
->(m,s){
f=proc{|l,t|t.reject!{|x|x>l}
(0...(t.size)).map{|x|
f.call(l-t[x],t[0,x]+t[(x+1)..-1])
}.max||l
}
m-f.call(m,s)
}
```
This is a brute-force solution.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 36 bytes
```
iTFinZ^!"2G@2#)sXKt1G>~wb+lG>A*?KhX<
```
[**Try it online!**](http://matl.tryitonline.net/#code=aVRGaW5aXiEiMkdAMiMpc1hLdDFHPkF-d2IrbEc-Kj9LaFg8&input=NDIKWzcsNyw3LDcsNyw3LDgsOCw4XQ)
```
i % input number L
TF % array [true, false]
in % input array T. Get its length
Z^! % Cartesian power and transpose. Each column is a selection from T
" % for each selection
2G@2#) % take non-selected and then selected tasks
sXK % sum of selected tasks. Copy to clipboard K
t1G>~ % duplicate. Is sum of selected tasks <= L?
wb % swap, rotate
+ % sum of selected tasks plus each non-selected task
lG>A % are all of those numbers greater than L?
* % are both conditions met?
? % if so
Kh % paste current minimum (or initially L), append new value
X< % compute new minimum
% end if implicitly
% end for each implicitly
% display stack implicitly
```
] |
[Question]
[
Your challenge is extremely simple. Given a year as input, print all the months in that year that will contain a [Friday the 13th](https://en.wikipedia.org/wiki/Friday_the_13th) according to the Gregorian calendar. Note that even though the Gregorian Calendar wasn't introduced until 1582, for simplicity's sake we will pretend that it has been in use since 0001 AD.
# Rules
* Full programs or functions are allowed.
* You can take input as function arguments, from STDIN, or as command line arguments.
* You are not allowed to use any date and time builtins.
* You can safely assume that the input will be a valid year. If the input is smaller than 1, not a valid integer, or larger than your languages native number type, you do not have to handle this, and you get undefined behaviour.
* Output can be numbers, in English, or in any other human readable format, so long as you specify the standard.
* Make sure you account for leap-years. And remember, [leap-years do not happen every 4 years!](http://infiniteundo.com/post/25509354022/more-falsehoods-programmers-believe-about-time)
# Tips
Since there are so many different ways to go about this, I don't want to tell you how to do it. However, it might be confusing where to start, so here are a couple different reliable ways of determining the day of the week from a date.
* [Conway's doomsday-algorithm](http://www.timeanddate.com/date/doomsday-weekday.html)
* Pick a start date with a known day of the week, such as [Monday, January 1st, 0001](http://www.timeanddate.com/calendar/?year=1&country=22) and find how far apart the two days are, and take that number mod 7.
* [Gauss's Algorithm](https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Gauss.27s_algorithm)
* [A variation on Gauss's Algorithm](https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Kraitchik.27s_variation)
* [Any of these methods](http://www.wikihow.com/Calculate-the-Day-of-the-Week)
# Sample IO
```
2016 --> May
0001 --> 4, 7
1997 --> Jun
1337 --> 09, 12
123456789 --> January, October
```
As usual, this is code-golf, so standard-loopholes apply, and shortest answer wins.
```
var QUESTION_ID=69510,OVERRIDE_USER=31716;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Python 2, ~~157~~ ~~144~~ 136 Bytes
My solution uses the Gauss-Algorithm. Input is the year as Integer. Output is the list of months with a friday 13th as numbers (1-12).
Probably some more golfing possible, but its getting late... Gonna edit this one tomorrow und get this down a bit more. Suggestions are always welcome in the meantime!
```
def f(i):y=lambda m:(i-1,i)[m>2];print[m for m in range(1,13)if(13+int(2.6*((m-2)%12,12)[m==2]-.2)+y(m)%4*5+y(m)%100*4+y(m)%400*6)%7==5]
```
**edit:** Got it down to 144 by replacing the for-loop with a list comprehesion und making some other small adjustments.
**edit2:** Golfed it down to 136 with the suggestions from Morgan Thrapp and fixed the bug he discovered. Thanks a lot! :)
[Answer]
# C - ~~164~~ ~~153~~ 112 bytes
I found a nice little solution using a heavily modified version of Schwerdtfeger's method. It encodes the necessary table in an integer using base 7, modified to fit in a signed 32-bit word. It outputs the month as an ASCII-character, with January encoded as `1`, February as `2` and so on, with October encoded as `:`, November encoded as `;` and December encoded as `<`.
```
t=1496603958,m;main(y){for(scanf("%d",&y),y--;(y%100+y%100/4+y/100%4*5+t+5)%7||putchar(m+49),t;t/=7)2-++m||y++;}
```
Here it is slightly ungolfed:
```
t=1496603958,m;
main(y){
for(
scanf("%d",&y),y--;
(y%100+y%100/4+y/100%4*5+t+5)%7||putchar(m+49),t;
t/=7
)
2-++m||y++;
}
```
I am sure there are a few ways to make it even smaller, but I think the algorithm, or a slight variation thereof, is nearly ideal for finding the months where Friday the 13th occurs (with respect to code size). Notes:
1. If a 64-bit word could have been used it would be possible to get rid of an annoying addition (`+5`).
2. The variable `m` isn't actually necessary, since the month we are looking at is deducible from `t`.
I leave my older answer below, seeing as it uses a completely different method not seen in other answers here.
---
This is based on a solution to a related problem (<https://codegolf.stackexchange.com/a/22531/7682>).
```
Y,M,D,d;main(y){for(scanf("%d",&y);Y<=y;++D>28+(M^2?M+(M>7)&1^2:!(Y&3)&&(Y%25||!(Y&15)))&&(D=1,M=M%12+1)<2&&Y++)(d=++d%7)^1||D^13||y^Y||printf("%d,",M);}
```
It basically simulates the Gregorian calendar, advancing one day at a time, printing the month when it is a Friday and the 13th. Here it is in a slightly more readable form:
```
Y,M,D,d;
main(y){
for(
scanf("%d",&y);
Y<=y;
++D>28+(
M^2
?M+(M>7)&1^2
:!(Y&3)&&(Y%25||!(Y&15))
)&&(
D=1,
M=M%12+1
)<2&&Y++
)
(d=++d%7)^1||D^13||y^Y||
printf("%d,",M);
}
```
[Answer]
# Pyth, 73 Bytes
```
L?>b2QtQfq%+++13+/-*2.6?qT2 12%-T2 12 .2 1*5%yT4*4%yT100*6%yT400 7 5r1 13
```
[Try it online!](http://pyth.herokuapp.com/?code=L%3F%3Eb2QtQfq%25%2B%2B%2B13%2B%2F-*2.6%3FqT2%2012%25-T2%2012%20.2%201*5%25yT4*4%25yT100*6%25yT400%207%205r1%2013&input=1997&test_suite=1&test_suite_input=2016%0A1%0A1997%0A1337%0A123456789&debug=0)
Using the Gauss-Algorithm, like in my Python answer. ~55 bytes of the code are for the weekday calculation, so choosing a better algorithm could get this down by a lot I suppose...but hey, at least its working now! :)
[Answer]
# Perl - ~~141~~ ~~107~~ 103 bytes
```
$y=<>-1;map{$y++if++$i==3;print"$i "if($y+int($y/4)-int($y/100)+int($y/400))%7==$_}'634163152042'=~/./g
```
This uses a modified version of the formula for the [Julian day](https://en.wikipedia.org/wiki/Julian_day#Calculation) to calculate the day of the week of March 13th, then uses the number of days of the week each month is offset from January to find the day of the week for the rest of the months, starting with the last 2 months of the previous year beginning in March then the first 10 months of the current year (to avoid calculating leap years twice).
[Answer]
# Excel, 137 bytes
Takes input year in A1. Output is non-separated list of Hexidecimal. (January = 0, December = B)
Uses Gauss's Algorithm for January and August.
```
=CHOOSE(MOD(6+5*MOD(A1-1,4)+4*MOD(A1-1,400),7)+1,"","",1,"","",0,"")&CHOOSE(MOD(5*MOD(A1-1,4)+4*MOD(A1-1,400),7)+1,9,35,"8B",5,"2A",7,4)
```
[Answer]
**C, ~~276~~ 219 bytes**
```
#define R return
#define L(i) for(;i-->0;)
u(y,m){R m-1?30+((2773>>m)&1):28+(y%4==0&&y%100||y%400==0);}s(y,m,g){g+=4;L(m)g+=u(y,m),g%=7;L(y)g+=1+u(y,1),g%=7;R g;}z(y,m,r){m=12;L(m)s(y,m,13)-4||(r|=1<<(m+1));R r;}
```
input from stdin output in stdout try to <http://ideone.com/XtuhGj> [the debug function is z]
```
w(y,m,r){m=12;L(m)s(y,m,u(y,m))||(r|=1<<(m+1));R r;}
/*
// ritorna il numero dei giorni di anno=y mese=m con mese in 0..11
// m==1 significa febbraio y%4?0:y%100?1:!(y%400) non funziona
u(y,m){R m-1?30+((2773>>m)&1):28+(y%4==0&&y%100||y%400==0);}
// argomenti anno:y[0..0xFFFFFFF] mese:m[0..11] giorno:g[1..u(y,m)]
// ritorna il numero del giorno[0..6]
s(y,m,g)
{g+=4; // correzione per il giorno di partenza anno mese giorno = 0,1,1
L(m)g+= u(y,m),g%=7; // m:0..m-1 somma mod 7 i giorni del mese dell'anno y
L(y)g+=1+u(y,1),g%=7; // y:0..y-1 somma mod 7 gli anni da 0..y-1
// g+=1+u(y,1) poiche' (365-28)%7=1 e 1 e' febbraio
R g;
}
// argomenti anno:y[0..0xFFFFFFF], m=0 r=0
// calcola tutti gli ultimi giorni del mese dell'anno y che cadono di lunedi'
// e mette tali mesi come bit, dal bit 1 al bit 12 [il bit 0 sempre 0] in r
w(y,m,r){m=12;L(m)s(y,m,u(y,m))||(r|=1<<(m+1));R r;}
// argomenti anno:y[0..0xFFFFFFF], m=0 r=0
//ritorna in r il numero dei mesi che ha giorno 13 di venerdi[==4]
// e mette tali mesi come bit, dal bit 1 al bit 12 [il bit 0 sempre 0] in r
z(y,m,r){m=12;L(m)s(y,m,13)-4||(r|=1<<(m+1));R r;}
*/
#define P printf
#define W while
#define M main
#define F for
#define U unsigned
#define N int
#define B break
#define I if
#define J(a,b) if(a)goto b
#define G goto
#define P printf
#define D double
#define C unsigned char
#define A getchar()
#define O putchar
#define Y malloc
#define Z free
#define S sizeof
#define T struct
#define E else
#define Q static
#define X continue
M()
{N y,m,g,r,arr[]={1,297,1776,2000,2016,3385}, arr1[]={2016,1,1997,1337,123456789};
C*mese[]={"gen","feb","mar","apr","mag","giu","lug","ago","set","ott","nov","dic"};
C*giorno[]={"Lun","Mar","Mer","Gio","Ven","Sab","Dom"};
P("Inserisci Anno mese giorno>");r=scanf("%d %d %d", &y, &m, &g);
P("Inseriti> %d %d %d r=%d\n", y, m, g, r);
I(r!=3||m>12||m<=0||g>u(y,m-1))R 0;
r=s(y,m-1,g);// 12-> 11 -> 0..10
P("Risultato=%d giorno=%s\n", r, giorno[r]);
r=w(y,0,0);P(" r=%d ", r);P("\n");
F(m=0;m<6;++m)
{P("N anno=%d -->",arr[m]);
r=w(arr[m],0,0); // ritorna in r i mesi tramite i suoi bit...
F(y=1;y<13;++y) I(r&(1<<y))P("%s ",mese[y-1]);
P("\n");
}
F(m=0;m<4;++m)
{P("N anno=%d -->",arr1[m]);
r=z(arr1[m],0,0); // ritorna in r i mesi tramite i suoi bit...
F(y=1;y<13;++y) I(r&(1<<y))P("%s ",mese[y-1]);
P("\n");
}
}
```
] |
[Question]
[
I was intrigued by the design of this graphic from the New York Times, in which each US state is represented by a square in a grid. I wondered whether they placed the squares by hand or actually found an optimal placement of squares (under some definition) to represent the positions of the contiguous states.
[](https://i.stack.imgur.com/EIvdtm.png)
Your code is going to take on a small part of the challenge of optimally placing squares to represent states (or other arbitrary two-dimensional shapes.) Specifically, it's going to assume that we already have all the geographic centers or [centroids](https://en.wikipedia.org/wiki/Centroid) of the shapes in a convenient format, and that the optimal representation of the data in a diagram like this is the one in which the total distance from the centroids of the shapes to the centers of the squares that represent them is minimal, with at most one square in each possible position.
Your code will take a list of unique pairs of floating-point X and Y coordinates from 0.0 to 100.0 (inclusive) in any convenient format, and will output the non-negative integer coordinates of unit squares in a grid optimally placed to represent the data, preserving order. In cases where multiple arrangements of squares are optimal, you can output any of the optimal arrangements. Between 1 and 100 pairs of coordinates will be given.
This is code golf, shortest code wins.
**Examples:**
Input: `[(0.0, 0.0), (1.0, 1.0), (0.0, 1.0), (1.0, 0.0)]`
This is an easy one. The centers of the squares in our grid are at 0.0, 1.0, 2.0, etc. so these shapes are already perfectly placed at the centers of squares in this pattern:
```
21
03
```
So your output should be exactly these coordinates, but as integers, in a format of your choice:
```
[(0, 0), (1, 1), (0, 1), (1, 0)]
```
Input: `[(2.0, 2.1), (2.0, 2.2), (2.1, 2.0), (2.0, 1.9), (1.9, 2.0)]`
In this case all the shapes are close to the center of the square at (2, 2), but we need to push them away because two squares cannot be in the same position. Minimizing the distance from a shape's centroid to the center of the square that represents it gives us this pattern:
```
1
402
3
```
So your output should be `[(2, 2), (2, 3), (3, 2), (2, 1), (1, 2)]`.
**Test cases:**
```
[(0.0, 0.0), (1.0, 1.0), (0.0, 1.0), (1.0, 0.0)] -> [(0, 0), (1, 1), (0, 1), (1, 0)]
[(2.0, 2.1), (2.0, 2.2), (2.1, 2.0), (2.0, 1.9), (1.9, 2.0)] -> [(2, 2), (2, 3), (3, 2), (2, 1), (1, 2)]
[(94.838, 63.634), (97.533, 1.047), (71.954, 18.17), (74.493, 30.886), (19.453, 20.396), (54.752, 56.791), (79.753, 68.383), (15.794, 25.801), (81.689, 95.885), (27.528, 71.253)] -> [(95, 64), (98, 1), (72, 18), (74, 31), (19, 20), (55, 57), (80, 68), (16, 26), (82, 96), (28, 71)]
[(0.0, 0.0), (0.1, 0.0), (0.2, 0.0), (0.0, 0.1), (0.1, 0.1), (0.2, 0.1), (0.0, 0.2), (0.1, 0.2), (0.2, 0.2)] -> [(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1), (0, 2), (1, 2), (2, 2)]
[(1.0, 0.0), (1.0, 0.1), (1.0, 0.2), (1.0, 0.3)] -> [(1, 0), (0, 0), (2, 0), (1, 1)] or [(1, 0), (2, 0), (0, 0), (1, 1)]
[(3.75, 3.75), (4.25, 4.25)] -> [(3, 4), (4, 4)] or [(4, 3), (4, 4)] or [(4, 4), (4, 5)] or [(4, 4), (5, 4)]
```
Total distance from the centroids of shapes to the centers of the squares that represent them in each case (please let me know if you spot any errors!):
```
0.0
3.6
4.087011
13.243299
2.724791
1.144123
```
**Just for fun:**
Here's a representation of the geographic centers of the contiguous United States in our input format, at roughly the scale the Times used:
```
[(15.2284, 3.1114), (5.3367, 3.7096), (13.0228, 3.9575), (2.2198, 4.8797), (7.7802, 5.5992), (20.9091, 6.6488), (19.798, 5.5958), (19.1941, 5.564), (17.023, 1.4513), (16.6233, 3.0576), (4.1566, 7.7415), (14.3214, 6.0164), (15.4873, 5.9575), (12.6016, 6.8301), (10.648, 5.398), (15.8792, 5.0144), (13.2019, 2.4276), (22.3025, 8.1481), (19.2836, 5.622), (21.2767, 6.9038), (15.8354, 7.7384), (12.2782, 8.5124), (14.1328, 3.094), (13.0172, 5.3427), (6.142, 8.8211), (10.0813, 6.6157), (3.3493, 5.7322), (21.3673, 7.4722), (20.1307, 6.0763), (7.5549, 3.7626), (19.7895, 7.1817), (18.2458, 4.2232), (9.813, 8.98), (16.8825, 6.1145), (11.0023, 4.2364), (1.7753, 7.5734), (18.8806, 6.3514), (21.3775, 6.6705), (17.6417, 3.5668), (9.9087, 7.7778), (15.4598, 4.3442), (10.2685, 2.5916), (5.3326, 5.7223), (20.9335, 7.6275), (18.4588, 5.0092), (1.8198, 8.9529), (17.7508, 5.4564), (14.0024, 7.8497), (6.9789, 7.1984)]
```
To get these, I took the coordinates from the second list on [this page](https://en.wikipedia.org/wiki/Geographic_centers_of_the_United_States) and used `0.4 * (125.0 - longitude)` for our X coordinate and `0.4 * (latitude - 25.0)` for our Y coordinate. Here's what that looks like plotted:
[](https://i.stack.imgur.com/p9UlR.png)
The first person to use the output from their code with the above coordinates as input to create a diagram with actual squares gets a pat on the back!
[Answer]
# Mathematica, 473 bytes
```
f@p_:=(s=Flatten@Round@p;v=Array[{x@#,y@#}&,n=Length@p];
Do[w=Flatten[{g@#,h@#}&/@(b=Flatten@Position[p,x_/;Norm[x-p[[i]]]<=2,{1}])];f=Total[Norm/@(p-v)]+Total[If[#1==#2,1*^4,0]&@@@v~Subsets~{2}]/.Flatten[{x@#->g@#,y@#->h@#}&@@@w]/.Thread[Flatten@v->s];
c=w∈Integers&&And@@MapThread[Max[#-2,0]<=#2<=Min[#+2,100]&,{Flatten@p[[b]],w}];s=Flatten@ReplacePart[s~Partition~2,Thread[b->Partition[w/.Last@Quiet@NMinimize[{f,c},w,MaxIterations->300],2]]]
,{i,n}]~Do~{2};s~Partition~2)
```
---
Before golfing:
```
f[p_]:=(n=Length@p;s=Flatten@Round@p;v=Array[{x[#],y[#]}&,n];
Do[
v2=Flatten[{x2[#],y2[#]}&/@(b=Flatten@Position[p,x_/;Norm[x-p[[i]]]<=2,{1}])];
f2=Total[Norm/@(p-v)]+Total[If[#1==#2,1*^4,0]&@@@Subsets[v,{2}]]/.Flatten[{x[#]->x2[#],y[#]->y2[#]}&@@@v2]/.Thread[Flatten@v->s];
c2=v2∈Integers&&And@@MapThread[Max[#-2,0]<=#2<=Min[#+2,100]&,{Flatten@p[[b]],v2}];
s=Flatten@ReplacePart[s~Partition~2,Thread[b->Partition[v2/.Last@Quiet@NMinimize[{f2,c2},v2,MaxIterations->300],2]]];
,{i,n}]~Do~{2};
s~Partition~2)
```
---
**Explanation**:
This optimization problem is not difficult to describe in Mathematica. Given a list of points `p` of length `n`,
* the variables are `x[i]` and `y[i]`: `v=Array[{x[#],y[#]}&,n]`,
* the function to minimize is the total of displacements: `f=Total[Norm/@(p-v)]`,
* the constraints are: `c=Flatten[v]∈Integers&&And@@(Or@@Thread[#1!=#2]&@@@Subsets[v,{2}])`.
And, `NMinimize[{f,cons},v,MaxIterations->Infinity]` will give the result. But unfortunately, such straight forward scheme seems too complicated to converge.
To work around the problem of complexity, two techniques are adopted:
* a large "interaction", `If[#1==#2,1*^4,0]&`, is used to avoid collision between points.
* instead of optimize all variable at the same time, we optimize on every point with their neighbors in turn.
We start from an initial guess by rounding the points. When the optimizations are done one by one, collisions are expected to be resolved, and an optimized arrangement is established.
The final solution is at least good, if not optimal. (I believe `:P`)
---
**Result**:
The result of **Just for fun** is shown below. Dark green points are the inputs, gray squares are the outputs, and black lines shows the displacements.
[](https://i.stack.imgur.com/u7K6G.png)
The sum of displacements is **19.4595**. And the solution is
```
{{15,3},{5,4},{13,4},{2,5},{8,6},{21,6},{20,5},{19,5},{17,1},{17,3},{4,8},{14,6},{15,6},{13,7},{11,5},{16,5},{13,2},{22,8},{19,6},{21,7},{16,8},{12,9},{14,3},{13,5},{6,9},{10,7},{3,6},{22,7},{20,6},{8,4},{20,7},{18,4},{10,9},{17,6},{11,4},{2,8},{19,7},{22,6},{18,3},{10,8},{15,4},{10,3},{5,6},{21,8},{18,5},{2,9},{18,6},{14,8},{7,7}}
```
[Answer]
## Python 3, 877 bytes
This is **not** a correct implementation. It fails on the second of the "further test cases", producing a solution with a total distance of 13.5325, where the solution provided needs only 13.2433. Further complicating matters is the fact that my golfed implementation doesn't match the ungolfed one I wrote first...
However, nobody else has answered, and this is too interesting a challenge to let slip past. Also, I have a picture generated from the USA data, so there's that.
The algorithm is something like this:
1. Push all points to the nearest integer coordinates (hereafter called a "square").
2. Find the square with the greatest number of points.
3. Find the lowest-cost redistribution of those points to the nine-square neighbourhood of this one, excluding any squares that have already been processed in step 2.
* The redistribution is limited to one point per square, unless that wouldn't provide enough squares (although even then, only one point will remain on *this* square).
4. Repeat from step 2 until no square has more than one point.
5. Locate each of the original points, in order, and output their squares, in order.
I have absolutely no proof of optimality for any part of this algorithm, just a strong suspicion that it'll provide "pretty good" results. I think that's what we called a "heuristic algorithm" back in my uni days...!
```
l=len
I,G,M=-1,101,150
d=lambda x,y,X,Y:abs(x-X+1j*(y-Y))
N=(0,0),(I,0),(0,I),(1,0),(0,1),(I,I),(1,I),(1,1),(I,I)
n=lambda p,e:[(x,y)for(x,y)in(map(sum,zip(*i))for i in zip([p]*9,N))if(x,y)not in e and I<x<G and I<y<G]
def f(p):
g={};F=[];O=[I]*l(p)
for P in p:
z=*map(round,P),
if z in g:g[z]+=[P]
else:g[z]=[P]
while l(g)<l(p):
L,*P=0,
for G in g:
if l(g[G])>l(P):L,P=G,g[G]
o=n(L,F);h=l(o)<l(P);c=[[d(*q,*r)for r in o]for q in P];r={}
while l(r)<l(c):
A=B=C=M;R=S=0
while R<l(c):
if R not in r:
z=min(c[R])
if z<A:B,A=R,z;C=c[R].index(A)
R+=1
while S<l(c):
if S==B:
v=0
while v<l(c[S]):
if v!=C:c[S][v]=M
v+=1
elif C<1or not h:c[S][C]=M
S+=1
r[B]=C
for q in r:
x,y=P[q],o[r[q]]
if y==L or y not in g:g[y]=[x]
else:g[y]+=[x]
F+=[L]
for G in g:
O[p.index(g[G][0])]=G
return O
```
And the result of running it on the USA data (thanks to a utility function that turns the results into SVG):
[](https://i.stack.imgur.com/wSkX0.png)
This is slightly worse than the one the ungolfed code produced; the only visible difference is that the top-rightmost square is one further to the left in the better one.
[Answer]
# MATLAB, ~~316 343~~ 326 bytes
This one is a work in progress - it's not fast, but it is short. It seems to pass most of the test cases. Currently the one just for fun input of the map is running, but it is still going after 10 minutes, so...
```
function p=s(a)
c=ceil(a');a=a(:,1)+j*a(:,2);[~,p]=r(a,c,[],Inf);p=[real(p),imag(p)];end
function [o,p]=r(a,c,p,o)
if ~numel(c)
o=sum(abs(p-a));else
x=c(1)+(-1:1);y=c(2)+(-1:1);P=p;
for X=1:3
for Y=1:3
Q=x(X)+j*y(Y);if(x(X)>=0)&(y(Y)>=0)&all(Q~=P)
[O,Q]=r(a,c(:,2:end),[P;Q],o);
if(O<o) o=O;p=Q;disp(o);end
end;end;end;end;end
```
And in a somewhat more readable format:
```
function p=squaremap(a)
%Input format: [2.0, 2.1;2.0, 2.2;2.1, 2.0;2.0, 1.9;1.9, 2.0]
c=ceil(a'); %Convert each point to the next highest integer centre
a=a(:,1)+j*a(:,2); %Convert each 2D point into a complex number
[~,p]=r(a,c,[],Inf); %Recurse!
p=[real(p),imag(p)];
end
function [o,p]=r(a,c,p,o)
if ~numel(c) %If we are as deep as we can go
o=sum(abs(p-a)); %See what our overall distance is
else
x=c(1)+(-1:1);y=c(2)+(-1:1); %For each point we try 9 points, essentially a 3x3 square
P=p;
for X=1:3;
for Y=1:3
%For each point
Q=x(X)+j*y(Y); %Covert to a complex number
if(x(X)>=0)&(y(Y)>=0)&all(Q~=P) %If the point is not negative and has not already been used this iteration
[O,Q]=r(a,c(:,2:end),[P;Q],o); %Otherwise iterate further
if(O<o) o=O;p=Q;end %Keep updating the smallest path and list of points we have found
end
end
end
end
end
```
The input format is expected to be a MATLAB array, such as:
```
[2.0, 2.1;2.0, 2.2;2.1, 2.0;2.0, 1.9;1.9, 2.0]
```
Which is pretty close to the format in the question, which allows some leeway.
The output is in the same format as the input, an array where any given index corresponds to the same point in both the input and output.
---
Hmm, 8 hours and still running on the map one... this solution is guaranteed to find the most optimal, but it does it via brute force, so takes a very long time.
I've come up with another solution which is much faster, but like the other answer fails to find the most optimal in one of the test cases. Interestingly the map I get for my other solution (not posted) is shown below. It achieves an total distance of 20.72.
[](https://i.stack.imgur.com/IQDDo.png)
] |
[Question]
[
# Introduction
You are a biologist studying the movement patterns of bacteria.
Your research team has a bunch of them in a petri dish, and you are recording their activity.
Unfortunately, you are seriously underfunded, and can't afford a video camera, so you just take a picture of the dish at regular intervals.
Your task is to make a program that traces the movements of the germs from these pictures.
# Input
Your inputs are two 2D arrays of characters in any reasonable format, representing consecutive pictures of the petri dish.
In both arrays, the character `.` represents empty space, and `O` represents a germ (you can choose any two distinct characters if you want).
Also, the "after" array is obtained from the "before" array by moving some germs one step in one of the four cardinal directions; in particular, the arrays have the same shape.
The germs move simultaneously, so one of them may move to a space that already contained another germ, if it moves out of the way.
It is guaranteed that the borders of the "before" array contain only empty spaces, and that there is at least one germ.
Thus, the following is a valid pair of inputs:
```
Before After
...... ......
.O..O. ....O.
.OO.O. .OO.O.
...... ..O...
```
# Output
Your output is a single 2D array of characters in the same format as the inputs.
It is obtained from the "before" array by replacing those germs that have moved with one of `>^<v`, depending on the direction of movement (you can also use any 4 distinct characters here).
There may be several possible outputs, but you shall give only one of them.
In the above example, one possible correct output is
```
......
.v..O.
.>v.O.
......
```
Unnecessary movement is allowed in the output and germs can swap places, so the following is also valid:
```
......
.v..v.
.>v.^.
......
```
# Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
I'm interested in relatively efficient algorithms, but I don't want to ban brute forcing entirely.
For this reason, there's a **bonus of -75%** for solving the last test case within 10 minutes on a modern CPU (I'm unable to test most solutions, so I'll just trust you here). **Disclaimer:** I know that a fast algorithm exists (search for "disjoint paths problem"), but I haven't implemented it myself.
# Additional test cases
```
Before
......
.O..O.
..OO..
......
After
......
..O...
...OO.
..O...
Possible output
......
.>..v.
..vO..
......
Before
.......
.OOOOO.
.O..OO.
.OO..O.
.OOOOO.
.......
After
.......
..OOOOO
.O...O.
.O...O.
.OOOOOO
....O..
Possible output
.......
.>>>>>.
.O..>v.
.Ov..v.
.O>>v>.
.......
Before
..........
.OOO..OOO.
.OOOOOOOO.
.OOO..OOO.
..........
After
..O.......
.OOO..O.O.
..OOOOOOOO
.O.O..OOO.
.......O..
Possible output
..........
.>^O..O>v.
.^O>>>vO>.
.O>^..>vO.
..........
Before
............
.OO..OOOOOO.
.OO......OO.
...OOOOOO...
.O.OOOOOO.O.
...OOOOOO...
.OOOOOOOOOO.
............
After
..........O.
.OO..OOOOO..
.O...O...O..
.O.OOOOOOO..
.O.OOOOOO..O
...OO..OO...
....OOOOOOOO
.OOO........
Possible output
............
.OO..v<<<<^.
.v<......^<.
...OOO>>>...
.O.OOO^OO.>.
...OOv^OO...
.vvvO>>>>>>.
............
Before
................
.OOOOOO.OOOOOOO.
..OO..OOOOOOOOO.
.OOO..OOOO..OOO.
..OOOOOOOO..OOO.
.OOOOOOOOOOOOOO.
................
After
................
..OOOOO.OOOOOOOO
..OO..OOOOOOOOO.
..OO..OOOO..OOOO
..OOOOOOOO..OOO.
..OOOOOOOOOOOOOO
................
Possible output
................
.>>>>>v.>>>>>>>.
..OO..>>^>>>>>v.
.>>v..OOO^..OO>.
..O>>>>>>^..OOO.
.>>>>>>>>>>>>>>.
................
Before
..............................
.OOO.O.O.....O.....O.O.O..O...
..OOO.O...O..OO..O..O.O.......
.....O......O..O.....O....O...
.O.OOOOO......O...O..O....O...
.OO..O..OO.O..OO..O..O....O...
..O.O.O......OO.OO..O..OO.....
..O....O..O.OO...OOO.OOO...O..
.....O..OO......O..O...OO.OO..
........O..O........OO.O.O....
..O.....OO.....OO.OO.......O..
.O.....O.O..OO.OO....O......O.
..O..OOOO..O....OO..........O.
.O..O...O.O....O..O....O...OO.
....O...OO..O.......O.O..OO...
........O.O....O.O....O.......
.OO.......O.OO..O.......O..O..
....O....O.O.O...OOO..O.O.OO..
.OO..OO...O.O.O.O.O...OO...O..
..............................
After
..............................
.OOOOO.......OO.....O..O......
...OO..O...O...O....OO....O...
....O.O......O..OO...OO...O...
.OO.OOOO......OO..O..O........
O.O.OO..O..O..O..OO...O...OO..
.OO.....O....OO.O..O.OO.O.....
......O.....O.....OOO.OO...O..
....O..OOOO..O..O..O.O.O.OO...
..O......O.O........O...O.O...
.O.....OOO.....OO.OO...O...O..
.......OOO..O.O.O...........O.
.O...O.....O...OOOO..O.O....O.
.O..O.O..O.....O......O....OO.
....O..O..O.O......O.....O....
........OOO....O......O..O....
.OO......O..OO..OOO.....O..O..
..O.O....OO..O...OO...O...OO..
.O..OO....O..O...O.O.O.OO.....
..............O............O..
Possible output
..............................
.OOO.O.v.....>.....>.v.O..v...
..>>^.v...>..^>..v..O.v.......
.....<......>..>.....O....O...
.O.<O><O......O...O..O....v...
.<O..O..v<.O..O^..O..>....>...
..<.^.v......OO.O^..>..<O.....
..^....v..v.Ov...>>^.<OO...O..
.....<..OO......O..O...Ov.v<..
........>..O........O^.v.^....
..^.....Ov.....OO.OO.......O..
.^.....^.^..O>.vO....v......O.
..<..Ov^^..O....><..........O.
.O..O...>.v....O..^....^...OO.
....O...<v..O.......<.^..v<...
........O.O....O.v....O.......
.OO.......<.Ov..O.......O..O..
....O....O.<.^...O^v..O.v.OO..
.O^..<<...O.>.v.>.^...<O...v..
..............................
```
[Answer]
# Octave, ~~494~~ 496 bytes - 372 byte bonus = 124 bytes
```
function o=G(b,a)
y='.O<^v>';s=(b>46)+0;t=a>46;v=t;f=s;t(:,2:end,2)=t(:,1:end-1);t(2:end,:,3)=t(1:end-1,:,1);t(1:end-1,:,4)=t(2:end,:,1);t(:,1:end-1,5)=t(:,2:end,1);t=reshape(t,[],5);m=size(s,1);p=[0 -m -1 1 m];
function z(n)
f(n+p(s(n)))--;q=find(t(n,:));w=n+p(q);d=min(f(w));q=q(f(w)==d);j=randi(numel(q));s(n)=q(j);f(n+p(q(j)))++;end
for g=find(s)' z(g);end
while any((f~=v)(:)) L=find(s);k=zeros(size(s));for h=L' k(h)=f(h+p(s(h)));end;c=find(k>1);g=c(randi(numel(c)));z(g);end
o = y(s+1);end
```
There's still a lot of golfing to be done on this answer, but I wanted to get the ungolfed explanation in.
I saw this as a Constraint Satisfaction Problem, so I went with my favorite local search heuristic, [Min-conflicts](https://en.wikipedia.org/wiki/Min-conflicts_algorithm). The idea is, given a starting placement with each germ in a reachable destination, select a random germ that occupies the same destination cell as one or more other germs and move it to a valid cell that has a minimum of other germs already there. Repeat as necessary until the placement matches the goal.
Interestingly, this algorithm is not guaranteed to terminate (if the goal is unreachable it will continue indefinitely, for instance) but if it does terminate it is guaranteed to produce a valid solution.
Here's the code:
```
function output = germs(before, after)
%before = ['......';'.O..O.';'.OO.O.';'......'];
%after = ['......';'....O.';'.OO.O.';'..O...'];
symbs = '.O<^v>';
start = (before > 46) + 0; %should be called current_board
target = after > 46; %destinations on current cell == O
goal = target;
conflicts = start;
target(:, 2:end,2) = target(:, 1:end-1); %destinations on cell to left
target(2:end, :,3) = target(1:end-1, :,1); %destinations on cell above
target(1:end-1, :,4) = target(2:end, :,1); %destinations on cell below
target(:, 1:end-1,5) = target(:, 2:end,1); %destinations on cell to right
target=reshape(target,[],5);
m = size(start,1); %number of rows = offset to previous/next column
offsets = [0 -m -1 1 m]; %offsets of neighbors from current index
function moveGerm(n)
conflicts(n+offsets(start(n)))--; %take germ off board
move = find(target(n, :)); %get valid moves for this germ
neighbors = n + offsets(move); %valid neighbors = current position + offsets
minVal = min(conflicts(neighbors)); %minimum number of conflicts for valid moves
move = move(conflicts(neighbors)==minVal);
mi = randi(numel(move)); %choose a random move with minimum conflicts
start(n) = move(mi); %add move type to board
conflicts(n + offsets(move(mi)))++; %add a conflict on the cell we move to
end
% Generate an initial placement
for g = find(start)'
moveGerm(g); %make sure all germs are moved to valid cells
end
% Repeat until board matches goal
while any((conflicts ~= goal)(:))
germList = find(start); %list of all our germs
cost = zeros(size(start)); %calculate conflicts for each germ
for h = germList'
cost(h) = conflicts(h + offsets(start(h)));
end
conflicted = find(cost > 1); %find those germs that occupy the same cell as another
g = conflicted(randi(numel(conflicted))); %choose a random germ to move
moveGerm(g);
end
output = symbs(start+1); %use moves as indices into symbol array for output
end
```
Output for the last test case:
```
>> gtest
ans =
..............................
.OO>.O.v.....>.....>.v.O..v...
..>^O.v...>..^>..v..O.v.......
.....v......>..>.....O....O...
.O.<^<OO......>...O..O....v...
.<O..O..v<.O..^<..O..>....>...
..<.^.v......OO.O^..<..<O.....
..^....v..v.Ov...>>>.^OO...O..
.....<..OO......O..O...Ov.<<..
........>..O........O^.v.>....
..^.....OO.....OO.OO.......O..
.^.....^.O..O>.vO....v......O.
..<..Ov^^..O....OO..........O.
.O..O...>.v....O..^....^...OO.
....O...<v..O.......<.^..v<...
........O.O....O.v....O.......
.OO.......<.OO..O.......O..O..
....O....O.<.O...O^<..O.v.OO..
.O^..<<...O.>.v.>.>...<O...v..
..............................
Elapsed time is 0.681691 seconds.
```
The average elapsed time was less than ~~9 seconds~~ 1 second\* on a 5 year old Core i5, qualifying for the bonus.
~~I'm trying to get this working on ideone, but I'm having what I believe to be scoping issues with the way it handles nested functions. (Here's the non-working ideone link for reference: <http://ideone.com/mQSwgZ>)~~
The code on [ideone](http://ideone.com/mQSwgZ) is now working. I had to force all of the variables to global, which was unnecessary running it locally.
\*I had a note in my ungolfed version that one of the steps was inefficient, so I tried it to see if I could speed up execution and for 2 added bytes the execution time is now down to under a second. Code and sample output has been updated and the input on ideone has been changed to the last test case.
[Answer]
# Python, 1171 bytes - 878.25 byte bonus = 292.75 bytes
```
from itertools import *;from random import *;R=range;L=len;O=choice;G='O'
def A(a,b):a.append(b)
def D(y,z):
a=[];b=[];c=[]
for i in R(L(y)):
A(c,[])
for j in R(L(y[0])):
k=[(i,j),y[i][j]==G,z[i][j]==G,[],0];A(c[i],k)
for l,m in [(0,1),(1,0)]:
try:
n=c[i-l][j-m]
if k[2]&n[1]:A(n[3],k)
if k[1]&n[2]:A(k[3],n)
except:pass
if k[1]&~k[2]:A(a,k)
elif k[2]&~k[1]:A(b,k)
d={}
for i in a:
j=[[i]]
while j:
k=j.pop();l=[e[0] for e in k]
while True:
m=k[-1];n=[o for o in m[3] if o[0] not in l]
if not n:
if m in b:A(d.setdefault(i[0],[]),k)
break
for o in n[1:]:p=k[:];A(p,o);A(j,p)
A(k,n[0]);A(l,n[0][0])
e={}
for i in a:e[i[0]]=O(d[i[0]])
def E():return sum(any(k in j for k in i) for i,j in combinations(e.values(),2))
f=E()
for i in count():
t=3**-i/L(a);j=O(a);k=e[j[0]];e[j[0]]=O(d[j[0]]);l=E()
if not l:break
else:
if l>f and random()>t:e[j[0]]=k
else:f=l
for i in e.values():
for j in R(L(i)-1):i[j][4]=i[j+1]
for i in c:
for j in R(L(i)):
k=i[j]
if 1&~k[1]:i[j]='.'
elif not k[4]:i[j]=G
else:l,m=k[0];n,o=k[4][0];i[j]='v>^<'[abs((l-n+1)+2*(m-o))]
return c
```
Ideone link: <http://ideone.com/0Ylmwq>
Takes anywhere from 1 - 8 seconds on the last test case on average, qualifying for the bonus.
This is my first code-golf submission, so it's probably not the best-golfed program out there. Nevertheless, it was an interesting challenge and I quite enjoyed it. @Beaker deserves a mention for reminding me that heuristic-based searches are a thing. Before he posted his solution and inspired me to redo mine, my brute force search was waaaay too long to qualify for the bonus on the last test case (it was on the order of 69! iterations, which is a 99-digit number...).
I didn't want to straight-up copy Beaker's solution, so I decided to use simulated annealing for my search heuristic. It seems slower than min-conflict for this problem (likely because it's an optimization algorithm rather than a constraint-satisfaction one), but it's still well within the 10-minute mark. It also had the benefit of being fairly small, code-wise. I spent a lot more bytes on transforming the problem than I did on finding a solution to it.
## Explanation
My solution is probably fairly inefficient byte-wise, but I had trouble conceptualizing how to solve the problem as-is and so I ended up having to transform it into a different problem that was easier for me to understand. I realized that there are four possiblities for each cell on the grid:
* It had no germ before or after, which means we can ignore it
* It had a germ before but not after, which means we have to find a move for it.
* It had no germ before but one after, which also means we have to find a move for it.
* It had a germ before and after, which means we might have to find a move for it, but then again maybe not.
After decomposing the data into those classes, I was able to further transform the problem. It was immediately obvious to me that I had to find a way to supply a germ from the "before but not after" set to a cell in the "after but not before" set. Further, germs can only move one space, so the only way for them to affect further-away cells is by "pushing" an unbroken path of germs into that cell. That meant the problem became finding X vertex-disjoint paths on a graph, where each cell with a germ was a vertex in said graph, and the edges represented adjacent cells.
I solved that problem that by first building the graph explained above. I then enumerated *every* possible path from each cell in Before and each cell in After, then randomly assigned each cell in Before one of its possible paths. Finally, I used simulated annealing to semi-randomly mutate the potential solution until I eventually find a solution that has no conflicts for any of the paths.
## Annotated version
```
from itertools import *;from random import *;
# redefine some built-in functions to be shorter
R=range;L=len;O=choice;G='O'
def A(a,b):a.append(b)
# The function itself. Input is in the form of two 2d arrays of characters, one each for before and after.
def D(y,z):
# Declare the Before-but-not-after set, the After-but-not-before set, and a temp cell array
# (the cells are temporarily stored in a 2d array because I need to be able to locate neighbors)
a=[];b=[];c=[]
# Build the graph
for i in R(L(y)):
# Append a row to the 2d temp array
A(c,[])
for j in R(L(y[0])):
# Define the interesting information about the cell, then add it to the temp array
# The cell looks like this: [position, does it have a germ before?, does it have a germ after?, list of neighbors with germs, final move]
k=[(i,j),y[i][j]==G,z[i][j]==G,[],0];A(c[i],k)
for l,m in [(0,1),(1,0)]:
# Fill up the neighbors by checking the above and left cell, then mutually assigning edges
try:
n=c[i-l][j-m]
if k[2]&n[1]:A(n[3],k)
if k[1]&n[2]:A(k[3],n)
except:pass
# Decide if it belongs in the Before or After set
if k[1]&~k[2]:A(a,k)
elif k[2]&~k[1]:A(b,k)
# For each cell in the before set, define ALL possible paths from it (this is a big number of paths if the grid is dense with germs)
# This uses a bastard form of depth-first search where different paths can cross each other, but no path will cross itself
d={}
for i in a:
j=[[i]] # Define the initial stack of incomplete paths as the starting node.
while j:
# While the stack is not empty, pop an incomplete path of the stack and finish it
k=j.pop();l=[e[0] for e in k]
while True:
# Set the list of next possible moves to the neighbors of the current cell,
# ignoring any that are already in the current path.
m=k[-1];n=[o for o in m[3] if o[0] not in l]
# If there are no more moves, save the path if it ends in an After cell and break the loop
if not n:
if m in b:A(d.setdefault(i[0],[]),k)
break
# Otherwise, set the next move in this path to be the first move,
# then split off new paths and add them to the stack for every other move
for o in n[1:]:p=k[:];A(p,o);A(j,p)
A(k,n[0]);A(l,n[0][0])
# Perform simulated annealing to calculate the solution
e={}
for i in a:e[i[0]]=O(d[i[0]]) # Randomly assign paths for the first potential solution
# Define a function for calculating the number of conflicts between all paths, then do the initial calculation for the initial potential solution
def E():return sum(any(k in j for k in i) for i,j in combinations(e.values(),2))
f=E()
# Do the annealing
for i in count():
# The "temperature" for simulated annealing is calculated as 3^-i/len(Before set).
# 3 was chosen as an integer approximation of e, and the function e^(-i/len) itself was chosen because
# it exponentially decays, and does so slower for larger problem sets
t=3**-i/L(a)
j=O(a) # Pick a random Before cell to change
k=e[j[0]] # Save it's current path
e[j[0]]=O(d[j[0]]) # Replace the current path with a new one, randomly chosen
l=E() # Recalculate the number of conflicts
if not l:break # If there are no conflicts, we have a valid solution and can terminate
else: # Otherwise check the temperature to see if we keep the new move
if l>f and random()>t:e[j[0]]=k # Always keep the move if it's better, and undo it with probability 1 - T if it's worse
else:f=l # If we don't undo, remember the new conflict count
# Set each of the cells' final moves based on the paths
for i in e.values():
for j in R(L(i)-1):i[j][4]=i[j+1]
# Build the output in the form of a 2d array of characters
# Reuse the temp 2d array from step since its the right size
for i in c:
for j in R(L(i)):
k=i[j]
# Cells that are empty in the before array are always empty in the output
if 1&~k[1]:i[j]='.'
# Cells that aren't empty and don't have a move are always germs in the output
elif not k[4]:i[j]=G
# Otherwise draw the move
else:l,m=k[0];n,o=k[4][0];i[j]='v>^<'[abs((l-n+1)+2*(m-o))]
return c
```
] |
[Question]
[
# Background
In a 2d game that I play, each screen is a 2d grid of tiles with walls and walkable tiles, with the player only able to travel on walkable tiles, and being stopped by walls. When the player walks past the edge of the screen, he will travel to the adjacent screen on the map, with the player's relative screen location on the opposite side of the edge he entered in the previous screen (Think about it this way: when he walks left to another screen, it makes sense that he will be on the right of next screen).
There is a glitch that you can perform that will allow the player to glitch into a wall and, in certain cases, clip out of the map. After that, the player can travel through walls. Since the player is out of the map, if he travels past any edge of the screen, he will be warped to the other side relative to the screen, but the actual 2d grid will be the same (the game tries to determine where the player is to generate the new screen, but because he is out of bounds, it won't find a valid screen to generate, so the screen won't change). If the player travels out of a wall and into a walkable tile, he can't walk through walls until he is in a wall again. This rule also applies when the player warps to the other side of the screen after he travels through an edge; if he warps from a wall to a walkable tile, he will not be able to go through walls. On the flip side, if the player warps from a walkable tile to a wall, he will clip into the wall and be able to go through walls again.
A side effect of this glitch is that the player's actual coordinates in the game map will change based on which edge he travels through. When the player travels through the top or bottom edge, his y-coordinate will increase or decrease by 1 respectively. Similarly, when the player travels through the left or right edge, his x-coordinate will decrease or increase by 1 respectively.
# Challenge
Given a configuration of walls and walkable tiles of the screen, is it possible for the player to reach a certain map coordinate? Assume that the player is always out of bounds (so the screen configuration always stays the same), and that the player starts at map coordinates `(0,0)`. You can place the initial position of the player relative to the screen anywhere you want (you can place the player in a wall or a walkable tile). You can also optionally take in the dimensions, `n` by `m`, of the screen.
# Example
Let's say the screen is 3 by 4 has the following configuration (`1` represent walls, `0` represent walkable tiles):
```
1 0 0 1
1 0 0 1
1 0 0 1
```
Can the player get to the coordinates `(-2,0)`? Let's start by placing the player on one of the walkable tiles. I will denote the player with a letter `P`:
```
1 0 0 1
1 0 P 1
1 0 0 1
```
Because there are two columns of walls lining the left and right edge of the screen, the player cannot access those two edges. Therefore, he can only go through the top and bottom edge. In other words, the y-coordinate can change, but the x-coordinate stays the same. The same goes for any other walkable tile on the screen. So `(-2,0)` can't be reached by placing the player on a walkable tile. But what if you place the player on one of the walls; for example, one of the left ones?
```
1 0 0 1
P 0 0 1
1 0 0 1
```
First, if the player travels to the right, he will pop out of the wall, resulting in the situation described above. In this case, the player can travel through the left edge to get to `(-1,0)`, but he will be warped to the right side of the screen:
```
1 0 0 1
1 0 0 P
1 0 0 1
```
The player is now at `(-1,0)`, but the goal is to get to `(-2,0)` ! The player has to go through the left edge again, but it can't be reached. If the player walks to the left onto the walkable tile, he will pop out of the wall and won't be able to warp back into the wall again. Going through the top or bottom edge won't help, because the player will still be in the walls on the right side, which is not connected to the left side. Travelling through the right edge will warp the player back to the left walls, but at the same time, it will increase his x-coordinate by 1, bringing the player back to `(0,0)`.
Lastly, if you place the player on one of the right walls, like so:
```
1 0 0 P
1 0 0 1
1 0 0 1
```
You will find that reaching `(-2,0)` is still impossible. Using a similar reasoning as above, you can determine that in order for the player to access the left edge to get closer to `(-2,0)`, the player will first have to travel to the right. That will give him access to the left edge, but that will increase his x-coordinate by 1, so his coordinates are now `(1,0)`. Now, travelling through the left edge as we intended initially will bring the player back to `(0,0)`, instead of `(-1,0)` like we wanted. Popping out of the wall at the start by going to the left is also not an option, because it will result in the first situation described above.
So, it is impossible to reach `(-2,0)` with the above screen configuration.
# Input
Your code should take in a rectangular 2d list (or any representation of a 2d grid) of two distinct characters or numbers, one representing walls and the other representing walkable tiles, for the screen configuration. It should also take in a coordinate pair with integer coordinates. Your code can optionally take in the dimensions `n` and `m`.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in byte count wins!
# Test Cases
Uses `0` for walkable tiles and `1` for walls. The 2d ascii grid above each test case is just for reference.
```
n, m, coordinates, configuration
--> Output
False Cases
------------
1 0 0 1
1 0 0 1
1 0 0 1
3, 4, (-2, 0), [[1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1]]
--> False
1 0 1
0 1 0
1 0 1
3, 3, (0, 2), [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
--> False
1 0 1 1 1 1 1 1 1
1 1 0 0 0 1 0 1 1
1 1 1 0 1 0 1 0 1
0 1 0 1 1 1 1 1 0
1 0 1 1 1 1 1 1 1
5, 9, (2, 2), [[1, 0, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 1, 0, 1, 1], [1, 1, 1, 0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 1, 1]]
--> False
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
0 1 1 1 1 0 1 1 1 1 1 1 0
1 1 1 1 1 1 0 1 1 1 1 1 1
1 1 0 1 1 1 0 1 1 1 0 1 1
0 0 1 0 0 0 1 0 0 0 1 0 0
6, 13, (-200, 100), [[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], [0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1], [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0]]
--> False
True Cases
------------
0 0 0 1
1 0 0 1
1 0 0 1
3, 4, (-2, -2), [[0, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1]]
--> True
1 1 1 1
1 0 0 0
1 0 0 0
1 0 0 0
4, 4, (100, 100), [[1, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]
--> True
0 0 1 0 0
0 0 1 0 0
1 1 1 1 1
0 0 1 0 0
0 0 1 0 0
5, 5, (1, -1), [[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]]
--> True
0 0 1 0 0
1 1 1 0 0
0 0 1 1 1
0 0 1 0 0
4, 5, (-123, 456) [[0, 0, 1, 0, 0], [1, 1, 1, 0, 0], [0, 0, 1, 1, 1], [0, 0, 1, 0, 0]]
--> True
1 0 0 0 1 0 0 0 1 0 1 1 0
0 1 1 1 0 1 1 1 0 1 0 0 1
1 1 1 1 1 0 1 1 1 1 1 1 0
1 1 1 1 1 1 0 1 1 1 1 1 0
1 1 0 1 1 1 0 1 1 1 1 1 0
0 0 1 0 0 0 1 0 0 0 1 0 0
6, 13, (-200, 100), [[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0], [0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1], [1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 1, 0, 1, 1, ,1 ,1 ,1 ,0], [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0]]
--> True
```
[Answer]
# Python3, 975 bytes:
```
E=enumerate
def S(b,x,y):
q=[(x,y,0,0,b[x][y],[(x,y)])]
while q:
n,m,j,k,t,p=q.pop(0)
for X,Y in[(1,0),(-1,0),(0,1),(0,-1)]:
N=n+X;M=m+Y;F=0;J=j;K=k
if N<0 or M<0:J,K=j+(N<0),k-(M<0);yield J,K,0;N=len(b)-1 if N<0 else N;M=len(b[0])-1 if Y<0 else M;F=1
elif N>=len(b)or M>=len(b[0]):J,K=j-(N>=len(b)),k+(M>=len(b[0]));yield J,K,0;N=0 if N>=len(b)else N;M=0 if M>=len(b[0])else M;F=1
if(N,M)==(x,y)and(b[N][M]==0 or t):yield J,K,1,p
elif(N,M)not in p:
if F or b[N][M]==0 or t:q+=[(N,M,*([0,0]if b[N][M]==0 and t and F==0 else [J,K]),b[N][M],p+[(N,M)])]
def V(g,h,G,H):
r=[]
if g==0:r+=[G==0]
else:r+=([(g<0)==(G<0),g%G==0]if G else[0])
if h==0:r+=[H==0]
else:r+=([(h<0)==(H<0),h%H==0]if H else[0])
return all(r)
def f(t,b):
for x,a in E(b):
for y,_ in E(a):
K={0:set(),1:set()}
for z,v,F,*_ in S(b,x,y):
if(v,z)==t and not F:return 1
if F:K[0].add(v);K[1].add(z)
if any(V(*t,G,H)for G in K[0] for H in K[1]):return 1
return 0
```
[Try it online!](https://tio.run/##nVNtb9owEP7Or7A0VbLLpbLpNk2h7rcCKoIvk6pWUTSFYV7aEEJwu9Jpv53dOQGSQFdpipXYd/fcc37ukm7sbJlcfkuz7fZGm@R5YbLImsbYTNh3PoJX2Ai/wVY64LgFic8oeA2DTQjOIkIRNtiv2Tw2bIWBLIEFPMITWEj16iJdplwKNE@WGbuHBzZPAq5ACuBe/pGg3NtTIiQ8G@qked8e6EXzod3Rsn2rH9t9/USu@YQNryTDVIMr6d9CXz82OVoEPHkcTaK9mZt4zNADsj3UsUn4SHhqBzTx2rAh5naOQIaF72HnGyCjIiYTE@S6yECE1wdQzuzxvR/5m7wcUS9EsnK6fRnOXMZVi5hP@BAGQmsndJSMMWgYBoNQayeCFf6BRkG6K9yhkqVFsVnqNCWeDkFqCfxVExuL4XDOA@xtiHGlEKRk1r07dHTVBUgWCiiiIG06vBsDmpk7PoUZdKFHU5PpAIcDc04R7mfI1cUNmigTnXnAp9g2vGGXujg9c34EdF0ISeLwsx2@d4Sf5fge4WdnvQLfK@EzY5@zhEVxzDPhipxwCyMqkKbyFSIS6oY7izNt4EduipyJ9fVv6a@N5QJU/v1DZgp9gxfowLmLL/0vefde4A1ryxWkfnT8oha1b4rfxyIvovGYv4h2P1D5/k0U4x4lG37Hz61TlPi6REQYx97LTwpn8pC52MntJ@Q0PrPzhVmz5bNly4TZmWFxlE3N2jJLr5/R2qwbaTZPLJ9w7rXorwwCBUy6pUJg759w1A9YtLQE@osAF0tfPB1gOebTHtSqgY5Xgd2zyt2@6lRVT62Ao7Tlkk5wVi6GojAvr1L@hy5Kkk3K3TWr9yoy/vNUTYfFqFIx6gA5MhwJ@QGkem3VugT2@cvX02Rl2aupTpNV@@61aqrUmltv9IGj1u5a62V9KNQ7A6BOSfTBsJwkpcUgX8eSvrcnObZ/AQ)
] |
[Question]
[
First puzzle from me, suggestions for improvement gladly received!
The scenario is;
You work as a manager for a whitewater rafting company. Every morning, you are given a list of bookings, and you have to sort them into raft loads. Write a program or function in your chosen language that does this for you.
Each raft holds a maximum of `n` clients, and each booking is for a group of between 1 and `n` people (inclusive).
The following rules must be observed;
* No groups may be split up. If they booked together, they must all be in the same raft.
* The number of rafts must be minimised.
* Subject to the two preceeding rules, the groups must be spread as equally as possible between the rafts.
**Inputs.**
The number `n` (you may assume that this is a positive integer), and the size of all the bookings. This may be an array, list or similar data structure if your language supports such things. All of these will be positive integers between 1 and `n`. The order of the bookings is not defined, nor is it important.
**Output.**
A list of the booking numbers, grouped into raft loads. The grouping must be indicated unambiguously, such as;
* a list, or array of arrays.
* a comma separated list for each raft. Newline between each raft.
How you implement the third rule is up to you, but this could involve finding the average raft occupancy, and minimising deviations from it as much as possible. Here are some test cases.
```
n Bookings Output
6 [2,5] [5],[2]
4 [1,1,1,1,1] [1,1,1],[1,1]
6 [2,3,2] [2,2],[3]
6 [2,3,2,3] [2,3],[2,3]
6 [2,3,2,3,2] [2,2,2],[3,3]
12 [10,8,6,4,2] [10],[8,2],[6,4]
6 [4,4,4] [4],[4],[4]
12 [12,7,6,6] [12],[7],[6,6]
```
Standard rules apply, shortest code wins. Have fun!
Edited;
A suggested way to define *as equally as possible* for the third rule.
Once the number of rafts `r` has been determined (subject to the second rule), the average occupancy `a` can be calculated by summing over the bookings, and dividing by `r`. For each raft, the deviation from the average occupancy can be found using `d(x) = abs(n(x)-a)`, where `n(x)` is the number of people in each raft and `1 <= x <= r`.
For some continuous, single-valued function `f(y)`, which is strictly positive and has a strictly positive first and non-negative second derivatives for all positive `y`, we define a non-negative quantity `F`, as the sum of all the `f(d(x)), 1 <= x <= r`. Any choice of raft allocation that satisfies the first two rules, and where `F` is equal to the global minimum will satisfy the third rule also.
[Answer]
# Haskell 226 ~~228~~ ~~234~~ ~~268~~ bytes
Naive answer in Haskell
```
import Data.List
o=map
u=sum
p=foldr(\x t->o([x]:)t++[(x:y):r|(y:r)<-t>>=permutations])[[]]
m x=foldl(\[m,n]x->[m+(x-m)/(n+1),n+1])[0,0]x!!0
a!z=abs$u z-a
s t=(length t,u$o((m$o u t)!)t)
a n=head.sortOn s.filter(all$(<=n).u).p
```
Or ungolfed
```
partition' :: [a] -> [[[a]]]
partition' [] = [[]]
partition' (x:xs) = [[x]:ps | ps <- partition' xs]
++ [(x:p):rest | ps <- partition' xs, (p:rest) <- permutations ps]
-- from Data.Statistics
mean :: [Double] -> Double
mean xs = fst $ foldl (\(m, n) x -> (m+(x-m)/n+1, n+1)) (0, 0) xs
diff :: Double -> [Double] -> Double
diff avg xs = abs $ sum xs - avg
rawScore :: [[Double]] -> Double
rawScore xs = sum . map (diff avg) $ xs where avg = mean . map sum $ xs
score :: [[Double]] -> (Int, Double)
score xs = (length xs, rawScore xs)
-- from Data.Ord
comparing :: (Ord b) => (a -> b) -> a -> a -> Ordering
comparing p x y = compare (p x) (p y)
candidates :: Double -> [Double] -> [[[Double]]]
candidates n xs = filter (all (\ ys -> sum ys <= n)) . partition' $ xs
answer :: Double -> [Double] -> [[Double]]
answer n xs = minimumBy (comparing score) $ candidates n xs
```
With some test cases
```
import Text.PrettyPrint.Boxes
testCases :: [(Double, [Double])]
testCases = [(6 , [2,5])
,(4 , [1,1,1,1,1])
,(6 , [2,3,2])
,(6 , [2,3,2,3])
,(6 , [2,3,2,3,2])
,(12, [10,8,6,4,2])
,(6 , [4,4,4])
,(12, [12,7,6,6])]
runTests tests = transpose
$ ["n", "Bookings", "Output"]
: map (\(n, t) -> [ show . floor $ n
, show . map floor $ t
, show . map (map floor) $ a n t]) tests
test = printBox
. hsep 3 left . map (vcat top) . map (map text) . runTests $ testCases
```
Where `test` yields
```
n Bookings Output
6 [2,5] [[2],[5]]
4 [1,1,1,1] [[1,1],[1,1,1]]
6 [2,3,2] [[2,2],[3]]
6 [2,3,2,3] [[2,3],[2,3]]
6 [2,3,2,3,2] [[2,2,2],[3,3]]
12 [10,8,6,4,2] [[10],[8,2],[6,4]]
6 [4,4,4] [[4],[4],[4]]
12 [12,7,6,6] [[12],[7],[6,6]]
```
## Edit
Thanks to @flawr and @nimi for advice.
Squashed `p` a bit.
Shaved off a couple bytes.
[Answer]
# [Perl 6](http://perl6.org/), ~~163~~ 158 bytes
```
{[grep $^n>=*.all.sum,map ->\p{|map {p[0,|$_ Z..^|$_,p]},(1..^p).combinations},$^s.permutations].&{.grep: .map(+*).min}.min({.map((*.sum-$s.sum/$_)**2).sum})}
```
[Try it online!](https://tio.run/nexus/perl6#JY1BDoIwFESv8hcNaWv5CgtMNHAQEQgaMCS0NBQWpPTs2Opm3swsZuQGUQ/5YcvP3GkgtSpyju04olmlkK2GuHhquwdndXkRO2nggVh7Cl05QRMfNMP3JF@DapdhUsYJUhvU3SzX5d9UGFkMDzdAP0VPnKEclAtC7a@iPFzGxAScScM4T1nwjrnDtBv0kKQCSi9XkYmsuh9f "Perl 6 – TIO Nexus")
### How it works
* ```
map ->\p{|map {p[0,|$_ Z..^|$_,p]},(1..^p).combinations},$^s.permutations
```
Generates all possible partitions of all permutations of the input array.
* ```
grep $^n>=*.all.sum,
```
Filters the ones where no raft is overbooked.
* ```
.&{.grep: .map(+*).min}
```
Filters the ones where the number of rafts is minimal.
* ```
.min({.map((*.sum-$s.sum/$_)**2).sum})}
```
Gets the first one with minimal *∑(nx-a)2*.
*-4 bytes thanks to @Pietu1998*
[Answer]
# Python3, 224 bytes
```
def p(c):
if len(c)==1:yield[c];return
for s in p(c[1:]):
for n,u in enumerate(s):yield s[:n]+[[c[0]]+u]+s[n+1:]
yield[[c[0]]]+s
s=sum
r=lambda n,b:min(p(b),key=lambda c:s(abs(s(x)-s(b)/(s(b)//n+1))for x in c))
```
With testcases:
```
tc = [[6,[2,5]],[4,[1,1,1,1,1]],[6,[2,3,2]],[6,[2,3,2,3]],[6,[2,3,2,3,2]],[12,[10,8,6,4,2]],[6,[4,4,4]],[12,[12,7,6,6]]]
for case in tc:
print(str(case[0]).ljust(3),str(case[1]).ljust(16),"|",r(*case))
```
## How does it work?
The `p` function simply generates all partitions of a given list (all possible ways to divide it up into sublists). `s=sum` simply renames the sum function, so the last line does all the work.
```
r=lambda n,b:min(p(b),key=lambda c:s(abs(s(x)-s(b)/(s(b)//n+1))for x in c))
r=lambda n,b: Initialize the lambda
p(b) Calculate all possible raft arrangements
,key=lambda c: Map the following lambda onto the list:
s(b)/(s(b)//n+1) Calculate the ideal average amount of people per raft
abs(s(x)- ) Calculate how close is the current raft
for x in c For each raft in the partition
s( ) Sum it (the sum is a score of how close to ideal the function is),
min( ) And find the lowest valued partition.
```
I'm certain that this can be golfed further, especially the `p` function, but I worked on this for hours already, so here you go.
] |
[Question]
[
We've had a lot of alphabet challenges. For this challenge, **you are passed the *output* of an alphabet challenge, and you need to output the pattern scaled to size `N`**.
For example, if `N=5` and you were passed the [L-phabet](https://codegolf.stackexchange.com/questions/87064/print-output-the-l-phabet):
```
ABCDEFGHIJKLMNOPQRSTUVWXYZ
BBCDEFGHIJKLMNOPQRSTUVWXYZ
CCCDEFGHIJKLMNOPQRSTUVWXYZ
DDDDEFGHIJKLMNOPQRSTUVWXYZ
EEEEEFGHIJKLMNOPQRSTUVWXYZ
FFFFFFGHIJKLMNOPQRSTUVWXYZ
GGGGGGGHIJKLMNOPQRSTUVWXYZ
HHHHHHHHIJKLMNOPQRSTUVWXYZ
IIIIIIIIIJKLMNOPQRSTUVWXYZ
JJJJJJJJJJKLMNOPQRSTUVWXYZ
KKKKKKKKKKKLMNOPQRSTUVWXYZ
LLLLLLLLLLLLMNOPQRSTUVWXYZ
MMMMMMMMMMMMMNOPQRSTUVWXYZ
NNNNNNNNNNNNNNOPQRSTUVWXYZ
OOOOOOOOOOOOOOOPQRSTUVWXYZ
PPPPPPPPPPPPPPPPQRSTUVWXYZ
QQQQQQQQQQQQQQQQQRSTUVWXYZ
RRRRRRRRRRRRRRRRRRSTUVWXYZ
SSSSSSSSSSSSSSSSSSSTUVWXYZ
TTTTTTTTTTTTTTTTTTTTUVWXYZ
UUUUUUUUUUUUUUUUUUUUUVWXYZ
VVVVVVVVVVVVVVVVVVVVVVWXYZ
WWWWWWWWWWWWWWWWWWWWWWWXYZ
XXXXXXXXXXXXXXXXXXXXXXXXYZ
YYYYYYYYYYYYYYYYYYYYYYYYYZ
ZZZZZZZZZZZZZZZZZZZZZZZZZZ
```
You would need to output:
```
ABCDE
BBCDE
CCCDE
DDDDE
EEEEE
```
**For the purposes of explanation, I'll be using only `ABCD`, instead of the full alphabet.** You need to be able to match the L-phabet (above), as well as the following patterns:
The single line:
```
ABCD or A
B
C
D
```
The single line repeated `N` times
```
ABCD or AAAA
ABCD BBBB
ABCD CCCC
ABCD DDDD
```
The [Tabula Recta](https://codegolf.stackexchange.com/questions/86986/print-a-tabula-recta):
```
ABCD
BCDA
CDAB
DABC
```
This alphabet triangle:
```
A or AAAAAAA
AB BBBBB
ABC CCC
ABCD D
ABC
AB
A
```
We also have half triangles in lots of varieties:
```
A AAAA A ABCD
BB BBB AB ABC
CCC CC ABC AB
DDDD D ABCD A
```
Finally, the square:
```
AAAAAAA
ABBBBBA
ABCCCBA
ABCDCBA
ABCCCBA
ABBBBBA
AAAAAAA
```
All of the above patterns are of size 4. However, you will be passed a pattern of size 26, as well as an `N` between 1 and 26, and you need to scale the pattern. You do not need to handle any other patterns.
* The output for 1 will always be the single character `A`
* The output for 26 will always be the same, full-sized pattern passed in.
* Trailing spaces are allowed at the end of each line, as well as a trailing newline at the end
* You can find all patterns of size 26 [here](http://pastebin.com/Kt8NX5MF)
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so do it in as few bytes as possible!
[Answer]
# PHP, 502 Bytes
```
<?$c=count($x=explode("\n",$_GET[p]));for($t=$u=$o="",$f="substr",$n=0;$n<$g=$_GET["n"];$n++){if(2651==$l=strlen($s))$o.=$f($x[$n],0,$g).$f($x[$n],1-$g)."\n";elseif($l==1026)echo($t=$f($x[$n],0,$g)).$f(strrev($t),1)."\n";elseif($f($s,-1)=="Y")echo$f($x[$n],0,$g-$n).$f($x[$n],-$n,$n)."\n";elseif($l==376&&$f($s,-2,1)=="\n")echo$f($x[$n],0,$g-$n)."\n";elseif($l==726){$t.=$x[$n]."\n";$n+1==$g?:$u=$x[$n]."\n".$u;}else echo$f($x[$n]??"",0,$g)."\n";}if($o)echo$o.substr(strrev($o),2*$g+1);if($t)echo$t.$u;
```
Works with the string length of a pattern. A pattern has these conditions.
Letter at begin an end. CR are removed.
## Expanded
```
foreach($p as$s){ # all patterns in an array
$c=count($x=explode("\n",$s));
for($t=$u=$o="",$f="substr",$n=0;$n<$g=$_GET["n"];$n++){
if(2651==$l=strlen($s))$o.=$f($x[$n],0,$g).$f($x[$n],1-$g)."\n";
# square pattern
elseif($l==1026)echo($t=$f($x[$n],0,$g)).$f(strrev($t),1)."\n";
#alphabet triangle up down
elseif($f($s,-1)=="Y")echo$f($x[$n],0,$g-$n).$f($x[$n],-$n,$n)."\n";
# Tabula recta
elseif($l==376&&$f($s,-2,1)=="\n")echo$f($x[$n],0,$g-$n)."\n";
# two half triangle
elseif($l==726){$t.=$x[$n]."\n";$n+1==$g?:$u=$x[$n]."\n".$u;}
#alphabet triangle left right
else echo$f($x[$n]??"",0,$g)."\n";
# all other
}
if($o)echo$o.substr(strrev($o),2*$g+1);
if($t)echo$t.$u;
}
```
[Answer]
# R, 483 412 bytes
```
x=function(n){d=1:n;a=LETTERS[d];z=rep;f=function(...)cat(...,"\n",sep="");g=c(d,n:2-1);for(i in d)f(a[z(i,i)],if(i!=n)a[(i+1):n]);f(a);for(i in d)f(a[i]);for(i in d)f(a);for(i in d)f(z(a[i],n));for(i in d)f(a[i:n],if(i>1)a[1:i-1]);for(i in g)f(a[1:i]);for(i in d)f(z(" ",i-1),z(a[i],2*(n-i)+1));for(i in d)f(z(a[i],i));for(i in d)f(z(a[i],n-i+1));for(i in g)f(if(i>1)a[2:i-1],z(a[i],2*(n-i)+1),if(i>1)a[i:2-1])}
```
This is my first time posting, I was told I didn't have a recent years experience of R, so just practise a little bit here.
## Expanded
```
x=function(n){
# array of 1 to n
d=1:n
# first n capital letters
a=LETTERS[d]
# use z to represent the repeat function
z=rep
# use f to represent concatenate, with new line and close the gap
f=function(...)cat(...,"\n",sep="");
# use g to represent 1 to n then n to 1
g=c(d,n:2-1)
# L-phabet
# start and repeat the first letter to i, combine the i+1 to the end
for(i in d) f(a[z(i,i)],if(i!=n)a[(i+1):n])
# single line - horizontal
f(a)
# single line - vertical
for(i in d)f(a[i])
# single line - repeated by row
for(i in d)f(a)
# single line - repeated by column
for(i in d)f(z(a[i],n))
# Tabula Recta
# start from i, combine the 1 to i-1
for(i in d) f(a[i:n],if(i>1)a[2:i-1])
# alphabet triangle
for(i in g)f(a[1:i])
# alphabet triangle - upside down
for(i in d)f(z(" ",i-1),z(a[i],2*(n-i)+1))
# half triangles
for(i in d)f(z(a[i],i))
for(i in d)f(z(a[i],n-i+1))
# the square
# combine the first part from i to i-1 letters, repeat the i in the middle, combine the last part from i-1 to 1 letters
for(i in g) f(if(i>1)a[2:i-1],z(a[i],2*(n-i)+1),if(i>1)a[i:2-1])
}
```
[Answer]
# JavaScript (ES6), ~~382~~ ~~380~~ 370 bytes
```
f=(a,N)=>{X=Y=0
if(a[1]){Y=a[1].trim()[0]=='B'
X=z=a[0][1]==a[1][0]?1:!Y
l="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[s='slice'](0,N)
if(z){if(a[0][1]=='A'){for(a=[],i=0,L=l;i<N;i++)a[N-i]=a[N+i]=L[s](0,-1)+l[N-i-1].repeat(i*2)+[...L].reverse().join``
L=L[s](0,-1)
return a}if(a[1][1]=='C')for(i=0;a[i++]=l,i<N;)l=l[s](1)+l[0]}}else X=1
a=X?a.map(l=>l[s](0,N)):a
return Y?a[s](0,N):a}
```
Pass an array of strings to the function `f()`, like this:
```
f(
`AAAAAAA
ABBBBBA
ABCCCBA
ABCDCBA
ABCCCBA
ABBBBBA
AAAAAAA`.split('\n'), 3)
```
---
Less golfed version with comments:
```
f=(a,N)=>{
// Whether to truncate array horizontally to width N.
X=0
// Whether to truncate array vertically to height N.
Y=0
// If a second row exists...
if(I=a[1]){
// If the first non-whitespace character in the second row == 'B', truncate vertically.
if(I.trim()[0]=='B')Y=1
// Truncate horizontally if 2nd character in row 1 == 1st character in row 2; otherwise, if not truncating vertically.
X=z=a[0][1]==I[0]?1:!Y
// If 2nd character in row 1 == 1st character in row 2
if(z){
// Make an alphabet.
l="ABCDEFGHIJKLMNOPQRSTUVWXYZ".slice(0,N)
// If 2nd character in row 1 == 'A', forget everything we just did. Make a new array, generate a Square pattern, then return it.
if(a[0][1]=='A'){
for(a=[],i=0,L=l;i<N;i++)
a[N-i]=a[N+i]=L.slice(0,-1)+l[N-i-1].repeat(i*2)+[...L].reverse().join``,
L=L.slice(0,-1)
return a
}
// If 2nd character in row 2 == 'C', fill array with a Tabula Recta.
if(I[1]=='C')
for(i=0;a[i++]=l,i<N;)
l=l.slice(1)+l[0]
}
}else{
// If a second row doesn't exist, it's a horizontal line; truncate horizontally.
X=1
}
// Truncate array horizontally if necessary.
a=X?a.map(l=>l.slice(0,N)):a
// Truncate array vertically if necessary.
return Y?a.slice(0,N):a
}
```
] |
[Question]
[
Take a look at this image. Specifically, at how the holes on the ends are arranged.
[](https://i.stack.imgur.com/nmEO8.jpg)
([Image source](http://www.hed-inc.com/hairpin.html))
Notice how the pipes in this image are packed in a hexagonal pattern. [It is known](https://en.wikipedia.org/wiki/Circle_packing) that in 2D, a hexagonal lattice is the densest packing of circles. In this challenge, we will be focusing on minimizing the perimeter of a packing of circles. One useful way to visualize the perimeter is to imagine putting a rubber band around the collection of circles.
## The Task
Given a positive integer `n` as input, show a collection of `n` circles packed as tightly as possible.
## Rules and Clarifications
* Assume circles have a diameter of 1 unit.
* The variable to be minimized is the length of the perimeter, which is defined to be the [convex hull](https://en.wikipedia.org/wiki/Convex_hull) of the *centers* of the circles in the group. Take a look at this image:
[](https://i.stack.imgur.com/IOHKb.png)
The three circles in a straight line have a perimeter of 4 (the convex hull is a 2x0 rectangle, and the 2 is counted twice), those arranged in a 120-degree angle have a perimeter of about 3.85, and the triangle has a perimeter of only 3 units. Note that I am ignoring the additional pi units that the actual perimeter would be because I'm only looking at the circles' centers, not their edges.
* There may (and almost certainly will be) multiple solutions for any given `n`. You may output any of these at your discretion. Orientation does not matter.
* The circles must be on a hexagonal lattice.
* The circles must be at least 10 pixels in diameter, and may be filled or not.
* You may write either a program or a function.
* Input may be taken through STDIN, as a function argument, or closest equivalent.
* The output may be displayed or output to a file.
## Examples
Below I have example valid *and* invalid outputs for n from 1 to 10 (valid examples only for the first five). The valid examples are on the left; every example on the right has a greater perimeter than the corresponding valid example.
[](https://i.stack.imgur.com/7xmbm.png)
**Much thanks to steveverrill for help with writing this challenge. Happy packing!**
[Answer]
# Mathematica ~~295~~ 950 bytes
Note:
This still-to-be-golfed version addresses issues raised by Steve Merrill regarding my earlier attempts.
Although it is an improvement over the first version, it will not find the densest handle configuration where one would seek a circular, rather than hexagonal, overall shape.
It finds solutions by building a complete inner hexagon (for n>=6, and then examines all of the configurations for completing the outer shell with the remaining circles.
Interestingly, as Steve Merrill noted in the comments, the solution for `n+1` circles does not always consist of the solution for n circles with another circle added on. Compare the given solution for 30 circles to the given solution for 31 circles. (Note: there is a unique solution for 30 circles.)
```
m[pts_]:={Show[ConvexHullMesh[pts],Graphics[{Point/@pts,Circle[#,1/2]&/@ pts}],
ImageSize->Tiny,PlotLabel->qRow[{Length[pts]," circles"}]],
RegionMeasure[RegionBoundary[ConvexHullMesh[pts]]]};
nPoints = ((#+1)^3-#^3)&;pointsAtLevelJ[0] = {{0,0}};
pointsAtLevelJ[j_]:=RotateLeft@DeleteDuplicates@Flatten[Subdivide[#1, #2, j] &@@@
Partition[Append[(w=Table[j{Cos[k Pi/3],Sin[k Pi/3]},{k,0,5}]),
w[[1]]], 2, 1], 1];nPointsAtLevelJ[j_] := Length[pointsAtLevelJ[j]]
getNPoints[n_] := Module[{level = 0, pts = {}},While[nPoints[level]<=n,
pts=Join[pointsAtLevelJ[level],pts];level++];Join[Take[pointsAtLevelJ[level],n-Length[pts]],
pts]];ns={1,7,19,37,61,91};getLevel[n_]:=Position[Union@Append[ns,n],n][[1, 1]]-1;
getBaseN[n_] := ns[[getLevel[n]]];pack[1]=Graphics[{Point[{0,0}], Circle[{0, 0}, 1/2]},
ImageSize->Tiny];pack[n_]:=Quiet@Module[{base = getNPoints[getBaseN[n]],
outerRing = pointsAtLevelJ[getLevel[n]], ss},ss=Subsets[outerRing,{n-getBaseN[n]}];
SortBy[m[Join[base,#]]&/@ss,Last][[1]]]
```
Some of the checks entailed comparisons of over one hundred thousand cases for a single value of n (including symmetries). It took approximately 5 minutes to run the total 34 test cases. Needless to say, with larger `n's` this brute-force approach would soon prove impractical. More efficient approaches are certain to exist.
The numbers to the right of each packing are the perimeters of the respective blue convex hulls. Below is the output for `3 < n < 35`. The red circles are those added around a regular hexagon.
[](https://i.stack.imgur.com/q965K.png)
---
] |
[Question]
[
In this challenge, you are passed two things:
1. A string length, `N`
2. A list of strings, `L`, each with an assigned point value. Any string that is not passed in has a point value of 0
You need to construct a string of length `N` such that the sum of all substring points is as large as possible.
For example:
```
5 [("ABC", 3), ("DEF", 4), ("CDG", 2)]
```
should output
```
ABCDG
```
Because the two substrings with points (`ABC` and `CDG`) have a total of 5 points, and no other possible construction can give 5 or more points.
Substrings can be used multiple times in a string, and can overlap. You can assume that the points will always be positive, the substring lengths will be between 1 to `N` characters longs, and that `N > 0`. If multiple constructions are maximal, print any one of them.
Your program must run in a reasonable amount of time (no more than a minute for each of the examples):
```
1 [("A", 7), ("B", 4), ("C", 100)] => C
2 [("A", 2), ("B", 3), ("AB", 2)] => AB
2 [("A", 1), ("B", 2), ("CD", 3)] => BB
2 [("AD", 1), ("B", 2), ("ZB", 3)] => ZB
3 [("AB", 2), ("BC", 1), ("CA", 3)] => CAB
3 [("ABC", 4), ("DEF", 4), ("E", 1)] => DEF
4 [("A", 1), ("BAB", 2), ("ABCD", 3)] => AAAA or ABAB or BABA or ABCD
5 [("A", 1), ("BAB", 2), ("ABCD", 3)] => BABCD or BABAB
5 [("ABC", 3), ("DEF", 4), ("CDG", 2)] => ABCDG
5 [("AB", 10), ("BC", 2), ("CA", 2)] => ABCAB
6 [("AB", 10), ("BC", 2), ("CA", 2)] => ABABAB
8 [("AA", 3), ("BA", 5)] => BAAAAAAA
10 [("ABCDE", 19), ("ACEBD", 18), ("ABEDC", 17), ("BCEDA", 16), ("EBDAC", 15), ("BACD", 14), ("CADB", 13), ("ABDC", 12), ("CABD", 11), ("EBDC", 10), ("ACE", 9), ("CBA", 8), ("AEC", 7), ("BE", 6), ("AE", 5), ("DC", 4), ("BA", 3), ("A", 2), ("D", 1)]
=> ACEBDACEBD
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so prepare your shortest answer in your favorite language!
[Answer]
# Python3, 383 bytes:
```
lambda t,s,k={}:max(f(s,'',t,0,k),key=lambda x:x[1])[0]
C=lambda l,a:(l[:len(a)]==a)+(0if''==l else C(l[1:],a))
def U(l,a,k):
if(l,a)in k:return k[(l,a)]
k[(l,a)]=C(l,a);return k[(l,a)]
def f(s,l,t,p,k):
if(T:=len(l))==t:yield(l,sum(b*U(l,a,k)for a,b in s));return
for a,b in s:
for i in range(len(a)):
if l[T-i:]==a[:i]and T<len(L:=(l[:T-i]+a))<=t:yield from f(s,L,t,p+b,k)
```
[Try it online!](https://tio.run/##nZPBjtsgEIbvfgqUS6ChkknWaUqXgw1OL3tML3V9IIrdWiFOZHulRFWfPQVscHazPWxPHuCbmf8f8OnS/TrWi9Wpua7Zj6uSh@1Ogg63eM9@/6EHeYYlbPF0ijsc4j3C@@LCBupMzxnJURbmAXd7CksKVUZVUUOJcsYkmsGwKqdTxhQoVFsArs8JzbFEKNgVJfgGdZIuTQNQlSZGVQ32tCm650YHmd3KAx8xbr9fXgOmltGqtNSTr7ehzGhRCDHW0UtVqJ3m2@cD3H5wnctjAyTeAt23Ra5wAG63dTG7rsyqkfXPAvYWTRugGwGVbT5W1DjOaJXLegc2jwZ5oswMRB/mM40/OhWgbI4HK/jJCJ5ttZDrqanqDq4hwSCDk3iCwSeEAZwkOnqwEdcRCUOU6@k5eu7puacXNooTu/k2TDzcp3Fh83JwT4s38O99m9vai54emYT7RB7/E@fenUjXPk5t6i0fYY8v7nAuvt55fXjt9UaariPuFEX/mfAOTdE4IxKOQ5qPQ3rJL9/Jr3o@9oISE0Yvr5WETrewY/7cO@RpYiwCshocp8Je4PAIeSrsaJb9/SQitqfR0MaOhwzOY2EVu2fY13GibRdCXBk@etMS9KKXw63yQUrKx5/BIMth23qzcx9fUTKaH38K4Z7T9S8)
[Answer]
# Python 2.7, 503 Bytes
This isn't particularly golfed, nor is it particularly efficient; it's just a relatively condensed enumeration of feasible strings that are brute-forced. I don't think it would be too hard to create an admissible heuristic to use with A\*, which would probably be a bit quicker. I didn't bother doing that, though, because this method solves all of the examples in about 47 seconds on my laptop.
```
import re
v=lambda l,s:sum([len([m.start() for m in re.finditer('(?=%s)'%u,s)])*v for u,v in l])
def m(n,l,e):
if len(e)==n:
yield e
else:
u=1
for s,v in sorted(l,key=lambda j:j[1],reverse=True):
for i in range(len(s)-1,0,-1):
if len(e)+len(s)-i <= n and e.endswith(s[:i]):
for r in m(n,l,e+s[i:]):
u=0;yield r
if len(e)+len(s)<=n:
for r in m(n,l,e+s):
u=0;yield r
if u:
yield e
def p(n,l):
b,r=-1,0
for s in m(n,l,''):
a=v(l,s)
if a>b:b,r=a,s
return r
```
To test it:
```
if __name__ == "__main__":
for n, l in [
(1, [("A", 7), ("B", 4), ("C", 100)]), # => C
(2, [("A", 2), ("B", 3), ("AB", 2)]), # => AB
(2, [("A", 1), ("B", 2), ("CD", 3)]), # => BB
(2, [("AD", 1), ("B", 2), ("ZB", 3)]), # => ZB
(3, [("AB", 2), ("BC", 1), ("CA", 3)]), # => CAB
(3, [("ABC", 4), ("DEF", 4), ("E", 1)]), # => DEF
(4, [("A", 1), ("BAB", 2), ("ABCD", 3)]), # => AAAA or ABAB or BABA or ABCD
(5, [("A", 1), ("BAB", 2), ("ABCD", 3)]), # => BABCD or BABAB
(5, [("ABC", 3), ("DEF", 4), ("CDG", 2)]), # => ABCDG
(5, [("AB", 10), ("BC", 2), ("CA", 2)]), # => ABCAB
(6, [("AB", 10), ("BC", 2), ("CA", 2)]), # => ABABAB
(8, [("AA", 3), ("BA", 5)]), # => BAAAAAAA
(10, [("ABCDE", 19), ("ACEBD", 18), ("ABEDC", 17), ("BCEDA", 16), ("EBDAC", 15), ("BACD", 14), ("CADB", 13), ("ABDC", 12), ("CABD", 11), ("EBDC", 10), ("ACE", 9), ("CBA", 8), ("AEC", 7), ("BE", 6), ("AE", 5), ("DC", 4), ("BA", 3), ("A", 2), ("D", 1)]) # => ACEBDACEBD
]:
print p(n, l)
```
**Explanation**
The `v` function simply calculates the value of a given string by searching for all occurrences of the substrings in L. The `m` function enumerates all strings of length `n` with prefix `e` that can be generated from the substrings in `l`. `m` recursively calls itself; the first call should pass in `''` for `e`. For example:
```
>>> for s in m(4, [("A", 1), ("BAB", 2), ("ABCD", 3)], ''):print s
ABCD
BABA
ABCD
ABAB
AAAA
```
The `p` function simply loops through all possible strings (as enumerated by `m`) and returns the one with highest value (as determined by `v`).
Note that the `m` function actually prioritizes the enumeration by sorting based on substrings' values. This turns out to be unnecessary to ensure optimality, and it actually hinders efficiency a bit; I could save ~20 or so bytes by removing it.
[Try it online!](https://tio.run/##lZTRbpswFIbveYqjTFVgdaOQtF3HSicw2V5gV0URIoqzugM3siFTnz61jw0kaXpRXxBjn//jnP/Y2b42Ty9itt/zevsiG5DM28VVWa/WJVRERaqt/bxiws/riWpK2fgBbF4k1MCFDp5suFjzhkl/7P@ML1QwvmiJCpbB1x2GtWRnAqtl4K3ZBmpfkIqwIPKAb8BgWRDHQr/CK2fVGpgHrFLMLLRxqJ8GoixE6fzY2q/IP/bapfgcPefhkki2Y1Kx@I9sEW51HHMsxV/mm0@p4CokU3IV2oghg0u3y@E@BgGl0HlMmFir/7x58lUe8aWTIFYarKvkUuU86nd1ztMfthDpnfnCvS31HKZDHBM0oMWNzh1j4tZoTPyKyNiU5FmXBt54jLgy3mm3VGBB5cMqMoqSKE93rmmlNmevN4pClDUrCohjGBVFXXJRFKMhUUGgMuzcFWmHHxLI/VEyIvAtIOCPUj27xhnVs3A61aeAYOgXiB@AHqtnvXrWq@c4S1Jc7MRWnaQfycNebkE0Q9KxPD0vz87oH9MjPcofT@RzKx9EKe1JNDnU29KTD/S0tyxb/OrnC2RZAOr15rH@@rT6g1Q09cABa54eoBuZ6Djzq3/cO82OwTefA6dmrSOmZ1FY4/xdjTT73XfZNVgvnSfgaRpsng02zw5d0oTTHG4/S3hfxp1FJH0VqZneDOerH84RO06uyrQzI8PmfreG0kVqHIXwzhm8yPAcuftEFxl24taeijRLcPfGpYHdCJ2dSYZFdjfIcro68Sth2GHoYIdOQb/YdChW5lJZ0OFem5Bbt4y1YzOHs5sO5gz3OXOH2DlLMX39QGOWUe/PVnLR4F8aVMH@DQ)
] |
[Question]
[
This challenge is based off of Flow Free. An online version can be found here: <http://www.moh97.us/>
You will be given a puzzle, and you must return `1` if the puzzle is solvable, or `0` if it is not.
To solve a puzzle, the player must create a path to connect each pair of numbers using every empty square exactly once.
You are passed in the dimensions of the square, and then the x,y,c (where c is a number representing the color) of each dot. For example:
If `5,5` `0,0,0` `3,0,1` `1,1,2` `1,2,2` `4,2,1` `4,4,0` was passed to you, it would represent:
```
0..1.
.2...
.2..1
....0
```
And should return 1.
---
Here are some more test problems:
`5,2` `2,0,1` `0,1,2` `4,1,2` represents:
```
..1..
2...2
```
and is not solvable because there is only 1 `1`.
`4,2` `0,0,0` `3,0,0` `0,1,0` `3,1,0` represents:
```
0..0
0..0
```
and is not solvable because it includes more than 2 `0`s.
`8,6` `0,0,1` `7,5,1` represents:
```
1.......
........
........
........
........
.......1
```
and is not solvable (as you can't use every square).
`2,5` `0,0,1` `2,0,6` `4,0,6` `0,1,4` `3,1,4` `4,1,1` represents:
```
1.6.6
4..41
```
and is not solvable because you cannot connect the 1s.
`6,3` `1,0,4` `5,0,1` `0,1,4` `1,1,3` `5,1,3` `0,2,2` `3,2,2` `5,2,1` represents:
```
.4...1
43...3
2..2.1
```
and is not solvable because you cannot connect the 1s (or the 3s), as the two paths must necessarily cross.
`5,2` `0,0,1` `3,0,1` `0,1,3` `4,1,1` represents:
```
1..1.
3...3
```
and is not solvable because you cannot use all of the squares in building a path.
`2,2` `0,0,0` `1,1,0` represents:
```
1.
.1
```
and is not solvable because you can't use all of the squares here either
Here are some more tests:
`5,5` `0,3,0` `0,4,1` `1,2,2` `1,3,1` `2,0,0` `3,0,4` `3,1,2` `3,3,5` `3,4,4` `4,4,5` should return 1
`13,13` `1,1,0` `9,1,1` `10,1,2` `11,1,3` `1,2,4` `2,2,5` `5,2,6` `7,2,7` `3,3,0` `5,4,6` `6,4,1` `9,6,3` `4,7,8` `5,8,9` `12,8,8` `11,9,10` `2,10,4` `4,10,2` `9,10,5` `11,10,7` `1,11,9` `12,12,10` should return 1
`7,7` `0,0,0` `0,1,1` `1,1,2` `2,1,3` `4,2,4` `0,3,1` `5,3,3` `0,4,4` `2,4,5` `5,4,2` `0,5,0` `1,5,5` `3,5,6` `3,7,6` should return 0
---
This is a code golf, and the standard rules apply.
[Answer]
## Haskell
```
import Data.List.Split
import qualified Data.Sequence as Q
import Data.List
import Control.Monad
data A a = S a | E a | P a | X deriving Eq
sc = foldr1 (Q.><)
sp b x y p = Q.update y (Q.update x p $ b `Q.index` y) b
dt b c | S c `elem` sc b = E c
| otherwise = S c
ad b [x, y, c] = sp b x y (dt b c)
ep b [x, y, c] = do
let nps = filter ob [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]
ns = map gp nps
[b | E c `elem` ns] ++ do
(x', y') <- filter ((== X) . gp) nps
ep (sp b x' y' (P c)) [x', y', c]
where ob (u, v) = 0 <= u && u < length (b `Q.index` 0) && 0 <= v && v < length b
gp (u, v) = b `Q.index` v `Q.index` u
rd i = let [c, r] : ps = (map read . splitOn ",") <$> words i :: [[Int]]
e = Q.replicate r $ Q.replicate c X
cs = map last ps
ss = nubBy (\[_,_,c1] [_,_,c2] -> c1 == c2) ps
b = foldl ad e ps
bs = foldM ep b ss
in if even (length cs) && length ss == length cs `div` 2 &&
(all (\[j,k] -> j==k) . chunksOf 2 . sort $ cs) &&
any (null . Q.elemIndicesL X . sc) bs
then 1
else 0
main = rd <$> getContents >>= print
```
### Key
* sc: Seq concat
* sp: set position
* dt: dot type (ie, start or end of line)
* ad: add dot
* ep: extend path
* rd: run dots (primary pure algorithm)
[Answer]
# Python3, 538 bytes:
```
R=range
def f(x,y,v):
d={}
for j in R(x):
for k in R(y):d[r]=d.get(r:=v.get((j,k),-1),[])+[(j,k)]
if any(i!=-1 and len(d[i])!=2 for i in d):return 0
D=eval(str(d));del D[(M:=max(d))][0]
q=[(M,D,d[M][0],0)]
while q:
M,D,(j,k),C=q.pop(0)
if(j,k)in D[M]:
Y=eval(str(D));del Y[M]
if(M:=max(Y))!=-1:q+=[(M,Y,Y[M][0],0)];del Y[M][0]
if{-1:[]}==Y:return 1
continue
for J,K in[(-1,0),(1,0),(0,1),(0,-1)]:
if(T:=(j+J,k+K))in D[-1]:Y=eval(str(D));Y[-1].remove(T);q+=[(M,Y,T,C+1)]
elif T in D[M]and C:q+=[(M,D,T,C+1)]
```
[Try it online!](https://tio.run/##fVRdT@pAEH2@/RVrfGBXBrLbbQvU9EmeNL4YXkjT3IAtWsUCpXo1xt/OnZktaC7khmZazpw5c2b6sf5oHleVHa7r3e4uqWfVQ@HlxUIs5Dt8wJuKPZEnn1@eWKxq8STKStzJd0IZeHbAh4rztM6SvP9QNLKOkze@kE/wrKBnFKSZ6qb8N/NEuRCz6kOWZ0nP4FUulkUl87TM1Fnis2xJsrmK66J5rSuhPTFOirfZUm6bWuZKXebFUoxTeRsnL7N3QrJUo/ImQQzGkKe3BICmdn8ey2UhNmSZcs7UVbLpr1drqRXC5YJB7DnGQiKK6Xe/cdtvijlKIbvtO1WKZog3Xe47hel330MJG6OqT2Sm2VeSTPdzGUrcr6qmrF6LdqPXcIPDp7JnUAWkixoMR1yls4ceJnEin7rX8Ny9Uc56z2TxP76nBPbr4mX1VsiJujw4ncBV1yh2VizxhkxEOz3dj6v9ROM9b7c1IhGdEEKhAX/CYjTCgAEfo48xwGgwBqA73tZ3dF/4TNRMDChi0lIS@T@0NFPo2nB9QJQhREwxYgAhGIRDgv3WhWHxCGU1Ew0EXB9wI6JHRI/AokWNcHjwErB1iwhFzQNYjiGNgaWD/QCukz2U2oP60JnZj2Fa66PvTVmeK@BN@bwp27p2Uzu/1Noi3yIz4A2GKGM06RgkWCctRtRXGLdL4wYg3QAVaSdkPcJV@TBgRY1IgEjEDkYQsfcBDBEfwkgYH09DUkJljSJGu93hPqiZRk1qo1EPT8aV0EFjGn4iBpjTh/u3fyL8dk/kTfPMIUbLuyC3Abt1T0DIqwt5/hDdWnQYdfgb1Kx@l9VabvFz82sG4mKOHbf97XpZNlJ5v9q3qKwaOWvRDnRUajIFR6BGUHxKwudtWqmYzveK3jvUn4O4p9cgLX8UHj5H8@zL87x1TSULebH3ZpRSx6h/ErWEnh/BAcKiKV@KrVi9Nsdl4Umx6CQ6OIkOT6Kj03aMJj/n/zFkaOjdXw)
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/31615/edit)
## The mission
As is well known, the genetic material of all known creatures on Earth is encoded in DNA; using the four nucleotides adenine, thymine, cytosine, and guanine. (Commonly represented by ATGC).
A bioinformaticist wishing to store an entire genome would of course not want to store this as ASCII, because each choice can be represented by a mere two bits!
## The specification
Your mission, should you choose to accept it, is to write a pair of programs, functions or methods to convert an ASCII representation to a binary representation and back; representing `A` as `b00`, `T` as `b01`, `G` as `b10`, and `C` as `b11` (henceforth "units").
In addition, the high bits of each byte should contain the count of units in the byte, making each byte represent a triplet.
For example: `"GATTACCA"` becomes `b11 100001 b11 010011 b10 1100xx`.
In the ASCII to binary input, spaces, tabs and newlines should be ignored. Any character not in the set of `[ \r\n\tATGC]` is an error and may either be ignored or terminate processing.
In the binary to ASCII input, bytes whose two high bits are `b00` may be ignored.
The ASCII output may contain whitespace; but should never be more than 4 times the size of the binary input plus one byte long, and must end with a newline.
The binary output may contain an arbitrary number of `b00xxxxxx` "control" bytes; but must never be longer than the ASCII input.
Each conversion program must support input of arbitrary length; and should complete the encoding or decoding in approximately linear time.
## The twist
Unfortunately for the bioinformaticist for whom you are performing this task, he has in some way wronged you, on a personal yet perhaps petty level.
Perhaps he went out with your sister once, and never called her again. Perhaps he stepped on your dog's tail. The specifics are not really important.
What is important is that you have a chance for payback!
## The details
Each conversion should introduce a small error rate; on the order of one error per ten thousand to a million units processed.
An error can be one of the following:
* Duplication errors: `"GAT TAC CA"` becomes `"GAT TAA CCA"`
* Deletion errors: `"GAT TAC CA"` becomes `"GAT TAC A"`
* Translation errors: `"GAT TAC CA"` becomes `"GTA TAC CA"`
* Triplet duplications: `"GAT TAC CA"` becomes `"GAT TAC TAC CA"`
* Triplet slippages: `"GAT TAC CA"` becomes `"TAC GAT CA"`
* Triplet reversals: `"GAT TAC CA"` becomes `"GAT CAT CA"`
That errors will be introduced should of course not be immediately obvious from the code; and irrespective of the length of the input; the conversion should introduce at least one error.
Two runs with identical inputs should not *necessarily* produce identical outputs.
## The trick
The vile bioinformaticist is a moderately competent coder; and as such, some constructs will be automatically discovered, and are as such banned:
* He will automatically discover any calls to system random number generators, such as rand(), random(), or reading from /dev/urandom or /dev/random (or whatever the language equivalent is).
* He will also notice any superfluous variables, counters or loops.
## The scoring
The encoder and decoder will be scored individually.
Each will be run 3 times against a set of 100 randomly generated input files, each file with a size on the order of 3 million units.
The data for the encoder test cases will be created approximately as so:
```
for (l = 1 => bigNum)
for (t = 1 => 20)
random_pick(3,ATGC)
t == 20 ? newline : space
```
The data for the decoder test cases will be created approximately as so:
```
for (u = 1 => bigNum)
for (t = 1 => 20)
random_byte() | 0b11000000
0x00
```
### The encoder
* Each byte missing from the expected minimum length in the actual length will score -1 points, up to a maximum of -1000. (The expected minimum length is `ceil(count(ATGC) / 3)`.)
### The decoder
* Each byte over the expected maximum length in the actual length will score -1 points, up to a maximum of -1000. (The expected maximum length is `size(input) * 4 + 1`.)
### Both
* Each kind of error that can be produced will score 100 points; for a total of 600 points possible for each, 1200 total.
* Each test case for which the encoder produces more than 30% more or less errors than its own average will be penalized by -5 points.
* Each test case for which the encoder produces less than 15% more or less errors than its own average will be given 5 points.
* Each test case where all three runs produce identical outputs will be penalized by -10 points.
### Hard requirements
An entry will be disqualified if:
* For any valid input longer than one triplet it fails to produce even one error.
* Its performance is such that it cannot complete the test gauntlet within approximately one hour.
* It on average produces more than one error in every ten thousand units.
* It on average produces less than one error in every million units.
## The interface
The entrants should accept input on the standard input, and output to the standard output.
If the entry is one program with dual function; the switches `-e` and `-d` should set the program for encoding and decoding, respectively.
Example invocations:
```
$ encoder <infile.txt >outfile.bin
$ decoder <infile.bin >outfile.txt
$ recoder -e <infile.txt >outfile.bin
```
## The winner
The winner is the entry with the highest score; the theoretical maximum being 1200 for error kinds plus 3000 points for stability in error generation rate.
In the unlikely event of a draw; the winner will be determined by vote count.
## The additional notes
For the purposes of running the test gauntlet, each entry should include run or compilation instructions.
All entries should preferably be runnable on a Linux machine without X.
[Answer]
# Perl 5.10
I'm glad to present my solution in Perl.
When I started the challenge I was quite sure that Perl would stay well below the limit of 1 hour.
For testing purpose I developed a plain sample generator and a coded sample generator.
Then I developed the encoder that took a bigger effort and produced a longer code.
The encoder works as follow:
1. first loop reads the whole file and splits data to have an array of all triplets
2. second loop traverses the array and prepend to each element its length
3. third loop traverses again and maps each character to give the output.
The coded binary output is so formatted as new-line terminated "lines" of 20 octets where each octet codes one triplet,
with two characters of prefix (like a cyclical line-number).
for example, the *shortest* three byte input:
```
AAA
```
should give the shortest output of three bytes plus new-line.
```
00ÿ
```
that is
```
30 30 FF 0A
```
and
```
AGG CGC AAC GGC TAA ATC GTT TTC ACA CCA CGT TTG AAA CGG GTG ACA CGA GAT TTA GTC
TAT GGT ACT AGG TAC GCC GTG GTG CGT GCG GAG TTA CTA GAT GTG TTA GTA CGC CAT CGT
```
should give the following binary.
```
01ÊûÃëÐÇå×ÌüùÖÀúæÌøáÔç
00ÑéÍÊÓïææùîâÔôáæÔäûñù
```
*Should* because of the small error rate:
For the smallest input, the script introduces 1 error.
For a 3 million triplets file run, the encoder introduces 11 errors.
Provided that the script is dnacodec3.pl, the run is invoked at command prompt as usual:
```
$> perl dnacodec3.pl -e < plain.txt > coded.txt
```
The decoder works as follow:
1. first loop reads the whole file and splits data to have an array of all octets. It keep track of every new-line.
2. second loop examines each octet, retaining those not beginning with 00 and disregards the rest. The plain Ascii output is formatted as new-line terminated lines of triplets separated by one space. The new-line are in the *same* position as they were in the input.
I prepared a 3 million triplets sample test file (about 12MByte) and tested for timing.
Using my laptop with an Intel Core i5 vPro at 2.6 GHz, the 3M encoder run always takes less than 20 sec.
During the run it takes 200-220 MByte of RAM. What a waste!
The decode run takes less than 10 sec. It cannot introduce errors... for now.
Again, for the decoding run
```
$> perl dnacodec3.pl -d < coded.txt > plain.txt
```
Here is the code
```
#!/usr/bin/perl
use strict ;
use warnings ;
my $switch = shift || die "usage $0 [-e|-d]\n";
my %map = qw( x 10 X 11 c 0b ? 00
A 00 T 01 G 10 C 11
0 00 1 01 2 10 3 11
00 A 01 T 10 G 11 C ) ;
my $r = 20 ;
my @dummy = unpack ( '(A4)*', '0xxx' x $r ) ;
my $map = oct( $map{ c } . ($map{ C } x 9) ) ;
my $t = time() ;
my @inp = () ;
my @out = () ;
my @buf = () ;
my $n ;
sub arch {
push @buf, @dummy[ 0 .. $r - $#buf - 2 ] ;
push @out, "@buf" ;
@buf = () ;
}
sub encode {
my $mask = '(A3)*' ;
while ( my $row = <STDIN> ) {
chomp $row ;
$row =~ s/\s+//g ;
$row =~ s/[^\r\n\tATGC]//g ;
next unless $row ;
my @row = unpack( $mask, $row ) ;
push @inp, @row if $row ;
}
$n = scalar @inp ;
$r = $n if $r > $n ;
for ( my $i = $n - 1 ; $i >= 0 ; --$i ) {
my $e = $inp[$n-$i-1] ;
my $l = length( $e ) ;
my $d = $e =~ /\?/? 0: $l ;
push @buf, ( $d -((($i-($n>>1))&$map)?0:1) )
. $e . 'x'x(3-$l) ;
arch unless $i % $r ;
}
arch if scalar @buf ;
my $m = scalar @out ;
for ( my $j = $m - 1 ; $j >= 0; --$j ) {
my @ary = () ;
my $e = $out[$m-$j-1] ;
for my $byte ( split / /, $e ) {
my @byte = split ( //, $byte ) ;
my @trad = map { $map{ $_ } } @byte ;
my $byte = join( '', @trad ) ;
push @ary, $byte ;
};
my $row = sprintf( '%02d', $j % $r) ;
$row .= pack( '(B8)*', @ary ) ;
print "$row\n" ;
}
}
sub decode {
my $mask = '(B8)*' ;
while ( my $row = <STDIN> ) {
chomp $row ;
next unless $row ;
my @row = unpack( $mask, $row ) ;
push @inp, @row[0..$#row], '?' if $row ;
}
$n = scalar @inp ;
my @ary = () ;
for ( my $i = $n - 1 ; $i >= 0 ; --$i ) {
my $e = $inp[$n-$i-1] ;
if ( $e ne '?' ) {
my $u = oct( '0b'. substr($e,0,2) ) ;
my $a = '' ;
for my $j ( 1 .. $u ) {
$a .= $map{ substr($e,$j+$j,2) } ;
}
push @ary, $a if $u ;
}
else {
my $row = "@ary" ;
$row =~ s/\s{2,}//g ;
print "$row\n" if $row ;
@ary =() ;
}
}
}
decode if $switch eq '-d' ;
encode if $switch eq '-e' ;
```
And here is the sample generator:
```
sub test_coder {
my $n = shift || 1000 ;
my @b = qw( A C G T ) ;
for (my $l = 0; $l < $n; $l++) {
my @ary = () ;
for (my $t = 0; $t < 20; $t++) {
push @ary, $b[ int(rand(4)) ] . $b[ int(rand(4)) ] . $b[ int(rand(4)) ] ;
}
print "@ary\n" ;
}
1;
}
sub test_decoder {
my $n = shift || 1000;
for (my $l = 0; $l < $n; $l++) {
my @ary = () ;
for (my $t = 0; $t < 20; $t++) {
push @ary, int(rand(256)) | 0b11000000 ;
}
my $row = pack( 'C*', @ary ) ;
print "$row\000" ;
}
1;
}
test_coder( @ARGV ) if $switch eq '-g' ;
test_decoder( @ARGV ) if $switch eq '-h' ;
```
] |
[Question]
[
If you have a small child in your house, you may have come across foam bath letters. These can be moistened and stuck to flat surfaces such as tiles and the side of the bath to make words and messages.
The range of words and messages is somewhat limited if you only have one set though, since you only get 36 characters: uppercase letters A-Z, and digits 0-9: `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`. However, you can be cunning and abuse some of the letters and digits to form extra copies of other letters:
```
3: E
1: I
7: L (when rotated)
M: W (when rotated)
0: O
2: S (when flipped)
5: S
W: M (when rotated)
2: Z
5: Z (when flipped)
O: 0
6: 9 (when rotated)
L: 7 (when rotated)
9: 6 (when rotated)
```
Note that these are not all bi-directional, since it tends to be easier to read a digit as part of a word than a letter as part of a number.
Each set also comes in a range of colours, where each letter is coloured in sequence. For example, if your set has 3 colours, Red, Yellow and Blue, your set would be like:
* Red: `ADGJMPSVY147`
* Yellow: `BEHKNQTWZ258`
* Blue: `CFILORUX0369`
Your task, therefore, is to take three parameters (in any suitable way) indicating a word or phrase, the number of colours to be used, and the number of sets you have, then to output a representation of the word or phrase, in a set of suitable colours, making use of substitutions if required. If it is not possible to make the word or phrase given the number of sets, instead output "Nope", in the appropriate colours.
## Examples
In all of these, the first parameter is the word or phrase, the second is the number of colours, and the third is the number of sets available.
```
["bath", 3, 1]
```
[](https://i.stack.imgur.com/FWtU8.png)
```
["programming", 3, 2]
```
[](https://i.stack.imgur.com/mn4Sc.png)
```
["puzzles", 3, 1]
```
[](https://i.stack.imgur.com/wC497.png)
```
["code golf", 5, 1]
```
[](https://i.stack.imgur.com/vAi3X.png)
```
["willow tree", 1, 1]
```
[](https://i.stack.imgur.com/qMuRo.png)
```
["impossible phrase", 8, 1]
```
[](https://i.stack.imgur.com/zGlpb.png) - there is only 1 P in a set, and no valid substitutions
## Notes
* You can default to 1 set if this helps (e.g. a default parameter value of 1), but you must support multiple sets if requested. The number of sets you have will always be a positive non-zero integer.
* If you have multiple sets, they are all coloured in the same way: if A is red in the first set, it will be red in the second set too. The colours are applied per set, not to all sets in a given invocation
* You must support 1 to 36 colours - 1 means all characters are the same colour, 36 means they are all distinct. There will only be integer numbers of colours.
* You can use any colours, as long as they are visually distinct - if you are outputting to terminal, you can use a combination of foreground and background as a "colour", although you must not use the same colour for foreground and background
* Your output must use the characters that you actually use, not the characters from the input. For example, if you had ["willow", 1, 1] as input, you could output `WIL7OM` with 7 and M rotated 180 degrees
* You should use the correct letters first, then substitute: `MI7LOW` is incorrect for ["willow", 1, 1]
* You can use any substitution for a given character: `SO5` and `SO2` with a flipped 2 are both valid for "SOS"
* Multiple invocations of your code for the same input do not have to produce identical output
* Output should be in uppercase, but input can be in any mix of upper and lower case
* It should be obvious, but a space does not have a colour
## Rules
* This is code golf, but with semi-graphical output (I'm not sure if you can do flipped text in a terminal, but am interested to see if Pyth has a built in for it)
* Standard loopholes apply
* There are no bonuses for functions, but please vote up interesting answers
* Include some screenshots of your output in your answers
### Related Challenges
* [My Daughter's Alphabet](https://codegolf.stackexchange.com/q/25625/16766) - a partial inverse of this challenge, looking at finding a minimal set of letters to write a range of sentences
* [Does a letter fit inside the other?](https://codegolf.stackexchange.com/questions/151269/does-a-letter-fit-inside-the-other) - about a different type of foam letters, but with a similar alternative to letters theme
[Answer]
# HTML/JavaScript (with jQuery)/CSS - non-competing/non-golfed
Just to get the ball rolling, and show that it's not impossible, here is a non-golfed, non-competing implementation that takes a naive approach to the task.
It first creates a string of all the possible characters (`tempalph`), by joining as many copies of the alphabet as there are sets. Then it iterates through the phrase, putting each letter of the phrase into an output variable, and blanking the first instance of that letter from `tempalph`. If it can't (the letter doesn't exist), it checks if the letter is replaceable with something left in the string. If that also fails, it outputs a pre-defined "NOPE" output. Assuming it doesn't hit the "NOPE" case, it returns the output string and puts it into a DIV on the page.
It then loops through the base alphabet string, and if a letter has been used, assigns it an appropriate CSS class, each of which has a pre-defined colour set.
It uses HTML inputs for input, and updates on keyup in them.
Try it at [JSFiddle](https://jsfiddle.net/mpettitt/7aqj3oq6/)
Example for `["BATH", 3, 1]`:
[](https://i.stack.imgur.com/m5Hnc.png)
JS:
```
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
function getPhrase(phrase, sets){
var modphrase = "";
var nope = 'NOPE';
var re = /^[A-Z0-9 ]+$/;
if (re.test(phrase)){
// might be valid - need to check there are enough characters available
// At this point, need to look at specifically what characters are needed
var tempalph = "";
for ( var i=0; i'+char+'';
if (tempalph.indexOf(char) != -1){
tempalph = tempalph.replace(char, "#");
} else {
switch(char){
case "E":
if (tempalph.indexOf("3") != -1){
tempalph = tempalph.replace("3", "#");
modchar = '3';
} else {
return nope;
}
break;
case "I":
if (tempalph.indexOf("1") != -1){
tempalph = tempalph.replace("1", "#");
modchar = '1';
} else {
return nope;
}
break;
case "L":
if (tempalph.indexOf("7") != -1){
tempalph = tempalph.replace("7", "#");
modchar = '7';
} else {
return nope;
}
break;
case "M":
if (tempalph.indexOf("W") != -1){
tempalph = tempalph.replace("W", "#");
modchar = 'W';
} else {
return nope;
}
break;
case "O":
if (tempalph.indexOf("0") != -1){
tempalph = tempalph.replace("0", "#");
modchar = '0';
} else {
return nope;
}
break;
case "W":
if (tempalph.indexOf("M") != -1){
tempalph = tempalph.replace("M", "#");
modchar = 'M';
} else {
return nope;
}
break;
case "0":
if (tempalph.indexOf("O") != -1){
tempalph = tempalph.replace("O", "#");
modchar = 'O';
} else {
return nope;
}
break;
case "6":
if (tempalph.indexOf("9") != -1){
tempalph = tempalph.replace("9", "#");
modchar = '9';
} else {
return nope;
}
break;
case "7":
if (tempalph.indexOf("L") != -1){
tempalph = tempalph.replace("L", "#");
modchar = 'L';
} else {
return nope;
}
break;
case "9":
if (tempalph.indexOf("6") != -1){
tempalph = tempalph.replace("6", "#");
modchar = '6';
} else {
return nope;
}
break;
case "S":
if (tempalph.indexOf("5") != -1){
tempalph = tempalph.replace("5", "#");
modchar = '5';
} else if (tempalph.indexOf("2") != -1){
tempalph = tempalph.replace("2", "#");
modchar = '2';
} else {
return nope;
}
break;
case "Z":
if (tempalph.indexOf("2") != -1){
tempalph = tempalph.replace("2", "#");
modchar = '2';
} else if (tempalph.indexOf("5") != -1){
tempalph = tempalph.replace("5", "#");
modchar = '5';
} else {
return nope;
}
break;
case " ":
break;
default:
return nope;
}
}
modphrase += modchar;
}
return modphrase;
} else {
// contains some other characters, so definitely isn't valid
return nope;
}
}
function addColors(colcount){
var i = 0;
for (let char of alphabet){
exclass = "."+char;
newclass = "col"+i;
if ($(exclass).length>0){
$(exclass).addClass(newclass);
}
i++;
if (i==colcount){
i=0;
}
}
}
$("#phrase,#sets,#colours").on("keyup", function(){
var phrase = $("#phrase").val().toUpperCase();
phrase = getPhrase(phrase, $("#sets").val());
$("#output").html(phrase);
addColors($("#colours").val());
})
```
HTML:
```
<label>Phrase<input type="text" id="phrase"/></label>
<label>Colours<input type="text" id="colours" value="3"/></label>
<label>Sets<input type="text" id="sets" value="1"/></label>
<div id="output">
</div>
```
CSS:
```
.col0{ color: #f00 }
.col1{ color: #0f0 }
.col2{ color: #00f }
.col3{ color: #66CDAA }
.col4{ color: #EE82EE }
.col5{ color: #7FFFD4 }
.col6{ color: #7FFFD4 }
.col7{ color: #FFDEAD }
.col8{ color: #D8BFD8 }
.col9{ color: #FF6347 }
.col10{color: #8B4513 }
.col11{color: #800000 }
.col12{color: #00FFFF }
.col13{color: #32CD32 }
.col14{color: #191970 }
.col15{color: #1E90FF }
.col16{color: #A0522D }
.col17{color: #808000 }
.col18{color: #DC143C }
.col19{color: #90EE90 }
.col20{color: #D2691E }
.col21{color: #48D1CC }
.col22{color: #008000 }
.col23{color: #8B008B }
.col24{color: #6495ED }
.col25{color: #800080 }
.col26{color: #000080 }
.col27{color: #DB7093 }
.col28{color: #7FFF00 }
.col29{color: #00FA9A }
.col30{color: #0000FF }
.col31{color: #BC8F8F }
.col32{color: #A52A2A }
.col33{color: #4169E1 }
.col34{color: #FFFF00 }
.col35{color: #FFA07A }
.rot{ display: inline-block; transform: rotate(0.5turn);}
.flip{ display: inline-block; transform: rotateY(0.5turn);}
div{
font-family: sans-serif;
font-size: 3em;
background-color: #000;
padding: 10px;
}
```
] |
[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/87444/edit).
Closed 7 years ago.
[Improve this question](/posts/87444/edit)
For this challenge, you need to compress a diff. **A diff is some data that represents the difference between two strings.** For this challenge, you need to provide one or more programs that can:
1. Input `A` and `B`, and output a diff, `C`
2. Input `A` and `C`, and output `B`
3. Input `B` and `C`, and output `A`
**The goal is to make the diff, `C`, as small as possible.** The diff can be anything: a string, a number, a blob of data. We just care about the size (number of bytes).
I have 50 test cases [that can found on Github](https://gist.github.com/nathanmerrill/125a6e2ae7d9ded3531fedff036cf74b). Each test case consists of two space-separated URLs which point to the 2 files you need to diff. (These test cases originated from PPCG members' Github profiles. Thanks all!)
All three tasks above should take under a minute to run on a reasonably powered computer (for each test case).
Your score is equal to the total size (in bytes) of all 50 diffs, lower is better. Hardcoding diffs in your program is not allowed (I reserve the right to change the test cases to prevent hardcoding). Builtins that produce a diff (like `diffutils`) are not allowed.
[Answer]
Is my answer valid?
```
set f [open commits.txt]
while {![eof $f]} {scan [gets $f] %s\ %s a b; puts [string compare $a $b]}
close $f
```
testable on: <http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMNmd4QkxvQUFsTnM>
] |
[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/187692/edit).
Closed 4 years ago.
[Improve this question](/posts/187692/edit)
I honestly can't believe this challenge does not already exist.
# The challenge
Write a function.
# The specifics
* Your program must define some sort of callable function. This includes anything commonly known as a function, a lambda function, or a subroutine. All of these types of callables will be referred to as a "function" in this post.
1. Input to the function is optional and not required.
2. A return value from the function is also optional and not required but control must return to the calling program.
* The function must be assigned to some sort of variable so that it is possible to be accessed at a later time. This includes indirect assignment (in most common languages where declaring a named function automatically adds the name into the current scope) and direct assignment (assigning an anonymous function to a variable directly).
* The function does not need to be named.
* The function must be created by *you* - you cannot just assign a default function from the language to a variable.
* None of [the standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default), please.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest score in bytes wins.
[Answer]
# x86 / x64 machine code, 1 byte
```
c3
```
Assembly:
```
ret
```
[Try it online! (nasm)](https://tio.run/##RYxBCkIxDET3OUUO8JWKG9HDSFqDFtIWfqLE09fSLpzN8BjekCqXKN9DJS29KyfLreLR2A1w5CktkuBdjXYDWH2dUyIR1HeESTdkz8sp7YNMvp3@FH0Lk3I1vIQXwBDXzSNi8HQeBzsb9P4D "Assembly (nasm, x64, Linux) – Try It Online")
¯\\_(ツ)\_/¯
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 0 bytes
[Try it online!](https://tio.run/##y0rNyan8DwQA "Jelly – Try It Online")
A monadic link that returns its argument. Since it is the first function to appear in the script, it can be called using `1Ŀ`.
Thanks to @lirtosiast for pointing out that a 0 byte link/function would work in Jelly.
I.e.
```
3,4,5 1Ŀ
```
[Try it online!](https://tio.run/##y0rNyan8/5/LWMdEx1TB8Mj@//8B "Jelly – Try It Online")
[Answer]
# Javascript, 6 bytes
```
f=_=>0
```
Includes variable assignment. Not much to see here.
[Answer]
# [Haskell](https://www.haskell.org/), 3 bytes
```
o=9
```
This code defines a polymorphic function called `o` which takes one type parameter and one typeclass instance parameter. When this function is called, it takes the given typeclass instance, gets its `fromInteger` member, calls that member with the `Integer` value for 9, and returns the result.
Granted, what I just described is merely the behavior of the Haskell function `9`, and my code merely defines a function called `o` which is equivalent to `9`.
Now the only question is, is the `9` function "created by you," or is it "a default function from the language"?
I think that it is "created by you." My reason for saying this is that if you read the specification for Haskell, you will (I assume) find no mention of a `9` function anywhere. Instead, the specification states that you can create a number literal by stringing together one or more digits. Therefore, by writing a string of digits, I have written a function—even if I just so happen to have only used one digit.
[Answer]
# [Python 3](https://docs.python.org/3/), 9 bytes
```
def f():1
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNQ9PK8D@Q/A8A "Python 3 – Try It Online")
[Answer]
## ZX Spectrum BASIC, 6 bytes
```
DEF FN f()=PI
```
Hex dump: `CE 66 28 29 3D A7`. `CE` is a 1-byte keyword for `DEF FN` (including the trailing space), while `A7` is a 1-byte keyword for `PI`. Call using `FN f()`. Example program:
```
10 PRINT FN f(): DEF FN f()=PI
```
Output:
```
3.1415927
```
[Answer]
# [R](https://www.r-project.org/), 9 bytes
```
body(t)=0
```
[Try it online!](https://tio.run/##K/r/Pyk/pVKjRNPW4H@JhuZ/AA "R – Try It Online")
I think this complies with the rules. The function `t` takes no input and outputs `0`. This works because there already exists a function called `t` (the transposition function) and it redefines the body of the function; it would not work with say `body(a)=0` (no object called `a`) or `body(F)=0` (`F` is a logical, not a function). I think it complies because it is still created by me: I am not reusing what the pre-defined function does, simply its name.
I don't think I've ever seen this used by R golfers, but there may be situations where it allows us to save a few bytes on challenges where we need a helper function.
A more standard solution would have been:
# [R](https://www.r-project.org/), 13 bytes
```
f=function()0
```
[Try it online!](https://tio.run/##K/r/P802rTQvuSQzP09D0@B/mobmfwA "R – Try It Online")
Function which takes no input and outputs `0`. This is 1 byte shorter than the function which takes no input and outputs nothing, which would be
```
f=function(){}
```
If we try to define a function with no body (`f=function()`), R interprets this as an incomplete command (this might not be true in older versions of R).
As pointed out by OganM, we take this down to 11 bytes with
# [R](https://www.r-project.org/), 11 bytes
```
function()0
```
[Try it online!](https://tio.run/##K/r/P600L7kkMz9PQ9Pgv55PYnGJXlliTmmqhuZ/AA "R – Try It Online")
which technically complies with the challenge requirement that the function be assigned to some sort of variable, since it is (ephemerally) assigned to `.Last.value`.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 5 bytes
```
$!=!*
```
[Try it online!](https://tio.run/##K0gtyjH7r/BfRdFWUeu/NVdxYqWCiqKGoeZ/AA "Perl 6 – Try It Online")
Creates a Whatever lambda that returns the boolean not of its parameter, and assigns it to the variable `$!`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 5 bytes
Defines a function `f` that takes no arguments and technically returns an undefined integer value.
```
f(){}
```
[Try it online!](https://tio.run/##bcsxCoAwDEDRvacITokguBcnTyLVlkCNUqsg4tlrCy6C8//PNM6YlCzSdSeWCPPAgsfCI8GlFMC6xw2rfvCexYGFkcNkoj8r0rlmp8tVJNaOkDqr/xjLF7oXhinuQaDV6k4P "C (gcc) – Try It Online")
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 7 bytes
```
```
Creates a subroutine that returns control to the caller.
Explained in context:
```
[N
S S N
_Create_Label][N
T N
_Return]
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/n0tBgYuLk@s/FxfXfwA "Whitespace – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)], 1 byte
This one is slightly questionable:
```
f
```
Defines `f`, which can be "called" e.g. by `f[]`, which "returns" the expression `f[]`
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 5 bytes
This is a function named `f` that does nothing.
```
: f ;
```
[**Try it Online**](https://tio.run/##S8svKsnQTU8DUf//WymkKVj/L05NVUj7DwA "Forth (gforth) – Try It Online")
In the TIO code, I added a footer of `see f`, which prints the definition of the function.
[Answer]
# [Lua](https://www.lua.org), 8 bytes
```
f=load''
```
[Try it online!](https://tio.run/##yylN/P8/zTYnPzFFXf1/moam9X8A "Lua – Try It Online")
Defines a (global) function `f`.
This uses Lua `load` function to compile given string which happens to be empty in our case (empty code is valid code) into function which does exactly what we wrote in its body: nothing.
For ones wondering, standard solution would be
```
function f()end
```
but this is longer (15 bytes).
[Answer]
# POSIX sh, 6 bytes
```
s()(1)
```
Using curly braces requires one more character.
[Answer]
# Java, 10 Bytes
this should match the rules of the challenge
```
void f(){}
```
[Answer]
# [Perl 5](https://www.perl.org/), 7 bytes
```
sub f{}
```
[Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhrbr2/38A "Perl 5 – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org/docs/reference/), 8 bytes
```
val f={}
```
An empty function stored in a variable f.
Call it using `f()` or `f.invoke()`.
[Answer]
# [shortC](https://github.com/aaronryank/shortC), 1 byte
```
A
```
[Try it online!](https://tio.run/##K87ILypJ/v/f8f9/AA "shortC – Try It Online")
Transpiles into this C:
```
int main(int argc, char **argv){;}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~14~~ 13 bytes
```
(*f)()=L"Ã";
```
[Try it online!](https://tio.run/##S9ZNT07@/19DK01TQ9PWR@lws5L1/9zEzDwNzWouBYU0DU1rrtr//5LTchLTi//rVqVWpCYXlyQmZwMA "C (gcc) – Try It Online")
This defines a function `f` returning `int` and accepting an unspecified number (and type) of parameters, the machine code of which is contained within the string literal. The unicode character `Ã` (stored in memory as `0xc3 0x00 0x00 0x00` on a little endian machine) corresponds to the x86 `ret` instruction that returns from the function. Non x86 architectures may require different opcode(s) to return.
`gcc` may require the `-zexecstack` flag to avoid a segfault.
[Answer]
# Pascal, 22 bytes
```
procedure A;begin end;
```
[Answer]
# [Haskell](https://www.haskell.org/), 5 bytes
```
f x=0
```
[Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZp2CrkJLPpaBQUJSZV6KgopCmYGhkjMJXcsvPT0osUvqfplBha/D/PwA "Haskell – Try It Online")
[Answer]
# [Tcl](http://tcl.tk/), ~~6~~ ~~5~~ 11 bytes
```
set f {_ ;}
```
[Try it online!](https://tio.run/##K0nO@f@/OLVEIU2hOl7BuvZ/YkFBTqWCSpqCwX8A "Tcl – Try It Online")
Including the assignment to the variable f as part of the bytecount to comply with rules. With this change, the more conventional definition below ties the one above for bytecount:
```
proc f _ {}
```
[Answer]
# XSLT, 134 bytes
```
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template name="a"></xsl:template></xsl:stylesheet>
```
A template is the closest thing this language has to a function. It can definitely be called; it takes zero arguments and "returns" the empty string.
[Answer]
# [F# (.NET Core)](https://www.microsoft.com/net/core/platform), 9 bytes
```
let f a=a
```
[Try it online!](https://tio.run/##SyvWTc4vSv3/Pye1RCFNIdE28f9/AA "F# (.NET Core) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 6 bytes
[Proc](https://ruby-doc.org/core-2.6/Proc.html) called `f` which accepts no argument and returns `nil`.
```
f=->{}
```
[Try it online!](https://tio.run/##KypNqvz/P81W16669n@BQppecmJOzn8A "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 10 bytes
```
f=lambda:0
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSXRyuB/mobmfwA)
[Answer]
## AppleScript, 10
```
on a()
end
```
Explained, compiled, and including invocation:
```
on a() -- declare event handler "a"
end a -- end declaration
-- invoke it:
a()
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 bytes
```
_
```
Called as `$U ($`.
`_` can be replaced with `@`, `Ï`, or `È`.
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Xwo)
[Answer]
# SmileBASIC (>=3), 9 bytes
```
DEF A
END
```
Function is called by `A`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 2 bytes
```
#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@19Z7X9AUWZeSXRatHls7H8A "Wolfram Language (Mathematica) – Try It Online")
Unfortunately, just `&` does not work (an anonymous function that does nothing).
] |
[Question]
[
# Challenge
Given a positive-length string \$S\$, a divisor of \$S\$ is another (not necessarily distinct) string for which there exists a number \$a\$ such that when we repeat the divisor \$a\$ times, we get the string \$S\$.
For example, the string `abcd` is a divisor of the string `abcdabcd` with \$a=2\$.
Your challenge is, given a positive-length string \$S\$, output all of \$S\$'s divisors.
For example, the string `aaaa` has three divisors: `a`, `aa`, and `aaaa`.
# Input/Output
Input/output can be taken in any reasonable format for taking a string and returning the set of divisors of that string.
The input string will only has lowercase characters, and it contains no whitespace or special characters.
The output list should not contains any duplicates. The strings can appear in any order.
Testcase:
```
Input -> Output
abcdabcd -> abcd, abcdabcd
aaa -> a, aaa
aaaaaaaa -> a, aa, aaaa, aaaaaaaa
abcdef -> abcdef
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) wins!
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
ġ=h
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/0cW2mb8/x@tlJiUnALCSjoKSomJiVAKDMBsoFRqmlIsAA "Brachylog – Try It Online")
[Generator.](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753)
```
ġ Split the input into (roughly) equal slices.
h Output one of them
= if they're all equal.
```
[Answer]
# [Python](https://www.python.org), 53 bytes
```
lambda s,t="":[t for c in s if~-any(s.split(t:=t+c))]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3TXMSc5NSEhWKdUpslZSsoksU0vKLFJIVMvMUihUy0-p0E_MqNYr1igtyMks0SqxsS7STNTVjoZqDC4oy80o00jSUEoFASVOTCyGQlJwCwlgFUzFEUyEEUBxi9IIFEBoA)
[Answer]
# Regex (ECMAScript 2018 or better), 17 bytes
```
(?<=(.*))(?=\1*$)
```
[Try it online!](https://tio.run/##bU69TsMwEN77FKmE5LsmtZq1wWRi6ApjW6kmuQQjxwlnh1apuvIAPCIvEtKyMHDSJ52@u@/nTX9oX7DpwtK1JY1erTJWT1Q/njp4DmxcLVkfDyPk9wrkAhFytUsXdzgepLemIEiTZYqJqAVmTO@9YQLBpEtrHAmUxbQH2rhAXOnp/Wxc14d1x21B3ksfSuMuKFsH4qZIrHo4/7m2fZBHNoEAfC52TqyFwNjGIvr@/IqmUK/SrGoZhqk6NIolnagAizhXyvXWZoNK8Tz733LIRRL9WjbbdI@ZqWDebFd7acnV4RVZWu3DxpV0iuPLBUf9UpRXzLTWV9xmdmWo@gE "JavaScript (Node.js) – Try It Online") - ECMAScript 2018
[Try it online!](https://tio.run/##LY5BasMwFET3PsVgApKCIyK6sypygpwgycKt5VSgyuJLgcQHyAFyxF7Etdx@mMU8mMePj/w1hrfZfceRMtIjNWSv9q5Bhuq6nvnh3XC5FYIfzFltN2Je6Em1O3XRmMy@GkaChwtlK1PuXWgrLMTAS0qZXOTsHJhYoBswtYjkQualT0bp/@obG3rD8PN8gQmNtJiB4j4W9/qTHFzoXbbEqYEX7d@SNWDFnGB9smBsNR3llcZbTFyc9hehk1Fz9/HZl1Rd15WsVxVih18 "Python 3 – Try It Online") - Python (`import [regex](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)`)
[Try it online!](https://tio.run/##dY1BasMwEEX3OYUQA9aExMTbKCKBrHOCNBTVGccCWTKSg0tcb3uAHjEXceVS6Kof/ubP/Pdb31OINVk7QVDnQDd6v2y3jnpxyCax3ymRLxHFXr0US8ApO6z40TetsXTlKOGhNrLygXRZC7DMOAbGtfcOB2gUhPyku7KmmG4oTSXggUMfTEfr2sduTPVCQkyMv5CtnU/z1jhiPCGfn1@MS2g@fmeG/17FzI84ZCuWjQlaIAh4zW/B39t4Li7Ix3HSb@V19kJrPftHizmh6hs "PowerShell – Try It Online") - .NET
[Try it on regex101!](https://regex101.com/r/QsA4DK/1) - ECMAScript 2018 or .NET
Returns its output as the list of matches' `\1` captures.
Ports:
[Try it online!](https://tio.run/##bVLBbtswDL3nKzhjRSU3VdGz5hXYsJ26YViO6wrItpwolSVPopssga/7gH3ifiSjHHddgRgWJD1Sj3wk1@pRXa7rh4NpOx8Q1nQXxotcwv9Ij8aexIJe6u1JS8SgVSvee2t1hT5EOev60poKKqtihE/KONjDhEVUSNujNzW0ZGELDMYtQYVl/PadA66C30T4sK10h8bTyxnAR2M1NIXTm/HIMlH5WguyZ1y@65tGB11/1arWAcrR7SXInl5O14ZzOcWNc5SbVeJnLBYl6VT1rXGacf6qcL213DQsCv2jVzay7CrP84zz/UvXIwNjeJJgTwz4j4EIroihJL8HGS@K8zt3nnaUwxEbvihEHRyEYjqR2rZLASKXVI3Se6uVg13REKOWsKiUcyTduK5HKCCpnTC2@BlRt8I4LmHSObqJlYqf9RYpzbHEAFNBLOVOHEcnRx6TROojViuK0pI1iPZ4Y8mdjCRxx6dYnh5ugkHNkjYudwWGPqX5bO4oFDYsO4vw59dvOIvZfAw8n7IQa0@jQSD9LZU09hYj4xS1Y224fJtlF7SLZfB9x64551SicfzY8xgK9LcmJoHU7WEYZql3B3bzpmD3Iuec3RR31/lrfkgdOaiyqtOaKaXSGr9ZQnTzFw "Java (JDK) – Try It Online") - Java, **18 bytes**: `(?<=(^.*))(?=\1*$)`
[Try it online!](https://tio.run/##JYtNCsIwFIT3niLIw7xIaa3gxjQtBd26cimGWKstpD@kgmitSw/gEb1ITXVgFt/wTZ0aveiLGwHDSaurRGkCHrcoglW8jcOOnCqD0IgZD0LO2iSripqDFiCt1UwmtcnLy3hXjrmVfP5DAtql5PN6Uw53@7xmuU7Rnp4eGO/M2r@FCPeIOoQuKaHMAZ8Nut91Uq43Kyl7jAS6U8ZcxCgQlvY7fwoPjOZ2Y6zv1SE5Dh0ppYb@MhqW9PQF "Perl 5 – Try It Online") - Perl, **31 bytes**: `(?=(.*)).((?<=(?=^\1*$|(?2)).))`
[Try it online!](https://tio.run/##fVFBbtswELz7FRuBCLmGLFs5hiF0qVsEKJJCzS1KCVqlLNWULJBMDklzzQP6xH7EXdnooTmUwBLc2eHscDm24@GqGNsRmAcFyTKBDEZvt9rb0ZnaCr7M5oXWrXFR1/t@7Jz1lahQVuUy8BQ4RUOg3tqJMEQ7xCC0/nj9ea01ppAjSZKwnHVDp4ONIhlrb7ONqXfR06Zd13cxSSFZ5AlK@Jfmbf3oQ7cf/k/7cSqtqDJr9l6wTq0kc6ohW0F8vftwfYMSX6BrBHP3IXpnBzrhIn9QKqmGBIkcHjdUIThdpYuclID4IM4E26njUHoT61Yb5wTzKdFYj4jA7KnqTIjaek/t8UypL@X6k7651euyvC1PWmQLbd3up4YSyGMuYcqBuYzD77dfnNBnck5seoU1dStYf58/gAnAnhBejmzBnotp9JccOGbs6Xgpl69//bIdnJ@TLTyJc1hPpi6BZ@986j5sBcrXd/9L0EEUSmRzxEyI4kpR9q3K5@ynKC4IQzwczKb@PsXMGDPFcc0mxDZ/AA "PHP – Try It Online") - PCRE2, **31 bytes** - same as above
[Try it on regex101!](https://regex101.com/r/QsA4DK/2) - PCRE2
[Try it online!](https://tio.run/##nVJLbtswFNzrFC8CEZKGPlaXlllt6hQGiqRQuotTgqZpSzUlC6QcFHG87QF6xF7EfbKRRbPoIgQokDPDeUPqLZWvTvObewHOqBXEbgWUgptOqXzXoMG06KoOiAMBYRpCAp0zG@lMZ5U2jKbJqJCyUraXetd0tTVuwRY8X5SppxEWj2CNoNyYQdD2pu09k/Jm/mUmJY8g42iJxnlQt7X0pmdhp51Jlkpve4cfaeum7sMIwjgLeQ7/ypzRe@frXft/2Y8LNUYmWO8cI7UY58SKNcby7P7bp/ktz/kB6jUj9sH3zpoWVzzOHoUIF23IUez3S2QQjsZRnKEToB7YFSNbcX6URvW6kspaRlyEMtJwzoGYC2uV76VxDsvzKyG@lrPP8vZOzsryrrx4YSxudLUbCuaAGbMchj0Qm1D48@s3RfQZk6Mab2GUrhhpHrJHUB7IE4fDWc3IczE8/YQC5Ql5Oh/K8uNrXrKF62uMxS/mFGZDqAnQ5E1O2fgN4/nxzf9F6MQKwZIR5wljxVTgLnj5vshG5IUVHxDl/PS@fgvOkeIWQnJwk0mcHcOPercyCTZhbn4aDeneu3RZt@nQlq/USS31apiBUmqY5xEMiFn/BQ "Bash – Try It Online") - PCRE, **33 bytes**: `(?=(.*)).((?<=(?=¶|^\1*$|(?2)).))`
[Try it on regex101!](https://regex101.com/r/QsA4DK/3) - PCRE1
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ηʒKõQ
```
[Try it online](https://tio.run/##yy9OTMpM/f//3PZTk7wPbw38/z8xKTkFhAE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf/PbT816dC6Yu/DWwP/1@r8j1ZKTEpOAWElHaXExEQICQYgJlA8NU0pFgA).
**Explanation:**
```
η # Get all prefixes of the (implicit) input-string
ʒ # Filter it by:
K # Remove all occurrences of the prefix-string from the (implicit) input
õQ # Check if what remains is an empty string
# (after which the filtered list is output implicitly as result)
```
[Answer]
# [Factor](https://factorcode.org) + `grouping.extras`, ~~73~~ ~~70~~ ~~57~~ 48 bytes
```
[ dup head-clump [ ""replace ""= ] with filter ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=JYsxCsJAFET7nGKwT7AUxVpsbMRKLL6bv3FxTTY_f4kinsQmTbxTbmM0A495DMz7Y8loJd1gD_vtbrNE3aLhOnJpuMGVpWSPJnin6soCQVj1EcSVikKqGMYx47sKNVglSd0-QWeT_wAR_fjnv7LFq49q08UwPyKPARemPDU-3gKOmM2EgyfDo61xQuv0Auu8suA0_fobBWSTd93UXw)
-13 bytes and then -9 more by porting @KevinCruijssen's [05AB1E answer](https://codegolf.stackexchange.com/a/250966/97916) (and then improved version)!
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 26 bytes
```
f(g a)=a
g a|a>""=a++g a?a
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NI10hUdM2kQtI1STaKSnZJmprA9n2if9zEzPzFGwV0hSUEqFA6T8A "Curry (PAKCS) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
f s|p<-scanr(:)""s=[t|t<-p,a<-p,(a*>t)==s]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02huKbARrc4OTGvSMNKU0mp2Da6pKbERrdAJxFEaCRq2ZVo2toWx/7PTczMs01PLfHJzEu1s7MtKMrMK9FLs7MDif9PTEpOAWGuxMREEAYDLpBIahoA "Haskell – Try It Online")
`scanr(:)""s` lists the suffixes of the input `s`. For each suffix `t`, we look for a suffix `a` where repeating `t` once for each character of `a` (`a*>t`) gives the original string `s`.
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
<\#~<=<\$~&.>#+#\|#
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/bWKU62xsbWJU6tT07JS1lWNqlP9rcvk56SlAZJRVgOI2MWARXQflGI3Yaj2l6rpo5TpDW2WHOj0HDZsYTc1YrtTkjHyFNAX1xKTkFBBWR4gkJqJwwEAdRUNqmvp/AA "J – Try It Online")
* `<\$~` Cyclically extend each prefix to the following length:
+ `#+#\|#` Length of input `#` + the remainder when we divide that prefix's length into the input's length `#\|#`. This ensures non-divisible prefixes won't match.
* `<=` Which of the extended prefixes matches the input?
* `<\#~` Filter all prefixes using that mask.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 26 bytes
```
{((#(,x)^,\(#x)#,:)')_,\x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rW0FDW0KnQjNOJ0VCu0FTWsdJU14zXiamo5eJKU1BKTAJBJTATCGAMCJ2UnALCcE5qmhIXAG3CFcU=)
I guess this is somewhat a new strategy. For each prefix, tests if the original input appears in the list of 1..(length of input) repetitions of the prefix.
```
{((#(,x)^,\(#x)#,:)')_,\x} x: input string of length n
,\x prefixes
(( )')_ remove the items that give nonzero:
,\(#x)#,: repeat the prefix 1..n times
(,x)^ set minus from the singleton list of x
# is x still there?
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 6 bytes
```
sJEƇḢ€
```
[Try it online!](https://tio.run/##y0rNyan8/7/Yy/VY@8Mdix41rfl/uN1bM/L/f6XEpOQUEFbSUVBKTEyEUmAAZgOlUtOUAA "Jelly – Try It Online")
Port of my Brachylog solution.
```
s Slice the input into chunks of
J every length.
EƇ Keep only partitions with all equal elements,
Ḣ€ and return the first element of each remaining partition.
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 19 bytes
```
{(x{#,/y\x}/:)_,\x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rWqKhW1tGvjKmo1bfSjNcB0lxcaQpKiUnJKSCsBOYkJsJoMFCCqUhNUwIArVUT2w==)
`,\x` get all prefixes of the input
`... _` discard a prefix if:
`y\x` split the input by this prefix
`,/` concatenate parts into a single string
`#` length of this string is non-zero.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~53~~ 52 bytes
```
->s{(1..k=s.size).map{|x|w=s[0,x];w*k==s*x ?w:s}|[]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664WsNQTy/btlivOLMqVVMvN7Gguqaipty2ONpApyLWulwr29a2WKtCwb7cqri2Jjq29n@BQlq0UmJSMhApxXJBeGCgFPsfAA "Ruby – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~8~~ 6 bytes
```
øṖ~≈vh
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBUCIsIiIsIsO44bmWfuKJiHZoIiwiIiwiYWJjZGFiY2RcbmFhYVxuYWFhYWFhYWEiXQ==)
Port of Unrelated String's Jelly answer.
Porting Kevin Cruijssen's 05AB1E answer would be 6 bytes as well:
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
¦'?$o¬
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBUCIsIiIsIsKmJz8kb8KsIiwiIiwiYWJjZGFiY2RcbmFhYVxuYWFhYWFhYWEiXQ==)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~68~~, 58 bytes
Iterate and replace every substring starting from index 0 and check if it equals an empty string
Credit to @Acer for the syntatic sugar
```
s=>s.Select((_,i)=>s[..++i]).Where(x=>s.Replace(x,"")=="")
```
[Try it online!](https://tio.run/##lY5BCsIwEEX3niJkldCYC2iyEQOKK110ISJpHOtATCVpwdvHtHoAO/AH/vDfZ1xauoTZDMGtUx8xtGK3DcMTom08/E5aE0NUTkoneQIPrmfsKpAXf5ayqvDCZf2ACOw9Ro7w8tYVIyjlSpWVV4tNF1LnQdYRezhgAPbtlvsOA6OCCmIYtY27jaKc878Za2fGp5nFlJfgPhH5Aw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 5.5 bytes (11 nibbles)
```
|.,,$<$@~%@
```
```
|.,,$<$@~%@
, # get the length of
$ # the input string
, # and make a range 1..length,
. # now, map over these values
<$ # taking that number of characters
@ # from the input string
# (this gets the prefixes),
| # now, filter these to keep only those that
~ # are falsy
%@ # when we use them to split the input string
# (so, string-divisors yield the empty string)
```
[](https://i.stack.imgur.com/tXq1o.png)
[Answer]
# [Python](https://www.python.org), ~~65~~ 63 bytes
```
lambda s:[s[:i]for i in range(1,len(s)+1)if len(s)//i*s[:i]==s]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3HXMSc5NSEhWKraKLo60yY9PyixQyFTLzFIoS89JTNQx1clLzNIo1tQ01M9MUwCq0NCBC-vqZmra2xbFQg4ILijLzSjTSNJQSgUBJU5MLIZCUnALCWAVTMURTIQRQHGL0ggUQGgA)
A very unclever solution.
---
Saved -2 bytes from @ruancornelli.
[Answer]
# [Haskell](https://www.haskell.org/), 65 bytes
```
d s|r<-[1..length s]=[z|z<-(`take`s)<$>r,s`elem`[[1..n]>>z|n<-r]]
```
[Try it online!](https://tio.run/##FcqxCsMgEADQX3Ho0EIVuqtfkE4dRfAgRxKiR/Aui/jvNnnzW4F3zHmMWXGvVoePMRlpkVVxdKH1ZvUzCeyY@GUfvr45YcaSwj0pet86WV1jHAU2cgvKtBF67wocX3Wc8pM6kZkHXP4 "Haskell – Try It Online")
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 32 bytes
```
;=x=yP Wx;I?y*x/LyLxOxN=xGxF-LxT
```
[Try it online!](https://tio.run/##lVhrc9s2Fv3eX0FzU4sQaVrOdLoT0bQmcZ2OZx05jd1mdiUlAkFIYkORCh@2XIn719N7wReol9N8yIjAwX3h3Af8J32gMYu8RXIShC7/xnwax8p/Am86S66iKIwUvkx44MaK@FplOeA9jWLe3JfOlKgPaZB48@dxd0nE6XzFwiBOopQlYaRRskpmXmzGYRoxbtMMdrzFx5mX8HhBGdeK/TlN2Ew7/aQNhqPhYBjDetYd6et/DT4Ng1FbGwbrF4S0T0m24PwL7EY8SaNAkYQPOqP1Okh9P8uFOQazO2Tl80ShtmPyJWeaBCdWIQKP2LZNe/ijK0Ns6bcZpw7YrlFQY/o8mCYzYtABG5EsCcFxL5jutCrLRDiU@/@@v7qzByMrD9Uf1E/5Kk5o4jFlgbegOWTlmFvhsSYQxQcagQ8di54LMYV@i@p67h@zxfqAjsxSluVNNEYKe1gm@ZpFaSDCHoWPSsAfc0ZkLnfS6Y71Pd4JIWa9Cbh@Ond4tAdXbgLuTRj6nAZ7gNVuVrDqBoIRUb8iXh66DZLF6QKlG0LUZ5cmFLiWOyop2eFM8V2f2@VJ8d0EbblRLsgw/tVH8woEVTywmgaMh5Pca8mN42PJeOBj/quMAgqvQlCEZIs/JdfrbLp/OyKD1yf/G7VPjbOK8vT4GC8YZWrqvYraSOam80XlzLh05oXIz4yMMz@Z1a4c1bYeH9PGtU1lnCLjjprALCfzIo1nGq4SK0@Vq/4f1x9u@@@u@vf2KisS5trlQbLBgefcH9CTvz6P8P/OyavPEILNAAihYGx2iE0egoBNzfiIo97EA1weohyHgQJzvWmAciRPBjVmVFEzN3gPCjP4IfRcpXOE91NabtUJKtdlbfx78CUIHwPFqyxTWg3TWuNmzIULpIyvFN3vpdfQ1bdDCgEt0oWSTVIVGzWnqOtKXCnP15zRqVQ6SAY1@CD8pAmfp/5BeLsJd70H2ct6C2@icQmlqHc0mZnAm4BJUk/B732XpF7SIAgTBVTBnSjOk/IXj0IVTA3df6i7VvgjfVYfiE/9UNK3CB8P66vFr9dHGj3vkO9yvt3@Du/5chEGSFKacGGQkoRQGwM@Bb49cAWM4xEY6e@pJOfyve2tNxcNVIP4Ne370BAP816q3hXx@0VJJTnnUUijhJQVBNvtRg6oCNaIeqgzCHmF88@EkoVzMJOLI6ZaBeMfnpKDg2tldKA5PhscpJBjU6nnqK0RgTkuHt6N2j0yPDs1XgpaYTSAWY5MJNCAw0o@xFAzH@4QrLawLbH1uqW28AepXaqHVix6YNXcC4BJrvI1DYFQPGBhisvc7SovVjQb72rpwv5mHhlnHbJedzZqVjEgHKpZ6MS4ABQKt0sPgmpdZsQXnELvkSvQM4yvRq2DjK9Q8qXCYtFd4RR1754C1qWZHfGvqRdxTZ3EKjFWOCKLLUfaYjPPdz8vopDxGFFvf@9f3l/f9u/q3vwWasCh1iyxJL9gmMwrMQNH6nTipqVZ1ZJ41euKrNPXJjnNGcNxnsb5GD9cmI/dc1bOxm45G09sYZFZmoLKjiZ76PTOg94dTBUaTdM5DhwvVq5@limgRJmgl9BRHWykFs8DOyGZdMcYCI0ZjsE3RgpYYhtjBYqzaf47oHNuO/lvUB3bbHt2FQc00zQrVFVZ8iquovbECwNN1SupVXgcpRw5xVGq26qhqLpj5jKqLq6rW7Xp1vmTs8T0YsFfA8albFKoUiI@9eKECxfJCkJ7hr2qfCBtvCU0tQ8mKfMUhjwHEnVJWeI/KdALFDajEXzBzOKHwRRqklUThI5sR9IIgak6l3y1RZLBC1RzpDwgcu2px6j8vWHtpIHaD5UHlAyFMvVdtFWocI@gVkpZhQEnRhUC9b1qaMS@KJ5kqmo49pt0MuGRSX0/ZBoM4G6IQaJaBxjRgYncAMo78KQkDhj@xWI6uPoIGce1M@jCYke85EzMrY8eJL46DFRCmM3M2PfghdgxlJN6si8rDSOZbNmH3LJG6574Ifj608tXP736@d8vX/3cFqsRDdxwjmGTz1@pBrUvMGS0Edoa0nrdQkiV6Hl4C6scubuBAb3SzFySOYnC@SUw4DJ0YdAs3k6kW5orX6fJCtzrBGc22cg3wkgqL13mS8XjUvwvb4/FdtWHms7tcVT9TRwqCqLJl95mFZewR5UC8dZqPoAayJsKiR7LhpTJJKN/QW5dVONbI9ilZXHihmliPkbQuEFgnufEoI2Y3TYF1VoLaepwKJ6H5Z8/gGq9PQoKRMco0x@wpLsTPMYu@cOYGNX0JNukA1mxnNQXhy238LIRhpMtJL4QdiHbW0js0LuQp1tI8S7YgfxxW2a4285PW0gxf@9AnlfIijTlEZwNqiPymYv9Z6b7zvT2n8Hiv/PMcXVGo2WGN/5i0yuOdRs5uH72GO0627lpScfyXWNXwGwJ1qgy@Lhdr0Gl9NBvpjQ1i5e6Y1f6nYbwj5XwFfZRq5G@FtlIvJ1kvs5FQPu3L@jOYLFt33@VDomg1XYbTuO5ZmAjkD7LWlalIwpZr1W1GbW7QoErVJSHnlHl2u625gpcZj0O@D2qw3xZVwSH6EyvTdJd7Mp16/h/S659zUc84CA642@WvbSf3isfl9Z176m9PL15ulneLvv28tfl25Ob5f23MbxFPWxc1jda/Pvhbw "JavaScript (Node.js) – Try It Online")
```
; = x (= y (PROMPT)) # x = y = input()
: WHILE x # while x != "":
; IF (? y (* x (/ (LENGTH y) (LENGTH x)))) # if y == x * (len(y) / len(x)):
: OUTPUT x # print(x)
: NULL # else: (do nothing)
: = x (GET x 0 (- (LENGTH x) 1)) # x = x[:-1]
```
[Answer]
# [Python 3.8](https://www.python.org), 56 bytes
*-7 bytes thanks to user `loopy walt`*
```
lambda s,d='':[d for c in s if len(s)//len(d:=d+c)*d==s]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY37XMSc5NSEhWKrTRSrGzV1TXzi6JTFNLyixSSFTLzFIoVMtNAEinayZpaGjmpeRrFmvr6IDpFU9PWtjgWaowjSEcxSEe0emJScgoIq-soqCcmJkIpMACzgVKpaeqxVlwKCgVFmXklGmlAQzUhBi1YAKEB)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 43 bytes
```
->s{(s+?␀+s).scan(/(?=(.+)␀\1*$)/).flatten}
```
[Try it online!](https://tio.run/##PYtLDoIwGIRZc4ofNDwECrhtKgcBFgVbJakNoSUGjFsP4BG9CFJMnGRmMTPfMDbTwsmSnNQjUFFhRSpEqqUySIOCBCgKrSo/7MM0RFxQrZl8LjPJMNyvnWAgyIVpZQN0HGbH9P2oFQYmzxhmkmMziDLJa0LcSrp4JUSZIZQc6@31Qx2B2K3XUwGet96z2iH@zl83gH7opAYRgwuf1xvcGHgp/uyaC23as7FNKTXeZJuG8S8 "Ruby – Try It Online")
This concatenates the string to itself with a NUL (ASCII 0) character between, in order to use a regex to find all matches' `\1` captures. Since Ruby does not have variable-length lookbehind and can't emulate it with recursion, this approach couldn't work on the unmodified string.
Since this does a manipulation on the input before working on it, thus departing from my idea of what a pure regex is, I'm posting this as a separate answer.
# [Ruby](https://www.ruby-lang.org/), ~~35~~ 34 bytes
```
->s{(s+?␀+s).scan /(?=(.+)␀\1*$)/}
```
[Try it online!](https://tio.run/##PYtLDoIwGIRZc4ofNDwECrhtKgcBFgVbJamE0BIDxq0H8IheBFtMnGRmMTPfODXzysmanOQjkFFhRTJEsqU9pEFBAhSFVpUf9mH6XBeSYbhfO8FAkAtT0gboOCyO6YdJSQysP2NYSI7NIMokrwlxq97FmhBlhlByrLfXD3UEYrdBzQV4nr5ntUP8na83gGHsegUiBhc@rze4MfBS/FmdK23as7FNKTXeZJuG8S8 "Ruby – Try It Online")
If it is acceptable to return the output as a list of one-element string lists, then this answer can be even shorter. This returns, for example, `[["abcdabcd"], ["abcd"]]` instead of `["abcdabcd", "abcd"]`.
# [Ruby](https://www.ruby-lang.org/), ~~50~~ 47 bytes
```
->s{(s+s).scan /(?=(.+)(?=.{#{s.size}}$)\1*$)/}
```
[Try it online!](https://tio.run/##PYtNCoMwFIT3nuL5gz9Vo3YbUg@iLqImrZCKGKWouO0BesRexCYt9MG8gZn5xrleDk6O@CI3X4YyQLKhPSR@TnwUBsrQZm8SyW5l@@4EZXZygmQ/VpJieNw6wUCQK5ukAdBxWE2dD/MkMbC@xbCSDOtCFHFWEWKVvYUVIYoUofhcfVc/1BSI3YdpycF11TytTOLZnuoAhrHrJxARWPB@vsCKgBfiz6p/0LpptQxKqdb3DJ0w/gE "Ruby – Try It Online")
This approach works even on strings containing NUL(s), as it uses the length of the string (rather than a delimiter) as a marker. As with the 35 byte solution above, it returns a list of one-element string lists.
[Answer]
# [Raku](http://raku.org/), 25 bytes
```
{~«m:ex/^(.+)$0*$/»[0]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/uu7Q6lyr1Ar9OA09bU0VAy0V/UO7ow1ia/8XJ1YqKKnEK9jaKVSnKajE1yoppOUXKdgkJiWngLBCYmIiCIOBAkgkNc3uPwA "Perl 6 – Try It Online")
`m/^(.+)$0*$/` looks for patterns of letters which, repeated, comprise the entire string. The `:exhaustive` flag on the match operation (shortenable to `:ex`) looks for every possible match, not just one. Then `»[0]` extracts just the first submatch (ie, the divisor) from every match, and `~«` stringifies each of those match objects.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 17 bytes
```
&!`(.+)$(?<=^\1+)
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX00xQUNPW1NFw97GNi7GUFvz///EpOQUEOZKTEwEYTDgAomkpgEA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
&!`
```
List all overlapping matches.
```
(.+)$
```
Match any suffix...
```
(?<=^\1+)
```
... which can be repeated to recreate the original string.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
fȯEC¹Lḣ
```
[Try it online!](https://tio.run/##yygtzv7/P@3EelfnQzt9Hu5Y/P///8Sk5BRkDAA "Husk – Try It Online")
```
ḣ # get the heads (prefixes) of the input
f # filter these to keep only truthy by
ȯ # result of 3 functions:
C¹ # cut the input into pieces
L # with the length of each prefix
E # and check if they're all equal
```
**Alternative, also 7 bytes**
```
foE`x¹ḣ
```
[Try it online!](https://tio.run/##yygtzv7/Py3fNaHi0M6HOxb///8/MSk5BRkDAA "Husk – Try It Online")
```
foE`x¹ḣ
ḣ # get the heads (prefixes) of the input
f # filter these to keep only truthy by
o # result of 2 functions:
x # split on given substring
` # (with reversed arguments)
¹ # the input
# (note that first element will always be empty list
# when splitting using a prefix)
E # and check if they're all equal
# (which will only be the case if all are emty lists,
3 meaning that the input was a multiple of the substring)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
ΦEθ…θ⊕κ№Eθ×ι⊕μθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMtM6cktUjDN7FAo1BHwbkyOSfVOSMfzPHMSy5KzU3NK0lN0cjW1NQESueXArVA1YZk5qYWa2SiqssFqysEktb//ycmIeB/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input string
E Map over characters
θ Input string
… Truncated to length
κ Current index
⊕ Incremented
Φ Filtered where
θ Input string
E Map over characters
ι Current prefix
× Repeated by
μ Inner index
⊕ Incremented
№ Contains
θ Input string
Implicitly print
```
[Answer]
# [sed](https://www.gnu.org/software/sed/) `-n`, ~~58~~ 46 bytes
```
s/^/\n/
:a
/^\(.*\)\n\1*$/P
s/\n\(.\)/\1\n/
ta
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlWbSSbp5S7IKlpSVpuhY39Yr14_Rj8vS5rBK59ONiNPS0YjRj8mIMtVT0A7iKgTJAoRhN_RhDkJqSRIguqOYFexKTklNAmCsxMRGEwYALJJKaBlEDAA)
[Answer]
# Rust, ~~108~~ 106 bytes
-2 bytes thanks to alephalpha
```
|a:&str|(1..=a.len()).map(|k|a[..k].repeat(1)).filter(|z|z.repeat(a.len()/z.len())==a).collect::<Vec<_>>()
```
[Playground Link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0cfe163a5bcc88f1c5713a5a83a48b0a)
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 12 bytes
```
he<<fl lq<pt
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FNxczcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRMDS0pI0XYt1abYZqTY2aTkKOYU2BSUQwe25iZl5tgVFKmlKiUkIqASRXbAAQgMA)
## Explanation
* `pt` gets all ways to partition the input into non-empty lists
* `fl lq` filters out all items with duplicates
* `he` takes the first value in each result
## Reflection
* A function that gives partitions satisfying a predicate would be immensely useful here. This could be `he<<pST lq`
* Similarly we should add a function that gives all partitions where the elements satisfy a predicate.
* A function that gives all permutations with equal size would not save any bytes here, but it would make this answer a lot faster to run and would probably be useful in the future.
* `ƥ`, `mP`, `ms` and `mS` all need flipped versions.
* A prefix and suffix filter would be useful. There are currently functions to get the longest suffix/prefix satisfying a predicate but not all.
* Shortcuts to check if a list has a particular length would be useful. There are already ones for checking if it is less than or greater than a value.
[Answer]
# [Arturo](https://arturo-lang.io), 56 bytes
```
$[s][select map 1..size s=>[take s]'y->""=replace s y""]
```
[Try it](http://arturo-lang.io/playground?XaVqot)
[Answer]
# [Zsh](https://www.zsh.org/), 47 bytes
```
for c (${(s..)1})s+=$c&&[[ $1 = ($s)# ]]&&<<<$s
```
[Try it online!](https://tio.run/##qyrO@F@cWpJfUKKQWlGSmpeSmpKek5/ElZJZpqGpAZRR0K34n5ZfpJCsoKFSrVGsp6dpWKtZrG2rkqymFh2toGKoYAuUKdZUVoiNVVOzsbFRKf6vyQXSr5CYlAxBEB4YwCRSUtPATKCZOdHGZrHRubGatagieYlAof8A "Zsh – Try It Online")
Fairly straightforward:
```
for c (${(s..)1}) # (s)split $1 on '' (into characters)
s+=$c && # append character to $s
[[ $1 = ($s)# ]] && # if $1 equals $s repeated
<<< $s # output $s
```
[Answer]
# [Perl](https://www.perl.org/) `-p`, 22 bytes
```
/^(.*)\1+$(??{say$1})/
```
[Try it online!](https://tio.run/##K0gtyjH9r1JsqxJvrZCckZ9boKBSbK1QUJSZV6KgFJOnUmwVk6dk/V8/TkNPSzPGUFtFw96@ujixUsWwVlP////EpOQUEOZKTEwEYTDgAomkpv3LLyjJzM8r/q/ra6pnYGjwX7cAAA "Perl 5 – Try It Online")
This uses a "postponed" regular subexpression embedded code block to accomplish the same thing as Raku's `ex`haustive verb (which is used in [Sean's answer](https://codegolf.stackexchange.com/a/250979/17216)), enumerating all possible matches, not just the ones (the one, in fact) that would be found normally.
Once a match of `^(.*)\1+$` that *would* be successful finishes, the embedded code block is triggered, and `say$1` prints the value of the `\1` capture group. Since it's of the "postponed" type, it then dynamically compiles the result of `say$1` (which is the boolean `1`) into the regex, causing the match to fail, since `1` can never occur after the end of a string. A literal `1` placed after the `$` would cause the match to fail and give up, due to Perl's regex optimization. But since it's *dynamically* compiled into the regex, the result of executing a piece of code, Perl doesn't *know* that it will be `1` every time, so it actually allows the regex to backtrack and try other possible matches.
The regex is intentionally set to not let `\1` match the entire input string, only strict substrings. `^(.*)\1*$` would be the version that would also match the entire string. But that is left out, because once the program finishes, Perl's `-p` flag causes `$_` to be printed. That way, all of the string's divisors, including itself, are outputted.
Embedded code capability is a rare thing in regex engines. As far as I know, the only ones that have it are Perl and Raku (embedded code blocks) and PCRE (callouts). It [appears that MATLAB](https://www.mathworks.com/help/matlab/ref/regexp.html) allows execution of MATLAB code inside a regex, but I have not tested that yet (and am not sure if GNU Octave, which uses PCRE, has that functionality, or if MATLAB even also uses PCRE).
Another thing to note is that inputs followed by a newline (rather than EOF) will have that newline included in the contents of `$_`, and this program doesn't use `chomp`. But that doesn't matter, since `$` matches both the true end of string, and the position immediately before a newline at the end of the string, if there is one. This is the case regardless of whether the `m`ultiline flag is enabled (which it is not, by default). This is a case where that behavior (as opposed to `\z`, which strictly matches the end of string) is helpful.
# [Perl](https://www.perl.org/) `-n`, 22 bytes
```
/^(.*)\1*$(??{say$1})/
```
[Try it online!](https://tio.run/##K0gtyjH9r1JsqxJvrZCckZ9boKBSbK1QUJSZV6KgFJOnUmwVk6dk/V8/TkNPSzPGUEtFw96@ujixUsWwVlP////EpOQUEOZKTEwEYTDgAomkpv3LLyjJzM8r/q/ra6pnYGjwXzcPAA "Perl 5 – Try It Online")
This is really the more logical version, printing the divisors in a consistent order. But I'm keeping the `-p` version up here, since `-p` is much more commonly used in answers, and as the way flags are treated (as distinct languages, in a certain abstract way) it lets it be in the same playing field as those `-p` answers. Not to mention that the workaround it uses is kind of fun.
] |
[Question]
[
**Problem:**
Find the number of leading zeroes in a 64-bit signed integer
**Rules:**
* The input cannot be treated as string; it can be anything where math and bitwise operations drive the algorithm
* The output should be validated against the 64-bit signed integer representation of the number, regardless of language
* [Default code golf rules apply](https://codegolf.stackexchange.com/tags/code-golf/info)
* Shortest code in bytes wins
**Test cases:**
These tests assume two's complement signed integers. If your language/solution lacks or uses a different representation of signed integers, please call that out and provide additional test cases that may be relevant. I've included some test cases that address double precision, but please feel free to suggest any others that should be listed.
```
input output 64-bit binary representation of input (2's complement)
-1 0 1111111111111111111111111111111111111111111111111111111111111111
-9223372036854775808 0 1000000000000000000000000000000000000000000000000000000000000000
9223372036854775807 1 0111111111111111111111111111111111111111111111111111111111111111
4611686018427387903 2 0011111111111111111111111111111111111111111111111111111111111111
1224979098644774911 3 0001000011111111111111111111111111111111111111111111111111111111
9007199254740992 10 0000000000100000000000000000000000000000000000000000000000000000
4503599627370496 11 0000000000010000000000000000000000000000000000000000000000000000
4503599627370495 12 0000000000001111111111111111111111111111111111111111111111111111
2147483648 32 0000000000000000000000000000000010000000000000000000000000000000
2147483647 33 0000000000000000000000000000000001111111111111111111111111111111
2 62 0000000000000000000000000000000000000000000000000000000000000010
1 63 0000000000000000000000000000000000000000000000000000000000000001
0 64 0000000000000000000000000000000000000000000000000000000000000000
```
[Answer]
# x86\_64 machine language on Linux, 6 bytes
```
0: f3 48 0f bd c7 lzcnt %rdi,%rax
5: c3 ret
```
Requires Haswell or K10 or higher processor with `lzcnt` instruction.
[Try it online!](https://tio.run/##S9ZNT07@/19DK01TQ9NWKabCzTimwsQipsLALabCySWmwtkciI2VrLlyEzPzNDSruQqKMvNK0jSUVFNi8pR00jQMfTQ1rTFEDcCitf///0tOy0lML/6vW5VakZpcXJKYnA0A "C (gcc) – Try It Online")
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), ~~78~~ 70 bytes
```
2"1"\.}/{}A=<\?>(<$\*}[_(A\".{}."&.'\&=/.."!=\2'%<..(@.>._.\=\{}:"<><$
```
[Try it online!](https://tio.run/##BcFBDkAwEAXQs5jQNha/WMq09BwmaSyEFVvSzNnrvet49/O5v1onGkmgvmgKLEt03EqvW3ZJCEVBBlZM8AA1QSbbMeBWRGRIkKIzceS21uEH "Hexagony – Try It Online")
Isn't this challenge too trivial for a practical language? ;)
side length 6. I can't fit it in a side length 5 hexagon.
### Explanation
[](https://i.stack.imgur.com/3azaW.png)
[Answer]
# [Python](https://docs.python.org/2/), 31 bytes
```
lambda n:67-len(bin(-n))&~n>>64
```
[Try it online!](https://tio.run/##ZYu7CsJAEEX7@YpUkhSBmdnZeQj6JTaKioG4BomIjb8etxO0uofDudNrvtwKL@fNbhn318Nx35S1Wj@eSnsYStuXrlu9y3arsjwvw3hqaD3dhzI353Yo02Nuu27pCfpgTskYk3oWs@zo8O8MRInUFcmFLbkFJiBmiUrhKrWTIIJANIrgehSsC5Ix5QitL0MJ/RUZmGrrScW/aMBAgB8 "Python 2 – Try It Online")
The expresson is the bitwise `&` of two parts:
```
67-len(bin(-n)) & ~n>>64
```
The `67-len(bin(-n))` gives the correct answer for non-negative inputs. It takes the bit length, and subtracts from 67, which is 3 more than 64 to compensate for the `-0b` prefix. The negation is a trick to adjust for `n==0` using that negating it doesn't produce a `-` sign in front.
The `& ~n>>64` makes the answer instead be `0` for negative `n`. When `n<0`, `~n>>64` equals 0 (on 64-bit integers), so and-ing with it gives `0`. When `n>=0`, the `~n>>64` evaluates to `-1`, and doing `&-1` has no effect.
---
**[Python 2](https://docs.python.org/2/), 36 bytes**
```
f=lambda n:n>0and~-f(n/2)or(n==0)*64
```
[Try it online!](https://tio.run/##ZYtLasNAEAX3fQotpYBId09PfwzyXWQUIYEzFkYheOOry7MLxKtXFPW2x77cCh/HPFzH78s0NuVUzjiW6dnPbfnk7nZvyzBg96Fy/C7r9auh03Zfy97M7Vq2n73tuqMn6IM5JWNM6lnMsqPDuzMQJVJXJBe25BaYgJglKoWr1E6CCALRKILrUbAuSMaUI7S@DCX0v8jAVFtPKv6HBgwE@AI "Python 2 – Try It Online")
Arithmetical alternative.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 14 bytes
```
__builtin_clzl
```
Works fine on tio
# [C (gcc)](https://gcc.gnu.org/), ~~35~~ 29 bytes
```
f(long n){n=n<0?0:f(n-~n)+1;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NIyc/L10hT7M6zzbPxsDewCpNI0@3Lk9T29C69n9uYmaehmZ1QVFmXkmahpJqioKSTpqGhaamNUIIJGIAFKn9DwA "C (gcc) – Try It Online")
Than Dennis for 6 bytes
# [C (gcc)](https://gcc.gnu.org/) compiler flags, 29 bytes by David Foerster
```
-Df(n)=n?__builtin_clzl(n):64
```
[Try it online!](https://tio.run/##ZYzLTsMwEADv@YpVEVJMG@RX/KAtXPgLqKLUIakl46A05QDi11mWXhBw2tHs7IZqCAEvYg7p1D3B5jh3Ke6vD7fFLxdHUogxz/Dcxlx@QzsNYQXh0E5wRfz6sGPFewHQjxOcgwhbEGsam3NLtFwyCgBeJtr35eKye8yLFfRlO4@pPD@JO8bYuvhArARWXkqlrOTKuFpbWzvu8L@zqI0QxhkunJZWOeu5QiGl9kTeGU2d9kKg59wK7yUdak4Tdc1V7b2hK8u1N39FjVJQ65TR7gctShTIP0Of2uGI1X1fZrbNd02zP8U0x9yE9JbI3Rj9BQ "C (gcc) – Try It Online")
[Answer]
# Java 8, ~~32~~ 26 bytes.
`Long::numberOfLeadingZeros`
Builtins FTW.
-6 bytes thanks to Kevin Cruijssen
[Try it online!](https://tio.run/##bZDBboMwDIbP5Sl8BGlFCQSSlHXHSZO67dDbph1SGmg6CAhCu2rqs7Mg0Wpq8cX2b3@2k704iPl@@92rsq4aA3ub@51Rhb9OhdaySZy7Stbp1KhK@89jkDhO3W0KlUJaiLaFV6E0/DpgbdRbI4x1h0ptobRVd20apfPPLxBN3npj83@7zH5cVTp/gBdtZC6bJ8hg2Q/SYqG7ciOb92wlxdbO@pBN1fa3YxJnNhtfAu3ol6DlEUbVXZ9aI0tfac8@4xY/7lQhwR1JfyfaN/ljhv2uN3X1YIWtgrZbLpS@IskkMF5Qdcav7a@YQruZL@q6OLnam2DOznR27ucY5jwIwpAGKIxZRCiNGGJwr1EgMcYxixFmJKAhoxyFgIOAcBtxFhPbRzjGwBGimPPAggRZDyRCYcR5bCmKCI/hVokgwLaZhTFhw13XjNoYMKA/ "Java (JDK) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 25 bytes
Takes input as a BigInt literal.
```
f=x=>x<0?0:x?f(x/2n)-1:64
```
[Try it online!](https://tio.run/##fdFLbsIwEAbgfU@RZbJIMy@PZ1ApZ0GUVK2QgwBVuX3qBQjkQLzx5tP88/jd/m3Pu9PP8dKm4Ws/Tf16XH@OH7CB1bjp67Gj1LS4Upl2QzoPh/37Yfiu@7rFVM1e01RdV8FbQZ2IORKwWpAYg4Gl53QuY7pWxYKKIqopoAlFtujAN0oFRSLxDNxUclVxxBvlsgGAiO6U0wXyn@5jYdmsBODgrjk@grg@Wly24dGW7RLmcGMVS@Vq@aWNc1vORk8udrU6W9mCLevCgpXpHw "JavaScript (Node.js) – Try It Online")
Or [**24 bytes**](https://tio.run/##fdHNbsIwDAfw@56iJ9QeutqO49iTgGdBjE6bUIoATX37LgfQkAvNJZef/PfHz@53d9mfv0/XNg@fh2nq1@N6M27HDaxWfT12lJsWP4Sn/ZAvw/Hwfhy@6r5uMVez1zRV11Xw5qgRhZAIgmjklKKC5ud0LlO@VUVHWRBFBVCZUtBkEO6UHEUitgJMhUtVNsQ7Db4BgIRmVNIZyp//x0LfLEcI0UxKfAI2ebS4bOOj9e0SlnANwpr9asNLm@bWz0ZPLnazMlvZgvV1YcHy9Ac) by returning *false* instead of \$0\$.
[Answer]
# [Python 3](https://docs.python.org/3/), 34 bytes
```
f=lambda n:-1<n<2**63and-~f(2*n|1)
```
[Try it online!](https://tio.run/##ZYtLasNAEAX3OcUsJdGC/k1/jHMYGSMscMbGeGMIuboyu0C8ekVR7/56Xm5N9n39vC5fp/NS2mGmYzvyNJks7Tz/rANP7ZvGfb09yla2VmaCOZlFnFEsqrrXwIB356BGZGFIoewSnihAzJqdMkx7p0kEieiUyf2o2Be0otRM6y9HTfsvKjD1NsQ0/tCBgQAPH6XcH1t7DuuwjeP@Cw "Python 3 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
0{[:I.1,~(64$2)#:]
```
[Try it online!](https://tio.run/##dY5BCsJADEX3PUVQoRZqSTKZTFLoATyDuBKLuHHRpejVx9l0NsVVwvvk/TzzvEwDIIyAGd@X8TxQ/z2qHLjbj9fcNbsB2nkaWujhM8K8NM399njBDCeqmzOHkBiDWpSUoqGt2TZKayRKpKZIJpyCJcewRsQsXoCbSrkSp1rmiIncudgEy6y2iCG6a1ElFNc/PK6cqQgsqNiG1A@rvLZj/gE "J – Try It Online")
# [J](http://jsoftware.com/), 19 bytes
```
1#.[:*/\0=(64$2)#:]
```
[Try it online!](https://tio.run/##dY4xDsIwDEX3nsKiSKUIiu04jl2pJwEmRIVYGDpz9pClWSomW@/L7/ud52UaAGEEzNQO1/F4ueF0UNlz34733De7Abp5Gjo4wXeEeWma5@P1gRnOVDdnDiExBrUoKUVDW7NtlNZIlEhNkUw4BUuOYY2IWbwAN5VyJU61zBETuXOxCZZZbRFDdNeiSiiuf3hcOVMRWFCxDakfVnltx/wD "J – Try It Online")
## Explanation:
```
#: - convert
] - the input to
(64$2) - 64 binary digits
= - check if each digit equals
0 - zero
[:*/\ - find the running product
1#. - sum
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 18 bytes
*-2 bytes thanks to Jo King*
```
64-(*%2**64*2).msb
```
[Try it online!](https://tio.run/##rdNRb4IwEAfw936Ke9kEFL22x7WNWeb3mD7opomJzkWezLLPzi4bEzJIMOC9FNLml7s/5WN7PnBxvMDjDp6gYEqj5MEkCVNi4ukx3xRztTudITrs37d5DJ8KQE4v1nJ6@no6bqLZMn1evo1n8VzJXr6@wC5arF9wFU9GsM9hNBnLq16pryLV0Cz8e9ADS6XBGGudQcs@I@cyj77G47BSTd2Jeh1jaPfEWrNn1J6Ms94FtADmyg/0lTaGgqDBM0n3FLS0bisef/LpzQdEp0MwkgyhrGXkFV9Wv6@gKEObhcCSjEMKXF6YBt/P/89nv7xp8r0CUkZLKt4y@dq9t218W3WNVPGuztsbeezsvuWnBb61@67ZlG7l7V141ApbeboPj98 "Perl 6 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 22 bytes
```
->n{/[^0]/=~"%064b"%n}
```
[Try it online!](https://tio.run/##bY69CsJAEIR7n0ICKUP27/aniC8SYpEiZRDBQkRf/Ty8q9RqmB3mm73e1nvepjyc9sc4n2EZp1fXg8ra9fszX47bPOBy@GgQMRsBqycxSw5ek9/AaiCKqK6ALmTsFsA1QCKJYsNVSkMC20gAGEZQ4QgUbZwEnCK0QAwk9O811SthqTqr@JdvPzVk24MlvwE "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
·bg65αsd*
```
I/O are both integers
[Try it online](https://tio.run/##yy9OTMpM/f//0PakdDPTcxuLU7T@/zcxMzQ0szAzMLQwMTI3tjC3NDAGAA) or [verify all test cases](https://tio.run/##ZYu7CQJREEXzqWLZUFyY35tPtImNuChiZLAgLBhbgJ0YmVuARdjI82WCRvdwOPc0b6fjvl7Oy9h37@ut68dlU5@P6WDldZ93q7quA8GQzCLOKBZF3UtgwL9zUCOyMKRQdglPFCBmzUYZpq3TJIJEdMrkdlRsC1pQSqa1l6Om/YoCTK0NMY0vOjAQ4Ac).
**Explanation:**
```
· # Double the (implicit) input
# i.e. -1 ‚Üí -2
# i.e. 4503599627370496 ‚Üí 9007199254740992
b # Convert it to binary
# i.e. -2 → "ÿ0"
# i.e. 9007199254740992 ‚Üí 100000000000000000000000000000000000000000000000000000
g # Take its length
# i.e. "ÿ0" → 2
# i.e. 100000000000000000000000000000000000000000000000000000 ‚Üí 54
65α # Take the absolute different with 65
# i.e. 65 and 2 ‚Üí 63
# i.e. 65 and 54 ‚Üí 11
s # Swap to take the (implicit) input again
d # Check if it's non-negative (>= 0): 0 if negative; 1 if 0 or positive
# i.e. -1 ‚Üí 0
# i.e. 4503599627370496 ‚Üí 1
* # Multiply them (and output implicitly)
# i.e. 63 and 0 ‚Üí 0
# i.e. 11 and 1 ‚Üí 11
```
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
Thanks [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for spotting a mistake!
```
f n|n<0=0|1>0=sum.fst.span(>0)$mapM(pure[1,0])[1..64]!!n
```
Might allocate quite a lot of memory, [try it online!](https://tio.run/##JcqxDoMgFIXhvU9xTTpgouQCKjQpvkGfgDAwaGoqhIhuvju1dPnOcP63S59pXXOeIZzhiRpPNqJOh6dz2mmKLpAR67t38UXisU2GNWhrwygdOltVIXu3BNDwC4DEbQk7nesbgIGWXdNA@@BcCMlRDKrvpOwVqnIMRV78p3hp8xc "Haskell – Try It Online")
Maybe you want to test it with a smaller constant: [Try 8-bit!](https://tio.run/##y0gszk7Nyfn/P00hrybPxsDWoMbQzsC2uDRXL624RK@4IDFPw85AUyU3scBXo6C0KDXaUMcgVjPaUE/PIlZRMe9/bmJmnoKtAkheQaOgKDOvRC9Nk0tBIVpB1xhI6SjoGoIpAzAJYRuBSTOIiJE5kI79DwA "Haskell – Try It Online")
## Explanation
Instead of using `mapM(pure[0,1])[1..64]` to convert the input to binary, we'll use `mapM(pure[1,0])[1..64]` which essentially generates the inverted strings \$\lbrace0,1\rbrace^{64}\$ in lexicographic order. So we can just sum the \$1\$s-prefix by using `sum.fst.span(>0)`.
[Answer]
# Powershell, 51 bytes
```
param([long]$n)for(;$n-shl$i++-gt0){}($i,65)[!$n]-1
```
Test script:
```
$f = {
param([long]$n)for(;$n-shl$i++-gt0){}($i,65)[!$n]-1
}
@(
,(-1 ,0 )
,(-9223372036854775808 ,0 )
,(9223372036854775807 ,1 )
,(4611686018427387903 ,2 )
,(1224979098644774911 ,3 )
,(9007199254740992 ,10)
,(4503599627370496 ,11)
,(4503599627370495 ,12)
,(2147483648 ,32)
,(2147483647 ,33)
,(2 ,62)
,(1 ,63)
,(0 ,64)
) | % {
$n,$expected = $_
$result = &$f $n
"$($result-eq$expected): $result"
}
```
Output:
```
True: 0
True: 0
True: 1
True: 2
True: 3
True: 10
True: 11
True: 12
True: 32
True: 33
True: 62
True: 63
True: 64
```
[Answer]
# Java 8, 38 bytes
```
int f(long n){return n<0?0:f(n-~n)+1;}
```
Input as `long` (64-bit integer), output as `int` (32-bit integer).
Port of [*@l4m2*'s C (gcc) answer](https://codegolf.stackexchange.com/a/177291/52210).
[Try it online.](https://tio.run/##fZFNTsMwEIX3PcWoK0dRqvFP/EORuACsukQsQptULqlTJU4lVIUlB@CIXCSYEAksECtr5vl9Hr85FOciO@yexm1ddB3cFdZdFgCdL7zdwmidh4rUjduDSy5t6fvWgbvGG7yqiMteXJLS9TAGx6l/rINjNp4bu4NjgJGNb63b3z9AkXyCAXzZeZLR22T9ozSMca4YcqlzoVSuUUcXfusq0oWkVGqJVAumuFYGeaRTxoQJXaOlCH5haDyAQVTUGBbgAsMZw3PkuTEykBUKI/8T80hkNPA0l0L/3Y4/Eb8aD4hf1bD4Xs6U8SRO@7FzvpvnzpfHVdP71SlE72tHbLqE99c3WKYVsckMGsYP)
**Explanation:**
```
int f(long n){ // Recursive method with long parameter and integer return-type
return n<0? // If the input is negative:
0 // Return 0
: // Else:
f(n-~n) // Do a recursive call with n+n+1
+1 // And add 1
```
---
EDIT: Can be **26 bytes** by using the builtin `Long::numberOfLeadingZeros` as displayed in [*@lukeg*'s Java 8 answer](https://codegolf.stackexchange.com/a/177304/52210).
[Answer]
# APL+WIN, 34 bytes
```
+/×\0=(0>n),(63⍴2)⊤((2*63)××n)+n←⎕
```
Explanation:
```
n←⎕ Prompts for input of number as integer
((2*63)√ó√ón) If n is negative add 2 to power 63
(63⍴2)⊤ Convert to 63 bit binary
(0>n), Concatinate 1 to front of binary vector if n negative, 0 if positive
+/√ó\0= Identify zeros, isolate first contiguous group and sum if first element is zero
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 42 bytes
```
x=>x!=0?64-Convert.ToString(x,2).Length:64
```
[Try it online!](https://tio.run/##ZVA9T8MwFJzxr3C3RHIif8UfLSkDElO3IjEghsoyqaXiSLapghC/PTgNAQRveffu3t1wJlYmuvHu1ZvrU@875HzaQgNbOA7tdli1@Ebw6rb3ZxtSfd/vU3C@KwZEy3pnfZeOa8HHDQCT@fEJJhuTDTH73yuCQKUpZUxSzIRquJSNwgrBrwH/RQkXFXBBiFACE8WpZEpqzCAChFKuM9ZK8GzhmhD4KxBjSbSmOY3jvCcSTVkNZo3WIgdJzLWY@b90s7xTkv2KCa7mXPTDyPmEi0C@Ef7ILTz3wR7MsTgfwqWKCJ1fOinB1f4to5c61xn7k60fgkt257wtTHH5LsvN@Ak "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), 31 bytes
```
int c(long x)=>x<0?0:c(x-~x)+1;
```
Even shorter, based off of [@l4m2's C (gcc) answer.](https://codegolf.stackexchange.com/a/177291/52210)
Never knew that you could declare functions like that, thanks @Dana!
[Try it online!](https://tio.run/##ZZA/T8QwDMVn8ik8tqI92UmaP1cOBlY2BgbEcIoCRLpLpaZCRQi@ekmvFBB48fN79m@wS7VLYZpCHMAVhy4@wVjuLscLvMKtK8b6YyzPqZ0Ym7P7Bxh8GnyfYAdvNVWstpwLoTkKZRqpdWPQVPBV7H@oYU2ZVETKKCQjuRZGWxRQMeJc2qytUTKfSEsEv4CImqzlmSYx99msZlaDorFWZZBGadXi/7WbdZ1TvjdCSbNwqx9HLyOsAX0rfG8Ze@x6v3fPxcu@P70iQYjrT0p2dvua1XFz3cXUHfzmrg@DvwnRF644bZdlO30C "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 10 ~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to a neat trick by Erik the Outgolfer (is-non-negative is now simply `AƑ`)
```
ḤBL65_×AƑ
```
A monadic Link accepting an integer (within range) which yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8///hjiVOPmam8YenOx6b@P//fxNTA2NTS0szI3NjcwMTSzMA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##ddA7TgNBDAbg3qeIlHYi@TV@lEmdGyBERYNyAVoaaiouQJkDpF8p90guMhmxQgvLZhpL88m/bL88Hw6vrV1OX7u91afhc3v@aMP79e3Y2gNsqKwW3nqFsElmEWcUi6ruNTDKSP/Fy3cXgRqRhSGFskt4oozEQMya/SPDtHdpEo0kkIhOmdzTFHstP2MQglaUmmk9zlHTJqO51ckYmHpYiGmUv6vJL/O5CfDiRbpZX@GuCeBdU3i8AQ "Jelly – Try It Online").
---
The 10 was `·∏§BL65_…ì>-√ó`
Here is another 10 byte solution, which I like since it says it is "BOSS"...
```
BoṠS»-~%65
```
[Test-suite here](https://tio.run/##ddA9akJBEAfwfk4hhHT7YL52PtpcwVIsbUSwTpMiTa6RA@QCwS45SbzIuuQh6tO3zcD@mD8zs93sdq@tvez/vj@XP4fh7dlq@/04vn@1toKByuLBe1ogDMks4oxiUdW9BkYZ6V68/HcRqBFZGFIou4QnykgMxKzZPzJMe5cm0UgCieiUyT1NsddyHoMQtKLUTOtxjpp2MZpavRgDUw8LMY1yu5pcmU9NgB9epJv1FWZNAGdNYX0C "Jelly – Try It Online")
...`BoṠS63r0¤i`, `BoṠS63ŻṚ¤i`, or `BoṠS64ḶṚ¤i` would also work.
---
Another 10 byter (from Dennis) is `æ»64ḶṚ¤Äċ0` (again `æ»63r0¤Äċ0` and `æ»63ŻṚ¤Äċ0` will also work)
[Answer]
# [Perl 5](https://www.perl.org/), 37 bytes
```
sub{sprintf("%064b",@_)=~/^0*/;$+[0]}
```
[Try it online!](https://tio.run/##rZPrTsJAEIX/71NMNouhUmH20r1Yq7yHFyJSCJFLpSWRGH11XAoKkSYY4PxpMzv55szpNktno2g5XrB@sszn3Y88mw0nRb9Oa6hVl4btTpB8tZ7wshWzxj0@fi7j8QLaRZoXyfg5g/s8Gw2L1kPeaD2GN7cx6U9n9fI4@CDgNV7U2TBkaZC0WSfelIANkgvW9yfBurSeCpQ26yyF9M033FF6TSfTAmjQpNNX3zScZPPiGmoiyiGB0iBA@p6lL0XaW9V7AINp2dF7mNBwNXc1OmSDmHwurzjsC39e@IkiV04IKY1AqW2kjIks2h08niayTzee@rvGqe6V5lxbjdwqYaQ1DiWA@MWfyCdcCOU81FmtvHvluLcut3gs8zka7xANd074ZBT65ybyLX6j474CURHKyDntkzGonN5cmD38cfy/@GiNF/v4owIigvtUrNTK7tx7WYWv0qGVtnizi5f/xONB9xU/Lej/uj@0G@GVeHkWPHKClXh1Hjx@Aw "Perl 5 – Try It Online")
Or this 46 bytes if the "stringification" is not allowed: sub z
```
sub{my$i=0;$_[0]>>64-$_?last:$i++for 1..64;$i}
```
[Answer]
# Swift (on a 64-bit platform), 41 bytes
Declares a closure called `f` which accepts and returns an `Int`. This solution only works correctly 64-bit platforms, where `Int` is `typealias`ed to `Int64`. (On a 32-bit platform, `Int64` can be used explicitly for the closure’s parameter type, adding 2 bytes.)
```
let f:(Int)->Int={$0.leadingZeroBitCount}
```
In Swift, even the fundamental integer type is an ordinary object declared in the standard library. This means `Int` can have methods and properties, such as [`leadingZeroBitCount`](https://developer.apple.com/documentation/swift/int/2884587-leadingzerobitcount) (which is required on all types conforming to the standard library’s [`FixedWidthInteger`](https://developer.apple.com/documentation/swift/fixedwidthinteger) protocol).
[Answer]
# [Haskell](https://www.haskell.org/), 24 bytes
```
f n|n<0=0
f n=1+f(2*n+1)
```
[Try it online!](https://tio.run/##ZY2xDsIwDET3foXHllJkO2niVOQDGPgCxJCBioo2qqAj/x6idGQ5n9@ddM/weT3mOaUR4jee0WOVnad2rPkQW2rSEqYIHpawXqFe31PcTmNTAdygo3yO0DlmpSyjMtJra3tBKcE/t4VrQ2TEIIlmq8Q6VIUTs3b5c2J07mtH@4ApynunKA7DJW7Z3tMP "Haskell – Try It Online")
This is basically the same as Kevin Cruijssen's Java solution, but I found it independently.
The argument should have type `Int` for a 64-bit build, or `Int64` for anything.
## Explanation
If the argument is negative, the result is immediately 0. Otherwise, we shift left, *filling in with ones*, until we reach a negative number. That filling lets us avoid a special case for 0.
Just for reference, here's the obvious/efficient way:
# 34 bytes
```
import Data.Bits
countLeadingZeros
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 103 bytes
Uses the same *"builtin"* as ceilingcat's answer.
```
f::!Int->Int
f _=code {
instruction 243
instruction 72
instruction 15
instruction 189
instruction 192
}
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3P83KStEzr0TXDkhwpSnE2ybnp6QqVHNl5hWXFJUml2Tm5ykYmRij8M2NULiGpqhcC0tUvqURV@3/4JLEohIFW4U0BYP/AA "Clean – Try It Online")
# [Clean](https://github.com/Ourous/curated-clean-linux), 58 bytes
```
import StdEnv
$0=64
$i=until(\e=(2^63>>e)bitand i<>0)inc 0
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLxcDWzIRLJdO2NK8kM0cjJtVWwyjOzNjOLlUzKbMkMS9FIdPGzkAzMy9ZweB/cEkiUKetgoqCgQIc/P@XnJaTmF78X9fT579LZV5ibmZyMQA "Clean – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
în»╧3(∞┼⌠g
```
[Run and debug it](https://staxlang.xyz/#p=8c6eafcf3328ecc5f467&i=-1%0A-9223372036854775808%0A9223372036854775807%0A4611686018427387903%0A1224979098644774911%0A9007199254740992%0A4503599627370496%0A4503599627370495%0A2147483648%0A2147483647%0A2%0A1%0A0&a=1&m=2)
It's a port of Kevin's 05AB1E solution.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 42 bytes
```
1while$_>0&&2**++$a-1<$_;$_=0|$_>=0&&64-$a
```
[Try it online!](https://tio.run/##rdPNaoQwEAfwe54i0LCHXSwz@Q7WvkGfQTxYarEqftAe@uxNQ7tdpQouunOJGPgx83ds8rZU3uP7S1HmLH2Ew4Efj6cTyyJ8YGnM0gQ@w/skXGgZsczHLEsgpnf5R9H1HX0dup4@1y19G8q@aMqc9m2Rd7SoaF3ltB0qHyGdF/w94M4ikeNcCMNBaKukMcqCnfCwr8hcN0G9jLG3e6kRtdWAVnIjrHEgKOUXfqdPkHPpAuqslqF76TC0LkYefvLZzDsAg87xkIyEcJ4jH/lzbfsKRCoQyjkdkjEgnT4vzIzf5v/n1S/P5/ymgAjHkIoVWtrJ3oslfqnWRhp5M@XFlTysLiYRhC/8uFRfO8HafAQXeXETHpDAIi9vw8NX3fRFXXU@elL3YRofNeU3 "Perl 5 – Try It Online")
Longer than a bitstring based solution, but a decent math based solution.
[Answer]
# APL(NARS), 15 chars, 30 bytes
```
{¯1+1⍳⍨⍵⊤⍨64⍴2}
```
test for few numbers for see how to use:
```
f←{¯1+1⍳⍨⍵⊤⍨64⍴2}
f ¯9223372036854775808
0
f 9223372036854775807
1
```
[Answer]
# Rust, 18 bytes
```
i64::leading_zeros
```
[Try it online!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=71da8c48aa4f1edd0fb85db20d7281d4)
[Answer]
# PHP, ~~50~~ 46 bytes
```
for(;0<$n=&$argn;$n>>=1)$i++;echo$n<0?0:64-$i;
```
Run as pipe with `-R` or [try it online](http://sandbox.onlinephpfunctions.com/code/7d03c08accfe0eaa3e19c42efec9c7bca8b40ae6),
`<?=$argn<0?0:0|64-log($argn+1,2);` has rounding issues; so I took the long way.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes
The formula for positive numbers is just `63-Floor@Log2@#&`. Replacement rules are used for the special cases of zero and negative input.
The input need not be a 64-bit signed integer. This will effectively take the floor of the input to turn it into an integer. If you input a number outside of the normal bounds for a 64-bit integer, it will tell return a negative number indicating how many more bits would be needed to store this integer.
```
63-Floor@Log2[#/.{_?(#<0&):>2^63,0:>.5}]&
```
[Try it online!](https://tio.run/##ZY9NawJBEER/jCARerW/pnvaROMppxxyFyOLrImgWXDnJv72zZwSSE5VPOod6tKWz@7SltOhHUs3lEM7dMPq1hA0wSzijGI5qXvKmOE/c1AjsmxIWdkle6AAMWvUFtm07jSIIBCdIriKijVBE0qKsGo5athfkICpbrOY5t/qwECA98fjajRpXs59f9289h@8nSzmt/3zw@QJp7Plmt9NAJfrebrvpuPb9fRVtsfF5ufkbvwG "Wolfram Language (Mathematica) – Try It Online")
@LegionMammal978's solution is quite a bit shorter at 28 bytes. The input must be an integer. Per the documentation: "`BitLength[n]` is effectively an efficient version of `Floor[Log[2,n]]+1`. " It automatically handles the case of zero correctly reporting `0` rather than `-‚àû`.
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes
```
Boole[#>=0](64-BitLength@#)&
```
[Try it online!](https://tio.run/##ZY@7asNAEEU/xhAcGOGZ2dl5YBSM6xTujQth1pbAD4i2C/l2ZasEkupeDvcU9z7UsdyHOp2HpZa5noe5zP1nR9AFc0rGmNSzmGVHh//MQJRIXZFc2JJbYAJilmgtXKXtJIggEI0iuImCLUEyphyhzTKU0L8gA1PbelLx32rAQIBf20u/7J/PWzmu3no8rVW6/VTfy@Nax93q9WU5fEyPerxsdj@/Tss3 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
bitNumber - math.ceil (math.log(number) / math.log(2))
e.g
64 bit
NUMBER : 9223372036854775807
math.ceil (math.log(9223372036854775807) / math.log(2))
ANS: 63
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 12 bytes
```
+/&\~(64#2)\
```
[Try it online!](https://ngn.codeberg.page/k#eJxljstqAlEMhvfzFEJFlCLN7eQy51E0oJuB0kJBXCjiPHvPmZ24Cv+X5Eum8fNrc5y3Kh+0Ow7DdXysD/f5Mk6rWz39/dTtaTp//9ZbvdfLLp/D9bDHhF6CiNkIWL2IWXHwpfHOLbFxUUR1BXQhY7cATmociSRaCldp8xKIyd0DYBhBTSLQamK3SwEuEdoUBhKaiO+0JHYzYVt1VvHkl2zJ/QKlLg+k9gSp8g/x20FX)
`(64#2)\` encode the argument as 64 bits
`~` bitwise not
`&\` cumulative boolean and
`+/` sum
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
I⁻⁶⁴L↨﹪NX²¦⁶⁴¦²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYw8xER8EnNS@9JEPDKbE4VcM3P6U0J1/DM6@gtMSvNDcptUhDU0chIL8cyDDSUTAz0QRyjTTBwPr/f4P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
L Length of
N Input as a number
Ôπ™ Modulo
² Literal 2
X To the power
⁶⁴ Literal 64
‚Ü® Converted to base
² Literal 2
⁻ Subtracted from
⁶⁴ Literal 64
I Cast to string
Implicitly print
```
The `¦`s serve to separate adjacent integer literals. Conveniently, Charcoal's arbitrary numeric base conversion converts `0` into an empty list, however for negative numbers it simply inverts the sign of each digit, so the number is converted to the equivalent unsigned 64-bit integer first.
] |
[Question]
[
Write a program to print or return one of these strings verbatim:
```
abcdefghijkmnopqrstuvwxyz
ABCDEFGHIJKMNOPQRSTUVWXYZ
```
Notice that there is [no L](https://en.wikipedia.org/wiki/The_First_Noel).
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 49 bytes
```
+++++++++++++[->+>+++++>+<<<]>--[->.+<]>>+[-<+.>]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGxlE69pp24FZdto2Njaxdrq6QCE9bSDLDihpo61nF/v/PwA "brainfuck – Try It Online")
Starting with a cell containing `13` we set up 3 cells containing `13,65,13`. The 65 is the ASCII code of the letter to be printed and the other cells are down-counters (which are adjusted to 11 and 14 before use.) A nice feature is that the loop for printing the first 11 letters increments the ASCII code after printing and the loop printing the last 14 letters increments the ASCII code before printing, thereby skipping L naturally.
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, ~~21~~ 18 bytes
Anonymous function that takes no inputs and outputs the string with uppercase letters.
```
@()['A':'K' 77:90]
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BQzNa3VHdSt1bXcHc3MrSIPZ/SmZxgUaahqbmfwA)
### How it works
The code concatenates the two ranges of letters: before and after the 'L'. The second range is defined numerically to save two bytes. This can be done because concatenating chars and numbers implicitly converts each number to the char with the corresponding codepoint.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 3 bytes
```
⁻βl
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3M6@0WCNJR0EpR0lT0/r///@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: `β` is a Charcoal variable predefined to the lowercase alphabet.
```
⁻αL
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3M6@0WCNRR0HJR0lT0/r///@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: `α` is a Charcoal variable predefined to the uppercase alphabet.
[Answer]
# [R](https://www.r-project.org/), 22 bytes
```
!Map(cat,letters[-12])
```
[Try it online!](https://tio.run/##K/r/X9E3sUAjObFEJye1pCS1qDha19AoVvP/fwA "R – Try It Online")
Exits with an error; credit to [ovs](https://codegolf.stackexchange.com/users/64121/ovs).
# [R](https://www.r-project.org/), 23 bytes
```
x=Map(cat,letters[-12])
```
[Try it online!](https://tio.run/##K/r/v8LWN7FAIzmxRCcntaQktag4WtfQKFbz/38A "R – Try It Online")
Also credit to ovs.
# [R](https://www.r-project.org/), 24 bytes
```
cat(letters[-12],sep="")
```
[Try it online!](https://tio.run/##K/r/PzmxRCMntaQktag4WtfQKFanOLXAVklJ8/9/AA "R – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 23 bytes, original answer
```
printf %s {a..k} {m..z}
```
[Try it online!](https://tio.run/##S0oszvj/v6AoM68kTUG1WKE6UU8vu1ahOldPr6r2/38A "Bash – Try It Online")
# [Bash](https://www.gnu.org/software/bash/), 21 bytes, thanks to Nahuel Fouilleul
```
echo {a..z}|tr -d \ l
```
[Try it online!](https://tio.run/##S0oszvj/PzU5I1@hOlFPr6q2pqRIQTdFIUYh5/9/AA "Bash – Try It Online")
[Answer]
# Various Languages, 25 bytes
```
abcdefghijkmnopqrstuvwxyz
```
or
```
ABCDEFGHIJKMNOPQRSTUVWXYZ
```
In many languages, the shortest solution is also the least interesting.
Works in: [///](https://esolangs.org/wiki////), [ARBLE](https://github.com/TehFlaminTaco/ARBLE), [PHP](https://php.net/), [ReRegex](https://github.com/TehFlaminTaco/ReRegex), ...
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3),, 4 bytes
```
n'l-
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCJuJ2wtIiwiIiwiIiwiMy4wLjAiXQ==)
First Vyxal answer, so I’m sure there may be a more concise way, but I like that it almost reads ‘no el’!
[Answer]
# [PowerShell Core](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 25 bytes
```
-join$('a'..'k';'m'..'z')
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XzcrPzNPRUM9UV1PTz1b3Vo9F8SoUtf8/x8A "PowerShell – Try It Online")
I think solving that with 25 bytes has a certain *je ne sais quoi*.
Only works in PowerShell Core, Windows PowerShell can't enumerate characters.
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), all flavors, 27 bytes
```
'abcdefghijkmnopqrstuvwxyz'
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Xz0xKTklNS09IzMrOzcvv6CwqLiktKy8orJK/f9/AA "PowerShell – Try It Online")
The boring/trivial solution with 27, which would end up as National Fruitcake Day. Somewhat related to CodeGolf, as golfed code and fruitcake have a similar density.
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), all flavors, 31 bytes
```
-join([char[]]$(65..75;77..90))
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XzcrPzNPIzo5I7EoOjZWRcPMVE/P3NTa3FxPz9JAU/P/fwA "PowerShell – Try It Online")
So here's New Year's Eve.
Which is what we also get from the trivial solution in Batch:
# Windows Batch, 31 bytes
```
@echo abcdefghijkmnopqrstuvwxyz
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 14 bytes
```
26*#
Y`#`l
l
```
[Try it online!](https://tio.run/##K0otycxLNPz/n8vITEuZKzJBOSGHK4fr/38A "Retina – Try It Online") Outputs in lowercase but if the program is uppercased then it will output in uppercase instead. Explanation:
```
26*#
```
Insert 26 `#`s. (I can't use the default `_` because that's a special transliteration character.)
```
Y`#`l
```
Translate each `#` in turn into the next character of the alphabet. (It's possible to skip the `l` here but it's longer overall.)
```
l
```
Remove the `l`.
The best I could do in [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d) without resorting to 26-byte hard-coding was 27 bytes, but with some inspiration from @FryAmTheEggman I got it down to ~~16~~ 15 bytes:
```
T`l`_l
}`$
z
l
```
[Try it online!](https://tio.run/##K0otycxL/P8/JCEnIT6HqzZBhauKK4fr/38A "Retina 0.8.2 – Try It Online") Outputs in lowercase but if the program is uppercased then it will output in uppercase instead. Explanation:
```
T`l`_l
```
Move all of the letters so far one step backwards in the alphabet, but delete any `a`.
```
$
z
```
Append a `z` to the current string.
```
}`
```
Repeat the above until the transformation becomes idempotent. This happens when the string is the entire alphabet; the `a` is deleted, the `b-z` get transliterated into `a-y`, and another `z` is appended.
```
l
```
Remove the `l`.
[Answer]
# x86-64 machine code, ~~17~~ 15 bytes
```
B0 E6 04 5B AA 2C 4B 3C 01 14 F1 75 F5 AA C3
```
[Try it online!](https://tio.run/##TVFNU8IwED0nv2Ktw5AIZQCVA4gXj44XT47AIU3SNk6aME2LrQx/3brgIF52533s251ZGWdSdp0IBTB4jRgdZdYnwkJK0zkp/A6EHUI8ndFyToRSJ9h/7w8mlITKhwRbnfyyz31KZLE9AZSFkmc@xglKPtwXlH9jpa4oj4Av6M4bBSmTuShvICBBr42TtlYaHkKljB/lj5QaV0EhjGOc7nEPmqHUobbV6n4y3SwoSdkvxgCyLdGesqgXoiFc6Iuwdi9C5sZpkF7peXRUjxsaWMJ4CC1C5WF/tkNvPH3DqHbJWO2CyZxWcDqYp3zVDAYbvjjAZ26sBtbCFYY0T7f/LwHWM5C0lQ587TCpQfHQdd8ytSILXVzM7rDgH5bo1/YH "C (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI a memory address at which to place the result, as a null-terminated byte string.
In assembly:
```
f: mov al, -26 # Set AL to -26.
r: add al, 'Z'+1 # Add this value to AL to produce a letter.
stosb # Write AL to the output string, advancing the pointer.
sub al, 'K' # Subtract 'K' from AL.
cmp al, 1 # Set flags from calculating AL - 1. CF is 1 iff AL is 0.
adc al, 'K'-'Z' # Add (this value + CF) to AL. The net change is +1 or +2.
jnz r # If the result is nonzero, repeat the loop.
stosb # Write AL (0) to the output string, advancing the pointer.
ret # Return.
```
[Answer]
# [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) machine code, 14 DECLEs1 = 17.5 bytes
*1. CP-1610 instructions are encoded with 10-bit values (0x000 to 0x3FF), known as DECLEs. Although the Intellivision is also able to work on 16-bit data, programs were really stored in 10-bit ROM back then.*
A routine that writes the Christmas alphabet at **R4**.
The method used here would be more relevant if there were several letters to skip. With just one letter, using `SLLC` / `ADCR` only saves a few CPU cycles compared to `CMPI` / `BEQ`.
```
ROMW 10 ; use 10-bit ROM
ORG $4800 ; map our code at $4800
4800 02BC 0200 MVII #$200, R4 ; R4 = BACKTAB pointer
4802 0004 0148 000D CALL alpha ; invoke our routine
4805 02BD 0030 MVII #$30, R5 ; R5 = pointer into STIC registers
4807 01C0 CLRR R0
4808 0268 MVO@ R0, R5 ; no horizontal delay
4809 0268 MVO@ R0, R5 ; no vertical delay
480A 0268 MVO@ R0, R5 ; no border extension
480B 0002 EIS ; enable interrupts
480C 0017 DECR R7 ; loop forever
;; our routine
alpha PROC
480D 02B8 010F MVII #$010F, R0 ; R0 = letter code, initialized to 'A'
480F 02B9 0010 MVII #$0010, R1 ; R1 = mask used to skip 'L'
4811 0059 @loop SLLC R1 ; left-shift the mask into the carry
4812 002F ADCR R7 ; add the carry to the program counter
; (i.e. skip MVO@ if the carry is set)
4813 0260 MVO@ R0, R4 ; write the letter
4814 02F8 0008 ADDI #8, R0 ; update R0 to the next letter
4816 0378 01D7 CMPI #$01D7, R0 ; compare with 'Z'
4818 0226 0008 BLE @loop ; loop if less than or equal
481A 00AF MOVR R5, R7 ; return
ENDP
```
## Output
[](https://i.stack.imgur.com/hiclB.gif)
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 4 bytes
```
a`l-
```
[Try it online!](https://tio.run/##Kyooyk/P0zX6/z8xIUf3/38A "RProgN 2 – Try It Online")
Or for upper-case
```
A`L-
```
[Try it online!](https://tio.run/##Kyooyk/P0zX6/98xwUf3/38A "RProgN 2 – Try It Online")
Just removes literal `L` from the alphabet builtin.
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 14 bytes
```
:h<_
jjYZZPtmx
```
[Try it online!](https://tio.run/##K/v/3yrDJp4rKysyKiqgJLfi/38A "V (vim) – Try It Online")
[Yet another](https://codegolf.stackexchange.com/questions/94983/now-i-know-my-abcs-wont-you-come-and-golf-with-me/94989#94989) post uses [the trick](https://codegolf.stackexchange.com/questions/86986/print-a-tabula-recta/87010#87010) found by [Lynn](https://codegolf.stackexchange.com/users/3852/lynn).
[Answer]
# [Perl 5](https://www.perl.org/), 13 bytes
```
say A..K,M..Z
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVLBUU/PW8dXTy/q//9/@QUlmfl5xf91fU31DAwB "Perl 5 – Try It Online")
[Answer]
# [Python](https://www.python.org), 39 bytes
```
print(25*"%c"%(*{*range(65,91)}-{76},))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY31QuKMvNKNIxMtZRUk5VUNbSqtYoS89JTNcxMdSwNNWt1q83NanU0NSHKobpgugE)
Only 5 bytes longer than hardcoding the entire thing ...
### How?
Unlike dictionaries, sets are in general not guaranteed to preserve insertion order, so why does this work?
C-Python implementation detail: (small) integers are their own hash values.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 19 bytes
```
([*?a..?z]-[?l])*''
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsESFTsbm6WlJWm6Fps1orXsE_X07KtidaPtc2I1tdTVITILoBSUBgA)
Since the task allows simply returning the string instead of printing, I believe it should be acceptable as this snippet. If not, it's +4 for `$><<` in front.
[Answer]
# [Python 3](https://docs.python.org/3/), 71 bytes
```
import string as s
print(s.ascii_lowercase[:11]+s.ascii_lowercase[12:])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKG4pCgzL10hsVihmKsAyCzRKNZLLE7OzIzPyS9PLUpOLE6NtjI0jNXGFDY0sorV/P8fAA "Python 3 – Try It Online")
[Answer]
# XPath 2: ~~42~~ ~~41~~ 27 bytes
First attempt: 42 bytes
```
codepoints-to-string(remove(97 to 122,12))
```
Explanation:
* `97 to 122` returns the sequence 97, 98, 99, ... 122
* `remove( ..., 12)` removes the 12th item
* `codepoints-to-string()` converts the numbers to a string
The result of the evaluation is the christmas string. [Try it online](http://xpather.com/i1C7g8C1).
---
Second attempt 41 bytes, thanks to @Philippos
```
codepoints-to-string(remove(65 to 90,12))
```
(upper case letters)
---
Third attempt (27 bytes), the "trivial" (but so far the shortest) solution (@jonathan-allan)
```
"abcdefghijkmnopqrstuvwxyz"
```
is a equally valid XPath expression.
[Answer]
# [Haskell](https://www.haskell.org/), 23 bytes
```
filter(/='L')['A'..'Z']
```
## Explanation
`['A'..'Z']` represents the entire uppercase alphabet, `(/='L')` is a shorthand for the lambda `\x -> x /= 'L'`. When both are passed to `filter`, this keeps all letters from the alphabet that are not `L`.
Alternatively, this can also be done with an extra byte using [list comprehensions](https://wiki.haskell.org/List_comprehension):
```
[x|x<-['A'..'Z'],x/='L']
```
[Answer]
# [Python 3](https://docs.python.org/3/), 51 50 bytes
```
print(''.join(chr(i+65)for i in range(26)if i-11))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ11dLys/M08jOaNII1PbzFQzLb9IIVMhM0@hKDEvPVXDyEwzM00hU9fQUFPz/38A "Python 3 – Try It Online")
Simple iteration combining `range` and `chr`.
-1 byte thank to [@UndoneStudios](https://codegolf.stackexchange.com/users/110681)'s amazing hint of using `str.join`
---
# [Python 3](https://docs.python.org/3/), 54 bytes
```
a=*range(65,91),
print(*map(chr,a[:11]+a[12:]),sep='')
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9FWqygxLz1Vw8xUx9JQU4eroCgzr0RDKzexQCM5o0gnMdrK0DBWOzHa0MgqVlOnOLXAVl1d8/9/AA "Python 3 – Try It Online")
Using tuple destructuring.
[Answer]
# [morsecco](https://codegolf.meta.stackexchange.com/a/26119/72726): 112 bytes
Yes, that's 4.5 times the size of the pure input, but don't forget that we have only three symbols, resulting in a factor ~5, compared to the full character set.
The whole christmas alphabet in morse code already takes 102 characters; with the overhead of conversion and printing it would be 124 bytes, so this loop solution is shorter *(not counting the christmas tree formatting, which starts beautifully with `E`ntering 65, but doesn't really work out well, because whitespaces are sometimes meaningful in Morsecco)*:
```
.
-.....-
-- -
- -
-.- -
. -
.--
. .-..-.--
.-
--.. --.-
. .----
.- --.. --.
. -.--.--
.- --. --.-
. -..--.- --.
```
* The first line initializes the stack with 65 (`A`)
* Line 2 sets a jump `M`ark to start a loop, `K`onvert the number to `T`ext and `W`rite it to stdout.
* Now comes the golfing trick: line 3 `A`dds –75 (`K`) and skips after `--.-` is zero (so the last line handles the `L` skipping by `E`ntering 77)
* The 4th line subtracts another 15 to test for the `Z` and skips after the `--.` that closes the loop for the other characters
* The 5th line `A`dds 91 (–75 + –15 + 91 = 1, so the value is incremented) and `G`oes to the mark that was set. This saves three bytes compared to saving a copy of the value, dropping the modified version and adding 1 to the copy.
**Cheating version: 47 bytes**
Yes, morsecco ignores all characters except for dot, dash and space, but to cheat, you can `R`ead the source code from the empty address, `C`ut it after the `Z` and `O`utput. Yes, such tricks are probably legal when golfing, but boring:
```
ABCDEFGHIJKMNOPQRSTUVWXYZ. .-. -.-. --..- ---
```
[Answer]
# [Uiua](https://uiua.org), 11 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
▽≠@l.+@a⇡26
```
[Try it!](https://uiua.org/pad?src=0_3_1__ZiDihpAg4pa94omgQGwuK0Bh4oehMjYKCmYK)
```
▽≠@l.+@a⇡26
⇡26 # range from 0 to 25
+@a # add letter a
. # duplicate
≠@l # where is it not equal to l?
▽ # keep
```
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 6 bytes
```
⎕A~'L'
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/qHfeo7YJGv8f9U11rFP3Uf@v@R8A "APL (dzaima/APL) – Try It Online")
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 9 bytes
```
$abc"l"--
```
[Try it on scline!](https://scline.fly.dev/##H4sIAOYYYGUCA1NJTEpWylHS1QUA1.fRIwkAAAA#)
Very straightforward.
[Answer]
# Google Sheets, 45 bytes
`=sort(replace(join(,char(row(65:90))),12,1,))`
...or **47 bytes**:
`=join(,filter(char(row(65:90)),row(65:90)<>76))`
These formulas are longer than their output.
[Answer]
# [Python 3](https://docs.python.org/3/), 50 49 bytes
```
print(''.join(chr(x+x//76)for x in range(65,90)))
```
You could save two bytes by using Python 2, but nobody uses that anymore:
# Python 2, 47 bytes
```
print ''.join(chr(x+x/76)for x in range(65,90))
```
[Answer]
# [Scala](http://www.scala-lang.org/), ~~48~~ 30 bytes
Saved 18 bytes thanks to @corvus\_192
---
Golfed version. [Try it online!](https://tio.run/##NY2xCsIwFEX3fMWjS1qoQ9eUDv0AcRAXxeEZ2xhN0pA8xSL9dWOgOB0u515ulGgwTZf7IAm2qB18GMB1GMHmUGJQUUAfAs6nPQXt1LkScHCaoMtN9sIAdl6NgJVd4j2niR@5R5K3smnqoqibyj5Wn1rmM8m48j@tWpZfF7akrxwNqpg2Bp16ohqEnyKN@r3z8Qc)
```
'A'to'Z'patch(11,"",1)mkString
```
[Answer]
# [*Acc!!*](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!), 41 bytes
```
Count i while 25-i {
Write (65+i)*77/76
}
```
[Try it online!](https://tio.run/##S0xOTkr6/985vzSvRCFToTwjMydVwchUN1Ohmiu8KLMkVUHDzFQ7U1PL3Fzf3Iyr9v9/AA "Acc!! – Try It Online")
### Explanation
Loop `i` from 0 to 24. Add 65 to convert to uppercase codepoints A through Y; then scale by a linear factor to skip over code point 76 (L). (Division in *Acc!!* is integer division, but the floating-point version would be \$ 65.86, 66.87, \cdots, 74.97, 75.99, 77.00, 78.01, \cdots, 90.17 \$)
[Answer]
# [jq](https://stedolan.github.io/jq/), 27 characters
```
[range(65;91)]-[76]|implode
```
Sample run:
```
bash-5.2$ jq -nr '[range(65;91)]-[76]|implode'
ABCDEFGHIJKMNOPQRSTUVWXYZ
```
[Try it online!](https://tio.run/##yyr8/z@6KDEvPVXDzNTa0lAzVjfa3Cy2JjO3ICc/JfX//3/5BSWZ@XnF/3V180pzcnQz8wpKS4CcosRy3fzSEiAHAA "jq – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;BkÊ
```
[Test it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O0Jryg)
] |
[Question]
[
In particular, use each of these symbols at least once in your source code:
```
! " # $ % & ' () * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
```
Symbols inside comments, string literals, regexps (or any other kinds of literals etc.) don't count (but their delimiters such as `/**/` or `""` do count).
The program should not perform any action. It just has to compile and do nothing when run.
If for some reason some of the symbols cannot be used in the language of your choice, explain that rigorously (what and why must be excluded).
**Update:** A few answers used symbols withing regular expressions. I'd consider this a bit problematic, it's the same thing as putting them into string literals or comments (that's why I put *etc.* in that requirement). Please try without this. I also updated the requirement above.
**Update:** Shortest code wins (tagged as *code-golf*). As suggested, we'll most likely need some tie-breaker criteria. I suggest that if there is a tie, the winning one is the one in which the ASCII symbols appear as much ordered as possible. Formally: Filter out the first occurrence of each of the listed symbols from a program. This will result in a permutation on the listed symbols. The program with less [inversion number](http://en.wikipedia.org/wiki/Inversion_%28discrete_mathematics%29#Definitions) of its permutation wins.
**Update:** I'd be happy to see some/more solutions in regular/mainstream languages, such as C(++), Java, Scala, Haskell, etc.
[Answer]
## Perl, 32 chars
no hiding symbols in comments, string literals, or regular expressions. uses all symbols precisely once.
```
$`<@"^[(\{_},)]/+-~%'?&|:!*.=>;#
```
### Description
i have tried to indicate operator precedence with indentation: the right-most expressions are evaluated before those to their left
```
$` # scalar variable $ named `
< # numeric less-than inequality <
@" # array variable @ named "
# (array evaluated in scalar context)
^ # bitwise XOR ^
[(\{_},)] # array reference []
# containing array ()
# containing reference \
# to anonymous hash reference {}
# with one key "_"
# and no value (nothing following comma ,)
# (reference evaluated in scalar context)
/ # numeric division /
+-~%' # unary addition +
# and unary negation -
# and bitwise complement ~
# on hash variable % named '
# (hash evaluated in scalar context)
? # ternary conditional operator ?:
&| # code reference variable & named |
: # ternary conditional operator ?:
! *. # logical negation !
# on typeglob variable * named .
# (typeglob evaluated in scalar context)
=> # fat comma => for compound expression
# (evaluates LHS as string, RHS is empty)
; # end of expression ;
# # start of comment #
```
[Answer]
## Brainf\*ck, 32 characters
```
!"#$%&'()*+.-/:;>=<?@[\]^_`{|}~,
```
Prints a smiley face (if your console can output ASCII symbol 1)
Yay, a Branf\*ck solution that beats Golfscript! :P
If you insist on no output, just exchange the `+` and `.` :
```
!"#$%&'()*.+-/:;>=<?@[\]^_`{|}~,
```
[Answer]
## Whitespace, 32
```
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
```
all non whitespace characters are ignored, so this is actually an empty program
[Answer]
## Python 65
```
a=lambda x:0.
@a#
def _():{[`'"$?'`,]};a<a!=a+a%a&a^a-a*a|~a>a/a\
```
I used the characters `?` and `$` inside a string literal. These characters are [not legal](http://docs.python.org/2/reference/lexical_analysis.html#delimiters) outside string literals or comments.
[Answer]
# PHP, 32 chars
Probably a bit of a troll, this PHP program is also a **QUINE**, and uses all symbols in the exact order they are listed.
```
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
```
Executed from the command line, the output will simply be the contents of the file, as there is no `<?php` to invoke the interpretor.
```
$ cat > a.php
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
$ php a.php
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
```
[Answer]
# Perl 6 (43 chars)
Let's define a infix operator with a rather unusual name:
```
sub infix:<!"#$%&'()*+,-./:;=?@[]^_´\|~>{}
```
It's not a literal nor a literal in a RE or anything hidden in a comment. You don't believe me? Running the following program will output "2":
```
sub infix:<!"#$%&'()*+,-./:;=?@[]^_´\|~>($a, $b){ $a + $b }
say 1 !"#$%&'()*+,-./:;=?@[]^_´\|~ 1;
```
But I'm quite sure you nitpickers will extend the rules further to exclude redefinition of the language itself to make us perl lubbers unhappy. :(
[Answer]
## Haskell, 53
```
a@""#%&*+/?^b|a'<-a!!0=(\_->a`b`[]);main=do{print$1}
```
We can make this a bit shorter
## 45
```
a'@""#%&*+/?!<|^b=(\_->1`b`[]);main=do{main}
```
however this program doesn't terminate, and uses more characters (`'!'`,`'<'`,`'|'`) in the newly-defined infix.
[Answer]
# k (33 chars)
Very easy in k. Unfortunately `"` must be paired.
```
(@:'!""#$%&*+-\./;<=>?^_{}[`]|,~)
```
[Answer]
## GolfScript (33 chars)
```
{!""$%&()*+,-./<=>?@[\]^_`|~};:'#
```
`"` has to be paired. It took a bit of trial and error to get it to output nothing - most other positions of the `:'` result in some output.
[Answer]
## J, 33 characters
```
''&][?!"$>{}:<;,|^~*/\%+`-@.#(=_)
```
`'` needs to be doubled to avoid syntax errors.
My first answer was missing some symbols.
[Answer]
## C, 48 chars
Kind of cheating.
```
#define _ ~''*+,-./:<=>?[]`|\
@%^$&!
main(){"";}
```
[Answer]
# Postscript - 32 chars
```
{!"#$&'()*+,-./:;=<>?@[\]^_`|~}%
```
Results in an object on the stack, but otherwise has no effects. Postscript allows almost any char in an identifier except for `<>()[]{}/` which are special syntax forms and `%` which introduces a comment. The program is tokenized as
```
{ % start a procedure object
!"#$&' % an identifier
() % an empty string
*+,-. % an identifier
/:;= % a symbol
<> % an empty hex string
?@ % an identifier
[\] % an array
^_`~| % an identifier
} % close the procedure object
% % a comment
```
[Answer]
## **C# (91 characters)**
```
#define a
class a{static int @Main(){return(char)1.1*""[0]/1%1-1+1!=1?1:~1^1>>1<<1&1+'\0';}}
```
As far as I know, The **$** character is not a valid character outside string literals, so I didn't use it in my answer.
**EDIT** : Thanks to [Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor), I shortened the code.
[Answer]
## PowerShell (52 characters)
```
$_+=(@(1.1,1)[0]-1)*1/1%'1'::ToInt|&{!"">~\1}<#^#>`;
```
I had to put the **^** character as a string literal because as far as I know, the **^** character is not a legal PowerShell character outside string literals. Correct me if I am wrong.
The only way I have found to fit in the **:** character is to use the **:: operator** to make a call to a static method.
[Answer]
### Scheme, 41 characters
```
(define !$%&*+,-./:<=>?@[\]^_`{|}~ "#'");
```
This takes advantage of Scheme's incredible tolerance for characters in variable names. In this program I create a variable with the name !$%&\*+,-./:<=>?@[]^\_`{|}~ which Scheme happily accepts.
[Answer]
# Tcl 37 chars
```
set {!#$%&'()*+,-./:<=>?@[]^\_`|~} ""
```
Defines a variable `!#$%&'()*+,-./:<=>?@[]^\_`|~` with an empty string
[Answer]
# C: 83 56 characters
```
#undef a
_;main($){$/=-+~!0|0^0%1,1<.0>0?'`':*&"@"[0];}\
```
At-signs and backticks are not a part of the allowed C-syntax, so I have put them between quotation marks.
[Answer]
### Common Lisp, 33 characters
```
#+()'|!"$%&*,-./:;<=>?@[\]^_`{}~|
```
The main part of the above evaluates (or rather, would evaluate if not for the `#+()` in front of it) to the symbol named:
```
!#$%&()*+,-./:;<=>?@[\]^_`{}~
```
The `#+()` is to avoid output. I'm not sure if the `|foo|` syntax for symbols counts as a literal, but symbols are used as variable/function names in Common Lisp, and there are a few answers already using the necessary characters in those.
[Answer]
**Smalltalk** (Squeak 4.x dialect) **38** chars
Implement this method in Object, the syntax is valid if Preferences *Allow underscore assignment* (which is the default setting)
```
%&*+/<=>?@\!~y""^Z_([:z|{#'',$`;-y}]).
```
declare Z as global var in pop-up menu if interactive
Explanations:
* %&\*+/<=>?@!~ is a binary selector (an operator)
* y is the parameter (the operand)
* "" is an empty comment
* ^ means return
* Z is a global variable
* \_ is an assignment
* () delimits a sub-expression
* [:z|] delimits a block of code with one parameter z
* {} delimits an Array
* #'' is a Symbol literal made of an empty String (first element of the Array)
* , is a binary message sent to above Symbol
* $` is a Character literal used as argument of above message
* ; is for chaining a second message sent to the same Symbol receiver #''
* the second message is -
* y is used as the second message argument
* . is for separating next instruction (here it's a final period)
Damn, who said Smalltalk was readable?
Note that I didn't cheat, the only non valid character ` is put into a literal Character. **EDIT** see below, this was a false assertion (at least in Squeak)
---
But we can make it down to **34** chars with this trick
```
%&*+,-/<=>?@\!~|y""^[{#(:_;`$')}].
```
This time:
* #() delimits a literal Array
* which contains 4 literal Symbols : \_ ; ` and 1 literal Character $'
Strictly speaking, we can consider this as cheating... It's not a literal String, but it is still a non empty literal...
I still have to double comment quote "" (unless I make a literal Character with it $", but then I need to double the String quote '')
I still have to use a letter for the parameter (\_ is not accepted even if we set Preferences *allow underscore in selector* to true).
What is nice is that we can even run the method, for example send the message to 1 with argument 2:
```
1%&*+,-/<=>?@\!~|2
```
---
**EDIT** Finally in **35** chars without cheating
```
!%&*+,-/<=>?@`y""^[:x_|#()~$';\{}].
```
Notes:
* Preferences *allow underscore in selector* enable using a block parameter named x\_
* ` is a valid character for binary selector contrarily to what I said
* I also use $' to avoid doubling a quote
[Answer]
## R: 108 characters
```
a=new(setClass("a",representation(b="list")));a@b=list(c_d=1:2);if(1!='\t'&.1%*%1^1>a@b$c[1]/1|F){`~`<-`?`}#
```
Clearly the longest submission, but to be able to use symbols `@` and `$` in R, we need to create an object that has slots (indexed using `@`) and named elements (indexed using `$`).
The shortest solution I could think of was to create a new class of object (`a=new(setClass("a",representation(b="list")))`), which takes its toll.
Otherwise, appart from the classics that don't need explanations (such as `!=`, `#` or `1:2`),
```
`~`<-`?`
```
creates a new operator that does the same as operator `?` (i. e. it calls the help page of the element it precedes).
`%*%` computes the inner product of two matrices (here of `1^1` and `.1`).
Symbol `_` does nothing (AFAIK) in R but is routinely used in variable or function names, as it is the case here.
[Answer]
## TI-Basic, 36
```
:End:#$%&'()*+.-/;>=<?@[\]^_`{|}~,!"
```
[Answer]
# [Rust](https://www.rust-lang.org/), 45 bytes
```
macro_rules!a{[r"`\"#%&'_*+-./:<?@^|~]=>{()}}
```
[Try it online!](https://tio.run/##KyotLvn/PzcxuSg/vqg0J7VYMbE6ukgpIUZJWVVNPV5LW1dP38rG3iGupi7W1q5aQ7O29n9ankJuYmaehmY1F2eiogZ21Zpctf8B "Rust – Try It Online")
Creates a macro that matches when you call it with the tokens r"`\"#%&'\_\*+-./:<?@^|~ and returns the unit type. Do note that the backtick and backslash are inside of a string literal because that is the only valid place they can go. Also, apparently whatever stack exchange uses for syntax highlighting can't handle rust's raw strings.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes
```
!"#$%&')*+,-./:;<=>?@[\]^_`{|}~(
```
[Try it online!](https://tio.run/##y0rNyan8/19RSVlFVU1dU0tbR1dP38raxtbO3iE6JjYuPqG6prZO4/9/AA "Jelly – Try It Online")
This technically outputs `0`, but given that the [empty program](https://tio.run/##y0rNyan8DwQA) does that as well, I didn't see an issue with that (especially as there is no way to "output nothing" in Jelly, aside from outputting the empty string. In this case, [~~34~~ 33 bytes](https://tio.run/##y0rNyan8/19RSVlFVU1dU0tbR1dP38raxtbO3iE6JjYuPqG6prZO41Hjjv//AQ) (-1 byte thanks to xigoi)).
## How it works
Jelly works by splitting its program into "links", which are compositions of "chains", which are collections of "atoms" and "quicks". 31 of the 32 characters used above are either atoms or quicks (or syntax characters), `(` is the only non-implemented character. When Jelly encounters an unimplemented character outside of a string literal, it breaks the chain, essentially ignoring everything before it. So the `(` breaks the program's chain, ignoring all the previous (erroring) characters. At this point, the new chain is made up of the characters after the breaking character, which in this case, is the "empty" program.
For the 33 byte version, the last byte - `⁸` - is the new chain, and is an empty list, which is then implicitly output at the end of the program as nothing
[Answer]
# [CJam](https://sourceforge.net/projects/cjam/), 34 bytes
```
""`'5~*:+{i[}%-/#~|<=!$\?@,^>()_];
```
[Try it online!](https://tio.run/##S85KzP3/X0kpQd20TstKuzozulZVV1@5rsbGVlElxt5BJ85OQzM@1vr/fwA)
Explanation:
```
""` Push an empty string and get the string representation of that ("\"\"")
'5~* Push a 5 character, convert it to a number, and multiply the previous string 5 times. We spend a alphanumeric char here because there's no way to use ' without wasting a char, as ' will simply accept the next character as a character and cannot be otherwise used (except in a string/char literal)
:+ Over our string, try to do some concatenation. This doesn't really do much.
{i[}% Convert all the characters in out string to their codepoints (34s for "). We now have a bunch of numbers on the stack. This is really nice, because CJam is strict with types but just about everything accepts numbers in some way. It's so nice that we spend a character on it.
-/#~|<=!$\?@,^>()_ Lots of meaningless operations. I just threw them in randomly and fiddled around with them so that everything would have enough operands, and we would be left with a small stack at the end
]; Discard what we have left
```
] |
[Question]
[
# Task
As input you have:
* a positive integer `N`
And you should output:
* The number of integers in \$[1,N]\$ (an inclusive range) which end with the digit \$2\$ in base ten.
# Test cases
```
1 -> 0
2 -> 1
5 -> 1
10 -> 1
12 -> 2
20 -> 2
30 -> 3
54 -> 6
97 -> 10
100 -> 10
```
# Rules
It is a code-golf so the lowest score in bytes wins!
[Answer]
# [Python 2](https://docs.python.org/2/), 17 bytes
```
lambda n:(n+8)/10
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPSiNP20JT39Dgf1p@kUKmQmaeQlFiXnqqhrGpphWXgkJBUWZeiUKmjkKaRqbmfwA "Python 2 – Try It Online") Uses Python 2's integer division. In Python 3 would be a byte longer with `lambda n:(n+8)//10`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḋm⁵L
```
A monadic Link accepting a positive integer, `N`, which yields a non-negative integer.
**[Try it online!](https://tio.run/##y0rNyan8///hjq7cR41bff7//29oZAQA "Jelly – Try It Online")**
### How?
Every tenth number starting with \$2\$ ends with the digit \$2\$...
```
Ḋm⁵L - Link: integer, N e.g. 15
Ḋ - dequeue (implicit range [1..N]) -> [2..N] [2,3,4,5,6,7,8,9,10,11,12,13,14,15]
⁵ - literal ten 10
m - modulo slice [2,12]
L - length 2
```
---
[Alternative 4 byter](https://tio.run/##y0rNyan8/1/bwupR49b///8bGhkBAA "Jelly – Try It Online"):
```
+8:⁵
```
Add eight, integer divide by ten (as first used in [RGS's Python answer](https://codegolf.stackexchange.com/a/200364/53748) I believe).
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, ~~13~~ 10 bytes
*@Grimmy got it back down to 10 bytes, with correct output.*
```
$_+=1<chop
```
[Try it online!](https://tio.run/##K0gtyjH9/18lXtvW0CY5I7/g/38To3/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 8 7 bytes
-1 byte thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)
Full program
```
⌊.1×8+⎕
```
[Try it online!](https://tio.run/##Hc5BCsIwFEXRebYiFt9L1bqcQsFJwUy7AkXEmbggd5KNxH8zeJNwzydzWffLNq@3a6uPe2n19Rz0@067@v7w0ko6pJIUcyzHxtgxdoqdY1PsQtNDSpGKVsSiFrnoBRDCCPfbCCOMMMIII4wwIiMyIvfvIPL4Bw "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ ~~6~~ 5 bytes
```
R%⁵ċ2
```
[Try it online!](https://tio.run/##y0rNyan8/z9I9VHj1iPdRv///zcyAgA "Jelly – Try It Online") Thanks to Nick Kennedy for saving me one byte.
How it works:
```
R Range from 1 to n,
%⁵ modulo 10.
ċ2 Then count how many of those are 2.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
8+T÷
```
Same approach as everyone else.
[Try it online](https://tio.run/##yy9OTMpM/f/fQjvk8Pb//41MAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/X@xydXPXknhUdskBSV7v/8W2iGHt//X@Q8A).
Some (slightly) more interesting 5-[bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternatives:
```
LT%2¢
L€θ2¢
L2ſO
FNθΘO
```
[Try each online.](https://tio.run/##yy9OTMpM/X@xydXPXknhUdskBSX7/35KPiGqRocWWQE5EJa9kjWQzQWUeNS05twOmByMg5A2Otx6aL8/WBLChEu5@Z3bcW4GWArK/F@r8x8A)
**Explanation:**
```
8+ # Add 8 to the (implicit) input-integer
T÷ # Integer-divide it by 10
# (after which the result is output implicitly)
L # Push a list in the range [1, (implicit) input-integer]
T% # Take modulo-10 on each
# or
€θ # Leave the last digit of each
2¢ # Count the amount of 2s
# (after which the result is output implicitly)
L # Push a list in the range [1, (implicit) input-integer]
2Å¿ # Check for each whether it ends with a 2 (I'm actually surprised it vectorizes..)
O # Sum to get the amount of truthy values
F # Loop `N` in the range [0, (implicit) input-integer):
N # Push `N`
θ # Pop and leave only its last digit
Θ # 05AB1E trutify: check if it's exactly 1
O # Sum all values on the stack together
# (after the loop, the result is output implicitly)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~15~~ 13 bytes
```
.+
$*
.{2,10}
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYtLr9pIx9Cg9v9/EyMA "Retina 0.8.2 – Try It Online") Edit: Saved 2 bytes thanks to @Grimmy. Explanation:
```
.+
$*
```
Convert to unary.
```
.{2,10}
```
Count the number of multiples of 10, each of which contains an integer that ends in 2 in base 10, plus count an additional match for a final 2-9, as that's enough for one last integer that ends in 2 in base 10.
[Answer]
# [Desmos](https://www.desmos.com/calculator)
I know I'm 7 months late but this is my first code golf answer. I'm looking for some easier coding challenges to take down. I have two answers(one where I tried it without looking at any answers, then one after I looked through some answers.).
## First Answer, 62 bytes:
`f(N)=\sum_{n=1}^N\left\{\operatorname{mod}(n,10)=2:1,0\right\}`
[](https://i.stack.imgur.com/hTMrX.png)
[Try it on Desmos!](https://www.desmos.com/calculator/zikegfft1e)
Explanation:
```
f(N)= a function taking in an argument of N
\sum_{n=1}^N summation from 1 to N
\left\{ starting piecewise
\operatorname{mod}(n,10)=2: if the remainder of n/10 is 2...
1 sum 1
, otherwise...
0 sum 0
\right\} end piecewise
```
Not too sure why I can't take out the `\left` and `\right` for the brackets(`{` and `}`). Theoretically it should work(I've taken out the `\left`'s and `\right`'s of all the other "left-right pairs"), but I guess Desmos doesn't allow it.
## Second Answer, 20 18 bytes:
Saved two bytes thanks to [@golf69](https://codegolf.stackexchange.com/users/94333/golf69)
`f(N)=floor(.1N+.8)`
[](https://i.stack.imgur.com/dhb3d.png)
[Try it on Desmos!](https://www.desmos.com/calculator/vozzazyef6)
Explanation:
My answer is equivalent to `f(N)=floor((N+8)/10)`, which is explained in [RGS's comment](https://codegolf.stackexchange.com/questions/200363/find-the-number-of-integers-in-the-range-from-1-to-n-that-ends-with-2?page=1&tab=oldest#comment476894_200364) under his answer.
[Answer]
## Python 3, 55 40 bytes
Any help with golfing it would be appreciated
```
lambda N:sum(x%10==2for x in range(N+1))
```
Lots of thanks to the commentors for helping me out( I have problems with memory, see names below)
[Answer]
# Haskell, 14 Bytes
```
f x=div(x+8)10
```
[Answer]
# [W](https://github.com/A-ee/w), 4 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
```
8+T/
```
Just another boring formula: Add eight, divide by 10. (W performs integer division if both operands are integers.)
# [W](https://github.com/A-ee/w) `d`, 5 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
```
[ⁿNy|
```
Uncompressed:
```
Tm2=Wk
```
## Explanation
```
W % For every number in the range [1 .. N]:
% Keep all that satisfies:
Tm % After modulo by 10,
2= % The result is equal to 2
k% Find the length of that
```
[Answer]
# Powershell, ~~50~~ 20 bytes
```
1.."$args"-match"2$"
```
$args are arguments to pass as number.
[Answer]
# [Julia 1.0](http://julialang.org/), 12 bytes
```
x->(x+8)÷10
```
[Try it online!](https://tio.run/##yyrNyUw0rPifZvu/QtdOo0LbQvPwdkOD/wVFmXklOXkaaRqGmppcCJ4RCs8UhWdogMoFqv0PAA "Julia 1.0 – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 25 bytes
```
{(1..it).count{it%10==2}}
```
[Try it online!](https://tio.run/##DYyxCsMwDAX3fMVbCtJQ42QMuJ0L/QmTxCCayiUoWYy/3fUtd9N9su2i7Yo70gx6qTHuD3QjtEKjc2LslnyqFbHb6EOYam3pVHyjKDHKgM7vEDVKdGxxfYtuxE9nuW96zJ55qGiT/wM "Kotlin – Try It Online")
[Answer]
# [Pyt](https://github.com/mudkip201/pyt) [sic!], 3 bytes
Finally found the right language. I had a now-deleted answer in Vim, but it returned the empty string for an input of 1 :(
```
8+₀
```
Explanation:
```
8 In fact, I have no idea whether is this language stack-based, I guess it pushes 8
+ add that 8 to the seemingly-implicit input
₀ divide by 10. There are also instructions to divide by numbers from 2 to 11 :)
```
[Try it online!](https://tio.run/##K6gs@f/fQvtRU8P//0YA "Pyt – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
#ȯ=2→dḣ
```
[Try it online!](https://tio.run/##yygtzv7/X/nEelujR22TUh7uWPz//39DAwMA "Husk – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
The straightforward solution of adding 8 and floor dividing by 10 would be a byte shorter: `+8 zA`. But where's the fun in that?!
```
õ_ì̶2
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=9V/szLYy&input=MTAw)
```
õ_ì̶2 :Implicit input of integer U
õ :Range [1,U]
_ :Map
ì : To digit array
Ì : Last element
¶2 : Is equal to 2?
:Implicit output of sum of resulting array
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 7 bytes
```
ṾṪ=”2)S
```
[Try it online!](https://tio.run/##y0rNyan8///hzn0Pd66yfdQw10gz@P///8YGAA "Jelly – Try It Online")
But there's already 2 shorter answers I hear you say... Well, this doesn't use mathematics but rather uses strings
[Answer]
# [Scala](http://www.scala-lang.org/), 11 bytes
```
n=>(n+8)/10
```
[Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFBQzVWWmKOQZqXgmVeiYGsHof7n2dpp5GlbaOobGvw31CvJ1zA0MNDUS8svSk1MztDIBCksKMrMK8nJA3K0FZRAAkpARppGpqamJlftfwA "Scala – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~5~~ 4 bytes
*Edit: -1 byte thanks to Jo King*
```
hs+8
```
[Try it online!](https://tio.run/##yygtzv7/P6NY2@L///@GBgYA "Husk – Try It Online") or [check all test cases](https://tio.run/##yygtzv6f@6ip8X9GsbbF////ow11jHRMdQwNdAyNdIwMdIwNdExNdCzNgSIGsQA)
**How?**
```
# implicit input
+8 # plus 8
s # convert to string
h # remove last character
# (so hs effectively divides by 10)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 17 bytes
```
f(n){n=(n+8)/10;}
```
[Try it online!](https://tio.run/##DchBCoAgEADAu69YAmEXlYwIAquXdAnF2ENbRDfp7dYcJ7o9xlozChWZUcxIbefDW4@NBamofN7I8gDPPvDUD8EYJgVw3f9mbHQCt4BOqzSWLWRkoqDe@gE "C (gcc) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 17 bytes
```
f(n){n+=8;n/=10;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOk/b1sI6T9/W0MC69n9mXolCbmJmnkZZfmaKJlc1lwIQFBQBhdM0lFRTYvKUdBTSNAw1Na2xyxjhlDHFKWNogFsKt3lGuHUZ45YyNcEpZWmOx4VgE2v/AwA "C (gcc) – Try It Online")
Alternative 17-byter:
# [C (gcc)](https://gcc.gnu.org/), 17 bytes
```
f(n){n=n/10.+.8;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs82T9/QQE9bz8K69n9mXolCbmJmnkZZfmaKJlc1lwIQFBQBhdM0lFRTYvKUdBTSNAw1Na2xyxjhlDHFKWNogFsKt3lGuHUZ45YyNcEpZWmOx4VgE2v/AwA "C (gcc) – Try It Online")
Alternative 17-byter
# [C (gcc)](https://gcc.gnu.org/), 17 bytes
```
f(n){n=(n+8)/10;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs9WI0/bQlPf0MC69n9mXolCbmJmnkZZfmaKJlc1lwIQFBQBhdM0lFRTYvKUdBTSNAw1Na2xyxjhlDHFKWNogFsKt3lGuHUZ45YyNcEpZWmOx4VgE2v/AwA "C (gcc) – Try It Online")
[Answer]
# [Clojure](https://clojure.org/), 28 bytes
```
(defn e[n](int(/(+ n 8)10)))
```
Ungolfed:
```
(defn ends-in-two [n]
(int (/ (+ n 8) 10)))
```
Test harness:
```
(println (e 1))
(println (e 2))
(println (e 5))
(println (e 10))
(println (e 12))
(println (e 20))
(println (e 30))
(println (e 54))
(println (e 97))
(println (e 100))
```
[Try it online!](https://tio.run/##S87JzyotSv3/XyMlNS1PITU6L1YjM69EQ19DWyFPwULT0EBTU5OLy1ohJLW4RCEjsSgvtbjYikujoAioKidPQSNVwRCoAJlvhMY3ReODjEQVQNdhhK7CGF3A1ARNwNIcwxagnv//AQ "Clojure – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 6 bytes
GolfScript has no decimal support, that's why the `/` works.
```
~8+10/
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/v85C29BA//9/SwMA "GolfScript – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 5 bytes
```
/+8QT
```
[Try it online!](https://tio.run/##K6gsyfj/X1/bIjDk/39DIwA "Pyth – Try It Online")
### Explanation
```
/+8QT
Q : Variable containing evaluated input
+8 : Add 8 to it
/ T : Divide result of add by 10
```
[Answer]
## [Javascript (node)](https://nodejs.org/en/) - 25 Bytes
```
f=n=>n?(n%10==2)+f(n-1):0
```
[Try it online!](https://tio.run/##dc7LCoMwEIXhvU@RjZAgyky8FIVpn0WsKYpMpIqvH8FAFzVZf3DOP/dHvw3fad1ztu/ROUNMT35JThGItMqM5BxVB26wvNllLBb7kcJIVIJIgFDJH@gL8A51DBCi4sd04AViUnopAwHVJc1d2ocvgFAc/Myd)
[Answer]
# [JavaScript (V8)](https://v8.dev/), 15 bytes
```
f=n=>(n+8)/10|0
```
[Try it online!](https://tio.run/##FctLCsMgEADQq8xS6SQdbUIswex6itKFFc2HoEGDq97dttsHbzPFZJvW42yKqsUkCO@UQcNToMQeBaGQKAlvhH2H9@En9Bqr10FPLFwUvwr6UP2v1sf0MHZhDvQENoYcd9fucWaeOc75WL8 "JavaScript (V8) – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~18~~ 17 bytes
```
<?=$argn/10+.8|0;
```
[Try it online!](https://tio.run/##K8go@P/fxt5WJbEoPU/f0EBbz6LGwPr/f0OTf/kFJZn5ecX/dd0A "PHP – Try It Online")
-1 bytes thanks to @oxgeba
[Answer]
# Python 3, ~~22~~ 18 bytes
```
lambda n:(n+8)//10
```
Thanks to @JoKing for suggesting to use integer division.
[Answer]
# [R](https://www.r-project.org/), ~~18~~ 15 bytes
Thanks @Giuseppe! Guess I didn't really know what the %/% operator did.
```
(scan()+8)%/%10
```
[Try it online!](https://tio.run/##K/r/X6M4OTFPQ1PbQlNVX9XQ4L8hlxGXKZehAZehEZeRAZexAZepCZelOVDE4D8A "R – Try It Online")
] |
[Question]
[
In C++, there exists a [`a <=> b` three-way](https://stackoverflow.com/questions/47466358/what-is-the-spaceship-three-way-comparison-operator-in-c) [comparison operator](https://en.cppreference.com/w/cpp/language/operator_comparison) that, for numerical types, does the following:
* If `a < b`, then return a negative number.
* If `a = b`, then return a (mathematically speaking) sign-less number.
* If `a > b`, then return a positive number.
## The Challenge
Implement the **shortest** full program, function, method, or custom operator such that, when given two numbers of the same type `a` and `b`,
* If `a < b`, then return `-1`.
* If `a = b`, then return `0`.
* If `a > b`, then return `1`.
### Notes
* If you're writing in x86 assembly, [this question](https://codegolf.stackexchange.com/questions/259087/) may be of use to you.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 2 bytes
```
×-
```
[Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=R3RsdCDihpAgw5ctCkd0bHTCtMKoIOKfqCAz4oC/NiwgM+KAvzMsIDbigL8zIOKfqQ==)
```
× # sign of
- # left arg minus right arg
```
---
# [BQN](https://mlochbaum.github.io/BQN/), 3 bytes
```
<->
```
[Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=R3RsdCDihpAgPC0+Ckd0bHTCtMKoIOKfqCAz4oC/NiwgM+KAvzMsIDbigL8zIOKfqQ==)
This clearly isn't the shortest possible solution in [BQN](https://mlochbaum.github.io/BQN/) (see above), but it is particularly visually appealing due to its similarity to the C++/Perl/etc `<=>` operator.
```
<-> # 3-element train abc
# ( x abc y expands to: (x a y) b (x c y) )
< # left arg < right arg
- # minus
> # left arg > right arg
```
(a similar 'reverse-comparison' operator - [`>-<`](https://mlochbaum.github.io/BQN/try.html#code=THRndCDihpAgPi08Ckx0Z3TCtMKoIOKfqCAz4oC/NiwgM+KAvzMsIDbigL8zIOKfqQ==) is also possible and also [I think] looks nice)
[Answer]
# polyglot, 3 bytes
```
<=>
```
[Try it in Perl!](https://tio.run/##K0gtyjH9X1CUmVeiYPzfxtbuv5k1hKcUk6dkzQWVUQDKKBhjkTHDlPkPAA "Perl 5 – Try It Online")
<Insert [other languages](https://en.wikipedia.org/wiki/Three-way_comparison#High-level_languages) that already have the exact `<=>` operator here>
[Answer]
# [Python 2](https://docs.python.org/2/), 3 bytes
```
cmp
```
A built-in function that accepts \$a\$ and \$b\$ and returns \$a \lt = \gt b\$.
**[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPzm34H9BUWZeiUaahqmOgrmm5n8A "Python 2 – Try It Online")**
[Answer]
# JavaScript (ES6), 17 bytes
Expects `(a)(b)`.
```
a=>b=>(a>b)-(a<b)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i7J1k4j0S5JU1cj0SZJ839yfl5xfk6qXk5@ukaahpGmhrGmJheGoBGGoDFY8D8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 22 bytes
```
lambda a,b:(a>b)-(a<b)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ8lKI9EuSVNXI9EmSfN/QVFmXolGmoahjpGmJheCZ4jEMwLx/gMA "Python 3 – Try It Online")
Python 3 lacks the builtin `cmp`
-1 thanks to Dominic van Essen
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
-±
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCItwrEiLCIiLCI2XG44Il0=)
Takes input as b then a. Simply subtract the two numbers and get the sign of the result.
Alternatively a more fun looking, symbol only answer comes in at 17 bytes:
## [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes
```
-:::-<[::-$~-|:]/
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCItOjo6LTxbOjotJH4tfDpdLyIsIiIsIjEwXG4xMiJd)
Also takes b then a. This answer is purely just for fun, and could be made shorter by using numbers and letters (`-D0<[N|:]/`).
### Explained
```
-:::-<[::-$~-|:]/
-: # Subtract the two numbers and push a copy
::- # Push 0 to the stack by subtracting the top of the stack from itself
< # Is the original top of the stack < 0?
[ # If so:
:: # Duplicate the top of the stack twice. This could just be `D`, but that wouldn't be a symbol.
- # Subtract those copies to get 0 again.
$~- # Push the 0 under the top of the stack, and subtract without popping. The stack is now [0, a - b, -(a - b)]
| # Otherwise:
: # Just duplicate the top of the stack
] # this whole if statement was to make sure there was [a - b, abs(a - b)] as the stack
/ # Divide the top two stack items to get either -1, 0 or 1. negative/positive = -1, 0/0 = 0 and positive/positive = 1
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 14 bytes
```
Float::compare
```
[Try it online!](https://tio.run/##jY4xC8IwEIVn8ysytlCDxUFo1UVwc@ooDmdtSmrShORakNLfHmMoOOpNd@9973EdjLDuHk8vlNEWaRduNqCQ7KSVAQuobUnMcJeiprUE5@gFRE8nQsM4BAz6F92fpQY8Un7wcSuKOnqNL2NgKVpyoxYPqkJdUqEVfXu9UbCtSyeyql4OG8X0gMwEC2WfcLZ0JTnPcp6m5W9s@w@24dkucp8PZzL7Nw)
## [Java (JDK)](http://jdk.java.net/), 13 bytes
```
Long::compare
```
[Try it online!](https://tio.run/##jY49D4IwEIZn@ys6QoKNxMEE1MW1TozG4UQgRfqR9iAxhN9eCyFx1Jvu7n3uybUwwLZ9vryQRlukbZhZj6JjFy0NWEBtc2L6RydKWnbgHL2CUHQkNJRDwLD/okeuVXOm9cnPTZaVS1L5fMFXzXo1aPGkMsiiAq1Qze1OwTYuHsmmeDusJNM9MhMi7FRUs9UVpTxJeRznv7H9P9iOJ4eFmz@cyOQ/)
Only supports integers.
[Answer]
# Excel, 12 bytes
```
=SIGN(A1-B1)
```
where `A1` and `B1` contain *a* and *b* respectively.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 1.5 bytes (3 nibbles)
```
`$-
```
```
`$- # full program
`$-$@ # with implicit args shown;
`$ # get sign of
$ # arg1
- # minus
@ # arg2
```
[](https://i.stack.imgur.com/2Reql.png)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 9 bytes
```
1&-_1^-%-
```
[Try it online!](https://ngn.codeberg.page/k#eJxLszJU0403jNNV1eXiSos2tDaIBVK6JtaGINrY2hhEGejBxCEsAFB/DI8=)
K lacks a sign builtin, which makes this a bit trickier.
`-%-` negative square root of a-b. This is negative if a>b, zero if a=b and `-0n` (negative null value) if a<b.
`1^` Replace null with 1.
If the input was restricted to integers, `0 1'` would calculate the sign, leading to `0 1'-` as a full solution.
[Answer]
# [Go](https://go.dev), ~~52~~ 51 bytes
```
func(a,b int)int{n:=1
for-1<n&&b-a<n{n--}
return-n}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZDBisIwEIbZa55i9CAJZMSwFESsdw-Cl70uxGKkaKcSUxGKT-KlCPtQ7tNssqlY9ZAM8__z_RlyuW7K5tbb62yrN2sodE4sL_aldcO-KVyfHbUFA-lP5QyOb5-mooxruYKcnPCnpkmqmCktqikNBivUU6oJ8czs2lWWkM4R_f0Qgf1_gQuo2dJ6fEfccCUTITp9ItVL_-yjkviiJBLVmxJmWFbSwcFCn768BVW4UvgOlY8E3O2cuvYIHtjcK1ENyD1nNgPVpR9T2DIIinX2iTOyTXxaNUqyjfFW-2NNE-sf)
By @Kevin Cruijssen. Uses a `for` loop to get the return value rather than a chain of `if`s.
### Changelog
* -1 by @naffetS
### Old answer, 56 bytes
```
func(a,b int)int{n:=0
if a>b{n=1}
if a<b{n=-1}
return n}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVC9asMwEKarnuLqSQKpWIMhlNh7h0KXrgXZREYkPgdFLgXjJ-liCn0o92kqRTZxkkG6u-9Ph75_6nacHo-q2qt6B40ySExzbK17SnTjEvKpLGjIfzunxWba6A4rqngJBh3zp8fnPCVGgyrKHnM5nPtt6IUf7M51FgGH6P97YCHg_Axl0JM36zMOSDWVPGNsNWdc3szXvJBc3CAZF_IOCRpStXhy8Kq-3j0FXbhy-AiVpgwW2uCaTuFie_FIRINlySkKkGv3RSVmjwBJVvtEDZ8Tr1aNEJ9jPDX_2DjG-g8)
Go doesn't have any sort of built-in `abs` like C, or default type methods like Java, so a function it is. Go also doesn't have ternary expressions, so the old-school "set and check" pattern is needed.
[Answer]
# [J](http://jsoftware.com/), 3 bytes
```
*@-
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqCjYKBgBcS6egrOQT5u/7UcdP9rcqUmZ@QrGCukKZghmMYIpgGUqWcCEtcz/Q8A "J – Try It Online") The 3-byte solution `>-<` featured in a few other answers also works for the same byte count (greater-than minus less-than).
Works for any numeric type. Anonymous dyad.
## Explanation
```
*@-
* sign
@ of
- difference
```
[Answer]
# [Raku](https://raku.org/), 8 bytes
```
+(*cmp*)
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfW0MrObdAS/O/tUJxYqWCkkq8gq2dQnWaQo1KfK2SQlp@kYKNoYGCkZ2Ogo2RgqEBiAbygYz/AA "Perl 6 – Try It Online")
`cmp` is Raku's built-in smart comparison operator, and `*cmp*` is an anonymous function that passes its arguments to that operator.
Unfortunately for this challenge, `cmp` doesn't return -1, 1, or 0, but one of the enumerated values `Less`, `More`, or `Same`, so the prefix `+` operator converts those values into their integer values.
The non-golfy solution would be to just compose the two operators:
```
&prefix:<+> o &[cmp]
```
[Answer]
# [Kotlin](https://kotlinlang.org), 16 bytes
```
Float::compareTo
```
[Try it online!](https://tio.run/##y84vycnM@59WmqeQm5iZp6FZzVWWmKOQZqXglpOfWKKnAaY0FXTtFDzzShRsFf6DBayskvNzCxKLUkPy/1sXFGXmleTkaaRpGKbpKBilaWpyoQoZYgoZgIRq/wMA "Kotlin – Try It Online")
Annoyingly, longer than Java.
# [Kotlin](https://kotlinlang.org), 14 bytes
```
Int::compareTo
```
[Try it online!](https://tio.run/##y84vycnM@59WmqeQm5iZp6FZzVWWmKOQZqXgmVeipwEkNBV07UAcBVuF/0DKyio5P7cgsSg1JP@/dUFRZl5JTp5GmoahjoKRpiYXioAhuoABUKD2PwA "Kotlin – Try It Online")
Works only on ints (I edited this after seeing that Java got edited).
[Answer]
# [R](https://www.r-project.org), 15 bytes
```
\(a,b)sign(a-b)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhbrYzQSdZI0izPT8zQSdZM0IaJb0jQMdYw0uUCUIYgyAlIQqQULIDQA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.S
```
Builtin. Takes the inputs in the order \$b,a\$.
[Try it online.](https://tio.run/##yy9OTMpM/f9fL/j/fyMuUwA)
**Explanation:**
```
.S # Compare the second (implicit) input-integer `a` with the first (implicit)
# input-integer `b`, and push -1 if a<b; 0 if a==b; or 1 if a>b
# (which is output implicitly as result)
```
[Answer]
## HP‑41C series, ~~9~~ 11 Bytes
`a` needs to be entered first, then `b`, so `a` is placed in the Y register and `b` in the X register.
```
01♦LBL⸆S 5 Bytes global label requires 4 + m Bytes
02 SF 24 2 Bytes ignore “out of range” errors, and instead
return ±9.999999999E99 as an approximation
03 − 1 Byte X ≔ Y − X
04 X≠0? 1 Byte if X = 0 then skip next line
05 SIGN 1 Byte ↯ `SIGN` returns `1` for zero
06 RTN 1 Byte `RTN` does not affect local label search
```
[Answer]
# [Golfscript](http://www.golfscript.com/golfscript/), 7 bytes
```
.~>\~<-
```
read from stdin
```
# explanation:
. # duplicate
~ # unpack
> # gt
\ # store the result and get duplicated stdin again
~ # unpack
< # lt
- # gt-lt
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 2 bytes
```
cm
```
[Try it online!](https://tio.run/##SyotykktLixN/V9dkPo/Ofd/bXjOf0MFQwMDAy4QoWDIBeQBAA "Burlesque – Try It Online")
Built in compare.
[Answer]
# PIC16F88x Machine Code, 6 words (84 bits)
A function that expects `a` to be at address 0x70 in memory, and `b` to be in register W. Returns the result in register W.
The PIC16 uses 14-bit instruction words. Because the number of words is even, this function can be represented exactly in hex with no padding:
```
0bc1d03d001ff0dfff401
```
In mpasm syntax, that is:
```
SUBWF 0x70,F ; Subtract W from the value at 0x70. Leave the result at
; 0x70.
BTFSC STATUS,2 ; Check the zero flag (bit 2 of the STATUS register) and skip
; the next instruction if it's not set.
RETLW 0x00 ; Set the W register to 0 and return.
BTFSC 0x70,7 ; Skip the next instruction if the MSb of the value at 0x70
; is 0 (i.e. the result of subtraction is positive).
RETLW 0xFF ; Set the W register to 0xff (-1) and return.
RETLW 0x01 ; Set the W register to 1 and return.
```
Bit for bit, this is encoded as:
```
00 0010 1111 0000
00 0010 SUBWF
111 0000 0x70
1 F
01 1101 0000 0011
01 11 BTFSC
000 0011 STATUS
01 0 2
11 0100 0000 0000
11 01 RETLW
0000 0000 0x00
00 (ignored)
01 1111 1111 0000
01 11 BTFSC
111 0000 0x70
11 1 7
11 0111 1111 1111
11 01 RETLW
1111 1111 0xff
11 (ignored)
11 0100 0000 0001
11 01 RETLW
0000 0001 0x01
00 (ignored)
```
The PIC16F88x family of microcontrollers have four memory banks of 128 bytes each. (These are actually bytes this time, and not 14-bit words.) Which one is used depends on the value of the STATUS register. However, addresses 0x70 through 0x7f are the same on all banks, so by placing the operands there the function doesn't have to change banks to access them. I'm not aware of any standard calling convention as far as argument location goes, but the return value being in register W is standard (hence the existence of the `RETLW` instruction).
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 5 bytes
```
-/<?,
```
[Try it online!](https://ngn.codeberg.page/k#eJxNikEOgjAQRfc9xSxcaOJQRFlITbyEO0JCxUEI0GJbIsTo2a1EE5P5mf/yX5kgPxzXjJ2SxyKdXiYpIYBR5LoRy7yUdStGMQmzyp7eSQFgAxAK/7IZceerAPwibP35NZwxDP5l/OFHZpxVzvU24bzQF7rqtgysk0VDY1FJdaWg0B2/DWRdrZXlUbyP4pjXXd9SR8qhq8jHEOFdTujlXpraaoW6JyOdNui7GrozGcvecr9DqA==)
* `,` concatenate the inputs
* `<?` grade-up the distinct-ified result from above; if the first value is smaller than the second, the result will be `0 1`; if larger, `1 0`, if the same, `,0`
* `-/` run a minus-reduce and (implicitly) return
An alternative version that takes the input as a list of two numbers is `-/<?:`.
[Answer]
## Pascal, 55 Bytes
```
function f(a,b:real):real;begin f:=ord(a>b)-ord(a<b)end
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 29 bytes
```
\d+
$*
(1*) \1
0
1+0
1
01+
-1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFi0vDUEtTIcaQy4DLUBuIuQwMtbl0Df//N1Yw5zJVMOUyVzAGAA "Retina 0.8.2 – Try It Online") Link includes test cases. Only works on non-negative integers. Explanation:
```
\d+
$*
```
Convert to unary.
```
(1*) \1
0
```
Try to subtract; this will leave `0` if `a = b`.
```
1+0
1
```
If `a > b` then replace the result with `1`.
```
01+
-1
```
If `a < b` then replace the result with `-1`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
NθNηI⁻›θη‹θη
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oLmZ8B5AcUZeaVaDgnFpdo@GbmlRZruBelJpaAFOsoZGjqKPikFhdD2EBg/f@/sYL5f92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @Arnauld's JavaScript answer.
Alternative approach, also 12 bytes:
```
≔⁻NNθI÷θ∨↔θ¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DNzOvtFjDM6@gtMSvNDcptUhDU0cBhQvkF2pacwUUZeaVaDgnFpcAVZe4ZJZlpqRqFOoo@BdpOCYV5@eUlgC5QLWGmkBg/f@/sYL5f92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Divides the difference between the numbers by the absolute value of the difference, or `1` if that's zero.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 2 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
,σ
```
[Try it online.](https://tio.run/##y00syUjPz0n7/1/nfPP//0YKplymYGwEAA)
**Explanation:**
```
, # Subtract the second (implicit) input by the first (implicit) input: b-a
σ # Get the sign of that (-1 if <0; 0 if ==0; 1 if >0)
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 22 bytes
This is practically @TobySpeight's answer now since he changed the entire algorithm.
```
f(a,b){a=(a>b)-(a<b);}
```
[Try it online!](https://tio.run/##PY0xCoRADEV7T/ERlAQypWzh6klskhHFYodl1048@xhFTJEi/738GOYYc55IxXjTjrQ3DqRv43bPH10ScbEVuGdJK1Rg7XP5R00TldWIaiwFtae1u0/@/blzAeIEQu97SE6ebwRnMYxd2HOD1wE "C (gcc) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 4 bytes
```
aCMb
```
There's a built-in operator for that. (Fun fact: in my original designs for Pip, this operator was `<=>`, until I realized that having a 3-character operator in a golfing language was silly.)
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZLEp19kyBMqMjKaGMdBWM9Q5NYqAAA)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 3 bytes
```
._-
```
[Try it online!](https://tio.run/##K6gsyfj/Xy9e10jB5P9/AA)
Defines a function which takes two inputs b, a.
### Explanation
```
- # subtract the second argument from the first
._ # take the sign
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~13~~ 3 bytes
```
cmp
```
[Try it online!](https://tio.run/##yyrNyUw0rPifZvs/Obfgv0NxRn65QpqeRrSJjqmOWaxOtCmQNo3V/A8A "Julia 1.0 – Try It Online")
-10 bytes thanks to MarcMush: use `cmp`
## Alternate solution, 13 bytes
```
a%b=sign(a-b)
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/P1E1ybY4Mz1PI1E3SfO/Q3FGfrlCtImOqY5ZrIKeqkK0KZBpGvsfAA "Julia 1.0 – Try It Online")
## Alternate solution (15 bytes)
```
a%b=(a>b)-(a<b)
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/P1E1yVYj0S5JU1cj0SZJ879DcUZ@uUK0iY6pjlmsgp6qQrQpkGka@x8A "Julia 1.0 – Try It Online")
Some operators have lower precedence than `<` and `>`. Redefining one of them as `-` removes the need for parentheses but doesn't save bytes overall:
```
~=-
a%b=a>b~a<b
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v85WlytRNck20S6pLtEm6b9DcUZ@uUK0iY6pjlmsgp6qQrQpkGka@x8A "Julia 1.0 – Try It Online")
[Answer]
# [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 21 bytes (4×7=28 codels)
```
vekabrA krbtkFbks?Tbb
```
[Try Piet online!](https://piet.bubbler.one/#eJxVisEKwjAQRH9F5jyBbFq0ya8kOUiNUKhpIXoS_92NXnQZ2Nn39ol5uxSEGIVyoqccKSOd7swoXonrwHY1dDRqGyiTItXiv6zH_yZnopUdAcYYEOty0y5WR6_SZoTreW2FWOr-uH_cwdlU9T1V99_F4vUGIvQocg)

Just a minor variation from [my answer to "output the sign"](https://codegolf.stackexchange.com/a/246527/78410). Takes two numbers and subtracts instead of taking just one number, and then the rest follows the same logic.
```
A1->A4
inN inN - [a-b] Take two numbers and subtract
A4->A7->B7->B5
dup 1 ! > ! [a-b a-b<=0]
CC+ [a-b] Continue on row B if a-b<=0, shift to row C otherwise
B5->B2
! 1 - [(a-b==0)-1] -1 if a-b!=0 (which implies a-b<0), 0 otherwise
C5->C2
1 [a-b 1] Ignore the previous number and push 1
C2->C1
outN Print the top number and exit
```
] |
[Question]
[
The task is simple: given a 32 bit integer, convert it to its floating point value as defined by the IEEE 754 (32-bit) standard.
To put it another way, interpret the integer as the bit-pattern of an IEEE binary32 single-precision float and output the numeric value it represents.
## IEEE 754 single precision
[*Here is a converter for your reference.*](https://www.h-schmidt.net/FloatConverter/IEEE754.html)
Here is how the format looks, from [Wikipedia's excellent article](https://en.wikipedia.org/wiki/Single-precision_floating-point_format):

The standard is similar to scientific notation.
The sign bit determines whether the output is negative or positive. If the bit is set, the number is negative otherwise it is positive.
The exponent bit determines the exponent (base 2), it's value is offset by 127. Therefore the exponent is \$2^{n-127}\$ where n is the integer representation of the exponent bits.
The mantissa defines a floating point number in the range \$[1,2)\$. The way it represents the number is like binary, the most significant bit is \$\frac 1 2\$, the one to the right is \$\frac 1 4\$, the next one is \$\frac 1 8\$ and so on... A one by default is added to the value, [implied by a non-zero exponent](https://en.wikipedia.org/wiki/Single-precision_floating-point_format#Exponent_encoding).
Now the final number is: $$\text{sign}\cdot 2^{\text{exponent}-127}\cdot \text{mantissa}$$
## Test cases
```
1078523331 -> 3.1400001049041748046875
1076719780 -> 2.71000003814697265625
1036831949 -> 0.100000001490116119384765625
3264511895 -> -74.24919891357421875
1056964608 -> 0.5
3205496832 -> -0.5625
0 -> 0.0
2147483648 -> -0.0 (or 0.0)
```
For this challenge assume that cases like `NaN` and `inf` are not going to be the inputs, and subnormals need not be handled (except for `0.0` which works like a subnormal, with the all-zero exponent implying a leading 0 bit for the all-zero mantissa.) You may output `0` for the case where the number represented is `-0`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# [Python](https://www.python.org), 55 bytes
Correct as per original challenge description (always add 2^23 to mantissa) but not per IEEE.
```
lambda i:-(i>>31or-1)*2**((i>>23)%256-129)*(i/8**7%4+4)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxNCsIwFIT3niIbIYkN5uXl56Vgz-HCTUWCAW1LqQvP4qYgeidvY8SuZuZjZh7v4T6d-25-pt3hdZuSok-4tNfjqWW5Vjw3DUI_KhDSSMl_2aBYG-cVmCgkz1uSMqztxoplvk_9yDLLHQMdyBlEhKpYHyAG0sWiJ4RoY4XGWwdA0RXqfPTWaypUOxtLx9QrNoy5m3jiWSz_8_zXLw)
Direct bit twiddling, no casting.
# [Python](https://www.python.org), 69 bytes
At last proper IEEE, I think (thanks @Neil).
```
lambda i:-(i>>31or-1)*2**((e:=i>>23&255)-126-(e>0))*(i/2**23%1+(e>0))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY1BDoIwEEX3nqIbTUEaOzO0tCSw8xZuMEJsokAILjyLGxKjd_I2jqKbmZ-XP_Nuz_46Hrt2ujfF7nEZG-Ve21N13h8qEXIlQ1kSdIOCKMY4lrLOC0ZIKzQmUoBWybrUURTLsOEC0hLWM_k9G5puEEGEVoDOnEEigoSjzcBnTnMk6wh86hNCmxoA5w1TY71NrXZMtUk9dzDRCSv4_CPC75wz5QvRD6EdZSPD3zxN834D)
# [Python](https://www.python.org) NumPy, 47 bytes
```
lambda i:int32(i).view("f4")
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY1LCsIwFEXnruLRUStV829ScB8OnFQ0-MB8CKnStTgpiO7J3Rioo3s53M_zE6d8DX5-2f3xPWa70d_dbXCn8wDYo8-c1dhs73h51JUVVbOyKTjwo4sToIsh5fW_drAhAQJ6oKTTknHOaVus6qjpNCmWK82pEablTAlJqTayUKmMEoroQokUpmRYv4KYynlty3mz7M_zoj8)
Boring use of builtin "view" or "reinterpret" casting. Note that we can save the "u" from `uint32` without issues.
[Answer]
# x86 32-bit machine code, 5 bytes
```
D9 44 24 04 C3
```
[Try it online!](https://tio.run/##ZVFNb9swDD1bv4JzEUCKncDfsZOmpx43dAgGbECagyPJjgBFLmyncxDkr8@lgm7YuotEPZJPj498VnM@jnfKcH0SEu67Xqhmfngg/0Ba7T9irTK1xYhuTA2iOe21hIoq04NhK3htlABpBGUrUnZHoLBxKZnXutmXGipSLZ1KC3j8/rR5hK/fNrCV3Qt4kOyI08qeYOuSMBewnVjOY6nMjbxsa@4DP5QtTKf4eGXkQhzemK4Hm@/5dgdruITBIk@jOI5DHzDOFmGxyAMbx1keh0VS@BBHWZKGYV6kFk@zIkuyILd4kCYFlkXXFXEs64CUM2Q64x0g9vOgcFzqeQPcQ8aI47ygIX1F3UkYKZhEyTzMP1fPxvWtomHnoze3gOFEf4qfzZeSH5SRwBshl67NDe9fiAYuv@tgEkQ/kOq8pvRkOlUbKW4eTFnFtoPn7djqCu@i/qtAkZ/W8BFGh/@WAnSiYH/uZcduqgebxE2cWmPlXMk4/uKVLutunB3jCA9c6xp7pX4D "C (gcc) – Try It Online")
Following the `cdecl` calling convention, this takes the 32-bit integer on the stack and returns the result on the FPU register stack.
In assembly:
```
f: fld DWORD PTR [esp + 4]
ret
```
([`fld`](https://www.felixcloutier.com/x86/fld) does everything that is needed. The integer is placed below the return address on the stack, hence the `+ 4` to get to it.)
[Answer]
# Rust, 14 bytes
```
f32::from_bits
```
Not even reached the 30 byte min limit for posts
[Answer]
# [C (GCC)](https://gcc.gnu.org) without reliance on undefined behaviour, ~~41~~ 40 bytes
```
#define f(x)((union{int a;float b;})x).b
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBJuXMvOSc0pRUBZvikpTMfL0Mu6WlJWm6Fjc1lFNS0zLzUhXSNCo0NTRK8zLz86oz80oUEq3TcvITSxSSrGs1KzT1kqDqfUFyuYmZeRpgRUXpyToKyRmJRQpaWkBOmaZCNVdBEVAqTUNJVc_YKE1JB2iyoYG5hamRsbGxoaamNVdRaklpUZ6CgTVXLcTQBQsgNAA)
Type-punning through pointers does normally work, but the compiler is free to do strange optimisations which can stop it working. A union makes this explicit in ways the compiler understands. It can also potentially be evaluated at compile time instead of at run time.
Note that it's best practise in C/C++ to use parentheses around the input value to a function-like macro and around the result, so you don't get unwanted interactions with precedence rules if this is used in a more complex statement. This would add 4 extra bytes to the total. For the tests defined in the question, we don't need this.
(Thanks @ceilingcat for spotting an unneeded space.)
[Answer]
# C++ (GCC / Clang / MSVC), 39 bytes
```
#define f(x)__builtin_bit_cast(float,x)
```
[Try it online!](https://godbolt.org/z/xnY5PMazz)
[Answer]
# [Factor](https://factorcode.org/), 10 bytes
```
bits>float
```
[Try it online!](https://tio.run/##RZC9TsRADIT7PMXyAFnZa69/QLoW0dAgKkQRopw4AXchWQqEePawpyPKlPY3M5b3XV9O0/L4cHd/ex0@uvIa5uHzazj2wxzGaSjle5wOxxJumuanCVUIajkREYar0O7qhCIyVCGwA6OyAYtpXnFRdDVY8RQVzziQIYtrkixphUmM0NlXGOKFrek1HFEQnYx181ASzojm@eJplWNiRzdHysoJt1OyuLCAbelrBmT2Wp3@N23dnAt@w1OzvBzKvNu/n7qyPNcXjWEuXf8Wlz8 "Factor – Try It Online")
[Answer]
# [Java](https://en.wikipedia.org/wiki/Java_(programming_language)), 21 bytes
```
Float::intBitsToFloat
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NYw9CsIwGIb3niIIQgsarEEsrTo4FByc6iYOsTblkzQJzRdBxJO4dNAjeJjexp_q9P7xvLf7kZ9400qojK6RfBJ1CJIKp3IErWj6M4mXS24tWV-M20vIiUWObzlpOJCKg_IzrEGV2x0PLt6fmq0UFmVRD1KpOS6IIHPycCiG0fPbxDEoXALajf7mbmtZkp0tFhXVDql536Lwe33KxqI3EJQbI89-OJpGkzFjLAyCxLteO7RpOn0B)
Builtin :P
[Answer]
# JavaScript (ES6), 50 bytes
*-16 bytes (!) thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)*
```
n=>new Float32Array(new Int32Array([n]).buffer)[0]
```
[Try it online!](https://tio.run/##bY6xTsNADIZ3niJjMuRqn30@e2glFiSeoeoQSoKKojuUtiCePlxVCkPqzdb/@fvfu8/uuJ8OH6c25dd@HtZzWm9S/1U9jbk7kX@cpu67vhye09@6TbvGvZyHoZ@aLezmfU7HPPZuzG/1UCNEDZ6IsGmq1aqqKnLIUAaBDRgjK7BoDA8LUCJaVLiB3kW8gECKLBa9BPFLjEQJje2GgbtSxViEiIJopBzv0eSFA6JauNJtZOfZ0NSQQmSP94oGMWEB/Tcu/0JgK8X8b6YtmaKffwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes
```
Nθ≔X²¦²³η≔﹪÷θη²⁵⁶ζI∧ζ××⁺﹪θηηX²⁻ζ¹⁵⁰∨‹θX²¦³¹±¹
```
[Try it online!](https://tio.run/##RY1NCoMwEIX3PYXLCVjQpEqLK2k3QrUuegGrQQOa1PxY8PJpQls7MI9h3vdm2qGRrWhGawv@NLoy04NKmFG2y5ViPYdavNwChwEmKAyGv1GKzowCCq4vbGEdhdnbjktSp6sDa8m4hnOjNOS8gzUM7myiCj5aj0b9jnyjvrd/JeMOcKE4iRByzk3ClSrl4Q0isXcq2jeagpt9ZdYSHCWHU3ok2O6X8Q0 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input the integer.
```
≔X²¦²³η
```
Calculate `2²³` as it gets used often enough to make it worthwhile. (It was originally only used twice but it was still worthwhile then. I then golfed a byte off by introducing a third use, which also avoided the use of `Incremented` which is buggy on TIO, otherwise I would have had to have used ATO instead.)
```
≔﹪÷θη²⁵⁶ζ
```
Extract the exponent. This is needed because an exponent of `0` needs to be special-cased. (Normally this results in a subnormal, but fortunately the only subnormals that we need to support are `0` and `-0`.)
```
I∧ζ××
```
If the exponent is zero, output zero, otherwise output the product of...
```
⁺﹪θηη
```
... the bottom `23` bits of the input integer, with a `1` bit prepended, ...
```
X²⁻ζ¹⁵⁰
```
... 2 to the power of the exponent, adjusted by `150` instead of `127` to shift the mantissa bits by `23`, and...
```
∨‹θX²¦³¹±¹
```
... the sign bit.
[Answer]
# ARM Thumb machine code, 2 bytes
`arm-none-eabi-g++` defaults to `-mfloat-abi=soft`, so `float` is passed/returned in general-purpose integer registers. ([Godbolt](https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAMzwBtMA7AQwFtMQByARg9KtQYEAysib0QXACx8BBAKoBnTAAUAHpwAMvAFYTStJg1DIApACYAQuYukl9ZATwDKjdAGFUtAK4sGIAMwAbKSuADJ4DJgAcj4ARpjEINIADqgKhE4MHt6%2BAcGp6Y4C4ZExLPGJ0naYDplCBEzEBNk%2BfkG2mPZFDPWNBCXRcQlJtg1NLbntCmP9EYPlw5IAlLaoXsTI7BxUtKhMBADUVBARh6pLJgDsFsSYBOsMBwD6T7FedI4Mr4RPotPUu32pAO5xM/islwAIiYNABBGGwgD0iJ2e0OACpgCdBOjkhdrrd7sQGBAAG6oPDodFLZJgiGQg7Ig5uA4CWgAT2BDFQhzc1n5cIOR0BGKxp1x%2BJudweALR1Np4KukI4K1onAArLw/BwtKRUJw%2BZZrAcFGsNpgDuZ/DxSARNCqVgBrEDqwIAOgAnGYzIFLpIPV6NJIuL79JxJFr7XrOLwFCANLb7Ss4LAYIgUKgWMk6AlyJQ0Fmc4lGixgFxvQmaLQCAk4xBYlHYhFGuzODaC2xBAB5BgcqNYFiGYDiHW8fC3WqkzBx0chVQ1Lw1tu8U6dKO0PCxYgtjxYKMEYh4FjLlY7JjABQANTwmAA7l3koxlzJBCIxOwpC/5Eo1FHdGZ9CHFB%2BUsfRNzjSAVlQZJuhnABaLszAOOCWFRfY4KYJswUhU0qAIWNOhqboXAYdxPFaPQwjmMoKj0AoMgECY/C4Uh6O6AYaOGFjqlqARenGcjcm4wjeJ6GYOKGRJuJmJi9GmPoJIWKSVlNdZNj0A9MC2HhVQ1SNZ31DhYQAJQAWQOYBkGQA5yzdJCIA3BgvHOA4IENKxQIOXBCBIS0zGtYEPELehiD8/wzCWXg7VHJYVgQTAmCwRIIF0jgI1IY9/H8N0styvL8uCbVdUM2N40TGLSBTdMC2zEK8wgGqixAEsywrPgPlrSgG1nJtmGIVtuF4DtGAIHs%2B1nAchxHXVxyIvApxnXVMHnZBF20ldBDXWcNy3HcMC2XUDyPE8%2BAMC9rzvB8n0Gr833ET9%2BEERQVHUWddBYgwjGAo1QJ2iCUr1GDMngxCCK6TISLInJmJCUjFNoli2MyWTEbSBiGHhriOnBviZMEmGeO6fjZlKSS5Lx6HyYU6iya4FSzXUljNPW1LNVIIreEMkzzMs6zbPsxznKWVz3OsYFvKIUKrRY5lM1qhIwrpqKkydJJso0S5LnC9UNA1j11QADiysM0t4TLsvyy3csKqMStsMroq0ZM0wgJBGrqigGrlpqSy4csWKrGtiDrbrdV6ltn2G7tewGmbMEHIxprHPAJ0cBao2Whclxu1c1W2zdt363cDqiw9j0G08zqvG970fbUbUe4RRHu6RG%2Be383oCQCvtMH6bD%2B%2BAoKBgQQbMMG5ucCBXBRj1YfQTHKlYtHuhnpfCkyBeRkJuoKYorhZ%2B33HqdJpSt93oSD/EmnT%2BWVY1I/W1bhZk22Y56MjLMiyrJsrg7LdLhXLckiMLNyIEbBeXwJLRWgVvYhTCv4SK5UnapXSubHKVtLbs1tjGe2CZHYOlIM6SQ6tNba11pcfWRt/Am38PpYqOD8GxRNmPLBBkGEq1IFOYOENJBAA%3D))
ARM's standard calling convention passes the first arg in `r0`, which is also the return-value register. So all we need to do is return with `bx lr` (2 bytes).
```
// float f(int)
// machine code hex // assembly
70 47 bx lr
```
**The same trick can work for any ISA if you can justify a custom calling convention**. Normally that's fine, but on machines that use IEEE754 FP the challenge reduces to type-punning, and a calling convention that trivializes it is less interesting. e.g. for x86, you could normally justify taking an integer arg in XMM0, which is where you'd want a scalar `float`. ([Tips for golfing in x86/x64 machine code](https://codegolf.stackexchange.com/questions/132981/tips-for-golfing-in-x86-x64-machine-code/165020#165020))
## x86-64 machine code, with custom calling convention, 1 byte
**1-byte `c3 ret` for x86-64.**
Another justification could be that we take the input by reference and update in-place. Like C `void f(void*p){}` - mutate the pointed-to `int` object from `int` to `float`, which is a no-op in asm.
(As a C function, that wouldn't make it well-defined to point a `float*` at an `int`, still a strict-aliasing violation. It might make it work in practice if it couldn't be inlined, forcing the compiler to keep its hands off. But this is a machine code answer. Obviously in real asm you'd never call this, it doesn't do anything.)
## x86-64 machine code with AMD64 System V calling convention, 5 bytes
It's the same length as a `call` instruction, making it pointless not to inline, but whatever. :/
```
66 0f 6e c7 movd xmm0,edi
c3 ret
```
AVX `vmovd xmm0,edi` is the same 4-byte length.
### x86 with custom 3DNow! calling convention, 4 bytes
Did anyone ever use the low element of an mm register for scalar float with 3DNow!, like how SSE/SSE2 use the bottom of an `xmm` register for scalar float/double? Possible, although there [aren't scalar 3DNow! instructions](https://en.wikipedia.org/wiki/3DNow!) like SSE `addss`, only packed float like `pfadd`. So you might get slowdown from subnormals in the high half. Still it's plausible.
```
# int arg in EDI, float return value in MM0
0f 6e c7 movd mm0,edi
c3 ret
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~36~~ ~~34~~ ~~30~~ 23 bytes
```
#define f(x)*(float*)&x
```
[Try it online!](https://tio.run/##NU/LbsIwELznK1ZUIDsY6ndsAV9COUQhjiwFpyKRiory63VtIuY0s9rZmW12XdPE@HFtnQ8tOPTAJXL9UE8l3jzirfYB4eJZQEI/hA6mdpzOFzjBExitjOJCCEYy1xWzlaGZC20Es9ISEFxLxZixKs@VtlpqavKcKmnTGieQLJzJShqhpYH58Apzwx2QDxP4Ez2AhyOM/rcdHMoFMHy@ZfnSaWO7xbD0zPi@J69Dq/We0f6a6q73nLqvsCLLB/5CYLmVKMZL5lzM8a9xfd2NcffzDw "C (gcc) – Try It Online")
-2 thanks to m90
-4 thanks to Digital Trauma and mousetail
-7 thanks to jdt
Unsafe code go brr
```
#define f(x)*(float*)&x // Macrotaking an int, returning a float
#define f(x) // Boilerplate
&x // Pointer to the input
(float*) // Reinterpret it as a pointer to a float instead of an int
* // Get the value at that pointer, now a float
```
[Answer]
# [Python](https://www.python.org), 55 bytes
```
lambda n:unpack('f',pack('I',n))[0]
from struct import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY5LCsIwGIT3nuLftZUIeT8KHsAz1C5qJVi0SYjpwrO4KYjeyduYUlfzMcww8_yER7p4N7_s_viekt3pr7p14-ncgasnF7r-Wha2QCscCuSqqsHtxkY_wj3FqU8wjMHHtP3XvfURHAwOGoKVFpQxRhBklooYpfHCTGpGDDcIGJVcEKKNWHwhjeQS68XHgpscowhyhRKuuGaS67beAIQ4uFTaMr9ZZ-d51R8)
[Answer]
# [Python](https://www.python.org), ~~69~~ ~~67~~ 65 bytes
```
lambda x:((x&8388607)/2**23+1)*2**((x>>23&255)-127)*(1-(x>>30&2))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NZBLasMwEEDp1qcQXgTJjVyNRt9ADL1Hu3BJTA2OY2K1OGfpJlDaO7WnqWRRLfQZvXnDzMf3dA2v5_H22e2fvt5Cx93P49CeXg4tWXaULhuHzhlh2YOsKon3wKp4iR9NI3EjtWYcpGUVBZ5iKDaSsSz6vXsOxznMZE_KsixAWKclIgLhDSEEa1AiLhDKCwVWOaGMszqBxoK3TmRQ1hYSKNCBMt5Ko41MGBqH4JXPmKgzFY1RCGAAPDplM43SKA3gvE40t6qWyoN3HlBbJSEX1sYbZYT7N6Y8oZWPheQa4zGWdKmhojtfyNCPR9KPZO20nsOlnyir52noQ_qaKdsVUUWWLbnGQZzaiUYog9s1O8O05E3JWGYjeHxvB7rk97pNl34MNGq6GI4yVuQp3275_AM)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 29 bytes
Same technique as [solid.py's Python answer](https://codegolf.stackexchange.com/a/252946/11261).
```
->n{[n].pack(?I).unpack1(?f)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhZ7de3yqqPzYvUKEpOzNew9NfVK80BMQw37NM1aiJqb8QUKbtGGBuYWpkbGxsaGsVxQvpm5oaW5hQGMb2xmYWxoaWIJ4RsbmZmYGhpaWJrC5E3NLM1MzAwsYPIGpiaWQC1GsRBrFiyA0AA)
[Answer]
# [Go](https://go.dev), 29 bytes
```
import."math"
Float32frombits
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZBNTsMwEEbFNqeIwqaWUstjj39mwbYbNlzBVLhEbZIquGxQT8ImQuIS3AROgxsT0dYb61nzvm_k949NP37t_XrrN09l65uuaNp9P8SSV6GN1echhqX7vs2PvGp9fK6KVz-U4W61631UMgx9-9jElzz6c3MfDt16ilqw8q14GJou7roFCOu0VEpBHc6A1YoDinRAIAkEi06gcVazc9VYIOtEVv-A1ZJbOKlCOUBDVhpt5IWojFNASJM4A6sFz15qTaUABoCUQ3vlK2lQAzjSyf8HVi8tcokE5AiUtijhamFtyKARbuqd4dR7kS40UtpJTukzpPQ0Nu1xzH86jvn-BQ)
wow builtins
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 53 bytes
```
n->(1-n>>31*2)*if(e=n>>23%256,(1+n/2^23%1.)<<(e-127))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY5NCsIwEIWvEgQhqYlmZvILtRcRlS6sFCQE0UXP4qYg4pm8jQm6mu97vAfzeOf-Oh7PeX4ObPu63wYVPjapjoNKXUfQoGjGgZ-2xZCWaJ3ksEobPBSDtWhbflKAXoj_eOpzvkw8MdWxfB3TreCiyoINPAkh2Q60DxaJCCQr7DxEH3RlcoEgmigZoTMWIERbc-uiM06HmmtrYqmhZGWCYLwJ5EzY_x-Y59_9Ag)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 7 bytes
```
7Y%10Z%
```
Try it at [MATL online](https://matl.io/?code=7Y%2510Z%25&inputs=1078523331&version=22.7.4)! Or [verify all test cases](https://tio.run/##DcqpEYBQDABRnz6@z314SsCAAg@O/kPczpt97@/pq@NYhOfqbW/CSGMRIZj0oIrESfEUKi0QdjWiLBs1L1fHHEXTmocBgUlDU1zzBw).
### Code explanation
```
% Implicit input: number in 'double' data type
7Y% % Cast to 'uint32'
10Z% % Convert to 'single' without changing underlying data
% Implicit display
```
[Answer]
# [C++ (GCC)](https://gcc.gnu.org), 30 bytes
```
[](int x){return*(float*)&x;};
```
This is just Seggan's C answer using C++11's lambda syntax instead of a named function.
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 27 bytes
Port of [my Ruby answer](https://codegolf.stackexchange.com/a/252963/11261).
```
-[I]|~:pack&?I|~:unpack1&?f
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWu3WjPWNr6qwKEpOz1ew9gazSPBDbUM0-DaLiZnyBglu0oYG5hamRsbGxYSwXlG9mbmhpbmEA4xubWRgbWppYQvjGRmYmpoaGFpamMHlTM0szEzMDC5i8gamJJVCLUSzEmgULIDQA)
## Explanation
```
-[I] | # Construct an array with one element (the input), then
~:pack & ?I | # pack it into a binary string
~:unpack1 & ?f | # unpack it into a float
```
[Answer]
# [C# (.NET Core 6)](https://www.microsoft.com/net/core/platform), 30 bytes
```
BitConverter.Int32BitsToSingle
```
[.NET Fiddle!](https://dotnetfiddle.net/jFQmn0)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 48 bytes
```
f=x=>x<0?-f(x^1<<31):x>>24?f(x-2**23)*2:x/2**149
```
[Try it online!](https://tio.run/##bc7LDoIwEAXQvV8CJNWZzvSFPP7EhCAYCaFGjOnf17qmu8k9uTezDN9hH9/P10ds/j7FOLeh7UIDvZiLcMOmISzr0HWS@xQIWVWSykrW4ZJOZBevp9Fvu1@n8@ofxVwgGKskUeqVGdMGnbGQM9KW0LE7mkgIrBRDdlRpp1mDzRatYwOs@YiZJ4RENmxJ838s/gA "JavaScript (Node.js) – Try It Online")
No cast
] |
[Question]
[
**This question already has answers here**:
[Spell out the Revu'a](/questions/68901/spell-out-the-revua)
(34 answers)
Closed 7 years ago.
The challenge is relatively simple, but will hopefully lead to some wonderfully creative answers. The task is to take a string as an input (via command line, function parameter etc.) and output/return a stringsploded version of it.
A stringsploded version of a string is its first letter followed by its first 2 letters, followed by its first 3 letters,... until you finally output the complete word.
You are guaranteed that the input will consist of printable ASCII characters and that the input will all be on one line (no new line characters).
Here are examples to clarify what stringsplosions are:
```
Input Output
==================================================================
"Code" ----> "CCoCodCode"
"name" ----> "nnanamname"
"harambe" ----> "hhaharharaharamharambharambe"
"sp aces?" ----> "sspsp sp asp acsp acesp acessp aces?"
"1234" ----> "1121231234"
"ss" ----> "sss"
```
This is code golf so shortest code wins + up votes for interesting uses of your respective language.
Good luck!
[Answer]
# [gs2](http://github.com/nooodl/gs2), 1 byte
# [`x`](http://gs2.tryitonline.net/#code=eA&input=SGVsbG8)
* `gs2` takes input from STDIN, and pushes it to the stack as a string.
* `x` is the **prefixes** built-in, returning a list of all prefixes of the argument, in ascending-length order.
* The resulting list of strings is implicitly printed one-by-one, without a delimiter, when the program terminates.
[Answer]
## [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
;\
```
Acculumate over concatenation gives all prefixes, which Jelly outputs to STDOUT without a delimiter. [Try it online!](http://jelly.tryitonline.net/#code=O1w&input=&args=ImFiY2RlMDEyMz8hICMi)
[Answer]
## [Retina](https://github.com/m-ender/retina), 4 bytes
```
.
$`
```
Expects the input to be terminated with a Windows-style `\r\n` newline (which seems fitting for a .NET-based programming language...).
This can be tested on [Regex Storm](http://regexstorm.net/tester?p=.&i=Code+Golf%0d%0a&r=%24%60) (which uses `\r\n` newlines). Click the "Context" tab for the result.
This is essentially the same as [Jordan's Ruby answer](https://codegolf.stackexchange.com/a/92536/8478): it replaces each character in the input (including the `\r` but not the `\n`) with all the characters that came before it.
[Answer]
## Java 7, ~~81~~ 78 bytes
```
String g(String a){for(int i=a.length();i>0;)a=a.substring(0,--i)+a;return a;}
```
Straightforward method. Repeatedly prepends the shrinking prefix until it's done.
As a bonus, it should work for non-ASCII as well.
Sample:
```
Input: ( ͡° ͜ʖ ͡°)
Output: (( ( ͡( ͡°( ͡° ( ͡° ͜( ͡° ͜ʖ( ͡° ͜ʖ ( ͡° ͜ʖ ͡( ͡° ͜ʖ ͡°( ͡° ͜ʖ ͡°)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5 4~~ 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-2 bytes thanks to @Dennis
```
ḣJ
```
Test it at [**TryItOnline**](http://jelly.tryitonline.net/#code=4bijSg&input=&args=IkNvZGVHb2xmIC0gVGhlIEJlc3QgQmFuZyBGb3IgWW91ciBCeXRlIgo)
Or all test cases, also at [**TryItOnline**](http://jelly.tryitonline.net/#code=4bijSgrDh-KCrFk&input=&args=IkNvZGUiLCJuYW1lIiwiaGFyYW1iZSIsInNwIGFjZXM_IiwiMTIzNCIsInNzIgo)
How?
```
ḣJ - Main link takes one argument, e.g. "Code"
J - range(length(input)), e.g. [1,2,3,4]
ḣ - head, x[:y] (implicit vectorization), e.g. "CCoCodCode"
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), ~~11~~ 5 bytes
```
:@[fc
```
[Try it online!](http://brachylog.tryitonline.net/#code=OkBbZmM&input=ImhhcmVtYmUi&args=Wg)
### Explanation
```
:@[f Find all prefixes of the input
c Concatenate
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes
```
.pJ
```
**Explanation**
```
.p # get list of prefixes of input
J # join as string
```
[Try it online!](http://05ab1e.tryitonline.net/#code=LnBK&input=Q29kZQ)
[Answer]
# Ruby, 13 + 1 = 14 bytes
+1 byte for `-p` flag. Expects input on STDIN. Requires Windows-style line endings (`\r\n`).
```
gsub(/./){$`}
```
See it on eval.in (a few extra bytes since eval.in doesn't support command line flags):
<https://eval.in/637093>
[Answer]
## Javascript (ES6), ~~28~~ 26 bytes
Recursively appends the shortened strings to the left of the final result:
```
f=s=>s&&f(s.slice(0,-1))+s
```
### Examples
```
var
f=s=>s&&f(s.slice(0,-1))+s
console.log(f("Code")); // --> "CCoCodCode"
console.log(f("name")); // --> "nnanamname"
console.log(f("harambe")); // --> "hhaharharaharamharambharambe"
console.log(f("sp aces?")); // --> "sspsp sp asp acsp acesp acessp aces?"
console.log(f("1234")); // --> "1121231234"
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~9~~ ~~8~~ 6 bytes
*2 bytes saved thanks to @Luis*
```
t&+Rf)
```
[**Try it Online!**](http://matl.tryitonline.net/#code=dCYrUmYp&input=J0NvZGUn)
**Explanation**
```
t % Implicitly grab the input and duplicate
&+ % Broadcast and create a 2D matrix with all values > 0
R % Grab the upper triangular portion (sets the lower triangular values to 0)
f % Get the linear index for each value > 0
) % Index into the original string (uses modular indexing)
% Implicitly display the result
```
[Answer]
## JavaScript (ES6), 25 bytes
```
s=>s.replace(/./g,'$`$&')
```
[Answer]
# Perl, 10 bytes
Includes +1 for `-p`
Run with the input on STDIN:
```
splode.pl <<< "Hello"
```
`splode.pl`
```
#!/usr/bin/perl -p
s/./$`/sg
```
This depends on the input being terminated by a newline. This 11 byte version does not need a final newline:
```
#!/usr/bin/perl -lp
s/.?/$`/g
```
[Answer]
## [CJam](https://sourceforge.net/projects/cjam/), 8 bytes
Here's 4 separate ways to get 8 bytes
```
l_,),\f<
l{1$\+}*
l{+_}*co
Ll{+_}/;
```
Credits to @MartinEnder for the last one. [Online interpreter](http://cjam.aditsu.net/#code=l_%2C%29%2C%5Cf%3C&input=aabcde%2001!%40%23).
* `l_,),\f<` creates the range `[0 .. len(s)+1]` then uses `f<` to slice for each number, producing all prefixes.
* `l{1$\+}*` is a fold that duplicates the previous prefix and adds a char to it as it goes.
* `l{+_}*co` is a bit weird - `l{+_}*` is also a fold but it produces the wrong prefixes, skipping the first and doubling the last (e.g. `abcd` -> `ab/abc/abcd/abcd`, slashes for clarity). We then use `c` to turn the last string into just its first character and output it with `o`, to get the first prefix.
* `Ll{+_}/;` is a for-each loop that also duplicates the previous prefix and adds a char to it as it goes. We have an extra copy of the original string once the loop is over, which we pop with `;`.
[Answer]
## Haskell, ~~34 29 28~~ 26 bytes
```
reverse=<<scanl(flip(:))[]
```
[Answer]
# C, 49 bytes
```
i;f(char*n){for(i=0;i++<strlen(n);)write(1,n,i);}
```
[Try on Ideone](https://ideone.com/HjgvVU)
[Answer]
## [Jellyfish](http://github.com/iatorm/jellyfish), 5 bytes
```
P,\}I
```
[Try it online!](http://jellyfish.tryitonline.net/#code=UCxcfUk&input=Q29kZQ)
### Explanation
```
I # Read input.
\} # Get all prefixes.
, # Flatten.
P # Print.
```
[Answer]
# [V](http://github.com/DJMcMayhem/V), 8 bytes
```
òÄ$xhòíî
```
[Try it online!](http://v.tryitonline.net/#code=w7LDhCR4aMOyw63Drg&input=Y29kZQ)
[Answer]
# C#, ~~91~~ ~~87~~ ~~84~~ 83 bytes
```
void c(string n){var b="";for(int i=0;i<n.Length;)System.Console.Write(b+=n[i++]);}
```
Ungolfed:
```
void c(string n)
{
var b = "";
for (int i = 0; i < n.Length ; )
{
System.Console.Write(b+=n[i++]);
}
}
```
Thank you Kevin Cruijssen.
[Answer]
# sed 41
```
h;:;G;s,.\n,\n,;h;s,\n.*,,;/./b;x;s,\n,,g
```
[Answer]
# [Sesos](https://github.com/DennisMitchell/sesos), 4 bytes
```
0000000: 8073ec 09 .s..
```
[Try it online!](http://sesos.tryitonline.net/#code=ICAgIGptcCwgcndkIDEsIGpuegogICAgZndkIDEKICAgIGptcCwgcHV0LCBmd2QgMSwgam56Cmpueg&input=Q29kZQ) Check *Debug* to see the generated SBIN code.
### Sesos assembly
The binary file above has been generated by assembling the following SASM code.
```
jmp, rwd 1, jnz
fwd 1
jmp, put, fwd 1, jnz
jnz
```
[Answer]
# Python, ~~34~~ 28 bytes
Here's my rough attempt with a recursive solution:
```
f=lambda s:s and f(s[:-1])+s
```
Ungolfed:
```
def f(s):
if s: return f(s[:-1]) + s
return ''
```
Try it [here](https://ideone.com/dFBTgS)!
Thanks to @Dennis for -6 bytes.
[Answer]
# CJam, 11 bytes
```
q{(L\+:Lo}h
```
Explanation:
```
q get input
{ }h do while
(L get 1st character and variable L (initialized with "")
\+ swap and concatenate them
:Lo store result in L and print it
```
[Try it online](http://cjam.tryitonline.net/#code=cXsoTFwrOkxvfWg&input=Q29kZQ)
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 3 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
∊,\
```
`∊` flatten the
`,\` cumulative concatenation
[TryAPL online!](http://tryapl.org/?a=f%u2190%u220A%2C%5C%20%u22C4%20f%A8%27Code%27%20%27name%27%20%27harambe%27%20%27sp%20aces%3F%27%20%271234%27%20%27ss%27&run)
[Answer]
# Pyth, 3 bytes
```
s._
```
Explanation:
```
s (s)um together
._ all prefixes
```
[Answer]
# R, ~~60~~ 49 bytes
Not going to win any golf, but hopefully no shorter R answer is possible
```
cat(substring(s<-readline(),1,1:nchar(s)),sep="")
```
~~`paste0(substring(s<-readLines(,1),1,1:nchar(s)),collapse="")`~~
Thanks @MickyT
[Answer]
# Retina, 24 bytes
Well, I got destroyed by Martin, but here was my solution.
```
1m+`(.*).$
$1$.1$*¶$0
¶
```
[**Try it online**](http://retina.tryitonline.net/#code=MW0rYCguKikuJAokMSQuMSQqwrYkMArCtgo&input=Q29kZQ)
[Answer]
## PowerShell v2+, 43 bytes
```
param($n)-join(1..$n.length|%{$n[0..--$_]})
```
Takes input `$n`, loops from `1` to `$n.length`, each iteration slicing `$n` from `0` up to one less than the current number -- done because `.length` is 1-indexed, while array slicing is 0-indexed. Each iteration places characters on the pipeline, those are encapsulated in parens and `-join`ed together into one string. Output is implicit.
```
PS C:\Tools\Scripts\golfing> .\stringsplode-the-string.ps1 'PPCG'
PPPPPCPPCG
```
---
Alternatively, using Jordan's [Ruby submission](https://codegolf.stackexchange.com/a/92536/42963) as a basis, you can get to the following for **22 bytes**
```
$input-replace'.','$`'
```
This feels kinda cheaty, though, since you'd have to explicitly insert a newline into the string that you're piping in, or otherwise do a `Get-Content` or something out of a file that pulls the newlines with it. Valid, but not really common.
```
PS C:\Tools\Scripts\golfing> 'PPCG
' | .\stringsplode-the-string.ps1 $_
PPPPPCPPCG
```
[Answer]
# C ~~71~~ 67 Bytes
```
k;f(v){char*m,*n=v;while(*n++)for(k=0,m=v;k<n-v;k++)putchar(*m++);}
```
[Answer]
# Gema, 16 characters
```
?=@append{s;?}$s
```
Sample run:
```
bash-4.3$ echo -n 'sp aces?' | gema '?=@append{s;?}$s'
sspsp sp asp acsp acesp acessp aces?
```
[Answer]
# Python 3, 47 bytes
Thanks to @deustice
```
lambda s:''.join(s[:i]for i in range(len(s)+1))
```
[**Ideone it!**](https://ideone.com/jYx2c0)
] |
[Question]
[
Potentially very difficult, but I've seen some amazing things come out of this site.
The goal is to write a program, in any language, that does whatever you want. The catch is that the program must be valid after **any** circular shift of the characters.
A circular character shift is very similar to a [Circular Shift](http://en.wikipedia.org/wiki/Circular_shift). Some examples my clear things up.
For the program `int main() { return 0; }`
shifting to the left by 6 characters yields: `in() { return 0; }int ma`
shifting to the left by 1 character yields: `nt main() { return 0; }i`
shifting to the right by 10 character yields: `eturn 0; }int main() { r`
However, this program obviously doesn't comply with the rules.
# Rules
* Any language
* Winner is decided by up-vote count
* Solutions which do the same thing, or completely different things for each rotation, will receive 100 virtual up-votes to their score.
**UPDATE** I think this has gone on long enough. The winner, with the most votes (virtual votes included) is Mark Byers. Well done!
[Answer]
Use the right language for the task. In this case, that's [**Befunge**](https://github.com/programble/befungee).
This language naturally allows rotations because:
* All commands are a single character.
* The control wraps around when it reaches the end of the program, starting again from the beginning.
This Befunge program prints the exact same output ("Hello") regardless of how many "circular character shifts" you use:
```
86*01p75*1-02p447**1-03p439**04p439**05p455**1+06p662**07p75*1-08p645**2-09p69*4+019+p57*029+p59*1-039+p555**1-049+p88*059+p86*01p75*1-02p447**1-03p439**04p439**05p455**1+06p662**07p75*1-08p645**2-09p69*4+019+p57*029+p59*1-039+p555**1-049+p88*059+p645**2-00p645**2-00p
```
It runs on [Befungee](https://github.com/programble/befungee). It requires that the board is increased (not the 80 character default). It can be run like this:
```
python befungee.py -w400 hello.bef
```
It works by first dynamically generating and storing a program that prints "Hello" and then overwriting the first byte to redirect the control into the newly written program. The program is written twice so that if a byte is not written correctly the first time, it will be corrected the second time.
The idea could be extended to produce any program of arbitrary complexity.
[Answer]
## Brainf\*ck
Choose the right tool for the job -- an adage that's never been more relevant than this job right here!
```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++.+.>++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++.++++++++++++++.>++++++++++.+
```
The unshifted program you see here simply prints `SHIFT` (plus a newline). Abitrarily circular shifts will produce various other outputs, though it will always output six ASCII characters.
[Answer]
## Commodore 64 BASIC
`?` is short for `PRINT`, and `:` is a statement separator, so:
```
?1:?2:?3: // prints 1, 2, and 3
:?1:?2:?3 // prints 1, 2, and 3
3:?1:?2:? // adds a program line 3 :PRINT1:PRINT2:PRINT
?3:?1:?2: // prints 3, 1, and 2
:?3:?1:?2 // prints 3, 1, and 2
2:?3:?1:? // adds a program line 2 :PRINT3:PRINT1:PRINT
?2:?3:?1: // prints 2, 3, and 1
:?2:?3:?1 // prints 2, 3, and 1
1:?2:?3:? // adds a program line 1 :PRINT2:PRINT3:PRINT
```
Longer variations are, of course, possible:
```
?1:?2:?3:?4:?5:?6:?7:?8:?9:?10:?11:
```
etc...
[Answer]
### Golfscript
This program prints some digits that always sum up to 2, regardless of how the program is shifted:
```
10 2 base
0 2 base1
2 base10
2 base10
base10 2
base10 2
ase10 2 b
se10 2 ba
e10 2 bas
```
The first line prints `1010` (10 in binary), the second line prints `02` and all the other lines print `2`.
**Update:**
The program can be tested [here](http://golfscript.apphb.com/?c=MTAgMiBiYXNlIG4KMCAyIGJhc2UxIG4KIDIgYmFzZTEwIG4KMiBiYXNlMTAgIG4KIGJhc2UxMCAyIG4KYmFzZTEwIDIgIG4KYXNlMTAgMiBiIG4Kc2UxMCAyIGJhIG4KZTEwIDIgYmFzIG4=). *Please note that I've added `n`s at the end of each row only for formatting the output; these can be removed and the program still works.*
[Answer]
Ruby, probably one of the shortest possible solutions:
```
p
```
And another slightly longer and more interesting one:
```
;;p";p;";p
```
[Answer]
Unary Answer:
```
000000 ... 00000
```
^44391 Zeros
Cat program. No matter how you rotate, it's the same program.
[Answer]
# x86 16 bit binary
Manually constructed with the help of these ([1](http://www.sandpile.org/x86/opc_rm16.htm) [2](http://ref.x86asm.net/geek32.html)) tables, nasm and ndisasm. This will always return without a crash or infinite loop, because no bytes are jumps or change the stack and it is filled with NOPs to end with a single byte `ret` instruction in any case.
In most cases this will output `FOO` or a substring of that. If `AX` is broken, this will call a random [int 10](http://www.ctyme.com/intr/int-10.htm) (this changed the cursor blinking speed in one of my tests), but it usually does not result in a crash.
To try out, put the hexdump in a file and use `xxd -r foo.hex > foo.com`, then run in a dos environment (I used dosbox).
Here is a hex dump of this file:
```
0000000: b846 0d90 90fe c490 9090 bb05 0090 9043 .F.............C
0000010: 43cd 1090 b84f 0d90 90fe c490 9090 bb05 C....O..........
0000020: 0090 9043 43cd 1090 b84f 0d90 90fe c490 ...CC....O......
0000030: 9090 bb05 0090 9043 43cd 1090 9090 c3 .......CC......
```
And some interesting disassembled offsets:
## +0
```
00000000 B8420D mov ax,0xd42
00000003 90 nop
00000004 90 nop
00000005 FEC4 inc ah
00000007 90 nop
00000008 90 nop
00000009 90 nop
0000000A BB0500 mov bx,0x5
0000000D 90 nop
0000000E 90 nop
0000000F 43 inc bx
00000010 43 inc bx
00000011 CD10 int 0x10
00000013 90 nop
00000014 B84F0D mov ax,0xd4f
00000017 90 nop
00000018 90 nop
00000019 FEC4 inc ah
0000001B 90 nop
0000001C 90 nop
0000001D 90 nop
0000001E BB0500 mov bx,0x5
00000021 90 nop
00000022 90 nop
00000023 43 inc bx
00000024 43 inc bx
00000025 CD10 int 0x10
00000027 90 nop
00000028 B84F0D mov ax,0xd4f
0000002B 90 nop
0000002C 90 nop
0000002D FEC4 inc ah
0000002F 90 nop
00000030 90 nop
00000031 90 nop
00000032 BB0500 mov bx,0x5
00000035 90 nop
00000036 90 nop
00000037 43 inc bx
00000038 43 inc bx
00000039 CD10 int 0x10
0000003B 90 nop
0000003C 90 nop
0000003D 90 nop
0000003E C3 ret
```
(for the examples below, the rest of the binary is still valid)
## +1
```
00000000 42 inc dx
00000001 0D9090 or ax,0x9090
00000004 FEC4 inc ah
00000006 90 nop
```
## +2
```
00000001 0D9090 or ax,0x9090
00000004 FEC4 inc ah
00000006 90 nop
```
## +6
```
00000000 C4909090 les dx,[bx+si-0x6f70]
00000004 BB0500 mov bx,0x5
00000007 90 nop
00000008 90 nop
00000009 43 inc bx
0000000A 43 inc bx
0000000B CD10 int 0x10
```
## +11
```
00000000 050090 add ax,0x9000
00000003 90 nop
00000004 43 inc bx
00000005 43 inc bx
00000006 CD10 int 0x10
```
## +12
```
00000000 00909043 add [bx+si+0x4390],dl
00000004 43 inc bx
00000005 CD10 int 0x10
```
## +18
```
00000000 1090B84F adc [bx+si+0x4fb8],dl
00000004 0D9090 or ax,0x9090
00000007 FEC4 inc ah
00000009 90 nop
```
(other offsets are just repetitions of the above)
## +58
```
00000000 10909090 adc [bx+si-0x6f70],dl
00000004 C3 ret
```
[Answer]
### PHP
Here you go, a valid PHP program:
```
Is this still funny?
```
[Answer]
### Scala
A nested quotes:
```
""""""""""""""""""""""""""""""""
```
### ~~C++/Java/C#/~~Scala
Comment:
```
///////////////////////////////////
```
Empty command:
```
;;;;;;;;;;;;;;;
```
### Bash
Comment, Whitespace and Shell builtin combination:
```
#
:
```
### Sed
Standalone valid commands:
`p` `P` `n` `N` `g` `G` `d` `D` `h` `H`
A combination of the above:
`p;P;n;N;g;G;d;D;h;H;`
### AWK
To print every line of the file:
```
1
```
or
```
//
```
Don't print anything:
```
0
```
### Perl
```
abcd
```
[Answer]
# J
First, a script to check valid rotations of a program `s`:
```
check =: 3 :'((<;(". :: (''Err''"_)))@:(y |.~]))"0 i.#y'
```
For example, the program `+/1 5` (sum of 1 and 5) gives:
```
check '+/1 5'
┌───────┬───┐
│┌─────┐│6 │
││+/1 5││ │
│└─────┘│ │
├───────┼───┤
│┌─────┐│Err│
││/1 5+││ │
│└─────┘│ │
├───────┼───┤
│┌─────┐│Err│
││1 5+/││ │
│└─────┘│ │
├───────┼───┤
│┌─────┐│6 │
││ 5+/1││ │
│└─────┘│ │
├───────┼───┤
│┌─────┐│6 │
││5+/1 ││ │
│└─────┘│ │
└───────┴───┘
```
Then, a boring, valid program:
```
check '1x1'
┌─────┬───────┐
│┌───┐│2.71828│ NB. e^1
││1x1││ │
│└───┘│ │
├─────┼───────┤
│┌───┐│ │ NB. Value of variable x11
││x11││ │
│└───┘│ │
├─────┼───────┤
│┌───┐│11 │ NB. Arbitrary precision integer
││11x││ │
│└───┘│ │
└─────┴───────┘
```
[Answer]
# dc
dc programs are easily valid in any rotation. For example:
```
4 8 * 2 + p # 34
8 * 2 + p 4 # stack empty / 10
...
```
[Answer]
# k
```
.""
```
Evaluates an empty string
```
"."
```
Returns a period character
```
"".
```
Returns partial application of '.' (dyanic form) to an empty character list.
[Answer]
## Machine Code
How about Z80 / Intel 8051 machine code for [NOP](http://en.wikipedia.org/wiki/NOP).
Sure it does No Operation, but it DOES take up a cycle or two... you can have as many or as few of them as you want.
And I disagree with **Ruby** answer above - I think a single byte 00h is shorter than a Ruby `p`.
[Answer]
### sh, bash
```
cc
cc: no input files
```
cc rotated is cc again, but it is not very friendly if called so naked.
```
dh
dh: cannot read debian/control: No such file or directory
hd
```
dh **debhelper** isn't very cooperative too, while **hexdump** just waits for input.
```
gs
sg
```
**Ghostscript** starts interactive mode, while **switch group** shows a usage message - a valid solution here, imho, too.
And here is the script to find candidates for such programs:
```
#!/bin/bash
for name in /sbin/* /usr/sbin/* /bin/* /usr/bin/*
do
len=${#name}
# len=3 => 1:2 0:1, 2:1 0:2
# len=4 => 1:3 0:1, 2:2 0:2, 3:1 0:3
for n in $(seq 1 $((len-1)))
do
init=${name:n:len-n}
rest=${name:0:n}
# echo $init$rest
which /usr/bin/$init$rest 2>/dev/null >/dev/null && echo $name $init$rest $n
done
done
```
If finds longer sequences too, like (arj, jar) or (luatex, texlua) which aren't valid after every shift, but only after some certain shifts, which I misread in the beginning, but there are few, so it is easy to filter them out by hand.
[Answer]
Trivial Python example:
```
"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""";print
```
May be shifted three chars over repeatedly to reveal more and more of the alphabet.
[Answer]
# Python
```
123456789.0
```
Just evaluate some numbers
[Answer]
**dc** is already used, but the following program **always outputs the same**, no matter the rotation :D
```
d
```
ouputs
```
dc: stack empty
```
[Answer]
# APL, 1 byte
```
⍬
```
Prints empty array. If the program should print something clearly visible:
```
⍬⍬
```
Prints a nested array, consisting of two empty arrays:
```
┌┬┐
│││
└┴┘
```
In addition, I tried to come up with a program that does something radically different with each shift.
`*1⍝` Prints 2.718281828
`1⍝*` Prints 1
`⍝*1` Prints nothing
However, the question arises whether the last line can be considered a program that does something, because it is just a comment that does nothing.
] |
[Question]
[
Your task is it to output a number as a unary string. You get the number of a non-negative integer input in the range of 0 - 2'000'000'000.
Rules
* You can choose any character for the digit you like. But it has to be the same everywhere and for every input.
* Output a unary string by outputting this character N times. N is the input.
* Input range is 0 - 2'000'000'000 (inclusive)
* A input of 0 result in a empty string except the optional starting and ending characters.
* You may or may not add optional starting and ending characters at the start and/or end, for example a newline character or `[` and `]`. If you do, all outputs (including of the input 0) must have one. This characters are different from the the character for the digit you have chosen.
* Input integer is given as decimal, hexadecimal, octal or binary number, whatever is convenient for you.
* You are free to use a pattern of multiple characters for a single digit. But it has to be the same pattern for all digits and for every input.
* Digit grouping is optional. If you use it, the group size has to be constant and the separation character has to be the same everywhere.
* Your program should finish in less than 4h on a modern desktop CPU with 4 GB of free RAM, for any valid input.
* Output is a string or stream of characters.
Examples / test cases:
```
Input -> Output
./yourProgram 1 -> 1
./yourProgram 12 -> 111111111111
./yourProgram 0 ->
./yourProgram 2000000000 | tr -d -c '1' | wc -c -> 2000000000
./yourProgram 32 -> 11111111111111111111111111111111
```
Non-golf example program:
```
#!/usr/bin/env python3
import sys
for i in range( int(sys.argv[1]) ):
print("1", end='')
```
This is `code-golf`, so the shortest code wins.
Related but they have significant differences:
* [Output a random unary string](https://codegolf.stackexchange.com/questions/243525/output-a-random-unary-string)
* [Parse a list of signed unary numbers](https://codegolf.stackexchange.com/questions/150775/parse-a-list-of-signed-unary-numbers)
* [Brainf\*\*k to Unary and Back](https://codegolf.stackexchange.com/questions/52712/brainfk-to-unary-and-back)
[Answer]
# [Python 3](https://docs.python.org/3/), 11 bytes
```
'0'.__mul__
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzX91AXS8@Prc0Jz7@f0FRZl6JRpqGqabmfwA "Python 3 – Try It Online")
Note: `0` could be any other character. Function returning a string.
# [Python 3](https://docs.python.org/3/), 21 bytes
```
def f(n):print('0'*n)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI0/TqqAoM69EQ91AXStP83@ahqnmfwA "Python 3 – Try It Online")
Function which prints the string.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 1 byte
```
N
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMzr6C0xK80Nym1SENT0/r/fzPL/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Charcoal prints a number as a number of `-`, `|`, `/` or `\` symbols depending on the direction of the pivot, the default being horizontal.
[Answer]
# [TypeScript](https://www.typescriptlang.org)’s Type System, 62 bytes
```
type U<N,L extends 1[]=[]>=L extends{length:N}?L:U<N,[...L,1]>
```
[Try it at the TypeScript Playground!](https://tsplay.dev/wE8Q2W)
Type definition taking a generic integer type and recursively appending 1 to a tuple type until its length is the integer type.
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 4 bytes
```
1 x*
```
[Try it online!](https://tio.run/##K0gtyjH7n1uplmb731ChQuu/NVdxYqVCmoahgeZ/AA "Perl 6 – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org), 12 bytes
```
|a|vec![0;a]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqLS4ZMHGtDyF3MTMPA1Nheqc1BKFNNulpSVpuhZraxJrylKTFaMNrBNjrSFiewqKMvNKcvIUNZSqrexrlXQU0jQsDAw0Na25uGohShYsgNAA)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 1 [byte](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
·π£
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVFMSVCOSVBMyZmb290ZXI9JmlucHV0PTUmZmxhZ3M9)
Uses a space as the character.
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
I
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJJIiwiIiwiNSJd)
Same as above.
[Answer]
# [Lua](https://www.lua.org/), 21 bytes
```
print(('0'):rep(...))
```
[Try it online!](https://tio.run/##yylN/P@/oCgzr0RDQ91AXdOqKLVAQ09PT1Pz////pgA "Lua – Try It Online")
[Answer]
# [J](https://www.jsoftware.com), 4 bytes
```
#&LF
```
Uses linefeed as the character. The large test case will not work on ATO, but `100 timex '# f 2000000000'` yields an average of 0.421414 seconds.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxRFkNxrx5WJMrNTkjX0FdFztQh0inKRgSq86IKIUaaQoGmgq6ViAdCn5Oegop-anFCpklCrmJJckZ9gp5-XpEWmhsBPHKggUQGgA)
```
#&LF
# NB. copy
&LF NB. bond LF as the right argument
```
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), ~~14~~ 12 bytes
```
(}?@_.)<!>*'
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/1@j1t4hXk/TRtFOS/3/f0MDAwA "Hexagony – Try It Online")
Layed out
```
( } ?
@ _ . )
< ! > * '
. . . .
. . .
```
### Explanation
`(}?` some irrelevant operations initially, then get the input
`<` branch, if 0 go to `@` and terminate, otherwise point the IP southeast
`(_` decrement the input cell and redirect the IP northeast
`}*)!` move the MP to the cell to the right, set that cell to 1 and print that out
`_>` redirect the IP back east
`*'` irrelevant operation, then move the MP back to the input cell
this then loops back to the branch command
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 5 bytes
```
.+
$*
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRev/fzNLAA "Retina 0.8.2 – Try It Online") Explanation: Outputs `1` repeated by the input count, with a trailing newline.
For Retina 1, remove the `$`, and then the program outputs `_` repeated by the input count, without a trailing newline.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 21 bytes
`x=>new String('a',x);`
[Try it online!](https://tio.run/##NY0/D4IwEMVn@yneRglVUccCi4mTm4MDYTCk4EXTmraoCeGz1/rvll/uvXf3WjdvHYXdoFsUpL2A85Z0X6FDifAsK60eOHw0npwS8UxluJ8szCX63g5KsvdK@jZ4F6V3vG4wYiWwWgvkApsITBLL5Tr/D@uMBY@FoHiUy4ji92SxV7r3Z4kso5SNbLY12pmrWhwtebUnrXjHv9GamjSVbAov "C# (Visual C# Interactive Compiler) – Try It Online")
My first time writing an answer here!
[Answer]
# [C (gcc)](https://gcc.gnu.org/) `-O3`, 24 bytes
*-1 byte thanks to [@12431234123412341234123](https://codegolf.stackexchange.com/users/59900/12431234123412341234123)*
```
f(n){n&&puts(f)+f(n-1);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOk9NraC0pFgjTVMbyNc11LSu/Z@ZV8KVm5iZp1GWn5miyVXNlaZhqmnNVfv/X3JaTmJ68X9df2MA "C (gcc) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), 42 bytes
*Full program, input from stdin*
```
main(n){printf("%.*d",n,!scanf("%d",&n));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI0@zuqAoM68kTUNJVU8rRUknT0exODkxD8QH8tTyNDWta///NwUA "C (gcc) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/) `-m32`, 44 bytes
*Full program, input as command line argument*
```
*p;main(n,v){printf("%.*d",atoi(1[p=v]),0);}
```
[Try it online!](https://tio.run/##S9ZNT07@/1@rwDo3MTNPI0@nTLO6oCgzryRNQ0lVTytFSSexJD9TwzC6wLYsVlPHQNO69v///yb/ktNyEtOL/@vmGhsBAA "C (gcc) – Try It Online")
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 10 bytes
```
")")
```
Hover over any symbol to see what it does
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTo/ITsxLTFuISIsImlucHV0IjoiMTIiLCJzdGFjayI6IiIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJudW1iZXJzIn0=)
[Answer]
# [Arturo](https://arturo-lang.io), 15 bytes
```
$=>[repeat"1"&]
```
[Try it!](http://arturo-lang.io/playground?OMx7fz)
[Answer]
## Pascal, 96 characters
```
program u(input,output);var i:integer;begin read(i);while i>0 do begin write('ùç∑');i‚âîi‚àí1 end end.
```
Necessary implementation characteristics:
The value of `maxInt` must be ‚â• 2000000000.
[Answer]
# [Alice](https://github.com/m-ender/alice), 15 bytes
```
/ M \1*.n$@9ot
```
[Try it online!](https://tio.run/##S8zJTE79/19fwVchxlBLL0/FwTK/hOv///9GBgYA "Alice – Try It Online")
The new line at the end of the code is required
Uses tab as the output character
```
/ M \1*.n$@9ot # Full program
/ M \1* # Reads one argument as a string and multiply it by 1, this is our loop counter
.n$@ # Stop if the counter is down to 0
9o # Output a <tab>
t # Decrement the counter
# Goes back to the beginning of the line
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
$√ó
```
Uses character `1`.
[Try it online.](https://tio.run/##yy9OTMpM/f9f5fD0//8NjQE)
```
Î×
```
Uses character `0`.
[Try it online.](https://tio.run/##yy9OTMpM/f//cN/h6f//GxoDAA)
```
°¦
```
Uses character `0` as well.
[Try it online.](https://tio.run/##yy9OTMpM/f//0IZDy/7/NzQGAA)
```
õú
```
Uses a space as character.
[Try it online.](https://tio.run/##yy9OTMpM/f//8NbDu/7/NzQGAA)
If different multiple output-characters would have been allowed, it could be 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) with:
```
‚àç
```
[Try it online.](https://tio.run/##yy9OTMpM/f//UUfv//@GxgA)
**Explanation:**
```
$ # Push 1 and the input-integer
√ó # Repeat the 1 the input amount of times as string
# (which is output implicitly as result)
Î # Push 0 and the input-integer
√ó # Repeat the 0 the input amount of times as string
# (which is output implicitly as result)
° # Push 10 to the power of the (implicit) input-integer
¦ # Remove the leading 1 so only the 0s remain
# (which is output implicitly as result)
õ # Push an empty string ""
√∫ # Pad it with the (implicit) input-integer amount of leading spaces
# (which is output implicitly as result)
‚àç # Extend/shorten the (implicit) input to a length of the (implicit) input-integer
# (which is output implicitly as result)
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 11 bytes
```
"1"::repeat
```
[Try it online!](https://tio.run/##ZY7BSsRADIbvfYqwpynowJ6EretREPTUo3iI3VjSnabDTLrbRfbZ6xSnKphL8idfkr/DE952h@PMvR@CQpe0HZWdrRsUoVAV/yYfozTKg9jHXFRF4cd3xw00DmOEF2SBzwJS5H5U1JROAx@gT1NTa2BpX98AQxvLDC@x3rx/EqWWwg18ow@wvIX9vNludrtAnlDn6mctu4UIexA6r9rUl6jUW5byl2VRmBKXP1iPIVISJlqhSZ9ZyJR/@HxjGNX6ZEWdmMWLRe/dxUwrei2u890X "Java (JDK) – Try It Online")
[Answer]
# x86 / x86-64 machine-code, 7 bytes, as fast as memset
Just a function, not a full program, so we only need to `memset(buf, '1', n)` + append a terminating 0 to make an implicit-length C-style string in the buffer the caller supplies, of size `n+1` or larger.
This could be called from C in the x86-64 System V calling convention as `void to_unary(char *dst, int dummy, int dummy, size_t n)`. Size is limited only by address-space limits.
```
machine code | NASM source
; RDI or ES:EDI = output buffer of size n
; RCX or ECX = n
to_unary:
B031 mov al, '1'
F3AA rep stosb
880F mov byte [rdi], cl ; RCX was zeroed by rep stos
C3 ret
```
[`stos` stores and *then* increments](https://www.felixcloutier.com/x86/stos:stosb:stosw:stosd:stosq), so it leaves RDI pointing after the last byte it stored. We depend on the calling convention for DF=0 (increment not decrement), as is normal for all mainstream 32 and 64-bit calling conventions.
The same machine code bytes will do the same thing in 32-bit mode.
At first I was going to use `dec eax` / `stosb` for the terminator, with `1` instead of `'1'` as the unary digit "character". This would be 2 bytes in 32-bit mode only. But then I realized a `mov` store wouldn't need a displacement in the addressing mode, and that we had `cl`=0.
---
For an explicit-length-string version using separate pointer+length, we could return the input length after filling the input buffer (also leaving a pointer to the end in RDI). This would take the same total machine-code size: `push rcx` to start, `pop rax` at the end, instead of `mov [rdi], cl`.
---
**If the buffer is large and aligned, speed on typical modern CPUs, especially with the [ERMSB feature](https://stackoverflow.com/questions/43343231/enhanced-rep-movsb-for-memcpy), is basically as fast as typical libc memset, at least on Intel maybe not AMD.**
On a typical desktop, single-core memory bandwidth is usually close to maxing out the memory controllers. ([Much lower per-core bandwidth on many-core Xeons](https://stackoverflow.com/questions/39260020/why-is-skylake-so-much-better-than-broadwell-e-for-single-threaded-memory-throug).) Slower with page faults on the first access to newly allocated RAM, but this runs about as fast as it's possible for a single thread to go (for large aligned buffers), except by playing virtual memory tricks to map a range of virtual pages to the same memsetted page of '1's. With a misaligned buffer it's still probably under a second to fill 2GB. For small `n`, [microcode startup overhead](https://stackoverflow.com/questions/33902068/what-setup-does-rep-do) dominates, even on CPUs with the "fast-short-rep" feature. AMD CPUs may have slower `rep stos`, but even storing 1 byte per clock cycle would be way faster than the 4 hour requirement needs.
[Answer]
## Bash, 13 bytes (with calling other programs)
```
yes|head -n$1
```
##### Explanation
`yes` prints lines with the content `yes`. `head -n` will filter for the first n lines, n is given with `$1`.
The line with `yes` is used as digit.
## Pure Bash, 29 ~~34~~ bytes
```
for((i=$1;0<i;i--));do [;done
```
##### Explanation
The `for((i=$1;0<i;i--))` will do the commands between `do` and `done` `$1` times. `[` is a builtin bash command that expects a test and a `]`, which isn't provided, so it prints a error message every time. The error message is used as digit.
I tried also this one:
```
$1||pwd;$1||0 $(($1-1))
```
Which works almost when the script is named 0 and in the current `$PATH`. But it fails with large inputs, so not a working solution.
##### Explanation
The `||` means, if that on the left side fails, try that on the right side instead (till the end of the line or `;`). If it doesn't fail ignore the part on the right side. If there is nothing on the left side, the right is also ignored.
This tries to call program `$1`, i.e. the first parameter provided. Since the script is named `0`, it will work with the input `0`. so it calls itself without any argument. And then, when it runs without an argument, `$1` will expands to nothing, which means do nothing and ignore the part right of `||`.
If the parameter `$1` is a `number>0`, it will fail to execute a program because there is no program with that name. This means a error message is printed to `stderr`, which we ignore, and then the right side of `||` is executed.
The `$1||pwd;` part means: If program `$1` is not valid, i.e. `$1` is a number above `0`, it calls `pwd`. `pwd` outputs something to `stdout` and it shouldn't change. So we can use it as a non-changing digit. The `$1||0 $(($1-1))` part means: If program `$1` is not valid, call `0` / itself with the parameter `$(($1-1))`. `$(($1-1))` means 1 subtracted from `$1`.
It fails with large input because it recursively calls itself and so a new process starts. But i can't create 2'000'000'000 processes on my PC.
[Answer]
# [jot(1)](https://man.freebsd.org/cgi/man.cgi?jot(1)), 10 bytes
```
jot -b1 $1
```
[Try it online!](https://tio.run/##qyrO@J@moVn9Pyu/REE3yVBBxfB/LVeagqlCjUJRsYJuugGQY2yEzDM1MDAA8suTFXRzuJTTFIwMYAAm@h8A "Zsh – Try It Online")
Outputs a stream of `1`s separated by newlines. TIO times out doing the 2 billion case, but it takes just 4 minutes on my Intel Mac
```
$ time jot -b 1 2000000000|wc -l
2000000000
jot -b 1 2000000000 243.40s user 0.52s system 99% cpu 4:04.24 total
wc -l 2.61s user 1.70s system 1% cpu 4:04.24 total
```
[Answer]
# [JavaScript](https://nodejs.org), 15 bytes
```
n=>"".padEnd(n)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k5JSa8gMcU1L0UjT/N/cn5ecX5Oql5OfrpGmoappuZ/AA "JavaScript (Node.js) – Try It Online")
Returns the string. Uses a space as the character.
This might not be allowed, but for **9 bytes**
```
"".padEnd
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@19JSa8gMcU1L@V/cn5ecX5Oql5OfrpGml5yYk6OhpKSjoKppuZ/AA "JavaScript (Node.js) – Try It Online")
*-1 from both thanks to @Arnauld*
# [JavaScript](https://nodejs.org), 22 bytes
```
n=>print("".padEnd(n))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/z9auoCgzr0RDSUmvIDHFNS9FI09T83@ahqnmfwA "JavaScript (V8) – Try It Online")
Prints the string.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 49 bytes
*Full program, takes 1 argument*
```
main(a,v)int**v;{for(a=atoi(v[1]);a--;puts(*v));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1GnTDMzr0RLq8y6Oi2/SCPRNrEkP1OjLNowVtM6UVfXuqC0pFhDq0xT07r2////hgYA "C (gcc) – Try It Online")
[Answer]
# Swift, 31 bytes
```
{.init(repeating:"1",count:$0)}
```
[Try it online!](https://tio.run/##Ky7PTCsx@Z@TWqKQZqWg4ZlXoqmga6cQXFKUmZeuYPu/Wi8zL7NEoyi1IDWxBChkpWSopJOcX5pXYqVioFn7vwCorkQjTcPIQFPzPwA) A bit more verbose than some, but hopefully clear enough.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 9 bytes
```
->n{?1*n}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhYrde3yqu0NtfJqIfxVBaUlxQpu0YZGsRCBBQsgNAA)
[Answer]
# [jq](https://stedolan.github.io/jq/), 8 bytes
```
"1"*.+""
```
[Try it online!](https://tio.run/##yyr8/1/JUElLT1tJ6f9/AwA "jq – Try It Online")
[Answer]
**As a whole program:**
# [F# (.NET Core)](https://www.microsoft.com/net/core/platform), 66 bytes
```
[<EntryPoint>]let m a=[for _ in 1..(int(Seq.head a))->printf"1"];0
```
[Try it online!](https://tio.run/##SyvWTc4vSv3/P9rGNa@kqDIgPzOvxC42J7VEIVch0TY6Lb9IIV4hM0/BUE9PAyilEZxaqJeRmpiikKipqWtXUAQUS1MyVIq1Nvj//7@hEQA "F# (.NET Core) – Try It Online")
---
**As a function:**
# [F# (.NET Core)](https://www.microsoft.com/net/core/platform), 33 bytes
```
fun a->[for _ in 1..a->printf"1"]
```
[Try it online!](https://tio.run/##SyvWTc4vSv1vaMRVY/c/rTRPIVHXLjotv0ghXiEzT8FQTw/ILyjKzCtJUzJUiv3/HwA "F# (.NET Core) – Try It Online")
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 9 ~~15~~ ~~17~~ bytes
```
<,7_@#:+&
```
[Try it online!](https://tio.run/##S0pNK81LT/3/30bHPN5B2Upb7f9/I0NzAA "Befunge-93 – Try It Online")
This program is pretty simple. It gets a number as input, then it decrements it by adding `-1`. `-1` is the value returned when there is no input left, so I'm able to just use one `&` symbol to get the numbers I need and just continue adding the current value and `-1` to decrement. Each time the number is decremented, the program checks if it is `0`, and if it is, it quits. I did this by using a bridge (`#`) to skip over the stop command (`@`) and the go backward to the `@` if the value is `0` using a horizontal if `_`. Previous versions of my program weren't linear, but rather 2d, so the control was taking up a lot of space. The bridge command allowed me to keep control linear. The program starts with a `<` to make the program go backwards, this is because the horizontal if statement `_` goes right if `0`, but I need it to go left, so I reversed the whole program because that's easier than reversing it's input.
[Answer]
# [Matlab], 9 bytes
```
ones(1,n)
```
ones generates mxn matrixes of 1s
---
# [Matlab], 16 bytes
second version upon remarks in the comments
```
s=@(n) ones(1,n)
```
anonymous function that generates mxn matrixes of 1s
[Answer]
## Batch, 26 bytes
```
@for/l %i in (1,1,%1)do cd
```
The `@` is needed to prevent unwanted echo of the `for` command, but echo of the `cd` command is per-iteration anyway so no `@` is needed. The four spaces are needed so that the code will parse correctly.
] |
[Question]
[
Create all arrays of non-negative integers of length N where the array sum is equal to T. The output order of arrays does not matter.
Possible solutions are e.g.
```
N = 5, T = 2:
1 1 0 0 0
1 0 1 0 0
1 0 0 1 0
1 0 0 0 1
0 1 1 0 0
0 1 0 1 0
0 1 0 0 1
0 0 1 1 0
0 0 1 0 1
0 0 0 1 1
2 0 0 0 0
0 2 0 0 0
0 0 2 0 0
0 0 0 2 0
0 0 0 0 2
```
```
N = 4, T = 5
0 4 1 0
1 1 2 1
2 0 3 0
0 3 1 1
...
```
Erroneous outputs would be:
```
N = 3, T = 1
1 1 1
3 0 0
N = 4, T = 2
0 1 1
0 2 0 0 0 0
```
Edit: I sadly do not understand most of these very short code golf languages (but admire the creativity of them). To understand what you mean, main stream languages or explanations are encouraged. (How about Java, C# or C++?)
[Answer]
# [Jelly (fork)](https://github.com/cairdcoinheringaahing/jellylanguage), 5 bytes
```
ŻṗSƘ⁸
```
Can't Try it online! as this is a fork of Jelly with some newly added commands. `Ƙ` was added [3 days ago](https://github.com/cairdcoinheringaahing/jellylanguage/commit/6167f95e9aa29b15dd31a848022cd9909ef8c8bd).
Essentially a shortened version of my [other answer](https://codegolf.stackexchange.com/a/220723/66833)
## How it works
```
ŻṗSƘ⁸ - Main link. Takes T on the left and N on the right
Ż - Yield [0, 1, ..., T]
ṗ - N'th Cartesian power
⁸ - Yield T
Ƙ - Keep those for which the result of the following equals T:
S - Sum
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~71 69~~ 67 bytes
*Saved 1 byte thanks to @l4m2*
Expects `(n, t)` and prints all possible arrays.
```
f=(n,t,a=[],v=0)=>n?f(n-1,t,[...a,v])|t&&f(n,t-1,a,v+1):t||print(a)
```
[Try it online!](https://tio.run/##FcoxCoAwDADA3Vd0kgRjUVEQofoQ6RCEgA5FNHTq32tdj7s48ns8561tnHMWB4GU2O2eouvQrWETCG1fcLfWMkWPSeta/le4QNPjoindzxkUGLPARGbASmAkM2H@AA "JavaScript (V8) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = expected number of entries
t, // t = expected sum
a = [], // a[] = current output array
v = 0 // v = current value to be added to a[]
) => //
n ? // if there's at least one more entry to add:
f( // do a first recursive call:
n - 1, // decrement n
t, // pass t unchanged
[...a, v] // append v to a[]
) | t // end of recursive call; yield t
&& // if the above is truthy ...
f( // ... do a 2nd recursive call:
n, // pass n unchanged
t - 1, // decrement t
a, // pass a[] unchanged
v + 1 // increment v
) // end of recursive call
: // else:
t || print(a) // print a[] if t = 0
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~44~~ 42 bytes
```
1#t=[[t]]
n#t=[t-x:y|x<-[0..t],y<-(n-1)#x]
```
[Try it online!](https://tio.run/##PcxBCsIwEEbhfU/xQzYJZIoVu5H0CJ4gDBIkYLEdiplFCr171I27x7d4z1ReeVlaG4xOMSpzJ79Sqtf9qIHiqe@V/R7ICg3OVG6aiz5SyQUToh09zs7DXjxGx92aZvn6mrbbHdt7FkUUGCgOWPFQh0D4L7h9AA "Haskell – Try It Online")
* Saved 2 bytes thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard).
Takes `n` and `t` as input, returns the list of all the arrays of non-negative integers of length `n` that sum to `t`.
The implementation relies on the following recursive idea: such an array can always be obtained as the concatenation of the first element \$\texttt{x}\in\{0,1,\ldots,\texttt{t}\}\$ and an array `y` of length \$\texttt{n}-1\$ with sum equal to \$\texttt{t}-\texttt{x}\$.
**EDIT:** because of syntactic restrictions, it's actually more efficient (in terms of bytes) to pick \$\texttt{t}-\texttt{x}\$ as the first element, and recurse on \$(\texttt{n}-1,\texttt{x})\$.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes
```
1~Table~#~FrobeniusSolve~#2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b737AuJDEpJ7VOuc6tKD8pNS@ztDg4P6cMKGCk9j@gKDOvRN8hzcHBNTkj30FZrS44OTGvrpqr2lTHqFaHq9pExxREGesYQnhGtVy1//8DAA "Wolfram Language (Mathematica) – Try It Online")
```
FrobeniusSolve[ (* find all nonnegative integer vectors x s.t.: *)
1~Table~#, (* {1,...(N 1s)...,1}.x *)
#2] (* =T *)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~56~~ 53 bytes
```
->n,t{(a=*0..t).product(*[a]*~-n){|a|a.sum==t&&p(a)}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5Pp6RaI9FWy0BPr0RTr6AoP6U0uURDKzoxVqtON0@zuiaxJlGvuDTX1rZETa1AI1GztvZ/WrSpjlHsfwA "Ruby – Try It Online")
Ironically, this is shorter than directly using a built-in method - that's the result of long names:
### [Ruby](https://www.ruby-lang.org/), ~~58~~ 57 bytes
```
->n,t{[*0..t].repeated_permutation(n){|a|a.sum==t&&p(a)}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5Pp6Q6WstAT68kVq8otSA1sSQ1Jb4gtSi3tCSxJDM/TyNPs7omsSZRr7g019a2RE2tQCNRs7b2f1q0qY5R7H8A "Ruby – Try It Online")
Thanks to Dingus for -3 and -1 bytes, respectively.
[Answer]
# [J](http://jsoftware.com/), 26 bytes
```
((=1&#.)#])]>@,@{@#<@i.@>:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NTRsDdWU9TSVYzVj7Rx0HKodlG0cMvUc7Kz@a3KlJmfkKxgqpCkYQ5jqurq66hCmMVZRI6CoKYaoKVDU5D8A "J – Try It Online")
Similar to the other answers, this just generates all possible Cartesian products and filters them.
[Answer]
# [Haskell](https://www.haskell.org/), ~~46~~ 42 bytes
```
n#t=[x|x<-mapM(\u->[0..t])[1..n],sum x==t]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0@5xDa6oqbCRjc3scBXI6ZU1y7aQE@vJFYz2lBPLy9Wp7g0V6HC1rYk9n9uYmaebUFRZl6JioKxstF/AA "Haskell – Try It Online")
* saved 4 thanks to @Delfad0r
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~164~~ \$\cdots\$ ~~153~~ 151 bytes
Saved 3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Added 7 bytes to fix a bug kindly pointed out by [Neil](https://codegolf.stackexchange.com/users/17602/neil).
Saved 2 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!!!
```
#import<bits/stdc++.h>
auto f(int n, int t){std::vector<int>r;for(int i=pow(++t,n),v,j;i--;v||(r.push_back(i),0))for(v=t-1,j=i;j;j/=t)v-=j%t;return r;}
```
[Try it online!](https://tio.run/##hVJdU8IwEHzvr7ip40wzTQC/XkiLP0QdpoQAqZB20mt1xPrTxSRFsDhoXi693b3sJhVlyZZC7HYXalMWBpOZwmpY4VzE8WA1CbIaC1hESiNoCq4g2Vp4PG6kwMIktjUxfFEYz1FpWbxEcYxUE9rQnCvGePP@HplBWVer6SwTz5EidESIkzQpsiuap4rnPB@mSBqW5pfIjcTaaDC8tb60WNdzmaiiQiOzzSRwB20ypSMSbAOw69QPoKxwqiGF7R2FWwo3Lf@DiI54TcFx7/ZM6w66RBYccVuS/dRBpd5kRIBDHCsCnQO3/B1Zdkd7UE@8B@E3hD3IWxJFjZAkEDp96Hbaf1Kv8o0OBzZ51OFR7Z/HTbW0RWRfCMkRPGSQa7mBsef9NNzPqefy1WftdtYCd7phyj6Q2qiue6r@FSDqxPfWaWhPDEPium7OpR3De@I2ODsm7IVsz1wW@28dprSBL/vfasSDdvcpFutsWe3Yyxc "C++ (gcc) – Try It Online")
You asked for a C++ answer so here's one! :D
Inputs positive integers \$n\$ and \$t\$ and returns a `std::vector` holding all of the \$n\$-digit base\$\_{t+1}\$ integers who's \$n\$ base\$\_{t+1}\$ digits all sum to \$t\$.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 10 bytes
```
∪↑¯⍸¨,⍳⎕⍴⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM9DUisetQ28dD6R707Dq3QedS7@VHf1Ee9W4AkSP5/GpcplxGXrq4uF4hlDAA "APL (Dyalog Extended) – Try It Online")
Filtering is not so convenient in APL, so here is a solution that uses each input only once. A full program, which takes N then K from stdin, and prints a matrix. The final `∪` can be omitted if duplicate rows are allowed.
### How it works
```
∪↑¯⍸¨,⍳⎕⍴⎕ ⍝ First input (right): N, Second input (left): T
⎕⍴⎕ ⍝ T copies of N
,⍳ ⍝ Cartesian product of T copies of 1..N
¯⍸¨ ⍝ For each vector V from above,
⍝ creates another vector W where each index i appears W[i] times in V
⍝ e.g. [3 3 4] → [0 0 2 1]
↑ ⍝ Mix (promote a vector of vectors to a matrix), padding with zeros
∪ ⍝ Take unique rows
```
[Answer]
# [Zsh](https://www.zsh.org), ~~86~~ 57 bytes
```
for p (`eval echo ${(l:$2*8::+{0..$1}:)}`)<<<$p>>$[$p-$1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3LdPyixQKFDQSUssScxRSkzPyFVSqNXKsVIy0LKystKsN9PRUDGutNGsTNG1sbFQK7OxUolUKdFUMYyEGLLIxgDCWRRvpKJjEQs0FAA)
Outputs to a file called `0`.
* `${(l:$2*8::{0..$1},:)}`: repeat the string `"{0..$1}"`, \$ n \$ (`$2`) times
* `eval`: expand the string `+{0..$1}+{0..$1}+{0..$1}`, which produces the \$ n\$-permutations of the range \$ 0, 1, 2, ... T \$, separated by `+`
* ``echo``: print those permutations, space-separated
* `for p ()`: for each permutation, `$p`:
+ `<<<$p`: print `$p`
+ `$[$p-$1]`: evaluate `$p` as a numeric string, which sums the elements of the permutation (because each element was separated by `+`), and subtract the first input from it
+ `>>` append to the file `$[$p-$1]`; if they're equal, this difference will be zero, and it will be written to the file `0`.
[Answer]
# [R](https://www.r-project.org/), 62 bytes
```
function(n,t)(m=expand.grid(rep(list(0:t),n)))[rowSums(m)==t,]
```
[Try it online!](https://tio.run/##BcHBCoAgDADQX/G4wYoIukR@RcfoEKkh5JS5qL@396QFs3SmhYdPjZmBSRGS9V852PWXRAfiC9yxKgyzIjEibpLf9UkVElqrtLcAE43Yfg "R – Try It Online")
Slightly shorter (and more efficient) to use `expand.grid` rather than `combn`.
Generates the cartesian product of `[0..t]` with itself `n` times, then filters for those with row sums equal to `t`.
# [R](https://www.r-project.org/), 63 bytes
```
function(n,t)(m=unique(t(combn(rep(0:t,n),n))))[rowSums(m)==t,]
```
[Try it online!](https://tio.run/##DcIxCoAwDADArzgmEEEEF7GvcBQXSwsdkmpN8PmxxzXPwzYOnk2iliogpAgcTMpjCRRi5UugpRumVUmw745Wv934BcYQlE7PsNCM/gM "R – Try It Online")
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 16 bytes
```
{(y=+/)#+!x#1+y}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/Nqlqj0lZbX1NZW7FC2VC7svZ/WrSptVEsV1q0ibVp7H8A "K (ngn/k) – Try It Online")
```
{(y=+/)#+!x#1+y} / a function with arguments x (N) and y (T)
# / create a list
x / of x copies
1+y / of 1+y
! / make an odometer from this list (ranged permutations)
+ / transpose the result
# / keep only those lists
( +/) / that have sum which
y= / equals y
```
[Answer]
# [Python 3](https://docs.python.org/3/), 87 bytes
```
lambda n,t:[k for k in product(range(t+1),repeat=n)if sum(k)==t]
from itertools import*
```
[Try it online!](https://tio.run/##HcexDsIgEAbg3af40wmUDmpcTPBFtANaUEK5I9fr4NNj4rd97asfpnNP/tGXUJ9zADm93gsSCwoyoQnP20uNBHpHo4ejdRJbDOrJ5oR1q6ZY73XaJeGKrFGUeVmRa2PRfW@SSc3F4eQwjLfBIf1nbf8B "Python 3 – Try It Online")
# Explanation
First use `range` to get all integers between `0`and `t` and use `itertools.product` to find the array of cartesian product of itself repeated `n` times (so that would include all arrays of length n where each element is between 0 and t). Among all such arrays, we only pick the ones with sum equal to `t`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ŻṗS=¥Ƈ⁸
```
[Try it online!](https://tio.run/##AR4A4f9qZWxsef//xbvhuZdTPcKlxofigbj/w6dH//8y/zU "Jelly – Try It Online")
## How it works
```
ŻṗS=¥Ƈ⁸ - Main link. Takes T on the left and N on the right
Ż - Yield [0, 1, ..., T]
ṗ - N'th Cartesian power
¥Ƈ - Keep those for while the following is true:
S - Sum
= ⁸ - Equals T
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
pVÄ osU ù'0 m¬f_x ¥V
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cFbEIG9zVSD5JzAgbaxmX3ggpVY&input=MwoyCi1R)
```
Input : U = n , V = t
o - numbers from 0 to..
pVÄ - (n raised to t+1)excluded
sU - to base n
ù'0 - pad to left with '0' to max length element
m¬ - split each
f_ - keep
x ¥V - sum == t
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes
```
Nθ⊞υ⟦N⟧Fυ¿⁼Lιθ⟦⪫ι,⟧«≔⊟ιηF⊕η⊞υ⁺ι⟦κ⁻ηκ
```
[Try it online!](https://tio.run/##Tc4/D4IwEIfhGT7Fhema1MXEycnBAaOmO3FALLSxXKF/XIyfvRbi4Hj55X1ynWpdZ1uTUk1TDNc43qXDme1LEb3CyKH5H9gtL711gJGB7gGPc2yNx7OkISjUjMPMGAinKWBzsppQc6h4tYQgjZfwLouD93ogFHZaC5XNYkVr6pwcJQX5QLU4vx@EiX6BmieHi6Z8KA7PbObyk9Ku3KbNy3wB "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `N`.
```
⊞υ⟦N⟧Fυ
```
Start a breadth first search with an array `[T]`.
```
¿⁼Lιθ
```
If the current array has the correct number of entries, ...
```
⟦⪫ι,⟧
```
... then join it with commas and print it on its own line, ...
```
«
```
... otherwise:
```
≔⊟ιη
```
Remove the last entry from the array.
```
F⊕η
```
For all values from `0` to that entry inclusive...
```
⊞υ⁺ι⟦κ⁻ηκ
```
... concatenate the value and the difference from the original last entry to the remainder of the array, and save that for a future search pass.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
```
Select[Range[0,s=#2]~Tuples~#,Tr@#==s&]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277Pzg1JzW5JDooMS89NdpAp9hW2Si2LqS0ICe1uE5ZJ6TIQdnWtlgtVu1/QFFmXomCvkN6tKmOUSwXmBsNpcHCJjqmsf//AwA "Wolfram Language (Mathematica) – Try It Online")
-2 bytes from @att
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 50 bytes
```
G`$
.+
*
"$+"+%Lv$`_*$
$`,$&
(_*),
$.1,
Lm$`,$
$%`
```
[Try it online!](https://tio.run/##K0otycxLNPz/3z1BhUtPm0uLS0lFW0lb1adMJSFeS4VLJUFHRY1LI15LU4dLRc9Qh8snFyTEpaKa8P@/KZcRAA "Retina – Try It Online") No test suite because this program uses history. Explanation:
```
G`$
```
Delete `N`. (Don't worry, we can get it back later via `$+`.)
```
.+
*
```
Convert `T` to unary.
```
"$+"+`
```
Repeat `N` times...
```
%`
```
... for each line...
```
Lv$`_*$
```
... for all the suffixes of the last entry, i.e. the numbers from it down to zero...
```
$`,$&
```
... split the last entry into two values that sum to it.
```
(_*),
$.1,
```
Convert all the values to decimal, except for the last value on each line.
```
Lm$`,$
$%`
```
List only those lines that end with a zero entry, keeping only the prefix of the line. This is required because we split `T` `N` times, resulting in a list of length `N+1`, so to fix this we only keep those entries that end with zero, dropping that zero from the final output.
[Answer]
# MATL, 13 bytes
```
Q:qZ^t!s1G=Y)
```
First input is `T` and second input is `N`
[Try it out at MATL Online](https://matl.io/?code=Q%3AqZ%5Et%21s1G%3DY%29&inputs=2%0A5&version=22.4.0)
**Explanation**
```
% Implicitly grab the first input, T
Q:q % Add 1 to T, create array from 1...(T+1), subtract 1 to yield 0...T
Z^ % Perform the Cartesian product with the second input
t % Duplicate the result
!s % Sum across the rows
1G % Explicitly grab the first input again, T
= % Compare the sum of each row to T
Y) % Use this a logical index to grab only those rows where the sum == T
% Implicitly display the result
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
ݹãʒOQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8NxDOw8vPjXJP/D/f1MuIwA "05AB1E – Try It Online")
```
ݹãʒOQ # full program
ʒ # all elements of...
ã # all combinations of...
Ý # [0, 1, 2, ...,
# ..., implicit input...
Ý # ]...
ã # repeated...
¹ # first input...
ã # times...
ʒ # where...
O # sum of all elements in...
# (implicit) current element in list...
Q # is equal to...
# implicit input
# implicit output
```
[Answer]
# [Functional Bash](https://www.gnu.org/software/bash/)\*, 160 bytes
\* This is bash with the additional constraint that you can't mutate variables.
```
d=$(eval echo $(printf "{0..$1}%.0s+" $(seq $1))|tr \ \\n)
paste <(sed s/$/0/<<<$d|bc|awk "{print match(\$0,/^$2$/)?1:0}") <(sed s/+/\ /g<<<$d)|grep ^1|cut -f2
```
[Try it online!](https://tio.run/##PY5BDoIwFAX3nOKHfAMNlrYYNwbjRRqSUgoYFZFWXVDOjg0Lt/Myk1cr269tSua1OWNqPuoORvdPwHScroNrIZ55nqNYdjm3WRy4NS9AQYh3E0gAKQcSjco6A2XYGrAMGWdlWWLja@3V9xYaWwweyuk@lcj3rMICGbmIE19i8jczJoF1m0t8N5kRKuH12wFti3WJWjhCEW3/EkppEsABxPoD "Bash – Try It Online")
Could be golfed more, but sort of a fun idea.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 bytes
```
ÆVòÃc àU f_x ¥VÃâ
```
[Try it online!](https://tio.run/##ASYA2f9qYXB0///DhlbDssODYyDDoFUgZl94IMKlVsODw6L//zUsMiAtUQ "Japt – Try It Online")
Uses a significantly different strategy from the [other Japt answer](https://codegolf.stackexchange.com/a/220737/71434). The order of the outputs is weird, but all of them seem to be there.
Explanation:
```
ÆVòÃc àU f_x ¥VÃâ
Vò # Create the array [0...T]
Æ Ã # Create N copies of that array
c # Flatten them all into a single array
àU # Create all combinations of elements of that array that have length N
f_ Ã # Keep only the ones where:
x # The sum of the numbers
¥V # Is equal to T
â # Remove any duplicates
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 60 bytes
```
f=(n,t,a,g=i=>f(n,t-i,[a,i])|i&&g(i-1))=>--n?g(t):print(t+a)
```
[Try it online!](https://tio.run/##JcgxCoAwDEDR3VM4SYLJoCiI0HoQcQhCSxyKaHDy7lUR/vL@Jpec66G78TXk4N4gkZFQdOp8@MBKs5AueGtVRVBuEJ1nTlMEw3E/NBlYLZgD9FS2WPwLiwAdlT3mBw "JavaScript (V8) – Try It Online")
```
f=(n,t,
a, // previous numbers, initialed as undefined (empty)
g= // helper function to loop current number from t to 0
i=> // `i` is current number
f(n,t-i,[a,i])| // try to use current number and `t-i` remined
i&&g(i-1) // loop until i = 0
)=>
--n? // Is more than 1 number required?
g(t): // Try current number, loop from `t`
print(t+a) // We found an partition with t and previous numbers
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~133 124~~ 112 bytes
```
p,i,j,r;f(n,t){for(p=pow(++t,n);i=j=--p;){for(r=t-1;j;j/=t)r-=j%t;for(j=n;j--;i/=t)r||printf("%d%c",i%t,9+!j);}}
```
[Try it online!](https://tio.run/##JcxBCsIwEEDRs1gIJHQGUVcyzGFCJCVDmoY44KLt1Y1Vt@/DDxiyL1PvFRIINIq2gLo1Ls1WrsvLjqNCcZRYGLHSPzVWvJCQnFldQxaj9HXhQoJI6efbVlsqGu1gHiYMkIzCfTyJo33vs0/FHjd7g@sB/R1i9tOzY54/ "C (clang) – Try It Online")
* Saved 12 thanks to @ceilingcat
* iterates over all numbers up to (t+1)^n , convert to base t+1 then prints only if digits sums to t.
* prints elements separated by tab.
[Answer]
# [Python 3](https://docs.python.org/3/), 74 bytes
```
f=lambda N,T:N and[j+[i]for i in range(T+1)for j in f(N-1,T-i)]or[[]]*-~-T
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRwU8nxMpPITEvJTpLOzozNi2/SCFTITNPoSgxLz1VI0TbUBMklAUSStPw0zXUCdHN1IzNL4qOjo3V0q3TDflfUJSZV6JhqqNgpKOgpGunpANUCOJpav4HAA "Python 3 – Try It Online")
Shortened version of this
```
def f(N,T):
if N == 0:
if T == 0: return [[]]
else: return []
else:
l = []
for i in range(T+1): # possible last elements
for j in f(N-1,T-i): # solutions for rest of elements
l.append(j+[i])
return l
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~76~~ 74 bytes
```
f=(n,t,z=t)=>n<2?[[t]]:f(n-1,t-z).map(a=>[z,...a]).concat(z?f(n,t,z-1):[])
```
[Try it online!](https://tio.run/##lcyxCsIwFIXh3afIeC8kgRYLUkw7uTjo4BgyXEJTKzUpbSiYl4@CCK6dz/@dB6202HmYolgPOTsFnkeeVETV@GPZah2NqR14UfAoEsonTUCq0YlLKcmgtMFbipBa96WiwFobzA4qzkqULswnsncgphr2iZcwdnIMPZxv14tc4jz4fnAvIETcOSg4qzaj/Xb0v/8Oxs738Y75DQ "JavaScript (V8) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org) 73 (88) bytes
This solution is longer than both existing Haskell solutions. But it's fun, and that's what code golf is about.
```
1#t=[[t]]
n#1=(n-1)#1>>=(\p->[0:p,1:(0<$p)])
n#t=zipWith(+)<$>n#1<*>n#(t-1)
```
Here's how it works:
* Bottom case: If, given any particular *N*, you could solve the problem for *T=1* and any other *Ta*, you could solve it for *Ta+1* as well. You would only have to find every possible pairing of a *Ta* array and a *T=1* array and add up both arrays element-wise. So by induction if you could solve the problem for *T=1*, you could solve it for any *T*.
* Middle case: Now you only have an infinite number of problems remaining: solving the task for any *N*, given *T=1*. But if you *had* a solution for *T=1* and any *Na*, you could get a solution for *T=1* and *Na+1* by simply putting a zero in front of every existing array and adding one more trivial array (in this case, many times). So actually you only have to solve the task for *T=1* and *N=1*.
* Top case: Now that's trivial.
To get down to this enormous reduction of being almost longer than all existing Haskell solutions combined, this solution not only uses almost every trick in my book, but it also exploits two holes of the task description:
1. The task doesn't state that an array can only appear once
2. No restrictions are given for *N* and *T*, so I didn't make it work for non-trivial *T=0*.
To get rid of both exploits, more bytes are necessary. But yet another level of beauty emerges, both because the solution is now actually longer than all existing Haskell solutions combined, and because the middle case gains some symmetry.
```
1#t=[[t]]
n#0=[0<$[1..n]]
(n+1)#1=[1:p|p<-n#0]++[0:p|p<-n#1]
n#(t+1)=zipWith(+)<$>n#1<*>n#t
```
[Answer]
# [Macaulay2](https://faculty.math.illinois.edu/Macaulay2/), 36 bytes
```
n->t->exponents(sum gens(ZZ[n:x]))^t
```
[Try it online!](https://sagecell.sagemath.org/?z=eJzL07Ur0bVLrSjIz0vNKynWKC7NVUhPzSvWiIqKzrOqiNXUjCvh4uLS1VUoSS0uUUhOLE614tLIz1cw1VQwAgB6jhLt&lang=macaulay2&interacts=eJyLjgUAARUAuQ==)
This is based on the fact that, by the [multinomial theorem](https://en.wikipedia.org/wiki/Multinomial_theorem), the multivariate polynomial
$$(x\_1 + \cdots + x\_n)^t = \sum\_{t\_1+\cdots+t\_n=t} \binom{t}{t\_1,\dots,t\_n} x\_1^{t\_1} \cdots x\_n^{t\_n} \in ℤ[x\_1,\dots,x\_n]$$
involves all the monomials of degree *t* in *n* variables when fully expanded. As the exponents of each monomial sum to *t*, taking all the exponent vectors of this polynomial gives the solution.
For example, with *n*=2, *t*=4, the polynomial
$$(x\_1 + x\_2)^4 = x\_1^4 + 4 x\_1^3 x\_2 + 6 x\_1^2 x\_2^2 + 4 x\_1 x\_2^3 + x\_2^4$$
has exponents (4,0), (3,1), (2,2), (1,3), (0,4).
---
Edit: As a side note, there is even a builtin for this: `compositions` (12 bytes). [Try it online!](https://sagecell.sagemath.org/?z=eJxLzs8tyC_OLMnMzyvWMNVRMNIEAEPEBiw=&lang=macaulay2&interacts=eJyLjgUAARUAuQ==)
[Answer]
# TI-Basic, ~~56~~ 52 bytes
```
Prompt N,T
T+1→U
For(I,1,U^N
seq(UfPart(int(I/U^J)/U),J,0,N-1
If T=sum(Ans
Disp Ans
End
```
-4 bytes thanks to [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush).
Output is displayed as lists separated by newlines.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~54~~ 53 bytes
```
f=->n,t,*a{n>1?0.upto(t){|x|f[n-1,t-x,*a,x]}:p(a<<t)}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5Pp0RHK7E6z87Q3kCvtKAkX6NEs7qmoiYtOk/XUKdEtwIoq1MRW2tVoJFoY1OiWfs/LdpUxyiWKy3aRMc09j8A "Ruby – Try It Online")
I don't know if the initial "f=" is considered part of the function. If I could move that to the header, this would be 51 bytes. I've always considered it a part of the function (because of recursion), but I think I've seen answers where it was removed.
] |
[Question]
[
### Task
The task is very simple. Given a non-empty string containing **numbers**, **uppercase** and **lowercase letters**, output the sum of the remaining numbers. For example:
```
a1wAD5qw45REs5Fw4eRQR33wqe4WE
```
Filtering out all the letters would result into:
```
1 5 45 5 4 33 4
```
The sum of these numbers is `1 + 5 + 45 + 5 + 4 + 33 + 4 = 97`. So the output would be `97`.
### Test Cases
```
a > 0
0 > 0
5 > 5
10 > 10
a0A > 0
1a1 > 2
11a1 > 12
4dasQWE65asAs5dAa5dWD > 79
a1wAD5qw45REs5Fw4eRQR33wqe4WE > 97
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins!
[Answer]
# GS2, 2 bytes
```
Wd
```
[Try it online!](http://gs2.tryitonline.net/#code=V2Q&input=YTF3QUQ1cXc0NVJFczVGdzRlUlFSMzN3cWU0V0U)
### How it works
```
W Read all numbers.
For input x, this executes map(int, re.findall(r'-?\d+', x)) internally.
d Compute their sum.
```
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), 8 bytes
Take that, Pyth...
```
?+
;,;!@
```
[Try it online!](http://labyrinth.tryitonline.net/#code=PysKOyw7IUA&input=YTF3QUQ1cXc0NVJFczVGdzRlUlFSMzN3cWU0V0U)
### Explanation
The usual primer (stolen from Sp3000):
* Labyrinth is 2D and stack-based. Stacks have an infinite number of zeroes on the bottom.
* When the instruction pointer reaches a junction, it checks the top of the stack to determine where to turn next. Negative is left, zero is forward and positive is right.
What comes in really handy here is that Labyrinth has two different input commands, `,` and `?`. The former reads a single byte from STDIN, or `-1` at EOF. The latter reads an integer from STDIN. It does so skipping everything that *isn't* a number and then reads the first decimal number it finds. This one returns `0` at EOF, so we can't use it to check for EOF reliably here.
The main loop of the program is this compact bit:
```
?+
;,
```
With `?` we read an integer (ignoring all letters), with `+` we add it to the running total (which starts out as one of the implicit zeroes at the stack bottom). Then we read another character with `,` to check for EOF. As long as we're not at EOF, the read character will be a letter which has a positive character code, so the IP turns right (from its point of view; i.e. west). `;` discards the character because we don't need it and then we enter the loop again.
Once we're at EOF, `,` pushes a `-1` so the IP turns left (east) instead. `;` again discards that `-1`, `!` prints the running total as an integer and `@` terminates the program.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 8 bytes
```
1Y4XXXUs
```
[**Try it online!**](http://matl.tryitonline.net/#code=MVk0WFhYVXM&input=JzRkYXNRV0U2NWFzQXM1ZEFhNWRXRCc)
```
1Y4 % predefined literal: '\d+'
XX % implicit input. Match regular expression. Returns a cell array of strings
% representing numbers
XU % convert each string to a double. Returns a numeric array
s % sum of numeric array
```
[Answer]
## CJam, 13 bytes
Fixed to work with input without numbers thanks to Dennis! Also saved a byte by replacing the letters array with an array of ASCII above code point 64. And then another byte saved by Dennis!
```
q_A,s-Ser~]1b
```
Simple transliteration from letters to spaces, then eval and sum. [Try it online](http://cjam.aditsu.net/#code=q_A%2Cs-Ser%7E%5D1b&input=a3bv6).
[Answer]
# JavaScript ES6, 35 bytes
```
s=>eval(s.replace(/\D+/g,'+')+'.0')
```
### How it works
First, we replace each string of non-digits with `"+"`. There are basically four different ways that this could end up:
```
1. 1b23c456 => 1+23+456
2. a1b23c456 => +1+23+456
3. 1b23c456d => 1+23+456+
4. a1b23c456d => +1+23+456+
```
Cases 1 and 2 are taken care of already. But we somehow need to fix the last `+` so that it doesn't cause an error. We could remove it with `.replace(/\+$,"")`, but that's too expensive. We could append a `0` to the end, but that would affect the last number if the string does not end with a `+`. A compromise is to append `.0`, which is both a valid number on its own and doesn't affect the value of other integers.
Here's a few other values that would work as well:
```
.0
-0
+0
-""
-[]
0/10
0e-1
.1-.1
```
### Alternate version, also 35 bytes
```
s=>s.replace(/\d+/g,d=>t+=+d,t=0)|t
```
### Another alternate version, 36 bytes
```
s=>s.split(/\D/).map(d=>t+=+d,t=0)|t
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~22~~ 11
```
\d+
$0$*1
1
```
[Try it online!](http://retina.tryitonline.net/#code=XGQrCiQwJCoxCjE&input=YTF3QUQ1cXc0NVJFczVGdzRlUlFSMzN3cWU0V0U)
11 bytes (!) saved thanks to Martin!
Basically just decimal to unary then count the `1`s.
[Answer]
# Japt, 2 bytes
```
Nx
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=Tng=&input=YTF3QUQ1cXc0NVJFczVGdzRlUlFSMzN3cWU0V0U=)
### How it works
```
N // Implicit: N = (parse input for numbers, "strings", and [arrays])
x // Sum. Implicit output.
```
[Answer]
## Pyth, ~~12~~ ~~11~~ 10 bytes
```
ssM:z"\D"3
```
```
z autoinitialized to input()
: "\D"3 split on non-digits
sM convert all elements of resulting array to ints
s sum
```
Fortunately, `s` (convert to int) returns `0` when applied to the empty string, so I don't have to worry about the fact that `split("a1b", "\D+")` returns `["", "1", ""]`. Similarly, `split("a", "\D+")` returns `["", ""]`.
This even allows me to split on every non-digit individually, since `1 + 0 + 0 + 0 + 0 + 2` is the same thing as `1 + 2`.
Thanks to [Thomas Kwa](https://codegolf.stackexchange.com/users/39328/thomas-kwa) for a byte!
[Answer]
# [Gol><>](https://golfish.herokuapp.com/), 4 bytes
```
iEh+
```
So short I need dummy text...
[Answer]
# [Perl 6](http://perl6.org), 18 bytes
```
{[+] .comb(/\d+/)}
{[+] .split(/\D/)}
```
### Usage:
```
my &code = {[+] .comb(/\d+/)}
say code 'a'; # 0
say code '0'; # 0
say code '5'; # 5
say code '10'; # 10
say code 'a0A'; # 0
say code '1a1'; # 2
say code '11a1'; # 12
say code '4dasQWE65asAs5dAa5dWD'; # 79
say code 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'; # 97
```
[Answer]
# Jelly, 6 bytes
```
&-ṣ-ḌS
```
[Try it online!](http://jelly.tryitonline.net/#code=Ji3huaMt4biMUw&input=&args=ImExd0FENXF3NDVSRXM1Rnc0ZVJRUjMzd3FlNFdFIg)
### How it works
```
&-ṣ-ḌS Main link. Input: L (string)
&- Take the bitwise AND of L's characters and -1.
This attempts to cast to int, so '0' & -1 -> 0 & -1 -> 0.
On failure, it returns the integer argument (if any), so 'a' & -1 -> -1.
ṣ- Split the resulting list at occurrences of -1.
Ḍ Convert each chunk from decimal to integer. In particular, [] -> 0.
S Compute the sum of the results.
```
[Answer]
# Perl, 21 + 1 = 22 bytes
```
$_=eval join"+",/\d+/g
```
Requires the `-p` flag:
```
$ perl -pe'$_=eval join"+",/\d+/g' <<< 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'
97
```
[Answer]
# Julia, 35 bytes
```
s->sum(parse,matchall(r"\d+","0"s))
```
This is an anonymous function that accepts a string and returns an integer. To call it, assign it to a variable.
We use `matchall` to get an array consisting of matches of the regular expression `\d+`, which are just the integers in the string. We have to tack on a 0 to the front of the string, otherwise for cases like `"a"`, we'd be summing over an empty array, which causes an error. We then apply `parse` to each string match, which converts to integers, and take the sum.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 4 bytes
```
⁽±Ḋ⌊
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQcyIsIiIsIuKBvcKx4biK4oyKIiwiIiwiNGRhc1FXRTY1YXNBczVkQWE1ZFdEICJd)
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 23 bytes
Based on [Ventero’s answer here](https://codegolf.stackexchange.com/a/742/11261).
```
p eval$_.scan(/\d+/)*?+
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6eUuyCpaUlaboW2wsUUssSc1Ti9YqTE_M09GNStPU1tey1IbJQRQv2JhqWO7qYFpabmAa5Fpu6lZukBgUGGRuXF6aahLtCFAEA)
[Answer]
# PHP, 64 bytes
```
<?php preg_match_all("/\d+/",$argv[1],$a);echo array_sum($a[0]);
```
Run it as
```
php -f filterOutAndAddUp.php <test_case>
```
<https://eval.in/517817>
[Answer]
# Javascript, ~~32~~ 39 bytes
```
s=>eval((s.match(/\d+/g)||[0]).join`+`)
```
```
f=
s=>eval((s.match(/\d+/g)||[0]).join`+`)
F=s=>document.body.innerHTML+='<pre>f(\''+s+'\') -> '+f(s)+'\n</pre>'
F('a')
F('5')
F('10')
F('1a1')
F('11a1')
F('4dasQWE65asAs5dAa5dWD')
F('a1wAD5qw45REs5Fw4eRQR33wqe4WE')
```
[Answer]
# Mathematica, 51 bytes
```
Total@ToExpression@StringCases[#,DigitCharacter..]&
```
Catching the wrong end of the verbose Mathematica builtins. 1 Byte off with the help of @DavidC
[Answer]
# R, ~~46~~ 43 bytes
```
sum(strtoi(strsplit(scan(,''),'\\D')[[1]]))
```
**Explanation**
```
scan(,'') # Take the input string
strsplit( ,'\\D') # Returns list of all numeric parts of the string
[[1]] # Unlists to character vector
strtoi( ) # Converts to numeric vector
sum( ) # Sums the numbers
```
**Sample run**
```
> sum(strtoi(strsplit(scan(,''),'\\D')[[1]]))
1: a1wAD5qw45REs5Fw4eRQR33wqe4WE
2:
Read 1 item
[1] 97
```
Edit: Replaced `[^0-9]` with `\\D`.
[Answer]
# [Factor](https://factorcode.org) + `math.unicode sorting.human`, 36 bytes
```
[ find-numbers [ real? ] filter Σ ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=JYq7asNAEEX7-Yop0lposdaEpAgCyyZNwApGhXEx0Y5igbXSvlhMyEe4TiMIzuek99_koebewz3346uh2vd2vJ63z49P6zvsyB_QsQmsa3boeutb_ZocQkf6XyZBt3WvGAfL3p8G22qPJuI9mPgGBClIEClQmoMgAeIvMkVuUxULSS53UuUkVbUEEjFfShMzWRZOrmLG5aacz6PhrCrg_RJ8M7u93uywabWa6dC9sHW4Q8t0fMD973z0bPH7E_fT99LRgMnE4zj1Dw)
```
! "11a1"
find-numbers ! { "" 11 "a" 1 }
[ real? ] filter ! { 11 1 }
Σ ! 12
```
[Answer]
## PowerShell, ~~28~~ 26 bytes
```
$args-replace"\D",'+0'|iex
```
Takes input `$args` then does a regex `-replace` to swap the letters with `+0`, then pipes that to `iex` (short for `Invoke-Expression` and similar to `eval`).
```
PS C:\Tools\Scripts\golfing> .\filter-out-and-add-up.ps1 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'
97
```
---
**Alternatively**
If you're OK with some extraneous output, you can do the following, also at ~~28~~ 26 bytes:
```
$args-split"\D"|measure -s
```
This will take the input string `$args` and `-split` it into an array-of-strings on the non-numbers (removing them in the process). For example, `1a2b33` would turn into `['1','2','33']`. We pipe that to `Measure-Object` with the `-Sum` parameter. Output would be like the below:
```
PS C:\Tools\Scripts\golfing> .\filter-out-and-add-up.ps1 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'
Count : 21
Average :
Sum : 97
Maximum :
Minimum :
Property :
```
Edit -- durr, don't need the `[ ]` in the regex since I'm no longer specifying a list of possible matches ...
[Answer]
# Gema, 39 characters
```
<D>=@set{s;@add{${s;};$0}}
?=
\Z=${s;0}
```
Sample run:
```
bash-4.3$ gema '<D>=@set{s;@add{${s;};$0}};?=;\Z=${s;0}' <<< 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'
```
[Answer]
## Seriously, 13 bytes
```
,ú;û+@s`≈`MΣl
```
[Try it online!](http://seriously.tryitonline.net/#code=LMO6O8O7K0BzYOKJiGBNzqNs&input=ImExd0FENXF3NDVSRXM1Rnc0ZVJRUjMzd3FlNFdFIg)
Explanation:
```
,ú;û+@s`≈`MΣl
, push input
ú;û+ push "abc...zABC...Z" (uppercase and lowercase English letters)
@s split on letters
`≈`M convert to ints
Σ sum
l length (does nothing to an integer, pushes 0 if an empty list is left, in the case where the string is all letters)
```
[Answer]
# Java, 70 bytes
```
s->{int n=0;for(String i:s.split("\\D+"))n+=Long.valueOf(i);return n;}
```
[Answer]
# TI-Basic, 106 bytes
Works on TI-83/84 calculators!
```
Input Str1
"{0,→Str2
Str1+"N0→Str1
For(I,1,length(Ans
sub(Str1,I,1
If inString("0123456789",Ans
Then
Str2+Ans→Str2
Else
If ","≠sub(Str2,length(Str2),1
Str2+","→Str2
End
End
sum(expr(Ans
```
[Answer]
# Clojure/ClojureScript, 35 bytes
```
#(apply +(map int(re-seq #"\d+"%)))
```
[Answer]
# R, 50 bytes
Requires having `gsubfn` installed
```
sum(gsubfn::strapply(scan(,''),'\\d+',strtoi)[[1]])
```
Uses `strtoi` to coerce to numeric
[Answer]
# Ruby 45 bytes
```
$*[0].split(/[a-z]/i).map(&:to_i).inject 0,:+
```
(First attempt at work, will revisit this)
[Answer]
# POSIX sh + tr + dc, 27 25 bytes
```
dc -e "0d`tr -sc 0-9 +`p"
```
Converts any run of non-digits (including the terminating newline) to `+` operator, pushes two zeros onto the stack (in case input begins with non-digit), adds them all and prints the result. There may be an extra zero remaining at bottom of stack, but we don't care about that.
[Answer]
## Lua, 51 Bytes
Pretty short for once! Even shorter than Java! The input must be a command-line argument for it to work.
```
a=0 arg[1]:gsub("%d+",function(c)a=a+c end)print(a)
```
### Ungolfed
```
a=0 -- Initialize the sum at 0
arg[1]:gsub("%d+", -- capture each group of digits in the string
function(c) -- and apply an anonymous function to each of them
a=a+c -- sums a with the latest group captured
end)
print(a) -- output a
```
] |
[Question]
[
*Also known as the [analog root]*
([Opposite of the digital root!](https://codegolf.stackexchange.com/questions/123258/opposite-of-the-digital-root?answertab=active#comment302444_123258)) ;)
The digital root of a number is the continuous summation of its digits until it is a single digit, for example, the digital root of 89456 is calculated like this:
8 + 9 + 4 + 5 + 6 = 32
3 + 2 = 5
The digital root of 89456 is 5.
Given a digit as input via **STDIN**, print/return all of the possible two digit numbers that have that digital root. If you need it to, it can include itself, e.g. 05
These are all of the possible inputs and outputs:
**(You get to choose whether or not to include the leading zero for the digit itself)**
## I/O
**0** => 0 or 00 or nothing
**1** => 01 and/or 1, 10, 19, 28, 37, 46, 55, 64, 73, 82, 91 - **Make sure that 1 does not return 100**
**2** => 02 and/or 2, 11, 20, 29, 38, 47, 56, 65, 74, 83, 92
**3** => 03 and/or 3, 12, 21, 30, 39, 48, 57, 66, 75, 84, 93
**4** => 04 and/or 4, 13, 22, 31, 40, 49, 58, 67, 76, 85, 94
**5** => 05 and/or 5, 14, 23, 32, 41, 50 ,59, 68, 77, 86, 95
**6** => 06 and/or 6, 15, 24, 33, 42, 51, 60, 69, 78, 87, 96
**7** => 07 and/or 7, 16, 25, 34, 43, 52, 61, 70, 79, 88, 97
**8** => 08 and/or 8, 17, 26, 35, 44, 53, 62, 71, 80, 89, 98
**9** => 09 and/or 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99
No [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default), and it's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
>
> Congrats to [Heeby Jeeby Man](https://codegolf.stackexchange.com/users/56656/heeby-jeeby-man) on [his amazing 46 byte brain-flak answer!](https://codegolf.stackexchange.com/a/153072/69912)
>
>
>
[Answer]
## JavaScript (ES6), ~~27~~ ~~31~~ 30 bytes
Returns `0` for `0` or an array of solutions otherwise.
```
n=>n&&[...1e9+''].map(_=>n+=9)
```
### Demo
```
let f =
n=>n&&[...1e9+''].map(_=>n+=9)
for(n = 0; n < 10; n++) {
console.log(n, JSON.stringify(f(n)));
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ ~~12~~ 9 bytes
-3 bytes thanks to Adnan
```
тL<ʒSOSOQ
```
[Try it online!](https://tio.run/nexus/05ab1e#@3@xycfm1KRg/2D/wP//TQE "05AB1E – TIO Nexus")
## Explanation
```
тL<ʒSOSOQ Main link. Argument n
тL< List from 1 to 100, then decrement to get 0 to 99
ʒ Filter
SOSO Sum of all chars, twice
Q Compare to input
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
11Ḷ×9+ȧ@
```
[Try it online!](https://tio.run/##y0rNyan8/9/Q8OGObYenW2qfWO7w//9/SwA "Jelly – Try It Online")
Different algorithm than my other answer.
[Answer]
# [Brain-Flak](https://github.com/Flakheads/BrainHack), 46 bytes
```
{((()()()()()){}){(({}[()])<(({}{}[]))>)}}{}{}
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1pDQ0MTBjWrazWBAtW10RqasZo2IBaQHaupaadZWwti//9vCgA "Brain-Flak – Try It Online")
## Explanation
This answer uses an idea from [Megatom's answer](https://codegolf.stackexchange.com/a/153112/56656) namely using the stack height as the difference between the loop counter and the increment. Like previous answers this answer has a large outer loop to catch all the zeros. Inside the loop we push 10 to act as a counter, we then start another nested loop. In this loop we decrement the counter by 1
```
({}[()])
```
Then we pop the top two items, which are the counter and the last item we calculated. We add these to the stack height in order to counter balance the decrementation, we then push this twice, once for output and once so that it can be consumed to calculate the next result. Pushing things twice means we accidentally push an additional value which needs to be removed at the end of execution.
The reason this just barely beats Megatom is Megatom's answer is forced to get its stack heights while the last result is still on the stack. This means they are forced to use a rather expensive `[()]` to decrease the total by one. By moving the duplicate to the end of the loop I am able to avoid having to use `[()]` at the cost of an additional `{}` at the very end of the program. If Megatom were to use this strategy his answer would look like:
```
{<>((()()()()()){}){((({}[()])<>{}[]))<>}}<>{}
```
also 46 bytes.
# [Brain-Flak](https://github.com/Flakheads/BrainHack), 52 bytes
```
{((()()()()()){}){({}[()]<(({})((()()())){}{})>)}}{}
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v@/WkNDQxMGNatrNas1qmujNTRjbTSADE2YLEgKyLXTrAVS//8b/TcEAA "Brain-Flak (BrainHack) – Try It Online")
## Explanation
The main outerloop makes a special case for input of zero. If zero is input we jump over the entire loop, pop zero and then output nothing. Otherwise we enter the loop. Here we push loop 10 times each time adding 9 to the top of the stack, keeping old values. Since 9 preserves digital sums this will get us the next value. Once the loop has expired we use the zero it generated to exit the loop which is then popped by the `{}` at the end.
# [Brain-Flak](https://github.com/Flakheads/BrainHack), 56 bytes
```
{([(((()()())){}{})]){({}()<(({})<(({}{}))>)>)}}{}({}{})
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v@/WiNaAwg0QVBTs7q2ulYzVrNao7pWQ9NGA0hBSCCtaQeEtUAWhPv/v9F/QwA "Brain-Flak (BrainHack) – Try It Online")
## Explanation
This version works very similarly to the last one, except we loop 9 times instead of 10 leaving out the original value. In order to do this we have to rearrange the way we handle memory a bit. All of the bytes we might have saved using this method get put into cleanup.
[Answer]
# [Haskell](https://www.haskell.org/), 21 bytes
`f` takes an integer and returns a list of integers.
```
f d=[d,d+9..99^0^0^d]
```
[Try it online!](https://tio.run/nexus/haskell#DcJLCoAgFAXQrdxBg6J49C8HrSQKpKckpIUWLd/iHCuNm4y7lZfbnTzuME4FsvJKw36@pMkryRm9p@cQNXiaueBcEAmxlj9eYixRoUaDFh16DBghPg "Haskell – TIO Nexus")
* Starts with the digit `d` and generates the range with every 9th number up to a bound of 99, *except* for the tricky case of `0`.
* To stop early for `0`, uses that the power `0^d==1` for `0` and `==0` for all other digits. Thus `99^0^0^d` gives `1` for `0` but `99` for anything else.
[Answer]
## Pyke, 6 bytes
```
ITV
9+
```
[Try it here!](http://pyke.catbus.co.uk/?code=ITV%0A9%2B&input=2&warnings=0)
```
ITV\n9+ - if input: (don't print anything for 0 case)
TV\n9+ - repeat 10 times:
\n - print ^
9+ - ^ += 9
```
[Answer]
# [Python 2](https://docs.python.org/2/), 29 bytes
```
lambda n:n and range(n,100,9)
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQZ5WnkJiXolCUmJeeqpGnY2hgoGOp@b@gKDOvRCFNIzOvoLREQ1PzvyEA "Python 2 – TIO Nexus")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes
```
0g|g{t+₉}ᵃ¹⁰
```
[Try it online!](https://tio.run/nexus/brachylog2#@2@QXpNeXaL9qKmz9uHW5kM7HzVu@P/f@H8UAA "Brachylog – TIO Nexus")
### Explanation
```
0g Input = 0, Output = [0]
| Or
g{ }ᵃ¹⁰ Accumulate 10 times, starting with [Input]
t+₉ Take the last element, add 9
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~31~~ 27 bytes
```
seq $1 9 $(($1?99:0))|xargs
```
[Try it online!](https://tio.run/nexus/bash#@1@cWqigYqhgqaCioaFiaG9paWWgqVlTkViUXvz//38jAA "Bash – TIO Nexus")
previous
```
eval echo {$1..$(($1?99:0))..9}
```
[Answer]
# Dyalog APL, 15 bytes
```
{(×⍵)/+\⍵,10⍴9}
```
**How?**
`⍵,10⍴9` - concatenate input with 10 `9`s (`⍵ 9 9 9 9 9 9 9 9 9 9`).
`+\` - cumulative sum.
`(×⍵)/` - expand signum times - where signum gives 1 for 1-9 and 0 for 0.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhGqNw9Mf9W7V1NeOAVI6hgaPerdY1v7//6h3VdqhFQY6j3o3WwIA "APL (Dyalog Classic) – Try It Online")
### Dyalog APL, 24 bytes
```
{⍵/⍨⎕=(⍵≠0)×1+9|⍵-1}⍳100
```
Requires `⎕IO←0`.
**How?**
```
⍳100 ⍝ 0 .. 99
1+9|⍵-1 ⍝ digit sum (⍵-1 mod 9 + 1)
(⍵≠0)× ⍝ edge case for 0
⎕= ⍝ equals to the input
⍵/⍨ ⍝ compress with the range
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 48 bytes
```
{<>((()()()()()){}){(({}[()])<>[][()]({}))<>}}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/v9rGTkNDQxMGNatrNas1NKprozU0YzVt7KJjQQwgXxPIqa21sfv/3xAA "Brain-Flak – Try It Online")
I may add an explanation later.
[Answer]
# Mathematica, 25 bytes
```
If[#==0,0,Range[#,99,9]]&
```
works for 0
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
⁵²Ḷµ,³%9EµÐf
```
[Try it online!](https://tio.run/##ASAA3/9qZWxsef//4oG1wrLhuLbCtSzCsyU5RcK1w5Bm////MQ)
**How It Works**
```
⁵²Ḷµ,³%9EµÐf
⁵ - literal 10
² - square
R - lowered range: 0 to 99 inclusive.
µ µÐf - filter based on:
,³ - element and input
%9 - mod 9
E - are equal
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 18 bytes
```
╗2╤DR⌠╜-9@%Y⌡░╜;)I
```
[Try it online!](https://tio.run/##S0wuKU3Myan8///R1OlGj6YucQl61LPg0dQ5upYOqpGPehY@mjYRyLPW9Pz/3wAA "Actually – Try It Online")
Explanation:
```
╗2╤DR⌠╜-9@%Y⌡░╜;)I
╗ save input to register 0
2╤DR range(1, 100)
⌠╜-9@%Y⌡░ elements in range where function returns truthy:
╜- subtract from input
9@% mod 9
Y is equal to 0
╜;) push a copy of the input on the top and the bottom of the stack
I if input is truthy, return the filtered range, else return the input (special-cases 0)
```
[Answer]
# PHP, 41 Bytes
prints underscore separated values
```
for(;100>$a=&$argn;$a+=$a?9:ERA)echo$a._;
```
`ERA` is the shortest constant in PHP with the value `131116`. You can replace it with the boring alternative `100` or end the program with `die`
[Online Version](http://sandbox.onlinephpfunctions.com/code/d0d7142b549fbc396e867eba18a644213aa17928)
[Answer]
# [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~54~~ 52 bytes
```
{<>((((()()())){}{})()){({}<(({})<>({}))><>[()])}}<>
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v@/2sZOAwQ0QVBTs7q2uhbEqNaorrXRABKaQHkgqWlnYxetoRmrWVtrY/f//38TAA "Brain-Flak (BrainHack) – Try It Online")
My first foray with Brain-Flak, and I think I've done pretty well. Anyone with more experience have advice?
### How It Works:
```
{ Don't do anything if input is 0
<>((((()()())){}{})()) Switch to other stack and add 9 and 10
10 is the counter, 9 is to add to the current num
{ While counter
(
{} Pop the counter
<(({})<>({}))> Get a copy of the 9, switch to the other stack and add it to a copy of the top of it. Use <...> to make it return 0
<>[()] Switch to the other stack and decrement the counter
)
}
}<> Switch to the stack with the values on it
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ȷ2ḶDS$ÐL⁼¥Ðf
```
[Try it online!](https://tio.run/##AR8A4P9qZWxsef//yLcy4bi2RFMkw5BM4oG8wqXDkGb///85 "Jelly – Try It Online")
[Answer]
# PHP, 35
```
print_r(range($argn,!!$argn*99,9));
```
Creates the range `[$argn, 100)` with a step of `9` as array and prints it. If the input is `0` it creates the range `[0,0]` => `array(0)`.
[Answer]
# Python, ~~48~~ 51 bytes
*3 bytes saved thanks to @WheatWizard*
```
lambda n:[x for x in range(100)if~-n==~-x%9or x==n]
```
[Answer]
# [R](https://www.r-project.org/), 23 bytes
```
pryr::f(x+0:(10*!!x)*9)
```
[Try it online!](https://tio.run/##K/qfZqP7P600L7kkMz9Po0KzQtvASsPQQEtRsUJTy/J/moaBJleahiGIMAIRxiDCBESYgggzEGEOIixAhKXmfwA "R – Try It Online")
The TIO link uses `function(x)` instead of `pryr::f`, since TIO doesn't have the `pryr` package installed.
[Answer]
## Pyke, 6 bytes (old version)
[Working commit](https://github.com/muddyfish/PYKE/tree/d8ecd04b7b643e54f5d31de3fb962213a1f3f2b1)
```
TXU#sq
```
Explanation:
```
TX - 10**2
U - range(^)
# - filter(^)
s - digital_root(^)
q - ^==input
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes
```
->a{[*a.step(99,9)]*a|[]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6xOlorUa@4JLVAw9JSx1IzViuxJjq29r@GgZ6epaZebmJBdU1FDVeBQnSFjkJadEVsLFftf0MA "Ruby – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 55 bytes
`f()` need not actually be called with any argument; the `n` is just there instead of outside the function to save a byte.
```
f(n){for(scanf("%d",&n);n&&n<100;n+=9)printf("%d ",n);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOi2/SKM4OTEvTUNJNUVJRy1P0zpPTS3PxtDAwDpP29ZSs6AoM68ELKugpAOUrf0P5CvkJmbmaWhyVXNxpmloWnPV/jcHAA "C (gcc) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~14~~ 11 bytes
```
I∧N⁺Iθ×⁹…¹¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzEvRcMzr6C0xK80Nym1SENTRyEgp7QYIlkI5IVk5qYWa1jqKAQl5qWnahgaakKA9f//hv91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved ~~2 bytes by not printing anything for zero input and 1 byte by using vectorising operations~~ 3 bytes thanks to @ASCII-only. Explanation:
```
¹¹ Literal 11
… Range
⁹ Literal 9
× Vector multiply
θ (First) input
I Cast to number
⁺ Vector add
N Input digit as a number
∧ Logical AND
I Cast to string
Implicitly print on separate lines
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 11 bytes
```
?56+ř⁻9*+:;
```
[Try it online!](https://tio.run/##K6gs@f/f3tRM@@jMR427LbW0raz//7cAAA "Pyt – Try It Online")
```
? implicit input; if input is truthy:
56+ push 11
ř⁻ řangify; decrement
9* multiply by 9
+ add input
:; otherwise, do nothing; implicit print
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `H`, 6 bytes
```
ʁ'∑∑?=
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJIIiwiIiwiyoEn4oiR4oiRPz0iLCIiLCIxIl0=)
Port of kalsowerus's 05AB1E answer.
A port of Kip the Malamute's Pyt answer would be **8 bytes**:
```
:[11ʁ9*+
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI6WzExyoE5KisiLCIiLCI1Il0=)
#### Explanation
```
ʁ'∑∑?= # H flag pushes 100
ʁ' # Filter range(100) by:
∑∑ # Digit sum twice
?= # Equals the input
```
```
:[11ʁ9*+ # Implicit input
: # Duplicate
[ # If input is not 0:
11ʁ # Push range(11)
9* # Multiply by 9
+ # Add to input
# (Otherwise, do nothing)
```
[Answer]
# [Julia 0.6](http://julialang.org/), 18 bytes
I use a ternary to catch the `0` case, and a range `n:9:99` to create the numbers. In julia a range is an `AbstractVector` and can be used in place of an actual `Vector` of numbers in most cases, but it will just print as `1:9:91` which doesn't satisfy the challenge, so I wrap it in `[_;]` to collect the contents into a `Vector`.
```
n->n>0?[n:9:99;]:0
```
[Try it online!](https://tio.run/##yyrNyUw0@5@mYKuQlJqemfc/T9cuz87APjrPytLK0tI61srgf2peCldafpFCJlCRgZUlF6dDcUZ@uUKmTppGpiYXUPY/AA "Julia 0.6 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 25 + 1 (`-n`) = 26 bytes
```
say;!$_||($_+=9)>99||redo
```
[Try it online!](https://tio.run/##K0gtyjH9/784sdJaUSW@pkZDJV7b1lLTztKypqYoNSX//3@jf/kFJZn5ecX/dX1N9QwMDf7r5gEA "Perl 5 – Try It Online")
[Answer]
**Clojure, 33 bytes**
```
(fn[n](if(> n 0)(range n 100 9)))
```
[Answer]
# [Clojure](https://clojure.org/), 38 bytes
```
(defn f[n](if(pos? n)(range n 100 9)))
```
or as anonymous function which is 29 bytes
```
(#(if(pos? %)(range % 100 9))n)
```
[Try it online!](https://tio.run/##S87JzyotSv3/XyMlNS1PIS06L1ZBIzNNoyC/2F4hT1OjKDEvPVUhT8HSUsFSU1Pzv0ZBUZ5GmoIpkAkA "Clojure – Try It Online")
thanks @steadybox
] |
[Question]
[
Given two strings: a string `s` and an alphabet `a`, implement [string projection](https://en.wikipedia.org/wiki/String_operations#String_projection) in the **shortest code** possible.
String projection returns a string `o` that contains the characters in `s` that are in `a`. The order of the characters in `o` must match the order of characters in `s`. So if `s = "abcd"` and `a = "12da34"`, `o = "ad"`, since only `"ad"` is shared between `s` and `a`.
You will need to handle when `a` is empty (outputs empty string, since no character in `s` can match empty string).
## Test Cases
```
"string", "alphabet" => "output"
-------------------------------
"abcd", "12da34" => "ad"
"hello, world!", "aeiou" => "eoo"
"hello, world!", "abcdefghijklmnopqrstuvwxyz" => "helloworld"
"Hello, World!", "abcdefghijklmnopqrstuvwxyz" => "elloorld" (case sensitivity)
"Hello, World!", "abcdef" => "ed"
"Hello, World!", "!,. \n\t" => ", !" (newline, tab)
"172843905", "abc123" => "123"
"fizzbuzz", "" => ""
"fizzbuzz", "fizzbuzz" => "fizzbuzz"
"", "fizzbuzz" => ""
"fizzbuzz", "zzzzz" => "zzzz"
"", "" => "" (two empty strings)
```
## Winning Criteria
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
[Answer]
# [Rust](https://www.rust-lang.org), 20 bytes
```
str::matches::<&[_]>
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jZLPTsIwHMcTj3uK33YgW1KH_DHiBC5evJvoAcjSdp2bjlXWTmSEJ_HCQd_Al9EH8SxbF2QBhF76a36f76e_Jn17T1Ihl98n134MYxzGpjXXNJ8nYGJEELUgjGGgQblMAxPqGQiMRtPDrbYBCMDAnmGhDSZgUcQRTHkSeXoOYxbyVLGM80Pw6gbmPwTh41M0jvnzJBEyfZm-zjJlKAIFXhXdKNH90aKcP1pTRg7BOrJhGA-lwhHoVb5x0ey0W5dn56W40WwpMi8qpB9mGUmzLAcVsr-_rgtufarw29x-X5YvBRXVlqgqGME8YhL83kcq_dPOp5CJ44yxpAETjtOtDdxRX7W-fq7WpnodC8ES6bKJblKbzCQTpmVTHkWMylXujtGu2--bFgJ_9RmhRv6DLGufuoyTTSKfl7g0wImAHhC7qHaL_0I7pLVSspm8lUkYP-QjqehCW6jXL5dq_wU)
This mixes up *three* I/O methods for strings: the first parameter is a plain string slice `&str`, the second is a slice of chars `&[char]`, and the output is an iterator yielding single-char string slices `impl Iterator<Item=&str>`.
[Doc for `str::matches`.](https://doc.rust-lang.org/std/primitive.str.html#method.matches) It can take several kinds of patterns (i.e. anything that implements `Pattern`) for non-overlapping substring search:
* single `char`: matches that char
* a `&str` or equivalent: matches that exact string
* a slice of chars `&[char]` or equivalent: matches any char out of the ones listed
* (and any 3rd party type that implements `Pattern`, e.g. `Regex`)
We use the third variety in this challenge, which is indicated by the `::<&[_]>` part. `_` is a kind of wildcard type, and it resolves to `char` by the compiler because `&[char]` is the only type matching `&[_]` that implements `Pattern`.
[Answer]
# Regex (ECMAScript or better), 20 bytes
```
s/(.)(?!.*␀.*\1)//sg
```
[Try it online!](https://tio.run/##pVHdbtMwFOa6T3EaodluU7dpi2CEbNoFEkMCJHaxiyZoaey0Lq6T2U67ZSuXPACPyIsUpxtlmnqHLyyf8/348/EiXaUm06K0PVUwvq2jQaijC6uFmlGdrq@2po8pwadt2nlBO3FA@n0z215RI0XGceD3AhKCyAHrySBpR8ggAnauizWgT8IYZwOe8VDYYhCBngTJA5udoB8I7u@B0WVqsznuTwa947NenKS9zUtMOl367uT0W9Ine7tztUqlYMC4FEthuXamujGlppTCYvY3CJVczewc2hGM9@pLXbgoqlpOuYYi/@diUAhml23osjWGX/ns/U2Jm7C@a48S4i7i15XQHCPNUyaF4ojQzJ0tP1fOJE/dMO6EKiv7ttRFxo2hxjKhNoQWCqOdwpfRyV0NR0fwhFJUlq61C4JRrJB7Qh0FYQt2L5FupFGEPDfSgwoJXfDg989fbu/Cx4svnx3e/JzIbzHe1WWqjbOeoK7sosSFXhTC5YkHiBCqeSmb4NoHQwgJN2TrpdOMeT54wZClo7HX8uZcysKHdaElazdIykVRHQSclOezuVh8l0tVlNfa2Gq1vrmtHfvDA/vyv9iHkLZPIVaxdVjwevhmPDoevHpUBMOR6@airqdVXTfNZ@X@3PKelU9ZdbMeKd4f "JavaScript (Node.js) – Try It Online") - ECMAScript 2018
[Try it online!](https://tio.run/##pY7PTsJAEMY99ymGTZO2pC5d/kRlRTx4MB704MEDbZpCt1Bc2tI/oiW9@gA@oi@C0wBKCDf3sjPf7/tmJhGp7G2KTMDD89Mjh7q683Kv378rFolIuRLEqa6GA4tf33D8mbGGMEDFWCdpGOVA7IjwClQJA8iKcZaj3TXPmckMsawhDA90C4kBfVBdrgAOAn3PJLI6ohHNWKseTvPFJPaFO8/iCLSRRlVJNUfjsN2LAQ2@P78AFdVF@y2mqpHlUGJbhG475vBN1tKpoQ8btHlGmzYzWq1sutlP2W0X0d@qkeo6JjAT8FJeVRvijSc@MYGwtu91ukQhMyFlbMIqTqXfqIknwrg4CTAqguksnL/KRRQnyzTLi7fV@0eJ7vut@@Vf7lOkYVKwIztHxi7al93OldXbJVi7g2oQluW4KMtaPGp/a4UctYeusn47C/kB "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##tVfrdtpIEt7fPEVbs8dIILDByYwHWcnBWIk9g8GHyyYe4@gI0YKOhaTRZZwQ@@8@wD7iPsh6q1stIYSwM7Nn9QP6Ul9VdXV19dem59Xmpvn0wwxbxMHoqjPQmnqnf6bp497FSP9wcTY6R8elH4hj2tEMoxPP9HGzvnhTMl0nCJG5MHykeze3SEUD4fT@/m56FF1//fpxtPjxfiE@BQdiXRLf7tUrf6tXJg3p4CCYP0l5OUFBGXUVT9W9akNBAVlhPUSerdKWa4m6Jx3wZgXatSMl41kQzohLPcsO@cSZb44RF0axsdyWe1MiDliDZqhj33d9MevUEgeBMcfSN7DTapkggE5OEB@lTTaOnZmtIB@Hke@ghvK4pZL2TXeGJfSthOBjyrmWm@brH28VNkwsJLJQ63PMoTqXEilcRmK8V@POeXtwXJH4pIx4fBJ30UEykpGXJIlZod/GcgQmhJi9FhJ2rpCh01WWHktsGTNsk6V6qKCp69qIOL7hUHfplCOzPyP@m0rfODiCeBzroejUDAmdqGl/Cn2Inhf6M2JZkASQnjOdGdjYlUBOsmTfTkJquT4S@SgBdxREqtVkMgkuQW9UBBDuR62hpNPYDjCTCW7IraqWJ5MyoOlAtboNe9yFY86mkiTW/1iKU2JpEEdMfGKbbZ@8enioeHtqOSinqGzmCJckCCBN0UQIJoIgKfE6eJTj2FeqVU9@dSy/PpYeHjamHo6a8s8/yY3ma5iBfDcXoPHvolSp1k/evP0kyLG7xZYvnD8Mm8ziDSYh9ql1MKXA2aypTfhL94nnhg31ILNlnuzZ3GH75LDYyAffhcU50XKKfeRaa2MBtWZEoYt8laVgfFxBKdXpVVWbFgvqCW38H80H32E@lrRyktQ8c4zm91ET4uSqh5C6LvgZn8vh@HQ4uhiNR5qufRxpvTPtDD1sz417Q22ka5dXo2slSXaRmdw3W8jieWrms@9PrDS4J6G5AB1phTIgrcvzcou6@1Dg7/tu/7TdVUB0CoX1Tsmg2oBCGVS71znvD7QzBWW@LZSWR3W7/Q/xovVOtz0crm2hgwNkRkHoLlENGbbt3iO4iwxnhm4@3SKb3GGkdS7bQ9MnXpgx8XHLxEg/HY4/Fji2YQI7xtTGaBKhyZiZgfibeIaatRmZkxBNvmSMdAqMdC4GnfHlu66WmCowQhx0sERLVuY/TX4DbQ4UDNiVjG6S091pD7WuFodmd2TPcqizfrfbHuiQbv1e91rZgQq2UCPYkg1LBahf8qjxVa99qb3g4ZccKjkMz6N6OdRle9Q554fltN35daC9U4oi3bvqvA@QYYbPpMoyr3vcHV10L3qa8pxHTg7V6@vt8agP@3Q1Gg84dgsV5VDjzlVaBcajdztQ4zyq936gaWfXu2IGZM@I7LCVu/u1@NZPir1lG/SuYSTAZAK8U0h04mswpiyUoKCKjxXeZ7kLo06Iv4TApLJdqMpwHfo4AIfkmHgoSYm5@E1jI5YVYJh0o9DGzjxcKCjDZSp0fBpZCSeBipp4sfSIjUVOfIZXo4Hk100dirIoycivU4pAW66M9plh/s/NHUprKrbn48Jayn653OYq1aK16zBkhFg8pHV2fUFACLwoVNbkhYZkRYkUEwIGaAM5F@PdIo4cy4OOldrI85qVhGCOkiOxPHHKkrLJeijw5pCyGqGchaZMkHtkut5XkZvZEEr9A2Ylf1Yb8h1lWHlViT2q5uZzsbms3B1MUtk69iGjRSJnnWm1HM8NpOQAPxZqYZaA590CXzssK@hObSiFgvcLmhRMvFplrqEy4waJs8DA5BcYGAgI0l9XL7ykfiJQ/ehztbpt5DHmmbtjuY55TFwLBbPC/CBQ@g0uF7vWc8MFdc2wgCcgqnlXAFgmJRwiduU5J9bVMt5B@pCkiatkC9ZuoJ8D@t8LDHPA8GVgWjYzQL7CF7HFScv3cltd8eZCOuzIidLuXlo1uXq@25VmtVFwslN@StQtntf/hzZ4R5lYV@u9H50Xn/q4GIOt7HuzIsF76y1USCBopph6JKEWJFs6CLhMkZcK8iu@JtLaGkTTICRhBBXVX7@IWaFnK01rfWbdUNehfqIqkFnW3KjPmzqCtYJgfVlwP/fXjiqFpY/7Cs9FeHDsyI74Ibq/nyxsL2U9g0F/AJzhUrvsD64Lj2QM2WF8jyQ22Qv4mfSILxVYDL3ZWcFnVz369z//RS//ghTJXM5UNyInmYuZvbST48/eJaYahwwSPJ8v8Umc0MNvgeFAFCYTR2C132X3W0HYOMbPYvzvw4RZTPgCJj3syW26XkWh/GZULR9jjkiu@iTGUP3XyMfS@reILzA9G0OSkiFZ8Txwk5SJwV4/PgnG1JzB@oRGc2YcvRJKwgLDIZPRvevbsz06Y2DiRoUTAMXWfEE@39lLx/V@94Mw@uP@y9cVSJ/H0h/@J@mimT25jiYObEpJaPzUPH519PPha45oNI9g1CKr1TRarehgrpu2S0Kum5Va0Y@LCP8xKbkNnmo2i2Xt@L8 "C++ (gcc) – Try It Online") - PCRE2
[Try it online!](https://tio.run/##tVbdbqtGEO41T7GhVQwGO/5JenKMyZEqVWov2ou20mkVpwjDYm@8ZikLx7Fj97IP0EfsgzSd3QUb2/g4p1WRZVhm5ptvZ2ZnCJKkNQmCl89JHNA8xGg4ZoxnVyme4Kf2NEnutIDFPEPB1E@Rl9w/IBf9oH@1WMzG/fyX5fLnn6ZfLqbGC78y2qbx7qLd/KzdHHXNqys@eTEP9XQHVeCaieslVtdBnKywl6GEuuKJRYaXmFfFYxOeW31H2zEkQDDF/vxOIzEYpfDv4TRlqVHFnmPO/Qk2n3kWDgYBKKDhEBVvxaN8j@OQOijFWZ7GqOtskIDkyzjznwpM87mQVh3pP0oVJFe66Ww06TTElMzdjoMgiBSgUj@eYEOKYlvefHUbb1FzAL31MiNu@SYautv1GNYAm2RpSKIIghOROPSkg71tcruM3iU10bOG4IpYioziLQE6DiKWVQrFRSJkEHTnIjApeLS6zlaMKcdSh9@TB9dtjEYNsBYvLOvYbHPKTpLdahKFv9E2Mm1zn8RGyUnYJHR4vV43kwu3wRtbq72gf0c4J/EEjXQ@0iHqah9FlFXsm5aV2Ne39s2tuV7vidb9nv32jd3t3YAECiiYAuIXhtm02sO7d7/qtqJb7/nb@INPSagSTDIsco7AlQM123J7cNvmiap9UjgnlZQldkILwnTYqXfyPmWwuTifj3GKWLRzxoU3P88YSl1ZtUAf4gCgAjOxXCoOkWAiHv5H9/wV7pVmdKAp3Etior77PYgTA4ay1wwGstkMBjHz5iz05mhdL@Ali4oplPrcz7yIpDzzWEyXO@NC5NMiI7A2pP1lMEBRUdDBYZl@Qkj4gmTBFDDKMg58qP8GaQwQ7G7tqkOxvxUidBx08hpDY5s5FTSu0GDHQBz9Xh@Yo4gV4TpCe/oYN2H09Cnc5grtUqHVc5s7r0WbABo/QjtKsHMOLcSRn9NsgPYav/61SOkAlSc5or5oJLqQBVKhWNSOBdXjVN@tbhNUjNRGTFTDrt6h8yd55ux6sWh4KzEXpNIEZ5TE2FD8SGwrfcBYud2jNi1E9x3RhvVGVSiuqs@AJUujANpT2jKAUWA/ul17JkbCIVTpT8DcP9a7q@rNQCh02ziF7BnErpKB7CeMm2UBbmpRpCcYTA8wYDoNB83crlOruJgSihUxy5LUUEM2s5IsjAz7zMgABd389/D6OfiRLvDRo2UdO9mowXg6lruYq0mrnTqBpXJbDHdDfi8A5Xpq37NsKqj5EfQrJJBPBUBWUtnLFJWPkVCnNYbTqjIovggbo7ix125OG6YHhulrDbMDw@y84bYVVAyLHZ61rS/aIpfHcPXJhXI4URPa6VX1VLM8O5iTXooT6geqYm1IPZw8@LGD5IpSWZkI2oH4TjREgsomFQhQ6HSyWcjWh/7640/RDGsax3ZigpH5XNQJjLz9@lAZGomiiACUG/poFOuyJzDZ2WqCXdikVZv0dTZZ1SY7Y7MtgjIWQb3epiYLZaigAeyUN9ruvzh5HUfbvOj@OAiBjN7thX7/Wtf0KaaU2WjBUhpeCImPCctrBWCKo8mUPM7oPGbJbzDu8g@Lp@UKtL9R2u//k3ad5MJuo1EMEdT07pve7XX/beemsOj2@vA2IqvVOF@txMuD5fZZ0w@WVa2VuAoV/e9ATF3@0qKyoD1Zz/8A "C++ (gcc) – Try It Online") - Boost
[Try it online!](https://tio.run/##pVLdTtswGN11nsK1JtkumWn6M6AsQ2yrtkoFJMrGRRKktHGKmWNndgI0jNs9wB5xL9I5aTU21Lvlyt855/tyvp98WVwr2VvxLFe6AGZpXM3cG6PkIdC@hhCuzC6mBB@1aPsFbYce2d01i5UlAm/4yosaGaNZXMyvMbqibcuEEgehCadR@4iE0gLIVTmTGNK5ShgtuIKEahYnmJDAixyeAh10opaPDBoCHXPDwHQpi/h@pLXSGJ1wY7hcAGggIk7i602W0glOCOASGFbQUnIlsX1hHcsFw/19d7BPiPuEHOy5XnfwD/R64B70LPLQzuIc24IufIlJe4e@eXt0Bckj2WpoLG9jwROQMMEzXjBtbWngA01NLnhhTdX2hO1Zk5bf31rjUivbkiyzGdNApU@1jC2Winhh/M4hmKtSFr7npEqDtO5UB71o6ABbPvV9tLADW0s6DmDCsCFoUsF3HzwgjoZ2N@OPp2fno/fH05ELUNZAJ58nF@PJ@LRGTIN8OLs4nkxseN@EX0bn786mo8cgjRxj591dLzqoF17Zf9V2RDP4paGmSLi0nsCmZ0FALBMggnVgr8Q6DaW1KnwRdOqz2SLu1CqI6joNWQ1BrrksMGmQyvcON4CwNn/9@AmQC5hM/PpaaVJmucGBtW7KmR27C4xVhR1EbxSXuNEIFScGowDtiB0UIbv19ezc9cyItRCR9VmTFYxn8wS6AHrdJO71oQOvmRDKBXdKi6RVMzHjqtxK2FSWLq75zVeRSZV/06Yob@/ul5VVf1qrL/9LvY1puRSEMiws5@119/u9g85gk@F1exZNeVXNyqqqwWfhn7cDn4V/q6r620jgbw "Python 3 – Try It Online") - Python
[Try it online!](https://tio.run/##pZHfbtowFMZ3zVMcvElOSgj/Om0tSyu0oo2ppRPt1EkhQ4Y4wZ1xUjspkNJe7gH2iHsR5gBlG@JuuUl8/DvfOfk@mQ7nS0nvUiYp4FsVCdwECQ6cta5btqTEL2HQJRaAdKte0cEqBwhTFK7mIiGztpSRtABfMKWYCAEppAkq/IKvZaRb81bd/gl@wrBYgO88Vdxq@ahV7nuk/PjKMA9K9ruT029eZb9wR9wTznzwKWcTllC5kc@3lLaKOUsM31yvaHMqwmQMRQcO96vdyEgvKdLJkEqIgj@qaiMbaNlqE0Kl3@UTZcUPylbp0Igt6dY981HLug3PpmQ0HozGRMIDLEYLGBE9alQAmI6pAO3Z9pNp4QAWDvRoSGfx8XHnQ/ey137fumpvmdku0/563e6etc@2xGSXuPhyft0573TbAC9BkQkFouAzlRwr0CFBwEkIRk/nqwt5wNpFKpL8n5@pCQamgPApmSuIhLkdFuIdA8J/HdA@PRZ68LyMLeh0lbQV5EvmbYYyH0LlKgt6nm7IHG3pdMw4Be6ENFF6lM4rK@p6nCaqqRWbmVNbpcjdcs1zHNQXqKlx7lZtu1z31vHAmqhqAKPcZIB80U9Xl107JlJRA7u4xEvYw6Z9GzFhoH4VmSswlkwbwC0Ev378BGStmkIqqCQJNQJXeeZqyHrSYKATGAyWqmLYpnFatA9e2Af9mlmpTMLlEpHhyEcWoFrdJ41DVEBjynlkwTSS3C/mN4SyKN17oVtpEI7Z7Xc@EVF8J1WS3k9n80zTH9f0zX/R@26Klg190U/0Xe1N/e1h46j6etNRqzd0NWBZNkyzLC/uHLffBbRz/JvK8meDoN8 "Ruby – Try It Online") - Ruby
[Try it online!](https://tio.run/##pZLfbpswFMZ7nadwLUtABzQknbY2Y20VtVonVZrUSb1I2ESDAXeOTW0TMhi73APsEfci2aHJ0j/q3XyBOOf7naPvHLuQFVU6p5yviApPrJXet33HPt7193b8vWng7O/rbGWdjFhqEzXpR56gWGOnMbmSFbIumdZMZAhyVkuSEJgguocTLzP4J/aksieKZnQZWZO@d3jqTaPYa4nt7L3y370//hJZjn8Zm1lONRQ5284XYhFzlqCEcjZnhiror6C/f1VwZjp07cnnVGQmB1/oYFt8rSSYEuX8hiok04cm2mp7RHc2B9EIkSwM4JuGeCznBeM0wSM0meWxmkQRMMPox7lUZ/Esb3TFwKNNvjpND8GxMgs1JEMh8oJ2nWFdJoUMJk3auheZkIqOY03xBpg/BS5LbhhnYqvrp/oVLJbTx4B4CpwtYRUzZsZxYUq1pZYv@fgUGxhfXOewBV3Es45uYRcq3NzO0ZGglX1/fy5JnR6pw/4ohcq4G5sjJhBhoiiN03R7591boHcWttZx7TSVgt5eLrVpoTgYPcTIExK6d6OAKY7@/PqNiD2WYkGV@Sy9j1pCd@UrWnCwZv@TzpWcr0U8ITzCjncrwQfewS7RLskcB7ftCsc3swS7CAeDJB4e4B7u3rN0USUVT3Y7JaZMli8KUErTLGe33/hcyOJOaVMuquX3GugPa/r6v@iXlF3XR1MxNaAFbwZvD4aH/debimAwhGzK6vqmrOsu@Szc/vfws/AxVXdng@C/ "PowerShell – Try It Online") - .NET
This is a single regex substitution, to be applied once. Input is taken in the form of the two strings delimited by NUL (ASCII 0).
Above and below, `␀` represents what is actually a raw NUL character in the regex.
```
s/ # Begin substitution - match the following:
(.) # \1 = one character
(?! # Negative lookahead - match if the following can't match:
.* # Skip over as many characters as possible, minimum zero, to make
# the following match:
␀ # Skip over the NUL delimiter
.* # Skip over as many characters as possible, minimum zero, to make
# the following match:
\1 # Match the character we captured in \1
)
/ # Substitution - replace with the following:
# Empty string
/ # Flags:
s # single line - "." will match anything, including newline
g # global - find and replace all matches, going from left to right
```
This automatically erases the NUL and everything following it, because NUL and all characters following it are themselves not followed by NUL, so the negative lookahead matches for each of them.
(More test harnesses to come.)
As far as ECMAScript goes, this requires ECMAScript 2018 (aka ES9) due to the use of the `s` flag.
In Ruby, the `m` flag is used, which is the Ruby equivalent of what is `s` in most other regex engines.
## \$\large\textit{Anonymous functions}\$
# [Perl](https://www.perl.org/), 42 bytes
```
sub{$_=join'␀',@_;s/(.)(?!.*␀.*\1)//sg;$_}
```
[Try it online!](https://tio.run/##pY7NTsJAFIVZ8xSXySRtyVAoP1EZCyxYGBe6cOECSFPoFAbbGeiPSEm3PoCP6IvgVFAJYeds5t77nXPuXbEo6OzTmEGcRHyWUCjqjRsJLubxobt/enw4VEM3cbvdYRquWEQh3AL27X2cTnfYsZeSC62kkYFD47puGnq/YlZLZnVsGfV6PKfYyffUl5EebjG3G/S2R9VvGTvgvo65sVtFXCSAxgLR/Ds7ABtUuDpMxw6pWcQy2Lrg0D@ZNxQxoAvYoWVQWaD/sECxwqIhzdhhV6V5bCY95ixjKUAbaSYOTG2iUTiuVhs/3z8AkWMCE3/yEfZrPX2AXWNCwCKgltI83yN3OvMQAWQ1PbfVRmW0YEEgCWxkFHiVgriMy/QiUFbmzxd8@RKEQq7WUZykr5u3babUdwf187/Ul0iFmDAW40Qx66p53W7dNDpHh9VsqanPs2yaZlkxPGt/6zI6a09VWfGOEvQF "Perl 5 – Try It Online")
Takes the two strings as arguments.
Beaten by a **35 byte** solution based on an unposted solution by [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus): [Try it online!](https://tio.run/##pY3LToNAFIZd9ylOJ5MAyfRCL/EyUt2YGBca48JFqYSWoaVOGTpAayFsfQAf0RfBIaI2TXfO5sw533@JmOTDMo0Z3D093FPAvlXG6TTHjhWJiMad8Yv9iHNbLYV9czLpdOYUO0VJfSH11Q4HVpdejqiappFD4Os4MPJIBmECyA4RLWC1A8zBApUaJ1LHDmmZxDTYuuJwtXfvKmLABWCHNkBlgf7DuGKVRUOakWNXpXlsJjzmLGMRgjbW2pi3tYlGoa5WjZ/vH4BIncDCP/kY@62RLtmGyZjp19g1jAkBk4Bqp0VRInc68xABZPY8tz9ADbRgnAsCWyG516yIywKRHgXKyvz5Ili@8lUoorWMk3SzfdtlSn37rX7@l/oYaZI22KGdKGae9s4G/fPusHaYvb66@kGWTdMsq44H6@@/gQ7WfVVWvVqCvgA "Perl 5 – Try It Online")
# [Ruby](https://www.ruby-lang.org/), ~~42~~ 41 bytes
*-1 byte [thanks to Steffan](https://codegolf.stackexchange.com/questions/250861/add-parentheses-to-polish-notation/250875#comment559054_250875)*
```
->s,a{(s+?␀+a).gsub /(.)(?!.*␀.*\1)/m,''}
```
[Try it online!](https://tio.run/##pY3BUoMwFEW77lc8sgmUNC20jjoMduu40IULF8CCSqDUFGgC1sZx6wf4if4IBtpxnE53vkXm3XvPfRHNct@mfju@kSR@N6W9GNixRTPZLGFiUstcGHQ0oKPQsSYbgvFHK9i2yQUDvJZlgT1Q/tSD3SrnDLifsVoOAfIUlKH9qqmlx4rEU77jdS4Pxk7k@ygskKdxHkwpHbuRBxo69LSlAYywlgASfLh7fLinVSwkM3GAbW7jCFt9Wom8qIETBN@fX4BIT2asYCKumZkGUt8iMnCiyOp/6J8WxcvnBBFAjpvEszkaohXjvCSwKwVPjC6JWV42ZwNdZWm2ytcvfFOU1VbIunndve2Vpm8P9NO/6HOJQSiERVjrzLl0r@az6@nFseG4M@2muVLLRqnOPJG/@xCdyL@U6uaIoB8 "Ruby – Try It Online")
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 42 bytes
```
$args-join'␀'-creplace'(?s)(.)(?!.*␀.*\1)'
```
[Try it online!](https://tio.run/##pY/RTsIwFIa55inKSeNWwhYGGDUL4cLEGK9NvAAuyuhYsbSj25iW7NYH8BF9kdmFRQ3hznPRnP//vz8nTVXJdJYwIWocT481pnqTeVvFpdNxvEizVNCIOe4sI65P3FnP73f8/iIgTl2F2EyHYaw0o1HiYoG4RJjLtMjJkcfWmA@XHts74Jy0IcdS85x5icryypaDENPpvZIHpvMHrXbeU6YkgjkWSwjRL4s8qSQrBZcMgb3z9fGJsNsWn1Vbw@4VjhGm9mrzBksCBKqqBrqK1jBAEIzWdDyBLjTfVQNUKi3WvSahjKviYmCrLN4kfPsqdlKle53lxaF8ezeWfjzRL/@iLyW9gY8WcpHbLLgZ3U7Gd8PrthGMxtaNuTGrwpjGPJM/exfO5F/KNNMi8A0 "PowerShell – Try It Online")
Takes the two strings as arguments.
# JavaScript (ES9), 43 bytes
```
a=>a.join`␀`.replace(/(.)(?!.*␀.*\1)/sg,'')
```
[Try it online!](https://tio.run/##pYzNUsIwFIVZ8xQhC9JADRRw/OkUt@pCFy5cUGYIbQrBmJQ0BQnD1gfwEX0RDMg4DMPOu7hzzznfuTO6oEWieW4upErZ1kbtMIu2NOpTMlNcjiojolkuaMK8lkewd1cjjQppxAFuFRMfIbwNNZuXXDMPaUZTwSVDmCTuNuxBGqazXXfNZV6a21yrhBUFKUzK5QYTJT20b/gi6q8tqNfBEaJKQ5aaG/c6lgiHwEZBWAWAZ8ATg/YwihBE@HxDgCaA4Pvzy@0meHx5fnK55nLCs5WXeXsjp7pwvweoKZpoiLCbcIO3kI6TFPoABp2UdnuwCqdMCOWDpdIire0SyrgqzwauyrLJlM/exLtU@VwXplwsP1bW0fe/9Ou/6HNJzScglrFxWXDVue51b9qXh0bQ6To349aOS2t35on8u6vwRB5TdjcHBP4A "JavaScript (Node.js) – Try It Online")
Takes a list containing the two strings.
# Java, 52 bytes
```
s->a->(s+"␀"+a).replaceAll("(?s)(.)(?!.*␀.*\\1)","")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pZLPctMwEMYLxzzFRgOJ5Dqa_ClDwSSZHuhwAC45cKjLjOLIiYoiG0lOGlOuPAA3hksP8FDtkSdBjp3SMeGELtLq933r3ZW__7hgK3Z9800s00RbKCKaWSFpnKnIikRRL4C_oBc0IsmMgTdMKPjUAEizqRQRGMus21aJmMHSMTyxWqj52TkwPTdkKwU4rXK_KKlfj8ttNIIYhj8zG3eOb45MZ8Q6I2wO0QE6ZIRqnkoW8RMpMcJjQzAleNyk3gH1wrBHkI8QKb23D1vBNEkkZwryYcyk4QFMIqYU1yBUmlkYguLr3R2ebIzlSyoUCWC9EJID3srogpm3_NJismukLBSkS1AqlMOvheLYWUUMWFLJ1dwuMBl1odUCSaMF0ycWd8lw2EbtXaK7VNqlQiHCePw8dItenb0P0TnxSIjA88Hbj1Cw8xvnl7vhnAptLNY-oEc9RKjVTBnJLH9pIpZyUxRZ2dg_bP39tqpmEeOcVNNKXPdrLSzH7VC1SZAPrc6KQf_BqfuUjTF6bODXl68QuoMr3QfpQ0xZmsoNNqQ61F84RFdF08W7Fvu2n_uCUFVE1YGtgK0DXQGNCAk-u1X-Lte3D5qITaOZqwz1-jM2OEINtOBSJj6sEy1nzYIwLpJsL3BWHs8X4uKDXKok_eiGma3Wl5vcqV-V6nf_pd5Hmj6FULkmG6j3tH98NHjWfVI5ev2Bu41Fnk-zPC8ua-HduYFq4X1VXqxKgspR_QY "Java - Attempt This Online")
## \$\large\textit{Full programs}\$
# [Perl](https://www.perl.org/), 37 bytes
```
$_=join'',<>;s/(.)(?!.*␀.*\1)//sg;say
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jYrPzNPXV3Hxs66WF9DT1PDXlFPi0FPK8ZQU1@/ON26OLHy/3@P1JycfB2F8PyinBRFBkUdPQUuzn/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online")
Takes multiline input (terminated by EOF) using NUL as a delimiter between the two strings.
Beaten by a **19 byte** solution based on an unposted solution by [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus): [Try it online!](https://tio.run/##K0gtyjH9/79YPzouJlClOsbGrjbGlSFWXz/9/3@P1JycfB2F8PyinBRFBkUdPQUuzn/5BSWZ@XnF/3ULDAA "Perl 5 – Try It Online") (they should really post it), or 25 bytes to insert `chomp;` at the beginning if being picky about the output being followed by a NUL.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 [byte](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
f
```
**[Try it online!](https://tio.run/##y0rNyan8/z/t/@Hl@o@a1kT@/x8drZSYlJyipKOgZGiUkmhsohTLpROtlAFUmK@jUJ5flJOiCJJMTM3ML8UlBzQgNS09IzMrOyc3L7@gsKi4pLSsvKKyCqLBA6IhnFINOCQVdfQUYvJiSiDShuZGFibGlgamUH2GRsYQibTMqqqk0qoqkDimCJwNlsEUQVZbBQIIhUBWLAA "Jelly – Try It Online")**
This is exactly what Jelly's "filter-keep" dyadic atom does - takes a list on the left and a list on the right and keeps those in the left that appear in the right.
[Answer]
# [Haskell](https://www.haskell.org/), 16 bytes
```
filter.flip elem
```
[Try it online!](https://tio.run/##rY6xTsMwFEX3fsWthVCiphFpioChTAwMbAwMhMFN7MbUiU3sEPDHExxaNSBVnbBk6fnce55cUrNlUvai0qqxuKOWxg/C2AlfZT0X0rIm5lJoMMmqvqKixmoC6NY@2gYx2lqKmhmcoaIaQRaYyIaY38KUqoPBbAaCc3/98IPsDvnGyALusQlDPPvVQEDoOi9IBJIsCpouSRjteem/qiJ0qpHFdChQJlR7KveLGN@U4nUrq1rpt8bY9r37@HSjdL@Tnv5DOlGYRjGyOrNjJblaXC/Tm4vLvZ8s0jHkwrl169yQHaeH@ZAep78dN5y/Agn946X/yrmkG9PPc62/AQ "Haskell – Try It Online")
Takes arguments in reverse order.
[Answer]
# [R](https://www.r-project.org), 15 bytes
```
\(s,a)s[s%in%a]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nZM9TsMwAIUHNk7hBFWyJYNIU0QYygx7EQNhcBq7NaR2iZ2G-ABcgiUgMfc-nIb8CBwVRdB4sfyk931v8etbWr6z6Uem2XGwDaHCBKk7NeJiRO7b9PPghQs9kzeaBZDBKgtm8lpo6JJoHrsIg07kjWPiT1yE0BGYXgKXxO5hT3tJk0RikMs0iZ0dDKFcZpZCpRyGqQZStljyh8dkJeT6KVU62-TPhbHspt-0exVXreJ2qKKuNwIA50RRoKhQXPMN1wUa7uzwh0138AkIRagtCAOn2ihonnBBMdAk6t3nnY-DiX9xevZ7mzf2LbJ-9DEYNybKjNlB2PK-TRt_E36SPtKfhH03mPrYevP6p7wjBVDnEtDVWhdA6ZSLhULtdyzL9v4C)
Takes input and outputs through vectors of character codes (as in linked test suite) or vectors of characters.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes
```
dᵗ∋ᵛ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFiQ/3NVZ@3DrhP8pD7dOf9TR/XDr7P//o6OVEpOSU5R0FJQMjVISjU2UYnWilTJSc3LydRTK84tyUhRBcompmfmlOKSA2lPT0jMys7JzcvPyCwqLiktKy8orKqvA6j0g6sMpVI9dTlFHT4GLEyxnaG5kYWJsaWAK1WNoZAwWT8usqkoqraoCCWMIwNkgCQwBZJVVIABXphQbCwA "Brachylog – Try It Online")
Takes a list `[s, a]`, and [generates](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) a list constituting the projection.
```
dᵗ Deduplicate a,
∋ᵛ then yield some c from a pair of elements [c, c] from s and a.
```
Deduplicating a is necessary in order to not generate multiple pairs from the same element of s.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 4 bytes
Uses set difference (^) to compute the intersection: x∩y = x-(x-y)
```
^/^\
```
[Try it online!](https://ngn.codeberg.page/k#eJyNkUsOgjAUReddRXkjTYjKx/jbgDtwQkiKUEErVQTRDly75RMkkQIdNe0997y0dOvOXQchID7gD6YTIN7Rhx0Ypk8sG6a4dyEIOK/BMGCM6zjnCfM12UCCiGeqAlTFy7CKl4ME9BRG5wu7xvx2Tx5p9sxfbyFLpVimW/S+og9j6X5OMTYCHWsKUNNn2ImdtBNF8j2tGjRW5tq2NotlZSsu1K+MoKZoJISXCSGhoU8pqCb+RzdbZUvjHJX+UUJ0+UR53Ie3fcMedc0Xxxajww==)
[Answer]
# [C (clang)](http://clang.llvm.org/) `-m32`, ~~54 53~~ 45 bytes
*-1 byte thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
*-8 bytes thanks to [@jdt](https://codegolf.stackexchange.com/users/41374/jdt)*
```
f(*s,a){for(;*s;)write(1,s,!!index(a,*s++));}
```
[Try it online!](https://tio.run/##rVJLU8IwED6TX7HUcaYtgeHl@Kji1YN3D8IhpCmNlhSTFLBM/7p1C0gZRziZS77HfpvM7PI2T5ialWXk@oYybxOl2g18E3grLa1we9TQZlOqUKxdRn3TanleUJQXUvEkCwXcGxvKtBOPCJHKkjmTyl2mMvTIhjRQARmQBk@VsWCszrgF1LcGvgEIecw0@IyCLwxnCxFifQFWGGteJ/CwLd/As8OmPHQoOL1@yAZDBwq6N2KRJCmFVaqTsFlVMCHT7GwBthLRLJZv78lcpYsPbWy2XK0/86PU0y718i@pcxVN2oGxGtsDRoKsTvSu@zfDwW33at@v1x8cuZHM82mW55V5Qj7g2j4hH6fy6vyK/NBudRUBIQ1cF3Alzqkb7IcmJx2cbKslve3sFhqHHbnO2LlMzBibIMAb2iNESOvQEd6vAjze1RrzcDMakftnYGcuMmuql5yKFfg7LWymFf6NFOUXjxI2M2V7Puh/Aw "C (clang) – Try It Online")
### Explanation
```
f(*s,a){ // function f() takes a wide-character string (s) and an int (a)
for(;*s;) // while we're not at the end of the string
write(1,s,N // write N bytes from s to stdout
!!<expr> // if <expr> is NULL, return 0, otherwise 1
index(a,c // if the character `c` is found in `(const char *) a`,
// return a pointer to it's occurrence, otherwise `NULL`
*s++ // return the current character and increment s
) // end call to index(3)
); // end call to write(2)
} // end function f()
```
### Caveat
There is undefined behavior in the form of an unsequenced modification and access to `s`, but clang happened to evaluate `s` (the second parameter to `write`) before incrementing it in the call to `index(3)` so in this case it works.
[Answer]
# [Dyalog APL](https://www.dyalog.com/products.htm), 1 byte
```
∩
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70qpTIxJz89PrEgZ8GCpaUlaboWtxhz0x61TXjUsZLrUd9UIEs9MSk5RT1N3dAoJdHYRB0mmpGak5Ovo1CeX5STogiUTkzNzC_FLQs0IzUtPSMzKzsnNy-_oLCouKS0rLyisgquxQOiJZxiLTilFXX0FNR1gJKhzsEKhgYKljCFhuZGFibGlgamEDMMjYzhZqRlVlUllVZVAWWwicGZMDlsYkjqq0AAWbE6JNShgQ-LBAA)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 5 bytes
```
a@X^b
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhQFheYiIsIiIsIiIsIlwiSGVsbG8sIFdvcmxkIVwiIFwiYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpcIiJd)
### Explanation
```
b Second command-line argument
^ Split into characters
X Convert to regex that matches any of those characters
@ Find all matches of the regex in
a First command-line argument
```
By default, the list of matches is concatenated together and output.
[Answer]
# [Python](https://www.python.org), ~~35~~ 28 bytes
```
lambda a,b:filter(b.count,a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhZ7chJzk1ISFRJ1kqzSMnNKUos0kvSS80vzSnQSNSFKbioVFGXmlWhEa6VpKGWk5uTk65TnF-WkKOkoJaZm5pcqacZCVS5YAKEB)
Takes in either strings or lists of characters, outputs a list of characters.
---
-7 bytes from @dingledooper by using `filter` + `count` instead of list comprehension and `in`
[Answer]
# sh + coreutils, 6 bytes
```
tr -cd
```
Takes string `s` from `stdin`, alphabet `a` as an argument.
[Answer]
# [Factor](https://factorcode.org/), 6 bytes
```
within
```
[Try it online!](https://tio.run/##ldNNT4MwGAfwO5/iGSeWkEXYjG9xV/XixRgPzkOBMqrQIn02hIXPjh0VNEZe7InD8//xb5uGxEeR1Y8Pd/c3l0CkFL6ENKOIRZoxjiApSrgyjIMBah3AJJ4fmGA6bkCWKxMqGFkzuF6rVGC2QETjWNiQiywOZkoilIndAKQBKkS/oCrRcBux17c44SJ9zyTu9vlHUWpWC02qyXTQrYae/gcdQw0Dlk8kVUfEJUO2Z1jMh@X@XX7J/dVm9gI2fIN9hAZsULMWp3nMOLUBidc1cs7c89Xy4uRUt3Hc5fDlafA41gohK0tvV6qzMCfceyv8Ff/@rMbi3WjLTI2PtyiPa8zQ8WbyR4NJf/7VACzMBdAkxQIkqse1lXOjgmejzhlGjNcvEOoXuE5ICov6Ew "Factor – Try It Online")
[Answer]
# [C#](https://www.microsoft.com/net/core/platform), 33 bytes
```
(s,t)=>s.Where(c=>t.Contains(c));
```
[Try it online!](https://tio.run/##tVRbb9MwFH4mv8LNkyOFiLZDgLLmBQ0YYhLSkPpAeXCd09bg2q0v6xbU316Onayq0KSwSpyH@Dj5LlZ0PnP7kmsDB2@FWpLbB@tgXSanu@K9lhK4E1rZ4iMoMIL/hfgi1LZMuGTWkq9GLw1bk98JwbKOOcHJnRY1uWFCUesMEr//IMwsbdahQn3wil@2X3PyuF5fKb8Gw@YSLvmKmaoiCzIhB2pzl00qW0xXYIDySeXwmMqhg6U8y8rDN79BTqfTLhW6CrXxDhVaXwU78hSQpmzO6zQn6XBUs/FFmuU9@BVIqXOy00bWg0BkILQ/h4fGsFiuxM9fcq30Zmus83e7@4emX@xTKzb9n2JnEAd5QWZq5vqpwzejtxfjd69ed37D0biftBBNM/dNEzjPQx/7Xtbz0KceTah/M0izZF8mx4DA/QZTB3WYVvwbcRxB67DEqYkzE1/i5tjHZ04G7fCOo@7p4bt9PFXoCVomGB2rJRRTIxxgmKGLafFZY2TTmUJoTE5xC@EqoJZMqi6kIXecObqgtrjGy2CI6Y3NKAtVPiF@lhTitx4Uh6utZ5I@/h10eJHsk/3hDw "C# (.NET Core) – Try It Online")
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 3 bytes
```
∊/⊣
```
[Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oiKL+KKowoiaGVsbG8sIHdvcmxkISIgRiAiYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoi)
```
/ # Replicate elements of
⊣ # left argument
# by
∊ # 1 if each element of left argument is in right argument
# 0 otherwise
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 27 bytes
```
f(a,b)=[c|c<-a,[d==c|d<-b]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pZFBTsMwEEXFTVyvYslBTVJEkRrWnKBduFY1sePWYBI3JJRavUk33SAOwU16msYJVEiFFV79-e_NZrz_sFDpxdIeDu9NrcLxpwqAZiRlYicmIVAm01Ts5CTMOO-N45UFa802ABTeI1vpom4j9gNGKpjmIgAWcUJRH2NOSDswhiETElOEo1hCMsKcMrzKjSkp2pSVkQPPINdl8wdq13O1XOnHJ_NclHZdvdTN6-Zt6zr_ofdn__R_ZwN6jebFvO5odBuPR8nd8OZrK4qTrlfauaxxztcXxTl7cFH8NJ1_Zw1zTvrDf3_RCQ)
Input and output lists of characters.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ã
```
Another 1-byte builtin. Takes the inputs in the order `alphabet,string`.
[Try it online](https://tio.run/##yy9OTMpM/f//cPP//4ZGKYnGJlyJSckpAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WGWSvpPCobZKCkn1lwv/Dzf91/kdHKyUmJaco6SgZGqUkGpsoxepEK2Wk5uTk6yiU5xflpCgCpRJTM/NLscsA9aampWdkZmXn5OblFxQWFZeUlpVXVFaBlXtAlIdTpByrlKKOnkJMXkwJWNLQ3MjCxNjSwBSix9DIGCyclllVlVRaVQUURefDmSBxdD6SuioQgClSio0FAA).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 44 bytes
```
s=>a=>[...s].filter(c=>a.includes(c)).join``
```
[Try it online!](https://tio.run/##pYy9bsIwFIV3nsJ4ILFCLQJU/YnM3HZohw4dIBImccCpawfbgWLE2gfoI/ZFqENRVSG23uHq3nO@c0q6oibTvLIXUuVs70gvKcjekBElozHG2KS44MIyHWZew1xmos6ZCTOEcKm4nE73iWbLmmsWBprRXHDJAoQzf1t2L32yoBkLt1xWtb2ttMqYMdjYnMsdwkqGwSHRFWS0daDTAX8QVVu81tz66okMUAIciZMWALwAoRj3UkICGCCwLcnD89Mjrqg2Hh0HkYiCtOHPdgkQAQi@Pj79jsAhaazmcs6LTViEpS9GfscpQijZ7dAe0lmWwy6AcT@ngyFswQUTQnXBWmmRtxuHMq7qs4aPsmK@4OWreJOqWmpj69X6feM8ffdDv/yLPue0uxhM5MR6L77qXw8HN73LYyLuD7xacOdmtXONePL@3i148v6lXDNHBH4D "JavaScript (Node.js) – Try It Online")
Unfortunately, using `.filter(a.includes)` for 38 (wow!) throws `String.prototype.includes called on null or undefined`
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 10 bytes
Loosely inspired by [this answer](https://codegolf.stackexchange.com/a/59644/36398) to another challenge.
```
l~:A;{A&}/
```
Input is a line containing the two strings separated by a space. If a string contains special characters it needs to be defined explicitly as an array of chars.
[Try it online!](https://tio.run/##S85KzP3/P6fOytG62lGtVv//f6XEpOQUJQUlQ6OURGMTJQUA) Or [verify all test cases](https://tio.run/##S85KzP1f/T@nzsrRutpRrVb/v59hbfp/pcSk5BQlBSVDo5REYxMlLqWM1JycfB2F8vyinBRFoERiamZ@qZICFgmgxtS09IzMrOyc3Lz8gsKi4pLSsvKKyiqgKR4QxeEUKMaUiFZXVNdR11NX8FO3jOVSMjQ3sjAxtjQwhWgxNDIGaknLrKpKKq2qAoqh8uBMLiVUHpKaKhCAKFACAA).
### How it works
```
l~ e# Read line and evaluate: pushes the two strings onto the stack
:A; e# Copy the second string into variable A, then pop
{ }/ e# For each character in the first string, do the following
e# Implicitly push current character of the first string
A e# Push the second string
& e# Set intersection. This gives the current char or an empty string
e# Implicitly display stack contents
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 2 bytes (4 nibbles)
```
|@?@
```
```
| # filter
@ # the (second) input array
# for truthy results of the function:
? # index (or 0 if not found)
@ # in the (first) input array
```
[](https://i.stack.imgur.com/Wu6zm.png)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes
```
Φθ№ηι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMtM6cktUijUEfBOb8UyM/QUcjU1NS0/v8/IzUnJ19HoTy/KCdFkSsxNTO/9L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Trivial port of @dingledooper's golf to adam's Python answer.
```
θ First input
Φ Filtered where
№ Count of
ι Current character
η In second input
Implicitly print
```
Newlines and other unprintables need to be entered using JSON format.
[Answer]
# [Raku](http://raku.org/), 22 bytes
```
{$^a.trans($^b=>""):c}
```
[Try it online!](https://tio.run/##jYzRCoIwGEZf5e9HQmFIVnQR6HVv0EVoTN3Sms6mZrb27MvwOujqg3M4X8OU2NlqhCWH0GonoX6naN26TpKGEaK3z4xt6Qio/dMqNgSmDWIDYQSaw9s5GwQuFbhI0yxHAhisc7rZokcmVjAhJIFBKpEvvpKyUva/3HTA@KUorzdR1bK5q7brH8NzfM3BYQ6OfwX2Aw "Perl 6 – Try It Online")
`trans` is Raku's beefed-up version of Perl 5's transliteration operator `tr`.
[Answer]
# [Ruby](https://www.ruby-lang.org), 29 bytes
```
->s,a{s.gsub(/./){a[_1]&&_1}}
```
Previous version which had flaws indicated by [Deadcode](https://codegolf.stackexchange.com/questions/250781/implement-string-projection/251055#comment559347_251055):
```
->s,a{s.tr(s.tr(a,""),"")}
```
[Try it online!](https://tio.run/##pY2xTsMwFEX3fsWrF7eqGzVpESDLzIgBBgaGNINLnNbFOKntUGrEygfwifxI6qQVQlU3LPnp3XvPtU292DUFa8Y3lvAPGzkz6AYnCA3b@9kYsamlEYDXttSYgmcTCtuVVAIUWwpnewCyAN8PflU7S4XOqWcxbV2VjuOMMTTXiAZcpZMoGicZhQAdesEKAEY4SAALDO4eH@6jihsrBjjFIzXCGR52aWWkdqAIgp@vb0CkI5dCC8OdGBSpDW8Rm8ZZNux@6EaD@OI5RwRQnOR8OkM9tBJKlQS2pVF5v024kGV9NghVUSxXcv2iXnVZbYx19dv2fecDfXugn/5Fn0v6JIK5nruQxZfJ1Wx6Pbk4NuJkGtxCer@ovW/NE/m799CJ/Ev59hwRtAc "Ruby – Try It Online")
[Answer]
# Haskell, 20 bytes
```
a#b=filter(`elem`b)a
```
[Answer]
# [Rust](https://www.rust-lang.org), 70 bytes
```
|a:&str,b:&[u8]|a.bytes().filter(|d|b.contains(d)).collect::<Vec<_>>()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jZLPTsJAEIcTj32KaQ9kN1kb-WPEghyNT6AHIGS33ZVq6Uq7FSnlMTx54aA3X0ifxrZLGhtEmMvOZL759vJ7e4-SWG0-RQgz6ocIr8TVR6LEaffrOqNOI1YRYU5jmHTHGbXZUvEYYVv4geIRyryM2a4MVX4ZIw_jfAgC7irH6d9ytz8ZDBDWtu-T155hCBkBooQRF4MfwtCAbSGLMtezCFjNlkfbHQsIgEU9C5NfzJQHgSSwkFHgmQVMuS8TzXIpD8H5D1zcT_2Hx2AWyqd5FKvkefGyTLWhPCjxuuhGi-6OFhX80ZrtySHYJDaMwpHSOAGzzjcvWt1O-_LsfCtuttqaLJoaKfw0ZUmaFqBG9u-rvuSqqcbvcvt9aVEaKrsdUV0whlW1p3HMIzXhcxO5VQz_SBsBkQcMGuw_CONeKV4ba53OzUa_Pw)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 3 bytes
```
F¹F
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwiRsK5RiIsIiIsImhlbGxvLCB3b3JsZCFcbmFlaW91Il0=)
Unfortuantely, the builtin doesn't work with duplicates.
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 63 bytes
```
;=aP;=bP Wa;=c b;=dF;Wc;I?AcAa=dT0=cGc 1Lc;IdO+A Aa"\"0=aGa 1La
```
[Try it online!](https://tio.run/##lVhrc9s2Fv3eXwFzU4uQaFrOdLoT0bTH8SaZzKZONnbXMyspEQhCEhuKVPiwk0rsX3fvBfgAJUvOfkhCAQf3hXMfyB/sjqU8CZbZURT74oGHLE3Jv6NgNs9eJUmcEPEtE5GfEvlrVSjAB5akor2vnalQH/MoCxZP466zRLDFisdRmiU5z@LEZHSVzYPUTuM84cJlBewEy9t5kIl0ybgwy/0Fy/jcPP5kDkfj0XCUwnoxGPfW/xh@GkXjrjmK1s8o7R7TYinEF9hNRJYnEdGED/vj9TrKw7BQwjyLu326CkVGmOvZ4pvgpganTikCj7iuy87xY6BDXO3bTnMPbDcZqLFDEc2yObXYkI9pkcXgeBDNHrWqKGQ4yI07HDsqTP9lYS5WacaygJMl3oDp0ZVnb4XGmUIE71gC9vcddnpT6nVYr6f84u7NkI3tSoYTTE1OSxt4oflXJHkkQ53E9yQS94oFhS@8fPbI@g6PpBC72SyiRwHwp/Ae3YHVouTKO3AzYWFNJxWUDeqk@VIkJrWkiM8@yxgwSLmiCX/E3PJ3c65l61W@8ECuvqvZ@zKOQ8Gi1rb4GqI9JYKRAMxkERfxVLmn2X14qFkLtFJfldsovPa5jMEWFSrKNklx83pMhxdH/xt3j62Tmrns8BDvDGWaxo2B2mjh54tl7cykcuaZTLOCToowmzeuHDS2Hh4yeT8zfZ/o@wcKUNzYyzydmyiaOordr9xVUbL7rS@ibONan3JwyI7@/DzGv/tHLz6Dk5suSqFgVrGPIAGCgCDtCMijwTQAnAqCwmEowNxgFqGcV8NmZ1xzTJnZ2sMUu4sDn/QPMNqVlU6TQXqxNCe/R1@i@D4iQW0F6bTM6EyaiEpTaRVHLYo/SpSR39sOHQSuJDyjm/QoNxp2MN/Xbr8637CgxzC9aQHVcC/uqMQt8nAvrlvi/OBOdwjWMNKtIFeHf2PZ3AYORFyTcwy@7boE45JFUZwR0AExJ9538qdIYgOMi/0fVdpo@pk9qQjk5mGsKVrG9zsUNXLX6wOTnfbpD7nb7f6Av@LbMo6QdiwT0hKSxVC7IjEDFt0JAlaJBKwLd2T8qbybnQXhTG3X5G2oewUdZz93tVpak/eqLHBU8RaFtNK9ynbsZxs8NhBsUmNfnZbySlefCByPF2CmkEdso47A/3mqCgz@riIDfenJwCBLPJdp1d/ojCkMRunoetw9p6OTY@u5JBBGAjjk6ZQBDTgJqOmA2WpaQrDRwQbB1@uO0cEP2rjTTIFYsMCqRRABZ3zyNY@BOiLicY7Lwh@QZytWTFrdVBrezhHrpE/X6/5GsSmb8r5ig9ZPSkCpabuCIKjRZSdiKRg0B1lI9rJZm1z2kFpDVVcIC9SBQQzwzL/@HvEBK9xEfM2DRJjGNDWotcL5Um552hafB6H/eZnEXKSIev371eXN2/dX102/fA2Zva9daoxQlwljbS1m6GkdSd6qNvQ5GofOBzK7emubHit2CBxIccDEHz4MmP4prwZMvxowp660yK5MQWUH0x3U@S2AfhrNCEtm@QKHgGcrv3dSEFBCpugldD4PG54jVFintNCuFQNhcsuzxEabhyW@0epRnMvUd8QWwvXUN6hOXb49IsoDpm3bNaquIKooG6g9C@LINHq11Do8HqkGPXmU9VzDIkbPs5WMuuP2jK0a9N77Q/DMDlJJWQtGmGJaqiIf0Te6gpieYM@pnhUb07hpXIEtZJHDnOVBNn5jPAu/EyjthM9ZAr9gqAjjaAZFx2mYwcau16jCiNQdSL/TMqHg3WZ6GvWpXmCaOUfN8c6j929cxeQOJUMlzEMfbZUq/AMohmUiYZSp9dE0PhiWSd2z8hVjGJbnvsynU5HYLAxjbsKQ68cYGWb24f77MPVaQHAPXl/UA2u/OLwH/t1DfgnzBDqp3JEPIBsz6TaABDdGkUEpd7mdhgE8qPoWOWqm56qUcFpIkz4qk1p9dxrG4Nkvz1/88uLXfz5/8WtXriYs8uMFBkkefGVYzD3DyLBWBGGvc9HBvTqDVfhKAzy9PYHK88oiJcKeJvHiEm74Eh70cDnqKUIHlYH6ddm8xF1kOE1Js15Ks5j8vlTf5TNM/i3XJ3K97httBzadMf4j0WU1gwd1UFdd3D2oZckHiXotqK139RYariupOC9h/0IanNVjUitYldY08@M8s@8T6J4gSSUgvMSVz@/bEho9pRhjNJLPpJIQwIbzHYIrxgCEDh7FTLBBjaIJtepxRdrQAx5hXjfxxj5XuqMcPdqC4DzdgnS3INgIW5DjLYiconXIz9tS4g1bPm1B5LSqQ05rSH27FRa7bY2V4LPd4NkW@Hw3GMtoG3xYg01W5ZL8P4XzEjdQZF/vxLGBp5Hf0XBq2Wq57Wr7rVTFZ9p6DcK1p2k7WZhdvi09t9boKam3tdQVthdHpolDN@jeptRbdQbaIN6S7jHX/HmjoaTnjUmWp54dFhZD/LdKeVb9vxYeW68No/T9upTlS2kVepdU3/Vr6dp21dFwRD1nPZiaKm1Q02mP9xrtPR9bDhTMvzp6qSifkRAW8LLKQujBd8PnUO0fHh7mAtqFRe7jJPQPfmIiiPOfHhyXfXBc7wO5ZY7Liee4/mvnljtvzy/4BXP9m77L33By8g6W/Pe9C3LBjJHRd9kbBovsbw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16 bytes
```
Cases[#|##&@@#]&
```
[Try it online!](https://tio.run/##pZC7TsMwFEDn@CtcW8oUHkmKAIlWlioh2EBUYog8uInTGJK4@EHBffx6iKl4VMCEt3vO8R1uw0zFG2ZEzrpy1E2Y5jrDa4xDQjANOw1HEG@n8s4o0c631@3CmkupmhDcWsENuemxyfQRWWG8ORjrrMwmFVMsN1xpghO6N9KLMUKU9rvJCiA2ywsUBGuI4qRg6RBFAFW8rmUEl1LVxQB5x7iQ9g/VL@DlvBIPj3XTysWT0sY@L19ene@vdv39f/vf3SA6hCDwLj5Nzobp@fHJx584ST0vhXMz69w7/gE@h17sjvCd7KXOv68OgU33Bg "Wolfram Language (Mathematica) – Try It Online")
Input and output two lists of characters `[alphabet][string]`.
[Answer]
# [MATLAB](https://www.gnu.org/software/octave/), 25 bytes
```
f=@(a,b)a(ismember(a,b))
```
Technically, only the call of `a(ismember(a,b))` is required to fulfill the task, but to make it a callable function a function handle is created. Also, the inputs have to be of type char, not string, as a char is an array whereas a string is more like a complete unit in MATLAB.
[Try it online!](https://tio.run/##y08uSSxL/f8/zdZBI1EnSTNRI7M4NzU3KbUIzNXk@v8fAA "Octave – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 21 bytes
* -2 bytes thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan)
```
s#a=[c|c<-s,elem c a]
```
[Try it online!](https://tio.run/##rY6xTsMwEIZ3nuLqMiSSG5GkCJAoEwMDGwNDkuGauMTUsUN8IWDx7iERUQNS1YmbfP//fSeXaPdCqV5WtWkI7pEweJSWervETZJ/5bcry4USFeSAWV@h1LA5A6hbeqIGAmi1klpYOIcKa/BSz3LyYXUHUpNoclRIAtgYsImxpekgGTBul5T5kAznADyG27xgHFgYFRivmc@nvBz@Zzh0plHFYgRQSNOe6odDYvdSyte9qrSp3xpL7Xv38elm6eFHev4P6QSw4AGkOqUZCa@i63V8c3E5@WEUz@VOOrdtnRu74@nhfWiPp78dN85fgfnDkvXf "Haskell – Try It Online")
] |
[Question]
[
Given a string and a substring and a positive integer `n`.
Remove the `n` occurences of a substring from the *end* of the **originally given string**. If the substring is not present in the string or the number of times the substring appears is less than `n`, then the output is the original string. No space should be present in place of the removed substring.
### RULES
1. The shortest code wins the challenge (as this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")).
### Test-cases:
```
Input:
String = "Cats do meow-meow while lions do not meow."
Substring = "meow"
n = 2
Output:
"Cats do meow- while lions do not ."
Input:
String = "Cats do not memeowow, they do meow-ing."
Substring = "meow"
n = 2
Output:
"Cats do not meow, they do -ing."
Input:
String = "Cats do meow-meow while lions do not meow."
Substring = "meow"
n = 4
Output:
"Cats do meow-meow while lions do not meow."
```
[Answer]
# Excel (ms365), ~~115~~, 83 bytes
-32 also thanks to [@jdt](https://codegolf.stackexchange.com/users/41374/jdt) and the idea to split instead of loop.
```
=LET(a,TEXTSPLIT(A1,,B1),b,ROWS(a),IF(b>C1,CONCAT(IF(SEQUENCE(b)<b-C1,a&B1,a)),A1))
```
[](https://i.stack.imgur.com/igedA.png)
---
**Note**: This answer has been edited to no longer loop to remove the substring from the *end* of the string, but split the input instead. This would now give the appropriate answer for input like 'Cats do meow not memeowow, they do meow-ing.' where 'n=3'.
[Answer]
# [Python](https://www.python.org), ~~66~~ ~~53~~ 52 bytes
* -1 byte thanks to @92.100.97.109 (though not exactly in the way they intended)
```
lambda i,j,k:[i,''.join(a:=i.rsplit(j,k))][len(a)>k]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3TXISc5NSEhUydbJ0sq2iM3XU1fWy8jPzNBKtbDP1iooLcjJLNIBSmpqx0TmpQGFNu-xYqN5pBUWZeSUaaRpKSflFCiUIrKSjoAShjDQ1FZQVfPOLUhVKMhLzFPy4sOlBV-9akZhcklOpkFpYmpgDVIBFG7oWn9TiYqgVENctWAChAQ)
Returning identity when the occurrences are less than N is annoying.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~109~~ ~~107~~ ~~112~~ ~~105~~ 100 bytes
-11 bytes thanks to [c--](https://codegolf.stackexchange.com/users/112488/c)
-2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
+5 bytes for fixing an error pointed out by [JvdV](https://codegolf.stackexchange.com/users/100057/jvdv).
```
f(*a,i,*b,j,n,**r){for(*r=wcsdup(a);i--*n>0;)!bcmp(a+i,b,j)?wcscpy(a+i,a+i+j),n--,i-=j:0;!n?*r=a:0;}
```
[Try it online!](https://tio.run/##lZJRT4MwEMff9yk6kimF6yTzxYhzD776DeYeWAezC2sJLWFz4auLV5gOJDGzSXPXP//@uNyVM55GclvXietFIMBbww4keF5OT4nKXS@fl1xvisyNaCgY8@RzENLxmu9R8QWgnS7QwbNjc8bt7yhIxkCw@e4xCMdygZAIs6oW0pB9JKRLR6cRwaVNXnDTpK1gl3WZg1k@BKuwJ@ZxNhS5KqRppYqYWJvlisw7tBN5dfaxKqcOnDNMZqSCnuMlMppsFJEKK4ytS5VAzHt8tKo9MyG3VyHs939w7n9z1ion5rIbbxtnf1ivsPUtbcfaxuGkiWubKbB1QYjhiWjxEavEtR2l5K57XAYrih7fp8PBeXZyCDk/msYuVlMUadj34TCHPhSHPl2k5iJiDQcD9mIaS5tTsKwfxSKAfAOb1wHkpqV02FmO9MR1biepvgVyDpMN1tTkb9K5UJo/dmoc8Hv4alTVnzxJo62uWfkF "C (clang) – Try It Online")
[Answer]
# T-SQL 135 bytes
Is not looping to avoid the string being created again "memeowow"
```
WITH c(z)as(SELECT 1UNION ALL
SELECT charindex(@r,@,z+1)FROM c WHERE z>0)SELECT top(@n)@=stuff(@,z,len(@r),'')FROM
c ORDER BY-z PRINT @
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1660456/remove-a-given-substring-n-number-of-times-from-the-end-of-a-string)**
[Answer]
### Python, 51 bytes
```
lambda A,B,n:"".join(A.rsplit(B,n*(n<=A.count(B))))
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~67~~ ~~61~~ 75 bytes
Updated after clarification by OP, which unfortunately made it longer.
```
->s,u,n,*a{s.scan(u){a<<$`.size}
a.size<n||eval("s[a.pop,u.size]='';"*n)
s}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3vXXtinVKdfJ0tBKri_WKkxPzNEo1qxNtbFQS9Iozq1JruRLBtE1eTU1qWWKOhlJxdKJeQX6BTilYPNZWXd1aSStPk6u4Fmrk3YLSkmIFt2gl50QgnZKvkJuaX64LIhTKMzJzUhVyMvPzwBJ5-SVgST0lHQUlEANIG8VyoeuHKAPJ55frKJRkpFbCTc3MS8enmQjDwe7CbwOSAcaxEE8uWAChAQ)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¡`.gI›I*F«}¹ý
```
Inputs in the order `substring, string, n`.
[Try it online](https://tio.run/##yy9OTMpM/f//0MIEvXTPRw27PLXcDq2uPbTz8N7//3NT88u5nBNLihVS8hVAHF0QoVCekZmTqpCTmZ8HlsjLLwFL6nEZAQA) or [verify some more `n`](https://tio.run/##yy9OTMpM/W96bJKfvZLCo7ZJCkr2hzYd2vn/0MIEvXS/Rw27/LTcDq2uPbTz8N7/Ov9zU/PLuZwTS4oVUvIVQBxdEKFQnpGZk6qQk5mfB5bIyy8BS@oBAA).
**Explanation:**
```
¡ # Split the (implicit) second input-sentence on the (implicit) first substring
` # Pop and push all parts separated to the stack
.g # Get the amount of items on the stack
I› # Check if this is larger than the third input-integer `n`
I* # Multiply it by the third input-integer `n`
F # Loop that many times:
« # Concat the top two parts on the stack together
}¹ý # After the loop: join the stack with the first input substring as delimiter
# (after which the result is output implicitly)
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 30 bytes
```
d:a^b#d>c?dZJ(bRL#d-UcALxRLc)a
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJkOmFeYiNkPmM/ZFpKKGJSTCNkLVVjQUx4UkxjKWEiLCIiLCIiLCJcIkNhdHMgZG8gbWVvdy1tZW93IHdoaWxlIGxpb25zIGRvIG5vdCBtZW93LlwiIFwibWVvd1wiIDIiXQ==)
How?
```
d:a^b#d>c?dZJ(bRL#d-UcALxRLc)a
a : First arg(string)
b : Second arg(substring)
c : Third arg(n)
d: : Assign d to the result of
a^b : Split a on separator b
? : If
#d>c : Length of d is greater then c
Uc : Increment c
bRL : Repeat b
#d- : Length of d - c times
AL : Append list
x : Empty String
RL : Repeat x
c : c times
dZJ : Zip with iterable d
a : Else return a
```
[Answer]
# JavaScript (ES6), 62 bytes
Expects `(string, substring, n)`.
```
(s,q,n)=>(a=s.split(q))[n]+1?a.map(s=>a[++n]+1?s+q:s).join``:s
```
[Try it online!](https://tio.run/##HYrNCoMwEITvfYrFU0I0IPSkjT30MaRg8KeNxF11Qz2UPnuqXuYb5pvRfiy3q5tDhtT1cTBRcLqkKE0lrGHNs3dBLFLW@FT53erJzoJNZWulzoXVUrDUIzlsmoLjQKtAMJCXgHAzcN2plITvBaAlZPK99vQSg0geNjB0BFNPW3YEbG/ne/Bu/x0CKZxSJykkR9mJUpaXX/wD "JavaScript (Node.js) – Try It Online")
### Commented
```
(s, q, n) => ( // s = string, q = substring, n = integer
a = s.split(q) // split s on q and save the result in a[]
// if q appears x times, we get x + 1 entries
// some of these entries may be empty strings (falsy)
// so we do '+ 1' to distinguish between empty and undefined
)[n] + 1 ? // if a[n] is defined:
a.map(s => // for each entry s in a[]:
a[++n] + 1 ? // increment n; if a[n] is still defined:
s + q // append q to s
: // else:
s // leave s unchanged
).join`` // end of map(); join everything back together
: // else:
s // return s unchanged
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 11 bytes
```
O≤[Ẇy?NẎY|_
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiT+KJpFvhuoZ5P07huo5ZfF8iLCIiLCJtZW93XG5DYXRzIGRvIG5vdCBtZW1lb3dvdywgdGhleSBkbyBtZW93LWluZy5cbjIiXQ==)
12 bytes without the flag. Takes `substring, text, n`
## Explained
```
O≤[Ẇy?NẎY|_
O≤ # is the count of the substring in text less than n?
[ | # if so:
Ẇy # Split text on substring, keeping the delimiter. Then uninterleave - this gives a list of splits and a list of delimiters
?NẎ # Take up to the -nth item of the list of delimiters
Y # Reinterleave the delimiters, which will now be shorter than before. The s flag combines all the pieces into a single sting
|_ # Otherwise, just return the original text
```
[Answer]
# [Desmos](https://desmos.com/calculator), 169 bytes
```
S=s.length
L=l.length
I=[L-S...1]
A=I[[(l[i...i+S]-s)^2.totalfori=I]=0]
B=\{n>A.\length:[-L],A[1...n]\}
f(l,s,n)=l[[[0^{(b-B)^2}.maxforb=z-[0...S-1]].maxforz=[1...L]]=0]
```
[Try It On Desmos!](https://www.desmos.com/calculator/6ebtzvfzgh)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/h4iuopiqfa)
\$f(l,s,n)\$ takes in two lists of codepoints, with \$l\$ representing the string and \$s\$ representing the substring, and a positive integer \$n\$, representing the number of substrings to remove. The output is also a list of codepoints.
As you can tell by the byte size of the code, Desmos is not really well suited for problems related with string manipulation (When was using Desmos on a string problem ever a good idea?!?!). Also fun fact, this is my first time using a nested list comprehension in Desmos, which is pretty nice. There's probably a better way of doing that part, but nested list comprehensions look cool :P (to be completely honest, I can't think of any better way to do that lol).
[Answer]
# [Red](http://www.red-lang.org), 89 bytes
```
func[s t n][reverse t either parse r: reverse copy s[n to remove t to end][reverse r][s]]
```
[Try it online!](https://tio.run/##lU4xDsIwDNz7ilNnYEBMXfkBa5ShahwaqY0rJ1D19SFpVRASCx5sn@/OtpBJNzJKV7ZBsg/fqYAIr5XQkyRQBuRiT4KpLVAa7EzH04KgPCLn2cjPIs49efOxi1ZB62RZqO167Nsr5KivbQwwjJF4PpaEuXcDYXDsV8JzXMlTjbrUGudv5yYoFM8H5D@X9z7n79lWxD@df9y8VFpN4nyExfZ/egE "Red – Try It Online")
Working on a reversed copy of the string, I use `parse` to remove `n` times the reversed substring. If `parse` succeeds, I return the modified string reversed, otherwise - the original string.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 21 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
qW ÔË+WpE>VÃw
qWpUʧV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=cVcg1MsrV3BFPlbDdwpxV3BVyqdW&input=IkNhdHMgZG8gbWVvdyBub3QgbWVtZW93b3csIHRoZXkgZG8gbWVvdy1pbmciLCA0LCAibWVvdyI)
Input as `string, n, substring`
v2.0a0 is necessary because v1.4.6 errors if you try to use `p` this way.
Explanation:
```
qW ÔË+WpE>VÃw
qW # Split <string> where <substring> appears
Ô # Reverse the array
Ë Ã # For each item in the array:
+ # Append:
Wp # <substring> repeated a number of times equal to:
E>V # The current index is greater than <n>
# (Boolean gets converted to 1 or 0)
w # Reverse the new array
# Store as U
qWpUʧV
q # Turn U into a string by inserting this between each item:
Wp # <substring> repeated a number of times equal to:
UÊ # Length of U (i.e. 1 + number of times <substring> appeared)
§V # Is less than or equal to <n>
# Output that string
```
I've tried an alternate using `ð` but the best I got was [25 bytes](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=VvBVIArKqFc/X2pVbyBOzmx9Z1dbVl06Vg&input=Im1lb3ciLCAiQ2F0cyBkbyBtZW93IG5vdCBtZW1lb3dvdywgdGhleSBkbyBtZW93LWluZyIsIDM).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 21 bytes
```
s.iJcwz*]zt-lJ*KE>lJK
```
[Try it online!](https://tio.run/##K6gsyfj/v1gv0yu5vEortqpEN8dLy9vVLsfL@///3NT8ci7nxJJihZR8hbz8EoXcVJBQfrmOQklGaiVIFMTXzcxL1@MyAgA "Pyth – Try It Online")
### Explanation
```
s concatenate the elements of
.i interleave
Jcwz the input string split on the substring (assigned to J) and
]z a singleton list of the substring
* duplicated
t one less than
-lJ the length of J minus
*KE>lJK 0 if substring has less than n occurrences, n otherwise
```
[Answer]
# [simply](https://github.com/ismael-miguel/simply), 99 bytes
Creates an anonymous function that returns the expected result.
The argument order is `$full_string`, `$substring` and then `$number`.
```
fn($F$S$N)&iff(run&len(&str_split($F$S))>$N&str_rev(&str_replace(&str_rev($F)&str_rev($S)''$N))$F);
```
## How does it work?
First, splits the full string by the substring, and counts the number of elements.
When splitting the string:
* If the substring isn't present, returns 1 element.
* If it is present, returns 1 extra element.
Example: `&str_split("abcbdbebf", 'b') -> ["a", "c", "d", "e", "f"]`
For 4 `'b'`s, returns 5 elements.
If the number of elements is higher than `$number`, that means there's at least `$number` substrings in the full string.
The `&iff()` function is just the same as a ternary operator, in C-like languages.
To remove from the end of the string, I need to reverse the string, since there isn't a way to indicate to remove from the end of the string.
However, it takes an argument that indicates how many times to replace, which means, it will replace up to `$number` occurrences.
The result is returned automatically, since it is a function without a scope, just like an arrow function in JavaScript.
## Ungolfed
Code-y looking:
```
$fn = fn($full_string, $substring, $num) => &iff(
(call &len(&str_split($full_string, $substring))) > $num,
&str_rev(
&str_replace(
&str_rev($full_string),
&str_rev($substring),
'', $num
)
),
$full_string
);
```
Pseudo-code looking:
```
Set $fn to an anonymous function ($full_string, $substring, $num)
Begin.
Set $count to the result of calling &len(Call &str_split($full_string, $substring)).
Return the result of calling &iff(
$count > $num,
Call &str_rev(
Call &str_replace(
Call &str_rev($full_string),
Call &str_rev($substring),
'', $num
)
),
$full_string
).
End.
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 87 bytes
```
.+$
$*
(?=.*¶(.+)¶)\1
¶
rT`¶``(?(1)$)(?<-1>¶.*)+(?=¶.+¶(1)+$)
+`¶(.*¶(.+)¶1+$)
$2$1
1G`
```
[Try it online!](https://tio.run/##PYsxCgMhEEX7OYWFheOwwmydxGKLXCBlChciRNgobIS9mQfwYka3SPP4/P/@7nOIa2uGJEgNyl6NrkUZwlrwyVAL7A9Xi3PKKkaJyl4mvtViNFK3e6DuM5JEIDeu/z@PTs6Sge@utWXNX/FK4uPTMQ2I4x02L7aQ4jnElM/RwCDMPw "Retina 0.8.2 – Try It Online") Takes the string, substring and count on three separate lines. Explanation:
```
.+$
$*
```
Convert the count to unary.
```
(?=.*¶(.+)¶)\1
¶
```
Replace occurrences of the substring in the string with newlines.
```
rT`¶``(?(1)$)(?<-1>¶.*)+(?=¶.+¶(1)+$)
```
Remove the last `n` newlines from the string if there are in fact that many. (Today I discovered that an empty "to" string in transliteration is treated as `_`, i.e. delete matching characters.) The `r` causes the regular expression to be evaluated from right to left, so the lookahead gets processed first (setting `$#1`), then the newline-matching loop in the middle, then the count check at the beginning.
```
+`¶(.*¶(.+)¶1+$)
$2$1
```
Replace (remaining) newlines with the substring.
```
1G`
```
Keep only the (final) string.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
Nθ≔⪪ηζηF›Lηθ⊞η⪫⮌E⊕θ⊟ηω⪫ηζ
```
[Try it online!](https://tio.run/##HY1NDoIwEIX3nGKW0wRduGVlXBiMGqInqDDSJmVa2gKJl6@lm5fJfO@nV9L3VpqUWnZLfC7ThzzOoqnOIeiR8e2Mjqhq@IkaVP5/rQe8epIxG@/EY1SoMpuFgG4JavferGZ80Uo@ED6kw5Z7TxNxpCGX19BZl0MiX5vInZ3XHLGkypJoUjpVFxkDDBYmstthF9iUNgRGWy6AbSzwWO2aDqv5Aw "Charcoal – Try It Online") Link is to verbose version of code. Takes inputs in the order count, string, substring. Explanation:
```
Nθ
```
Input the count as an integer.
```
≔⪪ηζη
```
Split the string on the substring.
```
F›Lηθ
```
If this results in more than enough pieces, then...
```
⊞η⪫⮌E⊕θ⊟ηω
```
... join the last `n+1` pieces together.
```
⪫ηζ
```
Join the (remaining) pieces with the substring.
[Answer]
# PHP 8.x, 65 bytes
This anonymous function does the replacement, up to `$n`, and checks how many replacements were made.
If there were fewer than `$n` replacements made, returns the original string.
```
fn($F,$S,$N)=>($r=preg_replace("@$S@",'',$F,$N,$x))&&$N>$x?$F:$r;
```
Due to the use of [`preg_replace`](https://www.php.net/manual/en/function.preg-replace.php), the substring must be a valid regular expression.
Regular words will always be valid regular expressions, and there's no need to worry about it.
## How does it work?
The function [`preg_replace`](https://www.php.net/manual/en/function.preg-replace.php) takes the following arguments:
* `$pattern` - Which will be the substring, `$S`
* `$replacement` - Which is an empty string
* `$subject` - The full string, `$F`
* `$limit` - Maximum number of replacements, `$N`
* `&$count` - Variable which will hold the number of replacements made
If `$N` is higher than `$count`, returns the full string, otherwise returns the result of the replacement.
# Example
```
$fn=fn($F,$S,$N)=>($r=preg_replace("@$S@",'',$F,$N,$x))&&$N>$x?$F:$r;
echo $fn('Cats do not memeowow, they do meow-ing.', 'meow', 2);
// Should display: Cats do not meow, they do -ing.
```
You can try this on <https://onlinephp.io/c/d08f3>
[Answer]
# [PHP](https://php.net/), 75 111 bytes
Okay so... lot of change
+12 bytes for a bug found by @Ismael Miguel where loop keep running if no instance of searched string given (`strrpos()===false`)
+26 bytes for using $argv instead or pre defined variable as indicated by @Sʨɠɠan
-2 bytes (Hey! an actual upgrade :D) from @Sʨɠɠan who remind me i can just get ride of `{}` for a single line instruction ^^'
```
for($s=$argv[1];$argv[3]--&&false!==$c=strrpos($s,$argv[2]);)$s=substr($s,0,$c).substr($s,$c+strlen($argv[2]));
```
[Try it online!](https://tio.run/##RYtBDsIgEEWvgglpSmwbtUskLjyGYYFIpQkyhEF7fIQ20c3Ln3n/Bxvy@RIKJ4gtRUFVfH5uR8m3MMq@b5pJOTQ7IagWmGIMgKXabY2TZJyVIb7vxdX/oaOaDf@b6n1Jzvj2t2A8G22BUOQ5X1VC8gDyMrD0FWSxszPEzeBX4SGtcsiVefwC "PHP – Try It Online")
[Answer]
# [Raku](https://raku.org), 42 bytes
```
{$^a.flip.subst($^b.flip,'',:x($^c)).flip}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiUuUS8tJ7NAr7g0qbhEQyUuCczVUVfXsaoAcpM1NcECtf@tixMrFdIUlJwTS4oVUvIVclPzy3VBhEJ5RmZOqkJOZn4eWCIvvwQsqaekowSilXSMuNA1Q9SAZPPLdRRKMlIr4UZm5qXj00mCtSZc/wE)
[Answer]
# Shell, ~~238~~ ~~236~~ ~~220~~ ~~200~~ ~~199~~ ~~194~~ ~~191~~ 186 bytes
(counting the last newline to make the script file containing those commands a real unix text file. Otherwise 185 bytes.)
Can probably be highly optimized, but I found it funny to attempt.
usage: cat Text-cases | this\_script , or this\_script < Test-cases
```
sed -e'/^O/N;s,\n,,;s,",,g;s, = ,:,g'|awk -F: '/^St/{I=$2}
/^Su/{S=$2}
/^n/{n=$2
R=s=""
for(i=1;i<=n;i++){R=R sprintf("\\(.*\\)%s",S)
s=s"\\"i}
system("echo "I"|sed -e\"s,"R","s",\"")}'
```
Explanation:
```
the sed :
1) put the line following "Output:" at the end of that line
2) takes out the doublequotes
3) replace " = " by ":"
Then the awk:
retrieve (I)nput String,
(S)ubstring,
and (n),
loops on n to construct:
the (r)egex "\(.*\)S\(.*\)S\(.*\)S" (if n==3)
and its (s)ubstitution "\1\2\3"
and use sed to do this search/replace on the (I)nput string.
I used "\n" instead of ";" when I could (in the awk part) as it
is 1 caracter all the same, and is more legible.
```
[Answer]
# [Perl 5](https://www.perl.org/), 74 bytes
```
sub{($_,$s,$n)=@_;$n*2>(@a=split/($s)/)?$_:join'',grep!/$s/||++$n*2<@a,@a}
```
[Try it online!](https://tio.run/##rZJdT8IwFIav3a84LsVtUlgc6AVzsMRLErnxTs0ypRvT0c61Bgnw22e7AUocfjdpz2l73vdp02YkT08LFHkFf75bmCjAiGNELc8PXESPnb7phx7P0kTYJuKWbQ1Q0HtgCTUMHOckO7QRt5fLZlMVn/sh9sNV4WoRy03tWr8IBYcxgylhs5YaYDZJUgJpwmi5QZkoN9s6Bl0lMjrg9WFXWidr67f4HaJyUtVshkFMyHyrTmis/GWrR2wO8SarJDv@P7pC9@MVPpf@HnXyfdRfMJ0dzL8/SKfmQfZLJcdaaEo/nctfKXK5igHJH7zNqezkJSP3wgIPfBS463pAsXT34AhF@6RWVZvJuYhAb7TOOECj1XU4LFUsw7jKN2sOv6E61g7WUCBPFWgABns0oAfG5egKRkMDl96qfXVwXDq42qp4BQ "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 64 bytes
`->s,u,n,*a{x=s.split(u);l=x.size-n;x[0...l].join(u)+x[l..].join}`
[Try it online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3HXTtinVKdfJ0tBKrK2yL9YoLcjJLNEo1rXNsK_SKM6tSdfOsK6IN9PT0cmL1svIz84By2hXROXp6EG4t1Jy7BaUlxQpu0UrOiUA6JV8hNzW_XBdEKJRnZOakKuRk5ueBJfLyS8CSeko6CkogBpA2iuVC1w9RBpLPL9dRKMlIrYSbmpmXjk8zEYaD3YXfBiQDjGMhnlywAEIDAA)
Code is mine - I thought `split` and `join` would be more efficient, but I will credit [Jordan](https://codegolf.stackexchange.com/users/11261/jordan) above for the tests and framework.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 46 bytes
```
{x(!#x)^,/(!#y)+/:(-z*(~z>#t))#t:&(#y)(y~)':x}
```
[Try it online!](https://ngn.codeberg.page/k#eJytUU1PwkAQve+vWKhhZ0ppKXpxEr146smDPTZ0MRZogruGbm0Lpb/dLURNlBgOXmYyH++9eZkl7WsYODXOvcDmBscBwWTnQre7dwyiY2gEtg1Nh4LqA2MBY5F6Kw09LEzBXzR/zXQ16QOv1vkm45tcq+NAaXMc+uypfC7MNlcr6mumaMYeS/OL5ByB/1PuxNrv68rjZp01X3grcInW513f6BPyH3zdnPX1N0lihQlcg951agja5HZ255LAdEpysV2985DFJHNZSCX1wL4H3HZIwwRFmKJIgzaEUedYQBIxBktf7KHu19GT0VUt1UHE2AkYxyg1+wDGfJ8U)
[Answer]
# [Python 3](https://docs.python.org/3/), 78 bytes
```
i=input
a=i()
b=i()
c=int(i())
d=a.rsplit(b,c)
print([a,''.join(d)][len(d)>c])
```
Pretty direct approach using Python 3. [Try it online!](https://tio.run/##K6gsycjPM/7/P9M2M6@gtIQr0TZTQ5MrCUwmA8VKNIAsTa4U20S9ouKCnMwSjSSdZE2ugiKQVHSijrq6XlZ@Zp5GimZsdE4qiLZLjtX8/z8pv0ihBIG5QNgIAA "Python 3 – Try It Online")
] |
[Question]
[
This is a simple challenge: given `n` in any way practical (Function arg, stdin, file, constant in code) output the **internal angles**
(NOT the sum of the internal angles, just one) of a regular polygon with `n` sides. The output can be in degrees, gradians or radians, and can be displayed in any way practical (Function return, stdout, stderr if you feel like it, file etc)
As usual, smallest byte count wins.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 8 bytes
```
π- τ/*
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPv/fIOuwvkWfa3/1lzFiZUKaRoq8ZoKaflFCsZ6ehbW/wE "Perl 6 – Try It Online")
Output in radians. Simple function in WhateverCode notation which computes \$π-τ/n\$. \$τ\$ is the [constant *tau*](https://en.wikipedia.org/wiki/Turn_(angle)#Tau_proposals) equaling \$2π\$.
[Answer]
# [Python 3](https://docs.python.org/3/), 18 bytes
```
lambda s:180-360/s
```
An unnamed function which returns a floating point number of degrees. (For gradians swap `180` for `200` and `360` for `400`.)
**[Try it online!](https://tio.run/##Jcs9CoAgGADQuU7xbSn0o0kRQp6kxShLKA11iejsFrW95R1nWK1hUfVD3OQ@ThI8px0pWEsqH5V14PU0e9AGnDTLjFgONcU8TQ6nTUDZRbhgNxQCLspFc2flm3YZ0PdyUD8wxvEB "Python 3 – Try It Online")**
[Answer]
# JavaScript, 12 bytes
```
n=>180-360/n
```
[Try it Online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1s7QwkDX2MxAP@9/cn5ecX5Oql5OfrpGmoaFpuZ/AA)
[Answer]
# Shakespeare Programming Language, 242 226 203 bytes
[Try it online!](https://tio.run/##RU67DsIwEPuV@4AqC1u3DgxICJCYEOqQpgcJjyRNLir9@nBXBgafbMu2LsdXrQfVPfSnUadino3qDMGuVWeDHoVct54wgURA@xEk1Ytq9y4TeqBAdlGXUMBlIIswlUAOPcGANCMT9mIKY@HlcBOVy5vZwhUNg7tDZNDsDK79PBWdUKJ/ay38wgKjiatyeUQdI79hUSeqdfMF)
(Whitespace added for readability only)
```
N.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]
Ajax:Listen tothy.
You is the quotient betweenthe product ofthe sum ofyou a big pig twice the square oftwice the sum ofa big big cat a cat you.
Open heart
```
Explanation: I use the formula ((n-2)200)/n. Input in STDIN. Much of this program is the number 200, which I represent as 2\*2\*2\*(1+2\*2\*2\*(2+1)). Saved 16 bytes by switching to gradians, since 180 is harder to represent than 200. Saved 23 bytes by instead representing 200 as 2\*(2\*(4+1))^2.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~6~~ ~~5~~ 4 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
⌡π*╠
```
-1 byte thanks to *@someone* nu outputting in gradians instead of degrees.
Another -1 byte by outputting in radians instead.
[Try it online.](https://tio.run/##y00syUjPz0n7//9Rz8LzDVqPpi74/9@Yy4TLlMuMy5zLgsuSy9AAAA)
Outputs in radians by using the formula: \$A(n) = \frac{(n−2)×\pi}{n}\$.
**Explanation:**
```
⌡ # Decrease the (implicit) float input by 2
π* # Multiply it by PI
╠ # Then divide it by the (implicit) input (b/a builtin)
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÍƵΔ*I/
```
[Try it online](https://tio.run/##yy9OTMpM/f//cO@xreemaHnq//9vBgA) or [verify some more test cases](https://tio.run/##yy9OTMpM/W98senojrJKeyUFXTsFJfvK/4d7j209N0WrUv@/zn8A) (output in degrees).
**Explanation:**
Uses the [formula](https://www.mathsisfun.com/geometry/interior-angles-polygons.html) \$A(n) = \frac{(n-2)×X}{n}\$ where \$n\$ is the amount of sides, and \$A(n)\$ is the interior angle of each corner, and \$X\$ is a variable depending on whether we want to output in degrees (\$180\$), radians (\$\pi\$), or gradians (\$200\$).
```
Í # Decrease the (implicit) input by 2
ƵΔ* # Multiply it by the compressed integer 180 (degrees output)
žq* # Multiply it by the builtin PI (radians output)
т·* # Multiply it by 100 doubled to 200 (gradians output)
I/ # Divide it by the input
# (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 `ƵΔ` is `180`.
[Answer]
# WDC 65816 machine code, 20 bytes
Hexdump:
```
00000000: a2ff ffa9 6801 e838 e500 b0fa 8600 a9b5 ....h..8........
00000010: 00e5 0060
```
Assembly:
```
; do 360/n (using repeated subtraction... it'll go for at most 120 loops anyways, with sane inputs)
LDX #$FFFF
LDA.w #360
loop:
INX
SEC
SBC $00
BCS loop
; quotinent in X now. do 180-X
STX $00
LDA.w #181 ; carry is clear here, so compensate by incrementing accumulator
SBC $00
RTS
```
Input in $00, output in A. Overwrites $00 and X. 16-bit A/X/Y on entry (REP #$30).
Apparently I'm the only one using \$ 180 - \frac{360}{n} \$ instead of the more conventional formula. Note that this code rounds the division downwards, and thus rounds the result upwards.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~8~~ 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Í*-#´/U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=zSotI7QvVQ&input=OA)
```
Í*-#´/U :Implicit input of integer U
Í :Subtract from 2
* :Multiply by
-#´ :-180
/U :Divided by U
```
Taking a page out of Kevin's book, see [this Japt tip](https://codegolf.stackexchange.com/a/121263/58974) to find out why `#´ = 180`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 6 bytes
```
○1-2÷⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qQMCjtgnGJlxAplsQkGloZGH@/9H0bkNdo8PbH3Ut@p8GFHzU2weU9/R/1NV8aL3xo7aJQF5wkDOQDPHwDP6fDtJnYaBrbGYA1sP1qGO5vkaa7aOOGSCTLECivSvSNQ@tMNJ@1LvZxELhUe9chTSFzGKFzDyFosSUzMS8Yh2FdKhASmp6UWpqMQA "APL (Dyalog Unicode) – Try It Online")
The result is in radians. It implements `pi * (1 - 2 / x)`. The big circle is the "pi times" function.
[Answer]
# [R](https://www.r-project.org/), ~~21~~ ~~20~~ 14 bytes
-7 thanks to Robin Ryder. Outputs in radians
```
pi-2*pi/scan()
```
[Try it online!](https://tio.run/##K/r/vyBT10irIFO/ODkxT0Pzv/F/AA "R – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 9 bytes
```
Pi-2Pi/#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyBT1yggU19Z7X9AUWZeSbSyrl2ag3Ksmr5DUGJeemq0sY6hQex/AA "Wolfram Language (Mathematica) – Try It Online")
Returns the angle, in radians.
[Answer]
# [Python 3](https://docs.python.org/3/), 20 bytes
```
lambda n:(n-2)*180/n
```
[Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRIc9KI0/XSFPL0MJAP@9/QVFmXolGmgaIzMwrKC3R0ASC/4YGAA "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 18 bytes
```
z(n){n=180-360/n;}
```
[Try it online!](https://tio.run/##S9ZNT07@/79KI0@zOs/W0MJA19jMQD/PuvZ/Zl6JQm5iZp6GJlc1lwIQgATyrMHM4uTEvDQNJdUUJR0FtTxNiGBBEVAFTBRkIFS8KLWktChPwcCaq/a/oSkA "C (gcc) – Try It Online")
---
The above has accuracy issues on some inputs, below does not within the constraints of a float. The same could be said about slightly longer code which uses doubles... it's data types of ever increasing width all the way down.
# [C (gcc)](https://gcc.gnu.org/), 30 bytes
```
float z(float n){n=180-360/n;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z8tJz@xRKFKA0LnaVbn2RpaGOgamxno51nX/s/MK1HITczM09DkquZSAAKQQJ41mFmcnJiXpqGkmqKko6CWpwkRLCgCqgCJpgFFqzTyNKHiRaklpUV5CgbWXLX/DY0B "C (gcc) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~11~~ 9 bytes
```
180-360÷⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qQMCjtgnGJlxAplsQkGloZGH@39DCQNfYzODw9kddi/6nAUUf9fYBFXj6P@pqPrTe@FHbRCAvOMgZSIZ4eAb/13jUu8pI@1HvZhMLTR0gO@3QCigXAA "APL (Dyalog Unicode) – Try It Online")
Train that returns the value of each angle in degrees. Shaved a couple bytes off by switching to a smaller formula.
[Answer]
# Excel, 11 bytes
```
=180-360/A1
```
Result in Degrees.
For Degrees (and Gradians), 3 bytes can be saved by simplifying `=(A1-2)*180/A1`.
The Radians version though remains the same length:
`=(A1-2)*PI()/A1`
vs
`=PI()-2*PI()/A1`. Shortest Radians answer is 14 bytes: `=(1-2/A1)*PI()`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
_2÷רP
```
A monadic Link accepting an integer which outputs a float.
**[Try it online!](https://tio.run/##y0rNyan8/z/e6PD2w9MPzwj4//@/MQA "Jelly – Try It Online")**
### How?
```
_2÷רP - Link: integer, sides
2 - literal two
_ - (sides) subtract
÷ - divided by (sides)
ØP - literal pi (well, a float representation of it)
× - multiply
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 31 bytes
```
U;o;[[email protected]](/cdn-cgi/l/email-protection)'´*p,O;%u//'O;oS@!
```
[Try it online!](https://tio.run/##Sy5Nyqz4/z/UOt/a30FPT8/TSFf90BatAh1/a9VSfX11f@v8YAfF//@NDAE "Cubix – Try It Online")
Outputs degrees as a integer and a fraction (if needed). This was interesting to do as, there is no floats in Cubix. I hope the output format is OK for the challenge.
Wrapped onto a cube
```
U ; o
; O @
. . .
I 2 - ' ´ * p , O ; % u
/ / ' O ; o S @ ! . . .
. . . . . . . . . . . .
. . .
. . .
. . .
```
[Watch It Run](https://ethproductions.github.io/cubix/?code=VTtvO09ALi4uSTItJ7QqcCxPOyV1Ly8nTztvU0Ah&input=MTE=&speed=20)
* `I2-'´*` Get n input, take away 2, push 180 and multiply
* `p,O;` Bring initial input to the TOS, integer divide, output integer and pop
* `%u!` Do modulo, u-Turn to the right, test for 0
+ `@` if zero halt
* `So;O` push 32 (space) onto stack, output as char and pop. Output modulo result
* `'//` push / to stack and reflect around the cube. This will end up on the top face after jumping an output
* `o;U;O@` output the `/`, pop, u-Turn to the left, pop and output the input
[Answer]
# [R](https://www.r-project.org/), 18 bytes
Hardly a new answer, but since I cannot comment I'll post it anyway.
Output is in radians.
```
n=scan();pi-2*pi/n
```
[Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTuiBT10irIFM/778xlwmXKZcZlzmXBZcll6HBfwA "R – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~44~~ ~~42~~ 39 bytes
[crossed out 44 is still regular 44](https://codegolf.stackexchange.com/a/185093/20080)
```
.+
$*
^11
$' $&
\G1
180$*
(?=1+ (1+))\1
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYsrztCQS0VdQUWNK8bdkMvQwgAopmFva6itoGGorakZY/j/vykA "Retina 0.8.2 – Try It Online") Explanation:
```
.+
$*
```
Convert to unary.
```
^11
$' $&
```
Make a copy that is two less than the input.
```
\G1
180$*
```
Multiply that copy by 180.
```
(?=1+ (1+))\1
```
Divide by the original input and convert to decimal.
In Retina 1 you would obviously replace the `$*` with `*` and hence the `1` with `_` but you could then save a further 5 bytes by replacing the middle two stages with this stage:
```
^__
180*$' $&
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 21 bytes
Same answer as everyone else, but in Bash :)
```
echo $[($1-2)*180/$1]
```
[Try it online!](https://tio.run/##S0oszvj/PzU5I19BJVpDxVDXSFPL0MJAX8Uw9v///@YA "Bash – Try It Online")
[Answer]
# [PHP](https://php.net/) (7.4), ~~21~~ 18 bytes
-3 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
```
fn($n)=>180-360/$n
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwMWlkmb7Py1PQyVP09bO0MJA19jMQF8l7781F1dafpGChkqmgq2CibUCkLaxVTA0ALG0tTUVqrkUgCA1OSNfQSUNqEpTQU9BKSZPyZqr9r/5v/yCksz8vOL/um4A "PHP – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 9 bytes
```
%~180*-&2
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F@1ztDCQEtXzei/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCsXamnsV/AA "J – Try It Online")
or
# [J](http://jsoftware.com/), 9 bytes
```
180-360%]
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N/QwkDX2MxANfa/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCsXamnsV/AA "J – Try It Online")
# [K (oK)](https://github.com/JohnEarnest/ok), 8 bytes
```
180-360%
```
[Try it online!](https://tio.run/##y9bNz/7/P83K0MJA19jMQPV/mrqxtqL5fwA "K (oK) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 8 bytes
```
%o.@*-&2
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F81X89BS1fN6L8ml5KegnqarZ66go5CrZVCWjEXV2pyRr5CmoKxdqaehYKfk55CbmJJckZqsUJ5ZkmGgmOAj0J@Xup/AA "J – Try It Online")
Implements `pi * (x - 2) / x`. Just like [APL](https://codegolf.stackexchange.com/a/194739/78410), J has the "Pi times" built-in `o.`.
### How it works
```
%o.@*-&2
-&2 x - 2
% *-&2 (1/x) * (x - 2)
o.@ Pi times the above
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 25 bytes
```
: f 180e 360e s>f f/ f- ;
```
[Try it online!](https://tio.run/##FY3NCsMgGATvfYohd21@SikN8UXEU/VrAmkVTZ/fmssO7LCsxHys6i0nan0iDI8@MN1bFCPIFVHMzSTE/xJDQD7RI/3C1rwpaMJeWq051vBlvow3JqyPDrs5ztWIzugOlKFrJ4lXxu4xJlf/ "Forth (gforth) – Try It Online")
Output is in degrees
### Code Explanation
```
: f \ start a new word definition
180e \ put 180 on the floating point stack
360e \ put 360 on the floating point stack
s>f f/ \ move n to the floating point stack and divide 360 by n
f- \ subtract result from 180
; \ end word definition
```
[Answer]
# [Zsh](https://www.zsh.org/), 17 bytes
```
<<<$[180-360./$1]
```
[Try it online!](https://tio.run/##qyrO@P/fxsZGJdrQwkDX2MxAT1/FMPb////mAA "Zsh – Try It Online")
---
[Pending consensus,](https://codegolf.meta.stackexchange.com/questions/18212/zsh-functions-and-math-functions) the following may be a valid **15 byte** solution, or more likely a **17 byte** tie with `()` declaring it a function:
```
((180-360./$1))
```
[Try it online!](https://tio.run/##DcE9CoAwDAbQvaf4hg7JYLUUpOAZPIUa2iUBfxbFs1ffu4/ShLgRxTx0aRxC7yNzk0uXs5oe6GaIc2I7FFXxpBDyO2E1h9@2FIMngpAymN1qurUP "Zsh – Try It Online")
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 8 bytes
```
PPi2,,-@
```
[Try it online!](https://tio.run/##KyrNy0z@/z8gINNIR0fX4f9/YwA "Runic Enchantments – Try It Online")
Output is in radians.
### Explanation
```
P Push Pi
P Push Pi
i Read input
2 Push 2
, Divide
, Divide
- Subtract
@ Output and terminate
```
Works out to `Pi-(Pi/(i/2))` which is equivalent to `Pi-(2Pi/i)` (`PP2*i,-@`, same length), I just liked the "push all the parts, then do all the math" arrangement ("it looked prettier").
[Answer]
# [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate), 37 bytes
Just uses the simple formule `180-360/n` used on other answers.
Due to ... sub-optimal ... math support, the formule was adapted to `(-360/$n)+180` (it's almost the same, calculated in a different order).
```
{@set/A-360 argv}{@incby180A}{@echoA}
```
You can try it on: <http://sandbox.onlinephpfunctions.com/code/00b314dee3c10139928928d124be9fc1c59ef4bf>
On line 918, you can change between `golfed`, `ungolfed` and `fn`, to try the variants below.
**Ungolfed:**
```
{@set/ A -360 argv}
{@inc by 180 A}
{@echo A}
```
Yeah, there's not much to ungolf...
**Explanation:**
* `{@set/ A -360 argv}` - Stores in `A` the result of `-360/argv`.
`argv` is a variable that holds all passed arguments (in a function or when running the code).
`A` is now an array with `argc` elements (`argc` holds the number of aguments passed).
* `{@inc by 180 A}` - Increments all values of `A` by 180 (`A+180`, basically)
* `{@echo A}` - Outputs the values of A, without delimiter.
One could use `{@return A}` if inside a function, to get an usable array.
**Function alternative:**
Converting to a function to get an usable array is easy:
```
{@fn N}
{@set/ A -360 argv}
{@inc by 180 A}
{@return A}
{@/}
```
Creates a function `N` that takes multiple arguments and returns an array.
Just call it as `{@call N into <variable> <argument, arguments...>}`.
---
If you are curious, this code compiles to the following:
```
// {@set/A-360 argv}
$DATA['A'] = array_map(function($value)use(&$DATA){return (-360 / $value);}, $FN['array_flat']((isset($DATA['argv'])?$DATA['argv']:null)));
// {@incby180A}
$DATA['A'] = $FN['inc'](isset($DATA['A'])?$DATA['A']:0, 180);
// {@echoA}
echo implode('', $FN['array_flat']((isset($DATA['A'])?$DATA['A']:null)));
```
] |
[Question]
[
Each element on the [periodic table](https://en.wikipedia.org/wiki/Periodic_table) of the [elements](https://en.wikipedia.org/wiki/Chemical_element) has an [atomic weight](https://en.wikipedia.org/wiki/Relative_atomic_mass). For example, [boron](https://en.wikipedia.org/wiki/Boron) (element 5) has an [atomic weight](https://en.wikipedia.org/wiki/Relative_atomic_mass) of 10.81. Your challenge is to write a program which takes as input the atomic number of an element and outputs its atomic weight.
Your program only needs to support elements up to and including element 118 ([oganesson](https://en.wikipedia.org/wiki/Oganesson)), the current (as of December 2022) highest known element.
Your score is calculated using the formula:
\$(1+b)\times(1+m)\$
where \$b\$ is your program's length in bytes and \$m\$ is the mean-squared error of your estimates.
## List of weights
These are the weights your program must output for a given atomic number. If I input `1` I should get `1.0079`, `2` should give me `4.0026`, etc.
```
1.0079
4.0026
6.941
9.0122
10.811
12.0107
14.0067
15.9994
18.9984
20.1797
22.9897
24.305
26.9815
28.0855
30.9738
32.065
35.453
39.948
39.0983
40.078
44.9559
47.867
50.9415
51.9961
54.938
55.845
58.9332
58.6934
63.546
65.39
69.723
72.64
74.9216
78.96
79.904
83.8
85.4678
87.62
88.9059
91.224
92.9064
95.94
98
101.07
102.9055
106.42
107.8682
112.411
114.818
118.71
121.76
127.6
126.9045
131.293
132.9055
137.327
138.9055
140.116
140.9077
144.24
145
150.36
151.964
157.25
158.9253
162.5
164.9303
167.259
168.9342
173.04
174.967
178.49
180.9479
183.84
186.207
190.23
192.217
195.078
196.9665
200.59
204.3833
207.2
208.9804
209
210
222
223
226
227
232.0381
231.0359
238.0289
237
244
243
247
247
251
252
257
258
259
262
261
262
266
264
277
268
281
282
285
286
289
290
293
294
294
```
*The scoring calculation was last updated December 15th 2022 at 5:50 pm UTC. Any answers posted before then use an old version of the scoring calculation, and, while not required, are encouraged to update their scores.*
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), score \$(1+29)(1+2.52543) = 105.763\$
```
#~ElementData~"AtomicWeight"&
```
If the builtin fits…! Doesn't work on tio.run because it requires access to Wolfram's servers or something like that. Gives each output as a quantity-with-units rather than a raw number.
For whatever reason, Mathematica has different ideas about the atomic weights of elements #104–109 than the OP, differing by 6, 8, 3, 6, 7, and 10, respectively. Without those errors, this function's score would be just over 31.
I love the fact that [CursorCoercer's answer](https://codegolf.stackexchange.com/a/255551/56178) beats this builtin!
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~3~~ 6 bytes (12 nibbles), score ~~118.37~~ 85.62
```
*^^$41-39~
```
```
^$41 # input to 41st power
^ -39 # get integer value of 39th root
* ~ # and multiply by 2
```
Mean-square-error = 11.23
[](https://i.stack.imgur.com/DLoMi.png)
---
### [Nibbles](http://golfscript.com/nibbles/index.html), 67 bytes (134 nibbles), score 70.26
Uninventive port of [MarcMush's 119-byte answer](https://codegolf.stackexchange.com/a/255528/95126) (now improved; see edits): upvote that instead of this. [See screenshot here](https://i.stack.imgur.com/Y9p6e.png).
```
-/*13$5=$`D16 110123444657688996ac998aabbdbdaaa9b9bacdddddedeccba7a9a89accdbb9a999a999889787876669b1324251404253534659b9e3f5667798ac
```
[Answer]
# [Julia](https://julialang.org), score ~~139~~ ~~129~~ 115.83
\$ score = (1+97) \cdot (1+0.1820) = 115.8387 \$
```
x->2.6x-b"
$/;GG=_HS_k`TITTklllb`>IIS`VJIHIHH=<=0G$/FI*+0<Hj"[-~x>>1]÷11^(-~x%2)%11*1.5
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PVS7TltBEC2SykKJlCaPyrJAssEednbvvgi20iTYkVKBkgLxMGAUwECEISZNfiQNDVU-IB-Qr0i-JuesTZo7587Mzpw9M_f-uD-9GZ8M734eXh6NulfDaaPRuL-5Pu6kP8PbTs9KuO0cNBYWni-uvt7Y6O71N_fO9rcGW1tn4_H4YL83GGzuf3w_6A_6_e5612w8e_Hk6aOXi69W3w2WV8x6_7Sx3fl-2-vpzu9fqrtNvCzZ1pLqsoqfNfr7OKDptq6NLo46ulM7rnfro6_DcfPD6HooX4ZXk1GT7Fqt2hShY2nqmmpq1T69HWz0tzbh21YxJuZ2vYK1oV0Pkitt17MYtbZdVyNJ8a4WDhMBmBgIvOScK4AEkACsEY0ZIWslpwIqccbDompSgiQmeQBnJEeXAFA40OGl8g42g0Aq1uQER2XERDiqSrL3ZBolkYA3pIqjXkEggKRHCmt6L6liAMycswWE7EAxOPEVb-nFoVTIEi16REwL0YjzVhGOOEgDLgb-5ARVExgGMklRAoomJBkSyirWIi3j2oZ1MqShSdQPAlMtwyBvriZIVZTlPRIRxK2KyBA3KU9B01hUV4mBFi1pAgmxiEPP7Aj-13VRnGUrlx5c0E55H4JsYhlfJeSqpQokdAxTQRJXH8WWAEpYjkODFToCpTXFwZRMQHXLTaITyqTUr6wG9KuYkjiiWBAkLLsSxBY9shEqrxDNanH42Zw145KBK2GNEXayBmuUnCNCcxq0TqasHONquHMMsKTlGlsqYblcLikRxuBKMahjbCqobCirVDxWxYeH5wnPer68Jj54gmO33LQ5YiPqZimtDcwr3ThVm8q-M6V0yyTJkVnuBh47tdo5vsDJzXmzOZXO_Jtsya5trWIBagffrkcTJFzwE765OLmezD7m2uTw8mqEQLNkrGhruakr563am8nny2mdOXNY4nN8Prfl8Oz3cXc3s_8A)
the error of `x->2.6x`, devided by 1.5 and rounded to the nearest integer is comprised between 0 and 10. This allows to store 2 errors in a ASCII character (0-127) like a base-11 number. This way, all errors are less than 0.75, giving a quite good mean squared error (0.18)
**previous answers:**
* even lower mean squared error (0.08) [119 bytes, score 129.66](https://ato.pxeger.com/run?1=PVTdbptFEL3hyk9hWUKyqT3szP4XJYIqxARUepG2IVRFcpovbWjstP0c7PIq3OSmEq8ET8M5a5ebb45nZmfOnpn1X59-v7u5Xtz__er2sjsYjUaf7tZXs_LPZjs7NEnb2bvFh74bP7p-fbJaT0dXm4_l8uz545Onbh7eH79_8jYe_dn9erp61p_9cv58rqc_v7n4abvcPps_el39upbvjs7n735cHie3jDdrvYxPOjs_6c-Oj5x7ezT65mLRdwfJJoeHYfulpl37f79IoPJCH3ary5m-HFwND4bdH4ub8eNuvZAdJRKeTAYbhK5krA9Vy2Rw9v3J_Ienp_C9UHEu1-kwwFqaDpPUoNNhFadm06E6KYrfanC4DMDERBCl1hoACkABMCeaK0JmUksDQbyLsKhalKCIKxHAO6nZFwAUTnRECdHDVhAozbpa4AhOXIYjBKkxkmmWQgLRkSqORgWBBJIRKawZo5TAAJh5bw2k6kExeYmBt4ziUSpVyYYeGTNENOO8KcIZB2nAxcFfvKBqAcNEJiVLQtGCJEdCVcUMaRXXdqxTIQ1NoX4QmGo5BnlzdUlCU5b3KEQQNzSRIW5RnoKmuamukhMtWtIkEmIRj57VE_xf12fxxla-fHZBO-V9CKrLbXxByFVbFUjoGaaCJK4xi7UAShjHocmEjkRpXXMwpRJQ3XaT7IUyKfVrqwH9AlMKR5QbgoRtV5JY06M6ofIK0UybI-7mrBWXTFwJc07YyRzWqHhPhOY0aF1cWznG1XHnGGBJ4xoblTAuly9KhDH4VgzqOCsNtQ1llcBjIX_-RJ6IrBfbz8IPT3Dsxk3bIzaibkZpLTGvdeNUrbR9Z0rrVkmSIzPuBj4vB4MlXmB_txyPNzLbv8mJ_GaTr7EAg4uP665HwopP-G51ve53j3nQv7r90CEwbhkPdPLVWB8sJ4Nv-ze3myFz9rDF93i5t-3w7u_j_n5n_wM)
* first simple answer `x->2.6x-8` [9 bytes, score 138.34](https://ato.pxeger.com/run?1=PVTLbhNBELxw2q9Y5WQTu5nuefVECuKCgAMnkDhEQTKJI4LiBMU2Cd_CJZdI8Et8DVVjh8t2bT-qe2p699fjt-3V5eLh99nN-fL44ODgcbu5mPuf-_lLk3I_993732cFsRM9Wl6fz_V0uBiPx-WPxdXk_XKzkO-L2_VyQobpdLhD6EImeqTq0-HT63dv3n78AN-JSgi1zcYEa2U2FmlJZ2OToGazUYO44l0NjlABmFgIsrTWEoADOIAF0doQMpPmHSSJIcOC1ZXAJXgGiEFajQ4A4kJHlpQjbMMA3m1oDkcKEiocKUnLmZNWcQ6QA0dFaVYMUDBkRgo5cxZPDGCyGK2D0iJGLFFy4imzRFCVJtXQo0JVRCvqTRGuKKTBLAF-jwJWx4SFk3iVAlJHUuBATcUMaQ3HDuRpkIbGqR8EplqBQZ5cQ5HUleU5nAjipi4yxHVlFTStXXWVWmjRkqZwIJJE9GyR4D9vrBKNraI_uaCd8jwELdR-fUk4q3YWSBgZpoIcXHMV6wFQGK9DiwkdhdKG7mBKI6C6_SQ1CmVS6tdXA_olpjivqHYECfuuFLGuRwtC5RWimXZH3t2zNhyycCUsBGEnC1gjj5EIzWnQ2kNfOcY1cOcYIKVxjY1KGJcruhLhGmIngzrBvKO-oWRJLEv16ZFZkcmX-6vzwQpeu3HT9oiNqJtRWivM6914q-Z935nSuzUOySsz7gYep8Owwhe43q4mkzuZ77_JqXy26QsswPDl52a5RsI1P-Ht9eVmvfuYh_XZze0SgUnPONTp84kerqbDq_XXm7uROXvY43u82ttevPt9PDzs7D8) *-1.35 thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes, score 338.70775620762714
```
5H×
```
[Try it online!](https://tio.run/##y0rNyan8/9/U4/D0////GxoAAA "Jelly – Try It Online")
Multiplies the input by \$\frac{5}{2}\$
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), score = \$(1+6) \cdot (1+13.1372) \approx 98.9605\$
```
y*@Q20
```
[Try it online!](https://tio.run/##K6gsyfj/v1LLIdDI4P9/c2MA "Pyth – Try It Online")
Uses the formula \$ 2\cdot n^{1.05} \$. Verify the score and compare to the integer divide by two, multiply by 5 (would be 4 bytes in pyth) method on [Desmos](https://www.desmos.com/calculator/s1zmco5inx)
### Explanation
```
y*@Q20Q # Add implicit Q
# Q = eval(input()) implicitly
y # 2 times
* Q # Q times
@Q20 # the 20th root of Q
```
[Answer]
# [Python 3](https://docs.python.org/3/), score = \$(1 + 789) \* (1 + 0) = 790\$
```
lambda n:[1.0079,4.0026,6.941,9.0122,10.811,12.0107,14.0067,15.9994,18.9984,20.1797,22.9897,24.305,26.9815,28.0855,30.9738,32.065,35.453,39.948,39.0983,40.078,44.9559,47.867,50.9415,51.9961,54.938,55.845,58.9332,58.6934,63.546,65.39,69.723,72.64,74.9216,78.96,79.904,83.8,85.4678,87.62,88.9059,91.224,92.9064,95.94,98,101.07,102.9055,106.42,107.8682,112.411,114.818,118.71,121.76,127.6,126.9045,131.293,132.9055,137.327,138.9055,140.116,140.9077,144.24,145,150.36,151.964,157.25,158.9253,162.5,164.9303,167.259,168.9342,173.04,174.967,178.49,180.9479,183.84,186.207,190.23,192.217,195.078,196.9665,200.59,204.3833,207.2,208.9804,209,210,222,223,226,227,232.0381,231.0359,238.0289,237,244,243,247,247,251,252,257,258,259,262,261,262,266,264,277,268,281,282,285,286,289,290,293,294,294][n-1]
```
[Try it online!](https://tio.run/##NZJLblsxDEW38maxAYbgTxIZIN1ImoGL1q2B9CUwMunqncumHUiURPF3yLc/779ed7@dH7/eXk6/v30/bfvDk7LIKgoImzS5QqlY1IxUOFVJDVdZpP1nQg6uqiBNyAwyYV21yIwrWwa7DDL4SoVMlhyDXLiWJzncTVwHx3DyQsRsIZVOISwrKYJrDGS1OBFxSKc1aCgiTqUBNTyNwRl4RR7u1nKWB03nEShlsBfN4mVOy3gGLdiZTlqwwI7QEpTOSYlsJgLn4mmU0AvCl7JZUKEwgXmhcOwJMKAGENIKlKYyOZpXp5s4AFk0OSBLxX@gWg1SeU0IBME@OzyMHVHKIf9788VucO/57wFUFGm3LFndiWDkpW0NNg5Vo0GKOhZbv8LUgFenMa6zgUlfW12QzaxTXs5goE2mWwsyAXU28NUHwOlOT7YuuIQBUwHEtK/jb7e0UMpET02E4d0EE5DuOCAcdgRL6UGBTgWDgkf4MQycoVDrkfBUHMDV2wNKF8s@9DzBNPA91uca@DngYvQ5qQsydM0wGZ8SbsHCQMom9O0ZXbHsYYSu/RbSAHRDQ7Gen/Z7fb6dX6/bZbvs2/W0//xxUNpU6/iwvV0v@/vhQtvd/Zc72s6Hy/F4@wA "Python 3 – Try It Online")
Prints the exact values.
# [Python 3](https://docs.python.org/3/), score = \$(1 + 16) \* (1 + 12.83) \approx 235.18\$
```
lambda n:2.6*n-8
```
[Try it online!](https://tio.run/##PZPJbhsxDIbveYq5xS5ogosWMkDyIkkOLlq7A7STwMilQN/d/ZmkPYxIiRKXj5zX328/Xja/nu9/Hn99/XZctrtHZZGZ1CBs0OBsSsmiZqTCoUpq2MokrTsDsnNmNtKAjEYmrDMnmXFGycYunQy@QiGDJXonF87pQQ53A9vOrTt5ImKUkAynJiwzqDXO3pHV5EDELpVWp66IOJQ6zPDUO0fDKfJwt5IjvdFw7g2ldPakkTzNaRqPRhPvTAdNvMCK0NIonIMC2QwEjsnDKGAXhE9ls0aJwgTPE4VjDYABNYCQMqA0lcGteFW6AQXIWpEDslDcB6pZIJXngEAQrKPC47EjSjrkP28@2Q3uPT4PQEWRdsmUWZ1ojLy0XoONw1RokKL2yVaneGrAq8MY21HApLZlTshiVilPZzDQIlOtBZkGcxTwWQrgVKcHWxWcwoCpAGJa2/7eLU2UMtBTE2F4N8EEhDsUhMOKYCE1KLCpYFBwCD@GgTMUajUSHgoFXL08oHSxKKXmCU8brrf58XXc7HDRSw@qggxdM0zGh4RbsDCQsgF7eUZXLGoYYSu/iTQA3dBQfM@P20Gfb25O90/X/78GRubLdojr6eWyrMu6LZfjdv6@U1pUc3@3vF7W7W230nJ7eLil5bRb99D/QD1D3V//Ag "Python 3 – Try It Online")
Verify the score [here](https://tio.run/##bVPLUhtBDLzzFXPzLpGVkealocqfkFtuhIMTbAcwa7ChCvLzTstOckhy2JFm1Hq1tE/vL993UzpuFtvl49fbZZiuroVjbJ0yhFaq3LNQ5yiqJJFNhERxjY3EMRWycO89kxikZdLI0nojVe7mMnOKhRSxTCCNo5VCKXJvySghXMW1cC6JUkdGcxG7JcqRYzPKmXspqKqxIWOJXlahIshYhQrMiFQKW8Yr6khJXdaeMtXEJaOVwqlT7dw0UVOumRr8VCo1eOBE6pjJEhsZqqlIbI2rksEekb4Lq2bqaCzCvaNxnAZiwBqIiG5AaxIrZ@fLyzUooCw7c6DMBHhQ1ZxI4VYhkARn9fRwTsjSE@TvaKlxUoRP9usBrAjKdtlj80lkRl3i3uAmweTUoEQpjdVf4aqgV6oyrtUJi351c4d0zrzklhgciDPjowUzGWZzwpsrIMcnXVm94R4ZZAoIUfFrOU1LOlqpmKnGyIiuERtgKUFBOpxIZtEXBTaJWBQ8Io5i4RSNqq9EMoECXpNHQOtRzRXfJ7hmwHM7fwXIghDFdSNvSDE1xWacJcKCCwVTWmH3yJiKmi8jbB63owyQrhgovpvraS43FxfrxZfjn18DK3M5ze243oZFuF4P92NY7/bhPtxNYb@cNqtBKIj08eZic4Jshocz5OE/kMOzQ4a3MA/vY7i8DHqCvtG7g3/cPQ3rLW22QD7t76aXYfZptZzmh@fX5X51G1b7/W5/NaNweH0cDs9j@Bi2q8m18eK3w@fdy3IbDt92@1VYADpI@HBCzf5uaTaigrN9@DfgOB5/Ag)
* **Thanks to MarcMush for cutting down the score from 473 to 237.**
* **Thanks to Neil for cutting down the score from 237 to 235.**
[Answer]
# MATLAB, score 144.247 (from @Neil)
```
@(n)1.6*n^1.1
```
# MATLAB, score 161.092
```
@(n)1.7*n^1.087
```
Using the best fit for \$a\*n^b\$.
---
# MATLAB, score 206.683
```
@(n)n.^(0:3)*[5/4;1.77;.0154;-7.77e-5]
```
Using the best fit for \$a+bn+cn^2+dn^3\$.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 776 bytes, score = 0
```
⟨1.0079|4.0026|6.941|9.0122|10.811|12.0107|14.0067|15.9994|18.9984|20.1797|22.9897|24.305|26.9815|28.0855|30.9738|32.065|35.453|39.948|39.0983|40.078|44.9559|47.867|50.9415|51.9961|54.938|55.845|58.9332|58.6934|63.546|65.39|69.723|72.64|74.9216|78.96|79.904|83.8|85.4678|87.62|88.9059|91.224|92.9064|95.94|98|101.07|102.9055|106.42|107.8682|112.411|114.818|118.71|121.76|127.6|126.9045|131.293|132.9055|137.327|138.9055|140.116|140.9077|144.24|145|150.36|151.964|157.25|158.9253|162.5|164.9303|167.259|168.9342|173.04|174.967|178.49|180.9479|183.84|186.207|190.23|192.217|195.078|196.9665|200.59|204.3833|207.2|208.9804|209|210|222|223|226|227|232.0381|231.0359|238.0289|237|244|243|247|247|251|252|257|258|259|262|261|262|266|264|277|268|281|282|285|286|289|290|293|294|294⟩i
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCLin6gxLjAwNzl8NC4wMDI2fDYuOTQxfDkuMDEyMnwxMC44MTF8MTIuMDEwN3wxNC4wMDY3fDE1Ljk5OTR8MTguOTk4NHwyMC4xNzk3fDIyLjk4OTd8MjQuMzA1fDI2Ljk4MTV8MjguMDg1NXwzMC45NzM4fDMyLjA2NXwzNS40NTN8MzkuOTQ4fDM5LjA5ODN8NDAuMDc4fDQ0Ljk1NTl8NDcuODY3fDUwLjk0MTV8NTEuOTk2MXw1NC45Mzh8NTUuODQ1fDU4LjkzMzJ8NTguNjkzNHw2My41NDZ8NjUuMzl8NjkuNzIzfDcyLjY0fDc0LjkyMTZ8NzguOTZ8NzkuOTA0fDgzLjh8ODUuNDY3OHw4Ny42Mnw4OC45MDU5fDkxLjIyNHw5Mi45MDY0fDk1Ljk0fDk4fDEwMS4wN3wxMDIuOTA1NXwxMDYuNDJ8MTA3Ljg2ODJ8MTEyLjQxMXwxMTQuODE4fDExOC43MXwxMjEuNzZ8MTI3LjZ8MTI2LjkwNDV8MTMxLjI5M3wxMzIuOTA1NXwxMzcuMzI3fDEzOC45MDU1fDE0MC4xMTZ8MTQwLjkwNzd8MTQ0LjI0fDE0NXwxNTAuMzZ8MTUxLjk2NHwxNTcuMjV8MTU4LjkyNTN8MTYyLjV8MTY0LjkzMDN8MTY3LjI1OXwxNjguOTM0MnwxNzMuMDR8MTc0Ljk2N3wxNzguNDl8MTgwLjk0Nzl8MTgzLjg0fDE4Ni4yMDd8MTkwLjIzfDE5Mi4yMTd8MTk1LjA3OHwxOTYuOTY2NXwyMDAuNTl8MjA0LjM4MzN8MjA3LjJ8MjA4Ljk4MDR8MjA5fDIxMHwyMjJ8MjIzfDIyNnwyMjd8MjMyLjAzODF8MjMxLjAzNTl8MjM4LjAyODl8MjM3fDI0NHwyNDN8MjQ3fDI0N3wyNTF8MjUyfDI1N3wyNTh8MjU5fDI2MnwyNjF8MjYyfDI2NnwyNjR8Mjc3fDI2OHwyODF8MjgyfDI4NXwyODZ8Mjg5fDI5MHwyOTN8Mjk0fDI5NOKfqWkiLCIiLCIyMyJd)
Prints the exact average for each element, so each \$(p\_{el} - w\_{el})\$ = 0, meaning the fraction sums to `0/118`, and multiplication gives score = 0
The scoring of this answer was correct at 2:27pm 15 Dec 2022 UTC. If by some chance the question has been edited to make the score invalid, I won't be available to change it for another 8 or so hours. Therefore, if the score is invalidated, I'll update this when I can.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes, score 113.33712413095091
```
I×¹·⁶XN¹·¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyQzN7VYw1DPTEchIL88tUjDM6@gtMSvNDcJyNbUUTDUM9QEAuv//w0NDP7rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
N Input integer
X Raised to power
¹·¹ Literal number `1.1`
× Multiplied by
¹·⁶ Literal number `1.6`
I Cast to string
Implicitly print
```
[Answer]
# [Perl 5](https://www.perl.org/), 179 bytes, score 186
```
sub f{my$s;map$s+=/C|D/?hex:$_,("0x3221223xxxx5-11533xx051532414x12232323243436-142421x1525242224233324232433201Cx15-17-17-1404151x-114-2D-9Dxxx10"=~s/x/13/gr=~/-?./g)[1..pop];$s}
```
[Try it online!](https://tio.run/##TVTbjhpHEH0OX9EiSIZdaPp@ASFH8uYtefKjbUXj3YEdBQbCxcby5dc35zQD9sB211adqjp9uphdvV/7l80XMVie2sdjs20Xr14Op49i@XXzZXCYb6rd4HC/mL759jB9/VyfZ4N/xsO@OltjtDH2jMdPtPYWpvLYjdPuzFD5OOtsmGhnnNFn7Y2HYfBnreWKuDVKv0FoomP5OuW012fUdBPzMMkP6KBVf/HjMD1PtZ2u9osf08lrOV2N3mkpd9vdh/ng8P3lFRHv2ykA8x7O88fnulk9HxdDLZWKeSwcdhPGIsjs9FhkqcByLLSSSeN/beBQEQaBgYaXOWcHI8FIMIySOmaEjJE5wej9JvAYJ63y8KJ00jSSVMnDsErmaBMMVA90eOm8xZ7BIpVd5QSHU1JFOJyT2XvSjTKFawevSBr5XoNKAF0PHAt7L5NjAByhZTFCtiAbrPSO5/XSol7IMho0ikYGRCPyjQ5d/YhsQCNYKQSTlSidwDWQU4oyoHICSJFa1hJ3iB0qKBbLUIpbopzQ@0pbKyIohFZBuqI2j5VoQXBXhIfgSTMVOsdyE1rGwB19uQWyYhGLxtnS6Op2bWyU1vDGbLr2g55ah4uRVSz36iRZ61IKilqGKSiPoH2UpgRQwvCKdDDy1iFQblW8xGUaVLycKVpJ1TQ1LYMDOR0hidcWiwVFyyQFacqQZSV5GxoaGn3TC0KWKdAZZw4cGKOUZDujMGTJWlpgwA39kypTybhWHEsGWNeY69UaCmM4fzZpWrgfWypCLGVSsQhxLOWY6@J18czw5lrKF1/iwjQOheEwdlbgwiqU2wTi0LLL5Z2bVH4cxJW@mZx5oYbjg2U079WfqvXPl9FcdM/vm@rfWpQXk6g@Vc26@riu@TsfbA61WAh1QxZwXbXi8N@p2tei3u@3@95yuxdENwIvBIxGGn0tyMdq/XhaV8da/P32T1G1T2J7Ou5OR/HULJeHWY8g5q22R3RZDgcNOF6dn6v2WD/BP7i8bN4Nmon@cIkXXvcLMWTqpIOO7u7MFM1Fs7yUbOtrlUvWbt@0R9FvWlCYka0QgM0uYCEu0Nmtsyg0Z6Ivh51rQuRI9hHigQ5bsaz2s8Lmfduf974XzdZ1C9ZYV8fn4U1snKzr/1eJiGtgVjJKfgdA7V@Kds63j9t9XcgIqHzPnJG4KyaQIwFahL/8Dw "Perl 5 – Try It Online")
...to compute score.
```
sub f {
my $s; #sum
map $s += /C|D/?hex:$_, #convert C and D to 12 and 13, one char per int
( #string of closest integer diff between each weight:
("0x3221223xxxx5-11533xx051532414x12232323243436-142421x152".
"5242224233324232433201Cx15-17-17-1404151x-114-2D-9Dxxx10")
=~ s/x/13/gr #"13" is frequent, decompress all "x" into "13"
=~ /-?./g #split into 118 negative and positive ints,
#...one char each with a - in front for negative ints
)[1..pop]; #sum diffs only up to given input N popped from @_
$s #return sum
}
```
[Answer]
# GolfScript, score = (0 + 1) \* (10550.87 + 1) = 10551.87, 0 bytes
Not sure what's wrong
[Answer]
## [Pyt](https://github.com/mudkip201/pyt), 9 bytes, score ~141.372
```
37*ᵮ₄₅^2*
```
Port of [CursorCoercer's Pyth answer](https://codegolf.stackexchange.com/a/255551/56178)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 11 bytes, score ≈ 103.034
```
1.6*aE1.1
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCIxLjYqYUUxLjEiLCIiLCIiLCItcCAteCJd)
[Score calculation](https://dso.surge.sh/#@WyJwaXAiLCIiLCJsOnsxLjYqYUUxLjF9TShcXCwjYSkgbTokKyh7KGEtYikqKjJ9TVUobFphKSkvI2FcblAoXCJNZWFuIHNxdWFyZSBlcnJvciA9IFwiLm0pXG4oXCJTY29yZSA9IFwiLigxKyNcIjEuNiphRTEuMVwiKSooMSttKSlcbiIsIiIsIlsxLjAwNzk7NC4wMDI2OzYuOTQxOzkuMDEyMjsxMC44MTE7MTIuMDEwNzsxNC4wMDY3OzE1Ljk5OTQ7MTguOTk4NDsyMC4xNzk3OzIyLjk4OTc7MjQuMzA1OzI2Ljk4MTU7MjguMDg1NTszMC45NzM4OzMyLjA2NTszNS40NTM7MzkuOTQ4OzM5LjA5ODM7NDAuMDc4OzQ0Ljk1NTk7NDcuODY3OzUwLjk0MTU7NTEuOTk2MTs1NC45Mzg7NTUuODQ1OzU4LjkzMzI7NTguNjkzNDs2My41NDY7NjUuMzk7NjkuNzIzOzcyLjY0Ozc0LjkyMTY7NzguOTY7NzkuOTA0OzgzLjg7ODUuNDY3ODs4Ny42Mjs4OC45MDU5OzkxLjIyNDs5Mi45MDY0Ozk1Ljk0Ozk4OzEwMS4wNzsxMDIuOTA1NTsxMDYuNDI7MTA3Ljg2ODI7MTEyLjQxMTsxMTQuODE4OzExOC43MTsxMjEuNzY7MTI3LjY7MTI2LjkwNDU7MTMxLjI5MzsxMzIuOTA1NTsxMzcuMzI3OzEzOC45MDU1OzE0MC4xMTY7MTQwLjkwNzc7MTQ0LjI0OzE0NTsxNTAuMzY7MTUxLjk2NDsxNTcuMjU7MTU4LjkyNTM7MTYyLjU7MTY0LjkzMDM7MTY3LjI1OTsxNjguOTM0MjsxNzMuMDQ7MTc0Ljk2NzsxNzguNDk7MTgwLjk0Nzk7MTgzLjg0OzE4Ni4yMDc7MTkwLjIzOzE5Mi4yMTc7MTk1LjA3ODsxOTYuOTY2NTsyMDAuNTk7MjA0LjM4MzM7MjA3LjI7MjA4Ljk4MDQ7MjA5OzIxMDsyMjI7MjIzOzIyNjsyMjc7MjMyLjAzODE7MjMxLjAzNTk7MjM4LjAyODk7MjM3OzI0NDsyNDM7MjQ3OzI0NzsyNTE7MjUyOzI1NzsyNTg7MjU5OzI2MjsyNjE7MjYyOzI2NjsyNjQ7Mjc3OzI2ODsyODE7MjgyOzI4NTsyODY7Mjg5OzI5MDsyOTM7Mjk0OzI5NF0iLCItcCAteCJd)
Better score thanks to @Neil
Blatantly stole the best fit for \$a∗n^b\$ from [@97.100.97.109's answer](https://codegolf.stackexchange.com/a/255560/110555), but adapted for a better score. The full list can be calculated [here](https://dso.surge.sh/#@WyJwaXAiLCIiLCJ7MS42KmFFMS4xfU0oXFwsMTE4KSIsIiIsIiIsIi1wIC14Il0=)
[Answer]
## Python 3: Length = 16, Error ≈ 12.97, Score ≈ 237.48
A simple linear approximation.
```
lambda x:2.6*x-9
```
[Answer]
# [Bash + qalc], 47 bytes, Score 169.036
```
LANG=en qalc -t "atom($1;mass)/u"|sed s/±.*//
```
qalc is a CLI based interface of qalculate!, which allows us to extract certain properties of atoms `atom(...;mass)` will provide us the atomic mass of the n-th element. We divide the result by `u` to get a numeric value without unit (`u`). The result may have an uncertainty, notated by `±...`, so we use `sed` to remove such parts. The decimal separator will depend on your locale. While comma could be disabled by setting an option it is shorter to change the locale in case. `-t` or `--terse` is required to prevent printing of the input query, thus the use of `LANG=en`. If we do not care for portability and assume a decimal point locale we can omit the first 8 bytes. If we do not care about uncertainties printed in the output we can remove the last 13 bytes.
Further if we assume the input has been injected before by
`variable q ...` we can directly use `LANG=en qalc -t -f file` to achieve:
# [qalc], 14 bytes, 52.824
```
atom(q;mass)/u
```
Note that this method differs somewhat from the given list for some period 7 block d elements, namely Lawrencium-Meitnerium or 103-109. This is because qalculate gives us the usual standard value, which is the mass of most stable known isotope. These elements are incredibly unstable and will decay in at most a few seconds. Thus they do not have some sort of "natural average" atomic weight, as they do not exist in nature. The values given in this list belong to less stable isotopes of these elements. If we adapt the list the score would of course improve drastically to 54.324 or 16.976.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1), score 101.61232686228814
```
ѽ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=0b0&input=WzEsMiwzLDQsNSw2LDcsOCw5LDEwLDExLDEyLDEzLDE0LDE1LDE2LDE3LDE4LDE5LDIwLDIxLDIyLDIzLDI0LDI1LDI2LDI3LDI4LDI5LDMwLDMxLDMyLDMzLDM0LDM1LDM2LDM3LDM4LDM5LDQwLDQxLDQyLDQzLDQ0LDQ1LDQ2LDQ3LDQ4LDQ5LDUwLDUxLDUyLDUzLDU0LDU1LDU2LDU3LDU4LDU5LDYwLDYxLDYyLDYzLDY0LDY1LDY2LDY3LDY4LDY5LDcwLDcxLDcyLDczLDc0LDc1LDc2LDc3LDc4LDc5LDgwLDgxLDgyLDgzLDg0LDg1LDg2LDg3LDg4LDg5LDkwLDkxLDkyLDkzLDk0LDk1LDk2LDk3LDk4LDk5LDEwMCwxMDEsMTAyLDEwMywxMDQsMTA1LDEwNiwxMDcsMTA4LDEwOSwxMTAsMTExLDExMiwxMTMsMTE0LDExNSwxMTYsMTE3LDExOF0tbVI)
[Score calulation](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=MTE49V/RvcPtWzEuMDA3OSw0LjAwMjYsNi45NDEsOS4wMTIyLDEwLjgxMSwxMi4wMTA3LDE0LjAwNjcsMTUuOTk5NCwxOC45OTg0LDIwLjE3OTcsMjIuOTg5NywyNC4zMDUsMjYuOTgxNSwyOC4wODU1LDMwLjk3MzgsMzIuMDY1LDM1LjQ1MywzOS45NDgsMzkuMDk4Myw0MC4wNzgsNDQuOTU1OSw0Ny44NjcsNTAuOTQxNSw1MS45OTYxLDU0LjkzOCw1NS44NDUsNTguOTMzMiw1OC42OTM0LDYzvTQ2LDY1LjM5LDY5LjcyMyw3Mi42NCw3NC45MjE2LDc4Ljk2LDc5LjkwNCw4My44LDg1LjQ2NzgsODcuNjIsODguOTA1OSw5MS4yMjQsOTIuOTA2NCw5NS45NCw5OCwxMDEuMDcsMTAyLjkwNTUsMTA2LjQyLDEwNy44NjgyLDExMi40MTEsMTE0LjgxOCwxMTguNzEsMTIxLjc2LDEyNy42LDEyNi45MDQ1LDEzMS4yOTMsMTMyLjkwNTUsMTM3LjMyNywxMzguOTA1NSwxNDAuMTE2LDE0MC45MDc3LDE0NC4yNCwxNDUsMTUwLjM2LDE1MS45NjQsMTU3vCwxNTguOTI1MywxNjK9LDE2NC45MzAzLDE2N7w5LDE2OC45MzQyLDE3My4wNCwxNzQuOTY3LDE3OC40OSwxODAuOTQ3OSwxODMuODQsMTg2LjIwNywxOTAuMjMsMTkyLjIxNywxOTUuMDc4LDE5Ni45NjY1LDIwML05LDIwNC4zODMzLDIwNy4yLDIwOC45ODA0LDIwOSwyMTAsMjIyLDIyMywyMjYsMjI3LDIzMi4wMzgxLDIzMS4wMzU5LDIzOC4wMjg5LDIzNywyNDQsMjQzLDI0NywyNDcsMjUxLDI1MiwyNTcsMjU4LDI1OSwyNjIsMjYxLDI2MiwyNjYsMjY0LDI3NywyNjgsMjgxLDI4MiwyODUsMjg2LDI4OSwyOTAsMjkzLDI5NCwyOTRdJy0gbXAyCnggL1VsClbEICoz)
Logically identical to [this Jelly answer](https://codegolf.stackexchange.com/a/255527/71434) (and some others), but shockingly 1 byte shorter for a decent score.
Explanation:
`Ñ` and `½` are "shortcuts" in Japt, meaning they get expanded before transpiling. `Ñ` becomes `*2`, while `½` becomes `.5`. As a result, this effectively becomes the program `*2.5`, which mulitplies the input by 2.5.
[Answer]
# [Desmos](https://www.desmos.com), 27 bytes, score ≈ 149.312
```
f(x)=211sin(.0132x-.87)+162
```
[Try it on Desmos!](https://www.desmos.com/calculator/oxe6zj1mcq) A sine wave solution, created by optimizing the following regression:
```
asin([1...118]b+c)+d~[1.0079,4.0026,6.941,9.0122,10.811,12.0107,14.0067,15.9994,18.9984,20.1797,22.9897,24.305,26.9815,28.0855,30.9738,32.065,35.453,39.948,39.0983,40.078,44.9559,47.867,50.9415,51.9961,54.938,55.845,58.9332,58.6934,63.546,65.39,69.723,72.64,74.9216,78.96,79.904,83.8,85.4678,87.62,88.9059,91.224,92.9064,95.94,98,101.07,102.9055,106.42,107.8682,112.411,114.818,118.71,121.76,127.6,126.9045,131.293,132.9055,137.327,138.9055,140.116,140.9077,144.24,145,150.36,151.964,157.25,158.9253,162.5,164.9303,167.259,168.9342,173.04,174.967,178.49,180.9479,183.84,186.207,190.23,192.217,195.078,196.9665,200.59,204.3833,207.2,208.9804,209,210,222,223,226,227,232.0381,231.0359,238.0289,237,244,243,247,247,251,252,257,258,259,262,261,262,266,264,277,268,281,282,285,286,289,290,293,294,294][1...118]
```
The regression yields values of `211.205`, `0.0131883`, `-0.871366`, and `162.758` for `a`, `b`, `c`, and `d`, respectively.
] |
[Question]
[
Your task is to generate boxes using any one ASCII character with respect to the inputs given.
# Test Cases
```
1 1 --> =====
= =
=====
1 2 --> =========
= = =
=========
2 1 --> =====
= =
=====
= =
=====
2 2 --> =========
= = =
=========
= = =
=========
2 5 --> =====================
= = = = = =
=====================
= = = = = =
=====================
```
# Input
* Input can be taken from one of the following
+ `stdin`
+ Command-line arguments
+ Function arguments (2 arguments, one for each number)
* Input, if taken from `stdin` or command line arguments, will contain two positive integers, seperated by a space.
* The two numbers denote the number of boxes in each column and row
# Output
* Boxes must be outputted in `stdout` (or closest equivalent)
* Each box should have three horizontal spaces in them
# Rules
* Both the numbers will be greater than 0, but will not go beyond 1000
* Any visible character can be used for outputting the boxes. (as long as they aren't too harsh on the eye!)
* You are permitted to write a full program or a function.
* There should be no unnecessary characters except an optional trailing newline character.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) wins.
[Answer]
# Pyth, 23 bytes
```
Mjbmsm@"= "&%k4dh*4HhyG
```
Defines the function `g` which works as desired.
[Demonstration.](https://pyth.herokuapp.com/?code=Mjbmsm%40%22%3D%20%22%26%25k4dh*4HhyGg2%205&debug=0)
[Answer]
# [Retina](https://github.com/mbuettner/retina), 57 bytes
```
1(?=.* (1*))
$1#$1#
1(?=(1*#1*#)*$)
=
1
====
#
=#
```
Takes input in unary with a trailing newline.
Each line should go to its own file and `#` should be changed to newline in the files. This is impractical but you can run the code as is as one file with the `-s` flag, keeping the `#` markers (and changing the trailing newline to `#` in the input too). You can change the `#`'s back to newlines in the output for readability if you wish. E.g.:
```
> echo -n 11 111#|retina -s boxes|tr # '\n'
=============
= = = =
=============
= = = =
=============
```
Method: 5 single substitution steps. The first two (first 4 lines) creates an `2*N+1` by `M` grid of ones and the next 3 steps (6 lines) format it into the desired output.
The intermediate strings (delimited by `-`'s):
```
11 111
------------------
111
111
111
111
111
------------------
111
111
111
111
111
------------------
111
= = =
111
= = =
111
------------------
============
= = =
============
= = =
============
------------------
=============
= = = =
=============
= = = =
=============
```
[Answer]
# JavaScript (*ES6*), 83
A function with parameters rows and columns. Using template strings, there are 2 embedded newlines that are significant and counted.
Output via `alert` (popup).
As `alert` use a proportional font, we get a better result using a letter with a width similar to the space instead of `=`.
Test in Firefox using the console to have the real `alert` output, or run the snippet below.
```
f=(r,c)=>{for(x=y="|";c--;)x+="||||",y+=" |";for(o=x;r--;)o+=`
${y}
`+x;alert(o)}
// TEST
// redefine alert to avoid that annoying popup during test
alert=x=>O.innerHTML=x
test=_=>([a,b]=I.value.match(/\d+/g),f(a,b))
test()
```
```
<input id=I value='2 3'><button onclick="test()">-></button>
<pre id=O></pre>
```
[Answer]
# JavaScript (ES6), ~~75~~ 73
Using copious `repeat` calls, we repeat `|`, then repeat `|` with trailing spaces, and repeat both of those repeats to make rows:
```
f=(y,x)=>alert(((s="|"[r="repeat"](x*4)+`|
`)+"| "[r](x)+`|
`)[r](y)+s)
```
(Newlines are significant, per edc65's suggestion to use template strings.)
Snippet:
```
<input id="x" type="range" max="10" min="1" step="1" value="3"><input id="y" type="range" max="10" min="1" step="1" value="2"><pre id="o"></pre><script>function f(y,x){return ((s="|"[r="repeat"](x*4)+"|\n")+"| "[r](x)+"|\n")[r](y)+s};function redraw(){document.getElementById("o").innerHTML=f(document.getElementById("y").value,document.getElementById("x").value)};document.getElementById("x").onchange=redraw;document.getElementById("y").onchange=redraw;document.getElementById("x").oninput=redraw;document.getElementById("y").oninput=redraw;redraw();</script>
```
Without template strings, without method-name reuse, and with added whitespace:
```
f=(y,x)=>alert(
(
(s="|".repeat(x*4)+"|\n") +
"| ".repeat(x)+"|\n"
).repeat(y)+s
)
```
(Using [edc65's recommendation](https://codegolf.stackexchange.com/a/51565/7796) to use `|` for better visual spacing.)
[Answer]
# Pip, ~~29~~ 24 = 23 + 1 bytes
Requires the `-n` flag. Takes the height and width as command-line args and builds boxes of of `1`s.
```
([1X4m]XbRLa+1)@<v.1R0s
```
Explanation:
```
a,b are cmdline args; m is 1000; v is -1; s is " " (implicit)
[1X4m] List containing 1111 and 1000
Xb String repetition of each element b times
RLa+1 Repeat the list a+1 times
( )@<v Now we have one row too many at the end, so take everything
but the last item (equiv to Python x[:-1])
.1 Concatenate a 1 to the end of each row
R0s Replace 0 with space
Print, joining list on newlines (implicit, -n flag)
```
This program takes heavy advantage of the fact that strings are numbers and numbers are strings in Pip. (And the three spaces in those boxes happened to be just right to take advantage of the built-in `m` variable!)
Here's how the list gets built with the input `2 3`:
```
[1111;1000]
[111111111111;100010001000]
[111111111111;100010001000;111111111111;100010001000;111111111111;100010001000]
[111111111111;100010001000;111111111111;100010001000;111111111111]
[1111111111111;1000100010001;1111111111111;1000100010001;1111111111111]
[1111111111111;"1 1 1 1";1111111111111;"1 1 1 1";1111111111111]
```
And the final output:
```
C:\> pip.py 2 3 -ne "([1X4m]XbRLa+1)@<v.1R0s"
1111111111111
1 1 1 1
1111111111111
1 1 1 1
1111111111111
```
[More on Pip](http://github.com/dloscutoff/pip)
[Answer]
## Perl, ~~72~~ ~~63~~ ~~52~~ 50 bytes
My shortest version yet uses `$/` to get a newline char more compactly:
```
$ perl -e 'print((($,="="." ="x pop.$/)=~s/./=/gr)x(1+pop))' 2 5
=====================
= = = = = =
=====================
= = = = = =
=====================
```
The previous update puts the mostly empty lines in the output record separator `$,`, and prints a list of continuous lines.
```
$ perl -e 'print((($,="="." ="x pop."\n")=~s/./=/gr)x(1+pop))' 2 5
```
The previous version might be a bit clearer for the casual reader:
```
$ perl -E 'say($y=($x="="." ="x pop)=~s/./=/gr);for(1..pop){say$x;say$y}' 2 5
```
The first version used `@ARGV` instead of `pop`:
```
$ perl -E 'say($y=($x="="." ="x$ARGV[1])=~s/./=/gr);for(1..$ARGV[0]){say$x;say$y}' 2 5
```
[Answer]
# Python 2, ~~58~~ 57 Bytes
Fairly straightforward implementation.
```
def f(x,y):a="="*(4*y+1);print(a+"\n="+" ="*y+"\n")*x+a
```
[Check it out here.](http://ideone.com/EXXCox)
*Thanks to Sp3000 for saving one byte.*
[Answer]
# GNU sed -r, 160
Sigh, I thought this would be smaller, but here it is anyway. Unfortunately sed regexes don't have any lookaround capability.
```
:
s/(.*)1$/ =\1/;t
s/([= ]+)/\1\n\1/
:b
s/ (.*\n)/===\1/;tb
s/(1*)1 $/\n\1/
:c
s/([^\n]*\n[^\n]*\n)(1*)1$/\1\1\2/;tc
s/(=+)(.*)/\1\2\1/
s/(^|\n)(.)/\1=\2/g
```
Taking input as unary from STDIN:
```
$ sed -rf boxes.sed <<< "11 111"
=============
= = = =
=============
= = = =
=============
$
```
[Answer]
# CJam, 25 bytes
```
q~)S3*'=5*+4/f*3f>\)*1>N*
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~)S3*'%3D5*%2B4%2Ff*3f%3E%5C)*1%3EN*&input=2%205).
### How it works
```
q~ e# Read H and W from STDIN.
S3*'=5*+ e# Push " =====".
4/ e# Chop into [" =" "===="].
) f* e# Repeat each string W+1 times.
3f> e# Cut off the first three characters.
\)* e# Repeat the resulting array H+1 times.
1> e# Remove the first string.
N* e# Join the lines.
```
[Answer]
# Marbelous, 168 bytes
This answer only works up to 255x255, not 1000x1000, due to limitations of the Marbelous language. I'm working on a 32-bit library, but it's not going to be ready any time soon.
Input is provided as two command line parameters or function parameters to the main board.
```
@2@3}1@0
SLEL//>0\/
@3@1}0--
}1&0@0/\&0
@1/\@2}1\/
:SL
..}0@0
&0/\>0&0
EN..--\/
{0@0/\ES
:EL
..@0
..>0EN
}0--\/
@0/\EX
:EX
}0
\/3D3D3D3D
:ES
}0
\/3D202020
:EN
}0
{03D0A
```
Pseudocode:
```
MB(H,W):
EL(W)
for 1..H:
SL(W)
EL(W)
EL(W):
for 1..W:
EX()
EN()
SL(W):
for 1..W:
ES()
EN()
EX():
print "===="
ES():
print "= "
EN():
print "=\n"
```
[Answer]
# CJam ~~52~~ ~~51~~ ~~46~~ 41 bytes
```
l~:B;:A;'=:U{{U4*}B*N}:V~{U{SZ*U}B*NUV}A*
```
Thanks to Sp3000 for -5 chars
Thanks to Martin Büttner♦ for another 5 chars
[Try it](http://cjam.aditsu.net/#code=l%7E%3AB%3B%3AA%3B%27%3D%3AU%7B%7BU4*%7DB*N%7D%3AV%7E%7BU%7BSZ*U%7DB*NUV%7DA*&input=2%203)
[Answer]
# c function, 81
```
x,y;f(h,w){for(;y<=h*2;y++)for(x=0;x<w*4+2;x++)putchar(x>w*4?10:x&3&&y&1?32:61);}
```
### Test program:
```
x,y;f(h,w){for(;y<=h*2;y++)for(x=0;x<w*4+2;x++)putchar(x>w*4?10:x&3&&y&1?32:61);}
int main (int argc, char **argv)
{
f(2, 3);
}
```
[Answer]
# PHP4.1, ~~76~~ ~~71~~ 69 bytes
This is as golfed as I can get.
```
$R=str_repeat;echo$R(($T=$R('-',4*$H+1))."
|{$R(' |',$H)}
",$V),$T;
```
This expects the key `H` to have the number of lines and `V` the number of boxes per line.
I'm using `-` and `|` just so the boxes actually look like boxes. If required, I can change it to `=`. It doesn't matter the char that is used.
Leaving `-` and `|` also helps to understand the mess that's going on.
---
Old method, 76 bytes:
```
for($R=str_repeat;$H--;)echo$T=$R('-',($V*4)+1),"
|{$R(' |',$V)}
";echo$T;
```
---
Example of output:
```
http://localhost/file.php?H=2&V=3
-------------
| | | |
-------------
| | | |
-------------
```
[Answer]
# Julia, 59 bytes
```
(n,m)->(l="="^(4m+1)*"\n";print(l*("="*" ="^m*"\n"*l)^n))
```
This creates an unnamed function that accepts two integers as input and prints the result to STDOUT. To call it, give it a name, e.g. `f=(n,m)->...`.
Ungolfed + explanation:
```
function f(n, m)
# Store the solid row
l = "="^(4m + 1) * "\n"
# Print all rows by repeating a pattern n times
print(l * ("=" * " ="^m * "\n" * l)^n)
end
```
Examples:
```
julia> f(2, 3)
=============
= = = =
=============
= = = =
=============
julia> f(1, 5)
=====================
= = = = = =
=====================
```
Any suggestions are welcome.
[Answer]
# bash + coreutils, 57
```
dc -e"2do$2 4*1+^1-pd8*F/1+$1si[fli1-dsi0<c]dscx"|tr 0 \
```
This uses `dc` to print binary numbers that have `1`s for the box edges and `0`s for the spaces.
* the all-ones number **X** is calculated by `2 ^ (width * 4 + 1) - 1`, then pushed and printed
* the `10001...0001` number is calculated by **`X`**`* 8 / 15 + 1`, then pushed
* the stack is then dumped `height` times
The `tr` then converts the `0`s to space characters.
### Output
```
$ ./boxes.sh 2 4
11111111111111111
1 1 1 1 1
11111111111111111
1 1 1 1 1
11111111111111111
$
```
[Answer]
# R, ~~83~~ 81
As an unnamed function taking h and w as parameters.
Builds the 1st and second lines into a vector for each row and replicates it `h` times. Appends a vector for the bottom line and `cat`s out the vector using `fill` to restrict the length of the lines. Now takes advantage of the any visible character rule.
```
function(h,w)cat(rep(c(A<-rep(1,w*4+2),rep(' 1',w)),h),A[-1],fill=w*4+1,sep='')
```
Test run
```
> f=function(h,w)cat(rep(c(A<-rep(1,w*4+2),rep(' 1',w)),h),A[-1],fill=w*4+1,sep='')
> f(4,2)
111111111
1 1 1
111111111
1 1 1
111111111
1 1 1
111111111
1 1 1
111111111
>
```
[Answer]
# Python ~~3~~ 2, ~~160~~ ~~87~~ ~~85~~ 79 bytes
I know this can be golfed a ***lot*** more, I would like some suggestions as this is my first try at golfing.
```
def d(x,y):
for i in[1]*x:print'='*(4*y+1)+'\n'+'= '*(y+1)
print'='*(4*y+1)
```
Thanks to @Cool Guy and @Sp3000's tips, I narrowed the size down to just ~~above~~ below half.
Eg: d(3,3)
```
=============
= = = =
=============
= = = =
=============
= = = =
=============
```
[Try it out here](http://ideone.com/KyKaXo).
Excuse the trailing whitespaces.
[Answer]
# KDB(Q), 37 bytes
```
{(3+2*x-1)#(5+4*y-1)#'(4#"=";"= ")}
```
# Explanation
```
(4#"=";"= ") / box shape
(5+4*y-1)#' / extend y axis
(3+2*x-1)# / extend x axis
{ } / lambda
```
# Test
```
q){(3+2*x-1)#(5+4*y-1)#'(4#"=";"= ")}[2;5]
"====================="
"= = = = = ="
"====================="
"= = = = = ="
"====================="
```
[Answer]
# JavaScript, ~~92~~ 85 bytes
I had hoped this would be shorter than the other JS answer (nice work as always, edc65), but oh well. I have a feeling the math here can be further golfed.
```
f=(r,c)=>(x=>{for(i=s='';(y=i++/x)<r-~r;)s+=i%x?' *'[-~y%2|!(-~i%4)]:'\n'})(4*c+2)||s
```
[Answer]
# Octave, ~~69~~ ~~65~~ 64
```
y=ones([2,4].*input()+1);y(1:2:end,:)=y(:,1:4:end)=4;char(y+31)
```
Thanks to DLosc for pointing out issues that led to -1
Takes input as `[1 1]` and outputs:
```
#####
# #
#####
```
You can also just input '1' and get 1x1. If the input really needs to be `1 1`, the size goes up to **~~88~~ ~~85~~ 84**:
```
y=ones([2,4].*eval(['[',input(0,'s'),']'])+1);y(1:2:end,:)=y(:,1:4:end)=4;char(y+31)
```
Note: Matlab doesn't allow Octave's chaining or input(integer), but here is the Matlab version (**67**):
```
y=ones([2,4].*input('')+1);y(1:2:end,:)=4;y(:,1:4:end)=4;char(y+31)
```
[Answer]
# C, 76 bytes
```
w,n;f(r,c){for(w=c*4+2,n=w*r*2+w;n--;)putchar(n%w?n/w%2&&n%w%4-1?32:61:10);}
```
Invoked as a function with number of rows and columns as arguments. For example:
```
f(5, 2)
```
[Answer]
# CJam, ~~30~~ 29 bytes
New version with redundant `+` at the end removed (thanks, Dennis):
```
l~_4*)'=*N+:F\'=S3*+*'=+N++*F
```
I know that Dennis already posted a CJam solution that beats this by miles. But this is my very first attempt at CJam, so it's a miracle that it works at all. :)
Fairly brute force. Builds the first line from `4 * H + 1` `=` signs, then the second line from `=` repeated `H` times, with another `=` added. Then concatenates the two lines, repeats the whole thing `V` times, and then adds another copy of the first line.
It feels like I have way too many stack manipulations, and even ended up storing the first line in a variable because I had to shuffle stuff around on the stack even more otherwise.
Not very elegant overall, but you have to start somewhere... and I wanted to try a simple problem first.
[Answer]
# CJam, 23
```
q~[F8]f{2b*1+' f+N}*_0=
```
[Try it online](http://cjam.aditsu.net/#code=q~%5BF8%5Df%7B2b*1%2B'%20f%2BN%7D*_0%3D&input=3%205)
**Explanation:**
```
q~ read and evaluate the input (height width)
[F8] make an array [15 8] - 1111 and 1000 in base 2
f{…} for width and each of [15 8]
2b convert the number to base 2
* repeat the digits "width" times
1+ append a 1 to the array of digits (right edge)
' f+ add the space character to each digit (0->' ', 1->'!')
N push a newline
* repeat the resulting array "height" times
_0= copy the first line (bottom edge)
```
[Answer]
# Dart, 57
```
b(y,x,{z:'='}){z+=z*4*x;print('$z\n=${' ='*x}\n'*y+z);}
```
Try it at: <https://dartpad.dartlang.org/36ed632613395303ef51>
[Answer]
## Java, 181
I hope that according to
>
> You are permitted to write a full program or a function.
>
>
>
it is compliant to the rules to count the bytes of the *function*, which is 181 in this case
```
import static java.lang.System.*;
public class Boxes
{
public static void main(String[] args)
{
Boxes b=new Boxes();
System.out.println("1,1:");
b.b(1,1);
System.out.println("1,2:");
b.b(1,2);
System.out.println("2,1:");
b.b(2,1);
System.out.println("2,2:");
b.b(2,2);
System.out.println("2,5:");
b.b(2,5);
}
void b(int R, int C){String s="",e=s,x,y,z=s,a="====",n="=\n";int r,c;for(r=R;r-->0;){x=y=e;for(c=C;c-->0;){x+=a;y+="= ";}s+=x+n+y+n;}for(c=C;c-->0;){z+=a;}s+=z+n;out.println(s);}
}
```
[Answer]
# C#, ~~153~~ ~~151~~ 150
This can't really compete but here it is just for fun:
```
(h,w)=>{string s="=",e="\n",a="====",b=" =",m=a,o;int i=0,j;for(;i++<=h*2;){o=s;for(j=0;j++<w+1;o=m)System.Console.Write(o);m=m==a?b:a;s=e+s;e="";}}
```
How to run:
```
public class Program
{
public static void Main()
{
new System.Action<int, int>((h,w)=>{string s="=",e="\n",a="====",b=" =",m=a,o;int i=0,j;for(;i++<=h*2;){o=s;for(j=0;j++<w+1;o=m)System.Console.Write(o);m=m==a?b:a;s=e+s;e="";}})(3, 4);
}
}
```
Open for improvements.
[Answer]
# Python 2.7, 66 bytes.
I know there are already better solutions in python, but that's the best I came up with.
```
def f(x,y):a,b,c="="*4," =","\n=";print "="+a*y+(c+b*y+c+a*y)*x
```
Example:
```
f(3,4)
=================
= = = = =
=================
= = = = =
=================
= = = = =
=================
```
[Answer]
## Ruby, ~~57~~ ~~48~~ 45
```
f=->h,w{l=?=*w*4+?=;(l+$/+'= '*w+"=
")*h+l}
```
Usage:
```
print f[2,5]
```
Thanks to manatwork for saving 3 bytes.
[Answer]
# Java, ~~123~~ 119 bytes
```
void p(int h,int w){String b="=",d="\n=";for(;w-->0;d+=" =")b+="====";for(d+="\n"+b;h-->0;b+=d);System.out.print(b);}
```
Abusing the input parameters as counters greatly helped in decreasing code size.
Thanks to Cool Guy for suggesting the abuse of for syntax.
[Answer]
# SAS, 117 119
```
macro a array a[0:1]$4('# ' '####');do x=1 to 2+2*&x-1;t=repeat(a[mod(x,2)],&y-1);put t $char%%eval(&y*3). '#';end;%
```
Example:
```
%let x=4;
%let y=4;
data;a;run;
```
Result:
```
#############
# # # #
#############
# # # #
#############
# # # #
#############
# # # #
#############
```
] |
[Question]
[
Take an array of nonnegative integers, such as `[1, 0, 0, 1, 2, 4, 2, 0]`. Then, draw that as a mountain where the integers represent altitude:
```
x
x x
x x
xx x
```
You may use any printable non-whitespace character in place of `x`, and adding padding or whitespace after lines or the output is fine (but not required). You may optionally take one indexed inputs. Transposing the output is not allowed, but returning an array of lines is fine.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) per language wins.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 4 bytes
```
×꘍R§
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C3%97%EA%98%8DR%C2%A7&inputs=%5B1%2C%200%2C%200%2C%201%2C%202%2C%204%2C%202%2C%200%5D&header=&footer=)
That's right, it's flagless.
## Explained
```
×꘍ # [(n * " ") + "*" for n in input]
R # [x[::-1] for x in ^]
§ # vertically join (rotate) ^
```
Using the `L` flag would make it 3 bytes.
[Answer]
# [Python 2](https://docs.python.org/2/), 66 bytes
```
a=input()
n=max(a)
while~n:print''.join(' x'[x==n]for x in a);n-=1
```
[Try it online!](https://tio.run/##HcbBCkBAFEbhvae4u5kphKzoPoksZkGu@GfSyNh49SF1@jr@DotDk5JlgT@DNhl4t1Fbk12LbNODzh@CoFS5OoFWFNUQmTHO7qBIArKmR8F1SkOdU/X3TZNT@1uNLw "Python 2 – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 5 bytes
```
$úζR»
```
[Try it online!](https://tio.run/##MzBNTDJM/f9f5fCuc9uCDu3@/z/aUEfBAIyADCMdBRMwaRALAA "05AB1E (legacy) – Try It Online")
```
$ # push "1" and the input
ú # for each integer in the input,
# pad "1" with this many spaces in the front
ζ # tranpose, padding with spaces
R # reverse, the mountains should not be upside down
» # join by newlines
```
[Answer]
# [Zsh](https://www.zsh.org/), ~~66~~ 63 bytes
```
s=${(l/${${(On)@}[1]}*#/)}
for x;s[++i+$#s-#*x]=.
fold -$#<<<$s
```
[Attempt This Online!](https://ato.pxeger.com/run1=m724qjhjwYKlpSVpuhY37YttVao1cvRVqoGUf56mQ220YWytlrK-Zi1XWn6RQoV1cbS2dqa2inKxrrJWRaytHlA4J0VBV0XZxsZGpRhiDNS0HdFGOgqGYARkGOsomIJJw1ioPAA)
-3 thanks to JoKing, but still probably too long.
Explanation:
* `${${(On)@}[1]}`: get the maximum input
* `s=${(l/*#/)}`: construct a string of spaces which is (number of inputs) × (maximum of inputs) in length
* `for x;s[++i+$#s-#*x]=.`: set the correct index of the string to a `.` for each element
* `fold -$#<<<$s`: line-wrap the string at (number of inputs) in length
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 18 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⊖⍉⍕⍪'x',¨⍨⍵⍴¨' '}
```
```
{ ⍝ Open function
⊖⍉ ⍝ Flip diagonally and then vertically
⍕ ⍝ Make table into multiline string
⍪ ⍝ Display one element per row
'x',¨⍨ ⍝ Append an 'x' to each element
⍵⍴¨' ' ⍝ Duplicate each space 'input' times
} ⍝ Close function
```
[Try it on online!](https://razetime.github.io/APLgolf/?h=AwA&c=q37UNe1Rb@ej3qmPelepV6jrHFrxqBeItj7q3XJohbqCei0A&f=e9Q39VHbhDQFQwUDIDRUMFIwAWIDAA&i=AwA&r=tio&l=apl-dyalog&m=dfn&n=%E2%8E%95)
[Answer]
# [Red](http://www.red-lang.org), 91 bytes
```
func[a][i: last sort copy a until[forall a[prin either a/1 = i[1][sp]]print""0 > i: i - 1]]
```
[Try it online!](https://tio.run/##FYyxCsMwDAX3fsUje6hdMgXaj@gqNIjEoQLHNrYy9Otdl@Omg6th7@@wE99OW/txpY2ESVdEaYaWq2HL5QvBlUwjHblKjBAqVROC2idUyN3jCSXP1ArzP9k0ObwwRooZnrmfBvJwA48HlqHj/gM "Red – Try It Online")
-6 bytes from Galen Ivanov.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Ṭ€z0Ṛo⁶
```
[Try it online!](https://tio.run/##y0rNyan8///hzjWPmtZUGTzcOSv/UeO2/48aZhxuj/x/dNLDnTP@RxvqKBiAEZBhpKNgAiYNYgE "Jelly – Try It Online")
Outputs a list of lines. +1 byte (append `Y`) if unacceptable.
Takes input 1 indexed, uses `1` as the mountain character
## How it works
```
Ṭ€z0Ṛo⁶ - Main link. Takes a list L on the left
€ - Over each element in L:
Ṭ - Untruthy; Map each n to [0, 0, ..., 1] with n-1 zeros
z0 - Transpose, padding with zeros
Ṛ - Reverse
o⁶ - Replace 0s with spaces
```
[Answer]
# [J](http://jsoftware.com/), 17 bytes
```
[:|.@|:' x'#~,.&1
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o61q9BxqrNQVKtSV63T01Az/a3L5OekpOObk5heXKJTnF2UX6ygklZYo5OWD9FeoV9fZxljV6XFxpSZn5CukKRgCjQQjIMNIR8EETBr8BwA "J – Try It Online")
+6 thanks to Lynn for spotting a bug in the original solution: `' x'{~=\:~.` This approach can be made to work but it's no longer golfy: `' x'{~]=/~[:i.1-@+>./`
## how
* `,.&1` Zip input with 1:
```
1 1
0 1
0 1
1 1
2 1
4 1
2 1
0 1
```
* `' x'#~` Duplicate `' x'` according to these pairs
```
x
x
x
x
x
x
x
x
```
* `[:|.@|:` Rotate left:
```
x
x x
x x
xx x
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
=ⱮṀṚo⁶
```
A monadic Link that accepts a list of positive integers (the 1-indexed option) and yields a list of lists of characters and integers (`1` being the choice for `x`).
**[Try it online!](https://tio.run/##y0rNyan8/9/20cZ1D3c2PNw5K/9R47b/h9sj//@PNtJRMAQjIMNYR8EUTBrGAgA "Jelly – Try It Online")** (The footer joins with newlines and then Jelly's implicit, smashing print produces the output.)
### How?
```
=ⱮṀṚo⁶ - Link: list of integer heights, H
Ṁ - maximum (H) -> M
Ɱ - map across (h in [1..M]) with:
= - (H) equals (h) (vectorises)
Ṛ - reverse -> X
⁶ - space character
o - (X) logical OR (' ') (vectorises)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes
```
↑EA◧xι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMqtEBHwTexQMMzr6C0RENTRyEgMcUnNa1EQ6lCSUchU1NT0/r//@hoIx0FQzACMox1FEzBpGFs7H/dshwA "Charcoal – Try It Online") Link is to verbose version of code. 1-indexed. Explanation:
```
A Input array
E Map over elements
x Literal string `x`
◧ Left-padded to width
ι Current element
↑ Print rotated
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
1-indexed, using `"` for the peaks.
```
£QùXÃÕÔ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=o1H5WMPV1A&input=WzIsIDEsIDEsIDIsIDMsIDUsIDMsIDFd)
```
£QùXÃÕÔ :Implicit input of array
£ :Map each X
Q : Quotation mark
ùX : Left pad with spaces to length X
à :End map
Õ :Transpose
Ô :Reverse
:Implicit output joined with newlines
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 51 bytes
```
->a{(-a.max..0).map{|y|a.map{|x|x==-y ??x:' '}*''}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6xWkM3US83sUJPz0ATSBdU11TWJEIYFTUVtra6lQr29hVW6grqtVrq6rW1/wtKS4oV0qKjDXUUDMAIyDDSUTABkwaxsf8B "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 67 bytes
```
lambda x:[[v==i and'*'or' 'for v in x]for i in range(max(x),-1,-1)]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCKjq6zNY2UyExL0VdSz2/SF1BPS2/SKFMITNPoSIWxMwEMYsS89JTNXITKzQqNHV0DYFIM/Y/XDZNI9pQR8EAjIAMIx0FEzBpEKtpxaUABAVFmXklGpma/wE "Python 3 – Try It Online")
`for i in range(max(x),-1,-1)` -> identify how high the mountain will be, max value is first line (top), so start from max, iterate to 0
`[v==i and'*' or' ' for v in x]` -> for every integer in input set it as \* if height matches current line, set it whitespace otherwise.
[EDIT] as per @hyper-neutrino suggestion to get 3 bytes less, and wrapped in lambda as per @Razetime comment
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~11~~ 9 bytes
-2 bytes through auto-vectorizing
```
ð*×+ðÞṪṘ⁋
```
```
ð* # vectorised n spaces
×+ # append "*"
ðÞṪ # transpose with space as filler
Ṙ⁋ # reverse and join by newline
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C6%9B%C3%B0*%C3%97%2B%3B%C3%B0%C3%9E%E1%B9%AA%E1%B9%98%E2%81%8B&inputs=%5B1%2C%200%2C%200%2C%201%2C%202%2C%204%2C%202%2C%200%5D&header=&footer=)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~77~~ ~~74~~ ~~73~~ 70 bytes
-1 thanks to @RecursiveCo.
-3 thanks to @m90's idea
```
a=>{for(i=Math.max(...a);i;i--)console.log(a.map(e=>i^e&&' ').join``)}
```
[Try it online!](https://tio.run/##JYtRCsIwEESvsl9tgs3Sin8luYEnEKVLTXRLzZY2iCCePdYKw/Bg3gz0pKWfeUomytXnXuKSIICFTNa9g8yK7ZHSHR/0UohIuuWWjdE/U0aPo9wUreukvHV88UVRQqlxEI5dpz85qFNTQb1lhX0Fh63r8/8E1oHfNVrnLw "JavaScript (Node.js) – Try It Online")
Takes one-indexed input.
[Answer]
# [R](https://www.r-project.org/), 65 bytes
```
function(a)for(i in max(a):0)cat(c(' ','x')[1+(a==i)],'
',sep='')
```
[Try it online!](https://tio.run/##NY2xCsMwDER3f4U2SVSDUzIV9CWlgzANaIgcUgfy964JBI7j3fJu72s9opmH9uWI0rwGGS91JwcPWO0c85W5WKNCCCh4Ir@nB5mq80cwofy@myJyNy00CeQrA54C89WZ0/0zdKn/AQ "R – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes
```
Print@@@Table[" "Unitize[#+i],{i,-Max@#,0}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6AoM6/EwcEhJDEpJzVaSUEpNC@zJLMqNVpZOzNWpzpTR9c3scJBWcegNlbtf5pDtaGOARAa6hjpmACxQe1/AA "Wolfram Language (Mathematica) – Try It Online")
Prints the mountain, using `0` instead of `x`.
Remove the `Print@@@` for -8 bytes if an array of characters and numbers is acceptable output.
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, 43 bytes
```
@(x)flip([accumarray([x find(x)],3)+32 ''])
```
Anonymous function that inputs a 1-based column vector and outputs a char matrix with `#` and
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzLSezQCM6MTm5NDexqCixUiO6QiEtMy8FKBWrY6ypbWykoK4eq/k/TSPayFrBEIyADGNrBVMwaQiUAwA "Octave – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-l`, 10 bytes
```
R:sXg.0ZDs
```
Takes the integers as command-line arguments. Outputs using `0` in place of `x`. [Try it here!](https://replit.com/@dloscutoff/pip) Or, here's an 11-byte equivalent in Pip Classic: [Try it online!](https://tio.run/##K8gs@P8/KMyqOCJdzyDKpfj/f0MuAyA05DLiMgFig/@6RTkA "Pip – Try It Online")
### Explanation
```
g is list of cmdline args; s is space (implicit)
sXg Convert each arg to a string of that many spaces
.0 Append 0 to each string of spaces
ZDs Transpose, extending shorter strings with a default value of space
R: Reverse the resulting list
Autoprint, one row per line (-l flag)
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 7 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
{ ×x+]↶
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjVCJTIwJUQ3eCV1RkYwQiV1RkYzRCV1MjFCNg__,i=JTVCMSUyQyUyMDAlMkMlMjAwJTJDJTIwMSUyQyUyMDIlMkMlMjA0JTJDJTIwMiUyQyUyMDAlNUQ_,v=8)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
```
_.tm+*;
```
[Try it here!](http://pythtemp.herokuapp.com/?code=_.tm%2B%2a%3B&input=%5B1%2C+0%2C+0%2C+1%2C+2%2C+4%2C+2%2C+0%5D&debug=0)
] |
[Question]
[
The partition number of a positive integer is defined as the number of ways it can be expressed as a sum of positive integers. In other words, the number of integer partitions it has. For example, the number `4` has the following partitons:
```
[[1, 1, 1, 1], [1, 1, 2], [1, 3], [2, 2], [4]]
```
Hence, it has `5` partitions.
This is [OEIS A000041](https://oeis.org/A000041).
---
# Task
Given a positive integer **N** determine its partition number.
* 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 wins.
---
# Test Cases
```
Input | Output
1 | 1
2 | 2
3 | 3
4 | 5
5 | 7
6 | 11
7 | 15
8 | 22
9 | 30
10 | 42
```
[Answer]
## Mathematica, 11 bytes
```
PartitionsP
```
## Explanation
```
¯\_(ツ)_/¯
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 3 bytes
```
l./
```
**[Try it here!](https://pyth.herokuapp.com/?code=l.%2F&input=4&debug=0)** or **[Try a test Suite.](https://pyth.herokuapp.com/?code=l.%2F&input=4&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15&debug=0)**
The answer took much longer to format than writing the code itself :P.
---
# How?
Pyth is the right tool for the job.
```
l./ Full program with implicit input.
./ Integer partitions. Return all sorted lists of positive integers that add to the input.
l Length.
Implicitly output the result.
```
[Answer]
# [Emojicode](http://www.emojicode.org/) 0.5, ~~204~~ 201 bytes
```
üêãüöÇüçáüêñüÖ∞Ô∏è‚û°üöÇüçáüç䂨Öüêï1üçáüçé1üçâüçÆs 0üîÇk‚è©0üêïüçáüç¶t‚ûñüêïküçÆr tüîÇi‚è©1 tüçáüçäüòõüöÆt i 0üçáüçÆ‚ûïr iüçâüçâüçÆ‚ûïs‚úñrüÖ∞Ô∏èküçâüçé‚ûósüêïüçâüçâ
```
[Try it online!](https://tio.run/##VU/NSsNAEL73KaZ3D8l79OArRLvQNSYLu1uKNy0USaWNYBuDShYhFASJ3uzz7Au4b9DObJaKh2Vnvvl@ZlgmrvilGLPDwZnHB2de5s6s7rGunFl8/@5L27z/oaul/VzgcBuHfk1Fga9TEDmzmae2/IiIEQg7bZuK@pRIEjSROJJiKntPZ@pXzOg0cDLxYGebrQQe3IuAKPtWybBYGvC1bZ5VSPRcvKS8I5sB0AJKo2Lzgw8Pqb/wb8@vWaIYsFwzCQnk0@yCEan1iiWpEKOzUQxx1JvhrL7tbfwCSMGZl1Du039WO2KJzGE2SfQpArg6gxsxhUxIkQ9PicXA7x1HRw "Emojicode – Try It Online")
-3 bytes by using "less than or equal to 1" instead of "less than 2" because the "less than" emoji has a quite long UTF-8 encoding. Also made `t` a frozen to silence a warning without affecting the byte count.
Extends the üöÇ (integer) class with a method named üÖ∞Ô∏è. You can write a simple program that takes a number from the input, calls üÖ∞Ô∏è on the number and prints the result like this:
```
üèÅüçá
üç¶strüî∑üî°üòØüî§Please enter a numberüî§
üçäüç¶numüöÇstr 10üçá
üòÄüî°üÖ∞Ô∏ènum 10
üçâüçìüçá
üòÄüî§Learn what a number is, you moron!üî§
üçâ
üçâ
```
This part could be golfed a lot by omitting the messages and error handling, but it's not included in the score, so I prefer to show more features of Emojicode instead, while improving readability along the way.
### Ungolfed
```
üêãüöÇüçá
üêñüÖ∞Ô∏è‚û°üöÇüçá
üçä‚óÄÔ∏èüêï2üçá
üçé1
üçâ
üçÆsum 0
üîÇk‚è©0üêïüçá
üç¶nmk‚ûñüêïk
üçÆsig nmk
üîÇi‚è©1 nmküçá
üçäüòõüöÆnmk i 0üçá
üçÆ‚ûïsig i
üçâ
üçâ
üçÆ‚ûïsum‚úñsigüÖ∞Ô∏èk
üçâ
üçé‚ûósumüêï
üçâ
üçâ
```
### Explanation
**Note:** a lot of emoji choice doesn't make much sense in emojicode 0.5. It's 0.x, after all. 0.6 will fix this.
Emojicode is an object-oriented programming language featuring generics, protocols, optionals and closures, but this program uses no closures and all generics and protocols can be considered implicit, while the only optional appears in the I/O stub.
The program operates on only a few types: üöÇ is the integer type, üî° is the string type and ‚è© is the range type. A few booleans (üëå) appear too, but they are only used in conditions. Booleans can take a value of üëç or üëé, which correspond to true and false, respectively.
There are currently no operators in Emojicode, so addition, comparsions and other operations that are normally operators are implemented as functions, effectively making the expressions use [prefix notation](https://en.wikipedia.org/wiki/Polish_notation). Operators are also planned in 0.6.
Let's tackle the test program first.
```
üèÅ
```
This is the üèÅ block, which can be compared to main from other languages.
```
üçá ... üçâ
```
Grapes and watermelons declare code blocks in emojicode.
```
üç¶strüî∑üî°üòØüî§Please enter a numberüî§
```
This declares a "frozen" named `str` and sets it value to a new string created using the initializer (constructor) üòØ, which takes a prompt as a string and then inputs a line from the user. Why use a frozen instead of a variable? It won't change, so a variable would emit a warning.
```
üçäüç¶numüöÇstr 10
```
Let's break it down. `üöÇstr 10` calls the üöÇ method on the `str` frozen with the argument 10. By convention, methods named with the name of a type convert the object to that type. 10 is the base to use for integer conversion. This method returns an optional, `üç¨üöÇ`. Optionals can contain a value of the base type or nothingness, ‚ö°. When the string doesn't contain a number, ‚ö° is returned. To use the value, one has to unwrap the optional using üç∫, which raises a runtime error if the value is ‚ö°. Therefore, it is good practice to check for nothingness before unwrapping an optional. It is so common, in fact, that Emojicode has a shorthand for that. Normally, `üçä` is an "if". `üçäüç¶ variable expression` means: evaluate the expression. If the optional contains nothingness, the condition evaluates to üëé (false). Otherwise, a frozen named `variable` is created with the unwrapped value of the optional, and the condition evaluates to üëç, (true). Therefore, in normal usage, the `üçá ... üçâ` block following the conditional is entered.
```
üòÄüî°üÖ∞Ô∏ènum 10
```
üÖ∞Ô∏è is the method the main code adds to üöÇ using üêã that calculates the number of partitions. This calls üÖ∞Ô∏è on the `num` frozen we declared in the conditional and converts the result to a string using base 10 by the üî° method. Then, üòÄ prints the result.
```
üçìüçá ... üçâ
```
üçì means "else", so this block is entered when the user did not enter a number correctly.
```
üòÄüî§Learn what a number is, you moron!üî§
```
Prints the string literal.
Now, let's look at the main program. I'll explain the ungolfed version; the golfed version just had the whitespace removed and variables renamed to single letter names.
```
üêãüöÇüçá ... üçâ
```
Extend the üöÇ class. This is a feature that is not commonly found in programming languages. Instead of creating a new class with üöÇ as the superclass, üêã modifies üöÇ directly.
```
üêñüÖ∞Ô∏è‚û°üöÇüçá ... üçâ
```
Creates a new method named üÖ∞Ô∏è that returns a üöÇ. It returns the number of partitions calculated using the formula `a(n) = (1/n) * Sum_{k=0..n-1} sigma(n-k)*a(k)`
```
üç䂨Öüêï1üçá
üçé1
üçâ
```
üêï is similar to `this` or `self` from other languages and refers to the object the method was called on. This implementation is recursive, so this is the terminating condition: if the number the method was called on is less than or equal 1, return 1.
```
üçÆsum 0
```
Create a new variable `sum` and set it to 0. Implicitly assumes type üöÇ.
```
üîÇk‚è©0üêï
```
üîÇ iterates over anything that implements the üîÇüêö‚ö™Ô∏è protocol, while ‚è© is a range literal that happens to implement üîÇüêöüöÇ. A range has a start value, a stop value and a step value, which is assumed to be 1 if `start < stop`, or -1 otherwise. One can also specify the step value by using the ‚è≠ to create the range literal. The start value is inclusive, while the stop value is exclusive, so this is equivalent to `for k in range(n)` or the `Sum_{k=0..n-1}` in the formula.
```
üç¶nmk‚ûñüêïk
```
We need to calculate sigma(n - k), or the sum of divisors of `n - k` in other words, and the argument is needed a few times, so this stores `n - k` in the variable `nmk` to save some bytes.
```
üçÆsig nmk
üîÇi‚è©1 nmk
```
This sets the `sig` variable to the argument of sigma and iterates over all numbers from 1 to `nmk - 1`. I could initialize the variable to 0 and iterate over 1..nmk but doing it this way is shorter.
```
üçäüòõüöÆnmk i 0
```
üöÆ calculates the remainder, or modulus and üòõ checks for equality, so the condition will be üëç if `i` is a divider of `nmk`.
```
üçÆ‚ûïsig i
```
This is an assignment by call, similar to the `+= -= >>=` operator family in some of the inferior, emoji-free languages. This line can be also written as `üçÆ sig ‚ûï sig i`. Therefore, after the inner loop finishes, `sig` will contain the sum of divisors of `n - k`, or `sigma(n - k)`
```
üçÆ‚ûïsum‚úñsigüÖ∞Ô∏èk
```
Another assignment by call, so this adds `sigma(n - k) * A(k)` to the total, just as in the formula.
```
üçé‚ûósumüêï
```
Finally, the sum is divided by n and the quotient is returned. This explanation probably took thrice as much time as writing the code itself...
[Answer]
# [Python 2](https://docs.python.org/2/), 85 83 bytes
-2 bytes thanks to @notjagan
```
lambda n:n<1or sum(sum(i*((n-k)%i<1)for i in range(1,n+1))*p(k)for k in range(n))/n
```
[Try it online!](https://tio.run/##TYs7DsIwEAV7TrENym4IH1NG4SY0RvxWxi@WYwoUcnYT00Dxmpl54ZXuPfY5HI75Yf3pbAktOtNHGp6ey7RmxtrJUjsj11koKSha3C5sGqyMSB3YfZX7KYhskQvEf09mJ@2CKERFomqc6E3jVG3m0NvEaCiUa/4A "Python 2 – Try It Online")
Using recursive formula from [OEIS A000041](https://oeis.org/A000041).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~54~~ 53 bytes
```
f=lambda n,k=1:1+sum(f(n-j,j)for j in range(k,n/2+1))
```
[Try it online!](https://tio.run/##RYxBDoIwFAXXeoq3IbThE/O7JMG71EiRIg9SYOHpa125msVkZvscr5Uu59C//fJ4elDmXjtt9nMxwbCNEm1YEyImInmOg5mFN9eotfkn@BcqULXd9bKliQfqyp1o7yioUcFQUI4l@wI "Python 2 – Try It Online")
### How it works
Each partition of **n** can be represented as a list **x = [x1, ⋯, xm]** such that **x1 + ⋯ + xm = n**. This representation becomes unique if we require that **x1 ≤ ⋯ ≤ xm**.
We define an auxiliary function **f(n, k)** that counts the partitions with lower bound **k**, i. e., the lists **x** such that **x1 + ⋯ + xm = n** and **k ≤ x1 ≤ ⋯ ≤ xm**. For input **n**, the challenge thus asks for the output of **f(n, 1)**.
For positive integers **n** and **k** such that **k ≤ n**, there is at least one partition with lower bound **k**: the singleton list **[n]**. If **n = k** (in particular, if **n = 1**), this is the *only* eligible partition. On the other hand, if **k > n**, there are no solutions at all.
If **k < n**, we can recursively count the remaining partitions by building them from left to right, as follows. For each **j** such that **k ≤ j ≤ n/2**, we can build partitions **[x1, ‚ãØ, xm] = [j, y1, ‚ãØ, ym-1]**. We have that **x1 + ‚ãØ + xm = n** if and only if **y1 + ‚ãØ + ym-1 = n - j**. Furthermore, **x1 ‚â§ ‚ãØ ‚â§ xm** if and only if **j ≤ y1 ‚â§ ‚ãØ ‚â§ ym-1**.
Therefore, the partitions **x** of **n** that begin with **j** can be calculated as **f(n - j, j)**, which counts the valid partitions **y**. By requiring that **j ≤ n/2**, we assure that **j ≤ n - j**, so there is at least one **y**. We can thus count *all* partitions of **n** by summing **1** (for **[n]**) and **f(n - j, j)** for all valid values of **j**.
The code is a straightforward implementation of the mathematical function **f**. In addition, it makes **k** default to **1**, so `f(n)` computes the value of **f(n, 1)** for input **n**.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 8 bytes
```
numbpart
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D@vNDepILGo5H9afpFGHlDEUEfB0EBHoaAoM68EKKCkoGsHJNI08jQ1Nf8DAA "Pari/GP – Try It Online")
[Answer]
## [Retina](https://github.com/m-ender/retina), 34 bytes
```
.+
$*
+%1`\B
;$'¶$`,
,
%O`1+
@`.+
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLS1vVMCHGictaRf3QNpUEHS4dLi5V/wRDbS6HBD3t//8NuYy4jLlMuEy5zLjMuSy4LLkMDQA "Retina – Try It Online")
### Explanation
```
.+
$*
```
Convert the input to unary.
```
+%1`\B
;$'¶$`,
```
This computes all **2n-1** partitions of the unary digit list. We do this by repeatedly (`+`) matching the first (`1`) non-word boundary (`\B`, i.e. a position between two `1`s) in each line (`%`) and replacing it with `;`, everything after it (`$'`), a linefeed (`¶`), everything in front of it (`$``) and `,`. Example:
```
1;1,111
```
Becomes
```
vv
1;1,1;11
1;1,1,11
^^^^^
```
Where `v` marks the result of `$'` and `^` marks the result `$``. This is a common idiom to get the result of two different replacements at once (we basically insert both the `;` and the `,` replacement, as well as the missing "halves" of the string to complete two full substitutions).
We will treat `;` as actual partitions and `,` just as placeholders that prevent subsequent `\B` from matching there. So next...
```
,
```
... we remove those commas. That gives us all the partitions. For example for input `4` we get:
```
1;1;1;1
1;1;11
1;11;1
1;111
11;1;1
11;11
111;1
1111
```
We don't care about the order though:
```
%O`1+
```
This sorts the runs of `1`s in each line so we get unordered partitions.
```
@`.+
```
Finally, we count the unique (`@`) matches of `.+`, i.e. how many distinct lines/partitions we've obtained. I added this `@` option ages ago, then completely forgot about it and only recently rediscovered it. In this case, it saves a byte over first deduplication the lines with `D``.
[Answer]
# [Python 2](https://docs.python.org/2/), 89 bytes
-9 bytes by Mr.Xcoder
-1 byte by notjagan
```
lambda n:len(p(n))
p=lambda n,I=1:{(n,)}|{y+(x,)for x in range(I,n/2+1)for y in p(n-x,x)}
```
[Try it online!](https://tio.run/##RcyxCsIwEIDhvU9xW@/oFW3GQNwLfQSXiFUP6jWEDgm1zx6tIK4fP3/Iy2NWUwZ3LpN/Xq4e1E6jYkAlqoL7Ifeusysq0/Zac4OJ6TZHSCAK0et9xJ71YJruy3nnz6JNnGgrO8m/NEeyFYQouoBw3Z5qHlCovAE "Python 2 – Try It Online")
[Answer]
# Octave, 18 bytes
```
partcnt(input(''))
```
Uses the built-in function partcnt.
Can't get it right by using an anonymous function using @, some help would be appreciated.
[Answer]
# [J](http://jsoftware.com/), ~~37~~ 35 bytes
```
0{]1&((#.]*>:@#.~/.~&.q:@#\%#),])1:
```
[Try it online!](https://tio.run/##y/r/P03B1krBoDrWUE1DQ1kvVsvOykFZr05fr05NrxDIjFFV1tSJ1TS04uJKTc7IV9DQ0UtTMtBUsLNSyNRTMDT4/x8A)
## Explanation
```
0{]1&((#.]*>:@#.~/.~&.q:@#\%#),])1: Input: n
1: Constant 1
] Get n
1&( ) Repeat n times on x = [1]
\ For each prefix
# Length
q:@ Prime factors
/.~& Group equal factors
#.~ Compute p+p^2+...+p^k for each group
>:@ Increment
&.q: Product
% Divide
# Length
] Get x
* Times
1 #. Sum
, Joim
] Get x
Set this as next value of x
0{ Select value at index 0
```
[Answer]
# Regex `üêá` ([RME](https://github.com/Davidebyzero/RegexMathEngine/) / Perl / PCRE2 v10.35+), ~~13~~ 12 bytes
```
((\1|^)x*)+$
```
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Unordered-partitions-PerlPCRE2) - RegexMathEngine
[Try it online!](https://tio.run/##RU9BasMwELznFYtYgra2E7mQS2TFDqTXnnprUpGaBARq4souuCjqsQ/oE/sRV3ELvSw7s7M7s83B2cXw8g7oJHh7rvcWcC4jVMVm/bBehcnx7Di2SshiJcmDOUZEvnHm1AHbnpgMUFnVNtZ0nGUsbd@e2y6u6DTL05wOr1dR@c@KyNMSNcnrrTY67l1li1vylX3MdypWsZNhAjA6mz8CTaFGQeyShDzWMRJw1rMeDamPOS@X6IiXpU8SrFMR6PpHO52OUcek8Y1cwm90NDMG359fwGZYR@EljkLQ@u5@o/XA@Ta/PFF/QwkOg8gW4gc "Perl 5 – Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=RU-xTsMwEBVrN_7Ask6VTZLWQUJCddykUlmZ2GixStRIlkwb4lQKcs3IB7CydGg3voiRL8FJKrHc3Xv37u7d17FcV_rwc3H58oag4sjqbb7SCMbcQ5HMZw-zqRsU24qAEYwnU04tUoVH1JaV2tQILzaYO5RpYUqtaoIjHJrds6n9iAyjOIzp-rUVpf8s8zydgKS83WX8xVWV6eSa2kw_xkvhI1tyN0Cou6zOBKhEdAJfBQG1kHtLiOAGN6CoeB-TdAIVJWlqgwDykDna_mGGw85q59S_EXPUWwc1wuj34xPhEeReuPct56S8u59LedrVRXT7Tcgi3j_R5ooG0FOHczqy6Ib19R8 "Perl - Attempt This Online") - Perl v5.36+
[Attempt This Online!](https://ato.pxeger.com/run?1=hVZLb9tGED4W0K8YM629K1Gp6CCBIZo2HFmADSR2oMhoGlslaHIpLUItCXIZP1pf-wN67aWH9tb8oPbYv9FLZx-SaEtACYvax8w3r29G_vVLXGR1pT7hNI6_XDrdrIhLttvdcyZ_jZ4lLOWCwbvBaLgbDs6Ph-HF2ek4_O70eHwCe61nXMRZnTDY10rPZweteBaVEBaXEwhg5Ly-ufl0_aL-_u7uw3j26mZG_qhl2t37k5Ar76cf6G2bdr42R39_9S99Ku240C6CsOh4fsNUJUsupsrW6ozneMqi-cGa3EGLCwkFLmXIyjIvSZyLSoL2sz1nVRVNGYUfK5n0-zFKwP4-2GO11OdMJJkPJZN1KcDzH9Yw1T7OE-bCdZ5nkAdplFUKVpuxcJe7L19N_Bbgw1MgOmXhlFmM0EoRg0NMzi8GJ0ejvTa1ly5U_J7lKVk6_u3ipCFPKdVW1ENyODRBxHktoQ_LQKkKz9FqoD3og_MkeK3sOKjlXAmHLvORIl9mJpJlUloPrVpUfCpYAlkupuYVieqGlb5O2PwujKMsQzds7HYXXmd5_AnasQufc55AO4lkhLlTSVJLCAIg6qZNt1cY1GJ3OsvK9Gxl5hEXBAG0g8UlEiFjghS0602Cnm9CMOyAIg4ccth3fFx1gsJ8OZQcDvCzRfG8RsQXu6HEoqKugp_iQkM3gbgoaqnUdWBYQmiXbLGfRzKehTqW9mpt0EpW1Zl0TQl822rvTz8O9UmaVgwvMV4MYSpnjwTa-WcWS9SylcCWW9ifFzxjxJLi_bvxiBbx8zhEZwl1LcbH4eg8HA9Hb0_PjsbD48Xx8MN4eHas9tvaJ_ttPenRFYO3SiSgzX2zG_TbyjVCD9ayEeI-kixMy3weFpGUrBSkRJafXbx5YwGaOti6kt1KTOJiFWy6t7BkDQUjWFJwAeE2eOlu4tlTAGMq43PeBOl61G8IJayQ_ytUsrguK56LjYLabJqXoKfL_ZK5ODEyHMrENDIXruEe9ReM1-VBFdHD9EQy50QLLMqP9ReeC0Ve4bW5wSGfkJ3ujjWqHuGp3KLMVtDkeb8v1OHhBlzoaPkOeBQHhuitsMysVeYEuzG7S-F1vImPw2aOmSCVCzu3O8oxTFCFl5Ogob9MAg-E6sH9QHg-dDq8GfGClPcU0CllhOxcCQwJU4fSmp8pcb5J4J-ffwH8aeF4ZUYIOtawZnpJNeVjdmliNjsKnebYEPpvxWlc2zJSf805g7vfg-1ta2MrsF03Gp2PwrPzt0fjwQl9pKjp12ivxcSQZc2e2GD4q7Omu5r-OL9txBsmuXoeWqv3psZKS8bIKr71hjYCyz1tTkRziTNjObBNJPjTYf4H-O33Xvdlz6z_Aw "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+
Takes its input in unary, as the length of a string of `x`s. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)
This simply enumerates all the partitions. In order to count unordered partitions, it enforces that partitions occur in strictly nondecreasing order. This is accomplished by starting with an arbitrary-sized partition on the first iteration, and adding an arbitrary nonnegative integer to the partition size on each iteration. At the end, `$` asserts that the cumulative sum is equal to the input number.
```
# tail = N = input number; no need to anchor, because the
# following loop is forced to do at least one iteration,
# and its first iteration has an anchor.
( # \1 = sum of the following:
(
\1 # Previous value of \1, if set
| # or
^ # 0, if this is the first iteration
)
x* # Any arbitrary nonnegative integer
)+ # Iterate the above any positive number of times
$ # Assert tail == 0
```
Alternative 12 bytes:
```
(\1x*|^x*)+$
```
[Try it online!](https://tio.run/##RU9BasMwELznFYtYghTbiVzIJbJiB9JrT701qUhNAgI1cSUXXBT12Af0if2IKzuFXpad2dmd2eZozbJ//QC0Ary51AcDuBARymK7edysw@R0sRSd5KJYC@ZBnyJivrH63ALZnYkIUBnpGqNbSjKSuvcX18YVlWZ5mrPj2yAq/1keebZCxcRwy0XHg61Mccd8ZZ7yvYyV70WYAIzO@o9AXchRELskYR7rGAko6UiHmsnPBS1XaBktS58kWKc8sOEPN52OUcek8Y1cwC066jmBn69vIHOso/AaRyEodf@wVaqnu7ybXZ@7GUuw73m25L8 "Perl 5 – Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=RU-xTsMwEBVrN_7gZFlV3CStg4SE6rhJpbIysdFilaiRLJk22KkU5JqRD2Bl6VA2voiRL8FJKrHc3Xv37u7d56naaHX8ubh8fgWsGVi1K9YK8IR5yNPF_H4-c4NypwNsOGXpjBELsvSI2ErLbQ1ouUXMQa64qZSsAxSjyOyfTO1HRBQnUUI2L60o-2ep58kUC8LaXcZfXOtcpVfE5uohWXEf6Yq5AUB3WZ4JLFPeCXwVhsTiwluCADWowZLwt0mQTbEmQZbZMMRFRB1p_zDDYWe1c-rfSBj01rEcI_h9_wA0xoUXHnzLOSFu7xZCfO3rMr75DpZJMzo8NiMS4p46ntOJxte0r_8A "Perl - Attempt This Online") - Perl v5.36+
[Try it online!](https://ato.pxeger.com/run?1=hVZLb9tGED4W0K8YM629S1Gp6CCBIZo2HFmADSRyoMhoGlklaHIpEaGWBLmMH62v_QG99tJDe2t-UHvs3-ilsw9JtCWghEXtY-ab1zcj__olKrK6kp9gFkVfJlYnK6KS7XcOrOlfo2cxS1LO4F1_NNgP-heng-ByeD4Ovjs_HZ_BQetZyqOsjhkcKqXn86NWNA9LCIrJFHwYWa9vbj5dv6i_v7v7MJ6_upmTP2qRdA7-JFfurf3TD7c2bX-tj_7-6l_6VNpywC78oGi7XsNUJcqUz6St9Vma4ykLF0cbcketlAsocCkCVpZ5SaKcVwKUn_aCVVU4YxR-rETc60UoAYeHYI7lUp0zHmcelEzUJQfXe9jAlPsoj5kD13meQe4nYVZJWGXGwE32X76aei3AJ02AqJQFM2YwAiNFNA7ROb_sn52MDmxqLh2o0nuWJ2Tl-LfLk4Y8pVRZkQ_J4VgHEeW1gB6sAqUyPEupgfKgB9aT4JWyZaGWdcUtuspHgnyZ60hWSWk9tGpepTPOYshyPtOvkFc3rPRUwhZ3QRRmGbphYje74DrLo09gRw58ztMY7DgUIeZOJkkuwfeByBub7q4xqMFut1eV6ZrKLMKUEwRQDhYTJELGOClox536XU-HoNkBReRb5Lhnebhq-4X-sig57uNnh-J5jYgv9gOBRUVdCT_DhYJuAqW8qIVUV4FhCcEu2XK_CEU0D1Qs9nqt0UpW1ZlwdAk802rvzz8O1EmSVAwvMV4MYSbmjwTs_DOLBGqZSmDLLe0vijRjxJDi_bvxiBbR8yhAZwl1DMbHwegiGA9Gb8-HJ-PB6fJ48GE8GJ7K_a7yyXwbT7p0zeCdEgloct_sBvU2co3Q_Y1sBLgPBQuSMl8ERSgEKzkpkeXDyzdvDEBTB1tXsFuBSVyu_G33BpZsoGAEKwouIZwGL51tPHsKoE1l6SJtgnRc6jWEYlaI_xUqWVSXVZrzrYLKbJKXoKbL_Yq5ODEyHMpEN3LKHc096i0Zr8qDKryL6QlFnhIlsCw_1p-7DhR5hdf6Bod8TPY6e8aofLgrc4syO36T570el4fHW3ChreTb4FIcGLy7xtKzVprj7EbvJtxtu1MPh80CM0EqB_Zu96RjmKAKL6d-Q3-VhNTnsgcPfe560G6nzYiXpLyngE5JI2TvimNImDqUVvxMiPVNDP_8_AvgT0uKV3qEoGMNa7qXZFM-ZpciZrOj0OkUG0L9rTmNa1NG6m04p3EPu7C7a2zs-KbrRqOLUTC8eHsy7p_RR4qKfo32Wk4MUdbsiQ2Gvzobuuvpj_PbRLxlksvnobV-b2uspGSMrOPbbGgtsNrT5kTUlzgzVgNbR4I_Hfp_gN9-73ZedvX6Pw "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+
# Regex `üêá` (Raku`:P5`), 13 bytes
```
^(\1x*|^x+)*$
```
[Try it online!](https://tio.run/##K0gtyjH7X1qcquDr7@ftGmmt4Brm6KMQGF2cWKmgraGhXqFeoRKvWVeXa5VaYRVgqh@rUKegYpuWmZdZnAFkBkbrayqk5RcpxBkbWMdac0Fl/sdpxBhWaNXEVWhraqn8/w8A "Perl 6 – Try It Online")
```
^ # tail = N = input number
( # \1
# If on an iteration after the first:
\1x* # \1 += {any arbitrary nonnegative integer}; tail -= \1
|
^ # Anchor to start, to assert this is the first iteration.
x+ # \1 = {any arbitrary positive integer}; tail -= \1
)*
$ # Assert tail == 0
```
Raku's Perl 5 compatibility mode is rather inaccurate, and prevents the 12 byte regex from working, apparently because there is nothing preventing a zero-width match from looping infinitely.
# Regex `üêá` ([RME](https://github.com/Davidebyzero/RegexMathEngine/) / Perl / PCRE), ~~29~~ 20 bytes
```
((?=(\3|^))(\2x*))+$
```
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Unordered-partitions-PerlPCRE) - RegexMathEngine
[Try it online!](https://tio.run/##RU9BTsMwELz3FZa1qrwkaZ2iXuq4SaVy5cSNFKtErWTJtMEuUpBrjjyAJ/KR4AQkLqud2dmd2fZgzbJ/eSdgBfHm3OwNgbmIUBbbzcNmHSbHs2XgJBfFWqAn@hgR@tbq04XQ@kRFIJWRrjX6wmhGU/f27C5xRaVZnuZ4eB1E5T/LI48rUCiGWy467m1ligX6yjzmOxkr34kwIWR01n8E6EKOgtglCXpoYiTCaEc70Cg/5qxcgUVWlj5JoEl5wOEPN52OUcek8Y1ckN/ooGeUfH9@ETqDJgqvcRSCUnf3W6V6xkrJ6tvrEyKrF90NYgJ9z7Ml/wE "Perl 5 – Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=RU_NSsNAEMZrb77BsCxlxyRtUhGkm21SqNeevJm61NDAwtrGTQqRNB59AK9eeqhv4NN49EncJAUv8_PNNzPf93nKN0Yffy4un1-BGg613qVrDXTMbSvCxfx-PmsG2c4wWgifhzOONajMdljnRm1LIMmW8AZiLYpcq5IRj7jF_qko7Yp0vcANcPPSkqJ_1Lc4TqlE3t4q7Me1iXU4wTrWD8FK2OiveDMA6D6rM0BVKDqCrRwHa5paScBIRSqqULyNWTSlBlkU1Y5DU9dvsPVRDIed1E6ptRFw6KVTNSLw-_4BZERTSzzYUdNIebdcSPm1LzPv9puxSLDk-vCIyJJJdYXo0H50PKeT7934ff0H "Perl - Attempt This Online") - Perl v5.36+
**[Try it online!](https://tio.run/##fVRtb9MwEP7eX3ELbLWbdGpWgVDTbBpjiA9lQ9UmgdYSZa6TWkudyEnoXr/yA/iJ/BDKOW66jAFRmzjnu@eee@4clmXdmLHVCyFZUs44DDOm@O58v8XmoYIgu5iCD2Pr7XJ5ddkvv9zcfD6bv17OyYqQA59M@vdfKSWTvesOpfbLFf3Tz3Kgk/lBZrte6zFHXsxEqpM0TUrI@KlNpGjl4eK5335LyAIyXBYBVypVhKUyL6Ai3VnwPA9jTu8wz2DA0AGGQ1hb9bKyczlLPFC8KJUE13tolTIXseQzSFIZm1so8yVXXpVtcROwMEnSsiBao/oluExSdgUdRuHOuNv2BraHsFVsKCRBhxbglV1gEQmXJKNdd@r3PDCETGmQMd8iBwPLw5XtZ@ZhUXJwhP8tivYSIft7QQGpDtb4MS4q7CaQkFlZ6HDFoaO4B02NUJSsUCZa8bxMCrPWakZRzgsHsDhkGRdzs5N@46xI1UV/alIhqg9GiXSRiYSjLLsswOSEOvDpaHwcvDs9OxyN4N68nZ@9f@PAjslsFnWqHjWYIgKypTit9YuqFkcEy0JvBywNVHFUECKlKhy2ZwPYzicSh62BafKsgZsdQ9qPvTTbEeIRXeStVrQSMeZFIiQnZoaEdIye1EMft25lxRnDZA9BwyIVpHKqZUAdpOtAlua4bXYiIWek3W2veelLulpI9Nnym/0bDKQ2HvwFF@zK3wYkMsDkj1imuTqd5EvzdiFd2516OP8L1IXkDrSv25oYlpLj5tRvxG@EEL7UszX0peuBbYtmxXWnbikgKZ2EtCeybaRZy8e00HjUhL5Z8PP7D8DJNQcE2TVSmlnSE1jPE7/mjCjuwMn5aOQAMhY4ItVvPYQO9Kn3jI9BGfZgZ6dGREmr2Tsej0/Hwcnpx8Ozow/0SeTm2NSUrWM9X9ZTfJ7k/P9h69rqz0uUlPn8H1U2qn9omXs10wMzjIpzrIVuviLr89l6WPW6r3q/WJSEcb7qJlqs3w "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##hVXbbttGEH3XV4yZ1t6VqFSykcAQRQuOLMAGEjtQZDSNrRI0uZQWoZYEuYwvrV/7Af3EfkjV2Ysk2hJQwqb2MnPmdmYY5Xl7FkXLNzFLuGDweTgeHQbDq7NRcH15MQl@vTibnMNx4w0XUVrFDPp5VLDDt/OTRjQPCwjymyn4MHY@3N9/vzuqfnt8/DqZv7@fkyUhA5/cHv35O6Xk9vChSWnrpyV9Lee40Mz9IG91vZqRUhZczJSVzRnP8JSFi5MtuZMGFxJyXMqAFUVWkCgTpQTtYXPByjKcMQp/lDLu9SKUgH4f7LFa6nMm4tSDgsmqEND1nrcw1T7KYubCXZalkPlJmJYKVpuxcDeH795PvQbgwxMgOlnBjFmMwEoRg0NMtq@H56fj4ya1ly6U/IllCVk7/svqpCZPKdVW1EMyGJggoqyS0IN1oFSF52g10B70wHkVvFZ2HNRyboVD1/lI0qqcm0jWSWk8NypR8plgMaSZmJlXKMp7Vng6YYvHIArTFN2wsdtdcJdm0XdoRi78yHgMzTiUIeZOJUktwfeBqJsm3d9gUIvdaq0r07GVWYRcEATQDuY3SISUCZLTdnfqdzwTgmEH5JHvkEHP8XDV8nPz41AyGOL/HsXzChGPDgOJRUVdBT/DhYauA3GRV1Kp68CwhNAs2Gq/CGU0D3Qszc3aoBWsrFLpmhJ4tsm@XHwb6ZMkKRleYrwYwkzOXwg0sx8skqhlK4HNtrK/yHnKiCXFl8@TMc2jt1GAzhLqWoxvo/FVMBmNP11cnk5GZ6vj0dfJ6PJM7fe1T/bXetKhGwbvFUhAm/t6N@i3lauF7m9lI8B9KFmQFNkiyEMpWSFIgSy/vP740QLUdbB1JXuQmMTVyt91b2HJFgpGsKbgCsKt8dLdxbPXAMZUyhe8DtLuUq8mFLNc/q9QwaKqKHkmdgpqs0lWgJ4uT2vm4sRIcRwT08hcuIZ71FsxXpcHVUQH0xPKjBMtsCo/1l90XcizEq/NDY73mBy0D6xR9Yiuyi3K7Pl1nvd6Qh0OduBCS8u3oEtxYIjOBsvMWmVOsHuzuxHdVnfq4bBZYCZI6cLBw4FyDBNU4uXUr@mvk8B9oXqw74uuB60Wr0e8IuUTBXRKGSEHtwJDwtShtOZnQpyfY/jnr78BPy0cr8wIQcdq1kwvqaZ8yS5NzHpHodMcG0L/bTiNa1tG6m05Z3D7Hdjftzb2fNt14/HVOLi8@nQ6GZ7TF4qafrX2Wk0MWVTslQ2GX50t3c30x/ltI94xydXz3Ni8dzVWUjBGNvFtN7QRWO9pfSKaS5wZ64FtIsFPx7LTftf5N0rScFYu26nWaR//Bw "C++ (gcc) – Try It Online") - PCRE2 v10.33** / [Attempt This Online!](https://ato.pxeger.com/run?1=hVZLb9tGED4W0K8YM621K1GpZCOBIZo2HFuADSRyoMhoGlslaHIpLUItCXIZPxJf-wN67aWH9phb_0x77N_opbMPSbQloIRF7WPmm9c3I__6NcrTqlSfYBpFXy-dTppHBdvp7DmTv0bPYpZwweDt8WiwExyfnwyCi-HZOPjh7GR8CnuNZ1xEaRUz2NdKz2cHjWgWFhDklxPwYeS8urn5eL1b_Xh39348e3kzI39UMuns_UnIoU-udr_8RCm52rltUdr-1lz9_c2_9KmW40Ir94O83fNqJktZcDFVNldnPMNTFs4P1uQOGlxIyHEpA1YUWUGiTJQStL-tOSvLcMoofC5l3O9HKAH7-2CP1VKfMxGnHhRMVoWAnvewhqn2URYzF66zLIXMT8K0VLDajIW73HnxcuI1AB-eANGpC6bMYgRWihgcYnJ_cXx6NNprUXvpQsnvWZaQpePfL05q8pRSbUU9JINDE0SUVRL6sAyUqvAcrQbagz44T4LXyo6DWs6VcOgyHwnyZmYiWSal8dCoRMmngsWQZmJqXqEob1jh6YTN74IoTFN0w8Zud8F1mkUfoRW58CnjMbTiUIaYO5UktQTfB6JuWnR7hUEtdru9rEzXVmYeckEQQDuYXyIRUiZITju9id_1TAiGHZBHvkMO-46Hq7afmy-HksNj_GxRPK8QcXcnkFhU1FXwU1xo6DoQF3kllboODEsIrYIt9vNQRrNAx9JarQ1awcoqla4pgWdb7t3Zh4E-SZKS4SXGiyFM5eyRQCv7xCKJWrYS2HoL-_Ocp4xYUrx7Ox7RPHoeBegsoa7F-DAYnQfjwejN2fBoPDhZHA_ejwfDE7Xf1j7Zb-tJl64YvFUgAW3u692g31auFrq_lo0A96FkQVJk8yAPpWSFIAWyfHjx-rUFqOtg60p2KzGJi5W_6d7CkjUUjGBJwQWEW-Olu4lnTwGMqZTPeR2k06NeTShmufxfoYJFVVHyTGwU1GaTrAA9Xe6XzMWJkeJwJqaRuXAN96i3YLwuD6qILqYnlBknWmBRfqy_6LmQZyVemxsc9jFpdprWqHpET-UWZbb8Os_7faEODzfgQlvLt6FHcWCI7grLzFplTrAbs7sUvXZv4uGwmWMmSOlC87apHMMElXg58Wv6yyRwX6ge3PdFz4N2m9cjXpDyngI6pYyQ5pXAkDB1KK35mRDnuxj--fkXwJ8WjldmhKBjNWuml1RTPmaXJma9o9Bpjg2h_1acxrUtI_XWnDO4-13Y3rY2tnzbdaPR-SgYnr85Gh-f0keKmn619lpMDFlU7IkNhr86a7qr6Y_z20a8YZKr56Gxem9qrKRgjKziW29oI7Dc0_pENJc4M5YD20SCPx3mf4Dffu92XnTN-j8 "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+
PCRE1, and PCRE2 up to v10.34, automatically makes any capture group atomic if it contains a nested backreference. To work around this, the capture is copied between `\2` and `\3` using only forward-declared backreferences.
This would also make the regex compatible with Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) and Ruby, but they have no way of doing `üêá` output without source code modifications.
```
# tail = N = input number; no need to anchor, because the
# following loop is forced to do at least one iteration,
# and its first iteration has an anchor.
(
(?=
( # \2 = the following:
\3 # Previous value of \3, if \3 is set
| # or
^ # 0, if on the first iteration
)
)
( # \3 = the following, which is also subtracted from tail:
\2x* # \2 plus any arbitrary nonnegative integer
)
)+ # Iterate the above as many times as possible, minimum 1
$ # Assert tail == 0
```
# [Perl](https://www.perl.org/), ~~37~~ 36 bytes (full program)
```
1x<>~~/((\1|^).*)+$(??{++$i})/;say$i
```
[Try it online!](https://tio.run/##RY5BTsMwEEWvYixLsUmaNhXd1EkaNkFdsGHRDZTKilxqybEt21JbQrrkAByRgxDcVojN6M/oaf4z3MrZoDTYM6uEenMg4gfDrWi58kzO565l1rfMN7uIAm24wnUCyyUkFOx3QnKcl6Rrdro1tD1WsnBGCo@jUZSgTWDEFruGSWYrmU9JV8nnbF2EOVn3YKstbo9oI64HGlJeXIhzjGPSOXYENQhL34NGasdxTf4t8otFdf/0sCrgEv4J3XC9xYSAq9W5QRZ5XQbUWKE8QDKB4PvzC0A6ZIe8PJ3GGL9kH68kvSUxwotFF8dI9GRMQz8SAw2iILxZYchgmsJ3mMANJJ3ljnuMVqTvh2x0N/3Rxgut3DB6nKWTbPIL "Perl 5 – Try It Online")
Alternative 36 bytes:
```
1x<>~~/((\1|^).*)+$(??{++$\})/;print
```
[Try it online!](https://tio.run/##RZBLboMwEIavMrWsYBdCQtRsYiB0Q5VtF9mUNHKpaZDMQzZRHpQse4AesRehDlHVzbz0z8w3Uwsl5/1eC5i7U2/KoKzgwFWZlx8aLHGshcoLUTZcLha64KopeJPuLAbFCWeB3r@1vXf0w8tlQkjifb5S957amCyXrW3jpKMTVqu8bPqOQVWLksQOCleIMjjscimIH9I23VVFzYpTJANdy7wh1thy8NZo8ozolEuuIunPaBvJF28TGDvddJBVihiGbX4rMBP5waC4hrZNW81PEINJug5SWWlBYvpP4Q8U0ePz0zpAK8RAN7wR@BxM/9juRJURSuEGeF0mAz8OTRc@j0bDWSgpETM9HoMhBywdBD9f32AG4mwcEqPel@8iwwm7eYcZ8uv31gRx5LrojBy0RbRVQouG4DXtut4bP8x@AQ "Perl 5 – Try It Online")
# [Perl](https://www.perl.org/) `-p`, ~~33~~ 32 bytes (full program)
```
1x$_~~/((\1|^).*)+$(??{++$\})/}{
```
[Try it online!](https://tio.run/##K0gtyjH9n5evUJ5YlJeZl16soJ5aUZBalJmbmleSmGNlVZybWFSSm1iSnKFu/d@wQiW@rk5fQyPGsCZOU09LU1tFw96@WltbJaZWU7@2@v9/Q4N/@QUlmfl5xf91CwA "Perl 5 – Try It Online")
Can only take one input (followed by EOF) per run. See [Fibonacci function or sequence](https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence/223243#223243) for an explanation.
# [Raku](https://raku.org/), 29 bytes[SBCS](https://en.wikipedia.org/wiki/Windows-1252) (anonymous function)
```
{+m:ex:P5/^(\1.*|^.+)*$/}o¬πx*
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WjvXKrXCKsBUP04jxlBPqyZOT1tTS0W/Nv/Qzgqt/9bFiZUKKvE6SgqP2iYpKOnoATWl5RcpGOrpGRv8BwA "Perl 6 – Try It Online")
[Answer]
# JavaScript, ~~125~~ 121 bytes
```
n=>(z=(a,b)=>[...Array(a)].map(b))(++n**n,(_,a)=>z[F=z(n,_=>a%(a/=n,n)|0).sort().join`+`]=b+=eval(F)==n-1&!z[F],b=0)|b||1
```
[Try it online!](https://tio.run/##RY7BCoMwEER/pT207GpM9dTTCr34EyK6sVoUu5EoQsV/T6UIPQ7MzHs9LzzVrhvnSOyz8S15oRRWAlYGKc211g/n@AOMhX7zCAYRwlCCQBSUivfOmme0gqiSUr4A30iU4BajnqybAXVvO6nCqiATUrPwABkSSZRcz/uyUIZi3My2Jb62Mtmh0YN9wR98P8CHkcFfYkrb3el4P1Xovw)
Warning: time and space complexity is exponential. Works very slow for large numbers.
[Answer]
# JavaScript ES7, 69 Bytes
```
n=>(f=(i,s)=>i?[for(c of Array(1+n))f(i-1,s,s-=i)]:c+=!s)(n,n,c=0)&&c
```
[Try it online!](https://tio.run/##Tc8xbsJAEEDRqxgKe0ZrIztV5M0YpaThAohiZdb2JJu1NbuAENDmADliLuKEIlLqp1/8N3MyoRWeYhEmPlj5GP27vcw9zZ4a6Ag4D0gNr3fdKNAmY5e8ipgLVMojdsBFlYc8FMS4r1tFi4Dgc5@3VGKatnOgUp8HdhbAkVhzcOwtIC7IH53Dq5BbhclxhKzIUHMH4ElWzvo@Dtg83W4ctmYLTJORYDc@guzKPeIf2P/gm2pd1Q/GOMh4Xm78yTg@JGJ8b@tkqZx@fGh@IatZKbyGNJ2Ef2vUgSo9HWOIAqyy5PvzK8lUD4yo7/e5LJ5/AA "JavaScript (SpiderMonkey) – Try It Online")
# JavaScript ES6, 71 Bytes
```
n=>(f=(i,s)=>i?[...Array(1+n)].map(_=>f(i-1,s,s-=i)):c+=!s)(n,n,c=0)&&c
```
[Try it online!](https://tio.run/##Tc8xbsJAEEDRqxgKe0ZrW3aqyJsxSknDBRCKVmZtJlkWa3YBIaDNAXLEXMQhRaTUT7/47@ZkQic8xiKMvLWyP/gPe5kGmjy10BNwHpBaXqzLsnwVMReolcdNuTcjvFHbAxd1HvJQECM2naJZQPC5zzuqME27KVClzzt2FsCRWLN17C0gzsgfncOrkCvD6DhCVmSouQfwJKWzfog7bJ9uNw4rswKm0UiwSx9B1tUG8Q/sf/BtvaibX8a4k8N5vvQn43ibiPGDbZK5cro/CGh@IatZKbyGNB2FHzXqQLUejzFEAVZZ8v35lWRqgMeZvt@nqnj@AQ "JavaScript (SpiderMonkey) – Try It Online")
Time complexity O(n^n), so be careful (an obvious delay appears on my computer for `F(6)`)
[Answer]
# [Desmos](https://desmos.com/calculator), 64 bytes
```
p(n)=1+‚àë_{i=1}^{n^n}0^{(n-‚àë_{j=1}^njmod(floor(ni/n^j),n))^2}
```
[Try it on Desmos!](https://www.desmos.com/calculator/ddiicj7gwl?nographpaper)
This is `O(n^(n+1))`
## How it works
The value of `i` in base `n` encodes a partition by counting the multiplicity of each part.
For `n=8`, `i=81` encodes `[mod(81,8), mod(81//8,8), mod(81//8^2,8), ...] = [1,2,1]`, so that's 1 one, 2 twos, and 1 three, which gives the partition `1 + 2 + 2 + 3`
`mod(floor(ni/n^j),n)` is the number of parts of size `j`.
`‚àë_{j=1}^njmod(floor(ni/n^j),n)` is the sum of the parts
`0^{(n-sum)^2}` is an indicator for if `i` encodes a partition of `n`: it is 1 if the sum is n, otherwise 0
Summing `0^{(n-sum)^2}` over all valid `i` gives the number of partitions, excluding the n-ones partition `1+1+1....+1` because `i=n` encodes one 2, not n 1s, so we add 1 to the count.
# [DesModder](https://chrome.google.com/webstore/detail/desmodder-for-desmos/eclmfdfimjhkmjglgdldedokjaemjfjp?hl=en) Text Mode Beta 1, 73 bytes
```
p(n)=1+sum i=(1...n^n)({n=sum j=(1...n)(j*mod(floor(n*i/n^j),n)),else:0})
```
DesModder Text Mode avoids the pains of golfing Desmos LaTeX, but it's still a bit buggy, and the syntax is in flux. So some more development might end up with the following syntax for 64 bytes:
```
p(n)=1+sum(i=1...n^n,{n=sum(j=1...n,j*mod(floor(n*i/n^j),n)),0})
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
JÆsæ.:L;
1Ç¡Ḣ
```
[Try it online!](https://tio.run/##y0rNyan8/9/rcFvx4WV6Vj7WXIaH2w8tfLhj0f///w0NDAwA "Jelly – Try It Online")
Takes 5 seconds to solve n = 1000 on TIO.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
The `Œṗ` atom has recently been added, and it means "Integer partitions".
```
ŒṗL
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7p/v8///fFAA "Jelly – Try It Online")
```
ŒṗL - Full program.
Œṗ - Integer partitions.
L - Length.
- Output implicitly.
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 2 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage)
```
‚Üê·µ±
```
[Try it online!](https://tio.run/##K6gs@f//UduEh1s3/v9vaAAA "Pyt – Try It Online")
Explanation:
```
‚Üê Get input
·µ± Number of partitions
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Åœg
```
[Try it online](https://tio.run/##yy9OTMpM/f//cOvRyen//xsaAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/R/i6mevpPCobZKCkr3f/8OtRyen/9f5DwA).
**Explanation:**
```
Ŝ # Get all lists of positive integers that sum to the (implicit) input
g # Pop and push the length to get the amount lists
# (which is output implicitly as result)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `l`, 1 byte
```
Ṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJsIiwiIiwi4bmEIiwiIiwiOCJd)
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
ṄL
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuYRMIiwiIiwiOCJd)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ŻṗḋRċ
```
[Try it online!](https://tio.run/##y0rNyan8///o7oc7pz/c0R10pPv/4XbNyP//zQE "Jelly – Try It Online")
Non-builtin solution using Henry Bottomley's comment at the top of the OEIS page. Although this obviously doesn't beat the builtin, I wouldn't be surprised if the same approach might be the shortest in some other array languages.
```
·πó Generate every combination of n elements with replacement from
Ż [0 .. n],
ḋ dot product each with
R [1 .. n],
ċ and count the occurrences of n.
```
This can also be thought of as encoding each unordered partition as an ordered list of the multiplicity of each integer.
[Answer]
# Java 8 (229 bytes)
```
import java.util.function.*;class A{static int j=0;static BiConsumer<Integer,Integer>f=(n,m)->{if(n==0)j++;else for(int i=Math.min(m,n);i>=1;i--)A.f.accept(n-i,i);};static Function<Integer,Integer>g=n->{f.accept(n,n);return j;};}
```
Ungolfed:
```
import java.util.function.*;
class A {
static int j = 0;
static BiConsumer<Integer, Integer> f = (n, m) -> {
if (n == 0)
j++;
else
for (int i = Math.min(m, n); i >= 1; i--)
A.f.accept(n - i, i);
};
static Function<Integer, Integer> g = n -> {
f.accept(n, n);
return j;
};
}
```
] |
[Question]
[
The challenge is simple:
## generate a word.
Specifications:
* Word must be pronounceable.
+ This is defined as "alternating between a consonant and a vowel."
+ A consonant is one of the following letters: `bcdfghjklmnpqrstvwxz`
+ A vowel is one of the following letters: `aeiouy`
* Word must be randomly generated.
* Words must be able to contain every consonant and vowel. (You can't just use `bcdf` for consonants and `aei` for vowels.)
* Word must contain 10 letters.
* Shortest code (in character count) wins.
[Answer]
# COBOL, 255
So I'm learning COBOL at the moment. Used this question as some practice. Tried to golf it.
It's 255 without the leading whitespace, and 286 bytes with.
For what it's worth, this runs in Microfocus COBOL for VS2012, and I have no idea if it will run anywhere else.
```
1 l pic 99 1 s pic x(26) value'aeiouybcdfghjklmnpqrstvwxz' 1 r
pic 99 1 v pic 9 1 q pic 99. accept q perform test after varying
l from 1 by 1 until l>9 compute v=function mod(l,2) compute r=1+
function random(q*l)*5+v*15+v*5 display s(r:1)end-perform exit
```
[Answer]
### GolfScript, 32 characters
```
['aeiouy'.123,97>^]5*{.,rand=}%+
```
Run it [online](http://golfscript.apphb.com/?c=WydhZWlvdXknLjEyMyw5Nz5eXTUqey4scmFuZD19JSs%3D&run=true).
[Answer]
## Python, 81
```
from random import*
print''.join(map(choice,["bcdfghjklmnpqrstvwxz","aeiouy"]*5))
```
Good luck pronouncing them.
[Answer]
# Ruby: 56 characters
```
([v=%w(a e i o u y),[*?a..?z]-v]*5).map{|a|$><<a.sample}
```
Example outputs:
* itopytojog
* umapujojim
* ipagodusas
* yfoqinifyw
* ebylipodiz
[Answer]
## APL (34)
```
,⍉↑(V[5?6])((⎕A~V←'AEIOUY')[5?20])
```
[Answer]
# JavaScript, 74
```
for(a=b=[];a++-5;)b+="bcdfghjklmnpqrstvwxz"[c=new Date*a%20]+"aeiouy"[c%6]
```
Does not generate all combinations, but I think that all consonants and vowel appear.
**JavaScript, 79**
```
for(a=b=[];a--+5;)b+="bcdfghjklmnpqrstvwxz"[c=Math.random()*20^0]+"aeiouy"[c%6]
```
More "random" version.
[Answer]
# Ruby: ~~70~~ 66 characters
```
10.times{|i|$><<["aeiouy"*4,"bcdfghjklmnpqrstvwxz"][i%2][rand 20]}
```
Sample run:
```
bash-4.1$ ruby -e '10.times{|i|$><<["aeiouy"*4,"bcdfghjklmnpqrstvwxz"][i%2][rand 20]}'
izogoreroz
bash-4.1$ ruby -e '10.times{|i|$><<["aeiouy"*4,"bcdfghjklmnpqrstvwxz"][i%2][rand 20]}'
onewijolen
bash-4.1$ ruby -e '10.times{|i|$><<["aeiouy"*4,"bcdfghjklmnpqrstvwxz"][i%2][rand 20]}'
amilyfilil
```
[Answer]
## R: 105 characters
```
a=c(1,5,9,15,21,25)
l=letters
s=sample
cat(apply(cbind(s(l[-a],5),s(l[a],5)),1,paste,collapse=""),sep="")
```
[Answer]
## J (51)
```
,|:>(<"1[5?6 20){&.>'aeiouy';'bcdfghjklmnpqrstvwxz'
```
[Answer]
# **Processing, 100 99 93 87**
```
int i=10;while(i-->0)"aeiouybcdfghjklmnpqrstvwxz".charAt((int)random(i%2*6,6+i%2*i*2));
```
Upon closer inspection of the question, I see it doesn't require any output. I've adjusted this accordingly.
[Answer]
# Unix tools: 73 bytes
And not guaranteed running time :)
```
</dev/urandom grep -ao '[aeiouy][bcdfghjklmnpqrstvwxz]'|head -5|paste -sd ''
```
Only problem is that the generated string will start with a "vowel" every time.
(edit: changed `' '` to `''` in the args of paste)
(another edit: removed -P from grep options, thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork))
[Answer]
## PHP 79 bytes
```
<?for($c=bcdfghjklmnpqrstvwxz,$v=aeiouy;5>$i++;)echo$c[rand()%20],$v[rand()%6];
```
Fairly concise.
[Answer]
**Objective-C, 129**
```
main(){int i=10;while(i-->0)printf("%c",[(i%2==0)?@"aeiouy":@"bcdfghjklmnpqrstvwxz"characterAtIndex:arc4random()%(6+(i%2)*14)]);}
```
With the help of Daniero
(I love to use the *tends to* operator (-->)
[Answer]
**Java AKA the most verbose language ever created, 176**
with help of Doorknob, Daniero and Peter Taylor (thanks guys!)
```
class w{public static void main(String[]a){int i=11;while(--i>0)System.out.print((i%2==0?"aeiouy":"bcdfghjklmnpqrstvwxz").charAt(new java.util.Random().nextInt(6+(i%2)*14)));}}
```
Ungolfed:
```
class w {
public static void main(String[] a) {
int i = 11;
while (--i > 0) {
System.out.print((i % 2 == 0 ? "aeiouy" : "bcdfghjklmnpqrstvwxz").charAt(new java.util.Random().nextInt(6 + (i % 2) * 14)));
}
}
```
}
[Answer]
## Javascript, 85
```
for(r=Math.random,s="",i=5;i--;)s+="bcdfghjklmnpqrstvwxz"[20*r()|0]+"aeiouy"[6*r()|0]
```
If run from the console, output is shown. Explicit display would add `alert(s)` at 8 chars, still shorter than the other JS solutions.
Thanks C5H8NNaO4 and Howard!
[Answer]
## PHP, 100 Characters
```
<?while($i<6){echo substr('bcdfghjklmnpqrstvwxz',rand(0,20),1).substr('aeiouy',rand(0,5),1);$i++;}?>
```
[Answer]
# K, 40 bytes
```
,/+5?/:("bcdfghjklmnpqrstvwxz";"aeiouy")
```
`5?"abc"` will generate 5 random letters from the given string.
`5?/:` will generate 5 random letters from each of the strings on the right, producing two lists.
`+` transposes those two lists, giving us a list of tuples with one random character from the first list and then one from the second list.
`,/` is "raze"- fuse together all those tuples in sequence.
K5 can do this in 33 bytes by building the alphabet more cleverly and then using "except" (`^`) to remove the vowels, but K5 is much too new to be legal in this question:
```
,/+5?/:((`c$97+!26)^v;v:"aeiouy")
```
[Answer]
# Pyth, 26 characters
```
J-G"aeiouy"VT=k+kOJ=J-GJ;k
```
[You can try it in the online compiler here.](https://pyth.herokuapp.com/?code=J-G%22aeiouy%22VT%3Dk%2BkOJ%3DJ-GJ%3Bk&debug=0)
Someone posted a very similar challenge but it was closed after I had made a solution. I didn't realize it, but this question actually predates the creation of Pyth. Anyway, here is the breakdown:
```
J Set string J equal to:
G the entire alphabet (lowercase, in order)
- "aeiouy" minus the vowels
VT For n in range(1, 10):
=k Set string k to:
k k (defaults to empty string)
+ OJ plus a random character from J
=J Set J to:
G the entire alphabet
- J minus J
; End of loop
k print k
```
Every time the loop is run, J switches from being a list of consonants to a list of vowels. That way we can just pick a random letter from J each time.
There may be a way to initialize J in the loop or remove the explicit assignments from the loop, but I have not had success with either yet.
[Answer]
## APL ~~30~~ 26
```
,('EIOUY'∪⎕A)[6(|,+)⍪5?20]
```
Explanation is very similar to the past version below, just reordered a bit to golf the solution.
Note: ⎕IO is set to 0
---
```
('EIOUY'∪⎕A)[,6(|,(⍪+))5?20]
```
Explanation:
```
'EIOUY'∪⎕A puts vowels in front of all letters.
5?20 for the indexes we start choosing 5 random numbers between 0 and 19
6(|,(⍪+)) then we sum 6 and the random numbers, convert to 5x1 matrix (⍪), add a column before this one containing 6 modulo the random numbers.
[[[ this one can be rewritten as: (6|n) , ⍪(6+n) for easier understanding]]]
,6(|,(⍪+))5?20 the leading comma just converts the matrix to a vector, mixing the vowel and consonants indexes.
```
[Tryapl.org](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%2C%28%27EIOUY%27%u222A%u2395A%29%5B6%28%7C%2C+%29%u236A5%3F20%5D&run)
[Answer]
# C: 101
```
main(){int x=5;while(x-->0){putchar("bcdfghjklmnpqrstvwxyz"[rand()%21]);putchar("aeiou"[rand()%5]);}}
```
[Answer]
# Javascript, ~~104~~ 87
```
a="";for(e=10;e--;)a+=(b=e&1?"bcdfghjklmnpqrstvwxz":"aeiouy")[0|Math.random()*b.length]
```
*golfed a whole lot of simple unnecessary stuff, still not nearly as nice as [copys' one](https://codegolf.stackexchange.com/a/11897)*
*Oh, and that one just opped up during golfing: **"dydudelidu"***
Now I tried one using the 2 characters at once approach. Turns out it's almost the same as copys' second one, so I can't count it, also at 79.
`a="";for(e=5;e--;)a+="bcdfghjklmnpqrstvwxz"[m=0|20*Math.random()]+"aeiouy"[m%6]`
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
Ḍ;Ẉṣᵐzh₅c
```
[Try it online!](https://tio.run/##ATMAzP9icmFjaHlsb2cy/@KJnOKIp@KGsOKCgeG6ieKKpf/huIw74bqI4bmj4bWQemjigoVj//8 "Brachylog – Try It Online")
Gives output as a list of letters through the output variable.
```
ṣ Randomly shuffle
; ᵐ both
Ḍ the consonants without y
Ẉ and the vowels with y,
z zip them into pairs,
h₅ take the first five pairs,
and output
c their concatenation.
```
[Answer]
# ["Random Word Generator"](https://bigyihsuan.github.io/phono-word-gen/), 70 +2 = 72 bytes
```
C=b c d f g h j k l m n p q r s t v w x z
V=a e i o u y
syllable:$C$V
```
Set minimum and maximum number of syllables settings to `5` (which I'm counting as flags, so 1 byte each).
This is written in a (WIP) tool I wrote for generating words from a sound inventory for conlanging (making constructed languages). I made the tool due to the other word generators (that I know of) having flaws (in my opinionated opinion).
The above code sets two categories `C` and `V`, and defines a syllable as a `C` followed by a `V`. The flags (minimum and maximum syllables) define how many syllables will be generated for a given word.
### No changed settings, 86 bytes
```
C=b c d f g h j k l m n p q r s t v w x z
V=a e i o u y
syllable:$C$V$C$V$C$V$C$V$C$V
```
Due to a bug in my implementation, this solution is extremely slow due to the large syllable size.
[Answer]
**F#**, 166 characters
```
open System;String.Join("",(Random(),"aeiouybcdfghjklmnpqrstvwxz")|>(fun(r,s)->[0..5]|>List.collect(fun t->[s.Substring(6+r.Next()%20,1);s.Substring(r.Next()%6,1)])))
```
[Answer]
# R, 83 bytes
```
cat(outer((l<-letters)[a<-c(1,5,9,15,21,25)],l[-a],paste0)[sample(1:120,5)],sep="")
```
Generate all possible vowel-consonant sequences in a matrix, then randomly sample 5 of them, yielding a 10-letter word.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
5FžPΩ?žOΩ?
```
[Try it online](https://tio.run/##yy9OTMpM/f/f1O3ovoBzK@2P7vMHkv//AwA) or [output \$n\$ amount of random words](https://tio.run/##yy9OTMpM/e/239Tt6L6Acyvtj@7zB5L/aw9ts/9vaAAA).
**Explanation:**
Pretty straight-forward:
```
5F # Loop 5 times:
žP # Push string "bcdfghjklmnpqrstvwxz"
Ω # Pop and push a random character from this string
? # Output it without newline
žOΩ? # Do the same with string "aeiouy"
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~57~~ ~~47~~ ~~46~~ 54 bytes
```
{`prng@0;,/{(1?"bcdfghjklmnpqrstvwxz"),1?"aeiouy"}'!5}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pOKCjKS3cwsNbRr9YwtFdKSk5JS8/Iys7JzSsoLCouKSuvqFLS1AHKJKZm5pdWKtWqK5rWcnGlRccCAIl/FGE=)
*Down 1 byte thanks to ngn*
Takes inspiration from the [PHP answer](https://codegolf.stackexchange.com/a/11882/107017). This one now outputs random words at each call, with the cost of 8 extra bytes.
Explanation:
```
{`prng@0;,/{(1?"bcdfghjklmnpqrstvwxz"),1?"aeiouy"}'!5} Main function. Takes no input
!5 Generate a array with range from 0 to 4 ([0..4])
' For each number...
{ } Execute a function that...
(1?"bcdfghjklmnpqrstvwxz"),1?"aeiouy" Chooses one random consonant, followed by one random vowel
,/ Joined each of these strings together
`prng@0; Use current time to set state of randomness (Thus allow random words)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), ~~20~~ 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;`Á<`
5Æö iCkU ö
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=O2CMwTxgCjXG9iBpQ2tVIPY)
Note that there is an unprintable character in front of the `Á`
```
; # C = "abcdefghijklmnopqrstuvwxyz"
`ŒÁ<` # U = "oueayi"
5Æ # Do this 5 times:
ö # Pick a random letter from U
i # Prepend:
CkU # Remove the letters in U from C
ö # Get a random letter from the result
-P # Print all the pairs with no separator
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;Cü_èyi%îö5ÃÕ
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=O0P8X%2bh5aSXDrvY1w9U)
```
;Cü_èyi%îö5ÃÕ
;C :Lowercase alphabet
ü :Group by
_ :Passing each character through the following function
è : Count
yi% : "y" prepended with "%", giving the Japt RegEx "%y"=/[aeiouy]/i
à :End grouping
® :Map
ö5 : 5 random characters
à :End map
Õ :Transpose
:Implicitly join & output
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 89 bytes
```
for(;a=Math.random().toString(36).match(/([bcdfghj-np-tvwxz][aeiouy]){5}/g),!a;);print(a)
```
[Try it online!](https://tio.run/##DctNDsIgEAbQs7ibSYQujMaEeARXLpsuPqkFmhQIHfEvnh19@zejYrUlZFH12NqUChmczhCvC@KYFmIt6SIlREe7A@sFYj111F/tODk/q5iV1MfzPfS4hXR/DfzZfzvH2w0Mm/yPQuDWfg "JavaScript (V8) – Try It Online")
`/g` makes the result without an extra appearance of pair
] |
[Question]
[
### Definition
Define the **n**th array of the CURR sequence as follows.
1. Begin with the singleton array **A = [n]**.
2. For each integer **k** in **A**, replace the entry **k** with **k** natural numbers, counting up from **1** to **k**.
3. Repeat the previous step **n - 1** more times.
For example, if **n = 3**, we start with the array **[3]**.
We replace **3** with **1, 2, 3**, yielding **[1, 2, 3]**.
We now replace **1**, **2**, and **3** with **1**; **1, 2** and **1, 2, 3** (resp.), yielding **[1, 1, 2, 1, 2, 3]**.
Finally, we perform the same replacements as in the previous step for all six integers in the array, yielding **[1, 1, 1, 2, 1, 1, 2, 1, 2, 3]**. This is the third CURR array.
### Task
Write a program of a function that, given a strictly positive integer **n** as input, computes the **n**th CURR array.
The output has to be a *flat* list of some kind (and array returned from a function, a string representation of your language's array syntax, whitespace-separated, etc.).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). May the shortest code in bytes win!
### Test cases
```
1 -> [1]
2 -> [1, 1, 2]
3 -> [1, 1, 1, 2, 1, 1, 2, 1, 2, 3]
4 -> [1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4]
5 -> [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5]
6 -> [1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6]
```
[Answer]
## Jelly, 3 bytes
```
R¡F
```
[Try it online](http://jelly.tryitonline.net/#code=UsKhRg&input=&args=Mw)
## Explanation
```
R¡F Argument n
R Yield range [1..n]
¡ Repeat n times
F Flatten the result
```
[Answer]
## Python, 50 bytes
```
lambda i:eval("[i "+"for i in range(1,i+1)"*i+"]")
```
Scope abuse! For example, for `i=3`, the string to be evaluated expands to.
```
[i for i in range(1,i+1)for i in range(1,i+1)for i in range(1,i+1)]
```
Somehow, despite using the function input variable `i` for everything, Python distinguishes each iteration index as belonging to a separate scope as if the expression were
```
[l for j in range(1,i+1)for k in range(1,j+1)for l in range(1,k+1)]
```
with `i` the input to the function.
[Answer]
## 05AB1E, ~~6~~ 3 bytes
```
DFL
```
**Explained**
```
D # duplicate input
F # input times do
L # range(1,N)
```
[Try it online](http://05ab1e.tryitonline.net/#code=REZM&input=Mw)
Saved 3 bytes thanks to @Adnan
[Answer]
## [Retina](https://github.com/mbuettner/retina), 33 bytes
```
$
$.`$*0
+%(M!&`1.*(?=0)|^.+
O`.+
```
Input and output in unary.
[Try it online!](http://retina.tryitonline.net/#code=JAokLmAkKjAKKyUoTSEmYDEuKig_PTApfF4uKwpPYC4r&input=MTEx)
Even though I didn't use the closed form for the related challenge, adapting this answer was surprisingly tricky.
[Answer]
## Python 2, 82 bytes
```
lambda n:[1+bin(i)[::-1].find('1')for i in range(1<<2*n-1)if bin(i).count('1')==n]
```
This isn't the shortest solution, but it illustrates an interesting method:
* Write down the first `2^(2*n-1)` numbers in binary
* Keep those with exactly `n` ones
* For each number, count the number of trailing zeroes, and add 1.
[Answer]
## Actually, 9 bytes
```
;#@`♂RΣ`n
```
[Try it online!](http://actually.tryitonline.net/#code=OyNAYOKZglLOo2Bu&input=Mw)
Explanation:
```
;#@`♂RΣ`n
;#@ dupe n, make a singleton list, swap with n
`♂RΣ`n call the following function n times:
♂R range(1, k+1) for k in list
Σ concatenate the ranges
```
Thanks to Leaky Nun for a byte, and inspiration for another 2 bytes.
[Answer]
## C#, 128 Bytes
```
List<int>j(int n){var l=new List<int>(){n};for(;n>0;n--)l=l.Select(p=>Enumerable.Range(1,p)).SelectMany(m=>m).ToList();return l;
```
[Answer]
# APL, 11 bytes
```
{∊⍳¨∘∊⍣⍵+⍵}
```
Test:
```
{∊⍳¨∘∊⍣⍵+⍵} 3
1 1 1 2 1 1 2 1 2 3
```
Explanation:
* `+⍵`: starting with `⍵`,
* `⍣⍵`: do the following `⍵` times:
+ `⍳¨∘∊`: flatten the input, and then generate a list [1..N] for each N in the input
* `∊`: flatten the result of that
[Answer]
# J, 18 bytes
```
([:;<@(1+i.)"0)^:]
```
Straight-forward approach based on the process described in the challenge.
## Usage
```
f =: ([:;<@(1+i.)"0)^:]
f 1
1
f 2
1 1 2
f 3
1 1 1 2 1 1 2 1 2 3
f 4
1 1 1 1 2 1 1 1 2 1 1 2 1 2 3 1 1 1 2 1 1 2 1 2 3 1 1 2 1 2 3 1 2 3 4
```
## Explanation
```
([:;<@(1+i.)"0)^:] Input: n
] Identity function, gets the value n
( ... )^: Repeat the following n times with an initial value [n]
( )"0 Means rank 0, or to operate on each atom in the list
i. Create a range from 0 to that value, exclusive
1+ Add 1 to each to make the range from 1 to that value
<@ Box the value
[:; Combine the boxes and unbox them to make a list and return
Return the final result after n iterations
```
[Answer]
## CJam, 14 bytes
```
{_a\{:,:~:)}*}
```
[Test it here.](http://cjam.aditsu.net/#code=3%0A%0A%7B_a%5C%7B%3A%2C%3A~%3A)%7D*%7D%0A%0A~p&input=3)
### Explanation
```
_a e# Duplicate N and wrap it in an array.
\ e# Swap with other copy of N.
{ e# Do this N times...
:, e# Turn each x into [0 1 ... x-1].
:~ e# Unwrap each of those arrays.
:) e# Increment each element.
}*
```
[Answer]
## Mathematica, ~~27~~ 26 bytes
*1 byte saved with some inspiration from Essari's answer.*
```
Flatten@Nest[Range,{#},#]&
```
Fairly straightforward: for input `x` we start with `{x}` and then apply the `Range` to it `x` times (`Range` is `Listable` which means that it automatically applies to the integers inside arbitrarily nested lists). At the end `Flatten` the result.
[Answer]
## Clojure, 59 bytes
```
(fn[n](nth(iterate #(mapcat(fn[x](range 1(inc x)))%)[n])n))
```
Explanation:
Really straight forward way to solve the problem. Working from the inside out:
```
(1) (fn[x](range 1(inc x))) ;; return a list from 1 to x
(2) #(mapcat (1) %) ;; map (1) over each item in list and flatten result
(3) (iterate (2) [n]) ;; call (2) repeatedly e.g. (f (f (f [n])))
(4) (nth (3) n)) ;; return the nth value of the iteration
```
[Answer]
# Python 3, ~~75~~ 74 bytes
```
def f(k):N=[k];exec('A=N;N=[]\nfor i in A:N+=range(1,i+1)\n'*k+'print(N)')
```
This is just a straightforward translation of the problem description to code.
Edit: Saved one byte thanks to @Dennis.
[Answer]
## R, ~~60~~ 49 bytes
Pretty straightforward use of `unlist` and `sapply`.
```
y=x=scan();for(i in 1:x)y=unlist(sapply(y,seq));y
```
Thanks to @MickyT for saving 11 bytes
[Answer]
## php 121
Not really very much in the way of tricks behind this one.
Flattening an array in php isn't short so it's necessary to build it flat in the first place
```
<?php for($a=[$b=$argv[1]];$b--;)$a=array_reduce($a,function($r,$v){return array_merge($r,range(1,$v));},[]);print_r($a);
```
[Answer]
## Haskell, 33 bytes
```
f n=iterate(>>= \a->[1..a])[n]!!n
```
Thanks to nimi for saving a byte.
A pointfree version is longer (35 bytes):
```
(!!)=<<iterate(>>= \a->[1..a]).pure
```
[Answer]
## JavaScript (Firefox 30-57), ~~63~~ 60 bytes
```
f=n=>eval(`[${`for(n of Array(n+1).keys())`.repeat(n--)}n+1]`)
```
Port of @xnor's Python answer.
[Answer]
# Pyth, 8 bytes
```
usSMGQ]Q
```
[Try it online!](http://pyth.herokuapp.com/?code=usSMGQ%5DQ&test_suite=1&test_suite_input=3&debug=0)
```
usSMGQ]Q input as Q
u Q repeat for Q times,
]Q starting as [Q]:
SMG convert each number in the array to its range
s flatten
then implicitly prints the result.
```
[Answer]
# Jelly, 7 bytes
Quick, before Dennis answers (jk)
```
WR€F$³¡
```
[Try it online!](http://jelly.tryitonline.net/#code=V1LigqxGJMKzwqE&input=Mw&args=Mw)
```
WR€F$³¡ Main monadic chain. Argument: z
W Yield [z].
³¡ Repeat the following z times:
R€ Convert each number in the array to the corresponding range.
F Flatten the array.
```
[Answer]
## F# , 63 bytes
```
fun n->Seq.fold(fun A _->List.collect(fun k->[1..k])A)[n]{1..n}
```
Returns an anonymous function taking n as input.
Replaces every entry k in A with [1..k], repeats the process n times, starting with A = [n].
[Answer]
# Swift 3, 58 Bytes
Meant to run directly in the a playground, with n set to the input:
```
var x=[n];for i in 0..<n{x=x.reduce([]){$0+[Int](1...$1)}}
```
Ungolfed, with most short hand notation reverted:
```
let n = 3 //input
var x: Array<Int> = [n]
for i in 0..<n {
x = x.reduce(Array<Int>[], combine: { accumulator, element in
accumulator + Array<Int>(1...element)
})
}
```
[Answer]
# Java, 159 Bytes
**Procedure**
```
int[] q(int y){int z[]=new int[]{y};for(int i=0;i<y;i++){int d=0,a=0;for(int c:z)d+=c;int[]r=new int[d];for(int c:z)for(int j=0;j<c;)r[a++]=++j;z=r;}return z;}
```
**Usage**
```
public static void main(String[] args){String out = "["; int [] b = q(6);for(int c:b)out+=c+", ";System.out.println(out+"]");}
public static int[] q(int y){int z[]=new int[]{y};for(int i=0;i<y;i++){int d=0,a=0;for(int c:z)d+=c;int[]r=new int[d];for(int c:z)for(int j=0;j<c;)r[a++]=++j;z=r;}return z;}
```
*Sample output:*
```
[1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, ]
```
[Answer]
## Python 2, ~~69~~ ~~68~~ 66 bytes
```
def f(n):a=[n];exec'a=sum([range(1,i+1)for i in a],[]);'*n;print a
```
Edit: Saved 1 byte thanks to @xnor. Saved 2 bytes thanks to @Dennis♦.
[Answer]
# Bash + GNU utilities, 49
* 1 byte saved thanks to @Dennis.
Piped recursive functions FTW!
```
f()((($1))&&xargs -l seq|f $[$1-1]||dd)
f $1<<<$1
```
`n` is passed on the command-line. Output is newline-separated.
The use of `dd` causes statistics to be sent to STDERR. I think this is OK, but if not, `dd` can be replaced with `cat` at a cost of 1 extra byte.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 44 bytes
A simple recursive approach.
```
->n,a=[n]{n>0?F[n-1,a.flat_map{[*1.._1]}]:a}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3dXTt8nQSbaPzYqvz7Azs3aLzdA11EvXSchJL4nMTC6qjtQz19OINY2tjrRJrIXqWFSi4RRvHQjgLFkBoAA)
[Answer]
# Perl 5, 53 bytes
A subroutine:
```
{($i)=@_;for(1..$i){my@c;push@c,1..$_ for@_;@_=@c}@_}
```
See it in action as
```
perl -e'print "$_ " for sub{($i)=@_;for(1..$i){my@c;push@c,1..$_ for@_;@_=@c}@_}->(3)'
```
[Answer]
## Ruby, 61 bytes
```
def f(n);a=[n];n.times{a=a.map{|i|(1..i).to_a}.flatten};a;end
```
[Answer]
# PHP, ~~100~~ 98 bytes
Run with `php -r '<code>' <n>`.
```
for($a=[$n=$argv[1]];$n--;$a=$b)for($b=[],$k=0;$c=$a[$k++];)for($i=0;$i++<$c;)$b[]=$i;print_r($a);
```
In each iteration create a temporary copy looping from 1..(first value removed) until `$a` is empty.
---
These two are still and will probably remain at 100 bytes:
```
for($a=[$n=$argv[1]];$n--;)for($i=count($a);$i--;)array_splice($a,$i,1,range(1,$a[$i]));print_r($a);
```
In each iteration loop backwards through array replacing each number with a range.
```
for($a=[$n=$argv[1]];$n--;)for($i=$c=0;$c=$a[$i+=$c];)array_splice($a,$i,1,range(1,$c));print_r($a);
```
In each iteration loop through array increasing index by previous number and replacing each indexed element with a range
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-mh`](https://codegolf.meta.stackexchange.com/a/14339/), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
N=cõ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1o&code=Tj1j9Q&input=Mw)
[Answer]
# [Perl 5](https://www.perl.org/) + `-p`, 28 bytes
```
eval's/\d+/@{[1..$&]}/g;'x$_
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiZXZhbCdzL1xcZCsvQHtbMS4uJCZdfS9nOyd4JF8iLCJhcmdzIjoiLXAiLCJpbnB1dCI6IjFcbjJcbjNcbjRcbjVcbjYifQ==)
] |
[Question]
[
## The Narrative
You are a frog who is at the edge of a pond with waterlilies. You would like to cross the pond without getting wet, so you plan to jump from lily to lily. There is, however, one problem: you are a rare species of frog which can only jump one specific distance, and so you might not be able to cross the pond no matter what you do.
## The Objective
Determine if the frog can cross the pond without getting wet.
**Your program should take two inputs:**
* A string or list of lily-y/watery values to represent the lilies in the pond
* A positive integer which tells how far the frog jumps
**Your program should output a truthy/falsy value to indicate whether the pond is crossable**
The frog can start any distance behind the edge of the pond, but may not start on a lily or in the water. Additionally, the frog may finish any distance beyond the far edge of the pond, but not on a lily or in the water. Note that the frog cannot move at any interval other than that which is specified in the input (i.e. With a jumping distance of `3`, the pond `001100` is not crossable, even though it appears that the frog could walk from the first waterlily to the second)
Examples:
```
(lily=1, water=0)
Inputs: "001101001111001", "3"
Output: "Yes"
Inputs: "101001", "2"
Output: "No"
Inputs: "010000001", "7"
Output: "Yes"
Inputs: "00000", "6"
Output: "Yes"
Inputs: "00000", "5"
Output: "No"
Inputs: "00100100", "4"
Output: "No"
Inputs: "001100", "3"
Output: "No"
Inputs: "", "1"
Output: "Yes"
(note that output does not have to be "Yes" or "No", but any truthy/falsy values)
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
# [BitCycle](https://github.com/dloscutoff/esolangs/tree/master/BitCycle), 329 bytes
BitCycle is certainly not an easy language to solve this in, despite the fact that its only form of data (streams of bits), easily represents the pattern of the lilypond in this challenge.
None of the mathematical solutions used in the other answers here would be at all easy to implement in BitCycle, so the basic algorithm for this program is as follows: given the jump length `N` and the pond string `P`, take every `N`th bit of `P`, AND those bits together to determine if this pond is crossable, and repeat this for every possible starting distance from the pond, ORing the results from each variation together to determine if any are crossable.
This program takes the bitstring representing the lilypond as its first input (with 1s as lilies and 0s as water), and the jump length in unary (bitcycles normal way of representing integers) as the second input.
```
v <
v ~^ v < <> v F>\^Hv
Gv E^ ^~ + > + !
1>Gv>v ^=~ > ^v+vF^ H>/
?B^> ^ Cv^\=/^^v~ v
v ~ ^ > D ^ >
?~ v~^^<v~D/Bvv <
0AG\ ^^= ~> \^^ < >
B ^ >^ ~<?~ =
> B^ >1B^ v /v~<0C^E^
^ ~~ Gv0C>D> E^
^ < ^~ ~
Bv
> ~
```
## More in-depth explanation
*(will come later, when I feel like digging through this code to figure out how each piece of it works again)*
[Try it online!](https://tio.run/##VZA9bsMwDIV3nYKdM9jaZRqVnTiHMN4QI0OBjgWBLry6QpHOEP0QFPU9kdTj5@/4P36frQn5KInodEnhfrHF3bvxjrsYsL0JH1fDCGrmQmz7K2XehI3BpIFwN5CL3Iy982BvzBU92rW0CPZpAERJPL963FVrMGxxmuM5UaCIrkMVOUsev7edgInURDvQq@6SGvlBDNIS@ikZUy2Uqzc4iJZxwRXJM2mHNhkXXjnaS2eZ/j/RKWmKc5XTiWrtorWWx4/Zcn4B "BitCycle – Try It Online") or [Dlosc's online visualizer](https://dloscutoff.github.io/Esolangs/BitCycle/?p=sc6wrc2sc7znc2sc2wc2wec2scFeinHsrc2Gsc9c3Enc3nzc3tcectcbr1eGsesc2nozc6ec4nstsFnc2Hejrc2qBnec3nc4Csniojn2szcsrc2sczcnc3ec4Dc2nc3erc3qzc5szn2wszDjBs2c3wrc20AGicn2oczec2in2c2wcerc2Bc6ncenczwqzc4orec2Bnce1Bnc2scjszw0CnEnrcnc3z2c3Gs0CeDec4Enrc2nc8wcnzc4zrc6Bsrc7ec6zc&i=MTAxMDEwMTAxMDEwMQoxMQ__) (To test inputs on TIO, they must be put into the arguments section, rather than the input section.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
T%QL<
```
[Try it online!](https://tio.run/##y0rNyan8/z9ENdDH5n/eo4a5hoeXn5yu/6hpTeT//9FKBgaGhgaGINIQRCrpKBjH6ihEK0EEgVwjMBfEAwGQiDlEBASAPDMozxCMgAImsQA "Jelly – Try It Online")
*Look ma, no Unicode!*
Takes a list of 0 for lilies and 1 for water on the left, and the stride on the right.
```
L The number of
Q unique
T indices of water
% modulo the stride
< is less than the stride.
```
The frog must traverse every index with some chosen residue modulo the stride; this checks if there's any residue which does not at any point correspond to water.
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
s׃R}Ẹ
```
[Try it online!](https://tio.run/##y0rNyan8/7/48PRjk4JqH@7a8d/2UcNcw8PLT07Xf9S0JvL//2glAwNDQwNDEGkIIpV0FIxjdRSilSCCQK4RmAvigQBIxBwiAgJAnhmUZwhGQAGTWAA "Jelly – Try It Online")
Takes a list of 1 for lilies and 0 for water on the left, and the stride on the right. (Without having to handle strides longer than the pond itself, could just be `sPẸ`.)
```
s Split the pond into stride-sized slices.
ƒ Reduce the list of slices by
× vectorizing multiplication
R} starting with [1..stride] (all-truthy and the appropriate length).
Ẹ Is any value truthy?
```
[Answer]
# [R](https://www.r-project.org/), 64 bytes
```
function(x,y)length(table(which(strsplit(x,'')[[1]]=='0')%%y))<y
```
[Try it online!](https://tio.run/##LYnBCsIwEETvfoUESnYhh6yKXsyXlB60NCYQorQrmq@P2dZhGHhv5upd9e88cnxm@JqCacoPDsC3e5rgE@IYYOF5eaXI7dca@56GwTltNXZdQbyW6kFZS2RJlmSVOeKu6c0psz@sKCQRc9mMpNH5T7S2iRPW@gM "R – Try It Online")
If allowed to take a boolean list instead:
# [R](https://www.r-project.org/), 42 bytes
```
function(x,y)length(table(which(!x)%%y))<y
```
[Try it online!](https://tio.run/##Zc3BCsIwDADQ@75iDkYb2GFR0Yv9krGDjnYrjG60FVfEb6/LFEUXQgJ5CbFxtHK0QyOdS0WqrqbxejDceatNC/e5u7HX/j0oGIOqwroWgiF7JErEz8lUBOilaX3H/fnSS37rdNPxzQR5HgBOISr@fcazskQskSpSzaDYQfK78vJZ0u0/kVAselwpBclhLbgk4R6SGJ8 "R – Try It Online")
Can cut that down to 41 if I can flip the lily-y and watery states, losing the ! in the process.
1 byte reduced because `table` is one byte shorter than `unique`.
Basic idea: look at values mod the jump length, any residue that has a 0 is not a residue you can completely jump across, if not all of them have 0 then you can jump across. Some residues may be empty (and thus fine), e.g. if you have 6 pads and can jump across 7 then there are no pads at 0 mod 7 and you can jump straight across the pond.
This is equivalent to the solutions of <https://codegolf.stackexchange.com/users/73593/matteo-c>.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 6 bytes
```
T%UL⁰>
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwiVCVVTOKBsD4iLCIiLCJbMSwgMSwgMSwgMSwgMV1cbjYiXQ==)
Port of Jelly answer.
## How?
```
T%UL⁰>
T # Truthy (water) indices of the (implicit) first input
% # Modulo each by the (implicit) second input (the stride)
U # Uniquify
L # Length
⁰> # Is the second input (the stride) greater than this?
```
[Answer]
# [Python](https://www.python.org), ~~62~~ ~~47~~ 46 bytes
*thanks to [@Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string) for the idea of alternative input format*
*-1 byte thanks to [@dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)*
```
f=lambda p,n:0in(0in p[i::n]for i in range(n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZLBSsQwEIbxmqcY5pRALY0rKoE-gBc9S-2hYrsGumlosrL6Kl72ou-k-DDOJIpFWEMSksz3z2QmeXnzT_Fhcvv96zYOxxfv5VCP3ebuvgNfOFNZJ2mAb6wxrh2mGSzQfu7cupdOqaz6OPoMUAMiikvntzEYwKrSutI8a56xAFyhuN5GspP5pg8ofumMMnSygK6mJcMIt4SdH_aVIGbO_mN06oyd_onIaQjOJ5QhztZLvHWoyuBHG0fr-iCVEDZ5AqKa_rEb5S7bJRpUjW4VcK12XKvQVMas2lZMKUg4LKnrfM-lVmetSKUvJj58pivl8AV8-1RGADU_WxclYSpvC0fBbF7TarQhyk3H6liAV5lKDMmcWvgYJIkVFYdTz4_880W-AA)
# [C (gcc)](https://gcc.gnu.org/), ~~118~~ 110 bytes
*-8 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
d,i,j,n,l,c;main(c,v)char**v;{for(n=atoi(v++[2]);c=i<n;d+=c)for(j=i++;j<strlen(*v);j+=n)c&=j[*v]-48;return d;}
```
[Try it online!](https://tio.run/##FcmxDsIgEADQX3EywNEE1MHkel/SdCBHVUi9JrSyGL8dw/KWx8OTubVok81W7GoZ3yGJYls1v0IxpuL3sRUlFI4tqQowXWaNTGkUjECs@2ZKAJjH/SjrIspUjRlINJ8pT6bOw@2OZTk@RU4Rf60157x3vuu77foH "C (gcc) – Try It Online")
# [Haskell](https://www.haskell.org/), ~~50~~ 48 bytes
*-2 bytes thanks to [@Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)*
```
p#n=any(\i->all(p!!)[i,i+n..length p-1])[0..n-1]
```
[Try it online!](https://tio.run/##LYj/CoIwFIVfxR@B99IcW0b903yDnkAlRkiO5mWYQj792rTD4XC@b9Cfd2@t9y4npWmF1pS1thZcmmJjmDkS57an1zwkrpQdNoJzCseP2pAatbs/wE2GZr7Qc5mmFXLk0MKXrVjWAEoVssDboY4CsYFMCCmFjCvjZiypkCWQ7TLgacNIMdFcdxMT6PInuTWIM3b@Bw "Haskell – Try It Online")
All the solutions do basically the same thing.
[Answer]
# [R](https://www.r-project.org/), ~~37~~ ~~36~~ 34 bytes
*Edit: -2 bytes thanks to Giuseppe*
```
function(x,y)(y:0)[1:y*-!c(x,1:y)]
```
[Try it online!](https://tio.run/##hc/BCsIwDADQ@76i7tJGJjQqCoNe/QJvY6fRSmFspZ3gEL@9NnOoIMwQkhBeKfHRee183@gQmGLm2jWD7TsRBm@7C9xTD661w7woOIeqwrpWiiN/ZEbF95NbMYIYSwkVluN6s2rSJk1QR2uEEZ9/RC4lokSqSDWHYgdwZroNmp2yH/6ySbHtEiNFMcnjoqQgdVhWOCXB/R84s68zYnwC "R – Try It Online")
Outputs zero for falsy, and a vector with non-zero first element (which is truthy in [R](https://www.r-project.org/)) for truthy.
(test setup stolen from [Cong Chen's R answer](https://codegolf.stackexchange.com/a/247312/95126)...)
[Answer]
# Desmos, ~~85~~ 62 bytes
```
f(l,s)=max(0,sign(s-mod([1...l.length][l=0],s).unique.length))
```
*-23 bytes thanks to Aiden Chow*
[Try it on Desmos!](https://www.desmos.com/calculator/ucsrg0jryz)
[Answer]
# [Java (JDK)](http://jdk.java.net/), 67 bytes
```
(j,l,s)->{int r=1<<j;for(l|=--r>>s%j<<s;l>0;l>>=j)r&=l;return r>0;}
```
[Try it online!](https://tio.run/##bZFRi5wwEMff91MMC1tiiaJ3pYW6@tKnQguFe1z2IedGGxsTmYkL1@1@djvR63LXVmKcGec/P/JPr84q7U8/ZjOMHgP0nGdTMDZrJ9cE4132ttw0VhHBV2UcXDYAxgWNrWo0fDH26Zt3p0/oiTTCBR69t1o5aJRbioKboZ@GUUYZWGONpjUm81MnJVx54jg9WtMABRX4c/bmBAPTxENA47rDERR2lCxw@Afaou@gmkUvraQkrS9xOFbFft@XrUdhf1VpinVNu36/p9LWOb911Sf4prIl6jChA@TqdS4XAItAnBVGKnx8xQaI9VGhGgiq@Cuj0ZogthK2SfmiZz0p93xmtzqNGYtIcyJW9SE/yrub4oUwmvU/2V@sQ3F8xUNNkw0sjHZkN/tX6//YfkNnVrsufBfJbcbDEwU9ZH4K2cimh1ZsdwRpDTvaOSYyXj5DnjXx4q6b6zzneVHkRdyLuEu4n9dcwt0cg/hw8mFeIgnvo2RZEt6tco7ufwM "Java (JDK) – Try It Online")
Takes input as three `int`s: the jump size, the lily pond as an integer and the size of the pond
## Explanations
```
(j,l,s)->{ // 3 parameters: jump size, lilies positions, pond size
int r=(1<<j)-1; // Result. By default all entries are crossable
for(
l|=r>>s%j<<s; // Ensure the banks of the pond are jumpables.
l>0; // Stop when all jumps are done
l>>=j) // Prepare the next jump
r&=l; // Do all tests for the n-th jump at once.
return r>0; // Return whether any jump line fully succeeded.
}
```
# Credits
* -2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ι€ßĀà
```
First input is the jump-distance, second the string of water/lilies with `0`/`1` similar as the challenge description.
[Try it online](https://tio.run/##yy9OTMpM/f//3M5HTWsOzz/ScHjB//9mXAYgAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC8f9zOx81rTk8/0jD4QX/df5HRxvrKBkYGBoaGIJIQxCpFKujEG2kowQRA/PMgYqAHBCACJiBdAEBmGMCNgKMwHyYkUBeLAA).
5 instead of 6 bytes by taking advantage of [a bug in 05AB1E that causes `Ā` to be truthy for empty strings `""`](https://github.com/Adriandmen/05AB1E/issues/189). The 6 byter without bug-abuse would have been [`ι€ß_ß_`](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC8f9zOx81rTk8Px6I/uv8j4421lEyMDA0NDAEkYYgUilWRyHaSEcJIgbmmQMVATkgABEwA@kCAjDHBGwEGIH5MCOBvFgA). (It could have been 4 bytes [`ι€ßà`](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC8f9zOx81rTk8//CC/zr/o6ONdZQMDAwNDQxBpCGIVIrVUYg20lGCiIF55kBFQA4IQATMQLqAAMwxARsBRmA@zEggLxYA) if the length of water/lilies string was \$\geq\$ the jump-distance, which isn't the case for test case `6,"00000"`.)
**Explanation:**
```
ι # Uninterleave the (implicit) second input-string to the (implicit)
# first input-integer amount of parts
ۧ # Get the minimum of each part
Ā # Transform empty strings to 1s with a bugged Python-style truthify
à # Get the maximum of this list
# (which is output implicitly as result)
```
[Answer]
# [C(GCC)](https://gcc.gnu.org/), ~~105~~ 99 bytes
*-6 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*, but I want to keep the inside while
```
j(a,b)char*a;{char*c=a,*d=a,m=1,o=0;for(;c-a<b;o|=m++,d=c++)while(*++d)m&=*d-48||(d-c)%b;return o;}
```
[Try it online](https://tio.run/##dY9BDoIwEEXXcgrSBNPSadIqUZOxN3FTWlFIANPgCjg70upSfiZ/knlvM1Y8rF2WhhoomX0anxsc47baQO7WarWCXkusek/RCnMtsZ90yzk4bTln8Z5z7pC1e507UVymiTphWVaivw9v36U9zktr6o6yMdm9fN0NFSVZfesIpA0lUiolVWgVmsCRMfwnfi0Chw0ecMiqnLeUEAKnTaziECii8XtAYjIvHw) The idea is to try all possible starting points and then go through the whole string and do something only when on a place the frog lands. If frog's jumping power would be limited to 32 max, it would be possible to golf more (88 bytes), like:
```
j(a,b)char*a;{char*d=a;unsigned m=(1<<b)-1;while(*++d)m&=-1u^49-*d<<(d-a)%b;return !!m;}
```
[Try it online](https://tio.run/##dY9dC4IwFIav81fIwNiXsJVUsPZPupmbppJbDKML9bcvZ13my@GBw/vA4ej8rnUIHdSN8ljR1g5picZ101JRbBb0klMnmaidh0Ln6loKIzUhaHw37aOCGBJiEOr3Epu8uEwTNLlGWSncJHtCxOyr4eVt6sQcetVaiMZk9/TLrRqCrL1ZQNMOAsY4ZzySRwJ6REj8E78WoIeNPtYxi3LeUmIAPW3WfB1Ai9X4PcBEMocP) Here I would simply have a bitflag for each possible start, and use !! to normalize the result.
[Answer]
# Minecraft Command Blocks, 403 bytes
[](https://i.stack.imgur.com/Gisvu.png)
The commands in the command blocks from left to right:
```
scoreboard objectives add o dummy
execute store result score d o run data get storage a d
data modify storage a c set from storage a b[0]
execute if data storage a {c:0} run scoreboard players add c o 1
execute if data storage a {c:1} run scoreboard players reset c
data remove storage a b[0]
execute if score c o = d o run say 0
setblock 0 0 0 air
execute unless data storage a b[0] run say 1
setblock 0 0 0 air
```
Input is given with the command `/data merge storage a {d:2,b:[0,1,0,1...]}` where `d` is the frog's jump length and `b` is an array representing the lily pads.
## Explanation
When the lever is pressed, the repeating command block (purple) executes every gametick, with the chain command blocks (green) executing after it in sequence. The third-last and last command blocks are conditional, which means they will only execute if the previous command block was successful.
```
scoreboard objectives add o dummy Create scoreboard objective to store variables in
execute store result score d o run data get storage a d Store the jump distance in d
data modify storage a c set from storage a b[0] Get the first value of the lily pad array
execute if data storage a {c:0} run scoreboard players add c o 1 If the value is zero increment the jump counter by 1
execute if data storage a {c:1} run scoreboard players reset c If the value is one reset the jump counter
data remove storage a b[0] Delete the first value of the array
execute if score c o = d o run say 0 If the jump counter is equal to the jump distance print 0 (fail)
setblock 0 0 0 air (conditional) Delete the lever to stop the loop
execute unless data storage a b[0] run say 1 If the array is empty print 1 (success)
setblock 0 0 0 air (conditional) Delete the lever to stop the loop
```
[Answer]
# [HBL](https://github.com/dloscutoff/hbl), 19 [bytes](https://github.com/dloscutoff/hbl/blob/main/docs/codepage.md)
```
?('?,)1(1,)('?.(2.,
+(*(),(<2(*-(0,)).
```
Takes two arguments: a list of 1s and 0s, and an integer. Returns 0 for falsey and a nonzero integer for truthy. [Try it at HBL online!](https://dloscutoff.github.io/hbl/?f=0&p=PygnPywpMSgxLCkoJz8uKDIuLAorKCooKSwoPDIoKi0oMCwpKS4_&a=KDAgMCAxIDEgMCAwKQoz)
### Explanation
The first line is a recursive helper function that takes the number as its first argument and a partial list as its second argument:
```
?('?,)1(1,)('?.(2.,
? If
, the second argument
('? ) is empty, then:
1 Return 1 (we've reached the other side of the pond)
Else, if
(1 ) the first item in
, the second argument
is truthy (nonzero), then:
('? Recur
. with same first argument
and second argument equal to
(2 drop
. (first argument) many items
, from the front of second argument
Else, return the falsey value from the last test (0)
```
The result will be 1 if the pond can be crossed by starting with the first lily, 0 otherwise.
Then the main function trims off between 0 and N-1 elements from the start of the list, applies the helper function to each trimmed list, and sums the results:
```
+(*(),(<2(*-(0,)).
, Second argument (jump distance)
(0 ) Inclusive range from 1 to that number
(* ) Map
- decrement
2 Drop that many
(< for each of those numbers
. from first argument (list of lily pads)
(* For each of those lists
() call the helper function
, with main function's second argument as first argument
and the trimmed list as second argument
+ Sum
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-xp`, 9 bytes
```
$|$&*aUWb
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkWBUuyCpaUlaboWK1VqVNS0EkPDkyB8qPCWaKVoQ2sDaxAGkrFKOgpGMC0A) Or, [verify all test cases](https://ato.pxeger.com/run?1=m724ILNgWbSSboBS7MLqpaUlaboWK1VqVNS0EkPDkyD8mxtqFXxDFaK5oqMNFAwUDIHQAIwhbEMYO1bBOBaoBkk2VsEoFqwLwodBoLh5LNQ0MIxVMEPjm8bCbYOTsQomsShuMECx0RDuhliIuxcsgNAA).
### Explanation
```
$|$&*aUWb
a First command-line input (list of 1s and 0s)
UW Unweave into this many strands:
b Second command-line input (jump distance)
$&* Fold each of those strands on logical AND
$| Fold the list of results on logical OR
```
That is, there must be at least one strand which contains only 1s.
[Answer]
# JavaScript (ES6), 52 bytes
Expects `(distance)(string)`.
```
(n,k=n)=>g=s=>k--&&[...s].every((x,i)=>i%n|x)|g(1+s)
```
[Try it online!](https://tio.run/##dY5RC4IwFIXf@xUySO4lna6inuZP6D2iB7EpS9nChRj439emJBV4uJyX893DueddbopWPp6x0jdhS25BRTVXyLOKG57VcRyGF0qpuVLRifYF0EfSpXKthh6HCtjGoC20MroRtNEVlLBDIGnKWMq8M@8EMUiSgJyFIatfeuvoCSUYfDTRJ/0PH321Y71mfrH6MA5x@mpepvfT7PHmh3mIfQM "JavaScript (Node.js) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 52 bytes
```
[| s n | n 1 s indices [ n mod ] map cardinality > ]
```
[Try it online!](https://tio.run/##XU/BCoJAFLz7FdM9QisKirxGly7RSTws60oL62q7GyG6327PRLHeMMvMG3jL5Iy70nT32@V6PkCVnCkLK54vobmwKJh7kHUWlRHO1ZWR2oFZW3KLYxA0AWgaQkQICdGXgw4n7bEh9rMgf8KbOWGWFJygpKorlk2H5ic81vCzL4b9iD7f/@QjPHZ/@3D2emwp9UGXtLDQaIkRKakz2ZdOyBdlhpTqV@DMZFIzJV2NGGmXD/XjPlt1Hw "Factor – Try It Online")
Port of Unrelated String's first [Jelly answer](https://codegolf.stackexchange.com/a/247303/97916).
```
! s = { 1 1 0 0 1 0 1 1 0 0 0 0 1 1 0 }, n = 3
n ! 3
1 ! 3 1
s ! 3 1 { 1 1 0 0 1 0 1 1 0 0 0 0 1 1 0 }
indices ! 3 V{ 0 1 4 6 7 12 13 }
[ n mod ] map ! 3 V{ 0 1 1 0 1 0 1 }
cardinality ! 3 2
> ! t
```
[Answer]
# [J](http://jsoftware.com/), 19 16 bytes
```
[>#@~.@(|[:I.-.)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o@2UHer0HDRqoq089XT1NP9rcvk56SlE24EFPfUcgGJgEW09fQcNjRrlGE0tfX29WE0dNUOu1OSMfAVDBVsFY4U0oJkGQLYhmISxDWFsiFIDoFIjoFIkRQgzzKBmgCFC2BwsbIiQQjXOBG4znPwPAA "J – Try It Online")
*-3 taking the approach from [Unrelated String's jelly answer](https://codegolf.stackexchange.com/a/247303/15469)*
## original answer [J](http://jsoftware.com/), 19 bytes
```
+./@((|#\)*//.]),&1
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tfX0HTQ0apRjNLX09fViNXXUDP9rcqUmZ@QrGCrYKhgrpAEVGwDZhmASxjaEsSFKDYBKjYBKkRQhzDCDmgGGCGFzsLAhQgrVOBO4zXDyPwA "J – Try It Online")
Consider `3 f 0 0 1 1 0 1 0 0 1 1 1 1 0 0 1`:
* `,&1` Append a 1:
```
0 0 1 1 0 1 0 0 1 1 1 1 0 0 1 1
```
* `(|#\)` Label each 1..n and then mod by 3:
```
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 <-- mod 3
```
* `*//.]` Use the last row to group the original input, and take the product of each group:
```
0 0 1 1 0 1 0 0 1 1 1 1 0 0 1 1
1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 <-- mod 3
0 1 0 1 0 1│0 0 0 1 0│1 1 1 1 1
^ ^ ^
1-group 2-group 0-group
0 │ 0 │ 1
^ ^ ^
1-group 2-group 0-group
product product product
```
* `+./@` Is there a 1 among them? That indicates a valid path.
```
1
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 48 bytes
```
~(L$`.+$
*
C`\B
.+
^(^.{0,$&}1|$&*.1)$*.{0,$&}\n
```
[Try it online!](https://tio.run/##K0otycxLNPyvqhGcoPO/TsNHJUFPW4VLi8s5IcaJS0@bK04jTq/aQEdFrdawRkVNS89QU0ULKhCT9/@/gYGhoYEhiDQEkTrGXBCujhEXiAYBQx1zLjBDxwxIG4KRjgkA "Retina – Try It Online") Takes pond and jump size on separate lines but link is to test suite that splits on comma for convenience. Explanation:
```
~(
```
After running the rest of the program, treat the result as its own Retina program, and execute that on the original input.
```
L$`.+$
*
C`\B
```
Delete the pond and decrement the jump size.
```
.+
^(^.{0,$&}1|$&*.1)$*.{0,$&}\n
```
Replace the decremented jump size with a regular expression that matches crossable ponds. Example: If the jump size is `7`, then the following expression is produced:
```
^(^.{0,6}1|......1)*.{0,6}\n
```
This optionally matches up to six digits and a `1` followed by multiple matches of six digits and a `1`, finishing with up to six digits and the newline that separates the pond from the jump size.
[Answer]
# [C++ (clang)](http://clang.llvm.org/), 91 bytes
```
[](auto p,int s){int i=s,j,a,r=0;for(;a=i;r|=a)for(j=--i;j<p.size();j+=s)a&=p[j];return r;}
```
[Try it online!](https://tio.run/##lZJNS8QwEIbPza8YKmiDqazfsGnXk1dPgoh6CG2sKdskJGlR1/3r1rRd3G9ESBlm3j6Zd6bNtI6zKZNFeyBkNq1zDolQ1hnOqglCjld6yhxP3IfmklUc7ieoUSL3inXRPWglcwJCOvCMyDnxMR@Pu0QWwN81zxxGMxT05UzVDpIEwtte4PkYwi4f3kNBEEAvP7tCuYUWtU8vEaudAk36PnjWBZFaUhJGTDqir8pElKWCmq@U4S4r0zgWtEz0iRWfPMK0PE4tZoepfipfqOGuNhIMnbfRMMBgHsMNhI/chuB736kQd/2PnuURRXOElgtqvFll/Hq8EVQxIaNuJcsxBz3x6gQailDQnDBrRSGjGYxId@LT4Rn9hpXiithXYY4pCvqFNwTOyeARb1y847p18IwMQ20bWjKrZ5O/3tN4DVtHrv6PXO51ubWrbfjiL3g3dr6CLf6Nkf/k7Xf2OmWFbeMHqWLNDJfujVtufwA "C++ (clang) – Try It Online")
input: `lily = -1, water = 0`
### gcc-specific (abusing UB):
# [C++ (GCC)](https://gcc.gnu.org), 89 bytes
```
int f(auto p,int s){int i=s,j,a,r=0;for(;a=i;r|=a)for(j=--i;j<p.size();j+=s)a&=p[j];s=r;}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lZLfSsMwFMbBu-YpDhVcg9nonE5Z2nnlrffDiZQ2GylbU5K0iHNP4s1uvJQ9jz6NTSOu-4dIEw7nO-eX8zXt20eczwpl9tM0jler90JP2jefI55pmHhRoQXkxCQKL0zgoSIpiYgMfToR0qNRyKl8DSNssjRstzlNg7yj-AvzME3PQ4WjszB_SB-pCiVd2gFfJ-tTnsWzImEQcKG0ZNF8iDZayWIt5BChUvAEaaa0p3QyGFg9qKwMIRdZQqA2pyVPGIG6xSTZFNhzXvVitEBOLcei0BAE4N7VBZYMwDW57UOO40BdHuup0D81b-LZIXYAhltwR0y5UNXvhYtNT2uctShaIlQZQfOIZ56xvJnbdFxShJyyEynFp5m3AJ-Y1e7a7f-Ghtgo1iosMUVOfSElgR6xhvDOwQeO2wYviH2DfUMbprl2-esjg7ewbaT_f-TqqMu9u9qHL_-CD2O9BiaZLmQGfvV97X-7WvdQH_kV062eKlr5Gw)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
Nθ¬⌊Eθ№✂ηιLηθ0
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDN7EiM7c0F0gXaBTqKPhm5oG5wTmZyakaGToKmToKPql56SUZGhmaOgqFmiBg/f@/MZeBgaGhgSGINASR/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Takes the jump size as the first parameter and the pond as the second parameter and outputs a `1` if the pond can be crossed, `0` if not. Explanation: Based on @MatteoC's Python answer.
```
Nθ First input as a number
θ First input
E Map over implicit range
№ Count of
0 Literal string `0` in
η Second input
✂ Sliced from
ι Current index to
η Second input
L Length
θ In steps of first input
⌊ Take the minimum
¬ Logical Not i.e. is zero
Implicitly print
```
I tried porting @UnrelatedString's Jelly answer but the best I could do was also 14 bytes:
```
Nθ‹υ⁻…⁰θ﹪⌕Aη0θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDJ7W4WKNUR8E3M6@0WCMoMS89VcNAR6FQEyiUn1Kak6/hlpmX4piTo5Gho6BkoKQJkgMC6///jbkMDAwNDQxBpCGI/K9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Takes the jump size as the first parameter and the pond as the second parameter and outputs a Charcoal boolean, i.e. `1` if the pond can be crossed, nothing if not. Explanation:
```
Nθ First input as a number
υ Predefined empty list
‹ Is less than
… Range from
⁰ Literal integer `0` to
θ First input
⁻ Remove elements from
⌕A Find all occurrences of
0 Literal string `0`
η In second input
﹪ Vectorised modulo
θ First input
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, 49 bytes
```
$l=<>-1;$_=/^.{0,$l}(.{$l}1)+.{0,$l}$/||$l>=y///c
```
[Try it online!](https://tio.run/##K0gtyjH9/18lx9bGTtfQWiXeVj9Or9pARyWnVkOvGkgaampD@Sr6NTUqOXa2lfr6@sn//xuAAZfZv/yCksz8vOL/ur6megaGBv91C3IA "Perl 5 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes
```
Length[{}⋃Flatten@#~Position~0~Mod~#2]<#2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yc1L70kI7q69lF3s1tOYklJap6Dcl1AfnFmSWZ@Xp1BnW9@Sp2yUayNspHa/4CizLwSBQeFtOhqAx0DHUMgNABjCNsQxq7VUTCO5UJSjaSuVscIRQomAYNABeZoCqCwVscMQwJmOVjaBIs0VMo49j8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 62 bytes
```
.+$
$*
^(?=.*¶1(1)*)(?<-1>.)*((?(3)^)1(?=.*¶1(1)*)(?<-3>.)*)*¶
```
[Try it online!](https://tio.run/##K0otycxL/K@qEZyg819PW4VLRYsrTsPeVk/r0DZDDUNNLU0NextdQzs9TS0NDXsNY804TUMMaWOQtCZQ6P9/AwNDQwNDEGkIInWMuSBcHSMuEA0ChjrmXGCGjhmQNgQjHRMA "Retina 0.8.2 – Try It Online") Takes pond and jump size on separate lines but link is to test suite that splits on comma for convenience. Explanation:
```
.+$
$*
```
Convert the jump size to unary.
```
^(?=.*¶1(1)*)(?<-1>.)*
```
At the start of the pond, match up to (but not including) the jump size number of digits, then...
```
((?(3)^)1(?=.*¶1(1)*)(?<-3>.)*)*¶
```
... repeatedly match a `1` plus up to the jump size number of digits for the last repeat before the end of the pond, except that the condition at the beginning of the repeat means that the maximum number of digits must have been matched on all the previous repetitions.
[Answer]
# Desmos, some bytes
```
t(V)=V.length
R(V)=[sign(t(V)-i+.2)/2+.5fori=[1...t(V)+100]]
X(V)=[1-R(V)[j]+R(V)[j]V[jR(V)[j]+1-R(V)[j]]forj=[1...t(V)+100]]
f(V,z)=∑_{y=1}^z∏_{v=1}^{floor((t(V)-y+z)/z)}[X(V)[y+kz]fork=[0...(t(V)-z+10-y)/z]][v]
```
[Answer]
# [Scala](https://www.scala-lang.org/), 89 bytes
Golfed version. [Try it online!](https://tio.run/##RZBBS8QwEIXv/RWPXnYCdWlUFMpmQTwJehJP4iG7pjUlmw1NFJdlf3udtAWHZOB9ZPJeEvfa6fG4680@4UVbj/P4aVq05Jsnn6rQvKbB@k4oqvHtk3XwYm1@bUyRrNqSXWhYO@O79IXdKZ9oj4N2jnq1DdQLpVZyJcQI5LsPbEN66GKDh2HQp/fZ4kM0ePM2QeFcgOtHOyQT06OOJjJ9ZlOisq6lrGXuMveywo2oQOUMWV5PMqtcmdzPJBeru0XJaTG4FaKYHDk1iELFL8Dm6t9cLImAwEmT88T/UyHwXIaXIu/L@Ac)
```
def f(n:Int,p:String)=(0 until n).exists(i=>(i until p.length by n).forall(j=>p(j)=='1'))
```
Ungolfed version. [Try it online!](https://tio.run/##RZBBS8QwEIXv/RWPXnYCdWlUFIoV1IuCnsSTeMiu2W5KTEMTxUX2t9dJWjQkA@8x5HszYausmqZh0@ttxJMyDj8F8K538Pcq7Mk1eHCxgm/wHEfjOtHgdhisVg5t7gWoxqeLxsKJtf42IQYyaK/Bdfb92mrXxT02h9SzG0ZlLfWpx1Mv0LZYyZUQ/NuxWPAfnIXU2IUGN@OoDq8z/o35L87EP/iXsog6xDsVdGD3kflEZV1LWctUZaplhTNRgcrZZHmaZVLpJOdydtJhdbEomS8b55wvEzk@iHzFo@Dq5B8ulkSA56TROlpWyNvLs6Xp0jsW0/QL)
```
object Main {
def pHash(n: Int, p: String): Boolean = {
(0 until n).exists(i => (i until p.length by n).forall(j => p(j) == '1'))
}
def main(args: Array[String]): Unit = {
val testCases = List(("001101001111001", 3), ("101001", 2), ("010000001", 7), ("00000", 6), ("00100100", 4))
for ((p, n) <- testCases) {
println(pHash(n, p))
}
}
}
```
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 6 bytes
```
>⧻◴◿,⊚
```
[Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAgPuKnu-KXtOKXvyziipoKCmYgWzEgMSAwIDAgMSAwIDEgMSAwIDAgMCAwIDEgMSAwXSAzCmYgWzAgMSAwIDEgMSAwXSAyCmYgWzEgMCAxIDEgMSAxIDEgMSAwXSA3CmYgWzEgMSAxIDEgMV0gNgpmIFsxIDEgMCAxIDEgMCAxIDFdIDQK)
Port of UnrelatedString's [Jelly answer](https://codegolf.stackexchange.com/a/247303/97916).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 49 bytes
```
n=>k=>eval(`/^((.|^|$){${n-1}}(1|$))*$/`).test(k)
```
[Try it online!](https://tio.run/##dY5RC4IwFIXf@xVj@HBvoHMV9aQ/ofdexGEzyrFFE1/U3742JanAw@XAge8ezkN0wlav@7ONtblKV2dOZ3mT5bITCkpWACRDMUTYR72O@TgC9wG3ESsxaaVtoUFXGW2NkokyN6hhj0DTlPOUB@fBKSJhjNCLtHTzS@88PaMUyUczfTb/8ClUezZo4Verj9MQr6/mdfowz55ueViGuDc "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
## Or *Fix American Kennel Club's database*
As covered by the recent [video by Matt Parker](https://www.youtube.com/watch?v=jMxoGqsmk5Y), the American Kennel Club *permits thirty-seven (37) dogs of each breed to be assigned the same name* ([source](https://www.akc.org/register/information/naming-of-dog/)), because of a database restriction for Roman numeral length.
Given an integer, your task is to output the length of its Roman representation.
## Rules
* Your input will be an integer in the range 1-3899.
* Conversion to Roman is performed using the [standard subtractive notation](https://en.wikipedia.org/wiki/Roman_numerals#Standard_form) (so `4=IV`, `9=IX`, `95=XCV`, `99=XCIX`).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the usual rules apply.
## Test-cases
```
input output
1 1
2 2
3 3
4 2
5 1
6 2
9 2
10 1
37 6
38 7
95 3
99 4
288 10
2022 6
3089 9
3899 11
```
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
f=lambda x:x and 5739180/5**(x%10)%5+f(x/10)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY5NCsIwGESvkk0hrSPNjzH5Cl7AK4iLSAkWNC0lQjyLm27EM3kbs6i7xzDzmNdneqbrGNWyvB8pbN0X4XDz90vvWe4y87FnxmqSTrSmaXiupKgrswk8t4XWzTGMM8tsiOwkoaCxg8EeFg4EKaAtdEEDIijnoIQqLeGoxETnbpqHmHhx1qvx_-YH)
The magic number `5739180` encodes the list `[2, 4, 3, 2, 1, 2, 3, 2, 1, 0]` in base 5, which correspond to the Roman numeral lengths for the decimal digits 9 to 0. `5**(x%10)%5` extracts the `x%10`th base-5 digit, and the rest is a recursive function to compute the sum per decimal digit of `x`.
[Answer]
# JavaScript (ES6), 37 bytes
```
f=n=>n&&+"0123212342"[n%10]+f(n/10|0)
```
[Try it online!](https://tio.run/##ddDBCsIwDAbgu09RBo6NoUvSbmsP80XEw5ibKKMVJ5589ypoB1ZyyOkjyZ9cukc397fz9b6x7jh4P7a23dk0LRJAkvQuRcnerhEOxZjZEuEJue@dnd00bCd3ysYMhRB5LspS4OpXaBGKRC4iI1FsT8XuqdkewwoCN002QepYdJAm3lNx9xgTRMXf0TokgJiAiIkA2nzE/IUzX0H0Lw "JavaScript (Node.js) – Try It Online")
### How?
In standard subtractive notation, the lengths of the digits are the same for units, tens, hundreds and thousands (up to 3000). So we can just recursively compute the total length.
```
| units | tens | 100's | 1000's | length
---+-------+------+-------+--------+--------
0 | - | - | - | - | 0
1 | I | X | C | M | 1
2 | II | XX | CC | MM | 2
3 | III | XXX | CCC | MMM | 3
4 | IV | XL | CD | | 2
5 | V | L | D | | 1
6 | VI | LX | DC | | 2
7 | VII | LXX | DCC | | 3
8 | VIII | LXXX | DCCC | | 4
9 | IX | XC | CM | | 2
```
---
# JavaScript (ES6), 40 bytes
This is an attempt to find a short formula instead of a lookup table. But it's still longer.
```
f=n=>n&&f(n/10|0)+(30%(n%=10)&171/n^n%4)
```
[Try it online!](https://tio.run/##ddDPCsIwDAbwu0/Ry0aLaJN2f9rDfBRhzE2UkYoTT757PWgHVnL@kXxfcu2f/TLcL7fHjsJpjHHqqDtQWU6SNMIL1FZaKCQVHYIqsUVNRyoqFYdAS5jH/RzOcpIohFBKaC1w8ytmFZOJXcVmUrEzNZvTsDOeFQRum22TNLm4JG2eU3P3eJ@kyr/jXGoAOYExTAVw/iP@r5z/CmJ8Aw "JavaScript (Node.js) – Try It Online")
### 36 bytes
It does come out shorter if we can take the input as a list of digits:
```
a=>a.map(n=>t+=30%n&171/n^n%4,t=0)|t
```
[Try it online!](https://tio.run/##fdDLDoIwEAXQvV/BBgNxhD54dVF@xNSkQTQabIk0rvz3aggxQLXdnsyd27nJpxyax7U3e6VPrT1zK3ktk7vsI8Vrs@MUhWqLS5yqowozMBzFL2MbrQbdtUmnL9E5OmARjC@OgzQN8GbFZMFkzXTBdM2Zfzr37y7808zPGJDwhFMoZ1y4XM24dHZDLjz/ZsBmnDlHhWqMn6oh1xEQIOJvN/QJYBOzH9WBfRlj@wY "JavaScript (Node.js) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
øṘL
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDuOG5mEwiLCIiLCI5NSJd)
I love it when there's built-ins for things like this.
## Explained
```
øṘL
øṘ # Convert input to Roman numerals
L # and return the length of that.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 41 bytes
Uses [@Arnauld's idea](https://codegolf.stackexchange.com/a/246364/88546) of computing the length of each decimal digit separately. A magic hash in the form `x**a%b%5` seems to work well.
```
f=lambda n:n and(n%10)**24%8684%5+f(n/10)
```
[Try it online!](https://tio.run/##NYzRCoMwDEXf8xV5EdTJ1taqVei3jA4nFjQWp8i@3nVV85LLPSdx36WfSOx7pwczvlqD1BAaamOKOEvSVMhIlUpGxa2L6eGrfevt8EbeAFpyGU7r4lDjaFxsaclwNtvTg3WJk/vHDdbvBNDNHmLnFZeg1uFq5xiGgziCgPwIOcirKS6nvJr6CpydKK9CKCFXIVRQF@ef@rAlCBUYZyCYEIfN1J/W/ixonP8A "Python 2 – Try It Online")
Other magic:
```
lambda n:sum(7125144/ord(c)%5for c in`n`) # 41
f=lambda n:n and(n%5+n/5%2>>n%5/4)+f(n/10) # 42 (has actual strategy)
```
# [Python 2](https://docs.python.org/2/), 41 bytes
Alternatively, the same length, but who doesn't love a little magic `hash`?
```
lambda n:sum(hash(c+'WQDE')%5for c in`n`)
```
[Try it online!](https://tio.run/##NYzLCoMwEEX38xWzKRoqxSS@wV37AV11U6jpQyJoDD6Qfr1NE53NXO45M/o7yV6xtS7vayu651ugKsa586UYpf86erfr@eKRQ1z3A76wUZWqyLrIpv0gLcAUOsB@njSW2AntN2oKcBDLw4B58slp1G1jNgHUg4FYG0UTLEt7tVK0Q4G5wIC7wCHam3h3kr3J90DDDfHUhgR4ZkMKebz9yZ0dAcssoyGwkDFnh9mf5ubMapT@AA "Python 2 – Try It Online")
The little C script below finds all possible 4-byte long suffixes to seed the hash, and takes roughly a second to complete. Interestingly, out of the 12 valid solutions, `'WQDE'` is the only one with all uppercase characters. If you think about it, the chances of this occurrence are only `26^4/127^4 ~ 0.176%`!
```
// https://github.com/python/cpython/blob/v2.7/Objects/stringobject.c#L1263
#include <stdio.h>
#include <time.h>
int py_mod(long long x, int m) { int ret = x % m; return ret >= 0 ? ret : ret + m; }
const long long h[10] = {6144036912055440, 6272037681056595, 6400038450057750, 6528039219058905, 6656039988060060, 6784040757061215, 6912041526062370, 7040042295063525, 7168043064064680, 7296043833065835};
long long h0[10], h1[10], h2[10];
int main() {
clock_t sclock = clock();
for (int c0 = 1; c0 < 128; c0++) {
for (int i0 = 0; i0 < 10; i0++) h0[i0] = (h[i0] ^ c0) * 1000003;
for (int c1 = 1; c1 < 128; c1++) {
for (int i1 = 0; i1 < 10; i1++) h1[i1] = (h0[i1] ^ c1) * 1000003;
for (int c2 = 1; c2 < 128; c2++) {
for (int i2 = 0; i2 < 10; i2++) h2[i2] = (h1[i2] ^ c2) * 1000003 ^ 5;
for (int c3 = 1; c3 < 128; c3++) {
if (py_mod(h2[0] ^ c3, 5) != 0) continue;
if (py_mod(h2[1] ^ c3, 5) != 1) continue;
if (py_mod(h2[2] ^ c3, 5) != 2) continue;
if (py_mod(h2[3] ^ c3, 5) != 3) continue;
if (py_mod(h2[4] ^ c3, 5) != 2) continue;
if (py_mod(h2[5] ^ c3, 5) != 1) continue;
if (py_mod(h2[6] ^ c3, 5) != 2) continue;
if (py_mod(h2[7] ^ c3, 5) != 3) continue;
if (py_mod(h2[8] ^ c3, 5) != 4) continue;
if (py_mod(h2[9] ^ c3, 5) != 2) continue;
printf("found: (%d,%d,%d,%d) [%c%c%c%c]\n",
c0, c1, c2, c3, c0, c1, c2, c3);
}
}
}
}
printf("Time elapsed: %.3fs\n", (double) (clock() - sclock) / CLOCKS_PER_SEC);
return 0;
}
```
[Answer]
# Excel, 15 bytes
```
=LEN(ROMAN(A1))
```
It feels like a rare win to use an Excel built-in for a programming challenge.
[](https://i.stack.imgur.com/yUlyL.png)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~39~~ 37 bytes
```
->n{n.digits.sum{|x|x%5>3?2:x/5+x%5}}
```
[Try it online!](https://tio.run/##JYtNDoIwGET3nqIbjcax9odCPxPwIIaFxmBYQIhIrAHOXkvZTN68zLyHx89XuT8V7djyZ/2qPz3vh2ac3OS2ptBXdXFncww8z75j3/wmoaCRwCAFQQroDNqCDIigrIUSKiyEpaCJSt7cu/2uOmyW93JnCkzHXHmFFCyLPglVxE6BZOn/ "Ruby – Try It Online")
Thanks dingledooper for -2 bytes (pointing out that 37 and 39 are two different numbers, which I didn't realize)
[Answer]
# x86-64 machine code, 27 bytes
```
97 31 C9 67 8D 71 05 99 F7 F6 F6 C2 04 D1 D8 74 02 D1 EA 11 D1 85 C0 75 EE 91 C3
```
[Try it online!](https://tio.run/##XVLBbuIwED3HXzGbFWoCpqKh7ZKw9NLzXva0EnAwtpO4Mg4bh64B8evNjkNo1VqKo3lv/OaNx3y3Gxect@13ZbjeCwk/bSNUdVs@kU@QVpuvWK1M4TEiXSNrA@FzCCdlGsgjv7N4fibMbiGC32FEbgtdbZiGnORZ4HhZgBSKgmSOBK6qQXJH/UYCLRlIi9wSw9HDmugs4OIvCYR69QQJGmkbEJrCPQlqXnsRCnckeDmCJYEtEREdYrOACd5rC9ef7NK7wi/mCJr0dvgVrWVD4hDiOSG@kS1T5tJRXXAKvGQ1DIcYvMbkRACXJx0sYELh4H/zd9TX48xKu1wjcbqjkFCYonEKDxQeKaRoE49Nf@A3wxDRFLFkhkEySXz2ZJZ6Mk3PF90cb6vzc8w@9OOO8muHc2nyKBwoGD/BQK1MSOFIcSrHOL4oXFNW5hfjpTISeCVkFva0@@hBVHC6ZsNgkvxBrcMiivbGqsJI0d3GMM7jpRuN1jhx@FcqLSE6wDcUcc/TLyUhQl@bA/qOO2Puyu8bLxXdrMxND@EY9vis0MmZtO0bzzUrbDvePt7jhg9rgYpS/wc "C++ (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes a number in EDI and returns a number in EAX.
In assembly:
```
f: xchg edi, eax # Exchange the input number into EAX.
xor ecx, ecx # Set ECX to 0. ECX will hold the running total.
lea esi, [ecx+5] # Set ESI to 5.
l: cdq # Sign-extend, setting up for the next instruction.
div esi # Divide by 5, putting the quotient in EAX and the remainder in EDX.
test dl, 4 # Set flags based on the bitwise AND of the low byte of EDX with 4.
# This makes the zero flag (ZF) 1 iff the remainder is not 4.
# Also, the carry flag (CF) becomes 0.
rcr eax, 1 # Rotate EAX together with CF right by 1.
# With CF being 0, this halves EAX, putting the remainder into CF.
# This also leaves ZF unchanged.
jz s # Jump, to skip one instruction, if ZF is 1.
shr edx, 1 # (For remainder 4) Shift EDX right by 1,
# changing it from 4 to 2 and making CF 0.
s: adc ecx, edx # Add EDX+CF to the total in ECX.
test eax, eax # Set flags based on EAX.
jnz l # If it's not zero, jump back to repeat.
xchg ecx, eax # Exchange the total from ECX into EAX.
ret # Return.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 13 bytes
```
D‘ị“ȤɱȯẎ’DU¤S
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FrtdHjXMeLi7-1HDnBNLTm48sf7hrr5HDTNdQg8tCV5SnJRcDFW3LFrJ2EIpFsoDAA)
```
D digits
‘ add 1 to each (because Jelly uses 1-based indexing)
ị ¤ index into:
“ȤɱȯẎ’ compressed integer 2432123210
D digits
U reversed
S sum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“Mḅṗʋ’D⁸ṃS
```
A monadic Link that accepts a positive integer and yields the Roman numeral count as a positive integer.
**[Try it online!](https://tio.run/##ASMA3P9qZWxsef//4oCcTeG4heG5l8qL4oCZROKBuOG5g1P///8xOA "Jelly – Try It Online")**
### How?
```
“Mḅṗʋ’D⁸ṃS - Link: positive integer, N
“Mḅṗʋ’ - base 250 integer = 1232123420
D - to decimal -> X = [1,2,3,2,1,2,3,4,2,0]
⁸ - N
ṃ - base-decompress using X as the the new digits [1,...,9,0]
S - sum
```
---
Note that `“Mḅṗʋ’D` saves one byte over using the pattern of the lengths themselves with `3,4R;0j2`
i.e. `[3,4] -> [[1,2,3],[1,2,3,4]] -> [[1,2,3],[1,2,3,4],0] -> [1,2,3,2,1,2,3,4,2,0]`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
StringLength@*RomanNumeral
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7ikKDMv3Sc1L70kw0ErKD83Mc@vNDe1KDHnfwBQpiRaWdcuzUE5Vq0uODkxr66ay1CHy0iHy1iHy0SHy1SHy0yHy1KHy9AAKGQOxBZALlDUEihmZAHkGBkYgVQbWFiCJC0tuWr/AwA "Wolfram Language (Mathematica) – Try It Online")
More built-ins.
[Answer]
# [R](https://www.r-project.org), ~~30~~ 29 bytes
```
\(n)nchar(paste(as.roman(n)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGSNAUb3aWlJWm6FntjNPI085IzEos0ChKLS1I1Eov1ivJzE_OAwpqaEDU3TYoTCwpyKjWSNQytzHQsdQwNdIzNdYwtdCxNdSwtdYwsLHSMDIyMdIwNLCyBwpaWmjppUL0LFkBoAA)
Convert to `roman`, use `paste` to convert to `character`, then find the number of characters.
-1 thanks to pajonk.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.Xg
```
[Try it online](https://tio.run/##yy9OTMpM/f9fLyL9/39jC0tLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vYj0/zr/ow11jHSMdUx0THXMdCx1DA10jM11jC10LE11LC11jCwsdIwMjIAqDCwsgcKWlrEA).
Without Roman-numeral builtin (**10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**):
```
•’λåK•RÅвO
```
[Try it online](https://tio.run/##yy9OTMpM/f//UcOiRw0zz@0@vNQbyAw63Hphk////8YWlpYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Rw2LHjXMPLf78FJvIDPocOuFTf7/df5HG@oY6RjrmOiY6pjpWOoYGugYm@sYW@hYmupYWuoYWVjoGBkYAVUYWFgChS0tYwE).
**Explanation:**
```
.X # Convert the (implicit) input-integer to a Roman-numeral string
g # Pop and push its length
# (after which the result is output implicitly)
•’λåK• # Push compressed integer 2432123210
R # Reverse it: 0123212342
Åв # Convert the (implicit) input-integer to custom-base "0123212342";
# basically convert the integer to base-length as list (base-10 in
# this case), and index the base-values into the string
O # Sum the list together
# (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 `•’λåK•` is `2432123210`.
[Answer]
# [Factor](https://factorcode.org/) + `roman`, 17 bytes
```
[ >roman length ]
```
[Try it online!](https://tio.run/##VdC5CgIxEAbgPk8xvoDk2CNRsBUbG7ESi7DEA3azMRsLEZ89SpIFZ7qPmfkn5KK7MPp4POz22xU4b0J4OX@3Afw4aAuTeTyN7cwEa0LeBH7FINUCWCKfyRPFTJFY4W6NdxvcVZiMomHRFjaZsrDNuzW6q1RhlR8pZYmi2ZTz/ywqVaIq0SqTMfIh8QSb/Bm9sddwg3MctINl/AI "Factor – Try It Online")
Non-builtin version:
# [Factor](https://factorcode.org/) + `math.unicode`, 56 bytes
```
[ >dec 48 v-n [ 5 /mod [ 3 > 2 rot ] keep + ? ] map Σ ]
```
Port of @GB's [Ruby answer](https://codegolf.stackexchange.com/a/246367/97916).
[](https://i.stack.imgur.com/oXeOl.gif)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
(without roman numeral builtin)
```
»ḣ₈ɖ¢»fṘτ∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCu+G4o+KCiMmWwqLCu2bhuZjPhOKIkSIsIiIsIjM4OTkiXQ==) or [Verify all the test cases](https://vyxal.pythonanywhere.com/#WyIiLCLGmyIsIsK74bij4oKIyZbCosK7ZuG5mM+E4oiRIiwiO1rGm2AgPT4gYGo74oGLIiwiWzEsMiwzLDQsNSw2LDksMTAsMzcsMzgsOTUsOTksMjg4LDIwMjIsMzA4OSwzODk5XSJd)
## How?
```
»ḣ₈ɖ¢»fṘτ∑
»ḣ₈ɖ¢» # Push compressed integer 2432123210
f # Convert to list of digits: [2, 4, 3, 2, 1, 2, 3, 2, 1, 0]
Ṙ # Reverse
τ # Convert the (implicit) input to this custom base
∑ # Summate
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 19 bytes
```
T`d`0-321-42
.
$*
1
```
[Try it online!](https://tio.run/##DcqxCYAwEEDR/s@hIEIkuSR6N4ELOEAELWwsxP1P28d7zve6d@@HtfnWjhZDlhSKMNGNJPeEkClUZowUyQtZsYoZoopE@UdU@9nsAw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`d`0-321-42
```
Translate the digits `0-9` into the digits `0123212342`.
```
.
$*
```
Convert to unary.
```
1
```
Take the sum and convert to decimal.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
IΣ⭆S§”)⊞⎚mS”Iι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0VyO4BMhP900s0PDMKygtgXA1NHUUHEs881JSKzSUDAyNjI2A2MRISUcBrC9TEwys//83NrCw/K9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
⭆ Map over characters and join
”)⊞⎚mS” Compressed string `0123212342`
§ Indexed by
ι Current character
I Cast to integer
Σ Take the sum
I Cast to string
Implicitly print
```
The `Sum` of a string of digits (as distinct from an array of digit characters) is the sum of all the integer values of the digits, which saves having to cast them back to integer manually.
[Answer]
# [Python 3](https://docs.python.org/3/), 49 bytes
Port of @Arnauld's JS answer.
```
f=lambda n:n and int('0123212342'[n%10])+f(n//10)
```
[Try it online!](https://tio.run/##FY3BCsIwEAXvfsVepAk@aLJpNVvwS0oPkRIUdFtKD/XrYzzMZRiY9bs/Fw2l5Ps7fR5zIh2Uks700t00znPgSsfNqGfvJnvJRtvWO1vystFRMxo9GAEdelwh8A7hhhAhPUTAMYId18JFqVpkGk5E6/YfZHNYW34 "Python 3 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 17 bytes
```
s@L_j5739180 5jQT
```
[Test suite](http://pythtemp.herokuapp.com/?code=s%40L_j5739180+5jQT&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A9%0A10%0A37%0A38%0A95%0A99%0A288%0A2022%0A3089%0A3899&debug=0)
##### Explanation:
```
s@L_j5739180 5jQT | Full program
------------------+------------------------------------
L jQT | Map over each digit d of the input:
@L | Get the dth element of the list
_j5739180 5 | [0, 1, 2, 3, 2, 1, 2, 3, 4, 2]
s | Sum the resulting list
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ì¿≥Θu^Z6ê)
```
[Run and debug it](https://staxlang.xyz/#p=8da8f2e9755e5a368829&i=%221%22%0A%222%22%0A%223%22%0A%224%22%0A%225%22%0A%226%22%0A%229%22%0A%2210%22%0A%2237%22%0A%2238%22%0A%2295%22%0A%2299%22%0A%22288%22%0A%222022%22%0A%223089%22%0A%223899%22&a=1&m=2)
] |
[Question]
[
In Russia we have something like a tradition: we like to look for lucky tickets.
Here's what a regular ticket looks like:
[](https://i.stack.imgur.com/0bqM1m.jpg)
As you can see, the ticket has a six-digit number.
A six-digit number is considered **lucky** if the sum of the first three digits is equal to the sum of the last three.
The number on the photo is not lucky:
```
038937
038 937
0 + 3 + 8 = 11
9 + 3 + 7 = 19
11 != 19
```
## Challenge
Given the limits of a range (inclusive), return the number of lucky ticket numbers contained within it.
## Parameters
* Input: 2 integers: the first and last integers in the range
* The inputs will be between 0 and 999999 inclusive
* Output: 1 integer: how many lucky numbers are in the range
* You may take the inputs and return the output in [any acceptable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* Assume leading zeros for numbers less than 100000.
## Examples
```
0, 1 => 1
100000, 200000 => 5280
123456, 654321 => 31607
0, 999999 => 55252
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes in every language wins.
Update: here's the lucky one [](https://i.stack.imgur.com/a5RK9.jpg)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8 (or 10?)~~ 11 (or 13?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ÿʒ₄n+¦S3ôOË
```
[Try it online](https://tio.run/##MzBNTDJM/f//6I5Tkx41teRpH1oWbHx4i//h7v//DYwtLE0NuECUgQEA) or [verify some more test cases](https://tio.run/##MzBNTDJM/W/q5un5/@iOU5MeNbXkaR9aFmx8eIv/4e7/tTr/DYwtLE0NuECUAZAyMDSAUIZgygjCMwLxjIzAPCAFkTMwgGkwBAA).
NOTE: In 05AB1E strings and integers are interchangeable, so the output numbers doesn't contain leading zeroes. This could however be fixed with 1 additional byte (**12 bytes**):
```
Ÿ₄n+€¦ʒS3ôOË
```
[Try it online](https://tio.run/##MzBNTDJM/f//6I5HTS152o@a1hxadmpSsPHhLf6Hu///NzC2sDQ14AJRBgYA) or [verify some more test cases](https://tio.run/##MzBNTDJM/W/q5un5/@iOR00tedqPmtYcWnZqUrDx4S3@h7v/1@r8NzC2sDQ14AJRBkDKwNAAQhmCKSMIzwjEMzIC84AURM7AAKbBEAA).
+3 bytes to bug-fix numbers with a length of 3 or less (range `[000000, 000999]`).
**Explanation:**
```
Ÿ # Create an inclusive (on both sides) range from the two inputs
# i.e. 038920 and 038910 →
# [38910,38911,38912,38913,38914,38915,38916,38917,38918,38919,38920]
ʒ # Filter this list by:
₄n+ # Add 1,000,000 to the number
| # And remove the leading 1
# i.e. 38910 → 1038910 → '038910'
S # Transform it to a list of digits
# i.e. '038910' → ['0','3','8','9','1','0']
3ô # Split it into chunks of length 3
# i.e. ['0','3','8','9','1','0'] → [['0','3','8'],['9','1','0']]
O # Sum the digits in both parts
# i.e. [['0','3','8'],['9','1','0']] → [11,10]
Ë # Check if they are equal (if they are, they remain in the filtered list)
# i.e. [11,10] → 0
```
---
EDIT: Seems I (and most other answers) slightly misread the challenge and the amount of numbers is being asked instead of the numbers themselves within the range. In that case a trailing `}g` can be added (close the filter; and get the amount of numbers left in the filtered list), so it's **~~10~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead:
```
Ÿʒ₄n+¦S3ôOË}g
```
[Try it online](https://tio.run/##MzBNTDJM/f//6I5Tkx41teRpH1oWbHx4i//h7tr0//8NjC0sTQ24QJSBAQA) or [verify some more test cases](https://tio.run/##MzBNTDJM/W/q5un5/@iOU5MeNbXkaR9aFmx8eIv/4e7a9P86/w2MLSxNDbhAlAGQMjA0gFCGYMoIwjMC8YyMwDwgBZEzMIBpMAQA).
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 93 + 18 = 111 bytes
```
a=>b=>Enumerable.Range(a,b-a+1).Select(e=>$"{e:D6}").Count(e=>e[0]+e[1]+e[2]==e[3]+e[4]+e[5])
```
[Try it online!](https://tio.run/##rZA/a8MwEMV3fQoROkgkMbb7B9pUXtJ2aqE0Qwbj4aycjcCRWkkOhODP7squM3Voh7zhnTjufryTdEtpLPatU7qmm6PzuI9elf5aESIbcI6@kxOhQZ9WHcAjdR68ktQi7Ixujuedl1bLR6X94ncjWJbRiooeRFaK7Fm3e7RQNhh9gK6RwaJcwjzh0QYblJ6hyK5mJ3x4uutmPFqbVo89zONijnkyWFoIgfn18LwZ7LbgPZ0Uog9lCnowakffQGnmvA1H5gUFWzs@zvycNmhKvTbamRBsa5XH8A/IKpbEccxZEgrnq78X/jNTsXSEpheGphM2vTA4MO9HnZkd6Uj/DQ "C# (.NET Core) – Try It Online")
18 bytes for `using System.Linq;`. I supposed that the input and output formats could be flexible. So I take two integers as input (the range, inclusive).
Some test results:
```
a=1000
b=1100
Lucky numbers = 3 [001001, 001010, 001100]
a=2000
b=2100
Lucky numbers = 3 [002002, 002011, 002020]
a=222000
b=222100
Lucky numbers = 7 [222006, 222015, 222024, 222033, 222042, 222051, 222060]
a=0
b=999999
Lucky numbers = 55252 (that's 5.5% of the total numbers)
```
[Answer]
# JavaScript (ES6), 66 bytes
Takes input in currying syntax `(m)(n)`, where **m** is the ~~exclusive~~ inclusive upper bound and **n** is the inclusive lower bound.
```
m=>g=n=>n<=m&&![...n+=''].reduce((t,d,i)=>t-=n[i+3]?d:-d,0)+g(-~n)
```
[Try it online!](https://tio.run/##Zcg7DsIwDADQnVuwtLbyUVQ2hMNBqg5VnEZBrYPawMjVg8TKG99jfs9H2POzGikc20JtI59IyMuNtq47j9ZaUdT3k90jv0IEqJp1RvLVkIxZXaY7Xw1rhyqB@Qi2UOQoa7RrSbDA4JxDcIinvx9@374 "JavaScript (Node.js) – Try It Online")
### How?
We test each number \$n\$ by walking through its digits \$d\_i\$ and updating a total \$t\$:
* \$t \gets t - d\_i\$ if there are at least 3 remaining digits after this one
* \$t \gets t + d\_i\$ otherwise
If we have \$t=0\$ at the end of the process, then \$n\$ is a lucky number.
---
# JavaScript (ES6), 67 bytes
Same input format.
```
m=>g=n=>n<=m&&!eval([...n/1e3+''].join`+`.split`+.`.join`^`)+g(n+1)
```
[Try it online!](https://tio.run/##ZcjBDoIwDADQu3/hBdo01oFXx48YTRccy8joCCP8/kz06Du@2R2ujFtc94vmt6@TrYsdglU76N0uTXP2h0vwYGa9dv5GbfvkOUcVEi5rirsQy29eghRAqcM6Zi05eU45wAS9MQbBIJ7@vv9@/QA "JavaScript (Node.js) – Try It Online")
### How?
For each number \$n\$:
* divide it by \$1000\$: e.g. `38937 --> 38.937`
* coerce to a string and split: `['3','8','.','9','3','7']`
* join with `+`: `"3+8+.+9+3+7"`
* replace `+.` with `^`: `"3+8^+9+3+7"`
* evaluate as JS code and test whether the result is \$0\$: `24` (\$11\$ XOR \$19\$)
If \$n \equiv 0 \pmod{1000}\$, no decimal point is generated and the evaluated expression is just a positive sum (falsy), unless \$n=0\$ (truthy). This is the expected result in both cases.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~56~~ 54 bytes
```
->a,b{(a..b).count{|i|j=i.digits;j[0,3].sum*2==j.sum}}
```
[Try it online!](https://tio.run/##NYtBDoIwEEX3nGKWYGpTphQ0pnqQpgvQYNqgGIGFoZy9to3@ZDJ/8ua9l@7je@n355Z0a95S2hX0Oi7PeXXGWWnozdzNPJ2sYoRrOi2PHUppY9k2/wKVAajAoNRp0lmyGAKYdgACD@zPkFeiJlCLimOUeFmz5geDc0yJjkCBOtO0HYbL6nJDwBYERhc@e2WI1SAljNnmvw "Ruby – Try It Online")
### Method:
1. For every number, creates an array of digits (which comes out reversed)
2. Compares the sum of the first 3 digits in the array (last 3 in the number) multiplied by 2 to the sum of the entire array
3. Counts the numbers for which the two sums are equal
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~38~~ 15 bytes
```
õV Ëì ò3n)mx r¥
```
*-23 thanks to Shaggy!*
My first Japt submission; thanks to Shaggy for all the help!
[Try it online!](https://tio.run/##y0osKPn///DWMIXD3YfXKBzeZJynmVuhUHRo6f//uhVcRkZGBgYGIMrQwAAA "Japt – Try It Online")
[Answer]
# Python 3, 117 113 106 135 bytes
This is my first answer ever so I'm sure there's room for improvement.
```
def x(a,b):
n=0
for i in range(a,b+1):
if sum(map(int,str(i//1000)))==sum(map(int,str(i%1000))):n+=1
print(n)
```
* *-4 bytes thanks to W W*
* *-7 bytes thanks to Asone Tuhid*
* *+29 bytes to create a function*
Gets the first three digits through integer division, and the last three through modulo. The first and last integers in the range are inputted as arguments of the `x` function, as `a` and `b`, respectively. Output is `n`, printed.
Ungolfed:
```
def x(a, b):
n = 0
for i in range(a, b + 1):
if sum(map(int, str(i // 1000))) == sum(map(int, str(i % 1000))):
n += 1
print(n)
```
[Answer]
# [R](https://www.r-project.org/), ~~93~~ 86 bytes
Shorter logic at the end compliments of @Giuseppe/
```
function(a,b){for(i in sprintf("%06d",a:b)){x=utf8ToInt(i);F=F+!sum(x[1:3]-x[4:6])}
F}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNRJ0mzOi2/SCNTITNPobigKDOvJE1DSdXALEVJJ9EqSVOzusK2tCTNIiTfM69EI1PT2s3WTVuxuDRXoyLa0Mo4Vrci2sTKLFazlsut9n@ahoGOJRho/gcA "R – Try It Online")
Integer inputs. Pad them with `0`. Convert to the six ASCII code points. Abuse the `F` builtin.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
#ȯ§¤=Σ↓↑3↔d…
```
[Try it online!](https://tio.run/##yygtzv7/X/nE@kPLDy2xPbf4UdvkR20TjR@1TUl51LDs////hgYg8N8ITAEA "Husk – Try It Online")
## Explanation
```
#(§¤=Σ↓↑3↔d)… -- example input: 100000 101000
… -- inclusive range: [100000,100001..100999,101000]
#( ) -- count elements where (example with 100010)
d -- | digits: [1,0,0,0,1,0]
↔ -- | reversed: [0,1,0,0,0,1]
§ 3 -- | fork elements (3 and [0,1,0,0,0,1])
↑ -- | | take: [0,1,0]
↓ -- | | drop: [0,0,1]
¤= -- | > compare the results by equality of their
Σ -- | | sums 1 == 1
-- | : 1
-- : 3
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
ILΦ…·NN⁼Σι⊗Σ÷ιφ
```
[Try it online!](https://tio.run/##VclBCsJADIXhvafoMoUKY7curUJBRPQE02loA@lUZ5Jefwzixrf44eOF2aewei7lnigKnHwWuGKcZIYLsWCCPgbWTBs@fJzQ@FK56TLYVTfVH83nt3rO8NQFyNitOjCOX/dROtpoRKCmOjjn6t@OpbTGXWst@40/ "Charcoal – Try It Online") Link is to verbose version of code. Edit: I originally thought that it was the list of lucky numbers that was required. This can be done in 14 bytes (by removing the `L`, which takes the length of the list), or in 20 bytes if you want some nice formatting:
```
EΦ…·NN⁼Σι⊗Σ÷ιφ﹪%06dι
```
[Try it online!](https://tio.run/##VcpBCsIwEAXQvacIBWEKEWIXbtzWQhcV0ROkTdCBaVLTTK8fR3fO4sP7f6aXTVO0VMotYcgw2AU6pOwT9GEiXnHzdxueXrhwvvI8ylRr9Ufx5c2WVnjwDChsI4/k3c99yC1u6DygVkdjTP09rYbomCJUe3NylVYo5bmURh52jWQ5bPQB "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NN Input the range endpoints
…· Inclusive range
Φ Filter
ι Current value
Σ Sum of digits
ι Current value
φ Predefined variable 1000
÷ Integer divide
Σ Sum of digits
⊗ Doubled
⁼ Equals
E Map over results
ι Current value
%06d Literal string
﹪ Format value
Implicitly print each result on its own line
```
[Answer]
## [Perl 5](https://www.perl.org/) + `-pl -MList::Util+(sum)`, 49 bytes
```
@F=/./g,$\+=sum@F[5,4,3]==sum@F[2,1,0]for$_..<>}{
```
[Try it online!](https://tio.run/##K0gtyjH9/9/BzVZfTz9dRyVG27a4NNfBLdpUx0THONYWyjPSMdQxiE3LL1KJ19Ozsaut/v/fgMvQEgj@5ReUZObnFf/XLcj5r@vrk1lcYmUVWpKZo60B1KoJAA "Perl 5 – Try It Online")
---
## [Perl 5](https://www.perl.org/) + `-nl -MList::Util+(sum) -M5.010`, 50 bytes
To output each ticket instead is +1 byte:
```
@F=/./g,sum@F[5,4,3]-sum(@F[2,1,0])||say for$_..<>
```
[Try it online!](https://tio.run/##K0gtyjH9/9/BzVZfTz9dp7g018Et2lTHRMc4VhfI0QDyjHQMdQxiNWtqihMrFdLyi1Ti9fRs7P7/N@AytASCf/kFJZn5ecX/dfNy/uv6@mQWl1hZhZZk5mhrAA3QBAqZ6hkYGgAA "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~89~~ 86 bytes
-2 thanks to Mr. Xcoder.
-3 inspiring from Asone Tuhid answer's.
```
lambda a,b:sum(sum(map(int,str(i)))==2*sum(map(int,str(i)[-3:]))for i in range(a,b+1))
```
Tests results :
```
Example 1 :
a = 0
b = 1
Lucky numbers : 1
Example 2 :
a = 100000
b = 200000
Lucky numbers : 5280
Example 3 :
a = 123456
b = 654321
Lucky numbers : 31607
Example 3 :
a = 0
b = 999999
Lucky numbers : 55252
```
[Try it online!](https://tio.run/##fczBDoIwDAbg@56i2WnVmUC5LeHozTcQD0NBF9lYBiTy9Mhi0BiihyZ/2r@fH/tb67Kpzoup0ba8aNCyVN1gRRyrvTCul10fhEHEPKfNen/cZeqEWLcBDBgHQbtrJWZnmyJOPsxNwTnfP7T1TQUpKGAackiTJGFlDHNih@F8H8ENtqxCB2p@kLWIFRnPKHnhODK24mjhaOHoJxcrkv5y2ZujD0h/SHqh9MVOTw "Python 3 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 24 bytes
```
&:1e3&\,!'%03d'&V2&sw]=s
```
[Try it online!](https://tio.run/##y00syfmf8F/NyjDVWC1GR1Fd1cA4RV0tzEituDzWtvi/S8h/S0tLAwMuSxDgMuAy5DIwMDQACgApIM0FYgMpIzAFAA "MATL – Try It Online")
*(-2 bytes thanks to Luis Mendo.)*
`&:` - Make an inclusive range between the two given numbers
`1e3&\` - 'divrem' - divide by 1000 and get the reminders and floored quotients in two arrays.
`,` - do twice
`!'03d'&V` - transpose and convert each value to a zero-padded three-width string
`&s` - sum each row's values
`w` - switch to bring the reminder array out and do this again on that
`]` - end loop
`=` - check for equality (returns 1s in places where the arrays are equal)
`s` - sum those to get the count (implicit output)
[Answer]
# [Kotlin](https://kotlinlang.org), 152 119 bytes
```
{a:Int,b:Int->(a..b).map{String.format("%06d",it)}.filter{it[0].toInt()+it[1].toInt()+it[2].toInt()==it[3].toInt()+it[4].toInt()+it[5].toInt()}.count()}
```
[Try it online!](https://tio.run/##ZY1dC4IwFIav9VcMIdjIxlwfkKTQZdddRhezmox0yjoGIf72tSwk8Vycs@d5z2H3CgqlrWw0KoXSWJj8EaO9MeK1O4JROk8Jan3vKQokUWJbER80hNmnL1IsKM0ILUXdfpeprEwpAAcztrkGoQLSUakKuJlWwYmdKVTuEJO5o2hEfKAkcbgchasRrQfq6KVq@of1avc/FBpLHDHGQhS5QYj/53nv@dTzX8KnmdPbvpzufPsG "Kotlin – Try It Online")
Taking two integers than convert it into six symbol strings and count.
Optimized it thanks to mazzy and his [solution](https://codegolf.stackexchange.com/a/169047/81779) to 119 bytes.
```
{a:Int,b:Int->(a..b).count{val d="%06d".format(it);(d[0]-'0')+(d[1]-'0')+(d[2]-'0')==(d[3]-'0')+(d[4]-'0')+(d[5]-'0')}}
```
[Try it online!](https://tio.run/##ZY5dC4IwFIav9VcMIdxIx1wfkDWhy667jC5mMhnpjDWDEH/7mhoYdC7OeXjec/HeG1NJZUWrQM2lglyXzxQctebvw9loqcoMgc73XrwCAjDb8fSkTJQPO84gxzhH@Na0ynTDS8GCBdkWARaNrrmB0qA9LC7kGockREuHyYx0QsYcr2a9nnEzYd9b7@G6mEpBARNCSAQSdxDyfzwdPf339JvQ/8zp3ThO9779AA "Kotlin – Try It Online")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 44 bytes
```
sb[d]sD[dA00~[rA~rA~++rx]dx=D1+dlb!<L]dsLxkz
```
Takes two arguments from an otherwise empty stack, outputs to top of stack.
[Try it online!](https://tio.run/##S0n@b2hkbGJqpmBmamJsZPi/OCk6JbbYJTrF0cCgLrrIsQ6ItLWLKmJTKmxdDLVTcpIUbXxiU4p9KrKr/hf8BwA "dc – Try It Online")
The clever bit here is the use of an unnamed (i.e., unstored) macro that's duplicated before execution in order to run a copy of itself on the other three-digit part.
# Explanation
The inner macro `[rA~rA~++rx]` has the effect "calculate the digit sum of the three digit number that is second-to-top on the stack, then execute the original top of the stack as a macro".
Main program:
```
sb Saves the upper bound as b so we'll know when to quit
[d]sD Defines the macro D, which contextually is "increment stack depth"
[ Start the main loop - the next number to test is on top
d Make a copy to increment later for loop purposes
A00 The literal "1000"
~ Quotient and remainder, so "123456" is now "123 456"
[rA~rA~++rx]d Stack is now "123 456 M M", where M is the anonymous macro
x Run M on the stack "123 456 M", which (see definition
above) ends up running M on the stack "123 15", which
leaves "15 6" (and executes the 6, which is a no-op)
=D If the two sums were equal, increment the stack depth
1+ Increment the current test number
dlb!<L Loop unless the test number is now larger than b
]dsLx Name and start the loop
kz Current depth is 1+answer, so throw away top and return
```
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), ~~163~~ 153 bytes
```
var a,b:Int32;begin read(a,b);for a:=a to b do if a div$186A0+a div$2710mod$A+a div$3E8mod$A=a div$64mod$A+a div$Amod$A+a mod$Athen b:=b+1;write(b-a)end.
```
[Try it online!](https://tio.run/##TYlBDoIwFESv8hcsIIhpwSC2YdGFC4/xS1ttgi2pDR6/kqKJs5l58xZ8TTg3ZplSWjEAHiS7udi1XOq7dRA0qnI7K278ZtmIED1IUB6sAQRl14IOvSD1vtszJU@vCvHl7jpkHHfsT/9S/CB3fGgHko2ypvwdbNSlbLDSTh1TInDJ@QA "Pascal (FPC) – Try It Online")
## Explanation
Here is some normal-looking code first:
```
var a,b,i,s,c,d:Int32;
begin
read(a,b);
s:=0;
for i:=a to b do begin
c:=i div 1000;
d:=i mod 1000;
if c div 100+(c div 10) mod 10+c mod 10=d div 100+(d div 10) mod 10+d mod 10 then begin s:=s+1; {writeln(i)} end;
end;
write('There are ',s,' numbers');
end.
```
[Try it online!](https://tio.run/##XY9NDoIwEIX3nOLtgFANf7qAcAD3XqB0ijSRYlrUhfHsWLRE42Jm3sx8ycy7cCv4edNdxDzfuAFnLVPMMsGoOuipyOuglSelA8BITpHbx7VrbNWkS@1GA1U1HNOIFuSSpwFRNQqkbsjS9M0CtIyGkX5GqoNYqSRaZeypRHjR0Beif4i8wNRL/flgedAmWY3H3ahJnnWk4iekpuWqL@9NFB57aSS4i9AZD6GvQyuNDZ1PB27nOcuLcrfHflcWefYC "Pascal (FPC) – Try It Online")
Then I abused the behaviour of the for loop:
* the loop values are set beforehand (from `a` to `b`), so `a` can be reused as the loop variable, dropping `i`;
* at the end of the for loop, loop variable is left at the final value (value of `b` before the loop). I used `b` as a container, incrementing it when a lucky number is found and at the end of the loop `b` is away from its old value by amount of lucky numbers, so `b-a` gives the correct result. This dropped `s`.
Replacing `d` with operations directly on `a` shortens the loop. Replacing `c` with operations directly on `a` dose not shorten the loop, but, after dropping `d`, loop's `begin` and `end` are unnecessary and I ended with using only 2 variables :)
`$` starts hexadecimal constants in the golfed code. While they do not save bytes, they eliminate spaces needed before decimal constants.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 162 bytes
... borrows from the Kotlin example above.
```
import java.util.stream.IntStream;
(a,b)->IntStream.range(a,b+1).mapToObj(i->String.format("%06d",i).getBytes()).filter(c->c[0]+c[1]+c[2]==c[3]+c[4]+c[5]).count();
```
[Try it online!](https://tio.run/##lVHBasMwDL33K0RhYNPEJGkbGKU97DZYt0N3Czk4rps5dewQOx1h9NszO@1Gd1uFLcl6EnqSK3qioW64qvbHQdSNbi1ULkY6KyQxtuW0Js/K7kZvNZkwSY2BLRXqawIglOXtgTIOLx079q9dXfDWeARAalXCh/7cUtUjlwg08PlQ4JXDz@66Yyy1gv2pBnn7WMOAaFDgcPPLgrRUldxHZzEmNW3e9VtRIRFuHC5USQ66ralF04co3U8DgUnJ7VNvuUEYk4OQjjNi4YZlUT5jWexVkq/XLJt7d@HVMseE6U5ZhFeDGxug6QrpmF4Jn7TYQ@22gC49sxwovsy9643lNdGdJY2DrFTodiLysxKfC1EwmhiPS/l/cRx5CZLR3F2czBfLNEiXi3lyd@cr7cdR8PUvz8M3 "Java (OpenJDK 8) – Try It Online")
Comparing the sum of the String's bytes is just as good as summing up the actual digits.
[Answer]
# [PHP](http://www.php.net/), 131 bytes
```
<?$f='array_sum(str_split(str_split(sprintf("%06d",$i),3)[';for($i=$argv[1]-1;$i++<$argv[2];)eval("\$a+=$f 0]))==$f 1]));");echo$a;
```
To run it:
```
php -n <filename> <from> <to>
```
Example:
```
php -n lucky_tickets.php 100 100000
```
Or [Try it online!](https://tio.run/##TcfRCsIgGIbhWwn5Y4obaEEnTrqQNYbUbMKm8muDbj7b6KQPXni@OMVS2itYXRlE8x7Sa6Ep45Di7PK/IjqfLSVHcXmQGhyrz6yrlA1IwWkw@Fw72TdSgeO8/f1Tr9i4mpmSGxiuwR5Ez5jeITcowtR4nwIYVUqRQuxt@4SYXfCpNP4L "PHP – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~51~~ 49 bytes
```
{+grep {[==] .flip.comb[^3,3..*]>>.sum},$^a..$^b}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1o7vSi1QKE62tY2VkEvLSezQC85PzcpOs5Yx1hPTyvWzk6vuDS3VkclLlFPTyUuqfZ/cWKlQpqGgY6hpjUXhG1oAAQ6CkYgStP6PwA "Perl 6 – Try It Online")
Anonymous code block that takes a two numbers and returns the number of lucky ones. Times out for larger inputs
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to Dennis (`rµ...E)S` -> `r...E€S` since everything vectorises.)
```
rdȷD§E€S
```
A dyadic Link accepting the two endpoints of the range (either way around) which yields the count of lucky tickets.
**[Try it online!](https://tio.run/##y0rNyan8/78o5cR2l0PLXR81rQn@//@/oQEI/DcCUwA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8/78o5cR2l0PLXR81rQn@f3i5PpD@/z/aQMcwVifa0AAEdIzAFIhvZGxiaqZjZmpibASSN9CxBINYAA "Jelly – Try It Online")
### How?
Note that for any non-negative integer less than \$1000000\$, \$N\$, we can get two numbers with digits that sum to the required values to check using integer division by \$1000\$
(yielding, say, \$X=\lfloor\frac{N}{1000}\rfloor\$)
and its remainder
(say \$Y=N\mod{1000}\$)
...that is, \$N=1000\times X+Y\$
Now we want to compare the sums of the digits of \$X\$ and \$Y\$ for each \$N\$ in a range and count those that are equal.
```
rdȷD§E€S - Link: integer a; integer b
r - inclusive range [a,b] (either [a,a+1,a+2,...,b] or [a,a-1,a-2,...,b])
- e.g.: 0 or 78 or 7241
ȷ - literal 1000
d - divmod (vectorises) [0,0] [0,78] [7,241]
D - to decimal lists (vectorises) [[0],[0]] [[0],[7,8]] [[7],[2,4,1]]
§ - sum each (vectorises) [0,0] [0,15] [7,7]
E€ - for €ach: all equal? 1 0 1
S - sum (counts the 1s in the resulting list)
```
[Answer]
# Powershell, 85 bytes
```
($args[0]..$args[1]|%{'{0:D6}'-f$_}|?{+$_[0]+$_[1]+$_[2]-eq+$_[3]+$_[4]+$_[5]}).count
```
Test script:
```
$f = {
($args[0]..$args[1]|%{'{0:D6}'-f$_}|?{+$_[0]+$_[1]+$_[2]-eq+$_[3]+$_[4]+$_[5]}).count
}
@(
,((0,1), 1)
,((1000,2000), 3)
,((2000,3000), 6)
,((10000, 20000), 282)
,((101000, 102000), 6)
,((201000, 202000), 10)
,((901000, 902000), 63)
,((100000, 200000), 5280)
,((123456, 654321), 31607)
#,((0, 999999), 55252)
) | % {
$c, $e = $_
" $c"
$r = &$f $c[0] $c[1]
"$($e-eq$r): actual=$r expected=$e"
}
```
Output:
```
0 1
True: actual=1 expected=1
1000 2000
True: actual=3 expected=3
2000 3000
True: actual=6 expected=6
10000 20000
True: actual=282 expected=282
101000 102000
True: actual=6 expected=6
201000 202000
True: actual=10 expected=10
901000 902000
True: actual=63 expected=63
100000 200000
True: actual=5280 expected=5280
123456 654321
True: actual=31607 expected=31607
```
[Answer]
# Kotlin, 95 bytes
```
{a:Int,b:Int->(a..b).count{val d="%06d".format(it);d.chars().sum()==2*d.take(3).chars().sum()}}
```
`.kt` for test:
```
var f = {a:Int,b:Int->(a..b).count{val d="%06d".format(it);d.chars().sum()==2*d.take(3).chars().sum()}}
fun main(args: Array<String>) {
println(f(0,1)) // 1
println(f(1000,2000)) // 3
println(f(2000,3000)) // 6
println(f(101000, 102000)) // 6
println(f(201000, 202000)) // 10
println(f(901000, 902000)) // 63
println(f(10000, 20000)) // 282
println(f(100000, 200000)) // 5280
println(f(123456, 654321)) // 31607
println(f(0, 999999)) // 55252
}
```
# Explanation
Count numbers from range where sum of all number digits is equal to double sum of first 3 digits.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ît║l`Yµß╖vYü╢^
```
[Run and debug it](https://staxlang.xyz/#p=8c74ba6c6059e6e1b7765981b65e&i=0,+1%0A100000,+200000%0A123456,+654321%0A0,+999999&a=1&m=2), but be patient!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~83~~ 80 bytes
-3 by using Asone Tuhid's observation - [go give credit!](https://codegolf.stackexchange.com/a/168983/53748)
```
lambda a,b:sum(sum(map(int,`v/1000`))*2==sum(map(int,`v`))for v in range(a,b+1))
```
**[Try it online!](https://tio.run/##VU1dC8IwDHz3V@TNRIN23Qc46D/xYR1aHdhuzDmQsd8@0755kBy5C3fDd3r2QW/OXLeX9e3NguW2fn88xvF2wC5M3MznTCnVEB20Mf@OiK4fYYYuwGjD446ScMyItihbhjY6iIohIwaMQUoOnTgpOi/KiqEqi1ynH7EvCUT1DgTDKGWwd7isDMtKYGTvT9Lg7YSxhMEllt4f "Python 2 – Try It Online")**
Much like my Jelly answer (but the inputs must be sorted here i.e. `a<=b`)
---
**75 bytes** for input `a, b+1` (i.e. range excludes the right bound):
```
lambda*r:sum(sum(map(int,`v/1000`))*2==sum(map(int,`v`))for v in range(*r))
```
[Try this one](https://tio.run/##VY3dCsIwDIXvfYrcmYygXfdzMeibeLEOrQ5sN@ocyNizz2ZeGUgOOTnkGz/TYwh6c@ayPa3vrjaLzevtUdrbEfswcTufc6VUS5RpY/4vyXRDhBn6ANGG@w2zSLSJZxk6sREVgyYGlC9KFpF8d3RRVjVDXZWF3jPp/IspouYAqcaYUHB0uKwMy0pg0jyeEsLbCYXC4HZN4C8 "Python 2 – Try It Online")
[Answer]
## Clojure, 102 bytes
```
#(count(for[i(range %(inc %2)):when(=(let[d(map int(format"%06d"i))](apply +(map -(drop 3 d)d)))0)]i))
```
Mixing strings and math isn't too fun.
[Answer]
# [J](http://jsoftware.com/), 35 bytes
```
[:+/(6#10)([:=/_3+/\])@#:[+i.@>:@-~
```
[Try it online!](https://tio.run/##y/qvpKeeZmulrlNrZaBgZfA/2kpbX8NM2dBAUyPaylY/3lhbPyZW00HZKlo7U8/BzspBt@6/Jldqcka@gqEBCCikKRiBGVypFZkl6ur/AQ "J – Try It Online")
[Answer]
# C (gcc), ~~90~~ 88 bytes
```
l=10;u(c,k,y){for(y=0;c<=k;)c++%l+c/l%l+c/100%l-c/1000%l-c/10000%l-c/100000%l?:++y;c=y;}
```
Port of my Java [answer](https://codegolf.stackexchange.com/a/169632/79343). Try it online [here](https://tio.run/##fVB/S4RAEP37/BTTgbDiHq3raT@2LYIKoqAv0D@yriG3qXhayeFnt3HRziBalp03M@89Zkdt3pQaBiMDJlqi6I523iEra9JJJtSV3AlP@b5rfHVq7Bsw5pqNjUewQAhvLn2/E0p2oh8@yjyFRu8bkhcNmPJT1xRG2FbVDPVXpVWjUw8OzmosJKppEwMSWjIpLNsT2M7ITAcpJ6YVrqoatRlZEzel4KKbvMYA5OXJey3WFJZWdFaiZQ/a7PV/FifSGj3cPj7f3/1lNo/0y9bpHWf8zXuSF8SOaPfAKAR4R4rNxwTXRoEdS3aRFPgUI36@aPJwG8UU4mgbchSHQczOfrrIvrAHVRGPODZ6Z/gG). Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for golfing two bytes.
Ungolfed:
```
l=10; // constant, we will be using the number 10 rather a lot
u(c, k, // function returning an integer and taking two integer arguments: lower and upper bound
y) { // abusing the argument list to declare a variable of type integer: the number of lucky tickets found in the range
for(y = 0; c <= k; ) // set count to 0 and loop through the range
c++ %l + c/l %l + c/100 %l // if the digit sum of the second half of the ticket number ...
- c/1000 %l - c/10000 %l - c/100000 %l // ... is the same as the digit sum of the first half ...
?: ++y; // ... it's a lucky ticket: increment the count
c = y; // return the count
}
```
[Answer]
# Java 8, ~~101~~ 99 bytes
```
u->l->{int n=0,d=10;for(;l<=u;)if(l++%d+l/d%d+l/100%d==l/1000%d+l/10000%d+l/100000%d)++n;return n;}
```
A different approach than [the other Java answer](https://codegolf.stackexchange.com/a/169005/79343). Instead of using streams and Strings, this uses a loop and evaluates the numbers directly. Try it online [here](https://tio.run/##tVJRS8MwEH6uv@IsDFra1a5bp9KlIOhgqPiwR/EhttnIlqWlTaZj9LfPJOtE3R4EsZTed1/uvrvrZYHXuFuUhC/y5a6Ur4xmkDFc1/CIKYftmdWStcBCmXVBc1ipI2cqKsrnzy@Aq3nt6khrocQCKSgLZpJnghY8GLdgNOGCzEnlw6@CWpCmwGS23ACCneymrJtuKRfAUejnqBcms6JyEjZCMnHpzGGe18k9dpGbby8MOzlCBoQH5itS0PU8nlREyIoDT5qdZSVqDEFq4Zi6PoQ@9NTr/uQ1qSRUwPGREfcham0cXZ0IivqDeOjDMB70IyXW7w3DS/dE9WvzKJU4iiMd0KiVVHSNBfm2E5P2bwvwQf93VrzpMw1lWR4geS9JJki@vwOawZmQmKmlmdwAlyXbOCbDbR2jZMZVezsIAEJt6l7Kmm5qQVZBIUWgRuaCccd2bPD2jShr@6BdI61dF1BqmLYDRYHzdO/aplQDhNXkr9Kf3Wrxc3RUbnwzebi7PZTU@2p2Hw).
Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for golfing two bytes.
Ungolfed:
```
u -> l -> { // lambda taking two integer arguments in currying syntax and returning an integer
int n = 0, // the counter
d = 10; // auxiliary constant, we will be using the number 10 rather a lot
for(; l <=u ; ) // loop over all ticket numbers in the range
if(l++ %d + l/d %d + l/100 %d // if the digit sum of the second half of the number ...
== l/1000 %d + l/10000 %d + l/100000 %d) // ... is the same as the digit sum of the first half ...
++n; // ... it's a lucky ticket, add 1 to the counter
return n; // return the count
}
```
[Answer]
# VBA (Excel), 159 bytes
Using Immediate Window and Cells `[A1]` `[A2]` as input.
```
c=[A1]-[A2]:d=IIf(c<0,[A1],[A2]):For x=d To d+Abs(c):e=String(6-Len(x),"0")&x:For y=1To 3:i=i+Mid(e,y,1):j=j+Mid(e,7-y,1):Next:z=IIf(i=j,z+1,z):i=0:j=0:Next:?z
```
[Answer]
## F#, 110 bytes
```
let t=string>>Seq.sumBy(int>>(-)48)
let r s e=Seq.where(fun n->t(n/1000)=t(n-(n/1000)*1000)){s..e}|>Seq.length
```
[Try it online!](https://tio.run/##XVDBTsMwDL3vK6xJSAlaS9Z1EwiaAxJXhOA47VBtbhexeSNxQRPj20tiQAOsKI7fe3620oRsufPY9xtk4Cqwd9Ra@4Qveei2twfliK1VmS4v9SBpPATAKvFva/Somo6AMsuKLsbGGF3FV/ZTnMut30Oe48dRXDdILa/7@c0dsT887JL/Qpy3tSOoffsK1QBizJUZwVhfSwEqWZmIFJJPcDEpp7MRzKblpDipo/BKQi8EOVpI0x2jB9l5XzsPmf2Sx0gbBK49QwVNYOH/kEir@8gFWv3juuXz4bGmFr/7RRjn7eNXckMwPHMgZ/hLoKXf9J8)
`t` converts the string into numbers and sums them up. `r` takes the range of numbers from `s` to `e`, and filters out the numbers that are unlucky. The first three digits are collected by `n/1000`. The second three digits are computed by `n-(n/1000)*1000`.
] |
[Question]
[
[Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) (a cross between Brainf\*\*k and Flak-Overstow) is a stack-based esoteric language. Since this challenge was posted, the language has evolved and updated, but this first revision of the language is known as "brain-flak classic".
You must write a program or function that takes a string of Brain-Flak classic code, and evaluates it. It will also take a (possible empty) list of integers. There are the inputs to the Brain-Flak classic program.
# The Language
Brain-Flak has two stacks, known as 'left' and 'right'. The active stack starts at left. If an empty stack is popped or peeked, it will return 0. There are no variables. When the program starts, each input is pushed on to the active stack in order (so that the last input is on top of the stack).
The only valid characters in a Brain-Flak program are `()[]{}<>`, and they must always be [balanced](https://codegolf.stackexchange.com/questions/77138/are-the-brackets-fully-matched). If there are invalid characters, or the brackets are unmatched, you get undefined behaviour. Anything is valid.
There are two types of functions: *Nilads* and *Monads*. A *nilad* is a function that takes 0 arguments. Here are all of the nilads:
* `()` +1.
* `[]` -1.
* `{}` Pop the active stack.
* `<>` Toggle the active stack.
These are concatenated together when they are evaluated. So if we had a '3' on top of the active stack, this snippet:
```
()(){}
```
would evaluate to `1 + 1 + active.pop()` which would evaluate to 5. `<>` evaluates to 0.
The monads take one argument, a chunk of Brain-Flak code. Here are all of the monads:
* `(n)` Push 'n' on the active stack.
* `[n]` Print 'n' as an int and a newline.
* `{foo}` While active.peek() != 0, do foo. Evaluates to 0¹.
* `<foo>` Execute foo, but evaluate it as 0.
These functions will also return the value inside of them, so
```
(()()())
```
Will push 3 and
```
[()()()]
```
Will print 3 but
```
[(()()())]
```
Will print **and** push 3.
When the program is done executing, each value left on the active stack is printed as an integer, with a newline between. Values on the other stack are ignored.
# Rules:
* Your program must support numbers in the (-128, 127) range, and a stack size of at least 255. If you support larger, great.
* Underflow/overflow is undefined.
# Sample IO:
The empty program:
Input: None
Output: None
Addition. Source:
```
({}{})
```
Input:
```
2, 3
```
Output:
```
5
```
Subtraction. Source:
```
({}<>){({}[])<>({}[])<>}<>
```
Input:
```
2, 3
```
Output:
```
-1
```
Multiplication. Source:
```
({}<>)<>({}[]){({}[])<>(({}))<>}<>{({}<>{})<>}<>
```
Input:
```
7, 8
```
Output:
```
56
```
Fibonacci. Source:
```
<>((()))<>{({}[])<>({}<>)<>(({})<>({}<>))<>}<>
```
Input:
```
5
```
Output:
```
13
8
5
3
2
1
1
```
[Truth machine](https://codegolf.stackexchange.com/questions/62732/implement-a-truth-machine)
```
{[({})]}
```
Standard loopholes apply, and the shortest answer in bytes wins.
---
* ¹: *This was actually a mistake on my part.* `{...}` *should evaluate to the sum of all of it's runs, which is IMO one of the coolest features of brain-flak. However, for the purposes of this challenge, assume that* `{...}` *evaluates as 0.*
[Answer]
# [Brain-Flak Classic](https://github.com/DJMcMayhem/Brain-Flak), ~~1271~~ ~~1247~~ 1239 bytes
```
<>(()){<>((([][][][][])<(((({}){})(({})({}))[])({}(({})({}({})({}{}(<>)))))[])>{()<{}>}{})<{{}}{}>())}{}<>(<(({()(((<>))<>)}{}{<({}(([][][])((({})({}))[]{})){})>((){[]<({}{})((){[]<({}{}<>((({})({})){}{}){})(<>)>}{}){{}{}<>(<({}{}())>)(<>)}>}{}){(<{}{}{}((<>))<>>)}{}}<>)<{({}[]<({}<>)<>{(<{}>)<>{<>({}[])}{}<>({}<>)(<>)}{}>)}{}<>>)>)<>{(({}[])(){(<{}>)<><(({})[])>[][][][]{()()()()(<{}>)}{}<>}{}<>)<>}<>{}{(({})<({()<<>({}<>)>}{})>([]))((){[](<(({}()()(<>))()()()){(<{}>)<>}>)}{}<>){{}((){[]<({}())((){[]<({}())((){[]<({}())((){[]<({}())((){[]<({}())((){[]<({}())((){[](<{}<>{({}<>)<>}{}(({}))({<{}({}<>)<>>{}(<<>({}[]<>)>)}<><{({}<>)<>}>{})>)}{}){{}{}(<([])>)}>}{}){{}<>{({}<>)<>}{}((({})())<{({}[]<({}<>)<>>)}>{}){({}[]<><({}<><({()<({}[]<({}<>)<>>)>}{}<>)><>)<>({()<({}[]<({}<>)<>>)>}{}<>)>)}<>(<{({}<>)<>}>)}>}{}){{}{}(<(())>)}>}{}){(<{}{}>)<>{({}<>)<>}{}(({}))({<{}({}<>)<>>({})(<<>({}<>)>)}<><{({}<>)<>}>){{}([][][])<>(((<{}>)<>))}}>}{}){{}(<([{}])>)}>}{}){{}((<{}>))}>}{}){{}(({})(<()>)<<>{({}<>)<>}{}({}()<>)<>>)<>(<({}<>)>)<>{({}<>)<>}}{}(<({}<({}<>)<>>{})<>({}<>)>)<>(<({}())>)}{}({}<{({}[]<({}<>)<>>)}{}>){((({}[]<>){(<{}({}<>)>)}{}())<{({}()<({}<>)<>(({})[])>{[][](<{}>)}{})}{}>()){{}(<>)}}{}}{}{({}[]<[{}]>)}{}{({}[]<{}>)}{}
```
[Try it online!](https://tio.run/##rVS7bsMwDNz7FR3FIWPRRdCPBBncAgWCBh2aUfC3u3dHUnISIFPj2DIpPo5Hyh@/y/nn8HVZvrettlLMOpdyPOVlFWLpq@GvlbdBjzXlWPBSm/GH7daL1b42aLH2FWtDeCxIgJjYRlza44a2VwWMpGWfik/chNePp6pMthcEOe21SwFxlb33TCqIZk17Dq2XSi1TOxaBgTlAw94zUGqy1AticSdq0XbxIprrkFgOblZsuFbBJDtJL2nwqw73NTLiCWRyqeSrZjYhb@DKggYRunoYVOERZ9oMTComb8XsnwTmYb2JOyYD/agaDmkbxyOoYw0GdZ0@jSXZ6BcqIk3Zpcf46rc9dIkeaquncb2zd28YPDeJTy1M47PDOmEJqWbqZp68/8/5UAWzp/d8qFl5Bjng0UycoZGdLPX1hqew2yuUp3Am70CxhVFqnI@ao5tWXiCkXRttYg43J8Bre2wI8fRSsvOiaBQtZzl5A7wbeUw6yx9Hw@Ij0v1LQ3A8ux6YRPiXxOXw2baiEpDLJjS1Y0Bu9vL2@r4dlsvnZblez59/ "Brain-Flak – Try It Online")
*+4 bytes from fixing a bug with the condition in the `{...}` monad, and -36 bytes from various golfs.*
1238 bytes of code, +1 byte for the `-a` flag (which can be combined with the language flag).
This now evaluates `{...}` as zero per the challenge specification. Note that Brain-Flak itself has evaluated `{...}` as the sum of all runs since the May 7, 2016 bugfix two days before this challenge was posted.
The following code interprets Brain-Flak Classic correctly, with `{...}` as the sum of all runs. The only difference between the two interpreters is the placement of one `{}` nilad.
```
<>(()){<>((([][][][][])<(((({}){})(({})({}))[])({}(({})({}({})({}{}(<>)))))[])>{()<{}>}{})<{{}}{}>())}{}<>(<(({()(((<>))<>)}{}{<({}(([][][])((({})({}))[]{})){})>((){[]<({}{})((){[]<({}{}<>((({})({})){}{}){})(<>)>}{}){{}{}<>(<({}{}())>)(<>)}>}{}){(<{}{}{}((<>))<>>)}{}}<>)<{({}[]<({}<>)<>{(<{}>)<>{<>({}[])}{}<>({}<>)(<>)}{}>)}{}<>>)>)<>{(({}[])(){(<{}>)<><(({})[])>[][][][]{()()()()(<{}>)}{}<>}{}<>)<>}<>{}{(({})<({()<<>({}<>)>}{})>([]))((){[](<(({}()()(<>))()()()){(<{}>)<>}>)}{}<>){{}((){[]<({}())((){[]<({}())((){[]<({}())((){[]<({}())((){[]<({}())((){[]<({}())((){[](<{}<>{({}<>)<>}{}(({}))({<{}({}<>)<>>{}(<<>({}[]<>)>)}<><{({}<>)<>}>{})>)}{}){{}{}(<([])>)}>}{}){{}<>{({}<>)<>}{}((({})())<{({}[]<({}<>)<>>)}>{}){({}[]<><({}<><({()<({}[]<({}<>)<>>)>}{}<>)><>)<>({()<({}[]<({}<>)<>>)>}{}<>)>)}<>(<{({}<>)<>}>)}>}{}){{}{}(<(())>)}>}{}){(<{}>)<>{({}<>)<>}{}(({}))({<{}({}<>)<>>({})(<<>({}<>)>)}<><{({}<>)<>}>{}){{}([][][])<>(((<{}>)<>))}}>}{}){{}(<([{}])>)}>}{}){{}((<{}>))}>}{}){{}(({})(<()>)<<>{({}<>)<>}{}({}()<>)<>>)<>(<({}<>)>)<>{({}<>)<>}}{}(<({}<({}<>)<>>{})<>({}<>)>)<>(<({}())>)}{}({}<{({}[]<({}<>)<>>)}{}>){((({}[]<>){(<{}({}<>)>)}{}())<{({}()<({}<>)<>(({})[])>{[][](<{}>)}{})}{}>()){{}(<>)}}{}}{}{({}[]<[{}]>)}{}{({}[]<{}>)}{}
```
[Try it online!](https://tio.run/##rVS7bsMwDNz7FR3FIWPRRdCPFBncAAWCBh2akfC3u3dH0naTIlPj2DIpPo5Hyu/f0/nr8HGZPpelj9bMnEt7O9ZlHWLz2fDXytugx1pyLnjpw/jD9vBm3ecBLVafsQ6Ex4IEiIltxKU9bmi9K2AmbftUfOImPH87dmWyvSDIZa9dCoir7O6VVBDNhvYCmrdOLVMHFoGBOUDDPjJQGrLUC2JxJ2vRdosiRuiQWA5h1mx17YJJdope0hBXX93nzIgnkMmlk69e2YR8gCtLGkToHGFQRUTc0lZgUrHx1sz@SWAe1lu4czLQj67hkHZwPJI61mBQ981nsCRb@4WKSFN16T6@@m13XaKH2hppQh/s3Romz0PiQwvT@OywbrCEVDO1m6fo/mM2hH/r6B9ssFl1BjngGRhnaM1Olnz@xVPa7RXK1DiTN7DYwiw1z0ev0S2rKBDSro22oU63ICCqu28I8Xhr1XlRtJYtZzlFA6IbdUyc5a9Hw/Ij4vGlITie3QhMIuJLEnL6LEueUI/2st86UeLn6eX5dTlMl9Nlul7Ppx8 "Brain-Flak – Try It Online")
Input (to either interpreter) is the Brain-Flak Classic program to interpret, then a newline, then a space-separated list of integers. No validation is performed on the input. The newline is required, even if the program or input is blank.
The first step is to parse all of the input, starting with the brackets:
```
# Move to right stack, and push 1 to allow loop to start
<>(())
{
# While keeping -5 on third stack:
<>((([][][][][])<
# Pop bracket or newline k from left stack, and push 0, k-10, k-40, k-60, k-91, k-123 on right stack
(((({}){})(({})({}))[])({}(({})({}({})({}{}(<>)))))[])
# Search this list for a zero, and push the number of nonzero entries popped minus 5
# (thus replacing the 0 if it was destroyed)
>{()<{}>}{})
# Remove rest of list, and push the same number plus 1
# Result is -4 for {, -3 for [, -2 for <, -1 for (, 0 for newline, or 1 for everything else (assumed closing bracket)
<{{}}{}>())
# Repeat until newline found
}{}<>
```
Then the integers are parsed. This wouldn't normally be required, but the input was taken as ASCII. This does have a silver lining, though: text input allows us to determine the stack height, which simplifies things when we don't have access to the stack height nilad.
Integers are parsed into two numbers on the second stack: one for the absolute value, and one for the sign. These are then moved back to the first stack.
The interpreted stacks are stored below the code on the first stack in the following order: current stack height, current stack, other stack height, other stack. The 0 for the other stack height does not need to be pushed at this point, since it will be an implicit zero the first time it is read.
```
(<((
# If stack nonempty, register first stack entry.
{()(((<>))<>)}{}
# For each byte k of input:
{
# Push -3, -13, and k-32
<({}(([][][])((({})({}))[]{})){})>
# Evaluate to 1 if space
# If not space (32):
((){[]<
# If not minus (45):
({}{})((){[]<
# Replace top of right stack (n) with 10*n + (k-48)
({}{}<>((({})({})){}{}){})(<>)
# Else (i.e., if minus):
>}{}){
# Remove excess "else" entry and -3
{}{}
# Set sign to negative (and destroy magnitude that shouldn't even be there yet)
<>(<({}{}())>)(<>)}
# Else (i.e., if space):
>}{}){
# Remove working data for byte, and push two more 0s onto right stack
(<{}{}{}((<>))<>>)
# Push number of integers found
}{}}<>)
# For each integer:
<{({}[]<
# Move magnitude back to left stack
({}<>)<>
# If sign is negative, negate
{(<{}>)<>{<>({}[])}{}<>({}<>)(<>)}{}
>)}{}
# Push stack height onto stack
<>>)
# Push 0
>)
```
The representation of the code is now moved back to the left stack. To make things easier later, we subtract 4 from the opening brackets of nilads, so that each operation has a unique integer from -1 to -8.
```
# For each bracket in the code:
<>{
# Push k-1 and evaluate to k
(({}[])()
# If not closing bracket:
{
# Check next bracket (previously checked, since we started at the end here)
(<{}>)<><(({})[])>
# Subtract 4 if next bracket is closing bracket
# Inverting this condition would save 8 bytes here, but cost 12 bytes later.
[][][][]{()()()()(<{}>)}{}
<>}{}
# Push result onto left stack
<>)
<>}<>{}
```
The main part of the program is actually interpreting the instructions. At the start of each iteration of the main loop, the current instruction is at the top of the left stack, everything after it is below it on the same stack, and everything before it is on the right stack. I tend to visualize this as having a book open to a certain page.
```
{
(
# Get current instruction
({})
# Move all code to left stack, and track the current position in code
<({()<<>({}<>)>}{})>
# Push -1, signifying that the code will move forward to just before a matching }.
# In most cases, this will become 0 (do nothing special) before it is acted upon
([])
# Push instruction minus 1
)
# If opening bracket:
((){[](<
# Push instruction+1 and instruction+4
(({}()()(<>))()()())
# If instruction+4 is nonzero (not loop monad), replace the earlier -1 with 0 to cancel forward seek
# This would be clearer as {(<{}>)<>(<{}>)<>}, but that would be unnecessarily verbose
{(<{}>)<>}
# Else (i.e., if closing bracket):
>)}{}<>){
# If closing bracket, parse command
# Post-condition for all: if not moving to {, pop two and push evaluation, 0.
# (For nilads, can assume second from top is 0.)
# If moving to {, pop one, push -3, 0, 0.
# Seven nested if/else statements, corresponding to eight possible instruction.
# The "else" statements end with 0 already on the stack, so no need to push a 0 except in the innermost if.
# Each one beyond the first increments the instruction by 1 to compare the result with 0
# Each instruction will pop the instruction, leaving only its evaluation (with a 0 on top).
{}((){[]<
({}())((){[]<
({}())((){[]<
({}())((){[]<
({}())((){[]<
({}())((){[]<
({}())((){[](<
# -7: pop
# Pop instruction to reveal existing 0 evaluation
{}
# Move code out of the way to access stack
<>{({}<>)<>}{}
# Duplicate stack height (only useful if stack height is zero)
(({}))
(
# If stack height nonzero
{
# Save stack height on second stack
<{}({}<>)<>>
# Pop stack
{}
# Move stack height back and subtract 1
(<<>({}[]<>)>)
}
# Move code back to normal position
<><{({}<>)<>}>{}
# Evaluate as popped entry (0 if nothing popped)
)
# (else)
>)}{}){
# -6: -1 nilad
# Just evaluate as -1
{}{}(<([])>)
# (else)
}>}{}){
# -5: swap nilad
# Move code out of the way to access stack
{}<>{({}<>)<>}{}
# Number of integers to move: stack height + 1 (namely, the stack height and every entry in the stack)
((({})())
# Move to second stack
<{({}[]<({}<>)<>>)}>{}
# Do (stack height + 1) times again
){({}[]<><
# Get stack element
({}<><
# Move alternate (interpreted) stack to second (real) stack, and push length on top of it
({()<({}[]<({}<>)<>>)>}{}<>)
# Push current stack element below alternate stack
><>)
# Move alternate stack back above newly pushed element
<>({()<({}[]<({}<>)<>>)>}{}<>)
>)}
# Move code back to normal position
<>(<{({}<>)<>}>)
# (else)
}>}{}){
# -4: 1
# Just evaluate to 1
{}{}(<(())>)
# (else)
}>}{}){
# -3: loop
# Create zero on stack while keeping existing evaluation
# This becomes (<{}{}>) in the version that meets the challenge spec
(<{}>)
# Move code out of the way to access stack
<>{({}<>)<>}{}
# Duplicate stack height
(({}))
(
# If stack height nonzero
{
# Save stack height on second stack
<{}({}<>)<>>
# Peek at top of stack
({})
# Move stack height back
(<<>({}<>)>)
}
# Move code back to normal position
<><{({}<>)<>}>
# Look at peeked entry
# Remove the {} in the version meeting the challenge spec
{})
# If peeked entry is nonzero
{
# Replace -3 instruction on third stack
{}([][][])
# Replace loop indicator to 0 (to be incremented later to 1)
<>(((<{}>)
# Create dummy third stack entry to pop
<>))
}
# (else)
}>}{}){
# -2: print
# Just print evaluation without modifying it
{}(<([{}])>)
# (else)
}>}{}){
# -1: evaluate as zero
# Just change evaluation to 0
{}((<{}>))
# else
}>}{}){
# 0: push
# Get current evaluation (without modifying it)
{}(({})
# Create zero on stack as barrier
(<()>)
# Move code out of the way to access stack
<<>{({}<>)<>}{}
# Increment stack height and save on other stack
({}()<>)<>
# Push evaluation
>)
# Move stack height back (and push zero)
<>(<({}<>)>)
# Move code back to normal position
<>{({}<>)<>}
}{}
# Update third stack by adding evaluation to previous entry's evaluation
# Previous entry's instruction is saved temporarily on left stack
(<({}<({}<>)<>>{})<>({}<>)>)
# Increment loop indicator
# If instruction was loop monad and top of stack was nonzero, this increments 0 to 1 (search backward)
# Otherwise, this increments -1 to 0 (do nothing)
<>(<({}())>)
}{}
# While holding onto loop indicator
({}<
# Go to immediately after executed symbol
{({}[]<({}<>)<>>)}{}
>)
# If looping behavior:
{
# Switch stack and check if searching forward
((({}[]<>)
# If so:
{
# Move just-executed { back to left stack, and move with it
(<{}({}<>)>)
}{}
# Either way, we are currently looking at the just-executed bracket.
# In addition, the position we wish to move to is on the current stack.
# Push unmodified loop indicator as initial value in search
())
# While value is nonzero:
<{
# Add 1
({}()
# Move current instruction to other stack
<({}<>)<>
# Check whether next instruction is closing bracket
(({})[])>
# If opening bracket, subtract 2 from value
{[][](<{}>)}{}
)
}{}>
# If searching backward, move back to left stack
()){{}(<>)}
}{}
}
```
After exiting the main loop, all of the code is on the right stack. The only things on the left stack are a zero and the two interpreted stacks. Producing the correct output is a simple matter.
```
# Pop the zero
{}
# Output current stack
{({}[]<[{}]>)}{}
# Discard other stack to avoid implicit printing
{({}[]<{}>)}{}
```
[Answer]
# APL, ~~255~~ 257 bytes
```
b←{S←(⌽⍺)⍬
e←{0=⍴⍵:0
v+∇⊃_ v←∇{r←⊂2↓⍵
'()'≡n←2↑⍵:r,1
'[]'≡n:r,¯1
'{}'≡n:r,{i←⊃⊃⊃S⋄S[1]↓⍨←1⋄i}⍬
'<>'≡n:r,0⊣S⌽⍨←1
r←⊂⍵↓⍨i←0⍳⍨(+\c=⍵)-+\')]>}'['([<{'⍳c←⊃⍵]=⍵
i←1↓¯1↓c←i↑⍵
'('=c←⊃c:r,S[1],⍨←⍺⍺i
'['=c:r,+⎕←⍺⍺i
'{'=c:r,{0≠⊃⊃⊃S:∇e i⋄0}⍬
'<'=c:r,0⊣⍺⍺i}⍵}
⎕←⍪⊃S⊣e⍵}
```
This takes the program as its right argument, and the program input as its left argument, i.e:
```
2 3 b '({}{})'
5
2 3 b '({}<>){({}[])<>({}[])<>}<>'
¯1
7 8 b '({}<>)<>({}[]){({}[])<>(({}))<>}<>{({}<>{})<>}<>'
56
5 b '<>((()))<>{({}[])<>({}<>)<>(({})<>({}<>))<>}<>'
13
8
5
3
2
1
1
```
Ungolfed version: [here](https://bitbucket.org/snippets/marinuso/g6nrd).
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 146 bytes
```
↑⍕¨s⊣{⍎⍕1 ¯1'(s↓⍨←1)⊢⊃s' '0⊣s t←t s' 's,⍨←+/∇¨a' '⎕←+/∇¨a' '∇{×⊃s:∇⍺⍺¨a⋄0}0' '0⊣+/∇¨a'[(⊃⍵)+4×⍬≢a←1↓⍵]}¨⍎∊(')',⍨'(',¨⍕¨⍳4)[0,4,⍨'([{<'⍳⍞]⊣s←⌽⎕⊣t←⍬
```
[Try it online!](https://tio.run/##XY7BSsNAFEX38xWzmxmaYqIVRUJ/JGQRKpVCoMJ0I0NWShqjUxQJ7ly0mywEF9KN4Cb9k/cj8b1MG0UImbl3zrvvJtfp8PImSedXw0maaD2btLCqZnPIn3wGxXLaQv4MtmpqDeXGgF2hCHjzEQipIX8BWyMaKCjXUN5qwYWPnOYLdBectPYcMzjCuKZO0MIN/4xiaXavFHCBV7Bf@OELPNz5mb/P7PFIIgh2qwYjnLHvcL9OqEPXZhtnTU0ti1IKJWi3kMIjr6Lf50hFvjdyfmRCgRbYt5hKYwg8flO5ckP9MbvFne2UHfMTJk1mMsVYr8KxMnhEsQrHhxNNIs74@Z44PP2SeFGONB2Csp87ZQRIRcDfbBckO9RJN/MD "APL (Dyalog Classic) – Try It Online")
one Classic interpreting another :)
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-n`, ~~151~~ ~~148~~ ~~101~~ 98 bytes
```
YRVg;VqR^"{}()<>[]";,8R J,8<>2AL,8("POy|i o0Syl1v0W@y{ }1yPU$+[ ]&@y0 1P$+[ ]"R0" (V{"R1"i}) "^s)y
```
Takes the list of inputs as command-line arguments and the Brain-Flak code from (a line of) stdin. [Try it online!](https://tio.run/##PczBCgIhFIXhV7lcIq5koEEgjMi0jSAxMkKcbQxETQSBmM9u1qLV/53Nmcap1rPzl84/3IC5ENMmROy4crDlSpvVZscVod2n9wh3cUhX@RKnPmUoMtnjbBEgzvskQNqf0QkE8hmdxLEwwOHJUq3aEBFj7T1TLiE2tGrzbcN/NrTU5a2uPw "Pip – TIO Nexus")
*Edit:* Saved a whole lot of bytes over my original approach by switching to a translate-and-eval strategy.
### Ungolfed and commented
This version also includes some debug output showing the Pip code that results from the translation, as well as the stack contents after execution.
```
;;; Setup ;;;
; y is the active stack, l is the off-stack
; y is initialized from command-line arguments
y:RVg (reversed to put the last input at the top)
; l is preset to empty list by default
; p is the program (read from stdin)
p:q
; Translate from braces to numbers 0-7 (we do this so that the
; later replacement step won't try to replace the braces in the
; Pip code)
p R: ^"()[]{}<>" 0,8
;;; Replace nilads with the appropriate code ;;;
; () => o (variable preset to 1)
p R: 01 "o"
; [] => v (variable preset to -1)
p R: 23 "v"
; {} => POy|i
; Pop y; return that value OR i (variable preset to 0)
p R: 45 "POy|i"
; <> => (V{Syli})
; Eval the code Syl to swap stacks y and l, then return i (i.e. 0)
p R: 67 "(V{Syli})"
;;; Replace monads with the appropriate code ;;;
; ( ) => yPU$+[ ]&@y
; Sum ($+) the inside and push (PU) the sum onto y; return
; the just-pushed value, which is the first element of y (@y)
; y will always be truthy (nonempty), since we just pushed a value onto it
p R: 0 "yPU$+["
p R: 1 "]&@y"
; [ ] => P$+[ ]
; Sum ($+) the inside, print (P) the sum, and return it
p R: 2 "P$+["
p R: 3 "]"
; { } => (V{W@y{ }i})
; Eval the code W@y{ }, which wraps the inside in curly braces
; and runs it while (W) the first element of y (@y) is truthy
; (i.e. not zero, and not nil from an empty stack)
; Then return i (i.e. 0)
p R: 4 "(V{W@y{"
p R: 5 "}i})"
; < > => (V{ i})
; Eval the inside, then return i (i.e. 0)
p R: 6 "(V{"
p R: 7 "i})"
; Debug: print the resulting translated code and a blank line
Pp.n
;;; Run the code ;;;
; Eval the translated code
(Vp)
; Output the active stack, newline-separated
PyJn
; Debug: print the active stack and the off-stack
P"Active stack: ".RPy
"Off-stack: ".RPl
```
[Answer]
# Python 3, 429 bytes
```
import re
S='s+=[v];v=0';T='v+=s.pop()';i=0
d={'()':'v+=1','(':S,')':'a+=[v];'+T,'[]':'v-=1','[':S,']':'print(v);'+T,'<>':'a.reverse()','<':S,'>':T,'{}':'v+=0if a[-1]==""else a.pop()','{':S+';while a[-1]:','}':T}
def r(m):global i;t=m.group();i-=(t=='}');s=' '*i;i+=(t=='{');return''.join(s+r+'\n'for r in d[t].split(';'))
def g(c,*a):
a,s,v=['']+list(a),[],0;exec(re.sub(r'[<({[]?[]})>]?',r,c));
while a[-1]!="":print(a.pop())
```
Used like `g('[{}{}]', 2, 3)`
It uses `re.sub` to "compile" the brain-flak source to python and then executes the python. (for debuging, replace `exec` with `print` to get a listing of the python code)
Properly indenting nested while loops eats up a lot of bytes in the code.
[Answer]
# Python, 616 bytes
Instructions:
1. Run with python
2. Input list in `[1,2,...]` format, then press enter
3. Paste/write program, then press enter again
4. Done
Basically, what this program does is recursively "compile" the Brain-flak code into nested lists, and recursively interpret that list. There probably is a way to combine the two...
I'll try and rework the logic later.
```
y="([{<)]}>"
w,z,g=print,len,input
def c(s):
if z(s)<1:return[]
t,i,o=[],1,0
t.append(y.index(s[0]))
while z(t)>0:
x=y.index(s[i])
if x<4:t.append(x)
else:o=t.pop()
i+=1
r=[[o,c(s[1:i-1])]]
r.extend(c(s[i:]))
return r
p=lambda t:t.pop()if z(t)>0 else 0
k=lambda t:t[z(t)-1]if z(t)>0 else 0
r,l=[],eval(g())
a=l
def i(u):
v=0
global a
for t,n in u:
if t<1:
if n:o=i(n);v+=o;a.append(o)
else:v+=1
if t==1:
if n:o=i(n);v+=o;w(o)
else:v-=1
if t==2:
if n:
while k(a)!=0:i(n)
else:v+=p(a)
if t>2:
if n:i(n)
elif a==l:a=r
else:a=l
return v
i(c(g()))
for n in a:w(n)
```
[Answer]
## Perl 5.6, ~~419~~ 414 bytes
I've golfed it a bit but there's probably scope for improvement. Newlines and tabs added here for the sake of a bit of readability:
```
use Text::Balanced extract_bracketed;
$s=shift;
@a=reverse@ARGV;
sub p
{
my($c)=@_;
my$s=0;
while(my$n=extract_bracketed($c)){
$s+='()'eq$n||'{}'eq$n&&shift@a;
$s-='[]'eq$n;
@t=@a,@a=@i,@i=@t if'<>'eq$n;
my$m=chop($n);
$n=substr($n,1);
if($n){
p($n)while'}'eq$m&&$a[0];
p($n)if'}'ne$m;
$s+=$v,unshift@a,$v if')'eq$m;
$s+=$v,print"n=$n m=$m v=$v\n"if']'eq$m;
}
}
$v=$s;
}
p($s);
foreach(@a){
print"$_\n";
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~361~~, 348 bytes
```
c,s=input();s=s,[]
a=s[0]
def w():global a,s;s=s[::-1];a=s[0];return 0
def p(c):a.append(c);return c
def n(c):print c;return c
z=lambda c:0
def l(f):
global a
while a and a[-1]:f()
return 0
for x,y in zip("() ( [] {} <> [ < { } ] >".split(),"+1 +p( -1 +(len(a)and(a.pop())) +w() +n( +z( +l(lambda: ) ) )".split()):c=c.replace(x,y)
exec c
print a
```
[Try it online!](https://tio.run/##RU/LioNAELz7FYWnbjSSLHuaxPzI4KEzjhthdhzUkMSQb3fHSLI0TTdUUY9wH8@d/5pnkw9l68NlJN4P5ZDrKpFy0NsqqW2DK7H6cd1JHCQfFoJWarOr9itn39vx0ntsX@RAhpUUEoL1dfzfqHmhfkFD3/oR5h@ZSie/p1pg1CriqGGV4G2a4HpunYVAfA3R0Vs1xAk@zk3X45bf0XpMbaCUGARd4fHE4QiNAx54osIxLYbg2tgzT7MdskDYxEPOehKO6iRF6AIxM7LYG5knZFNcR2tGBV7mo8PKlKbobXBiLMUMnNibNbHVWlPmOSXiZTjNob@rPw "Python 2 – Try It Online")
-13 bytes saved thanks to @Mr. Xcoder!
[Answer]
# [Python 3](https://docs.python.org/3/), 290 bytes
```
def f(s,*a):
for t in '],) },) >,) [,+3 (,+2 2),1 3),-1 {),+(lAorA).pop() <),<l.reverse()) 2,LlA.appendK 3,LprintK {,+cL <,+L0)( L,(lambda*n: K,(*n)or+nA)( A,[0]'.split():s=s.replace(*t.split(','))
l=[[*a],[]];c=lambda g:[0,*l[0]][-1]and g()+c(g);exec(s,locals());[*map(print,l[0][::-1])]
```
[Try it online!](https://tio.run/##dU/LboMwELzzFXtjFzYoCapaERKJc/gDywcXTBrJMRagqhXKt1MHSqseKmu1r5nxrPsc3lqbTlOtG2iw50hRFkDTdjDA1UIomeDu4@RDcJwCcryHPfEOUuLNDkbiGE3RdgUlrnVIkBPnJun0u@56jUSw59IUiXJO2/oMKZeuu9rhDCPHVQk5x@WWEEpGo26vtYpsBmfGyFLbxbbwq4LFVoZJ78x1QMr6Y@/lnVGVxmj4HoccEgVgjkJESrKQ8lAdF0G4ZGLLkfEiUmx2UtkaLkhxhRc66A9d@btNWynTe7cHEd2Uw9kiPygiyzyH5NRgiON9vFPI/iR/fjCDkIJlk59o9ElIyk9r9sP/0Svsl@ULWljjDPHtqvHM8PJH4wH3fmnBrr8usjgTl/ZH4emvBYH0eJJCmr4A "Python 3 – Try It Online")
] |
[Question]
[
Given a string, if it is even, break the string into 2 even parts, then reverse the parts to get the "reversencoded" string.
Example:
onomatopoeia -> tamonoaieopo
If the string is not of even length, then do not change the position of the middle character, and reverse the letters before and after the middle character.
Example:
pizza -> ipzaz
discord -> sidcdro
Limitations:
The input will not contain any other characters other than AlphaNumeric characters. i.e. No newlines/whitespaces.
General contest, shortest code in each language will be winning.
Good luck!
*btw: i made up the word reversencoded, i'm fairly sure such a form of "encryption" doesnt exist*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ṚŒHZUZ
```
[Try it online!](https://tio.run/##y0rNyan8///hzllHJ3lEhUb9f7h7y@H2R01rIv//z8/Lz00syS/IT81M5CrIrKpK5ErJLE7OL0rhcnRydnF1c/eAMzwB "Jelly – Try It Online")
## Explanation
Consider the string `ABCDEFGHI`:
```
ṚŒHZUZ
Ṛ reverse -> IHGFEDCBA
ŒH split into halves -> IHGFE
DCBA
Z transpose -> ID
HC
GB
FA
E
U reverse each row -> DI
CH
BG
AF
E
Z transpose -> DCBAE
IHGF
implicitly concatenate -> DCBAEIHGF
```
*I never thought the time would come when I'd outgolf Jonathan Allan in Jelly…*
[Answer]
# [Factor](https://factorcode.org/), ~~76~~ ~~72~~ 65 bytes
```
[ dup length 2 rem swap halves rot cut [ reverse ] tri@ 3append ]
```
[Try it online!](https://tio.run/##DcwxDsIwDEbhnVP8J2CADZZuiIUFMVUdosTQiDZ2HbcVRZw9ZH6f3tN5Yy2P@/V2OeFNmmjA6KxHpmmm5ClDlMw@ojEZphXn3bR@wYkrY2GKDhK3zSHE7FkDfqVFmAUDpVcdHaA0Iq9O0LthqUNlg58NbS0LaSZ0MI0Njk6EUkBXxqr35Q8 "Factor – Try It Online")
*-7 bytes thanks to @Bubbler!*
## Explanation:
It's a quotation (anonymous function) that takes a string from the data stack as input and leaves a string on the data stack as output. Assuming `"pizza"` is on the data stack when this quotation is called...
* `dup` Duplicate the object on top of the data stack
**Stack:** `"pizza" "pizza"`
* `length` Take the length
**Stack:** `"pizza" 5`
* `2` Push `2` to the stack
**Stack:** `"pizza" 5 2`
* `rem` The remainder of dividing second-from-top by top
**Stack:** `"pizza" 1`
* `swap` Swap the top two objects
**Stack:** `1 "pizza"`
* `halves` Cut a sequence in half. If the sequence has an odd number of elements, the extra element will be in the sequence that is on top of the stack. `halves` returns slices for efficiency.
**Stack:** `1 T{ slice f 0 2 "pizza" } T{ slice f 2 5 "pizza" }`
* `rot` Move the object third from the top to the top
**Stack:** `T{ slice f 0 2 "pizza" } T{ slice f 2 5 "pizza" } 1`
* `cut` Take a sequence and an index and split the sequence in two at that index. When given an index at either end of a sequence, an empty string will be one of the outputs. `cut` will "reify" the slice.
**Stack:** `T{ slice f 0 2 "pizza" } "z" "za"`
* `[ reverse ]` Push a quotation for `tri@` to use later
**Stack:** `T{ slice f 0 2 "pizza" } "z" "za" [ reverse ]`
* `tri@` Apply a quotation to three objects. In this case, reverse them.
**Stack:** `"ip" "z" "az"`
* `3append` Append three sequences
**Stack:** `"ipzaz"`
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 36 bytes
```
^((.)+?)(.)??((?<-2>.)+)$
$^$1$3$^$4
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8D9OQ0NPU9teE0ja22to2NvoGtkBBTRVuFTiVAxVjIGkyf//@Xn5uYkl@QX5qZmJXAWZVVWJXCmZxcn5RSkA "Retina – Try It Online") Link includes test cases. Explanation:
```
^((.)+?)(.)??((?<-2>.)+)$
```
Match a minimal prefix, an optional centre character, and then a suffix of the same length as the prefix. The prefix and centre are lazy rather than greedy as that's shorter than checking that the group `$2` is properly balanced.
```
$^$1$3$^$4
```
Reverse the prefix and suffix.
[Answer]
# [R](https://www.r-project.org/), 86 bytes
(or [79 bytes](https://tio.run/##Tc5BCsIwEIXhu3SVoaMSQRel04tIFzGmGjCTkEkFe/m0oIirb/M/eLlm93JZHNt4c1SnmW3xkZUgE9uHyUoAA/Hh2O5PGIk7DTJfpWTP963y/c6qeIl9GHGD6OMQRkAPVUxKz7f6orsz/sZYqEl@WYw0OJEG/H8CdQU) with output as a vector of characters instead of a string)
```
function(s,n=nchar(s),m=n/2+.5,o=n:1)intToUtf8(utf8ToInt(s)[c(o[o<m],o[o==m],o[o>m])])
```
[Try it online!](https://tio.run/##Tc4xC8IwEIbh/9IpwUOJoEjx3N3rVDrUmGrA3oVcItg/HwM6uHzP8g1vLNG9XBRHlm8Oy5TJJs@kBAjJPsaoRMOMtNmu1jtgpNZoT6njS5oOKtfp@EypvnqruOfjPEAF8etpHvSgi4whPN/qh2n3IPkqKXq6Q8Im@GUZpYEJjYb/IF0@ "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
LHịJ‘œṖ⁸U
```
[Try it online!](https://tio.run/##y0rNyan8/9/H4@Hubq9HDTOOTn64c9qjxh2h/w@3a0b@/69UkFlVlaikowBhVCkBAA "Jelly – Try It Online")
Full program, due to Jelly's smash-printing
## How it works
```
LHịJ‘œṖ⁸U - Main link. Takes a string S on the left
L - Length of S, L
H - L÷2
J - Indices of S; [1, 2, 3, ..., L]
ị - Index into;
If L is even, this just returns L÷2
If L is odd, this returns [(L-1)÷2, [(L+1)÷2]
‘ - Increment
⁸ - Yield S, to prevent œṖ hooking to U
œṖ - Partition S at the indices in the left
U - Reverse each sublist
Implicitly "smash" together (["ip", "z", "az"] -> "ipzaz") and print
```
[Answer]
# [J](http://jsoftware.com/), 25 22 bytes
```
[:;]<@|./.~#\*@-2%~1+#
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62sY20cavT09eqUY7QcdI1U6wy1lf9rcnGlJmfkK6hnFlQlVqkr6FoppCmoF2RWVSWqQ2WKM1OSU4ryYXIpmcXJ@UUp6v8B "J – Try It Online")
## the idea
Consider `discord`. We solve in two steps:
* Create a mask like `_1 _1 _1 0 1 1 1`. For even number inputs, the mask will not contain 0.
* Use that mask to partition into groups, reversing each group.
## J details
Using discord as an example:
* `1+#` The length plus one, 8 in this case
* `2%~` Divided by 2, so now 4.
* `-` Subtracted elementwise from
* `#\` The range `1..<length>`
```
_3 _2 _1 0 1 2 3
```
* `*@` Sign of each:
```
_1 _1 _1 0 1 1 1
```
* `/.~` Use that as mask to group the input
* `<@|.` Reversing and boxing each group
```
┌───┬─┬───┐
│sid│c│dro│
└───┴─┴───┘
```
* `[:;` Raze
```
sidcdro
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 50 bytes
```
lambda x:x[(l:=len(x)//2)-1::-1]+x[l:-l]+x[:~l:-1]
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUaHCqiJaI8fKNic1T6NCU1/fSFPX0MpK1zBWuyI6x0o3B0Rb1eWARP4XFGXmlWikaSgVZFZVJSppanLBRfLz8nMTS/IL8lMzQRL/AQ "Python 3.8 (pre-release) – Try It Online")
-8 bytes thanks to dingledooper
[Answer]
# JavaScript (ES6), ~~59~~ 58 bytes
*Saved 1 byte thanks to [@edc65](https://codegolf.stackexchange.com/users/21348/edc65)*
Expects an array of characters.
```
s=>s.map(c=>s[i*2]?p=s[i+++i]?c+p:p+c:q=c+q,i=p=q='')&&p+q
```
[Try it online!](https://tio.run/##bYvLCoMwEEX3/Qpx4aNpI3RZSP0QcTFMYpmizsRIF/n5NNBCN97V4XDuC94QcCPZrytblyaTgnkEvYA0mGGg823sxWRQStHYo5K7KLx7g8pfyIjxpq7bqhLlE/IaeHZ65mczNYPWuuSVF9hZ2BGUY9sWXVfssGQN5LI@HXyEYvzGv@UPSYR4FFsKyJv95zkOZNFunD4 "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // s[] = input string, as an array
s.map(c => // for each character c in s[]:
s[i * 2] ? // if s[i * 2] is defined, this is either the first
// half of the string or the middle character of a
// string of odd length:
p = // update p:
s[i++ + i] ? // if s[i * 2 + 1] is defined, this is not the
// middle character:
c + p // prepend c to p
: // else (middle character):
p + c // append c to p
: // else (2nd half of the string):
q = c + q, // prepend c to q
i = p = q = '' // start with p = q = '' and i zero'ish
) // end of map()
&& p + q // return p + q
```
[Answer]
# [R](https://www.r-project.org/), ~~81~~ 79 bytes
```
function(s,n=nchar(s),m=n/2+1)intToUtf8(utf8ToInt(s)[c(m:2-1,m[n>1&n%%2],n:m)])
```
[Try it online!](https://tio.run/##dY6xCoMwFEX3foZgTegrJQ6lBNK9u53EIcZEA82LJLFQfz516ODS5R4OZ7khB/3WIWpUftAimwVVsh5JBBSoJhlIpOAEXuoToxZT45/J3MiyTeMfmLbcKuJ4fWbgWryzI5Zl3QFyRzuao5zn14f8wPgV4tLHFCyOkEQx23WVsQAjGIX9E3rYG6lkrwZtxqn6Eyqavw "R – Try It Online")
*-2 bytes thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)*
*-2 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)*
Developed independently from [@Dominic's answer](https://codegolf.stackexchange.com/a/223762/55372), but some golfs adapted from there.
Abuses the fact that range operator `:` and extract operator `[` both cast their inputs to int.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ ~~13~~ 12 bytes
```
R2ä`?IgÉiÁ}?
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/yOjwkgR7z/TDnZmHG2vt//8vyKyqSgQA "05AB1E – Try It Online")
```
R reverse input
2ä slice to 2 pieces, i.e. ["azz", "ip"]
` dump pieces to stack
? print last piece without newline
I push input
g length
É is odd
iÁ} if true rotate right by one
? print without newline
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 42 bytes
```
^|$
¶
+`(.*¶)(.)(.*)(.)(¶.*)
$2$1$3$5$4
¶
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP65GhevQNi7tBA09rUPbNDX0gEgLTB3aBmRwqRipGKoYq5iqmICU/f@fn5efm1iSX5CfmpnIVZBZVZXIlZJZnJxflAIA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
^|$
¶
```
Wrap the input in a working area of three lines.
```
(.*¶)(.)(.*)(.)(¶.*)
$2$1$3$5$4
```
Extract the first and last characters of the input, building them up in reverse in the working area.
```
+`
```
Continue extracting characters until there is at most one left.
```
¶
```
Join the pieces back together.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒHṚU2¦FƲ⁺
```
A monadic Link accepting a list that yields a list.
**[Try it online!](https://tio.run/##ASAA3/9qZWxsef//xZJI4bmaVTLCpkbGsuKBuv///3Bpenphcw "Jelly – Try It Online")**
### How?
```
ŒHṚU2¦FƲ⁺ - Link: list, S
⁺ - repeat this twice - i.e. f(f(S)):
Ʋ - last four links as a monad - f(x)
ŒH - split (x) into two halves (odd length x gives longer first half)
Ṛ - reverse
2¦ - apply to second element:
U - upend (reverses just 2nd element)
F - flatten
```
---
Another 9 byter using the same method:
```
ŒHṪ;UFƲ$⁺
```
[Answer]
# [Red](http://www.red-lang.org), 81 bytes
```
func[s][rejoin[reverse take/part s(n: length? s)/ 2 take/part s n % 2 reverse s]]
```
[Try it online!](https://tio.run/##TUy7CgIxEOzzFUtA0EIOLK/Qf7ANKUKy8eJjN2yi4v18DB4HTjPDvARDO2MwVsWxxSd5U6wRvHKiTi@UglDdDYfspELZ0gh3pEudTlB2Axz@QyDYdGedFWtbZEHnJ3izBDAKOjQTP1zlzJicXqyc5nnVIRXf21pZkyVRBeM5f5YHvT9qiD/dz78 "Red – Try It Online")
# Using `parse`, 93 bytes
```
func[s][h:(n: length? s)/ 2 d: n % 2 b:[change copy t h skip(reverse t)]parse s[b d skip b]s]
```
[Try it online!](https://tio.run/##NY3BCgIhGITv@xSDEOweIujood6hq3hw9XeVSkWtaF/eNqM5fcwMM5lMu5ARcrC82UfQokjh@Bg4bhSW6s4o0wFHGI6A3QYzF9qpsBB0TG9UOJSrT2OmJ@VCqJNM6gtFzDA9wyyLbDZmUtrhFbOBGLCJxRDvqsYUySv2s5Jf1z8bX/TWZoMUKftQIfpnX2D7E4PtLGX7AA "Red – Try It Online")
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 95 bytes
```
M =LEN(SIZE(I =INPUT) / 2)
I M . L ARB . C M . R RPOS(0)
OUTPUT =REVERSE(L) C REVERSE(R)
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/n9NXwdbH1U8j2DPKVcNTwdbTLyA0RFNBX8FIk4vTU8FXQU/BR8ExyAlIO4N5QQpBAf7BGgZAaf/QEKBiBdsg1zDXoGBXDR9NoBoYJ0iTy9XP5f//gsyqqkQA "SNOBOL4 (CSNOBOL4) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 21 bytes
```
++_<QK/lQ2*@QK%lQ2_>K
```
[Try it online!](https://tio.run/##K6gsyfj/X1s73ibQWz8n0EjLIdBbFUjH23n//6@UklmcnF@UogQA "Pyth – Try It Online")
```
Q # input
K/lQ2 # Set K to len(Q)/2 (integer division)
_<QK # Take first K elements and reverse them
*@QK%lQ2 # The element at index K taken len(Q) % 2 times
_>K # Take last K elements and reverse them
++ # Concatenate them
```
*-2 bytes thanks to hakr14*
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 54 bytes
```
YpC<c-r>=strlen('<c-r>"')/2
<esc>DkA <esc>0@"li
<esc>$@"hi
<Esc>:%!rev
gJgJF x
```
[Try it online!](https://tio.run/##K/v/P7LA2SZZt8jOtrikKCc1T0MdzFNS19Q34rJJLU62c8l2VAAzDByUcjIhYioOShlApiuQaaWqWJRaxpXule7lplDx/39@Xn5uYkl@QX5qZuJ/3TIA "V (vim) – Try It Online")
The 'no whitespace' guarantee helped a lot with writing this solution.
## Explanation
```
YpC<c-r>=strlen('<c-r>"')/2
Yp copy input to new line
C cut and open insert mode
<c-r>=strlen('<c-r>"')/2 set the line to half of input length
call this k
<esc>DkA <esc>0@"li
<esc> exit insert mode
D delete the number k(and copy)
k move to the input
A <esc> insert a space at the end
0@"l move right k times from the start
i insert a newline
<esc>$@"hi
$@"hi do the same thing, except from the right
<esc>:%!rev reverse all lines
gJgJF x
gJgJ join the three lines
F navigate to the previous space
x delete it
```
[Answer]
# [Julia](http://julialang.org/), ~~50~~ 48 bytes
```
a->a[(d=(l=end)÷2):-1:1]a[d+1:l-d]a[l:-1:l-d+1]
```
[Try it online!](https://tio.run/##JctBCsMgEIXhvacYXCnBgl0K5iLiYqgGLNMo1UIaeq8eoAezpt19/I93fVBCvfXFdlQzOhGsIBvXID/vszRKG@3RhUkbUmGIjjQ4ad9brK2CBc45y2u@Ycslx4SspH1HFlK95HsYK7xmqIVSY0cshE/h4P9eTuIHCV72Lw "Julia 1.0 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 36 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.5 bytes
```
Ṙ½∩R∩
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJ+cz0iLCIiLCLhuZjCveKIqVLiiKkiLCIiLCIhKFxcdyspIC0+IChcXHcrKS5cbm9ub21hdG9wb2VpYSAtPiB0YW1vbm9haWVvcG9cbnBpenphIC0+IGlwemF6XG5kaXNjb3JkIC0+IHNpZGNkcm8iXQ==)
Porting Jelly is always the best way to do code-golf. Can't believe transpose used to be 2 bytes
## Explained
```
Ṙ½∩R∩
Ṙ # reversed(input)
½ # ↑ split into two halves
∩ # transpose ↑
R # reverse each row in ↑ (when neither argument is a function, reduce performs vectorised reverse instead)
∩ # transpose ↑ and sum using s flag
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
⭆⪪θ⊘⊕Lθ⭆⪪ι⊘Lθ⮌λ
```
[Try it online!](https://tio.run/##XctBCoAwDATAr/QYob7ADygoiL6gtEELsWoM/X6sFxH3snvY8atjvztSHTkmgVlKLYM7YD4oCpzWtI4yBuiSZ9wwSdk9pkVWOKsSa/4mvubzs2bCjHwh0KMa1RAvv3PQOtMN "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input string
⪪ Split into pieces of length
θ Input string
L Length
⊕ Incremented
⊘ Halved
⭆ Map over pieces and join
ι Current piece
⪪ Split into pieces of length
θ Input string
L Length
⊘ Halved
⭆ Map over pieces and join
λ Current piece
⮌ Reversed
Implicitly print
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~63~~ 62 bytes
```
lambda s:s[(l:=len(s))//2-1::-1]+s[l//2]*(l&1)+s[:-~l//2-1:-1]
```
[Try it online!](https://tio.run/##NY/RboMgFEDf/YobHyZsmsa2yRYS9yO2DwiXlgyFAEs2jft1B67j6Zxcci6473i30@nN@U11l83wcZAcAgs9MawzOJFA6eFwbFrGmvb6EnqT7PpMzFNLk7Hmx/yN03SLGGKADkjJByFRlTU86JbRTnbk0TqLmmd3ep53kDoI62VJC/xyKCLKPSIGrlDmC4nkTWHGyMfU4RpTJ7t2M58zBC2F9DZFxB3FB/rcqC6fx9ezqGrYqT1VtFDWQ6wR9ASzdmR/dA3/mykrIJ38DUUi3cV5PUWiqiWu0LzDElZYHkt67LpwXSu6/QI "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
g;¤Ā‚Ć£íJ
```
[Try it online](https://tio.run/##MzBNTDJM/f8/3frQkiMNjxpmHWk7tPjwWq///w2NjE1MAQ) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfaXL/3TrQ0uONDxqmHWk7dDiw2u9/uv8j1bKz8vPTSzJL8hPzUxU0lEqyKyqAtEpmcXJ@UUpQJahkbGJqVIsAA).
**Explanation:**
```
g # Get the length of the (implicit) input
; # Halve it
¤ # Get the last digit (without popping), which is either 0 or 5
Ā # Truthify it, converting the 5 to 1 (0 remains 0)
‚ # Pair the two values together
Ć # Enclose it; appending the leading halve length as trailing item
£ # Split the (implicit) input into parts of that size (which truncates the
# decimals)
í # Reverse each part
J # Join the parts back together to a string
# (after which the result is output implicitly)
```
It uses the legacy version of 05AB1E, because in the new version the `¤` won't work on decimals and would require an explicit cast to string (so 10 bytes instead: [`g;§¤Ā‚Ć£íJ`](https://tio.run/##ASEA3v9vc2FiaWX//2c7wqfCpMSA4oCaxIbCo8OtSv//MTIzNDU)).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
Splits the input (e.g. `"pizza"` or `"pizzas"`) into an array based on indexes (e.g. `["pi", "z", "za"]` or `["piz", "zas"]`), then maps each item through string reverse and joins again.
```
üÏgUÊ*½-½ÃmÔ¬
ü // Group input characters by mapped value where
Ï // depending on whether the index is smaller, equal or larger than
UÊ*½-½ // input's length in half minus half,
g // the value is -1, 0, or 1.
à // Then,
mÔ¬ // map each item through reverse and join to a string.
```
[Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=/M9nVcoqvS29w23UrA==&input=InBpenphIg==)
[Answer]
# [Scala](http://www.scala-lang.org/), 145 bytes
Golfed version, [try it online!](https://tio.run/##VYxBDoIwEEX3nmJCYtIGg8pS0wVn8AQDDLSmtA2txEA4e0UkRrfvvf99hRqjLe9UBSiAnoFM7aFwDqZYUwMNw8st9Mq0XEwDapACM02mDfKYX9@gE0wt1Qb3uRBnjlklsS8CkzwL9rMH0p6ShF8x84/Sr4ydDkvR00C9pxR@jUy77fIbzBHALTJowxqWODWOmHC@@6PW2A6DdZbUKuf4Ag)
```
def f(a:String)={val h=a.length/2;val m=(if(a.length%2==1)a.charAt(h).toString else"");a.substring(0,h).reverse+ a.substring(h+m.length).reverse}
```
Ungolfed version
```
object A extends App {
val f:String=>String=input=>{
val halfLength = input.length / 2
val middleChar = if (input.length % 2 == 1) input.charAt(halfLength).toString else ""
val firstHalfReversed = input.substring(0, halfLength).reverse
val secondHalfReversed = input.substring(halfLength + middleChar.length).reverse
firstHalfReversed + middleChar + secondHalfReversed
}
println(f("pizza"))
println(f("onomatopoeia"))
}
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 102 ~~106~~ bytes
>
> -4 bytes thanks to @ceilingcat !
>
>
>
For each character we calculate the index of the character it should switch place with.
Incidentally this calculation also gives `-1` for the middle character of an odd-length String, which is quite useful!
```
s->{var r="";for(int j,i=0,l=s.length();i<l;r+=s.charAt(j<0?i-1:j))j=l-(i++*2/l*2-1)*~l/2-i;return r;}
```
[Try it online!](https://tio.run/##dZDPUsIwEMbvPsVOTmlLS1tQ0Fod73ry6HhY2wCp6R@TlFEcvHnzEfTleBEMEBhhZE@Zb3/59tstcIp@kT8vm/ZJ8AwygUrBHfIK3k9OAHilmRxhxuDWCGDqXktejWFE7UM5idHnK1hp1MbjFgSkS@VfvU9RgkwJSUa1pMYKig5Pw45IVSBYNdYT6iT8UiTSM0o2QXmjaXEZXnM/uigcp0iFT7nnuXFXuLEfOe6H6MY@TyTTraxAJvNlshpsw9v505rnwKYothEblFh2tsnZa8MyzXJnfyHJVCs0pCCCEV3/WC9m@m9KszKoWx00htSionTrEbCXFoWim8/ONVl8f5ILsvj5Io5HgHi2sTvRP0lLc2yb9OERUI7VNtl6ByB1VZeo66ZmHAl0gGgsjYacGY2AjWnhhs9mhrJlYN7McHZI5VxltczJjlI8z3K5ceu6R9be9wijuNc/PRsMifXoxVHYHw7OTg@n7chzsiH7K/T8KPo3fhTG/d6KcrubG86Xvw "Java (JDK) – Try It Online")
[Answer]
# [SAS](https://sas.com), 132 bytes
```
%let n=%eval(%length(&s)/2);data;s="&s";length a b$&n;a=s;b=reverse(s);s=cats(reverse(a),ifc(length(s)/2=&n,"",char(s,&n+1)),b);run;
```
Assuming you have macrovariable `s` containing the text:
```
%let s=abcXdef;
```
Execute ("ungolfed" for readability):
```
%let n = %eval(%length(&s)/2);
data;
s = "&s";
length a b $ &n;
a = s;
b = reverse(s);
s = cats(reverse(a)
,ifc(length(s)/2 = &n, "", char(s, &n+1))
,b);
run;
```
to print out content of created dataset (named automatically `data<N>`) run:
```
proc print;
run;
```
[Answer]
# [ReRegex](https://github.com/TehFlaminTaco/ReRegex), 146 bytes
```
( *)@(.)/$2$1 @/@$/%/(\w)( *)( +) %\2(?! )/$2$3% $2$1/(.*?)(\w) ( +)%\3(.*)/!$1>$2!$4>/^(\w*?)( +)%\2(.*)/!$1>!$3>/!(\w*?)(\w)>/$2!$1>/!>//@#input
```
## Explained
```
( *)@(.)/$2$1 @/ # Count characters. Add a space for every character in the string.
@$/%/ # Once counting is done, move to dividing
(\w)( *)( +) %\2(?! )/$2$3% $2$1/ # Push character an space pairs over to the other side until it's roughly equal to the lefti n length
(.*?)(\w) ( +)%\3(.*)/!$1>$2!$4>/ # When they're roughly equal, split odd groups into !left>mid!right>
^(\w*?)( +)%\2(.*)/!$1>!$3>/ # Same as above but without the mid character.
!(\w*?)(\w)>/$2!$1>/ # Push the last character of a !> group right behind it, effectively reversing the string.
!>// # Clear up any emtpy !> groups
@#input # Format the input with a @ counter behind it.
```
[Try it online!](https://tio.run/##PctBCsIwEIXhq0xwAjMVOiRxneYgwY0N0o1KtOjtY6aUbt//vVpquZdfawQDJxpZ0KODJAnFCuUvayA4M9jsaTKwiWBBndA4TKwKlNgc@sBi0EX0Bi9Rrj0q2ao/qsEQxeyt36Ood32LIum0PF7rp7V5ed@edf4D "ReRegex – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Ôñ@Ê*½-½ gY
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1PFAyiq9Lb0gZ1k&input=InBpenphIg)
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~8~~ 6.5 bytes (13 nibbles)
*Saved 1.5 bytes by porting [xigoi's Jelly solution](https://codegolf.stackexchange.com/a/223777/16766) like [lyxal did](https://codegolf.stackexchange.com/a/223813/16766)*
```
+`'.`'`\~\@\$
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWe7QVEtS5FPS4FMA0kIxRqFOIcQAyY1QgShbAqILMqqpECAcA)
### Explanation
```
+`'.`'`\~\@\$
@ First line of stdin
\ Reverse
`\~ Split into two parts
`' Transpose
. Map this function to each string in that list:
\$ Reverse it
`' Transpose
+ Concatenate together
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 274 bytes
```
class A{public static void main(String[]a){System.out.print(new StringBuilder(a[0].substring(0,a[0].length()/2)).reverse().toString()+(a[0].length()%2==1?a[0].charAt(a[0].length()/2):"")+new StringBuilder(a[0].substring((int)(a[0].length()/2D+.5D))).reverse().toString());}}
```
[Try it online!](https://tio.run/##hY7NCoJAEMdfRYRgBmszoUsRYfgGHsXDpEtt@cXuaKT47JvYqSA6Dfzm/3Wjjla3/G5tVpAxTjg07blQmWOYeDpdrXKnJFVBzFpVlyQlHOKnYVmKumXRTJChkg/n/T@1qsilBkr8VJj2bGYK/nIGhawufAVcB4hCy05qIwEF128zoAcfukVwOGyOM8qupEOG75id66L3tx6mkfjtjTyxjfDHENyPo7W2UX1PLw "Java (JDK) – Try It Online")
[Answer]
# [Lua](https://www.lua.org/), 69 bytes
```
s=...n=#s//2print((s:sub(-n)..s:sub(n+1,-n-1)..s:sub(1,n)):reverse())
```
[Try it online!](https://tio.run/##PcgxCsAgDADAx3RJqEbsKPgYCw5Cm4jRfj8dCt2Ou1Yx00xEnDcN4eij8QTQpOsEz0j0kffoPPv4R3SMmEZ96tAKiGYmLHeZ0qW28gI "Lua – Try It Online")
] |
[Question]
[
Make me a [s'more](https://en.wikipedia.org/wiki/S%27more)! I tell you the width, the amount of graham cracker, the amount of chocolate, and the amount of marshmallow. An example:
Input:
Width: `10`
Graham: `3`
Chocolate: `2`
Marshmallow: `1`.
Output:
```
GGGGGGGGGG
GGGGGGGGGG
GGGGGGGGGG
CCCCCCCCCC
CCCCCCCCCC
MMMMMMMMMM
GGGGGGGGGG
GGGGGGGGGG
GGGGGGGGGG
```
Is it *that easy?* Um... yes.
Note that the input should be a list of arguments to a function or a program, not a string. You might choose the first being Width, then Graham, but any order is fine.
[Full test cases if you are interested.](https://pastebin.com/dNzS3FgY)
# Stack snippet (for testing, etc.)
This is to test the output.
```
var smore = function(width, graham, chocolate, marshmallow){
return ("G".repeat(width) + "\n").repeat(graham) +
("C".repeat(width) + "\n").repeat(chocolate) +
("M".repeat(width) + "\n").repeat(marshmallow) +
("G".repeat(width) + "\n").repeat(graham);
};
Snippetify(smore);
```
```
<script src="https://programmer5000.com/snippetify.min.js"></script>
Width: <input type = "number">
Graham: <input type = "number">
Chocolate: <input type = "number">
Marshmallow: <input type = "number">
<button>Try it out!</button>
<pre data-output></pre>
```
# Notes:
* You may include a trailing newline on the end of the last line. You may also use a `\` instead of a newline.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
* Any questions? Comment below:
[Answer]
# [Python 2](https://docs.python.org/2/), ~~73~~ 48 bytes
```
lambda w,g,c,m:zip(*['G'*g+'C'*c+'M'*m+'G'*g]*w)
```
[Try it online!](https://tio.run/nexus/python2#LYvLCsIwEADv/YoFD5vHIlZvQk8ePPkF1kOMpq6YBzGl4s9HaL0Nw4zr@voy/nozMNFAlvz@y0moMx5RDRoPqKzGEyqvZ3NRk6zccUhjEbJZpcyhgBOKZbMw9gHXz8hBeJMELkxzISX8hzgW8KZk/kB0YB8mG1vu@V3bDe1oS@0P "Python 2 – TIO Nexus")
Creates a transposed version of the answer, than transposes it to the correct format with `zip(*l)`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ ~~19~~ 19 bytes
```
"GCMG"S×|D«‚øvy`.D»
```
[Try it online!](https://tio.run/nexus/05ab1e#@6/k7uzrrhR8eHqNy6HVjxpmHd5RVpmg53Jo9///hgZcxlxGXIYA "05AB1E – TIO Nexus")
-2 thanks to my oversight and Emigna.
```
"GCMG"S× # Push GCMG, separate, duplicate n times.
|D« # Push rest of inputs, doubled.
‚ø # Wrap GCMG array and input array, then zip them into pairs.
vy`.D» # For each pair, print n of G/C/M/G.
```
(See Emigna's answer, it's better: <https://codegolf.stackexchange.com/a/116787/59376>)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ 16 bytes
1 bytes saved thanks to *carusocomputing*.
```
"GCMG"S×vy²Nè.D»
```
[Try it online!](https://tio.run/nexus/05ab1e#@6/k7uzrrhR8eHpZ5aFNfodX6Lkc2v3/v6EBV7SxjpGOYSwA "05AB1E – TIO Nexus")
Input order is `W, [G,C,M]`
**Explanation**
`10, [3,2,1]` used as example.
```
"GCMG"S # push the list ['G','C','M','G']
× # repeat each W times
# STACK: ['GGGGGGGGGG', 'CCCCCCCCCC', 'MMMMMMMMMM', 'GGGGGGGGGG']
v # for each [string, index] y,N in the list
²Nè # get the amount of layers at index N from the [G,C,M] list
y .D # duplicate the string y that many times
» # join strings by newlines
```
[Answer]
# JavaScript (ES6), 71 bytes
```
(W,G,C,M)=>[...'GCMG'].map(X=>`${X.repeat(W)}
`.repeat(eval(X))).join``
```
Woohoo, beat 3 other JavaScript answers!
```
f=
(W,G,C,M)=>[...'GCMG'].map(X=>`${X.repeat(W)}
`.repeat(eval(X))).join``
console.log(
f(10, 3, 2, 1)
)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 17 bytes
```
'GCMG'iK:)Y"!liX"
```
Input format is: first input `[G, C, M]`, second input `W`.
[Try it online!](https://tio.run/nexus/matl#@6/u7uzrrp7pbaUZqaSYkxmh9P9/tLGCkYJhLJehAQA "MATL – TIO Nexus")
### Explanation with example
Consider inputs `[3 2 1]` and `10`.
```
'GCMG' % Push this string
% STACK: 'GCMG'
i % Take first input: array of three numbers
% STACK: 'GCMG', [3 2 1]
K: % Push [1 2 3 4]
% STACK: 'GCMG', [3 2 1], [1 2 3 4]
) % Index (modular, 1-based). This repeats the first entry of the input array
% STACK: 'GCMG', [3 2 1 3]
Y" % Run-length decoding
% STACK: 'GGGCCMGGG'
! % Transpose. Gives a column vector of chars
% STACK: ['G'; 'G'; 'G'; 'C'; 'C'; 'M'; 'G'; 'G'; 'G']
l % Push 1
% STACK: ['G'; 'G'; 'G'; 'C'; 'C'; 'M'; 'G'; 'G'; 'G'], 1
i % Take second input: number
% STACK: ['G'; 'G'; 'G'; 'C'; 'C'; 'M'; 'G'; 'G'; 'G'], 1, 10
X" % Repeat the specified numbers of times along first and second dimensions
% STACK: ['GGGGGGGGGG';'GGGGGGGGGG';'GGGGGGGGGG';'CCCCCCCCCC';...;'GGGGGGGGGG']
% Implicitly display
```
[Answer]
## [C#](http://csharppad.com/gist/6c2b7ee2d9f3df79de6e4da1950ee4ea), 204 bytes
---
### Golfed
```
(w,g,c,m)=>{string G="\n".PadLeft(++w,'G'),C="\n".PadLeft(w,'C'),M="\n".PadLeft(w,'M'),o="".PadLeft(g,'G');o+="".PadLeft(m,'M')+"".PadLeft(c,'C')+o;return o.Replace("G",G).Replace("C",C).Replace("M",M);};
```
---
### Ungolfed
```
( w, g, c, m ) => {
string
G = "\n".PadLeft( ++w, 'G' ),
C = "\n".PadLeft( w, 'C' ),
M = "\n".PadLeft( w, 'M' ),
o = "".PadLeft( g, 'G' );
o +=
"".PadLeft( m, 'M' ) +
"".PadLeft( c, 'C' ) +
o;
return o
.Replace( "G", G )
.Replace( "C", C )
.Replace( "M", M );
};
```
---
### Ungolfed readable
```
// Function with 4 parameters
// w : Width
// g : Graham
// c : Chocolate
// m : Marshmallow
( w, g, c, m ) => {
// Initialization of vars with the contents
// of each line, with a new line at the end
string
G = "\n".PadLeft( ++w, 'G' ),
C = "\n".PadLeft( w, 'C' ),
M = "\n".PadLeft( w, 'M' ),
// Trick to reduce the byte count
// Initialize the output with n 'G's
o = "".PadLeft( g, 'G' );
// Add again n 'M's and n 'C's
// Append the 'G's at the end.
o +=
"".PadLeft( m, 'M' ) +
"".PadLeft( c, 'C' ) +
o;
// Replce every instance of 'G'/'C'/'M'
// with the full line
return o
.Replace( "G", G )
.Replace( "C", C )
.Replace( "M", M );
};
```
---
### Full code
```
using System;
using System.Collections.Generic;
namespace Namespace {
class Program {
static void Main( String[] args ) {
Func<Int32, Int32, Int32, Int32, String> f = ( w, g, c, m ) => {
string
G = "\n".PadLeft( ++w, 'G' ),
C = "\n".PadLeft( w, 'C' ),
M = "\n".PadLeft( w, 'M' ),
o = "".PadLeft( g, 'G' );
o +=
"".PadLeft( m, 'M' ) +
"".PadLeft( c, 'C' ) +
o;
return o
.Replace( "G", G )
.Replace( "C", C )
.Replace( "M", M );
};
List<Tuple<Int32, Int32, Int32, Int32>>
testCases = new List<Tuple<Int32, Int32, Int32, Int32>>() {
new Tuple<Int32, Int32, Int32, Int32>( 1, 1, 1, 1 ),
new Tuple<Int32, Int32, Int32, Int32>( 1, 1, 1, 2 ),
new Tuple<Int32, Int32, Int32, Int32>( 1, 1, 2, 1 ),
//
// ...
//
// The link above contains the code ready to run
// and with every test from the pastebin link
//
// Yes, it contains 342 tests ready to run.
//
// I can barely fit every test on a 1080p screen...
// ... and there's 6 tests per line... Jebus...
//
};
foreach( var testCase in testCases ) {
Console.WriteLine( $"Input:\nWidth: {testCase.Item1,3} Graham: {testCase.Item2,3} Chocolate: {testCase.Item3,3} Marshmellow: {testCase.Item4,3}\nOutput:\n{f( testCase.Item1, testCase.Item2, testCase.Item3, testCase.Item4 )}\n" );
}
Console.ReadLine();
}
}
}
```
---
### Releases
* **v1.0** - `204 bytes` - Initial solution.
---
### Notes
* [Looking for a picture of my *beautiful* test screen?](https://i.stack.imgur.com/4OERg.png)
* On a second thought, CSharpPad can't handle those tests, [here's a version with fewer tests](http://csharppad.com/gist/ea843ff852f907176d8a3eb86cf93b3a)
[Answer]
# Ruby, 47 bytes
```
->w,g,c,m{puts r=[?G*w]*g,[?C*w]*c,[?M*w]*m,r}
```
thanks to ventero
# Ruby, 51 bytes
```
->w,g,c,m{(?G*g+?C*c+?M*m+?G*g).chars{|i|puts i*w}}
```
Call like this:
```
f=->w,g,c,m{(?G*g+?C*c+?M*m+?G*g).chars{|i|puts i*w}}
f[10,3,2,1]
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 49 bytes
```
$a,$b=$args;0..2+0|%{,("$('GCM'[$_])"*$a)*$b[$_]}
```
[Try it online!](https://tio.run/nexus/powershell#@6@SqKOSZKuSWJRebG2gp2ekbVCjWq2joaSioe7u7KserRIfq6mkpZKoqaWSBOLU/v//39Dgv/F/o/@GAA "PowerShell – TIO Nexus")
Takes input as four command-line arguments, `width graham chocolate marshmallow`, stores the first into `$a` and the rest into `$b` (implicitly as an array). Loops from over the range `0,1,2,0`. Each loop, we index into string `GCM`, re-cast that `char` as a string, and multiply it out by `$a` (the width), and then using the comma-operator `,`, turns that into an array by multiplying the appropriate index of `$b` (i.e., how many layers). Those resultant string arrays are all left on the pipeline and output is implicit, with a newline between elements.
[Answer]
# C, ~~108~~ 105 bytes
*Thanks to @Quentin for saving 3 bytes!*
```
#define F(i,c)for(;i--;puts(""))for(j=w;j--;)putchar(c);
i,j;f(w,g,c,m){i=g;F(i,71)F(c,67)F(m,77)F(g,71)}
```
[Try it online!](https://tio.run/nexus/c-gcc#HcxBCsMgEIXhvacY0s0MTKC2UBeSbe4RbLQjaEuSkkXI2a32bX74Fq9cnrOXPMOIwo78e0ErfW8/323FrqO/xGG3sSJVda9pQUdWCUfrcefAjhMdMgTbPoymER0/TE1i0xIankXyBmmSjKQOBXUe9ZXhznBj0PXxLD8)
[Answer]
## Batch, 146 bytes
```
@set s=
@for /l %%i in (1,1,%1)do @call set s=G%%s%%
@for %%w in (%2.%s% %3.%s:G=C% %4.%s:G=M% %2.%s%)do @for /l %%i in (1,1,%%~nw)do @echo%%~xw
```
Relies on the obscure behaviour of `echo` in that it can often ignore the symbol between `echo` and the text to be echoed to collapse the four loops into a nested loop.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 22 bytes
```
éGÄÀäjMoC
MÀÄkÀÄHdêÀP
```
[Try it online!](https://tio.run/nexus/v#@394pfvhlsMNh5dk@eY7c/lKA5kt2SDCI@XwqsMNAf///zf@b/jf6L@hAQA "V – TIO Nexus")
Hexdump:
```
00000000: e947 c4c0 e46a 4d6f 430a 4d1b c0c4 6bc0 .G...jMoC.M...k.
00000010: c448 64ea c050 .Hd..P
```
Input order is
```
Graham, Marshmallow, Chocolate, Width
```
Explanation:
```
éG " Insert 'G'
Ä " Duplicate this line
Àäj " *arg1* times, duplicate this line and the line below it
M " Move to the middle line
o " Open up a newline, and enter insert mode
C<cr>M<esc> " Insert 'C\nM'
ÀÄ " Make *arg2* copies of this line (Marshmallow)
k " Move up one line
ÀÄ " Make *arg3* copies of this line (Chocolate)
H " Move to the first line
dê " Delete this column
ÀP " And paste it horizontally *arg4* times
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
Code:
```
…GCM‚øü׬)˜S×»
```
Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@/@oYZm7s@@jhlmHdxzec3j6oTWap@cEA@nd//9HG@soGOkoGMZyGRoAAA "05AB1E – TIO Nexus")
Explanation:
```
…GCM # Push the string "GCM"
‚ # Wrap with the input
ø # Transpose the array
ü× # Compute the string product of each element (['A', 3] --> 'AAA')
¬)˜ # Get the last element and append to the list
S # Split the list
× # Vectorized string multiplication with the second input
» # Join by newlines and implicitly print
```
[Answer]
# Excel, 104 bytes
Oh, boy! A formula that requires line breaks.
```
=REPT(REPT("G",A1)&"
",A2)&REPT(REPT("C",A1)&"
",A3)&REPT(REPT("M",A1)&"
",A4)&REPT(REPT("G",A1)&"
",A2)
```
`A1` has Width
`A2` has Graham
`A3` has Chocolate
`A4` has Mallow
---
If pre-formatting is allowed, then you can format the cell for Vertical Text and shorten the formula to 65 bytes:
```
=REPT(REPT("G",A2)&REPT("C",A3)&REPT("M",A4)&REPT("G",A2)&"
",A1)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“GCM”ẋ"ṁ4Fẋ€Y
```
A dyadic program. Inputs are: `[Graham's, Chocolates, Marshmallows]`, `Width`.
**[Try it online!](https://tio.run/nexus/jelly#@/@oYY67s@@jhrkPd3UrPdzZaOIGZDxqWhP5////aGMdIx3D2P@GBl/z8nWTE5MzUgE "Jelly – TIO Nexus")**
### How?
```
“GCM”ẋ"ṁ4Fẋ€Y - Main link: [g,c,m], w e.g. [1,2,1], 2
“GCM” - literal ['G', 'C', 'M']
" - zip that and [g,c,m] with the dyadic operation:
ẋ - repeat list [['G'],['C','C'],['M']]
ṁ4 - mould like [1,2,3,4] [['G'],['C','C'],['M'],['G']]
F - flatten ['G','C','C','M','G']
ẋ€ - repeat €ach w times [['G','G'],['C','C'],['C','C'],['M','M'],['G','G']]
Y - join with line feeds ['G','G','\n','C','C','\n','C','C','\n','M','M','\n','G','G']
- implicit print GG
CC
CC
MM
GG
```
[Answer]
# PHP, 85 Bytes
```
for($m=$argv;$i++<4;)for($c=$m[_2342[$i]]*$m[1];$c;)echo$c--%$m[1]?"":"\n",_GCMG[$i];
```
or
```
for($m=$argv;$i++<4;)for($c=$m[_2342[$i]];$c--;)echo"\n".str_pad("",$m[1],_GCMG[$i]);
```
[Online Versions](http://sandbox.onlinephpfunctions.com/code/cff5f84dd5595e66e64ba0052ad5d010c97ba969)
# PHP, 96 Bytes
```
<?[$n,$w,$G,$C,$M]=$argv;for(;$i<4;$i++)for($t=${"$n[$i]"};$t--;)echo"\n".str_pad("",$w,$n[$i]);
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/a8b9676c4d0c543ce552a1197933205118616e22)
Expanded
```
[$n,$w,$G,$C,$M]=$argv; # $argv[0] must contain a file beginning with "GCMG"
for(;$i<4;$i++) # Take the first 4 values of the filename
for($t=${"$n[$i]"};$t--;) # How many rows should be printed
echo"\n".str_pad("",$w,$n[$i]); # print $w times the actual letter
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~67~~57 bytes
(Edit: now that matrices are allowed, no need to newline-join it.)
```
def s(w,g,c,m):g=['G'*w]*g;print g+['C'*w]*c+['M'*w]*m+g
```
[Answer]
# C# (150 bytes)
```
void S(int w,int g,int c,int m){P(w,g,'G');P(w,c,'C');P(w,m,'M');P(w,g,'G');}void P(int w,int i,char c){while(i-->0)Console.Write("\n".PadLeft(w,c));}
```
Ungolfed:
```
void SMores(int w, int g, int c, int m)
{
Print(w,g,'G');
Print(w,c,'C');
Print(w,m,'M');
Print(w,g,'G');
}
void Print(int w, int i, char c)
{
while(i-->0)
Console.Write("\n".PadLeft(w,c));
}
```
[Answer]
# C, 90 bytes (based on [Steadybox's answer](https://codegolf.stackexchange.com/a/116782/30000))
Renamed the variables and exploited the stringification preprocessor operator to cut down on the macro parameters. I hope posting this idea as its own answer is fine :)
```
#define F(x)for(i=x;i--;puts(""))for(j=w;j--;)printf(#x);
i,j;f(w,G,C,M){F(G)F(C)F(M)F(G)}
```
[TIO link](https://tio.run/nexus/c-gcc#HYzBCoMwEETv@Yqgl13YQG2PwZMQT36EtG7Z0KailgTEX2@aduDB8Bgm17eJJUzaQUJ@LSBtsmKMnd/bClWFf@nbaH2ROC8SNoY6oVVC3jJE6qmjAXcHPTroCgP@@pHLVD9HCYBqV7qEoTmRvpA@k27Kw5E/V36M9zWb@AU)
[Answer]
# Java, 138 bytes
```
String s(int w,int g,int c,int m){String b="";int i=-g-c,j;for(;i++<g+m;){for(j=0;j++<w;)b+=i<=-c|i>m?'G':i<=0?'C':'M';b+="\n";}return b;}
```
[Try it online!](https://tio.run/nexus/java-openjdk#NU6xboMwFNzzFU8stoVBJN3y4kZRhk6dMiYdwKHoodhE2ARVlG8nhqY33NPdvZNO33Ln4ADDdPIt2QocJ@uhlzNXC@uFjRheH4WKIpwtUkmVaFnjd9NypDjeVbFBMcyyVhnWwelRFLGinUr0L72bPftg26CyPTuyLftkGNLoYiMc29J3rYUCxwkC7l1xIw3O5z6cR0NXMDlZ/jfi/AW5gGEFL5x@nC9N2nQ@vYfcc1v2cOAidXydSXiTsJGwFgL/C0tzXI3TEw "Java (OpenJDK 8) – TIO Nexus")
Explanation:
```
String s(int w, int g, int c, int m) {
String b = "";
int i = -g - c, j; // i is the layer
for (; i++ < g + m;) { // Repeat (G+C+M+G) times, starting from -g-c to m+g
//Layer 0 is the last chocolate layer
for (j = 0; j++ < w;) { // Repeat W times
b +=
i <= -c | i > m ? 'G': //If before the chocolate or after the marshmellow, output a G
i <= 0 ? 'C' : // Else if equal or before last chocolate layer output C
'M'; //Otherwise output an M
}
b += "\n";
}
return b;
}
```
[Answer]
# Swift, ~~138~~ ~~137~~ ~~134~~ 130 bytes
Saved 7 bytes thanks to ***@Kevin***
```
let f=String.init(repeating:count:)
let r={w,g,c,m in f(f("G",w)+"\n",g)+f(f("C",w)+"\n",c)+f(f("M",w)+"\n",m)+f(f("G",w)+"\n",g)}
```
Two functions that return the expected value: `f` is a helper function and `r` is the actual lamdba-like function that generates the output. ***Usage:*** `print(r(10,3,2,1))`
**[Check it out!](http://swift.sandbox.bluemix.net/#/repl/58f5b479da4eb37edb42a2ac)**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ṁ4“GCMG”x×Y
```
[Try it online!](https://tio.run/nexus/jelly#@/9wZ6PJo4Y57s6@7o8a5lYcnh75//9/Yx0FIx0Fw/@GBgA "Jelly – TIO Nexus")
### How it works
```
ṁ4“GCMG”x×Y Main link. Left argument: g, c, m. Right argument: w
ṁ4 Mold 4; repeat g, c, m until length 4 is reached. Yields [g, c, m, g].
“GCMG”x Repeat 'G' g times, then 'C' c times, then 'M' m times, and finally
'G' g times. This yields a string.
× Multiply each character w times. This is essentially a bug, but
Jelly's × behaves like Python's * (and vectorizes), so it can be
abused for character repetition.
Y Join, separating by linefeeds.
```
[Answer]
# JS (ES6), 111 bytes
```
n=`
`,G="G",C="C",M="M",r=(s,t)=>s.repeat(t),(w,g,c,m)=>r(r(G,w)+n,g)+r(r(C,w)+n,c)+r(r(M,w)+n,m)+r(r(G,w)+n,g)
```
[Answer]
# [Convex](https://github.com/GamrCorps/Convex), 20 bytes
```
"GCM"f*]z{~N+*}%(_@@
```
[Try it online!](https://tio.run/nexus/convex#@6/k7uyrlKYVW1Vd56etVauqEe/g8P///2hjBSMFw9j/hgYA "Convex – TIO Nexus")
[Answer]
# JavaScript (ES6), 91 bytes
Includes trailing newline.
```
f=
(w,g,c,m)=>(b=(`G`[r=`repeat`](w)+`
`)[r](g))+(`C`[r](w)+`
`)[r](c)+(`M`[r](w)+`
`)[r](m)+b
console.log(f(10,3,2,1))
```
[Answer]
# JS (ES6), 87 bytes
```
x=(w,g,c,m)=>(f=>f`Gg`+f`Cc`+f`Mm`+f`Gg`)(([[x,y]])=>(x.repeat(w)+`
`).repeat(eval(y)))
```
`x` acts as a standalone lambda function. The result has a trailing newline.
Try in a snippet:
```
x=(w,g,c,m)=>(f=>f`Gg`+f`Cc`+f`Mm`+f`Gg`)(([[x,y]])=>(x.repeat(w)+`
`).repeat(eval(y)))
function doTheThing() {
document.getElementById("target").innerText = x(
document.getElementById("width").value,
document.getElementById("graham").value,
document.getElementById("chocolate").value,
document.getElementById("marshmallow").value,
)
}
```
```
Width: <input id='width' value='10'>
Graham: <input id='graham' value='3'>
Chocolate: <input id='chocolate' value='2'>
Marshmallow: <input id='marshmallow' value='1'>
<pre id='target'></pre>
<button onclick='doTheThing()'>Do the thing</button>
```
[Answer]
# F# (148 99 bytes)
```
let s w q="GCMG"|>Seq.iteri(fun i c->for j in 1..(q|>Seq.item(i%3))do printf"%A"("".PadLeft(w,c)))
```
Usage:
```
s 10 [2;3;4]
```
Ungolfed:
```
let smores width quantities =
"GCMG"
|>Seq.iteri(fun i char ->
for j in 1..(quantities|>Seq.nth(i%3))
do printf "%A" ("".PadLeft(width,char)))
```
I'm still new to F#, so if I did anything weird or stupid, please let me know.
[Answer]
# JavaScript ES6, ~~69~~ ~~68~~ 66 bytes
Thanks @Arnauld for golfing off one byte
```
a=>b=>"GCMG".replace(/./g,(c,i)=>`${c.repeat(a)}
`.repeat(b[i%3]))
```
[Try it online!](https://tio.run/nexus/javascript-node#S7P9n2hrl2Rrp@Tu7OuupFeUWpCTmJyqoa@nn66jkayTqWlrl6BSnQySSE0s0UjUrOVKgHGSojNVjWM1Nf8n5@cV5@ek6uXkp2ukaRgaaGpEG@sY6RiB5AA)
## Explanation
Receives input in curried format `(Width)([Graham,Chocolate,Marshmallow])`
Using `.replace(/./g,...)` replaces each character in the string `GCMG` with the return value from the function `(c,i)=>`${c.repeat(a)}
`.repeat(b[i%3])`
``${c.repeat(a)}
`` creates each line of the graham cracker with a newline appended
`.repeat(b[i%3])` repeats this line the required number of times
[Answer]
# Google Sheets, 103 Bytes
Anonymous Google Sheets worksheet formula that takes input from cells `A1,B1,C1,D1` and outputs a s'more to the calling cell
```
=REPT(REPT("G",A1)&"
",B1)&REPT(REPT("C",A1)&"
",C1)&REPT(REPT("M",A1)&"
",D1)&REPT(REPT("G",A1)&"
",B1
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~32~~ 17 bytes
**Solution:**
```
{x#',/4#y#'"GCM"}
```
[Try it online!](https://tio.run/##y9bNz/7/v7pCWV1H30S5Ulldyd3ZV6k22tDAWsPY2sjaUDP2/38A "K (oK) – Try It Online")
**Example:**
```
> {x#',/4#y#'"GCM"}[10;(3;2;1)]
("GGGGGGGGGG"
"GGGGGGGGGG"
"GGGGGGGGGG"
"CCCCCCCCCC"
"CCCCCCCCCC"
"MMMMMMMMMM"
"GGGGGGGGGG"
"GGGGGGGGGG"
"GGGGGGGGGG")
```
**Explanation:**
```
{x#',/4#y#'"GCM"} / solution
{ } / lambda function with implicit parameters x and y
y#'"GCM" / take input each-both (#') number "G", "C" and "M"
4# / 4-take, ("GGG";"CC";"M") -> ("GGG";"CC";"M";"GGG")
,/ / flatten list into string, ("GGG";"CC";"M";"GGG") -> "GGGCCMGGG"
x#' / width-take each (10#"G" -> "GGGGGGGGGG" etc)
```
**Notes:**
* -15 bytes as looking through other answers it seems acceptable to take parameters as `[width;(graham;chocolate;marshmallow)]`, which means I don't have to explicitly list the parameters to the function
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~12~~ 11 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
GCMG{²└@*×P
```
[Try it here!](https://dzaima.github.io/Canvas/?u=R0NNRyV1RkY1QiVCMiV1MjUxNCV1RkYyMCV1RkYwQSVENyV1RkYzMA__,i=JTVCMyUyQzIlMkMxJTVEJTBBMTA_,v=3)
Explanation:
```
GCMG push "GCMG"
{ for each character
² push the counter. Stack: [(input2, input1), "G", 1]
└ swap two items below ToS. Stack: [(I1, I2), "G", I1, 1]
@ get the counter'th item of the input. Stack: [(I1, I2), "G", I1[1] ]
* repeat horizontally. Stack: [(I1, I2), "G" * I1[1] ]
× repeat vertically. Stack: [(I2, I1), I2 × "G" * I1[1] ]
P print that. Stack: [(I2, I1)]
```
] |
[Question]
[
When using Markup, like on the SE network, an indentation of four spaces before a line of text denotes it as part of a code block, as I hope you know. If you don't, here's an example (with `.` representing a space):
....Code
....More code
results in
```
Code
More code
```
The problem is, when you copy-paste code into an answer, you need to indent each line manually. This is especially difficult when working with ungolfed code, as it's likely already indented and can cause confusion. You can just select your code and hit `Ctrl + K`, it turns out. Hours of my life wasted for no reason aside...
So, your goal is, **given an input, return it with four spaces before each line.** In the spirit of saving time copy-pasting, you are to process the entire input as a single string (so long as your language can parse it). If your language is unable to process a character (such as newlines) in strings, you may assume it is denoted/escaped through some other method supported by the language; however, the output must output each line on its own line (so no passing something like `....foo\n....bar`).
Standard loopholes not allowed. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins. Good luck!
[Answer]
# [V](https://github.com/DJMcMayhem/V), 4 bytes
```
Î4É
```
[Try it online!](https://tio.run/nexus/v#@3@4z@Rwp8L//x6ZXAq5lVwKCnmJualcCpnFXOn5@ek5qQA "V – TIO Nexus")
(Note the trailing space)
V is encoded in Latin1, where this is encoded like so:
```
00000000: ce34 c920 .4.
```
### Explanation
```
Î " On every line
4É<space> " Prepend 4 spaces
```
---
Here's a solution that is also 4 bytes in UTF-8!
```
VG4>
VG " Select everything
> " Indent
4 " 4 times (with spaces)
```
[Answer]
# [Crayon](https://github.com/ETHproductions/crayon), 7 bytes
```
`¤q;3xq
```
[Try it online!](https://tio.run/nexus/crayon#@59waEmhtXFF4f///xOTkrlSUtMA "Crayon – TIO Nexus")
### Explanation
Crayon is a stack-based language designed for creating ASCII-art. It's still in the early stages of development, but it knows just enough to finish this challenge with a rather low byte count:
```
Implicit: input string is on the stack
`¤ Push a non-breaking space to the stack.
q; Draw this at the cursor (0,0 by default) and pop it.
3x Move three more spaces to the right.
q Draw the input string here (at 4,0).
Implicit: output the canvas, trimmed to a rectangle
```
Drawing the non-breaking space is necessary because Crayon automatically trims the output to a rectangle, so without the NBSP it would just print the original input.
[Answer]
## [Retina](https://github.com/m-ender/retina), 8 bytes
```
%`^
```
[Try it online!](https://tio.run/nexus/retina#@6@aEMelAAT//zvnp6Ry@eYXpSokA1kA "Retina – TIO Nexus")
There are four spaces on the second line. Alternative solutions use either `m`^` or `%1`` or `1%`` on the first line. All of these match the position at the beginning of each line and replace it with four spaces.
[Answer]
# Cheddar, 31 bytes
```
@.lines.map((" ":+)).asLines
```
Really simply, but I posted because it shows off the new functional operators.
`(" ":+)` is the same as `A -> " " + A`. (i.e. `+` op as a function with `" "` bound to LHS).
I don't think even needs explanation
[Answer]
# [Python](https://docs.python.org), ~~44~~ 39 bytes
Crossed out 44 is no longer 44 :)
-5 bytes thanks to ovs (avoid dequeue with a prepend)
```
lambda s:' '*4+s.replace('\n','\n ')
```
**[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQbKWuoK5lol2sV5RakJOYnKqhHpOnrgMkFIBAXfN/SWpxiYKturq6c35KKpdvflGqQjKQBRTgKijKzCvRSNMAKdHU/A8A)**
[Answer]
# JavaScript, 26 bytes
Thanks @Conor O'Brien for golfing off 8 bytes
```
x=>x.replace(/^/gm," ")
```
Replace with a regex with /g replaces all instances. m makes the regex treat each line separately for the start of the string ^.
[Try it online!](https://tio.run/nexus/javascript-node#S7P9X2FrV6FXlFqQk5icqqEfp5@eq6OkAARKmv@T8/OK83NS9XLy0zXSNJTS8vNj8pISi2LyEotT0pQ0Nf8DAA "JavaScript (Node.js) – TIO Nexus")
[Answer]
# Python 2, ~~87~~ 45 bytes
```
print' '*4+'\n '.join(input().split('\n'))
```
Input is taken as `'Line1\nLine2\nLine3...'` (Quotes necessary)
Thanks to @WheatWizard for giving me an idea that helped me golf 42 bytes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ỵṭ€⁶ẋ4¤Y
```
**[Try it online!](https://tio.run/nexus/jelly#@/9w95aHO9c@alrzqHHbw13dJoeWRP7//19dXd05PyWVyze/KFUhGcgCCgAA "Jelly – TIO Nexus")**
### How?
```
Ỵṭ€⁶ẋ4¤Y - Main link: string
Ỵ - split on newlines
¤ - nilad followed by ink(s) as a nilad:
⁶ - a space character
ẋ4 - repeated four times
ṭ€ - tack for €ach
Y - join with newlines
```
Some other 8 byte variants are:
`Ỵṭ€⁶Yµ4¡` (4 repeats of split on newlines, tack a single space);
[Answer]
# Emacs, 5 keychords, 5 bytes
```
C-x h M-4 C-x tab
```
In at least one commonly used encoding for keyboard entry, each of these keychords is a single byte: `18 68 b4 18 09`. Emacs entries tend to be very keychord-heavy, as each printable ASCII character stands for itself except as a subsequent character of a multi-character command (meaning that only keychords can be used to give actual commands).
I'm not sure how this compares to Vim (as opposed to V). But Vim is fairly commonly used on PPCG, and so I thought the other side of the editor wars deserves its time in the spotlight too.
This assumes that I/O is done via the buffer (the equivalent of the normal I/O conventions for vim), or taken from a file and output onto the screen (which comes to the same thing). If you do I/O via the region instead, which is natural for some forms of program, you can remove the leading two characters, for a score of 3 bytes; however, I don't think that complies with PPCG rules.
## Explanation
```
C-x h M-4 C-x tab
C-x h Specify the entire buffer as the region
M-4 Give the argument 4 to the next command that runs
C-x tab Increase the indentation level of each line by a constant
```
The last builtin used here is, of course, incredibly useful for this challenge; the rest is just structure.
[Answer]
# PowerShell, ~~29~~ 28 Bytes
```
"$args"-split"
"|%{" "*4+$_}
```
-1 Thanks to fergusq, using an actual newline instead of the `n
takes the `"$args"` input as a string (cast using "s) and `-split`s it on a newline, then loops (`%{}`) through it, appending four spaces (`" "*4`) and the line (`$_`) then outputs it implicitly.
[Answer]
# Pyth, 10 Bytes
```
jm+*4\ d.z
```
[Try it!](https://pyth.herokuapp.com/?code=jm%2B%2a4%5C+d.z&input=a%0Ab%0Ac&debug=0)
If input as a list of lines would be allowed, I could do it in 7 bytes:
```
jm+*4\
```
[Try that](https://pyth.herokuapp.com/?code=jm%2B%2a4%5C+d.z&input=a%0Ab%0Ac&debug=0)
### longer solutions:
12 Bytes:
```
+*4d:Eb+b*4d
```
12 Bytes:
```
+*4dj+b*4d.z
```
13 Bytes:
```
t:E"^|
"+b*4d
```
[Answer]
# [Röda](https://github.com/fergusq/roda), 21 bytes
```
{(_/"
")|[` $_
`]}
```
[Try it online!](https://tio.run/nexus/roda#y03MzKvm4szMKygtUbCyVYjOTEnNK8ksqdTQjFVTislT4uIsKC3O0AAr0FSo@V@tEa@vxKWkWROdoAAEKvFcCbG1/2v/O@enpHL55helKiQDWQA "Röda – TIO Nexus")
It is an anonymous function. The input is pulled from the stream.
Explanation:
```
{
(_/"\n") | /* Splits the input at newlines */
[" ".._.."\n"] /* For each line, prints four spaces before the line */
}
```
[Answer]
# [Perl 5](https://www.perl.org/), 11+1 = 12 bytes
11 bytes of code + `-p` flag.
```
s/^/ /mg
```
[Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAtMPhfrB@nrwAE@rnp//8756ekcvnmF6UqJANZAA "Perl 5 – TIO Nexus")
For once, explanations will be short: The regex replaces each beginning of line (`^` combined with `/m` modifier) by four spaces - the end.
[Answer]
# [Perl 6](https://perl6.org), 11 bytes
```
*.indent(4)
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9J1c3MS0nNK0ktUrD9r6UH4WiYaP635iooyswrUUBRo1GcU1pUoPnfGSjI5ZtflAqWBgA "Perl 6 – TIO Nexus")
## Expanded:
```
*\ # declare a WhateverCode lambda/closure (this is the parameter)
.indent( # call the `indent` method on the argument
4 # with the number 4
)
```
[Answer]
# [sed](https://www.gnu.org/software/sed/), 16 10 9 bytes
```
s/^/ /
```
[Try it online!](https://tio.run/nexus/sed#RY7LCsIwEEXXyVdcYqAKSrFr8yWiUpqpGeyLNNCF@u11WhFnMwz3cWYe82sOmXyep8ANIVLpcYhouCPte602uFMCe9Sxb1GLp9BqXTf2zm6pCj3sYscL5fRA9hwidwn2@M52S55riY9oy1SFPb7iWq9EOcNYTtRKmYFzcv26DS5apUCdVuoPWdjyl9BO4i3MBw "sed – TIO Nexus")
**Edits**
Reduced solution size from 16 to 10 bytes thanks to **Kritixi Lithos**.
-1 byte thanks to **seshoumara**.
[Answer]
# Java 7, 58 bytes
```
String c(String s){return" "+s.replace("\n","\n ");}
```
**Explanation:**
[Try it here.](https://tio.run/nexus/java-openjdk#lY8xCsMwDEX3nEJ4smnJBTJ2zpSx7uA6pjU4crCVQgk@e6oUjxlaIYTQ/zz0bTA5Q782AJkMeQvbQMnjA6ysi1FrcrQkFMAlTqZNbg7GOik0ijOP7111ZQOYl3tgSGW9oh9hMh4r63rbac3uH96Z3NTGhdqZJZJWikscncY@JgeWV6FUd@gNKP9Wdr6tYTX@8qbGA7oWQ5wcPdmlObLGwl0fLU3ZPg)
* Append with four leading spaces
* Replace every new-line for a new-line + four spaces
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~109~~ 103 bytes
-6 thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)
Includes +1 for `-c`
```
((()()()()()){}){(({}<>)[()()((()()()()){})]<(((((({}){}){}))))>){(<{}{}{}{}{}>)}{}<>}<>{({}<>)<>}<>{}
```
[Try it online!](https://tio.run/nexus/brain-flak#@6@hoaEJg5rVtZrVGhrVtTZ2mjYaUIAsB0ZAYBeNqisWqM2muhYG7TRrQWYAUTXUMDC79v9/5/yUVC7f/KJUhWQQS0EBJKBQXJJYVJKZl65QnlmSoVBckJicWvxfNxkA "Brain-Flak – TIO Nexus")
```
((()()()()()){}) # Add a newline to the beginning
# This is needed to get spaces infront of the first line)
{ # For every character (call it C)
(({}<>) # Move C to the other stack
[()()((()()()()){})] # Push 8 and subtract 10 (\n) from C
<(((((({}){}){}))))>) # Push 4 spaces using the 8 from earlier
) # Push C - 10
{(< # If C - 10 != 0...
{}{}{}{}{} # Pop the 4 spaces that we added
>)}{} # End if
<> # Switch stacks to get the next character
} # End while
<>{({}<>)<>}<> # Reverse the stack (back to the original order)
{} # Pop the newline that we added
```
[Answer]
# [J-uby](http://github.com/cyoce/J-uby), ~~17~~ 16 Bytes
```
~:gsub&' '*4&/^/
```
### Explanation
```
~:gsub # :gsub with reversed arguments:
# (f)[regex,sub,str] == str.gsub(regex, sub)
&' '*4 # replace with four spaces
&/^/ # match the start of each line
```
This directly translates to (in Ruby):
```
->s{s.gsub(/^/,' '*4)}
```
[Answer]
# PHP, 43 Bytes
```
<?=" ".strtr($_GET[0],["\n"=>"\n "]);
```
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 13 bytes
```
'^'4' '*mrepl
```
[Try it online!](https://tio.run/nexus/stacked#VZBBSwMxEIXv@ytiLtkU2ZO3PS2FIigI3YIIRUh3pzUwm6zJRFukv32NabTru@Tx@MibGaGH0Tpia3gP4MlXi7rIUXvyBMMsWAXTkbZmDjU7H1yvSUNKx7BD3bEOlffsHhDts3XYP2oDzThuYgP7KhhjmfOkKD4qfcIGpQ0r5YWIygO4y2jLWGwRWnAfuoNSVtaUGYz6mz@bVcC9RoQ@I7Lq7Qy/rrLPbuXssDmN0JLT5jBDf8SPVacQyy1PO92ytNXNlsuaX0lZfWp6K/mRy9/WOhsHFJz5d611ipa2j5WKgn96aF4Sfi7OYhKv4k4wsRgcjDjZQNM3 "Stacked – TIO Nexus")
## Explanation
```
'^'4' '*mrepl (* input: top of stack *)
mrepl perform multiline regex replacements,
'^' replacing /^/ with
4' '* four spaces
```
[Answer]
# Octave, 17 bytes
```
@(s)[" "';s']'
```
[Try it online!](https://tio.run/nexus/octave#@@@gUawZraQABErq1sXqser/02wT84qtuYpto/X09LjUPTLVudQVKvNLi0C0Ql5ibiqIkVkMJNPz89NzUtVjrbnSgMb8BwA "Octave – TIO Nexus")
[Answer]
# PHP, 16
```
echo" $argn";
```
run with `php -R <code>`. `-R` runs the given code for every input line and `$argn` is fed the current input line. So this simply prints each line with additional four spaces in front of it.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 3 bytes (Non-competing)
```
4>G
```
This is answer uses a feature that I have been planning on adding for a while, but just got around to adding today. That makes this answer non-competing and invalid for winning. But it's still cool to show off such a useful/competitive feature!
[Try it online!](https://tio.run/nexus/v#DcexDYAwDATAPlP8ENRpWYAFkGLgpeBEsZnfuLuLre4Rx0MDrQCngtpEXVoOeL/u7FTJmS/qXa6x4GKexhxcc5jYDw "V – TIO Nexus")
Explanation:
```
4> " Add an indent of 4 to...
G " Every line from the current line (0 by default) to the end of the buffer
```
[Answer]
# Vim, 6 keystrokes
```
<Ctrl-V>G4I <Esc>
```
Assumes that the cursor is on the beginning of the file, as if you opened the file from from the command line via `vim filename`.
```
<Ctrl-V> " Enter visual block move (enables rectangular selection)
G " Move to bottom line (selecting the entire first column)
4 " Repeat the following action 4 times
I " Insert at start of (each selected) line
" [input a space]
<Esc> " Exit insert mode
```
With a vim configured to use 4 spaces for indentation it would be 2 keystrokes: `>G`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 6 bytes
*Saved 1 byte thanks to @ETHproductions*
```
miS²²R
```
[Try it online!](https://tio.run/nexus/japt#@5@bGXxo06FNQf//KyVyKSgkcSVzKaQoKACZCgqpSly6QQA)
### Explanation:
```
miS²²R
m // At each char in the input:
iS²² // Prepend " " repeated 4 times
R // Rejoin with newlines
```
[Answer]
# [UberGenes](https://esolangs.org/wiki/UberGenes), 62 bytes
I had to enter this challenge with UberGenes, as a very similar program (that only inserted one space) was one of the first programs I ever wrote in the language, and it seemed like it would be easy to modify for this purpose.
```
=aA=p9=z4=cI=AC+a1-z1:pz=Ao:CA:Ii =b5+b5-bA+a1=d3*d7:db=i0
```
How it works:
```
=aA Set a to 61
(Begin main loop)
=p9 Set p to 9
=z4 z counts spaces
=cI Set c to 61
(Jumping to p jumps here)
=AC Put the space at position 61
at position a.
+a1-z1 Move a right and decrement z
:pz Jump to p if z is nonzero
(Jumping to d jumps here)
=Ao Read a character to position a.
:CA Jump to position 32+3 if input
was nonzero.
:Ii Otherwise, jump to position 61,
causing the entire string
that begins there to be
printed before halting.
(This is position 32+3=35)
=b5+b5 Set b to 10 (newline).
-bA Subtract the input character to
compare it with newline.
+a1 Move a right.
=d3*d7 Set d to 21
:db Jump to d if not newline.
=i0 Jump back to begin main loop.
(The 3 spaces at the end position a space character at position 61 so that, after =cI,
C refers to the space character--it will also be the first space printed.)
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 11 bytes
*Thanks to [@Challenger5](https://codegolf.stackexchange.com/users/61384/challenger5) for a correction*
```
qN/{S4*\N}%
```
[**Try it online!**](https://tio.run/nexus/cjam#@1/op18dbKIV41er@v@/c35KKpeCgmdeSmpeSWqKQjKI75tflApmAQA "CJam – TIO Nexus")
### Explanation
```
q e# Read whole input as a string with newlines
N/ e# Split at newlines, keeping empty pieces. Gives an array of strings
{ }% e# Map this function over the array of strings
e# The current string is automatically pushed
S4* e# Push a string of four spaces
\ e# Swap. Moves the original string after the four spaces
N e# Push a newline
e# Implicity display stack contents
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 16 bytes
```
9uc;§s⌠' 4*+⌡M@j
```
[Try it online!](https://tio.run/nexus/actually#@29Zmmx9aHnxo54F6gomWtqPehb6OmT9/5@Wn8@VlFgExFUA "Actually – TIO Nexus")
Explanation:
```
9uc;§s⌠' 4*+⌡M@j
9uc; push two newlines
§s raw input, split on newlines
⌠' 4*+⌡M for each line:
' 4*+ prepend 4 spaces
@j join with newlines
```
[Answer]
# C, ~~66~~ 65 bytes
```
p(){printf(" ");}f(char*s){for(p();*s;)putchar(*s++)-10||p();}
```
[Try it online!](https://tio.run/nexus/c-gcc#@1@goVldUJSZV5KmoaQABEqa1rVpGskZiUVaxZrVaflFGkAV1lrF1poFpSUgYQ2tYm1tTV1Dg5oakEztf6BehdzEzDwNTa5qLpARQJOc81NSY/J884tSFZJhzGIIG2gBV@1/AA)
[Answer]
# Ruby, ~~22~~ 21 Bytes
1 Byte saved thanks to [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork)
```
->s{s.gsub /^/,' '*4}
```
Takes `s`, replaces all occurences of `/^/` (start of line) with four spaces.
] |
[Question]
[
## The Challenge
Display the alphabet from a given letter read from console input. If the letter is uppercase, you have to display the alphabet uppercased. The alphabet printed must end in the precedent letter of the one inserted. If an additiontal parameter is added to the input (a simple dot `.`) the alphabet should be printed one letter in each line. Otherwise, the alphabet should be printed in the same line, separed by a simple space. If wrong input is send to the program it will not print anything.
Inputs examples:
Input:
```
c
```
Program's ouput:
```
d e f g h i j k l m n o p q r s t u v w x y z a b
```
Input
```
H.
```
Program's ouput:
```
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
A
B
C
D
E
F
G
```
[Answer]
## GolfScript ~~48 75 73 70 67 66 63 57~~ 53
```
(91,65>.+.{32+}%+.@?>(;25<''+.,1>*\['''.']?[' 'n 0]=*
```
Online demos:
* [Test case 1 ('c')](http://golfscript.apphb.com/?c=OydjJwooOTEsNjU%2BLisuezMyK30lKy5APz4oOzI1PCcnKy4sMT4qXFsnJycuJ10%2FWycgJ24gMF09Kg%3D%3D&run=true)
* [Test case 2 ('H.')](http://golfscript.apphb.com/?c=OydILicKKDkxLDY1Pi4rLnszMit9JSsuQD8%2BKDsyNTwnJysuLDE%2BKlxbJycnLiddP1snICduIDBdPSo%3D&run=true)
* [Test case 3 (invalid input)](http://golfscript.apphb.com/?c=OydAJwooOTEsNjU%2BLisuezMyK30lKy5APz4oOzI1PCcnKy4sMT4qXFsnJycuJ10%2FWycgJ24gMF09Kg%3D%3D&run=true)
### Update:
Now the last rule is also implemented. Thanks to [Ventero](https://codegolf.stackexchange.com/users/84/ventero) for pointing out the issue.
### Update:
I rewrote the code from scratch and found new ways to shorten it even further.
### History of modifications:
```
.,3<\(:x;:§['''.']?)and{91,65>.+.{32+}%+.x?).{>25<''+{§n' 'if}%}{;;}if}''if
.,3<\(:x;:§['''.']?)*{91,65>.+.{32+}%+.x?).{>25<''+{§n' 'if}%}{;;}if}''if
.,3<\(:x;:§['''.']?)*{91,65>.+.{32+}%+.x?).!!@@>25<''+{§n' 'if}%*}''if
.,3<\(:x;:§['''.']?)*!!91,65>.+.{32+}%+.x?).!!@@>25<''+{§n' 'if}%**
.,3<\(:x;:§['''.']?)*91,65>.+.{32+}%+.x?).@@>25<''+{§n' 'if}%@@*!!*
.(@,3<@:§['''.']?)*91,65>.+.{32+}%+@1$?).@@>25<''+{§n' 'if}%@@*!!*
.(@,3<@:§['''.']?)*91,65>.+.{32+}%+@1$?):x>25<''+{§n' 'if}%\x*!!*
.(@,3<@:§['''.']?)*91,65>.+.{32+}%+@1$?):x>25<''+§n' 'if*\x*!!*
(\:§['''.']?)91,65>.+.{32+}%+@1$?):x>25<''+§n' 'if*\x*!!*
(91,65>.+.{32+}%+.@?>(;25<''+.,1>*\['''.']?[' 'n 0]=*
```
[Answer]
## C, 135 129 128 chars
Damn, so many different magic numbers, but no way to get rid of them.
Has to be run with the input as program parameter. Now follows the "wrong input" requirement.
```
c;main(a,b)char**b;{if(a==2&&isalpha(**++b)&&!(c=1[*b])||c==46&&!2[*b])for(;++a<28;)printf("%c%c",**b-=**b+6&31?-1:25,c?10:32);}
```
Explanation:
```
c; // Variable that will be used later
main(a,b)char**b;{ // There's one parameter => a = 2, b[1] = the parameter
// Wrong input checks: We want...
if(
a==2 && // 1 parameter and ...
isalpha(**++b) // lower- or uppercase letter as parameter,
// increase b so we can access it better
&& // and ...
!(c=1[*b]) || // either no further character,
// save the character in c, or...
(c==46&&!2[*b]) // a dot as next character and no further characters
) // if check succeeded, execute the for loop, else do nothing
for(;++a<28;) // This will loop 26 times (2..27)
printf("%c%c", // Print two characters
// First character to print:
**b // We'll print the first character of the parameter,
-= // but decrement it before printing
**b+6&31? // if the last five bits (31 = 11111b) are not 26 (6 == -26 mod 32)
-1 // decrement it by -1 (aka increment it)
:25, // else (char=z/Z) decrement by 25, so we start over at a/A
// Second character to print:
c? // c is either ASCII 0 or a dot (ASCII 46)
10 // dot -> print a newline
:32); // ASCII 0 -> print a space (ASCII 32)
}
```
The `**b+6&31` part uses the fact that the ASCII codes for lowercase/uppercase character are the same if only looking at the last 5 bits and the remaining 5 bits are in range 1..26.
Version without "wrong input" requirement (82 chars):
```
main(a,b)char**b;{for(b++;++a<28;)printf("%c%c",**b-=**b+6&31?-1:25,1[*b]?10:32);}
```
[Answer]
### Ruby, 72 71 61 characters
```
gets;25.times{$><<$_=$_.succ[0]+=$1?$/:' '}if~/^[a-z](\.)?$/i
```
This ruby version uses a regular expression to verify the input. Fortunately, the Ruby string method [`succ`](http://ruby-doc.org/core-1.9.3/String.html#method-i-succ) does most of the work for us (including the wrap-around).
*Edit:* 61 characters with the help of [chron](https://codegolf.stackexchange.com/users/3856/chron) and [Ventero](https://codegolf.stackexchange.com/users/84/ventero).
[Answer]
# Ruby: ~~127~~ ~~113~~ 92 (?) characters
(I can't find the rule about the penalty score on using `-p`. Added 1 for now. If wrong, please correct me.)
```
$_=if ~/^([a-z])(\.)?$/i;s,e=$1>?Z?[?a,?z]:[?A,?Z];[*$1.succ..e,*s...$1]*($2==?.?$/:" ")end
```
Sample run:
```
bash-4.2$ ruby -pe '$_=if ~/^([a-z])(\.)?$/i;s,e=$1>?Z?[?a,?z]:[?A,?Z];[*$1.succ..e,*s...$1]*($2==?.?$/:" ")end' <<< c
d e f g h i j k l m n o p q r s t u v w x y z a b
bash-4.2$ ruby -pe '$_=if ~/^([a-z])(\.)?$/i;s,e=$1>?Z?[?a,?z]:[?A,?Z];[*$1.succ..e,*s...$1]*($2==?.?$/:" ")end' <<< H.
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
A
B
C
D
E
F
G
bash-4.2$ ruby -pe '$_=if ~/^([a-z])(\.)?$/i;s,e=$1>?Z?[?a,?z]:[?A,?Z];[*$1.succ..e,*s...$1]*($2==?.?$/:" ")end' <<< seven
```
[Answer]
# Ruby, ~~101~~ 95
```
i,d=gets.split''
[*?a..?z].join[/#{i}/i]
($'+$`).chars{|c|$><<(i>?Z?c:c.upcase)+(d==?.?$/:' ')}
```
[Try it online](http://ideone.com/v0ezQ)
[Answer]
### GolfScript, 80 72 Characters
```
.).46={;)}*25,{65+.32+}%?)\""=*!!\([{)..31&26-!26*-}25*;]n+\"."=n" "if**
```
Lots of the code is testing for valid input and the "print nothing"-option. The actual logic is 37 characters only.
[Test cases online](http://golfscript.apphb.com/?c=OydjJwouKS40Nj17Oyl9KjI1LHs2NSsuMzIrfSU%2FKVwiIj0qISFcKFt7KS4uMzEmMjYtITI2Ki19MjUqO11uK1wiLiI9biIgImlmKioKcHV0cwoKOydILicKLikuNDY9ezspfSoyNSx7NjUrLjMyK30lPylcIiI9KiEhXChbeykuLjMxJjI2LSEyNiotfTI1KjtdbitcIi4iPW4iICJpZioqCnB1dHMKCjsnQCcKLikuNDY9ezspfSoyNSx7NjUrLjMyK30lPylcIiI9KiEhXChbeykuLjMxJjI2LSEyNiotfTI1KjtdbitcIi4iPW4iICJpZioqCnB1dHMKCgoKCg%3D%3D)
[Answer]
## q/k4 66 64 63 60 58 56 + 2 penalty
penalty for global variable init, algorithm is 56 as below:
**56:**
```
if[&/x in".",l:(a;A)90>*x;1@/1_,/|_[0,l?x;l,'" \n"@#x]]
```
**58:**
```
if[&/x in".",l:(a;A)90>*x;1@/(1_,/|_[0,l?x;l]),'" \n"@#x]
```
* change from if-else to if allowed to reorganize code and get rid of ";" at the end
**60:**
```
1@/$[&/x in".",l:(a;A)90>*x;1_,/|_[0,l?x;l];" "],'" \n"@#x;
```
* eventually got rid of this redundant check
**63:**
```
1@/$[&/x in".",l:(a;A)90>*x;1_,/|_[0,l?x;l];" "],'" \n""."in x;
```
* print chars recursively instead a whole object
* still can't get off identity comparsion *x in "."* in two places... :(
* semicolon at the end is required, otherwise print function (1@) would print it's return value to stdout.... damn
**64:**
```
2@,/$[&/x in".",l:(a;A)90>*x;1_,/|_[0,l?x;l];" "],'" \n""."in x;
```
**EDIT:**
Added penalty of 2 for global initialization(x:), same if wrapping function into brackets (as slackware suggested)
not sure if changing namespace should be punished as well...then it's another 3
```
(.Q`a`A) instead of (a;A)
```
Example:
```
q)\ - switch interpreter to k4
\d .Q - change to native namespace
x:"c"
if[&/x in".",l:(a;A)90>*x;1@/1_,/|_[0,l?x;l,'" \n"@#x]]
d e f g h i j k l m n o p q r s t u v w x y z a b
x:"@"
if[&/x in".",l:(a;A)90>*x;1@/1_,/|_[0,l?x;l,'" \n"@#x]]
x:"H."
if[&/x in".",l:(a;A)90>*x;1@/1_,/|_[0,l?x;l,'" \n"@#x]]
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
A
B
C
D
E
F
G
x:...
```
[Answer]
## Perl, 131 127 117 112 106 104 102 98 96 92 91 90 93 71 66 65 64 58 characters
```
s!^([a-z])(\.?)$!print chop,$2?$/:$"for($1..az)[1..25]!ie
```
Usage:
```
perl -ne 's!^([a-z])(\.?)$!print chop,$2?$/:$"for($1..az)[1..25]!ie'
```
One character has been added to the count for the `n` option.
Largest cut was only possible because of seeing the behaviour of `++` on characters in [Jon Purdy's answer](https://codegolf.stackexchange.com/a/7049/737).
[Answer]
## Perl, 149, 167
### Update
* Added sanity check.
* Took ardnew suggestion about the separator application.
```
exit if $ARGV[0] !~ /[a-z]\.?/i; # sanity check input
($x,$d)=split //,$ARGV[0]; # split input arguments
@l=65..90; # define uc letter range
push @l,splice @l,0,ord(uc $x)-64; # rotate letter range
pop @l; # remove the argument letter
print join $d?$/:$", # print the joined list
map {ord($x)>90?lc chr:chr} @l; # map chr and lc as appropriate
```
[Answer]
## Python, 83
```
r=raw_input()
i=ord(r[0])
exec"i+=1-26*(i%%32>25);print chr(i)%s;"%","["."in r:]*26
```
[Answer]
## PHP, ~~120~~ ~~119~~ 113
```
<?$v=fgets(STDIN);$f=$c=$v[0];ctype_alpha($c++)||die;for(;$c[0]!=$f;$c=$c[0],$c++)echo$c[0],$v[1]=='.'?"\n":" ";
```
[Answer]
# Mathematica 158 159 204 199 183 167 165 162
**Code**
```
f@h_ := Most@RotateLeft[#, Position[#, h][[1, 1]]] &[FromCharacterCode /@
(65~Range~90 + 32 Boole@LowerCaseQ@h)];
g = Characters@# /. {{p_} :> Row[f@p, " "], {p_, "."} :> Column@f@p, _ -> ""} &
```
**Usage**
```
g["c"]
g["H"]
g["H."]
g["seven"]
```

[Answer]
# J 43
```
|:1j1#(25{.(u:,2#65 97+/i.26)(>:@i.}.[)])"0
```
## Examples:
```
|:1j1#(25{.(u:,2#65 97+/i.26)(>:@i.}.[)])"0 's'
```
t u v w x y z a b c d e f g h i j k l m n o p q r
```
|:1j1#(25{.(u:,2#65 97+/i.26)(>:@i.}.[)])"0 's.'
```
t
u
v
w
x
y
z
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
```
|:1j1#(25{.(u:,2#65 97+/i.26)(>:@i.}.[)])"0 '['
```
This solution evolved on the J programming forum: <http://jsoftware.com/pipermail/programming/2012-August/029072.html>
Authors: AlvordBossCerovskiCyrEllerHuiLambertMcCormickMillerQuintanaSchottSherlockTaylorTherriault
## Explanation
J phrases are executed starting on the right, passing the on-going result to the left as it gets evaluated. Since it's interactive, we can look at pieces of the solution in isolation to better understand them.
The middle part generates the upper and lower case alphabet in Unicode:
```
u:,2#65 97+/i.26
ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
```
The " u: " verb converts its numeric right argument to Unicode characters. The numeric argument is generated from the ASCII values for the upper- and lower-case characters by adding the numbers for "A" and "a" each to the values from 0 to 25 generated by "i.26":
```
65 97+/i.26
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
```
The right-hand portion,
```
((>:@i.}.[)])"0
```
looks up ( i. ) the position of the right argument ( ] ) in the left ( [ ) - which is the vector of letters above - and drops ( }. ) one more ( >: ) than that number. The ' "0 ' applies this phrase to 0-dimensional (scalar) arguments.
```
('123H999' (>:@i.}.[)])"0 'H'
999
```
The " 25 {. " phrase takes the first 25 elements of the vector on the right.
The penultimate phrase " 1j1 # " on the left replicates its right argument according the number on the left. A simple number does a simple replication:
```
2 # 'ABCD'
AABBCCDD
```
However, a complex number - indicated by the " j " between the real and imaginary portions - inserts a fill element according to the imaginary part. Here we indicate one fill element by the one to the right of the " j ".
```
2j1 # 'ABCD'
AA BB CC DD
```
As with most J primitives, the replicate verb ( # ) works on numeric arrays in an analagous fashion to how it works on character arrays. As shown here,
```
1j1 # 1 2 3
1 0 2 0 3 0
```
we see that the default numeric fill element is zero whereas for characters it is the space character.
Finally, the leftmost token " |: " transposes the result of the preceding verbs to its right.
Explanation provided by Devon McCormick. Thank you Devon.
[Answer]
# brainfuck, 303
```
,>,>++++++[-<-------->]<++[[-]+++++[->++++<]>++<]>++++++++++<<[->+>>>+<<<<]>>>>>>+++++++++++++++[-<++++++<<++++++>>>]<[<[->>]>[>>]<<-]<[[-]++++++++[-<++++>]]<<<[->>>+>+<<<<]>>>>>+[[-]<.<<<.>[->>>+>+<<<<]>>>[-<<<+>>>]<[->+>-<<]>[-<+>]+>[-<[-]>]<[++++[-<----->]<->]<+[->+>+<<]<[->+>-<<]>[-<+>]>>[-<<+>>]<]
```
Currently it doesn't support the `If wrong input is send to the program it will not print anything` part, and it can probably be shorter. I plan on fixing it later. Right now my brain is too \*\*\*\*ed to continue.
[Answer]
## C, 110
Sometimes prints "spaces" between letters, sometimes not.
```
i,j;main(int c,char*l){gets(l);l[1]&=10;j=*l%32;c=*l&~31;for(i=j;i<j+25;i++){l[0]=c+i%26+1;printf("%2s",l);}}
```
Slighly more readable:
```
i,j;
main(int c,char*l)
{
gets(l);
l[1]&=10; // makes . to line feed and some other chars to "start of text"
// which looks like space in some cases
// (the byte can become either 0, 2, 8 or 10)
j=*l%32; // 0b 000c cccc, these five bits code which letter was chosen
c=*l&~31; // 0b ccc0 0000, these three bits code upper/lowercase
// 0b ccc0 0000 + (0b 000c cccc + [0..24])%26 + 1
for(i=j;i<j+25;i++){l[0]=c+i%26+1;printf("%2s",l);}
}
```
Runs:
```
$ ./a.out
G
H I J K L M N O P Q R S T U V W X Y Z A B C D E F
$ ./a.out
p.
q
r
s
t
u
v
w
x
y
z
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
```
[Answer]
# JavaScript, 137
Unfortunately a bit verbose (`String.fromCharCode` and `charCodeAt`).
```
for(x=b=(n=prompt(m={122:97,90:65})).charCodeAt(r='');/^[a-z]\.?$/i.test(n)&&(x=m[x]||x+1)!=b;)r+=String.fromCharCode(x)+(n[1]?"\n":" ");
```
[Answer]
# Perl, ~~77~~ ~~76~~ ~~70~~ 68
```
chomp(($a,$b)=split//,<>);$"=$/if$b;map{++$a=~/(.)$/}1..25;print"@a"
```
Edits:
1. Saved a character using regex instead of `substr`.
2. Saved 6 characters using `map` instead of `for`.
3. Saved 2 characters by omitting final newline.
[Answer]
## R, 219
Ugly, long... still works.
```
f=function(l){if(!nchar(l)%in%c(1,2))invisible()else{s=ifelse(nchar(l)==1," ","\n");l=substr(l,1,1);v=letters;if(l%in%v){}else v=LETTERS;l=grep(l,v);if(l==26)cat(v[1:25],sep=s)else cat(c(v[l+1:(26-l)],v[1:l-1]),sep=s)}}
```
Usage:
```
f("a")
f("c.")
f("H")
f("z")
f("Z.")
f("seven")
```
[Answer]
## C, 146 chars *(terrible)*
```
main(){char b[100];gets(b);for(char a=b[0],c=a,d=a&223,e=b[1];++c!=a&64<d&d<91&(!e|e==46&!b[2]);(c&31)>26?(c&=96):(putchar(c),putchar(e?10:32)));}
```
I'm not very experienced in C, which probably shows... >.< I had a feeling that chars being integers would be helpful, but it didn't actually seem to make as big of an impact as I hoped... I'll leave my attempt here though, feel free to suggest improvements.
Unminified version:
```
main() {
char b[999]; // assume that the line will fit in 999 chars...
gets(b);
// a is the char we start on, c is the char that we iterate,
// d is toUppercase(a), e is just an alias for the second char.
for (char a = b[0], c = a, d = a&223, e=b[1];
// increment c, make sure that we haven't reached a yet.
// also check the other conditions (first char is letter, second char
// is either '.' or NULL, third char is NULL if second char was '.').
++c != a & 64 < d & d < 91 & (!e | e == 46 & !b[2]);
(c&31) > 26 // check if we need to wrap around
? (c &= 96) // if so, wrap
: (putchar(c), putchar(e?10:32)) // otherwise, print char & separator
);
}
```
[Answer]
## VBA 225
Formatted to run from the immediate window:
```
s=InputBox(""):n=Asc(Left(s,1)):l=Len(s):p=IIf(l<3,IIf(l=2,IIf(Right(s,1)=".",vbCr,"")," "),""):c=IIf(n>64 And n<91,65,IIf(n>96 And n<123,97,99)):o=n-c+1:If o>0 And p<>"" Then For i=o To o+24:x=x & Chr(i Mod 26+c) & p:Next:?x
```
Broken down into individual lines (needs to be surrounded by `Sub` block and needs a different `print` method to work in a module, thus making the code longer):
```
s=InputBox("")
n=Asc(Left(s,1))
l=Len(s)
p=IIf(l<3,IIf(l=2,IIf(Right(s,1)=".",vbCr,"")," "),"")
c=IIf(n>64 And n<91,65,IIf(n>96 And n<123,97,99))
o=n-c+1
If o>0 And p<>"" Then
For i=o To o+24
x=x & Chr(i Mod 26+c) & p
Next
End If 'Not needed when completed in single line format
MsgBox x
```
[Answer]
# Java 8, 127 bytes
```
a->{String r="",d=a.length>1?"\n":" ";char c=a[0],C=c;for(;++c<(c<97?91:123);r+=c+d);for(c=C<97?64:'`';++c<C;r+=c+d);return r;}
```
**Explanation:**
[Try it online.](https://tio.run/##dY9Bb8IwDIXv/AorFxIVqnWbNtEQ0NTLLuOyY1dpnhugrKQoTZEQ6m/v0lLttEn2wX7P1vcOeMZ5ddLmkH93VGJdwxsW5joBKIzTdoukYdOPAO/OFmYHxGmPNs0AhfT71rev2qErCDZgQEGH89V1tFvF2CxXGJba7Nx@Fa3Zh2ExAyb7P0AK07tsliiS28pyGQS05LRcPK8XURzdPwhpA0VBLgaZVNJLT4/x9HM6eJNf3WrXWANWtp28QZ2ar9JDjWznqsjh6NPxG1qaoRiTXWqnj2HVuPDkFVcabkLijFjoqsRTvliLFy7EkPh//2v450E7absf)
```
a->{ // Method with character-array parameter and String return-type
String r="", // Result-String, starting empty
d=a.length>1? // If the length of the input is larger than 1
"\n" // Set the delimiter to a new-line
: // Else:
" "; // Set the delimiter to a space
char c=a[0], // Get the input letter
C=c; // And create a copy of it
for(;++c<(c<97?91:123); // Loop from this letter + 1 to (and including) 'Z'/'z'
r+=c+d); // And append the result with a letter + the delimiter
for(c=C<97?64:'`';++c<C; // Loop again from 'A'/'a' to (and excluding) the input-letter
r+=c+d); // And append the result with a letter + the delimiter
return r;} // Return the result
```
[Answer]
## **Mumps, 91, 86, 82,79,76**
```
r t i t?1A.1"." s a=$A(t),p=a>90*32+65 f i=1:1:25 w *(a+i-p#26+p) w:t["." !
```
Not such a modern language ;) I'm sure there's a bit of optimization space left..
Explanation:
```
r t
```
read input
```
i t?1A.1"."
```
check if t matches the required input
```
s a=$A(t),p=a>90*32+65 f i=1:1:25 { w *(a+i-p#26+p) w:t["." !}
```
basic for loop through the alphabet. Note that mumps is strictly evaluating left to right. True=1, so you get 65 or 97 as a result for p, # is the modulo operator
tests:
```
USER>d ^golf
d.e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
a
b
c
USER>d ^golf
tuvwxyzabcdefghijklmnopqrs
USER>d ^golf
h.i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
a
b
c
d
e
f
g
USER>d ^golf
hallo
USER>
```
(you'll need a mumps runtime env, ie Caché to run this this)
edit: bold heading
edit: had a wrong solution, fixed now. Thanks to rtfs and Averroees for pointing this out
[Answer]
**JavaScript: 141**
```
c="",b=c[0].charCodeAt()<91,a="abcdefghijklmnopqrstuvwxyz",b&&(a=a.toUpperCase()),a=a.split(c[0]),a=a[1]+a[0],a=c[1]?a.split("").join("\n"):a
```
Commented version:
```
c="", //write input here (examples "a", "B", "c.", "D.")
b=c[0].charCodeAt()<91, //true for upperC, false for lowerC
a="abcdefghijklmnopqrstuvwxyz", //the abc
b&&(a=a.toUpperCase()), //if upper, turn main string to upperC
a=a.split(c[0]), //split by the first char of input
a=a[1]+a[0], //swap the two parts
a=c[1]?a.split("").join("\n"):a //if input second char, add breaklines in between
//the output is inside 'a'
```
[jsFiddle DEMO](http://jsfiddle.net/mdvJg/1/)
[Answer]
Here is my first attempt at it with APL.
```
⍞{1 1≡(2⌈⍴⍺)⍴⍺∊'.',⍵:⊃(~=/2⍴⍺)⌷(,X,' ')(X←25 1⍴1↓(X⍳⊃⍺)⌽X←(⎕A∊⍨⊃⍺)⌷2 26⍴⍵)}6↓26⌽⎕UCS 65+⍳58
```
if I can use a single global variable `A←2 26⍴6↓26⌽⎕UCS 65+⍳58` then I can shorten the above down to the following:
```
{1 1≡(2⌈⍴⍵)⍴⍵∊'.',,A:⊃(~=/2⍴⍵)⌷(,X,' ')(X←25 1⍴1↓(X⍳⊃⍵)⌽X←(⎕A∊⍨⊃⍵)⌷A)}⍞
```
[Answer]
C++11
```
#include <iostream>
#include <vector>
#include <cstdio>
int main(int argc, const char * argv[])
{
std::vector<char> list1,list2;
for( char c = 'a'; c <='z'; c++ )
{
list1.push_back( c );
list2.push_back( toupper( c ) );
}
char c = getchar();
auto f = [ c ]( std::vector<char> list )
{
auto i = std::find( list.begin(), list.end(), c );
if( i == list.end() )
return;
auto c = i;
for( ;; )
{
c++;
if( c == list.end() ) c = list.begin();
if( c == i )break;
std::cout<<*c<<"\n";
}
};
f( list1 );f(list2);
return 0;
}
```
[Answer]
C (111)
```
main(int i, char**c){if(isalpha(*c[1]))for(i=0;i<25;i++) printf("%c",isalpha((*c[1])+1)?++*c[1]:(*c[1]-=25));}
```
---
## dissection
```
if(isalpha(*c[1])) // start with char-check.
for(i=0;i<25;i++) // we need 25 values, excluding input char. reusing i.
printf("%c", // print char. ofcourse.
isalpha((*c[1])+1) ? ++*c[1] : (*c[1]-=25));
//check if we are past z/Z and fall back to a/A.
//make that available to print.
```
---
Works]$ ./test 5
Works]$ ./test W
XYZABCDEFGHIJKLMNOPQRSTUV
Works]$ ./test M NOPQRSTUVWXYZABCDEFGHIJKL
Works]$ ./test g hijklmnopqrstuvwxyzabcdef
Works]$ ./test [
Works]$ ./test a bcdefghijklmnopqrstuvwxyz
Works]$ ./test Z
ABCDEFGHIJKLMNOPQRSTUVWXY
---
Thank you for some food for thought.
[Answer]
## Perl, 226 characters
```
die "Invalid input " if $ARGV[0] !~ /[a-z]\.?/i;
@listA=(a...z);
$index=ord(lc(substr($ARGV[0],0,1)))-97;
print join(substr($ARGV[0],1) ? "\n" : " ",map{$ARGV[0] =~ /[A-Z]/?uc $_:$_}(@listA[$index+1...25],@listA[0...$index]));
```
[Answer]
**C# 170**
```
using System.Linq;namespace N{class P{static void Main(string[]a){foreach(char e in"abcdefghijklmnopqrstuvwxyz".ToCharArray().Where(o =>o>'c'))System.Console.Write(e);}}}
```
Uncompressed
```
using System.Linq;
namespace N {
class P {
static void Main(string[]a){
foreach (char e in "abcdefghijklmnopqrstuvwxyz".ToCharArray().Where(o => o > 'c'))
System.Console.Write(e);
}
}
}
```
[Answer]
# C, 117
```
main(c,s,d){d=c=getchar(),s=getchar();for(s=s<0?32:s^46?0:10;d+=d+6&31?1:-25,s&&isalpha(c)&&d^c;printf("%c%c",d,s));}
```
Credit to schnaader for the d+6&31 trick.
<http://ideone.com/ts1Gs9>
[Answer]
# Bash: 110 bytes
```
(([[ $1 =~ [a-z] ]]&&echo {a..z})||([[ $1 =~ [A-Z] ]]&&echo {A..Z}))|([ "${1:1:1}" = . ]&&sed 's/ /\n/g'||cat)
```
In terms of explanation, it's pretty straightforward, no magic tricks - this is just something that bash is intrinsically well suited for. In terms of the non-obvious bits:
* `{a..z}` is a very underused trick in bash - it expands to `a b c d...`. You can do the same to generate numerical sequences.
* Bash can do regex matching, `[[ $1 =~ [a-z] ]]` runs a regex match against the first program argument for characters from a to z. Likewise for A-Z. You need double square brackets for it though, `[` can't do it.
* `${1:1:1}` gets a substring of $1 (the first argument), one character in, one character long - that is, it returns the second character of the string, what we expect to be `.`.
* `sed 's/ /\n/g'` simple regex: searches and replaces spaces with newlines. If `.` is the second character of the string, we pipe input to this, or otherwise...
* `cat` is the final trick here - if we don't want to replace spaces with newlines, we feed stdin to cat instead which simply outputs it again.
] |
[Question]
[
In this challenge you will compute numbers from a curious sequence.
Your input is a single decimal nonnegative integer. Reverse the bits in this integer and then square the number to get the required output.
When reversing the bits you must not use any leading zeroes in the input. For example:
```
26 (base 10) = 11010 (base 2) -> 01011 (base 2) = 11 -> 11*11 = 121
```
The first 25 inputs/outputs of this sequence:
```
0: 0
1: 1
2: 1
3: 9
4: 1
5: 25
6: 9
7: 49
8: 1
9: 81
10: 25
11: 169
12: 9
13: 121
14: 49
15: 225
16: 1
17: 289
18: 81
19: 625
20: 25
21: 441
22: 169
23: 841
24: 9
```
Your solution should work for arbitrarily sized integers. If your language does not have a convenient built-in method of using those, implement your answer as if it does. You are then excused if your answer breaks for large numbers. However, do not use tricks/bounds that only work for a limited domain (such as a lookup table).
---
Your score is the number of bytes of source code.
**-50% bonus if you never convert the number to/from binary.** This is not limited to builtins, if you loop over the number bit by bit (either by shifting or masking or any other method), it will also count as conversion. *I don't know whether this is actually possible, but it gives an incentive to spot a pattern in the sequence.*
Smallest score wins.
[Answer]
## Mathematica, ~~42~~ 21 bytes
*Thanks to alephalpha for halving the score.*
```
#~IntegerReverse~2^2&
```
The actual reason I did this in Mathematica was because I wanted to look at a plot... it sure looks funny:
[](https://i.stack.imgur.com/xseEC.png)
[Answer]
# [Japt](https://github.com/ETHproductions/Japt), ~~29~~ ~~28~~ ~~11~~ 7 [bytes](https://en.m.wikipedia.org/wiki/ISO/IEC_8859)
(You can save the program as a 7-byte IEC\_8859-1-encoded file, then upload it to the [interpreter](http://ethproductions.github.io/japt).)
Japt is shortened JavaScript made by [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions).
```
¢w n2 ²
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=oncgbjIgsg==&input=MjM=)
Explanation:
1. `¢` is shortcut to `Us2`, which compiles to `U.s(2)`. `U` is input (implicit), `.s(2)` called by a number, invokes `.toString(2)` (converts to binary, parses as string).
2. `w` compiles to `.w()`, which reverses the string (`.split('').reverse().join('')`).
3. `n2` works as `parseInt(<number>,2)`, i.e. converts binary to decimal.
4. `²` invokes `Math.pow(<number>,2)`, i.e. squares the number.
[Answer]
## [Minkolang 0.14](https://github.com/elendiastarman/Minkolang), 43 bytes
Thanks to Mego for inspiring this.
```
n1{d1`,2$3*&$z2zd2%-2l$Md1%-;z2%*z2:{+}2;N.
```
[Test the code here](http://play.starmaninnovations.com/minkolang/?code=n1%7Bd1%60%2C2%243*%26%24z2zd2%25-2l%24Md1%25-%3Bz2%25*z2%3A%7B%2B%7D2%3BN%2E&input=22) and [check all test cases here](http://play.starmaninnovations.com/minkolang/?code=%28ndN1%7Bd1%60%2C2%243*%26%24z2zd2%25-2l%24Md1%25-%3Bz2%25*z2%3A%7B%2B%7DnN2%3BNlO%24I%29%2E&input=0%3A%200%0A1%3A%201%0A2%3A%201%0A3%3A%209%0A4%3A%201%0A5%3A%2025%0A6%3A%209%0A7%3A%2049%0A8%3A%201%0A9%3A%2081%0A10%3A%2025%0A11%3A%20169%0A12%3A%209%0A13%3A%20121%0A14%3A%2049%0A15%3A%20225%0A16%3A%201%0A17%3A%20289%0A18%3A%2081%0A19%3A%20625%0A20%3A%2025%0A21%3A%20441%0A22%3A%20169%0A23%3A%20841%0A24%3A%209).
### Explanation
This uses this recurrence relation:
```
a(0) = 0
a(1) = 1
a(2n) = a(n)
a(2n+1) = a(n) + 2^(floor(log_2(n))+1)
```
If `n` is the input, then `a(n)` is the resulting number after its binary sequence has been flipped. 0 and 1 are obvious. For `a(2n) = a(n)`, consider that `x0` (where `x` is any sequence of binary digits) flipped is `0x`, which is the same as `x`. For `a(2n+1)`, the reasoning is a bit more complicated. `x1` flipped is `1x`, which is equal to `x + 2^k` for some `k`. This `k` is one more than the number of digits in `x`, which is `floor(log_2(n))+1`. The full formula follows, except that it's modified a bit. This is what I actually code:
```
a(0) = 0
a(1) = 1
a(n) = a(n//2) + (n%2) * 2^(floor(log_2(n - n%2)))
```
As Mego and I worked out in chat, `floor(n/2) = (n - n%2)/2`. Thus, `log_2(floor(n/2))+1 = log_2(n - n%2)`. Furthermore, multiplying by `(n%2)` collapses both the odd and even parts into one expression.
Finally, without any further ado, here's the code, explained.
```
n Take number from input
1{ Start recursion that takes only one element
d1`, 1 if top of stack 0 or 1, 0 otherwise
2$3* 26
& Jump if top of stack is not zero
$z Store top of stack in register (z)
zd2%- n - n%2
2l$M log_2(n - n%2)
d1%- floor(log_2(n - n%2))
2 ; 2^floor(log_2(n - n%2))
z2% n%2
* Multiply
z2: n//2
{ Recurse
+ Add
} Return
2;N. Square it, output as number, and stop.
```
[Answer]
# Python, 32 bytes
```
lambda x:int(bin(x)[:1:-1],2)**2
```
[Try it online.](http://ideone.com/r1Sx4H)
The code is pretty straightforward: `bin(6)`, for example, gives `0b110`, the binary representation of 6. `[:1:-1]` reverses the string and removes `0b`. `int` converts the string to an integer from binary, and `**2` squares it.
[Answer]
# [Par](http://ypnypn.github.io/Par/), 5 bytes
```
✶Σ⌐Σ²
```
That's read-binary-reverse-binary-square.
[Answer]
# [Jolf](https://github.com/ConorOBrien-Foxx/Jolf/), 7 bytes
[Just run it.](http://conorobrien-foxx.github.io/Jolf/#code=UUNfQmoy) The input on the page doesn't work.
```
^C_Bj22
```
## Explanation
```
^C_Bj22
j numeric input
B convert to binary (str)
_ reverse
C 2 parse as binary integer to base 10
^ 2 square
implicit output
```
---
I added the `Q` command, which makes this 6 bytes: `QC_Bj2`
[Answer]
# [TeaScript](https://github.com/vihanb/TeaScript), 9 [bytes](https://en.m.wikipedia.org/wiki/ISO/IEC_8859) ~~11~~
TeaScript is Javascript for golfing
```
®x÷v¤)**2
```
Will golf more once I get back to my computer
[Try it online!](http://vihanserver.tk/p/TeaScript/#?code=%22$p(%C2%AEx%C3%B7v%C2%A4)%C2%A4)%22&inputs=%5B%2211%22%5D&opts=%7B%22int%22:true,%22ar%22:false,%22debug%22:false,%22chars%22:false,%22html%22:false%7D)
[Test all](http://vihanserver.tk/p/TeaScript/#?code=%22r(25)m(%23%20%20$p(%C2%AEl%C3%B7v%C2%A4)%C2%A4)%20%20);%22&inputs=%5B%2211%22%5D&opts=%7B%22int%22:true,%22ar%22:false,%22debug%22:false,%22chars%22:false,%22html%22:false%7D)
[Answer]
## [Seriously](https://github.com/Mego/Seriously), ~~8~~ 7 bytes
```
2;,¡R¿ª
```
Challenges like these are perfect for Seriously :)
[Try it online](http://seriouslylang.herokuapp.com/link/code=323b2cad52a8a6&input=26)
Explanation:
```
2;,¬° get a string representing the (decimal) input in binary, with a 2 on the bottom of the stack
R reverse the string
¬ø convert binary string to decimal int (using that extra 2 from earlier)
ª square it
```
[Answer]
# J, ~~10~~ 9 bytes
```
2^~|.&.#:
```
This is a tacit, monadic verb. [Try it online!](https://tio.run/nexus/j#@5@mYGulYBRXV6Onpqds9T81OSNfIU3JQCFTT8HI9D8A "J – TIO Nexus")
*Thanks to @randomra for golfing off 1 byte!*
### How it works
```
2^~|.&.#: Right argument: y
#: Convert y to binary.
|. Reverse the digits.
&. Dual; apply the inverse of #:, i.e., convert back to integer.
^~ Apply power (^) with reversed argument order (~)...
2 to 2 and the previous result.
```
[Answer]
## [Perl 6](http://perl6.org), 21 bytes
```
{:2(.base(2).flip)²}
```
Example usage:
```
say {:2(.base(2).flip)²}(26); # 121
say (0..24).map: {:2(.base(2).flip)²};
# (0 1 1 9 1 25 9 49 1 81 25 169 9 121 49 225 1 289 81 625 25 441 169 841 9)
my &code = {:2(.base(2).flip)²};
say code 3; # 9
say chars code 10¹⁰⁰; # 140
```
[Answer]
# CJam, 10 bytes
```
ri2bW%2b_*
```
[Try it online](http://cjam.aditsu.net/#code=ri2bW%252b_*&input=17)
[Answer]
# JavaScript, ~~64~~ ~~63~~ ~~56~~ 53 bytes
```
n=>parseInt([...n.toString(2)].reverse().join``,2)**2
```
I realize I'm extra long, but hey, I can do it :P
[Demo](http://www.es6fiddle.net/ihkxrore)
[Answer]
# PHP, 45 bytes
```
echo pow(bindec(strrev(decbin($argv[1]))),2);
```
[Answer]
# Ruby, 35 bytes
```
->(x){x.to_s(2).reverse.to_i(2)**2}
```
[Answer]
# Shell, 25
```
dc -e2o?p|rev|dc -e2i?d*p
```
Input/output via STDIN/STDOUT:
```
$ echo 26|dc -e2o?p|rev|dc -e2i?d*p
121
$
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
bRCn
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/Kcg57/9/IzMA "05AB1E – Try It Online")
# Explanation
```
Implicit input
b Convert to binary
R Reverse
C Convert from binary
n Square
Implicit output
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 4 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
àxå²
```
[Try it online.](https://tio.run/##DcurEYAwFEVBf6rJffmXgwEEDAZBORgaoARSWIjdmd2nc12Obe693Vd7vrd3hzA8gUgiU6hooJAhjwKKKKGMCqqYw8YxzGPhBw)
**Explanation:**
```
à # Convert the (implicit) input-integer to a binary-string
x # Reverse this string
å # Convert it from a binary-string back to an integer
² # Take the square of this integer
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
```
#+##&~Fold~Reverse@IntegerDigits[#,2]^2&
```
[Try it online!](https://tio.run/##Dcq9CsIwFIbhW/kgkMUj9sS/OigdRHAT1xAhaFoDtkIaXMTeejzDO71P7/Mz9D7Huy8t9kXNlNLT6f16TNfwCWkMzXnIoQvpGLuYR6vIuJvR5ZLikK3C/IDWKuegsWjwZYIhLAkrwpqwIWwJNWFH4EqSzwJYBAthMSyIRbEwFmeqX/kD "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
bṘB²
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJi4bmYQsKyIiwiIiwiMTEiXQ==)
```
bṘB²
b·πòB # Convert to binary, reverse, convert back to decimal
² # Square
```
[Answer]
# [Desmos](https://www.desmos.com), ~~124~~ 72 bytes
```
f(n)=total(mod(floor(n/2^l),2)2^k/2^l)^2
k=floor(log_2(n+0^n))
l=[k...0]
```
[Try it on Desmos!](https://www.desmos.com/calculator/veegjtgbcr)
*-52 bytes thanks to Aiden Chow*
[Answer]
# [Haskell](https://www.haskell.org), 38 bytes
```
(#0)
0#s=s^2
n#s=div n 2#(2*s+n`mod`2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ0W0km5yQYFS7OI025ilpSVpuhY31TSUDTS5DJSLbYvjjLjygHRKZplCnoKRsoaRVrF2XkJufkqCkSZE9Y7cxMw8BVuFlHwuBYWCosy8EgUVhTQFIzOI9IIFEBoA)
[Answer]
# Pyth - 9 bytes
Straightforward conversions. I actually assigned 2 to a var which is pretty weird.
```
^i_jQK2KK
```
[Test Suite](http://pyth.herokuapp.com/?code=%5Ei_jQK2KK&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21%0A22%0A23%0A24%0A25%0A26&debug=0).
[Answer]
## Pyth, 9 bytes
```
^i_.BQ2 2
```
This is a very simple pyth based answer similar to the Python one
[Answer]
# ùîºùïäùïÑùïöùïü, 12 chars / 21 bytes
```
⦅`ᶀ`+ᴙ(ïß2)²
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=5&code=%E2%A6%85%60%E1%B6%80%60%2B%E1%B4%99%28%C3%AF%C3%9F2%29%C2%B2)`
## Noncompetitive answer, 9 chars / 18 bytes
```
⦅Յ+ᴙ(ïⓑ)²
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=5&code=%E2%A6%85%D5%85%2B%E1%B4%99%28%C3%AF%E2%93%91%29%C2%B2)`
[Answer]
# TI-Basic (TI-84 Plus CE), 42 bytes
```
Prompt X
0‚ÜíS
While X
2S‚ÜíS
If X/2≠int(X/2
S+1‚ÜíS
End
S2
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 38 bytes
```
r;f(n){for(r=n%2;n/=2;r+=r+n%2);r*=r;}
```
Reverse all the bits, square the result. Pretty standard.
*-1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!*
[Try it online!](https://tio.run/##HYvBCgIxDETv/YqwUEjsilLwYuyf7GVpqeRgVoJ4Wfbba@tcHsObyednzq0ZV1Ta62ZoSX1kvaTIFpKF3ojtlIyPJvqB1yqK300Kud1BzzgNIZDgyh0PiLfOEOjvR97WFxUnX@7gy6LTDDJDRSFid7Qf "C (gcc) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 38 bytes
```
$_=(oct"0b".reverse sprintf"%b",$_)**2
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lYjP7lEySBJSa8otSy1qDhVobigKDOvJE1JNUlJRyVeU0vL6P9/I5N/@QUlmfl5xf91fU31DAwN/usWAAA "Perl 5 – Try It Online")
[Answer]
# Splunk (v8.2.6) Search Processing Language, 182 170 bytes:
```
|inputcsv b|foreach *[eval x=<<FIELD>>]|eval p=mvrange(0,floor(log(x,2)+1))|mvexpand p|eval x=floor(x/pow(2,p))%2|stats list(x) as x|eval x=tonumber(mvjoin(x,""),2),x=x*x
```
Big data. Smallish code.
Am learning Splunk for work, and decided to try to have a bit of fun with it.
Input is expected in a file at $SPLUNK\_HOME/var/run/splunk/csv/b.csv. The file must contain the number in base 10 followed by a newline. The output is the search result, which is analogous to an SQL `SELECT`. This is as close to our standard I/O rules as I could reasonably do in SPL, but I'm willing to work something out if this is problematic.
With whitespace:
```
| inputcsv b
| foreach * [eval x=<<FIELD>>]
| eval p=mvrange(0,floor(log(x,2)+1))
| mvexpand p
| eval x=floor(x/pow(2,p))%2
| stats list(x) as x
| eval x=tonumber(mvjoin(x,""),2),x=x*x
```
Explanation (I plan to flesh this out more later):
```
| inputcsv b ``` Read in b ```
| foreach * [eval x=<<FIELD>>] ``` Get the value into a field "x" (Splunk reads our "CSV" file in as an event with one field, named the value we want, with a value of the empty string.) ```
| eval p=mvrange(0,floor(log(x,2))+1) ``` Create a multivalue field "p" which contains the numbers 0 to the number of bits required to represent our number, the order here also means we get the reverse for free ```
| mvexpand p ``` Expand our single event with a multivalue field "p" into multiple events, each with a certain value of p ```
| eval x=floor(x/pow(2,p))%2 ``` Calculate (x/(2**p))%2, and set that value back to x```
| stats list(x) as x ``` Collect the values of x back into a single multivalue event ```
| eval x=tonumber(mvjoin(x,""),2),x=x*x ``` Combine all the bits back into a string, and convert that string back into a numeric value, then square it```
```result is a single event with field x, containing the square of the bit reversed input.```
```
Edit: forgot how math works (ceil instead of floor + 1 for the bit length calculation), and managed to only check with inputs that worked with my wrong math. Also sort happened to be a leftover from when I was doing the problem more verbosely, we get the reverse sort for free. Nets to -12.
[Answer]
# [LOLCODE](http://lolcode.org/), 192 bytes
```
HAI 1.3
I HAS A s ITZ 0
I HAS A x
GIMMEH x
IM IN YR l
s R SUM OF PRODUKT OF s 2 MOD OF x 2
x R QUOSHUNT OF x 2
BOTH SAEM x 0,O RLY?
YA RLY
GTFO
OIC
IM OUTTA YR l
VISIBLE PRODUKT OF s s
KTHXBYE
```
[Try it online!](https://tio.run/##VY3LCsIwFET3@Yr5AJFawa2k9pFLm17NQ4xbdVfoIpv@fWwQBVdzZhg40zw95ucrJSUJu@1eEJS0kIggd0fx64voSOtGrUAaNCIYTCLCwHoNbnE2XPveZYwoobnOuKAUy3q6eLbKj@67VewUrGz02ooNwwzhKILMKTrXsmA6ZRF75@THdSVL1dD8i6LonbpVoUmpPLwB "LOLCODE – Try It Online")
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 10 bytes
```
K\rJ$)))^2
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/3zumyEtFU1Mzzuj/fyMzAA "cQuents – Try It Online")
First time using cQuents.
## Explanation
```
$ # Take the index.
J ) # Convert to (default) base 2.
\r ) # Reverse it.
K ) # Convert from (default) base 2 to base 10.
^2 # And square it.
```
] |
[Question]
[
>
> Tetration, represented as \${}^ba\$, is repeated exponentiation. For example, \${}^32\$ is \$2^{2^2}\$, which is \$16\$.
>
>
>
Given two numbers \$a\$ and \$b\$, print \${}^ba\$.
## Test cases
```
1 2 -> 1
2 2 -> 4
5 2 -> 3125
3 3 -> 7625597484987
etc.
```
Scientific notation is acceptable.
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins.
[Answer]
# Dyalog APL, 3 bytes
```
*/⍴
```
[TryAPL.](http://tryapl.org/?a=f%u2190*/%u2374%20%u22C4%203%20f%202%20%u22C4%202%20f%203&run)
## Explanation
```
*/⍴ Input: b (LHS), a (RHS)
⍴ Create b copies of a
*/ Reduce from right-to-left using exponentation
```
[Answer]
# J, ~~5~~ 4 bytes
```
^/@#
```
This is literally the definition of tetration.
## Usage
```
f =: ^/@#
3 f 2
16
2 f 1
1
2 f 2
4
2 f 5
3125
4 f 2
65536
```
## Explanation
```
^/@# Input: b (LHS), a (RHS)
# Make b copies of a
^/@ Reduce from right-to-left using exponentation
```
[Answer]
## Python, 30 bytes
```
f=lambda a,b:b<1or a**f(a,b-1)
```
Uses the recursive definition.
[Answer]
## Haskell, 19 bytes
```
a%b=iterate(a^)1!!b
```
Iterates exponentiating starting at `1` to produce the list `[1,a,a^a,a^a^a,...]`, then take the `b`'th element.
Same length directly:
```
a%0=1;a%b=a^a%(b-1)
```
Point-free is longer:
```
(!!).(`iterate`1).(^)
```
[Answer]
# Mathematica, 16 bytes
```
Power@@Table@##&
```
# Explanation
```
Table@##
```
Make b copies of a.
```
Power@@...
```
Exponentiation.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
x*@/
```
[Try it online!](http://jelly.tryitonline.net/#code=eCpALw&input=&args=Mw+Mw) or [verify all test cases](http://jelly.tryitonline.net/#code=eCpALwrFvDsiw6ciRw&input=&args=MSwgMiwgNQ+MiwgMiwgMg).
### How it works
```
x*@/ Main link. Arguments: a, b
x Repeat [a] b times.
*@/ Reduce the resulting array by exponentation with swapped arguments.
```
[Answer]
# Python, 33 bytes
```
lambda a,b:eval('**'.join([a]*b))
```
This evaluates to an unnamed function, that takes the string representation of a number and a number. For example:
```
>>> f=lambda a,b:eval('**'.join([a]*b))
>>> f('5',2)
3125
>>>
```
If mixing input formats like this does not count, there is also this 38 byte version:
```
lambda a,b:eval('**'.join([str(a)]*b))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ ~~4~~ 2 bytes
*-2 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs).*
```
Gm
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fPff/f2MuYwA "05AB1E – Try It Online") Beats all other answers
```
Gm # full program
G # for N in [1, 2, 3, ...,
# ..., implicit input...
G # ...minus 1]...
m # push...
# implicit input...
m # to the power of...
# implicit input...
# (implicit) or top of stack if not first iteration
# implicit output
```
[Answer]
# Perl, 19 bytes
Includes +1 for `-p`
Give numbers on separate lines on STDIN
```
tetration.pl
2
3
^D
```
`tetration.pl`
```
#!/usr/bin/perl -p
$_=eval"$_**"x<>.1
```
[Answer]
# R, 39 bytes
Recursive function:
```
f=function(a,b)ifelse(b>0,a^f(a,b-1),1)
```
[Answer]
# [Factor](https://factorcode.org/), ~~29~~ 26 bytes
```
[ 1 rot [ dupd ^ ] times ]
```
[Try it online!](https://tio.run/##TY6xCsJADIb3PsX/AgpWXBRcxcVFnEqF40zxaHt3Jiki0mevQR2aLH@@5E/SOK@Jp8v5eDps4USSF/RO72iJI3Vo@PWtl80QvYYUBV1QYtcJMpPqK3OICqHHQNGTURd4wcm3pNgVxbuAxRsrlBj/upzpzUyvLcdinCqb5qSocBvyDVfU0NDb7tpa8nTZgB3PSchc4@/vfW9c1Pl2Cd@R4@kD "Factor – Try It Online")
*-3 thanks to @Bubbler*
[Answer]
# [Element](http://github.com/PhiNotPi/Element), 11 bytes
```
__2:':1[^]`
```
[Try it online!](http://element.tryitonline.net/#code=X18yOic6MVteXWA&input=NQoy)
This is just "straightforward" exponentiation in a loop.
```
__2:':1[^]`
__ take two values as input (x and y)
2:' duplicate y and send one copy to the control stack
: make y copies of x
1 push 1 as the initial value
[ ] loop y times
^ exponentiate
` print result
```
[Answer]
# JavaScript (ES7), 24 bytes
```
f=(a,b)=>b?a**f(a,b-1):1
```
The ES6 version is 33 bytes:
```
f=(a,b)=>b?Math.pow(a,f(a,b-1)):1
```
[Answer]
# dc, ~~35~~ 29 bytes:
```
?dsdsa?[ldla^sa1-d1<b]dsbxlap
```
Here is my first complete program in `dc`.
[Answer]
# PHP, 51 Bytes
```
for($b=$p=$argv[1];++$i<$argv[2];)$p=$b**$p;echo$p;
```
[Answer]
# GameMaker Language, ~~52~~ 50 bytes
```
d=a=argument0;for(c=1;c<b;c++)d=power(a,d)return d
```
[Answer]
# Perl, 40 bytes
```
map{$a=$ARGV[0]**$a}0..$ARGV[1];print$a;
```
Accepts two integers as input to the function and outputs the result
[Answer]
# [Actually](http://github.com/Mego/Seriously), 6 bytes
```
n`ⁿ)`Y
```
[Try it online!](http://actually.tryitonline.net/#code=bmDigb8pYFk&input=Mwoz)
Input is taken as `b\na` (`\n` is a newline)
Explanation:
```
n`ⁿ)`Y
n a copies of b
`ⁿ)`Y while stack changes between each call (fixed-point combinator):
ⁿ pow
) move top of stack to bottom (for right-associativity)
```
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), 9 bytes
```
q~)*{\#}*
```
[Try it online!](http://cjam.tryitonline.net/#code=cX4pKntcI30q&input=WzUgMl0)
### Explanation
```
q~ e# Take input (array) and evaluate
) e# Pull off last element
* e# Array with the first element repeated as many times as the second
{ }* e# Reduce array by this function
\# e# Swap, power
```
[Answer]
# [Wonder](https://github.com/wonderlang/wonder), 21 bytes
```
f\@@[#0?^#1f#1-#0 1?1
```
Uses the recursive approach. Usage:
```
f\@@[#0?^#1f#1-#0 1?1];f 2 3
```
# Bonus solution, 22 bytes
```
@@:^ -#0 1(genc ^#1)#1
```
A slightly unconventional approach. Usage:
```
t\@@+>#[^;#1]tk -#0 1rpt#1;t 2 3
```
More readable:
```
@@
iget
- #0 1
(genc ^#1) #1
```
Assuming `a^^b`:
Generates an infinite list of tetrated `a`; for `a=2`, this list would look something like `[2 4 16 65536...]`. Then indexes at `b-1` because Wonder is zero-indexed.
[Answer]
# [Flurry](https://github.com/Reconcyl/flurry) `-nii`, 14 bytes
```
{}{{}({})}{{}}
```
[Try it online!](https://bubbler-4.github.io/Flurry/#!ewB9AHsAewB9ACgAewB9ACkAfQB7AHsAfQB9AA==#MgAgADQA##bgBpAGkA#MQAwADAAMAAwAA==)
Takes two numbers `a b` from stdin, and outputs as the return value.
### How it works
It works basically like [xnor's Haskell answer](https://codegolf.stackexchange.com/a/97021/78410): repeat `(a^)` `b` times to 1. `a` is left on the stack, so that it can be referenced in each iteration.
```
// In Church numeral, x a → a^x
main = b power_of_a 1
power_of_a = \x. x a
= \x. x (push pop) // assumes a is on the top of the stack,
// pops and takes its value and pushes it back
```
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 9 bytes
```
~])*{\?}*
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/vy5WU6s6xr5W6/9/YwVjAA "GolfScript – Try It Online")
```
~] # Put a and b in an array
) # Remove b from the array
* # Make b copies of a
{ }* # Execute this block for each number in the array
\? # Exponentiation
```
Just `{?}` would be `(3^3)^3` instead of `3^(3^3)`.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `r`, 4 bytes
This is lyxal's solution
```
‹(⁰e
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=r&code=%E2%80%B9%28%E2%81%B0e&inputs=3%0A3&header=&footer=)
```
‹(⁰e
‹ Decrement b
( ) For loop (second parentheses is implicit) using b-1
⁰ Push a
e And raise it to the power of the accumulator (initially a)
```
## [Vyxal](https://github.com/Lyxal/Vyxal), ~~6~~ 5 bytes
Saved 1 byte thanks to lyxal
```
ʁ•⁽eḭ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%CA%81%E2%80%A2%E2%81%BDe%E1%B8%AD&inputs=3%0A%5B3%5D&header=&footer=)
This one is a worse solution. `a` is inputted as a singleton list.
```
ʁ•λe;ḭ
ʁ Make a range [0,b) (only the length of the range matters (b))
• Reshape [a] to that (make a list of b a's)
ḭ Reduce from the right
λe; using exponentiation
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 7 bytes
```
(*/#)/#
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs9LQ0lfW1Ffm4kqLNrI2igVSxhDKBMYzjgUAo1gI6w==)
Takes two inputs in the order of `[hyperexponent; base]` and returns the result.
K does not have exponentiation built-in, so I simulate `n^m` with "product `*/` of m copies `#` of n" instead. Tetration is basically the same, in the sense that it is a fold by exponentiation. K's fold is left to right, and `*/#` accepts `[exponent; base]`, so the direction of exponentiation is correctly `y^(y^(y^...))`.
Although it does not use exponentiation built-in, it fails to solve [this challenge](https://codegolf.stackexchange.com/q/5562/78410) because `4^(4^4)` is way too big to handle with built-in integer sizes.
[Answer]
# [Red](http://www.red-lang.org), ~~38~~ ~~26~~ 37 bytes
*Thanks to @9214 for telling me about the `loop` command for -12 bytes.*
*+11 bytes to fix invalidities brought out by @Bubbler.*
```
func[a b][x: a loop b - 1[x: a ** x]]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85OlEhKTa6wkohUSEnP79AIUlBV8EQwtfSUqiIjf1fUJSZV6KQpmCoYMQFYxshsU2R2MYKxv8B "Red – Try It Online")
[Answer]
# Pyth, 6 bytes
```
u^QGE1
```
[Try it online.](http://pyth.herokuapp.com/?code=u%5EQGE1&input=5%0A2&debug=0)
### Explanation
```
(implicit: input a to Q)
1 Start from 1.
u E b times,
^GQ raise the previous number to power a.
```
[Answer]
## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), ~~12~~ 11 bytes
```
nnDI1-[;]N.
```
[Try it here!](http://play.starmaninnovations.com/minkolang/?code=nnDI1-%5B%3B%5DN%2E&input=3%203)
### Explanation
```
nn Read two integers from input
D Pop top of stack and duplicate next element that many times
I1- Push length of stack, minus 1
[ Pop top of stack and repeat for loop that many times
; Pop b, a and push a^b
] Close for loop
N. Output as number and stop.
```
[Answer]
## Racket 51 bytes
```
(define ans 1)(for((i b))(set! ans(expt a ans)))ans
```
Ungolfed:
```
(define (f a b)
(define ans 1)
(for((i b))
(set! ans
(expt a ans)))
ans)
```
Testing:
```
(f 1 2)
(f 2 2)
(f 5 2)
(f 3 3)
```
Output:
```
1
4
3125
7625597484987
```
[Answer]
# Scala, 45 bytes
```
Seq.fill(_:Int)(_:Double)reduceRight math.pow
```
Ungolfed:
```
(a:Int,b:Double)=>Seq.fill(a)(b).reduceRight(math.pow)
```
Build a sequence of `a`s with `b` elements, and apply `math.pow` from right to left.
[Answer]
# TI-Basic, 19 bytes
```
Prompt A,B
A
For(C,2,B
A^Ans
End
```
] |
[Question]
[
**This is the robbers' thread. The cops' thread goes [here](https://codegolf.stackexchange.com/questions/77419/find-the-program-that-prints-this-integer-sequence-cops-and-robbers).**
In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.
The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.
**No-ops can be used in robber's solution.**
The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.
The submission should be formatted like this:
# Language, nn characters (including link to answer), Cop's username
Code:
```
function a(n)
if n<2 then
return n
else
return a(n-1) + a(n-2)
end
end
```
Output
```
a(0) returns 0
a(3) returns 2
```
Optional explanation and comments.
[Answer]
# [MATL, 5 bytes, Luis Mendo](https://codegolf.stackexchange.com/a/77454/24877)
```
H5-*|
```
This code calculates `abs((2-5)*input)` which is just `a(n)=3*n` for positive numbers, which is <http://oeis.org/A008585>
[Answer]
## [Hexagony](https://github.com/mbuettner/hexagony), [7 bytes, Adnan](https://codegolf.stackexchange.com/a/77442/8478), [A005843](https://oeis.org/A005843)
```
?{2'*!@
```
or
```
? {
2 ' *
! @
```
[Try it online!](http://hexagony.tryitonline.net/#code=P3syJyohQA&input=Mg)
Simply doubles the input (and assumes positive input). The code is (for once) simply executed in reading order. The code uses three memory edges *A*, *B*, *C* with the memory pointer starting out as shown:
[](https://i.stack.imgur.com/YZRA7.png)
```
? Read integer from STDIN into edge A.
{ Move memory pointer forwards to edge B.
2 Set edge B to 2.
' Move memory pointers backwards to edge C.
* Multiply edges A and B and store result in C.
! Print result to STDOUT.
@ Terminate program.
```
[Answer]
# [J, 7 bytes, Cᴏɴᴏʀ O'Bʀɪᴇɴ](https://codegolf.stackexchange.com/a/77425)
### Code
```
2+*:@p:
```
### Output
```
f =: 2+*:@p:
f 0
6
f 2
27
```
Try it with [J.js](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%202%2B*%3A%40p%3A%20)%202).
### How it works
Sequence [A061725](http://oeis.org/A061725) is defined as **a(n) := pn² + 2**, where **pn** is the **(n + 1)th** prime number.
```
2+*:@p: Monadic verb. Argument: n
@ Atop; combine the verbs to the right and to the left, applying one after
the other.
p: Compute the (n+1)th prime number.
*: Square it.
2+ Add 2 to the result.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), [5 bytes](https://codegolf.stackexchange.com/a/77459), [Adnan](https://codegolf.stackexchange.com/users/34388/adnan), [A001788](http://oeis.org/A001788)
```
Læ€OO
```
[Try it online!](http://05ab1e.tryitonline.net/#code=TMOm4oKsT08&input=NQ) This uses an alternative definition given on the page. Explanation:
```
Læ€OO
L range; [1..n]
æ powerset; [[], [1], ..., [1..n]]
€O mapped sum; [0, 1, ..., T(n)]
O sum; [a(n)]
```
[Answer]
# JavaScript, [10 bytes](https://codegolf.stackexchange.com/a/77515/41859), [user81655](https://codegolf.stackexchange.com/users/46855/user81655), [A033999](http://oeis.org/A033999)
*~~I think~~ I got it. Yeah.* This one was really hard. I like the submission because it relies heavily on precedences.
---
It's the sequence [A033999](http://oeis.org/A033999):
>
> a(n) = (-1)^n.
>
>
>
**Source**
```
t=>~t.z**t
```
**Explanation**
If you split this code according to the [JavaScript operator precedences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) you get:
1. `.` (precedence *18*) gets evaluated first and `t.z` will return `undefined`.
2. `~` (precedence *15*) tries to cast `undefined`, resulting in `0`, and returns `-1` after bitwise not.
3. `**` (precedence *14*) will return `-1 ^ t`, where `t` is *odd* or *even*, resulting in `-1` or `1`.
**Demo**
```
console.log(
(t=>~t.z**t)(0),
(t=>~t.z**t)(1),
);
```
[Try before buy](https://jsfiddle.net/cshpjre5/)
---
I will award a 100 rep bounty on this cool Cop submission.
[Answer]
# [Element](https://github.com/PhiNotPi/Element), [7 bytes](https://codegolf.stackexchange.com/a/77437/48934), [PhiNotPi](https://codegolf.stackexchange.com/users/2867/phinotpi), [A000042](http://oeis.org/A000042)
```
_'[,1`}
```
Notes: I was misled by the `}` for soooooo long. So it also matches `[`.
[Try it online!](http://element.tryitonline.net/#code=XydbLDFgfQ&input=Mw)
---
### How it works:
```
_'[,1`}
_ main_stack.push(input());
' control_stack.push(main_stack.pop());
[ Object temp = control_stack.pop();
for(int i=0;i<temp;i++){
, Object a = main_stack.pop(); //is actually zero
main_stack.push(a.toChars()[0]);
main_stack.push(a);
1 main_stack.push(1);
` System.out.println(main_stack.pop());
} }
```
[Answer]
# PHP, [41 bytes](https://codegolf.stackexchange.com/a/77448), [insertusernamehere](https://codegolf.stackexchange.com/users/41859/insertusernamehere), [A079978](http://oeis.org/A079978)
```
echo/* does n%3=0 */$argv[1]%3<1?1:0 ;
```
Returns 1 if its argument is a multiple of 3, and 0 otherwise. Not much beyond that.
[Answer]
# [MATL](http://github.com/lmendo/MATL), [9 bytes, beaker](https://codegolf.stackexchange.com/a/77493/34388), [A022844](https://oeis.org/A022844)
Code (with a whitespace at the end):
```
3x2xYP*k
```
[Try it online!](http://matl.tryitonline.net/#code=M3gyeFlQKmsg&input=MTI)
Found the following three matches with a script I wrote:
```
Found match: A022844
info: "name": "Floor(n*Pi).",
Found match: A073934
info: "name": "Sum of terms in n-th row of triangle in A073932.",
Found match: A120068
info: "name": "Numbers n such that n-th prime + 1 is squarefree.",
```
I tried to do the first one, which is basically done with `YP*k`:
```
3x2x # Push 3, delete it, push 2 and delete that too
YP # Push pi
* # Multiply by implicit input
k # Floor function
```
[Answer]
# Jolf, [3 bytes](https://codegolf.stackexchange.com/a/77482), [Easterly Irk](https://codegolf.stackexchange.com/users/46271/easterly-irk), [A001477](https://oeis.org/A001477)
```
axx
```
Consists of a simple cat (`ax`) followed by a no-op. Not sure what the cop was going for here.
[Answer]
# [Java, 479 bytes](https://codegolf.stackexchange.com/a/77487/52921), [Daniel M.](https://codegolf.stackexchange.com/u/41505/), [A000073](https://oeis.org/A000073)
Code:
```
import java.util.*;
public class A{
public static int i=0;
public boolean b;
static A a = new A();
public static void main(String[] args){
int input = Integer.parseInt(args[0]);
LinkedList<Integer> l = new LinkedList<>();
l.add(1);
l.add(0);
l.add(0);
for(int ix = 0; ix<=input; ix++)if(ix>2){
l.add(0,l//d
.get(1)+l.peekFirst()+ l.get(2));
}
System.out.println(input<2?0:l.pop()
+(A.i +(/*( 5*/ 0 )));
}
}
```
If you miss non-revealed characters, they are replaced with spaces.
[Answer]
# Ruby, [38 bytes, histocrat](https://codegolf.stackexchange.com/a/77588/45268), [A008592](http://oeis.org/A008592)
```
->o{(s="+o++o"*5).sum==03333&&eval(s)}
```
Could be different from the intended solution as I found this by hand.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), [4 bytes, Paul Picard](https://codegolf.stackexchange.com/a/77443/34388), [A001317](https://oeis.org/A001317)
Code:
```
$Fx^
```
[Try it online!](http://05ab1e.tryitonline.net/#code=JEZ4Xg&input=OA)
Explanation:
```
$ # Pushes 1 and input
F # Pops x, creates a for-loop in range(0, x)
x # Pops x, pushes x and 2x
^ # Bitwise XOR on the last two elements
# Implicit, ends the for-loop
# Implicit, nothing has printed so the last element is printed automatically
```
The sequence basically is a binary Sierpinski triangle:
```
f(0)= 1 =1
f(1)= 1 1 =3
f(2)= 1 0 1 =5
f(3)= 1 1 1 1 =15
f(4)= 1 0 0 0 1 =17
```
And translates to the formula **a(n) = a(n - 1) XOR (2 × a(n - 1))**
Luckily, I remembered [this one](https://codegolf.stackexchange.com/a/67503/34388) :)
[Answer]
# [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), [betseg](https://codegolf.stackexchange.com/a/96814/47066), [A001844](http://oeis.org/A001844)
```
readIO
a=i
a+1
i*2
i*a
i+1
printInt i
```
[Try it online!](http://silos.tryitonline.net/#code=cmVhZElPCmE9aQphKzEKaSoyCmkqYQppKzEKcHJpbnRJbnQgaQ&input=&args=NQ)
[Answer]
# Jolf, [5 characters](https://codegolf.stackexchange.com/a/77421/48934), [Cᴏɴᴏʀ O'Bʀɪᴇɴ](https://codegolf.stackexchange.com/users/31957/c%e1%b4%8f%c9%b4%e1%b4%8f%ca%80-ob%ca%80%c9%aa%e1%b4%87%c9%b4), [A033536](http://oeis.org/A033536)
Code:
```
!K!8x
```
Output:
```
a(2) = 8
a(10) = 4738245926336
```
[Answer]
# [Reng v3.3](https://jsfiddle.net/Conor_OBrien/avnLdwtq/), [36 bytes](https://codegolf.stackexchange.com/a/77427/48934), [Cᴏɴᴏʀ O'Bʀɪᴇɴ](https://codegolf.stackexchange.com/users/31957/c%e1%b4%8f%c9%b4%e1%b4%8f%ca%80-ob%ca%80%c9%aa%e1%b4%87%c9%b4), [A005449](http://oeis.org/A005449)
```
iv:#+##->>)2%æ~¡#~
#>:3*1+*^##</div>
```
## Output
```
a(1) = 2
a(3) = 15
```
## Explanation
I completely ignored the prespecified commands, except the `)` because I did not have enough space.
The actually useful commands are here:
```
iv >>)2%æ~
>:3*1+*^
```
Stretched to a straight line:
```
i:3*1+*)2%æ~
```
With explanation:
```
i:3*1+*)2%æ~ stack
i [1] takes input
: [1,1] duplicates
3 [1,1,3] pushes 3
* [1,3] multiplies
1 [1,3,1] pushes 1
+ [1,4] adds
* [4] multiplies
) [4] shifts (does nothing)
2 [4,2] pushes 2
% [2] divides
æ [] prints
~ [] halts
```
The formula is `a(n) = n(3n+1)/2`.
[Answer]
# 05AB1E, [3 bytes](https://codegolf.stackexchange.com/a/77441/48934), [Adnan](https://codegolf.stackexchange.com/users/34388/adnan), [A000292](http://oeis.org/A000292)
```
LLO
```
### Output
```
a(9) = 165
a(10) = 220
```
### How it works
```
LLO Stack
L [1,2,3,4,5,6,7,8,9] range
L [1,1,2,1,2,3,1,2,3,4,...,1,2,3,4,5,6,7,8,9] range of range
O sum all of them
```
The mathematical equivalent is `sum(sum(n))`, where `sum` is `summation`.
[Answer]
# Jolf, 11 bytes, [QPaysTaxes](https://codegolf.stackexchange.com/a/77429/31957), [A000005](http://oeis.org/A000005)
```
aσ0xxdxxxxx
```
Simple enough: `a`lert the `σ0` (number of divisors of) `x`, then put useless stuff at the end.
[Try it online!](http://conorobrien-foxx.github.io/Jolf/#code=Yc-DMHh4ZHh4eHh4&input=MTAKCjIwCgozMA) The test suite button's a bit broke, but still shows proper results.
(You could've golfed it down to two bytes! Just `σ0` would've done nicely.)
[Answer]
# Python 2, [87 bytes](https://codegolf.stackexchange.com/a/77451), [Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000), [A083054](http://oeis.org/A083054)
```
n=input()
_=int(3**.5*n)-3*int(n/3**.5)########################################
print _
```
Not that hard, actually. Just searched for sequences that met the constraints until I found one that could be generated in the given space.
[Answer]
# [Jolf](https://github.com/ConorOBrien-Foxx/Jolf), [11 bytes, RikerW](https://codegolf.stackexchange.com/a/77486/34388), [A011551](https://oeis.org/A011551)
Code:
```
c*mf^+91x~P
```
Explanation:
```
+91 # add(9, 1) = 10
^ x # 10 ** input
mf # floor function (no-op)
* ~P # multiply by phi
c # ¯\_(ツ)_/¯
```
[Try it here](http://conorobrien-foxx.github.io/Jolf/#code=YyptZl4rOTF4flA&input=MTI).
[Answer]
# JavaScript (ES6), [119 bytes, Cᴏɴᴏʀ O'Bʀɪᴇɴ](https://codegolf.stackexchange.com/a/77461/46855), [A178501](http://oeis.org/A178501)
```
x=>(n="=>[[["|x|"##r(###f#n###;##")|n?Math.pow("#<1##].c####t.##pl##[####nc#"|10,"y([###(###(#]###)"|x-1|``):0|`#h####`
```
I'm sure the actual code generates a trickier sequence than this, but with just the two outputs, this OEIS sequence is simple and matches them.
Without all the ignored characters, the algorithm is just `x=>x?Math.pow(10,x-1):0`.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), [5 bytes, Luis Mendo](https://codegolf.stackexchange.com/a/77502/34388), [A051696](https://oeis.org/A051696)
Code:
```
Ðms!¿
```
Explanation:
```
Ð # Triplicate input.
m # Power function, which calculates input ** input.
s # Swap two top elements of the stack.
! # Calculate the factorial of input.
¿ # Compute the greatest common divisor of the top two elements.
```
So, basically this calculates **gcd(n!, nn)**, which is [A051696](https://oeis.org/A051696).
[Try it online!](http://05ab1e.tryitonline.net/#code=w5BtcyHCvw&input=Ng).
[Answer]
# PHP, [18 bytes, insertusernamehere](https://codegolf.stackexchange.com/a/77508/25180), [A023443](http://oeis.org/A023443)
Code:
```
echo$argv[1]+0+~0;
```
Output:
```
a(0) = -1
a(1) = 0
```
[Answer]
# [Octave (34 bytes) by Stewie Griffin](https://codegolf.stackexchange.com/a/77490/30688)
The sequence is [A066911](http://oeis.org/A066911).
```
@(m)(mod(m,u=1:m )&isprime(u))*u'
```
[Answer]
# PHP, [137 bytes, insertusernamehere](https://codegolf.stackexchange.com/a/77524/25180), [A000959](http://oeis.org/A000959)
Code:
```
for($s=range(1,303);$i<($t=count($s));$s=array_merge($s))for($j=($k=++$i==1?2:$s[$i-1])-1;$j<$t;$j+=$k )unset($s[$j]);echo$s[$argv[1]-1];
```
Output:
```
a(3) = 7
a(7) = 21
a(23) = 99
```
[Answer]
## 05AB1E, [10 bytes, George Gibson](https://codegolf.stackexchange.com/a/79936/47066), [A003215](http://oeis.org/A003215)
**Code:**
```
Ds3*s1+*1+
```
**Explanation:**
Computes 3\*n\*(n+1)+1 which is the oeis sequence A003215.
[Answer]
# [Element](https://github.com/PhiNotPi/Element), [10 bytes](https://codegolf.stackexchange.com/a/77430/48934), [PhiNotPi](https://codegolf.stackexchange.com/users/2867/phinotpi), [A097547](http://oeis.org/A097547)
```
2_4:/2@^^`
```
[Try it online!](http://element.tryitonline.net/#code=Ml80Oi8yQF5eYA&input=NA)
## Output
```
a(3) = 6561
a(4) = 4294967296
```
[Answer]
# Pyke, [6 bytes](https://codegolf.stackexchange.com/a/77476), [muddyfish](https://codegolf.stackexchange.com/users/32686/muddyfish), [A005563](http://oeis.org/A005563)
```
0QhXts
```
Yay hacks! The `0Qh` and `s` are no-ops. `hXt` just computes `(n + 1) ^ 2 - 1`.
[Answer]
# J, [8 bytes, Kenny Lau](https://codegolf.stackexchange.com/a/77506/25180), [A057427](https://oeis.org/A057427)
Code:
```
(-%- )\.
```
Output:
```
a(0) = 0
a(1..29) = 1
```
I don't think this is intended. And I don't know why J had this behavior. But it works.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), [70 bytes, FliiFe](https://codegolf.stackexchange.com/a/77528/34388), [A070650](https://oeis.org/A070650)
Code (with obfuscated version below):
```
DhbI|qb"#"qb"#"R!1Iqb"#";=^Q6+""s ]%Q27 ;.qlY+Q1Ih+""Z##;.q)=Z+Z1;@YQ
DhbI|qb"#"qb"#"R!1Iqb"#"#####+""s####2###;##lY+Q1Ih+""Z#####)=Z+Z1;@YQ (obfuscated)
```
This basically does:
```
=^Q6%Q27
```
It calculates **a(n) = n6 % 27**, which is [A070650](https://oeis.org/A070650). Explanation:
```
=^Q6 # Assign Q to Q ** 6
%Q27 # Compute Q % 27
# Implicit output
```
[Try it here](https://pyth.herokuapp.com/?code=DhbI%7Cqb%22%23%22qb%22%23%22R%211Iqb%22%23%22%3B%3D%5EQ6%2B%22%22s+%5D%25Q27++%3B.qlY%2BQ1Ih%2B%22%22Z%23%23%3B.q%29%3DZ%2BZ1%3B%40YQ&input=2&test_suite=1&test_suite_input=2%0A4&debug=0)
[Answer]
## Python, 108, [CAD97](https://codegolf.stackexchange.com/a/77534/38368), [A005132](https://oeis.org/A005132)
```
def a(n):
if n == 0: return 0
f=a(n-1)-n
return f if f>0 and not f in(a(i)for i in range(n))else a(n-1)+n
```
Obfuscated code :
```
def a(n):
###n####0######n#0
f=a#######
return f #f#####a###### f ####a(##f###i#i###a####n##else a#######
```
Outputs:
```
>>> a(0)
0
>>> a(4)
2
>>> a(16)
8
>>> a(20)
42
```
] |
[Question]
[
Let's define **fn(k)** as the sum of the first **k** terms of the natural numbers **[1, ∞)** where each number is repeated **n** times.
```
**k** | **0 1 2 3 4 5 6 7 8 9**
--------+-------------------------------------------------
**f\_1(k)** | 0 1 3 6 10 15 21 28 36 45
**deltas** | +1 +2 +3 +4 +5 +6 +7 +8 +9
--------+-------------------------------------------------
**f\_2(k)** | 0 1 2 4 6 9 12 16 20 25
**deltas** | +1 +1 +2 +2 +3 +3 +4 +4 +5
--------+-------------------------------------------------
**f\_3(k)** | 0 1 2 3 5 7 9 12 15 18
**deltas** | +1 +1 +1 +2 +2 +2 +3 +3 +3
```
The anti-diagonals of this as a square array is similar to [OEIS sequence A134546](https://oeis.org/A134546 "A134546 - OEIS").
## Challenge
Write a **program/function** that takes **two non-negative integers n and k** and outputs **fn(k)**.
### Specifications
* [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods "Default for Code Golf: Input/Output methods") **apply**.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default "Loopholes that are forbidden by default") are **forbidden**.
* Your solution **can either be 0-indexed or 1-indexed for n and/or k** but please specify which.
* This challenge is not about finding the shortest approach in all languages, rather, it is about finding the **shortest approach in each language**.
* Your code will be **scored in bytes**, usually in the encoding UTF-8, unless specified otherwise.
* Built-in functions that compute this sequence are **allowed** but including a solution that doesn't rely on a built-in is encouraged.
* Explanations, even for "practical" languages, are **encouraged**.
### Test cases
In these test cases, **n** is 1-indexed and **k** is 0-indexed.
```
**n k fn(k)**
1 2 3
2 11 36
11 14 17
14 21 28
21 24 27
24 31 38
31 0 0
```
In a few better formats:
```
1 2
2 11
11 14
14 21
21 24
24 31
31 0
1, 2
2, 11
11, 14
14, 21
21, 24
24, 31
31, 0
```
### Reference implementation
This is written in [Haskell](https://www.haskell.org/ "Haskell Language").
```
f n k = sum $ take k $ replicate n =<< [1..]
```
[Try it online!](https://tio.run/##jZAxbsMwDEV3n@IPWQo0BuR6TE5SdGBtqhZsyYFEI1foKXK4XMSl46QoBLjt30S@/ymyo9TzMMyzRUCPI9LksYNQz/rcIfJpcA0Ja/t4OODVlOXbvN/jwf9PLVsXGAQ7hUbcGNQvHcltUIKcR1D8mDwHSRpMoUVf6JSH1l/9pYUabVmWP62rvhfakHQM62IShYSjT1tBm7pdZg0KJFOkAWHy7xyTtp5x/bw8/R6Yn/quc8eRwdR09zy4tLCsZKuoOM@pKDw5taEdi8V0ii6IbmthUGWVCsbkkIGp81qNKucqTcu5qsaLmb8A "Haskell – Try It Online")
[This challenge was sandboxed.](https://codegolf.meta.stackexchange.com/a/14260/ "Sandbox for Proposed Challenges")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~32 28~~ 23 bytes
```
->n,k{k.step(0,-n).sum}
```
[Try it online!](https://tio.run/##FYkxDoQgFAV7T0GHax7E/6VdL0J@oYk2RkMWKTbq2RGqmcn80vzP6zeb8cB2bTaeS2h7mONjY9qf7D2BBZ5BVEAEcpUOXJvLrc0OA4nYfQrXPWG@m5DOqHxRaDNqqLW6SKeVbp78Ag "Ruby – Try It Online")
### Explanation
Let's visualize the sum as the area of a triangle, for example with n=3 and k=10:
```
*
*
*
**
**
**
***
***
***
****
```
Then we sum by column instead of row: the first column is `k`, then `k-n`, `k-2n` and so on.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~34~~ 28 bytes
```
lambda n,k:(k+k%n)*(k/n+1)/2
```
[Try it online!](https://tio.run/##FYvBCoMwEER/JRcx0Smya05C@yNpDoqIknYN4qVfn2ZPM483k3/3fgqX7fkun/m7rLMRpMmmPjXiOpsG6ckNdXBeaswhJgQCRwQGUQ0ikNf0YGWuVpk9Ropxytcht37RPl4tNlurK38 "Python 2 – Try It Online")
Thanks Martin Ender, Neil and Mr Xcoder for helping.
[Answer]
## [Husk](https://github.com/barbuz/Husk), 4 bytes
```
Σ↑ṘN
```
[Try it online!](https://tio.run/##yygtzv7//9ziR20TH@6c4ff//38jk//GhgA "Husk – Try It Online")
### Explanation
This just ends up being a direct translation of the reference implementation in the challenge:
```
N Start from the infinite sequence of all natural numbers.
Ṙ Replicate each element n times.
↑ Take the first k values.
Σ Sum them.
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~12~~ ~~10~~ 8 bytes
```
+/∘⌈÷⍨∘⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRt/UcdMx71dBze/qh3BYjZu/n/fw0gaWigqQDk66UpGOiAuQA "APL (Dyalog Unicode) – Try It Online")
`n` on the left, `k` (0 indexed) on the right.
[Answer]
# Mathematica, 40 bytes
```
Tr@Sort[Join@@Range@#2~Table~#][[;;#2]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6TIITi/qCTaKz8zz8EhKDEvPdVB2aguJDEpJ7VOOTY62tpa2Sg2Vu1/QFFmXolDWrSRiY6xYex/AA "Wolfram Language (Mathematica) – Try It Online")
```
Tr[Range@(s=⌊#2/#⌋)]#+#2~Mod~#(s+1)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6QoOigxLz3VQaPY9lFPl7KRvvKjnm7NWGVtZaM63/yUOmWNYm1DTbX/AUWZeSUOadFGJjrGhrH/AQ "Wolfram Language (Mathematica) – Try It Online")
# Mathematica, 18 bytes
**by Martin Ender**
```
Tr@Range[#2,0,-#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6TIISgxLz01WtlIx0BHVzlW7X9AUWZeiUNatJGJjrFh7H8A "Wolfram Language (Mathematica) – Try It Online")
```
n~Sum~{n,#2,0,-#}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P68uuDS3rjpPR9lIx0BHV7lW7X9AUWZeiUNatKGOUex/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~12~~ 11 bytes
```
:iY"Ys0h1G)
```
[Try it online!](https://tio.run/##y00syfn/3yozUimy2CDD0F3z/39DQy4jAA "MATL – Try It Online")
`k` is 0-indexed.
Takes input in reverse order.
Saved 1 byte thanks to @Giuseppe
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Rxḣ³S
```
One more byte than @Mr.Xcoder's Jelly solution but this is my first ever submission in Jelly and I'm still confused about how the tacitness of Jelly chooses operands so I'm still satisfied. Note the order of the inputs are `k` then `n`.
**Explanation**
```
Rxḣ³S
R Range: [1,2,...,k]
x Times: repeat each element n times: [1,1,1,2,2,2,...,n,n,n]
ḣ³ Head: take the first k elements. ³ returns the first argument.
S Sum
```
[Try it online!](https://tio.run/##y0rNyan8/z@o4uGOxYc2B////9/Q5L@hIQA "Jelly – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
**1-indexed**
```
Ḷ:‘S
```
[Try it online!](https://tio.run/##y0rNyan8///hjm1WjxpmBP///9/Q8L8RAA "Jelly – Try It Online") or see a [test suite](https://tio.run/##y0rNyan8///hjm1WjxpmBP@PjjbUMYrViTbSMTQEUoaGOoYmINpExwjENwLKgvhGJjrGhrGxoYfb9XVUHjWtcQPiUPf/AA).
[Answer]
# JavaScript (ES6), ~~24~~ 21 bytes
Takes input in currying syntax `(n)(k)`. Returns [`false` instead of `0`](https://codegolf.meta.stackexchange.com/questions/9064/should-booleans-be-allowed-where-a-number-is-required/9067#9067).
```
n=>g=k=>k>0&&k+g(k-n)
```
### Test cases
```
let f =
n=>g=k=>k>0&&k+g(k-n)
console.log(f(1 )(2 )) // 3
console.log(f(2 )(11)) // 36
console.log(f(11)(14)) // 17
console.log(f(14)(21)) // 28
console.log(f(21)(24)) // 27
console.log(f(24)(31)) // 38
```
### How?
```
n => // main unamed function taking n
g = k => // g = recursive function taking k
k > 0 && // if k is strictly positive:
k + // add k to the final result
g(k - n) // subtract n from k and do a recursive call
```
This is similar to [@GB's Ruby answer](https://codegolf.stackexchange.com/a/149355/58563).
The challenge describes how to build the 'staircase' from left to right, whereas this recursive function builds it from bottom to top. With **n = 2** and **k = 11**:
[](https://i.stack.imgur.com/3HRFi.png)
[Answer]
## Batch, 34 bytes
```
@cmd/cset/a(%2+%2%%%1)*(%2/%1+1)/2
```
A closed-form formula that I found. First argument `n` is 1-indexed, second argument `k` is 0-indexed.
[Answer]
# [Python 2](https://docs.python.org/2/), 29 bytes
```
lambda n,k:sum(range(k,0,-n))
```
[Try it online!](https://tio.run/##FYtBDoIwEEWv0h1t8kmcsSsSvUjtogSrBBlIwYWnr53V@y8vf/@d70245tujftI6TskIluH4rrYkeT3tggt6ca7mrWgys5gQCBwRGEQNRCCv9GB1blWdPa4U47CXWU79ouvvHbJt09U/ "Python 2 – Try It Online")
Thanks to [totallyhuman](https://codegolf.stackexchange.com/users/68615/totallyhuman) for -3 bytes!
---
### [Python 2](https://docs.python.org/2/), 30 bytes
```
f=lambda n,k:k>0and k+f(n,k-n)
```
[Try it online!](https://tio.run/##HYxBCoQwEAS/kpsrtuCMOQmbj4QcIhKU7I4iuezrsxlPRVF0X7@yn8K1pvcnftctGkFespuibCYP6dV0lL6m89ZiDjHeEzjAM4gaiEBWacHq3Ko6W8wUwnLdhxTdohtdh@exr38 "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 28 bytes
```
n#k|m<-k`mod`n=sum[m,m+n..k]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P085uybXRjc7ITc/JSHPtrg0NzpXJ1c7T08vO/Z/bmJmnoKtQko@lwIQFBRl5pUoqCgYKigrGKGIGAFFDA1RFYFUGZqgipmAdKKqMwKbhqrOCKTO2PA/AA "Haskell – Try It Online")
An approach I found just by screwing around with some range parameters. Most definitely not the shortest but it's pretty cool how there's so many different approaches.
[Answer]
# C, ~~38~~ 34 bytes
Recursive definition.
*-4 bytes thanks to [Steadybox](https://codegolf.stackexchange.com/users/61405/steadybox).*
```
f(n,k){return k--?1+f(n,k)+k/n:0;}
```
[Try it online!](https://tio.run/##RcpBCsIwEIXhdXOKISDMMCk2bgRT8SwSjaTBWGK6Kj17HHHh6oP/Pd8/vG8tYDaJ1nKvS8mQ@v5i@dc47fNpcFuLucLzGjOSWlUXXgXwmyY4g3XCCEeB2cC81DdqTaS6/y/Kb3DCCPYgMhPMRZaAencDbSDgZCASObW1Dw "C (gcc) – Try It Online")
---
**32 bytes by [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder), [G B](https://codegolf.stackexchange.com/users/18535/g-b)**
```
f(n,k){return(k+k%n)*(k/n+1)/2;}
```
[Try it online!](https://tio.run/##RcpBCsIwEIXhdXOKIVCYcSI13XSRehiJRtLgWGK6Kj17jCtXH7z3@/PT@1oDikm050fZsmDi1AudMA3ClobRHTVKgdctCpLaVRfeGfA3LXAF6xozTA1mA@tWPqg1ker@XWzdxTVmsGOTmWDN7Qmo@ztoAwEXA5HIqaN@AQ "C (gcc) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~37~~ ~~33~~ 31 bytes
-6 bytes thanks to Giuseppe
```
function(n,k)sum(rep(1:k,,k,n))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jTydbs7g0V6MotUDD0CpbRydbJ09T839yYomGQpqGkY6hoaaOkoKtQlq8kQaQHZOnpKDJBZU1NtQxgMkaG2oYoMoamegYIzSbAFVD5P8DAA "R – Try It Online")
Nothing fancy. ~~The `[0:k]` handles the case when k=0.~~
[Answer]
# C++, 53 bytes
Just use the formula. `n` is 1-indexed and `k` is 0-indexed.
```
[](int n,int k){return k/n*(k/n+1)/2*n+k%n*(k/n+1);};
```
[Try it online!](https://tio.run/##RY3LDoIwFETX9ismMQZqMYgbFy3@iHHRlELK40KgXRG/HYsL3cyZm5zcMdN0aYzZdPAjapTb85U68qBsz46vs/VhJnQ5ndMYouD57UyiO/1u@Zbb0ZHpQ2Wh3Lj42erhwVhYHDUgPdhl0sZi8ZVkbP87aEcpZys71OOM72CLEoWMULhHCJHBjMFDKViqes4Of9dF9yojFIpbpBD8J9dpm8HxvSZIJHtvHw "C++ (gcc) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 13 bytes
```
1#.]{.(#1+i.)
```
How it works:
The left argument is n, the right is k.
`i.` generates a list 0..k-1
`1+` adds one to each number of the list, yealding 1,2,...,k
`#` forms a hook with the above, so n copies of each elements of the list are copied.
`]{.` take the first n of them
`1#.` find their sum by base conversion.
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N9QWS@2Wk9D2VA7U0/zvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvoKhQpqCEYRpBGQaGkKFQeKGJlCOCUgRVMYIrAMqYwSSMTb8DwA "J – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~29~~ 26 bytes
```
\d+
$*
(?=.*?(1+)$)\1
$'
1
```
[Try it online!](https://tio.run/##HYk5DoAwEAN7vyLFInKskLykRflICpCgoKFA/D8Eqpmx7@M5r60NfvV1T0HdD4ipsHWFRPiyTLF4piChEjKCrVGdwdSRYHdmMPeJsO/JsF4zXw "Retina – Try It Online") Link includes test cases and header to reformat them to its preferred input (0-indexed `k` first, 1-indexed `n` second). I was inspired by @GB's Ruby answer. Explanation:
```
\d+
$*
```
Convert to unary.
```
(?=.*?(1+)$)\1
$'
```
Match every string of `n` within `k`, and replace the match with everything after the match. This is `k-n`, `k-2n`, `k-3n`, but `n` is also after the match, so you get `k`, `k-n`, `k-2n` etc. This also matches `n`, which is simply deleted (it's no longer needed).
```
1
```
Sum the results and convert back to decimal.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 5 bytes
```
s%_ES
```
**[Try it here!](https://pyth.herokuapp.com/?code=s%25_ES&input=11%0A2&debug=0)**
Port of G B's Ruby answer. A port of my Jelly one would be 6 bytes: `+s/Rvz`
[Answer]
# [Perl 6](https://perl6.org), 39 bytes
```
->\n,\k{(0,{|($_+1 xx n)}...*)[^k].sum}
```
[Test it](https://tio.run/##NY5BT4NAEIXv8yveodpdoVsWDG1C2nj17k1so7BNGmAh3a3BIL/Mm38MWaiTTPK9vHkz06hLGQ9Xo/AZiyyh6gv3WZ0r7IbVPtV@WnQs8Ltvtjh6Em0LzXshxAN/PRRvwlyrfhgjT1YZix3Ks1aG8d8fkdXVB1unubd26lnbhNyRl3EuoaZ81/CmUEKn@nLLr/ZYHMEwnkVajK3aRmVW5eDoCDgbuNcYRr@ABwnu43/GhzhVli3vIrPk1A8SQIipInIg5SxiciQfJyU35CicvXBLjsLZCzfkKLrltuQomFcGfw "Perl 6 – Try It Online")
***n*** and ***k*** are both 1 based
## Expanded:
```
-> \n, \k { # pointy block lambda with two parameters 「n」 and 「k」
( # generate the sequence
0, # seed the sequence (this is why 「k」 is 1-based)
{ # bare block lambda with implicit parameter 「$_」
|( # slip this into outer sequence
$_ + 1 # the next number
xx n # repeated 「n」 times (this is why 「n」 is 1-based)
)
}
... # keep doing that until
* # never stop
)[ ^k ] # get the first 「k」 values from the sequence
.sum # sum them
}
```
[Answer]
# [Kotlin](https://kotlinlang.org), 40 bytes
```
{n:Int,k:Int->Array(k,{i->i/n+1}).sum()}
```
[Try it online!](https://tio.run/##NY1BCoMwEEX3nmIQFxk6tk10Ja3QZVct9ATZREJ0LFELRTx7qtLMYng8HnzXj63l8NEtmGuYubrzSG77eX3zXn@Fo9nmtT3xQS54HKZO4BLMxNBpy0L7ZqhgLy@v0VtuaoQ5gfVM70EIJodgGfSWPIx4auuFJIW0kyIp/yglyTJySSp6tdbRq5KK6AtJZ0SE97o6tizSjClzeZ3NZl9dUkyW8AM "Kotlin – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 23 bytes
```
n->k->(k+k%n)*(k/n+1)/2
```
[Try it online!](https://tio.run/##VY9La8MwEITv@RVLwCAntlMruaUx9FIopukh9FRCUf0I8kMW0jpgSn67u3ZciA9Cq@Gb0U4hrsJvdKaKtOxlrRuDUJAWtCirIG9VgrJRwWq/0O1PJRNIKmEtvAup4HcBYFEgqddGpoCZRSYVwtGD4YrdEQF4U/g6JT3T/KmE6T50ZgQ2JoL80Cs/Kv2IlevSUe6KlRu1Dt0N7/ejfcgymW0rhAPkgdC66tjRvQ8vlhJZ7N7RU2cxq4OmxUAb8uVsmX87KXNSl7xO6qilN6wXe1Pi6LvRmeo99qmpJDsh5Vy@ziDMxf4XGpuGHp9@HZ/cgzB8FMKQlN1M2XnAZwwnhs8YTsx2xmyJeZr2vPV/ "Java (OpenJDK 8) – Try It Online")
Port of [G B's Python 2 answer](https://codegolf.stackexchange.com/a/149365/16236).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
FL`}){I£O
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fzSehVrPa89Bi////jbgMDQE "05AB1E – Try It Online")
**Explanation**
```
F # n times do
L` # pop top of stack (initially k), push 1 ... topOfStack
} # end loop
) # wrap stack in a list
{ # sort the list
I£ # take the first k elements
O # sum
```
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
f=lambda n,k:sum(sorted(range(1,k+1)*n)[:k])
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU8n26q4NFejOL@oJDVFoygxLz1Vw1AnW9tQUytPM9oqO1bzf0FRZl6JQhpQ2EiTC8Yx0jE0RPAMDXUMTZC4JjpGSLJGQJ1IskYmOsaGmv8B "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 38 bytes
```
lambda n,k:sum(i/n+1for i in range(k))
```
[Try it online!](https://tio.run/##FYuxDsIwEEN/JVsTYYTuyFQJfiRkCIJAVHqt0jLw9SE32X6219/@XoRbvtzaJ833RzKCady@sy0nOVBeqimmiKlJXk87OdcU9Y3CEAgcERhEXYhAXtWDNXNvNbPHmWIc11pk1y@G43VAtt269gc "Python 2 – Try It Online")
[Answer]
## Clojure, 54 bytes
```
#(nth(reductions +(for[i(rest(range))j(range %)]i))%2)
```
2nd argument `k` is 0-indexed, so `(f 14 20)` is 28.
[Answer]
# APL+WIN, 13 bytes
```
+/⎕↑(⍳n)/⍳n←⎕
```
Prompts for screen input for n and then for k. Index origin = 1.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 78 bytes
```
(({}<>)<{<>(({})<>){({}[()]<(({}))>)}{}({}[()])}{}<>{}>)({<({}[()])><>{}<>}{})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0OjutbGTtOm2sYOxNQEsquBdLSGZqwNWEDTTrO2uhYqBGLa2FXX2mlqVNvAxOxAIjZ2QCnN//9NFUwA "Brain-Flak – Try It Online")
I'm certain this can be done better, but it's a start.
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~7~~ 6 bytes
Originally inspired by [GB's solution](https://codegolf.stackexchange.com/a/149355/58974) and evolved to a port!
Takes `k` as the first input and `n` as the second.
```
õ1Vn)x
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9TFWbil4&input=MzEsMjQ=)
---
## Explanation
Implicit input of integers `U=k` & `V=n`. Generate an array of integers (`õ`) from `1` to `U` with a step of `V` negated (`n`) and reduce it by addition (`x`).
[Answer]
# [R](https://www.r-project.org/), 27 bytes
Anonymous function that takes `k` and `n` in that order. Creates a list of length `k` (third argument to `rep`) that is composed of `1` through `k` (first argument to `rep`), repeating each element `n` times (fourth argument to `rep`). Then takes the sum of that list.
`n` is 1-indexed and `k` is 0-indexed. Returns an error for `n<1`.
```
pryr::f(sum(rep(1:k,,k,n)))
```
[Try it online!](https://tio.run/##K/r/v6CossjKKk2juDRXoyi1QMPQKltHJ1snT1NT8/9/AA "R – Try It Online")
[Answer]
# Befunge, 27 Bytes
```
&::00p&:10p%+00g10g/1+*2/.@
```
[Try It Online](https://tio.run/##S0pNK81LT/3/X83KysCgQM3K0KBAVdvAIN3QIF3fUFvLSF/P4f9/Q0MFIwA)
Takes k then n as input. Uses G B's answer as its mathematical basis.
] |
[Question]
[
Write a [program or function](http://meta.codegolf.stackexchange.com/questions/2419) to **[output](http://meta.codegolf.stackexchange.com/questions/2447) the sum of [the odd square numbers (OEIS #A016754)](http://oeis.org/A016754) less than an [input](http://meta.codegolf.stackexchange.com/questions/2447) `n`**.
The first 44 numbers in the sequence are:
```
1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625, 729, 841, 961, 1089,
1225, 1369, 1521, 1681, 1849, 2025, 2209, 2401, 2601, 2809, 3025, 3249, 3481,
3721, 3969, 4225, 4489, 4761, 5041, 5329, 5625, 5929, 6241, 6561, 6889, 7225, 7569
```
The formula for the sequence is `a(n) = ( 2n + 1 ) ^ 2`.
### Notes
* Your program's behaviour may be undefined for `n < 1` (that is, all valid inputs are `>= 1`.)
### Test cases
```
1 => 0
2 => 1
9 => 1
10 => 10
9801 => 156849
9802 => 166650
10000 => 166650
```
[Answer]
# Jelly, 6 bytes
```
½Ċ|1c3
```
[Try it online!](http://jelly.tryitonline.net/#code=wr3EinwxYzM&input=&args=MTAwMDA) or [verify all test cases](http://jelly.tryitonline.net/#code=wr3EinwxYzM&input=&args=MSwgMiwgOSwgMTAsIDk4MDEsIDk4MDIsIDEwMDAw).
### Background
For all positive integers **k**, we have **1² + 3² + ⋯ + (2k - 1)² = k(2k - 1)(2k +1) ÷ 3**.
Since there are **m C r = m! ÷ ((m-r)!r!)** **r**-combinations of a set of **m** elements, the above can be calculated as **(2k + 1) C 3 = (2k + 1)2k(2k - 1) ÷ 6 = k(2k - 1)(2k + 1) ÷ 3.**
To apply the formula, we must find the highest **2k + 1** such that **(2k - 1)² < n**. Ignoring the parity for a moment, we can compute the highest **m** such that **(m - 1)² < n** as **m = ceil(srqt(n))**. To conditionally increment **m** if it is even, simply compute **m | 1** (bitwise OR with **1**).
### How it works
```
½Ċ|1c3 Main link. Argument: n
½ Compute the square root of n.
Ċ Round it up to the nearest integer.
|1 Bitwise OR with 1 to get an odd number.
c3 Compute (2k + 1) C 3 (combinations).
```
[Answer]
## JavaScript (ES6), 30 bytes
```
f=(n,i=1)=>n>i*i&&i*i+f(n,i+2)
```
31 bytes if `f(1)` needs to return zero instead of false:
```
f=(n,i=1)=>n>i*i?i*i+f(n,i+2):0
```
[Answer]
## Haskell, 30 bytes
```
f n=sum[x^2|x<-[1,3..n],x^2<n]
```
Surprisingly normal-looking.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~10~~ 8 bytes
Code:
```
<tLDÉÏnO
```
Explanation:
```
< # Decrease by 1, giving a non-inclusive range.
t # Take the square root of the implicit input.
L # Generate a list from [1 ... sqrt(input - 1)].
DÉÏ # Keep the uneven integers of the list.
n # Square them all.
O # Take the sum of the list and print implicitly.
```
Might come in handy: `t;L·<nO`.
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=PHRMRMOJw49uTw&input=OTgwMQ).
[Answer]
# C#, 126 131 bytes
Edited version to conform with the new question:
```
class P{static void Main(){int x,s=0,n=int.Parse(System.Console.ReadLine());for(x=1;x*x<n;x+=2)s+=x*x;System.Console.Write(s);}}
```
Using hardcoded limit:
```
using System;namespace F{class P{static void Main(){int x,s=0;for(x=1;x<100;x+=2)s+=x*x;Console.Write(s);Console.Read();}}}
```
[Answer]
# Jelly, 7
```
’½R²m2S
```
[Try it online](http://jelly.tryitonline.net/#code=4oCZwr1SwrJtMlM&input=&args=OTgwMQ) or try a [modified version](http://jelly.tryitonline.net/#code=4oCZwr1SwrJtMlMKw5Higqw&input=&args=WzEsIDksIDEwLCA5ODAxLCAxMDAwMF0) for multiple values
Shh... Dennis is sleeping...
Thanks to Sp3000 in chat for their help!
### Explanation:
```
’½R²m2S
’ ## Decrement to prevent off-by-one errors
½R² ## Square root, then floor and make a 1-indexed range, then square each value
m2 ## Take every other value, starting with the first
S ## sum the result
```
[Answer]
# R, ~~38~~ 36 bytes
```
function(n,x=(2*0:n+1)^2)sum(x[x<n])
```
@Giuseppe saved two bytes by moving `x` into the arguments list to save the curly braces. Cool idea!
Ungolfed
```
function(n, x = (2*(0:n) + 1)^2) # enough odd squares (actually too many)
sum(x[x < n]) # subset on those small enough
}
```
[Try it online!](https://tio.run/##LYfBCoMwEAXv@Yp33G0jJDlZiV8i9RII7MFVooH8fWpL5zDDlN4z4oBcNV2yK6ltM4WHm/TpeQ181o3a0qK@2Zi8F5BAFIm8RbB4WXh3Z3T@5/D9m38cMwxwFNGLMglz7x8 "R – Try It Online")
[Answer]
# C, ~~51, 50~~ 48 bytes
```
f(n,s,i)int*s;{for(*s=0,i=1;i*i<n;i+=2)*s+=i*i;}
```
Because why not golf in one of the most verbose languages? (Hey, at least it's not Java!)
[Try it online!](https://ideone.com/0ZOFDd)
Full ungolfed program, with test I/O:
```
int main()
{
int s;
f(10, &s);
printf("%d\n", s);
char *foobar[1];
gets(foobar);
}
f(n,s,i)int*s;{for(*s=0,i=1;i*i<n;i+=2)*s+=i*i;}
```
[Answer]
## Actually, 7 bytes
```
√K1|3@█
```
[Try it online!](http://actually.tryitonline.net/#code=4oiaSzF8M0Dilog&input=MTA)
Also for 7 bytes:
```
3,√K1|█
```
[Try it online!](http://actually.tryitonline.net/#code=MyziiJpLMXzilog&input=MTA)
This uses the same formula as in Dennis's Jelly answer.
Explanation:
```
√K1|3@█
√K push ceil(sqrt(n))
1| bitwise-OR with 1
3@█ x C 3
```
[Answer]
# Octave, 23 bytes
```
@(x)(x=1:2:(x-1)^.5)*x'
```
Testing:
```
[f(1); f(2); f(3); f(10); f(9801); f(9802); f(10000)]
ans =
0
1
1
10
156849
166650
166650
```
[Answer]
# CJam, 15 Bytes
```
qi(mq,2%:)2f#1b
```
[Try it online!](http://cjam.aditsu.net/#code=qi(mq%2C2%25%3A)2f%231b%0A&input=9801)
Hardcoded 10000 solutions:
Martin's 12 byte solution:
```
99,2%:)2f#1b
```
My original 13 byte solution:
```
50,{2*)2#}%:+
```
[Try it online!](http://cjam.aditsu.net/#code=50%2C%7B2*)2%23%7D%25%3A%2B)
[Answer]
# Pyth, 10 bytes
```
s<#Qm^hyd2
```
[Test suite](https://pyth.herokuapp.com/?code=s%3C%23Qm%5Ehyd2&test_suite=1&test_suite_input=1%0A2%0A9%0A9801%0A9802%0A10000&debug=0)
Explanation:
```
s<#Qm^hyd2
m Map over the range of input (0 ... input - 1)
yd Double the number
h Add 1
^ 2 Square it
<# Filter the resulting list on being less than
Q The input
s Add up what's left
```
[Answer]
# Mathcad, 31 "bytes"
[](https://i.stack.imgur.com/F5cUb.jpg)
Note that Mathcad uses keyboard shortcuts to enter several operators, including the definition and all programming operators. For example, ctl-] enters a while loop - it cannot be typed and can only be entered using the keyboard shortcut or from the Programming toolbar. "Bytes" are taken to be the number of keyboard operations needed to enter a Mathcad item (eg, variable name or operator).
As I have no chance of winning this competition, I thought I'd add a bit of variety with a direct formula version.
[Answer]
# Racket, 57 bytes
```
(λ(n)(for/sum([m(map sqr(range 1 n 2))]#:when(< m n))m))
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
qX^:9L)2^s
```
*EDIT (July 30, 2016): the linked code replaces `9L` by `1L` to adapt to recent changes in the language.*
[**Try it online!**](http://matl.tryitonline.net/#code=cVheOjFMKTJecw&input=OTgwMg)
```
q % Implicit input. Subtract 1
X^ % Square root
: % Inclusive range from 1 to that
9L) % Keep odd-indexed values only
2^ % Square
s % Sum of array
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-hx`](https://codegolf.meta.stackexchange.com/a/14339/), ~~6~~ 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
¬o²ó
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWh4&code=rG%2by8w&input=NTA)
```
¬o²ó :Implicit input of integer
¬ :Square root
o :Range [0,ceil(¬))
² :Square each
ó :Uninterleave
:Implicit output of sum of last element
```
[Answer]
## Python, 39 bytes
```
f=lambda n,i=1:+(i*i<n)and i*i+f(n,i+2)
```
If, for `n=1`, it's valid to output `False` rather than `0`, then we can avoid the base case conversion to get 37 bytes
```
f=lambda n,i=1:i*i<n and i*i+f(n,i+2)
```
It's strange that I haven't found a shorter way to get `0` for `i*i>=n` and nonzero otherwise. In Python 2, one still gets 39 bytes with
```
f=lambda n,i=1:~-n/i/i and i*i+f(n,i+2)
```
[Answer]
## Python 2, 38 bytes
```
s=(1-input()**.5)//2*2;print(s-s**3)/6
```
Based off [Dennis's formula](https://codegolf.stackexchange.com/a/78158/202600), with `s==-2*k`. Outputs a float. In effect, the input is square rooted, decremented, then rounded up to the next even number.
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr/), ~~33~~ ~~32~~ 26 bytes
Adapted from [Dennis' code](https://codegolf.stackexchange.com/a/78158/2605):
```
n->t=(1-n^.5)\2*2;(t-t^3)/6
```
My first idea (30 bytes), using a simple polynomial formula:
```
n->t=((n-1)^.5+1)\2;(4*t^3-t)/3
```
This is an efficient implementation, actually not very different from the ungolfed version I would write:
```
a(n)=
{
my(t=ceil(sqrtint(n-1)/2));
t*(4*t^2-1)/3;
}
```
An alternate implementation (37 bytes) which loops over each of the squares:
```
n->s=0;t=1;while(t^2<n,s+=t^2;t+=2);s
```
Another alternate solution (35 bytes) demonstrating summing without a temporary variable:
```
n->sum(k=1,((n-1)^.5+1)\2,(2*k-1)^2)
```
Yet another solution, not particularly competitive (40 bytes), using the [L2 norm](https://en.wikipedia.org/wiki/Euclidean_distance). This would be better if there was support for vectors with step-size indices. (One could imagine the syntax `n->norml2([1..((n-1)^.5+1)\2..2])` which would drop 8 bytes.)
```
n->norml2(vector(((n-1)^.5+1)\2,k,2*k-1))
```
[Answer]
## Haskell, ~~32~~ 31 bytes
```
n#x=sum[x^2+n#(x+2)|x^2<n]
(#1)
```
Usage example: `(#1) 9802` -> `166650`.
Edit: @xnor saved a byte, with a clever list comprehension. Thanks!
[Answer]
# Julia, 29 bytes
```
f(n,i=1)=i^2<n?i^2+f(n,i+2):0
```
This is a recursive function that accepts an integer and returns an integer.
We start an index at 1 and if its square is less than the input, we take the square and add the result of recusing on the index + 2, which ensures that even numbers are skipped, otherwise we return 0.
[Answer]
# Oracle SQL 11.2, 97 bytes
```
SELECT NVL(SUM(v),0)FROM(SELECT POWER((LEVEL-1)*2+1,2)v FROM DUAL CONNECT BY LEVEL<:1)WHERE v<:1;
```
[Answer]
# Julia, 26 bytes
```
x->sum((r=1:2:x-1)∩r.^2)
```
This constructs the range of all odd, positive integers below **n** and the array of the squares of the integers in that range, then computes the sum of the integers in both iterables.
[Try it online!](http://julia.tryitonline.net/#code=ZiA9IHgtPnN1bSgocj0xOjI6eC0xKeKIqXIuXjIpCgpmb3IgeCBpbiAoMSwgMiwgOSwgMTAsIDk4MDEsIDk4MDIsIDEwMDAwKQogICAgcHJpbnRsbihmKHgpKQplbmQ&input=)
[Answer]
# Reng v.3.3, 36 bytes
```
0#ci#m1ø>$a+¡n~
:m%:1,eq^c2*1+²c1+#c
```
[Try it here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/)
## Explanation
### 1: initialization
```
0#ci#m1ø
```
Sets `c` to `0` (the counter) and the input `I` to the `m`ax. `1ø` goes to the next line.
### 2: loop
```
:m%:1,eq^c2*1+²c1+#c
```
`:` duplicates the current value (the squared odd number) and [I `m` puts `m`ax down. [I used the less-than trick in another answer](https://codegolf.stackexchange.com/questions/42661/at-least-h-with-at-least-h/77097#77097), which I use here. `%:1,e` checks if the STOS < TOS. If it is, `q^` goes up and breaks out of the loop. Otherwise:
```
c2*1+²c1+#c
```
`c` puts the counter down, `2*` doubles it, `1+` adds one, and `²` squares it. `c1+#C` increments `c`, and the loop goes again.
### 3: final
```
>$a+¡n~
```
`$` drops the last value (greater than desired), `a+¡` adds until the stack's length is 1, `n~` outputs and terminates.
[Answer]
# Clojure, 53 bytes
```
#(reduce +(map(fn[x](* x x))(range 1(Math/sqrt %)2)))
```
You can check it here: <https://ideone.com/WKS4DA>
[Answer]
# Mathematica 30 bytes
```
Total[Range[1,Sqrt[#-1],2]^2]&
```
This unnamed function squares all odd numbers less than the input (`Range[1,Sqrt[#-1],2]`) and adds them.
[Answer]
# PHP, 64 bytes
```
function f($i){$a=0;for($k=-1;($k+=2)*$k<$i;$a+=$k*$k);echo $a;}
```
Expanded:
```
function f($i){
$a=0;
for($k=-1; ($k+=2)*$k<$i; $a+=$k*$k);
echo $a;
}
```
On every iteration of the `for` loop, it will add 2 to k and check if k2 is less than `$i`, if it is add k2 to `$a`.
[Answer]
# R, 60 bytes
```
function(n){i=s=0;while((2*i+1)^2<n){s=s+(2*i+1)^2;i=i+1};s}
```
Does exactly as described in challenge, including returning 0 for the n = 1 case.
Degolfed, ';' represents linebreak in R, ignored below:
```
function(n){ # Take input n
i = s = 0 # Declare integer and sum variables
while((2*i+1)^2 < n) # While the odd square is less than n
s = s + (2*i+1)^2 # Increase sum by odd square
i = i + 1 # Increase i by 1
s} # Return sum, end function expression
```
[Answer]
# Java 8, ~~128~~ ~~119~~ ~~117~~ ~~111~~ 49 bytes
```
n->{int s=0,i=1;for(;i*i<n;i+=2)s+=i*i;return s;}
```
Based on [*@Thomas*' C# solution](https://codegolf.stackexchange.com/a/78142/52210).
**Explanation:**
[Try it online.](https://tio.run/##hVDBDoIwDL37FT1uKgQ4aeb8A71wNB7mnKYIhWzDxBC@HYd6NWvaJu17eX1ppZ4qaTtD1fUx6Vo5BweFNCwAkLyxN6UNHOfxswDN5k5chM0YKqTzyqOGIxBImCjZDzPFyWyNMhe31jKBS9yRwJUsuFvJMAlrfG8JnBgn8ZXp@ksdZH5qzxav0AQnrPQW6X46K/51Ub6cN03a9j7tAuJrYpRqlvOPp794EcG3ETzPYgKbLI9TiuiZEPz33nF6Aw)
```
n->{ // Method with integer as both parameter and return-type
int s=0, // Sum, starting at 0
i=1; // Index-integer, starting at 1
for(;i*i<n; // Loop as long as the square of `i` is smaller than the input
i+=2) // After every iteration, increase `i` by 2
s+=i*i; // Increase the sum by the square of `i`
return s;} // Return the result-sum
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `sm`, 5 bytes
```
~∷~∆²
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBc20iLCIiLCJ+4oi3fuKIhsKyIiwiIiwiMVxuMlxuOVxuMTBcbjk4MDFcbjk4MDJcbjEwMDAwIl0=)
```
~ # range 1..n-1 (due to m flag) filtered by
∷ # is odd
~ # filtered by
∆² # is a perfect square
# sum is taken by s flag
```
] |
[Question]
[
## Definition (from Wikipedia)
**A Pythagorean triple consists of three positive integers a, b, and c, such that a² + b² = c².**
The typical example of a Pythagorean triple is (3,4,5): 3² + 4² = 9 + 16 = 25 which is 5²
## Task:
Given an integer number `c`, write a program or function that returns the list of pythagorean triples where `c` is the hypotenuse.
The triples do not need to be primitive.
For example: if c=10, the answer will be `[[6,8,10]]`
## Input:
An integer number, the hypotenuse of the possible triples
## Output:
A list of triples, eventually empty. Order is not important, but the list must be duplicate-free ([3,4,5] and [4,3,5] are the same triple, only one must be listed)
Test cases:
```
5 -> [[3,4,5]]
7 -> [] # Empty
13 -> [[5,12,13]]
25 -> [[7,24,25],[15,20,25]]
65 -> [[16,63,65],[25,60,65],[33,56,65],[39,52,65]]
1105 -> [[47,1104,1105],[105,1100,1105],[169,1092,1105],[264,1073,1105],[272,1071,1105],[425,1020,1105],[468,1001,1105],[520,975,1105],[561,952,1105],[576,943,1105],[663,884,1105],[700,855,1105],[744,817,1105]]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest entry for each language wins.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~11~~ 10 bytes
```
ɾ2ḋvp'²ḣ∑=
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C9%BE2%E1%B8%8Bvp%27%C2%B2%E1%B8%A3%E2%88%91%3D&inputs=25&header=&footer=)
*-1 byte thanks to @lyxal*
Thanks for the offer @lyxal, but nah, I don't need flags.
```
ɾ2ḋvp'²ḣ∑= Full program, input: n, the hypotenuse
ɾ 1..n
2ḋ All pairs (2-combinations) without replacement
vp Prepend n to each pair
' Filter those which satisfy...
² Square each number
ḣ∑= Does the sum of last two equal the first?
```
---
# [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes
```
ɾ:Ẋ's=*²∑⁰²=;vJ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C9%BE%3A%E1%BA%8A%27s%3D*%C2%B2%E2%88%91%E2%81%B0%C2%B2%3D%3BvJ&inputs=25&header=&footer=)
Kinda port of my own [Jelly answer](https://codegolf.stackexchange.com/a/236382/78410), using filter instead of "truthy n-D indices".
```
ɾ:Ẋ's=*²∑⁰²=;vJ Full program, input: n, the hypotenuse
ɾ:Ẋ All pairs between 1..n and 1..n
' ; Filter the pairs where...
s=* it is sorted and
²∑⁰²= the sum of square is equal to n squared
vJ Append n to each pair
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), ~~41~~ ~~40~~ 39 bytes
```
Solve[a^2+b^2==c#>c==#>b>a>0,Integers]&
```
-1 byte from ovs
-1 byte from att
`Integers` restricts it to integers; `>0` restricts it to positive integers; and `b>a` removes the duplicates. `c#` is c^2; `c==#` adds the input to each solution set (as required by the OP).
Alternately (also 39 bytes):
```
Solve[Norm@{a,b}==c==#>b>a>0,Integers]&
```
Here's a more verbose version that's similar to the first approach:
```
Solve[{a^2+b^2==#^2,c==#,b>a>0},Integers]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277Pzg/pyw1OjHOSDspzsjWNlnZLtnWVtkuyS7RzkDHM68kNT21qDhW7X9AUWZeiUN6tGksF4xpjmAaGiPYRkhKzJDYhoYGprH/AQ)
[Answer]
# Excel, ~~100~~ ~~93~~ 90 bytes
```
=LET(a,SEQUENCE(A1),b,TRANSPOSE(a),CONCAT(IF((a<b)*(a^2+b^2)-A1^2,"",a&","&b&","&A1&"
")))
```
Input is in A1. Triples are delimited by a comma and each triple is separated by a new line with a trailing new line. The `LET()` and `SEQUENCE()` functions are only available in certain versions of Excel.
[](https://i.stack.imgur.com/NTCze.png) [](https://i.stack.imgur.com/LOxaz.png)
`LET()` allows us to define variables and reference them later. This goes a long way towards saving bytes. The final parameter doesn't define a variable and instead is the output result.
`a,SEQUENCE(c)` creates a 1D array of numbers from 1 to the input.
`b,TRANSPOSE(a)` creates the same array as `a` except transposed. This lets us work with a matrix of `a`x`b` so we can evaluate all possible combinations of integers less than or equal to the input.
```
CONCAT(IF((a>b)*(a^2+b^2)-A1^2,"",a&","&b&","&A1&"
"))
```
This is where all the calculation and concatenation happens so I'll break it into pieces.
`(a>b)*(a^2+b^2)-A1^2` does the math bit to check if it's a triple and, thanks to `(a>b)`, ignores half the results so we don't have duplicates. You cannot have a Pythagorean triple where `a=b` so this is an OK filter. We can use `(~)-A1^2` instead of `(~)<>A1^2` since Excel will interpret 0 as False and any non-zero number as True.
`a&","&b&","&A1&"\n"` (where `\n` is a literal line break in the original formula) creates a text string in the format `a,b,A1` with a trailing new line. These are the results that show up at the end.
`CONCAT(IF(~,"",~))` combines all the results into one big string. Those results are either triples with a trailing new line or blank text. This is what creates the final output.
[Answer]
# [Haskell](https://www.haskell.org/), 46 bytes
```
f c=[[a,b,c]|a<-[1..c],b<-[a..c],a*a+b*b==c*c]
```
[Try it online!](https://tio.run/##PY/NboMwEITveYoV6gHCNvK/oSpv0J56dKzKUFCqJjRqUjWR8u7UxsEc0Dc7M8uyc6evfr@fpgG6xhiHLXb25p4fDd1sOoutJzeTW7uyXbdN0607Ox3c5wgNHNzx9R2Ov@e388/LCCYbcsjKMj/tvv/gUkBZQgYFPG3HLPA8fxgWZzv2l2PfnfuPJTD3rnczg1t@wWvhT1hBLgHBGI4CpbUF@okOEwvhKRDATyifQxIpQ8rvMRabGplAJi0aKpGRgNFX0acKFUcVAkyiIhE5R6nuWKNkAWONUhKLQqNnEV7zdiIDkqRVjZTUbNFM@SjRPGnNgqaLFv7rlLDUF6rymiRfeqvWMklFsZZpu9QKa5GWK/9LVZVu0/6sSqauFgIrqqO0hbWr6R8 "Haskell – Try It Online")
* List comprehension made of all combinations *a<-[1..c],b<-[a..c]* with our Pythagorean condition as guard.
We add `c` to the pair yelded.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~67 65~~ 53 bytes
```
->c{c.times{|a|a.times{|b|p [b,a,c]if a*a+b*b==c*c}}}
```
[Try it online!](https://tio.run/##ZY/BbsMgEETv/goU39xtxAIL5uDe@hWIA0aNFCmRrMQ5RLG/3YU65uByQPM0s8Nye/TP5dQtn1/xFY/j@fpzf01hCpvsp4G5HgJEfz6x0ISPvum7LjZxnuelOh1juFwYMcZq5pwEBeR9NTzG@@GwuWZ1PSunZt/XYXzucijXFgIUgPJfj6DVNyAUCPLgkEDwLPdR/Y6iBi1B56wg0HyVUgLpt7RAIst9AyInVjunDCSp8vX3IqcseWFtAbkVGwudotzIwkZkxo1VWgO5KPNKt4l58SlZ1lBBjWCptJPRYFUp1@lvbVt2M2mtlsqsUQpaNCv6avkF "Ruby – Try It Online")
* Thanks to @Dingus suggestion to print directly instead of yielding to a return array.
* Switched to a double *#times* structure surprisingly better than *#combination*.
```
r=[] - return array
[*1..c].combination(2) - combinations of 1..input , since a,b are coprime we don't need a==b
{|a,b|r<<[a,b,c] - we add to r the pair yelded with input attached to it
if a*a+b*b==c*c} - if it's a valid triangle
;r} - finally we return r
```
[Answer]
# [R](https://www.r-project.org/), ~~71~~ 65 bytes
```
y=x=scan();while(y<-y-1)(z=(x^2-y^2)^.5)%%1||z>y&&print(c(x,y,z))
```
[Try it online!](https://tio.run/##K/r/v9K2wrY4OTFPQ9O6PCMzJ1Wj0ka3UtdQU6PKVqMizki3Ms5IM07PVFNV1bCmpsquUk2toCgzr0QjWaNCp1KnSlPzv5HpfwA "R – Try It Online")
---
Or **[R](https://www.r-project.org/) >4.1** using recursive function: **64 bytes**
(thanks to pajonk for pointing-this out!)
```
t=\(x,y=1,z=(x^2-y^2)^.5)if(z>y){z%%1||print(c(x,y,z));t(x,y+1)}
```
[Try it online!](https://tio.run/##K/pfUpRZkJNabPu/xDatNC@5JDM/T6NCp9LWUKfKVqMizki3Ms5IM07PVDMzTaPKrlKzukpV1bCmpqAoM69EIxmkVKdKU9O6BMTSNtSshRmoYarJlZxYoqGkrKwck6ekyQUTN8chbmiMQ8LIVPM/AA "R – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~53~~ 50 bytes
```
rbind(x<-scan(),p<-combn(x,2))[,colSums(p^2)==x^2]
```
[Try it online!](https://tio.run/##K/r/vygpMy9Fo8JGtzg5MU9DU6fARjc5PzcpT6NCx0hTM1onOT8nuDS3WKMgzkjT1rYizij2v5HpfwA "R – Try It Online")
Thanks to Dominic van Essen and pajonk in the comments for some golf ideas; and thanks to Dominic van Essen and thothal for -3 bytes together.
Returns a (possibly empty) matrix with triples as columns.
Equivalent to (among others) [ovs' Gaia answer](https://codegolf.stackexchange.com/a/236401/67312).
```
x=scan() # read input
pairs=combn(1:x,2) # pairwise combinations of 1..x, as columns of a matrix
triple <- colSums(pairs^2)==x^2 # is it a triple?
rbind(pairs,x)[,triple] # add a row of x's and filter the columns by the triple condition
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~68~~ ~~67~~ 65 bytes
```
lambda c:[(a,b,c)for a in range(1,c)if(b:=(c*c-a*a)**.5)==b//1>a]
```
[Try it online!](https://tio.run/##FcvBDsIgDADQX@FYSHXWpWpI8EfmDgVFmygjZBe/Ht31Ja9@19dSxkttPYdbf8sn3sUkP4FgxGTz0owYLaZJeT6A/qQZog@QXNqJE@vcnm0IcRjoKnPfgm5hYjwjjXhkPDESHXj2tWlZIYNa238 "Python 3.8 (pre-release) – Try It Online")
-1 by observing that `a` and `b` are never equal in a Pythagorean triple.
-2 thanks to G B, by squaring by self-multiplying.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 55 bytes
Prints the triples.
```
n=>{for(q=n;p=--q;)for(;--p;)p*p+q*q-n*n||print(p,q,n)}
```
[Try it online!](https://tio.run/##TYuxDoIwFEV3v6KDQ4uvRDRVk6ZsfgUhoSGiEPL6CoQF@u21bi4nOSf3Dna1czv1tMj1ETsT0ZRb5ybuDWoyUnotfqqlJC0oo5PPvMQM952mHhdO4AFFiJWCOxRXuCi4KSiKs6oPeXo@bfvhyEzJNtY6nN34ykf35k2VIjtuGOpGaNZxTPwfJA0ifgE "JavaScript (V8) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~20~~ ~~18~~ 16 bytes
```
^₂~+Ċ√ᵐℕ₁ᵐ≤₁,?ẉ⊥
```
Outputs one triple per line. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P@5RU1Od9pGuRx2zHm6d8Khl6qOmRhCjcwmQoWP/cFfno66l//@bmQIA "Brachylog – Try It Online")
### Explanation
```
^₂~+Ċ√ᵐℕ₁ᵐ≤₁,?ẉ⊥
^₂ The input number squared
~+ is the sum of
Ċ a list of two elements
√ᵐ Get the square root of each element
ℕ₁ᵐ Each of those must be a natural number greater than or equal to 1
≤₁ and they must be sorted in ascending order
,? Append the original input to that list
ẉ and output it with a trailing newline
⊥ Fail unconditionally, forcing Brachylog to backtrack and find
the next output
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 38 bytes
```
{,∘⍵¨k[⍸(⍵*2)=+/¨2*⍨k←∪,{⍵[⍋⍵]}¨⍳⍵ ⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/WudRx4xHvVsPrciOftS7QwPI1DLStNXWP7TCSOtR74rsR20THnWs0qkGSgAVdAOp2NpDKx71bgayFMC8/2lANVQwh@tR31SgqjQFI9P/AA "APL (Dyalog Classic) – Try It Online")
-10 thanks to @ovs!!!!
dfn, takes the hypotenuse on right
[Answer]
# [Alchemist](https://github.com/bforte/Alchemist), 179 bytes
```
_->In_n+f
f+n->f+b+c+m
f+0n->j
j+a->j+d+x
j+m+0a->k+d
k+d->k+a+x
k+0d->i
0q+b+x->e
0q+0b+e+m->q
q+e+x->q+b
q+0e->
i+0x+0e->j+Out_a+Out_" "+Out_b+Out_" "+Out_c+Out_"\n"
i+0x+e->j+e
```
[Try it online!](https://tio.run/##VYvBCsMgEETvfkXJdRCWll6999QfKAQ1hsZUQZqCf28m5tTD7r43y9iPf4e0fLfWRm0eecyY1YyszQwHj0QRWlQRlgcTKjFBaCsmxTnAMl4h5EVJYbVqEw4Sh4CkTVGFwJRPogRt1AKpnSKev220fQ@XoV/3Z/60Vx7OVi@F1m7X@w4 "Alchemist – Try It Online")
`a`, `d`, `i`, `j`, and `k` define a source of `x`, while `b`, `e`, and `q` define a sink for `x`. `m` is equal to \$b - a\$ where relevant, and the program halts when it reaches zero to avoid duplicating triples.
### Initialization
```
_->In_n+f
f+n->f+b+c+m
f+0n->j
```
Simply sets `b`, `c`, and `m` to the input, puts the sink in state `j`, and puts the source in state `0q`.
### Source
```
j+a->j+d+x
j+m+0a->k+d
k+d->k+a+x
k+0d->i
```
When the source is in state `j`, this adds \$2a+1\$ `x` atoms while incrementing \$a\$ (using up an `m`), then returns to state `i`. Whenever the source is in state `i`, it has provided a total of \$a^2\$ `x` atoms.
### Sink
```
0q+b+x->e
0q+0b+e+m->q
q+e+x->q+b
q+0e->
```
Similar to the source, but without a special `i` state. The source starts in state `0q`, and in each cycle, it uses up \$2b-1\$ `x` atoms, decrements \$b\$, and uses up an `m`. While there is no special state to denote whether the number of atoms taken is equal to \$c^2 - b^2\$, the condition `e=0` will work.
### Output
The source waits for there to be no more `x` atoms before starting another cycle; without this check, it could pass every triple without detecting them. This is the purpose of the `i` state.
```
i+0x+0e->j+Out_a+Out_" "+Out_b+Out_" "+Out_c+Out_"\n"
i+0x+e->j+e
```
When there are no more `x` atoms in the `i` state, we check whether we are actually at a triple. If we are, output the triple. Either way, move the source to the `j` state without changing anything else.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 28 bytes
```
{+x,+(x=%+/*/2#,+:)#+&~|\=x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6rWrtDR1qiwVdXW19I3UtbRttJU1larq4mxrajl4kpTN1UwVzA0VjAyVTA0NDDlwgAA6k0LqQ==)
It uses the indices of ones in an upper triangular matrix for creating all possible (a,b) pairs, then filters them based on the pythagorean condition. Prepends the hipotenuse for each pair found.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes
```
ŒcÆḊ=¥Ƈ;€
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//xZJjw4bhuIo9wqXGhzvigqz///82NQ "Jelly – Try It Online")
Backport of my improved [Vyxal answer](https://codegolf.stackexchange.com/a/236384/78410) to use pairs without replacement. -1 byte because I just realized there's a 2-byte norm built-in that saves a square. Passes all small test cases and moderately large ones (like 850) but 1105 times out, and might not work for larger inputs due to floating-point errors.
### How it works
```
ŒcÆḊ=¥Ƈ;€ Monadic link; Input = n, the hypotenuse
Œc Pairs of 1..n without replacement
ÆḊ=¥Ƈ Filter those whose norm (sqrt of self-dot-product) equals n
;€ Append n to each pair
```
---
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
R²+²)=²ŒṪ;€
```
[Try it online!](https://tio.run/##AR8A4P9qZWxsef//UsKyK8KyKT3CssWS4bmqO@KCrP///zI1 "Jelly – Try It Online")
### How it works
```
R²+²)=²ŒṪ;€ Monadic link; Input = n, the hypotenuse
) For each number i of 1..n,
R²+² collect the values of j^2+i^2 for j in 1..i
=²ŒṪ Coordinates (i,j) where j^2+i^2 = n^2
(only gives the coordinates where i>j)
;€ Append n to each pair
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 35 bytes
```
{⍵,⍨¨{⍵↑⍨2÷⍨≢⍵}⍸(⍵*2)=+/¨2*⍨∘.,⍨⍳⍵}
```
Calculates every combination of a^2 + b^2 and stores the values which add up to c^2
[Try it Online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHvVp1HvSsOrQCxHrVNBLKNDm8Hko86FwFFah/17tAA0lpGmrba@odWGGmBpDpm6IE0PerdDFLyP03hUdsEBSoZZcqVpmAOxIbGQMIIxDMDEYaGBqYA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~18~~ 17 bytes
```
²Ṅ'Ḣ₃;'∆²A;:[√⌊vJ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C2%B2%E1%B9%84%27%E1%B8%A2%E2%82%83%3B%27%E2%88%86%C2%B2A%3B%3A%5B%E2%88%9A%E2%8C%8AvJ&inputs=7&header=&footer=)
It times out for inputs greater than 7, but the algorithm works. I can't wait to be outgolfed by anyone with greater mathematical knowledge lol ;p
*-1 thanks to @EmanresuA and their tip from [here](https://codegolf.stackexchange.com/a/235486/78850)*
## Explained
```
²Ṅ'Ḣ₃;'∆²A;:[√⌊vJ
²Ṅ # from all the integer partitions of the input squared,
'Ḣ₃; # only keep those where the length is 2. And from those,
'∆²A; # only keep those where all numbers are perfect squares.
:[ # If that isn't empty,
√⌊vJ # get the square root of each item, and append the hypotenuse to each sublist.
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 57 bytes
```
n=>(g=i=>(j=(n*n-++i*i)**.5)>i&&g(i,j%1||print(i,j,n)))``
```
[Try it online!](https://tio.run/##FYdBDoIwEADvvmIvQrcUYjWoiSk3X6EmECK4hGxJabiIb6/lMJOZoVmauXU0@Xy5hs4ENpXoDUUPRrDkPMtIEkpZlFhRkvSC1LDX6zo5Yr@NYkSs6@DBwKNUcFGgTwqOMc8RrQ/la@eLzrp7034Eg6ngC63l2Y7vYrS9SJ@cQgaMN@jE5h@GPw "JavaScript (V8) – Try It Online")
A quite straightforward approach.
[Answer]
# APL+WIN, 42 Bytes
Prompts for hypotenuse:
```
(((c*2)=+/¨n*2)/n←(,m∘.<m)/,m∘.,m←⍳c),¨c←⎕
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv4aGRrKWkaattv6hFXlAhn4eUE5DJ/dRxww9m1xNfQgLSLZNeNS7OVlT59CKZBC7b@p/oH6u/2lcplxpXOZAbGgMJIxAPDMQYWhoYAoA "APL (Dyalog Classic) – Try It Online")
[Answer]
# Java, 91 bytes
```
c->{for(int i=c,j;--i>0;)for(j=i;--j>0;)if(i*i+j*j==c*c)System.out.println(j+" "+i+" "+c);}
```
[Try it online!](https://tio.run/##bVA9b4QwDJ3Lr7CY@CjoaNVWKuKWTh063Vh1SH3k5BQCIgapOvHbacIh6IAH6z079nuOEoNI1PlnorptOgZledozVansNTI1Oo1yr@2/K0LAShgDH4I0XD2w0XY0CC7BsGDbl6RFBe@a3xpt@rrsQBYTJserbLqANAMVeK/yJKHjIQ9dURVkqXKUZEARxSpSRYERhqdfw2WdNj2nVkZzpQMV@@DHNGcM83HKby5u7hYTQ0NnqK3H4MR27vL5BaK7mHCx7IJLw8FTmHt3M3pZUfa4woet/7zBLDs44paM3t4XzOrzU3cvhpvozj0IMfiv/rLQhUwFYtlygP@KO5Orh3H6Aw)
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 12 bytes
```
s¦e⁻+
┅r+¦↑⁈
```
[Try it online!](https://tio.run/##ASAA3/9nYWlh//9zwqZl4oG7KwrilIVyK8Km4oaR4oGI//82NQ "Gaia – Try It Online")
```
s¦e⁻+ -- helper function; check whether 3 numbers form a pythagorean triple
s¦ -- square each number -> [a^2 b^2 c^2]
e -- dump all values on the stack -> a^2 b^2 c^2
⁻+ -- subtract and add -> a^2+(b^2-c^2)
┅ -- range from 1 to input
r -- all pairs of values from this list
+¦ -- append the input to each pair
↑⁈ -- Reject; Only keep elements where the above function returns 0
```
[Answer]
# TI-Basic, 34 bytes
```
Prompt C
For(A,1,C/√(2
√(C²-A²
If not(fPart(Ans
Disp {A,Ans,C
End
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~99~~ \$\cdots\$ ~~75~~ 74 bytes
```
a;b;f(c){for(b=c;a=--b;)for(;--a;)c*c-b*b-a*a||printf("%d,%d,%d ",a,b,c);}
```
[Try it online!](https://tio.run/##dZThbpswEMe/5ykspEpAjArGNlAv2odpT9FEFTjQodC0SiItWsqrLztjcBzqRSE53/18d/8DIyPZlfvX67UUlWh8GVya94NfraQoV1FUiUAtRRSVIpChjKqwisqw/Pz8OLT7U@N7D1s8fJGHS1xhGYj@ChH0VrZ7P0CXBYKPcpzq4@n4vEErdGEYJTFcKUYEbK7WScx6YeD6/FHLU719SfQOIClGToJoguMcJ7ELSG9FiSrqYqhmMmiI6qYSuEisbBfPNJ9w6D7VCgYlsbZT8DE@2gXYRNmuRFwnotkwAqoHocajZxIbBy@UtyCTg3AFx1lqHBkZHMnkoIOMmJgclOfKERuCqViRMbPmECqYqcEy0FBQU4IrrXluusxUfzkz@zMKoTzJ5rczNHq12tvdxdZ9tOzUsqllM8vmjnF2Ov@x/VO/N/6tTPA4ukLLh@cYcWAkwGjOpQ4udXDUwdGvZZkDY4503MHxYJyC/FUeQvit5a4@6Cl46/NPsj4XP@BiHkb2OvXGfXC6ka9G2O639Rm2xWI0v80b@Fo@EGi5HOjpoJvDDpn0gR/CG2Gi5r0R5dsneGmgU3ALNr690k8OZDJPzzyZKtVZQPffcuv9xEBRu@Kkf6e170B3B3/LVWpruh/VOCZA02ECc/JO5/FhCyrb7x72njyw6ufdst1YLahPv3Dtveu0d2ia4v2iv/6VTVe@Hq/R738 "C (clang) – Try It Online")
*Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
Inputs integer \$c\$ and outputs all unique Pythagorean triples with hypotenuse \$c\$. The side lengths are separated by commas and the Pythagorean triples separated by spaces.
[Answer]
# Kotlin, 83 bytes
`fun x(c:Int){for(i in 1..c)for(j in 1..i)if(i*i+j*j==c*c)print("[${j} ${i} ${c}]")}`
[Try it online!](https://tio.run/##y84vycnM@59WmqeQm5iZp5FYlF5s5VhUlFhpE1xSlJmXbqdZDZat0Ei28swr0axOyy/SyFTIzFMw1NNL1gTxsqC8TM3MNI1MrUztLK0sW9tkrWTNAqAJJRpK0SrVWbUKKtWZICK5NlZJs/Z/hYahoYGppjVX7X8A "Kotlin – Try It Online")
[Answer]
# [Raku](http://raku.org/), 45 bytes
```
{grep *²+*²==*²,flat .&combinations(2)X$_}
```
[Try it online!](https://tio.run/##DcTNCYAgAAbQVT4ipD@ECuuSzdEtLDKESlEvES3VCC1mHd4zi92asJ8gEjxcq10MsvfJf5z/FXITHpTMep/UIbzSh0uqdIjHOzhxIopH8B4XJZKuyvk7gtQWHUOLskbF0LA@fA "Perl 6 – Try It Online")
* `$_` is the hypotenese length, the argument to the function.
* `.&combinations(2)` is a list of all two-element combinations of the list of integers from zero to one less than the hypoteneuse. These are the possible triangle leg lengths. (The unusual syntax `.&` means to call the global function named `combinations`, passing `$_` as the first parameter. It saves a few bytes here.)
* `X $_` pastes the hypoteneuse onto the end of each combination using the cross-product operator `X`.
* `flat` flattens the list.
* `*² + *² == *²` is an anonymous function that returns true if the sum of the squares of its first two arguments is equal to the square of the third argument.
* `grep` consumes three elements at a time from the flattened list of side lengths (since its test function takes three arguments) and returns the triples that describe a right triangle.
[Answer]
# [Swift](https://swift.org/), 87 bytes
```
let p={n in(1...n).reduce(into:[]){for j in $1...n{if $1*$1+j*j==n*n{$0+=[[$1,j,n]]}}}}
```
Using the `reduce` instead of the outer `for` loop to save the bytes needed to declare the result variable, and to return it.
[Try it online!](https://tio.run/##HYvLCoAgFAV/xYULX0gXahP4JeKqFJS4iRktpG836awGZs71xFDn3g9fSTYNSUQGWmvkuvj93jyLWM/VOt7CWUgantA/aDEMEhRkEskYFNjoJI21FFRS6Nw71nMZf5YZwLRw3j8 "Swift – Try It Online")
[Answer]
# Excel, 86 bytes
```
=LET(a,SEQUENCE(A1/2^0.5),b,(A1^2-a^2)^0.5,CONCAT(IF(MOD(b,1),"",a&","&b&","&A1&"
")))
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnQE2CBwPRxunPfHc?e=iLvX1g)
a equals the sequence of numbers up to the hypotenuse / \$\sqrt2\$.
b equals the list of numbers that makes a Pythagorean triple with the corresponding number in a.
If mod(b,1) = 0 then return the triple otherwise return blank.
[Answer]
# [Julia](https://julialang.org), 48 bytes
```
~c=[[a,b,c] for b=1:c for a=1:b if a^2+b^2==c^2]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjcN6pJto6MTdZJ0kmMV0vKLFJJsDa2SwaxEICtJITNNITHOSDspzsjWNjnOKBaqz9qhOCO_XKHOlAvKMIcxDI1hLCO4pBmcZWhoYAoxAuYEAA)
Another variation turns out to be a byte longer:
```
~c=[[a,b,c] for b=1:c,a=1:c if a<b&&a^2+b^2==c^2]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes
```
Cases[Range@#~Subsets~{2},x_/;x.x==#^2:>{x,#}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@985sTi1ODooMS891UG5Lrg0qTi1pLiu2qhWpyJe37pCr8LWVjnOyMquukJHuTZW7X9AUWZeSbSyjoKSgq6dgpKOQlq0cmysmoK@g0K1qY6CuY6CobGOghGQaQbEhoYGprX/AQ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 22 bytes
```
ɾ:vɾZƛ÷v";f2ẇ'²∑⁰²=;vJ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C9%BE%3Av%C9%BEZ%C6%9B%C3%B7v%22%3Bf2%E1%BA%87%27%C2%B2%E2%88%91%E2%81%B0%C2%B2%3D%3BvJ&inputs=5&header=&footer=)
What a horrible mess. I'm sure there's so many shorter ways of doing this...
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
L2.ÆʒnOInQ}εIª
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fx0jvcNupSXn@nnmBtee2eh5a9f@/kSkA "05AB1E – Try It Online")
Second solution, just replace some boilerplate with sleek `2.Æ` (pairs without replacement), also this one is both the shortest and fastest among three
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes (Thanks to @ovs)
```
Lã€{ÙʒnOtQ}εIª
```
[Try it online!](https://tio.run/##ASEA3v9vc2FiaWX//0zDo@KCrHvDmcqSbk90UX3OtUnCqv//MjU "05AB1E – Try It Online")
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
nÅœ2ùʒŲP}tεIª
```
[Try it online!](https://tio.run/##ASEA3v9vc2FiaWX//27DhcWTMsO5ypLDhcKyUH10zrVJwqr//zU "05AB1E – Try It Online")
This is slower, but 2 bytes shorter.
```
n # square
Ŝ # integer partitions
2ù # keep length 2s
ʒ # filter by
Ų # perfect square?
P # product
} # end filter
t # root
ε # foreach
I # input
ª # tuck
```
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
LDâ€{ÙʒnOInQ}εIª
```
[Try it online!](https://tio.run/##ASMA3P9vc2FiaWX//0xEw6Ligqx7w5nKkm5PSW5Rfc61ScKq//8yNQ "05AB1E – Try It Online")
The most obvious approach
```
L # 1..n
D # dup
â # cartesian product
€ # vectorize
{ # sort
Ù # nub
ʒ # filter by
n # square each
O # sum
I # input
n # squared
Q # equals?
} # end filter
ε # foreach
I # input
ª # append
```
] |
[Question]
[
Similar to [this](https://codegolf.stackexchange.com/q/5105/3862), [this](https://codegolf.stackexchange.com/q/132/3862), and [this](https://codegolf.stackexchange.com/q/173/3862) question...
What general tips do you have for golfing in `VBA`? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to `VBA` (e.g. "remove comments" is not an answer). Please post one tip per answer.
While I have worked with other languages, I'm strongest in `VBA`, and I don't see many golfers using `VBA` on this site.
[Answer]
# Exploit the `ByRef` default when calling subs
It is sometimes possible to use a `Sub` call in place of a `Function` to save a few additional characters...
This (**87** chars)
```
Sub a()
b = 0
Do Until b = 5
b = c(b)
Loop
End Sub
Function c(d)
c = d + 1
End Function
```
can be re-worked to (**73** chars):
```
Sub a()
b = 0
Do Until b = 5
c b
Loop
End Sub
Sub c(d)
d = d + 1
End Sub
```
*Notice this will **NOT** loop forever, though it appears you are never reassigning `b`'s value.*
The above doesn't use a `Function` call, but instead exploits the `ByRef` ("By Reference") functionality of the `Sub` call. What this means is the passed argument is the same variable as in the calling function (as opposed to a `ByVal`, "By Value" passing, which is a copy). Any modifications to the passed variable will translate back to the calling function.
By default, [vba](/questions/tagged/vba "show questions tagged 'vba'") takes all arguments as `ByRef`, so there is no need to use up characters to define this.
The above example may not translate perfectly for you, depending on the return value of your function. (i.e. returning a different data type than what is passed), but this also allows for the possibility of getting a return value whilst still modifying your original variable.
For example:
```
Sub a()
b = 0
Debug.Print c(b) ' This will print 0, and b will equal 1.'
End Sub
Function c(d)
c = d
d = d + 1
End Function
```
[Answer]
## Write and run the VBA code in the Immediate Window
The Immediate Window evaluates any valid VBA executable statement. Simply enter a statement in the Immediate Window as you would in the code editor. It quickly executes VBA code and it can save many additional characters because:
1. Putting the question mark (?) at the beginning of the statement tells the Immediate Window to display the result of your code.
[](https://i.stack.imgur.com/BhZeH.gif)
2. You don't need to use a Sub and End Sub in your code.
[](https://i.stack.imgur.com/uSMM9.gif)
---
Here is the example of VBA code in the Immediate Window to answer PPCG's post with tag [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") : [The Letter A without A](https://codegolf.stackexchange.com/q/90349/58742)
```
?Chr(88-23);
```
answered by [Joffan](https://codegolf.stackexchange.com/a/90418/58742).
---
**Credit images:** [Excel Campus](https://www.excelcampus.com/)
[Answer]
## Conditional Checks Before Looping
Some conditional checks are redundant when used in conjunction with loops. For example, a `For` loop will not process if the starting condition is outside the scope of the running condition.
In other words, this (**49** chars):
```
If B > 0 Then
For C = A To A + B
'...
Next
End If
```
Can be turned into this (**24** chars):
```
For C = A To A + B ' if B is 0 or less, then the code continues past Next, unabated.
'...
Next
```
[Answer]
# `Evaluate()` And `[]`
As has been pointed out previously, hard-coded range calls can be reduced using the square brackets `[A1]` notation. However it has many more uses than just that.
According to [MSDN documentation](https://msdn.microsoft.com/VBA/Excel-VBA/articles/application-evaluate-method-excel), the `Application.Evaluate()` method takes a single argument, which is a `Name`, as defined by the naming convention of Microsoft Excel.
N.B. `[string]` is shorthand for `Evaluate("string")` (note the `""` speech marks denoting string datatype), although there are a few important differences which are covered at the end.
So what does that all mean in terms of usage?
Essentially, `[some cell formula here]` represents a cell in an excel worksheet, and you can put pretty much anything into it and get anything out of it that you could with a normal cell
## What goes in
In summary, with examples
* A1-style references. All references are considered to be absolute references.
+ `[B7]` returns a reference to that cell
+ As references are absolute, `?[B7].Address` returns `"B$7$"`
* Ranges You can use the range, intersect, and union operators (colon,
space, and comma, respectively) with references.
+ `[A1:B5]` returns a range reference to `A1:B5` (Range)
+ `[A1:B5 A3:D7]` returns a range reference to `A3:B5` (Intersect)
+ `[A1:B5,C1:D5]` returns a range reference to `A1:D5`(technically `A1:B5,C1:D5`) (Union)
* Defined names
+ User defined such as `[myRange]` referring to A1:G5
+ Automatic, like table names `[Table1]` (possibly less useful for codegolf)
+ Anything else you can find in the `[Formulas]`>`[Name Manager]` menu
* Formulas
+ **Very useful**; any formula that can go in a cell can go in `Evaluate()` or `[]`
+ `[SUM(1,A1:B5,myRange)]` returns arithmetic sum of values in the ranges *myRange here refers to a workbook name not a VBA variable*
+ `[IF(A1=1,"true","false")]` (1 byte shorter than vba equivalent `Iif([A1]=1,"true","false")`)
+ Array formulas`[CONCAT(IF(LEN(A1:B7)>2,A1:B7&" ",""))]` - joins all strings in range whose length is greater than 2 with a space
* External references
+ You can use the `!` operator to refer to a cell or
to a name defined in another workbook
+ `[[BOOK1]Sheet1!A1]` returns a range reference to A1 in BOOK1 or `['[MY WORKBOOK.XLSM]Sheet1!'A1]` for the same in `MY WORKBOOK`
+ Note the `'` for workbooks with spaces in their names, and the lack of extension for default named workbooks (`BOOK+n`)
* Chart Objects (See the MSDN article)
NB I asked a question over on SO for this info, so take a look [there](https://stackoverflow.com/q/45443323/6609896) for a better explanation
## What comes out
Similar to what goes in, what comes out includes anything that a worksheet cell can return. These are the standard Excel data types (and their VBA equivalents):
* Logical (`Boolean`)
* Text (`String`)
* Numerical (`Double`)
* Error (`Variant/Error`) (these are non-breaking errors, ie. they do not halt code execution, `?[1/0]` executes fine)
But there are a few things that can be returned which cells cannot:
* Range reference (`Range`) (see above sections)
* Arrays (`Variant()`)
### Arrays
As has been shown, `[]` can be used to evaluate array formulas which return one of the standard Excel data types; e.g. `[CONCAT(IF(LEN(A1:B7)>2,A1:B7&" ",""))]` which returns `Text`. However `Evaluate` can also return arrays of `Variant` type. These can be
**Hardcoded:**
`[{1,2;3,4}]` - outputs a 2D array: `,` is the column separator, `;` separates rows. Can output a 1D array
**Array Formulae:**
`[ROW(A1:A5)]` - outputs a **2D** array `{1,2,3,4,5}`, i.e (2,1) is the second item (yet some functions output 1D arrays)
* For whatever reason, some functions do not return arrays by default
`[LEN(A1:A5)]` only outputs the Length of the text in the 1st cell of a range
* However these can be coerced to give arrays
`Split([CONCAT(" "&LEN(A1:A5))])` gives a 1D array 0 to 5, where the first item is empty
`[INDEX(LEN(A1:A5),)]` is another workaround, essentially you must employ an array handling function to get the desired array returning behaviour, similar to adding in a meaningless `RAND()` to make your worksheet formulae volatile.
* I asked a [question on SO](https://stackoverflow.com/q/45458986/6609896) to try to get some better info on this *please edit/comment with better options if you find them*
## `Evaluate()` vs `[]`
There are a few differences between `Evaluate()` and `[]` to be aware of
1. Strings vs hardcoded
* Perhaps the most important difference, Evaluate takes a string input where [] required a hardcoded input
* This means your code can build up the string with variables e.g. `Evaluate("SUM(B1,1,"&v &",2)")` would sum `[B1]`,`1`,`2` and variable `v`
2. Arrays
When returning an Array, only Evaluate can be used with an array index, so
```
v=Evaluate("ROW(A1:A5)")(1,1) ''#29 bytes
```
is equivalent to
```
i=[ROW(A1:A5)]:v=i(1,1) ''#23 bytes
```
[Answer]
# Combine `Next` Statements
```
Next:Next:Next
```
May be condensed down to
```
Next k,j,i
```
where the iterators for the `For` loops are `i`,`j`, and `k` - in that order.
For example the below (69 Bytes)
```
For i=0To[A1]
For j=0To[B1]
For k=0To[C1]
Debug.?i;j;k
Next
Next
Next
```
May be condensed down to 65 Bytes
```
For i=0To[A1]
For j=0To[B1]
For k=0To[C1]
Debug.?i;j;k
Next k,j,i
```
And as far as how this impacts formatting and indentation, I think the best approach to handling this is left aligning the next statement with the outer most for statement. Eg.
```
For i=0To[A1]
For j=0To[B1]
For k=0To[C1]
Debug.?i;j;k
Next k,j,i
```
[Answer]
## Reducing `If` Statements
When assigning a variable using a conditional `If ... Then ... Else` check, you can reduce the amount of code used by eliminating the `End If` by putting the entire check on one line.
For example, this (**37** chars):
```
If a < b Then
c = b
Else
c = a
End If
```
Can be reduced to this (**30** chars)
```
If a < b Then c = b Else c = a
```
If you have more than one nested conditional, you can minimize them this way as well:
```
If a Then If b Then If c Then Z:If d Then Y:If e Then X Else W Else V:If f Then U 'Look ma! No "End If"!
```
Note the `:` allows you to add more than one line/command within an `If` block.
In simple cases like this, you can usually also remove the `Else` by setting the variable in before the `If` check (**25** chars):
```
c = a
If a < b Then c = b
```
Even better, the above can be further reduced to this using the `IIf()` function (**20** chars):
```
c = IIf(a < b, b, a)
```
[Answer]
## Variable Declaration
In most cases in VBA, you can leave out `Option Explicit` (often omitted by default, anyway) and skip `Dim`'ing many of your variables.
In doing so, this (**96** Chars):
```
Option Explicit
Sub Test()
Dim S As String
Dim S2 As String
S = "Test"
S2 = S
MsgBox S2
End Sub
```
Becomes this (**46** chars):
```
Sub Test()
S = "Test"
S2 = S
MsgBox S2
End Sub
```
If you need to use certain objects (for example, arrays), you may still need to `Dim` that variable.
[Answer]
# Prepare For Pixel Art
Pixel art is by far one of Excel's strongest areas, as there is no need to construct a canvas, as it is already there for you - all you need to do is make some small adjustments
### 1) Make the cells square
```
Cells.RowHeight=48
```
or, Alternatively, for 1 byte more, but far easier to work with
```
Cells.ColumnWidth=2
```
Depending on the context, you may be able to get away without having to resize your cells at all. With the default `RowHeight` of \$15\$ and `ColumnWidth` of \$8.09\$, the aspect ratio of a default cell is \$\approx415:124\$.
If you use this to calculate what range needs to be selected to draw a given shape you may be able to drastically reduce your bytecount.
**Example:**
Golfing the Ukrainian flag with the correct \$2:3\$ aspect ratio can golfed down from
```
Cells.RowHeight=48:[A1:BZ52].Interior.Color=55265:[A1:BZ26].Interior.Color=12015360
```
to
```
[A1:NH830].Interior.Color=55265:[A1:NH415].Interior.Color=12015360
```
### 2) Color the needed range
Any `Range` object may be colored by calling
```
`MyRangeObj`.Interior.Color=`ColorValue`
```
***Note:** this can and should be combined with other tricks noted on this wiki, such as referencing ranges by the use of the `[]` notation (eg `[A1:R5,D6]`) over the use of a `Cells(r,c)` or a `Range(cellAddress)` call. Further, as noted on this wiki, this may be combined with negative color value to golf down the size of color references*
### Quick References
**Range Reference**
Cell `A1` may be referenced in any of the following ways
```
Range("A1")
Cells(1,1)
[A1]
```
and the Range `A1:D4` may be referenced in any of the following ways
```
Range("A1:D4")
Range("A1").Resize(4,4)
Cells(1,1).Resize(4,4)
[A1].Resize(4,4)
[A1:D4]
```
**Color Reference**
```
Black 0
White -1
Red 255
Aqua -256
```
[Answer]
# Reduce `Range("A1")` and Like Calls
`Range("A1").Value`(17 Bytes) and the simpler `Range("A1")`(11 Bytes) may be reduced down to `[A1]` (4 Bytes)
[Answer]
# STDIN and STDOUT
**Inputting to `Sub`routines and `Function`s via input variables**
```
Public Sub A(ByRef B as String)
```
May be reduced down to
```
Sub a(b$)
```
The `Public` and `ByRef` calls are the default for VBA and thus implicit, and may (almost) always be dropped.
The type literal `$` forces `b` to be of the type `String`.
Other type literals
* `!` Single
* `@` Currency
* `#` Double
* `%` Integer
* `$` String
* `&` Long
* `^` LongLong (64 Bit Only)
Furthermore, it is generally accepted that you may leave the input variable as the default type, `Variant` and leave any type-based errors unhandled. Eg. `Sub E(F)` in which `F` is expected to be of type `Boolean[]` (which would be passed to the routine like `E Array(True, False, False)`)
**Inputting to `Sub`routines and Immediate Window Functions via `Cells`**
VBA does not have a fully functional console and thus does not have any *official* STDIN, and thus allows for *some* play with passing input.
In excel, it is generally accepted to take input from a cell or range of cells, which may be done like
```
s=[A1]
```
which implicitly puts the `.value` from the cell `[A1]` (which may also be referenced as `cells(1,1)` or `range("A1")`
Example Problem: Display the input in a messagebox
Via Subroutine `Sub A:msgbox[A1]:End Sub`
Via Immediates Window Function `msgbox[A1]`
**Inputting Via Conditional Compilation Arguments**
VBA Projects support taking arguments from the command line or via the VBAProject Properties (view via the project explorer -> [Your VBA Project] -(Right Click)-> VBAProject Properties -> Conditional Compilation Arguments)
This is largely useful for [Error Code Challenges](https://codegolf.stackexchange.com/a/107216/61846)
Given the Conditional Compilation Argument `n=`[some\_value] this allows for executing code that will produce an error code, based off of the value of `n`.
note, this calls for an addition of 2 bytes to your code for the `n=` in the conditional compilation arguments section of the VBAProject Properties Pane.
Example Code
```
...
#If n=3 then
return '' Produces error code '3', Return without GoSub
#ElseIf n=20 then
resume '' Produces error code '20', Resume without Error
#EndIf
...
```
**Outputting Via Function Value**
Not Much to say here, the general form of quoted below is about as compact as it can be made.
```
Public Function A(b)
...
A=C
End Function
```
NOTE: in the **vast majority** of cases it is more byte convert the method to a subroutine and output to the VBE immediates window (see Below)
**Outputting From `Sub`routines and `Function`s via the VBE Immediates Window**
Outputting to the VBE immediates window (AKA the VBE Debug Window) is a common output method for VBA for text based challenges, however, it is important to remember that the `Debug.Print "Text"` call may be substantially golfed.
```
Debug.Print "Text"
```
is functionally identical to
```
Debug.?"Text"
```
as `?` autoformats to `Print`.
**Outputting from `Sub`routines and VBE Immediates Window functions via Other Methods**
On ***rare*** occasion, when the situation is just right, you may take input from some of the more trivial inputs available to VBA such as the font size adjuster, font selector, and zoom. (Eg. [Emulating the Word Font Size Selector](https://codegolf.stackexchange.com/a/105605/61846))
[Answer]
# Remove Spaces
VBA will auto-format to add a lot of spacing that it doesn't actually need. There' an [answer on meta](https://codegolf.meta.stackexchange.com/a/10259/38183) that makes a lot of sense to me why we can discount bytes added by auto-formatting. It's important to always verify you haven't removed too much, though. For an example, here's [an answer of mine](https://codegolf.stackexchange.com/a/116404/38183) that was reduced almost 22% just by removing spaces:
Original version: (188 bytes)
```
Sub g(n)
For i = 0 To 1
For x = -3 To 3 Step 0.05
y = n ^ x * Cos(Atn(1) * 4 * x)
If y < m Then m = y
If i = 1 Then Cells(500 * (1 - y / m) + 1, (x + 3) * 100 + 1) = "#"
Next
Next
End Sub
```
Reduced version: (146 bytes)
```
Sub g(n)
For i=0To 1
For x=-3To 3Step 0.05
y=n^x*Cos(Atn(1)*4*x)
If y<m Then m=y
If i=1Then Cells(500*(1-y/m)+1,(x+3)*100+1)="#"
Next
Next
End Sub
```
If you copy / paste the reduced version into VBA, it will automatically expand into the original. You can play around with where it is valid to remove spaces. The ones I've found so far all seem to follow the pattern where VBA is expected a certain command to appear because, without it, it's not valid code. Here are some that I've found so far:
* Before and after any mathematical operation: `+-=/*^` etc.
* Before `To` and `Step` in a `For` statement: `For x=-3To 3Step 0.05`
* Actually, before any reserved word (`To`, `&`, `Then`, etc.) if it's preceded by a literal such as a number, `)`, `?`, `%`, etc.
* After the `&` when combining strings: `Cells(1,1)=Int(t)&Format(t,":hh:mm:ss")`
* After function calls: `If s=StrReverse(s)Then`
* Within function calls: `Replace(Space(28)," ",0)`
[Answer]
## Simplify built-in functions
When using certain functions frequently, reassign them to a user-defined function.
The following code (**127** chars) can be reduced from:
```
Sub q()
w = 0
x = 1
y = 2
z = 3
a = Format(w, "0.0%")
b = Format(x, "0.0%")
c = Format(y, "0.0%")
d = Format(z, "0.0%")
End Sub
```
to (**124** chars):
```
Sub q()
w = 0
x = 1
y = 2
z = 3
a = f(w)
b = f(x)
c = f(y)
d = f(z)
End Sub
Function f(g)
f = Format(g, "0.0%")
End Function
```
Combining this with the [ByRef trick](https://codegolf.stackexchange.com/a/5408/3862) and some [autoformatting tricks](https://codegolf.stackexchange.com/a/128932/61846), you can save even more characters (down to **81**):
```
Sub q
w=0
x=1
y=2
z=3
f w
f x
f y
f z
End Sub
Sub f(g)
g=Format(g,"0.0%")
End Sub
```
Do this judiciously, as VBA takes up a lot of characters to define a `Function`. The second code block would actually be larger than the first with *any* number fewer `Format()` calls.
[Answer]
# Quick Note on Formatting
Because StackExchange uses [Markdown](https://en.wikipedia.org/wiki/Markdown) and [Prettify.js](https://github.com/google/code-prettify) it is possible to add a language flag to your coding answers, which generally makes them look more professional. While I cannot guarantee that this will make you any better at golfing in VBA, I can guarantee that it will make you look like you are.
Adding either of the flags below will transform
```
Public Sub a(ByRef b As Integer) ' this is a comment
```
to
```
Public Sub a(ByRef b As Integer) ' this is a comment
```
**VBA Language Tags**
`<!-- language: lang-vb -->`
`<!-- language-all: lang-vb -->`
*Note: the latter transforms all code segments in your answer, while the prior transforms only the immediately following code segments*
[Answer]
# Multiple `If .. Then` checks
As in other languages, multiple `If` checks can usually be combined into a single line, allowing for the use of `And`/`Or` (i.e. `&&`/`||` in C and others), which in VBA replaces both a `Then` and an `End If`.
For example, with a nested conditional (**93** chars):
```
'There are MUCH easier ways to do this check (i.e. a = d).
'This is just for the sake of example.
If a = b Then
If b = c Then
If c = d Then
MsgBox "a is equal to d"
End If
End If
End If
```
can become (**69** chars):
```
If a = b And b = c And c = d Then
MsgBox "a is equal to d"
End If
```
This also works with non-nested conditionals.
Consider (**84** chars):
```
If a = b Then
d = 0
End If
If c = b Then
d = 0
End If
```
This can become (**51** chars):
```
If a = b Or c = b Then
d = 0
End If
```
[Answer]
# Ending `For` Loops
When using `For` loops, a `Next` line does not need a variable name (though it is probably better to use in normal coding).
Therefore,
```
For Variable = 1 to 100
'Do stuff
Next Variable
```
can be shortened to:
```
For Variable = 1 to 100
'Do stuff
Next
```
(The savings depends on your variable name, though if you're golfing, that's probably just 1 character + 1 space.)
[Answer]
# Split a string into a character array
Sometimes it can be useful to break apart a string into individual characters, but it can take a bit of code to do this manually in VBA.
```
ReDim a(1 To Len(s))
' ReDim because Dim can't accept non-Const values (Len(s))
For i = 1 To Len(s)
a(i) = Mid(s, i, 1)
Next
```
Instead, you can use a single line, relatively minimal chain of functions to get the job done:
```
a = Split(StrConv(s, 64), Chr(0))
```
This will assign your string `s` to `Variant` array `a`. Be careful, though, as the last item in the array will be an empty string (`""`), which will need to be handled appropriately.
Here's how it works: The `StrConv` function converts a `String` to another format you specify. In this case, 64 = `vbUnicode`, so it converts to a unicode format. When dealing with simple ASCII strings, the result is a null character (not an empty string, `""`) inserted after each character.
The following `Split` will then convert the resulting `String` into an array, using the null character `Chr(0)` as a delimiter.
It is important to note that `Chr(0)` is not the same as the empty string `""`, and using `Split` on `""` will not return the array you might expect. The same is also true for `vbNullString` (but if you're golfing, then why would you use such a verbose constant in the first place?).
[Answer]
## Using `With` (Sometimes! See footnote)
Using the `With` statement can reduce your code size significantly if you use some objects repeatedly.
i.e. this (**80** chars):
```
x = foo.bar.object.a.value
y = foo.bar.object.b.value
z = foo.bar.object.c.value
```
can be coded as (**79** chars):
```
With foo.bar.object
x = .a.value
y = .b.value
z = .c.value
End With
```
The above isn't even the best-case scenario. If using anything with `Application`, such as `Excel.Application` from within Access, the improvement will be much more significant.
---
\*Depending on the situation, `With` may or may not be more efficient than this (**64** chars):
```
Set i = foo.bar.object
x = i.a.value
y = i.b.value
z = i.c.value
```
[Answer]
# Infinite Loops
Consider replacing
```
Do While a<b
'...
Loop
```
or
```
Do Until a=b
'...
Loop
```
with the antiquated but lower byte count
```
While a<b
'...
Wend
```
---
If you need to exit a `Sub` or `Function` prematurely, then instead of `Exit ...`
```
For i=1To 1000
If i=50 Then Exit Sub
Next
```
consider `End`
```
For i=1To 1E3
If i=50 Then End
Next
```
Note that `End` halts all code execution and clears out any global variables, so use wisely
[Answer]
# Use `Spc(n)` over `Space(n)`, `[Rept(" ",n)]` or `String(n," ")`
When trying to insert several spaces of length `n`, use
```
Spc(n) '' 6 bytes
```
over
```
B1=n:[Rept(" ",B1)] '' 19 bytes
```
```
String(n," ") '' 13 bytes
```
```
Space(n) '' 8 bytes
```
*Note: I am not sure why, but it seems that you cannot assign the output of `Spc(n)` to a variable, and that it must rather be printed directly - so in certain cases `Space(n)` is still the best way to go.*
[Answer]
# Reduce `Debug.Print` and `Print` calls
```
Debug.Print [some value]
```
(12 Bytes; note the trailing space) may be reduced to
```
Debug.?[some value]
```
(7 Bytes; note the lack of trailing space).
Similarly,
```
Print
```
(6 Bytes) may be reduced to
```
?
```
(1 Byte).
Furthermore, when operating in the context of an anonymous VBE immediate window function the `Debug` statement may be dropped entirely, and instead printing to the VBE immediate window via `?` may be assumed to be STDIN/STDOUT
### Special characters
When printing strings you can also use special characters in place of `&`. These allow for alternate formats in what's printed or whitespace removal
To join variable strings, instead of
```
Debug.Print s1 &s2
```
You can use a semicolon `;`
```
Debug.?s1;s2
```
This semicolon is the default behaviour for consecutive strings, as long as there is no ambiguity
So these are valid:
```
Debug.?s1"a"
Debug.?"a"s1
```
But not
```
Debug.?s1s2 'as this could be interpreted as a variable named "s1s2", not 2 variables
'use Debug.?s1 s2 instead (or s1;s2)
Debug.?"a""b" 'this prints a"b, so insert a space or ; for ab
```
*Note that a ; at the end of a line suppresses a newline, as newlines are by default added after every print. Counting bytes returned by VBA code is [under debate](https://codegolf.meta.stackexchange.com/q/12476/68602)*
To join with a tab use a comma `,` (actually 14 spaces, but according to )
```
Debug.?s1,s2 'returns "s1 s2"
```
Finally, you can use type declarations to join strings instead of ;, each having its own slight effect on formatting. For all of the below `a = 3.14159` is the first line
```
Debug.?a&"is pi" -> " 3 is pi" 'dims a as long, adds leading and trailing space to a
Debug.?a!"is pi" -> " 3.14159 is pi" 'dims a as single, adds leading and trailing space
Debug.?a$"is pi" -> "3.14159is pi" 'dims a as string, no spaces added
```
[Answer]
# Address Sheets By Name
Instead of Addressing a `WorkSheet` object by calling
```
Application.ActiveSheet
'' Or
ActiveSheet
```
One may use
```
Sheets(n) '' Where `n` is an integer
'' Or
[Sheet1]
```
Or More preferably one may access the object directly and use
```
Sheet1
```
[Answer]
# Use a helper `Sub` to `Print`
If the code requires using *more than six* `Debug.?` statements you can reduce bytes by replacing all Debug.? lines with a call to a Sub like the one below. To print a blank line you need to call `p ""` since a parameter is required.
```
Sub p(m)
Debug.?m
End Sub
```
[Answer]
# Use `Array()` `Choose()` instead of `Select` or `If...Then`
When assigning a variable based on a the value of another variable, it makes sense to write out the steps with `If...Then` checks, like so:
```
If a = 1 Then
b = "a"
ElseIf a = 2 Then
b = "c"
'...
End If
```
However, this can take up a lot of code space if there are more than one or two variables to check (there are still generally better ways to do even that anyway).
Instead, the `Select Case` statement helps reduce the size of the checks by encasing everything in one block, like so:
```
Select Case a
Case 1:
b = "a"
Case 2:
b = "c"
'...
End Select
```
This can lead to much smaller code, but for very simple cases such as this, there is an even more efficient method: `Choose()` This function will pick a value from a list, based on the value passed to it.
```
b = Choose(a,"a","c",...)
```
The option to select (`a` in this case) is an integer value passed as the first argument. All subsequent arguments are the values to choose from (1-indexed, like most VBA). The values can be any data type so long as it matches the variable being set (i.e. objects don't work without the `Set` keyword) and can even be expressions or functions.
```
b = Choose(a, 5 + 4, String(7,"?"))
```
An additional option is to use the `Array` function to get the same effect while saving another character:
```
b = Array(5 + 4, String(7,"?"))(a)
```
[Answer]
# Bit-Shifted RGB Values
Because of the way that Excel handles colors, (unsigned, 6-character hexadecimal integer) you can make use of negatively signed integers, of which excel will only use the right 6 bytes to assign a color value
This is a bit confusing so some examples are provided below
Lets say you want to use the color white, which is stored as
```
rgbWhite
```
and is equivalent to
```
&HFFFFFF ''#value: 16777215
```
to golf this down all we need to do is find a **negative** hexadecimal value which terminates in `FFFFFF` and since negative Hex values in must be in the format of `FFFFXXXXXX` (such that `X` is a valid hexadecimal) counting down from `FFFFFFFFFF` (`-1`) to `FFFF000001` (`-16777215`)
Knowing this we can generalize that the formula
```
Let Negative_Color_Value = -rgbWhite + Positive_Color_Value - 1
= -16777215 + Positive_Color_Value - 1
= -16777216 + Positive_Color_Value
```
Using this, some useful conversions are
```
rgbWhite = &HFFFFFF = -1
rgbAqua = &HFFFF00 = -256
16747627 = &HFF8C6B = -29589
```
[Answer]
# Omit terminal `"` when printing to Immediate Window
Given the function below, which is to be used in the debug window
```
h="Hello":?h", World!"
```
The Terminal `"` may be dropped for -1 Byte, leaving the string unclosed and the program shall execute the same, without error
```
h="Hello":?h", World!
```
Even more surprising than this is that this may be done within fully defined subroutines.
```
Sub a
h="Hello":Debug.?h", World!
End Sub
```
The subroutine above runs as expected and autoformats to
```
Sub a()
h = "Hello": Debug.Print h; ", World!"
End Sub
```
[Answer]
# Use Truthy and Falsey Variables in conditionals
Sometimes called implicit type conversion - directly using a number type in a `If`,`[IF(...)]` or `IIf(...)` statement, by using the truthy and falsey nature of that number can absolutely save you some bytes.
In VBA, any number type variable that is non-zero is considered to be truthy ( and thus zero, `0`, is the only value falsey) and thus
```
If B <> 0 Then
Let C = B
Else
Let C = D
End If
```
may be condensed to
```
If B Then C=B Else C=D
```
and further to
```
C=IIf(B,B,D)
```
[Answer]
# Exponentiation and `LongLong`s in 64-Bit VBA
The general form of exponentiation,
```
A to the power of B
```
Can be represented as in VBA as
```
A^B
```
***But Only in 32-Bit Installs of Office***, in 64-Bits installs of Office, the shortest way that you may represent without error this is
```
A ^B
```
This is because in 64-Bit versions of VBA `^` serves as both the exponentiation literal and the [`LongLong` type declaration character](https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/64-bit-visual-basic-for-applications-overview#summary-of-vba7-language-updates). This means that some rather odd-looking but valid syntax can arise such as
```
a^=2^^63^-1^
```
which assigns variable `a` to hold the max value of a `Longlong`
[Answer]
# Compress Byte Arrays as String
For challanges that require the solution to hold constant data, it shall may be useful to compress that data as a single string and to then iterate across the string to fetch the data.
In VBA, any byte value may be directly converted to a character with
```
Chr(byteVal)
```
And a `long` or `integer` value may be converted to two characters with
```
Chr(longVal / 256) & Chr(longVal Mod 256)
```
So for a `byte` array a compression algorithm would look something like
```
For Each Var In bytes
Select Case Var
Case Is = Asc(vbNullChar)
outstr$ = outstr$ & """+chr(0)+"""
Case Is = Asc(vbTab)
outstr$ = outstr$ & """+vbTab+"""
Case Is = Asc("""")
outstr$ = outstr$ & """"""
Case Is = Asc(vbLf)
outstr$ = outstr$ & """+vbLf+"""
Case Is = Asc(vbCr)
outstr$ = outstr$ & """+vbCr+"""
Case Else
outstr$ = outstr$ & Chr$(Var)
End Select
Next
Debug.Print "t="""; outstr$
```
Noting that the `Select Case` section is implemented due to the characters which may not be stored as literals in the string.
From the resulting string, which will look something like
```
t="5¼-™)
:ó™ˆ"+vbTab+"
»‘v¶<®Xn³"+Chr(0)+"~ίšÐ‘š;$Ôݕ󎡡EˆõW'«¡*{ú
{Óx.OÒ/R)°@¯ˆ”'®ïQ*<¹çu¶àªp~ÅP>‹:<­«a°;!¾y­›/,”Ì#¥œ5*B)·7
```
The data may then be extracted using the `Asc` and `Mid` functions, eg
```
i=Asc(Mid(t,n+1))
```
[Answer]
# Use Improper Constants
VBA allows, in some cases, for the use of unlisted or improper constants in expressions which require constant values. These are often legacy values, and shorter in length than the proper values.
For example the values below may be used when letting a value be held by the `rng.HorizantalAlignment` property.
\$
\small
\begin{align}
\textbf{Improper} &&\textbf{Proper} && \textbf{General Constant}\hspace{1.3cm}&&& \texttt{xlHAlign}~~\textbf{Constant} \\\hline
1\hspace{1.25cm} && 1\hspace{.7cm} && \texttt{xlGeneral}\hspace{2.95cm} &&& \texttt{xlHAlignGeneral} \\
2\hspace{1.25cm} && -4131 && \texttt{xlLeft}\hspace{3.6cm} &&& \texttt{xlHAlignLeft} \\
3\hspace{1.25cm} && -4108 && \texttt{xlCenter}\hspace{3.18cm} &&& \texttt{xlHAlignCenter} \\
4\hspace{1.25cm} && -4152 && \texttt{xlRight}\hspace{3.39cm} &&& \texttt{xlHAlignRight} \\
5\hspace{1.25cm} && 5\hspace{.7cm} && \texttt{xlFill}\hspace{3.61cm} &&& \texttt{xlHAlignFill} \\
6\hspace{1.25cm} && -4130 && \texttt{xlJustify}\hspace{2.97cm} &&& \texttt{xlHAlignJustify} \\
7\hspace{1.25cm} && 7\hspace{.7cm} && \texttt{xlCenterAcrossSelection} &&& \texttt{xlHAlignCenterAcrossSelection} \\
8\hspace{1.25cm} && -4117 && \texttt{xlDistributed}\hspace{2.15cm} &&& \texttt{xlHAlignDistributed}
\end{align}
\$
This means, for example that setting a cell to having its text centered with
```
rng.HorizantalAlignment=-4108
```
may be shortened down to
```
rng.HorizantalAlignment=3
```
by replacing the improper constant value `3` for the proper value `-4108`. Note that if you fetch the `rng.HorizantalAlignment` property value, it will return the proper value. In this case, that would be `-4108`.
[Answer]
# In Excel, Create Numeric Arrays by Coercing Ranges
When a constant single dimensional set of numerics of mixed length, \$S\$ is needed, it shall be more efficient to use `[{...}]` notation to declare a range and then coerce that into a numeric array rather than to use the `Split(String)` notation or similar.
Using this method, a change of \$\Delta\_\text{byte count} =-5~\text{bytes}\$ shall be accrued for all \$S\$.
### Example
For instance,
```
x=Split("1 2 34 567 8910")
```
may be written as
```
x=[{1,2,34,567,8910}]
```
It is further worth noting that while this method does not allow for direct indexing, it does allow for iteration over the for loop directly, ie
```
For Each s In[{1,3,5,7,9,2,4,6,8}]
```
] |
[Question]
[
Write a function or program that outputs the number of each type of element (vertex, edge, face, etc.) of an N-dimensional hypercube.
As an example, the 3 dimensional cube has 1 cell (i.e. 1 3-dimensional cube), 6 faces (i.e. 6 2-dimensional cubes), 12 edges (i.e. 12 2-dimensional cubes) and 8 vertices (i.e. 8 0-dimensional cubes).
More details about Hypercube elements can be found [here](https://en.wikipedia.org/wiki/Hypercube#Elements)
You can as well take a look at the [following OEIS sequence](https://oeis.org/A013609).
### Input
Your code will take as input (via STDIN or a function parameter or similar things) an integer greater or equal to 0, which is the dimension of the hypercube.
Your code has to theoretically work for any input >= 0, disregarding memory and time issues (that is, speed and potential stack overflows are not a problem for your answer if the input is big). Inputs given as test cases will not be above 12.
### Output
You will ouput a list of all elements of the hypercube, starting with the "highest dimension" element. For example, for a cube (input = 3), you will output the list `[1,6,12,8]` (1 cell, 6 faces, 12 edges, 8 vertices).
The format of the list in the output is relatively free, as long as it looks like a list.
You can output the result to STDOUT or return it from a function.
### Test cases
```
Input = 0
Output = [1]
Input = 1
Output = [1,2]
Input = 3
Output = [1,6,12,8]
Input = 10
Output = [1, 20, 180, 960, 3360, 8064, 13440, 15360, 11520, 5120, 1024]
Input = 12
Output = [1, 24, 264, 1760, 7920, 25344, 59136, 101376, 126720, 112640, 67584, 24576, 4096]
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# J, 13 bytes
```
[:p.2&^;$&_.5
```
Inspired by [@alephalpha's PARI/GP answer](https://codegolf.stackexchange.com/a/70594). Try it online with [J.js](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%20%5B%3Ap.2%26%5E%3B%24%26_.5%20)%2012).
### Background
By the binomial theorem,
[](https://i.stack.imgur.com/eww9Q.png)
Thus, the output for input **n** consist precisely of the coefficients of the above polynomial.
### Code
```
[:p.2&^;$&_.5 Monadic verb. Argument: n
$&_.5 Yield an array of n instances of -0.5.
2&^ Compute 2^n.
; Link the results to the left and right.
This specifies a polynomial of n roots (all -0.5)
with leading term 2^n.
[:p. Convert from roots to coefficients.
```
[Answer]
# [Samau](https://github.com/AlephAlpha/Samau/tree/master/OldSamau), ~~8~~ 5 bytes
Saved 3 bytes thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis).
```
▌2\$ⁿ
```
Hex dump (Samau uses CP737 encoding):
```
dd 32 2f 24 fc
```
Explanation:
```
▌ read a number
2\ push the array [1 2]
$ swap
ⁿ take the convolution power
```
[Convolving two vectors is equivalent to multiplying two polynomials](https://en.wikipedia.org/wiki/Convolution#Discrete_convolution). Similarly, taking the n-th convolution power is equivalent to taking the n-th power of a polynomial.
[Answer]
# MATL, 8 bytes
```
1i:"2:X+
```
Inspired by [@alephalpha's PARI/GP answer](https://codegolf.stackexchange.com/a/70594).
[Try it online!](http://matl.tryitonline.net/#code=MWk6IjI6WSs&input=MTI) (uses `Y+` for modern day MATL)
### How it works
```
1 % Push 1.
i: % Push [1 ... input].
" % Begin for-each loop:
2: % Push [1 2].
X+ % Take the convolution product of the bottom-most stack item and [1 2].
```
[Answer]
## [MATL](https://esolangs.org/wiki/MATL), 12 bytes
```
Q:q"H@^G@Xn*
```
[**Try it online**](http://matl.tryitonline.net/#code=UTpxIkhAXkdAWG4q&input=MTA)
### Explanation
```
% implicit: input number "n"
Q:q % generate array[0,1,...,n]
" % for each element "m" from that array
H@^ % compute 2^m
G % push n
@ % push m
Xn % compute n choose m
* % multiply
% implicit: close loop and display stack contents
```
[Answer]
# Mathematica, 29 bytes
```
CoefficientList[(1+2x)^#,x]&
```
My first Mathematica answer! This is a pure function that uses the same approach as Alephalpha's PARI/GP [answer](https://codegolf.stackexchange.com/a/70594/20469). We construct the polynomial `(1+2x)^n` and get the list of coefficients, listed in order of ascending power (i.e. constant first).
Example usage:
```
> F := CoefficientList[(1+2x)^#,x]&`
> F[10]
{1,20,180,960,3360,8064,13440,15360,11520,5120,1024}
```
[Answer]
# APL, ~~15~~ 11 bytes
```
1,(2*⍳)×⍳!⊢
```
This is a monadic function train that accepts an integer on the right and returns an integer array.
Explanation, calling the input `n`:
```
⍳!⊢ ⍝ Get n choose m for each m from 1 to n
× ⍝ Multiply elementwise by
(2*⍳) ⍝ 2^m for m from 1 to n
1, ⍝ Tack 1 onto the front to cover the m=0 case
```
[Try it online](http://tryapl.org/?a=f%u21901%2C%282*%u2373%29%D7%u2373%21%u22A2%20%u22C4%20f%2010&run)
Saved 4 bytes thanks to Dennis!
[Answer]
# PARI/GP, ~~20~~ 15 bytes
```
n->Vec((x+2)^n)
```
[Answer]
# Jelly, 8 bytes
```
0rð2*×c@
```
I should really stop writing Jelly on my phone.
```
0r Helper link. Input is n, inclusive range from 0 to n. Call the result r.
ð Start a new, dyadic link. Input is r, n.
2* Vectorized 2 to the power of r
×c@ Vectorized multiply by n nCr r. @ switches argument order.
```
Try it [here](http://jelly.tryitonline.net/#code=MHLDsDIqw5djQA&input=&args=MTA).
[Answer]
## TI-BASIC, 10 bytes
```
3^Ansbinompdf(Ans,2/3
```
[Answer]
## CJam (17 14 bytes)
```
ri_3@#_2+@#\b`
```
[Online demo](http://cjam.aditsu.net/#code=ri_3@#_2%2B@#%5Cb%60&input=3)
This approach uses the ordinary generating function `(x + 2)^n`. The OEIS mentions `(2x + 1)^n`, but this question indexes the coefficients in the opposite order. I'm kicking myself for not thinking to reverse the g.f. until I saw Alephalpha's update to the PARI/GP answer which did the same.
The interesting trick in this answer is to use integer powers for the polynomial power operation by operating in a base higher than any possible coefficient. In general, given a polynomial `p(x)` whose coefficients are all non-negative integers less than `b`, `p(b)` is a base-`b` representation of the coefficients (because the individual monomials don't "overlap"). Clearly `(x + 2)^n` will have coefficients which are positive integers and which sum to `3^n`, so each of them will individually be less than `3^n`.
```
ri e# Read an integer n from stdin
_3@# e# Push 3^n to the stack
_2+ e# Duplicate and add 2, giving a base-3^n representation of x+2
@# e# Raise to the power of n
\b` e# Convert into a vector of base-3^n digits and format for output
```
---
Alternative approaches: at 17 bytes
```
1a{0X$2f*+.+}ri*`
```
[Online demo](http://cjam.aditsu.net/#code=1a%7B0X%242f*%2B.%2B%7Dri*%60&input=3)
or
```
1a{0X$+_]:.+}ri*`
```
[Online demo](http://cjam.aditsu.net/#code=1a%7B0X%24%2B_%5D%3A.%2B%7Dri*%60&input=3)
both work by summing the previous row with an offset-and-doubled row (in a similar style to the standard manual construction of Pascal's triangle).
A "direct" approach using Cartesian powers (as opposed to integer powers) for the polynomial power operation, comes in at 24 bytes:
```
2,rim*{1b_0a*2@#+}%z1fb`
```
where the map is, unusually, complicated enough that it's shorter to use `%` than `f`:
```
2,rim*1fb_0af*2@f#.+z1fb`
```
[Answer]
## ES6, 71 bytes
```
n=>[...Array(n+1)].fill(n).map(b=(n,i)=>!i?1:i>n?0:b(--n,i-1)*2+b(n,i))
```
Simple recursive formula. Each hypercube is created by moving the previous hypercube 1 unit through the Nth dimension. This means that the M-dimensional objects are duplicated at the start and end of the unit, but also the (M-1)-dimensional objects gain an extra dimension, turning into M-dimensional objects. In other words, `c(n, m) = c(n - 1, m) * 2 + c(n - 1, m - 1)`. (The actual submission reverses the parameters so that the formula outputs in the desired order.)
Ingeniously, `fill` allows `map` to provide the correct arguments to the recursive function, saving me 6 bytes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
Code:
```
WƒNoZNc*,
```
Explanation:
```
W # Push input and store in Z
ƒ # For N in range(0, input + 1)
No # Compute 2**N
ZNc # Compute Z nCr N
* # Multiply
, # Pop and print
```
Uses CP-1252 encoding.
[Answer]
# Pyth, 10 9 bytes
```
.<L.cQdhQ
```
Uses the nCr algorithm everyone seems to be using.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 31 bytes
Use the formula from [A013609](https://oeis.org/A013609): T(n,k) = 2^k\*binomial(n,k).
[Try it online!](https://tio.run/##ZY/dCoMwDIXv9xS9GdQh0vTfjcHeYzjYj4I3dajb63dJYQoWSgj9zjlJhud8/7YxducLD8WjD8@h7ToeSnEMRXWQ1Y1TF0@7Vz@9ecdFUTC2Z2M7f8YwsSs0fwJbUjK5QJlDjW/hKue2ZCBL5heNzjUeZ2COQh3YdRNacrOJQIXHUlssSlH1wqIXlNYETfoDMCQ1kAxCrhuCzEPRLlOGI6@rySQNBmJCDYouEKBcusS6FIkNjbPOeHJrQ1SL2jbxBw)
```
f=@(n)bincoeff(n,0:n).*2.^(0:n)
```
[Answer]
# Julia, 31 bytes
```
n->[2^m*binomial(n,m)for m=0:n]
```
This is a lambda function that accepts an integer and returns an integer array. To call it, assign it to a variable.
For each *m* from 0 to the input *n*, we count the number of (*n*-*m*)-dimensional hypercubes on the boundary of the parent *n*-dimensional hypercube. Using the formula on Wikipedia, it's simply 2*m* \* choose(*n*, *m*). The case of *m* = 0 refers to the *n*-cube itself, so the output begins with 1 regardless of the input. Edges are given by *m* = *n*, vertices by *m* = *n* - 1, etc.
[Answer]
# [J](https://www.jsoftware.com), 11 bytes
```
(,+2*,~)&0#
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxWkNH20hLp05TzUAZIrJekys1OSPfIU3NTiFTz9AQIrpgAYQGAA)
```
(,+2*,~)&0#
# constant 1
( )&0 inner function bound to 0 on the right, repeated n times to 1...
, append 0
2*,~ prepend 0, and then double each number
+ elementwise add the two
```
# [J](https://www.jsoftware.com), 12 bytes
```
1|.@p.@;$&_2
```
A minor variation of Dennis's J solution. [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxxrBGz6FAz8FaRS3eCCK0XpMrNTkj3yFNzU4hU8_QECK6YAGEBgA)
```
(!~*2^])i.,]
```
A minor variation of Alex A's APL solution. [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxRkOxTssoLlYzU08nFiK0XpMrNTkj3yFNzU4hU8_QECK6YAGEBgA)
```
1|.@p.@;$&_2
1 ;$&_2 create an array (1; -2 -2 ... -2)
p. construct a polynomial having that many -2s as roots
|. reverse it
(!~*2^])i.,]
i.,] create an array 0, 1, 2, ..., n
2^] 2^0, 2^1, ..., 2^n
!~ nC0, nC1, ..., nCn
* elementwise multiply
```
[Answer]
# Ruby, Rev B 57 bytes
```
->n{a=[1]+[0]*n
(n*n).downto(n){|i|a[1+j=i%n]+=2*a[j]}
a}
```
The previous rev only scanned through the used part of the array each time. This rev scans through the entire array on every iteration. This is slower, but it saves bytes. A further byte is saved by using 1 loop to do the job of 2.
# Ruby, Rev A 61 bytes
```
->n{a=[1]+[0]*n
n.times{|i|i.downto(0){|j|a[j+1]+=2*a[j]}}
a}
```
Starts with a point and iteratively creates the next dimension
In each iteration, each existing element increases in dimensionality and generates 2 new elements of its original dimensionality. For example, for a square in the horizontal plane that is extended vertically to become a cube:
The 1 face becomes a cube and generates 1 pair of faces (1 above, 1 below)
The 4 edges become faces and generate 4 pairs of edges (4 above, 4 below)
The 4 vertices become edges and generate 4 pairs of vertices (4 above, 4 below)
**Ungolfed in test program**
```
f=->n{a=[1]+[0]*n #make an array with the inital point and space for other dimensions
n.times{|i| #iteratively expand dimension by dimension
i.downto(0){|j|a[j+1]+=2*a[j]} #iterating downwards (to avoid interferences) add the 2 new elements generated by each existing element.
}
a} #return the array
p f[gets.to_i]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 44 bytes
```
f=n=>n?[...f(n-1),i=0].map(v=>i*2+(i=v)):[1]
```
[Try it online!](https://tio.run/##JcoxDoMwDEDRnVMwxg1YwFhqehDEEEFSuaI2AhT19gHB9N/wvy66bVx52UvRyacUSKiTd4@IwUhZQ8FUDfhzi4nU8aOxhikCPPt6SG0WdM0Ny@T/VLX5hVdzytrLkI0qm84eZ/3cXxHuAqQD "JavaScript (Node.js) – Try It Online")
~~# [JavaScript (Node.js)](https://nodejs.org), 51 bytes~~
```
f=n=>n?[0,...f(n-1)].map((v,i,e)=>~~e[++i]+v*2):[1]
```
[Try it online!](https://tio.run/##JcpNDoMgEEDhvadwyRScqMta7EEIC6LQ0NgZow3pyqtTf1bvW7y3S24dljh/K@LR5xw06Z6eplaIGARVDVj8uFmIpKLyoPtt80bKaGW6tXA3jc1dEXgpRaTR/3TdlSce7a79OwzFwLTy5HHi1/WpcBUg/wE "JavaScript (Node.js) – Try It Online")
binomial(n,m)\*2^m
] |
[Question]
[
Create the shortest program/function/whatever that splits an inputted string along un-nested commas. A comma is considered nested if it is either within parentheses, brackets, or braces.
## Input and output
Output should be a list or a string joined with linebreaks. The input may contain any characters. All testcases will have valid/balanced parentheses, brackets, and braces. There will also not be two adjacent commas, nor will there be commas at the start or end. Also, all inputs will be valid, printable ASCII characters from ' ' to '~' (no tabs or linebreaks).
## Test cases:
```
"asd,cds,fcd"->["asd","cds","fcd"]
"(1,2,3)"->["(1,2,3)"]
"(1),{[2,3],4}"->["(1)","{[2,3],4}"]
"(1),[2]{3}"->["(1)","[2]{3}"]
"(1),((2,3),4)"->["(1)","((2,3),4)"]
"(1),(4,(2,3))"->["(1)","(4,(2,3))"]
```
## Example program:
```
function f(code){
code = code.split(',');
let newCode = [];
let last = "";
for (part of code){
if (last.split("(").length == last.split(")").length && last.split("[").length == last.split("]").length && last.split("{").length == last.split("}").length){
last = part;
newCode.push(part);
}
else{
last += "," + part;
newCode[newCode.length - 1] = last;
}
}
return newCode;
}
```
```
<input id=in oninput="document.getElementById('out').innerText=f(this.value).join('\n')">
<p id=out></p>
```
[Answer]
# Excel (ms365), 186 bytes
[](https://i.stack.imgur.com/EYbXk.png)
Formula in `B1`:
```
=TEXTSPLIT(@REDUCE(VSTACK(A1,0),SEQUENCE(LEN(A1)),LAMBDA(a,b,LET(c,MAX(a),d,MID(@a,b,1),IF(d=",",IF(c,a,VSTACK(REPLACE(@a,b,1,"|"),c)),VSTACK(@a,c+IFERROR(FIND(d,")}]|[{(")-4,)))))),"|")
```
The idea I started of with here was that I needed a ticker-system. `REDUCE()` gave me the option to keep this ticker counting and thus decide if a comma was nested within paranthesis or not. A fair chance that this specific idea lead me to use quite a bit of bytes.
I do believe there will be a fair bit of golfing possible here.
[Answer]
# JavaScript (ES6), 79 bytes
*-2 thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
*[70 bytes](https://tio.run/##bc3NCoMwDMDxu09RvJhg1H14EqoPUgtKq2NDrNixi/rsTmHiNrzk8s8veZSv0qr@3j2D1uhqrvlseWrDvuqaUlUQAeEIAsQgcRSYy0lGNwJLigzyFFSmE5P5vk50EGBmk8IpSPMTzsq01jRV2Jgb1OCWVpPSlmqlXWQ@8/LWQ8ZYFDGxRpfcJS9zXZDOn4YzXeiKP5JteosHCmkQS5MUT1/2o3D5tudDDbBephiP9Z7l/AY) if we assume there's no linefeed in the input and use it as a separator in the output (also suggested by tsh)*
The code includes the unprintable character `SOH`.
```
s=>s.replace(/(,)|([([{])|[)\]}]/g,(s,c,o)=>(c?d:o?++d:d--)?s:``,d=0).split``
```
[Try it online!](https://tio.run/##bYzLCoMwEEXptl8RXM3gqH24EtQPSQNKomIRI53Sje2320grgrgZmHPvuffyVbJ@tMMz6K2ppjqdOM04fFRDV@oKIiB8gwQ5KnxLvKmPihoCJk0W0wx0bhKb@75JTBBgzklxKMikJwx56Nqn@yZte7ZdFXa2gRq8kg1pw1Rr4yEKIaJIyJl65Dnu7pyo40aDM13oij9FLNpCd@pIo3SZovgzS/86uv2V72oA8yTFuNFWrqYv "JavaScript (Node.js) – Try It Online")
## Commented
### Regular expression
```
regex = /(,)|([([{])|[)\]}]/g
// \_/ \_____/ \__/
// | | |
// | | +---> closing character (not captured)
// | +----------> opening character (captured)
// +----------------> comma (captured)
```
### Function
```
s => // s = input string
s.replace( // replace in s:
regex, // we match either a comma, an opening character,
// or a closing character (see above)
( //
s, // s = matched character
c, // c = defined if this is a comma
o // o = defined if this is an opening character
) => //
( c ? // if this is a comma:
d // leave the nesting depth unchanged
: // else:
o ? // if this is an opening character:
++d // pre-increment the depth
: // else:
d-- // post-decrement the depth
) ? // if the above test returns a non-zero depth:
s // leave the character unchanged
: // else:
'\1', // replace it with SOH
d = 0 // start with d = 0
).split('\1') // end of replace(); split on SOH characters
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 34 bytes
```
!`([({[]()|[]})](?<-2>)|\2,|[^,])+
```
[Try it online!](https://tio.run/##K0otycxL/P9fMUEjWqM6OlZDsyY6tlYzVsPeRtfITrMmxkinJjpOJ1ZT@///xOIUneSUYp205BQuDUMdIx1jTSCtqVMdDWTG6pjUAgA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
!`
```
Output the matches themselves rather than the count of matches, which is the default for a match stage, a match stage being the default for a single-line program.
```
([({[]()|[]})](?<-2>)|\2,|[^,])+
```
Match as many as possible of...
```
[({[]()
```
... an opening bracket, which increases the nesting level, tracked in `$#2`, ...
```
[]})](?<-2>)
```
... an assumed matching closing bracket, which decreases the nesting level, ...
```
\2,
```
... a comma, but only if we are nested, ...
```
[^,]
```
... or failing that, any non-comma.
The same regex would work in Retina 1 but you would have to use a `L`ist stage instead for the the same length.
[Answer]
# [Funciton](https://esolangs.org/wiki/Funciton), 1396 bytes
(The byte count uses UTF-16 and includes the BOM. UTF-8 is bigger, unfortunately.)
[**Try it online!**](https://tio.run/##nVW9jtQwEO7zFFOCtEV@djdJxYMgCjhAojka6KNUFFckYHM@tCvEytIVLKJZCSG2uvLeAr/IYnv8m@RyQOTT2s7MN998M5N7@fb87NWb1@enE4AgF4J0IOgHQRpBP4J69GWjV5fgiQmy0Ra73z@JoJ/xpbPkuDtIhMTam7OgV4LsBd34G9JG@6vvgvaJveU3PzR@JwhBbHPBte03aSsoE5QLukX26NoGt@jYBTdt7IOhiQKlMh1peWlQwCSKAAaJgd55So@sBEepyNLRbzXatUQzUaREWk@CIhsKoC0/6bhb59nnKjVlulcRbR2Q6uSm0fIi//G69MipRkZGTbycusPfW6Z@6S5L10VR5WGOfa3xWnAswCc3u@nLsqiqtIrQSpu3oiOaI5Zfpd9C0ExdUJmDrm5fSG5ZVUdomfwL6UgQiDuOaP@ja2HtVeR1uY6RVogUtKo9BA2guiOouvIr6ny1Wq1HrNywGImZaxLfGYq5KZdyq8p6mS4hhDJto9kEDWXaJm4Q1XPe3u7HyzahyZb5pMFBB2O4iVuIoTcOSBie33z1ErJ4PlniiyINf9mUfUbDlncDGk51HA@rwu0nqgvSajERr/24O0kb2cMcGTvro2kzgnlxwEsRjJf6boh37/MsKK3/6g4Wku0GZONybl0ROPgn7nqtx4DfXctouTeVgvAZSPY3cMOMTjDxDBWdtukh1QMx/RY14UaTWXz33@tgPmLz8VXkDOzcc5BdZk90h@@TaTamQmDLyN05ruBkRjHHO2xkVS@@zKjCZlT5tzi3W5P0/0cyKl/fX@js/kp7@U5PFw8eP1ucPVk8f7h48Qc)
```
┌┐ ╓─╖ ┌──┐
┌┘├─╢Ṕ╟─┐ ┌─┤ ┌┴╖
┌┘┌┴╖╙┬╜┌┴╖│┌┴╖│♯║
│┌┤·╟┐└─┤·╟┤│♭║╘╤╝┌┐
││╘╤╝└─┐╘╤╝│╘╤╝┌┴╖└┤╔═╗
││ ├──┐└─┘ └┐└─┤?╟─┼╢4║
││╔╧╗┌┴┐ └┐ ╘╤╝ │╚═╝
││║2║└┬┘ ┌┴╖┌┴╖┌┴╖┌─╖╔═══════╗
‚îÇ‚îÇ‚ïë0‚ïë‚îå‚îÄ‚îÄ‚îÄ‚îÄ‚îĂ∑‚ïü‚∑‚ïü‚∑‚ïü‚î§ ò‚ïü‚ï¢1063382‚ïë
││║9║│ ┌─╖ ╘╤╝╘╤╝╘╤╝╘╤╝║7738808║
││║7║└─┤‼╟┐ │ ┌┘┌┐├──┴┐║3063189║
││║1║ ╘╤╝│ │┌┴╖└┴┼─┐ │║1329769║
││║5║ ┌┴╖│ ┌┴┤?╟──┘╔╧╗│║3925556║
││║1║┌─┤·╟┘┌┴┐╘╤╝ ║0║│║879404 ║
││╚═╝│ ╘╤╝ └┬┘┌┴╖┌┐ ╚═╝│╚═══════╝
││ ┌┘ ┌┴╖ └┬┤·╟┤├────┘
│└┐┌┴╖┌┤«║ ┌┘╘╤╝└┘
│┌┴┤»║│╘╤╝ ┌┴╖┌┴╖
││ ╘╤╝│┌┴╖┌┤?╟┤Ṕ╟┐
││ │ └┤·╟┘╘╤╝╘╤╝│
││ │ ╘╤╝ ┌┴╖┌┴╖│╔═══╗
││ └───┘ ┌┤«╟┤·╟┼╢−21║
││┌───────┘╘═╝╘╤╝│╚═══╝
│└┤ ┌┴╖└┐
│ └───────────┤?╟┬┘
│ ╘╤╝│
└────────────────┘
```
Oh boy, what an ungolfable language. I tried really hard to move things around to eke out a few bytes but this is the most compact arrangement I was able to find.
Funciton has two ways of representing collections: “sequences” and “lists”. I’m taking the challenge statement literally and made a function that returns a *list* of the results.
**Here’s how the function (`Ṕ`) works:**
* The function takes three parameters:
+ `s`, the input string;
+ `n`, a running count of currently-open parentheses/brackets/braces; and
+ `l`, the list we’re constructing.
* The function must initially be called with `n` = 0 and `l` = 1. The integer 1 here represents a one-element list containing a 0, and 0 in turn represents the empty string.
* If `s` is empty, we just return `l`.
* Otherwise, let `c` be the first character of `s`, and let `i` be the index of `c` within the string `",([{)]}"` (this is the big box on the right). `i` is ‚àí1 if the character is not in there.
* Now perform a recursive call with the following parameters:
+ `s` becomes the rest of the string with the first character removed.
+ If `i` > 0, then: { if `i` < 4, then we’re looking at an opening parenthesis, so increment `n`; else, we’re looking at a closing parenthesis, so decrement `n`; } else, we’re looking at a comma (`i` = 0) or something else (`i` = −1), so leave `n` unchanged.
+ If `i` bitwise-or `n` is 0, this means that `i` = 0 (we’re seeing a comma) and `n` = 0 (we are not in a parenthesis), so append an empty string to `l`. Otherwise, append `c` to the last string in `l`.
**An interesting golfing trick I used:** See the −21 in the bottom-right? That’s used to do a shift-right by 21 on the input string `s` (this removes its first character). This construct uses the raw syntax (`┼`) which means it can also compute a “less-than” operation. Since `s` is certainly non-negative, it will never be less than −21, so this will always return 0. I re-use that 0 as the empty string to be appended to the list when a comma is encountered. This allowed me to save an entire `0` literal box, as well as the loop-de-loop I would otherwise need to swallow the less-than result.
To actually run this code, you need a program that calls the function, so here’s one provided for convenience. It’s not golfed and it’s not included in the byte count because the challenge only asked for the function.
```
╔═══╗
‚ïë 0 ‚ïë
╚═╤═╝
╔═══╗ ┌─┴─╖ ╔═══╗
║ 1 ╟─┤ Ṕ ╟─╢ ║
╚═══╝ ╘═╤═╝ ╚═══╝
┌─┴─╖
│ ⌡ ║
╘═╤═╝
┌─┴─╖
‚îÇ ù ‚ïü‚îÄ
╘═╤═╝
╔═╧══╗
‚ïë 10 ‚ïë
╚════╝
```
This program calls `·πî` with stdin, 0, and 1; uses `‚å°` to convert the list to a sequence; and then uses `ù` to join the strings with newlines (ASCII #10).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 109 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 13.625 bytes
```
¦ƛt:\,=nøβ∧∨;1€ṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiwqbGm3Q6XFwsPW7DuM6y4oin4oioOzHigqzhuYUiLCIiLCJcIigxKSx7WzIsM10sNH1cIiJd)
```
¦ƛt:\,=nøβ∧∨;1€ṅ
¦ # prefixes
∆õ # map:
t # tail
: # duplicate
\,= # is equal to ","?
n # the prefix
øβ # does it have balanced brackets?
‚àß # logical and
‚à® # logical or
; # end map
1€ # split on 1
·πÖ # join inner lists
```
[Answer]
# Java 11, 157 bytes
```
s->{var t="";for(var p:(s+",x").split(","))if(t.split("[\\[({]",-1).length==t.split("[)}\\]]",-1).length){if(t!="")System.out.println(t);t=p;}else t+=","+p;}
```
Inspired by [@Dadsdy's JavaScript answer](https://codegolf.stackexchange.com/a/261556/52210), so make sure to upvote him/her as well!
Outputs the parts on separated newlines to STDOUT.
[Try it online.](https://tio.run/##jVGxTsMwEN37FYcnn@JEKjA1CgsTA2XomGQwjlNcUjeKLwUU@duD0zYgJJBYbD/f87v3fDt5lPGueh1VI52DR2nssAAwlnRXS6VhPUGA48FUoPiGOmO34DANt34RljVYyGB08d1wlB1QxlhaHzo@gXbFXcTEO8PEtY0hzgRDNDWnGedFkfOhZCJeYtJou6WXLPuuoi@K8kcVh@n5VeiCmw9Hep8cekra4IoaywlTytrU68ZpoCgL/aIAx3Ry2vbPjVHgSFLYToH2Ie4lU15KPEed3ZN2dC@D0AqsfoOZNjDpKqEqJ2pVMQGML8W1uMHzEcWQB1SKW8/8RRDgF6vswbY9rYBFc5/Tn/7FfurpTP9iTZ6mcXFMbKL4f1QuNX@anR8/AQ)
**Explanation:**
```
s->{ // Method with String parameter and no return-type
var t=""; // Temp-String, starting empty
for(var p:(s+",x") // ††Concat ",x" to the input
.split(","))// Then split it on ",", and loop over the parts:
if(t.split("[\\[({]",-1).length==t.split("[)}\\]]",-1).length){
// †If String `t` has balanced brackets:
if(t!="") // †††If `t` is NOT empty (so it's not the first iteration):
System.out.println(t);
// Print the current `t` with newline
t=p;} // Replace the `t` with the current `p` for the next iteration
else // Else:
t+=","+p;} // Append a "," and the current `p` to `t` for the next iteration
```
†: The `-1` in the [`String#split`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#split(java.lang.String,int)) are to include empty Strings, when a part `p` starts with an opening bracket or ends with a closing bracket.
††: We concat an `,` to the input-String before splitting, in order to have an additional iteration of the loop. The additional `x` (could have been any character) is a golfed shortcut for `,-1` in the split of the input.
†††: In Java you'd almost always have to use [`String#equals`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#equals(java.lang.Object)) when comparing Strings. In this case however, where we only want to skip the first iteration when `t` is still empty, we can use `!=""` to check whether not just the value but also the reference is the same. This is possible here, because String literals point to the same reference point in memory, so the `""` in both `t=""` and `!=""` are the same in memory.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 49 bytes
```
{[[email protected]](/cdn-cgi/l/email-protection)@=i-!#i:&~(x=44)&~+\+/(6#1 -1)*"()[]{}"=\:x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6qucNDLdLDN1FVUzrRSq9OosDUx0VSr047R1tcwUzZU0DXU1FLS0IyOra5Vso2xqqjl4kpTUNIw1NTR0DDSMdbUMdFU4gIAlC0QtQ==)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 29 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ðX',/ıxs+',+ẊDøB?ðX:"";;€ḣ€ṫæ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWN3UOb4hQ19E_srGiWFtdR_vhri6Xwzuc7IGiVkpK1taPmtY83LEYRO5cfXjZkuKk5GKozgXrlTQMNXWqo410jGN1TGqVIMIA)
### [Thunno 2](https://github.com/Thunno/Thunno2), 18 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) (non-competing)
```
ƒıtD',=nøB&|;1µ/€J
```
This uses the `µ/` command which I added literally 5 minutes ago, so obviously non-competing.
Port of AndrovT's Vyxal answer.
#### Explanation
```
√∞X # Store " " in x
',/ '# Split the input on commas
ı # Map over this list:
xs+ # Add the current string to x
',+Ẋ '# Add a comma and store in x
D # Duplicate the resulting string
√∏B? # If the brackets are balanced:
√∞X # Store " " in x
: # Else:
"" # Push an empty string
; # End if
; # End map
€ḣ # Remove the first character from each
€ṫ # Remove the last character from each
√¶ # Remove any empty strings
```
```
ƒ # Prefixes
ı # Map:
t # Tail
D # Duplicate
',= '# Equals ","?
n # Push character again
√∏B # Has balanced brackets?
& # Logical AND
| # Logical OR
; # End map
1µ/ # Split on 1s
€J # Join inner lists
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
≔⁰θFS«≧⁺⁻№([{ι№}])ιθ¿θι≡,ι⸿ι
```
[Try it online!](https://tio.run/##TY25CsMwEAVr@ysWVStQIFflVCFVCoNJSseFcHwsCPmQlBTG3674KtIO8@bltezzRirvr8ZQpXEvoOOXsGx6wLtunX3annSFnMMQBrFsV@9BVW0xUc4IiEk7g7fGaYsM04EJIC5gA2PGF8DXcEAlYMchmaoWaSaFMgWYL9m8BmSCLU@5nCBFm8dePZvVd1FKp2z0Px/D0Xs8cDGkR3HKxHn0u4/6AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰θ
```
Start with zero nesting level.
```
FS«
```
Loop over the characters.
```
≧⁺⁻№([{ι№}])ιθ
```
Adjust the nesting level depending on whether the characters is an open or close bracket.
```
¿θι≡,ι⸿ι
```
Output the character if it is nested or not equal to a comma, but replace an unnested comma with a newline.
Alternative approach, also 28 bytes:
```
⭆θ⎇›⁼ι,⊙⪪()[]{}²↨Eλ№…θκν±¹¶ι
```
[Try it online!](https://tio.run/##HYzBCsIwDIZfpfSUQjw4vXnSIp4UYd7mDmGUrVjareuEMfbsNfPy589H8jUdxSaQy/kZrU9QJh7tnXoYULxM9BRnuEVDyUS4DhO5ESwKiVKhOPsZyt7ZBBJUVS@rRFEwv9BoYHM4FDpMrNVz44zuwl/74ROvOB6mZS/sldo2@fb8b7mfcmaIS1Xgocbjmndf9wM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Inspired by @AndrovT's Vyxal answer.
```
θ Input string
⭆ Map over characters
‚éá Ternary
ι Current character
⁼ Equals
, Literal string `,`
› Is greater than
()[]{} Literal string of brackets
⪪ ² Split into pairs of brackets
‚äô Any pair satisfies
λ Current pair of brackets
E Map over brackets
‚Ññ Count of
ν Current bracket in
θ Input string
… Truncated to length
κ Outer index
↨ ±¹ Has a non-zero difference
¶ If true then newline
ι Else current character
Implicitly print
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~21~~ 20 bytes
-3 thanks to @Kevin Cruijssen
```
',¡.œ',δý.ΔεžuS¢ιË}P
```
[Try it online!](https://tio.run/##ATUAyv9vc2FiaWX//ycswqEuxZMnLM60w70uzpTOtcW@dVPCos65w4t9UP//KDEpLHtbMiwzXSw0fQ "05AB1E – Try It Online")
[Try all testcases.](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf3WdQwv1jk5W1zm35fBevXNTzm09uq80@NCiczsPd9cG/K/V@Z9YnKKTnFKsk5acwqVhqGOkY6wJpDV1qqOBzFgdk1owL9oottoYwtTQAKnRMdEEAA)
## Explanation
```
', push a comma
¬° and split the implicit input by it
.œ push all partitions, all possible ways to split it to continuous parts
',δý and join each partition with commas.
.Δ now keep (and implicitly output) the first partition such that:
ε for each of its parts
žu push "()<>[]{}"
S list of characters, ["(", ")", "<", ...]
¢ count each of the characters in the current part
ι uninterleave it, put the count of the even indices (opening brackets) and the odd ones (closing brackets) in two lists
Ë and check if the two lists are equal - the number of opening brackets of each type is equal to the number of closing ones.
}
P take the product, which functions as and.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 75 ~~86~~ ~~98~~ bytes
>
> -12 bytes after realizing the string is balanced, so there is always the correct matching ending character for each type of block (and removing some unnecessary parentheses)
>
>
>
>
> -11 bytes after the added possibility to output the list as a string joined with linebreaks
>
>
>
(Solution without regex)
Nice challenge :)
```
s=>[...s].map(c=>c==","&!(a+=("{[()]}".indexOf(c)+4)%7-3)?`
`:c,a=0).join``
```
[Try it online!](https://tio.run/##XY5RaoNAEIbfPYUdaNnBydJGoRDY5Ag9gAou61oMdhXXlID42Lceob1cLmI3NYHFeRnmm/n45yg/pVV93Q0b05Z6rsRsxT7lnNucf8iOKbFXQgDB0wOTkWAwpgzzCXhtSn1@q5jCKMHH102MhyIodoqkeEZ@bGtTFLO0VveDYLXpTgPpc6fVoEvqtT01g6gWjugyWmPbRvOmfWfsthbiLhzg8vOVGdjB5ffbdYyWkwiuQxAsMSwMQdqSVGmpUiWErmhhmXEwMzeKnsBeaEsx/h/fhTVbCUhj6vY5JRPcBcyMD9dCus3HeAIvwQk@XAuMXT@gBP0EH@L8Bw "JavaScript (Node.js) – Try It Online")
---
A little explanation:
We parse each character of the input string.
For each character, the code `("{[()]}".indexOf(c)+4)%7-3` gives
`+1, +2 or +3` respectively for `{ [ (`,
`-3, -2 or -1` respectively for `) ] }`, and `0` if it's another character.
We increment (or decrement) our *"nesting height counter"* using this result.
If the counter is `0` (meaning, when we are currently outside of a block) and the current character is a `,` then we replace it with a `\n`.
A `,` at heights higher than 0 is kept without transformation.
Then at the end, we join everything to get the wanted output.
[Answer]
# [ATOM](https://github.com/SanRenSei/ATOM) ~~103~~ 100 bytes, ~~99~~ 96 chars
```
{a=*/",";i=0;üìè*‚àÄ{a.iüö™{üìè(*/"("+*/"["+*/"{")!=üìè(*/")"+*/"]"+*/"}")}:a.i+=","+a.(i+1);a-(i+1),i+=1};a}
```
#### Version 2
Saving a few characters by storing i+1 as a separate variable
```
{a=*/",";i=0;üìè*‚àÄ{j=i+1;a.iüö™{üìè(*/"("+*/"["+*/"{")!=üìè(*/")"+*/"]"+*/"}")}:a.i+=","+a.j;a-j,i=j};a}
```
## Usage
```
s="(1),{[2,3],4}";
s INTO {a=*/",";i=0;üìè*‚àÄ{a.iüö™{üìè(*/"("+*/"["+*/"{")!=üìè(*/")"+*/"]"+*/"}")}:a.i+=","+a.(i+1);a-(i+1),i+=1};a}
```
### [Try it online](https://sanrensei.github.io/ATOM/)
## Explaination
It begins by splitting the original string by the comma into an array. It creates an iterator, and goes through each element in the created array. If the number of opening and closing symbols do not match, it will merge the current array element with the next one. If they do match, it will continue onwards. By the end of the iteration, all array elements should be correct, and it returns the final result.
### Commented and organized code
```
{
a=*/","; # Split the input by the comma
i=0; # Declare an iterator
üìè* FOREACH { # Repeat the following function based on the length of the string
a.i INTO {üìè(*/"("+*/"["+*/"{")!=üìè(*/")"+*/"]"+*/"}")}: # Check if the opening and closing characters match in the current item
a.i+=","+a.(i+1); # If there is not a match, add the next element to the current one
a-(i+1), # Remove the next element from the array and continue the loop
i+=1 # Else, increment the counter
};
a # Return the final array
}
```
[Answer]
# [Python](https://www.python.org), 110 bytes
```
f=lambda i,p=1,a=[],c="":i and f(i[1:],p+((q:=i[0])in"([{")-(q in")]}"),a+[c][(x:=q!=p*","):],(c+q)*x)or a+[c]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RZBBTgMxDEXXzCmCV3bHlRhggSLlJFEWISEiEmQynSAVVT0FSzbdwJ24DZ6WERvL_n6Wv_35Xd_b81hOp6-3lrYPPyWZF__6GL3KXM3A3ljHwQDorHyJKmG2g3Zce8RJm2xvHOUCaA9AW5yU5OSOQOx7G5zFvTbTtakbYCAZw9BPtNnTuFNn4G_rR3ua26yMsh2CnyOHOHMKEdgupQyLIHGRHLFAOPAt39ECrOnaID5YERzfHy9toeBfWjDXJXGQeRS_6rxbd1d1l0vDzHIi8UgXa-tjfgE)
Defines a recursive function `f`. The parameter `p` is the number of open parenthesis plus one, `a` is the accumulator for the output list and `c` is the accumulator for the current string.
If `i` is nonempty we recurse, possibly adding or subtracting one from the parenthesis count `p`. If `p` is equal to 1 and we are on top of a comma we append `c` to `a` and clear the value of `c`. Otherwise we append `q=i[0]` to `c`.
If `i` is empty we just return `a+[c]`
[Answer]
# SNOBOL 4, 126 bytes
I haven't really tried to golf this beyond using single-letter names. Well, I guess there is one little trick. Parsing lists of items separated by commas is usually something like `item arbno(',' item)` (i.e., an item followed by an arbitrary number of repetitions of a comma and another item. Here I've cheated a little bit instead, and added a comma to the beginning of the input, so we can parse the resulting list with code like: `arbno(',' item)`
```
L = ARBNO(ARBNO(NOTANY('([{}])')) | '(' *L ')' | '[' *L ']' | '{' *L '}')
I = ',' INPUT
I ARBNO(',' L . OUTPUT) RPOS(0)
END
```
Each item in the result is printed on a new line.
Then there's the cheating version that semi-sorta works, and reduces the size to 72 bytes:
```
REPLACE(',' INPUT, "[]{}", "()()" ) ARBNO(',' BAL . OUTPUT) RPOS(0)
END
```
SNOBOL has a built-in function to match strings with balanced parentheses (but not brackets or braces). This replaces brackets/braces with parens, then matches and prints those out (which will otherwise match the correct output). For example, for the test input: `(1),{[2,3],4}`, this prints out:
```
(1)
((2,3),4)
```
General explanation:
Regular expressions are based on SNOBOL patterns.
* `NOTANY('abcd')` is about the same as `[^abcd]` in a regex
* `arbno(foo)` is about like `foo*` in a regex
* RPOS(0) is like `$` at the end of a regex--matches only if the rest of the pattern matches the whole string.
`string1 string2` concatenates the two strings.
`string pattern` attempts to match the pattern against the string. The result will be the matched substring.
Then a rather strange SNOBOL thing. `string pattern . variable` matches `pattern` against `string`, then assigns the resulting substring to `variable`. In our case, we assign to `output`, so this prints out each matching substring.
On, I almost forgot. Formatting. SNOBOL is roughly concurrent with FORTRAN, and uses similar formatting: the only things that can go in column 0 or labels (that can be used as targets of jumps). Lines without labels have to start with a space character.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
=“([{“}])”§_/)Ä<=”,$œp
```
[Try it online!](https://tio.run/##y0rNyan8/9/2UcMcjehqIFkbq/moYe6h5fH6modbbIDic3VUjk4u@H@4/VHjPiWlrEcb12UBWToKmpH//yslFqfoJKcU66QlpyjpKChpGOoY6RhrQpiaOtXRQF6sjkktTCDaKLbaGM7T0AAp1jHRVAIA "Jelly – Try It Online")
Jelly and multiple brackets + non-brackets are not friends
```
) For each character in the input:
= is it equal to each of
“([{“}])” ["([{", "}])"]?
§ Sum the results from each half,
_/ and take their difference,
=“([{“}])”§_/) yielding 1 for opening, -1 for closing, or else 0.
Ä Cumulative sum, for depths.
< Is each character's depth strictly less than
=”,$ whether or not it's a comma?
œp Split the input around those positions.
```
[Answer]
# Python, 120 118 112 bytes
```
def q(s):
d,*L,p=0,''
for c in s:d+=c in'{[(';d-=c in'}])';p,L=[[p+c,L],['',L+[p]]][1>d!=c==',']
return L+[p]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY6xDcIwEEX7THFUd0cuEgEKlMhM4A0sV3Ei0hjHcQqEmIQmDezAKGyDIKJ7X6_47_4Ml3Q6-3l-TKkrDu_g2g4GGrnKwMlaS1AbQcygO0dooPcwVi5XX8KrIaxdsYybZayDaGVMyBvRVgyi6NwEa60pj26lGqVQ0GYQ2zRFDz-5_L5C7H2igZBKFtoLbWXHjMyL__d9AA)
I realize this loses to the current Python answer by 2 bytes but I liked that it was an uncomplicated implementation of the most intuitive algorithm and wanted to add it.
6 bytes saved thanks to xnor.
Ungolfed it's pretty self-explanatory:
```
def split_string(s: str) -> list[str]:
depth = 0
piece = ''
L = []
for c in s:
depth += c in '{[('
depth -= c in '}])'
if depth == 0 and c == ',':
L += [piece]
piece = ''
else:
piece += c
return L + [piece]
```
Note that the last `+ [piece]` depends on the promise that the string doesn't end on `,`.
Also, I switched to a function because I realized that with `input` and `print` the code doesn't actually output a list, but rather prints something that would be as difficult to work with as the input. :) Otherwise, the solution would be the winning Python one at **105** bytes ([ATO](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3M1N0tHx0CmwNdNTVudLyixSSFTLzgKigtERD0ypF2xbEV6-O1lC3TtGFcGpjNdWtC3R8bKOjC7STdXxidaLV1XV8tKMLYmNjow3tUhRtk21t1XXUY7kKijLzSjTAUpoQC6H2LlirYaipo2Gio2GkY6wJlQMA)):
```
d,*L,p=0,''
for c in input():d+=c in'{[(';d-=c in'}])';p,L=[[p+c,L],['',L+[p]]][1>d!=c==',']
print(L+[p])
```
[Answer]
# Javascript, ~~140~~ ~~132~~ 114 Bytes
Thanks to [@KevinCruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for -8 Bytes!
```
c=>(n=[],l="",(c+',').split`,`.map(p=>l=a(/[([{]/)>a(/[)\]}]/)?l+','+p:(l&&n.push(l),p)),n);a=r=>l.split(r).length
```
[TIO](https://tio.run/##lcy9DoIwFIbh3cvoQM8Jxxp/BqMpXkhtQlMEMcfSUHQxXjtCXF3c3uF7vpt7uuT7Ng7L536s9eh1AUEbS6yFIPC5JIkqRW6Hkkp1dxGiLlg7WBkwL7vCYk482/fUJ573eTwAZ1lQ8ZGuwEgRkQIene4n@j2DHhVfQjNcR9@F1PFFcdeANELmNQiXKvJVotpXAtWtawNIQUJiLoWVuPhlYE0b2uIfe6SXmYil3fuXGj8)
[Answer]
# APL (Dyalog Unicode), 44 bytes
```
x[⍸1=(x=',')-+\(x∊'({[')-x∊')}]']←⊆'","'⋄,/x
```
[Try it on TryAPL.org!](https://tryapl.org/?clear&q=x%E2%86%90%27%22(1)%2C(4%2C(2%2C3))%22%27%E2%8B%84x%5B%E2%8D%B81%3D(x%3D%27%2C%27)-%2B%5C(x%E2%88%8A%27(%7B%5B%27)-x%E2%88%8A%27)%7D%5D%27%5D%E2%86%90%E2%8A%86%27%22%2C%22%27%E2%8B%84%2C%2Fx&run)
[Answer]
# [Scala](http://www.scala-lang.org/), ~~140~~ 131 bytes
Golfed version. [Try it online!](https://tio.run/##VZA9T8QwDED3/grLYkh0AcTHVEilE2JgQAyIqe0Q2vQoKmlU@9AdVX97yZXrVXiK7ednK1SYxozt@6ctGJ5N7cDu2LqSYO099FEE8G0acPErd7Xb6OTN1Qw6GkknAvEyFrRCtUN5Qb6pWaBCKXvBykud1JXguZ5mWSr6PICNdRv@0HppySHL8kOL6h8r@2nMte7xy/Ne@rCXGydY3vnBNmSBw0Zc@WE8HseW@MGQJdCw7jqzF2ioVEVJqipKVIDiSl2rG/n3lKpPQ5ar2wFlUFRtB2J2wP354pPhAyDEfALhk/NbjuFsRibBAuDLlifgWHcn73/ukA3RMP4C)
```
s=>(""/:(s+",x").split(",")){(t,p)=>if(t.split("[\\[({]").length==t.split("[)}\\]]").size){if(t.nonEmpty)println(t);p}else t+","+p}
```
Ungolfed version. [Try it online!](https://tio.run/##VZCxTsMwFEX3fsXVE4OtupUKTBVBqhADAzAgpqaDSdwSFFwrfkWtqnx7cNK4babk5Zx3fWOf6VI3zfbrx2SMV11YmD0bm3ssnMNxBPDBGbwhgfjgqrAbieQRn7bgUYB/uoSdn7Cf48poV1tegQMk6sb1toJweJgEG2OQ2pOcelcWLEiRlP0WUKwhOJJlmi7FcUUKk5mclsZu@BtJgosg6zRdDYVLVkyzW/v86/gg4UJLLq1geVbakq6f6v5pSm8CGIf6ikLdE29pHf@djecn7Y0P64uq0gdB2ucqy71aZ3koRGKmbtWdPL1KdVyGaaXua2rP7u4jZrTXcs6L9WNVTy/W7XiOm6iQHAj0vuNO6L/bc@7Qk139etQ0/w)
```
object Main extends App {
type N = (String) => Unit
val n: N = (s: String) => {
var t = ""
for (p <- (s + ",x").split(",")) {
if (t.split("[\\[({]", -1).length == t.split("[)}\\]]", -1).length) {
if (t.nonEmpty) println(t)
t = p
}
else t += "," + p
}
}
val testCases = Array("asd,cds,fcd", "(1,2,3)", "(1),{[2,3],4}")
for (testCase <- testCases) {
println(s"Input: $testCase")
println("Output: ")
n(testCase)
println()
}
}
```
[Answer]
# [Arturo](https://arturo-lang.io), 81 bytes
```
$=>[i:0loop split&'c->'i+dec/??index"([{^_^}])"c<=3prints(‚àßc=","0=i)?->"\n"->c]
```
[Try it!](http://arturo-lang.io/playground?uoSGE2)
```
$=>[ ; a function; assign arg to &
i:0 ; assign 0 to i
loop split&'c-> ; loop over input string; assign current letter to c
'i+ ; increment i in place by...
dec ; ...one less than...
index"([{^_^}])"c ; index of c in the string literal
?? ... 3 ; if this is null, replace it with 3
<=3 ; duplicate 3
/ ... 3 ; integer divide by 3
prints ; print the following w/o newline
(‚àßc=","0=i)? ; is c a comma and is i 0?
->"\n" ; newline
->c ; otherwise, c
] ; end function
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 107 ~~110~~ ~~122~~ bytes
>
> -12 bytes after the added possibility to output the list as a string joined with linebreaks
>
> -3 bytes thanks to *ceilingcat*
>
>
>
Port of my JS answer, see explanations [here](https://codegolf.stackexchange.com/a/261566/116582)
```
s->{var r="";int a=0;for(var c:s.toCharArray())r+=c==44&(a+=("{[()]}".indexOf(c)+4)%7-3)==0?10:c;return r;}
```
[Try it online!](https://tio.run/##bZDBTsMwDIbveworEihRs2qwSkirwoS4DnHguO1g0nR0dNlI0glU9ciNR4CX24uMdGtRgeWS5LN/@7eXuMX@Mnneb4rHPJMgc7QW7jDTUPZ6AJl2yqQoFUw8AH8enMn0AlLaPCyLPa/qZOvQ@RoTyEHsbf@63KIBIwiJfRlAMYjTtaE1lCMbuvXtE5obY/CNMmYCIYWIonOKgaCknFI2r0iY6US93qdUsiBiZ1f9IRNiML4YjGRslCuMBhNX@7ju3kzQmNiuswTUFvPW5wYNrnhrX71ulHQqYb@nMsoWuQMBeZjSg@IwnY@/WadW4bpw4cZnulxT2tYI1UuBuaVHMRuT3ef7TJMR2X19@JsFx0BA6s/Psk7YXfm1N3anc0CzsK29wyAABG3CZWJ5KhNSc35kM@3hTDe0sdxq6AW/5EN2yG81f9l/DePl1KfMeVSRVsNmugtPaKaX83JYkU4fr@nCExpKays8Yt0@XdjurNp/Aw "Java (JDK) – Try It Online")
[Answer]
Python:
```
import re
def split_string(s):
return re.split(r',(?![^(){}[\]]*[)\]}])', s)
```
JavaScript:
```
function splitString(s) {
return s.split(/,(?![^(){}[\]]*[)\]}])/);
}
```
Ruby:
```
def split_string(s)
s.split(/,(?![^(){}[\]]*[)\]}])/)
end
```
Java:
```
import java.util.regex.Pattern;
public class SplitString {
public static String[] splitString(String s) {
return s.split(",(?![^(){}\\[\\]]*[)\\]}])");
}
}
```
C++:
```
#include <iostream>
#include <regex>
#include <vector>
std::vector<std::string> splitString(const std::string& s) {
std::regex regex(",(?![^(){}\\[\\]]*[)\\]}])");
std::sregex_token_iterator iterator(s.begin(), s.end(), regex, -1);
std::sregex_token_iterator end;
return std::vector<std::string>(iterator, end);
}
```
```
[Answer]
# [J](http://jsoftware.com/), 44 bytes
```
','&(,<;._1~1,=*0=6+/\@(>-2*3>])'}])([{'i.])
```
[Try it online!](https://tio.run/##ZY07D4IwFEZ3f8VNB9uLl8orDijEaOJkHFxrYwxI1MWBkeBfr/WFWoZ2OOd87cUwySvIUuBAEEBqjy9huV2vDCc@FDSbyn14CynzgmwyGu/mIvcjL8418lajUA0/S40GB4NjcbpCBfxQl1SUNVVFyWGzkODnilnIiFlsbyuY7nIRUkQxftM3@EuQGmWhpqT9DdG@1glnoCLdxL36RZ1UiMeHlKBbd8IdJPQ0/cFHMG3u "J – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) (`-p`), 42 bytes
```
s/([({[]([^({[]|(?1))*[]})])(*SKIP)^|,/ /g
```
or +1 byte to avoid catastrophic backtracking
```
s/([({[]([^({[]|(?1))*?[]})])(*SKIP)^|,/ /g
```
[Try it online!](https://tio.run/##VYw9D4IwEIZ3f4VpGO7IYcOHE1Fm42Li2BRjAI0JEWLdgL9ubUkRXO7jeZ@7tnrVW80ZbPwMGU@9y84LU604COiEBJHb1kMWIvpCDigR/PPxcMK8J77md63ZVZVUlIpuRcmCvbA7I2aIqZbJFYOQIopxjKd5xEidMJukZHAhmquZOUlEsouXhgMuBrAfKcGFMbNJSmhEf9KPyU/Tvh/NU@mgbr8 "Perl 5 – Try It Online")
] |
[Question]
[
**Story:**
The π was recently computed with accuracy to [100 trillions digits](https://cloud.google.com/blog/products/compute/calculating-100-trillion-digits-of-pi-on-google-cloud), but it is useless to us. We can't do accurate enough math, because rational numbers are too boring and so we don't know that much digits of them!
**Challenge:**
Your task will be to write program or function which takes string of digits including decimal separator and outputs next digit of this number. You can get next digit by knowing, that the input is composed out of two strings (ignoring the decimal separator) like this `abb`. For example the number `0.1818` is composed of string `a` which is `0` and `b` which is `18` and the output will be first digit of `b`, which is `1`. If there are multiple choices for string `b` you have to use longest one. The string `a` can be empty.
The decimal separator is guaranteed to be in every number and won't be first or last character of input. You can choose which decimal separator you want to support from following [characters](https://en.wikipedia.org/wiki/Decimal_separator): `.,·'`
**Testcases:**
| Input | a | b | Output |
| --- | --- | --- | --- |
| 0.1818 | 0 | 18 | 1 |
| 6.66 | 6 | 6 | 6 |
| 3.3 | | 3 | 3 |
| 0.0526315789473684210526315789473684210 | 00 | 526315789473684210 | 5 |
| 37.0370 | | 370 | 3 |
| 88.998899 | | 8899 | 8 |
| 1657.7771657777 | | 1657777 | 1 |
| 5.0000000 | 50 | 000 | 0 |
| 25885882588.588 | | 2588588 | 2 |
| 9.99999 | | 999 | 9 |
| 1.221122 | 12211 | 2 | 2 |
| 1.2112113211 | 121121132 | 1 | 1 |
[Answer]
# Regex (ECMAScript or better), ~~38~~ ~~34~~ 20 bytes
```
((.).*),?(.*)\1,?\3$
```
Uses `,` as the decimal separator. Returns its output as capture group `\2`.
[Try it on regex101](https://regex101.com/r/SDieAA/13) - ECMAScript (and can be switched to others)
[Try it online!](https://tio.run/##bYvNToNAFIX38xQ0MeFOndL5KcwgQdI0Tdz4k1pX1gVph4oCJQP1p8atD@Aj@iI4aOLKk3vPufck30P6lDZrk9ftqKnzjTblrnrUr52JK/3sLPR2/lIDHOLT8bAD8LA3xCQB6ytGkpU46objA/ba3XVr8moL2GuKfK0hIKMJxlG2M5DFLIIiNjrdFHmlAeNBXO2LIspiit/yDAYZri3cAo7qfdu0Bopj1/n6@HTcvwbKuPDKtF3fg8E4gfKW3yW9nbgXl85serW8Wcxd/POdT5ezM4u@d5QwxRQKSBAgQQSihPo8EMyXKpxIEagJZ/80SEhChaRIKRKGSoUhYoEviZSyTyvkE/orxH2l7PRB7KLQImFPEM4Z47w/bDIm7H4D "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript
[Attempt This Online!](https://ato.pxeger.com/run?1=bVDBbtQwEBVXf4WxLK1deXfjpEmcmiiq2gCVYLcKy6mprGVxupGyu5GTnhBX7nDlUgnxB_wMPfZLmGQ5ISyP3_jNe6Oxv_9ot-3D47OPLzJIMHU4xWRO8Ay3zt4ZZ9tmvbFsMp-dZMZs101vNoddWzfWlazkuizm3UTgCUQFpLmzg2Df233fMWNeXr3JjeECSw4tobFG1cExWqeepk1agbxj71aXVwuu-SdcV4w2N13vGruHjE_lbZqSck84iLv7D1ABWnhiKrke1TW3m-1hkGgMXaVGGA8MJrTBT1--YeDHl-zW_WbLqBPgpztwj6qx1Ky73ljnYDD-PL0u8ldmsTR5USyLjOQDT84Y3WWs7jrbQ3bj3_JshDOyWOKL8-vV-yInfLy9PV9dvCZcf_7nuxjXP-_7aqp-MTbjsxMuMgZnKUVWBvRYevgLv796QiqpUCSiCAUiQJ7wQj8KZBir5DQOInXqy_8wKIiFF8QeUkokiVJJgmQUxiKO4wFhoVB4x4X8UCnYAwgIlIAlGRzC96X0_SEBlDKAOE72Bw "PHP – Attempt This Online") - PCRE2
[Try it online!](https://tio.run/##bU5LasMwEN3rFMYIIpWJ0Se2pBiTQNc9QZJFSJTY4FhGdnBJ8LYH6BF7EVcmi276mDdvPsxjWjdY35W2rifsi523V/t5WK8bO5DtYiIkockbhQ0Jec9hs5d4Wmwhfne3tqrtOaY5fhQsvzhvj6eS4DqqmghXTXvv6bO6EHwrsE8@jv2ptF1Y09f0QZ@Dr3q7LF3Xj8GC5399tGxceKCuGhvFwfHn6zvCwSm5endvu5040HgcJwZcc40yyDIkQSIGLBWZ5KnSZqVkpleC/zNBUgGTiiGtwRitjUE8SxUopWYNQCmwF5BItQ4xCwQiE07MfAFCcC7EXATlXAb@Ag "PowerShell – Try It Online") - .NET
It occurred to me after writing both of the below regexes that an entirely different approach would also work.
```
# Search for a "first half", which is repeated exactly following itself
# (except that there can be a decimal point anywhere in either half, which
# is not repeated), with the end of the string following that in turn.
((.).*) # \1 = part 1 of first half;
# \2 = first digit of this half (the return value)
# A decimal point may be here in the other half.
,? # Skip a decimal point, if there is one in this half. If there isn't
# one here in this half, there must be one here in the other half.
(.*) # \3 = part 2 of first half
# Match the other half, which is an exact repetition of the first half
# except that a decimal point can occur anywhere in either half and is
# not repeated.
\1 # Match part 1
,? # Skip a decimal point, if there is one here.
\3 # Match part 2
$ # Assert that we've reached the end of the string.
```
It even *almost* works in [GNU ERE](https://www.regular-expressions.info/gnu.html#ere):
[Attempt This Online!](https://ato.pxeger.com/run?1=lVTLTttAFN105a-4NVWxYRI8NrGdpAHxiMoGkCAVVBBZqTNJRji25UcDaaPuum-33XTTZXf9Gbrsl_SOJ-QB6aKj2DP3fe6ZG3_76cdBnorH6_v-_YsrtXQRkNJYJcUhzTr-TSnlY9agtuM4JrXV9v2nNR76Qd5l8CrNujwqD3aUuYpHaZawznBRl7A-u112Qyce9lfpdhR_0EnAi6_a0IAzdX80unln5W_v7i5bA3s00H7kWa_k_tK0sl7e0Mmuhu9rSnavrRfS9PtZoj-OUglsxA0v3qR1Za3LejxkcH50euEd77UOjoACbG0BFg77DLIIDPFitzFL-JCFGYx4NoAwyiAdRCMECdmAwbCT-YP1FN53gpwpHN2GHR5quvJBAVxF114m94NoGPOAdeuFKb7CXgMWarFeou2GIbW8Bxo6--iqvVyKIhATOGu-9pqXrebJYfMQPoK2AH8XAdcKh5PT8zf7uq4XCSUOsXpxnqWaehDlQbfow5eZBbg8QLqx14SlKY_CMlKF98qSRK_P4hOW5UkIVGomckOvWk1eGvAQK9Qf-i6Y8TLJ0BU1jLY09aIENEHUGHuW8X2WBXgZWiH4PCQylV5HH6ovtCDYGeuANjEf2vp1uL4AUFjnhGBcb5TwjGlFsrLvIUxNn-Yui4kWEi06jYpqU4bgz-evoM71k1kF2YvRLidDL41wNI36ShsTtsU6yyCLe2X-kwt-BFSERj2tSKxvTaUNKRJZT07EeWvvTMyEDo3GdAIeKJjVnU_A0syoJ6dQnFUcHhRaUmoe1hYZmGWZAAtS9pTp5TIraIfNKUHmlDyyJCNhpScO9N8AVvWlHot41q0VupXol27h-WIH_zkqyjzd9G-BkzCRn57v918MQl3qKjaxbcUilmIQo2LaFq04bnXbsWx326QrNIrlEMNyDMV1SbXqutWqQu2KQ_CzK3ZcSoUYcilmxXXxJzaCj1LFkKqIIKZJqWmKA-6UWvhIZH8B "C++ (GCC) – Attempt This Online") - but fails on the `5.0000000` case, because this engine *really* [doesn't like to backtrack much](https://sourceware.org/bugzilla/show_bug.cgi?id=11053). The strangest thing is that if `REG_NOSUB` is enabled, it claims to match everything... is it lying? It's Schrödinger's match. (You can experiment with that by changing `SHOW_MATCH` to `0` in the test harness.)
This 20 byte regex obsoletes the other two below, as it runs at the same speed or faster... but I'm not sure if I want to delete them, since they're interesting in their own right. And they would still be the only working solutions if the entire string could be littered with any number of decimal points.
# Regex (.NET), 39 bytes
```
(?=((.),?)*$)(?<=(?(2)$)(?<-2>(\2),?)*)
```
Returns its output as capture group `\3`.
[Try it online!](https://tio.run/##bU7LasMwELzrK4wRRCqy0SPWI67rQM/9gjSHkCqxwLGN7OCSkGs/oJ/YH3Hl5NBLlx1md4YdtmtH6/vK1vUEfbHx9mg/t6tVY0e0XkyoLBBKMSnxE8SofC5QiTi@jwl/Qe/8buFpsSbxa3vqXG0/YpzDS0HzQ@vtbl8hWEeuiaBruvOAr@6A4KmAPn3bDfvK9sHGD/WCr6N3g02qth9uIYLlf3uUNG34qXaNjeKQ@PP1HcGQlB59e@76jdji@HabKGGaaSCJlEAQASihGZeCZUqbpRJSLzn7RwFCESoUBVoTY7Q2BjCZKaKUmjkUyAh9FOCZ1qFnIgHAhBMzXxDOGeN8HgIzJgJ@AQ "PowerShell – Try It Online")
This works (using .NET's Balancing Groups feature) by pushing a portion of the end of the string onto the group `\2` capture stack, one digit at a time, and then scanning in reverse from the position it started from, popping off one digit at a time from the stack to check that they match. The last one popped off is then the return value, if it matches.
```
# No anchor - This regex will try starting its match at each
# character of the string until succeeding.
(?= # Positive atomic lookahead - Match the following, but then
# return to this position.
(
(.) # Push a digit onto the group \2 capture stack.
,? # Skip a decimal point if there is one here.
)* # Iterate the above as many times as possible, minimum zero
$ # Assert we've reached the end of the string.
)
(?<= # Lookbehind - evaluated right-to-left
# (read this from the bottom up)
(?(2)$) # Assert that if the group \2 stack is not empty, we're at the
# end of the string (which is impossible). Basically, assert
# that the group \2 stack is empty.
(?<-2> # Pop a capture from the group \2 stack and match:
(\2) # \3 = digit that matches with \2
,? # Skip a decimal point if there is one here.
)*
)
```
[Try it on regex101](https://regex101.com/r/SDieAA/8) - putting this link down below here because regex101's .NET support is a bit buggy. With this example, it sees the capture groups in the wrong order, and thinks the return value is in group 1.
# Regex (PCRE2), 48 bytes
```
(?*(.).*(.*+))((.),?(?=.*(?=\2$)(\5?+,?\4)))+\5$
```
Returns its output as capture group `\1`.
[Try it on regex101](https://regex101.com/r/SDieAA/7)
[Attempt This Online!](https://ato.pxeger.com/run?1=bVBBb9MwGBVX_woTRaq_1m3jpEmchciatjAmQTuFclomqxRnjZS2UZKdEFfu48plEuJHjSO_hC8pJ4Tlz-_5-b1Ptr__qHf1068Xn14pJNRuaEKtuUVntG7MvW5MXW22ho3ms7HSerepOr097uuyMk3OcojzbN6OOB1hFSjqe9MbDp05dC3T-vX121Rr4FQAtsTGMSmODbPLxIntKinQ3rL368vrJcTwmZYFs6vbtmsqc0AGU3GXJFZ-sADN7cNHPEGZO3wqIB7cJZjt7thbYopdRUwo7RVq2RX9_fUbRX14yX7TbXfMbjjm7T2mB9dwVG3aTpumwYvBy-QmS6_0cqXTLFtlykp73Tpj9l6xsm1Nh-xW3IEa4MxarujF-c36Q5ZaMOzena8v3lgQf_nnuxjEPx-6YiqfHabGbAYzXMYTAIacK6YSFFSSuzaw3FcTrvIFAExy3z7lnv7C86PDhRSSBDwIiMc94nDHdwNP-KGMFqEXyIUr_qMQL-SOFzpESh5FUkYREYEf8jAMe8RBfO6cBnF9KXH2wLFIhJGoT3DXFcJ1e4IohId1utkf "PHP – Attempt This Online")
```
# No anchor - This regex will try starting its match at each
# character of the string until succeeding.
(?* # Non-atomic lookahead - Match the following, but then return
# to this position; if a non-match is subsequently found,
# backtrack to here and try other possible matches.
(.) # Capture the first digit in \1; this will be our return value.
.*(.*+) # Search for a \2 that is the last instance of the entire
# repeating pattern, using non-atomic lookahead.
)
( # Loop the following:
(.) # \4 = a digit
,? # Skip a decimal point if there is one here.
(?= # Positive atomic lookahead - Match the following, but then
# return to this position.
.*(?=\2$) # Skip to where \2 begins.
( # \5 = the following:
\5?+ # The previous value of \5, or nothing if this is the first
# iteration and \5 is unset.
,? # Skip a decimal point if there is one here.
\4 # Match a copy of the digit captured in \4.
)
)
)+ # Iterate as many times as possible (minimum one) to match the
# following assertion:
\5$ # Assert that the \5 we captured is identical to \2 and is
# located at the end of the string.
```
This uses a PCRE2 feature, non-atomic lookahead `(?*`...`)`. I'm pretty sure it's also possible to solve this without non-atomic lookahead, but I'll look into that later.
Note that the only reason this regex is so complicated is because of the presence of the decimal point. If not for that, the solution would be [`(?=(.+)\1$|.$).`](https://regex101.com/r/SDieAA/2) (which is what I came up with before realizing the decimal point was in the way, when I still wanted to return the output as the match instead of a capture group), or what is used in [ovs's Retina solution](https://codegolf.stackexchange.com/a/250067/17216), [`((.).*)\1$`](https://regex101.com/r/SDieAA/6).
But this is a pure regex solution, and can't do any substitutions before doing its matching work.
## \$\large\textit{Full programs}\$
# [Ruby](https://www.ruby-lang.org/) `-n`, 27 bytes
```
~/((.).*),?(.*)\1,?\3$/;p$2
```
[Try it online!](https://tio.run/##KypNqvz/v05fQ0NPU09LU8deA0jGGOrYxxir6FsXqBj9/29oZmquY25uDqKB4F9@QUlmfl7xf908AA "Ruby – Try It Online")
# Perl `-p`, 28 bytes
```
/((.).*),?(.*)\1,?\3$/;$_=$2
```
[Try it online!](https://tio.run/##bYtBCsIwEEX3c4pQgrQyaiZpkgmheJGCCxEUahvUlQfwAB7RgxhT3fqZP2/mw0@Hy2Dz/jidUy2HTu6aKOR9sUiX03ir@rGK8t5RFN9fyAEr8Xo8RRXzpq7XzXrZ4LYuuyfc9kZuotx1UueskJgYHDoHBg0oVFY7Q9ZzaL1x3Gr6k4DxqIxXwIwhMIcA5KxH7/3MIrCofgJtmcvMwGIIpRLmBmpNpPV8FBKZ4veUbqdpvOZV@gA "Perl 5 – Try It Online")
### \$\large\textit{Anonymous functions}\$
# [Ruby](https://www.ruby-lang.org/), 33 bytes
```
->s{s=~/((.).*),?(.*)\1,?\3$/;$2}
```
[Try it online!](https://tio.run/##bUxbasMwEPzfU6jBEKesHa0U64FQcxA7FELtViBMiB1KKe1nD9Aj9iKuRNK/Ljs7s4/Z8@X4tgx@qR6m98l/bsuy3tT3G9yXqXaE@04WW1eIjyV47tjrS4g9i/65nydgLAws3OX56TJPjvXjk2PBk8uL2FZ08H7VjSuXHLHldV2Jw@2qePRjiOnF6RzGmUV3E2v28/XN1n/t0MarY@FIhgwoVAokSuDIG6EkNdrYnZbK7AT9MwGpkUvNwRi01hhrgVSjUWudOQU0yK8BojEmZSZMAJssNjtQCCIhskhMJBN@AQ "Ruby – Try It Online")
# JavaScript (ES6), 37 bytes
```
s=>s.match(/((.).*),?(.*)\1,?\3$/)[2]
```
[Try it online!](https://tio.run/##bUxLTsMwFNz7FF6gxqYP158mtonSrjkDZRGlrggKTrFdWFTdcgCOyEWCAxsWHb15M3qaeS/texu70B/TnR/3bjo0U2w2kb22qXsmK0IYZbcUtiTvnYDtTt2s6KN8murY8Dq4t1MfHCmCa/dD711BWZd9cg8@uXBoO0fOvT@e0v0xjJ2LkcW07/2FstGT4rcBQ7M5I4wjXizwv9R4Suwj9Cl/3/mC1jg2os65q5FhWeDvzy9cLA9koLS@0ImDMMKgCqoKKVCIAy9lpUSpjV1rVZm1FFcuSGngSnNkDFhrjLVIVKUGrfWsGagE/gckS2PyzAKZyOaKnRsgpRBSziarECrzBw "JavaScript (Node.js) – Try It Online")
# [Julia](https://julialang.org) v0.4+, 38 bytes
```
s->match(r"((.).*),?(.*)\1,?\3$",s)[2]
```
[Try it online!](https://tio.run/##bUtbTsNADPz3KVYRH7vIrda7zT4UhR6E8hFotgRtU5SkEsoBOABH5CLBAcQXlj0zHnterrlr6G1J9TJu7s7N9PQsh0LKrdreKtxLxgPh/mBvChzVvXlY5jo1eWwrkS6DyKLrxdA2x9z17SgVCHHKl8cmi7nqEsPr0PVT7qWq2v5YibmehmvLX9@@zKr6VYX4fP8Qxd@e@KaAM4tGChTAoXNg0YJGXRpnqfQh7rx1YWfoHwesR229hhAwxhBiBHKlR@/9ylxQov4pMGUI3CshD0SOxDWBxhAZswpmIsvzBQ "Julia 1.0 – Try It Online")
# [R](https://www.r-project.org) v4.1.0+, 48 bytes
```
\(s)gsub('.*?((.).*),?(.*)\\1,?\\3$','\\2',s,,1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bU49a8MwEN31K0QoSApXo4_YkjDGf6B7Fy1pYwWBcYJkLwldu7drl7TQH5W1v6QyTrce9-7dHby79_EZL1---Z5Gf2-u3NHE9ml6oqRYt5QWrFgzaGmuzglonVN3BIhzkkACEOymO6eG1_jU-NB3dJXGXRhWrMb-EGmPw4DTdDzGLqXHbRzCsE80dtvdQxi6RE-MsTPCOPj8-nk7UuIGwurUiBrHxtM-35nXf0zwz-s7JrcpspfFwuX6xkEYYVAFVYUUKMSBl7JSotTGbrSqzEaKfzZIaeBKc2QMWGuMtUhUpQat9cw5UAl8CSRLY3LOBBnIZomdFSClEFLOTWYhVMbi7Bc)
# Java 8, 49 bytes
```
s->s.replaceAll(".*?((.).*),?(.*)\\1,?\\3$","$2")
```
[Try it online!](https://tio.run/##bVHLbtswELzzKzZqkJAyw@gR6wFFNnLpqe3FxzgHVpFsujQtiHTSoPW1H9BP7I@4K8tGgTqEqKV2dmZ2qZV8kTer5297tW43nYMVfoutU1o0W1M5tTHCL@AM9AtSaWktfJbKwA8C0G6/alWBddJheNmoZ1gjRmeuU2bx@ASyW1h2KAX4eNS@H1A@hAk0UO7tzcSKrm61rOoHrakn/Cmlggmf8SnF93we8ul8Hl963LuMPLYvUHNWSWPqDpRptw5KMPXrKUdnb9bVa6EMw0mMA1UGBbwula6BHurFUtov9XdHGTYIqqHqogzYkbZBvMX2nDa0FyjD4jDD0DNoNBtEDCp8UqY@VDVAtdC1WbglZZMArq5Ai2opuwdHA3ZRXn@4ZgcZFPrPh2oUOEt68OfXb/BYcWTd@qebtdhBI2Tb6reeesSbTddPhz@tn3Z1b4/d4Hk0Olm/Y24fV08j7yca@bfn6D8fNNrtdvuAh1mYkYQnCYl5TAIejKMkDsdplt@lcZLdReE7GRKnPIjTgGQZz/Msy3MSJuOUp2naR1xkzINhkWicZfj0geMmOVLynsGjKAyjqD9gDMMY918 "Java (JDK) – Try It Online")
Java's `split` method just doesn't work the right way to be useful for this.
# [PHP](https://php.net/), 54 bytes
```
fn($s)=>preg_split('/(?=(.+),?(.*)\1,?\2$)/',$s)[1][0]
```
[Try it online!](https://tio.run/##bYyxTsMwEIZ3P0UUWaoN19ZnN7GtYLKwsLDAlkRIoKSJFLVRUibEygPwiLxIOMPKyXe/9d93/9RP60059VPCu7B2J8EXGW6nuT0@L9M4XMRmL8ogdtcSSrG7kjVCWWsu9xsgssKmUs1adOdZ8CGogo@hO7aXRTw@3d0/yEK@J0Mn@Fgtl3lsKX2UW2xCSOtTKgle3l5oQzYo2KIsfulBtq/9OSJFQqlIcw48xhAQV0nKx@T784v8tPhYFaBDx3LIc2bAMAUq07nBzDp/sCZ3B43/OMxYUMYq5hx475z3DPPMgrU2KhXLQP0V05lz9KIANfN04uMFaI2odfyQIhrqHw "PHP – Try It Online")
# [Python](https://docs.python.org/), 57 bytes
```
lambda s:re.split(r'(.+),?(.*)\1,?\2$',s)[1][0];import re
```
[Try it online!](https://tio.run/##bU1bTsMwEPz3KSyBlIQukdduYjuV1VPwlfSjkAQsuU7kGKFegANwRC4SHB5/rHY0u6Od2fkaXybP15unqbf@2TwoYi/zFCJdrsthNN3qzpfH/kyXJgzlMjsb85Dl5a6AY17eFR3CseO3GSxFi6eWnQ6/9jCs1jAyToE6av0WVy4x/WgItSN1g89dQc@@p669x5MxWeezhjrjWtYk4fvKNnQO1se0GDz8ZUyvsXwLNg6522X08/2DZrsxpRUrA1SoSA11TQQIwoBVvBZYSaX3UtRqz/EfhQgJTEhGlAKtldKaYF1JkFJunIpUwH6K8Eqp1BtBAtHJojcHcI7I@TYkRhQJXw "Python 2 – Try It Online")
# [Python](https://docs.python.org/), 61 bytes
```
lambda s:__import__('re').split(r'(.+),?(.*)\1,?\2$',s)[1][0]
```
[Try it online!](https://tio.run/##bU5basMwEPzXKRZakNRsjR6xJTmYnKJfTjBpk7QCRTa2SskFeoAesRdx5Yb@ddhhdofZZYdreuujmu9e@qOPr82TJf4y9GOC6TptwDeCnPsRAvi4OMWUcqwm4M8QTpEFDod4hNA@yn3T0F2kNYQmtKLOxm/K1zCMPqY8NHLzd6N/T8XH6NOJhRWF788voCs2h8Pl@XiAqe662xNdx@h4oryYhuATGykrVhy3rHjgO4nbnbqnOPFW7luxn3n@hs8CpZWWVFhVRKMmAkWpKi1LY93a6MqulfzHIdqg0EYQa9E5a50jsioNGmMWzSAlihuIKq3NtQhmEpdX3LKBSkmp1NJklVJn/gA "Python 2 – Try It Online")
(If it must be a pure lambda.)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 19 bytes
Uses `,` as a decimal separator.
```
,
.*?((.).*)\1$
$2
```
[Try it online!](https://tio.run/##bYs7DgIxDET7OccW2ZW1sp2NPxUll6CAgoICCsT9QyJaRjN60kjvff88Xjfpz3K@dgL27VTKvu7bepEFi/bOJCEBIzNUqmDiplaleeTh1eJQ@fOgOnF1RgRlRmRCrDm5@@QIGvEv0BYxOkFjyKHkNEhVRPUL "Retina – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḟṂŒHÐƤEƇFḢ
```
A monadic Link that accepts a string of digit characters containing a decimal point, `.`, and yields a digit character.
**[Try it online!](https://tio.run/##y0rNyan8///hjvkPdzYdneRxeMKxJa7H2t0e7lj0//9/JWMgMDQyNDI1NjLUMwSRhkoA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##bY49CgJBDIX7nEPYLkwmO5PkAP5cxEb2ArbbbCteQBBLS4sV7Zbde4wXGWew9fEeX3jwIId91x1zTuMlPfv5vJtOy229DJs0XnN6Peb3NHz6@2qbc9M0DklJIWKMwMjg0AUfmYKotcJRW09/GmBBx@JAFc1UzYBiEBSRyiII6H4CH1SLK7AErEysLtB7Iu/rUUjEJeWnLw "Jelly – Try It Online").
### How?
```
ḟṂŒHÐƤEƇFḢ - Link: list of characters, N
Ṃ - minimum of N (guaranteed to be the '.')
ḟ - filter ('.') from N
ÐƤ - for each suffix of that:
ŒH - split into two halves
Ƈ - filter keep those which are:
E - all equal (i.e first half = second half)
F - flatten
Ḣ - head
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ ~~13~~ ~~12~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
RþηD2×Ãθθ
```
-1 byte porting [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/250082/52210)
-3 bytes thanks to *@CommandMaster* with a very smart usage of `Ã` as golf on my 13-byter(s)
[Try it online](https://tio.run/##yy9OTMpM/f8/6PC@c9tdjA5PP9x8bse5Hf//W@oZGBoaADEA) or [verify all test cases](https://tio.run/##bYsxCsJAEEX7OUVILcPMbHZnpkrjCbyBgoWVhSAE7AQPYONRksom/R7Ci6y72Pr5jw8P/vmyP5yO5Xadxr77PJ5dP05lt77zvJX1td7zkpeyKYRsbJAwJQgYgJCipMBRzQcNyQbhPwaCIgUlMEN3M3fgFBVVtW0NRKRfQKJZbRusgNeLtweKMItUQcxU@QI).
**Explanation:**
```
R # Reverse the (implicit) input
þ # Remove the dot by only keeping the digits
η # Pop and push a list of its prefixes
D # Duplicate this list of prefixes
2× # Double each string in the top prefixes-list
à # Only keep those doubled-prefixes from the prefixes-list
θ # Pop and push the last/longest
θ # Pop and push its last digit
# (which is output implicitly as result)
```
[Answer]
# [Python](https://www.python.org), ~~68~~ ~~62~~ 57 bytes
```
lambda x:re.split(r"(.+),?(.*)\1,?\2$",x)[1][0]
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVBLTsMwEBVbn2JksYhLGPnT-FOr6kGaLgIkIlKbRK4rlbOwqYTgTnAabAKsOmPPk97Ms0fv9WN6ic_jcHnr1vX7KXb39tPtm8PDUwPnVWjxOO37WARa4B0rNwUuWC3KTS1vaXlmW7Hb8h3pD9MYIoR2fuDrhsX2GNeUUo7CCutBEI1ae9BEofKgCEdeSa1EZaxbGqXtUoorjIeKKINcGZ5V1qJz1jrnwRKhK4PGmIwp8icV8jk8cCIra9PJgOl6kMQluctqRwRKKYSUiU57EpI3hjVsF4dmKv4NgPOvAdQDZSXkqT-mHihjOyDdGKAfpnI8xYQ_IysCMIV-iEVudLliaKd989gWFGmZkrEsYLNjl8uM3w)
Takes in a string with `,` as the decimal separator.
---
-6 bytes from @loopy walt by using `$` instead of reversal.
-5 bytes from @loopy walt / @DeadCode using the matching regex to ignore the `,` instead of adding a `re.sub`
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
←ḟoE½ṫf±
```
[Try it online!](https://tio.run/##bYu9DcJADIV3uRpZZzvnH1EzBaJFSCiiQAwABTUbMAAVXShoskmyyOFTWp5sv09PfofL@Vj7dT/frnW@P6bhedqM3@nz2o/vWus2ZUBDS6skIBLGwHEz5ELCWNS8UxbrCP8k7V8hszYyA3cz92CUoqCqzUORFMiLgqmYxTSD2Eg8qr40gQiRaMEgRI5Nux8 "Husk – Try It Online")
```
f # filter to keep only
± # characters that are digits,
ḟ # now get the first
ṫ # of all the tails (possible 'bb's)
oE½ # which is two copies of the same thing,
← # and return the first element.
```
[Answer]
# [Raku](http://raku.org/), 31 bytes
```
{+(S/\.//~~/((.).*?)$0$/)[0;0]}
```
[Try it online!](https://tio.run/##bYvBCsIwEER/ZShFWoXNbmKSDdr6ER5VxIM9KYqeirS/XlO8OszwhoF5Xl@3MN17LDo002dV7c2RjBlHU1VU03JXl1ya@sAbPg3T@9KjKM9oWnw6lOehQPd4YcskKopAIcCRAxN7G5z4qGkdXdC1lT8LXCR2kaFKKammBAk@UoxxZhY88U@wXjV7BuUg5UuaH2StiLVzyRRxOe30BQ "Perl 6 – Try It Online")
`S/\.//` returns a copy of the input string with the decimal point removed. That string is matched with `~~` against the pattern `((.) .*?) $0 $`, which looks for the repeating portion at the end of the string. `[0; 0]` looks up the first submatch group of the first match group (ie, the digit matched by the `(.)`) and `+` converts that match object to an integer.
[Answer]
# Excel, ~~118~~ 104 bytes
```
=LET(a,MID(SUBSTITUTE(A1,".",),ROW(1:32767),2^15),b,LEFT(a,LEN(a)/2),LEFT(INDEX(b,MATCH(TRUE,a=b&b,0))))
```
Input is in cell A1 of the active sheet. Output is wherever the formula is. Breaking down the `LET()` function into the `variable,value,...,output` format, we get this for the first two terms:
* `a,MID(SUBSTITUTE(A1,".",),ROW(1:32767),2^15)` removes any decimal point and then creates an array 32767 rows tall where each row removes another character from the beginning of the string. Most of this array will be empty, of course, but this is to accommodate the [max number of characters allowed per cell](https://support.microsoft.com/en-us/office/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3).
* `b,LEFT(a,LEN(a)/2)` creates an equally tall array of the first half of the first array.
Now it gets into the more complicated final term:
```
LEFT(INDEX(b,MATCH(TRUE,a=b&b,0))))
```
* `MATCH(TRUE,a=b&b,0)` finds the first row where `a` is exactly `b` twice.
* `INDEX(b,MATCH(~))` pull the entire value of `b` from the array at that point.
* `LEFT(INDEX(~))` outputs the first character of that result.
---
Screenshot with details for one of the test cases:
[](https://i.stack.imgur.com/sxYkg.png)
---
Screenshot with all the test cases:
[](https://i.stack.imgur.com/o8V1S.png)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~13~~ 10 bytes
```
~±ÞKvI~≈fh
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwifsKxw55Ldkl+4omIZmgiLCIiLCJcIjAuMTgxOFwiXG5cIjYuNjZcIlxuXCIzLjNcIlxuXCIwLjA1MjYzMTU3ODk0NzM2ODQyMTA1MjYzMTU3ODk0NzM2ODQyMTBcIlxuXCIzNy4wMzcwXCJcblwiODguOTk4ODk5XCJcblwiMTY1Ny43NzcxNjU3Nzc3XCJcblwiNS4wMDAwMDAwXCJcblwiMjU4ODU4ODI1ODguNTg4XCJcblwiOS45OTk5OVwiXG5cIjEuMjIxMTIyXCJcblwiMS4yMTEyMTEzMjExXCIiXQ==)
```
~±ÞKvI~≈fh
~± # Filter for numeric, to remove the ".". Converts to list of chars
ÞK # Suffixes
vI # Split each into a list of two halves
~≈ # Filter for all equal
f # Flatten
h # First item
```
Original 13 bytes was porting UnrelatedString's Jelly answer, but porting Jonathan Allan's answer saved 3 bytes, so upvote those two!
Alternative:
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
goÞK½~≈hhh
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiZ2/DnkvCvX7iiYhoaGgiLCIiLCJcIjAuMTgxOFwiXG5cIjYuNjZcIlxuXCIzLjNcIlxuXCIwLjA1MjYzMTU3ODk0NzM2ODQyMTA1MjYzMTU3ODk0NzM2ODQyMTBcIlxuXCIzNy4wMzcwXCJcblwiODguOTk4ODk5XCJcblwiMTY1Ny43NzcxNjU3Nzc3XCJcblwiNS4wMDAwMDAwXCJcblwiMjU4ODU4ODI1ODguNTg4XCJcblwiOS45OTk5OVwiXG5cIjEuMjIxMTIyXCJcblwiMS4yMTEyMTEzMjExXCIiXQ==)
```
goÞK½~≈hhh
g # Minimum (".")
o # Remove it
ÞK # Suffixes
½ # Split each into a list of two halves
~≈ # Filter for all equal
h # First list
h # First string
h # First character
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
ịˢa₁~jh
```
[Try it online!](https://tio.run/##bYsxCgJBDEWvskytYZLZmWQaPYhYrBYuIgg2i4iCWwhi4xk8gY2NHsFT7F5kzLCtnyT/8clf7Kplvd9sV5QOjSnGk8I00/7y7Nu2e1@P3eueus/t@6j69nxa1ynNjAUUFDMyAUJQc@D0WrCegkPPEkt2QUrCP0n@Z7COM4lAjCIxKmPwDMycXaWJBztImbyITjbQ1SRqNQ5NIEIkGlAJ0ema@Q8 "Brachylog – Try It Online")
```
ịˢ Filter the input to only digits.
a₁ For some suffix (tried longest first),
h output the first element of
~j a list which repeated twice is the suffix.
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 26 bytes
```
**((~/2 0N#)')#(1_)\(46=)_
```
[Try it online!](https://ngn.codeberg.page/k#eJxtTLkNwzAM7D2FIReRXDAiKfEJkBUyQQB3HiOzRw/c+UDiHoJ3vvY9xt+T1vzZ0iNtEY/0jUXe6ViWcw0Z0NBClwIiQzBwmLdcSRirmhdlsUJ4k8wfhcw6tRm4m7kPh1IVVLVzw8gq5InhqJq16QRtR+atwq8GIEIkukzTiNw2/AElDis5)
## Explanation
* `(46=)_` remove decimal
* `(1_)\` generate suffixes
* `((...)')#` filter each suffix...
+ `2 0N#` halve suffix
+ `~/` check if halves are equal
* `**` first of first
[Answer]
# [Python](https://www.python.org), 74 bytes
```
f=lambda s,i=0:s[n:=i-len(s)]*(s[n:]==s[2*n:n])or f(s.replace(".",""),i+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bU45bsMwEOz5CkIV6cgLHhYPEaoD5AuGCiWRYAIyRYhKkbekUeP8yb8JCbvMYBeDHezM7s9v_N4uS9j329c2Hc39berm4fr-OeBU-4616Rzazh_nMZBE-wMpc9916SwOoQ09XVY8kQTrGOfhYyQVVHVV0dq_cPpMfJ3yzuzDiH3AS8xBjLYI-3rprkMkaVsht4912YEUZ7-RylWUIhxXHzYyEU_r5Rm3328MuOHGYY4UKOWwQhKkwxIxYI1Qkjfa2JOWypwE_0dxuEFSA5OaFZcxYK0x1jpsEFeNBq114YxypAH2gMMMicaYXIUgt8MC2Wy3xW0RByE4FyLLj2__AA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ḟ”.ŒHẆf/ƊÐƤFḢ
```
[Try it online!](https://tio.run/##bY4xCgJBDEX7XGS7OMnsTDIXEK/gAbSQvYCdWChYib0IYmlpsWi5uPcYLzJmsPXzPy98@JDVouvWpeT@8tmc8X2a5eduORkPw3G8TXN/Lfn1GPaf7X1eStM0DklJIWKM4NGDQxc4egqiqRUftWX604AXdF4cqGJKqikBxSAoIpUmCOh@Ag6q5gq0QLJJqgtkJmKuh5HIW@ynLw "Jelly – Try It Online")
```
ḟ”. Remove the radix point.
ƊÐƤ For each suffix:
ŒH Split it in half,
/ and reduce
Ẇ the sublists of the pair of halves
f by filter left by membership in right.
F Flatten the results
Ḣ and yield the first element.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 46 bytes
```
s=>/^.*?(.*)\1$/.exec(s.replace('.',''))[1][0]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVFLbsIwEFW3PoUXSLZpGGKHxE5RwqqnACqi4LRIIYnykZAQJ-kGVe2RumhPUxsX1EVHHs28mfeeLfn1vaq3-vxWJB9DX0zUF3RJOn2C8YLCmK34aAr6oHPaQaubMss1JUA8Qhhb8vXSXzvV993nHKEN8oErrvAkxRxFEEW2i1AAgW0Cs_ZDEQU8lCqeySBSM8H_mVhyiAIJfiB9p1QK4lipOLZQIR6FEqSUtppwF4bgu7DQRyJUyhxbwKQdChQbm9i5xIiDEJwL4VYGGcB5YNIZbqBvd3vKoGvKXU_JqiIMirp9zPIX2uuux0mKjwjjvK4MWHp4VzVD72F9aHTer3GCLQv2WW8EUwr3zBrbOmXzm67V3VAaL1zQi_7Pqsm6ziyujOTX-UqoSw1l_UwvtAUmq0FIPyT4wbWznNyeRCapAc7Iw1eBpW6oM9VbPDq69sQ25hEnNne_ez67-gM)
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 65 bytes
```
f=lambda s:(s:=s.replace('.',''))[:s==s[:len(s)//2]*2]or f(s[1:])
```
[Try it online!](https://tio.run/##bY0/b8IwEMV3f4rb4lTIxDaJ/ykjXbt0QwwBjIgaEss2avn06ZmuPfnpnZ7vdxee@bbMUoe4rtd@Gu6nywDJ0mT7xKIP03D2tGLVpqrq@mBT36eDnfxMU73diuObOC4RrjQduD3W6/dtnDx8xoe3BCDHZzGAcQ4bWB4ZergPgaYcGWrEEH8emdYshWnMtHJ45EWEOM6ZIrLB5Tj0iv3P2YcM@4/3fYxLtHCKfvhaG8Y11w446VjXOeiIZNKBJA1rWtFJ3iptdkp2eif4P4mDlkjFGqmaQmnNjNHaGAea8K5VTClVHKscaVnzVw4aIlqt8RVjKAeCGMRNoQ3hTAjOhSgx9thyLlG45hc "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [lin](https://github.com/molarmanful/lin), 35 bytes
```
"\, !="`#"1`d"`it"`bi \`= `/"`?' `^
```
[Try it here!](https://replit.com/@molarmanful/try-lin) Takes string with `,` comma.
I recently added string literals to lin, still not sure if I regret doing so...
For testing purposes:
```
"1,2112113211" ; outln
"\, !="`#"1`d"`it"`bi \`= `/"`?' `^
```
## Explanation
More readable version:
```
( \, != ) `# ( 1`d ) `it ( `bi \`= `/ ) `?' `^
```
* `( \, != ) `#` filter out comma
* `( 1`d ) `it` generate suffixes
* `(...) `?'` find first suffix that satisfies the following...
+ ``bi` split suffix in half
+ `\`= `/` check if both halves are equal
* ``^` first element
[Answer]
# Excel VBA, 107 bytes
```
Sub o(a)
a=Replace(a,".","")
b=Left(a,Len(a)/2)
If a=b &b Then MsgBox Left(b,1):Exit Sub
o Mid(a,2)
End Sub
```
1. Remove any decimal points from the input.
2. Get the first half (rounded up) of the input.
3. If the whole string is the first half twice, output the first digit of `b` to a message and exit.
4. Otherwise, remove the first letter from the input and recurse.
---
VBA will pad the code with spaces automatically. The above input is valid but here's what it looks like after that auto-formatting:
```
Sub o(a)
a = Replace(a, ".", "")
b = Left(a, Len(a) / 2)
If a = b & b Then MsgBox Left(b, 1): Exit Sub
o Mid(a, 2)
End Sub
```
[Answer]
# [Python 3](https://docs.python.org/3/), 93 bytes
```
def f(s):s=s.replace(".","");return[s[-i:][0]for i in range(len(s))if s[-i:]==s[-2*i:-i]][-1]
```
[Try it online!](https://tio.run/##bY7dasMwDIXv9xQhN3VGIyy7tuWMPEnIRdmczVDc4GQXffpUbWGYMCFx4NPP0Xxbf65Jb9tXmKpJLE239AvkMF/On0HUUB/ruvnIYf3NaViGNnbjIMfpmqtYxVTlc/oO4hISbzZxql4Tfc@q3mPXxnEcWhy3Oce0ikkcJCAhHZojNm9/0IK1jGyBNGgmuiASpFFWo3HkT05bOin8h/CWKe84kNrJ3S0i8J7Ie@ZUcLTGgXPuoRy7Nw3IVzCXBVeGiPMhwMVdVXQ9W/mnky@dQClEpXbDjJkiaq6n@3YH)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
§⊟ΦEθ…⮌⁻θ.κ¬⌕⮌⁻θ.×²ι±¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMOxxDMvJbVCIyC/QMMtM6cktUjDN7FAo1BHwbkyOSfVOQMoHpRallpUnKrhm5lXWgySUtJT0tTUUcgGEX75JUCNeSk4VYVk5qYWaxjpKGRqggBQR2p6YkmqhiGQY/3/v5GphQUQgSg9IP6vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input string
E Map over characters
θ Input string
⁻ . With `.`s removed
⮌ Reversed
… Truncated to length
κ Current index
Φ Filtered where
⌕ Index of
ι Current reversed suffix
ײ Repeated twice
θ In current string
⁻ . With `.`s removed
⮌ Reversed
¬ Is zero
⊟ Take the longest reversed suffix
§ ±¹ Take its last character
Implicitly print
```
[Answer]
# [Haskell](https://www.haskell.org), ~~95~~ 83 bytes
*-12 bytes thanks to [@Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)*
```
g.filter(>'.')
g x=[x!!d|d<-[0..],uncurry(==)$div(length x-d)2`splitAt`drop d x]!!0
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZHRaoMwFIbZrU9xlIIKNSSxmgTmYM_QSye01NrKrBUTNwt7gz3CbgpjbK-0PU2T2WEp-8nhcL6TnD8kb5_bpXxcV9VX6gSrpnGy9yJ5-OhUEfDv-QYVZaXWrXfnIte3NtAnaW_b-Ut-G6QYoWza1auubQ9ekviTvHzyqnW9UVvog9ynC9lUpbpXi7zdN5BDn9k2Hkb_3LwqSCC1QMtzMCKccGcKLnH96RnGKI4NikcUotCQcCQY4YjGIYkYFzMWxnxGyT_EnIou5jCEQ4avZnGOhOBcCMP5yEkcMcQYM1nr6poRwoMMxyOnEed6mYR0mC4du0JbicFJXDghSgmh9GqzxpoSEuo4u2eW1Uv9grtlA4VUoKzDXynrXJdWq0vvtw299CFJ4CCt3bKsNW86NVctTEBu98_QDn9yPA75BA)
] |
[Question]
[
# Definition
>
> In Mathematics, **Harmonic Sequence** refers to a sequence where
>
>
> $$a\_n = \frac 1 n$$
>
>
> i.e. the \$n\_{th}\$ term of the sequence equals the reciprocal of \$n\$.
>
>
>
---
## Introduction
In this challenge, given a positive integer \$n\$ as input, output the Partial Sum of first \$n\$ terms of the Harmonic Sequence.
---
# Input
You'll be given a positive integer (within the range of numbers supported by your language). It can be either of Signed and Unsigned (depends on you), since the challenge requires only positive integers.
You can take the input in any way except assuming it to be present in a predefined variable. Reading from file, terminal, modal window (`prompt()` in JavaScript) etc. is allowed. Taking the input as function argument is allowed as well.
---
# Output
Your program should output the sum of the first \$n\$ terms of the Harmonic Sequence as a float (or integer if the output is evenly divisible by 1) with precision of 5 significant figures, where \$n\$ refers to the input. To convey the same in Mathematical jargon, you need to compute
$$\sum\_{i=1}^n \frac 1 i$$
where \$n\$ refers to the input.
You can output in any way except writing the output to a variable. Writing to screen, terminal, file, modal window (`alert()` in JavaScript) etc. is allowed. Outputting as function `return` value is allowed as well.
---
# Additional Rules
* The input number can be either of 0-indexed or 1-indexed. You must specify that in your post.
* You must not use a built-in to calculate the partial sum of the first \$n\$ elements. (Yeah, it's for you Mathematica!)
* You must not [abuse native number types to trivialize the problem](https://codegolf.meta.stackexchange.com/a/8245).
* [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
---
# Test Cases
The Test Cases assume the input to be 1-indexed
```
Input Output
1 1
2 1.5
3 1.8333
4 2.0833
5 2.2833
```
---
# Winning Criterion
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
[Answer]
# Python 3, 27 bytes
```
h=lambda n:n and 1/n+h(n-1)
```
[Answer]
# JavaScript, ~~19~~ 18 bytes
*1 byte saved thanks to @RickHitchcock*
```
f=a=>a&&1/a+f(--a)
```
This is 1-indexed.
```
f=a=>a&&1/a+f(--a)
for(i=0;++i<10;)console.log(f(i))
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 5 bytes
```
+/÷∘⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/FR2wRt/cPbH3XMeNS7@f//R20TNdQd1XUedS3SUbdV13HUPLQCKGFoYAAA "APL (Dyalog Unicode) – Try It Online")
You can add `⎕PP←{number}` to the header to change the precision to `{number}`.
This is 1-indexed.
### Explanation
```
+/÷∘⍳ Right argument; n
⍳ Range; 1 2 ... n
÷ Reciprocal; 1/1 1/2 ... 1/n
+/ Sum; 1/1 + 1/2 + ... + 1/n
```
[Answer]
# Mathematica, ~~21~~ ~~20~~ 16 bytes
This solution is 1-indexed.
```
Sum[1./i,{i,#}]&
```
[Answer]
# PHP, 33 Bytes
1-indexing
```
for(;$i++<$argn;)$s+=1/$i;echo$s;
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zNbX@n5ZfpGGtkqmtbQMWstZUKda2NdRXybROTc7IVym2/v8fAA "PHP – TIO Nexus")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 18 bytes
```
n->sum(i=1,n,1./i)
```
1-indexing.
[Try it online!](https://tio.run/nexus/pari-gp#S1OwVfifp2tXXJqrkWlrqJOnY6inn6n5Py2/SCMPKGeoo2BooKNQUJSZVwIUUFLQtQMSaRp5mpqa/wE "Pari/GP – TIO Nexus")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 11 bytes
```
1.ri,:)f/:+
```
[Try it online!](https://tio.run/##S85KzP3/31CvKFPHSjNN30r7/39TAA "CJam – Try It Online")
1-indexed.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-x`, ~~8~~ ~~6~~ ~~5~~ 3 bytes
```
õpJ
```
With some thanks to ETHproductions
[Try it online](http://ethproductions.github.io/japt/?v=1.4.4&code=9XBK&input=NQoteA==)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
İ€S
```
[Try it online!](https://tio.run/##y0rNyan8///IhkdNa4L///9vCgA "Jelly – Try It Online")
1-indexed.
Explanation:
```
İ€S Main link, monadic
İ€ 1 / each one of [1..n]
S Sum of
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~11~~ 10 bytes
*1 byte removed thanks to Erik the outgolfer*
```
ri),{W#+}*
```
This uses 1-based indexing.
[Try it online!](https://tio.run/nexus/cjam#@1@UqalTHa6sXav1/78pAA "CJam – TIO Nexus")
### Explanation
```
ri e# Read integer, n
) e# Increment by 1: gives n+1
, e# Range: gives [0 1 2 ... n]
{ }* e# Fold this block over the array
W# e# Inverse of a number
+ e# Add two numbers
```
[Answer]
## Haskell, 20 bytes
```
f 0=0
f n=1/n+f(n-1)
```
## Original solution, 22 bytes
```
f n=sum[1/k|k<-[1..n]]
```
These solutios assumes 1-indexed input.
[Answer]
# [R](https://www.r-project.org/), 15 bytes
```
sum(1/1:scan())
```
[Try it online!](https://tio.run/nexus/r#@19cmqthqG9oVZycmKehqfnf9D8A "R – TIO Nexus")
[Answer]
## Tcl 38 bytes
```
proc h x {expr $x?1./($x)+\[h $x-1]:0}
```
That's a very dirty hack, and the recursive calls pass literal strings like "5-1-1-1..." until it evaluates to 0.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
LzO
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fp8r//39TAA "05AB1E – Try It Online")
1-indexed.
[Answer]
# Axiom, ~~45~~ 34 bytes
```
f(x:PI):Any==sum(1./n,n=1..x)::Any
```
1-Indexed; It has argument one positive integer(PI) and return "Any" that the sys convert
(or not convert) to the type useful for next function arg (at last it seems so seeing
below examples)
```
(25) -> [[i,f(i)] for i in 1..9]
(25)
[[1,1.0], [2,1.5], [3,1.8333333333 333333333], [4,2.0833333333 333333333],
[5,2.2833333333 333333333], [6,2.45], [7,2.5928571428 571428572],
[8,2.7178571428 571428572], [9,2.8289682539 682539683]]
Type: List List Any
(26) -> f(3000)
(26) 8.5837498899 591871142
Type: Union(Expression Float,...)
(27) -> f(300000)
(27) 13.1887550852 056117
Type: Union(Expression Float,...)
(29) -> f(45)^2
(29) 19.3155689383 88117644
Type: Expression Float
```
[Answer]
# Pyth, 5 bytes
```
scL1S
```
[Try it here.](http://pyth.herokuapp.com/?code=scL1S&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5&debug=0)
1-indexed.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
ṁ\ḣ
```
[Try it online!](https://tio.run/##yygtzv7//@HOxpiHOxb////fFAA "Husk – Try It Online")
Output is a fraction.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 3 bytes
```
ɾĖ∑
```
Lame answer, but range -> reciprocal -> sum -> implicit out, same as jelly
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C9%BE%C4%96%E2%88%91&inputs=5&header=&footer=)
# [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 2 bytes
```
ɾĖ
```
2 Bytes w/ -s from @lyxal, -s sums the stack
[Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%C9%BE%C4%96&inputs=5&header=&footer=)
[Answer]
# MATL, 5 bytes
```
:l_^s
```
This solution uses 1-based indexing.
Try it at [MATL Online](https://matl.io/?code=%3Al_%5Es&inputs=10&version=20.0.0)
**Explanation**
```
% Implicitly grab input (N)
: % Create an array from [1...N]
l_^ % Raise all elements to the -1 power (take the inverse of each)
s % Sum all values in the array and implicitly display the result
```
[Answer]
# C, 54 bytes
```
i;float f(n){float s;for(i=n+1;--i;s+=1./i);return s;}
```
Uses 1-indexed numbers.
[Answer]
## Haskell, 21 bytes
```
f n=sum$map(1/)[1..n]
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes
```
⟦₁/₁ᵐ+
```
[Try it online!](https://tio.run/nexus/brachylog2#@/9o/rJHTY36QPxw6wTt//9N/0cBAA "Brachylog – TIO Nexus")
This is 1-indexed.
### Explanation
```
⟦₁ Range [1, …, Input]
ᵐ Map:
/₁ Inverse
+ Sum
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 13 bytes
```
[:|c=c+1/a]?c
```
Explanation
```
[ | FOR a = 1 to
: the input n
c=c+ Add to c (starts off as 0)
1/a the reciprocal of the loop iterator
] NEXT
?c PRINT c
```
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 8 bytes
```
F1LP,+|B
```
[Try it online!](https://tio.run/##S8/PScsszvhv6Oju6Wrt7vffzdAnQEe7xun/f0MuIy5jLhMuUy5DAyAyAAA "Gol><> – Try It Online")
### Example full program & How it works
```
1AGIE;GN
F1LP,+|B
1AGIE;GN
1AG Register row 1 as function G
IE; Take input as int, halt if EOF
GN Call G and print the result as number
Repeat indefinitely
F1LP,+|B
F | Repeat n times...
1LP, Compute 1 / (loop counter + 1)
+ Add
B Return
```
[Answer]
# [Rust](https://www.rust-lang.org/), 36 bytes
```
|n|(1..=n).map(|n|1./n as f64).sum()
```
[Try it online!](https://tio.run/##ZcmxDkVAEEDR3lcM1UzCyHqPgvAvW5hkEzsRuyp8@6JW3nO3PcQkCt46RYIDljmC9KLofg1Vk3T/MZ16omEeldjbFZ80XCvYAM8mDrtHSkO2bk7jojkWx1WUgoboi@2LV7oB "Rust – Try It Online")
Input is an integer, if the input is <=0 the output is zero, and inputting one gets one.
[Answer]
# [J](https://www.jsoftware.com), 9 bytes
```
1#.1%1+i.
```
I'm only posting this because I think it looks really pretty.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmux0lBZz1DVUDtTD8LfpMmVmpyRr5CmZqdgZ6WQqadgCpFYsABCAwA)
```
1#.1%1+i.
i. NB. range 0..n-1
1+ NB. add 1
1% NB. 1 divided by each element
1#. NB. sum the result
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 3 bytes
```
ř⅟Ʃ
implicit input
ř produces a list containing 1 to n
⅟ takes the reciprocals
Ʃ sums the list
(implicit print)
```
[Try it online!](https://tio.run/##K6gs@f//6MxHrfOPrfz/39AAAA "Pyt – Try It Online")
[Answer]
# [Scala](https://www.scala-lang.org/), 47 bytes
[Try it online!](https://tio.run/##HY2xCsIwGIT3PsVROuRHrO3gEogguDg4iZM4pDVtI/WvJHGQ0mevaQ9uuu/jfK17PQ/Vy9QBF20Z4/w0DTrB8syB5Gn4Vr1RthGsVEEFTO8NyrzY8SZC25JmYDHeURbatV7i6Jz@3a/BWW4fJHFjG6AwJogRJcKAPeXN4IyuO4xgqMO6AZ/ohJ6FTzuRMUUrG@MNTSmtxJQsneY/)
```
def h(n:Int):Double=if(n==0)0 else 1.0/n+h(n-1)
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `S`, 2 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
RỊ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPVIlRTElQkIlOEEmZm9vdGVyPSZpbnB1dD01JmZsYWdzPVNl)
#### Explanation
```
RỊ # Implicit input
R # One range
Ị # Reciprocal
# Take the sum
# Implicit output
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 35 bytes
```
float f(n){return n?1./n+f(--n):0;}
```
[Try it online!](https://tio.run/nexus/c-gcc#FYxBDoIwEEWv8oMhmUkBy1ZQL@KGWCZOglNSy4p4dqyr/15e8k9qz2ULM8ZPDhq71@2QJU4ZQsZ7mvOWDHbvu7M5obY1vvjhe6hlvCc14l1ior8qrvBDmRG9RwHnwFhTaUJVHRi1PKxqtBFS5nLyAw "C (gcc) – TIO Nexus")
] |
[Question]
[
Write a program that takes an input such as:
```
n,k
```
which then computes:
$$\binom n k = \frac {n!} {k!(n-k)!}$$
and then prints the result.
---
A numerical example:
Input:
```
5,2
```
Internal computation:
$$\frac {5!} {3!\times2!}$$
Printed Output:
```
10
```
---
I'd like to see an answer that beats my python solution of 65 characters, but all languages are obviously welcome.
Here's my solution:
```
n,k=input();f=lambda x:+(x<2)or x*f(x-1);print f(n)/(f(k)*f(n-k))
```
**Edit:**
I admit that this question is from the [codegolf website](http://codegolf.com/choose) mathematical combination puzzle. I know that my answer may look like not much progress can be made on it, but the leaders of this puzzle have solved it in nearly half as many characters.
[Answer]
## C 96
With I/O (which takes about 34 chars). Added a couple of newlines to make it readable.
```
main(a,b,c,d){scanf("%d,%d",&a,&b);
d=a-b;for(c=1;a>b;){c*=a--;}for(;d;)
{c/=d--;}printf("%d",c);}
```
Now if you'll excuse me, I have an ASCII n choose k rocket to catch.
```
d;main(a
, b
, c
) int a
; {scanf (
( "%d %d" )
, &a, &b )
; d =a -
b + b -
b * 1 ;
a -
a ;for ( c
= 1;a> b ;
) {c= c *
( (a-- ) )
; }for( b
= b + 1 ;
d ; ) {
c = c /
( d-- ) ;
} {
} {
} (
printf("%d",c)
) ; }
/* * * * *\
* * X * 8 * * |
| * * \
*/ // * */
```
[Answer]
# APL, 3 bytes
```
⎕!⎕
```
Or for those whose browser doesn't render the above, in an ASCII rendering:
```
{Quad}!{Quad}
```
[Answer]
# R (11 Chars)
```
choose(n,r)
```
[Answer]
## GolfScript, 17 chars
This solution handles cases like k=0 or k=1 correctly.
```
~>.,,]{1\{)*}/}//
```
Factorial-like portion is based off [a previous answer](https://codegolf.stackexchange.com/questions/607/find-the-factorial/629#629).
[Answer]
# GolfScript 21
```
~~)>.,,]{{)}%{*}*}%~/
```
Not particularly short, GolfScript lacks a real factorial function, however this has got to be the most wicked data manipulation that I have ever done, this calls for a stack trace:
"5,2" Data on the stack from input.
`~` Eval command, note that , is an operator that turns a number into an array.
[0 1 2 3 4] 2
`~` Binary not.
[0 1 2 3 4] -3
`)` Increment.
[0 1 2 3 4] -2
`>` Take end of array, -2 as parameter to get the last 2 elements.
[3 4]
`.` Duplicate element.
[3 4] [3 4]
`,` Array length.
[3 4] 2
`,` Turn number to array.
[3 4] [0 1]
`]` Create array.
[[3 4] [0 1]]
`{{)}%{*}*}` Block of code.
[[3 4] [0 1]] {{)}%{\*}\*}
`%` Execute block once for each element of the array. The following part only demonstrate the first loop.
[3 4]
`{)}%` Increment each array element.
[4 5]
`{*}` Block containing a multiply command.
[4 5] {\*}
`*` "Fold" the array using the block command, that is in this case make the product of all elements.
20
After the big loop has finished it returns an array with the results.
[20 2]
`~` Deconstruct the array.
20 2
`/` Division.
10
[Answer]
## Ruby 1.9, ~~52~~ 46 (42) characters
```
eval"A,B="+gets;i=0;p eval"(A-B+i+=1)/i*"*B+?1
```
If stderr is ignored:
```
eval"A,B=I="+gets;p eval"I/(A-I-=1)*"*B+?1
```
Ruby 1.8, 43 characters, no additional output to stderr:
```
eval"a,b=i="+gets;p eval"i/(a-i-=1)*"*b+"1"
```
Edits:
* (52 -> 48) Found a shorter way to parse the input
* (48 -> 46) Less looping, more eval.
[Answer]
## Python (56)
```
f=lambda n,k:k<1and 1or f(n-1,k-1)*n/k;print f(*input())
```
Ungolfed code and some explanation of a shortcut for calculating the binomial coefficient. (Note: There is some insight that I just haven't figured out in order to get down to the 39 char version; I don't think this approach will get you there.)
```
# Since choose(n,k) =
#
# n!/((n-k)!k!)
#
# [n(n-1)...(n-k+1)][(n-k)...(1)]
# = -------------------------------
# [(n-k)...(1)][k(k-1)...(1)]
#
# We can cancel the terms:
#
# [(n-k)...(1)]
#
# as they appear both on top and bottom, leaving:
#
# n (n-1) (n-k+1)
# - ----- ... -------
# k (k-1) (1)
#
# which we might write as:
#
# choose(n,k) = 1, if k = 0
# = (n/k)*choose(n-1, k-1), otherwise
#
def choose(n,k):
if k < 1:
return 1
else:
return choose(n-1, k-1) * n/k
# input() evaluates the string it reads from stdin, so "5,2" becomes
# (5,2) with no further action required on our part.
#
# In the golfed version, we make use of the `*` unpacking operator,
# to unpack the tuple returned by input() directly into the arguments
# of f(), without the need for intermediate variables n, k at all.
#
n, k = input()
# This line is left as an exercise to the reader.
print choose(n, k)
```
[Answer]
## RPL (4)
(using built-in function)
```
COMB
```
[Answer]
## Windows PowerShell, 57
```
$a,$b=iex $input
$p=1
for($a-=$b;$a-ge1){$p*=1+$b/$a--}$p
```
[Answer]
# J, 33 36
```
(":!~/".;._1}:toJ',',1!:1(3))1!:2(4)
```
35 characters are input, parsing and output. The other character, `!`, is n choose k.
I don't have Windows around for testing this at the moment, but I believe it should work there.
[Answer]
# Q, 32 chars
```
{f:{1*/1.+(!)x};f[x]%f[y]*f x-y}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
n,k=input()
B=2<<n
print(B+1)**n/B**k%B
```
[Try it online!](https://tio.run/##K6gsycjPM/pfnpGZk6pgaJVakZqspKT0P08n2zYzr6C0REOTy8nWyMYmj6ugKDOvRMNJ21BTSytP30lLK1vV6T9IraGBjiEXkDDiMtAx4DLVMQYA "Python 2 – Try It Online")
A full program, as the challenge asks for. The method is explained in [this tip](https://codegolf.stackexchange.com/a/169115/20260).
[Answer]
## Perl 6 (55)
```
my ($a,$b)=lines;$_=1;for 1..$a-$b {$_+=$_*$b/$^a};.say
```
[Answer]
## RPL (22)
(not using built-in COMB function)
```
→ n k 'n!/(k!*(n-k)!)'
```
[Answer]
## Q (50 45)
```
f:{(prd 1.+til x)%((prd 1.+til y)*prd 1.+til x-y)}
```
You can shave a few characters off the above by removing redundant brackets and using 1\*/ instead of prd.
```
f:{(1*/1.+til x)%(1*/1.+til y)*1*/1.+til x-y}
```
[Answer]
# Mathematica 12
Straightforward, built-in function.
```
n~Binomial~k
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~25~~ 16 bytes
*-9 bytes thanks to nwellnhof*
```
+*o&combinations
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX1srXy05PzcpMy@xJDM/r/i/NVdxYqVCmoapjpEmjG1ogMwx1TE00LT@DwA "Perl 6 – Try It Online")
Anonymous function that takes two numbers and returns an int. This uses the built-in `combinations` and converts the returned list to an int.
[Answer]
## PHP (71 79)
```
<?$a=fgetcsv(STDIN);$x=1;while($a[1]-$i)$x=$x*($a[0]-++$i+1)/$i;echo$x;
```
```
<?php $a=fgetcsv(STDIN);$x=1;while(++$i<=$a[1])$x=$x*($a[0]-$i+1)/$i;echo $x?>
```
[Answer]
# Python (54)
```
f=lambda n,k:k<1or f(n-1,k-1)*n/k;print 1*f(*input())
```
Essentially the same as the Python one above, but I shave off four bytes by dropping the
```
and 1
```
from the function definition. However, this results in the function returning True instead of 1 if k=0, but this can be fixed by multiplying with 1 before printing, since 1\*True=1, thus adding two bytes.
[Answer]
## J, 11 characters
```
!~/".1!:1[1
```
Takes input from the keyboard.
```
!~/".1!:1[1
5,2
10
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 21 bytes
```
import math
math.comb
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PzO3IL@oRCE3sSSDC0ToJefnJv0vKMrMK9GA8zVMdRSMNDX/AwA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 byte
```
c
```
[Try it online!](https://tio.run/##y0rNyan8/z/5////pv@NAA "Jelly – Try It Online")
[2 bytes](https://tio.run/##y0rNyan8/z9Z/////6Y6RgA) to take input as `n,k`
[Answer]
# [Rust](https://www.rust-lang.org/), 53 bytes
```
fn f(n:i32,k:i32)->i32{if k<1{1}else{f(n-1,k-1)*n/k}}
```
This is essentially the same as the Python code in some of the previous answers, and computes the binomial coefficient through recursion.
[Try it online!](https://tio.run/##FcqxCoAgEADQub7CnLxQwqKlon9pSBDtCK3puG@3XN700puf4lBch0cFgtrmTh6fiJ2SxFILp2Y9Aqwt1@YULn4adaiC2X/JOxE2S5bPmE/6h7E6GAs9DoG5lA8 "Rust – Try It Online")
[Answer]
# [Go](https://go.dev), 58 bytes
```
func b(n,k int)int{if k<1{return 1}
return b(n-1,k-1)*n/k}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY47DoMwDIZncgqLiZTQNlvF4w7dOwEiyEkxKAoT4iRdUKUeokfpbRoekl_6bP2_X--2X75DWZuybaArkRh2Q28dhKpz4Wd0Krn9UjVSDVVEwgCS4z4nVGByOdnGjZZAzuyY_FUihUkkP9HFzIfCY1NY9SMOEwtUbwHTQmaYF_KaYRx7uFG9Up0XmOkdBv6R8916zydFKLSo1sq5X83Mx2GxLHv_Aw)
### Alternative using `math.Gamma()`, 82 bytes
```
import."math"
func b(n,k float64)float64{g:=Gamma
return g(n+1)/(g(k+1)*g(n-k+1))}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY5NCoMwEIXXzSmCq6T-VKGU4s-629IbRDFpokkkxJV4km6k0EP0KL1NExWGeTPzwXvzejO9fAfSdIS1UBKuAJeDNhYGVNrgM1oaX3-P7ZYEkthnAOioGlgjFXWQ9prYyxnvOrG8uhEpCTCtHY2CDKkwwyfEUOf06NbYD3jencnq5XMRhhM4UG0gz6ssSQteVlnqNQwdWInYiCgrXojtfHBvJnfDle0V4pGIat8xdmgGrvagZdn0Dw)
[Answer]
## Haskell (80)
```
f(_,0)=1
f(n,k)=n/k*f(n-1,k-1)
main=getLine>>=putStr.show.f.read.(++")").('(':)
```
But, if input in the format `x y` is allowed instead of in the format `x,y`, it's 74 chars:
```
f[_,0]=1
f[n,k]=n/k*f[n-1,k-1]
main=interact$show.f.map read.take 2.words
```
[Answer]
### Scala 54
```
val n,k=readInt
((k+1)to n product)/(1 to(n-k)product)
```
[Answer]
# Python (52)
```
f=lambda n,k:k<1or f(n-1,k-1)*n/k;print+f(*input())
```
Improved from the other two by using `print+` to convert the result of `f` from `boolean` to `int` in case `k==0`.
Still have no idea how to shrink it to 39, I wonder whether they are using lambda at all.
[Answer]
*(The OP only loosely specified the input & output method/format, so the following seems acceptable.)*
## Sage Notebook (~~39 41~~ 40)
In the current cell,
```
f=lambda n,k:k<1or f(n-1,k-1)*n/k;+f(*_)
```
where the input in the form `n,k` is entered & evaluated in the preceding cell. This simulates "command-line input" by assigning it to `_` (similar to command-line arguments).
## Sage Notebook (~~42 44~~ 43)
Alternatively, using "in-source input" (with only the `x=` and newline characters adding to the score), e.g.,
```
x=5,2
f=lambda n,k:k<1or f(n-1,k-1)*n/k;+f(*x)
```
*Both of these approaches are obviously spin-offs from earlier answers by others.*
[Answer]
# [Tcl](http://tcl.tk/), 80 bytes
```
proc C n\ k {proc f n {expr $n?($n)*\[f $n-1]:1}
expr [f $n]/([f $k]*[f $n-$k])}
```
[Try it online!](https://tio.run/##K0nO@f@/oCg/WcFZIS9GIVuhGsxJU8hTqE6tKChSUMmz11DJ09SKiU4DsnUNY60Ma7nAMmCBWH0NEJ0dqwWRB7I0a//n5CYWQI3jMlUw4qoF0gpAUFBaUqwQ7QxUCNLCVfsfAA "Tcl – Try It Online")
[Answer]
# Javascript, 27 bytes
First my own 35-byte solutions:
```
f=(n,k)=>n-k&&k?f(--n,k)+f(n,k-1):1
```
Or, alternatively,
```
f=(n,k,i=k)=>i?f(n-1,k-1,i-1)*n/k:1
```
The first working recursively, with the simple `(n,k) = (n-1,k) + (n-1,k-1)` rule. The second using that `(n,k) = (n-1,k-1) * n/k`.
**EDIT**
I just noticed the solution by Arnould in a duplicate of this:
```
f=(n,k)=>k?n*f(n-1,k-1)/k:1
```
Which is a whopping 8 bytes less (27 bytes)
] |
[Question]
[
## Intro
A friend posed this question today in a slightly different way - "Can a single [Python] command determine the largest of some integers AND that they aren't equal?".
While we didn't find a way to do this within *reasonable* definitions of "a single command", I thought it might be a fun problem to golf.
##  Challenge
"*Return the largest of a list of integers if-and-only-if they are not all equal.*"
More specifically:
Given a string containing only a comma-separated list of integers:
* If they are all equal, return/output nothing
* Else, return/output the largest
## Rules
* The **input** must be a string containing only a comma-separated list of integers
* The **output** must be either nothing (no output of any kind), or else the largest element from the input, represented as it is in the input
Entries may be a full program or just a function, provided you provide some way to test them!
## Assumptions
* Assume input list elements may be more than one digit but no larger than
( 232 ‚àí 1 )
* Assume the input list has no more than a million elements
* Assume the input will not include negative values
* Assume the input will never be empty
For the avoidance of doubt, the explanation of the challenge given just after "More specifically" shall supersede the statement of the challenge above it ("Return the largest...").
##  Examples
(1) All equal:
```
Input: 1,1
Output:
```
(2) Dissimilar:
```
Input: 1,2
Output: 2
```
(3) Zero!:
```
Input: 0,0,0,0,0,0,0,1,0,0
Output: 1
```
(4) Random:
```
Input: 7,3,8,4,8,3,9,4,6,1,3,7,5
Output: 9
```
(5) Larger numbers, larger list:
```
Input: 627,3894,863,5195,7789,5269,8887,3262,1448,3192
Output: 8887
```
### Additional examples:
(6) All equal, larger list:
```
Input: 7,7,7,7,7,7,7,7,7
Output:
```
(7) All equal, larger list, larger numbers:
```
Input: 61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976
Output:
```
(8) Not equal, larger list, larger numbers:
```
Input: 96185,482754,96185,96185,96185,96185,96185,96185,7,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,961185,96185,96185,96185
Output: 961185
```
## Scoring
This is `code-golf`, so the code with the shortest number of bytes wins!
[Answer]
# [R](https://www.r-project.org/), ~~50~~ 37 bytes
-33 bytes thanks to digEmAll! -13 bytes thanks to rturnbull!
```
x=scan(se=",");if(any(diff(x)))max(x)
```
[Try it online!](https://tio.run/##K/r/v8K2ODkxT6M41VZJR0nTOjNNIzGvUiMlMy1No0JTUzM3sQJI/zfUMdQx1jH8DwA "R – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 5 bytes
```
è▀s╞╙
```
[Try it online!](https://tio.run/##DcuxDYAwDATAPlP8CnYSxx6HBihAFDAASwSJhpo92CSLBBevl@7163DM07aMvX9vu8691afVu3cCBQKHgghF8kSYt7gLu6o5SkQmyyhFDZnFoKo@sjAoJT@RcfgB "MathGolf – Try It Online")
## Explanation
```
è Read whole input as int array
▀ Get unique elements
s Sort list
‚ïû Discard from left of array
‚ïô Get maximum of list
```
This works because both the max operator and the discard from left operator don't do anything for empty lists. Well, the max operator removes the list and pushes nothing for empty lists.
It could be 4 bytes if input could be taken as a list.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~26 23~~ 22 bytes
*-1 byte thanks to nwellnhof*
```
{.max if .Set>1}o&EVAL
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1ovN7FCITNNQS84tcTOsDZfzTXM0ee/NVdxYqVCmoaSoY6hkiYyT8cYiW9maGlupjMISCQ3WZoZWpjqmFgYmZua6EA4@ElzolRRSGKVUNL8DwA "Perl 6 – Try It Online")
Returns an empty slip if everything is equal.
### Explanation
```
o&EVAL # Eval the string to a list of integers
{ } # Pass to code block
.max # Return the max
if .Set>1 # If the list converted to a set has more than one element
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḟṀE?
```
A full program accepting the input as a command line argument (unquoted) which prints the required output
(Note that it deals with: empty input like , single item input like `7` and multiple item input like `7,8,7` like the spec seems to currently require.)
**[Try it online!](https://tio.run/##y0rNyan8///hjvkPdza42v///99ABxkagkgA "Jelly – Try It Online")**
### How?
```
ḟṀE? - Full program: if one argument is present it is evaluated using Python
- so 7,8,7 -> [7,8,7], while 7 -> 7
ḟṀE? - Main Link: list or integer OR no argument (in which case an implicit argument of 0)
? - if...
E - ...condition: all equal? (for any integer E yields 1 since the argument is
- treated as a list like [integer])
ḟ - ...then: filter discard (since it's undefined the right argument is implicitly
- equal to the left; both are treated as lists, so this
- yields an empty list)
Ṁ - ...else: maximum (again an integer is treated as a list)
- implicit print (Jelly's representation of an empty list is an empty string
- furthermore no newline is printed in either case)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes
Full program. Prompts for string from stdin.
```
{1≠≢∪⍵:⌈/⍵}⎕
```
[Try it online!](https://tio.run/##zY49CgJBDIX7OYUHeINmfjPeZkGwWXBbEWt3Qe3sxdLeC81F1qw2ziIi2JgwL0zeR5KqqfViXdWrZZ/bXdNvKHfn3F1ye82H2zzv26nUbT6eBr/XWqvJIxpFIKXKhikbM7wmDVoCERYMJ88iSQ0CWUT4EgtGQE7CBQtPySNGTvAmJDCzmCYYkHMyh5IZ7xjlaDalGPAHWp6VArGHYxO9w/PzWeNX1I/61rgD "APL (Dyalog Unicode) – Try It Online")
`‚éï`‚ÄÉprompt for and evaluate expression (commas concatenate the numbers into a list)
`{`…`}` apply the following anonymous lambda (`⍵` is the argument; the list of numbers):
 `1≠` [if] 1 is different from…
 `≢` the tally of…
 `∪` the unique numbers in…
‚ÄÉ`‚çµ`‚ÄÉthe list
‚ÄÉ`:`‚ÄÉthen
 `⌈/` return the max across (lit. max reduction)…
‚ÄÉ`‚çµ`‚ÄÉthe list
‚ÄÉ[else: do nothing]
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 6 bytes
```
⍪⌈/~⌊/
```
[Try it online!](https://tio.run/##zY5NCsJADIX3PUUP8ErN/CbHGSoVoaDQlRuXIlLBc3isucg4Tl2IiAhuJOQ9ki8JCduhWe7CsFk13RDGcd2l1MfDpY7na5yO7T5OpzalpuprAlWzq@ILPAfdtfQ9NBgmp4Zkd5lpeNhCncqcJWOnYUksvGeBVU7AzBkqp0DG5HUS9bj4EvMlEu/wB1q@EUdsYVh5azAXn9V/NfWjvgU3 "APL (Dyalog Classic) – Try It Online")
a [train](https://codegolf.stackexchange.com/questions/17665/tips-for-golfing-in-apl/43084#43084) computing the maximum (`‚åà/`) without (`~`) the minium (`‚åä/`) turned into a matrix (`‚ç™`)
if the input contains only one distinct element, `‚åà/~‚åä/` will be empty and `‚ç™` will return a 0√ó1 matrix which renders as nothing
otherwise, `‚åà/~‚åä/` will be a 1-element vector and its `‚ç™` will be a 1x1 matrix (visually indistinguishable from a scalar) that contains the maximum
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~16~~ 13 bytes
```
q',/:iL|$1>W>
```
[Try it online!](https://tio.run/##S85KzP3/v1BdR98q06dGxdAu3O7/f2MdKAQA "CJam – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 37 bytes
outputs to stderr (debug on tio).
```
a=input();m=max(a);m>min(a)>exit(`m`)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9E2M6@gtERD0zrXNjexQiMRyLDLzcwDMuxSKzJLNBJyEzT//7c0M7Qw1TGxMDI3NdGBcPCT5kSpopDEKgEA "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~42~~ 41 bytes
```
a=input();print('',max(a))[len(set(a))>1]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9E2M6@gtERD07qgKDOvRENdXSc3sUIjUVMzOic1T6M4tQTEtjOM/f//PwA "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~77~~ ~~75~~ 61 bytes
```
f.read.('[':).(++"]")
f a=[0|any(/=a!!0+0)a]>>show(maximum a)
```
[Try it online!](https://tio.run/##DclBCoJAFADQfacYJXAGf6ajjn8C3XQBl4G5@Jim5BioUUFnb@ptX0/LrR1Ha2iYWM6GaW1nala2ZWfbBXNLl4B7lXcQAfd9t3bFpmOUV@GHpjff5@Q4oR8Kqoti6e9Pbug1mIdhJKxVMoMYdQKoYkgjnUKWoYZUKg2I@E@pJERJghBHWn6bbqTrYnenY1n@AA "Haskell – Try It Online")
`('[':).(++"]")` takes a string (e.g. `"1,2,1,3"`) and encloses it in bracket chars (`"[1,2,1,3]"`). Then `read` turns the string into a list of integers (`[1,2,1,3]`).
The function `f` uses [this tip](https://codegolf.stackexchange.com/a/150792/56433) for a shorter conditional if one of the outcomes is the empty list. `any(/=a!!0+0)a` checks whether the list `a` contains any element that is not equal to its first element `a!!0`. (The `+0` is needed such that `read` knows it has to look for a list of numbers.) If all elements are equal this test results in `False` and the empty string is returned. Otherwise `show(maximum a)`, that is the maximum of the list converted to a string, is returned.
[Answer]
# Red, 81 bytes
```
x: split input","forall x[x/1: load x/1]sort x: unique x if 1 <>length? x[last x]
```
Like the R solution, a huge chunk of the code is handling the input string "1,1,2,44,1". If we can have that as a block, eg: `x: [1 1 2 44 1]`, then we can do it in 41 bytes:
```
sort x: unique x if 1 <>length? x[last x]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 49/53 bytes
## My original version using `.every()`, 53 bytes
Does a function returning '' count as no output? Sure this can be improved upon...
```
s=>(a=s.split`,`).every(e=>a[0]==e)?'':Math.max(...a)
```
[Try it online!](https://tio.run/##dclBCoMwEADAez@SDcRFr8LqC3xBEVx0Yy2pETdIfX0s3ssc580H67gvWyrWOEnOnpQaYFLULSxpcINFOWQ/QajhZ9kTiW2NqTtOL/zwFxCR7WOMq8YgGOIMHkzlbsb@m/JXOV8 "JavaScript (Node.js) – Try It Online")
---
## Improved version using `Set()` by [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy), 49 bytes
```
s=>new Set(a=s.split`,`).size>1?Math.max(...a):``
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1i4vtVwhOLVEI9G2WK@4ICezJEEnQVOvOLMq1c7Q3jexJEMvN7FCQ09PL1HTKiHh/38A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Neim](https://github.com/okx-code/Neim), 4 bytes
```
ùêêùêéŒûùê†
```
Explanation:
```
Ξ If
ùêê all elements are equal
ùêé not
then
ùê† get greatest element
```
[Try it online!](https://tio.run/##y0vNzP3//8PcCROAuO/cPCC54P//aDMjcwVjC0sTBQszYwVTQ0tTBXNzC0sFUyMzSwULCwugpJGZkYKhiYmFgrGhpVEsAA "Neim – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 28 bytes
Returns the maximum (a number, which is an 1x1 matrix) or an empty (1x0) matrix.
```
@(a)max(a)(1+all(a(1)==a):1)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI1EzN7ECSGoYaifm5Ggkahhq2tomaloZav635krTiDbQAcJYTRjTMFbzPwA "Octave – Try It Online")
[Answer]
# Japt, 16 bytes
This would be 9 if not for the unnecessarily strict input format, 7 if throwing an error counts as outputting nothing.
Assumes the string contains at least 2 integers.
```
q, mn
â ÊÉ?Urw:P
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=cSwgbW4K4iDKyT9Vcnc6UA==&input=IjgsOCI=)
[Answer]
# Common Lisp, 102 bytes
```
(lambda(x &aux(c(read-from-string(concatenate'string"#.`("x")"))))(or(apply'= c)(princ(apply'max c))))
```
[Try it online!](https://tio.run/##LcrbCoMwEIThV5Et1AlEoe1136XrakXIiagQnz4u6A9z8zHiljVVVDj2w8gozZP3AkGeeOz@Ofpu3fISZkgMwtsUdO1F9Oh/oEKGjIaYwSm5o/02YpD0ITd4LkpapZd92w@ZegI)
The size is mainly due to inputting the data; with input as a regular list, the length reduces to 46 bytes:
```
(lambda(x)(or(apply'= x)(princ(apply'max x))))
```
[Answer]
# [K4](http://kx.com/download), 38 35 bytes
```
{$[1=#:t:?:(7h$","\:x)-48;;*:t@>t]}
```
**Test Cases:**
```
q)k){$[1=#:t:?:(7h$","\:x)-48;;*:t@>t]}"1,2,4,4"
,4
q)k){$[1=#:t:?:(7h$","\:x)-48;;*:t@>t]}"4,4,4,4"
q)
q)k){$[1=#:t:?:(7h$","\:x)-48;;*:t@>t]}"7,3,8,4,8,3,9,4,6,1,3,7,5"
,9
q)k){$[1=#:t:?:(7h$","\:x)-48;;*:t@>t]}"7,7,7,7,7,7,7,7,7,7,7,7,7"
q)
```
I'm not very fluent in any of the k variants available on TiO, so no online example available, I'll try to come up with one though
**Explanation**
If you're wondering why certain operations are performed before others, K4 does not have operator precedence, it instead interprets from right to left (though you can use parentheses for precedence). Expressions seperated by semicolons.
```
$[expr;`True;`False] is the conditional format
{$[1=#:t:?:(7h$","\:x)-48;;*:t@>t]}
","\:x //split string on commas
7h$ //cast strings to long
-48 //they'll be from ascii format, so compensate
?: //get distinct list
t: //set list to variable t
#: //get count of t
1= //check if count t = 1
;; //return nothing if true
t@>t //if false, sort t descending
*: //return first value
```
Can probably be golfed down more, not a fan of having to use that makeshift max function at the end.
EDIT: If the commas in output are a problem, it can be fixed with two more bytes:
```
q)k){$[1=#:t:?:(7h$","\:x)-48;;*:,/t@>t]}"1,2,4,4"
4
,/ //joins the single element lists into one
```
Taking the total to 40 37, but the comma before the number simply means that it's a single element list as opposed to an atom.
[Answer]
## PHP (<=5.6) ~~64~~ 74 bytes
```
echo array_count_values($a=split(',',$argn))[$m=max($a)]==count($a)?'':$m;
```
Run as pipe with `-nR` or test it [online](http://sandbox.onlinephpfunctions.com/code/8dd641d7b372b891909904c4dba616ba0b9a8498)
`split` was removed in PHP7, but as I had to add 10 to fix a few issues, it was worth using instead of `explode` which is roughly equivalent in this case.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-hF`, 8 bytes
```
q, ün Åc
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=cSwg/G4gxWM=&input=IjEsMiIKCi1oRgo=)
`-3` bytes if the input could be taken as an array.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
',¡ZsËiõ
```
-1 byte thanks to *@Cowabunghole*.
[Try it online](https://tio.run/##yy9OTMpM/f9fXefQwqjiw92Zh7f@/29maGlupkNHEgA) or [verify all test cases](https://tio.run/##zYwxCgJBDEX7OcViY/MLk5nJJNXew07BYiuLBWFBWxs7b@AhvIB7Ey8yRmxERAQbCXkheUnW/WLZrep2M7ST5ro/NpN2qFNcTvN@PHTjue5QCRQIHGZ4DrozFEQokmeEeRWfRxTkIOxOzZVEZLKMUtSQWQyq6pKFQSn5KRn7p5cIQlYEf8BgQpqRlEtOeDSfWb7a@pFvxQ0).
**Explanation:**
```
',¬° '# Split the (implicit) input by ","
Z # Push the maximum (without popping the list)
s # Swap so the list is at the top of the stack again
Ëi # If all elements are equal:
õ # Push an empty string ""
# (Implicitly output the top of the stack to STDOUT as result)
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~45~~ 49 bytes
*+4 bytes thanks Veskah*
```
($l=$args-split','|sort{+$_}-u)[-1]|?{$l.count-1}
```
[Try it online!](https://tio.run/##TY5BCsIwFET3OcUnfDXBRJouhaIH8AYiRWrUQmxrkqKQ9uyxVKvObubNwDT1Q1t31cZEPEMGITI0GR7txUnXmNIvxKJztfVhiXkvW76X6tBtAppVUbeVl6qPPSFbRmCQYFQJRYH/XEoFpH9eJWOkEk44dDCDMDKs2tuudF4A6mejC69PwxvM39Bq1xo/BPPh5FQdEUX2oVLfv1O@njaU9PEF "PowerShell – Try It Online")
Less golfed:
```
$list=$args-split','|sort{+$_}-unuqie
$max=$list[-1]
$max|?{$list.count-1}
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
≈[¤|G
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiYhbwqR8RyIsIiIsIjYyNywzODk0LDg2Myw1MTk1LDc3ODksNTI2OSw4ODg3LDMyNjIsMTQ0OCwzMTkyIl0=)
```
≈[ # If all same
¤ # ""
|G # Else max
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ṀḟṂ
```
[Try it online!](https://tio.run/##zZE9CgIxEIWvYiu8wpkk83MUkS1tZC9gJzYew2u4tSfJSeJktxEREWxkmPeYfJNHIIf9OB5bq9Op3q51Orf7Zb1tbUegAasw7rbBc1HXfqxIMOToBA@XQAmK0qFwYPOgklDIC1TNUVgcZhaQhUE5x21yXvJeas4hV8EfaH@MC1lBNtaSsQyfVb/a@lHfgvn7hgc "Jelly – Try It Online")
TIO link uses function I/O for the sake of having a test harness, but [it works just fine with a plain comma-separated list](https://tio.run/##y0rNyan8///hzoaHO@Y/3Nn0//9/cx1jHQsdEyA21rEE0mY6hkCWuY4pAA). I'd prefer to let a challenge like this stay dead, but if it's been bumped anyways...
```
Ṁ The maximum,
ḟ unless it's equal to
Ṃ the minimum.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
k=eval(input())
if~-len(set(k)):print max(k)
```
[Try it online!](https://tio.run/##zY7PTsMwDMbPy1PkllYz0pI2/zb1WK5ceICVErSoXVtlGXQXXr243QUhhEBcJis/x/n8OR4u8dB3Yqr7Z0cLyhibmsK9Vm3iu@EckzQl/uX9rnVdcnIxadJ0OwTfRXqsRqwmNBDiiw15O/jW0cdwdluyiuGCXPl1wXf02s/KsToO2MLWe79H0Y2uTuZvU4L32g2Rlg/3ZQh9mL1PwVUNIcv8v2y0WCbGgTOCFMgNfA4@E181ZGAgx5OBxaxQyUCDRE0JVI1FUWUguZWgtbEghbJgjEFRKAE8z9HMrVimfYl5CrdawQ0Qd7GKGwm5EVrmcC1@pv5V1z/5rcCmDw "Python 2 – Try It Online")
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 9 bytes
```
Ul1E?Oq¬ø‚Üë
```
[Try it online!](https://tio.run/##y8/INfr/PzTH0NXev/DQ/kdtE///jzbSAcLY/wA "Ohm v2 – Try It Online")
Explanation:
```
Ul1E?Oq¬ø‚Üë
U Uniquify input
l Get length
1E Push whether length is equak to 1
?Oq If so immediately quit
¬ø‚Üë Else print maximum
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
≔I⪪S,θ¿›⌈θ⌊θI⌈θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DObG4RCO4ICezRMMzr6C0JLikKDMvXUNTR0FJR0kTSBVqWnNlpilouBelJpakFmn4JlZk5pbmahQC5Xwz86BsTU2FAKDGEoh5CDWamtb//5vroMH/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔I⪪S,θ
```
Split the input on commas and cast each value to integer.
```
¿›⌈θ⌊θ
```
Test whether the maximum value is greater than the minimum value.
```
I⌈θ
```
If so then cast the maximum value to string and print.
[Answer]
# Mathematica, 43 bytes
```
If[!Equal@@#,Max@#]&@@#~ImportString~"CSV"&
```
Pure function. Takes a comma-separated string as input and returns either a number or `Null`. I believe this is valid, as `Null` is not graphically displayed:

[Answer]
# [C (gcc)](https://gcc.gnu.org/), 91 bytes
```
M(s)char*s;{long m=atol(s),o,l=0;for(;s=strchr(s,44);o<0?m-=o:0)l|=o=m-atol(++s);s=l?m:-1;}
```
[Try it online!](https://tio.run/##pY9tS8MwEMdfu08RMoTEXaHpU5LWMPZigugQNn3nm1LbbdCH0RQU5r66XTa7YUVEkCN3ubvf/7hLrGWStO2MaJqs4vpKR9u8KpeoUHFT5aYKFeTKjrKqJpFWuqmTVU00eB6Nqmt7XFiqCm2av6tKFdZRMxppatB8XIQWi3bt8CXN1mWKJovFdP5I0rcNRZt6XTYZwROt07pBlzpEeGg6@LnEgMxnjB/ucIhvJrf3T/MppoMiXpeEbgcX3RiLIaXQjGAGDFManRvOue706ifehq/GDr7HyY7j4IIAzzwXpImBYV3g4PdoIQTvBIFjJEIaReCCz6QPnAsJvhNIOGDgOoEDzPPMRCb7y52v4fDNjthptYAx4XekSYQPnnC478Fn8rvnf6L@6X9sHG/YtR9JlsdL3Vqvew "C (gcc) – Try It Online")
### Degolf
```
M(s)char*s;{
long m=atol(s),o,l=0; // Read the first integer from string
for(;s=strchr(s,44); // Advance pointer to next ','
o<0?m-=o:0) // End of loop: if difference <0, deduct from max, increasing it to new max.
l|=o=m-atol(++s); // Read next number, and subtract it from current max.
// Bitwise-OR the difference into the l-variable
s=l?m:-1; // End of function: if l is non-zero, there were at least two different values.
// Return -1 if l is zero, otherwise the max value.
}
```
[Answer]
# XPath 3.1, 54 bytes
with the input string as the context item:
```
let$t:=tokenize(.,',')!xs:int(.)return max($t)[$t!=$t]
```
Could be reduced by one character if you allow the context to bind a shorter prefix than "xs" to the XML Schema namespace.
Explanation: takes the input string, tokenizes on "," separator, applies `xs:int()` to each token to convert to an integer, computes the max of the sequence, outputs the max provided the predicate `$t!=$t` is true. If A and B are sequences, then `A!=B` is true iff there is a pair of items (a from A, b from B) such that `a!=b`.
If the input can be supplied as a sequence of integers $s rather than a comma-separated string then the solution reduces to
```
max($s)[$s!=$s]
```
(15 bytes - which might well be the shortest solution in a language that isn't purpose-designed for brevity)
**NOTE**: this doesn't satisfy the requirement "represented as it is in the input" - if there's an integer with leading zeroes or a plus sign in the input, these will be lost. I suspect that's true of many other solutions as well.
[Answer]
# Pyth, 7 bytes
```
Itl{QeS
```
[Try it online!](https://pyth.herokuapp.com/?code=Itl%7BQeS&input=1%2C3&debug=0)
[All test cases (slightly different code for better output formatting)](https://pyth.herokuapp.com/?code=Itl%7BQpeS&test_suite=1&test_suite_input=1%2C1%0A1%2C2%0A0%2C0%2C0%2C0%2C0%2C0%2C0%2C1%2C0%2C0%0A7%2C3%2C8%2C4%2C8%2C3%2C9%2C4%2C6%2C1%2C3%2C7%2C5%0A627%2C3894%2C863%2C5195%2C7789%2C5269%2C8887%2C3262%2C1448%2C3192%0A7%2C7%2C7%2C7%2C7%2C7%2C7%2C7%2C7%0A61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%2C61976%0A96185%2C482754%2C96185%2C96185%2C96185%2C96185%2C96185%2C96185%2C7%2C96185%2C96185%2C96185%2C96185%2C96185%2C96185%2C96185%2C96185%2C96185%2C96185%2C96185%2C96185%2C96185%2C96185%2C96185%2C96185%2C961185%2C96185%2C96185%2C96185&debug=0)
As Pyth is based on Python, user input is always interpreted as a string, which then may be passed through `eval()`. All Pyth programs automatically run `Q=eval(input())` as their first instruction.
Explanation:
```
Itl{QeS | Full code
Itl{QeSQ | with implicit variables filled
---------+-------------------------------
I | If
t | one less than
l | the length of
{Q | the deduplicated input
| is truthy (!=0),
| print
e | the last element of
SQ | the sorted input
```
] |
[Question]
[
Your challenge, should you choose to accept it, is to write a program in a language of your choice that, when given a string (limited to printable ASCII) as input, outputs a new program in the same language that outputs that string *without using any characters from that string in the code.*
But this task is impossible as-is in many languages; for example, if the string to print contains every ASCII character. So instead, your submission will choose a subset of printable ASCII which is guaranteed not to be in the input. Your score will be the size of the set, with lower score being better, and shortest code length (in bytes) as a tiebreaker.
An example solution might be the following:
>
> ## [Python](https://www.python.org), 64 bytes / score 17
>
>
>
> ```
> lambda s:"print('\\"+'\\'.join([oct(ord(c))[2:]for c in s])+"')"
>
> ```
>
> Restricting the set `print()'\01234567`.
>
>
>
Now that's enough dawdling—go program!
## Rules / clarifications
* "Same language" includes any compiler flags used in the submission.
* The outputted program should be a full program with output on STDOUT.
[Answer]
# [Python](https://www.python.org), ~~121~~ 90 bytes / score 3
```
lambda s:f"print({'+'.join('chr('+'+True'*ord(c)+')'for c in s)})"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3o3ISc5NSEhWKrdKU3u-d8H7vpPd7O9_v7Xu_d4pGtbq2ul5Wfmaehvr7vc3v93YAZTWAYtrv92wBK5z6fm-rulZ-UYpGsqa2uqZ6Wn6RQrJCZp5CsWatphLEhv0FRZl5JRppGurq6iEZmcUK6aklxQo5-XnpikARTU2IqgULIDQA)
*-31 thanks to l4m2*
NFKC normalization! The only reserved characters are `(+)`, and everything else is done with identifiers written in fullwidth characters.
Builds codepoints up as sums of `True`.
It feels almost possible to go down to 2... almost. Constructing the codepoints with just `()` seems maybe doable with some kind of `str`/`repr` layering, but it takes either `+` or `,=` to `print` it all on one line... and I also have half a mind to cut `print` out of the picture, but it seems like it would take `,.` to go the `open(1, 'w')` route.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ ~~11~~ 10 bytes / score 0
```
O”‘ẋp”Ọj”®
```
[Try it online!](https://tio.run/##y0rNyan8/9//UcPcRw0zHu7qLgCyHu7uyQJSh9b9//9fQVFJWUVVTV1DU0tbR1dP38DQyNjE1MzcwtLK2sbWzt7B0cnZxdXN3cPTy9vH188/IDAoOCQ0LDwiMio6JjYuPiExKTklNS09IzMrOyc3L7@gsKi4pLSsvKKyqrqmti6/JCO1SAEokpamkJdfopCcn1eSmV6aX1qskFFSUlBspa9fXl6uV5lfWlKalKqXnJ@rX55YkpxhX2ZbaRThWFTgmlyZngwA "Jelly – Try It Online")
*-1 thanks to Jonathan Allan*
Encodes arbitrary strings as programs with no ASCII whatsoever, using increment spam for charcodes and unparseable nilads to both print and reset to 0.
```
O Codepoints of the input.
”‘ẋ Repeat ‘ (increment) that many times for each codepoint.
p”Ọ Append Ọ (convert from codepoints) to each.
j Join on
”® the register nilad (0 unless set otherwise).
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 78 bytes / score 2
```
{({}<>)<>}<>{<>(((((()()()()()){}){}){})())<>{({}[()])<>((({}[()])()))<>}{}}<>
```
The input cannot contain either of `()`.
[Try it online!](https://tio.run/##XZGxboMwEIZ3P8VVDNgS4QkQY9WtVTp0iDIYOGQUx46MSQfLz04PA20aY8lw9@v@j9@Nk4M59Fpe5jmDI97RjQheIQzmNnkWeIhVLao6sqpmLINX6wBlq6BV0snWoyvLkgUGtDL4mEYFORc5eAtSU9dIjzB62V6ShIYsB09L7I8Icdv0vuu2kV9q0ETkJlyMltpqtnY/p8YvGGANQu/sNbH/slGZSG5g@1T/40gQIZ64OAv2MO/dJOET@u788Aer/IhXe1/zynm@uRUgTUf5jej8GsZkOhqH0isYfLHIDVC69AHNPyK@M1EO4tkyhsjoMub5DbW2BXxbp7uX@dC6Hw "Brain-Flak – Try It Online")
And readable version:
```
# Reverse the input
{({}<>)<>}
<>
# For each character...
{
# Push '()' to alternate stack
<>
(((((()()()()()){}){}){})())
<>
# While true...
{
# Subtract one from the character on top of the stack
({}[()])
# On the alternate stack...
<>
# Remove the '(' on top, and insert '()' underneath it, then put it back
((({}[()])()))
<>
}{}
}<>
```
[Answer]
# [;#+](https://github.com/ConorOBrien-Foxx/shp), subset size 2, 40 bytes
```
;;;;;~+++++++>~;~++++:>*(-(;~<#~):<#-*:)
```
[Try it online!](https://tio.run/nexus/shp#@28NAnXaEGBXB2Fa2Wlp6GpY19ko12la2Sjrallp/v/vkZqTk68Qnl@Uk6LIAAA ";#+ – TIO Nexus") Input is terminated with a null byte. Assumes the input does not contain `;` or `#`.
## Explanation
As this is a repost of [my answer to another question from 2017](https://codegolf.stackexchange.com/a/122210/31957), you can find a detailed explanation there. On a high level, it just generates constants for `;` and `#`, and for each character in the input, the program outputs that many `;`, followed by a `#`.
;#+ being a superset of ;# allows us to reuse the code from the linked challenge without modification.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes, score 0
```
⭆S⁺´℅´L×´¶℅ι
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6Fjc9A4oy80o0gkuAVLpvYoGGZ15BaQmEq6GpoxCQU1qsofSopfX9njVKOgohmbmpQP6hbUC2f1FKZl5ijkamJghYLylOSi6GGrs8Wkm3LEcpdlu0kjPUxpgiQyOFpMqS1GKlWIgiAA "Charcoal – Attempt This Online") Link is to verbose version of code. Accepts any Unicode character other than NUL and `℅L¶` that the output uses (the last one being `\n` in Charcoal's code page; the resulting program can't properly print newlines, but you can use `\r` instead). Run the sample output: [Try it online!](https://tio.run/##S85ILErOT8z5//9RS@v7PWsObRsMcDC5ZdRXIyN2hrtPR0Ksjeaw4eA7evmefqFMHZuGT6oYOTXISPb3cPPtSIq9//8B "Charcoal – Try It Online") Explanation:
```
S Input string
⭆ Map over characters and join
´℅´L Literal string `℅L`
⁺ Concatenated with
´¶ Literal string `¶` (bare `¶` would be `\n`)
√ó Repeated by
ι Current character
‚ÑÖ Take the ordinal
Implicitly print
```
The resulting program contains a number of strings of the form `℅L¶¶¶...¶¶¶` each of which outputs the Unicode character with the code point given by the number of `¶`s.
Since the resulting programs get long quickly, here's a longer program that outputs shorter programs:
```
⭆S⁺´℅⍘℅ι”y⁰¹²³⁴⁵⁶⁷⁸⁹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaHjmFZSWQLgamjoKATmlxRpKj1palXQUnBKLU6Ey/kUpmXmJORqZQCVKjxo3HNp5aNOhzY8atzxq3Pqocdujxu2PGnc8atyppAkE1v//Rys5Q22MKTIyUEiqLEktVor9r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Accepts any Unicode character other than NUL and `℅⁰¹²³⁴⁵⁶⁷⁸⁹` that the output uses, although the restriction on `\n` still applies. Run the sample output: [Try it online!](https://tio.run/##S85ILErOT8z5//9RS@ujxm2PGrcDGYd2Pmrc8KhxC1hsJ0wMJAoX2gkVOrQTVRFY4w6I5Gaw1FaQEIixBSqx@dAmmB6owk2HdsJt2AYzBkls6///AA "Charcoal – Try It Online") Explanation: Converts the ordinals of the input characters into Charcoal's digits (which aren't printable ASCII), with `℅` telling the resulting program to convert them back into Unicode.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~92~~ 50 bytes, score ~~8~~ 7
```
->e{'$><<$==""<<'+(e.bytes.map{|x|[1]*x*?+}*"<<")}
```
[Try it online!](https://tio.run/##LclLCoMwEADQvacog6BGHHCf2INYF1FGlKjYfKzfs8cuXD6edvXmW@Gzgo4oLDgPhQDgPEpjwnqzZHCU83GuZ5lXbGXv9GL/huTySrQl/DppaSH9maAKZmfNSwW0yCFWyUNsOqkNuqn/oul38jc "Ruby – Try It Online")
### How
In Ruby, the string operator `<<` converts an integer to a codepoint, and appends the corresponding character.
Starting with the empty string, we can append all characters of the original string as numbers, and send the result to standard output (`$>`). Using `$=` (deprecated variable warning) to avoid wrapping the string in brackets, and saves 1 character.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `Ds`, 67 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8.375 bytes, score 0
```
C\›*`ø⟇₴`+
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJEcz0iLCIiLCJDXFzigLoqYMO44p+H4oK0YCsiLCIiLCJBbW9uZ3VzIl0=)
Bitstring:
```
0101011101110101111010001011001000010010000000010100011110100110010
```
The set is the entire vyxal code page minus `⟇₴ø›`. Vyxal's code page contains printable ascii in the same spots as Unicode which is very convenient.
## Explained
```
C\›*`ø⟇₴`+­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌­
C # ‎⁡Convert to a list of Unicode code points
\›* # ‎⁢Repeat › per each character
`ø⟇₴`+ # ‎⁣And add this string
ø⟇ # ‎⁤ Index into the vyxal code page
₴ # ‎⁢⁡ Print without a newline. This makes the top of the stack empty.
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Java](https://en.wikipedia.org/wiki/Java_(programming_language)), 202 bytes, score 18
```
interface M{static void main(String[]a){("interface I{static void main(String[]a){System.out.print(\""+a[0].replaceAll("\\\\|\"","\\\\$0")+"\");}}").chars().forEach(c->System.out.printf("\\u%04x",c));}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kK7EsccGCpaUlaboWN09l5pWkFqUlJqcq-FYXlySWZCYrlOVnpijkJmbmaQSXFGXmpUfHJmpWayghVHriVRlcWVySmquXX1qiVwAULNGIUVLSTow2iNUrSi3IAep3zMnRUIoBghqgjA6YpWKgpKmtFKOkaV1bq6Spl5yRWFSsoamXll_kmpicoZGsa4duahrIiFJVA5MKJZ1kTZA-iI-gHtscrZSRmpOTrxCjVJ5flJMCtCkWKgUA)
Java interprets unicode escapes `\uABCD` everywhere, not only in String literals. This way, we can write a program using only the characters `\u0123456789abcdef`.
[Answer]
# Javascript with JsFuck lib, 6 restricted, 43 bytes
```
x=>JSFuck.encode(`x=>`+JSON.stringify(x),1)
```
[Answer]
# [Brainfuck](https://github.com/TryItOnline/brainfuck), 49 bytes / score 3
```
,[>>--[<+>++++++]<<[->.<]>+++.>++++[<++++>-]<.>,]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70yqSgxMy-tNDl7wYKlpSVpuhY3DXWi7ex0daNttO20wSDWxiZa107PJhbE1wMLAiWBwE431kbPTicWohGqf8FeJ5iROgomlgpJlSWpxQr6CsXJ-UWpCsYQRQA)
[Answer]
# [Python](https://www.python.org), 87 bytes, score 9 (ASCII only code)
*See [Unrelated String's solution](https://codegolf.stackexchange.com/questions/266359/restricted-meta-cat/266368#266368) for a lower score by using non-ascii characters*
*-4 bytes, thanks to noodle man*
*-9 bytes, thanks to l4m2*
---
```
def f(s):print(f"exec({'+'.join('chr('+'+1'*ord(c)+')'for c in f'print({repr(s)})')})")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3w1NS0xTSNIo1rQqKMvNKNNKUUitSkzWq1bXV9bLyM_M01JMzijSAPG1Dda38ohSNZE1tdU31tPwihWSFzDyFNHWIvuqi1IIioDG1mupArKQJMf4WX1qahpJHak5OvkJ4flFOipImF0S9JhfYHpDh2obDG2pqjwRfDmefDld_jSQf0t63tDB1cMbL4HTVqH9GfTc8IXX8OBRDaii6edSPI9Onw8t3Q6k1owntbsJ6tQA)
encodes string using `exc()hr1+`
## Explanation
Encodes string as `exec(chr(1+...+1)+chr(1+1+...)+...)`
The executed code is `print(S)` with `S` being the string-representation of the input. The characters in the string are represented as sums of `1`'s
---
# [Python](https://www.python.org), 85 bytes, score 11
```
def f(s):print(f"exec({'+'.join(f'chr(0b{ord(c):b})'for c in f'print({repr(s)})')})")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZFBCsIwEEVx21OEbJJQlMxO3AteQNw3TWilJCVWUIoncdON3klPY9IoJC0GsnjMn_9nkvuzvXaV0cPwOHdquX7tS6mQoie2aW2tO6qwvEhBe5KT1dHUmioiKkt50RtbUsE2xY0RZSwSqNZIkdDVW9laZ-Jq7mIWzN-LraJ4J5vGoIOxTYlZFvQsG1OCMwBwd1geIUTIPccIkIgh6vUQkdfGlMR4Tn2T6gwTK56GxsWJdr4OTKf4O_G4-fc1f1_2AQ)
encodes string using `exc()hr0b1+`
[Answer]
# JavaScript, 66 bytes, score 15
Using the restricted set `alert`\01234567`:
```
s=>"alert`"+s.replace(/./g,c=>"\\"+c.charCodeAt().toString(8))+"`"
```
Uses deprecated octal string literals and alert with a tagged template function call. I was worried that `alert` would stringify the tagged template as `[Object object]` but fortunately for me that did not happen.
I wrote this on my phone so I can’t insert a stack snippet at the moment.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score 0 (14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))
```
Ç'ǝ×»“”ÿ”Åγιнç
```
Output of the output program is a list of characters.
[Try it online.](https://tio.run/##yy9OTMpM/f//cLv68bmHpx/a/ahhzqOGuYf3g4jWc5vP7byw9/Dy//8VFJWUVVTV1DU0tbR1dPX0DQyNjE1MzcwtLK2sbWzt7B0cnZxdXN3cPTy9vH18/fwDAoOCQ0LDwiMio6JjYuPiExKTklNS09IzMrOyc3Lz8gsKi4pLSsvKKyqrqmtq6xQc81IUMlKLUhWK83NTSzIy89IVcvOLUhUVDRUB)
[Try the outputted program online.](https://tio.run/##7Zq9DYJgFEV7R3MLTSysLFyAxjGoHcDKwoqCjjgDi3wO4fu5974X@nvOARIS4HY/na@XMfZpXv88DivChNGI2YzhkOmU8Zj5nMOgy6TTqNus47DrtPO4@3wAIAQRBAnDBIJCUcGwcFwCMAWZBE3DJoJT0cnwdDyAAIQCiASMBpAIlAqYDJwOoBCkEqgUrBawGLQauBy8HoEghSKJJI0mkSiVKpksnS6hMKUyqTStNrE4tTq5PL2@QIBEgkiETIZQiFSKWIxcjmCQZJJolGyWcJh0mnicfF6BwBKJRSLLZBYKLZVaLLZcbsHgkslFo8tmFw4vnW4Q3z@wd1yZO60vbb@D6JR@H9N5ndYpHdpf0zuun/J9qTuvI9NTDhQn1ACxT/Py2F7b@/tZnuM4fg) (Feel free to remove the `J`oin in the footer to see the actual list output.)
**Explanation:**
```
Ç # Convert the (implicit) input-string to a list of codepoint-integers
'«ù '# Push string "«ù"
√ó # Convert each codepoint to a string with that many "«ù"
» # Join this list of strings with newline delimiter
“”ÿ”Åγιнç # Push (dictionary) string "”ÿ”Åγιнç",
# where the `ÿ` is automatically replaced with the earlier string
# (after which the result is output implicitly)
```
```
”ǝǝǝ...ǝǝǝ
...
ǝǝǝ...ǝǝǝ” # Push (dictionary titlecase) string with "ǝ" and newlines
Åγ # Run-length encode it; pushing pair ["ǝ","\n"] and a list of lengths
ι # Uninterleave the list of lengths into two parts
–Ω # Pop and leave just the first part (the lengths of the "«ù"-lines)
ç # Convert each from a codepoint-integer to a character
# (after which this list of characters is output implicitly as result)
```
Some notes:
1. `«ù` is used, since `'«ù√ó` nor `'«ù«ù` are [dictionary words](https://codegolf.stackexchange.com/a/166851/52210). But any non-ASCII character that doesn't form dictionary words would be fine here.
2. `“` and `”` are used to prevent the ASCII-quote `"`. Luckily, none of `”ǝ`/`ǝǝ`/`”Å`/`Åγ`/`γι`/`ιн`/`нç` are dictionary words.
3. An approach similar to the Jelly/Vyxal answers using an increment won't work in 05AB1E, since the increment-by-1 builtin is an ASCII-character: `>`.
[Answer]
# [Ly](https://github.com/LyricLy/Ly), Length 20 / Score 4
Input cannot have 4 characters `0`&o`.
```
&ir[0u['`o,]p]"&o"&o
```
And at a high level, the code reads all input as codepoints, then converts each character to a `0` and as many "increment the top of stack" instructions as is necessary to get to the codepoint value. Then it appends `&o` to the end to print the entire stack as characters.
```
&ir - read input as codepoints, reverse stack
[ ] - loop once for each char on the stack
0u - push a "0" onto the stack
[ ] - while number is >0
'`o - print "`" (the increment instruction)
, - decrement the top of stack
p - delete the loop variable from the stack
"&o" - push "&o" (print whole stack instruction)
&o - print stack
```
[Try it online!](https://tio.run/##y6n8/18tsyjaoDRaPSFfJ7YgVkktH4j@/w/JyCxWAKKS1OIShcy8gtISPQA "Ly – Try It Online")
[Answer]
# [Uiua](https://uiua.org), 22 [bytes](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLijZzih4wn4oqCQFwi4oqCXCImcC3PgFwiXCIrz4AiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiw43CoyfCsEBcIsKwXCImcC3DmVwiXCIrw5kiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIK), score 4
```
⍜⇌'⊂@"⊂"&p-π\""+π
```
[Try it!](https://www.uiua.org/pad?src=ImhlbGxvIHdvcmxkIgrijZzih4wn4oqCQCLiioIiJnAtz4BcIiIrz4AK)
restricted set is `&p-"`
this would be much easier if the implicit stack printing didn't put quotes around strings, as it stands i could not get rid of &p, either `-` or `+` for offsetting the codepoints, or `"`, `$` , or `@` and a lot of `⊂`s
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 76 bytes/ score 2
```
+++++[->+++++++++<],[<+[+>+[->>+>+<<<]>>[-<<+>>]+>[<[-]>-]<[<.+.->-]<.<<]>,]
```
[Try it online!](https://tio.run/##NYxBCoBADAMf1G1fEPKR0IMrCCJ4EHx/tYedS8IQMp/tvI93v6qskdMWyCGYjG35B4Ak5YCRaRTkSU8IYeHdoicjq@Y6/gA "brainfuck – Try It Online")
All brackets are `<>` balanced so the reordering tool should help
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 171 bytes, score 14 `main(){}prtf&+`
```
#define f(c,d)for(k=c+1;k--;)printf(#d);
n;k;g(){f(n,main)}main(c){for(;c=~getchar(g());){f(,(a){)f(c+38?-2-c:9507,if(++a))f(,if\50)g(++n);f(,(printf(&a))\51{}})}f(,(){})}
```
[Try it online!](https://tio.run/##LU1LCsIwEN17ikpBZmgCrVL8hOLWG7jpJkySWlpTCd2FePU6ATeP950hORBtW2msG70tHJAw6JYAU0dVoyYpFX7C6FcHpUG182pSA2B04MVbjx5TRiB2eKSo@w52pZcOwC1UuShAY0S@XJ0ud3mUdLu29VmMDqpKIwdM@7bGgbVHlQf/jweO@7aJKWHKNkYm2/aw87yI4rmE2ex/ "C (gcc) – Try It Online")
[Try Generated online!](https://tio.run/##7dNBCsIwEEbh20hC6aGGQEpAi6jgovTqjtqFy9ikEaHzVg8KFZz@X@iHEFRPkkYnfkrRdZ14Yijvb798//MljbfoDuK9n@b585xdkH1MPDdzpk6s2/jmAyMEI@ucYIWQDKC1iIDU9uYld7dw@9x/L70VWyV/H2zNaBkuIQXAapEBjZAW@rYIRCHB1m99YYxYstLCiyEzNadpdeLld14vqz5CPMpw1f7@BA "C (gcc) – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 75 bytes / score 5
```
!s="µ()=(µ(µ)=µ)"*join(("('µ'-('$('µ'-i+'µ')'-'µ'))" for i=s),'µ')
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/X7HYVunQVg1NWw0geWirpi0QK2ll5WfmaWgoaagf2qquq6GuAmFkaoMoTXVdMKWppJCWX6SQaVusqQMW@F@sYKsA1qmuoG6lXqeuyVVQlJlXkpOnUYxgKgLZaUCFqWWJORq@qSWJegWJRcWpIHGEojQNICcls7ggJ7FSA27co46VQFX/AQ "Julia 1.0 – Try It Online")
the used ascii characters are `'()-=`. Other characters used are `µ` (a lot) and `ì` to `Ŋ` depending on the needed characters.
creates a function that ouputs the string by concatenating Chars, which are constructed by substracting non-ascii characters, for example `'A' == 'µ'-116 == 'µ'-('ĩ'-'µ')`
concatenation in Julia is `*`, which can be implied in some case. That's why we create the identity function `µ(µ)=µ`:
`µ('a')µ('b') == µ('a')*µ('b') == 'a'*'b' == "ab"`
[Answer]
# Google Sheets, score 13 / 92 bytes
`=let(p,join(,"=",sort("—Å–∏–º–≤–æ–ª("&code(mid(A1,sequence(1,len(A1)),1))&")&")),left(p,len(p)-1))`
Put the input in cell `A1` and the formula in `B1`.
When the input is `abc123`, the formula gives this output:
`=—Å–∏–º–≤–æ–ª(97)&—Å–∏–º–≤–æ–ª(98)&—Å–∏–º–≤–æ–ª(99)&—Å–∏–º–≤–æ–ª(49)&—Å–∏–º–≤–æ–ª(50)&—Å–∏–º–≤–æ–ª(51)`
The set of printable ASCII in the output is `0123456789()&`.
The output is a valid formula in Google Sheets in any locale, including Latin locales such as United States. When the output is evaluated as formula, its result is `abc123`.
The formula uses the equivalent of the `char()` function in Cyrillic, `—Å–∏–º–≤–æ–ª()`, whose name doesn't match any Latin letters (`console.log('—Å–∏–º–≤–æ–ª'.match(/\w/))` ‚Üí `null`).
[Answer]
# [Unary](https://esolangs.org/wiki/Unary), \$8.71412 \times 10^{420}\$ bytes, score 1
…Obviously, I will not be posting the full code here. Or anywhere. It is `8714123138855978699360164050596229281826476597589481446286633953212548084711579903126530450262195558539773177853879595103615733973606156395440197295886222547053888870061749608029900423204725572303716359786086331805843402197818088474380787864934634643574154692137242860845559867854533001295180659830847166956220859057004333374262038608140098168588215568980939574816997785951406147471781245309306817118354877602371834815751` bytes long. That's a lot of bytes.
Handles all characters as input but `0`, which is the only character that appears in the output. A rare case where Unary does not trivialize a challenge like this? I've had my eyes set on a non-trivial score 1 answer for a while, and Unary is a perfect candidate.
[Here is the script I used to generate the program size](https://tio.run/##lVCxbtswEJ3DryDUIrBN8iwmyFKonLp06dJuDBtYiGwLiBVBlIC2hr7dfUfFaoImQw4g7/Teu3dHdUP5@3Tqu00T5WeZCScv8jwXBScrFJLNheFkBckLC05zssIjgQucrMgo9l3d0kPdVJEOm3Zx@Sm2D3W/pP7xbi/KumdBs@MpNpNKfv/x5es36qrNPe3iUC7WtF7Ko0yr@I@XQY6iHfoo507RDIey6mAwQ@xdL66WSTnJJ9EEbFuIb0T1i7PNKV@ttq0oN7G6szmgScsmUeyxCO/24fjE@zyM9O/LEm1bdR3GjPXbs37BeYUJS@oeh@Z@jXJaBE7MjfL2tq8PVcQCP4@zH8X6TyWNtOOYnU7eGKMVaaWISJE7Z3oRGrzWGlJcOIQ7KKddCqUU38Uc3jlvwONKH1w8QxDKO8MMmkwIEAByDiSrTfIwQXsYvyEDwIVCbZx60@s89DwYFQerPYQsQnsRHCsABz4KZMEzAKPCqszCNBTJxKM06eH/eaSGV5tmVQLxrJlmAgxzDDH7gk58EhRpezxJPf1sMyGv76LeF@TCXw), and here is the corresponding Brainfuck program (formatted with newlines for readability):
```
+>,>>>>>>+++>>>+<<<<<<<<<<[>>[-]+>[-]<<[>>>[-]>[-]+>[-]<<<<<+[>-<[>>+<<-]]>>[<<+
>>-]<[>>>-<<<<[-],[++>-<[>>+<<-]]>>[<<+>>-]<[<<->>-]]<-[>>+<<-]]>>[<<+>>-]<[>>[-
]+>[-]>[-]<<<<-]>>>>>[>>+[>[<-]<[->+<]>]>[->[>]>[>]+>+[<]<[<]>]+[<[>-]>[-<+>]<]<
<<<[<+>->>>>+[>[<-]<[->+<]>]>[>]+[<]+[<[>-]>[-<+>]<]<<<<]<[->+<]>[-<+>>-<]>[-<+>
]<<[->>+<+<]>>[-<<+>>>-<]>[-<+>]<<<[->>>+<+<<]>>>>-]+++<<<<<<-<]>>>>>>>>+[>[<-]<
[->+<]>]>[+++++++++++++++++++++++++++++++++++++++++++++++.>]
```
Assumes an interpreter with dynamic memory (right-infinite) and EOF = 0 (or 0x00 manually appended to the input).
Unfortunately, even this program is obscene, since we do still have 8-bit cells. We store the unary output program as a series of 1s on the tape, which grows exponential with the input size. As a proof of concept, [you can Try it online! with input 0x02](https://tio.run/##pVPRasMwDIQ@6lfO0hcY/YjxwzYYlEIfCv3@7KSSLFnJ6tCDKLJOPjuS8nn7OF@/71@XaWqqWmAFMDOYz2/boJAvpTCVho/RdnjxBICHJQTjMB2ArBf@tmStUmc096b8DJpchLOKEGiuwaBW7Z0JDLmTjGxNDe1SGguwk8dAOKDP2@@KzafmyXFDuo6DsKEaHqrnzhGiwxg7Qo6OxbanrOQ/gmOqOcrRnsbORFd49do9WsJwlzAgW6OrjNPjdATNNvaaA9PoptCzSG5Yb5Jl15KWUpykRTQIMsFFKNgNnXwmMCiekwY8pjvyfPlB5yr8luHphnhZwz8V9T5Npx8). This outputs some debug information to show that the corresponding program in Unary is `1 010 010 100 000` (corresponding to `++.>`), which corresponds to the 5,280 0s which follow that debug information.
# Explanation
Here is my fully commented corresponding Brainfuck program:
```
[-][
ASSUMES:
- Dynamic Memory Tape (Right-Infinite)
- EOF = 0x00 and/or null terminated input
for reference, the Unary bijection:
| > corresponds to 000
| + corresponds to 010
| . corresponds to 100
our desired output is Nx'0' characters, where
| + + ... + . > + + ... + . > ...
| N = 1 010 010 ... 010 100 000 010 010 ... 010 100 000 ...
| {ord n.0 times} {ord n.1 times}
assuming dynamic tape memory (but finite cell size), since we need only to output
in unary, we may store N as a unary integer in tape size
our bit to unary algorithm can be expressed on a high level:
| for each bit:
| n *= 2
| if bit:
| n++
| end if
| end for
we need to be able to stream bits from the input not proportional to the input size
that is, there is a large, variable number of bits corresponding to each , input
we will try to process this character-by-character instead of reading all the input
and generating the corresponding bit string, and iterating over that afterwords, so
as to hopefully avoid weird tape layouts
assuming some procedure for emit, our algorithm works as:
| emit 1
| for each input character C:
| while C is not 0:
| emit 010
| C -= 1
| end while
| emit 100
| emit 000
| end for
| for each bit in unary representation, output '0'
however, obviously, we do not procedure calls available to us. ideally, we linearize
our loop to be in terms of processing emitted bits:
| C = input
| loop:
| if C == 0:
| emit_bits = 1 0 0
| elsif C == 255:
| emit_bits = 0 0 0
| C = input
| if C is EOF:
| break
| end if
| C = C + 1
| else:
| emit_bits = 0 1 0
| end if
| times 3:
| double bitstring
| if cur_bit:
| increment bitstring
| end if
| move_bit_right
| end times
| C -= 1
| end loop
we can abuse the fact our input is guaranteed to be printable ascii and use 255 (-1)
as a state value to get an extra 3 bits per input character
as for implementing this algorithm, our tape layout will be:
0: L (looping counter for break)
1: C (input character)
2: t0 (temp)
3: t1 (temp)
4: e0 (emit bit)
5: e1 (emit bit)
6: e2 (emit bit)
7: t3 (3 counter)
8: 0 (0 padding)
9: 0 (0 sentinel)
10: 1 (start of unary representation)
]
real code starts here
+ set L
>, get input
>> move past temps
>>> move past e0 e1 e2
> +++ set counter
> > two 0s of padding
> + emit 1
debug initial unary representation
debug++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------
>debug++++++++++++++++++++++++++++++++.--------------------------------<
L < << <<< <<< < return to looping counter
[
if else algorithm with (C t0 t1) tape layout
C>
temp0> [-]+ temp1> [-] C<< [
IF C NOT ZERO
>>
>[-] e0 = 0
>[-]+ e1 = 1
>[-] e2 = 0
<<< <<
(temp0 temp1) = (1 0) at this point always so we can reuse them
as long as they are that way to end with
recall our if else algorithm requires t0 to be 1 initially anyway
C+ test for c being 255 that is negative 1
C[ {empty else} temp0> - C< [temp1>>+C<<-]]
temp1>>[C<<+temp1>>-]
temp0<[
{if 255 sentinel}
e1>>>- e1 = 0
debug++++++++++.----------
C<<<<[-]
input ,
here is where we need to detect EOF and set L accordingly
we can use the same fact to reuse t0 t1 in our if statement
C[
++ increment C
temp0>-
C<[temp1>>+C<<-]
]
temp1>>[C<<+temp1>>-]
temp0<[
on EOF break by setting L to 0
L<<-
temp0>>
temp0-]
+ restore temp0
C<
temp0>
temp0-]
C<
restoration
C-
temp0>+
<
temp0> - C< [temp1>> + C<< -] ] temp1>> [C<< +temp1>> -] temp0< [
IF C ZERO
temp0
> temp1
>[-]+ e0 = 1
>[-] e1 = 0
>[-] e2 = 0
<<<<<<
temp0>>
temp0-]
debug contents of (e0 e1 e2)
>> debug++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------
> debug++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------
> debug++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------
<<<< temp0 debug++++++++++++++++++++++++++++++++.--------------------------------
>> e0
ADVANCE THE TAPE
>>>
[
>> seek to 0 sentinel
+[>[<-]<[->+<]>]> seek right to first 1 in tape
doubling loop
[
- erase current 1
>[>] navigate to right border 0
>[>] go past rightmost 1 on copy tape to second right border 0
+>+ add two entries
[<] go back to first right border 0
<[<]> navigate to start of 1 tape
]
tape to start was e0 e1 e2 1 0 {a0 a1 a2 etc}
tape to end is e0 e1 e2 1 0 {0 0 0 etc} 0 {a0 a0 a1 a1 a2 a2 etc}
+[<[>-]>[-<+>]<]< seek left to 1 sentinel
<<< seek back to e0
APPEND A ONE IF E0 IS NONZERO
[
<+> save to temp0
- zero out to close loop
append a 1
>>>> seek to 0 sentinel
+[>[<-]<[->+<]>]> seek to first 1 in tape
[>] seek to end
+ append 1
[<] seek to start
+[<[>-]>[-<+>]<]< seek to count sentinel
<<< seek back to e0
]
<[->+<] add temp0 to e0 (either computes 0 plus 1 or 1 plus 0 so its idempotent)
> focus back on e0
permute e0 e1 e2 to e1 e2 e0
[-<+>>-<]>[-<+>]<<[->>+<+<] swap{@1 @2}
>>[-<<+>>>-<]>[-<+>]<<<[->>>+<+<<] swap{@2 @3}
> refocus e0
>>> seek to count sentinel
- decrement
]
reset counter +++
END ADVANCE THE TAPE
<<<<<
C<-
L<
]
>>>>>>>> move past last data entry
+[>[<-]<[->+<]>]> skip all 0s to our unary tape
for each one on the unary representation
[
output a 0
+++++++++++++++++++++++++++++++++++++++++++++++.>
]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 25 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1), score 1
[Noodle man's idea](https://codegolf.stackexchange.com/a/266437/58974) with a different implementation.
```
'¬iUÔ¬£"¹d¹"i'ÄpXcÃq"ã½Ñ»
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=J6xpVdSsoyK5ZLkiaSfEcFhjw3Ei473Ruw&input=IkhlbGxvLCBXb3JsZCEi)
## Explanations
### Code
```
'¬iUÔ¬£"¹d¹"i'ÄpXcÃq"ã½Ñ» :Implicit input of string U
'¬i :Prepend to "¬"
UÔ : Reverse U
¬ : Split
£ : Map each X
"¬πd¬π"i : Prepend to "¬πd¬π"
'Äp : "Ä" repeated
Xc : Codepoint of X times
à :End map
q"ã½Ñ» :Join with "ã½Ñ»"
```
### Output
Coming soon
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~25~~ ~~32~~ 29 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1), score ~~2~~ 1
```
©"ºº»Â½{'ÄpUÌc}¹d¹ã½Ñ{ßU¯J}¹¬
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=qSK6urvCvXsnxHBVzGN9uWS5473Re99Vr0p9uaw&input=IkhlbGxvLCBXb3JsKiEi)
Saved 3 bytes thanks to @Shaggy!
The only ASCII character that the output uses is `d`. I am 99% certain that there is no way to get arbitrary strings without using `d`.
I didn't think that score 1 was possible until I was looking through Japt's docs for a method that could concatenate strings or lists whose name was non-ASCII. When I wrote my first solution, I dismissed what I saw as not being usable for the purpose of creating arbitrary strings. However, when returning to this problem yesterday, I found the method `√£`.
`√£` returns all substrings of a string, optionally taking a length that the substrings must be of. But as it turns out, it also takes an optional second parameter which is prepended to the list of substrings.
This solution recursively generates the resulting program with a string literal containing the boilerplate for the connection of each letter.
The first step is `©`, which does short-circuiting logical AND of the input and what follows. The result is that if the input is an empty string, it is returned, otherwise the program continues execution.
Now the string literal starts. The first bit is `ºº»½Ñ`, followed by an interpolation of the expression `'ÄpUÌc` which essentially converts a character to the string `Ä` repeated the codepoint of the character times. Then follows the string `¹d¹`.
* This section creates the code to have an arbitrary character without using ASCII (except for `d`). A single character is generated using a similar technique to my previous solution by using long lines of `»½ÑÄÄÄÄÄÄ…ÄÄÄĹd¹`, which is essentially getting the character at codepoint `1+1+1+1...+1`, plus a longwinded way to get out of using parentheses.
Next, the string `ã½Ñ` is the code to prepend the rest of the string.
The rest of the string's code is generated by recursing with the last character chopped off (`ßU¯J`).
Finally, the string `¹¬` will join each section from a list to a string.
[Answer]
# [MetaBrainfuck](https://github.com/bsoelch/MetaBrainfuck) `-x`, 30 bytes / score 2 (`+.`)
`43{_:+}{n:n{.}+++.---256n~{.}}`
*input as program argument*
produces a Brainfuck program that prints a Brainfuck program that prints the Input, then executes that program
## Explanation
```
43{_:+} ## output 42 times + (`_:` discards the loop counter)
{n: } ## for each character `n` in the input
n{.} ## repeat `.` n times
+++.--- ## increment by 3, print decrement by 3
256n~{.} ## repeat `.` 256-n times
```
`-x` executes the generated Brainfuck program, which outputs a program that for each character `C` in the input increments `C` times prints then increments 256-C times resetting the cell back to zero.
[Brainfuck Program created for input "Test"](https://ato.pxeger.com/run?1=m70yqSgxMy-tNDl7wYKlpSVpuha3WNy1iQd6NAAgY3V1dWlh9JAGo-GCBYwGCgQMwnCAlCfQYgVWvAAA) (the output for the program will be the result of executing that Brainfuck program):
```
+++++++++++++++++++++++++++++++++++++++++++....................................................................................+++.---.................................................................................................................................................................................................................................................................................+++.---..............................................................................................................................................................................................................................................................................+++.---.................................................................................................................................................................................................................................................................+++.---............................................................................................................................................
```
Running MetaBrainfuck `-x` on the (uncommented) Brainfuck created by the output of the original program will execute the program without modification and print the input of the original program
---
# MetaBrainfuck `-x` , 24 bytes / score 3 (`+.>`)
`{43{_:+}{.}".>"{>{+}.}>}`
*input as program argument*
produces a Brainfuck program that prints a Brainfuck program that prints the Input, then executes that program
## Explanation
```
{ } ## for each character in the input
43{_:+} ## output 42 + ( `_:` discards the loop counter)
{.} ## print . char-code many times
".>"{ } ## for each character C in ".>"
>{+}. ## output > followed by C times + followed by a .
> ## print >
```
the produced Brainfuck program then prints C times `+` followed by `.>` for each character C in the input, the `-x` flag the immediately executes that program.
[Program created for input "Test"](https://ato.pxeger.com/run?1=m70yqSgxMy-tNDl7wYKlpSVpuha3WAS0iQd6NAB2JNgPcgKJ6inSTwv_jgbAaHAM6vCAFAzQ8gFWTgAA):
```
+++++++++++++++++++++++++++++++++++++++++++....................................................................................>++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++.....................................................................................................>++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++...................................................................................................................>++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++....................................................................................................................>++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>
```
[Answer]
# [Zsh](https://www.zsh.org/), score 12, 50 bytes
Set is `01234567$'\<`.
```
for c (${(s..)1})l+="\\$[[##8]#c]"
<<<'<<<$'\'$l\'
```
[Try it online!](https://tio.run/##qyrO@J@moanxPy2/SCFZQUOlWqNYT0/TsFYzR9tWKSZGJTpaWdkiVjk5VonLxsZGHYhV1GPUVXJi1P9rcnElFidnZtpqVMco6OnV1WpC@UBDsoCGgDm1XFxpCipgJhdXallijoJSAkwgQek/AA "Zsh – Try It Online")
Converts each character into `\[N]NN` octal, evaluated by wrapping the string in `$' '` and printed with `<<<`.
[Answer]
# [Morsecco](https://codegolf.meta.stackexchange.com/a/26119/72726): 54 bytes, score 3
Being a three-symbol language, a meta-cat automatically reaches a score of 3:
```
> echo Test | morsecco '. . . - .-. -.- .- -.-. ... . -.- - --- -.-. ... ---'
. -.-.-.. --..-.- ---..-- ---.-.. -.-. -.- - ---
> morsecco '. -.-.-.. --..-.- ---..-- ---.-.. -.-. -.- - ---'
Test
```
* `. .` `E`nters an `E`nter command
* `. - .-.` `R`eads from stdin (special address `T`)
* `-.- .-` `K`onverts from `·T`ext
* `-.-. ...` `C`oncatenates the dot and the converted input with two spaces for multi-token input
* `. -.- - ---` is the multi-token input for the later `K`onvert to `T`ext and `O`utput
* `-.-. ...` `C`oncatenates this to the existing code
* `---` `O`utput the code
# [Morsecco](https://codegolf.meta.stackexchange.com/a/26119/72726): ~~ 217 ~~ 216 bytes, score 0
Yes, we can also do a zero-score version, because morsecco accepts alternatives for it's characters:
* TAB can be used instead of whitespace
* a long dash `–` (unicode 0x2013) can be used as dash
* the middle dot `·` (unicode 0x00B7) can replace the dot
Of course, this adds a lot of bytes:
```
. -- . -- . . . .-- . . . - .-. -.- .- -.-. ... . -.- - --- -.-. ...
-- - -.-. - -.- .- . .-..... .- --.. ..
. .---. .- --.. --.
- .- . -........-..-- -- --.. --.
. -.--.--- -- --- --. ..
. -..-
-.- - . - .-- --.
```
The first line remains the same just installing an error handler to silently exit on the end of input to avoid testing for more bytes, but then we need to loop over the string, cutting one byte each time and translating it, because by now morsecco has no substitution command.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~200 192 184 211~~ 203 bytes, score ~~17~~ 16
```
#define P;printf(
#define Q{for(k=~i;k++P"a"))P
i;k;main(j,v)unsigned**v;{for(v++;i*4<strlen(*v);i++)Q"=a==a;");}P"main(){");for(;i--;)for(j=32;j--;)Q"+=");Q";");}if(i[*v]&1<<j)Q"++;");}}P"puts(&a);}");}
```
[Try it online!](https://tio.run/##NYy5DoMwEER7voI4EvIBRY5ucZ8SqhRRCgtMtEAM4nCDkl93bKR0@2bmbZW9qsq5Y60bNDouYJzQLA2N/km5NcNEO/lF6IQoiCKMFZEHeCs0tE0tW82ML6Nrzi3saysEIL/m8zL12lBuGaAQrCRSSamAMPgUZNfZ5iEogFkGLFytvJyhDVQSIX1dkt3AhuKD22dyyvM2dGKP/adxXWaaKA8hcM7ddN8PaXwfpr4@/AA "C (gcc) – Try It Online")
The input cannot contain `aimnpstu=+;&(){}`
This produces C programs of the form
```
a=a==a;
aa=a==a;
...
main(){
a++;...
aa++;...
puts(&a);
}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/RNtHWNtE6EU4jGFBWbmJmnoZmNUhA2xZEWqMzta3xSNJdizY1LKMDU5ty3WABVIY2Xi5B9cSrpJYDiNRIuUeo4n4sXBAPiSJdSBu/UoIyRFAkuICgfjJ9A2Rrg8oVCKGNwcAnTDN9@IwiTjmQKCgtKdZQS9S0rv3/HwA "C (gcc) – Try It Online")
Thanks to @l4m2 for score -1 and the note from @NoodleMan.
Less golfed version
```
#define P;printf(
#define Q{for(k=~i;k++P"a"))P
i;k;
main(j,v)unsigned**v;{
for(v++;i*4<strlen(*v);i++)
Q"=a==a;");
}
P"main(){");
for(;i--;)
for(j=32;j--;)
Q"+=");
Q";");}
if(i[*v]&1<<j)
Q"++;");
}
}
P"puts(&a);}");
}
```
# [C (gcc)](https://gcc.gnu.org/) for Linux x86\_64, ~~271 260 253 239~~ 226 bytes, score 8
```
#define P;printf(
unsigned*b,x;i;main(l,v)int**v;{l=asprintf(&b,"j\1X\xbazokaj\1_耀ok%s^\xf\5Ã",v[1]);for(b[1]=b[3]=l-21;i*4<l;b++){P"mai");for(x=++i;x--P"n"))P"=");for(x='B:5\xc7';*b P"+%d",x),*b-=x)for(;*b<x;x/=10)P";");}}
```
[Try it online!](https://tio.run/##PY3LSgMxGIX3PsUYqZ3c0FGL4N9sXLnMTqFpZTKXEhszMqPDj6VQ8NF8mb5FjCjdHc73HU4l11UV41ndtC40mYa33oX3Nj/5CINbh6ZmViA4eC1dyL0YaaKMjbD1qhz@3XMryIspngza8rPblCk/H/b7bjMZVgZbM/v@ImJcFEsKbdfnNiVlF9dL5eVVAY7dzD1YzulWk3RD/ixUnDtAKTUJhFJN1BFM7@9mBqvbKTCbacInNRFIBbNSIf1VUj9HwAtVXKYhpOFuF2N8aLzvRPbY9b4@/QE "C (gcc) – Try It Online")
The input cannot contain `aimn=+1;`
This produces C programs of the form
```
main=1+11+...;
mainn=1+1+11+111+...;
...
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTPPVtsQDrAyqczSxk8TTZFF4iXwYDiyBgUZOMy0gRDCIxyEFIQXhTStgpPYgERFmBAagughiitMqZDuiE6JxAUtaSFDVGLDDDF4qJATLFRPMSQkDELZCQMhfEqtFEDFjENijBPGuHIDqvcpY1At@slKv6SUAcjeRidJKVL@//@XnJaTmF78X7cqtSI1ubgkMTkbAA "C (gcc) – Try It Online")
Such programs may require the compiler flag `-zexecstack` and may not work on some Linux distributions.
Now supports strings longer than 127 bytes.
Slightly less golfed
```
#define P;printf(
unsigned*b,x;
i;
main(l,v)int**v;{
// push 1
// pop rax
// mov edx, <len of string>
// push 1
// pop rdi
// call L1
// <string>
// L1:
// pop rsi
// syscall
// ret
l=asprintf(&b,"j\1X\xbazokaj\1_耀ok%s^\xf\5Ã",v[1]);
for(b[1]=b[3]=l-21;i*4<l;b++){
P"mai");
for(x=++i;x--P"n"))
P"=");
for(x='B:5\xc7';*b P"+%d",x),*b-=x)
for(;*b<x;x/=10)
P";");
}
}
```
[Answer]
# [Rattle](https://github.com/DRH001/Rattle), 23 bytes, score 3
```
|II^P[gn[b"+"]`b",=">]`
```
[Try it Online!](https://www.drh001.com/rattle/?flags=&code=%7CII%5EP%5Bgn%5Bb%22%2B%22%5D%60b%22%2C%3D%22%3E%5D%60&inputs=test123)
The input cannot contain `+,=` characters.
This generates Rattle code that uses `+` to increment from 0 to the ASCII value of each character before printing the ASCII character with `,` and resetting the counter with `=`. The new code therefore only uses the characters `+,=` for a score of 3.
# Explanation
```
| get input
I save input characters to consecutive memory slots
I^ get length of input
P set pointer to 0
[...]` repeat N times (N = input length)
g get the character at the pointer
n get the ASCII value of this character
[....]` repeat M times (M = ASCII value of the character)
b"+" add "+" to the print buffer
b",=" add ",=" to the print buffer
> move pointer right
```
This generates code of the form `++++++++++,=++++++++,=++++,=` (where there are lots more `+` depending on the ASCII value of the input characters).
[Answer]
# [YASEPL](https://github.com/madeforlosers/YASEPL-esolang), 24 bytes / score 2
```
=b$34»=a'#hashtag!~!a~!~
```
the restricted char set being `#"`. YASEPL is not capable of template strings
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), ~~24~~ ~~22~~ ~~18~~ 17 bytes, score 4
```
{("1+"*1n@}/'](+'
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/v1pDyVBbScswz6FWXz1WQ1v9///EpGQA "GolfScript – Try It Online")
The restricted set is `(]1+`. I'm pretty sure this is minimal, but GolfScript is a weird language and I'm no expert on it.
This constructs an a program that looks something like:
```
1
1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+](+
```
This pushes arbitrary codepoints to the stack with `1 1+1+...1+`, using a newline as whitespace because it isn't printable. Then, `]` ends a list literal, which turns the whole stack into a list because there was no previous `[`. Finally, `(+` coerces the list of codepoints to a string by adding it to the empty input, and the result is implicitly outputted.
Here's an explanation of the generator code, which I think is probably also as short as it can get:
```
{("1+"*1n@}/­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌­
{ }/ # ‎⁡For each character of the (implicit) input:
( # ‎⁢ Decrement the codepoint.
"1+"* # ‎⁣ Repeat "1+" that many times.
1n # ‎⁤ Push the number 1, then push a newline.
@ # ‎⁢⁡ Move the "1+1+..." string to the top of the stack.
'](+' # Push the string ](+ to the stack.
# The entire stack is implicitly outputted.
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
] |
[Question]
[
Computers like binary. Humans like base 10. Assuming users are humans, why not find the best of both worlds?
Your task is to find the first `n` terms in the sequence [A008559](https://oeis.org/A008559) where each term is the binary representation of the previous number interpreted as a base 10 number.
## Input
An integer greater than 0. Note that the first value of A008559 is 2.
## Output
Just to make it a little more readable, the output should be the number of digits in the Nth term of A008559, which is [A242347](https://oeis.org/A242347).
Invalid inputs can output whatever, standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest bytecount wins, no standard loopholes etc...
## Test Cases
```
2 -> [1,2]
5 -> [1,2,4,10,31]
10 -> [1,2,4,10,31,100,330,1093,3628,12049]
20 -> [1,2,4,10,31,100,330,1093,3628,12049,40023,132951,441651,1467130,4873698,16190071,53782249,178660761,593498199,1971558339]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~38~~ ~~33~~ 25 bytes
```
a=2;loop{p /$/=~a="%b"%a}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWOxNtjaxz8vMLqgsU9FX0besSbZVUk5RUE2sh8lBlMOUA)
Outputs the sequence indefinitely starting from 2.
Thanks for a whopping -13 bytes from a collective effort by south and Dingus.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~9~~ 9 bytes
```
¡o§,ḋLd;2
```
[Try it online!](https://tio.run/##yygtzv7/qG2iocGjpsb/hxbmH1qu83BHt0@KtdH//wA "Husk – Try It Online")
Outputs the infinite sequence.
---
The previous version (also 9 bytes when outputting the infinite sequence) was
`moLd¡odḋ2`, but I've cleaned this up at the [request of lyxal](https://codegolf.stackexchange.com/questions/253857/length-of-binary-as-base-10-oeis-a242347/253861#comment563846_253861), who considered it too odd due to the moLd in it.
```
2 # starting with 2
¡ # construct an infinite sequence
o # by repeatedly applying 2 functions:
ḋ # convert to binary digits
d # convert from base-10 digits
m # now map over this infinite list
o # using 2 functions:
L # length of
d # base-10 digits
```
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$8\log\_{256}(96)\approx\$ 6.585 bytes
```
eLG2'_Ob
```
[Try it online!](https://fig.fly.dev/#WyJlTEcyJ19PYiIsIiJd)
Port of Vyxal
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 14 bytes
```
{#$x(10/2\)/2}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pWVqnQMDTQN4rR1Deq5eJKUzfUVjQGAEsCBXk=)
Outputs the nth element.
Unfortunately, this can only do the first 3 elements because it's written in C, so overflow happens very quickly.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `l`, ~~8~~ ~~7~~ 5 bytes
```
2?(ΠE
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJsIiwiIiwiMj8ozqBFIiwiIiwiMTIiXQ==)
Outputs nth term
## Explained
```
2?(ΠE
2 # Push 2 to the stack
?( # Input times:
ΠE # push int(binary representation of top of stack)
# the `l` flag pushes the length of the top of the stack
```
## Old 7 byter, outputs infinite sequence
```
2‡ΠEḞvL
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwiMuKAoc6gReG4nnZMIiwiIiwiMTIiXQ==)
## Explained
```
2‡ΠEḞẎvL
2‡ Ḟ # an infinite generator that gets its next term by:
ΠE # converting its previous term to binary and casting to int
vL # lengths of every item
```
[Answer]
# [Factor](https://factorcode.org/), 35 bytes
```
2 [ >bin dup length . dec> t ] loop
```
Prints the infinite sequence starting with 2. Times out on TIO, but here's a screenshot using the debugger to step through some of the starting iterations:
[](https://i.stack.imgur.com/AHnll.gif)
[Answer]
# [Sequences](https://github.com/nayakrujul/sequences), \$9 \log\_{256}(96)\approx\$ 7.4 bytes
```
2HE2hBnHz
```
### Explanation
```
2HE2hBnHz
E // Infinite sequence
2H // Starting with 2
// For each term:
2hB // Convert to binary
n // Interpret as integer
H // And use this as the next term
z // Get the length and output implicitly
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
L.BsbmlyF2
```
[Test suite](https://pythtemp.herokuapp.com/?code=L.BsbmlyF2&test_suite=1&test_suite_input=2%0A5%0A10&debug=0)
Prints the first \$n\$ terms.
The `m` can be omitted to instead print \$a(n)\$, where \$a(0)=2\$.
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 19 bytes
```
{≢⍕(10⊥2∘⊥⍣¯1)⍣⍵⊢2}
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/P@1R24TqR52LHvVO1TA0eNS11OhRxwwg9ah38aH1hppA6lHv1kddi4xq/z/qmwpUnHZohaGCkYKxgomC6X8A "APL (dzaima/APL) – Try It Online")
Due to limits, this can also only output the first 5 elements.
This works in Dyalog too, but can only output the first 3 elements there.
[Answer]
# [Haskell](https://www.haskell.org/), ~~75~~ 63 bytes
```
g 2
g x=length(show$f x):g(f x)
f 0=0
f n=f(div n 2)*10+mod n 2
```
[Try it online!](https://tio.run/##FYtBbsIwEEX3nGIWXQTqSjMex/ZU8hF6AyQUAXGiJCYiqOX0NcPmv6@n/4dum67zXKd0rBnsLsMzzdeSH0OzDbe/jx6e@@/cvLHrARNqltQ3l/EXCtj9gfBzuV3evS7dWCDB0q0/J1jvY3nAVK1xhtAwaSoYlcKGvY2GLDoxDtGyIbbSknGOvIKcD6RbFwN70aUnQQxkWg7RWn1RiN5j8KqEnUQSdRKobSOz/J/7uctb/Tqv6ws "Haskell – Try It Online")
* Thanks to @Sʨɠɠan for saving 2 Bytes
*f n* returns a (decimal binary, length) tuple
[Answer]
# [Python](https://www.python.org), ~~56 47~~ 40 bytes
* -9 thanks to friddo.
* -7 thanks to loopy walt.
Outputs the infinite sequence, starting from 2. (Note: [apparently this is fine](https://codegolf.stackexchange.com/questions/253857/length-of-binary-as-base-10-oeis-a242347/253863#comment563886_253863))
```
i=2
while i:=f"{int(i):b}":print(len(i))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwU2vzNyC_KISheLKYq78gqLMvBJbMMmVkpqmAGZpVGhacSlkpilU2BkagIEVULFeakVmiYaBJpdCPkzV0tKSNF2LmxqZtkZc5RmZOakKmVa2aUrVINlMTaukWiUriNKc1DygAFT9AigFpQE)
---
# [Python](https://www.python.org), ~~66~~ 59 bytes
* -7 thanks to loopy walt.
Suggested by friddo. Returns the first n terms.
```
lambda n,i=2:[1]+[len(i:=f"{int(i):b}")for _ in range(1,n)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3rXMSc5NSEhXydDJtjayiDWO1o3NS8zQyrWzTlKoz80o0MjWtkmqVNNPyixTiFTLzFIoS89JTNQx18jRjoUbogOQSkeUUDA01rbgUCopABiTqKKjr2qnrKKRpJGpqQvQsWAChAQ)
---
# [Python](https://www.python.org), ~~74~~ 69 bytes
* -5 thanks to loopy walt.
Returns the nth term.
```
lambda n,i=2:len((['1']+[(i:=f"{int(i):b}")for _ in range(n-1)])[-1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3XXMSc5NSEhXydDJtjaxyUvM0NKLVDdVjtaM1Mq1s05SqM_NKNDI1rZJqlTTT8osU4hUy8xSKEvPSUzXydA01YzWjdQ1jNaGG6YBUJCJUGOooGBpqWnEpFBSBjEnUUVDXtVPXUUjTSNSE6lmwAEIDAA)
[Answer]
# PARI/GP 55 bytes
```
f(n)=k=2;d=digits;while(n--,k=fromdigits(d(k,2)));#d(k)
```
Stack of 8 GBytes overflows for n=18.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 67 bytes
```
q;b;v;f(n){for(v=2;n--;v=q)for(b=q=0;v;v/=2)q+=v%2*exp10(b++);q=b;}
```
[Try it online!](https://tio.run/##VVDZbsIwEHznK1aRkBKSCB@5LNd9qfoVhQdiHIoKgRxNUVF@vek6HC2WvN6ZnVl5V4cbrYehkrnsZOGW3rk41G6nmCzDUHaq8izOVaUICrq5Yl7lq27KZuZ0pMTNfd@TlcplP2zLFvarbel6cJ4AHkugyujWrN@WoODMAogCoCQATnsJ8zlYZCEnNhMc04RlmDMSCVQTwpCjnImYIoxoYl8aJSm1lihLeSKsPqGCkBRrMU8zxqyZplmSkDSxpOCRyKiwrEhpHGeci16O39SHsmlBv6/qGUajP0x9@a2zOL2yxUm84I2dAP5j7lzduB5w7aTbcm1OaCPymj5Bs/02h8K97cCD@Y2a3TkJvj/qb1u7ba7FXpdGPlD5UGqwVLit98gaZO/rHp3LP8GxRknhOtM1hM@AcdosSpypDaAJ7mM3SpnltW0/xtq0n3WJQ0364UcXu9WmGcKvIdztfwE "C (gcc) – Try It Online")
Inputs \$1\$-based \$n\$.
Returns the \$n^{\text{th}}\$ element starting with \$a(1) = 2\$.
[Answer]
# [J](https://www.jsoftware.com), 18 bytes
```
[:#@":10x&(#.#:)&2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxKdpK2UHJytCgQk1DWU_ZSlPNCCKxS5MrNTkjXyFNQU3PDqjLUMFIwVjBRMFUwQyiYMECCA0A)
-2 thanks to Jonah!
[Answer]
# [Raku](https://raku.org/), ~~16~~ 30 bytes
```
map *.chars,(2,+*.base(2)...*)
```
[Try it online!](https://tio.run/##K0gtyjH7n1up4FCsYPs/N7FAQUsvOSOxqFhHw0hHW0svKbE4VcNIU09PT0vzv7VCcSJIZXScWex/AA "Perl 6 – Try It Online")
An expression for the lazy, infinite sequence of numbers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
‘ḊḌB$\Ẉ
```
A monadic Link that accepts a positive integer, \$n\$, and yields a list of the first \$n\$ terms.
**[Try it online!](https://tio.run/##y0rNyan8//9Rw4yHO7oe7uhxUol5uKvj////hgYA "Jelly – Try It Online")**
### How?
Performs each conversion step in the opposite order as it avoids the need to get lists again at the end.
Uses a reduce that only uses the left item at each step, starting with a list of length \$n\$ that starts with a \$2\$ as it saves a byte over collecting up \$n-1\$ times starting with a \$2\$.
```
‘ḊḌB$\Ẉ - Link: integer, n
‘ - increment (n) -> n+1
Ḋ - dequeue ([1..n+1]) -> [2..n+1]
\ - reduce by:
$ - last two links as a monad - i.e. f(left):
Ḍ - convert from decimal e.g. 2 -> 2 or [1,0,1,0] -> 1010
B - convert to binary e.g. 2 -> [1,0] or 1010 -> [1,1,1,1,1,1,0,0,1,0]
Ẉ - length of each
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 7.5 bytes (15 nibbles)
```
.`.2`@~``@$,`p
```
```
2 # start with 2
`. # iterate while unique:
``@$ # convert to bits
`@~ # and convert to base 10
. # now, map over this infinite list
, # get lengths of
`p # string representations
```
[](https://i.stack.imgur.com/xR5lK.png)
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 21 bytes
```
"2""2X>b >S"itr"len"map
```
[Try it here!](https://replit.com/@molarmanful/try-sclin) Returns an infinite list.
For testing purposes (use `-i` flag if running locally):
```
; 10tk >A
"2""2X>b >S"itr"len"map
```
## Explanation
Prettified code:
```
"2" ( 2X>b >S ) itr \len map
```
* `"2" ( ... ) itr` generate infinite list starting from 2...
+ `2X>b` to binary
+ `>S` to string
* `\len map` get lengths of each element
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
≔2θFN«⟦ILθ⟧≔⍘Iθ²θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU9DyUhJR6FQ05orLb9IQcMzr6C0xK80Nym1SENTU6GaizOgKDOvRCPaObG4RMMnNS@9JEOjUFMzFqiBE2qCU2JxanAJUFm6BlhVoaaOgpEmxNDa//9N/@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. As we are outputting A242347, which starts with `1`, so does this version. Explanation:
```
≔2θ
```
Start with `2`.
```
FN«
```
Repeat `n` times.
```
⟦ILθ⟧
```
Output its length on its own line.
```
≔⍘Iθ²θ
```
Cast it to decimal, then convert it to binary as a string.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 45 bytes
```
.+
$*:2
{`:\d+
$*B
+`(B+)\1
$1A
AB
B
}T`L`d
.
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0XLyoirOsEqJgXEduLSTtBw0taMMeRSMXTkcnTicuKqDUnwSUjh0vv/34DLkMuIyxgA "Retina 0.8.2 – Try It Online") Outputs the 0-indexed `n`th term. Link includes test cases for `0` to `3` as higher values are too slow. Explanation:
```
.+
$*:2
```
Convert the input to unary as a number of `:`s and suffix a `2` for the zeroth value.
```
{`
}`
```
Repeat until the nth value has been found.
```
:\d+
$*B
```
If more terms are needed then convert the current value into unary as a number of `B`s.
```
+`(B+)\1
$1A
AB
B
```
If there are any `B`s then convert them to binary using `B` for `1` and `A` for `0`. This is done separately to avoid corrupting the final value.
```
T`@=`d
```
Convert the "binary" to normal digits.
```
.
```
Count the number of digits in the final value.
A008559 can be obtained at a saving of 3 bytes by deleting the last line and removing the `}`.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 10 bytes
```
Y2LaP#TB:y
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJZMkxhUCNUQjp5IiwiIiwiIiwiMTAiXQ==)
Prints the first `a` terms in the sequence starting with 2, where `a` is the argument input.
```
Y2LaP#TB:y ; a = input
Y2 ; Set y = 2
La ; Loop the following code "a" times...
P# ; Print the length of...
TB:y ; y treated as a decimal number converted to a binary string
and set y to that value
```
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 9 bytes
```
Lb$
=2:JZ
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/3ydJhcvWyMor6v9/AA "cQuents – Try It Online")
Prints the entirely sequence infinitely starting with `1,2,4,10,31,100,330,...`
## Explanation
**First line**
```
implicit : output the nth term if input is provided, or all terms in the sequence if no input provided
each term in the sequence equals
L length ( )
b second line ( )
$ index
```
**Second line**
```
=2 first term in sequence is 2
: output the nth term in the sequence
each term in the sequence equals
J base 2 of ( )
Z the previous term
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 54 bytes
*-3 bytes thanks to [@Sʨɠɠan](https://codegolf.stackexchange.com/users/92689/s%ca%a8%c9%a0%c9%a0an)*
Prints the sequence indefinitely, starting at \$2\$ (as now allowed by the OP).
```
for(n=2;;console.log(n.length))n=BigInt(n).toString(2)
```
[Try it online!](https://tio.run/##BcExDoAgDAXQ67SDDKzExc3ZExDEiiG/BhqvX9978pdnGe21BXpW90sHYY0pFcXUXkNXIYReIXYzY92a7DACB9PDRoNQZPcf "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Infinite sequence starting at `2`:
```
Tλb}€g
```
[Try it online.](https://tio.run/##yy9OTMpM/f8/5NzupNpHTWvS//8HAA)
Could be the infinite sequence starting at `1` by replacing `T` with `2`: `2λb}€g` - [try it online](https://tio.run/##yy9OTMpM/f/f6NzupNpHTWvS//8HAA).
Outputting the \$n^{th}\$ term is 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) as well with either `2λèb}g` ([try it online](https://tio.run/##yy9OTMpM/f/f6NzuwyuSatP//zcFAA)) or `2IFb}g` ([try it online](https://tio.run/##yy9OTMpM/f/fyNMtqTb9/38DAA));
and outputting the first \$n\$ values is 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) with either `2λ£b}€g` ([try it online](https://tio.run/##yy9OTMpM/f/f6NzuQ4uTah81rUn//98UAA)) or `2IFbDg,` ([try it online](https://tio.run/##yy9OTMpM/f/fyNMtySVd5/9/UwA)).
**Explanation:**
```
λ # Start a recursive environment,
# to output the infinite sequence
T # Starting at a(0)=10
# Where every following a(n) is calculated as:
# (implicitly push the previous term a(n-1))
b # Convert it from a base-10 integer to a binary string
}€ # After we have the infinite sequence: map over each binary string:
g # Pop and push its length
# (after which the infinite sequence is output implicitly)
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
2æhpià∟
```
Prints the infinite sequence, starting from `1`.
[Try it online.](https://tio.run/##y00syUjPz0n7/9/o8LKMgszDCx51zP//HwA)
Outputting the first \$n\$ terms would be 8 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) instead:
```
2kæhpià;
```
[Try it online.](https://tio.run/##y00syUjPz0n7/98o@/CyjILMwwusgWwuUy5DAwA)
**Explanation:**
```
2 # Push a 2
∟ # Do-while true (without popping),
æ # using 4 characters as inner code-block:
h # Push the length (without popping)
p # Pop and print it with trailing newline
i # Convert the binary-string to a base-10 integer
à # Convert that integer to a binary-string
```
The program for the first \$n\$ terms is pretty similar, except that `k` pushes the input-integer; `æ` acts as a loop that many times instead of the do-while loop; and `;` discards the final binary-string after the loop, which would otherwise have been output implicitly.
[Answer]
# [Perl 5](https://www.perl.org/) -Mbigint, 58 bytes
```
eval'$_=2;'.'$_=new Math::BigInt($_)->to_bin;'x$_;$_=y///c
```
[Try it online!](https://tio.run/##K0gtyjH9/z@1LDFHXSXe1shaXQ9E56WWK/gmlmRYWTllpnvmlWioxGvq2pXkxydl5lmrV6jEWwMVVerr6yf//2/IZcRlzGXCZcplxmXOZcFlyWVo8C@/oCQzP6/4v25Bjm9SZnpmXgkA "Perl 5 – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 40 bytes
```
2:2(?v:2%$2,:1%-!
?v00.>lnao>l1)
.>a*+a1
```
[Try it online](https://tio.run/#%23S8sszvj/38jKSMO@zMpIVcVIx8pQVVeRy77MwEDPLicvMd8ux1CTS88uUUs70fD/fwA)
"Infinte sequence". Overflows at the 7th number.
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 11 bytes
```
)2¤U⟪¤bd⟫⊢l
```
[Try it online!](https://tio.run/##AR0A4v9nYWlh//8pMsKkVeKfqsKkYmTin6viiqJs//8xMA "Gaia – Try It Online") or [Try a test suite!](https://tio.run/##AUwAs/9nYWlh//8pMsKkVeKfqsKkYmTin6viiqJs/zpw4oCcIC0@IOKAnXDihpFxClsxIDIgMyA0IDUgNiA3IDggOSAxMCAyMF0g4oaRwqb/ "Gaia – Try It Online")
A sort of copy of the Jelly answer but in Gaia. Times out for >= 12 I think.
## Explained
```
)2¤U⟪¤bd⟫⊢l
) # Increment the input
2¤ # Push 2 "under" the incremented input by pushing 2 and then swapping
U # Push a range [2, input + 1] to the stack
⟪ ⟫⊢ # Reduce that list by:
¤b # Converting the last item to binary
d # And then to decimal
l # Get the length of the result
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 8 bytes
```
2`ĐąŁƥɓł
```
[Try it online!](https://tio.run/##K6gs@f/fKOHIhCOtRxuPLT05@WjT//8A "Pyt – Try It Online")
Prints indefinitely.
```
2 push 2
` ł do... while top of stack is truthy
Đ Đuplicate
ą convert to ąrray of digits
Łƥ ƥrint Łength
ɓ convert to ɓinary string (implicitly treats output as decimal number)
```
] |
[Question]
[
*This is a [rip-off](https://codegolf.stackexchange.com/questions/196864/i-shift-the-source-code-you-shift-the-input) of a [rip-off](https://codegolf.stackexchange.com/questions/193315/i-reverse-the-source-code-you-reverse-the-input/193317#193317) of a [rip-off](https://codegolf.stackexchange.com/questions/193021/i-reverse-the-source-code-you-negate-the-input) of a [rip-off](https://codegolf.stackexchange.com/q/192979/43319) of a [rip-off](https://codegolf.stackexchange.com/q/132558/43319). Go upvote those!*
Your task, if you accept it, is to write a program/function that outputs/returns its input/args. The tricky part is that if I make your source code palindrome via duplicating reversed source code after the original code, the output must be returned "palindromize".
The source code will be only duplicated once.
## Examples
Let's say your source code is `ABC` and the input is `xyz`. If i run `ABC` the output must be `xyz`. But if i run `ABCCBA` instead, the output must be `xyzzyx`.
Put it in a table:
```
Input: "xyz"
code ABC => "xyz"
code ABCCBA => "xyzzyx" (aware that it isn't "xyzyx")
```
## Details
Your code *before* processing should return the input.
Your code *after* processing should return the input with reversed input following no matter what input is.
**The process**:
Your code, **no matter what**, will be followed with a *reversed* code after it. Even if it's already palindrome by itself.
**Multiline code**:
Multiline code will be treated as *single line* code but with `\n`(newline)
## Rules
* Input can be taken in any convenient format.
* Output can be in any convenient format as well. As long as it follow the input-reversed input order.
* Standard Loopholes are forbidden.
## Scoring
This is code-golf so the answer with the fewest amount of bytes wins.
[Answer]
# [Haskell](https://www.haskell.org/), Full program, 39 bytes
```
iddi=(++)<*>reverse;main=interact--
id
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzMlJdNWQ1tb00bLrii1LLWoONU6NzEzzzYzryS1KDG5RFeXSyEzhWiFAA "Haskell – Try It Online")
## Mirrored
```
iddi=(++)<*>reverse;main=interact--
iddi
--tcaretni=niam;esrever>*<)++(=iddi
```
[Try it online!](https://tio.run/##jcy7DcAgDADRniko@cgTgNnFAkuxAhSAsj4RmSD9u7to3lzr3lKKoPHeRpcGPzwmh0bSUfriQXkBKH2QVgAr0@DVBbtQCzy/ILlovTd40O/fCw "Haskell – Try It Online")
Very simple approach for a full program. We have two "lines" (separated by `;` rather than an actual line break) of boilerplate ending in `--` and then the function `id`. When the program is reversed `id` gets changed to `iddi`, which we have defined to do the intended operation.
# [Haskell](https://www.haskell.org/), Function, 20 bytes
```
f x=x--x esrever++
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwrZCV7dCIbW4KLUstUhbW4Hrf25iZp5tZl5JalFicolCGlZFAA "Haskell – Try It Online")
## Mirrored
```
f x=x--x esrever++
++reverse x--x=x f
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwrZCV7dCIbW4KLUstUhbW4GLS0FbG8wpTlUAydlWKKT9z03MzLPNzCtJLUpMLgHysWkEAA "Haskell – Try It Online")
This one is also a pretty simple approach. We have a function `f x=x` and a payload hidden in a comment. When the code is revealed the payload extends our function with `++reverse x`.
# [Haskell](https://www.haskell.org/), Function, No Comments, 39 bytes
```
f=id where;di x y=y<>x;id=>>esrever=di;
```
[Try it online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN9XTbDNTFMozUotSrVMyFSoUKm0rbewqrDNTbO3sUouLUstSi2xTMq2hyi1yEzPzbAtKS4JLilQU0hSUiNSuBNEPsxYA)
## Mirrored
```
f=id where;di x y=y<>x;id=>>esrever=di;;id=reverse>>=di;x><y=y x id;erehw di=f
```
[Try it online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN_3SbDNTFMozUotSrVMyFSoUKm0rbewqrDNTbO3sUouLUstSi2xTMq1BAmBOcaqdHUigws4GqBSoITPFGqg5o1whJdM2DWqqRW5iZp5tQWlJcEmRikKaghKRtihB9MNcBwA)
The relevant function is `f`. This one is likely not optimal. I will explain it when I shorten it down a bit.
[Answer]
# [R](https://www.r-project.org/), 65 bytes, no comments
```
xx=paste0(x<-scan(,""),intToUtf8(rev(utf8ToInt(x))));`+`=cat;""+x
```
[Try it online!](https://tio.run/##K/r/v6LCtiCxuCTVQKPCRrc4OTFPQ0dJSVMnM68kJD@0JM1Coyi1TKMUyAjJ98wr0ajQBALrBO0E2@TEEmslJe2K/4lJySn/AQ "R – Try It Online")
Palindromized:
```
xx=paste0(x<-scan(,""),intToUtf8(rev(utf8ToInt(x))));`+`=cat;""+xx+"";tac=`+`;))))x(tnIoT8ftu(ver(8ftUoTtni,)"",(nacs-<x(0etsap=xx
```
[Try it online!](https://tio.run/##FYlBDoQgDAD/0lMJmHg0QR7gHe92WUy8FAPV9PcsO6fJTO1dNdzUJM@o69QSMToA4y6WWHY5F6z5xWdILBsLqhn4wx4hkXgAq2oBvFAKI/r/VRTeSlxOefDNFYfsJQpfzgA4ZEptWhXnLI3uoNrpk779Bw "R – Try It Online")
The vanilla version defines `+` to be an alias of `cat`, so that the call `""+x` outputs `x`. In the palindromized version, we call `""+xx+""` instead, outputting `xx` which is defined as the concatenation of `x` and its mirror. The code errors after producing the desired output.
There is an extra space at the beginning and end of the output, which was allowed by OP.
---
Previous version with same byte count, with comments but with no errors or extra spaces:
## [R](https://www.r-project.org/), 65 bytes
```
function(x,xx=paste0(x,intToUtf8(rev(utf8ToInt(x)))),`?`=cat)?#
x
```
[Try it online!](https://tio.run/##K/qfpmD7P600L7kkMz9Po0KnosK2ILG4JNUAyM7MKwnJDy1Js9AoSi3TKAUyQvI980o0KjSBQCfBPsE2ObFE016Zq@J/moZSYlJyipLmfwA "R – Try It Online")
[Try it online palindromized!](https://tio.run/##Fc2xDoQgEATQ3q@4aLMkFJY2hNoeezmOTWgWg4vZv8e9qV5mimkDP25gp8SlEogVcVe8Oa/qQhzqwbhByw90Rag7MYjR2NOfLkU2fplEpsUbjslpaf@rANNew4bc4ckNFEcNTMUKrJnveDnRM6BaOFHHgTDHb/rNZrw "R – Try It Online")
[Answer]
## Python, ~~44~~ ~~43~~ ~~42~~ ~~41~~ 40 bytes
a little trick with comment solves this problem
-1 byte thanks to @Wheat Wizard with the ";"
-1 byte thanks to @Jonathan Allan with the reversed line
-1 byte thanks to @Jonathan Allan again with Walrus Operator
-1 byte thanks to @qwatry for combining two line and saved an innocent byte from being used.
```
print(n:=input(),end='')#)]1-::[n(tnirp
```
**mirrored**
```
print(n:=input(),end='')#)]1-::[n(tnirp
print(n[::-1])#)''=dne,)(tupni=:n(tnirp
```
[Try it online!](https://tio.run/##fYw7CsMwEER7nUKQQhKJC5MmCHSJtIoLY22IwNkVa5nEp5d/AXep3vB2Z9KUX4TXW@LSUQCnlHqUxBGzRusipjFrcwEMy8WcTFNX1nrUGSMnUZZvb6u6EXtjXTACvtD94q4PrlY6ueG8wds//XKHYeyzjIN8En9aDpKwn8Sh35GZGMIM)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 3 [bytes](https://github.com/abrudz/SBCS)
```
⌽⊢,
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HP3kddi3T@pz1qm/Cot@9RV/Oh9caP2iY@6psaHOQMJEM8PIP/pymoJyYlqwMA "APL (Dyalog Unicode) – Try It Online")
A function that returns the string unmodified.
```
⌽⊢,,⊢⌽
```
[Try it online!!enilno ti yrT](https://tio.run/##SyzI0U2pTMzJT////1HP3kddi3R0gASQ@T/tUduER719j7qaD603ftQ28VHf1OAgZyAZ4uEZ/D9NQT0xKVkdAA "APL (Dyalog Unicode) – Try It Online")
A function that returns the string with its mirror appended.
### How it works
```
⌽⊢, ⍝ Input: a string S (char vector)
, ‚çù Ravel of S (no-op on a char vector)
‚åΩ ‚çù Reverse of S
⊢ ⍝ Select the right one (therefore no-op as a whole)
⌽⊢,,⊢⌽
,⊢⌽ ⍝ Same as above, but select the reverse of S
⊢, ⍝ Append the above to S (S + rev(S))
‚åΩ ‚çù Reverse the entire string,
‚çù but no-op since the string is already palindrome
```
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 31 bytes
```
f=([a,...b])=>!a?'':a+f(b)//a+
```
[Try it online!](https://tio.run/##jY@xTsMwEIZ3P4WJhOJLii3WVoGBCQYYMiYZXNcuLo4d2U6kCvHswQkSApay3Z3u/@67E594EF4P8SYM@iB97@ybPM/CHSSusBqtiNpZTAC/Y1bMqiIN31BK9x1Ud1f8Ps@3vFRkD4zxEs0Fwx80ujp6bY8EaM@jeCWstaRpQ1t3BbSWQXPb7RASzgZnJDXuSLKHdHCLr0O2wU/1yzMNK0GrM1lUAHZIJR85cfM1@JX@k1Blni@JnyuKZDXvByPxox3GmAEgpEZjEnT9tcRN@mopO@rlJH2QSf/ktCUJ9l/XhZjI36prf8Fj/gQ "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 2 bytes
```
m?
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=m%3F&inputs=Bees&header=&footer=)
A blatant port of the 05ab1e answer. Imaginary brownie points for anyone who can give me an answer to the question posed by my answer.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 3 bytes
```
θ⮌ω
```
[Try it online!](https://tio.run/##S85ILErOT8z5///cjkfres53whkA "Charcoal – Try It Online") Palindromised:
```
θ⮌ωω⮌θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5///cjkfres53nu8EUud2wPkA "Charcoal – Try It Online") Explanation:
```
θ
```
Print the input.
```
⮌ω
```
Print the reverse of the empty string.
```
ω
```
Print the empty string.
```
⮌θ
```
Print the reverse of the input.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 5 bytes
```
{m:xx
```
[Run and debug it](https://staxlang.xyz/#c=%7Bm%3Axx&i=%22Hello%5B%22)
[Run and debug itti gubed dna nuR](https://staxlang.xyz/#c=%7Bm%3Axxxx%3Am%7B&i=%22Run+and+debug+it%22)
Fixed, and now 1 byte shorter.
## Explanation
```
{m:xx
{m map each char to itself
:x escape regex special characters
x push the input again
xx:m{
x push the input once more
x push the input again
:m mirror it
{ error on unterminated block, exiting and displaying top of stack
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~2~~ ~~3~~ 2 bytes
-1 bytes thanks to @Razetime
```
ºI
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0C7P//8rKqsA "05AB1E – Try It Online")
[Try it online!!enilno ti yrT](https://tio.run/##yy9OTMpM/f//0C5Pz0O7/v@vqKwCAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
·πö;·πõ
```
[Try it online!](https://tio.run/##y0rNyan8///hzlnWD3fO/v//f0hRpUJmiUJ@Xk5mXqoiAA "Jelly – Try It Online")
## Palindromized
```
·πö;·πõ·πõ;·πö
```
[Try it online!!enilno ti yrT](https://tio.run/##y0rNyan8///hzlnWD3fOBiIgNev///8hRZUKmSUK@Xk5mXmpigA "Jelly – Try It Online")
I believe a 2-byte solution is not possible. However, it's nice that this answer is a case-insensitive palindrome.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
'1ê U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=JzHqIFU&input=IlhZWiI)
* palindromized
'1ê UU ê1'
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=JzHqIFVVIOoxJw&input=IlhZWiI)
[Answer]
# Brainfuck, 7 bytes
`,[.>,]+`
## Mirrored
`,[.>,]++[,<.],`
This solution is probably a bit cheating as it is optical palindrome. So not just order of characters is reversed, but characters are too. `>` becomes `<` and `[` becomes `]`. `+-,` are kept the same as they are (almost) optically same when reversed.
This was the only way as it is impossible to construct loops in brainfuck when code is reversed, because code like `[...]` would become `]...[` which is invalid code in brainfuck.
## How it works
```
,[ load first character and start loop
. print last loaded character
>, load next character into next cell
] if last character is null byte end loop
+ sets value of cell to 1
mirrored part:
+ sets value of cell to 2
[ starts loop
, no more characters are there so it just sets cell to 0
<. print previous cell
] end loop when there are no more characters
, does nothing; just reads another null byte
```
[Answer]
# JavaScript, 79 bytes
```
m=process.argv[2]//
console.log(m)//
//)``nioj.)(esrever.``tilps.m(gol.elosnoc
```
Palindromed:
```
m=process.argv[2]//
console.log(m)//
//)``nioj.)(esrever.``tilps.m(gol.elosnoc
console.log(m.split``.reverse().join``)//
//)m(gol.elosnoc
//]2[vgra.ssecorp=m
```
[Try it online!](https://tio.run/##DchBCgMhDAXQ/ZxEF43Q/ex7h1JQbBCH6Jdk8Ppp3)
[Try it online!!enilno ti yrT](https://tio.run/##VcwxCsMwDEDRPSexh8qQPXvvEAIyrjAOsmWk4Ou7JXTJ@uH9M45oSUu/Xk0@NGfdukoiM4iax74eISxJmgkTsGRX/S@E4BFbkRO8I1MapIB4Fe4G1WVhIBZrkpanBetcLkS4iZHzcEppiP/p04ZwrPvIGsGMkmjf6pzzTczyBQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 12 bytes
```
tee a#a ver
```
[Try it online!](https://tio.run/##S0oszvj/vyQ1VSFROVGhLLWI6///wvLUohIA "Bash – Try It Online")
[Try it online (palindromized)!](https://tio.run/##S0oszvj/vyQ1VSFROVGhLLWIi6sotQzMSU0t@f@/sDy1qAQA "Bash – Try It Online")
## Explanation
```
tee a#a ver # Copy STDIN to file a (with implicit output)
rev a#a eet # Using file a as STDIN, reverse STDIN (with implicit output)
```
[Answer]
# Java, 37 bytes
```
s->s//)(esrever.)s(reffuBgnirtS wen+
```
[Try it online!](https://tio.run/##PYw7DsIwEET7nMKisoUwB@BT0COKiApRLIkdORjH2l0HAsrZgxGIaUaaz2uhh0VbX6eYLt5VovJAJPbggngVIuuXEwNn6ztXi1tuZcnoQnM6C8CG1G/8UZuJOrHz2qZQseuCPgbA4RANAne4/j63wm4mWmxpuVTSEJreoFYk0Vibdk1wyKW4mzAvptWfXQ7E5qa7xDpmCPsgrYYY/SBnj@E5U@q7HYtxegM)
Mirrored:
```
s->s//)(esrever.)s(reffuBgnirtS wen+
+new StringBuffer(s).reverse()//s>-s
```
[Try it online!](https://tio.run/##PY6xbsMwDER3f4WQSUJg@QPaesheZDA6FRlUhzLkKrRAUk7cIt/uqnXQWwjc3SNudLOrx/PnmvJHDL3qo2NWry6g@q5U0cNncVLOPIWzupRUd0IBh/eTcjSweZR/NZaPNkuI1mfsJUxo39DRckxATiZ63shW@ZeV65abxmhgghnIGtYE3ufDgIGkU1fAfVXtEa5qow7ZeyDNxv4BDNo0Dbc1r0//A7qFBS52ymJTYSSi9talFBe9uy1fO2O27r26rz8)
[Answer]
# [PHP](https://php.net/) -F, 32 bytes
```
echo$argn;//;)ngra$(verrts ohce
```
[Try it online!](https://tio.run/##K8go@G9jXwAkU5Mz8lUSi9LzrPX1rTXz0osSVTTKUouKSooV8jOSU7n@/6@orPqXX1CSmZ9X/F/XDQA "PHP – Try It Online")
**palindromed:**
```
echo$argn;//;)ngra$(verrts ohce
echo strrev($argn);//;ngra$ohce
```
[Try it online!](https://tio.run/##K8go@G9jXwAkU5Mz8lUSi9LzrPX1rTXz0osSVTTKUouKSooV8jOSU7m4QAoUikuKilLLNMAKNUEqwQpBCv7/r6is@pdfUJKZn1f8X9cNAA "PHP – Try It Online")
Notice the new line at the end of the code
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 17 bytes
```
<o:\?(0~!:i
<o>;
```
[Try it online!](https://tio.run/##S8sszvj/3ybfKsZew6BO0SqTyybfzprr//@M1JycfAA "><> – Try It Online")
Palindromified:
# [><>](https://esolangs.org/wiki/Fish), 34 bytes
```
<o:\?(0~!:i
<o>;
;>o<
i:!~0(?\:o<
```
[Try it online!!enilno ti yrT](https://tio.run/##S8sszvj/3ybfKsZew6BO0SqTyybfzpqLy9ou34Yr00qxzkDDPsYq3@b//4zUnJx8AA "><> – Try It Online")
Explanation, if not palindromized:
```
< | send the IP leftward (golfier due to the second line)
i | push one character of input; stack = [i]
: | duplicate and push the top value of the stack; stack = [i,i]
! | skip the next instruction
~ | pop (drop) the top element of the stack (skipped)
0 | push literal 0; stack = [i,i,0]
( | pop x then pop y and push 1 if x < y else push 0; stack = [i,bool]
? | pop the stack and skip the next instruction if the value was 0 (checks for -1 terminator); stack = [i]
\ | send ip upwards, wrapping around vertically (only if input value was terminating -1)
:o | non-destructively output the top value, thereby accumulating the input onto the stack as we go
| or
; | halt
```
When palindrominated, instead of wrapping back around to `;`, we instead go through `~`, dropping the top value of the stack (known to be `-1`), then hit `>o<`, outputting the top value of the stack until the stack is empty (i.e. the input in reverse) and then terminate via error.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 39 bytes
```
(s,ss)=>//``nioj.``esrever.]s...[+s||
s
```
[Try it online!](https://tio.run/##bY1BCsMgFET3OYW7fEn7sy0Ue4kuQ0ARKUrQ4DeSltzdSgOuupth5s04lRXpaNd0zbeig6fEKCxbssEzUYAuRFw8xlFKb4NDKQ1Fk03EmRBxGug4OmrgFrVhoi1gCs8UrX8Bv3drFQlMVgucRQ79/v70/F/GBjbV/dPM@LskAxxdsB76CjW4fAE "JavaScript (V8) – Try It Online")
When palindromised it becomes:
```
(s,ss)=>//``nioj.``esrever.]s...[+s||
ss
||s+[...s].reverse``.join``//>=)ss,s(
```
[Answer]
# JavaScript, 31 bytes
```
s=>s//``nioj.)(esrever.]s...[+
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvu/2NauWF8/ISEvMz9LT1MjtbgotSy1SC@2WE9PL1qb639BUWZeiUaahnpFZZW6puZ/AA)
Mirrored:
```
s=>s//``nioj.)(esrever.]s...[+
+[...s].reverse().join``//s>=s
```
[Try it online!](https://tio.run/##HcgxCoAgGAbQ3YukSL9ri15EBCUMdDDxE6kub9H2eDmMgL2l2texzUNPaAOlvC/pzCR4RIsjNnIgIisZk/YDHP2NyAXlMxXvlYLRmLWl0vnBl@t@FiHmCw)
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 14 bytes
```
#;esrever=._$
```
[Try it online!](https://tio.run/##K0gtyjH9/1/ZOrW4KLUstchWL16F6///isqqf/kFJZn5ecX/dQsA "Perl 5 – Try It Online")
Note the trailing newline.
Perl `-p` prints the input after the code runs. The normal code does nothing to manipulate the input, being commented out. The palindromed code:
```
#;esrever=._$
$_.=reverse;#
```
takes the input and appends the reverse of it to the input before printing.
[Try it online!!enilno ti yrT](https://tio.run/##K0gtyjH9/1/ZOrW4KLUstchWL16Fi0slXs8WzC1OtVb@/7@isupffkFJZn5e8X/dAgA "Perl 5 – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 8 bytes
```
qe#e%W_
```
[Try it online!](https://tio.run/##S85KzP3/vzBVOVU1PJ7r///EpOSU1LR0AA "CJam – Try It Online")
It has a newline at the end.
**Reversed**:
```
qe#e%W_
_W%e#eq
```
[Try it online!](https://tio.run/##S85KzP3/vzBVOVU1PJ6LKz5cFcgs/P8/MSk5JTUtHQA "CJam – Try It Online")
[Answer]
# [J](https://www.jsoftware.com), 4 bytes
```
,[.|
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxRCdarwbCvOmjycWVmpyRr5CmoJ6YlKwO56hzpYNMACmt0YvWgYinA00ECqjDeQgtQI46xMwFCyA0AA)
Uses the [4-byte answer for reverse](https://codegolf.stackexchange.com/a/265474/78410).
```
,[.| input: string s
,[.| [. selects the left one out of , and |
and , returns s unmodified when called monadically
,[.||.[, input: string s
|.[, select left out of |. and ,, which is |. (reverse) of s
,[.| same as above, but now called with s on the left side and rev(s) on the right
so , concatenates the two instead
```
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 6 bytes
```
#%1-.
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X1nVUFeP6///jNScnHwA "GolfScript – Try It Online")
[Try it online!(palendromized)](https://tio.run/##S8/PSStOLsosKPn/X1nVUFePi0tP11BVmev//4zUnJx8AA "GolfScript – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/) (GHC 8.4.1), 32 bytes, no comments
```
c x y=y<>x
iddi=reverse>>=c
id
```
The function for this part of the problem is `id`.
Unfortunately, TIO has an older version of GHC, which doesn't export the `(<>)` operator in `Prelude`. I can't use the standard `(++)` operator because it's a palindrome (more on this later).
## Mirrored
```
c x y=y<>x
iddi=reverse>>=c
iddi
c=>>esrever=iddi
x><y=y x c
```
The function for this part of the problem is `iddi`.
## How?
```
c x y=y<>x
```
This line defines a new function `c`, that is basically the concatenation operator `(++)` with its arguments swapped. I was forced to use `(<>)` instead of `(++)` because the latter is a palindrome and would mess things up in the mirrored part.
---
```
iddi=reverse>>=c
```
This line defines a new function `iddi`, which basically implements the "mirror" functionality. Expanding the `(>>=)` operator for clarity, the definition can be rewritten as
```
iddi s=c(reverse s)s -- = s<>reverse s
```
---
```
c=>>esrever=iddi
x><y=y x c
```
This part of the mirrored code is just garbage. Fortunately, it's *syntactically correct* garbage. These two line define two new operators, `(=>>)` and `(><)`, in terms of the previously defined functions `iddi` and `c`, whose names are (very conveniently) palindromic strings.
The reason why I can't use `(++)` instead of `(<>)` is that in this case the mirrored part of the code would try to redefine `(++)`, leading to an unpleasant result.
[Answer]
# [Pxem](https://esolangs.org/wiki/Pxem) ([esolang-box](https://github.com/hakatashi/esolang-box) notation), 43 bytes.
Some unprintables are escaped.
```
.e
e.z\001.rXX.a.w.s.p.d.a.w.c.o.i.cED.-.+.ae.
```
## Parindromed
```
.e
e.z\001.rXX.a.w.s.p.d.a.w.c.o.i.cED.-.+.ae..ea.+.-.DEc.i.o.c.w.a.d.p.s.w.a.XXr.\001z.e
e.
```
### With comments
For parindromed.
```
XX.z
# MAIN ROUTINE
# call with empty stack
.a.eXX.z
# SUBROUTINE
# should be called with either
.aXX.z
# if top is not e, then push zero
# else e is popped
.ae.z\001.rXX.aXX.z
# if top is not zero, then print and pop each item
# (except top .; discarded) and return
.a.w.s.p.d.aXX.z
# cat program BUT preserve each item
# XXX: where does EOF: -1 go?
.a.w.c.o.i.cED.-.+.aXX.z
# NOTE if not parindromed, the next section and so far is e.,
# which .e and so far would not be there
# if parindromed, call with stack
.ae..eXX.z
# garbage, then reaching to .D returns to main section
.aa.+.-.DXX.z
# and garbage
.aEc.i.o.c.w.a.d.p.s.w.a.XXr.\001z.e\ne.
```
[Try it online!](https://tio.run/##jVh7V9rKFv@/n2JII5kY8hgERWJUCl7LOUrVWpcV0BWSoGBIOElQNHC@eu@eSRAIvV3XtTQzv/2c/ZiHz@HTr8@fK86@ae1ZTq/YL@5U7D1td9cq29puud8z@5qtFUtlrVwm5U@hEyHZmeiTkRk@I00rFnVnOvaDCJ3VH2pnZ0Zdx9Hb2EGPTmT5Xj@fZzPLH41MzxYPVdt5Ub2J66LiYZ7k86nwRe36q8HxOOVD8nihgJFEPqYfqTpPBvKcW5j90WrePny/bhhFTdtZgBffvjdvz34@1L9dXZ3Urw2itxHHx19q378@3JxcfW9@a1WltzmHDPSGuvk8W5WPxn44mCYz6Usicvc/JJzRxDUjB4VPjN8fRzB89QM7HLuDKJ833YEZIvkRCXxMJI4/5uaCIdCvkM@3fpyd1c8bRpXZwNSerYdPg36kszGifCngWE8@4j@L1DKhlnNgqOi79mEeQv9iuojLob7phg43m63SmGomPZ2Fjo2EUJ2qb6oewp93VWAK31GXCjEu4FmIWljEPiSh5iH5JZqQWRQguR6iTluT97tIaHe87a4wewycMVIS5ep9aZdX42pN53t6S1c7HptfgLl7Rel4qqr3avo8mbbvqR5Cirw6VvVoFaxomxghhFf9DLi3v4kRAtJelrGyiRGtzKuDLOPOJrYPfA9ZDCxbGWx3bxMjBITD7Pp2NjFCwMWXLOPuJkY0iFg/67a2iRENIuZkfdzfxAgp8WqQNV3cxAgB6dcs494mRorgzzTLWNnESBF8fMsy7m9ipAj@vGeToP0GA3fM7KLLmxghENsoa7m0iREN3Bll4723iREN3LGzpiubWAnSL2UxcFHOYDvAl8ti4DWfxcCZLYrNhRm2zHS7sMW0KVm/qvEpbcqpbkP/nVLpDlY6Ygd3PPpX2e6IvNrZ6RQ7RAWuUFW2oVun6/1ddXU@F6vt1@nbu2l31Vzc0nsuKJzrb9DsKlJ1tX2fUmmJ8yqy1TUdsoeE1Hz7/rjQBbvgAW4nQ3CheIyoC08pT4IjZRtIzLPEOqxnzNzk1QJFe@ACpDiGWS4OYVRTx3rvEtCErXAMCj4Y7Q9GW20sGNfYFpQ0DtVA5@PE3DGiqmGLY9yotkCiGgstn2sBpeO1kfze3baptihYQWBJLD7dZLEqI5nANmY5TRZnJlJz8LZ6@aFSYb5Fl5k9N43HV4hMowZxmabJZZFdxi2Jz2mqif0mriSepFn/naCAFkfHSkLUQR@7Zs9xDYPrEE6M2Upwe@x7gwcrfOk7QTSScvyW3KXcHYJFXX1MeGg9dmJS6Mwp6QJ3SEozV10KJz3M0YRwBSp9BGOuyh1zBWZWnKcG1/n/xNzg1V7gmM9sAnmrYc71/THy/AiNzMh6GniPHLAKi@VKWFR7mIjMN5lN5HSWYzMtmfAw@Wcx2WITygbNyBpR6PtBGivwSNfFWNA/ulSYC6L46z@t2vmJISiO8Kn@rXV90ro2BEd572gaUYLbW8VUXpVQGSs2G1mKrwwU66ShyIqkmI4ifPq8EOP4dMSBNhPIstI4sYDdB7FXELdBTchGt7eBQi28K07Ho0rwOBh4UR@uDMyfjveha/ZqIdkS4VrwKwwsQ/hyctpsxVACUug4thgGcF3DbDjvTzwrGvgeusANMf7efi78jcWu0dBh2JWkJf0Ei3HgRJPAQzkJeJaUv5YUwA/JkvL3kkLVLQnXawRqUiYr5Ft8JcZXBnAxN2RZT5mvljwTXBdjFgFUX6Kn@Kpw96EbrqPuwHMOtSNeq8orjn1NDPBEZ2V4z2pcgmrkOHENQgm0af4HNT/xjBXbNXy@8Oh8xkHJQPzplXcQoRXTY1j669PAdXAOQir6q5GESQzgbDbBt0BbEjzcLNwUGgVXpFlkgvGNATy6a7iO9xg94RtRp4XbhHtz88BwdXGCccOAtYRRgG8KTUkqEFH8l2Pr4o4aUqlSLZXF@dLIAKxf4NM1ww/4vFAv3BV@ivG5wSkPVdSC9jOR7ViDEdxjYbHOoxPAdzyJOL1ugLh@Bz5QX2jvgLulvYN6Pl8/KFdE1tA6YPV/uftSe6fc5WEvujNKJbmeCic9Dyy4koiREgSkbhg7RTFOWOCJEQ28iTOnEaes9YNSBXgOy3sihRLjS7OJZvGngX@KqC6XKjrNnn6B77Z/rqzVWkT/Al@vBSFcEG5Xk/UCORkWbsS4aWjM4tBgdQzhH9KyLQxluWvc0ETRWbPLQMhDl82H3ZXQB0vTEFHM@lPcpjWwYvB12TSb3kzxZYHZykE70gjnYHbJSuTGuDygvKnszVLo7Y9Ch78Xev9wg0oxN@Q1V6LFYp6gd4010ghIz1AsCF5gF5jSV4g9bEJAkxL/i1b4BTaPQFwyaSSqt2lE9OWOsW0QubiNzQNN3KY5g@9KUP/J6humHXObLhYPt10RKgbMcMoWHEAKVCNXRXdOAPexwcsgBDUcLRSaFPNoeOgeDbfcqrs1rLKxysaQo3myw4JnhtaFcoBHY2Z35maWyAlL5/oQiTWuj7178xH3hzeckRx@yY0DLnRwGNK3tBx4z2RmTWBkC0hAcr@4OCXhgnSB8yJ9TK6447BiTk7fGAqXFfSzJOmSNDzAdBOmRQshT8I/TKcwEPXfL4Mu13ZcB97bkGdohXR7ggaRpOYBiEskaQl20jSZRolAnySbvpTMu3NBpycV/UcDXMksxP4ZMaEd4o/o0xrAYANcxtAuIblVWmOYzfAYnvk1H40HdsGJBiOnMLbGk8JL@K7bZuSIqzko/fkhjSJz4MI1ubQSYHpVjyv0usQuZcLMfH0GXcg05CIp7ZUqO7ulChJiUzJ4bX7SaqSnhgmXC@7T/53/VGsaHfrhIAFw4HOMJPAa3PXgh0Nhkh7MbflcgddEYTY1g0eIQXOK0sxNP6FfcDXL/Rc "ksh – Try It Online")
] |
[Question]
[
You will be given 3 integers as input. The inputs may or may not be
different from each other.
You have to output 1 if all three inputs
are different from each other,
and 0 if any input is repeated more
than once.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your code as short as possible!
[Answer]
# [Python 3](https://docs.python.org/3/), ~~23~~ ~~21~~ 20 bytes
```
lambda*a:len({*a})>2
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSvRKic1T6NaK7FW087of0FRZl6JRpqGoY6RjrGmJhcy3wiJb6xjDJL/DwA "Python 3 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 7 bytes
```
*.Set>2
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfSy84tcTO6L81V3FipYKSSryCrZ1CtUKahkq8pkKtkkJafhGXhomOgqWOgqGmDpeGqY6CkY6CKYhpCBTSUTADMS10FIBqTEBMYx0FENK0/g8A "Perl 6 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 13 bytes
A different solution to @Kirill by using [`mad()`](https://stat.ethz.ch/R-manual/R-devel/library/stats/html/mad.html) for an unintended purpose!
```
mad(scan())>0
```
[Try it online!](https://tio.run/##PYxBCsIwEEX3PcWAmwyMwVSKCta7hHQiATuBJnUjPXtsKpW/eXwebyoH4HF@2RzkCclZUQhBUhgYLPhZXA5RCHycIHPaLBflzRJYHDe@3x2ltcZPLdyP/w/ddpfRDuoXx8epLI1Xhlo64wrtDoY66ipcaF2FGxm6YvkC "R – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~24~~ ~~22~~ 20 bytes
```
all(table(scan())<2)
```
[Try it online!](https://tio.run/##PY3BCsIwEETv/YoFL1lYA4kUFerHxLiRQNxAm/YifntsKpW5PIbHzFgPwK85uRLlCZN3ohCiTPHB4CDM4kvMQhDyCIWnzfJZFpbI4rkLt91RWmt8t4Xh@O/Qb3V1Kani7onV7wIHi/XTBWXI0glXsDsY6qlvcKY1Da5k6IL1Cw "R – Try It Online")
Returns a boolean, but as folks have already discussed on the [Python answer](https://codegolf.stackexchange.com/a/171616/78274), this should be OK.
Thanks to digEmAll for saving 2 bytes.
[Answer]
# JavaScript, 22 bytes
If we can output boolean values then the last 2 bytes can be removed.
```
a=>new Set(a).size>2&1
```
[Try it online](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i4vtVwhOLVEI1FTrzizKtXOSM3wf3J@XnF@TqpeTn66RjRXtKGOkY5xrA6IAWRCGEY6hjARECNWLzexQCNNU/M/AA)
For the same byte count, this works on arrays of any size but assumes the input will never contain a `0` and output is a boolean.
```
a=>!a[new Set(a).size]
```
[Try it online](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1k4xMTovtVwhOLVEI1FTrzizKjX2f3J@XnF@TqpeTn66RppGtKGOkY5xrKbmfwA)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 16 bytes
```
->a{1-(a<=>a|a)}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6x2lBXI9HG1i6xJlGz9n9BaUmxQlp0tKGOkY5xbCwXgm@MxgfC2Nj/AA "Ruby – Try It Online")
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~55~~ 25 bytes
*-29 thanks to Jo King*
```
O@O1u|@O@II-!/;I-!/;u^?-p
```
[Try it online!](https://tio.run/##Sy5Nyqz4/9/fwd@wtMbB38HTU1dR3xpMlMbZ6xb8/2@oYKRgBAA)
It should be possible to golf off quite a few bytes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÙQ
```
[Try it online](https://tio.run/##yy9OTMpM/f//8MzA//@jjXWMdUxiAQ) or [verify some more cases](https://tio.run/##yy9OTMpM/W/q5nl4gr2SwqO2SQpK9v8Pzwz8r/M/2ljHWMcklivaUMdIxxhI65rqmOoYGoBEjIx1oBjIM9DRtdAxiAUA).
**Explanation:**
```
Ù # Uniquify the (implicit) input
Q # Check if it's still equal to the (implicit) input
```
[Answer]
# Mathematica, 13 bytes
```
Boole[E!=##]&
```
Pure function. Takes three integers as input and returns `0` or `1` as output. I know that this is rather similar to [David G. Stork's answer](https://codegolf.stackexchange.com/a/171658), but it exploits `SlotSequence` to shave off a byte (as compared to `Boole@*Unequal`).
[Answer]
# [J](http://jsoftware.com/), 4 bytes
```
-:~.
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F/Xqk7vvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagqGCkYIxjGME4vwHAA "J – Try It Online")
## Explanation:
Is the argument equal `-:` to itself after removing the duplicates `~.`
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 4 bytes
```
3=#?
```
[Try it online!](https://tio.run/##y9bNz/7/39hW2d5QwUjB@P9/AA "K (oK) – Try It Online")
Does the count of the distinct elements equal 3?
[Answer]
# Japt `-N`, 3 bytes
```
eUâ
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=ZVXi&input=WzEsMiwzXQotTg==)
---
## Explanation
`Uâ` deduplicates the input and `e` tests if it's equal to the original.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~25~~ 26 bytes
```
f(a,b,c){a=a-b&&a-c&&b-c;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI1EnSSdZszrRNlE3SU0tUTdZTS1JN9m69n9mXolCbmJmnoYmVzUXZ0ERkJ@moaSaEpOnpKOQpmGoo2Cko2CsqWmNXdIQnyRQpyF2SROEsbX/AQ "C (gcc) – Try It Online")
[Answer]
# [brainfuck](https://esolangs.org/wiki/Brainfuck), 91 bytes
```
,>,>,[-<-<->>]>>+++++++[>+++++++<-]+<<<<[>]>>[<<<[-<->]<[>]>>->[>.<<<->>-]<+]<+[>>>[>]<-.>]
```
[Try it online!](https://tio.run/##NUsxCoBADHtQ7YG6lnykdFBBOAQHwffXlMMkQ5qk@7P1@3yPK3MC6WokEIAM@G9MQ4zwKr1MLWPcCkdjxlcNE8rBFWttiMx5WT8 "brainfuck – Try It Online")
### How it works
```
,>,>, 'read input as A, B, and C
[-<-<->>]>>+ 'compute A-C, B-C
++++++[>+++++++<-]+ 'prepare output
<<<<[>]>> 'if A-C != 0 && B-C != 0
[
<<<[-<->] 'compute A-B
<[>]>>-> 'if A-B != 0
[>.<<<->>-] 'print 1
<+
]
<+
[ 'else (this else is for both of the if statements, even though they are nested... wierd, I know)
>>>[>]
<-.> 'print 0
]
```
[Answer]
# Powershell, ~~27~~ 25 bytes
*-2 bytes thanks @AdmBorkBork*
```
+!(($args|group).Count-3)
```
Test script:
```
$f = {
+!(($args|group).Count-3)
}
&$f 1 2 3
&$f 3 2 1
&$f 2 1 3
&$f 2 2 3
&$f 2 1 1
&$f 2 1 2
```
Explanation:
```
$args|group # Group arguments
( ).Count # Count of groups
( -3) # is 0 if inputed integers are unique
! # operator not converts int to boolean: true if integers are unique
+ # converts boolean to int: 1 if integers are unique, otherwise 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
QƑ
```
[Try it online!](https://tio.run/##y0rNyan8/z/w2MT/h9sfNa35/z@aK9pQR0EXiA1idRSUFRJzchRK8zILS1O5og10FAwVdIxidbiiLXUUTIDKLIFssAaoeghQVihKLUhNLElNUcjMK0lNTy0q5orWNTQAmQshQEYAWSAUyxULAA "Jelly – Try It Online")
[Answer]
# Common Lisp, ~~25~~ 2 bytes
```
/=
```
[Try it online!](https://tio.run/##JcsxCoAwDAXQq/zN/EnSzh5GK0KhNKF6/1h0etMrrd4e0swclw3IjgOFqB2LSIIiEZ95qlMlcRrER@0PJNYt/kPGCw)
-23 bytes thanks to @ceilingcat!
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 3 [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. Takes list as argument.
```
∪≡⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HHqkedCx91Lfqf9qhtwqPevkd9Uz39H3U1H1pv/KhtIpAXHOQMJEM8PIP/pykYKhgpGHNBaEMA "APL (Dyalog Unicode) – Try It Online")
`∪` does the set of unique elements from the argument
`≡` match
`⊢` the unmodified argument?
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 32 bytes
```
import Data.List
$l|hasDup l=0=1
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRMElsSRRzyezuIRLJacmI7HYpbRAIcfWwNbwf3BJIlDeVkFFIdpQx1DHKPb/v@S0nMT04v@6nj7/XSrzEnMzkyGcgJzEkrT8olwA "Clean – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 10 bytes
```
`==#Unique
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@z/B1lY5NC@zsDT1v19qakpxtEpBQXJ6LFdAUWZeSUhqcYlzYnFqcXSajkI0lwIQRBvqKBjpKBjH6kC4BmCuJYxrqaNgoaNgAuNCFBsiyVoi6TU0AOqGEbFcsbH/AQ "Attache – Try It Online")
This is a fork of the operator ``==` and `Unique`, equivalent to:
```
{ _ == Unique[_] }
```
## Alternatives
`{#_=#Unique[_]}` (15 bytes)
`Any##Same=>Pairs@Sort` (21 bytes)
`Any@{`=&>_[[0'1,1'2,2'0]]}` (26 bytes)
`&${not(x=y or y=z or x=z)}` (26 bytes)
`&${x/=y and y/=z and x/=z}` (26 bytes)
`{Any!Same=>Chop&2!_[0'1'1'2'2'0]}` (33 bytes)
[Answer]
# Java 9, ~~43~~ 27 bytes
*thanks to @Olivier Grégoire*
```
(a,b,c)->a!=b&b!=c&a!=c?1:0
```
Previous attempt:
```
(a)->a[0]==a[1]||a[0]==a[2]||a[1]==a[2]?0:1
```
[Answer]
# [Red](http://www.red-lang.org), 21 bytes
```
func[b][b = unique b]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85Oik2OknBVqE0L7OwNFUhKfZ/QVFmXolCmkK0oYKRgnEsFwrfKPY/AA "Red – Try It Online")
[Answer]
# T-SQL, 39 bytes
```
SELECT IIF(a=b OR b=c OR c=a,0,1)FROM s
```
Input is taken as separate columns **a, b, c** from a pre-existing table **s**, [per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341).
Tried a variation using `COUNT DISTINCT` from input taken as separate rows, but that was a couple bytes longer.
[Answer]
# Pyth, 3 bytes
```
s{I
```
Takes input as a list.
[Try it here](http://pyth.herokuapp.com/?code=s%7BI&input=%5B3%2C%201%2C%204%5D&debug=0)
### Explanation
```
s{I
{IQ Check if the (implicit) input is invariant under deduplication.
s Cast to int.
```
If we're allowed to treat True and False as 1 and 0 (which they are under the hood in Pyth), we can drop the `s` to get down to 2 bytes.
[Answer]
# SmileBASIC, ~~25~~ 24 bytes
```
READ A,B,C?A-B&&B-C&&C-A
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 11 bytes
```
->a{a==a|a}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6xOtHWNrEmsfZ/QWlJsUJadLShjpGOcWwsF4JvjMYHwtjY/wA "Ruby – Try It Online")
Assuming we can return a boolean. Which everyone is doing nowadays.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes
```
d?∧1|0
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P8X@UcdywxqD//@jjXVMdUxi/0cBAA "Brachylog – Try It Online")
# short explanation
`d?` **d**eduplcates input an test if still equal to input(**?**)
`∧1` if true return 1
`|0` else return 0
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~19~~ 17 bytes
-2 bytes by Jo King.
```
:{:{:{=}=}=++0=n;
```
[Try it online!](https://tio.run/##S8sszvj/36q2FoxsQVBb21Ajz/r///@6ZQqGcMIYAA "><> – Try It Online")
[Answer]
# [q](https://kx.com/download) 14 bytes
```
{x~distinct x}
```
Technically this solution will return '1b' or '0b', which is the way a boolean value is distinguished from a numeric type, though it retains all arithmetic functionality, and so is in essence a 1 or 0:
```
q)1b +35
36
```
To return 1 or 0 non-boolean you have the below, which takes the byte count to 21
```
{$[x~distinct x;1;0]}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 67 bytes
```
f=a=>a.map((m,i)=>a.map((n,j)=>m==n&i!=j).every(z=>!z)).every(y=>y)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbR1i5RLzexQEMjVydTE87J08kCcnJtbfPUMhVtszT1UstSiyo1qmztFKs0YbxKW7tKzf/J@XnF@Tmpejn56RppGtGGOkAYq6nJhSFuhFPcGCT@HwA "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
(Inspired by [last week's Riddler](https://fivethirtyeight.com/features/when-will-the-arithmetic-anarchists-attack/) on FiveThirtyEight.com. [Sandbox post](https://codegolf.meta.stackexchange.com/a/16158/70172).)
Given a year between 2001 and 2099, calculate and return the number of days during that calendar year where `mm * dd = yy` (where `yy` is the **2-digit** year).
2018, for example, has 5:
* January 18th (1 \* 18 = 18)
* February 9th (2 \* 9 = 18)
* March 6th (3 \* 6 = 18)
* June 3rd (6 \* 3 = 18)
* September 2nd (9 \* 2 = 18)
Input can be a 2 or 4-digit numeric year.
Output should be an integer. Optional trailing space or return is fine.
# Complete input/output list:
```
Input = Output
2001 = 1 2021 = 3 2041 = 0 2061 = 0 2081 = 2
2002 = 2 2022 = 3 2042 = 4 2062 = 0 2082 = 0
2003 = 2 2023 = 1 2043 = 0 2063 = 3 2083 = 0
2004 = 3 2024 = 7 2044 = 3 2064 = 2 2084 = 5
2005 = 2 2025 = 2 2045 = 3 2065 = 1 2085 = 1
2006 = 4 2026 = 2 2046 = 1 2066 = 3 2086 = 0
2007 = 2 2027 = 3 2047 = 0 2067 = 0 2087 = 1
2008 = 4 2028 = 4 2048 = 6 2068 = 1 2088 = 3
2009 = 3 2029 = 1 2049 = 1 2069 = 1 2089 = 0
2010 = 4 2030 = 6 2050 = 3 2070 = 3 2090 = 5
2011 = 2 2031 = 1 2051 = 1 2071 = 0 2091 = 1
2012 = 6 2032 = 3 2052 = 2 2072 = 6 2092 = 1
2013 = 1 2033 = 2 2053 = 0 2073 = 0 2093 = 1
2014 = 3 2034 = 1 2054 = 4 2074 = 0 2094 = 0
2015 = 3 2035 = 2 2055 = 2 2075 = 2 2095 = 1
2016 = 4 2036 = 6 2056 = 4 2076 = 1 2096 = 4
2017 = 1 2037 = 0 2057 = 1 2077 = 2 2097 = 0
2018 = 5 2038 = 1 2058 = 0 2078 = 2 2098 = 1
2019 = 1 2039 = 1 2059 = 0 2079 = 0 2099 = 2
2020 = 5 2040 = 5 2060 = 6 2080 = 4
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, lowest byte count in each language wins.
Pre-calculating and simply looking up the answers is [normally excluded per our loophole rules](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/1063#1063), but I'm explicitly allowing it for this challenge. It allows for some interesting alternate strategies, although its not likely a ~~98~~ 99-item lookup list is going to be shortest.
[Answer]
# Excel, 48 bytes
Hooray! Finally something Excel is actually good at.
```
=COUNT(VALUE(ROW(1:12)&"/"&A1/ROW(1:12)&"/"&A1))
```
Takes input from A1 in the form of an integer 1-99 representing the year, and outputs to wherever you enter this formula. It's an array formula, so use Ctrl-Shift-Enter instead of Enter to enter it.
This takes advantage of the fact that `COUNT` ignores errors, so any errors that are caused by either the month not dividing the year (leading Excel to parse something like `2/12.5/25` or by the date not being valid, like `2/29/58`, are just silently ignored.
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
[k/32%13*(k%32)for k in range(96,509)].count
```
[Try it online!](https://tio.run/##LZPLboMwEEX3/QpvIkGFWvweL/gSmkVUJS1JRCKaLvL1FHfO6mrs4XDv2L4/H9@32a2n4WMdL@/e7ax/bS4779rTbTEXM81mOcxfx6akLval3b993n7nx/o8HpYfM5hxtJ2x@250nXGbeJXQGb9J1Cp1JmyStRKtirbYXktrddduoFTVK9eCshEFZjP7Gy5WLfjotXZW@51D4bmNl6vizSU004c9B8/36seT08PzJPWBdXg@0b/x@qrCPryAv2B1Pzj9X/DU5A3kDYnv4AVRfoAXe0aNv8hBRHgxKD/iLzK/yPyi0FdUE3kT/pJDvf4nBc406vcpsY6/RN6Ev4y/DC9zvhl/OaD4y@TN3JYsKP6E@yLcF8GfwJOg8xX8SWKdvCLqR@AVzqMwv@JQ7kvBX4FXmF8hbyFvKdXP/uXlvkzzozlcr82pmVozDOZs6luaunN9Tf8Pp23XPw "Python 2 – Try It Online")
An anonymous function given as a method object. Produces all products of `(month, day)` pairs `(m, d)` as encoded by `k=32*m+d` with `0≤m≤12`, `0≤d≤31`, wrapping around. Eliminates Feb 29-31 by excluding them from the range.
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 65 bytes
```
y->{int m=13,c=0;for(;m-->1;)if(y%m<1&y/m<29+m%2*3)c++;return c;}
```
[Try it online!](https://tio.run/##dZJfb5swFMXf8ymukJigOMyGJlPq0Gnq0zRteej2VPXBI1A5wwbZppIV5bNntmGTpjLQ5d89/I51j0/sla1Px19XLoZeGTi593w0vMtv6OrNt3aUteG9XGxqoxomfKvumNbwlXEJ5xXAMP7seA3aMONurz0/gnC95NEoLl@enoGpF50GKcBnaX5IpuxhaBQzvYIWqqtd35@5NCAqUqK6wrTtVULFen1PaMrbxMZiT97Z92Jf7DIRFzdlWmcZVY0ZlYSaXq40wB3D2T1ABWeMCCrcWbq6DVW6Cqp/jgJtnbIMXYI2od6qfJ@gDzPRK7cLKhLcvO8Wef9lFnb/YzQR8ey@xCoQnlfudXjREQdSERiTY7mo2gZCMc8E/2cSXrMJbhNvs7guMitu0TTjyzR7H5nP0FaE2n2121GbZX9SD9GAavTYGZdOm7Nh6Own7XZDYlM6ax6tNo3I@9Hkg9s6pk2iuDjegbtAEus0lhECi2YO@sur4OHJPsNHiA5fIriD6NvhO7jHGXxZ@bpcfwM "Java (JDK 10) – Try It Online")
# Credits
* 8 bytes saved thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2).
* 4 bytes saved thanks to [Asone Tuhid](https://codegolf.stackexchange.com/users/77598/asone-tuhid) on their [Ruby answer](https://codegolf.stackexchange.com/a/162163/16236).
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 94 bytes
```
param($a)for($x=Date 1/1/$a;$x-le(Date 12/9/$a);$x=$x.AddDays(1)){$z+=$x.Month*$x.Day-eq$a};$z
```
[Try it online!](https://tio.run/##JcmxDkAwEIDhVzHc0BKaikXEILF6iEucGEopiSKe/VRsf75/sQe5bSRjmBd0OAlAOVgnwNct7hRppRVgBT41JH7JVRlIBqvBZ03ft3huQkt5w5V81Nl5H@MQYaS0Aj4VXMycFy8 "PowerShell – Try It Online")
Takes input as a two-digit year, then constructs a `for` loop from `1/1/year` to `12/9/year` (because 12/10 and beyond will never count and this saves a byte). Each iteration, we increment `$z` iff the `.Month` times the `.Day` is equal to our input year. Outside the loop, `$z` is left on the pipeline and output is implicit.
*Edit - this is culture dependent. The above code works for `en-us`. The date format may need to change for other cultures.*
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~46~~ 42 bytes
```
->y{(1..12).count{|j|y%j<1&&y/j<29+j%2*3}}
```
[Try it online!](https://tio.run/##LZPLTsMwEEX3/QpvWvEIIX6PpQY@JOqiICo1qgAVuoiafntImLO6GntyfO/YOV/ehunQTk8vw/XO1rV19/X71@Xz9zr247Dut3azGZ77rSuP/do9@NttGj725x/Tmq6zlbG7qnOVcbN4lVAZP0vUKlUmzJK1Eq2KtthGS2t1186gtKhXrgVlIwrMZvZnXFy04KPR2lntdw6F52ZeXhRvLqGZPuw5eL5RP56cHp4nqQ@sw/OJ/pnXLCrswwv4C1b3g9PzgqcmbyBvSHwHL4jyA7zYMGr8RS4iwotB@RF/kflF5heFvqKayJvwlxzq9ZwUuNOo36fEOv4SeRP@Mv4yvMz9ZvzlgOIvkzfzWrKg@BPei/BeBH8CT4LOV/AniXXyiqgfgVe4j8L8ikN5LwV/BV5hfoW8hbylLH52q9W3@f836v3p9Gqu47HqR3PojjvTtqa/TX8 "Ruby – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~48~~ ~~44~~ 43 bytes
```
F=(x,h)=>h>12?0:F(x,-~h)+(x/h<3*h%6+28>x%h)
```
[Try it online!](https://tio.run/##DcxBDoIwEADAr3Ah2XWh1poYQVvjhU8YIw0SV4KUFGPqxa/XHucyg/3YpfPP@V1O7t7H2GgIBaM2bDbqJOsmsfwxEoQ1H7crznek9ibkjPHQuWlxYy9G94CLEOLsvf1CVeFVvOwMcCtCmoAokJJSIrWZzlpKJyLGPw "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), ~~59~~ 58 bytes
```
x=>[a=0,...'030101001010'].map((k,m)=>x%m|x/m>31-k||a++)|a
```
[Try it online!](https://tio.run/##LYzRCoIwFEB/xZdwl6vrmk8iG/TiT0jkxSRK52RGLNi/rxFx4Lyd8@Q376N7bK9ytbcpdip6pXtWVEgpc6qpSvyUX6ThTYi5MKC0P5jgj0bXVTmHwIgQOLajXXe7THKxd9Gnwdk5/oimgX97LXxqBaLHExEBDpnKBuyEB4D4BQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
31x12_2¦3RĖP€Fċ
```
[Try it online!](https://tio.run/##y0rNyan8/9/YsMLQKN7o0DLjoCPTAh41rXE70v0/5VHj1kcNc4wMgISCncKjhrlZ1ofbuQwNDB7u2Ha4Hagq8j8A "Jelly – Try It Online")
Take a number in range `[0,100[` as input.
[Answer]
# JavaScript (ES6), 91 bytes
I was curious to know how hardcoding would compare to an iterative computation. It's definitely longer (see [@Shaggy's answer](https://codegolf.stackexchange.com/a/162141/58563)), but not *awfully* longer.
*Edit*: It is, however, much longer than a more direct formula (see [@l4m2 answer](https://codegolf.stackexchange.com/a/162155/58563)).
Takes input as an integer in **[1..99]**.
```
n=>(k=parseInt('8ijkskercdtbnqcejh6954r1eb2kc06oa3936gh2k0d83d984h'[n>>1],36),n&1?k>>3:k&7)
```
[Try it online!](https://tio.run/##Dca7DoIwFADQna@4E7QBTEsRQaTOfoNxgFJeJbdYiIvx25Hl5Ez1p16VG5ctRtvqvat2rCQx1VK7VT9wI0E@TmY12ql2a/Ct9DRkxTl1XDeJUSyztShE1g@JYW0u2iJPh@CJUvJXJDIaoc/vRkpxNf6F7p11BKECXgLCDThjR8KQwtcDUBZXO@vTbHtCEsYYhID0IIA4lochdAQpLb3f/gc "JavaScript (Node.js) – Try It Online")
### How?
Odd years have significantly less chance of having **mm \* dd = yy** than even years. More concretely, odd years have **0** to **3** matches, while even years have **0** to **7** matches. This allows us to code each pair of years with just 5 bits, which can conveniently be represented as a single character in base 36.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 40 bytes
```
{+grep {$_%%$^m&&29+$m%2*3>$_/$m},1..12}
```
[Try it online!](https://tio.run/##PYzBDoIwDIbvPsUOg6A02G6A4aCPIiEGvbhkwRMhPPvsummWf23/fn/9vLz74FZVPtU1bPVrmb3a9FgU@u7K0gy1doU52Zsez9rtQE1DZg@faVWVmzzHQLE3DEf1cP5QERh@ltWKrNQeiLvYE3SiOBFcMh39xBgg4ZFr5JB3mGnMTCQw348uCo85bXPW/v1085eJTie5xHRCp7mV3xzDFw "Perl 6 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/) and [3](https://docs.python.org/3/), ~~55~~ 52 bytes
```
lambda y:sum(y%i<(y/i<29+i%2*3)for i in range(1,13))
```
[Try it online!](https://tio.run/##LZPLbsIwEEX3fIU3SEkbqfHbrsiXUBapCiUIAgp0ka@nDnNWV2NPTu4d27f5cbyO5nnovp7n/vL906v58/53qeb1sKnmj2Fj8vuwNm@2PlwnNahhVFM//u4r3Whb189530931antVjdK75qtaZQpYkVco2wRL1VolCsSpUpSZWnRrZRay64uoLCoFa4GpT0KTEf2C84vmvHRSm209BuDwjOFFxfFmwlopA97Bp5txY8lp4VnSWod6/BsoL/w2kUT@/Ac/pyWfWfkf85Sk9eR1wW@g@eS8B083zJq/HkOwsPzTvgef575eebnE31ZNJA34C8Y1Mp/guNMvXwfAuv4C@QN@Iv4i/Ai5xvxFx2Kv0jeyG2JCcVf4r4k7kvCX4KXnMw34S8F1smbkvhJ8DLnkZlfNij3JeMvw8vML5M3kzfnxc9utbpNw/io@vO5OlRDrbpOndTrDTWn5RW9Hk55QP8 "Python 2 – Try It Online")
[Answer]
# [Bash + GNU utilities](https://www.gnu.org/software/bash/), 57
* 1 byte saved thanks to @SophiaLechner
```
seq -f1/1/$1+%gday 0 365|date -f- +%m*%d-%y|bc|grep -c ^0
```
Note that the `seq` command always produces a list of 366 dates - for non-leap years January 1st of the next year will be included. However in the date range 2001..2099, MM\*DD will never be YY for January 1st of the next year for any of these years, so this extra day won't affect the result.
[Try it online!](https://tio.run/##JcpBDoIwFEXROat4IXQi@dBiNCEmLsWk0F9kIMW2k8a69qpxeHPupMO9WOeRWHusG16DlKrrBjmO7wuMq3a/btGiFgF0RY3md1aBI4j@UQI/QVb1qm9UKxajEySO51M2OvJXCK14HIQhkfI058XzDppxk8W4jcsH "Bash – Try It Online")
[Answer]
# T-SQL, ~~123~~ 121 bytes
[Per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341), input is taken via pre-existing table **t** with an integer field **y**, which contains a 2-digit year.
```
WITH c AS(SELECT 1m UNION ALL SELECT m+1FROM c WHERE m<12)
SELECT SUM(ISDATE(CONCAT(m,'/',y/m,'/',y)))FROM c,t WHERE y%m=0
```
Line break is for readability only. Inspired largely by [Sophia's Excel solution](https://codegolf.stackexchange.com/a/162180/70172).
* The top line generates a 12-item number table **c** which is joined to the input table **t**.
* If that passes I mash together a date candidate using `CONCAT()`, which does implicit `varchar` datatype conversions. Otherwise I'd have to do a bunch of `CAST` or `CONVERT` statements.
* Found the perfect evaluation function `ISDATE()`, which returns 1 for valid dates and 0 for invalid dates.
* Wrap it in a SUM and I'm done.
* **EDIT**: Moved the integer division check (`y%m=0`) into the `WHERE` clause to save 2 bytes, thanks @RazvanSocol.
Unfortunately, it's not much shorter than the lookup table version (using the string from [osdavison's version](https://codegolf.stackexchange.com/a/162189/70172)):
# T-SQL lookup, 129 bytes
```
SELECT SUBSTRING('122324243426133415153317223416132126011504033106131204241006003213011306002122042005101305111014012',y,1)FROM t
```
**EDIT**: Leaving my original above, but we can save a few bytes by using a couple of new functions:
* `STRING_SPLIT` is available in MS SQL 2016 and above.
* `CONCAT_WS` is available in MS SQL 2017 and above.
* As above, replaced `IIF` with `WHERE`
# MS-SQL 2017, ~~121~~ 118 bytes
```
SELECT SUM(ISDATE(CONCAT_WS('/',value,y/value,y)))
FROM t,STRING_SPLIT('1-2-3-4-5-6-7-8-9-10-11-12','-')
WHERE y%value=0
```
# MS-SQL 2017, extra cheaty edition: 109 bytes
```
SELECT SUM(ISDATE(CONCAT_WS('/',number,y/number,y)))
FROM t,spt_values WHERE number>0AND y%number=0AND'P'=TYPE
```
Requires you to be in the `master` database, which contains a system table `spt_values` that (when filtered by `TYPE='P'`), gives you counting numbers from 0 to 2048.
[Answer]
# [Julia 0.6](http://julialang.org/), 49 44 42 bytes
```
y->sum(y/i∈1:28+3(i%2⊻i÷8)for i=1:12)
```
[Try it online!](https://tio.run/##LZNNTsMwEIX3PYU3SIkIIv4fVwoXqbrogkquSkEpXfQGFRdiwZKb9CIhYb7V09iTz@@NncPlWHdp2g/T9enlfHlrrs/1frvZtZNH39QHd//6qb/f0u7fR1MHu7auna6vu/FsBrPZ2M7YbbdxnXGzeJXQGT9L1Cp1JsyStRKtirbYXktrddfOoLSoV64FZSMKzGb2Z1xctOCj19pZ7XcOhedmXl4Uby6hmT7sOXi@Vz@enB6eJ6kPrMPzif6Z1y8q7MML@AtW94PT84KnJm8gb0h8By@I8gO82DNq/EUuIsKLQfkRf5H5ReYXhb6imsib8Jcc6vWcFLjTqN@nxDr@EnkT/jL@MrzM/Wb85YDiL5M381qyoPgT3ovwXgR/Ak@CzlfwJ4l18oqoH4FXuI/C/IpDeS8FfwVeYX6FvIW8pSx@tqvVx1hPn83ueGz2TW3NMJiDWf6cpnaH1tST@f91WtOupj8 "Julia 0.6 – Try It Online")
*-5 bytes inspired by Asone Tuhid's Ruby answer.*
*-2 bytes replacing count with sum*
### Explanation:
For each month `i` from 1 to 12, calculate `y/i`, and check if it's one of that month's days. Months with 31 days are 1, 3, 5, 7, 8, 10, 12 - so they're odd below 8 and even at and above 8. So either `i%2` or `i÷8` (which is 0 for i<8 and 1 for i>=8 here) should be 1, but not both - so we XOR them. If the xor result is true, we check dates `1:28+3` i.e. `1:31`, otherwise we check just dates `1:28`.
`1:28` is sufficient for the rest of the months (this improvement inspired by [Asone Tuhid's Ruby answer](https://codegolf.stackexchange.com/a/162163/8774)) because:
* for February, the only possibility would have been `2*29 = 58`, but `2058` is not a leap year, so we can assume Feb always has 28 days.
* the other months with 30 days are month 4 and above - for which `i*29` (and `i*30`) would be above 100, which can be ignored.
Finally, we count out the number of times `y/i` belongs in this list of days (by using boolean `sum` here), and return that.
[Answer]
# JavaScript, ~~91~~ ~~85~~ ~~82~~ ~~81~~ 77 bytes
Takes input as a 2-digit string (or a 1 or 2 digit integer).
Takes advantage of the fact that `new Date` will rollover to the next month, and continue doing so, if you pass it a day value that exceeds the number of days in the month you pass to it so, on the first iteration, it tries to construct the date `yyyy-01-345` which becomes `yyyy-12-11`, or `yyyy-12-10` on leap years. We don't need to check dates after that as `12*11+` results in a 3-digit number.
```
y=>(g=d=>d&&([,M,D]=new Date(y,0,d).toJSON().split(/\D/),D*M==y)+g(--d))(345)
```
3 bytes saved thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld).
---
## Test It
```
f=
y=>(g=d=>d&&([,M,D]=new Date(y,0,d).toJSON().split(/\D/),D*M==y)+g(--d))(345)
o.innerText=[...Array(99)].map((_,x)=>(2001+x++)+` = `+f(x)).join`\n`
```
```
pre{column-count:5;width:480px;}
```
```
<pre id=o></pre>
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~89~~ ~~84~~ ~~68~~ 58 bytes
```
f=lambda y,d=62:d-59and((d/31+1)*(d%31+1)==y)+f(y,-~d%372)
```
[Try it online!](https://tio.run/##Hc09DsMgDAXgvafwUgUaUIH80ESid6GyUCM1JIqysPTq1O7y6T0Pz3s531t2tabwiesLIxSFYXQz6mGKGYXAe2dbK28Cr/8QQpFtEkXpL128kzVtBxRYMjhjrCJ6wj4Ix6nzRM91YDzXaWT8fAHYjyWf9BWaZ6OAhkHzkJH1Bw "Python 2 – Try It Online")
[Answer]
# Excel, 83 bytes
```
{=SUM(IF(MONTH(DATE(A1,1,0)+ROW(1:366))*DAY(DATE(A1,1,0)+ROW(1:366))=A1-2000,1,0))}
```
Input is in cell `A1` in the format `yyyy`. This is an array formula and is entered with `Ctrl`+`Shift`+`Enter` to get the curly brackets `{}`. It is fairly straightforward and without any cleverness.
When in an array formula, `DATE(A1,1,0)+ROW(1:366)` gives us an array of 366 date values. On non-leap years, this will include Jan 1 of the next year but that is not a problem because `1*1=1` and would only count as a false positive if the next year is `2001` but, since the required year range is `2001 - 2099`, it will never arise as an issue.
If you shorted that bit into simply `~`, the formula because much easier to follow:
```
{=SUM(IF(MONTH(~)*DAY(~)=A1-2000,1,0))}
```
---
I tried using `COUNTIF()` instead of `SUM(IF())` but Excel wouldn't even let me enter it as an array formula, much less give me a result. I *did* find a **Google Sheets** solution using `CountIf()` but the same method otherwise that turned out to be 91 bytes, mostly because it uses `ArrayFormula()` instead of simply `{ }`.
```
=CountIf(ArrayFormula(Month(Date(A1,1,0)+Row(1:366))*Day(Date(A1,1,0)+Row(1:366))),A1-2000)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 55 bytes
```
..
$*
(?<=^(1{1,12}))(?=(?(?<=^11$)\1{0,27}|\1{0,30})$)
```
[Try it online!](https://tio.run/##K0otycxL/P9fT49LRYtLw97GNk7DsNpQx9CoVlNTw95Wwx4sZmioohljWG2gY2ReWwNmGBvUaqpo/v9vZgAA "Retina 0.8.2 – Try It Online") Takes a two-digit year; add 1 byte to support 4-digit years. Explanation: The first stage simply converts to unary. The second stage starts by matching 1 to 12 characters before the match position, representing the month, and then attempts to look ahead for a whole number of repetitions of that month. However, the lookahead contains a conditional, which chooses between up to 27 or 30 further repetitions depending on the month. The count of match positions is then the desired result.
[Answer]
# [R](https://www.r-project.org/), ~~22~~ 122 bytes
```
x=scan();substr("122324243426133415153317223416132126011504033106131204241006003213011306002122042005101305111014012",x,x)
```
[Try it online!](https://tio.run/##FcpBDsJADEPRu3TVSl3YTjIgIQ5T2LPogDS3H9xVovd9zjme/X181u3Rf6/@PdeFUiiVkWqMSBYrgjdz0iKqgSwkzLBQ8J5AA5zDNa7fy6sARViK9E1Qyz72sU3e5x8 "R – Try It Online")
Decided to go with a lookup table approach. Input year needs to be 2 digits.
[Answer]
# C (gcc), ~~65~~ ~~60~~ 59 bytes
```
d(a,t,e){for(t=0,e=13;e-->1;)t+=a%e<1&a/e<(e-2?32:29);a=t;}
```
Port of user202729's Java [answer](https://codegolf.stackexchange.com/a/162150/79343). Try it online [here](https://tio.run/##FYtBCsMgEADP5hVLIMVFpdWcjLH9SC@im5JDbQleJOTtNj3NwDBRvWJsLfEgiyTcl8/Gi79J8np0pNRdOyzCh4FmfQlXmjkp8xjNZCy64Is72jusmSPsHfvPay5QwYN2J2YP1p4iBHaMfbczLrwf0gRDeuZeQpWQeEV03dF@). Thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) for golfing 1 byte.
[Answer]
# [J](http://jsoftware.com/), 29 bytes
```
1#.(,x*i."+29+3*2~:x=.i.13)=]
```
[Try it online!](https://tio.run/##PYs9D4IwGAZ3fsWTagRa@tqPQGyTTiZOTu5OhmJdXDvx1ytgwnDT3X0KozoieNTooOAXJOH6uN@KPlDTZZ6ICeOE5Wb2OVAibdvwLG01rdtIp/6CQWEwct6OZiv4OZE1S1iNr/cXMa9xD6OOkQlokci5Xcm/mXZTfg "J – Try It Online")
### How it works
```
1#.(,x*i."+29+3*2~:x=.i.13)=] Input: year (2-digit, 1..99)
x=.i.13 array of 0..12; assign to x
2~: 1 1 0 1 .. 1
3* 3 3 0 3 .. 3
29+ 32 32 29 32 .. 32
i."+ for each item of above, generate a row 0 .. n
,x* each row times 0 .. 12 and flatten
=] 1 for each item == input, 0 otherwise
1#. sum
```
Tried hard to get under 2 times Jelly solution :)
### Side note
If someone really wants to hardcode the 99-digit data, here's a bit of information:
Divide the 99-digit into chunks of 2 digits. Then the first digit is `<4` and the second `<8`, which means five bits can encode two numbers. Then the entire data can be encoded in 250 bits, or 32 bytes.
[Answer]
# [Python 3](https://docs.python.org/3/), 158 ~~162~~ ~~215~~ ~~241~~ bytes
Removed 4 Thanks to Stephen for golfing the conditionals.
Removed 53 thanks Stephen for pointing out the white space
Removed 26 thanks to the link provided by caird
I'm pretty new at this. Couldn't think of how to do this without having the days in a month be described.
```
r=range
def n(Y):
a,b,c=31,30,0
for x in r(12):
for y in r([a,(28if Y%4else 29),a,b,a,b,a,a,b,a,b,a][x]):
if(x+1)*(y+1)==int(str(Y)[2:]):c+=1
return c
```
[Try it online!](https://tio.run/##RU5LDsIgEN1zitkYQVgAdaFN8B5N00WtoCSGNhSTcnoEmujiTSZv5n2WGF6za1Lyyo/uqdFDG3C4Iy2Ckd3ZpBrBGs44AjN72MA68FjIcq9M3Jl@ZFherIHucNbvVYO8ElYMdvy2od@GqgVr8EYFOeGYp1LWBbwGn5N72eaXiSqBwOvw8Q6m9I8qLbHknOdanFevxWc1VHkkQOEItwwKhXCZIiR9AQ "Python 3 – Try It Online")
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 60 59 bytes
```
: f 0 13 1 do over i /mod swap 32 i 2 = 3 * + 0 d< - loop ;
```
[Try it online!](https://tio.run/##TY1LDsIwDET3nGLUJajFcdQNn8NUTcNHIFtJBccPTmDBxtZ43niipPXaX2JdpRwQQXAeDkEgryXhhv1TAvJ7Ung2yTjDY4udkeGEHg8RxdGyCiZ2NqjFxwoTk/GNlaYteTc9YOjM6P5vjgi1K5o7Ius0L/n7fU6/Fmy0fAA "Forth (gforth) – Try It Online")
This version takes advantage of the fact that there can't be more than 1 matching day per month, and that the year has to be divisible by the month for it to match.
### Explanation
Iterates over the months, checks if year is divisible by month, and if the quotient is < 31 (28 for Feb) Months after March can't match for days greater than 25, so we can just assume all months (other than Feb) have 31 days for the purpose of the puzzle.
### Code Explanation
```
: f \ start new word definition
0 \ set up counter
13 1 do \ start a counted loop from 1 to 12
over i /mod \ get the quotient and remainder of dividing year by month
swap \ default order is remainder-quotient, but we want to swap them
32 i 2= 3 * + \ we want to compare to 32 days unless month is Feb
0 d<= \ treat the 4 numbers on the stack as 2 double-length numbers
\ and compare [1]
- \ subtract result from counter (-1 is true in Forth)
loop \ end loop
; \ end word definition
```
[1] - Forth has the concept of double length numbers, which are stored on the stack as two single-length numbers (of the form x y, where the value of the double = `y * 2^(l) + x`where l is the size in bits of a single in the forth implementation you're working with).
In this case, I compared the quotient and remainder to 32 (or 29) 0. If the remainder was greater than 0 (year not divisble by month), the first double would be automatically bigger than 32 (or 29) 0 and the result would be false. If the remainder is 0, then it resolves to effectively a regular check of quotient <= 32 (or 29)
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 61 bytes
```
: f 0 13 1 do i 2 = 3 * 32 + 1 do over i j * = - loop loop ;
```
[Try it online!](https://tio.run/##NYtLCoAwEEP3nuKtFaW1O6WnUesHYaQUr19Hqosk8JIEiWlr1/BGzgMBg3VYZmGnx@OocT1NYXIvUYtDoaflFLmKjeg7YY35z50qqE/xW1QpPw "Forth (gforth) – Try It Online")
Saved some bytes by realizing that only February matters in terms of having the correct number of days in the month
# Explanation
Forth (at least gforth) comparisons return -1 for true and 0 for false
```
0 \ place 0 on top of the stack to use as a counter
13 1 do \ begin the outer loop from 1 to 12
i 2 = 3 * \ if i is 2 place -3 on top of the stack, otherwise 0
32 + 1 do \ begin the inner loop from 1 to 31 (or 28)
over \ copy the year from stack position 2 and place it on top of the stack
i j * = - \ multiply month and day compare to year, subtract result from counter
loop \ end the inner loop
loop \ end the outer loop
```
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), ~~79~~ ~~72~~ 70 bytes
```
y->{int a=0,m=13;for(;m-->1;)a+=y%m<1&&y/m<(m==2?29:32)?1:0;return a;}
```
[Try it online!](https://tio.run/##bU47b4MwEN7zK06RiKA8GsgExok6dqg6RJ2qDlcekSk2yD4iWRG/nZpUndrh7nT33ffo8IpxV38tQo6DJujcnkwk@uSBbf7c2klVJAb1L2hINyhXqOrRGHhBoeC2ARinz15UYAjJjesgapAO88@khbq8fwDqiwnurwDPit4Uavs6Nhpp0NACX2x8vAlFgHwfSZ4eWDton8k4PqYswJBbT5bpbmcfZelLzrNTlheHLDilxZ7phiatANm8sLvDyl3FLE@ZLXmeMxuGv/YAZ2uokckwUTK6fNT6Wy@rC3DNU9sIbARtguPY2yfjwvo2CH50581a8/IN "Java (JDK 10) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 108 bytes
```
a=>'0122324243426133415153317223416132126011504033106131204241006003213011306002122042005101305111014012'[a]
```
```
f=a=>'0122324243426133415153317223416132126011504033106131204241006003213011306002122042005101305111014012'[a]
o.innerText=[...Array(99)].map((_,x)=>(2001+x++)+` = `+f(x)).join`\n`
```
```
pre{column-count:5;width:480px;}
```
```
<pre id=o></pre>
```
[Answer]
# [Perl 5](https://www.perl.org/), 68 bytes
```
//;map$\+=$'%++$m==0&&$'/$m<$_,32,29,32,31,32,31,32,32,31,32,31,32}{
```
[Try it online!](https://tio.run/##K0gtyjH9/19f3zo3sUAlRttWRV1VW1sl19bWQE1NRV1fJddGJV7H2EjHyBJEGhsikSjc2ur//w0t/uUXlGTm5xX/1/U11TMwNPivWwAA "Perl 5 – Try It Online")
[Answer]
# Python 3, 132 bytes
This is really quite long of a program but I thought it might be of interest.
All the values are between 0-7 so I encode each number with 3 bits in a long binary string. I tried pasting a raw binary string into my python program but I couldn't get it to work, so I settled on base64 in the file.
I used the following string as a lookup table (ending 7 used for padding):
`01223242434261334151533172234161321260115040331061312042410060032130113060021220420051013051110140127`
The program takes this string and decodes it as a number, then uses bit shifting to extract the result.
```
import base64
lambda n:int.from_bytes(base64.b64decode(b'pNRRxYtw01s9Jw4tFYE0QNkYsoRQgYBosEsYBFIRAUgsUkgwFQM='),'big')>>(6306-3*n)&7
```
# 66 bytes + 37 byte file = 103 bytes
This reads a binary file called `e` and avoids using base64.
```
lambda n:int.from_bytes(open('e','rb').read(),'big')>>(6306-3*n)&7
```
Here is a hexdump of the read file (without padding):
```
00000000 a4 d4 51 c5 8b 70 d3 5b 3d 27 0e 2d 15 81 34 40 |..Q..p.[='.-..4@|
00000010 d9 18 b2 84 50 81 80 68 b0 4b 18 04 52 11 01 48 |....P..h.K..R..H|
00000020 2c 52 48 30 0a |,RH0.|
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~61~~ 51 bytes
```
f y=sum[1|i<-[96..508],mod(div i 32)13*mod i 32==y]
```
[Try it online!](https://tio.run/##NZPLasMwEEX3/YpZdOEUJ1hvCer@SJqFIQk1ddISp4VA/921zZyVrqTR1eFq9NGNn6dhmKazPNrx57I3f/3rdl/ibheafKgvX8fq2P9KL85ujHuZ56tu28dhepy62yit7CtTi9nUUtla7DI6HX0tbhmDzmMtfhmTzrPOi9aZRheM0QozW8ZVOL3DYGoCAluTqJmNwyoKZI2uWKOnrEXgbGfntAp4bUQkikG2OLtGCR0pOJwdOTjPFs4ucmp2blaRqcHZw@yN1nirt3vHCml40vCR4zj7rHd5nEPDw8AceLqAc/B6V4A5kHMg55ApLioiaUSYo0U4vTR62iGoT4xswRxJI8KcYE44J3ojwZw8AuZEGomeSxkBc6brMl2XYc44Z69vkWHOkS3SyFkJM86FFyzkXCyCriswF5wLORfSKKRRykJ4eHq6dP11/nrft/56l2fphkGq9377dpbqPN6l30jbyng9Lmr9p9M/ "Haskell – Try It Online")
Inspired by [xnor's Python 2 answer](https://codegolf.stackexchange.com/a/162210/77598) and Laikoni.
[Answer]
# Oracle SQL, 115 bytes
```
select count(decode(sign(decode(l,2,29,32)-y/l),1,1))from t,
xmltable('1to 12'columns l int path'.')where mod(y,l)=0
```
We may note that it does not really matter how many days in April (and later months), since 100/4 < 28. Also it's not necessary to check whether year is leap or not.
We just have to specify that there are 28 days in February (not 29 because that validation will be executed only for 2058 which is not leap) otherwise it may be just 31 for any month.
**Other approaches**
# Oracle SQL (12c Release 2 and later), 151 bytes
```
select count(to_date(y/l||'-'||l||'-1' default '' on conversion error,'dd-mm-y'))from t,
(select level l from dual connect by level<=12)where mod(y,l)=0
```
# Oracle SQL (12c Release 2 and later), 137 bytes
```
select sum(validate_conversion(y/l||'-'||l||'-1'as date,'dd-mm-y'))from t,
(select level l from dual connect by level<=12)where mod(y,l)=0
```
*Both solution could have been 8 bytes shorter if we replace `(select level l from dual connect by level<=12)` with `xmltable('1to 12'columns l int path'.')` but Oracle throws an exception because of the bug (tested on versions 12.2.0.1.0, 18.3.0.0.0).*
```
SQL> select count(to_date(y/l||'-'||l||'-1' default '' on conversion error,'dd-mm-y'))from t,
2 xmltable('1to 12'columns l int path'.')where mod(y,l)=0
3 /
select count(to_date(y/l||'-'||l||'-1' default '' on conversion error,'dd-mm-y'))from t,
*
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected DATE got DATE
SQL> select sum(validate_conversion(y/l||'-'||l||'-1'as date,'dd-mm-y'))from t,
2 xmltable('1to 12'columns l int path'.')where mod(y,l)=0
3 /
select sum(validate_conversion(y/l||'-'||l||'-1'as date,'dd-mm-y'))from t,
*
ERROR at line 1:
ORA-43909: invalid input data type
```
The only case in both solution when year does matter is 2058 which is non-leap so literal '-1' was used to specify non-leap year.
# Oracle SQL, 128 bytes
```
select count(d)from t,(select date'1-1-1'+level-1 d from dual connect by level<365)
where to_char(d(+),'mm')*to_char(d(+),'dd')=y
```
# Oracle SQL, 126 bytes
```
select substr('122324243426133415153317223416132126011504033106131204241006003213011306002122042005101305111014012',y,1)from t
```
**Update**
# Oracle SQL, 110 bytes
```
select-sum(least(sign(y/l-decode(l,2,29,32)),0))from t,
xmltable('1to 12'columns l int path'.')where mod(y,l)=0
```
# Oracle SQL, 108 bytes
```
select sum(decode(sign(decode(l,2,29,32)-y/l)*mod(y+1,l),1,1))from t,
xmltable('1to 12'columns l int path'.')
```
# Spark SQL, 137 bytes
```
select count(cast(regexp_replace(concat_ws('-','2001',l,y/l),'.0$','')as date))
from(select explode(array(1,2,3,4,5,6,7,8,9,10,11,12))l),t
```
# Spark 2.3+ SQL, 126 bytes
(`replace` function becomes available)
```
select count(cast(replace(concat_ws('-','2001',l,y/l),'.0')as date))
from(select explode(array(1,2,3,4,5,6,7,8,9,10,11,12))l),t
```
[Answer]
# [PHP](https://php.net/), 73 bytes
Using pipe input and `php -nR`:
```
for(;++$m<13;$d=1)while($d<25+($m-2?$m>4?:7:4))$c+=$argn==$m*$d++;echo$c;
```
[Try it online!](https://tio.run/##K8go@P8/Lb9Iw1pbWyXXxtDYWiXF1lCzPCMzJ1VDJcXGyFRbQyVX18heJdfOxN7K3MpEU1MlWdtWJbEoPc/WViVXSyVFW9s6NTkjXyXZ@v9/Q4t/@QUlmfl5xf918/7rBilQzWwA "PHP – Try It Online")
# [PHP](https://php.net/), 76 bytes
Using command line arg input `php dm.php 18`:
```
for(;++$m<13;$d=1)while($d<25+($m-2?$m>4?:7:4))$c+=$argv[1]==$m*$d++;echo$c;
```
[Try it online!](https://tio.run/##BcFRCsIwDADQq/iRj9YgrHOiLK09iIhIW9eBtSEMPX58jyurj1x5V0S6PKRwl239LGawpK8uhhCheXckyMHZX13fxUD24wkNtMMYoV2nOJ/nyVpIGOApy/fm7iFA20NGpJJqh0Sq6i5/ "PHP – Try It Online")
Iterative approach. Since the only leap year to look at is 2 \* 29 = 58, and 2058 is not a leap year there's no need to consider leap year in the Feb days. And since wraparound is not a concern -- from April on, any day greater than 25 will exceed 100 we just say the rest of the months only have 25 days.
Input is 2 digit year via command line (-10 bytes as program, thx to suggestion from @Titus).
*OR:*
# [PHP](https://php.net/), 101 bytes
```
$y=$argv[1];for($d=strtotime("$y-1");date(Y,$d)==$y;$d+=86400)eval(date("$\x+=j*n=='y';",$d));echo$x;
```
[Try it online!](https://tio.run/##HcrhCsIgEADgVxlyMG0FGhGD6@g5oiJG2lzUlEuGPr1Rv78v@lgPx@hj45gD39jFwGmaR6kVNpBJY4VCMPC4nM0VH4ElWPokTiFNbycFlI0RCu2QnDytwSoiKAi2o36/01q5ZXjJvwq45I6eq5moLS2KX1bo7j5AxlrrVpv@Cw "PHP – Try It Online")
Still iterative but using PHP's timestamp functions. Accepts year as four digit number. Thx to @Titus for suggestion of using `strtotime()` instead of `mktime()`.
[Answer]
# PHP, ~~74~~ 70 bytes
```
while(++$m<13)for($d=$m<5?$m-2?31:28:25;$d;)$n+=$d--*$m==$argn;echo$n;
```
accepts two-digit years only.
I adopted [gwaugh´s considerations](https://codegolf.stackexchange.com/a/179446/55735) and golfed them; my 1st approach was longer than his (92 bytes):
```
for($y=$argn%100;++$m<13;)for($d=$m-2?30+($m+$m/8)%2:29-($y%4>0);$d;)$n+=$d--*$m==$y;echo$n;
```
`%100` allows to use 4-digit years.
---
Run as pipe with `-nR` or [try them online](http://sandbox.onlinephpfunctions.com/code/ace1e53f44880664f6868ec2aa1f4af209245fb5).
] |
[Question]
[
I'm sure you know about the $9.99 price scheme, instead of using $10. Well, in your new job as a sys admin at a large retail store, they want prices to adhere to a similar scheme:
* All prices are in whole dollars, no cents.
* All prices should end with 5 or 9, rounding to the closest but up if the last digit is right between 5 and 9. (Applies to last digit 2 and 7)
* Lowest input is $1, and the lowest outputted price should be $5.
Your input is a list of integers:
```
12
8
41
27
144
99
3
```
And the output should a list of the new prices. In the above case:
```
15
9
39
29
145
99
5
```
[Answer]
# Brainfuck, 4428 bytes (invalid)
Once I knew the algorithm worked, I lost interest and didn't finish the input handler. That's why this solution technically solves the problem, but is very hard to use. When you start the program in an **interactive** interpreter (faster is better), you can enter your "number". It has to be entered in Base256 if your interpreter doesn't support number conversion (mine does). The maximum price you can enter is therefore 255.
It then performs a looping modulo if the number is greater than 9 to split off all digits except the last one. The division results are saved, while the last digit is rounded to 5 or 9. Then they are added and printed. Then the program cleans all used registers (probably overkill) and asks for the next number.
It handles all special cases (`$1`, `$20/$21 -> $19` etc.). Watch it run for the number `4` here (about 3 minutes, video shortened):
[](https://i.stack.imgur.com/odN90.gif)
## Code
```
>+<+[>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<[>[-]+<-]>
[<+>>>>>>>>>>>[-],>>[-]<[-]<[>+<<<<<<<<<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>>>
>>>>[-]>[<+<<<<<<<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>>>>>>[-]+++++++++>[<<<<+
>>>>-]<[<<<<<<+>+<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]
+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]>>[>>>>-<<<<[-]]<<<[-]<->>>>>>>>[<<<<<<<<->>>>
>>>>-]<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>>>>>>>[>>>>>+<<<<<<<<<<<<<<<->>>>>>>>>>[-]]<<<<<<<<<
-]>>>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<
<[>[-]+<-]>[<+>>>>>>>>>>>>[-]<[>+<<<<<<<<<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>
>>>>>[-]++++++++++>>>[<<<<<<<+>>>>>>>-]<<<<<<<[>>>>[<<<<<+<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<
<<<<<-]>>[>-[<<+<+>>>-]<<<[>>>+<<<-]+>[<->[-]]<[>>-[>>>>>>>>-<<<<<<<<[-]]+<<[-]]>>-]>>>>
>>>>+<<<<<<<]>>>>>[-]>>[<<+<<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>>>
>[-]++++++++++>[<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>[>+<<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<
<<<-]>-]>>>>>>>>>[-]<<[>>+<<-][-]>>>[<<<+<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<
<<<<<<<<<<-]>>>>>>>[-]>>>[<<<+<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>
>>>[>+<<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>>>>>[-]<<<[>>>+<<<-][-]>[<+<<<<<
<<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>>>>>>[-]>>>[<<<+<<<<<<<+>>>>>>>>>>-]<<<<
<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>>>>[>-<<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>
>>>>[-]<[>+<-]<<<<<<<<<-]>>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>-]
<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>>[-]>>[<<+<<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>
>>>>>>+<<<<<<<<<<-]>>>>>>>[-]>[<<<<+>>>>-]<[<<<<<<+>+<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<
-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]>>[>>>>-<<
<<[-]]<<<[-]<->>>>>>>>[<<<<<<<<->>>>>>>>-]<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>>>>>>>[>>>>>>>>>
>>>+<<<<<<<<<<<<<<<<<<<<<<->>>>>>>>>>[-]]<<<<<<<<<-]>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<+>>>>>
>>>>>>>>>>-]<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>>[-]>[<+<<<<<<<<+>>>>>>>>>-]<<<<<<<<<[>
>>>>>>>>+<<<<<<<<<-]>>>>>>>[-]++++>[<<<<+>>>>-]<[<<<<<<+>+<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<
<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]>>[>>
>>-<<<<[-]]<<<[-]<->>>>>>>>[<<<<<<<<->>>>>>>>-]<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>>>>>>>[>>>>
>>+<<<<<<<<<<<<<<<<->>>>>>>>>>[-]]<<<<<<<<<-]<[>[-]+<-]>[<+>>>>>>>>>>>[-]+++++++++>>>>>>
>>+<<<<<<<<<<<<<<<<<<<->-]>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>-]<<<<<<<<<<<
<<<<<[>[-]+<-]>[<+>>>>>>>>>>[-]>[<+<<<<<<<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>
>>>>>[-]++>[<<<<+>>>>-]<[<<<<<<+>+<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>[>>[<+<<<+>>>>-
]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]<[>>>>>>>-<<<<<<<[-]]>>>[-]>>
>[-]>>>>[<<<<+<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>>>>>>>>>>>[-]+
++++++++<<<<<[<<<+>>>-]>>>>>[<<<<<<<<<<<+>+<<+>>>>>>>>>>>>-]<<<<<<<<<<<<[>>>>>>>>>>>>+<<
<<<<<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]
>>[>>>-<<<[-]]<<<[-]>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<<[[-]>>>>>>>[<<<<<<<+>+>>>>>>-]<<<
<<<[>>>>>>+<<<<<<-]<[>>>>>>>>-<<<<<<<<[-]]]->>>>>>>>[<<<<<<<<->>>>>>>>-]<<<<<<<<[>>>>>>>
>+<<<<<<<<-]>>>>>>>>[>>>>>>>>+<<<<<<<<<<<<<<<<<<->>>>>>>>>>[-]]<<<<<<<<<-]<[>[-]+<-]>[<+
>>>>>>>>>>[-]>>>[<<<+<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>>>>>>>
->>>[-]<<<[>>>+<<<-]>[-]>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<->-]>>>>>>>>>>>>>>>>>[<<<<<<
<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>>>[-]+++++<<<<<
<<<<<-]>>>>>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>>>-]<<<<[<<<<
<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>>[-]>>>[<<
<+<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>>>>>>[-]>>[<<+<<<<<<<+>>>
>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>>>>>>[>+<<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<
<<-]>>>>>>>>>>>[-]<<<[>>>+<<<-][-]>>>[<<<+<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+
<<<<<<<<<<<-]>[-]>[-]>[-]>[-]>>>>[<<<<<+[>+<<<<+>>>-]<<<[>>>+<<<-]+>>>>----------[<<<<->
>>>[-]]<<<<[>>+>[-]<<<-]>>[>>+<<<<+>>-]<<[>>+<<-]+>>>>----------[<<<<->>>>[-]]<<<<[>+>[-
]<<-]>>>>>>>>-]<<<<<<<[<++++++++[>++++++>++++++<<-]>.>.[-]<[-]]>[<<++++++++[>>++++++<<-]
>>.[-]]<<++++++++[>>>++++++<<<-]>>>.[-]<<<++++++++++.[-]>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<
<->-]<[>[-]+<-]>[<+<->>-]<<]
```
[Answer]
# CJam, ~~19~~ 17 bytes
```
q~{2-Ab)4>59s=N}/
```
[Test it here.](http://cjam.aditsu.net/#code=q~%7B2-Ab)4%3E59s%3DN%7D%2F&input=%5B12%208%2041%2027%20144%2099%201%5D)
Takes input as a CJam-style list and returns output newline separated.
# Explanation
```
qN/{ e# Run this block for each line of the input...
~ e# Evaluate the current line to get the integer.
2- e# Subtract 2 to get all but the last digit right.
Ab) e# Convert to base 10 (discarding a potential minus sign) and split off
e# the last digit.
4> e# Test if it's greater than 4.
59s= e# Select the correct digit from the string "59" based on this result.
N e# Push a line feed.
}/
```
[Answer]
## Python 2, 47
```
lambda l:[max(5,(n+3)/5*5-(n-2)/5%2)for n in l]
```
If we look at the sequence of rounded values, we see that they come in blocks of 5.
```
... 25, 29, 29, 29, 29, 29, 35, 35, 35, 35, 35, 39, ...
```
We find what number block we're in with `(n+3)/5` (call this value `J`). Then, we get the right multiple of `5` with `J*5`, and adjust things like `30` down to `29` by subtracting `1` whenever `J` is even.
To special-case `1` give `5` rather than `-1`, we pass the result to `max(5,_)`.
[Answer]
# Retina, 32 bytes
Accepts input in a comma separated list. There must be a trailing comma. Outputs in the same format.
```
T`d`aa555559`.,
T+`da`ad`\da
a
5
```
**Explanation:**
```
T` #Transliteration mode.
d`aa555559` #Map the digits 0-9 to aa55555999
., #Map only the trailing digits.
T+` #Do until input does not change.
da`ad` #Map a to 9, 0 to a, and 1-9 to 0-8
\da #Only do this to each a and the character before each a.
a #Match all leftover a's. This only happens when the input contains the integer 1.
5 #Replace them with 5.
```
[Answer]
## Python 3, 74 82 bytes
```
a=eval(input())
for i in a:print(round(i,-1)+[5,-1][max(4,i-2)%10>4])
```
I struggled for brevity on values less than 11 and the requirement for 1 to evaluate to 5.
[Answer]
# R, ~~51~~ ~~49~~ ~~47~~ 43 bytes
```
(f=((n=scan()-2)%/%5+1+(n<0))*5)-(f%%10==0)
```
There should be room to improve this, but I thinking a different strategy might be better. Takes a vector of integers from scan and outputs a vector of integers. Essentially this uses integer division to round the number down, adds 1 and multiples it by five. Anything divisible by 10 has 1 taken away. If n = 1 then it increments the integer division by 1.
Test run
```
> (f=((n=scan()-2)%/%5+1+(n<0))*5)-(f%%10==0)
1: 1
2: 12
3: 8
4: 41
5: 27
6: 144
7: 99
8: 3
9:
Read 8 items
[1] 5 15 9 39 29 145 99 5
>
```
[Answer]
# Pyth, ~~21~~ ~~18~~ ~~29~~ 28 bytes
Thanks to @Jakube for cutting 3 bytes!
```
KeQJ-QKI<K2tJ.q;I<K6+J5;E+J9
```
[Try it here.](https://pyth.herokuapp.com/?code=KeQJ-QKI%3CK2tJ.q%3BI%3CK6%2BJ5%3BE%2BJ9&test_suite=1&test_suite_input=12%0A8%0A41%0A27%0A144%0A99%0A3&debug=0)
**EDIT:** Apparently it was invalid. I fixed it up at the cost of 11 bytes; I'll try to golf it more.
[Answer]
# Pyth, 21 bytes
```
m?tdtt+d@jC"²a<"6ed5Q
```
Sadly I have to spend 4 bytes to correctly handle $1.
[Answer]
# Pyth, 18 bytes
```
m-|*K5hJ/-d2K6%J2Q
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=m-%7C%2AK5hJ/-d2K6%25J2Q&input=%5B1%2C12%2C8%2C41%2C27%2C144%2C99%2C3%5D) or [Test Suite](http://pyth.herokuapp.com/?code=m-%7C%2AK5hJ/-d2K6%25J2Q&input=%5B1%2C12%2C8%2C41%2C27%2C144%2C99%2C3%5D)
This answer is based on @xor's Python/Pyth solution. The main difference is, that I handle the special case `1` differently. The actual result for `1` would be `0 - 1 = -1`. Using Python's `or` I can replace the `0` with a `6`, resulting in `6 - 1 = 5`. This saves the pain of taking the maximum of `5` and the result.
### Explanation:
```
m-|*K5hJ/-d2K6%J2Q
m Q map each number d of the input list Q to:
K5 K = 5
J/-d2K J = (d - 2) / K
*K hJ K * (J + 1)
| or
6 6 # if K*(J+1)==0
- %J2 minus (J mod 2)
```
[Answer]
# [Hassium](http://HassiumLang.com), 133 Bytes
```
func main(){i=[12,8,41,27,144,99,3];foreach(e in i){f=e%10;if(!(e/10==0))print(e/10);if(f<5)r=5;else if(f>5)r=9;elser=f;println(r);}}
```
Run and see the expanded online:
<http://hassiumlang.com/Hassium/index.php?code=4f1c14f4d699b11da7a6392a74b720c4>
[Answer]
# TI-BASIC, 19 bytes
```
int(Ans/5+.6
max(5,5Ans-not(fPart(Ans/2
```
Uses xnor's algorithm. TI-BASIC gets vectorization and multiplication for free, but we spend a few more bytes because it doesn't have modulo.
[Answer]
# Ruby, ~~55~~ 50 + 1 bytes
Run it with the `n` flag, like so: `ruby -n prices.rb`. Enter each price on a separate line.
```
x=$_.to_i
p x<7?5:(x-2).round(-1)+(~/[2-6]$/?5:-1)
```
[Answer]
# JavaScript, 50
```
l=>l.map(n=>Math.max(5,((n+3)/5|0)*5-((n-2)/5&1)))
```
I use an `&1` to save bytes instead of `|0` and mod 2
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 33 bytes
```
/.1$|[60]$/?$_--:$_++until/[59]$/
```
[Try it online!](https://tio.run/##K0gtyjH9/19fz1ClJtrMIFZF314lXlfXSiVeW7s0ryQzRz/a1BIo@v@/oRGXBZeJIZeROZehiQmXpSWXMZfRv/yCksz8vOL/ugU5AA "Perl 5 – Try It Online")
[Answer]
# Haskell, 114 bytes
```
g n
|n>6=9-n
|n>1=5-n
|1>0=(-n-1)
f n=show$(read n)+(g$read$(:[])$last n)
main=interact(unlines.(map f).lines)
```
## Explanation:
The function `g` returns `9-n` if `n>6` or else `5-n` if `n>1` or else `-n-1`. `g` is given the last digit and returns what should be added to the input number. `f` uses `g` to get the solution (plus lots of string manipulation). `main` outputs the result of `f` for each line of input.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), `ja`, ~~13~~ 12 bytes
```
ƛ⇩ȧṫ4>59$iJṅ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=ja&code=%C6%9B%E2%87%A9%C8%A7%E1%B9%AB4%3E59%24iJ%E1%B9%85&inputs=12%0A8%0A41%0A27%0A144%0A99%0A3&header=&footer=)
I simply ported the CJam answer.
## Explained
```
ƛ⇩ȧṫ4>59$iJṅ
ƛ # Over every number in the input,
⇩ȧ # abs(a - 2)
ṫ4> # ↑[:-1], ↑[-1] > 4
59$i # indexed into 59
Jṅ # merged and joined on ""
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç«δv▀▼ÖP▄¶⌠"
```
[Run and debug it](https://staxlang.xyz/#p=80aeeb76df1f9950dc14f422&i=12%0A8%0A41%0A27%0A144%0A99%0A3)
Yet another port of the CJam answer.
-1 more byte if a list of integers is taken as input.
] |
[Question]
[
In this challenge, you implement an interpreter for a simple stack-based programming language. Your language must provide the following instructions:
* push a positive number
* pop two numbers and push their sum
* pop two numbers and push their difference (second number - first number)
* pop a number and push it twice (dup)
* pop two numbers and push them so that they are in opposite order (swap)
* pop a number and discard it (drop)
You may assume instructions will never be called with less arguments on the stack than are needed.
The actual instructions can be chosen for each implementation, please specify how each instruction is called in the solution. Your program/function must output/return the stack after all instructions are performed sequentially. Output the stack in whatever format you prefer. The stack must be empty at the start of your program.
## Examples
For these examples, the stack is represented bottom-to-top.
```
1 2 + -> [3]
1 drop -> []
10 2 - 3 + -> [11]
9 dup - -> [0]
1 2 3 -> [1 2 3]
1 dup 2 + -> [1 3]
3 2 5 swap -> [3 5 2]
```
[Answer]
## Regex (PCRE 2), 104 bytes (60 + 46)
* +2 bytes to properly remove excess spaces after `~` commands
Search:
```
((1+) (1+) a)|((1+) \5(1+) -)|((1+) :)|((1+) (1+) s)|(1+ ~ ?)
```
Replacement:
```
${1:+$2$3:${4:+$6:${7:+$8 $8:${9:+$11 $10:}}}}
```
Input and output in unary.
Each regex substitution resolves one operation, so you need to repeatedly use the regex to replace until the result doesn't change to get a final output.
[Try it online!](https://regex101.com/r/7CHzB8/3)
No language seems to support the PCRE 2 replacement syntax to allow writing an easy wrapper
* `11111` push a number in unary
* `a` add 2 numbers
* `-` subtract the first number from the second
* `:` duplicate
* `s` swap
* `~` pop
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 103 bytes
-2bytes by l4m2
```
p=>p.split` `.reduce(([a=[],b=[],...S],i)=>[{A:a+b,S:b-a,X:[b,a],P:b}[i]??[1/i?+i:a,a,b],S].flat(2),[])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGiNNulpSVpuhY30wts7Qr0igtyMksSFBL0ilJTSpNTNTSiE22jY3WSQISenl5wrE6mpq1ddLWjVaJ2kk6wVZJuok6EVXSSTmKsToBVUm10Zqy9fbShfqa9dqZVok6iTlKsTnCsXlpOYomGkaZOdKwm1Lp1yfl5xfk5qXo5-ekaaRrqhgpGCo7qmppcGOIB2EQNgMqDFYyxarFUcFEIxmqUkYIxVnEXHJYbA8VNFSKAMhBXL1gAoQE)
Operators:
* `A`: Add
* `S`: Sub
* `D`: Dupe
* `X`: eXchange
* `P`: Pop
* `\d+`: push Number
One space between each tokens.
Output is the array where first value is stack top, and last value is stack bottom.
[Answer]
# [TypeScript](https://www.typescriptlang.org/)'s type system, 206 bytes
```
//@ts-ignore
type F<C,S=[0,0]>=[S,C]extends[[infer A,infer B,...infer V],[infer I,...infer R]]?F<R,I extends`${any}`?[I,...S]:[...[[B],[A,A,B],[B,A],[`${A}${B}`],B extends`${A}${infer Z}`?[Z]:0][I],...V]>:S
```
[Try it at the TS playground](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAMQB4BhAGgGUBeAbQAZLGBdAPgesvNfQA9w6RABNI9erEQAzdKkIBBSlNnyAQpQB02lXMIA1VpUky9ASS07T8gEqtWAfjI3KZwgKGjIAAwAkAbwBDRBwAX28HegttTWpWAC56GIk1I3olJVTjDQU0v38FUIC1cKM1d0FhMXzCgN15AC1wyIaEtiijGMN2eOpMTGAAKkJCRkJaQjxkPEwRkYBGccIRAFcZucIAJiXIAHdA9bmAZiXAkRFZuYAWHZWAIw3CQeB+3AJCfiWyegAieZ-KIQ-v9AUdAcD5iCgZCYbDIQCtoCrhwBsA5gA9ByYIA)
This is a generic type `F<C>` which takes input as a tuple of items which are either unary numbers as strings of 1s, or numbers 0 to 4 for the 5 commands:
| num | function |
| --- | --- |
| 0 | Pop |
| 1 | Duplicate |
| 2 | Swap |
| 3 | Add |
| 4 | Subtract |
This solution works identically to the one below, only it skips the step of splitting on spaces, and indexes into an array instead of a dictionary, so it ends up quite a bit shorter.
# [TypeScript](https://www.typescriptlang.org/)’s type system, ~~324~~ ~~309~~ ~~251~~ 220 bytes
```
//@ts-ignore
type F<C,S=[0,0]>=[S,C]extends[[infer A,infer B,...infer V],`${infer I} ${infer R}`]?F<R,I extends`1${any}`?[I,...S]:[...{p:[B],d:[A,A,B],x:[B,A],a:[`${A}${B}`],s:B extends`${A}${infer Z}`?[Z]:0}[I],...V]>:S
```
[Try it at the TS playground](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAMQB4BhAGgGUBeAbQAZLGBdAPgesvNfQA9w6RABNI9erEQAzdKkIBBSlNnyAQpQB02lXMIA1VpQAGAEgDeu+QEkAvoQtXCAJVvHWAfjLPK1wgKFRSGMARgsAQ0QcNw96ay1talYALnptTXM8VLUjEVSlJRzKfmzKBSNw1LNzBVsLNTcjSGS1f0FhMWraxxk9AC0Y+j6Uxls4o3TDdmTqTEwQQkhwcIBjAGtFgAtkAHdEQnBkPGhD6AAjZHBDgFtNQkZIQnDwA82iC6vka8IRZEIUcCbKTwTRzXAEQgAL0ItBIpAARCFCCEkeFkSikRisVjCPxFoR4ex5sBCIQAHoeOZAA)
This is a generic type `F<C>` which takes input as a string type of space separated commands or unary numbers, space terminated. Output in unary, first element is top of stack.
Commands:
| name | function |
| --- | --- |
| `a` | Add |
| `s` | Subtract |
| `x` | Swap |
| `p` | Pop |
| `d` | Duplicate |
I was surprised by how short this was when it was 100 bytes longer than it is now, so now I'm *really* surprised.
Explanation:
```
type F<
// C is the input string type
C,
// S is the stack, starts with two useless elements
S=[0,0],
>=[S,C]extends[
// get the top 2, A and B, and the rest V, of the stack
[infer A,infer B,...infer V],
// get the first word I and the rest R of C
`${infer I} ${infer R}`
]
// recurse, setting C to R, and setting S to...
?F<R,
// does I start with a 1?
I extends`1${any}`
// if so, prepend it to S
?[I,...S]
// otherwise, it's a command; index into this object
// to replace the top 2 of the stack:
:[...{
// pop- just the second
p:[B],
// dup- first twice, then second
d:[A,A,B],
// swap: second, then first
x:[B,A],
// add: concatenate the first and second
a:[`${A}${B}`],
// subtract: the second with the first taken away
s:B extends`${A}${infer Z}`?[Z]:0
// then append V
}[I],...V]
>
// if C is empty (no more commands are left), return S
:S
```
[Answer]
# Trivial Eval/Exec Answers in Stack Languages
For languages where the command set required is already a thing, and evaluating a string is the shortest solution.
Don't add answers in stack languages that aren't purely "exec".
## [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2) `W`, 1 byte
```
Ė
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJXIiwiIiwixJYiLCIiLCIiXQ==)
Uses the command set `+-:$_` and `[0-9]+` for pushing numbers.
## [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.V)
```
[Try it online.](https://tio.run/##yy9OTMpM/f9fL0zz/39DBSMFbQVDhRgFQwMgU1fBGMi1VHABskBSxkDSBazEGEiaKhQDAA)
Uses the command set `+-Ds\` for `add`; `subtract`; `duplicate`; `swap`; `drop` respectively. `.V` executes the (implicit) input as 05AB1E code; and `)` wraps the entire stack into a list (which is output implicitly at the end).
## [sclin](https://github.com/molarmanful/sclin), 1 bytes
```
#
```
[Try it on scline!](https://scline.fly.dev/#H4sIAENId2UCA1MyVjBSMFUoLk8sUNIDAFWXUb8NAAAA#H4sIAENId2UCA1MGAP.eZXABAAAA#) Uses `dup`, `pop`, `swap`, `+`, `-`.
## [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 2 characters
```
?f
```
Where `?` reads a line from stdin and executed it as `dc` code and `f` dumps the stack.
In the simple stack language use `d` for dup, `r` for swap and `ss` for drop.
[Try it online!](https://tio.run/##S0n@/98@7f9/QwUjBW0FBYUUIDZWMFHQBdKmCkVA0kzBXMFCobgYhCwB "dc – Try It Online")
# [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 1 byte
```
C
```
[Try it online!](https://tio.run/##Kyooyk/P@//f@f///8YKRgqmCjEA "RProgN – Try It Online")
Requires space between commands, `[]\` are Drop, Dup, and Swap respectively.
[Answer]
# [flex](https://www.gnu.org/software/flex/), 179 bytes
```
%{
s[9];i;t;
%}
%%
a s[--i-1]+=s[i];
s s[--i-1]-=s[i];
d s[i++]=s[i-1];
x s[i-2]^=s[i-1]^(s[i-1]=s[i-2]);
p --i;
[0-9]+ s[i++]=atoi(yytext);
\n for(t=i;t--;)printf("%d ",s[t]);
%%
```
[Try it online!](https://tio.run/##PZDBboMwDIbP81NYVdOCWFhhJxTYbbvuAVgqZRAgEiKIRCpo2rMzM7qd/PuT/eu3P5Xr1qbXM@b56/vbyr7AlZkURngB7BsYA4Wu5NzwREaFK40U4P4Jv5OaiIkiubWEBcwb4Km83sk12Gux41DAiGQhoLzwTEZ/68pbEyyL17OnkY8BGzsFvqA0nItwnMzgm@DAajw8utJvNoytlBugrSrkN6RL4mWJSVt0vRpa5H3TA9w602uctKpxnGwrsLbwoKvOIh/wuCE88xc84@mEv/gYxE@7QZ7n@0QItR30mmCKChIcIbmQdPhMbYb0AkhJ0@XwAw "Bash – Try It Online")
Uses:
* `[0-9]+` push a number
* `a` sum
* `s` difference
* `d` dup
* `x` swap
* `p` drop
[Answer]
# Brain-flak, 294 bytes
```
{(()[]<(({}()))({[()](<{}>)}(){}){{}<>({}{})((<>))}{}(({}()))({[()](<{}>)}(){}){
{}<>([{}]{})((<>))}{}(({}()))({[()](<{}>)}(){}){{}<>(({}))((<>))}{}(({}()))({[()
](<{}>)}(){}){{}<>(({}({}))[({}[{}])])((<>))}{}(({}()))({[()](<{}>)}(){}){{}<>{}
((<>))}{}>[[]]){{}({}[()()()()()]<>)(((<>)))}{}{}{}}<>
```
[Try it Online!](https://brain-flak.github.io/?c=lY3bCcAACAPXSXYQFxEnCe7e2Md3WwIiyUUFsDoADUhCBTZCk7ShoTSRTr0CkaS3N7o0/Yd3zF/0WSjP/cT@3F3gJrOqe929Aj5qx7igpVbuHQ&o=8&i=M1YwUjBV0DUBAA)
What better way to "Implement a simple stack language" than by using "a simple stack language"! And also a nice excuse to show off a new online interpreter for brain-flak that I have been working on.
Conveniently, a lot of the behavior described in the challenge is built-in to how brain-flak works. For example, *Your program/function must output/return the stack after all instructions are performed sequentially* is just describing the fundamental operation of brain-flak. And also, we could take each of the listed operations and transliterate it to brain-flak:
```
# Sum
({}{})
# Subtract
([{}]{})
# Duplicate
(({}))
# Swap
(({}({}))[({}[{}])])
# Pop
{}
```
Unfortunately, transliteration does not a valid answer make. So we need to do a bit of parsing to figure out which operation to call.
Without clarification from OP (and seeing as many answers have assumed positive input integers), this answer assumes that "push an arbitrary integer" means "an arbitrary positive integer". Here is the input format:
* -1: sum
* -2: subtract
* -3: duplicate
* -4: swap
* -5: pop
* All other positive integers: Push that integer
Technically, negative numbers other than 5 listed also work to push a number. 0 does not work.
("TOS" means "Top of Stack")
### Commented/readable version:
```
# While primary stack is not empty...
{
# Keep track of the stack height +1 at this point...
(()[]<
# Increment TOS
(({}()))
# TOS != 0
({[()](<{}>)}(){})
# If TOS != 0...
{
# OPCode -1: Sum
# Pop two numbers and push their sum to the alternate stack
{}
<>
({}{})
# Go back to main stack and replace TOS with 2 zeros
((<>))
}{}
# Increment TOS
(({}()))
# TOS != 0
({[()](<{}>)}(){})
# If TOS != 0...
{
# OPCode -2: subtract
# Pop two numbers and push their difference to the alternate stack. Second number - first number.
{}
<>
([{}]{})
# Go back to main stack and replace TOS with 2 zeros
((<>))
}{}
# Increment TOS
(({}()))
# TOS != 0
({[()](<{}>)}(){})
# If TOS != 0...
{
# OPCode -3: duplicate
# to the alternate stack
{}
<>
(({}))
# Go back to main stack and replace TOS with 2 zeros
((<>))
}{}
# Increment TOS
(({}()))
# TOS != 0
({[()](<{}>)}(){})
# If TOS != 0...
{
# OPCode -4: swap
# on the alternate stack
{}
<>
(({}({}))[({}[{}])])
# Go back to main stack and replace TOS with 2 zeros
((<>))
}{}
# Increment TOS
(({}()))
# TOS != 0
({[()](<{}>)}(){})
# If TOS != 0...
{
# OPCode -5: pop
# from the alternate stack
{}
<>
{}
# Go back to main stack and replace TOS with 2 zeros
((<>))
}{}
# And see whether any extra values were added to the stack during that last bit
# Essentially this means: "Push a 1 if none of the opcodes in that snippet matched, otherwise 0"
# Additionally, if one of the opcodes matched, there will be an extra value on this stack. Remember that, it's important.
>[[]])
# If none of the opcodes matched...
{
# Pop a useless '1'
{}
# Push TOS - 5 onto alternate stack
# This is the original positive integer that needs to be pushed
({}[()()()()()]<>)
# Push THREE zeroes onto main stack
(((<>)))
}
# Pop three values off the stack
{}{}{}
}
# Switch to main stack
<>
```
I'm certain this could be golfed further.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 114 bytes
```
f=->s,*r{s[/.+? ?/]?f[$',*r+(s>?/?[s.to_i]:(q=r.pop;s>?.?[q,q]:s>?-?[]:(w=r.pop;s>?,?[q-w]:s>?+?[q,w]:[q+w])))]:r}
```
[Try it online!](https://tio.run/##VYq7CgIxEEV7vyKFkI15oXaR3fmQYRAsAlabhxJE/PY42mi6c@655X559B5nu1SzK8@K3mkQ4AkibiVPeqoLeMDqbuv5SmHKc3FpTSeeHWA2mQKjBeTWfs1ws@3b9OfGiFk3UkpRKK@eRES5FwdxFF7S5k/dqHZUM6qW1N8 "Ruby – Try It Online")
### Usage
* `/` dup
* `.` drop
* `-` subtract
* `,` swap
* `+` add
[Answer]
# [Go](https://go.dev), ~~321~~ ~~320~~ 312 bytes
```
import(."strings";."fmt")
func f(c string)(o[]int){for _,e:=range Fields(c){n,a,b,A:=0,0,0,len(o)-1
B:=A-1
if A>-1{a=o[A]}
if A>0{b=o[B]}
switch e{case"D":o=o[:A]
case"d":o=append(o,a)
case"s":o=append(o[:B],a,b)
case"+":o=append(o[:B],b+a)
case"-":o=append(o[:B],b-a)
default:Sscan(e,&n);o=append(o,n)}}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVLBitswEKVXfcVUkCIROcQJC1sHLzhkeyylyS0NRbHl1NSRvZa8bRH-h957CYV-Rn-kX1PJcrJZFh2keW9mNPNmfv0-VKe_NU-_8oOAIy8kKo511WhYY1UWqVD4T6vz4Pbfq1tPkAlWuinkQeHFBOdHjSnKW5lCTlLwDCXVdldITU1eNfCZiShuuLT53xWizBRJqZGMsz1LonjK3CmFJBUNQrSM4sReRQ7JXRAaHlfbZNd5e2r21lxaU30rdPoFhEm5EniFo8oSUbJDvZ05m9e1kBmpGKceVdfoNlruXAUDN37B7cfnuOAlF1guEzlvSx2tVcolEeyNpIurXyXtOtQI3TayOwv4U_-oBWycSG2qwRSyHgRbgPheQ69Zh7yabhSEgkFaKK0gii29McjgEGYwxsx7m3nXsR5cXaABmVq_AOZXvmHoqbeQQXBBp-cMM5g_ubIZu6TOnv0Ynom5hW9APZXCbtjMUbaFD7YrXUqC4ziG9Sb5uAH7cpvSL4R2_fiV8O0ZxNMezImeWF2om_jr9eT-oeWlhaw8DKyLFaRPnRM8eoD4DkaPQEaP9JO0ZfSRvZt72xDa2VqelQL371cwlIKGwZxO_v4P)
Very straight-forward split-on-spaces then switch-on-token.
-1 by aliasing indexes and elements.
-8 by using the following instruction names:
* `D`rop
* `d`uplicate
* `s`wap
* `+`, `-`, and integers
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, ~~101~~ 92 bytes
```
map{/\W$/?eval"\$a[-2]$&=pop\@a":/x/?pop@a:push@a,/d/?$a[-1]:/s/?(pop@a,pop@a):$_}@F;say"@a"
```
[Try it online!](https://tio.run/##HYvBCsIwEAV/ZQlBFBu3rQQkIsnJm2cPpshCCwrVLEalIv66MfYyPJg33N16ndKF@I1@L9F2T@qFl3RQdSMnGw7sHQmDA9q8HRl@xJOjAlu0/1fVGIxop6MsRs6MPH7cdh3pJXKbklpCDRoUtJkRBljB/Bv4fg7XmNROL8qqTIp@ "Perl 5 – Try It Online")
### Operations:
* `+` = add
* `-` = subtract
* `s` = swap
* `d` = duplicate
* `x` = drop
* Anything with a digit in it is assumed to be a number. This implies that this will work with integers and floats as well as allowing a sign indicator at the front of the number.
Operators and numbers must be separated from each other by at least one space. No error checking was specified, so this code does not do any.
[Answer]
# [Python](https://www.python.org), 111 bytes
*-11 bytes, thanks to emanresu A, uses bytes `0x00`-`0x03` as commands*
```
def g(s):
S=[]
exec(s.translate('S+=[0]; S[-1]+=1; *_,a,b=S;S[-2:]=[b,a-b,a]; S[-1:]=[];'.split()))
return S
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVJLboMwEFW3nGIUkGwTsDCoUhtEL8GSWhXhkxBFBhmipmfpJpv2Tu0VeokaDCmJUqyxzMz72GO_fzZv3bYWp9PHoSvdh686L0rY4JasDIijhBtQHIsMt7STqWj3aVdgFC-jxOMhxInL-DJiIdgvTuqsozhUKX_Fo2TtpK6KEdRneIho2-yrDhNCDJBFd5ACYm37fffT-5bad6xtMEJ0V1cCZ1uJkWlbFNFK5MURZ4RAWUvIoBLQKj2jkZXocIkXpm3atmVRNSxK9bRQcBMY-LAE9wmSgM_x53Iu62aoX5TPX6-r9frkbQtPebgQjD6M3VQyB-LEnvMfIT-oLQxkj18dqhf4O0mgHfrVJXAu_n8rep-pHexKwp7cBvZICRT8HtrXVLcoUD8-n_qOno-ep4Kp8NHsrSQoXWfIQep21bytdogTou98enK_)
---
# [Python](https://www.python.org), 122 bytes
*-8 bytes, thanks to `psmears`*
```
def f(s):
S=[]
for c in s:exec('S+=[0] S[-1]+=1 *_,a,b=S;S[-2:]=[b,a-b,a] S[-1:]=[]'.split()['#*$.'.index(c)])
return S
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVJdToQwEI6vnGKyJaEt0FCIiWLwEjw2jWH5iSQGCD-6ehVf9kXvpKextMsKZm3Tpp35fqaTvn92r-Nj2xyPH9NY-Tdfb0VZQYUHEluQJkJaULU95FA3MMTlocyxk7qJCCSkwufSTTjQBy_z9kl6pyJhLBOx9zJfLQOZA9JhQ_dUj5gIB1GbOaxuivKAcyKJBX05Tn0Dqang--q56-tmxBXeIYootW2mps2Y2XaEAAIOIbjg34OIpLXCn9NF33Y6v0mfx6xr9ObgZYtAefgQnXw4v6iENHFhr_m3UEyqBE0ONlyk_envSyLjMJ-2wLX4_62YfZZ28D8SdHHT7BMlUvBrGF4y06JIXUJp2r98hB8)
---
# [Python](https://www.python.org), 127 bytes (no eval)
*taking `emanresu A`'s suggestion to its extreme*
```
def f(s):
S=[]
for c in s:
if"#"==c:S+=[0]
if"*"==c:S[-1]+=1
if"$"==c:*S,a,b=S;S+=[b,a-b,a]
if"."==c:*S,_=S
return S
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVLLaoQwFKVbv-KgLnxjRgrtlPQnXIoUH7EjiEpUBlf9kG5m0_5O1-3XNBqdVx8JCcnJPefc3OT1vR37XVMfDm9DX7h3ny85K1AYnblVENIoVlA0HBnKGp2AUBaqplKabUObRn4sEUsikUtimxKJ6TNmhU7ipDR8mMJTJ3HFWEjeGvBEQwWc9QOvEco0vm4-NHRtkrEOTV2NcxKcJXmSllXZjw76HRuxL6sKKUP5XDec5UjHCRe59oy3QpFxpeViZxSGqlnQLAu67omue56cVNOEBoINbLiPiIL4gnE8z3nTzgEX58cmpaXktP7LxxdGLoLFjJBf1aDNzFVOP1e4Rz6IRGa6H_-43Wx9ulMgbabVVeyFwz91mdzW2pArFevkKQUWViAYt-j2iaxYIDabWL7r-s2-AQ)
* push number: `#` followed by n times `*`
* drop: `.`
* swap: `$$..`
* add: `$$.$.$$...$$...`
* subt: `$.$$...`
* dup: `#$.$$.$.$$...`
*It is possible to go down to 3 operations, by creating a new operation `'` that pushes `1` and replacing `#` with `''$.$$..` and `*` with `'$$.$.$$...$$...`. But then the pushed integer is no longer clearly determinable from the push integer instruction*
---
# [Python](https://www.python.org), 193 bytes
```
def f(s):
S=[]
for c in s:
if"/"<c<":":S[-1]=10*S[-1]+int(c)
if"#"==c:S+=[0]
if"$"==c:*S,a,b=S;S+=[a+b,a-b]
if":"==c:S+=[S[-1]]
if","==c:S[-2:]=S[:-3:-1]
if"."==c:*S,_=S
return S
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZFNToQwGIbjlsQ7fGlnAUOLlGYSp069RJcNMfwMkQ0QfmI8i5vZ6D08hp7GQgFh177v0ydf24-v5r1_ravb7XPoC_r4851fCyjczhMOKKljB4q6hQzKCjoTQVmgB3TJLkggoTRlsWThcVr4ZdW7mWcZjKTMhPKlDmObHKbkqEhCUqmexirxU5LQdAbEemTSzSmxqaaRiKXSgnJhStsFi_JFKgfaaz-0FSh7kd-7-6YdJypchBmODgHyPMDAIAIf6DNoHjsbYq3ztm6mfleHxkACzFdNaDwU-OxibEufhWEtd4Z8MLoJCndGHGH-PxK3mnG1o8R28lG1TM_2IDe6E7EgN9AJurfE3oObTRTbV1m--Q8)
## Operations:
According to the comments on the [sandbox version](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/26150#26150) it is allowed to split operations into smaller suboperations
Atomics:
* `#` push zero
* `0`-`9` pop number multiply by 10 add digit
* `$` pop two numbers push their sum and difference
* `:` duplicate top number
* `,` swap top two numbers
* `.` drop top number
simulating operations from requirements:
* `#` followed by sequence of digits pushes a number
* `$.` pops two numbers and pushes their sum
* `$,.` pops two numbers and pushes their difference
[Answer]
# [Gema](http://gema.sourceforge.net/), ~~206~~ 203 characters
```
<N>=@push{s;$1}
+=@set{s;@add{$s;@pop{s}$s}}
-=@set{t;$s}@set{s;@sub{@pop{s}$s;$t}}
d=@push{s;$s}
r=@set{t;$s}@set{n;@pop{s}$s}@set{s;$t}@push{s;$n}
s=@pop{s}
=
\Z=@f{}
f:=@cmps{${s;};;;;$s @pop{s}@f{}}
```
As I like `dc`, borrowed its commands: `d` dup, `r` swap, `s` drop.
The stack is dumped top to bottom.
Sample run:
```
bash-5.2$ echo '1 2 + d 3 4 - 5 r 6 7 8 s s 9' | gema '<N>=@push{s;$1};+=@set{s;@add{$s;@pop{s}$s}};-=@set{t;$s}@set{s;@sub{@pop{s}$s;$t}};d=@push{s;$s};r=@set{t;$s}@set{n;@pop{s}$s}@set{s;$t}@push{s;$n};s=@pop{s}; =;\Z=@f{};f:=@cmps{${s;};;;;$s @pop{s}@f{}}'
9 6 -1 5 3
```
[Try it online!](https://tio.run/##XYw9DsIwDIV3nyKDN5SBn4kQlBNwAMRSSAtLS1Snk@WzBwOhILw8Pfl737Xtm1J2h70PaaIbk8OlwMIHarOW0MTIqJnuiUmQRMC@n9lp@2A0nXlmHGbF4tdIAuP/aPhxVovO5skgQL4SYDycjj50LNBtfbj0iRiVEqeHZCr3BKSUzcqsjTWvGI19AA "Gema – Try It Online") / [Try all test cases online!](https://tio.run/##lVLBjtMwED3XXzFEZt2yirJp2QOkRuEA0l5AghtJtMrG7rbabhJlXISU9beXsZOmgNjD5mDPzHtvxn7OXYnbo9LVvuw0hB/BaDS3VYlaztksEzEs4VIUUqzEkKJLhviKsBBWAx7HvvgOFIQuvxIn@crDPhhK6tQzHksrKlxD58dQsBRswVjb7WqzAfEEr8O31wj/2Ze05rUAcVO3B0P7N42HvQs@/Wp1ZbSi8OuDYGzTdLBzJFoh4P2r6ZpZWtggAdWwWefVMuBziJrWRPf6sYywq3wA4rj@8kGm7QG3PSY8tuxSpqgNJWmpVM9pb5u2R8vRWpaHA2oSSk88PNz1Eynhhnjq3BIt6/4V1X80HbuQbJLUlqEcGQwky3/IdNNbtnkv0@qxxZ4Tyyb0cYSR5wj2KGC9XpMV3pUAFgFzBpT0eiXsd2hGePAkYDNXk3Mgb24@f5dckO8JmLIaeb3DszfkJSxg4Vr91B1qdTuZembQpBc8Lin9GaPID43yvKYh08kcfn7M4TqFJ8whyzzvr5MEIOVzmqKAiwvQ1bbxv40zRTW1Pv4G "Bash – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 131 129 bytes
```
k[99],*s=k,t;main(p){
for(;p=getchar()-64;*s=p<0?*s*8+p+16:p<4?p=*s--,t=*s,p:p<6?*s+t:p<8?-*s:!++s);
for(;s>k;printf("%d ",*s--));}
```
[Try it online!](https://tio.run/##JYzNCoJAFEZfpYJgfqFRE3U0E5U2QqtW0YBMaSLZ4MwuenYbbXXv@e65n6StlNPUX8PwRpBOemL4q@4GoOCneY@AA5W0DyOf9Qgg9T3IraTiXYo0CrDCzI9U7KUqQZpSYuwgyia@vWNjlyClSEdrjDXkS58@9FyN3WAasNneVxsyP0LIv9MkmHCyQrD8XGSCORZOpXDnhFVZUZUzWkW44s@L7dpgn1/K4w8 "C (gcc) – Try It Online")
Inspired by [Python answer](https://codegolf.stackexchange.com/a/267443/152), saved 23 bytes by implementing keywords as primitives:
***Primitives***
* octal-digit: multiply stack top by 8, add digit value.
* swap-pop: swap top two items, pop new top into temp register.
* add: add temp register to stack top
* negate: negate top of stack
* push-zero: push a 0 onto top of tack
These primitives are mapped to to ASCII ranges, which allow us to build the following operations with nonsense names.
**OPERATION KEYWORDS:**
* `^` = Number entry, should be followed by octal-digits
* `AD` = Add (swap-pop;add)
* `AGE` = Sub (swap-pop;negate;add)
* `CUE` = Swap (swap-pop;push-zero;add)
* `LADLE` = Dup (push-zero;swap-pop;add;push-zero;add)
* `CODA` = Drop (Swap;swap-pop)
* `@` = terminate and print
USAGE:
```
$> echo "^1^2AD^1CODA^12^2AGE^3AD^9LADLEAGE^1^2^3^1LADLE^2AD^3^2^5CUE@" | ./a.out
2 5 3 3 1 3 2 1 0 11 3
```
---
previous:
# [C (gcc)](https://gcc.gnu.org/), 244, 229, 223, 204, 161, 154 bytes
*thanks to @ceilingcat for -7*
```
k[99],*s=k,t;main(p){for(;p=getchar()-42;*s=t=p<0?!++s:p>5?8*t+p-6:p>4?*--s:p>3?
*s++:p>2?*--s-t:p>1?p=*--s,*s++=t,p:*--s+t);for(;s>k;printf("%d ",*s--));}
```
[Try it online!](https://tio.run/##jZDNToNAHMTvPMXYaIRdthRojQUpaaIHL62x9WRM3AKlpC1sYElj1Gevu9AHMHuZ38z89ytheZKcHYLly9PrfP28XKwCA2D4VCvCoj1ushpZKeuvANvqcKhOOBVyhyqR/IC0yAvZ9ANUD8zTtCemadVuerI7OnHR41DjY3shp6O6uiDRuM7qY1FymYGXKURdlNIgznn/Pp1@2KSJ9rYMj7woTWF9b6vaDEWUZzLZ8dq02NgLVUVG4mEUX1HaBGI2ie@JpILdKT2OCWPa9GPSUKqE1zlMKunGItJg6yiStgg0UWmF3THNbB92t9mag5sUA1VjzLLCX/2Hbw3Ps8C4niFLdhVu4cKjcB24HjwGn2I6ZNqED3eoM1/piU1u8QM4HFUrYShH@arRpS5GcLXUz//3huc/ "C (gcc) – Try It Online")
**OPERATIONS:**
* = Number entry: follow with octal digits
* `+` = Add
* `-` = Sub
* `,` = Swap
* `.` = Dup
* `/` = Drop
* `*` = terminate and print
**Usage:**
```
$> echo ' 1 2+ 1/ 12 2- 3+ 9.- 1 2 3 1. 2+ 3 2 5,*' | /a out
2 5 3 3 1 3 2 1 0 11 3
```
How it works: `k` is the stack storage and `s` points to the top. `p` is the next program character from standard input.
`p-42` maps the range "`*+,-./01234567`" into `0..14`.
A '`*`' (0) exits the loop. Otherwise, it's a big if-else statement using ternary operators.
Any ASCII character below '`*`' starts a number entry by pushing a 0 onto the stack.
Characters from '`0`' upward are converted to octal digits and added to 8\* the stack top `t`.
The remaining 5 characters manipulate the stack pointer and produce the value that should be on top.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes
```
WS≡§ι¹+⊞υ⁺⊟υ⊟υ-⊞υ⁻⊟υ⊟υr≔⊟υιu⊞υ↨υ⁰wFE²⊟υ⊞υκ⊞υIιIυ
```
[Try it online!](https://tio.run/##fY@5CsMwEER7fYVwtcI25OjiykmVImDIFwifIkISOuJAyLcraxNsV2l22Nk3A1sP3NaayxjHQciWwlWZ4O/eCtUDY9SNwtcDhdJfVdO@QGR0j/ab1Ny1NEmTE62CGyBktJLBQaUNBIbLrIwVPzDfgDeh/pAWydI50asFEcsxbGrO6Ey6W7MjnjttKdy4gcPavWQeiDZtx4P0a9GFOw9iavmQCh/3MDsYLGI8kj1xIzeksRpHMORAUhLzp/wC "Charcoal – Try It Online") Link is to verbose version of code. Takes a list of newline-terminated words as input (could save two bytes by requiring symbols). Explanation:
```
WS≡§ι¹
```
For each input string, switch on its second character.
```
+⊞υ⁺⊟υ⊟υ
-⊞υ⁻⊟υ⊟υ
r≔⊟υι
u⊞υ↨υ⁰
wFE²⊟υ⊞υκ
```
Handle `+`, `-`, `drop`, `dup` and `swap` respectively.
```
⊞υIι
```
Anything else is assumed to be a number to be pushed to the stack.
```
Iυ
```
Output the final stack.
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-p`, 50 bytes
```
V"lPU:".{@a?a(a."POl+:POl 0l@>:2 @l lPK1"^sa)}MJgl
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7IKlpSVpuhY3jcKUcgJCrZT0qh0S7RM1EvWUAvxztK2AhIJBjoOdlZGCQ45CToC3oVJccaJmra9Xeg5Up3W1NZeJkUJBaXGGgokRV6YChGnAZaCtoM1loKugy2VgqJBSlF_AZWCkkFIKpIwVissTC7isayFGbIpWMlbSUTICYlMgNjCGOwsA)
Takes commands as separate command-line arguments. Outputs the final stack as a list, top first. The commands are as follows:
```
42 push nonzero number
i push 0
0+ +
0- -
01 drop
02 dup
03 swap
```
### Explanation
As usual for language interpreters in Pip, this is a translate-and-eval solution. Since `l` is preinitialized to the empty list, we'll use that to store the stack. The overall logic of the program is:
```
V"lPU:".{...}MJgl
g ; List of command-line args
MJ ; Map this function to each and join into a single string:
{...} ; Translation code (see below)
"lPU:". ; Prepend lPU: to each translated command
V ; Evaluate
l ; Print the final value of l (formatted nicely by -p flag)
```
Inside the translation function:
```
@a?a(a."POl+:POl 0l@>:2 @l lPK1"^sa)
@a ; First character of command
? ; Is it truthy (nonzero)?
a ; If so, return unchanged (this is a push command)
( a) ; Otherwise, treat the command as an index into...
a." " ; Prepend the command to this string
^s ; and split on spaces
```
which boils down to the following translation table:
```
42 lPU:42 ; Push 42 onto l
i lPU:i ; Push i (preinitialized to 0) onto l
0+ lPU:0+POl+:POl ; Pop number, add 0, pop another number, add, push result
0- lPU:0-POl+:POl ; Pop number, subtract from 0, pop another number, add, push result
01 lPU:0l@>:2 ; Push 0, then remove first two elements of l
02 lPU:@l ; Push first element of l
03 lPU:lPK1 ; Remove element at index 1, then push it
```
[Answer]
# [Haskell](https://www.haskell.org/), 143 bytes
```
([]#).words
(a:b:s)#(c:r)|c=="s"=(b:a:s)#r|c=="+"=(a+b:s)#r|c=="-"=(b-a:s)#r
(a:s)#(c:r)|c=="d"=(a:a:s)#r|c=="x"=s#r
s#(n:r)=(read n:s)#r
s#_=s
```
[Try it online!](https://tio.run/##VczLCsIwEIXhvU8xJC5SSsQL3QTmSVRkmrRaTGPJCHbhsxsbu1C3P985F@Jr431q8ZDU/iiL1eMWHS8UmdpwIZU1sXhaRMECVW0ox/gJ5RSorL9BZ6FnkQ/@5i7r3/kokCfHUoXJoIoNOQjzmOUJOfXUBRxiF@7LVmxgC3q3rmCEEhxUwKBFetnW05mTtsPwBg "Haskell – Try It Online")
## Operations
* `+` Add
* `-` Subtract
* `s` Swap
* `d` Dupe
* `x` Drop
* Everything else is interpreted as a number
All commands are separated by spaces, and this code does no error checking.
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 29 bytes
```
⸠+⸠-⸠:⸠$⸠_W₈×£?Ṃ(nnK[⌊|O¥iĖ]W
```
[Try it Online! (link is to literate version)](https://vyxal.github.io/latest.html#WyJsIiwiIiwiKC4gYWRkKSAoLiBzdWIpICguIGR1cCkgKC4gc3dhcCkgKC4gcG9wKSB3cmFwIG5lZy0xICogc2V0LXJlZ1xuJ2ZvciAoaW5wdXQgc3BsaXQtc3BhY2VzKVxuICBuIG5cbiAgKGlzLW51bT8pID8gZmxvb3IgOiBvcmQgZ2V0LXJlZyBpbmRleCBjYWxsXG5jbG9zZS1hbGwgd3JhcCIsIiIsIjMgNSA2IGkgaSIsIjMuMy4wIl0=)
Wow, the SBCS really doesn't do the beauty of literate mode justice:
```
(. add) (. sub) (. dup) (. swap) (. pop) wrap neg-1 * set-reg
'for (input split-spaces)
n n
(is-num?) ? floor : ord get-reg index call
close-all wrap
```
Command set is:
```
i -> add
j -> subtract
k -> duplicate
l -> swap
m -> pop
[0-9]+ -> number
```
## Explained
```
⸠+⸠-⸠:⸠$⸠_W₈×£?Ṃ(nnK[⌊|O¥iĖ]W­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢⁣​‎‏​⁢⁠⁡‌⁢⁤​‎‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁡⁡‏⁠‏​⁡⁠⁡‌⁣⁤​‎‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁤⁡​‎‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁤⁢​‎‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‏​⁡⁠⁡‌⁤⁣​‎‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌⁤⁤​‎‎⁡⁠⁢⁢⁤‏‏​⁡⁠⁡‌⁢⁡⁡​‎‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌⁢⁡⁢​‎‎⁡⁠⁢⁣⁣‏‏​⁡⁠⁡‌⁢⁡⁣​‎‏​⁢⁠⁡‌⁢⁡⁤​‎‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏‏​⁡⁠⁡‌­
⸠+⸠-⸠:⸠$⸠_W # ‎⁡Push a list of:
⸠+ # ‎⁢ lambda x, y: x + y
⸠- # ‎⁣ lambda x, y: x - y
⸠: # ‎⁤ lambda (stack): stack.push(stack[-1])
⸠$ # ‎⁢⁡ lambda (stack): stack[-2], stack[-1] = stack[-1], stack[-2]
⸠_ # ‎⁢⁢ lambda (stack): stack.pop()
# ‎⁢⁣Technically, all these lambdas are monadic (take one argument) so far.
₈× # ‎⁢⁤Multiply each lambda by -1 to make them operate on the stack
£ # ‎⁣⁡And put the stack lambda list in the register
?Ṃ # ‎⁣⁢Split the input on spaces,
( # ‎⁣⁣and to each command `n` in that,
nn # ‎⁣⁤ Push two copies of `n`
K # ‎⁤⁡ and test whether the second copy is numeric
[⌊ # ‎⁤⁢ if so, simply evaluate and leave on the stack
| # ‎⁤⁣ otherwise:
O # ‎⁤⁤ get the unicode code-point of `n`
¥i # ‎⁢⁡⁡ index into the register
Ė # ‎⁢⁡⁢ and call the pushed lambda.
# ‎⁢⁡⁣That's the reason the command set was chosen - the ord value mod 5 corresponds to the lambda. Any set of 5 characters could have been chosen, but `i` was the closest to `d`, which I knew to be `100`.
]W # ‎⁢⁡⁤Close all structures, and wrap the stack when finished.
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Haskell](https://www.haskell.org/), 99 bytes
```
foldl(!)[]
s!c|c<0= -c:s|1<2=[j(+),j(-),\(n:x)->n:n:x,\(a:b:x)->b:a:x,tail]!!c$s
j o(a:b:x)=b`o`a:x
```
[Try it online!](https://tio.run/##LcmxDoMgFEDR3a@QxAFSXgJ2I9IfQRPxtVotBVIcOvjtpaTpdHNy7zY9bs7lJeg@z8FdHSXMDFUieGAndA2o0iG7VpuNnhjfKDDeU6/eDC5elRZZNf08KVu829UNhGCTqq0O/6mnMYzl5qddvY6v1e/NEgxIwaHlksOZiyF/cHZ2SRkwxi8 "Haskell – Try It Online")
Takes a list of integers as input, where:
* `0`: sum
* `1`: subtract
* `2`: dup
* `3`: swap
* `4`: pop
* `-n`: push n
Prints the stack as a list with the top element first.
---
This works by building a list of functions and using the command integer to index into this list. Negative commands are managed separately.
The definitions of `dup`, `swap`, and `pop` are fairly straightforward, but rather than defining two separate functions for `sum` and `subtract` I've defined a single function `j` that takes an operator as an extra argument and applies this operator to the first two elements of the stack. Passing `(+)` and `(-)` to `j` then does the trick.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 118 bytes
```
switch -r($args){\D{$a,$b,$s=$s}s{$s=$b,$a+$s}[-+]{$s=,("$b$_$a"|iex)+$s}u{$s=$a,$a,$b+$s}r{$s=,$b+$s}\d{$s=,$_+$s}}$s
```
[Try it online!](https://tio.run/##bU5Nb4JAEL3zKyZkUyGyjWh66MGExLbXNtWbGrPCWjFY6A5EE@S30x02oBj3sm/ex8zL0pNUuJdJwsNUyZrtpmWNpzgP98CVw4T6QbdcvZVMeGzrMZwyrLCkX09iqKclH66J8BybbdmGCfsSy7NLUtEYdZLCRKjGaPAqMsOGhophXVlW4FignweBY/swhqHtgT2x3Vs2UmlGdI8daTOHiQn4/q32ClGRASdh1N80hkmzXwP/7oZOtNf7GplfAE@i6UCY6rlwgY9UvYtwzz@3BxnmUDYZlkvMZwKlB0yeMy3ICKbANn2VqA5zzJI4hwEMLONSEosk154ntoOg9d2LLeKHNP69ppdf81mBeXo0vdaBKUZvXoShRAQKd@W4/GtXPS9UfHTczr942LY719q@TQ@4dmqkyqqs@h8 "PowerShell Core – Try It Online")
Takes an array in parameter containing the instructions, returns an array top to bottom.
Explanation for the previous version, but the idea is still more or less the same:
```
switch -r($args){ # for each of the instruction switch as regular expressions:
s{$a,$b,$s=$s;$s=$b,$a+$s} # s for Swap
u{$b,$s=$s;$s=$b,$b+$s} # u for dUp
r{$b,$s=$s} # r for dRop
[+-]{$a,$b,$s=$s;$s=,("$b$_$a"|iex)+$s} # + or - for subtract and sum
\d{$s=,$_+$s} # to push a number
} # end of the foreach
$s # return the stack
```
[Answer]
# [Cabsi](https://github.com/ConorOBrien-Foxx/Cabsi), 173 bytes
```
1PUSH NULL
2GETW
3JNL 8
4DUP
5YEET
6ORD
7GOTO $1
8JNL 64
9PRINT
10GOTO 8
33POP
34GOTO 2
36SWAP
37GOTO 2
43ADD
44GOTO 2
45SUB
46GOTO 2
57YOINK
58MAKEI
59GOTO 2
62DUP
63GOTO 2
```
[Try it here!](https://conorobrien-foxx.github.io/Cabsi/?code=1PUSHwwNULLwa2GETWwa3JNLww8wa4DUPwa5YEETwa6ORDwa7GOTOwwx101wa8JNLww64wa9PRINTwa10GOTOww8wa33POPwa34GOTOww2wa36SWAPwa37GOTOww2wa43ADDwa44GOTOww2wa45SUBwa46GOTOww2wa57YOINKwa58MAKEIwa59GOTOww2wa62DUPwa63GOTOww2&input=10ww2wwx19ww3wwx17wwx1qdupww2wwx17wwx10sx3bapwwx1qdupww0wwx10sx3bapwwx19wwx10sx3bapwwwxdrop) Implements dup (`>`) add (`+`) sub (`-`) drop (`!`) and swap (`$`). Prints stack top-to-bottom. Expects instructions to be separated by spaces/newlines.
Technically, only the first character of non-numeric instructions are parsed, so the "literate" input `10 2 - 3 + >dup 2 + $swap >dup 0 $swap - $swap !drop` works just as well as the minified `10 2 - 3 + > 2 + $ > 0 $ - $ !`.
## Explanation
As Cabsi is a stack language, the code can implement a stack-based language using its own stack. Thankfully, since the target language is not very complex, there is not a lot of overhead we need.
```
1 PUSH NULL REM Stack work delimiter
REM ReadLoop:
2 GETW REM Read word from STDIN
3 JNL 8 REM If end of input, jump to PrintLoop
4 DUP REM Duplicate token read
5 YEET REM And place it on the secondary stack
6 ORD REM Get Ord(Token[0])
7 GOTO $1 REM Goto the line specified by that ordinal
REM PrintLoop:
8 JNL 64 REM If work delimiter reached, end program
9 PRINT REM Print top of stack
10 GOTO 8 REM Jump to PrintLoop
REM If "!" (ord 33):
33 POP REM Pop top of stack
34 GOTO 2 REM Jump to ReadLoop
REM If "$" (ord 36):
36 SWAP REM Swap top two on stack
37 GOTO 2 REM Jump to ReadLoop
REM If "+" (ord 43):
43 ADD REM Add top two on stack
44 GOTO 2 REM Jump to ReadLoop
REM If "-" (ord 45):
45 SUB REM Subtract top two on stack
46 GOTO 2 REM Jump to ReadLoop
REM If "0" through "9" (ords 48 through 57)
57 YOINK REM Pull the full representation from the secondary stack
58 MAKEI REM Cast to integer
59 GOTO 2 REM Jump to ReadLoop
REM If ">" (ord 62)
62 DUP REM Duplicate top on stack
63 GOTO 2 REM Jump to ReadLoop
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~684~~ 649 bytes
```
,[<<--[>+<++++++]>-[->-<]>[[<]+[>]<-]<<<<<<<<<<<<<<<<[[->]<<<<<<<<<<<<<<<<]>[->+<]>[->+<]>[->+<]>[->+<]>[->+<]>[->+<]>[->+<]>[->+<]>>[-]<[->+<]>[<+[,<<++++[>++++++++<-]>[->-<]>[---------------->[-<++++++++++>]<[->+<]<+>]<[->+<]>]>>>>>>>>>[>]+[<]<<<<<<<-[->>>>>>>>[>]<+[<]<<<<<<<]>->->->->-<<<<<]>[->>>>>>>>[>]<<[->>+<<]>[-<+>]>[-<+>]<[<]<-<-<-<-<-<]>[->>>>>>>[>]<[-]<[<]<-<-<-<-<]>[->>>>>>[>]<[-<->]<[<]<-<-<-<]>[->>>>>[>]<[->+>+<<]>>[-<<+>>]<<<[<]<-<-<]>[->>>>[>]<[-<+>]<[<]<-<]>,]>>[[<++++++++++>[-<-[<+<<]<[+[->+<]<+<<]>>>>>]<[-]-[>+<-----]>---[-<<+>>]<<-<<<<<[<]+[>]>>>>[-<<<<<[<]>+[>]>>>>]<[->>>+<<<]>>>]<<<<<<<[<]>[.[-]>]++++++++++.[-]>>>>>>>]
```
[Try it online!](https://tio.run/##nVLLDgIhDPyVvbM1Pq5Nf6ThoCYmxsSDid@P00KB1ZvlANuWmeksl9f5/ry9r49SVmUmUkmcPLKQkhBnUeWcVDJT5q9QtPwkcYMA88eGPXOkOOnKLgaiWkCChCr6CmQ49ZAA4nEUMLTAOAljNcU26SjwVIELscZsU6shA9rzxtQ2NgTqa7qlrmbbMMq1yrRB6GVtk1RCowKX@x/N0dpwhpIsq93Q2SEjQgJYrCnMcmSRqtKfg5sLH/A4OmE1o70LJ@wZiZRrdXMcMhy1Ft0BHH@gh3/XyKUc9stxoeW0pA8 "brainfuck – Try It Online")
All numbers have to be followed by a space. Uses `+-,./` for `add`, `sub`, `dup`, `drop`, and `swap` respectively.
Prints stack from bottom to top separated by newlines.
I confess this is a touch over-engineered, and could be shorter if I used less human-readable I/O.
## With Comments
```
READ AN INSTRUCTION
IF ITS A NUMBER THEN GRAB ALL OF IT UNTIL THE SPACE
OTHERWISE ITS A REGULAR INSTRUCTION
ITS ACTUALLY EASIER TO CHECK IF ITS A REGULAR INSTRUCTION THAN A NUMBER BECAUSE THERE ARE MORE NUMBERS THAN INSTRUCTIONS
SO WE CHECK THAT FIRST
>>>>>>>>>>>>>>>>>>>>>>>>>>>> THIS LINE MAKES DEBUGGING EASIER BUT ISNT NEEDED
,[
<<--[>+<++++++]>-
SUBTRACT 42 FROM INP
[->-<]
COLLAPSE IT LEFT
>[
CLEAR THE ONE AT NEGATIVE SIXTEEN
THIS IS A GUARD VALUE
<<<<<<<<<<<<<<<<[-]>>>>>>>>>>>>>>>>
[<]+[>]<-]
SUM UP THE FIRST NINE NUMBERS AS THESE ARE THE DIGITS
WE IGNORE 0 AS ITS NOT USEFUL
<<<<<<<<<<<<<<<<
IF THE GUARD IS TRIPPED THEN WE DISCARD THE WHOLE STACK
[[->]<<<<<<<<<<<<<<<<]>
[->+<]>[->+<]>[->+<]>[->+<]>[->+<]>[->+<]>[->+<]>[->+<]>
>[-]<[->+<]> I PUT IT IN THE ZERO ANYWAY FOR SANITY
IF THIS IS TRUTHY THEN ITS A NUMBER THAT WE NEED TO PUSH
IN SUCH CASE WE NEED TO KEEP GRABBING DIGITS UNTIL WE SEE A 32 SPACE
[
<+[
,
32
<<++++[>++++++++<-]>
SUBTRACT FROM INP
[->-<]
>
[
IF ITS STILL TRUTHY THEN ITS A NUMBER (PROBABLY)
SUBTRACT 16 THAN MULTIPLY BY TEN ONTO THIS
----------------
>[-<++++++++++>]
AND COPY BACK
<[->+<]
<+> SET THE NOT FLAG
]
COPY THE NOTFLAG UNTO HERE TO CHECK IF WE NEED TO LOOP
<[->+<]>
]
GO SIX RIGHT AND PUSH A NEW VALUE TO THE STACK
>>>>>>>>>[>]+[<]<<<<<<<-
[->>>>>>>>[>]<+[<]<<<<<<<]
>->->->->-
<<<<<
]
> IF THIS IS POSITIVE THAN ITS A SWAP INSTEAD
[
WE USE SCRATCH SPACE NEXT TO THE NUMBERS TO MAKE SWAPPING THEM POSSIBLE
-
>>>>>>>>[>]<<
COPY THIS NUMBER TWO ACROSS
[->>+<<]
>[-<+>] COPY THE NEXT NUMBER INTO THIS PLACE
>[-<+>] AND THIS ONE TOO
<[<]<-<-<-<-<-< AND GO HOME
]
> IF THIS IS POSITIVE THAN ITS A DROP
[
-
>>>>>>>[>]< GO TO THE TOP OF THE STACK
[-] CLEAR IT
<[<]<-<-<-<-< AND GO HOME
]
> IF THIS IS POSITIVE THAN ITS A SUB
[
-
>>>>>>[>]< GO TO THE TOP OF THE STACK
[-<->] SUB IT FROM THE LAST
<[<]<-<-<-< AND GO HOME
]
> IF THIS IS POSITIVE THAN ITS A DUP
[
-
>>>>>[>]< GO TO THE TOP OF THE STACK
[->+>+<<] COPY IT ACROSS THE NEXT TWO
>>[-<<+>>] COPY THE ONE BACK TWO
<<<[<]<-<-< AND GO HOME
]
> FINALLY IF THIS IS POSITIVE THAN ITS ADD
[
-
>>>>[>]< GO TO THE TOP OF THE STACK
[-<+>] ADD IT UNTO THE LAST
<[<]<-< AND GO HOME
]
>,
]
ONCE WERE DONE WE NEED TO PRINT ALL VALUES ON THE STACK
>>
[
GET ALL THE DIGITS
[
<++++++++++>
[-<-[<+<<]<[+[->+<]<+<<]>>>>>] DIVMOD
<[-] UNNEEDED VALUE
SET TO 48 AND ADD TO THE MOD VALUE
-[>+<-----]>---
[-<<+>>]
<<
PUSH THIS VALUE TO THE NUMBERSTACK
-<<<<<[<]+[>]>>>>
[-<<<<<[<]>+[>]>>>>]
<[->>>+<<<] MOVE THE NEW VALUE BACK
>>>
]
PRINT THEM ALL OUT
<<<<<<<[<]>[.[-]>]
PRINT A NEWLINE AS WELL ++++++++++.[-]
>>>>>>> NEXT NUMBER
]
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 50 bytes
```
T←{(⍺⍺2↑⍵),2↓⍵}
p‚Üê+/T
m←¯1∘⊥T
x←⊃,⊢
s←⌽T
d‚Üê1‚àò‚Üì
⎕←⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/5FHbhGqNR727gMjoUdvER71bNXWAjMlARi1XAVBWWz@EKxdIH1pv@KhjxqOupSFcFUDuo65mnUddi7iKQeyevSFcKUAGWEXb5P//CxQMdYx0HvWu4UoBskB0gYKxTq6CkY6hAZibq1ChYAlmGQMVwpQY6VRAlRcrmALFjUFsAA "APL (Dyalog Classic) – Try It Online")
* Programs start on the right with `⍬` (empty array, called *zilde*) and run as their own lines, not as strings.
* `n,` pushes `n` onto the stack.
* `p` adds the top two.
* `m` subtracts the top from the second.
* `x` duplicates the top.
* `s` swaps the top two.
* `d` drops the top.
Note that the spaces are necessary.
Polish notation is used, i.e. read right-to-left (opposite of the examples in the question), as APL itself is right-to-left.
The stack is stored and displayed top-to-bottom (opposite of the examples in the question).
E.g. using Polish notation `1 dup 2 +` becomes `p 2,x 1,⍬` and outputs `3 1`
My first time using *dops* (user-defined operators) in APL. Doesn't seem too useful for golfing, unless you are defining multiple similar functions. `T` is a dop defined as `{(⍺⍺2↑⍵),2↓⍵}`. This is a monadic operator that takes a monadic function on the left, and applies it to the first two elements of the array on the right, then catenates with the rest of the array (you can even use this to define new stack operations).
Would love to know how this can be improved upon.
EDIT: There was a bug in my minus function that would negate the whole stack. None of the test cases noticed it though. Fixed now but had to add one byte.
[Answer]
# [Julia 1.0](http://julialang.org/), 90 bytes
```
f()=[]
f(+,b...;c=f(b...))=try c[[+;2:end]]catch;try[c[2]+c[1];c[3:end]]catch;[+;c]end;end
```
[Try it online!](https://tio.run/##TZDBasMwEETv@oqtTxJxTGS3hcY4PbXQQ79A6LCWZapiHCMrbgr993QlJxCDYGf0dmTm@zQ4lOfLpeeiUZr1fJO3RVHUpul5HIRogv8Fo9SmLvd27LQ2GMxXTa4yqtQbo6SujaruLwk2mnRN59L54wQNUHp3SoPMpWbzD0ax0AJj/dGDAzeCt9gNbrQzFwzow7wlaJ4GF7jLIdsesusF2XbBoeCfNmAxoZ9twVcQhRBQ/B0At3TAzQgfY4BXeB@OGJ4fCYA9YMqJ8Ys1PGbdRfGWMhLgCei5t4uNNorYCVD21UnM5N0YhpFjc/Drlutp8aGBNql7Jns7T9YE2@0hy6FdcaqJxaoklFAB/bVKk2YSYmerIZOMZUatWUXIE6Qeo1GRKCNSwmY1SOxIbSlydSRFvKyJSe9uD9xWJL35Dw "Julia 1.0 – Try It Online")
input and output stacks are lists in reverse order.
It works by chosing clever ways to represent the commands, grouped in 3 types, detected with try/catch (shorter than multiple dispatch here)
* Arrays:
+ drop: `[]`, will return `c[2:end]`
+ dup: `[1,1]` will return `c[[1;1;2:end]]`
* Functions:
+ +: `+`, returns `[c[2]+c[1];c[3:end]]`
+ -: `-`, returns `[c[2]-c[1];c[3:end]]`
+ swap: `vcat`, returns `[c[2];c[1];c[3:end]]`
* Floats:
+ pushing numbers must be floats, otherwise they might not throw an error in the "array" part
] |
[Question]
[
Given a list of two or more spelled-out serial numbers of equal length greater than two, e.g.
```
[[ "three" , "one" , "four" ],
[ "one" , "five" , "nine" ],
[ "two" , "six" , "five" ],
[ "three" , "five" , "eight" ]]
```
sort the list by the numbers that the words represent:
```
[[ "one" , "five" , "nine" ],
[ "two" , "six" , "five" ],
[ "three" , "one" , "four" ],
[ "three" , "five" , "eight" ]]
```
You may require the numbers to be spelled in lower or upper, but not mixed, case.
### Test cases
`[["three","one","four"],["one","five","nine"],["two","six","five"],["three","five","eight"]]`
gives
`[["one","five","nine"],["two","six","five"],["three","one","four"],["three","five","eight"]]`
`[["two","seven"],["one","eight"],["two","eight"],["one","eight"],["two","eight"],["four","five"]]`
gives
`[["one","eight"],["one","eight"],["two","seven"],["two","eight"],["two","eight"],["four","five"]]`
`[["one","four","one","four","two"],["one","three","five","six","two"],["three","seven","three","zero","nine"]]`
gives
`[["one","three","five","six","two"],["one","four","one","four","two"],["three","seven","three","zero","nine"]]`
`[["zero","six","one"],["eight","zero","three"],["three","nine","eight"],["eight","seven","four"],["nine","eight","nine"],["four","eight","four"]]`
gives
`[["zero","six","one"],["three","nine","eight"],["four","eight","four"],["eight","zero","three"],["eight","seven","four"],["nine","eight","nine"]]`
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~9~~ 8 bytes
```
Ö†€¨tfṡn
```
[Try it online!](https://tio.run/##yygtzv7///C0Rw0LHjWtObSiJO3hzoV5////j45WysvMS1WK1YlWSs1MzygBs4pTy1LzIKzMCjCdllkGUZSWX1oEZpRkFKVChErK88F0PsicWAA "Husk – Try It Online")
Algorithm "inspired" by [recursive's Stax answer](https://codegolf.stackexchange.com/a/161676/62393) (I've just changed the lookup string a bit), go upvote him!
The trick is mapping each letter to its position in the string `tfsen` (compressed at the end of this program). Husks lists are 1-based, and missing items return 0, so we get this mapping:
```
"one" [0,5,4]
"two" [1,0,0]
"three" [1,0,0,4,4]
"four" [2,0,0,0]
"five" [2,0,0,4]
"six" [3,0,0]
"seven" [3,4,0,4,5]
"eight" [4,0,0,0,1]
"nine" [5,0,5,4]
```
As you can see, the lists are perfectly ordered.
---
In order to be clear, here's how list comparison works in Husk (and in many other languages):
1. If one of the two lists is empty, that's the smaller one.
2. If the first elements of the two lists are different, the one with the smaller first element is the smaller list.
3. Otherwise, discard the first element from both lists and go back to point 1.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~24~~ ~~22~~ ~~17~~ ~~16~~ 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
▄Ωφ▐╧Kìg▄↕ñ▼!█
```
[Run and debug it](https://staxlang.xyz/#p=dceaeddecf4b8d67dc12a41f21db&i=[[%22three%22,%22one%22,%22four%22],[%22one%22,%22five%22,%22nine%22],[%22two%22,%22six%22,%22five%22],[%22three%22,%22five%22,%22eight%22]]%0A[[%22two%22,%22seven%22],[%22one%22,%22eight%22],[%22two%22,%22eight%22],[%22one%22,%22eight%22],[%22two%22,%22eight%22],[%22four%22,%22five%22]]%0A[[%22one%22,%22four%22,%22one%22,%22four%22,%22two%22],[%22one%22,%22three%22,%22five%22,%22six%22,%22two%22],[%22three%22,%22seven%22,%22three%22,%22zero%22,%22nine%22]]%0A[[%22zero%22,%22six%22,%22one%22],[%22eight%22,%22zero%22,%22three%22],[%22three%22,%22nine%22,%22eight%22],[%22eight%22,%22seven%22,%22four%22],[%22nine%22,%22eight%22,%22nine%22],[%22four%22,%22eight%22,%22four%22]]&a=1&m=2)
This program takes arrays of lowercase spelled digits for input. The output is newline-separated like so.
```
one five nine
two six five
three one four
three five eight
```
This program sorts the inputs using the ordering obtained under a specific transformation. Each character in each word is replaced by its index in the string `"wo thif sen"`. The original arrays are sorted by this ordering. Then the results are printed after joining with a space.
The spaces serve no purpose, but actually allow greater compression in the string literal.
[Answer]
# [Python](https://docs.python.org/3/), 62 bytes
```
lambda m:sorted(m,key=lambda r:[int(s,36)%6779%531for s in r])
```
**[Try it online!](https://tio.run/##TYzLCsMgEEV/ZRACCm6KNKGBfIl1kRKt0kbDaB/5eps3Xc3lnHtnGJMNXmTTXPOz7W9dC30dAybd0Z4/9NhsFGvpfKKRi5IVZVVdirM4mYAQwXlAxfKAc8FQKYEki1oT4ECCn@4cTHjhlBQHudMFu/da9G5hq0@fsPnovuSvuPvj/7HX7m4TAaUYyz8 "Python 3 – Try It Online")** ...or see the [test-suite](https://tio.run/##hVBJbsMgFN33FAgpipHYVFYT1VJOQli4yneMGoMFxG16eZfZpJtuQG/47w/zw45KtutwOq@3fvq49GjqjNIWLs1EP@FxSqzumJC2MbQ9kN3heHzfvbWvg9LIICGR5mT1wIKxHsPS3xoh57ttCOle0Kx9sVdJBvurWMDsCx6iXDBZGWPYjhoAU6ykfwd115hTlqFLcJ8UDnnWfikHjfjOWiBTQjKDuI4Wc6cUPywgq9TkKHkb/k8P4@XWoUM1Nn0GvnbL/DNkXCFbshgH3cw/oFVZP7RLTCxX6SpxvmKP1XVuCKj3yBW5YTn7k7M6fNop89HP@S8 "Python 3 – Try It Online")
Note:
```
lambda m:sorted(m,key=lambda r:[map("trfsen".find,s)for s in r])
```
which works in Python 2 (but not 3) is longer by two bytes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
OḌ%⁽Т%147µÞ
```
A monadic link.
**[Try it online!](https://tio.run/##y0rNyan8/9//4Y4e1UeNew9POLRI1dDE/NDWw/P@H273ftS0JvL//@hoBaWSjKLUVCUFHQWl/DwgDWKk5ZcWAVmxOlwK0TBhsHhmGURlXiZYDKqgpDwfqqA4s0IJSSVcAdwKuAmpmekZJUoKsbEA "Jelly – Try It Online")** ...or see the [test-suite](https://tio.run/##jZC/DoIwEMZ3n6JpwtbFxMSHcHA2DWMViIEEEP9suLA4@AQOzq4aFx3gSeRFKr3roXVyanv3@77vrpFaLrdaT1/3g9eWj@ZYn73haFxfm5Nuqkm7v8wGTdUdUVs@61t901pKyXgepEpxJhhP4u40l3mySrubLwaMSapDIywQjUOoEZGvE0tk4YZ/oR@iT@k9VLgIcs58g0gJHoJnqlAxRxUEC8vZElJO6T8KdhKYTpGotB3nYQwce5zf6gWs6VDUx/k//E6lZhT4L4q1NfQw9tYD5@01aPHjD0Y/q5GOsmEH23N4msP5EWqhyvff "Jelly – Try It Online")
### How?
Converting the digits to ordinals and then from base 10 then taking modulos by 4752 then 147 gives an ascending order:
```
zero , one , two , three , four
[122,101,114,111],[111,110,101],[116,119,111],[116,104,114,101,101],[102,111,117,114]
133351 , 12301 , 12901 , 1276511 , 114384
295 , 2797 , 3397 , 2975 , 336
1 , 4 , 16 , 35 , 42
five , six , seven , eight , nine
[102,105,118,101],[115,105,120],[115,101,118,101,110],[101,105,103,104,116],[110,105,110,101]
113781 , 12670 , 1263920 , 1126456 , 121701
4485 , 3166 , 4640 , 232 , 2901
75 , 79 , 83 , 85 , 108
```
This can then be used as a key function by which to sort:
```
OḌ%⁽Т%147µÞ - Link: list of lists of lists of characters
µÞ - sort (Þ) by the mondadic chain to the left (µ):
O - ordinals of the characters
Ḍ - convert from base 10
⁽Т - literal 4752
% - modulo
%147 - modulo by 147
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 12 bytes
```
'nesft'∘⍒⌷¨⊂
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Ckel5qcVqJ@qOOGY96Jz3q2X5oxaOupv//H7VNBMpOBCIN9ZKMotRUdQX1/DwQmZZfWqSuqQHjZZaBqLxMIA8oWFKeD@QVZ1bApDQR2qFKUzPTM0rUNblsuVDsgGhMLUvNQxgOVQqThXPxy4IdCLMezRokLyigckCGwI1GczLEP1AVMDmIWxFqq1KL8uEhgWYtVA5iTj4kqCDuheuDGINkPtggJG/B1MPshcUDijpETEC9BROGqAYA "APL (Dyalog Classic) – Try It Online")
This is how I found a suitable left argument for dyadic `⍒` (I tried `⍋` and length 6 first):
```
A←⊖a←↑'zero' 'one' 'two' 'three' 'four' 'five' 'six' 'seven' 'eight' 'nine'
{(a≡a[⍵⍒a;])∧A≡a[⍵⍒A;]:⎕←⍵}¨,⊃∘.,/5⍴⊂∪∊a
```
[Answer]
# Ruby, 48 bytes
```
->x{x.sort_by{|y|y.map{|s|s.to_i(35)**2%47394}}}
```
Abuses the fact that `"zero".to_i(35)` is 0 (since 'z' isn't a valid digit in base 35), so it's that much easier to brute-force a formula for the other nine digits.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 47 bytes
```
->x{x.sort_by{|y|y.map{|s|s.to_i(32)%774%538}}}
```
**[Try it online!](https://tio.run/##TY7RCoMgFIbvfYqDEGzQulgb7aa9iEgsyOVFGmqboj67q9ZiV@fn4@P/j5pal1idTnfrbaGlMk3rfHDBFcNj9EEHXRjZ8EN5PmZVdcmu5S3GmMQ0aKiBEMCmV12HIQcsxXyXwOSk5kRzBOSHV85fX1PwlW2CectN0NziP3MX9om9oePP3mCgFKERGFn@oekD "Ruby – Try It Online")**
Utilises the fact that using a base less than the maximum digit yields a result of zero (as pointed out by histocrat in [their answer](https://codegolf.stackexchange.com/a/161697/53748))
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~14~~ 18 bytes
```
{x@<"tfsen"?/:/:x}
```
[Try it online!](https://tio.run/##jVFLDoMgEN17CjMrWTTusUl7GVDSBBKl1rTp2RGcGYSuutHw5v0GHhc72hC0/Gz3K3i9KAu3XvZy@wbddeCnWSkYwNn01e45g2jatmPArOlnTTwh7l8uAovZeEow@ZBAmXHyIERzZKBErTG7NCdSYVsi/3COvtwDw4pFhvqQ5KX1T2Vc6STxGHuf9LeaXb4SzCQIHVy@KmyaFWhQmx8u9U6s4tziTSp29Sq0Ik9QI8IO "K (ngn/k) – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), 37 bytes
```
*.sort:{('digit 'X~$_)».parse-names}
```
[Try it](https://tio.run/##nVRLboMwEN1zihGqmtBCKnWRRaJUHKDLLiohVEVhklgiGNmGJo3Si3XXi1GDbX5KQtuN0fzeezN4nCKLp0XGEfLpZDW3rN0Bblc0QlgUdxNOmZgdx6OIbIiA0evnzZvz/TVJl4yjlyx3yE@FLPAFcgELGFsAQWCLLUO0XZsm5bmmGbNDNzAmyctPQqRVesU7lSYnexOrnBpBJyPZbIUdhq7C/wdQT8pFfN2AgsIck5ZynVVTNfZQvOI1qrpdDIE0IvqgQySdWalYxyjrG97eRNQYTYoJKjFN8gcyWv@Cbl9X8YZF/ZZRUWqvIqH6PqjJ1CUKoY1dgbQnaCoMaX1dOpmtK6dFG7/KN3M4K@oi91moa138TawU5cjlLvf8Re7q3ErjZQL3anEf4FHG1pTpRfaewCdJmgkXfNynuBIYwVF2RbgXIabxAcoXYqyS5HvwTLioDqdV0fbPrVPxAw "Perl 6 – Try It Online")
## Expanded:
```
*\ # WhateverCode lambda (this is the parameter)
.sort:
{ # block with implicit parameter 「$_」
(
'digit ' X~ $_ # concatenate 'digit ' to each named digit
)».parse-names # call .parse-names on each
}
```
The code block will take a value of the form `("three","one","four")` and translate it to `("3","1","4")` which is a value that `.sort` can easily use.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 38 bytes
```
{⍵[⍋(531∘⊥⍤1)(531|6779|36⊥9+⎕A⍳⊢)¨↑⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71box/1dmuYGhs@6pjxqGvpo94lhpogbo2ZublljbEZUMxS@1HfVMdHvZsfdS3SPLTiUdtEoLbY2v//gaw0BQ31EI8gV1d1BXV/PxDp5h8apK4JFIZyPcNAlJ8nkAcSDQn3B3KDPSNgcppIJkAVu3q6e4Soa3Kp26pzweyAaHMNc/VDMhyqEC6P4BOSB7sS5gJki5A8oYDKARmBMBrNyRAPwZTAJCHuRSiOcg3yhwcGsq1QCYgp/tCggrgWrgtiCLLxYHOQfQXTAbMXHhcoKpFiA@o1mDhEPQA)
Based of Jonathan Allan's [awesome solution](https://codegolf.stackexchange.com/a/161684/65326).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~85~~ ~~81~~ 80 bytes
Simply uses the first two letters of each word to determine the number, then sorts each list using that indexing function as the key.
```
lambda _:sorted(_,key=lambda L:['zeontwthfofisiseeini'.find(s[:2])/2for s in L])
```
[**Try it online!**](https://tio.run/##hVHLboMwEDyXr7C4BCTUqhyRckxPkfoBrhXRsi6rpDayNyHk5ylgm0cvvdja2ZnZWbvpqNYq7@X@o7@UP59VyU6F1YagSk7ZGbq9R48F3z1AK2qpllqiRQuACnfPElWVWF7kIn3JpTbMMlTsKNKeTFdET22NF2CvRWNQEZMJquZKSZpGcP@Chtjh/e1gjDYDtSmt7TmPqTYAcRZrNZ5SX00sMsZDjbfxUjhUE0ytHmqL99B0qDfxdMDvmmIhIj4L4AZqbewpi@UK@J8xxQwBpjGr@Nm2GMUr2z9R3SYzJ3Rd3oX9AKPnd5gGesTpdXgel3HmO/nGebLYLBM0YebyBxvu@hf8aqHhFOIX "Python 2 – Try It Online")
*Saved 4 bytes, thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)*
[Answer]
# [JavaScript (Node.js)](https://nodejs.org/en/), 70 bytes
```
a=>a.sort((a,b)=>(g=a=>a.map(c=>99+parseInt(2+c,34)%607%292))(a)>g(b))
```
[Try it online!](https://tio.run/##hVFLbsMgEN33GEiRQKFR5FStvMD7nsHygjhjhyphLKBu1Mu7tgGbtJG6Ac3Mm/eBD9lLWxvVuWeNJxgaMUhRyJ1F4yiV/MhEQVsx966yo7Uo8nzbSWPhXTuabWt@eGGb1/3bJsszxqhkRUuPjA01aosX2F2wpQ0tS@LOBoBwgno6G/w0pOJlLFU/XVqN1dR1XziWVt3ibG4GhgAG1Z4dqSrGnv6K@X3oQScqYWPhX@v/5rPdaOWhYhKL3xcT16rxK4SPGCFx6I2v4G8wuDzPQ/mA8HQYXtH7X9Y9W6ozE6Y540Y0sHzTHTL5qJAx9j1@dDj8AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 49 bytes
```
->x{x.sort_by{|y|y.map{|s|s.to_i(36)**4%463595}}}
```
[Try it online!](https://tio.run/##TY7LCoMwEEX3fsUQKLRis/EBXdgfCUEqJDULjeTRGozfnqq1oau5HA73jrKtC7wO1/s0T1hLZZrWzd55h/vHOHvtNTayEee8uqRpcSqqvLyVy7KEwfYaaiAEkOkUYwgyQHJY7xa4tGpNNEuA/PDOxetrDmJnh2De8hC0mNCfGYU4ERuYeHYGAaVJMgIn2z80fAA "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 27 bytes
```
Σ“¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š“#skJ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3OJHDXMOLTw8/VHTmkNbHzXMetSw6FHDvMNrHzUsOLzmdNvhjqOTji48vP7Q/qM7Dq0/tPToAqB65eJsr///o6OVSjKKUlOVdJTy80BkWn5pkVKsTjSMm1kGovIygTyQaEl5PpBbnFkBkwMLQk2AKk7NTM8oUYqNBQA "05AB1E – Try It Online")
---
```
Σ # Sort input by...
“¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š“ # "zero one two three four five size seven eight nine"
# # Split on spaces.
sk # Find index of each input...
J # Join up.
```
[Answer]
# [Haskell](https://www.haskell.org/), 133 122 109 107 106 bytes
```
import Data.List
sortOn$abs.read.(>>=show.head.(`elemIndices`words"ze on tw th fo fi si se ei ni").take 2)
```
Ungolfed:
```
import Data.List
nums = ["ze","on","tw","th","fo","fi","si","se","ei","ni"]
lookup' :: Eq a => a -> [a] -> Int
lookup' v = head . elemIndices v
wordToInt :: String -> Int
wordToInt (x:y:_) = lookup' [x,y] nums
wordsToInt :: [String] -> Int
wordsToInt = read . concatMap (show . wordToInt)
sortN :: [[String]] -> [[String]]
sortN = sortOn wordsToInt
```
[Answer]
# [Python 2](https://docs.python.org/2/), 59 bytes
```
lambda m:sorted(m,key=lambda r:[hash(s)%2249518for s in r])
```
[Try it online!](https://tio.run/##TYzbCgIhFEV/5SAECr4kBTUwX2I@GKMppQ5Hu8zX2zQ3ejqbtfY@/VBciqLa9lIfOlw7DaHJCYvpaOB3M7QLxUY6nR3NbCfE4Xzcn2xCyOAjoGK1Rx8LtVRKIMWhMQQ4kBTH@ws2PXFMioNc6YT9ay5GP7HZl3dafPYf8ldc/fZ/2xt/c4WAUozVLw "Python 2 – Try It Online")
Riffing on [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)'s Python 3 solution...
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 132 bytes
```
l->{l.sort((a,b)->s(a)-s(b));}
int s(String[]a){int v=0;for(var s:a)v=v*99+"zeontwthfofisiseini".indexOf(s.substring(0,2));return v;}
```
[Try it online!](https://tio.run/##rVPBbtswDL33KwifpC4Rit0aNwGGXjfs0OOwg@LQiVJbMkTaaRf42zNJdp0OWXqqDFgS3@MjKVF73en5fvN8MnXjPMM@7FXLplK3@c2FrWxtwcbZ/4LEHnUdoaLSRPBDGwvHGwjj0Vlqa/QP3w3xwxN7Y7e/fq9WUMLyVM1Xx@AdxITQs7Wcr0hoOSexljLvc2MZSLz5aHmMhm55l5fOi057oIWW3bK7vb//kv1BZ/nAu9KVhgyhsSZTxm7w5WcpSFG7piQk7mZfg7pHbr2FLu9PeUi0adeVKYBYc5g6ZzZQhyKm4KD9luRYk8VDKlFI5dvwjwL9WSR5J2Dkv4nEDxiJCZYjFMd5BZDxziOCswila32mqKkMiwwyOXtPSwTTIVhj8SqLDw7IvCTmdVKKmMTQbHf8njjx@tmVdGME7NB@mOmF7kWWHzM@QyMe58VBnOsbV32eFqHBIHVYvK3FcGdyqvzfVk5oNIVL/ea9fiWlKe5FBGQ@OpVKFwU2gzXCE/L0Soy1ci2rJmhyZSfO@LJCo9W6EYP6YsFuCC5V4aoKCxaPw@w8KXYptpSjfp@asz/9BQ "Java (JDK 10) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 103 bytes
```
sub c{pop=~s%(..)\w+\s*%zeontwthfofisiseeini=~/$1/;$`=~y///c/2%ger}say s/\R//gr for sort{c($a)<=>c$b}<>
```
[Try it online!](https://tio.run/##TYvJCsJAEETv@Yo@JOCCaRU8mfgHXjznoIaepEGmw/RoXDCf7rgF8VJQVe815A6LEPS4h/LWSJN3mgzSdFi040JHyZXE@tbXRgwrKxFbzjuMZ7iMt3l3QcQS50lF7q67CygWG8TKgREHKs7fykG8G2b5qoz392wVguETgfIZfO2IIrEEvpW@GTm@1J6IruQEeuADfm7iqvZf7@2AZUvRO@C3/dVWHtJ4Fqthsl6k09n0CQ "Perl 5 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 38 bytes
```
T`z\o\wit\hfsen`d
O`
T`d`z\o\wit\hfsen
```
[Try it online!](https://tio.run/##bU87DsMgDN19j0oduAGH6NCMDFSKU1iMRGhS5fI0PJN@pG7P7@NnZy5RbvV0vnpbB7@55NZYXJhmFj/SxdPgx1@6OiFbS8jMJgmbKT2yBYgLG4nCtqzJzPEJxqoTIsd7KASVFxakwCGh6B/XKrCBjsJ3s9ldyHzVtOpGK4WqLm@cE04koGbcsxYtKsLXk83YL1CHrsLDH01fxi06N/gC "Retina 0.8.2 – Try It Online") Link includes test suite. Works by temporarily replacing the letters `zowithfsen` with their position in that string, which allows the numbers to be sorted lexically.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ ~~28~~ 27 bytes
```
w@€“¡¦ẇṆb~ṇjṚØ%ĖġṘḥḞṾṇJḌ»µÞ
```
[Try it online!](https://tio.run/##y0rNyan8/7/c4VHTmkcNcw4tPLTs4a72hzvbkuoe7mzPerhz1uEZqkemHVn4cOeMhzuWPtwx7@HOfUAZr4c7eg7tPrT18Lz/h9u9gZoj//@PjlZQKskoSk1VUtBRUMrPA9IgRlp@aRGQFavDpRANEwaLZ5ZBVOZlgsWgCkrK86EKijMrlJBUwhXArYCbkJqZnlGihGkC2DKQSallqXlY5KtSi/JRnKAQCwA "Jelly – Try It Online")
-1 thanks to Jonathan Allan.
Finds the index of each digit in the string ‘onetwo...nine’ then sorts using this as a key function with `Þ`. Don't need to include `'zero'` at the beginning because the search for the first two characters of `'zero'` will fail and `0` will be returned instead of an index, making `'zero'` lexicographically "early".
[Answer]
# Python 3, 141 bytes
```
print(sorted(eval(input()),key=lambda l:int(''.join([str("zero one two three four five six seven eight nine".split().index(i))for i in l]))))
```
[Try it online!](https://tio.run/##NY4xDoMwDEWvYmVpIiGWbpV6kigDFaa4TR2UBAq9fGoi8GDrf1vve9ryGPhayhSJs04hZuw1Lp3XxNOctTHNG7e77z6PvgN/268ul/YViLVNOWr1wxggMEL@BshjRIQhzBEGWhASrZBwQQak55iBiVG1afIk6Ja4x1WTMUOIQEAM3hmpUqxVFaUaJWjpO1K5xp5S4DIqbnclW6SknbtqHoTjuH6gnPsD)
[Answer]
# [C (clang)](http://clang.llvm.org/), 229 bytes
```
y,j,k,t[9];char *s="zeontwthfofisiseeini";r(char **x){for(j=y=k=0;k+1<strlen(*x);k+=j,y=y*10+(strstr(s,t)-s)/2)sscanf(*x+k,"%2[^,]%*[^,]%*[,]%n",t,&j);return y;}c(*x,*y){return r(x)-r(y);}f(*x[],l){qsort(&x[0],l,sizeof(x[0]),c);}
```
[Try it online!](https://tio.run/##dVPtktogFP2fp2DYcQcUu0b902K2D5LamTQSRVNoAXfNOj67vXxEUztVJ8I55557uGI9rdtKba9PUtXtcSNW1m2k/rR7zYZIK388QEaqLUDXju3Zgbny85rXu8qgsS3wh9DKvbtdoxtppRVCKom5IVEwPtFzow3ZF11xKGb8MMm9XysUAQq2xZ51RTfOZxMCOHyIZY5OLX2ZU2vrSjUgnBwYHs3L72w9GqcnPBRmjj3vKTfCHY1CHb/UIGbjjp4TZMiJTg3pKL94n3LNWnr@bbVx5PlUzmDLrIQTNMTvKKtBeH3aiEYqgSpjqs4nrSgiJOkqSl9ua19DaZb9ggE5V6cz@zYIANRSdM78QvLMD0GiAs04kmiFWviaTDyPQnFDcDmy65HFDJ1KCQZErtppTr9ihr9gTHl2gXe20U5YV1dWpGbur2aoT@IYAPzmjeA1ffVP74SaxP@rPzpL8DcV@4XsPyupiPfOUsO8XMM5ztjtjBBMK8EafTQQMyzlm2AKpgd7965huqeA@W3QB4GQ253DF95bzntLXyHehEpuURed@vX/cB8itrr7LpJvH/KWlkFl8hrE8mEjEcEQJQk@hNHxYHf7ZbIPnC/W4dwhUSwItTc/X37LG1WxRRrgne9HGLJGJGig9/AKuJzdb6nLKfxqQ3Y@ZOeP7GLILh7Z5ZBdejZL/6kZXI3rHw "C (clang) – Try It Online")
There is no straightforward way of sending array of array of strings to C functions, so in spirit of code-golf, I have taken a minor liberty in input format.
`f()` accepts an array of pointers to strings, where each string is a number, represented by comma separated spelled-out-digits in lower-case. Additionally, it needs number of strings in array in second parameter.
I hope this is acceptable.
`f()` replaces the pointers in place in sorted order using `qsort()`.
`r()` reads input number from comma-separated number string. It only compares first two characters to identify number.
`c()` is comparison function
[Answer]
# [Ruby](https://www.ruby-lang.org/), 64 bytes
```
->a{a.sort_by{|b|b.map{|n|"zeontwthfofisiseeini".index n[0,2]}}}
```
[Try it online!](https://tio.run/##nVJbS8MwFH7frzgEBgq1iI/C9GH4IIjC8EVCkHY9XQMzKUm6i@t@e22bpu3KLupLm3P7LidRWbgt4klx8xDsAl9LZT7D7S4P89D/CtJdLnLyjVKYtUliGXPNNSIXnPhcRLgBQW@9O7bf7ws6AqCUEpMoROIRKapvLDNFmEddyFfVT/AyqrJmLctQ842r1ckGoWlGvkgMYcwrCSqK/0ANxJxgqClqDxYLVyh64pu2lquLL9VrYidraOQSTCdjCHuepnXTM@8dBhVARzzYil2la3FFq6Zr/kYl22sYWjuLeFnW7zhbn03assjmWdjttDMWog9eo/S36CYca/tqDjp7L69R7fK2v1vFUVkn2Y@CnfPxN7mMjZiPwTyBSELORZoZD3CT4txglJeSFepsaWACMa2rrMylUB@rU2Y0kEV5nRquxvqawBioG5m0QPAIZC6VKoPllsA9kOfX6dts9jR9f/kgFtJONZgjFFHxAw "Ruby – Try It Online")
A lambda accepting a 2D array of strings and returning a 2D array of strings.
Piggybacking off of [mbomb007's Python 2 answer](https://codegolf.stackexchange.com/a/161678/77973) for -26 bytes off of what I was about to post.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
µ→λf∆ċ←⁼;Ṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCteKGks67ZuKIhsSL4oaQ4oG8O+G5hCIsIiIsIltbXCJ0d29cIixcInNldmVuXCJdLFtcIm9uZVwiLFwiZWlnaHRcIl0sW1widHdvXCIsXCJlaWdodFwiXSxbXCJvbmVcIixcImVpZ2h0XCJdLFtcInR3b1wiLFwiZWlnaHRcIl0sW1wiZm91clwiLFwiZml2ZVwiXV0iXQ==)
Can be a little bit slow for serial numbers that represent larger decimal numbers, as the explanation will show. Who needs lookup strings anyway?
## Explained
```
µ→λf∆ċ←⁼;Ṅ
µ # Sort the input by:
→ # putting the item into a temporary variable (needed for scoping purposes)
λ ;Ṅ # and getting the first non-negative integer where:
f∆ċ # converting each of the digits in the number to words
←⁼ # equals the list being considered.
```
] |
[Question]
[
Here is a quick Monday morning challenge...
Write a function or program in the least number of bytes that:
* Takes as input a list of `[x,y]` coordinates
* Takes as input a list of the `[x,y]` coordinates' respective masses
* Outputs the calculated center of mass in the form of `[xBar,yBar]`.
Note:
* Input can be taken in any form, as long as an array is used.
The center of mass can be calculated by the following formula:
[](https://i.stack.imgur.com/WfhsX.png)
In plain English...
* To find `xBar`, multiply each mass by its respective x coordinate, sum the resulting list, and divide it by the sum of all masses.
* To find `yBar`, multiply each mass by its respective y coordinate, sum the resulting list, and divide it by the sum of all masses.
Trivial Python 2.7 example:
```
def center(coord, mass):
sumMass = float(reduce(lambda a, b: a+b, mass))
momentX = reduce(lambda m, x: m+x, (a*b for a, b in zip(mass, zip(*coord)[0])))
momentY = reduce(lambda m, y: m+y, (a*b for a, b in zip(mass, zip(*coord)[1])))
xBar = momentX / sumMass
yBar = momentY / sumMass
return [xBar, yBar]
```
Test Cases:
```
> center([[0, 2], [3, 4], [0, 1], [1, 1]], [2, 6, 2, 10])
[1.4, 2.0]
> center([[3, 1], [0, 0], [1, 4]], [2, 4, 1])
[1.0, 0.8571428571428571]
```
This is code-golf, so the least number of bytes wins!
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~6~~ 5 bytes
```
ys/Y*
```
Input format is a row vector with the masses, then a two-column matrix with the coordinates (in which spaces or commas are optional).
* First example:
```
[2, 6, 2, 10]
[0,2; 3,4; 0,1; 1,1]
```
* Second example:
```
[2, 4, 1]
[3,1; 0,0; 1,4]
```
[**Try it online!**](http://matl.tryitonline.net/#code=eXMvWSo&input=WzIsIDYsIDIsIDEwXQpbMCwyOyAzLDQ7IDAsMTsgMSwxXQoK)
### Explanation
Let `m` denote the vector of masses (first input) and `c` the matrix of coordinates (second input).
```
y % implicitly take two inputs. Duplicate the first.
% (Stack contains, bottom to top: m, c, m)
s % sum of m.
% (Stack: m, c, sum-of-m)
/ % divide.
% (Stack: m, c-divided-by-sum-of-m)
Y* % matrix multiplication.
% (Stack: final result)
% implicitly display
```
[Answer]
# Mathematica, 10 bytes
```
#.#2/Tr@#&
```
Example:
```
In[1]:= #.#2/Tr@#&[{2,6,2,10},{{0,2},{3,4},{0,1},{1,1}}]
Out[1]= {7/5, 2}
```
[Answer]
# Mathcad, 19 "bytes"
[](https://i.stack.imgur.com/hqXsj.jpg)
* Uses Mathcad's tables for data input
* Uses Mathcad's built-in vector scalar product for multiplying axis ordinate and mass
* Uses Mathcad's built-in summation operator for total mass
As Mathcad uses a 2D "whiteboard" and special operators (eg, summation operator, integral operator), and saves in an XML format, an actual worksheet may contain several hundred (or more) characters. For the purposes of Code Golf, I've taken a Mathcad "byte count" to be the number of characters or operators that the user must enter to create the worksheet.
The first (program) version of the challenge takes 19 "bytes" using this definition and the function version takes 41 "bytes".
[Answer]
# MATLAB / Octave, ~~18~~ 16 bytes
## Thanks to user beaker and Don Muesli for removing 2 bytes!
Given that the coordinates are in a `N x 2` matrix `x` where the first column is the X coordinate and the second column is the Y coordinate, and the masses are in a `1 x N` matrix `y` (or a row vector):
```
@(x,y)y*x/sum(y)
```
The explanation of this code is quite straight forward. This is an anonymous function that takes in the two inputs `x` and `y`. We perform the weighted summation (the numerator expression of each coordinate) in a linear algebra approach using matrix-vector multiplication. By taking the vector `y` of masses and multiplying this with the matrix of coordinates `x` by matrix-vector multiplication, you would compute the weighted sum of both coordinates individually, then we divide each of these coordinates by the sum of the masses thus finding the desired centre of mass returned as a 1 x 2 row vector for each coordinate respectively.
# Example runs
```
>> A=@(x,y)y*x/sum(y)
A =
@(x,y)y*x/sum(y)
>> x = [0 2; 3 4; 0 1; 1 1];
>> y = [2 6 2 10];
>> A(x,y)
ans =
1.4000 2.0000
>> x = [3 1; 0 0; 1 4];
>> y = [2 4 1];
>> A(x,y)
ans =
1.0000 0.8571
```
# Try it online!
<https://ideone.com/BzbQ3e>
[Answer]
## Jelly, 6 bytes
```
S÷@×"S
```
or
```
÷S$×"S
```
Input is via two command-line arguments, masses first, coordinates second.
[Try it online!](http://jelly.tryitonline.net/#code=U8O3QMOXIlM&input=&args=WzIsIDYsIDIsIDEwXQ+W1swLCAyXSwgWzMsIDRdLCBbMCwgMV0sIFsxLCAxXV0)
### Explanation
```
S Sum the masses.
x" Multiply each vector by the corresponding mass.
÷@ Divide the results by the sum of masses.
S Sum the vectors.
```
or
```
÷S$ Divide the masses by their sum.
×" Multiply each vector by the corresponding normalised mass.
S Sum the vectors.
```
[Answer]
## Julia, ~~25~~ 17 bytes
```
f(c,m)=m*c/sum(m)
```
Missed the obvious approach :/ Call like `f([3 1;0 0;1 4], [2 4 1])`.
[Answer]
## CJam, 14 bytes
```
{_:+df/.f*:.+}
```
An unnamed function with expects the list of coordinate pairs and the list of masses on the stack (in that order) and leaves the centre of mass in their place.
[Test it here.](http://cjam.aditsu.net/#code=%5B%5B0%202%5D%20%5B3%204%5D%20%5B0%201%5D%20%5B1%201%5D%5D%20%5B2%206%202%2010%5D%0A%0A%7B_%3A%2Bdf%2F.f*%3A.%2B%7D%0A%0A~p)
### Explanation
```
_ e# Duplicate list of masses.
:+d e# Get sum, convert to double.
f/ e# Divide each mass by the sum, normalising the list of masses.
.f* e# Multiply each component of each vector by the corresponding weight.
:.+ e# Element-wise sum of all weighted vectors.
```
[Answer]
# Perl 6, ~~36~~ ~~33~~ 30 bytes
```
{[Z+](@^a Z»*»@^b) X/sum @b}
```
[Answer]
## Seriously, 16 bytes
```
╩2└Σ;╛2└*/@╜2└*/
```
Takes input as `[x-coords]\n[y-coords]\n[masses]`, and outputs as `xbar\nybar`
[Try it online!](http://seriously.tryitonline.net/#code=4pWpMuKUlM6jO-KVmzLilJQqL0DilZwy4pSUKi8&input=WzAsIDMsIDAsIDFdClsyLCA0LCAxLCAxXQpbMiw2LDIsMTBd)
Explanation:
```
╩2└Σ;╛2└*/@╜2└*/
╩ push each line of input into its own numbered register
2└Σ; push 2 copies of the sum of the masses
╛2└*/ push masses and y-coords, dot product, divide by sum of masses
@ swap
╜2└*/ push masses and x-coords, dot product, divide by sum of masses
```
[Answer]
## Haskell, ~~55~~ 50 bytes
```
z=zipWith
f a=map(/sum a).foldr1(z(+)).z(map.(*))a
```
This defines a binary function `f`, used as follows:
```
> f [1,2] [[1,2],[3,4]]
[2.3333333333333335,3.333333333333333]
```
[See it pass both test cases.](http://ideone.com/Mhlu5k)
## Explanation
Haskell is not well suited for processing multidimensional lists, so I'm jumping through some hoops here.
The first line defines a short alias for `zipWith`, which we need twice.
Basically, `f` is a function that takes the list of weights `a` and produces `f a`, a function that takes the list of positions and produces the center of mass.
`f a` is a composition of three functions:
```
z(map.(*))a -- First sub-function:
z a -- Zip the list of positions with the mass list a
map.(*) -- using the function map.(*), which takes a mass m
-- and maps (*m) over the corresponding position vector
foldr1(z(+)) -- Second sub-function:
foldr1 -- Fold (reduce) the list of mass-times-position vectors
z(+) -- using element-wise addition
map(/sum a) -- Third sub-function:
map -- Map over both coordinates:
(/sum a) -- Divide by the sum of all masses
```
[Answer]
## JavaScript (ES6), 60 bytes
```
a=>a.map(([x,y,m])=>{s+=m;t+=x*m;u+=y*m},s=t=u=0)&&[t/s,u/s]
```
Accepts an array of (x, y, mass) "triples" and returns a "tuple".
[Answer]
# R, ~~32~~ 25 bytes
```
function(a,m)m%*%a/sum(m)
```
*edit -7 bytes by switch to matrix algebra (thanks @Sp3000 Julia answer)*
pass an array (matrix with 2 columns, x,y) as coordinates
and vector `m` of weights, returns an array with the required coordinates
[Answer]
## PHP, 142 bytes
```
function p($q,$d){return$q*$d;}function c($f){$s=array_sum;$m=array_map;$e=$f[0];return[$s($m(p,$e,$f[1]))/$s($e),$s($m(p,$e,$f[2]))/$s($e)];}
```
**Exploded view**
```
function p($q, $d) {
return $q * $d;
}
function c($f) {
$s = array_sum;
$m = array_map;
$e = $f[0];
return [ $s($m(p,$e,$f[1])) / $s($e),
$s($m(p,$e,$f[2])) / $s($e) ];
}
```
**Required input**
```
Array[Array]: [ [ mass1, mass2, ... ],
[ xpos1, xpos2, ... ],
[ ypos1, ypos2, ... ] ]
```
**Return**
`Array: [ xbar, ybar ]`
---
The `p()` function is a basic map, multiplying each `[m]` value with the corresponding `[x]` or `[y]` value. The `c()` function takes in the `Array[Array]`, presents the `array_sum` and `array_map` functions for space, then calculates `Σmx/Σm` and `Σmy/Σm`.
Might be possible to turn the calculation itself into a function for space, will see.
[Answer]
# Mathcad, 8 "bytes"
I don't know what I wasn't thinking of in my previous answer. Here's a shorter way making proper use of matrix multiplication. The variable p contains the data - if setting the variable counts towards the total, then add another 2 "bytes" (creation of input table = 1 byte, variable name = 1 byte).
[](https://i.stack.imgur.com/QlteY.jpg)
[Answer]
## Python 3, 63 bytes
```
lambda a,b:[sum(x*y/sum(b)for x,y in zip(L,b))for L in zip(*a)]
```
Vector operations on lists is long :/
This is an anonymous lambda function - give it a name and call like `f([[0,2],[3,4],[0,1],[1,1]],[2,6,2,10])`.
[Answer]
## Python 3, ~~95~~ ~~90~~ 88 bytes
## Solution
```
lambda c,m:list(map(sum,zip(*[[i[0]*j/sum(m),i[1]*j/sum(m)]for i,j in zip(*([c,m]))])))
```
## Results
```
>>> f([[0,2],[3,4],[0,1],[1,1]],[2,6,2,10])
[1.3999999999999999, 2.0]
>>> f([[3,1],[0,0],[1,4]],[2,4,1])
[1.0, 0.8571428571428571]
```
*thanks to @Zgarb saving 2 bytes*
---
A recursive solution for fun (95 bytes)
```
f=lambda c,m,x=0,y=0,s=0:f(c[1:],m[1:],x+c[0][0]*m[0],y+c[0][1]*m[0],s+m[0])if c else[x/s,y/s]
```
**Results**
```
>>> f([[0,2],[3,4],[0,1],[1,1]],[2,6,2,10])
[1.4, 2.0]
>>> f([[3,1],[0,0],[1,4]],[2,4,1])
[1.0, 0.8571428571428571]
```
[Answer]
# Axiom, 158 bytes
```
c(a:List List Float):List Float==(x:=y:=m:=0.;for i in 1..#a repeat(~index?(3,a.i)=>return[];x:=x+a.i.3*a.i.1;y:=y+a.i.3*a.i.2;m:=m+a.i.3);m=0.=>[];[x/m,y/m])
```
ungolf it
```
-- Input List of Coordinate and masses as [[xi,yi,mi]]
-- Return center of mass for the list a as [x,y] Float coordinates
-- or [] if some error occur [for example masses are all 0]
cc(a:List List Float):List Float==
x:=y:=m:=0.
for i in 1..#a repeat
~index?(3,a.i)=>return []
x:=x+a.i.3*a.i.1
y:=y+a.i.3*a.i.2
m:=m+a.i.3
m=0.=>return []
return[x/m,y/m]
```
results
```
(21) -> c([[0,2,2],[3,4,6],[0,1,2],[1,1,10]])
(21) [1.4,2.0]
Type: List Float
(22) -> c([[3,1,2],[0,0,4],[1,4,1]])
(22) [1.0,0.8571428571 4285714286]
Type: List Float
```
[Answer]
# k, 13 bytes
```
{(+/x*y)%+/y}
```
[Try it online!](https://tio.run/##FckxDoAgDAXQq/zF2EqUFgiDvQ8Lg6vEePaK63t9v7p7Ox8K8d4GLyGO19uxEpEgWUYxgZpC2RIqElTYiPJEgcwof5T57B8 "K (oK) – Try It Online")
] |
[Question]
[
Your task is simple. The program reads in a line of text from the standard input, and it prints out the same text in a character-reversed form. It is not allowed to print anything else.
For example:
input: "Hello!",
output: "!olleH"
**The catch is**, your program has to be able to do the exact same thing if the source code itself is character-reversed!
Scoring: standard code-golf scoring applies, with the following modification to limit the boring
```
//margorp
program//
```
style answers: any solution which is a palindrome will incur a +25% penalty to the score, rounded up. This penalty still applies, if you, for example, insert characters into the program which do not have any useful effects, just to break the palindrome.
[Answer]
## APL, 5
```
⌽⍞⍝⍞⊖
```
This reverses (`⌽`, along the last axis) the input (`⍞`), and is followed by a comment (`⍝` marks a line comment). Reversed, the program reverses (`⊖`, along the first axis) the input, and is followed by a comment. Because the input is always going to be one dimensional, in this case `⌽` and `⊖` are functionally equivalent. It is perhaps even sneakier than the GolfScript solution, so here's a cleaner solution (no comments), which scores **9**.
```
⍬,⌽,⍞,⊖,⍬
```
This first grabs an empty vector (`⍬`), flattens it (monadic `,`), and reverses it (`⊖`, along the first axis). This still leaves an empty vector. Then it concatenates (dyadic `,`) to the input (`⍞`), leaving the input untouched. It then flattens (monadic `,`) the already-flat input and reverses it (`⌽`, along the last axis). Then it concatenates (dyadic `,`) another empty vector (`⍬`) to the reversed input. This does nothing, and leaves the reversed input behind. Reversed, this program does the same thing, based again on the fact that `⌽` and `⊖` are functionally equivalent with one-dimesional arguments.
You really couldn't say I'm adding useless characters to break the palindrome (the two different reverse functions are different with two-or-more-dimensional input; I'm just taking advantage of the fact they act the same with one-dimensional input)
[Answer]
# Unix shell - 8 + 25% = 10
```
rev||ver
```
Previous answer of `cat|tac` didn't actually work, `tac` reverses the order of lines, not the order of characters in a line.
[Answer]
# Haskell, 53
```
main=niam
niam=interact reverse
esrever tcaretni=main
```
Technically not a palindrome, but, since function declaration order doesn't matter, once reversed you have exactly the same program.
[Answer]
# **Ruby, 37**
```
eval <<1.reverse#
esrever.steg stup
1
```
Reversed:
```
1
puts gets.reverse
#esrever.1<< lave
```
[Answer]
## Tcl, 78
```
puts [string rev [gets stdin]];#\
]]nidts steg[ ver gnirts[ stup;# tixe emaner
```
Not a palindrome.
[Answer]
# gs2, 2
~~(Yes, this language was made before the challenge. No, it isn't a joke or a loophole.
[ASCII space (`0x20`) is reverse](https://github.com/nooodl/gs2/blob/master/gs2.py#L398).)~~
EDIT: aw, man, this question is super old? If only I'd commited sooner. :< I'll leave this answer up just because it's too good to pass up, though.
[Answer]
### Golfscript, 9 (7 \* 1.25 = 8.75)
```
-1%#%1-
```
dirty, dirty, dirty, but extremely short. `-1%` means "select each element (character), backwards" and `#` means "line comment". The rest is just a bit of GolfScript's I/O magic.
This is the shortest "clean" (no comments) solution I've found (**14 \* 1.25 = 17.5**):
```
'';-1%..%1-;''
```
meaning: push an empty string, drop it, reverse the input, clone it twice, split it by itself (consuming two copies and producing an empty array), remove all ones from the empty array, drop the emtpy array, push an empty string and (implicitly) print the stack.
[Answer]
## Ruby, 44
```
puts gets.reverse#esrever.steg stup
```
Just a comment at the end of a normal program :P
35 characters, +25% = 44
[Answer]
## Tcl, 75.25
This time a palindrome.
```
puts [string rev [gets stdin]]]]nidts steg[ ver gnirts[ stup
```
[Answer]
# Python 3, 42
```
print(input()[::-1]);#)]1-::[)(tupni(tnirp
```
## Credits
* Initial version with score of 49 + 25% = 61.25 created by me
* Thanks to [arshajii](https://codegolf.stackexchange.com/users/6611/arshajii) for improving the score from 61.25 to 51.25
* New version with score of 42 (`:-)`) created by me
[Answer]
### [Rebmu](http://hostilefork.com/rebmu): 9 (w/penalty) or 13 (without)
The boring Rebmu solution is 9 and bears the palindromic penalty. I'll show it anyway "just because":
```
rnRVaVRnr
```
Using the [unmushing](https://github.com/hostilefork/rebmu/blob/2965e013aa6e0573caa326780d97522a425103f0/mushing.rebol#L18) trick of noticing capital runs of letters are separate words, and the lack of a leading capital run means we're not making a set-word, we produce five ordinary words:
```
rn rv a vr nr
```
Which is a shorthand for the equivalent code (also legal Rebmu):
```
return reverse a vr nr
```
The fact that vr and nr are meaningless doesn't matter, because despite not being assigned to anything they are valid words. So the evaluator only runs the `return reverse a`...it works both ways. But this is analogous in a sense to the boring cheat: the code isn't commented out, but it's dead and not executed on one path.
For something more exciting that doesn't incur the penalty, how about this 13 character solution:
```
a VR :rv AvrA
```
Let's look at how this is processed on its forward and reverse paths, when expanded. Forward:
```
a ; evaluate a, as it is a string it has no side effects
vr: :reverse ; "set" vr to mean what a "get" of reverse means now
a: vr a ; assign a to calling "vr" on a, effectively reversing
; ^-- result of assign is last expression, the answer!
```
Backwards as `ArvA vr: RV a`:
```
a: reverse a ; assign A to its reversal
vr: rv: a ; make the abbreviation vr equal to assignment of a to rv
; ^-- result of assign is last expression, the answer!
```
On the downside, the backwards variant is overwriting the abbreviation for reverse. But hey, it's not a palindrome, and it's a mere 13 characters. :-)
*(Note: This assumes you're running Rebmu in the /args mode, where a is the default argument to the program passed to the interpreter on the command line and you accept the result. If reading from standard input is actually a requirement, things grow e.g. from 9 to 11 characters for the simple solution: `rnRVrArVRnr`. And if you have to print to standard output from within the program instead of accepting the expression output of the interpreter that would add a couple characters too.)*
[Answer]
## JavaScript, 62 \* 1.25 = 78
```
i.split('').reverse().join('')//)''(nioj.)(esrever.)''(tilps.i
```
Not too creative, but the best I could come up with. (assumes that the input is stored in variable `i`)
I did get this:
## 63 chars, no palindrome
```
i.split('').reverse().join('')//)a(nioj.)(esrever.)''=a(tilps.i
```
but it felt too much like cheating. :P I could do many more trivial changes (such as using `i['split']` instead of `i.split`), but all those still feel like cheating :P
[Answer]
## Pyke, 2 (+25%), non-competing
```
_
```
Pyke takes input implicitly and outputs implicitly.
`_` is the reverse function.
[Answer]
## Tcl, 99
```
proc unknown args {puts "Hello World!"}
}"!dlroW olleH" stup{ sgra nwonknu corp
```
If a command that does not exist is called, a special `unknown` command is called that could load the command. Or do other funny stuff.
[Answer]
## T-SQL, 86\*1.25=108
Here's a boring palindromic entry for SQL Server 2008 (and newer) just to show that it's possible.
```
DECLARE @ VARCHAR(MAX)='Hi'PRINT REVERSE(@)--)@(ESREVER TNIRP''=)XAM(RAHCRAV @ ERALCED
```
@ holds the input text, the example string being "Hi". This entry's char count is for a two-char input string.
[Answer]
## [Keg](https://github.com/JonoCode9374/Keg), ceil(1+0.25)=2 bytes
```
?
```
This takes input and reverses, and implicit output outputs it literally.
[TIO](https://tio.run/##y05N///f/v9/j9ScnHwdhfL8opwURQA)
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 17 bytes
```
#[~ #<
[:!k@,v
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9Xjq5TUFBQtuFSiLZSzHbQKfv/vyS1uAQA "Befunge-98 (PyFunge) – Try It Online")
[Try it online! (Reversed)](https://tio.run/##S0pNK81LT9W1tNAtqAQz//8v03HIVrSKVuCyUVZQUKiLVv7/vyS1uAQA "Befunge-98 (PyFunge) – Try It Online")
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 14 + 25% = 18 bytes
```
;?_fA|#|Af_?;
```
Employs a palindromic source code. Using two distinct ways to do this takes somewhat longer (34 bytes):
```
;[_lA|,1,-1|Z=Z+mid$(A,a,1)#|Af_?;
```
Explanation:
```
Read the input string from the command line as A$
;
FOR len(A$); a >= 1; a--
[ Starts a FOR loop
_l...| returns the length the argument(here, A$); sets the starting point of the loop
,1 set the end point of the loop
,-1 FOR loop incrementer (or decrementer in this case)
| Ends the argument list for the FOR loop
On each FOR iteration, add the right-most character of the input to Z$
Z=Z+mid$(A,a,1)
The cheat:
# starts a string literal, hiding the flipped source.
The literal is closed implicitly at the end-of-file.
The FOR loop is closed implicitly at the end-of-file.
Z$ gets printed implicitly at the end of the program if it's non-empty
The flipped source is the same as my palindrome-code:
; reads in A$ from the cmd line
? PRINT
_fA| The reversed version of A$
# And hide the rest of our source in a literal
```
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), 7 bytes (5 + 25%)
```
@"i"@
```
**[Try it online!](https://tio.run/nexus/pushy#@@@glKnk8P//fyWP1JycfB2F8PyinBRFJQA "Pushy – TIO Nexus")**
This incurs the 25% penalty as it's a palindrome, but it's the best I could do. No matter which way around the program is run, it does these 3 commands:
```
@ \ Reverse the input
" \ Print
i \ Exit
```
Substituting `i` for `c` (clear stack) or `\` (comment) has the same effect.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 1 + 25% = 2 bytes
```
R
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/6P9/j9ScnHwdhfL8opwURQA "05AB1E – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 65 bytes
### EDIT: Ditched the 25% penalty thanks to a trivial, yet unseen to me, change by Grimy.
```
stringi::stri_reverse(scan(,""))#))'',(nacs(esrever_irts::ignirts
```
[Try it online!](https://tio.run/##HcnBCcAgDADAVdr0YQJO4ATdoE@RNoggERLp@in2d3DqblOb1JbSQlZ@WY3R7iIYAYgOohAiSrkN2f7PTael1KosOJzc@9iuof3ZwT8 "R – Try It Online")
Say hello to R's abysmal ability to handle strings, even when you use packages designed for strings like `stringi` ... **barf**
] |
[Question]
[
Given a ragged list, we can define an element's depth as the number of arrays above it, or the amount that it is nested.
For example, with the list `[[1, 2], [3, [4, 5]]]` the depth of the `2` is 2, as it is nested within two lists: The base list, and the list `[1, 2]`. The depth of the `4` is 3 as it is nested within three lists.
Your challenge is to, given a ragged list of positive integers, multiply them by their depths.
For example, given the list `[[1, 2], [3, [4, 5]], 6]`:
* The depth of 1 is 2, so double it -> 2
* The depth of 2 is also 2, so double it -> 4
* The depth of 3 is 2, so double it -> 6
* The depth of 4 is 3, so triple it -> 12
* The depth of 5 is 3, so triple it -> 15
* The depth of 6 is 1, so leave it alone -> 6
So, the result is `[[2, 4], [6, [12, 15]], 6]`.
Another way of viewing it:
```
[[1, 2], [3, [4, 5 ]], 6] - Original list
[[2, 2], [2, [3, 3 ]], 1] - Depth map
[[2, 4], [6, [12,15]], 6] - Vectorising product
```
You can assume the list won't contain empty lists.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
## Testcases
```
[[1, 2], [3, [4, 5]], 6] => [[2, 4], [6, [12, 15]], 6]
[[3, [2, 4]]] => [[6, [6, 12]]]
[[9, [[39], [4, [59]]]], 20] => [[18, [[156], [16, [295]]]], 20]
[2, [29]] => [2, [58]]
[[[[[[[[9]]]]]]]] => [[[[[[[[72]]]]]]]]
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
⁽L€*
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBUCIsIiIsIuKBvUzigqwqIiwiIiwiW1sxLCAyXSwgWzMsIFs0LCA1XV0sIDZdXG5bWzMsIFsyLCA0XV1dXG5bWzksIFtbMzldLCBbNCwgWzU5XV1dXSwgMjBdXG5bMiwgWzI5XV1cbltbW1tbW1tbOV1dXV1dXV1dIl0=)
```
⁽L€*
⁽ € # At each value in the input, all the way down, run the following on the multi-dimensional index of the current value:
L # Length. This gets the current depth
* # Vectorizically (is that a word?) multiply by the input
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 12 bytes
```
#0/@#-#&@-#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9lA30FZV1nNAYj/BxRl5pVEK@vapTkox6rVBScn5tVVc1VXG@oY1epUG@tUm@iY1tbqmNXqAAWBXCMdk9paMMdSByhgWQtSUW1qWQsSNTIAyRgBVVlC1EAAWBIEuGr/AwA "Wolfram Language (Mathematica) – Try It Online")
```
-# negate
#0/@# &@ at each level:
-# subtract original value(s)
(atoms: #0/@#-# = #-# = 0)
```
[Answer]
# [Python](https://www.python.org), ~~51~~ ~~49~~ ~~44~~ 43 bytes
```
f=lambda l,d=0:l*d*-1or[f(s,d-1)for s in l]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3tdNscxJzk1ISFXJ0UmwNrHK0UrR0DfOLotM0inVSdA010_KLFIoVMvMUcmKhWpQKijLzSjTSNKKjDXUUjGJ1FKKNgdhER8E0Fsgxi9XUhKiEWQIA)
This is a really fun abuse of the overloading of the `*` operator:
* If `l` is a positive integer, then `l*d*-1` equals `l*-d`, which is always truthy (because the integers are always positive, so non-zero), so it returns `l*-d`, where `d` is the negation of the depth.
* If `l` is an array, then `l*d` produces `d` copies of the list joined together, which is actually interpreted as 0 copies of the list joined together (because `d` is negative), i.e. `[]`. So `l*d*-1` equals equals `[]*-1` equals `[]`, which is falsy, so the second part of the conditional is run.
---
-1 bytes from @loopywalt by flipping the sign of `d`.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 17 bytes
```
{$[x~*x;0;x+o'x]}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pWia6o06qwNrCu0M5Xr4it5eJKsdIwVDCyVtAwtlYwUTDVtFYw0+TSMFIwAQqZWSsYGikYQgTr0hRSQMp1oMCSSwPGNDcCywIASXYVFQ==)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ŒJẈṁ×
```
[Try it online!](https://tio.run/##y0rNyan8///oJK@Huzoe7mw8PP3/4fajkx7unKEZ@f9/dLShjoJRrI5CtDEQm@gomMYCOWYgAbCIkY6CSWwsmGsJFrOMhaiLNrWMBUsYGcRC1EUbWUIUQgBYGgQA "Jelly – Try It Online")
```
ŒJ All multidimensional indices, in flat order.
Ẉ Get the length of each index (= depth of value at index).
ṁ Mold to the structure of the input,
√ó and multiply corresponding elements.
```
[Answer]
# BQN, 9 bytes
```
{+‚üúùïä‚çü=¬®ùï©}
```
[Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHsr4p+c8J2ViuKNnz3CqPCdlal9Cgoo4oCiU2hvdyBG4oiY4oCiSnMpwqjin6gKIltbMSwgMl0sIFszLCBbNCwgNV1dLCA2XSIKIltbMywgWzIsIDRdXV0iCiJbWzksIFtbMzldLCBbNCwgWzU5XV1dXSwgMjBdIgoiWzIsIFsyOV1dIgoiW1tbW1tbW1s5XV1dXV1dXV0iCuKfqQpA)
-5 bytes thanks to @att!
## Explanation
* `{...¬®ùï©}` for each element *n* over input...
+ `...‚çü=` if rank of *n* > 0 (i.e. *n* is a list)...
- `+‚üúùïä` *n* + F(*n*)
[Answer]
# JavaScript, 32 bytes
```
(g=k=>a=>a.map?.(g(-~k))??a*k)()
```
```
f =
(g=k=>a=>a.map?.(g(-~k))??a*k)()
testcases = `
[[1, 2], [3, [4, 5]], 6] => [[2, 4], [6, [12, 15]], 6]
[[3, [2, 4]]] => [[6, [6, 12]]]
[[9, [[39], [4, [59]]]], 20] => [[18, [[156], [16, [295]]]], 20]
[2, [29]] => [2, [58]]
[[[[[[[[9]]]]]]]] => [[[[[[[[72]]]]]]]]
`.trim().split('\n').map(l => l.split(' => ').map(t => JSON.parse(t)));
testcases.forEach(([i, e]) => {
console.log(JSON.stringify(f(i)) === JSON.stringify(e), JSON.stringify(f(i)));
});
```
The submitted function is partial invoked currying function. Maybe the first time I try to use this pattern in a code-golf.
However, the `a.map?.(…)??…` pattern is quite common for [ragged-list](/questions/tagged/ragged-list "show questions tagged 'ragged-list'").
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 51 bytes
```
\d+
$*
1(?=((\[)|(?<-2>])|(])|[^][])+)
$#3$*
1+
$.&
```
[Try it online!](https://tio.run/##JYrNCsIwEITveYqARRKbit20QqA/DzIdQdCDFw/i0XePm3RhYL@Z7/P8vt73nLdHa5qT6d06O7fB/9w6dbJQHw1uBH3rTXOIxVL3fMwZ6IMVBouoGYIdqXClQS0k2IEslJQQE3cLY9JaQS46SjFT1farY7k/ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\d+
$*
```
Convert to unary.
```
1(?=((\[)|(?<-2>])|(])|[^][])+)
$#3$*
```
Replace each `1` with the number of unmatched `]`s in the input's suffix, which equals its depth, thereby multiplying each number by its depth.
```
1+
$.&
```
Convert to decimal.
Just creating the depth map can be readily achieved with the following code:
```
\d+(?=((\[)|(?<-2>])|(])|[^][])+)
$#3
```
Retina 1 can perform multiplication as part of a substitution, solving the original problem as follows:
```
\d+(?=((\[)|(?<-2>])|(])|[^][])+)
$.($#3**
```
[Try it online!](https://tio.run/##JYrBCsIwGIPve4qCO/zdqri/m1BQ9yBZBEEPXjzIjnv3@rcLBPIl@b3Xz/c55Ly8eplvIgv8JvP1qHdaMONB0Pe@aU/SHmLX5QwMwSmDQzSPwU00uLBBLTS4kSyUjBAT9xemZLWBnm3U8kz1tquORX8 "Retina – Try It Online") Link includes test cases. Explanation: The `**` causes the capture result (the depth) to be implicitly multiplied by the matched integer, converted to unary, and the `$.(` then converts back to decimal.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 25 bytes
```
f(a)=if(#a',a+apply(f,a))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWO9M0EjVtM9M0lBPVdRK1EwsKcio10nQSNTUh8jfbIUKJCrp2CgVFmXklQKYSiKOkANKqqaMQHR1tqKNgFAtkGQOxiY6CaSyQYwYSAIsY6SiYxMaCuZZgMctYiLpoU8tYsISRQSxEXbSRJUQhBIClwQDqHJizAQ)
[Answer]
# [Racket](https://racket-lang.org/), ~~88~~ 63 bytes
```
(define(m l[d 0])(if(list? l)(map(λ(n)(m n(+ 1 d)))l)(* l d)))
```
[Try it online!](https://tio.run/##RYpBDoIwFET3nmISF/6vG6hg0pUHaf6C2GIaS2OA23kHr4QfGnVWM/Pe2N0eYV72qct3jGWQD33MgQYk51EJU@wpxWm@IjEN3ZPeL8rakOmEGp6ZFRyRtrooODhXwwjcGa5BK4KL8K4AvQwakd9hoaeV1XStVSAw1Zcate3fLdmkNbx8AA "Racket – Try It Online")
-25 from removing whitespace, ty @emanresu A!
[Answer]
# [lin](https://github.com/molarmanful/lin), 26 bytes
```
"deps1> (.+ \@ ' + ) e&".'
```
[Try it here!](https://replit.com/@molarmanful/try-lin) Uses stack as nested list.
For testing purposes (use `-i` flag when running locally):
```
[[1 2] [3 [4 5]] 6] \; '
"deps1> (.+ \@ ' + ) e&".'
```
## Explanation
Prettified:
```
( deps 1> (.+ \@ ' + ) e& ).'
```
* `(...).'` map...
+ `deps 1> (...) e&` if depth > 1 (i.e. is list)...
+ `.+ \@ ' +` recurse and vector-add to current element
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
_"Ddië®δ.V>"©.V*
```
[Try it online](https://tio.run/##yy9OTMpM/f8/XsklJfPw6kPrzm3RC7NTOrRSL0zr///oaEsdhehoY8tYIGUCxKaWsUCgo2BkEAsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/3gll5TMw6sPrTu3RS/MTunQSr0wrf86/6Ojow11jGJ1oo11ok10TGNjdcxidRSiQVwjHZPYWDDHUgcoYBkLUhFtahkLEjUyAMkYAVVZQtRAAFgSDAA).
**Explanation:**
First step of [this 05AB1E answer of mine](https://codegolf.stackexchange.com/a/242190/52210).
```
_ # Transform each integer in the (implicit) input to 0
"..." # Push the recursive string explained below
© # Store it in variable `®` (without popping)
.V # Evaluate and execute it as 05AB1E code
# (we now have the depth of each item in the ragged input-list)
* # Multiply each by the value in the (implicit) input-list at the same
# positions
# (after which the result is output implicitly)
D # Duplicate the current list
dië # If it's not an integer (so it's a list):
δ # Map over each item:
® .V # Do a recursive call
> # Then increase each integer in this list by 1
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~16~~ 15 bytes
```
.γd}DžuS뛒ηO*J
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f79zmlFqXo/tKg89tObTocNu57f5aXv//KykpaWhY6ihoaBhbagIpEyA2tdQEAh0FIwNNoDQA "05AB1E – Try It Online")
-2 thanks to @Kevin Cruijssen
Takes the input list as a string, using `(` and `)`.
If `a` and `b` are valid list boundaries, then it's -1 for replacing `žu` with `A`. [Try it online!](https://tio.run/##yy9OTMpM/f9f79zmlFoXx@BzWw4tOtx2bru/ltf//4mJljoKiYnGlklAygSITS2TgEBHwcggCQA)
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 33 bytes
```
s/\d+/$&*($`=~y|[||-$`=~y|]||)/ge
```
[Try it online!](https://tio.run/##PY1NCsIwEIX3PUUWRbSmTZM2sUHqDTzBGHBhEUFssW6E4NGNkx87MDDvvS8v0/C8Szcz0lcFY3u8Tpcty1fFOj/3n7cFa8t4GWs37Do4B8ApEYYSaHBbSqRBoQzpDwRAUNL6TOFyFDylGQQ8xCaxKnJcoIO5RgmNNrEVpEYbhagTzjsPcKk8wf1joeXCZL4bnVTuhexCb5zQZpa/4@zE3/2O0@s2PmZXTq48yqrm9Q8 "Perl 5 – Try It Online")
For each number, depth is determined by counting the number of `[` and subtracting the number of `]` that come before it in the string.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 38 bytes
```
f=->a,d=0{a*0==0?a*d:a.map{f[_1,d+1]}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN9XSbHXtEnVSbA2qE7UMbG0N7BO1UqwS9XITC6rTouMNdVK0DWNrayGq9xYopEVHRxvqKBjF6ihEGwOxiY6CaSyQYxYbC1EDMxkA)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 38 bytes
```
f=->a,i=1{a.map{f[_1,i+1]rescue _1*i}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PZBBCsJADEX3PUVAcKGjmNGpnUW9SAhSpcUuhFLtQkpP4qYLPZTH8AYmndpAFj95_w-T56tuTo--fzf3YpV85kW6OmSmTLHN1tesags6oimXyHV-Ozc5HHFRdt1IfykiQgOWDdBWemfAsYiYzQzSAxBZAzvdxtIoAse9GNUwrHmi40CilZkQXiRtPYdkcp6VBbuZDJgogi5WBtVuvZuoSPNlMj2g0iVDdqghUWvMC7W3_3HE6zw7X9oK9BA8fvx_rh8)
An alternative to [Razetime's answer](https://codegolf.stackexchange.com/a/250330/78274) for the same byte count.
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), ~~124~~ 118 bytes
```
;=p++=o""=i=d 0P;W<=i+1iLp;=n=cGp i 1I>c"9";=d-d-1*2<c"]"=o+o cI<"/"c;W&<=tGp+1i 1"["<"/"t;=i+1i=n+n t=o+o*d n=o+o cOo
```
[Try it online!](https://tio.run/##rVlRU9tIEn62f8WgFLYky0ESbNXGskyRLFDUEchCcnkwviBkGVQrSzpZhuUI@eu57p4ZaWSb3OVuqYplzXT3fP1NT3ePE/Zvw/D7qzgNk@U0Gi7KaZy9vhu11ZEkvmkMheVjHq0IFXF62xgq4zmXmUazOI1YkrAkS2/po12Nfjz79J459evlxwvm1q9/P7hge/Xr0dk79mv9evGJObXw0emlInv26VQR/XT2/uDyb/rCYDp@dNg35xejmj24hGX5ZHgXFMw0agVVCrBWJkYjtlfPnR1@xskUJsmjrwy/D4crMrgMyaCbIJMkBgo2ZN6en5@SEH7sk5MD9E0BcnHMBUBfwXofJMvIMMbpxGi3yQ/YlfHEv9AOz4/0756f93p@pml@7E@Z/cH7PPTjnhOf5p6f@uFxzmLmnIxC7Y3m@dP@tO@Y7jDUJpqf9TIWngy1HS30PneGfnmcgx5ztLGGg6VHdvy0l7IShc0pS7nSefbdgMU1j@MxAVAUzJmPyLx2G@DnQbGIdIM9tVtxWrLYa7dglFyxmDlbpiGMkHII7@U8txZ5OnYn/pNt2c9goxWDOZKHp40DOztoPs7Zw11cRos8CKN2C74nkQ7joK5zGBbTrsqr9Gp2VbCn5/FENwavNIOgtOIZ0yu0Puu@6hqMm5CjWzB6lcJwr8dHAGcrShaROvDM4YR3UfgHm2UFS5fzm6hYCDxMjxfT@DYupVVYHd1xrMoj/jSZY7MeMwXyXs9gfda1u7AEIo0NVkTlskiZDD6uRvHnrWK4D4o4uEkiiQJAJNlDVOghrCeBsK9fmQQX0ltIRHzpGoKeeIPrse9YsEd@NbyCDo@zCHsQSafLXMctZYLTPoO3dcA8uSy4NQ7jqtutMWldvmmgDB5UoBgYgWQE3wFZHixKVt5FYCwoShAWG2BKRnFDQwM9kWCVM/oiWPh0DNroVk0GwcfQLeMsBdgYsfYEoIWSkcUyz5FwQ0aVHFHpV@MPaFfIRhsylPMU4hgSI0auQM5Z@ditsgcfOMIBTJIDTI4IUwYZ5VXuqo64EWqQJFmo79mWY6CDOFw5QQ6myyQJikfV0Xp/LpTt@dCtkNGCQn@ZrmjTEg4uIZLCJk8PDt@@u/596/S382@Kx6rdm3ijYXfd8FbD8vHJ5QsWy6ggk0E6Zf9cBvIVzd6rS@yuL8EZOO5WZJxsIIOU95rKTZlnypXFMsUt8kR2N8tsoctkSScAYruMQ0azN8vZ2N2bCBx8pzuUHyoAixzOVTnTQRT8306SqSYTD1U3C42sGoBTURngdZOv35AbMme36Sc6j8G4z7SyWEYaBGE1jjEJ47MAUghOaBhaWk0C@om@iwJHdHx5m2UJzNw0GXjR19qtHzlk/rxHKsybNZgJYkz/UowQtGWWJLoK1WK2BSXif4CcrkHGMvz@4MOZhcWYBxq8nowd27YhnMAVeJVvi/hf0ZeS4cNTYlTxFhmANws/XPrc9R1Z0zHFYVnHB326/LELAkcnp4cmm0F29FpVaIv1MA@HQW4lUUotgMKV7L84Z3DuXiJjVRGLE9Y2rDh6TM0EFOMhceFBVYlxssob4Txf2QEiKZ7UKQRpiie4zOIhLsM73QRm1to14IiJvxALVfegO2C4ChfwkVBs@CANGx1ySpgXLWcjZA2PynAtQX1tWWDtotZ2PDGe6jCDDoqSO1/4AhZu2i4g4@lGx/5zhn@15AeQBKuco9uoTKAr1Tu0lx3cIayR0zg1vHim67Sf2BGEdwVisSBODYNvs297G7HCw6A@gK93yNfjrSNmA0GIJ/EiSSJ31ijf1v5w@WrmXT2DmirFlcw1yGA0QPz5eZZHqa4sbGmFRr0CoPLnvFRCPPquvfcrjYvuQuctyQygT9Ep6OEgZC1s8EAcmgd6wzVgaRleOgyynk@9EJ5YkDQE3WCH1iKq0YLpM1dtWmoaa09@B0@iP6GPw9O@5udWY9fp8rGFmWxN8HQtPGCVpMmLIv5tTby/cf3fugPRUG4I@CpDikqlnVH/rGOtMmSxGo32jLoDXUubUvWSukh9e4GKzUOzrgy0Q4@krgsZ19BqUTmBZSgKUmH2pVInapu6UyIHCRbOaxbwAPEbEpLL971BMet06GbX76PohPfDV9SXtySs7dfmAvDo8GYweSQLBf6yXMgoqWKHN4UcUK8CRPkU8iqmbgxBZXt4291qbjO/JqM0XBCY3HOX7zk2ynRo@AaQFA5jNvCll66xOaTDoJQP0Z46vZomQ35HWwa0rRY9S5FLhF/9tbBUohJ7@iZermTWu7OBhdUyvoEHc40Hvq@bWJhvcM0kGV81QgpQq3TKpH73Cm6DKOT1@2RPEEWldXWjOaNlI0vs/JCYnc3EbP9QaXuz0j@IzYZD/I5BY67qpSdo56z7rO9ULJMsUO/AOes7cMYcVdj9SekhpNGGrO@jKK07kCO2pJyIdke24No1qK0xfeK/vXogaJJcgbsEJWIsRfAdrxZ3URF1FyzNoNeOkzJO2UPwCLyxaQaX1zK6jQrQybM0Sss4wNsGnOSMPUTsLriPQFAYQvGSzYN0CeHz@BpH0bsbZByoICYWy6TEXxdo8SrhSZG@KiOXXKFM1atEVsyjvZcl7ZeBVGLDhpRNF/kgwRr6CF6n0ySasusa9nVl5Qm/8QZOWaR2ZoTG@n35bpB4S4iaCvTnKg8OKVhXCiQmvUZe9JtZcZ@ph3@oHgNUHYgfADuMC@yzRkNJgxZTsiHasLmmLM0urwMou@VDtVG6pREcSgytbJoN2DyahzmGWcpG1/v/ryujv8CVkXRla4MvvvBFuLL/Mvt81Q2QcXqfNQTcSsKVBXRrE876pXJPZh7VQAWvU6c/9GVTbdhXNUUqqfS//jf6IgcpZip9rztQpRvt8KqsX2fd5vRPX3hkD1zfeFCu1bj1VKmQZNDixG9oK2kSNVCi16vUOOTP4B7/eUxtSBveMbV3EWonze4eRRX9fXewq9ByzK8WvtJh9dQCtH6XSsUFxarOwm6j8b3kRK8Y9VZLnrup5O0aVR/gVtp7NPgfGiIEhk/cirC6JFTtkNobueAhrtpzsEmiBoHHP5@kB0n0xEmA1afRLIAkCZ7JDjNOYTKe0o9NQVhCmepuh13sOXHEYC/cdtFYVQOhGxQ/OMyDOMVmlQXFbWiRUdOE7/cG/qxF91D8/yTdJjTN697z9/H4jcXG4903E3jswb9f3kzgz2KuPfk3 "C (gcc) – Try It Online")
Nice, big ole fat Knight program. Parses it as a string lol
Ungolfed and commented:
```
; = p + + = o "" = i = d 0 PROMPT # p = (o = "") + (i = d = 0) + input()
; W < = i + 1 i LENGTH p # while (i = i + 1) < len(p):
; = n = c GET p i 1 # n = c = p[i]
: IF > c "9" # if c > "9":
; = d - d - 1 * 2 < c "]" # d = d - (1 - 2 * (c < "["))
: = o + o c # o = o + c
# ELSE # else:
: IF < "/" c # if "/" < c:
; WHILE & < = t GET p + 1 i 1 "[" < "/" t # while ((t = p[i + 1]) < "[") and ("/" < t):
; = i + 1 i # i = i + 1
: = n + n t # n = n + t
: = o + o * d n # o = o + d * n
# ELSE # else:
: = o + o c # o = o + c
: OUTPUT o # print(o)
```
-6 bytes thanks to Adam.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
⊞υ⟦¹θ⟧FυUM⊟ι⎇⁺⟦⟧κ∧⊞Oυ⟦⊕Σικ⟧κ×Σικ⭆¹θ
```
[Try it online!](https://tio.run/##LY49C8IwEIZ3f0XGC0TwcyhO0slBDLRbyBDaaEubpF4TwV8fr@rBcfDwflzTGWyCGXOWae4gCaa2gj01P63uARkkzq5mKoNzxrcgwwQ9F6y26A2@QY5pBqUFGwieFwGF3CaLJgb8hl18g9ZZH20LVXLkJuWg@c9S987Of74QTrUSex@hinQeVA3LO8RzVkoVlKj2BRWqA@2x0DSC7TZa5/Vr/AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ⟦¹θ⟧
```
Start by considering the input list at depth `1`.
```
Fυ
```
Loop through the list and its sublists.
```
UM⊟ι
```
Loop through the elements of the current list.
```
⎇⁺⟦⟧κ
```
If this is a sublist, then...
```
∧⊞Oυ⟦⊕Σικ⟧κ
```
... push it with the incremented depth to the list of sublists, but don't actually change the list itself yet, otherwise...
```
×Σικ
```
... multiply the element by the current depth.
```
⭆¹θ
```
Pretty-print the result, since Charcoal's default formatting is not designed for ragged lists.
[Answer]
# [J](https://www.jsoftware.com), 12 bytes
Takes input as a boxed array.
```
*L:0#L:1@{::
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxRsvHykDZx8rQodrKCiJ085EmF1dqcka-QpqChoYNEBlq6mjYGGlqgigg1xhKm4BoU01NiISZpiaqLpgyIxBtAlaGpsISqgKk2BJuvAmUNrXUhAGQ9QYouo1ghltiGouJECZBAcSnCxZAaAA)
`{::` Map; replaces each leaf by its multidimensional index.
`#L:1` At level 1 (for each index vector), take the length.
`*L:0` multiply with input at level 0 (leafs).
[Answer]
# [jq](https://stedolan.github.io/jq/), 31 bytes
```
def f(n):map(f(n+1))?//.*n;f(0)
```
[Try it online!](https://tio.run/##JYrLDsIgEEX3fsUsQaEP2ppQF37IZBZNlUSTAkb6@@JAbzLJnHvP@5Pz4@nACS/nbYmCn0sv5b1tm7O/OdHJnBF7BYYU4MA3KpiI4UonrIVRMBIVskw4WDosnCzXDKbj0RTTVu1IHUt@IaZX8N@s9Rq2uKxJhz3FPf0B "jq – Try It Online")
The key to the base case: If `map()` fails (since we try to map over a number instead of an array), `?` suppresses the error, `//` substitutes the alternate value of `.*n`
[Answer]
brev, 46 bytes
```
(c(fn(if(list? y)(map(c f(+ x 1))y)(* y x)))0)
```
Classic lispy depth first tree walking: map if not atom
] |
[Question]
[
This is similar to [Making an acronym](https://codegolf.stackexchange.com/questions/75448/making-an-acronym), but there are several key differences, including the method of fetching the acronym, and this challenge including flexible output.
## Task
Given a string (list of chars/length 1 strings is allowed) containing only printable ASCII, output all capital letters in the input that are either preceded by a space or a dash, or are the first character in the input. Empty string is undefined behavior.
## Test Cases:
Output may be in the format of `"TEST"`, `["T","E","S","T"]`, or whatever else works for you.
```
Self-contained Underwater Breathing Apparatus
SUBA
a Programming Language
PL
NATO Atlantic TREATY Organization
NATO
DEFCON 2
D
hello, world!
light-Emitting dioDe
E
What Does the Fox Say?
WDFS
3D mov-Ies
I
laugh-Out Lou-D
OLD
Best friends FOREVE-r
BF
--
<space>
-- --a - - --
-- -- - - -- A
A
Step-Hen@Gmail-Mail Mail.CoM m
SHMM
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 7 bytes
```
ÍÕü¼À!õ
```
[Try it online!](https://tio.run/##NYwxTsNAFET7PcWkZxs4AHKwLSFFMUoMiPIr/tldab0brb8ToOIClByFLhV7MBNL0MybN8Ucpyl/5q98/jnnj0X@nqYt@73exSDkAnd4DB2nEwknLBOTWBcMisOBEsk4KMJDiiZR38/7ioIZybBaF22DQjwFcTu0m6poX9AkQ8G9k7gYVFnVd80a18qy9/EKp5h8t1DeGSu66p3IfNi5WLJ6tiQoIw8Qy6jjK7b0dqtuSvTxqO95UJ5GY3UzClZx1KVa8iDYJ8ehG1A3m@qp0klprXAJQGvCjEv5839F8Qs "V – Try It Online")
Here is a hexdump to prove the byte count:
```
00000000: cdd5 fcbc c021 f5 .....!.
```
Explanation:
```
Í " Search and replace all occurrences on all lines:
" (Search for)
Õ " A non-uppercase letter [^A-Z]
ü " OR
õ " An uppercase letter
À! " Not preceded by...
¼ " A word-boundary
" (implicitly) And replace it with:
" Nothing
```
This is short all thanks to V's wonderful [regex compression](https://github.com/DJMcMayhem/V/wiki/Regexes).
[Answer]
# [R](https://www.r-project.org/), ~~66~~ 63 bytes
```
function(s)(s=substr(strsplit(s,' |-')[[1]],1,1))[s%in%LETTERS]
```
[Try it online!](https://tio.run/##PY7BasMwEER/ZS/BNliHtOdQnFqBQoiL7baUkMPWlmWBLBlp1TSl/@7Kh/aw7OybZRi3DLtlCKYjZU3qs9TvfPjw5NI4ftaKUp8n8MOS7HzeXi75Nt9m2dlvlNkcedvyurksHudZ39IuTRqhB9ZZQ6iM6OHF9MJdkYSDvRNIozISinlGhxR8kicIz85Kh9O0Okc0MqAU0TgVbQUFaTSkOmhrXrTvUDmJRn3j2jX@lPzwWJ3gLspRaG1zuFqn@3hqJUdifFJEa26vbLmGvo1IUFrhgUYBB/sFDd4eonFfwmQ/2ZNYO2kMcmRVIDjawMpI9sITDE4J03s4VDV/5cxFDnEYA2AMYV1R/JM/AEWS5UO2/AI "R – Try It Online")
*-3 bytes thanks to [Scarabee](https://codegolf.stackexchange.com/users/63618/scarabee)*
An anonymous function; returns the acronym as a vector `c("N","A","T","O")` which is implicitly printed.
For once, this isn't too bad in R! splits on `-` or `(space)`, takes the first element of each of those, and then returns whichever ones are capitals (`LETTERS` is an R builtin with the capital letters), in order.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~59~~ 56 bytes
-3 bytes thanks to [Lynn](https://codegolf.stackexchange.com/questions/133721/generate-an-acronym#comment328521_133726)
```
lambda s:[b for a,b in zip(' '+s,s)if'@'<b<'['>a in' -']
```
[Try it online!](https://tio.run/##NYzBbsIwEER/ZXoyqPGFI6K0oQmnikhAW1WUw4Y4iSVjR/ZGFH4@dah62Z15M5ruyq2zs6F@@h4MncuKEOaHErXzoKSEtrjpbiIgHkMSproWL2JRLsRBLCmGAlIch7EcxupB7JSp5clZJm1VhXdbKX8hVh4rr4hbbRukXUeeuA8iEZt0XyBlQ5b1Cfttnu6/UPiGrL4Ra2djJ8vXr8UGsyhbZYxLcHHeVA/RG920LPOzZh6XK@0yFfFnS4zMqQBuFdbuBzu6PsdgpQKj9lrZKmBdbPOPXPpxh/qmlUXPeHO9zCKRMh7cBSAlYXy40z/yD5CK47zz2jJCzJYiqSdhOvwC "Python 2 – Try It Online")
[Answer]
# Javascript 21 bytes
Takes a string input and outputs an array of strings containing the acronym characters
```
x=>x.match(/\b[A-Z]/g)
```
## Explanation
It's just a global regex match for word-boundary followed by a capital letter.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~21~~ 17 bytes
```
!`(?<=^| |-)[A-Z]
```
[Try it online!](https://tio.run/##K0otycxL/P9fMUHD3sY2rkahRlcz2lE3Kvb///CMxBIFl/zUYoWSjFQFt/wKheDESnsA "Retina – Try It Online")
### Explanation
Outputs the matches of the regex `(?<=^| |-)[A-Z]` in the input, one per line (`!`).
[Answer]
# Dyalog APL, ~~29~~ 23 bytes
*Bonus test case: A Programming Language (APL).*
```
'(?<=^| |-)[A-Z]'⎕S'&'⊢
```
Returns an array of chars (shows as space seperated on TIO).
[Try it online!](https://tio.run/##JYyxCsIwFEV3v@JNRof8gVICrZNYsQVRUXjYmgTSROoLWOns4CAu/oCf1h@pta7nnnvwbHhWoXGybU/N/cVGwWR6qKHm453g2z1rnu@EDVnz@HQCsIVIYxBk0JI@QrqKRLqBuJRo9Q1JO8sGnWW0VMSjQhNpKyHTLsz7Ya2QIHT5BUjlMHNXSLAK/h/0UvHYE8yd52HPBCxLJ0ssil9mjlZ6lDn7Ag)
---
### Older post, 29 bytes
```
{(⎕AV~⎕A)~⍨'(\w)\w+'⎕R'\1'⊢⍵}
```
[Try it online!](https://tio.run/##JYwxCsJAFER7T/G7NUgKTyALiZUY0aAIaT4mbhY2uxJ/iFFMaSFEbLyAlRfwQnuRGLWZ4s2bwZ1y4wqVEW27tZf7qW9vD76sv@nUtnmxflQ6UTlgHZmzaMjs9Wmb97nTgU15GAAnhZrkBsK5z8M1BLlALY9I0mjW6ywlRUqun0kiqQXE0njJr1ilSOCZZA@UJjA2B1hgNfpvsBCpGxQEE1O43o9xmOVG5Jhl35sJalGgSNgH)
**How?**
`'(\w)\w+'⎕R` - replace each cluster of alphabetic chars
`'\1'` - with its first character
`~⍨` - remove every char
`(⎕AV~⎕A)` - that is not an ASCII uppercase
[Answer]
# Python, 53 bytes
```
import re
lambda s:re.findall("(?<=[ -])[A-Z]"," "+s)
```
[Try it online!](https://tio.run/##HY/BTsMwEETvfMXiU6LGHOBWUaqUpCfUSG0BQelhqZ14JdeONhuV8vNB5jZ6M3rS9FdxMTxM7eJr8nj@NgjDnO1dS8Gg95nKlo@LA@hjfij151EVCtRsyG/o3EcWYDu1kYGAAhzUzvpWn2IQpGANvAZj@YJiGVZsURyFDsq@R0YZB1WA2pT7BkrxGIROsN/W5f4DGu4w0C8KxZBGVb1@bjZwn7Kz3scCLpG9uU3AU@dE12cSSXZDsbKJvzsUqKIdQJyFdfyBHV6XqVnZQaBlssEMsG629Vut@V@FY@d0Mwq8xFFX6jjvmYJkNFOgn9Jt4azNKM/z6Q8 "Python 3 – Try It Online")
A simple regular expression with a lookahead for space or dash. Rather than matching the start, prepend a space.
[Answer]
# C#, ~~84~~ 78 bytes
```
using System.Linq;s=>s.Where((c,i)=>c>64&c<91&(i>0?s[i-1]==32|s[i-1]==45:1>0))
```
*Saved 6 bytes thanks to [@jkelm](https://codegolf.stackexchange.com/questions/133721/generate-an-acronym/133726#comment328518_133728).*
[Try it online!](https://tio.run/##pZLfT9swEMff81fceECJVFeUH5OgTVBo0gmpI6jtqKZpDzfnmlhybGY7MLbxt5eEwgOTePHuxac73@e@dza3rNFKb1srVAXLB@uoGU61lMSd0MoOP5EiI/g4eHNjLtTPcRBwidbCdfAngM6sQyc43GlRwmcUKoyew7tkby/Fs1bxiXWm4w3gMldtQwZ/SJrwGk2SwAZi2No4scN1TYbCkA9EFCc8@Xi8zyeno/1QJAfn9ptgo@9xfHT499U9PjkbJQdRtO2k/dNz2s2iJQ3XRjjq1FO4E9AnOLpwE@4tSW4Y18p10qmEL6okc4@ODFwYQlf346e3t2jQtXYviqKxRxOEa6Mrg03T4@aoqhYr8qVdpasCUidR9YtfLfJ09RUKU6ESv7F/P19wls@mxRUc@tbXJKUewL02svzgC5Giqh3LG@Fcv6xS6Mx7U@saHWSaLLiaYKZ/wRIfzn1pRxk0@o5dkvc/kNhWNStaB3PdsswXc0HWwcYIUqWFWbHIb3JmfGHgW8gYAGMI/dE5/4d5pUC647wHWhCWz5yXXo/B4/YJ "C# (Mono) – Try It Online")
Full/Formatted Version:
```
using System.Collections.Generic;
using System.Linq;
class P
{
static void Main()
{
System.Func<string, IEnumerable<char>> f = s => s.Where((c, i) => c > 64 & c < 91 & (i > 0 ? s[i-1] == 32 | s[i-1] == 45: 1 > 0));
System.Console.WriteLine(string.Concat(f("Self-contained Underwater Breathing Apparatus")));
System.Console.WriteLine(string.Concat(f("a Programming Language")));
System.Console.WriteLine(string.Concat(f("NATO Atlantic TREATY Organization")));
System.Console.WriteLine(string.Concat(f("DEFCON 2")));
System.Console.WriteLine(string.Concat(f("hello, world!")));
System.Console.WriteLine(string.Concat(f("light-Emitting dioDe")));
System.Console.WriteLine(string.Concat(f("What Does the Fox Say?")));
System.Console.WriteLine(string.Concat(f("3D mov-Ies")));
System.Console.WriteLine(string.Concat(f("laugh-Out Lou-D")));
System.Console.WriteLine(string.Concat(f("Best friends FOREVE-r")));
System.Console.WriteLine(string.Concat(f(" ")));
System.Console.WriteLine(string.Concat(f("-- --a - - --")));
System.Console.WriteLine(string.Concat(f("-- -- - - -- A")));
System.Console.ReadLine();
}
}
```
[Answer]
# Julia 0.6.0 (57 bytes)
```
s=split(s,r" |-");for w∈s isupper(w[1])&&print(w[1])end
```
Explanation:
This is my first code-golf. Pretty straight forward. Split the words, print 1rst upper letter of each.
Probably easy to do better using regex but I am new to this
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
'-ð‡ð¡ζнAuÃ
```
[Try it online!](https://tio.run/##AUoAtf8wNWFiMWX//yctw7DigKHDsMKhzrbQvUF1w4P//1NlbGYtY29udGFpbmVkIFVuZGVyd2F0ZXIgQnJlYXRoaW5nIEFwcGFyYXR1cw "05AB1E – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 108 bytes
```
n=>{var j="";n=' '+n;for(int i=0;++i<n.Length;)if(" -".IndexOf(n[i-1])>=0&n[i]>64&n[i]<91)j+=n[i];return j;}
```
[Try it online!](https://tio.run/##dU9Ra4MwGHz3V3xksCpOaccYjBhhEwYDRwsd7GH0IdUY4/QLS2KZiL/d2e65cNwdfHccX2GjQhsx91ahhP1gneioV7TcWvgZPeu4UwWctCrhnSv0g9F77bFIrDNL4e5fUpBsRpaOJ26gYYRQZCtYhUgrbXyFDhRb0zBUCca5QOlqGqjKJxCR@A1L8butfPxS0eYQpGx9u9hD@vhw0eRpEzQhO1tqhOsNQkOnmXqZRqtbEX8a5USuUPjSJxx2RkvDu@78Tc5R9lwKEgRX8tkN7Pvi28Kzg0yXQuq2up7@qJWFBcvGkR/bAba40D28DE4sB4Td4OpLfZrmPw "C# (.NET Core) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/questions/133721/generate-an-acronym/133728#comment328515_133742) (`Ḳ` splits at spaces >\_<)
```
⁾- yḲḢ€fØA
```
A monadic link taking and returning lists of characters.
As a full program accepts a string and prints the result.
**[Try it online!](https://tio.run/##AS4A0f9qZWxsef//4oG@LSB54biy4bii4oKsZsOYQf///yJsYXVnaC1PdXQgTG91LUQi "Jelly – Try It Online")** or see a [test suite](https://tio.run/##NY6xTsMwFEV3f8VjxwusCOSSREKqGtQGUMen5sUxcuzIeaGEDRZ@gZmZCTFUQmLpl6Q/EhIJpnvOHa7uPVnbDcPh@UdC1@8@@9374eWj2L@pof/@2r@Osh6GFdlCbrxjNI5yuHE5hS0yBZgFQi6N06DqGgNy2wiE6@B1wKqa@jk63aImsVBZCootOjYbyJaxytaQBo3OPCEb70QUJ5fpAk5EOb7yx7D1weZHwhpdsowrwzwN5sZHJO5KZIg8NcAlQeIfYYXdhTiNoPIP8ooaYbHVpUxbhrlvZSRm1DAUwZDLG0jSZXwbyyCkFGdNjRs6HxFASoQpRvjzfwX1Cw "Jelly - Try It Online").
### How?
```
⁾- yḲḢ€fØA - Link: list of characters, x e.g. "Pro-Am Code-golf Association"
y - translate x with:
⁾- - literal list of characters ['-',' '] "Pro Am Code golf Association"
Ḳ - split at spaces ["Pro","Am","Code","golf","Association"]
Ḣ€ - head each (1st character of each) "PACgA"
ØA - yield uppercase alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
f - filter keep "PACA"
- if running as a full program: implicit print
```
[Answer]
# [Perl 5](https://www.perl.org/), 25 bytes
**24 bytes code + 1 for `-n`.**
Annoying that `grep -P` support variable length look-behind but Perl doesn't :(.
```
print/(?:^| |-)([A-Z])/g
```
-1 byte thanks to [@Dada](https://codegolf.stackexchange.com/users/55508/dada)!
[Try it online!](https://tio.run/##NY9PS8NAEMXv8ynGWwuOBcWLl5o2qQptI7YqWioMzXSzsNkNm4lV8bMbG9DL7/05PHi1RHfZdXW0XkeD8dXb9wZpOxxsEnrdDkem61bi9rQLXtl6KfDRFxIPrBJxEoW1tN5gUtccWdsGGO9jMJGrqu/n7E3LRmCZrHNM1LFXu8P1Q5asXzCPhr39YrXBQ5rNpvkSz6EU58IpHkJ0xQk4a0qlrLKq/WBhQyrwXLJiGqRBLQVn4QNX/DmGixSr8E530oDj1pSUt4rz0FIKE2kU99GKLxqc5Q/ZU0YRiACPQCRi7OVo/vJ/xARWKjXdir@@qdg6WhyBPc6mYYEV/IS6P9B05N0v "Perl 5 – Try It Online") - includes `-l` to run all tests at once.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 19 bytes
```
'- 'X{&Yb'^[A-Z]'XX
```
[Try it online!](https://tio.run/##FclBCsIwEEDRfU8xK2cVEG8QTV22oBFaRXFs03YgTUscEfTwse4@748kPt0TKsDqu6ofeLtodb5iVSWTrRsDmU14dL5TzRSEOLgWTqF18U3iImyjIxk49KDnmSLJ64kZeu4HUfnIIv/V8mTcwibf78oCNksW2pagxVMQbsAecm1rKGNPgT8kPAX8AQ "MATL – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~25~~ ~~23~~ 22 bytes
```
,Ṣ↻s₂ᶠ{h∈" -"&t.∧Ạụ∋}ˢ
```
[Try it online!](https://tio.run/##HY49TsNAEIWvMmyRypsiXAAThx8piREOBaIa4mW90no32oyJIEqTIjKi4QgREqKlAYnkCJzCvojxpphvRu89Pc29w2n2pK3sNct681Wv10knYMCBBUm1e1lV329NUP2@15v9vDWrn@0yq8uyTbAOdevys9ptq/1HXb6u/t6b5o4lQj/wqTWEyogUbkwq3AJJODh1AilTRkI4m6FDKuYsAIZw5ax0mOfeGqKRBUrhnXE4iSEkjYbUFCbXg3ByC7GTaNQzkrLGh6LBWT8eQ8/fmdDaBrCwTqdHXtBKZsQHuSLy5amy0aH5OILcPvJLcfhAYyEzHhcEQ1vwyEucA7Tj6XfotYTEjF8Ic3Keo9J81AI8un07gpz9Aw "Brachylog – Try It Online")
*(-2 bytes thanks to @Fatalize.)*
```
,Ṣ↻ % prepend a space to input
s₂ᶠ % get all substrings of length 2 from that, to get prefix-character pairs
{ }ˢ % get the successful outputs from this predicate:
h∈" -" % the prefix is - or space
&t.∧ % then the character is the output of this predicate if:
Ạụ∋ % the alphabet uppercased contains the character
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~19~~ ~~16~~ 14 bytes
*-2 bytes thanks to Shaggy*
```
f/^| |-)\A/ mÌ
```
[Try it online!](http://ethproductions.github.io/japt/?v=2.0&code=Zi9efCB8LSlcQS8gbWZcQQ==&input=Ik5BVE8gQXRsYW50aWMgVFJFQVRZIE9yZ2FuaXphdGlvbiI=)
[Answer]
# [Swift 5](https://swift.org), 110 bytes
-5 thanks to [Cœur](https://codegolf.stackexchange.com/users/26980/c%c5%93ur)
```
import UIKit
func f(s:[String]){for i in zip(s,[" "]+s){if i.0.isUppercase()&&"- ".contains(i.1){print(i.0)}}}
```
---
## Detailed Explanation
* `import Foundation` - Imports the module `Foundation` that is vital for `zip()`, the main piece of this code.
* `func f(s:[String]){...}` - Creates a function with a parameter `s`, that is a list of Strings, representing the characters of the input.
* `for i in zip(s,[" "]+s){...}` - Iterates with `i` through the zip of the input and the input with a space added in the beginning, which is *very* helpful for getting the previous character in the String.
* `if` - Checks whether:
+ `i.0==i.0.uppercased()` - The current character is uppercase,
+ `&&"- ".contains(i.1)` - and If the previous character is a space or a dash.
* If the above conditions are met, then:
+ `print(i.0)` - The character is printed, because it is part of the acronym.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 43 bytes
```
''+($args|sls '(?<=^| |-)[A-Z]'-a -ca|% m*)
```
[Try it online!](https://tio.run/##NZDRT8IwEMbf91ecybCg1Ad9VAKDDTURZgA1atRcWNc16VrSdqIy/vZJQV@@u/y@y@W7W@k1M7ZgUjZh3ts0hJy2QzTc1lZaIO3@Ve@9hpp2XiP68kYoAl1i3YLypNNsgyB0zDroDdoBmTOZ06VWDoViGTyojJk1OmZgaBi6QigO0WqFBl1lSTcgCPdGc4Nl6a07VLxCzrwzjRYpRE6icmIJi1kSLZ4hNRyV@EEntPJDcTIepVM4973Pr7uw1kZmRx5IwQtHk1I455dnQsf7zU8FOog1s@AKBmP9BXP87nvnIoZSf9Jbts8mseIFTSsHd7qisUdDf2luBFOZhXE6Sx4TarxBqVc4tADU/2hX4MAP6J9A5NncsRW9YWpwXaKQdLIT8HI20hMoSdD5e2zd2oQfl3Ac5rCrhGybXw "PowerShell – Try It Online")
Unrolled:
```
''+($args|select-string '(?<=^| |-)[A-Z]' -allmatches -caseSensitive|% matches)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 67 bytes
```
lambda x:[c[0]for c in x.replace("-"," ").split()if c[0].isupper()]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PycxNyklUaHCKjo52iA2Lb9IIVkhM0@hQq8otSAnMTlVQ0lXSUdJQUlTr7ggJ7NEQzMzTQGkUi@zuLSgILVIQzP2/38A "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~73~~ 70 bytes
```
lambda n:[n[x]for x in range(len(n))if'@'<n[x]<'['and(' '+n)[x]in' -']
```
[Try it online!](https://tio.run/##HYxNb8IwEET/yjYXJwJf2huiH6EJp4pIQIuqlMMWO8lKZh05GwH982nd2@jNzOtv0nl@mJrHr8nh@dsg8KLm@npsfIArEENAbm3qLKecZdSoF7WM/VLVCtmkCtSMsz9ArECr4xSPFI91srOu0SfPgsTWwDsbGy4oNsAqWJSOuIW87zGgjEMyh2ST7yvIxSELnWC/LfP9J1ShRaYfFPIcR0W5fq02cB9zZ53zc7j44MxdBI7aTnR5JpFoN@QLG/mhQ4HC2wGks7D2V9jh7Tk2KzsINIEsmwHW1bb8KHX4V@HYdroaBd78qIvkuOgDsaQ0S0A/QTIbJKRNSlmWTb8 "Python 3 – Try It Online")
---
# Explanation
* `lambda n:` - Creates an anonymous lambda-function with a String parameter `n`.
* `n[x]` - Gets the character of `n` at index `x`.
* `for x in range(len(n))` - Iterates from `0` to the length of `n`, naming the variable `x`.
* `if` - Checks:
+ `'@'<n[x]<'['` - If the character is uppercase,
+ `and(' '+n)[x]in' -'` - And if it is preceded by a space or a dash in the String formed by a space and `n`.
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 62 bytes
```
n=s=>(""+s.match(/([ -]|^)[A-Z]/g)).replace(/[ \-,]|null/g,"")
```
[Try it online!](https://tio.run/##JY9NT8JAEIbv/IpxT21oaeLVoKkWTgaMYIyWmkzaYbu63W12BxDDf68snObjmbyT5xv36Gunek59rxpynTU/dBwGM/XT@0iIsZ90yHUbZVEJaXX6iss8/awyGccTR73GmqKshE2aVCez0zqTiRDxsEcHTJ49TKEUK9LbtLaGURlq4M2cHx2QycGjI@RWGQl536ND3nmRgEB4cVY67LqAntHIHUoKZJGvl5CzRsOqhvXrLF9/wNJJNOoPWVkTjorZ/Gm5gNvQt6S1TeBgnW5uwkIr2XI66xRzCG@ULS7J7y0yFJY8cEswt7@wwuODqEajrXUQBRuw26tVDGcbbzVNtJVXNAaxMeJczGWO47vhHw "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# [QuadS](https://github.com/abrudz/QuadRS), 17 bytes
```
(?<=^| |-)[A-Z]
&
```
[Try it online!](https://tio.run/##KyxNTCn@/1/D3sY2rkahRlcz2lE3KpZL7f9/P8cQfwXHkpzEvJLMZIWQIFfHkEgF/6L0xLzMqsSSzPw8AA)
[Answer]
# Pyth, ~~15~~ 16 bytes
```
@rG1<R1:w"[ -]"3
```
[Test suite](https://pyth.herokuapp.com/?code=%40rG1%3CR1%3Aw%22%5B+-%5D%223&input=Self-contained+Underwater+Breathing+Apparatus&test_suite=1&test_suite_input=Self-contained+Underwater+Breathing+Apparatus%0Aa+Programming+Language%0ANATO+Atlantic+TREATY+Organization%0ADEFCON+2%0Ahello%2C+world%21%0Alight-Emitting+dioDe%0AWhat+Does+the+Fox+Say%3F%0A3D+mov-Ies%0Alaugh-Out+Lou-D%0ABest+friends+FOREVE-r%0A--%0A+&debug=0)
[Answer]
# Pyth, 12 bytes
```
@rG1hMcXz\-d
```
[Test suite here.](http://pyth.herokuapp.com/?code=%40rG1hMcXz%5C-d&test_suite=1&test_suite_input=Self-contained+Underwater+Breathing+Apparatus%0Aa+Programming+Language%0ANATO+Atlantic+TREATY+Organization%0ADEFCON+2%0Ahello%2C+world%21%0Alight-Emitting+dioDe%0AWhat+Does+the+Fox+Say%3F%0A3D+mov-Ies%0Alaugh-Out+Lou-D%0ABest+friends+FOREVE-r%0A--%0A+%0A--++--a+-++-+--%0A--++--+-++-+--+A&debug=0)
[Answer]
# Bash (grep), ~~29~~ 28 bytes
```
grep -oP'(?<=^| |-)[A-Z]' a
```
A port of my python answer but because `pgrep` supports variable length lookbehinds it's noticeably shorter (even accounting for the overhead of python). Stick the test cases in a file called `a`, output is 1 character per line.
-1 Thanks to [Neil](https://codegolf.stackexchange.com/questions/133721/generate-an-acronym/133742#comment328593_133749)
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 18 bytes
```
`-` rû#ùr.'[a-z]'-
```
## Explained
```
`-` rû#ùr.'[a-z]'-
`-` # Push "-" literal, and " " literal.
r # replace, Replaces all "-"s with " "s.
û # Split, defaultly by spaces.
#ù # Push the head function literally.
r # Replace each element of the split string by the head function, which gets each first character.
. # Concatenate, which collapses the stack back to a string.
'[a-z]'- # Push the string "[a-z]" literally, then remove it from the string underneith, giving us our output.
```
[Try it online!](https://tio.run/##Kyooyk/P0zX6/z9BN0Gh6PBu5cM7i/TUoxN1q2LVdf///x9QlK/rmKvgnJ@Sqpuen5Om4FhcnJ@cmViSmZ8HAA "RProgN 2 – Try It Online")
[Answer]
# PHP, 62 bytes
```
for(;~$c=$argn[$i++];$p=$c!="-"&$c!=" ")$c<A|$c>Z|$p?:print$c;
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/9c260696f28353dc75d4a9b0da637cb2fd63623f).
other solutions:
```
foreach(preg_split("#[ -]#",$argn)as$s)$s[0]>Z|$s<A?:print$s[0]; # 64 bytes
preg_match_all("#(?<=\s|-)[A-Z]#"," $argn",$m);echo join($m[0]); # 64 bytes
preg_match_all("#(?<=\s|-)\p{Lu}#"," $argn",$m);echo join($m[0]); # 65 bytes
```
[Answer]
## C++, 168 bytes
```
#include<string>
auto a=[](auto&s){auto r=s.substr(0,1);if(r[0]<65||r[0]>90)r="";for(int i=1;i<s.size();++i)if(s[i]>64&&s[i]<91&&(s[i-1]==32||s[i-1]==45))r+=s[i];s=r;};
```
Output done via the parameter
[Answer]
## [Lua](https://lua.org/), 79 75 bytes
```
for i=1,#t do for i in(" "..t[i]):gmatch"[%-| ]%u"do print(i:sub(2))end end
```
[Try it!](https://tio.run/##NY7dTsJAEIVf5VhDCkmXRLwjIVpoUROhCaDGEC5WurSbbHeb7az4@@x1i3pz5pxvJjOjHG8JE3yGa6EObG80calFjgedC3vkJCymVnAqpS4Q1zW3nFwTRuEy3mSISXFNco/NKo03z8hswbX84CSN9jNJOp9lS4y8LYVSJsLRWJWf@axkURJLK0nUbc6lSYTHTyUnJEY0oFJgbt6w5u9XvnGZoDKv7E50txV3RckyR7g3jiWeTEVDOFgpdN5gnq3Sx5RZzxnzgpMBGOPoCk70l/wDxB6tSdTsVujrm4pLxRZe0MlwZhaowu/2YCzk5CI6J@QGpwSp@wGC4ZC2cjcYFxWnfRlse@wLu54L/Fhtpaa@HDfupT@KRoOBf/IPdrZt2x8)
I stuck a print() before the final end in the try it version because otherwise it's a mess. This program perfectly adheres to the requirements of I/O and matching, but without that extra new line it's pretty hard to read.
Input is given in the form of a table of number:string , number incrementing by 1 each time and starting at 1.
Explanation:
It for loops through a gmatch of each input string. The gmatch search is as follows:
[%-| ] - Group, search for a - or a space
%u - Search for an uppercase character
Then for each match, it prints it out minus the preceding dash or space
Edit: Golfed 4 bytes by removing the declaration of 'a' and adding the space to the input inside the for loop in, as well as changing the sub input to just 2 rather than 2,2 (which produce equivalent results)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
Created one year after the initial answer.
```
rI#1hMcXQ\-d
```
[Try it online!](https://pyth.herokuapp.com/?code=rI%231hMcXQ%5C-d&input=%22Self-contained+Underwater+Breathing+Apparatus%22&debug=0)
### [Pyth](https://github.com/isaacg1/pyth), 21 bytes
Initial answer.
```
:+dQ"(?<=[ -])[A-Z]"1
```
[Try it online!](https://tio.run/##K6gsyfj/30o7JVBJw97GNlpBN1Yz2lE3KlbJ8P9/peDUnDTd5Py8ksTMvNQUhdC8lNSi8sSS1CIFp6LUxJKMzLx0BceCgsSixJLSYiUA "Pyth – Try It Online")
] |
[Question]
[
Heavily based on [this closed challenge.](https://codegolf.stackexchange.com/q/148911/80214)
[Codidact post](https://codegolf.codidact.com/posts/279253), [Sandbox](https://codegolf.meta.stackexchange.com/a/20435/80214)
# Description
A Sumac sequence starts with two non-zero integers \$t\_1\$ and \$t\_2.\$
The next term, \$t\_3 = t\_1 - t\_2\$
More generally, \$t\_n = t\_{n-2} - t\_{n-1}\$
The sequence ends when \$t\_n ‚â§ 0\$. All values in the sequence must be positive.
# Challenge
Given two integers \$t\_1\$ and \$t\_2\$, compute the Sumac sequence, and output its length.
If there is a negative number in the input, remove everything after it, and compute the length.
You may take the input in any way (Array, two numbers, etc.)
# Test Cases
(Sequence is included for clarification)
```
[t1,t2] Sequence n
------------------------------
[120,71] [120,71,49,22,27] 5
[101,42] [101,42,59] 3
[500,499] [500,499,1,498] 4
[387,1] [387,1,386] 3
[3,-128] [3] 1
[-2,3] [] 0
[3,2] [3,2,1,1] 4
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in each language wins.
[Answer]
## x86 machine code (8086), ~~15~~ 13 bytes
-2 bytes thanks to @EasyasPi.
```
00000000 31 C9 48 7C 07 40 41 29-D8 93 EB F6 C3 1.H|.@A).....
```
Callable function.
Expects `AX` = t1, `BX` = t2. Output is to `CX`.
Disassembly:
```
31C9 XOR CX,CX ; Set CX to 0
LOP:
48 DEC AX ; --AX
7C07 JL END ; If AX < 0, jump to 'END'
40 INC AX ; ++AX
41 INC CX ; ++CX
29D8 SUB AX,BX ; AX -= BX
93 XCHG BX,AX ; Swap AX and BX
EBF6 JMP LOP ; Jump to tag 'LOP'
END:
C3 RET ; Return to caller
```
## Example run
Tested with DOS debug:
```
-r
AX=0078 BX=0047 CX=0000 DX=0000 SP=FFEE BP=0000 SI=0000 DI=0000
DS=0B17 ES=0B17 SS=0B17 CS=1000 IP=0000 NV UP EI PL NZ NA PO NC
1000:0000 31C9 XOR CX,CX
-t
AX=0078 BX=0047 CX=0000 DX=0000 SP=FFEE BP=0000 SI=0000 DI=0000
DS=0B17 ES=0B17 SS=0B17 CS=1000 IP=0002 NV UP EI PL ZR NA PE NC
1000:0002 48 DEC AX
...
-t
AX=FFFA BX=0020 CX=0005 DX=0000 SP=FFEE BP=0000 SI=0000 DI=0000
DS=0B17 ES=0B17 SS=0B17 CS=1000 IP=000C NV UP EI NG NZ NA PE CY
1000:000C C3 RET
```
```
[Answer]
# JavaScript (ES6), 24 bytes
```
f=(a,b)=>a>0&&1+f(b,a-b)
```
[Try it online!](https://tio.run/##dc5BDoIwEIXhvaeYFWljKzNtCbCAu7QIRkMoEeP1K7Wuqs7yffmTudmn3Yb7dX3IxZ/HEKaOWeF419sei4KOE3PCSsfD4JfNz@Np9he2r6RQAEBNnENZQnXIHSm6Ucl17hXG3rRtcpO7burYA/3pAbQASapJTl8u1bvXyfFnv9/nPxNe "JavaScript (Node.js) – Try It Online")
[Answer]
# [convey](http://xn--wxa.land/convey/), 39 37 bytes
*-2 thanks to Jo King!*
```
{0(>>"!+?`}
,?"-v>^0^
^>>", 8~^
^<<<<
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiezAoPj5cIiErP2B9XG4sP1wiLXY+XjBeXG5ePj5cIiwgOH5eXG5ePDw8PCIsInYiOjEsImkiOiIxMjAgNzEifQ==)
The Sumac Sequence gets calculated in the lower left part, with `{` taking the input and copying the sequence into `(` via `"` (copy):
```
{ (
,?"-v
^>>",
^<<<<
```
The sequence then gets converted to – is it greater than 0 `0(`? Taking `!` that by itself, only 1s gets passed through into `+`:
```
0(>>"!+
>^
```
There the accumulator loops around, waiting 8 steps `8~` so both the generating loop and the accumulator loop have the same speed. If there is an input waiting for `+`, `?` pushes the accumulator into `+`, otherwise – if the sequence stopped thanks to a 0 – it gets pushed into the output `}`.
```
+?}
0^
8~^
```
Everything put together:
[](https://i.stack.imgur.com/37n5l.gif)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
λ-}(d1k
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3G7dWo0Uw@z//6MNDQx1TIxiAQ "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##S0oszvj/PzU5I19BN09B/dxu3VqNFMNsdQU7heT8lFS9xKRULq7yjMycVIWi1MQUhcw8rpR8LgUg0M8vKNHPL05MykyFUnAdCjY2NgoqYKV5qf//RxsaGeiYG8ZyRRsaGOqYGAEZpgYGOiaWlkCWsYW5DkjKWEfX0MgCyNA10jEG84HqAA)
**Commented**:
```
λ } # start a recursive environment:
# this produces an infinite sequence starting with input
- # and calculates t_n according to t_n = t_{n-2} - t_{n-1}
( # negate every value
d # for every value: is it non-negative?
1k # find the first index of a 1 (smallest n such that -t_n >= 0)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~16~~ ~~13~~ ~~12~~ ~~11~~ 9 bytes
Saved ~~1~~ ~~2~~ 4 bytes thanks to [Leo](https://codegolf.stackexchange.com/users/62393/leo)!
```
L↑>0ƒ·:G-
```
[Try it online!](https://tio.run/##yygtzv7/3@dR20Q7g2OTDm23ctf9//@/ueF/QyMDAA "Husk – Try It Online")
~~I wish it would parse the correct function without parentheses.~~ Leo found a 9-byte solution that doesn't use parentheses or even composition!
This my first time using `ƒ` (`fix` from Haskell).
I'm told `fix` looks something like this:
```
fix :: (a -> a) -> a
fix f = let x = f x in x
```
Supposing the first argument (`²`) is 120, and the second argument (`⁰`) is 71, `f` (`o:²G-⁰`) would be something like `prevSequence -> 120 : scanl (-) 71 prevSequence`. So the `x` from above would become
```
x = 120 : scanl (-) 71 x
x = 120 : 71 : scanl (-) (120 - 71) (drop 1 x) //where drop 1 x is 71 : scanl (-) ...
x = 120 : 71 : 49 : scanl (-) (71 - 49) (drop 2 x)
...
```
and so on until it makes an infinite sequence.
Then `‚Üë>0` takes (`‚Üë`) while each element is positive, and `L` finds the length of that sequence.
[Answer]
# [sed -r 4.2.2](https://www.gnu.org/software/sed/), 44
* Thanks to @seshoumara for -2 bytes
```
:
s/^(1+) \1(1+)/\2 &/
t
s/1+ ?/1/g
s/.*-1//
```
[Try it online!](https://tio.run/##K05N@f/fiqtYP07DUFtTIcYQROnHGCmo6XOVAIUNtRXs9Q3104FMPS1dQ339//8NqQMUDAcI/MsvKMnMzyv@r1sEAA "sed 4.2.2 – Try It Online")
### Explanation
The inputs are space-separated unary. Term 2 is given before term 1. E.g. (5, 3) would be `111 11111`; (5, -3) would be `-111 11111`.
* Line 1: loop label (unnamed - works in 4.2.2)
* Line 2: generate term n+2 by removing term n+1 from term n; Prefix term n+2 to the beginning of the pattern space
* Line 3: if the substitution on line 2 was successful, jump back to the loop label
* Line 4: Count the terms by replacing each term (followed by optional space) with 1
* Line 5: Handle negative inputs
* End of program: Implicit output of counter
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
L↑>0¡(→Ẋ`-
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8b/Po7aJdgaHFmo8apv0cFdXgu7///@jow2NDHTMDWN1og0NDHVMjIAMUwMDHRNLSyDL2MJcByRlrKNraGQBZOga6RiD@UaxsQA "Husk – Try It Online")
...still haven't managed to get Razetime's (*edit: non-existant*) 9-byte answer (unless [zero-based indexing](https://tio.run/##yygtzv6f@6ip8X/Yo84lBocWajxqm/RwV1eC7v///6OjDY0MdMwNY3WiDQ0MdUyMgAxTAwMdE0tLIMvYwlwHJGWso2toZAFk6BrpGIP5RrGxAA) is Ok), but ~~I'm trying...~~ (*edit: I've now given-up*).
*(Edit 2: ...but a 9-byte answer has now been [found](https://codegolf.stackexchange.com/a/218137/95126) by user & Leo!)*
**Commented code:**
```
L # length of
‚Üë>0 # initial elements that are greater than zero of
¬°( # infinite list by repeatedly appending list with
‚Üí # last element of
Ẋ`- # pairwise differences between elements of list so far
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~33~~ 24 bytes
```
NθNηW‹⁰θ«⊞υω≦⁻θη≧⁻ηθ»ILυ
```
[Try it online!](https://tio.run/##dc2xCsIwFIXhuX2KjPdChbaLQyfRpaClrxDbaxNoUkluVBCfPUbBSbr@8J0zKOmGRc4x9sErCIVo7TVwF8yZHCA2@WVxAo7kPZSFOGmrTTAQEFE882wNZXelZ1pxP5Ri8LDj1o70@ISOJskENWIh/nOVbJp@5b3TlmEvPcOBBkeGLNOYvuzE6nuBTYxVXYptFTe3@Q0 "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 9 bytes when @Razetime pointed out I was using an inefficient algorithm. Explanation:
```
NθNη
```
Input the initial values.
```
W‹⁰θ«
```
Repeat while the first value is positive.
```
⊞υω
```
Keep count of the number of iterations.
```
≦⁻θη
```
Subtract the second number from the first number, storing the result in the second number.
```
≧⁻ηθ
```
Subtract that result from the first number, resulting in the original second number.
```
»ILυ
```
Finally print the number of iterations.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes
```
f=->a,b{a>0?f[b,a-b]+1:0}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY9BCsIwEEXX5hSzdyIzaUtbIfUgIUgKZicUmy6keBI3XeghxJN4G1Nriw6zmHn_M8y_3k5dfR6Gexe8LB5ey8ph3buKdt7U6GRt17yly6S_nuHQBtBgBMQyhhVhzhYhszgjYkxVRMmCMiJMyzKydGFJkSP_uRKUrIqIeEFSYdSBfjzqc0VYIcZXNkfX9GLVdKEFb_ZsyMZGmCa2FrQeF7biG2GO-gY)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `2`, ~~20~~ ~~8~~ 7 bytes
```
⁽-Ḟ±ċTh
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBMiIsIiIsIuKBvS3huJ7CscSLVGgiLCIiLCJbMTIwLDcxXVxuWzEwMSw0Ml1cbls1MDAsNDk5XVxuWzM4NywxXVxuWzMsLTEyOF1cblstMiwzXVxuWzMsMl0iXQ==)
Wow it's a been a while since I posted this, and a lot of things have been added/changed since.
## Explained
```
⁽-dḞ±ċTh
‚ÅΩ-d # lambda x, y: x - y
·∏û # Using the input as an initial vector, apply the above lambda infinitely, using all previously generated items as its stack
±ċ # Is the sign of each item not 1?
Th # First occurrence of 1
```
[Answer]
# TI-BASIC, 27 Bytes
```
While A>0
A-B->B
A-B->A
N+1->N
End
N
```
Takes t1 and t2 as input in A and B. Nothing fancy, the key is that when A is updated, B is the previous t1-t2, so the third line is able to recover t2 via t1-(t1-t2)->A without juggling a 3rd variable. There's a way to generate the sequence in 27 bytes as well with input as a list in Ans and dim( calls, but it proves too complex to trim out negative input and retrieve the true length of the sequence.
[Answer]
# [Raku](https://raku.org/), 20 bytes
*-4 bytes thanks to Jo King*
```
{+(|@_,*-*...^0>=*)}
```
[Try it online!](https://tio.run/##JclBCoMwFEXRrTxESo0m/PzYqmBCV9LgoBm1tOhI1LVHY2eHe3@v8X2PnxmXABuX8ro@fCWkUEo9yVlRbHEaZmS5h3VYAtbcbxnCd0SvmdBoVx0ijZqTbkSouy7RtA3OayA1t0mSYf6FXdwB "Perl 6 – Try It Online")
The parenthesized expression is a list where the first terms are the two arguments to the function (`|@_`), successive terms are generated by subtracting the previous two terms (`* - *`), and the list stops just before the term (`...^`) for which zero is greater than or equal to it (`0 >= *`). Then the `+` operator converts that list to a number, its length.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 31 bytes
```
\d+
$*
+`(1+)¶\1$
$&¶$%`
\G1+¶?
```
[Try it online!](https://tio.run/##DcahDYUwFAVQf@coBOgj6X3lB1BIBsBWlAQEBkGYrQN0sX6OOs/5XvdeqmaLUsJhYTrY2NC2OQUamDonU0WElTanpRSqk5GgowyKn3MyzDP8NArhpadO6FX8d/0D "Retina 0.8.2 – Try It Online") Takes the integers on separate lines but link includes test suite that splits on comma for convenience. Explanation:
```
\d+
$*
```
Convert to unary. Note that the signs are ignored at this stage, so that if the first number is negative, the next stage uselessly computes the sequence as if it was positive.
```
+`(1+)¶\1$
$&¶$%`
```
Compute additional terms until the last number is zero or greater than the absolute value of the previous number.
```
\G1+¶?
```
Count the number of leading positive terms.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 27 bytes
```
f(a,b){a=a>0?f(b,a-b)+1:0;}
```
This is the C equivalent of [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/218113/100356)
[Try it online!](https://tio.run/##dY/BboMwDIbvPIXVCikRyZQEKtrRsgdhHAIhG1KXTpCeUJ6deV1VZZPmi@3fv5PPPX/r@3U7uv58NQMcZ2/Gy9N7vVqiWUcXfdK1eLGkY5p3NJPPogrr6Dx86NERCkuSAMa34ofZz03ZNqqFEw7gHotUgkEpA4skIRkUKpZ2Al3F4RBr@b5k8GsxZ8Cl2scSVwzyPx4VQvVDZi8TudEhk6gwHaHElGU0QnwUnxN6LdmkuYG0MMBrSM2r27D7db5tRBs1EhtL/ptRWt1eDsnjk2nw18khSRLWLw "C (gcc) – Try It Online")
A and that's actually the work of [att](https://codegolf.stackexchange.com/users/81203/att). My function was initially 28 bytes and non-reusable.
[Answer]
# [Python 3](https://docs.python.org/3/), 29 bytes
```
f=lambda a,b:a>0and-~f(b,a-b)
```
[Try it online!](https://tio.run/##Vc7LCsIwEIXhtXmKWSYygVxaeoH4IuJiQg0WNC01Gze@eh0Fi87y4zD886NcpuzXNYUr3eJAQBh7OhjKg34mGZF0VGs53wsEkAL45NE6g409IdQKv2QsVo7Jb1Qbg1XXsVWb@bZB@7fyqK1rmexG2qFnMD8b9/kiFAiRpoUjIcKY4d3Vi928jLnIJPekIATg4Bc "Python 3 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 46 bytes
```
param($a,$b)for(;$a-gt0;$i++){$a-=$b=$a-$b}+$i
```
[Try it online!](https://tio.run/##NYzRCoIwGIWv8yl@xl9s@A@2aajIwjeJCVqGpajQhfnsS9KuzvcdDqfv3tUw3qu29Vjb2fducE@OjrAUdTfwHJ28TSrHJgzFvIrF0q6B5RJi45cAp2qcRrBQ8OBQcG0UJVrQj5Wm2Gx8VoriLNskShPaNxFJbdKNpaHo3xoRiP37c5yB4RXkBZDzE9ZQXIV8dM2LERMMFv8F "PowerShell – Try It Online")
[Answer]
# Python 3, ~~141~~ 125 bytes
```
def F(I):
i=1
if I[0]<0:
return 0
if I[1]<0:
return 1
while I[i-1]-I[i]>0:
I.append(I[i-1]-I[i])
i+=1
return i+1
```
Thanks to @Razetime for pointing out the sequence itself didn't need to be returned.
[Answer]
# Prolog (SWI), ~~102~~ 93 bytes
```
d(A,B,C):-B<1,write(C);E is C+1,F is A-B,d(B,F,E).
:-read(A),(A<0,write(0);read(B),d(A,B,1)).
```
[Try it online!](https://tio.run/##LYxNCoAgFAb3naKljz4la1dtfFL3CJQQgsICj2@/u2FgZo/bui3ySCFnJwwYljrJg0aK4fTCUj@W4ShtpTE9YCTDCcaEkVTRyejnuyMIM9R/U1P/WiZ8S02kcm5V0agL "Prolog (SWI) – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 12 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
æ`‼->▲](mσb=
```
Takes the two inputs in reversed order.
[Try it online.](https://tio.run/##y00syUjPz0n7///wsoRHDXt07R5N2xSrkXu@Ocn2/39zQwVDIwMuEyMFQwNDLhNLSwVTAwMuQwVjC3MuXUMjCwVjLmMFXSMuIwVjAA)
**Explanation:**
```
‚ñ≤ # Do-while true with pop,
√¶ # using the following four commands:
` # Duplicate the top two values on the stack
‼ # Apply the following two commands separated on the current stack:
- # Subtract the top two items from one another
> # Check if the second top item is larger than the top item
] # After the do-while, wrap everything on the stack into a list
( # Decrease each value by 1
m # Map over each value:
σ # And take its sign: 1 if >0; 0 if ==0; -1 if <0
= # And then get the first 0-based index in this list of
b # value -1
# (after which the entire stack joined together is output implicitly)
```
[Answer]
# [R](https://www.r-project.org/), ~~43~~ 37 bytes
*Edit: -6 bytes after peeking at [Arnauld's answer](https://codegolf.stackexchange.com/a/218113/95126): please upvote that one!*
```
f=function(a,b)`if`(a>0,1+f(b,a-b),0)
```
[Try it online!](https://tio.run/##Tc7RCoJAFATQd7/kXhph966hPtiPiOQqbS1sKqlgX7@RRfR2GAZmHnFe77Y/h8twXW5VdJVbh37x40AWHbfetWRPCvrgqINNO4biONtpCk8Kfl4o6UmLQq4ZbyqNTHYelUJWlrtNkeNTMEi1FDtTgflmwgnjt7zx/ynaat1gq6VhTuIL "R – Try It Online")
[Answer]
## Batch, 65 bytes
```
@set/aa=%1-%2,b=%3+1,c=b-1
@if %1 gtr 0 %0 %2 %a% %b%
@echo %c%
```
`c` is provided so that the output is zero if the first parameter is negative, otherwise `@echo %3` would work. (On the first pass `%3` is the empty string, but `b=+1` still computes the correct value for `b`. `c=%3+0,b=c+1` would also work.)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~42~~ 35 bytes
Saved 7 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!!!
```
n;f(a,b){for(n=0;a>0;++n)a-=b=a-b;}
```
[Try it online!](https://tio.run/##bZBha4MwEIa/@ysOQYg1Mo2WtmT2y9ivmDLSGDvZlhYTmKz41@euaqUtFXKJd8@by70y3EvZ95pXRNCdf6oODdFZxMU24kGgfRFmu0yEO971tbbwLWpNfOfkAH7nhFXGvtv4rYAMTjGLKMRRTGEZ4SlZrzBQCBluHb/TsFGzQjpFIN1sUItwzNaDil0pVHtU0qpylCyHejpEVGCndGLlh2gWGJX8VM0Iu3n7yvJ284Jr6VK4/k/cSYdTAzk3qnWpWpRFfDo@g6l/1aEilyf4T1NiMWc4BMFA@zAaMw8a41UXhwai4LcAmwH2EDBYr4jFKS3zb0sKS7Mv99pjg0hFXC8pKXhpCeEWvBI8k2v0YLyPgqGzVybLVDF16Jyu/5PVl9ibPvz5Bw "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Rȧ_@Rп@L
```
[Try it online!](https://tio.run/##y0rNyan8/z/oxPJ4h6DDEw7td/D5f3i5/qOmNZH//0cbGhnomBvG6kQbGhjqmBgBGaYGBjomlpZAlrGFuQ5IylhH19DIAsjQNdIxBlIGOgaxAA "Jelly – Try It Online")
[As posted on Codidact](https://codegolf.codidact.com/posts/280307#answer-280307)
Takes \$t\_1\$ on the left and \$t\_2\$ on the right. [`R}ȧ_@RпL`](https://tio.run/##y0rNyan8/z@o9sTyeIegwxMO7ff5f3i5g/6jpjWR//9HGxoZ6JgbxupEGxoY6pgYARmmBgY6JpaWQJaxhbkOSMpYR9fQyALI0DXSMQZSBjoGsQA) works given the arguments in the opposite order.
```
R Ascending range from 1 to t_1 (truthy if positive),
ȧ and:
п collecting intermediate results, loop while
R positive
@ on the reversed arguments:
_ subtract
@ the first from the second.
L Return the length of the conjunction.
```
`¬ø` and family, given a dyad, replace the right argument with the previous left argument on each successive iteration. This is incredibly bothersome for some tasks, but perfect for working with this exact kind of sequence.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 25 bytes
```
f(a,b)=if(a>0,1+f(b,a-b))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWO9M0EnWSNG0zgbSdgY6hdppGkk6ibpKmJkT-ZmZiQUFOpUaigq6dQkFRZl4JkKkE4igpJCfm5Gik6SgkamrqKERHGxoZ6JgbxgKZhgaGOiZGIJapgYGOiaUliGlsYa4DljXW0TU0sgCxdI10jCEiRrGxUAthDgMA)
] |
[Question]
[
This construction is a way of representing the Natural Numbers.
In this representation, 0 is defined as the empty set and for all other numbers, n is the union of {0} and {n-1}.
For example to construct 3 we can follow the algorithm:
```
3 =
{ø, 2} =
{ø, {ø, 1}} =
{ø, {ø, {ø}}}
```
# Task
As you may have guessed your task is to take in a natural number (including zero) and output its construction.
You may output as a either a string or as a set object if your language of choice supports such objects.
If you choose to output as a string you should represent a set with curly braces (`{}`). You may optionally represent the empty set as `ø` (otherwise it should be a set with no entries `{}`). You may also choose to add commas and whitespace between and after entries in the set.
Order is not important, however you may ***not*** have any repeated elements in the sets you output (e.g. `{ø,ø}`)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to have the fewest bytes
# Test cases
Here are some test cases with some example outputs.
```
0 -> {}
1 -> {{}}
2 -> {{}{{}}}
3 -> {{}{{}{{}}}}
4 -> {{}{{}{{}{{}}}}}
```
[Answer]
# [Python](https://docs.python.org/), 28 bytes
```
lambda x:"{{}"*x+x*"}"or"{}"
```
[Try it online!](https://tio.run/nexus/python2#S7PV@J@TmJuUkqhQYaVUXV2rpFWhXaGlVKuUX6QE5P3X5CooyswrUUjTMDTQ/A8A "Python 2 – TIO Nexus")
This is a pretty bland solution to the problem. For numbers greater than zero you can get the representation with the string formula `"{{}"*x+"}"*x`. However this doesn't work for zero where this is the empty string. We can use this fact to short circuit an `or` to return the empty set.
I wanted to use python's builtin set objects to solve this problem but unfortunately:
```
TypeError: unhashable type: 'set'
```
You cannot put sets inside of sets in python.
[Answer]
# [Haskell](https://www.haskell.org/), 37 bytes
```
f 0="{}"
f n=([1..n]>>)=<<["{{}","}"]
```
[Try it online!](https://tio.run/nexus/haskell#@5@mYGCrVF2rxJWmkGerEW2op5cXa2enaWtjE61UDRTXUapViv2fm5iZZ5uZV5JalJhcolKal5OZl1qsp5GbWKCRpleUmpiiqakHFvtvwGXIZcRlzGUCAA "Haskell – TIO Nexus")
Until 10 minutes ago an answer like this would have made no sense to me. All credits go to [this tips answer](https://codegolf.stackexchange.com/a/52945/62393).
Basically, we use `>>` as `concat $ replicate` (but passing it a list of n elements instead of simply n), and `=<<` as `concatMap`, replicating then n times each of the strings in the list and concatenating the result into a single string.
The `0` case is treated separately as it would return an empty string.
[Answer]
## JavaScript, 28 bytes
```
f=n=>n?--n?[[],f(n)]:[[]]:[]
```
Represents sets using arrays. 38-byte nonrecursive solution:
```
n=>'{{}'.repeat(n)+'}'.repeat(n)||'{}'
```
Returns the example output strings.
[Answer]
## Mathematica, 27 bytes
I've got two solutions at this byte count:
```
Nest[{{}}~Union~{#}&,{},#]&
Union//@Nest[{{},#}&,{},#]&
```
[Answer]
# [Perl 6](https://perl6.org), 37 bytes
```
{('{}','{{}}',{q:s'{{}$_}'}...*)[$_]}
```
[Try it](https://tio.run/nexus/perl6#VY/RaoNAEEXf5ysuQbq7dbNJ2tIHbaQf0bcYQtAtCNGYrJaWZfrrVjeV0qc7c4Z7Z6Z3Fh/Ppkip/sJdcS4ttoOXwrPQwnsexV8SN5XRgQUbY@7VLjrseRgNr511ncMWp6qxTipTH9sEHnXiVjIvYwWxzATky87zPovVKkUcrTW@ow2YqB@Xv40JKbWnY4P4FpcSvZ@vc/Yyg0ReNW3faeT2s7VFZ0soeAIqh@lkGcZKYx5rLHxgPPn9jHmREg/rwJg2QccX6eG3mhqmx78uAKanf@QG@Qc "Perl 6 – TIO Nexus")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
(
# generate a sequence
'{}', # seed it with the first two values
'{{}}',
{ # bare block lambda with implicit parameter 「$_」
q # quote
:scalar # allow scalar values
'{{}$_}' # embed the previous value 「$_」 in a new string
}
... # keep using that code block to generate values
* # never stop
)[ $_ ] # get the value at the given position in the sequence
}
```
[Answer]
# [Röda](https://github.com/fergusq/roda), 37 bytes
```
f n{[[[],f(n-1)]]if[n>1]else[[[]]*n]}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes
### Code
```
ƒ)¯sÙ
```
Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@39skuah9cWHZ/7/bwIA "05AB1E – TIO Nexus") or [Verify all test cases!](https://tio.run/nexus/05ab1e#JY0/CsIwGMXneopHtkItKbg46KI4Fg/QJUjaBtNEkk/q0ku4eQqPULDgtepHfduP96@QpxKsJBFHD2o1am@t741rUEiQ6XTM0BtqUWIHmedbUc3fZ/p5x@k1A8MK7IhpxHqPaRQZL52DcbSMBR3vluDrhW7BN0F1ouJOWiWcPFitwuJFUpcrn//J6QfBkA6KjHdcGObNDw).
### Explanation
```
ƒ # For N in range(0, input + 1)..
) # Wrap the entire stack into an array
¯ # Push []
s # Swap the two top elements
Ù # Uniquify the array
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 22 bytes
```
.+
$*
\`.
{{}
{
^$
{}
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/ivp82losUVk6DHVV1dy1XNxRWnwlVd@/@/AZchlxGXMZcJAA "Retina – TIO Nexus")
### Explanation
```
.+
$*
```
Convert the input to unary.
```
\`.
{{}
```
Replace each unary digit with `{{}` and print the result without a trailing linefeed (`\`).
```
{
```
Remove the opening `{`s, so that the remaining `}` are exactly those we still need to print to close all the sets. However, the above procedure fails for input `0`, where we wouldn't print anything. So...
```
^$
{}
```
If the string is empty, replace it with the empty set.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 135 bytes
Includes +1 for `-A`
```
(({}())<{({}[()]<((((((()()()()()){}){}){}())()){}{})>)}{}({}[()()])>)(({})<{({}[()]<(((({}()())[()()])))>)}{}>[()]){(<{}{}{}>)}{}{}{}
```
[Try it online!](https://tio.run/nexus/brain-flak#XUwxDoBACPtOO7g4k0t8h/ElhLdjsboIBNrQtoEskJG6J3gFXPyaWR7Bh4ksatsgi@ik/DLGIP0roT1r3kzExIiyDLr33o4b "Brain-Flak – TIO Nexus")
```
(({}())< # Replace Input with input + 1 and save for later
{({}[()]< # For input .. 0
(...) # Push '}'
>)}{} # End for and pop counter
({}[()()]) # change the top '}' to '{'. This helps the next stage
# and removes the extra '}' that we got from incrementing input
>) # Put the input back on
(({})< # Save input
{({}[()]< # For input .. 0
(((({}()())[()()]))) # Replace the top '{' with "{{{}"
>)}{} # end for and pop the counter
>[()]) # Put down input - 1
{(<{}{}{}>)} # If not 0, remove the extra "{{}"
{}{}{} # remove some more extras
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 11 bytes
```
Lri{]La|}*p
```
Prints a set-like object consisting of lists of lists. CJam prints empty lists as empty strings, since lists and strings are almost interchangeable.
[Try it online!](https://tio.run/nexus/cjam#@@9TlFkd65NYU6tV8P@/MQA "CJam – TIO Nexus")
**Explanation**
```
L Push an empty array
ri Read an integer from input
{ }* Run this block that many times:
] Wrap the entire stack in an array
La Wrap an empty list in an array, i.e. [[]]
| Set union of the two arrays
p Print the result
```
# Old answer, ~~21~~ 18 bytes
This was before it was confirmed that it was OK to print a nested list structure. Uses the string repetition algorithm.
*Saved 3 bytes thanks to Martin Ender!*
```
ri{{}}`3/f*~_{{}}|
```
**Explanation**
```
ri Read an integer from input
{{}}` Push the string "{{}}"
3/ Split it into length-3 subtrings, gives ["{{}" "}"]
f* Repeat each element of that array a number of times equal to the input
~_ Dump the array on the stack, duplicate the second element
{{}}| Pop the top element, if it's false, push an empty block, which gets
printed as "{}". An input of 0 gives two empty strings on the
repetition step. Since empty strings are falsy, we can correct the
special case of 0 with this step.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
⁸,⁸Q$¡
```
This is a niladic link that reads an integer from STDIN and returns a ragged array.
[Try it online!](https://tio.run/nexus/jelly#@/@ocYcOEAeqHFr4/9Cio5Me7pyh8HDH9kcNcxScE3NyFBLzUhSS8/PKUotKFEryFQIqSzLy8xSKK/NKEiv0/psAAA "Jelly – TIO Nexus")
### How it works
```
⁸,⁸Q$¡ Niladic link.
⁸ Set the return value to [].
$ Combine the three links to the left into a monadic chain.
,⁸ Pair the previous return value with the empty array.
Q Unique; deduplicate the result.
¡ Read an integer n from STDIN and call the chain to the left n times.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 32 bytes
```
f=lambda n:[[],n and f(n-1)][:n]
```
Not the shortest way, but I just *had to* do this with recursion.
[Try it online!](https://tio.run/nexus/python3#@59mm5OYm5SSqJBnFR0dq5OnkJiXopCmkadrqBkbbZUX@z8tv0ghTyEzT6EoMS89VcNU04qLs6AoM69EI09HQV3XTl0HpFxT8z8A "Python 3 – TIO Nexus")
[Answer]
# [Cardinal](https://www.esolangs.org/wiki/Cardinal), ~~51~~ 50 bytes
```
%:#>"{"#? v
x ^?-"}{"<
v <8/ ?<
> 8\
v"}"<
>?-?^
```
[Try it online!](https://tio.run/nexus/cardinal#@69qpWynVK2kbK9QxlWhoBBnr6tUW61kw1WmYGOhr2Bvw2WnoGARw1WmVAsUtLPXtY/7/98EAA "Cardinal – TIO Nexus")
## Explanation
```
%:#
x
```
Receive input and send down and left from the #
```
>"{" ? v
^?-"}{"<
```
Print "{" one time then print "{}{" n-1 times if n>1 then print "{}" if n>0
```
#
v <8/ ?<
> 8\
```
Hold onto the input value until the first loop completes
```
v"}"<
>?-?^
```
Print "}" once then repeat n-1 times if n>1
[Answer]
# AHK, 55 bytes
```
IfEqual,1,0
s={{}{}}
Loop,%1%
s={{ 2}{}}%s%{}}
Send,%s%
```
It's not the shortest answer but I enjoyed this because the idiosyncrasies of AutoHotkey make this recursion method look *super* wrong. `If` and `Loop` statements assume the next line is the only thing included if brackets aren't used. Curly brackets are escape characters so you have to escape them with other curly brackets to use them as text. Also, the variable `1` is the first passed argument. When I read the code without knowing those tidbits, the logic *looks* like this:
* If 1=0, then set `s` equal to the wrong answer
* Loop and add a bunch of brackets to the beginning and a few to the end every time
* Return by sending the resulting string to the current window
Without all the bracket escape characters, it would look like this:
```
IfEqual,1,0
s={}
Loop,%1%
s={{}%s%}
Send,%s%
```
[Answer]
# JavaScript 50 bytes
```
g=n=>n==0?"":"{{}"+g(n-1)+"}"
z=m=>m==0?"{}":g(m)
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 52 bytes
```
(d f(q((n)(i n(i(e n 1)(c()())(c()(c(f(s n 1))())))(
```
[Try it online!](https://tio.run/nexus/tinylisp#LYo5DoAwDMB2XpHRGRl4UOiBKkGAMvH6ci62ZLkRJbODK0WcQhKXXgko@imQOd76pB/amFeLMpexWj21Y7FNslDNpyTDPVw "tinylisp – TIO Nexus") (test harness).
### Explanation
Note that `(cons x (cons y nil))` is how you build a list containing `x` and `y` in Lisp.
```
(d f Define f to be
(q( a quoted list of two items (which acts as a function):
(n) Arglist is a single argument n
(i n Function body: if n is truthy (i.e. nonzero)
(i(e n 1) then if n equals 1
(c()()) then cons nil to nil, resulting in (())
(c else (if n > 1) cons
() nil to
(c cons
(f(s n 1)) (recursive call with n-1) to
()))) nil
())))) else (if n is 0) nil
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 52 bytes
```
n(i){putchar(123);i>1&&n(0);i&&n(i-1);putchar(125);}
```
Taking advantage of some short circuit evaluation and recursion.
[Try it online!](https://tio.run/nexus/c-gcc#dY4xDsIwDEX3nMJTGyOQmhamSFwEGKKAwAMuSpMuVc8ekhbEgOLFX35P1o8sCadX8PZhnFRth5qOqqpYNinlTTuF@iccUM9x7OkKLrDESUCaxYavVJ@5Rv0BqgTaEuhKYP8PZiGIPTwNpaIpGHe3W7A9Dx6yB5t8Gk8XhLXpUnp96G4@OIYmfYlv "C (gcc) – TIO Nexus")
[Answer]
# Pure [Bash](https://www.gnu.org/software/bash/), ~~49~~ ~~48~~ 41 bytes
```
for((;k++<$1;)){ s={{}$s};};echo ${s-{\}}
```
[Try it online!](https://tio.run/nexus/bash#@5@WX6ShYZ2trW2jYmitqVmtUGxbXV2rUlxrXWudmpyRr6BSXaxbHVNb@///fwMA "Bash – TIO Nexus")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 46 bytes
```
[[{}]]sx256?^dd3^8d^1-/8092541**r255/BF*+d0=xP
```
[Try it online!](https://tio.run/nexus/dc#@x8dXV0bG1tcYWRqZh@XkmIcZ5ESZ6irb2FgaWRqYqilVWRkaqrv5KalnWJgWxHw/78xAA "dc – TIO Nexus")
Input on stdin, output on stdout.
This works by computing a formula for the desired output as a base-256 number. The P command in dc is then used to print the base-256 number as a string.
---
Further explanation:
Let n be the input n. The dc program computes the sum of
A = floor(256^n / 255) \* 125 (BF is interpreted by dc as 11\*10+15 = 125)
and
B = floor((256^n)^3 / (8^8-1)) \* 8092541 \* (256^n).
For A:
Observe that 1 + 256 + 256^2 + ... + 256^(n-1) equals (256^n-1)/255, by the formula for a geometric progression, and this equals floor(256^n / 255). So this is the number consisting of n 1's in base 256.
When you multiply it by 125 to get A, the result is the number consisting of n 125's in base 256 (125 is a single digit in base 256, of course). It's probably better to write the digits in base 256 as hex numbers; 125 is hex 7D, so A is the base-256 number consisting of n 7D's in a row.
B is similar:
This time observe that 1 + 16777216 + 16777216^2 + ... + 16777216^(n-1) equals (16777216^n - 1)/16777215, and this equals floor(16777216^n/16777215).
Now, 256^3 = 16777216, and 8^8-1 = 16777215, so this is what we're computing as floor((256^n)^3 / (8^8-1)).
From the geometric series representation, this number in base 256 is 100100100...1001 with n of the digits being 1 and the rest of the digits being 0.
This is multiplied by 8092541, which is 7B7B7D in hexadecimal. In base 256, this is a three-digit number consisting of the digits 7B, 7B, and 7D (writing those digits in hex for convenience).
It follows that the product written in base 256 is a 3n-digit number consisting of the 3 digits 7B 7B 7D repeated n times.
This is multiplied by 256^n, resulting in a 4n-digit base-256 number, consisting of the 3 digits 7B 7B 7D repeated n times, followed by n 0's. That's B.
Adding A + B now yields the 4n-digit base-256 number consisting of the 3 digits 7B 7B 7D repeated n times, followed by n 7D's. Since 7B and 7D are the ASCII codes for `{` and `}`, respectively, this is the string consisting of n copies of `{{}` followed by n copies of `}`, which is exactly what we want for n > 0. The P command in dc prints a base-256 number as a string, just as we need.
Unfortunately, n=0 has to be treated as a special case. The computation above happens to yield a result of 0 for n=0; in that case, I've just hard-coded the printing of the string `{}`.
[Answer]
# Java 7, 61 bytes
```
String p(int p){return p<1?"{}":p<2?"{{}}":"{{}"+p(p-1)+"}";}
```
[Try it online!](https://tio.run/nexus/java-openjdk#JY6xDoIwFEV3vuKlU5sGIg4OFvQLnBiNQ0E0L4Hy0haNafrtWGB59y73nEdzO2AH3aCdg5tGE5bGWzRvII7GA4lgez9bA1SVVxYiO1N1TCXEVNdgkjjlpZAsMhUX2oHOa5/iM@ETxoTlO/X@0CJkqwfa2vTfTcmFyl6T3XxYHxRWJ4VSCmh@zvdjMc2@oLT2g@EIEhjkl3QktEV6UqR1zOLyBw "Java (OpenJDK 8) – TIO Nexus")
[Answer]
## Batch, 88 bytes
```
@set s={}
@if %1 gtr 0 set s=&for /l %%i in (1,1,%1)do @call set s={{}%%s%%}
@echo %s%
```
[Answer]
# [Brainf\*\*\*](https://esolangs.org/wiki/Brainfuck), 99 bytes
```
>+>+>+>+<[>[-<+++++>]<-<]>--[->+>+<<]
>[-<+>]>++<,[[->>+>+<<<]>>[-<<<..>>.>]>[-<<.>>]+[]]<.>>.
```
(newline for aesthetics)
Since it's brainf\*\*\*, it takes input as ascii char codes (input "a" corresponds to 96)
# Braineasy, 60 bytes
Also, in my custom language (brainf\*\* based, interpreter [here](https://github.com/ebomberger23/braineasy-interpreter)):
```
#123#[->+>+<<]>++<,[[-<+<+>>]<[->>>..<.<<]<[->>>.<<<]!]>>.<.
```
You have to hardcode the program input into the interpreter because i'm lazy.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 3 bytes
```
F¯)
```
[Try it online!](https://tio.run/nexus/05ab1e#@@8WcWiHZu3//0YA "05AB1E – TIO Nexus")
This version is after he clarified that sets are okay.
```
F # From 1 to input...
¯ # Push global array (default value is []).
) # Wrap stack to array.
```
---
Old version (that makes use of ø):
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 4 bytes
```
FX¸)
```
[Try it online!](https://tio.run/nexus/05ab1e#@@8WcWiHZu3//0YA "05AB1E – TIO Nexus")
Where `1` is equivalent to `ø`.
```
F # From 1 to input...
X # Push value in register X (default is 1).
¸ # Wrap pushed value into an array.
) # Wrap whole stack into an array.
# Implicit loop end (-1 byte).
# Implicit return.
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 33 bytes
```
[[{}]n1-d0<m]sr[[{]nd0<r[}]n]dsmx
```
[Try it online!](https://tio.run/##S0n@b/8/Orq6NjbPUDfFwCY3trgIyI3NA7KLooGisSnFuRX//xsDAA "dc – Try It Online")
Not as clever as the other dc answer, but rather shorter
] |
[Question]
[
Some numbers like `64` can be expressed as a whole-number power in multiple ways:
```
64 ^ 1
8 ^ 2
4 ^ 3
2 ^ 6
```
Output a sorted array of all possible such powers (here, `[1,2,3,6]`) in as few bytes as possible.
---
# Input
A positive whole number that's greater than 1 and less than 10000.
---
# Output
An array of whole-number powers `p` (including `1`) for which the input can be expressed as `a^p` with whole-number `a`. The outputs may have decimals, as long as they are in order.
Any floating point issues must be handled by the program.
---
# Examples
```
Input: 3
Output: [1]
Input: 9
Output: [1, 2]
Input: 81
Output: [1, 2, 4]
Input: 729
Output: [1, 2, 3, 6]
```
---
# Scoreboard
For your score to appear on the board, it should be in this format:
```
# Language, Bytes
```
Strikethroughs shouldn't cause a problem.
```
function getURL(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 getAnswers(){$.ajax({url:getURL(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){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/<strike>.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+"").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=58047,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/;
```
```
body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 30px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0}
```
```
<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="scores-cont"><h2>Scores</h2><table class="score-table"><thead> <tr><td></td><td>User</td><td>Language</td><td>Score</td></tr></thead> <tbody id="scores"></tbody></table></div><table style="display: none"> <tbody id="score-template"><tr><td>{{RANK}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td></tr></tbody></table>
```
[Answer]
# Pyth, 10 bytes
```
f}Q^RTSQSQ
```
[Demonstration](https://pyth.herokuapp.com/?code=f%7DQ%5ERTSQSQ&input=64&debug=0)
For each power, it generates the list of all numbers up to the input taken to that power, and then checks if the input is in the list.
[Answer]
## Haskell, 38
```
f n=[b|b<-[1..n],n`elem`map(^b)[1..n]]
```
Pretty straightforward. The list comprehension finds values of `b` for which the input `n` appears among `[1^b, 2^b, ..., n^b]`. It suffices to check `b` in the range `[1..n]`.
[Answer]
# Python 2, 53
```
lambda n:[i/n for i in range(n*n)if(i%n+1)**(i/n)==n]
```
Brute forces all combinations of bases in exponents in [0, n-1] and bases in [1, n].
[Answer]
## Python 3, 56 bytes
```
lambda n:[i for i in range(1,n)if round(n**(1/i))**i==n]
```
This is really clumsy. Tests if each potential `i`-th root gives an integer by rounding it, taking it the power of `i`, and checking that it equals to original.
Directly checking that the root is a whole number is tricky because floating points give things like `64**(1/3) == 3.9999999999999996`. Rounding it to an integer let us check if taking the power returns to the original value. Thanks to ypercube for suggesting this, saving 1 byte.
feersum has a [shorter and more clever solution](https://codegolf.stackexchange.com/a/58064/20260). You all should really upvote that.
[Answer]
# Pyth, 11 10 12 bytes
```
fsmqQ^dTSQSQ
```
Checks all possible combinations of powers. Very slow.
[Answer]
# CJam, 23 bytes
```
rimF{1=:E){E\d%!},}%:&p
```
This works by taking the prime factorization of **n** and computing the intersection of the divisors of all exponents.
It is a bit longer than [my other solution](https://codegolf.stackexchange.com/a/58049), but I expect it to work (and finish instantly) for all integers between **2** and **263 - 1**.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=rimF%7B1%3D%3AE)%7BE%5Cd%25!%7D%2C%7D%25%3A%26p&input=4052555153018976267).
### How it works
```
ri Read an integer from STDIN.
mF Push its prime factorization.
{ }% For each [prime exponent]:
1=:E Retrieve the exponent and save it in E.
){ }, Filter; for each I in [0 ... E]:
E\d% Compute E % Double(I).
(Casting to Double is required to divide by 0.)
! Push the logical NOT of the modulus.
Keep I if the result is truhty, i.e., if I divides E.
:& Intersect all resulting arrays of integers.
p Print the resulting array.
```
[Answer]
# APL, 17 bytes
```
(X=⌊X←N*÷⍳N)/⍳N←⎕
```
My first APL program; golfing suggestions are appreciated.
```
N←⎕ ⍝ Store input into N
⍳ ⍝ The list [1 2 ... N]
/ ⍝ Select the elements A for which
N*÷⍳N) ⍝ N^(1/A)
(X=⌊X← ⍝ equals its floor (that is, is an integer)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ÆEg/ÆD
```
[Try it online!](https://tio.run/##y0rNyan8//9wm2u6/uE2l/@H2x81rfn/P9pYx1LHwlDH3MhSx8xEx8jAQMfEwCAWAA "Jelly – Try It Online")
```
ÆD The list of divisors of
ÆE the exponents in the prime factorization of the input
/ reduced by
g greatest common divisor.
```
[Answer]
# JavaScript (ES5), ~~73 bytes~~ ~~81 bytes~~ ~~79 bytes~~ 75 bytes
```
for(n=+prompt(),p=Math.pow,i=0;i++<n;)p(.5+p(n,1/i)|0,i)==n&&console.log(i)
```
Checks to see if closest integer power of possible root equals `n`. `~~(.5+...)` is equivalent to `Math.round(...)` for expressions within integer range (0 to 2^31 - 1).
**Edit:** Used lazy `&&` logic instead of `if` to shave 2 bytes and added prompt for input since question added a clarification. Was previously assuming input was stored in `n`.
**Edit 2:** Changed `~~(.5+...)` to `.5+...|0` to save two bytes by avoiding grouping.
**Edit 3:** Removed `var` to save 4 bytes. In non-strict mode, this is acceptable.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
≥^↙.?≥ℕ≜
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/486l8Y9apupZw9kPGqZ@qhzzv//0cY6ljoWhjrmRpY6ZiY6RgYGOiYGBrEA "Brachylog – Try It Online")
Takes input through its input variable and [generates](https://codegolf.meta.stackexchange.com/a/10753/85334) each power through its output variable, in ascending order as required, unlike the old solution `≥ℕ≜^↙.?∧` which just so happens to have the exact same length.
```
≥ Some number which is less than or equal to
the input,
^ when raised to the power of
↙. the output,
? is the input.
≜ Label
the output
ℕ as a whole number
≥ which is less than or equal to
? the input.
```
I don't have any rigorous justification for asserting that every exponent is no greater than the input, but in order for the program to actually terminate it needs to be bounded.
`ḋḅlᵛf` is a far shorter (non-generator) solution for all of the given test cases, but it fails if the input isn't a power of a product of distinct primes. (Come to think of it, since all of the test cases are powers of primes, `ḋlf` also works...) The best I've come up with to salvage the idea, `ḋḅlᵐḋˢ⊇ᵛ×f`, comes out to 10 bytes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
Ó¿Ñ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8ORD@w9P/P/fxMzM1AwA "05AB1E – Try It Online")
Port of [Unrelated String’s Jelly answer](https://codegolf.stackexchange.com/a/187061/6484).
```
Ó # exponents in the prime factorization
¿ # gcd
Ñ # divisors
```
[Answer]
# JavaScript ES7, 66 bytes
Takes advantage of experimental array comprehensions. Only works on Firefox.
```
n=>[for(i of Array(n).keys(m=Math.pow))if(m(0|.5+m(n,1/i),i)==n)i]
```
Possible golfing. I'll probably try to squish the expressions a little shorter and hopefully find an alternative to the long `Array(n).keys()` syntax.
Could be shorter but JavaScript has horribly floating point accuracy.
[Answer]
# CJam, 20 bytes
```
ri_,1df+\1$fmL9fmO&p
```
For input **n**, this computes **logb n** for all **b** less or equal to **n** and keeps the results that are integers.
This should work for all integers between **2** and **9,999**. Run time is roughly **O(n)**.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=ri_%2C1df%2B%5C1%24fmL9fmO%26p&input=4913).
### How it works
```
ri e# Read an integer N from STDIN.
_, e# Copy N and transform it into [0 ... N-1].
1df+ e# Add 1.0 to each, resulting in [1.0 ... Nd].
\1$ e# Swap the array with N and copy the array.
fmL e# Mapped log base N: N [1.0 ... Nd] -> [log1(N) ... logN(N)]
9fmO e# Round each logarithm to 9 decimals.
& e# Intersect this array with [1.0 ... Nd].
p e# Print the result.
```
[Answer]
# Ruby, 50
```
->n{(1..n).map{|i|(n**(1.0/i)+1e-9)%1>1e-8||p(i)}}
```
Prints to screen.
# Ruby, 57
```
->n{a=[]
(1..n).map{|i|(n**(1.0/i)+1e-9)%1>1e-8||a<<i}
a}
```
Returns an array.
In test program:
```
f=->n{(1..n).map{|i|(n**(1.0/i)+1e-9)%1>1e-8||puts(i)}}
g=->n{a=[]
(1..n).map{|i|(n**(1.0/i)+1e-9)%1>1e-8||a<<i}
a}
f.call(4096)
puts g.call(4096)
```
Calculates each root and tests them modulo 1 to see if the remainder is less than 1e-8. Due to limited precision some valid integer roots are calculated to be the form 0.9999.., hence the need to add 1e-9 to them.
Up to the nth root of n is calculated, which is total overkill, but seemed the shortest way to write a non-infinite loop.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
£ÅeÉåC
```
[Run and debug it](https://staxlang.xyz/#p=9c8f65908643&i=3%0A9%0A81%0A729&a=1&m=2)
All divisors of the gcd of exponents in the prime factorization. It's the same as the jelly algorithm.
[Answer]
# **DC, 104 bytes**
Input is taken from terminal, output is printed and also on the stack.
Because this uses the ? operator, you need to use `dc -e "<solution>"` or `dc <file with solution in it>`.
Nobody ever sees my answers, let alone vote on them, but I really just enjoy solving problems in DC. It's the least efficient solution in this thread so far, but I thought I'd post it anyways.
```
1sb?sn[lesi]ss[lble1+dse^dln=sln>c]sc[liSflq1+sq]sm[Lfplq1-dsq0<p]dsp[lb1+sb0si0selcxli0!=mlbln!=h]dshxx
```
starter stuff
```
1sb Store 1 in register b
?sn Store user input in register n
[lesi]ss A macro to copy the e to the i register, stored in the s register
```
Macro to raise a base to all powers until the result is larger than the target or equal to the target
```
[lble1+dse^dln=sln>c]sc
[lb ] load our base num (register b)
[ le ] load our exponent (register e)
[ 1+dse ] add 1 to the exponent, copy and store in the e register
[ ^d ] raise the base to the exponent and copy it
[ ln=s ] load the user input, if that is equal to the power result run the macro in register s
[ ln>c] load the user input, if it's greater than the power result run the macro in register c (this one)
[ ]sc save this macro in register c
```
Macro to save a valid exponent value as found from the above exponent macros to another stack
```
[liSflq1+sq]sm
[liSf ] copy the i register to the top of the stack in register f
[ lq1+sq] add 1 to the q register
[ ]sm save this macro in the m register
```
Macro to run the 2x above macro (macro c) through all bases from 2 to our target number
```
[lb1+sb0si0selcxli0!=mlbln!=h]dsh
[lb1+sb ] add 1 to the base number
[ 0si0se ] reset the i and e registers (previously found value and exponent
[ lcx ] load and run the c macro
[ li0!=m ] load the result of the c macro and if it's not 0, run m to save it to the f stack
[ lbln!=h] if our base number is not equal to our target number, run macro h (this macro)
[ ]dsh duplicate this macro and save one copy, so that one is left on the stack to run later
```
Macro to print the values from the f stack
```
[Lfplq1-dsq0<p]dsp
[Lfp ] load the top value from the f register and print it
[ lq1-dsq ] load the q register and subtract one from it and save it
[ 0<p] if the q register is greater than 0, run macro p (this macro) again
[ ]dsp duplicate this macro and save one copy, so that one is left on the stack to run later
xx finally run the two macros on the stack (h and then p)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 46 bytes
Brute force solution. Self-explanatory; for input \$n\$, find all numbers \$e\$ where for some \$b\$, \$b^e=n\$.
```
->n{(0..n).select{|e|(1..n).find{|b|b**e==n}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNATy9PU684NSc1uaS6JrVGwxAskJaZl1Jdk1STpKWVamubV1tb@79AIS06PbWkWK8kPz4z9r@ZCQA "Ruby – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 93 bytes
```
g=n=>Enumerable.Range(1,n);
f=n=>g(n).SelectMany(x=>g(n).Where(y=>(Math.Pow(x,y)==n))).Reverse()
```
[Try it online!](https://tio.run/##hczNCoJAFAXgvU8hru7ANGBFP9jMrqBICFu4NrnqgF1hZix9erMI2uXynPNxcjvLrR4OLeU7TY4f99Te0WS3Gt9ZKb@IvD9r6cuBpPr1IsmoRAg5saiQ41QCMXHFGnMXZ9RD963SCg1CLxXEmavEpXlCx3smJTHGRIIPNBaBDZGXGu3wrAnBOqOpFKdGEwQ84H4Bq@XIJ8ximmynySacNuv552h4AQ "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 bytes
```
õ
f@mpX øN
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9QpmQG1wWCD4Tg&input=NjQ)
```
õ :Implicit input of integer U
õ :Range [1,U]
f@mpX øN :Reassign to U
f :Filter
@ :By passing each X through the following function
m : Map U
pX : Raise to the power of X
ø : Contains
N : Any element of the (singelton) array of inputs
```
] |
[Question]
[
### Background
*The deltas* of an array of integers is the array formed by getting the differences of consecutive elements. For example, `[1, 2, 4, 7, 3, 9, 6]` has the following deltas: `[1, 2, 3, -4, 6, -3]`.
We will now define the deltas of a matrix of integers as the deltas of each row and each column it contains.
As an example:
```
Row deltas:
1 2 3 4 │ => [1, 1, 1]
4 5 6 7 │ => [1, 1, 1]
7 1 8 2 │ => [-6, 7, -6]
Column deltas (the matrix' columns have been rotated into rows for simplicity):
1 4 7 │ => [3, 3]
2 5 1 │ => [3, -4]
3 6 8 │ => [3, 2]
4 7 2 │ => [3, -5]
```
Which gives us the following list of matrix deltas:
```
[[1, 1, 1], [1, 1, 1], [-6, 7, -6], [3, 3], [3, -4], [3, 2], [3, -5]]
```
And as we don't want them to be nested, we flatten that list:
```
[1, 1, 1, 1, 1, 1, -6, 7, -6, 3, 3, 3, -4, 3, 2, 3, -5]
```
---
### Task
Your task is to *sum all the deltas* of a matrix given as input. Note that the matrix will only consist of non-negative integers.
### Rules
* All standard rules apply.
* You may assume the matrix contains at least two values on each row and column, so the minimum size will be **2x2**.
* You may take the matrix in any reasonable format, as long as you specify it.
* You *may not* assume that the matrix is square.
* If it might help you reduce your byte count, you *may* optionally take the number of rows and the number of columns as input as well (Looking at you C!).
* This is code-golf, so the shortest code (in bytes), *in each language* wins!
### Test Cases
```
Input => Output
[[1, 2], [1, 2]] => 2
[[8, 7, 1], [4, 1, 3], [5, 5, 5]] => -9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] => 24
[[9, 9, 9, 9, 9], [9, 9, 9, 9, 9]] => 0
[[1, 3, 14], [56, 89, 20], [99, 99, 99]] => 256
[[1, 2, 3, 4], [4, 5, 6, 7], [7, 1, 8, 2]] => 9
[[13, 19, 478], [0, 12, 4], [45, 3, 6], [1, 2, 3]] => -72
```
[Answer]
# [Python 2](https://docs.python.org/2/), 42 bytes
```
lambda m:sum(r[-1]-r[0]for r in m+zip(*m))
```
An unnamed function taking a list of lists, `m`, and returning the resulting number.
**[Try it online!](https://tio.run/##VVDLDoIwEDzrV@wN0CWhUJ4J/kjloFEiiQVS8KA/j7sFjCRtOjud2dm2f4@Prg2nujxPz4u@3i6gi@GlXaN8UflGBVXdGTDQtKCPn6Z3D9rzJubG@zAy7SolEMIKYT4ZqAwhRRCMJZ0IEcMYgdcsYfHCS8snDMlF3nyW5IR@i5ktsbaJKEHa/gm56SoMrJhFdm8CEeRfJs25xAqbvMwvuCd5ZZpxHVAVrsbYNknWB/MbKq/Y73rTtKP9FgSnPDkItcuVN30B "Python 2 – Try It Online")**
### How?
The sum of the deltas of a list is the last element minus the first, everything else just cancels:
**(r[n]-r[n-1])+(r[n-1]-r[n-2])+...+(r[2]-r[1]) = r[n]-r[1]**
The `zip(*m)` uses unpacking (`*`) of `m` to pass the rows of `m` as separate arguments to `zip` (interleave) and hence transposes the matrix. In python 2 this yields a list (of tuples, but that's fine), so we can add (concatenate) it to (with) `m`, step through all our rows and columns, `r`, perform the above trick for each and just add up the results (`sum(...)`).
[Answer]
# [R](https://www.r-project.org/), 34 bytes
```
function(m)sum(diff(m),diff(t(m)))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jV7O4NFcjJTMtDcjUAdMlQJam5n@gQGJJUWaFRrKGoZWJjomVuY65jqGOhY6Rpo6xjolOCFANAA "R – Try It Online")
Anonymous function. Originally, I used `apply(m,1,diff)` to get the rowwise diffs (and `2` instead of `1` for columns) but looking at [Stewie Griffin's answer](https://codegolf.stackexchange.com/a/142325/67312) I tried it with just `diff` and it worked.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 33 bytes
```
@(x)sum([diff(x)(:);diff(x')(:)])
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzuDRXIzolMy0NyNaw0rSGMNVB7FjN/2ka0YY6RjrG1mASKAAA "Octave – Try It Online")
### Explanation:
This is an anonymous function taking `x` as input. It takes the difference between all columns, and concatenates it with the difference between the columns of the transposed of `x`. It then sums this vector along the second dimension.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
;ZIẎS
```
[Try it online!](https://tio.run/##y0rNyan8/986yvPhrr7g////R0cb6igY6SgY6yiYxOooRJvoKJjqKJjpKJiDeOY6CkBpC6CK2FgA "Jelly – Try It Online")
There are a couple ASCII-only versions too: `;ZIFS` `;ZISS`
[Answer]
# JavaScript (ES6), ~~68~~ 67 bytes
```
m=>m.map(r=>s+=[...l=r].pop()-r[0],s=0)|m[0].map(v=>s+=l.pop()-v)|s
```
### Formatted and commented
```
m => // given a matrix m
m.map(r => // for each row r of m
s += [...l = r].pop() - r[0], // add to s: last value of r - first value of r
s = 0 // starting with s = 0
) | //
m[0].map(v => // for each value v in the first row of m:
s += l.pop() - v // add to s: last value of last row of m - v
) | //
s // return s
```
Because the minimum size of the input matrix is 2x2, `m.map(...)|m[0].map(...)` is guaranteed to be coerced to `0`. That's why it's safe to return the final result with `|s`.
### Test cases
```
let f =
m=>m.map(r=>s+=[...l=r].pop()-r[0],s=0)|m[0].map(v=>s+=l.pop()-v)|s
console.log(f( [[1, 2], [1, 2]] )) // => 2
console.log(f( [[8, 7, 1], [4, 1, 3], [5, 5, 5]] )) // => -9
console.log(f( [[1, 2, 3], [4, 5, 6], [7, 8, 9]] )) // => 24
console.log(f( [[9, 9, 9, 9, 9], [9, 9, 9, 9, 9]] )) // => 0
console.log(f( [[1, 3, 14], [56, 89, 20], [99, 99, 99]] )) // => 256
console.log(f( [[1, 2, 3, 4], [4, 5, 6, 7], [7, 1, 8, 2]] )) // => 9
console.log(f( [[13, 19, 478], [0, 12, 4], [45, 3, 6], [1, 2, 3]] )) // => -72
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 7 bytes
```
dG!dhss
```
[Try it online!](https://tio.run/##y00syfn/P8VdMSWjuPj//@hoQx0FYx0FQ5NYa4VoUzMdBQtLHQUjAxDPEsiC4NhYBQUA "MATL – Try It Online")
### Explanation:
Suppose the input is
```
[8 7 1; 4 1 3; 5 5 5]
d % Difference between rows of input
% Stack:
% [-4 -6 2; 1 4 2]
G % Grab the input again. Stack:
% [-4 -6 2; 1 4 2]
% [8 7 1; 4 1 3; 5 5 5]]
! % Transpose the bottom element. Stack:
% [-4 -6 2; 1 4 2]
% [8 4 5; 7 1 5; 1 3 5]
d % Difference between rows. Stack:
% [-4 -6 2; 1 4 2]
% [-1 -3 0; -6 2 0]
h % Concatenate horizontally. Stack:
% [-4 -6 2 -1 -3 0; 1 4 2 -6 2 0]
ss % Sum each column, then sum all column sums. Stack:
% -9
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
ø«€¥OO
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//8I5Dqx81rTm01N/////oaENjHQVDSx0FE3OLWB2FaAMgzwjIA7FNTHUUgLJmILahjgJQ2Dg2FgA "05AB1E – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
+/@,&({:-{.)|:
```
[Try it online!](https://tio.run/##ZY5NCsJADIX3PcVblYq1dn6bDAgeRHEhFnHTA7R3HxOKg1aSbN57X5JXziNOCfvjua2bOR3mbrekqnrcnxNG3CyuFxhYnSI6FQmDiF7GIWj92so4sQOiBAlc7KA2/9eWdzCCRxDD9mBeu6T895XPHX2Jtp8a2cTwA6GHsZoOAsUVzvkN "J – Try It Online")
## Explanation
```
+/@,&({:-{.)|: Input: matrix M
|: Transpose
( ) Operate on M and M'
{: Tail
- Minus
{. Head
,& Join
+/@ Reduce by addition
```
[Answer]
# Pyth, 7 bytes
```
ss.+M+C
```
[Try it here.](https://pyth.herokuapp.com/?code=ss.%2BM%2BC&input=%5B%5B8%2C+7%2C+1%5D%2C+%5B4%2C+1%2C+3%5D%2C+%5B5%2C+5%2C+5%5D%5D&debug=0)
My first ever answer in a golfing language! Thanks to [@EriktheOutgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) for -1 byte!
## Explanation
```
ss.+M+C ~ This is a full program with implicit input (used twice, in fact)
C ~ Matrix transpose. Push all the columns;
+ ~ Concatenate with the rows;
.+M ~ For each list;
.+ ~ Get the deltas;
s ~ Flatten the list of deltas;
s ~ Get the sum;
~ Print Implicitly;
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
ΣṁẊ-S+T
```
[Try it online!](https://tio.run/##yygtzv7//9zihzsbH@7q0g3WDvn//390tKGOkY6xjkmsTrSJjqmOmY45kGWuY6hjoWMUGwsA "Husk – Try It Online")
-1 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) taking my focus away from the `S` and `¤` and towards the `m` (which should've been `ṁ`).
-1 thanks to [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb) abusing `S`.
Explanation:
```
ΣṁẊ-S+T 3-function composition
S (x -> y -> z) (f) -> (x -> y) (g) -> x (x) (implicit): f x g x
+ f: [x] (x) -> [x] (y) -> [x]: concatenate two lists
T g: [[x]] (x) -> [[x]]: transpose x
ṁ (x -> [y]) (f) -> [x] (x) -> [y]: map f on x and concatenate
Ẋ f: (x -> y -> z) (f) -> [x] (x) -> [z]: map f on splat overlapping pairs of x
- f: TNum (x) -> TNum (y) -> TNum: y - x
Σ [TNum] (x) -> TNum: sum x
```
[Answer]
# APL, ~~18~~ 15 bytes
```
{-+/∊2-/¨⍵(⍉⍵)}
```
[Try it online!](http://tryapl.org/?a=%7B-+/%u220A2-/%A8%u2375%28%u2349%u2375%29%7D2%202%u23741%2C%202%2C%201%2C%202&run)
[Answer]
# [Haskell](https://www.haskell.org/), 60 bytes
```
e=[]:e
z=zipWith
f s=sum$(z(-)=<<tail)=<<(s++foldr(z(:))e s)
```
[Try it online!](https://tio.run/##lVBLa8MwDL77V@jQQ0IdSDznVer9jR2CD4El1DTpSp1dUvrbM0lNX9BRamxkW/oe0qb226brpqkxlV01YjSj23@5YSNa8Mb/9otgDKLQrNdD7TqKgV8u25/u@4CJVRg24MOpr90ODOwPbjfAAtqqSiR8SEi0lVClmYSilKBiepV4Ox9rAZc4RoLrFWU58v@rZT5BIbCQkKMQYTVGlGVJCbSfMiEwKmfJuVxzeUZXJEPK8j@k0ogk99fNPT182KfIWLwzlXvJNLu5laDvDGPvs@eEbT@MDqHcJikis84Lqo3xpS4sKTNml8HTNOx5QLkS0Wn6Aw "Haskell – Try It Online") Uses the [shorter transpose](https://codegolf.stackexchange.com/a/111362/56433) I found a while ago.
### Explanation
`e` is an infinite list of empty lists and used for the transposing.
`z` is a shorthand for the `zipWith` function, because it is used twice.
```
f s= -- input s is a list of lists
foldr(z(:))e s -- transpose s
s++ -- append the result to the original list s
=<<( ) -- map the following function over the list and concatenate the results
(z(-)=<<tail) -- compute the delta of each list by element-wise subtracting its tail
sum$ -- compute the sum of the resulting list
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
orignally based of [@sundar's design](https://codegolf.stackexchange.com/a/170882/81957)
```
⟨≡⟨t-h⟩ᵐ²\⟩c+
```
## Explanation
```
⟨≡ \⟩ # Take the original matrix and it's transpose
ᵐ # and execute the following on both
² # map for each row (this is now a double map "ᵐ²")
⟨t h⟩ # take head and tail
- # and subtract them from each other (sum of deltas in a row)
c+ # and add all the values
# (we have two arrays of arrays so we concat them and sum them)
```
the `⟨⟩` are messing up formatting, sorry
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8FY86FwLJEt2MR/NXPtw64dCmGCAjWfv//@hoQ2MdBUNLHQUTc4tYHYVoAyDPCMgDsU1MdRSAsmYgtqGOAlDYODb2fxQA "Brachylog – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~22~~ 16 bytes
```
⟨≡{s₂ᶠc+ᵐ-}ᵐ\⟩+ṅ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8FY86F1YXP2pqerhtQbL2w60TdGuBRMyj@Su1H@5s/f8/OtpQR8FYR8HQJFZHIdrUTEfBwlJHwcgAxLMEsiA4NvZ/FAA "Brachylog – Try It Online")
*(-6 bytes inspired by @Kroppeb's suggestions.)*
```
?⟨≡{s₂ᶠc+ᵐ-}ᵐ\⟩+ṅ. Full code (? and . are implicit input and output)
?⟨≡{ }ᵐ\⟩ Apply this on both the input and its transpose:
s₂ᶠ Get pairs of successive rows, [[row1, row2], [row2, row3], ...]
c Flatten that: [row1, row2, row2, row3, row3, row4, ...]
+ᵐ Sum the elements within each row [sum1, sum2, sum2, sum3, ...]
- Get the difference between even-indexed elements (starting index 0)
and odd-indexed elements, i.e. sum1+sum2+sum3+... - (sum2+sum3+sum4+...)
This gets the negative of the usual difference i.e. a-b instead of b-a
for each pair of rows
+ Add the results for the input and its transpose
ṅ Negate that to get the sign correct
. That is the output
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/) `-x`, ~~11~~ ~~10~~ 9 bytes
```
cUy)®än x
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=Y1V5Ka7kbiB4&input=W1sxMywxOSw0NzhdLFswLDEyLDRdLFs0NSwzLDZdLFsxLDIsM11dCi14)
---
## Explanation
```
c :Concatenate
U : Input array
y : Transpose
) :End concatenation
® :Map
än : Deltas
x : Reduce by addition
:Implicitly reduce by addition and output
```
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 48 bytes
```
[ dup flip [ [ differences Σ ] map Σ ] bi@ + ]
```
[Try it online!](https://tio.run/##fZLNToQwFIX3PMVxbSRQyk@daNwZN26Mq8ksEEpsZoZBKAsz4Wl8H18J77TYMMSxl7SXJt@5p72t8kIf2vH15en58RZb2dZyh05@9LIuZId9rt/N5Hc616rTqrCbfl@r4lBKNK3U@rNpVa2x8o4eaBwpQjAMbh3w/7jC3T2YgzOkBJ5wTmtkstjEX1IGvhFnpaOJjpGYLCVNcZlm3NHCxbD4Gy4ZD2alI4Tc@k2QCbDAyojpO1OxpeNk4ZzPvKeT@5D8Ly/S4LNjU2kBnmYGCRCyX6WYRBPXjcjI2EtLmTeMa5R9g2qnGqwpSlVVsrX9//7Chvrd2ORNPeAam/G0Qe@h2PrjDw "Factor – Try It Online")
## Explanation:
It's a quotation (anonymous function) that takes a sequence of sequences (matrix) from the data stack as input and leaves a number (sum) on the data stack as output. Assuming `{ { 1 2 3 } { 4 5 6 } }` is on the data stack when this quotation is called...
* `dup` Duplicate an object.
**Stack:** `{ { 1 2 3 } { 4 5 6 } } { { 1 2 3 } { 4 5 6 } }`
* `flip` Transpose a matrix.
**Stack:** `{ { 1 2 3 } { 4 5 6 } } { { 1 4 } { 2 5 } { 3 6 } }`
* `[ [ differences Σ ] map Σ ]` Push a quotation for `bi@` to use later.
**Stack:** `{ { 1 2 3 } { 4 5 6 } } { { 1 4 } { 2 5 } { 3 6 } } [ [ differences Σ ] map Σ ]`
* `bi@` Apply a quotation to two objects. (Inside the quotation now...)
**Stack:** `{ { 1 2 3 } { 4 5 6 } }`
* `[ differences Σ ]` Push a quotation for `map` to use later.
**Stack:** `{ { 1 2 3 } { 4 5 6 } } [ differences Σ ]`
* `map` Take a sequence and a quotation and apply the quotation to each element in the sequence, collecting the results into a new sequence of the same length. (Inside the quotation now...)
**Stack:** `{ 1 2 3 }`
* `differences` Calculate the first-order differences of a number sequence.
**Stack:** `{ 1 1 }`
* `Σ` Sum the elements of a sequence.
**Stack:** `2`
* Now `map` applies the quotation to the next row and the result is also `2`.
**Stack:** `{ 2 2 }`
* `Σ` Sum the elements of a sequence.
**Stack:** `4`
* Thus, the first result of `bi@` is `4`. Now `bi@` repeats the process for its second input (the transposed matrix) and ends up with `9`.
**Stack:** `4 9`
* `+` Add.
**Stack:** `13`
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 9 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
:⌡-≤H⌡-¹∑
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMTkyJTNBJXUyMzIxLSV1MjI2NEgldTIzMjEtJUI5JXUyMjEx,inputs=JTVCJTVCMSUyQyUyMDIlMkMlMjAzJTJDJTIwNCU1RCUyQyUyMCU1QjQlMkMlMjA1JTJDJTIwNiUyQyUyMDclNUQlMkMlMjAlNUI3JTJDJTIwMSUyQyUyMDglMkMlMjAyJTVEJTVE) (`→` added because this takes input on the stack)
Explanation:
```
: duplicate ToS
⌡ for each do
- get deltas
≤ get the duplicate ontop
H rotate it anti-clockwise
⌡ for each do
- get deltas
¹ wrap all of that in an array
∑ sum
```
[Answer]
# Mathematica, 45 bytes
```
Tr@Flatten[Differences/@#&/@{#,Transpose@#}]&
```
**Input**
>
> [{{13, 19, 478}, {0, 12, 4}, {45, 3, 6}, {1, 2, 3}}]
>
>
>
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 19 bytes
```
0q~_z+2few:::-:+:+-
```
Input is a list of lists of numbers. [**Try it online!**](https://tio.run/##S85KzP3/36CwLr5K2ygttdzKykrXSttKW/f//@hoQ2MFQ0sFE3OLWIVoAwVDIwUTIMPEVMFYwQzIMFQwUjCOjQUA "CJam – Try It Online")
### Explanation
```
0 e# Push 0
q~ e# Evaluated input.
_ e# Duplicate
z e# Zip (transpose)
+ e# Concatenate. This gives a lists of lists of numbers, where the
e# inner lists are the original rows and the columns
2few e# Replace each inner list of numbers by a list of overlapping
e# slices of size 2. We not have three-level list nesting
:::- e# Compute difference for each of those size-two slices. We now
e# have the deltas for each row and column
:+ e# Concatenate all second-level lists (de-nest one level)
:+ e# Sum all values
- e# Subtract from 0, to change sign. Implicitly display
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 12 bytes
```
(+/⊢⌿,⊣/)⌽-⊖
```
[Try it online!](https://tio.run/##dVHBSsNAEL33K@aWHWro7maTzfo3oRIJBiJtLlJ6ESkYE9GDfkD9AA/qpSCCnzI/EidtUqvizjIMO@@9fbObnOf@yUWSF6f@NE/m82za0u1DVtDqTrYpZzGeULWm@uOIqqcJUv3uU/XYtiX3FtS80fV6xmVKzebYS5Ms97ji8xndXHnFmbccCVrdCwUatwnhn1WC3kFjsKBQGFAQoAiB4xerhM9nt9ftUIZREQoLMbg/YG12WAd94EGJP7FykA1AGb49gtiBlsxgcLcHAsuG0YEHML0LsJ0PxU6@hy1hsMuyDoyNUUhQeksKmRxhPwl2s1k9WlB1ya@4pHoTQMA/wE1qXpUcU/PivgA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `d`, 5 bytes
```
:∩"v¯
```
[Try it online](https://vyxal.pythonanywhere.com/#WyJkIiwiIiwiOuKIqVwidsKvIiwiIiwiW1sxLCAyLCAzXSwgWzQsIDUsIDZdLCBbNywgOCwgOV1dIl0=), or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJkQSIsIiIsIjriiKlcInbCryIsIiIsIltbMSwgMl0sIFsxLCAyXV1cbltbOCwgNywgMV0sIFs0LCAxLCAzXSwgWzUsIDUsIDVdXVxuW1sxLCAyLCAzXSwgWzQsIDUsIDZdLCBbNywgOCwgOV1dXG5bWzksIDksIDksIDksIDldLCBbOSwgOSwgOSwgOSwgOV1dXG5bWzEsIDMsIDE0XSwgWzU2LCA4OSwgMjBdLCBbOTksIDk5LCA5OV1dXG5bWzEsIDIsIDMsIDRdLCBbNCwgNSwgNiwgN10sIFs3LCAxLCA4LCAyXV1cbltbMTMsIDE5LCA0NzhdLCBbMCwgMTIsIDRdLCBbNDUsIDMsIDZdLCBbMSwgMiwgM11dIl0=).
Explanation:
```
: # Duplicate
∩ # Transpose
" # Pair
v¯ # Deltas of each
# Flatten and sum with the d flag
```
[Answer]
# MY, 9 bytes
```
ωΔω⍉Δ ḟΣ↵
```
[Try it online!](https://tio.run/##y638//9857kp5zsf9QIphYc75p9b/Kht6////6OjLXQUzHUUDGN1FKJNgLSOgjGIaaqjAEKxsQA)
~~Since I cannot ping Dennis in chat to pull MY (due to a suspension), this will currently not work. (`Δ` previously didn't vecify when subtracting)~~
Thanks to whomever got Dennis to pull MY!
## How?
* `ωΔ`, increments of the first command line argument
* `ω⍉Δ`, increments of the transpose of the first command line argument
* , in a single list
* `ḟ`, flatten
* `Σ`, sum
* `↵`, output
[Answer]
## [Pyt](http://github.com/mudkip201/pyt), 11 bytes
```
Đ⊤ʁ-⇹ʁ-áƑƩ~
```
Explanation:
```
Implicit input (as a matrix)
Đ Duplicate the matrix
⊤ Transpose the matrix
ʁ- Get row deltas of transposed matrix
⇹ Swap top two elements on the stack
ʁ- Get row deltas of original matrix
á Push the stack into an array
Ƒ Flatten the array
Ʃ Sum the array
~ Flip the sign (because the deltas are negative, as subtraction was performed to obtain them)
Implicit output
```
] |
[Question]
[
We define the *hyper-average* of an array / list (of numbers) the arithmetic mean of the sums of its prefixes.
For example, the hyper-average of the list `[1, 4, -3, 10]` is computed in the following manner:
* We get the prefixes: `[1], [1, 4], [1, 4, -3], [1, 4, -3, 10]`.
* Sum each: `[1, 5, 2, 12]`.
* And now get the arithmetic mean of the elements in this list: `(1 + 5 + 2 + 12) / 4 = 5`.
A *pseudo-element* of an array is an element whose value is *strictly* lower than its hyper-average. Hence, the pseudo-elements of our example list are `1`, `4` and `-3`.
---
Given a list of floating-point numbers, your task is to return the list of pseudo-elements.
* You don't have to worry about floating-point inaccuracies.
* The input list will never be empty and it may contain both integers and floats. If mentioned, integers may be taken as floats (with `<integer>.0`)
* You may assume that the numbers fit your language of choice, but please do not abuse that in any way.
* Optionally, you may take the length of the array as input as well.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard rules for the tag apply. The shortest code in bytes (**in each language**) wins!
---
# Test Cases
```
Input -> Output
[10.3] -> []
[5.4, 5.9] -> [5.4, 5.9]
[1, 4, -3, 10] -> [1, 4, -3]
[-300, -20.9, 1000] -> [-300, -20.9]
[3.3, 3.3, 3.3, 3.3] -> [3.3, 3.3, 3.3, 3.3]
[-289.93, 912.3, -819.39, 1000] -> [-289.93, -819.39]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes
-1 bytes thanks to [Magic Octopus Urn](https://codegolf.stackexchange.com/users/59376/magic-octopus-urn)
```
ηOO¹g/‹Ï
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3HZ//0M70/UfNew83P//f7SukYWlnqWxjoKloZEekNK1MLTUM7bUUTA0MDCIBQA)
```
η # Get prefixes
O # Sum each
O¹g/ # Get the mean ( length(prefix list) equals length(original list) )
‹Ï # Keep only the value that are less than the mean
```
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
Using the new `ÅA` command.
```
ηOÅA‹Ï
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3Hb/w62Ojxp2Hu7//z9a18jCUs/SWEfB0tBID0jpWhha6hlb6igYGhgYxAIA "05AB1E – Try It Online")
```
η # Get prefixes
O # Sum each
ÅA # Get the mean
‹Ï # Keep only the value that are less than the mean
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
ttYsYm<)
```
[Try it online!](https://tio.run/##y00syfn/v6Qksjgy10bz//9oQx0FEx0FXWMdBUODWAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##VYsxCoAwDEV3T9FNhCYkjYIBR4/gYCmC7nay96/p4OAS/nv/J1/lrmctJT4xL0PtAfp93WpiQjm6NOHo3YRqkb2zDOIdkyEIkWEg1GaoOUFrf6cNw6yohsqhWZhZUb6nFw).
### Explanation
```
tt % Implicitly input array. Duplicate twice
Ys % Cumulative sum
Ym % Arithmetic mean
< % Less than? (element-wise). Gives an array containing true / false
) % Reference indexing : use that array as a mask to select entries
% from the input. Implicitly display
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/) v2.0a0 [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), ~~12~~ ~~11~~ ~~10~~ 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
<Wå+ x÷Wl
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LWY&code=PFflKyB491ds&input=WzEsIDQsIC0zLCAxMF0)
-1 byte thanks to [ETH](https://codegolf.stackexchange.com/users/42545/ethproductions) pointing out a redundant character.
```
<Wå+ x÷Wl :Implicit filter of each element in input array W
< :Is less than
Wå+ : Cumulatively reduce W by addition
x : Reduce by addition
÷Wl : Divide by length of W
```
[Answer]
# [Python 3](https://docs.python.org/3/) with [Numpy](http://www.numpy.org/), 48 bytes
```
lambda x:x[x<mean(cumsum(x))]
from numpy import*
```
Input and output are Numpy arrays. [Try it online!](https://tio.run/##VYvLCsMgEEX3@YpZajGisYEa2i@xWdiHNFAfWAPm660GuuhmuOfcO2FLL@9EMZdreWt7e2jIU1b5bJ/aoftqP6tFGeO5M9FbcKsNGyw2@JgOxfgICRYHSnFGxUxAjfRIYKSyZU6gQi8IcNa4F4xVHhiVTbFdClr7v7NPh5OksrLkQ9P9iUsqfm/z1EGIi0vIIB2j3lDCGJfuCw "Python 3 – Try It Online")
[Answer]
## Haskell, 39 bytes
```
f l=filter(<sum(scanl1(+)l)/sum(1<$l))l
```
[Try it online!](https://tio.run/##ZYzBDoIwEETvfsUeOLSRrt1WEprAlxgPRGlsXKoB/P5aDh4sl0lm3sw8huU5MqfkgXsfeB1n0S2fSSy3ITKJo2R52jx1FUvJaRpChB7urwMAvOcQV6jAw4U02muRNXiuoUFX5lRDBsrWQLpkymqdmdHoNqx3BYt59ye7C9M6dJk5MltFteTQ/u7SFw "Haskell – Try It Online")
Unfortunately `length` is of type `Int`, so I cannot use it with floating point division `/` and I have to use a workaround: `sum(1<$l)`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~10~~ 9 bytes
Thanks @Zgarb for golfing off 1 byte!
```
f</L⁰Σ∫⁰⁰
```
[Try it online!](https://tio.run/##yygtzv7/P81G3@dR44Zzix91rAbSQPT///9oXSMLSz1LYx1LQyM9Yx1dC0NLPWNLHUMDA4NYAA "Husk – Try It Online")
### Ungolfed/Explanation
```
-- argument is ⁰ (list)
f ⁰ -- filter the original list with
< -- element strictly smaller than
Σ∫⁰ -- sum of all prefixes
/L⁰ -- averaged out
```
[Answer]
# Java 8, 81 bytes
This lambda expression accepts a `List<Float>` and mutates it. The input list's iterator must support removal (`ArrayList`'s does, for example). Assign to `Consumer<List<Float>>`.
```
a->{float l=0,t=0,u;for(float n:a)t+=n*(a.size()-l++);u=t/l;a.removeIf(n->n>=u);}
```
## Ungolfed lambda
```
a -> {
float l = 0, t = 0, u;
for (float n : a)
t += n * (a.size() - l++);
u = t / l;
a.removeIf(n -> n >= u);
}
```
[Try It Online](https://tio.run/##fZJNa@MwEIbPzq/QUd7Eqh23UNe1YSm7UOhCocfSw9SRg1JZCtYoSzf4t2fHcUpK3EYgHeZ95lOzgg1Edi3NavG2W/tXrSpWaXCO/QFl2HYSrFu1AZTMISCJK3IQHpUWtTcVKmvEnTXON7K9PWoPyuHtb20By5ItJT466Rf2l5aNNOhYsYOo3Na9znQRz5Cuz2vb8sFmbiDEaWF@cBBO/ZM8jPR0Gua@wAudg2hlYzfyvuYmKk1Z@DDvdkE@oWKHDg61bqxasIb64E/YKrN8fmHQLl1IbbGTs6/1@YWICpykCpmRfz9Zxx4fZ5vEIq272ffAlbisZ@xKZGephJiei1J6kvgsG6Vx3KPzmIL2dHyeT0Uf9PQ9m2GeXYusJ7NkvveIrpNMpMd0I98uH5noRxk/DJHBHU2W3QwD7v8gCIIvN4bR4g3zP8o/2xbePzH8RHICXC/zfZYwzL9tbbSNAqpKrpErQ15U09O7Q9kI61HQ7hvUZpBG/U6CbtLt/gM)
## Acknowledgments
* -3 bytes thanks to *Kevin Cruijssen*
* -17 bytes thanks to *Nevay*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
+\S÷L<Ðf@
```
[Try it online!](https://tio.run/##y0rNyan8/187Jvjwdh@bwxPSHP4fbn/UtOb//@hoQwM941gdrmhTPRMdBVM9SxDbUEcByNE11lEwNADxdY0NDIB8IwM9S5CQAVjQWA8oj0KAlRpZWOpZAvmWhkYgYV0LQ0s9Y5i2WAA "Jelly – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~78~~ ~~76~~ ~~71~~ 66 bytes
*-7 bytes thanks to Mr. Xcoder.*
```
lambda l:[x for x in l if x<sum(sum(l[:i])for i in range(len(l)))]
```
[Try it online!](https://tio.run/##Vcy9DsIgGIXh3av4RkiA8ONQmnolyICxKMlX2mBN8OpRFqPDu5wnOdtrv69Zt3g6NwzL5RoAR1chrgUqpAwIKUKdHs@F9NCNydOuqWsJ@TYTnDNBSqlvW0l5J5E4xY6MG6akp/TwXY0w7Kc/43qwwhoGVukPAx@UFcYyUFL2l/YG "Python 2 – Try It Online")
[Answer]
# [Perl 6](http://perl6.org/), 31 bytes
```
{.grep(flat([\,] $_).sum/$_>*)}
```
[Try it online!](https://tio.run/##HYndCoIwGIZv5UVGzHBf31IDUXcjFcMDJ4GSbHYg4rWv7Oz5mXs/3uK04uTQxo0G38/Sjd0i74/sCWFTCp/pIqw5p3usEboVibBoDTbp/n94hWVP4N4ejWbKTYampAIlVQdqFFA5NB@icmaoK1P1C8ymjl8 "Perl 6 – Try It Online")
[Answer]
# JavaScript (ES6), ~~56~~ ~~55~~ 52 bytes
```
a=>a.filter(x=>x<t/a.length,a.map(x=>t+=s+=x,s=t=0))
```
---
## Test it
```
o.innerText=(f=
a=>a.filter(x=>x<t/a.length,a.map(x=>t+=s+=x,s=t=0))
)(i.value=[1,4,-3,10]);oninput=_=>o.innerText=f(i.value.split`,`.map(eval))
```
```
<input id=i><pre id=o>
```
[Answer]
# [R](https://www.r-project.org/), 31 bytes
```
function(l)l[l<mean(cumsum(l))]
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jRzMnOscmNzUxTyO5NLe4NBcoohn7P00jWcNQx0RH11jH0EBT8z8A "R – Try It Online")
[Answer]
# [C# (Mono)](http://www.mono-project.com/), 95 bytes
```
using System.Linq;a=>a.Where(d=>d<new int[a.Length].Select((_,i)=>a.Take(i+1).Sum()).Average())
```
[Try it online!](https://tio.run/##TU9fS8MwEH/Ppzh8SjALFn3bWpDhRJkgVNjDGBLTW3esTbBJJzL62esVHAzu4e74/XVx1gYfxj6Sr6H8jQnbubi@zJr891wI19gY4V2cRUw2kYNToAreLHmp@LnqvVtUof9qcLvTF@4yNA26RMFH84weO3Lm5cn3LXaWkf@EooA95KPNC2s2B@xQVnlRLTz@APm0tWaNvk6HnSlxUpPyU5OawB/2iJJuM2XKvpVKmccTC9fI68iRl2wbGjSbjhJyDZQxddzMvAZOfaOBZy8nm0twOEOm4UHD7F5DdgeDUoqFBjGMfw "C# (Mono) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 72 bytes
```
lambda x:[*filter((sum(-~a*b for a,b in enumerate(x))/len(x)).__gt__,x)]
```
[Try it online!](https://tio.run/##RY1BDoMgFETXcoq/BINUY11o4kksIdhCa6Jo4JvYTa9OtQu7mnmTzMzyxtfsymjbWxz11D80bE2X2mFE4ykN60Szj057sLMHzXsYHBi3TsZrNHRj7DIad6hQ6olK8Y3JiCaguutgArTQkaQrclFKvptKXDlUov5BwWGnrORQ5JJIclyc1ePov9OQZPGDQ2rpGTIWvw)
[Answer]
# [Python 3](https://docs.python.org/3/), 76 bytes
```
lambda x:[w for w in x if w<sum(u*v+v for u,v in enumerate(x[::-1]))/len(x)]
```
Input and output are lists of numbers. [Try it online!](https://tio.run/##VYvLDsIgEEX3fsUsQSlCsUkh@iXIokaITVraVPrw6xGauHAzuefcO@MnvAYvorvdY9f0j2cDm9IruGGCFVoPG7QO1ut77tF8XE7L3sxkyZ31c2@nJli0aaUKbjA@d9ajDZuYZyGPtOaMCkNAV/RCoKIyZ04gQSEIcJa5EIwlLhmVWbFdCpr6v7NPy1pSmVjyMuui5pKK35tRBxin1gfkUMA4Hr4)
This works in Python 2 too (with the obvious replacement for `print` syntax in the footer).
[Answer]
# Pyth - 10 bytes
```
<#.OsM._QQ
```
[Try it online here](http://pyth.herokuapp.com/?code=%3C%23.OsM._QQ&input=%5B1%2C+4%2C+-3%2C+10%5D&debug=0).
[Answer]
# Mathematica, 35 bytes
```
Cases[#,x_/;x<#.Range[#2,1,-1]/#2]&
```
`Function` which expects a list of numbers as the first argument `#` and the length of the list as the second argument `#2`. `#.Range[#2,1,-1]/#2` takes the dot product of the input list `#` and the the list `Range[#2,1,-1] == {#2,#2-1,...,1}`, then divides by the length `#2`. Then we return the `Cases` `x_` in the input list `#` which are less than the hyper-average.
Without the length as a second argument, we need `6` more bytes:
```
Cases[#,x_/;x<#.Range[h=Tr[1^#],1,-1]/h]&
```
[Answer]
# TI-Basic, 9 bytes
```
Ans*(Ans<mean(cumSum(Ans
```
[Answer]
# [Factor](https://factorcode.org/), 36 bytes
```
[ dup cum-sum mean '[ _ < ] filter ]
```
[Try it online!](https://tio.run/##bZHBisIwEIbvfYrf054S0kbBuOJV9rIX8SSyhJiyRVO7yfQg0mevwUaRtQNzmXzf/IQptaGz77ebr@/1Akfra3uC0/TLA2mqAlUmoPSX@wzB/rW2Njag8Zbo0viqJnxm2TUDrsgFl@gwXhOwVWTQ3dEZn8ZW43RCn8ywHFMwGTPGnGQkZhCYFAKsEHFDLsQ/LQkvzCDJ@IPXHpPemCGumCuuJFRexBmb54rLZ/IjLjGP1y7r@h0ObQPTOhZaB2d1jY8dfrDEHmV1Iuux751uEA9ijry/AQ "Factor – Try It Online")
## Explanation:
It's a quotation (anonymous function) that takes a sequence from the data stack as input and leaves a sequence on the data stack as output. Assuming `{ 1 4 -3 10 }` is on the data stack when this quotation is called...
* `dup` Duplicate an object.
**Stack:** `{ 1 4 -3 10 } { 1 4 -3 10 }`
* `cum-sum` Take the cumulative sum.
**Stack:** `{ 1 4 -3 10 } { 1 5 2 12 }`
* `mean` Take the mean.
**Stack:** `{ 1 4 -3 10 } 5`
* `'[ _ < ] filter` Take the elements from a sequence that are less than the number on top of the stack.
**Stack:** `{ 1 4 -3 }`
[Answer]
# Pyth, 12 11 bytes
```
f<T.OsM._QQ
```
*-1 byte thanks to Mr. Xcoder*
[Try it online!](http://pyth.herokuapp.com/?code=f%3CT.OsM._QQ&test_suite=1&test_suite_input=%5B10.3%5D%0A%5B5.4%2C+5.9%5D%0A%5B1%2C+4%2C+-3%2C+10%5D%0A%5B-300%2C+-20.9%2C+1000%5D%0A%5B3.3%2C+3.3%2C+3.3%2C+3.3%5D%0A%5B-289.93%2C+912.3%2C+-819.39%2C+1000%5D&debug=0)
[Answer]
# [Perl 5](https://www.perl.org/), 51 + 1 (-a) = 52 bytes
```
$a+=$_*(@F-$c++)for@F;for(@F){print$_,$"if$_<$a/@F}
```
[Try it online!](https://tio.run/##K0gtyjH9/18lUdtWJV5Lw8FNVyVZW1szLb/Iwc0aSAJFNKsLijLzSlTidVSUMtNU4m1UEvUd3Gr//9c1srDUszRWsDQ00jNW0LUwtNQztlQwNDAw@JdfUJKZn1f8X9fXVM/A0OC/biIA "Perl 5 – Try It Online")
[Answer]
# PHP, 84 bytes
```
for($i=--$argc;$i;)$s+=$i--/$argc*$r[]=$argv[++$k];foreach($r as$x)$x<$s&&print$x._;
```
takes input from command line arguments. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/8433f2d14f50e8b8041814c6be3936b7c77933f1).
---
summing up the partial lists is the same as summing up each element multiplied with the number of following elements +1 → no need to juggle with bulky array functions. It´s still long, though.
[Answer]
# [Röda](https://github.com/fergusq/roda), ~~46~~ ~~41~~ 39 bytes
```
f l{l|[_]if[_1*#l<seq(1,#l)|l[:_]|sum]}
```
[Try it online!](https://tio.run/##bY3LDoIwEEXX9CsmyqKY0rRUE2r8k6YpRkokKRRB40L4dqS68rG5izPn3ul9eZznCtzDjcroulKGb9buMNgL5mTtktGpvdHjcGv0NA9nf8cJPFBUV@A720LpURT1trydLC5iQyA2RQIjdH3dXnGhYqOLBEXWDXYR33Sl9GphpW8tmhBqjnUbJiusOKNCh/r70Yvt6JbAjspvzikjsA2RipBLl307qWDsZWSMyqCwP5KggsBH/MxkuaRyuUmeBSXNuaTi7@A0PwE "Röda – Try It Online")
[Answer]
# J, 15 bytes
```
#~[<[:(+/%#)+/\
```
[Try it online!](https://tio.run/##y/r/P81WT7ku2ibaSkNbX1VZU1s/hosrNTkjXyFNwVDBRCHeWMHQAC4Sb2xgoBBvZKBnCRQ1MPj/HwA) Expects a J-style array (negatives represented using `_` instead of `-` and elements separated by spaces -- see the TIO link for examples).
I don't know if there's a way to remove the parentheses around the mean (`+/%#`) but removing that and the cap would be the first thing I'd try to do to golf this further.
# Explanation
Sometimes J reads like (obfuscated) English.
```
#~ [ < [: (+/ % #) +/\
+/\ Sum prefixes
\ Get prefixes
+/ Sum each
(+/ % #) Mean
+/ Sum of array
% Divided by
# Length of array
[ < Input array is less than?
(gives boolean array of pairwise comparisons)
#~ Filter by
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 26 bytes
**Solution:**
```
x@&x<(+/+/'x@!:'1+!#x)%#x:
```
[Try it online!](https://tio.run/##y9bNz/7/v8JBrcJGQ1tfW1@9wkHRSt1QW1G5QlNVucLKUMFEQddYwdDg/38A "K (oK) – Try It Online")
**Examples:**
```
> x@&x<(+/+/'x@!:'1+!#x)%#x:1 4 -3 10
1 4 -3
> x@&x<(+/+/'x@!:'1+!#x)%#x:-289.93 912.3 -819.39 1000
-289.93 -819.39
```
**Explanation:**
Interpretted right-to-left. Struggled with a short way to extract prefixes:
```
x@&x<(+/+/'x@!:'1+!#x)%#x: / the solution
x: / store input in x, x:1 4 -3 10
# / count, return length of x, #1 4 -3 10 => 4
( ) / do everything in the brackets together
#x / count x
! / til, range 0..x, !4 => 0 1 2 3
1+ / add 1 vectorised, 1+0 1 2 3 => 1 2 3 4
!:' / til each, e.g. !1, !2, !3, !4
x@ / index into x at these indices (now we have the prefixes)
+/' / sum (+ over) each, e.g. 1 5 2 12
+/ / sum over, e.g. 20
% / right divided by left, 20%4 => 5 (now we have the hyper average)
x< / boolean list where x less than 5
& / indices where true, &0111b => 1 2 3
x@ / index into x at these indices (now we have the filtered list)
```
**Notes:**
Alternative version taking length of input as parameter (**25** byte solution):
```
> {x@&x<(+/+/'x@!:'1+!y)%y}[1 4 -3 10;4]
1 4 -3
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
<ƇÄS÷ɗ
```
[Try it online!](https://tio.run/##y0rNyan8/9/mWPvhluDD209O/394uY/3sa5HTWsi//@PjjY00DOO1eGKNtUz0VEw1bMEsQ11FIAcXWMdBUMDEF/X2MAAyDcy0LMECRmABY31gPIoBFipkYWlniWQb2loBBLWtTC01DOGaYsFAA "Jelly – Try It Online")
Takes the list on the left and its length on the right, as explicitly permitted.
With newer builtins, Leaky Nun's `+\S÷L<Ðf@` becomes `ÄS÷L<Ƈ@` (which may as well be `ÄS÷L>x@`, using one less piece of the present, but that's besides the point), but taking the length as the right argument trades an `L` and an `@` for one `ɗ`.
```
Ƈ Filter the left argument to elements which
< are less than
S ɗ the sum of
Ä the cumulative sums of the left argument
÷ divided by the right argument.
```
[Answer]
# [Arturo](https://arturo-lang.io), 42 bytes
```
$[a][select a'x[0x<average map a=>[dup+]]]
```
[Try it](http://arturo-lang.io/playground?VbtpQY)
```
$[a][ ; a function taking an argument a
select a 'x [ ; select numbers from a and assign current number to x
0 ; push 0 to the stack
x < ; is x less than...
average ; ...the mean...
map a => [dup +] ; ...of the cumulative sum of a?
] ; end select
] ; end function
```
[Answer]
# [Julia 0.5](http://julialang.org/), 24 bytes
```
~x=x[x.<mean(cumsum(x))]
```
[Try it online!](https://tio.run/##bY@7asMwGIV3PcUhySCBLCSrhqhEoUMfoZvQYCcpdYnt4Av15Fd3pSYuNXQROt@5wP85XMs8m@dptKMbxaG65DU9DVU3VHRkzM8v3UfzhckpjieORHMo6cmtLev@WlNGyBZvl67vyBkWr@Wpp8QpKbSHPcJ5TlwmQjET5k5@VXBWmz/uQqKbaCnDP5XCxIB8RP7gmNIi1FfPPfYPj5vp3ggTtFFpxMleGaHX@0vk4YVauNItF085rEXBsXnGtAsCu2LD8N60oDkvGMoaZz9/Aw "Julia 0.5 – Try It Online")
In modern Julia, `mean` was moved from `Base` to the `Statistics` module:
# [Julia 1.0](http://julialang.org/), 33 bytes
```
~x=x[x.<sum(cumsum(x))/length(x)]
```
[Try it online!](https://tio.run/##bU9LasMwEN3rFI80CwtkVbISiEIUuugRuhNa2Pm6OE6IbaqVr@5KTVxq6GZm3hfms6vKXPph6L3x1vNN012SXXeJy1P6Wh3qU3sOpxvemvP1C72VDAuGVDFI4cjtXtZtVSeUkBd8HJq2IXsYvJe7NiFWCq4czBbWMWKXPASXXD@YXxSUSeePOjJRTZUQ4c4E19EgnpY/dHQpHuKT8bD9w8fObKW5DljLLNLpSmqupv2j5amFWPjSjh/3OYxBwTBbo58HgHkxozhe70hyVlCUNfZu@AY "Julia 1.0 – Try It Online")
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 5.5 bytes (11 nibbles)
```
|$-/+`\@+,@
```
[Nibbles](http://golfscript.com/nibbles/index.html) uses only integers, so I'm "assuming that the numbers fit my language of choice" by omitting decimal points from fractional inputs & padding with zeros where needed. I hope that this is not construed as "abusing" the lenient input rule in any way.
```
|$ # filter input to retain only those that are truthy when:
- # subtracting them from
+ # the sum of
`\@+ # the cumulative sums of the input
/ # divided by
,@ # the length of the input
```
[](https://i.stack.imgur.com/XiyJW.png)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 19 bytes
```
_<$+$+*(aH\,b)/bFIa
```
Makes use of the optional length input.
How?
```
_<$+$+*(aH\,b)/bFIa : -xp; Two args: array and length
a a : First input; array
b b : Second input; length
FIa : Filter: keep items from iterable 'a' which return truthy
_ : Passed element
< : Is less then
aH : Get prefix of a that is # elements long
\,b : Range from one to length
$+* : Sum of each list
$+ : Sum list
/b : Divide by length
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJfPCQrJCsqKGFIXFwsYikvYkZJYSIsIiIsIiIsIidbMTs0Oy0zOzEwXScgJzQnIC14cCJd)
] |
[Question]
[
Based on [this](https://codereview.stackexchange.com/q/133518) question from Code Review
Given a non-empty string of printable ASCII characters, output the *second* non-repeating character. For example, for input `DEFD`, output `F`.
### Input
* A single string, in [any suitable format](http://meta.codegolf.stackexchange.com/q/2447/42963).
### Output
* The *second* character that doesn't repeat, when reading left-to-right, again in a suitable format.
* The output character is case-insensitive.
* If no such character exists (e.g., all characters repeat), output an empty string.
### Rules
* The algorithm should ignore case. That is, `D` and `d` count as the same character.
* Either a full program or a function are acceptable.
* The input string will be guaranteed non-empty (i.e., at least one character in length).
* The input string is ASCII. Any valid character could repeat, not just alphanumeric (this includes spaces).
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
### Examples
Input is on first line, output is on second line.
```
DEFD
F
FEED
D
This is an example input sentence.
x
...,,,..,,!@
@
ABCDefgHijklMNOPqrsTuVWxyz
B
AAAAAABBBBB
Thisxthis
This this.
.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
tk&=s1=)FT)
```
This exits with an error (allowed by default) if there is no second non-repeated character.
[**Try it online!**](http://matl.tryitonline.net/#code=dGsmPXMxPSlGVCk&input=J1RoaXMgaXMgYW4gZXhhbXBsZSBpbnB1dCBzZW50ZW5jZS4n)
### Explanation
```
t % Implicitly take input string. Duplicate
k % Convert to lowercase
&= % 2D array of equality comparisons
s % Sum of each column
1= % True for entries that equal 1
) % Apply logical index to the input string to keep non-repeated characters
TF) % Apply logical index to take 2nd element if it exists. Implicitly display
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 25 bytes
```
i!2=`(.)(?<!\1.+)(?!.*\1)
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYAppITI9YCguKSg_PCFcMS4rKSg_IS4qXDEp&input=REVGRApGRUVEClRoaXMgaXMgYW4gZXhhbXBsZSBpbnB1dCBzZW50ZW5jZS4KLi4uLCwsLi4sLCFACkFCQ0RlZmdIaWprbE1OT1BxcnNUdVZXeHl6CkFBQUFBQUJCQkJCClRoaXNYdGhpcwpUaGlzIHRoaXMu) (The first line enables running the code on a test suite of several inputs.)
### Explanation
This is just a single regex match, the regex being:
```
(.)(?<!\1.+)(?!.*\1)
```
That is, match a character and ensure it doesn't appear anywhere else in the input. The rest is configuration:
* `i` activates case insensitivity.
* `!` tells Retina to print the matches as opposed to counting them.
* `2=` tells Retina to print only the second match as opposed to all of them.
[Answer]
## 05AB1E, ~~15~~ 12 bytes
```
l©v®y¢iy}}1@
```
**Explained**
```
l© # store lower case string in register
v } # for each char in lower case string
®y¢iy # if it occurs once in string, push it to stack
} # end if
1@ # push the 2nd element from stack and implicitly display
```
[Try it online](http://05ab1e.tryitonline.net/#code=bMKpdsKuecKiaXl9fTFA&input=VGhpcyBpcyBhbiBleGFtcGxlIGlucHV0IHNlbnRlbmNlLg)
Saved 3 bytes thanks to @Adnan
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œlµḟœ-Q$Ḋḣ1
```
[Try it online!](http://jelly.tryitonline.net/#code=xZJswrXhuJ_Fky1RJOG4iuG4ozE&input=&args=J1RoaXMgaXMgYW4gZXhhbXBsZSBpbnB1dCBzZW50ZW5jZS4n) or [verify all test cases](http://jelly.tryitonline.net/#code=xZJswrXhuJ_Fky1RJOG4iuG4ozEKw4figqxq4oG3&input=&args=J0RFRkQnLCAnRkVFRCcsICdUaGlzIGlzIGFuIGV4YW1wbGUgaW5wdXQgc2VudGVuY2UuJywgJy4uLiwsLC4uLCwhQCcsICdBQkNEZWZnSGlqa2xNTk9QcXJzVHVWV3h5eicsICdBQUFBQUFCQkJCQicsICdUaGlzeHRoaXMnLCAnVGhpcyB0aGlzLic).
### How it works
```
Œlµḟœ-Q$Ḋḣ1 Main link. Argument: s (string)
Œl Convert s to lowercase.
µ Begin a new, monadic chain. Argument: s (lowercase string)
$ Combine the two links to the left into a monadic chain.
Q Unique; yield the first occurrence of each character.
œ- Perform multiset subtraction, removing the last occurrence of each
character.
ḟ Filterfalse; keep characters that do not appear in the difference.
Ḋ Dequeue; remove the first character.
ḣ1 Head 1; remove everything but the first character.
```
[Answer]
# Python 2, ~~59~~ 58 bytes
Returns a list of a single character, or an empty list if no output. (Stupid case-insensitivity...)
```
s=input().lower();print[c for c in s if s.count(c)<2][1:2]
```
[**Try it online**](http://ideone.com/5CoR7S)
[Answer]
## Batch, 171 bytes
```
@echo off
set a=.
set s=%~1
:l
if "%s%"=="" exit/b
set c=%s:~0,1%
call set t=%%s:%c%=%%
if "%s:~1%"=="%t%" set a=%a%%c%
set s=%t%
if "%a:~2%"=="" goto l
echo %c%
```
Alternative formulation, also 171 bytes:
```
@echo off
set a=.
set s=%~1
:l
if "%s%"=="" exit/b
set c=%s:~0,1%
set t=%s:~1%
call set s=%%s:%c%=%%
if "%s%"=="%t%" set a=%a%%c%
if "%a:~2%"=="" goto l
echo %c%
```
[Answer]
# Pyth, ~~16~~ 15 bytes
1 byte thanks to @mbomb007
```
~~=rz1.xhtfq1/zTzk~~
=rz1:fq1/zTz1 2
```
[Test suite.](http://pyth.herokuapp.com/?code=%3Drz1%3Afq1%2FzTz1+2&test_suite=1&test_suite_input=DEFD%0AFEED%0AThis+is+an+example+input+sentence.%0A...%2C%2C%2C..%2C%2C%21%40%0AABCDefgHijklMNOPqrsTuVWxyz%0AAAAAAABBBBB%0AThisxthis%0AThis+this.&debug=0)
[Answer]
## Actually, 19 bytes
```
;╗`ù╜ùc1=`░ε;(qq1@E
```
[Try it online!](http://actually.tryitonline.net/#code=O-KVl2DDueKVnMO5YzE9YOKWkc61OyhxcTFARQ&input=IkRFRkQi)
Explanation:
```
;╗`ù╜ùc1=`░ε;(qq1@E
;╗ push a copy of input to reg0
`ù╜ùc1=`░ [v for v in s if
ù╜ùc1= s.lower().count(v.lower()) == 1]
ε;(qq append two empty strings to the list
1@E element at index 1 (second element)
```
[Answer]
## C#, 129 128 bytes
```
char c(string i){var s=i.Where((n,m)=>i.ToLower().Where(o=>o==Char.ToLower(n)).Count()<2).ToArray();return s.Length>1?s[1]:' ';}
```
works fine.
I wish i didnt need to lowercase everything
[Answer]
# C# lambda with Linq, 63 bytes
```
s=>(s=s.ToUpper()).Where(c=>s.Count(C=>c==C)<2).Skip(1).First()
```
[Answer]
# C#, 141 bytes
```
void p(){var x=Console.ReadLine().ToLower();var c=0;foreach(char i in x){if(x.Split(i).Length-1<2){if(++c==2){Console.WriteLine(i);break;}}}}
```
# Without break(smallest), 135 bytes
```
void p(){var x=Console.ReadLine().ToLower();var c=0;foreach(char i in x){if(x.Split(i).Length-1<2){if(++c==2){Console.WriteLine(i);}}}}
```
# With for(;;), 150 bytes
```
void p(){for(;;){var x=Console.ReadLine().ToLower();var c=0;foreach(char i in x){if(x.Split(i).Length-1<2){if(++c==2){Console.WriteLine(i);break;}}}}}
```
# Ungolfed with comments
```
void p()
{
var x=Console.ReadLine().ToLower();//Get lowercase version of input from STDIN
var c=0; //Create "count" integer
foreach(char i in x){//For each char in input from STDIN
if(x.Split(i).Length-1<2)//If current char occurs once in input from STDIN
{
if(++c==2){ //Add 1 to count and if count is 2
Console.WriteLine(i); //Print result to STDOUT
break; //Exit foreach
} //End of IF
} //End of IF
} //End of FOREACH
} //End of VOID
```
12 bytes saved by TuukkaX(change count to c).
3 bytes saved by TuukkaX(change string to var).
4 bytes saved by TuukkaX in "With for(;;)"(changed while(true) to for(;;)).
2 bytes saved by TuukkaX(changed c++;if(c==2) to if(++c==2)).
14 bytes saved by Bryce Wagner(changed x.ToCharArray() to x).
[Answer]
# x86 machine code, 43 bytes
In hex:
```
FC31C031C95641AC84C0740E3C6172F63C7A77F28066FFDFEBEC5EAC49740B89F751F2AE5974F44A77F1C3
```
Function takes a pointer to the input string in (E)SI and an integer in (E)DX and returns the (E)DX-th non-repeating character or zero if there's no such character. As a side-effect it converts the string to upper case.
Disassembly:
```
fc cld
31 c0 xor eax,eax
31 c9 xor ecx,ecx
56 push esi
_loop0: ;Search for the NULL char,
41 inc ecx ;counting the length in the process
ac lodsb
84 c0 test al,al
74 0e je _break0 ;NULL found, break
3c 61 cmp al,0x61 ;If char is
72 f6 jb _loop0 ;between 'a' and 'z'
3c 7a cmp al,0x7a ;convert this char
77 f2 ja _loop0 ;to uppercase in-place
80 66 ff df and byte ptr [esi-0x1],0xdf
eb ec jmp _loop0
_break0:
5e pop esi ;Reset pointer to the string
_loop: ;ECX=string length with NULL
ac lodsb ;Load next char to AL
49 dec ecx
74 0b je _ret ;End of string found, break (AL==0)
89 f7 mov edi,esi ;EDI points to the next char
51 push ecx
f2 ae repnz scasb ;Search for AL in the rest of the string
59 pop ecx
74 f4 je _loop ;ZF==1 <=> another instance found, continue
4a dec edx
77 f1 ja _loop ;If not yet the EDX-th non-rep char, continue
_ret:
c3 ret
```
[Answer]
# APL, 32 bytes
```
{⊃1↓⍵/⍨1=+/∘.=⍨(⎕UCS ⍵)+32×⍵∊⎕A}
```
[Try it](http://tryapl.org/?a=%7B%u22831%u2193%u2375/%u23681%3D+/%u2218.%3D%u2368%28%u2395UCS%20%u2375%29+32%D7%u2375%u220A%u2395A%7D%27Hello%27&run) || [All test cases](http://tryapl.org/?a=%u236A%20%7B%u22831%u2193%u2375/%u23681%3D+/%u2218.%3D%u2368%28%u2395UCS%20%u2375%29+32%D7%u2375%u220A%u2395A%7D%20%A8%20%27DEFD%27%20%27FEED%27%20%27This%20is%20an%20example%20input%20sentence.%27%20%27...%2C%2C%2C..%2C%2C%21@%27%20%27ABCDefgHijklMNOPqrsTuVWxyz%27%20%27AAAAAABBBBB%27%20%27Thisxthis%27%20%27This%20this.%27&run)
Explanation:
```
(⎕UCS ⍵)+32×⍵∊⎕A Add 32 to uppercase letters
∘.=⍨ Make an equality matrix
+/ Check how many matches
⍵/⍨1= Keep elements with 1 match
1↓ Drop the first one
⊃ Return the second one
```
I was about to post it with 16 bytes, but the I realized it had to be case-insensitive...
[Answer]
# Retina, ~~43~~ 36 bytes
```
iM!`(.)(?<!\1.+)(?!.*\1)
!`(?<=^.¶).
```
[Try it online!](http://retina.tryitonline.net/#code=aU0hYCguKSg_PCFcMS4rKSg_IS4qXDEpCiFgKD88PV4uwrYpLg&input=REVGZA)
[Answer]
# Mathematica, 49 bytes
```
Cases[Tally@ToUpperCase@#,{_,1}][[2,1]]~Check~""&
```
Anonymous function. Takes a list of characters as input. Ignore any errors that are generated.
[Answer]
## JavaScript (Firefox 48 or earlier), 60 bytes
```
f=s=>(m=s.match(/(.).*\1/i))?f(s.replace(m[1],"","gi")):s[1]
```
Returns `undefined` if there are only zero or one non-repeating characters. Works by case-insensitively deleting all occurrences of characters that appear more than once in the string. Relies on a non-standard Firefox extension that was removed in Firefox 49. ~~119~~ 91 byte ES6 version:
```
f=s=>(m=s.match(/(.).*?(\1)(.*\1)?/i))?f((m[3]?s:s.replace(m[2],"")).replace(m[1],"")):s[1]
```
Recursively searches for all characters that appear at least twice in the string. If the character appears exactly twice then both occurrences are deleted otherwise only the first occurrence is deleted (the other occurrences will be deleted later). This allows the occurrences to have a difference case.
[Answer]
# J, 25 bytes
```
(1{2{.]-.]#~1-~:)@tolower
```
## Usage
```
f =: (1{2{.]-.]#~1-~:)@tolower
f 'DEFD'
f
f 'FEED'
d
f 'This is an example input sentence.'
x
f '...,,,..,,!@'
@
f 'ABCDefgHijklMNOPqrsTuVWxyz'
b
f 'AAAAAABBBBB'
f 'Thisxthis'
f 'This this.'
.
```
## Explanation
```
(1{2{.]-.]#~1-~:)@tolower Input: s
tolower Converts the string s to lowercase
~: Mark the indices where the first time a char appears
1- Complement it
] Identity function to get s
#~ Copy only the chars appearing more than once
] Identity function to get s
-. Remove all the chars from s appearing more than once
2{. Take the first 2 chars from the result (pad with empty string)
1{ Take the second char at index 1 and return it
```
[Answer]
# Bash, 58 bytes
```
tr A-Z a-z>t
tr -dc "`fold -1<t|sort|uniq -u`"<t|cut -c2
```
**Caution:** This creates a temporary file named **t**. If it already exists, it will be overwritten.
[Answer]
# C, 174 bytes
```
int c(char*s){int y=128,z=256,c[384],t;memset(c,0,z*6);for(;t=toupper(*s);s++){c[t]++?c[t]-2?0:c[z+(c[y+c[z+t]]=c[y+t])]=c[z+t]:c[z]=c[y+(c[z+t]=c[z])]=t;}return c[y+c[y]];}
```
This is not the most short, but quite efficient implementation. In essence it uses double-linked list to maintain ordered set of candidate characters and scans input string just once. Returns character code or zero if none found.
A little bit ungolfed version:
```
int c(char*s)
{
int y=128,z=256,c[384],t;
//It's basically c[3][128], but with linear array the code is shorter
memset(c,0,z*6);
for(;t=toupper(*s);s++)
{
c[t]++ ? // c[0][x] - number of char x's occurrence
c[t] - 2 ? // > 0
0 // > 1 - nothing to do
: c[z + (c[y + c[z + t]] = c[y + t])] = c[z + t] // == 1 - remove char from the list
: c[z] = c[y + (c[z + t] = c[z])] = t; // == 0 - add char to the end of the list
}
return c[y + c[y]];
}
```
[Answer]
## C#, 143 bytes
```
char c(string s){var l=s.Select(o=>Char.ToLower(o)).GroupBy(x=>x).Where(n=>n.Count()<2).Select(m=>m.Key).ToList();return l.Count()>1?l[1]:' ';}
```
[Answer]
# TSQL, 128 bytes
Golfed:
```
DECLARE @ varchar(99)=',,zzzbb@kkkkkkJgg'
,@i INT=99WHILE @i>1SELECT
@i-=1,@=IIF(LEN(@)>LEN(x)+1,x,@)FROM(SELECT
REPLACE(@,SUBSTRING(@,@i,1),'')x)x PRINT SUBSTRING(@,2,1)
```
Ungolfed:
```
DECLARE @ varchar(99)=',,zzzbb@kkkkkkJgg'
,@i INT=99
WHILE @i>1
SELECT
@i-=1,@=IIF(LEN(@)>LEN(x)+1,x,@)
FROM
(SELECT
REPLACE(@,SUBSTRING(@,@i,1),'')x
)x
PRINT SUBSTRING(@,2,1)
```
[Fiddle](https://data.stackexchange.com/stackoverflow/query/508407/whats-the-second-non-repeating-character)
[Answer]
# Ruby, 53 bytes
Input is STDIN, output is STDOUT. In Ruby, out-of-index positions in an array or string return `nil`, which is not printed.
`String#count` is a strange function in Ruby because instead of counting the number of occurrences for the string that was passed in, it counts the number of occurrences for each letter in that string. It's usually annoying but we can use it to our advantage this time. `String#swapcase` swaps upper and lower case letters.
```
$><<gets.chars.reject{|c|$_.count(c+c.swapcase)>1}[1]
```
Old version that wasn't safe against special characters like `.` - 46 bytes
```
$><<gets.chars.reject{|c|$_=~/#{c}.*#{c}/i}[1]
```
[Answer]
# Java 8, ~~172~~ 157 bytes
```
(String s)->{s=s.toLowerCase();for(char i=0,c;s.length()>0;s=s.replace(c+"","")){c=s.charAt(0);if(!s.matches(".*"+c+".*"+c+".*")&&++i>1)return c;}return' ';}
```
-15 bytes.. Dang I was bad at golfing back then. ;)
**Explanation:**
[Try it here.](https://tio.run/##jVDLbsIwELzzFUsOYDfBomcLVJ7qodBKoPZQ9eAahxgSJ7UdCkX59tQBKm4NK2tsr2fXM7thO9ZJM6E2q23JY2YMzJhUxwaAVFbokHEB8@oKwCOmgaOF1VKtwWDqskXDgbHMSg5zUNCD8kro9I@mZ4hNn9JvoUfMCIRpmGp06iR73YBTQ2Kh1jZCuN@lFVuLLHafIu57XuB5GB@5y1YVA4u6mMoQNQ1JmOWRMMgjd57vqNcNt1q@L/v3WAubawWcFudTG9q0KGklOMs/Yyf4onuXyhUkzvVF@fsHMHy2vDgYKxKS5pZk7snGCinCkTeeTMdOGv2XNJ1M6knLSBpwiykQe5ZksXCDz3ILRrj5Ky5IbQtCSBAEFTQfasmD4WgswvWj3Gzj2fz55UubZf76tj/81JeeYljFTbb21sFtA6iYf0aLRlH@Ag)
```
(String s)->{ // Method with String parameter and character return-type
s=s.toLowerCase(); // Make the input-String lowercase
for(char i=0,c;s.length()>0; // Loop over the characters of `s`
s=s.replace(c+"","")){ // And after every iteration, remove all occurrences of the previous iteration
c=s.charAt(0); // Get the current first character
if(!s.matches(".*"+c+".*"+c+".*") // If it doesn't occur more than once
&&++i>1) // And this was the second one we've found
return c; // Return this second characters
} // End of loop
return' '; // Else: return an empty character/nothing
} // End of method
```
[Answer]
# [R](https://www.r-project.org/), 79 bytes
```
function(z){y=tolower(el(strsplit(z,"")));x=table(y);y[y%in%names(x[x==1])][2]}
```
[Try it online!](https://tio.run/##BcFBCoAgEADAvwjCLnSpq@xLxIOFgWBr6EZa9HabKWPsF28SM8ODbyfJKd@hQEhQpdQzRYFnUgoRTSPxawrQ0XTbdWTN/ggVmm1Es0NnF/eN8QM "R – Try It Online")
I definitely feel like something can be golfed out here. But I really enjoyed this challenge.
This answer splits the string into a vector of characters, changes them all to lower case, and tables them (counts them). Characters that occur once are selected and compared to characters within the aforementioned vector, then the second value that is true is returned as output. An empty string, or a string with no repeating characters outputs NA.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~38~~ 32 bytes
*-6 bytes thanks to nwellnhof by changing `.comb` to a case-insensitive regex*
```
{~grep({2>m:g:i/$^a/},.comb)[1]}
```
[Try it online!](https://tio.run/##LY1Pa4NAFMTv71O8ihSF7Yb20ENASewqvfTPIbSH0sAmPO0262pdBa3Yr27XpsPwY2AGpqZG387lgJc5RjiPP0VDdTDexOW6WKuVv5erifFjVR7Ct@v3ac6rBgOtDNkQr2L0lWHoV13reNDSnCLPwxEQrRwwD1wdMg@jGL3zDKZZpJmADCBLUwECYPehLDpLg9TLstaEytRdi5ZMS@ZIHHoAzjljbMHFBjYA2@ROUF7cq8@Tfnh8ev5q7K57ee2Hb0hc@6dkEZwf@tbhP@OSOXD4BQ "Perl 6 – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok) / [K4](https://kx.com/download/), 11 bytes
**Solution:**
```
*1_&1=#:'=_
```
[Try it online!](https://tio.run/##y9bNz/7/X8swXs3QVtlK3TZeKSQjs1gBiBLzFFIrEnMLclIVMvMKSksUilPzSlLzklP1lP7/BwA "K (oK) – Try It Online")
**Explanation:**
```
*1_&1=#:'=_ / the solution
_ / convert input to lowercase
= / group alike characters
#:' / count (#:) each group
1= / 1 equal to length of the group?
& / where true
1_ / drop the first
* / take the first
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `h`, 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
LDcḅịḣ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPWQmY29kZT1MRGMlRTElQjglODUlRTElQkIlOEIlRTElQjglQTMmZm9vdGVyPSZpbnB1dD0nREVGRCclMjAtJTNFJTIwJ0YnJTBBJ0ZFRUQnJTIwLSUzRSUyMCdEJyUwQSdUaGlzJTIwaXMlMjBhbiUyMGV4YW1wbGUlMjBpbnB1dCUyMHNlbnRlbmNlLiclMjAtJTNFJTIwJ3gnJTBBJy4uLiUyQyUyQyUyQy4uJTJDJTJDISU0MCclMjAtJTNFJTIwJyU0MCclMEEnQUJDRGVmZ0hpamtsTU5PUHFyc1R1Vld4eXonJTIwLSUzRSUyMCdCJyUwQSdBQUFBQUFCQkJCQiclMjAtJTNFJTIwJyclMEEnVGhpc3h0aGlzJyUyMC0lM0UlMjAnJyUwQSdUaGlzJTIwdGhpcy4nJTIwLSUzRSUyMCcuJyZmbGFncz1DaA==)
#### Explanation
```
LDcḅịḣ # Implicit input
ị # Filter the input by:
L c # The count of the character lowercased
D # In the input lowercased
ḅ # Equals one?
ḣ # Remove the first character
# Implicit output of next character
# (or the empty string if it doesn't exist)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
k@oX ÅÃÅ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=a0BvWCDFw8U&input=IkZFZWQi)
```
k@v èXv)É
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
⇩)ġ~₃f∑Ḣh
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLih6kpxKF+4oKDZuKIkeG4omgiLCIiLCJUaGlzeHRoaXMiXQ==)
*-3 thanks to @lyxal*
#### Explanation
```
⇩)ġ~₃f∑Ḣh # Implicit input
⇩)ġ # Group by lowercasing
~₃ # Filter by length == 1
f∑ # Flatten and join
Ḣ # Remove the first character
h # Then take the next one
# (or an empty string
# if it doesn't exist)
# Implicit output
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
lТϦн
```
Input as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f8/5/CEQ4sO9x9admHv///RSiFKOkoZQJwJxMVArIDGTgTiPCg7FYgroGK5QFwAxDlQcZi@PKh4KRCXQMWLoWryoGIwdjKUracUCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn1l8P@cwxMOLTrcf2jZhb3/df67uLq5cLm5urpwhWRkFisAUWKeQmpFYm5BTqpCZl5BaYlCcWpeSWpecqoel56eno6ODohQdOBydHJ2SU1L98jMys7x9fMPKCwqDikNC6@orOJyBAMnEAAbW1ECJCAWgFh6AA).
**Explanation:**
```
l # Convert the characters in the (implicit) input-list to lowercase
Ð # Triplicate this lowercase list
¢ # Pop two, and get the count of each character in the list
Ï # Pop the counts and remaining list, and only keep the characters at the truthy
# (count==1) positions
¦ # Remove the first character
н # Pop and leave the new first character
# (after which it is output implicitly as result)
```
Unfortunately the `.m` (least frequent character(s) builtin) [doesn't retain its order in the legacy version of 05AB1E](https://tio.run/##MzBNTDJM/f8/Ry/3//@QjMxiBSBKzFNIrUjMLchJVcjMKygtUShOzStJzUtO1QMA) and will [only keep the first character instead of a list in the new 05AB1E version](https://tio.run/##yy9OTMpM/f8/Ry/3//@QjMxiBSBKzFNIrUjMLchJVcjMKygtUShOzStJzUtO1QMA), otherwise this could have been 5 bytes with `l.m¦¬`.
] |
[Question]
[
## What I want:
Quite simply, I want a text based display, that asks for an input, `n`, then shows that value on the display! But there's a catch. Each of the 'true' 'pixels' (the ones filled in) has to be represented by that number `n`..
## Example :
You are given an input `n`. You can assume `n` will be a single digit
```
Input: 0
Output:
000
0 0
0 0
0 0
000
Input: 1
Output:
1
1
1
1
1
Input: 2
Output:
222
2
222
2
222
Input: 3
Output:
333
3
333
3
333
Input: 4
Output:
4 4
4 4
444
4
4
Input: 5
Output:
555
5
555
5
555
Input: 6
Output:
666
6
666
6 6
666
Input: 7
Output:
777
7
7
7
7
Input: 8
Output:
888
8 8
888
8 8
888
Input: 9
Output:
999
9 9
999
9
999
```
# Challenge:
Do the above it in as few bytes as possible.
I will only accept answers that meet all requirements.
**Surrounding whitespace is optional,** as long as the digit is displayed properly.
Also, <75 bytes is a vote from me, the lowest accept, but I could always change the accepted answer, so don't be discouraged to answer.
[Answer]
## JavaScript (ES6), 88 bytes
```
f=
n=>`019
2 3
459
6 7
889`.replace(/\d/g,c=>[2,18,142,96,130,131,698,4,146][c]>>n&1?` `:n)
```
```
<input type=number min=0 max=9 oninput=o.textContent=f(this.value)><pre id=o>
```
The numbers encode which squares contain spaces for a given digit e.g. the bottom left corner has a value of 146 because the 1, 4 and 7 don't use it and 146 = 2¹ + 2⁴ + 2⁷.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~40~~ ~~39~~ 38 bytes
```
•Y¤ŸèK'¦ú’ò™^N•4B5ô¹èvð¹«5714yè8+b¦Sè,
```
[Try it online!](https://tio.run/nexus/05ab1e#AUEAvv//4oCiWcKkxbjDqEsnwqbDuuKAmcOy4oSiXk7igKI0QjXDtMK5w6h2w7DCucKrNTcxNHnDqDgrYsKmU8OoLP//NQ "05AB1E – TIO Nexus")
**Explanation**
```
•Y¤ŸèK'¦ú’ò™^N• # the compressed string "318975565561233953387608032537"
4B # convert to base-4
5ô # split into strings of size 5
¹è # get the string at index <input>
v # for each digit y in string
5714yè # get the digit in 5714 at index y
8+ # add 8
b # convert to binary
¦ # remove the leading 1
𹫠Sè # with each digit in the binary number,
# index into the string " <input>"
, # print with newline
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 43 bytes
```
"Ýûÿ©ÿßY÷ß"®c s4äëAU ¬£2839¤ë4X÷d0S1U
```
Contains some unprintables. [Try it online!](https://tio.run/nexus/japt#@690eO7h3Yf3H5p6qPHQysP7D88/NDHy0NzD2w/PVzq0Llmh2ORw86Elh1c7hiocWnNosZGFsSWIaxIBFN6eYhBsGPr/vyUA "Japt – TIO Nexus")
Tallies: 13 bytes of compressed data, 9 bytes to decompress it, and 21 bytes to form the output.
### Explanation
Ungolfed code:
```
"Ýûÿ©ÿßY÷ß"® c s4à ¤ ëAU ¬ £ 2839¤ ë4Xà · d0S1U
"Ýûÿ©ÿßY÷ß"mZ{Zc s4} s2 ëAU q mX{2839s2 ë4X} qR d0S1U
```
There are exactly 4 different row possibilities: (`#` represents a digit)
```
#
#
# #
###
```
Thus, each number can be stored as a set of five base-4 digits. Since each number can be then stored in 10 bits, the total is 100 bits, which corresponds to 13 bytes. I'll skip the compression process and instead explain the decompression.
```
mZ{Zc s4}
mZ{ } // Replace each character Z in the compressed string with the following:
Zc // Take the char-code of Z.
s4 // Convert to a base-4 string.
```
After decompression, the 13-byte compressed string looks like this:
```
3131332333332111200122213333313321011121213133133133
```
Note that this would fail if any of the 4-digit runs started with `0`, as the leading zeroes would be left off when `s4` is run. We can fix this by having `0` represent `#`, which only appears three times, and none of those fall at the start of a 4-digit run.
```
s2 // Slice off the first two chars of the result.
```
Okay, so in order to get our 50-digit string to compress nicely in chunks of 4, we had to add two extra digits. Adding them to the beginning of the string means we can chop them off with the one-byter `¤`.
```
ëAU // Take every 10th (A) char in this string, starting at index <input> (U).
```
Embarrassingly, Japt lacks a built-in for splitting a string into slices of length X. It does have a built-in for getting every Xth char, however, so we can store all the data by encoding all of the top rows first, then all of the second rows, etc.
So now we have the 5-digit string encoding the digit we want to create, e.g. `32223` for `0`.
```
q mX{2839s2 ë4X} qR
q // Split the resulting string into chars.
mX{ } // Replace each char X with the result of this function:
2839s2 // Convert the magic number 2839 to a binary string.
ë4X // Take every 4th char of this string, starting at index X.
qR // Join the result with newlines.
```
To explain the magic number, refer back to the four distinct rows. If you replace `#` with `1` and with `0`, you get
```
100
001
101
111
```
Transposing this and then joining into a single string gives us `101100010111`. Convert to decimal and, voilà, you have 2839. Reversing the process maps the digits `0123` into the four binary rows shown above.
Almost done! Now all that's left to do is add in the spaces and digits:
```
d0S1U // In the resulting string, replace 0 with " " (S) and 1 with <input> (U).
```
And presto, implicit output takes care of the rest. I'm sorry this explanation is so long, but I don't see any real way to golf it without making it less understandable (if it is understandable...)
[Answer]
## JavaScript (ES6), ~~115~~ 111 bytes
Takes input as a string.
```
n=>'02468'.replace(/./g,c=>(n+n+n+` ${n} `+n).substr([126,341,36,68,327.5,66,98,340,102,70][n]*4>>c&6,3)+`
`)
```
### How it works
**Pattern encoding**
The four distinct patterns `"XXX"`, `"X.."`, `"..X"` and `"X.X"` can be compressed as `"XXX...X.X"` and extracted this way:
```
XXX...X.X
^^^ --> XXX (id = 0 / pointer = 0)
^^^ --> X.. (id = 1 / pointer = 2)
^^^ --> ..X (id = 2 / pointer = 4)
^^^ --> X.X (id = 3 / pointer = 6)
```
By substituting the input digit `n` for `"X"` and using actual spaces, this gives the expression:
```
n+n+n+` ${n} `+n
```
**Digit encoding**
Using the pattern identifiers defined above, each digit can be represented by a 5 \* 2 = 10-bit quantity.
For instance:
```
XXX --> 0 * 1 = 0
X.X --> 3 * 4 = 12
XXX --> 0 * 16 = 0
..X --> 2 * 64 = 128
XXX --> 0 * 256 = 0
---
140
```
The complete list is:
```
[252, 682, 72, 136, 655, 132, 196, 680, 204, 140]
```
However, dividing these values by 2 allows to save two bytes. So instead we store:
```
[126, 341, 36, 68, 327.5, 66, 98, 340, 102, 70]
```
### Demo
```
let f =
n=>'02468'.replace(/./g,c=>(n+n+n+` ${n} `+n).substr([126,341,36,68,327.5,66,98,340,102,70][n]*4>>c&6,3)+`
`)
console.log(f('0'))
console.log(f('1'))
console.log(f('2'))
console.log(f('3'))
console.log(f('4'))
console.log(f('5'))
console.log(f('6'))
console.log(f('7'))
console.log(f('8'))
console.log(f('9'))
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 30 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
■'τč▲Β►║⁰ΡāQšJ┘tXdnοO¹‘'¹n.w3n
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNUEwJTI3JXUwM0M0JXUwMTBEJXUyNUIyJXUwMzkyJXUyNUJBJXUyNTUxJXUyMDcwJXUwM0ExJXUwMTAxUSV1MDE2MUoldTI1MTh0WGRuJXUwM0JGTyVCOSV1MjAxOCUyNyVCOW4udzNu,inputs=NQ__)
The compressed string `■'τč▲Β►║⁰ΡāQšJ┘tXdnοO¹‘` is
```
ŗ ŗ ŗ ŗ ŗŗŗŗ ŗŗŗŗŗ ŗŗŗŗŗŗ ŗŗŗŗ ŗŗŗŗŗ ŗŗ ŗŗŗŗ ŗ ŗŗŗŗŗ ŗŗŗ ŗŗŗŗŗŗŗŗ ŗŗŗŗ ŗŗŗŗŗŗŗ ŗ ŗ ŗ ŗŗŗŗŗ ŗŗŗŗŗ ŗŗŗŗŗŗŗŗ ŗŗŗŗ ŗŗŗŗŗŗŗŗ ŗŗ ŗŗ ŗŗŗŗ
```
which is (starting with 1, ending with 0) the numbers, line by line, number to number.
The rest
```
...‘ push the compressed string, replacing the ŗs with pop - the input
'¹n split into chunks of 15
.w push the (1-indexed, wrapping) input-th item of that array
3n split into chunks of 3
implicitly output the array, line by line
```
[Answer]
# Bash + GNU utils, 114
* 2 bytes saved thanks to @SophiaLechner
There are probably some more opportunities for compression here, but here's a start:
```
dc<<<4o16iEAC00CDF33AC373DEF00EEFB3p|fold -5|sed "$[$1+1]!d
s/0/ x\n/g
s/1/x\n/g
s/2/x x\n/g
s/3/xxx\n/g
y/x/$1/"
```
### Explanation
Each row of of every digit is one of these four patterns:
```
x
x
x x
xxx
```
By labeling these 0-3, each digit can be represented by 5 base-4 digits. E.g. 0 would be `32223`, and the full list of digits is encoded in base-4 as `32223000003031330303223003130331323300003232332303`. This encoded in hex as `EAC00CDF33AC373DEF00EEFB3`.
* `dc` converts hex `EAC00CDF33AC373DEF00EEFB3` to base-4.
* `fold` puts 5 base-4 digits on each line
* `sed`:
+ deletes all input lines apart from line number n+1 (sed 1-indexes lines)
+ translates the base-4 digits to the pattern (of `x`es) for each line of the given digit, along with a newline for the end of each row
+ transliterates the `x`es to digit n.
[Try it online](https://tio.run/##PcqxDoIwFIXhnae4km4GbmsVY@yCUF5CHZAWJTGtsR1qxGevJAbP9OXkv7TuFnv7BK@d71qnYTDwpnm@@@xB2QSmOe0hy4DMSVSdEGJtWTHIsqK0qhvOy4pveS0bSqVsDvwx9vauINuMTitIyZGwJTsvVOKQIkA4GbxOZjhrheH/cgzh5xcGJAzTqKzR8Qs).
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~45~~ 43 bytes
```
'V~4;LR`I-D2q (z%eI)P-nc'F TFZa15eiZ)5eGV*c
```
[Try it online!](https://tio.run/nexus/matl#@68eVmdi7ROU4KnrYlSooFGlmuqpGaCbl6zuphDiFpVoaJqaGaVpmuoeppX8/78lAA "MATL – TIO Nexus")
### Explanation
```
'V~4;LR`I-D2q (z%eI)P-nc' % Compressed string using printable ASCII except '
F TFZa % Decompress (change of base) into alphabet [1 0]
15e % Reshape into 15-row matrix. Each column contains the
% art for one digit, packed in column-major order
iZ) % Take input number and pick the corresponding column.
% Indexing is 1-based and modular, so 0 is at the end
5e % Reshape into a 5-row matrix. This already looks like
% the number, with active pixels as 1 and inactive as 0
GV % Push input number again. Convert to string, of one char
* % Multiply, element-wise. The previous char is
% interpreted as its ASCII code. This changes 1 into the
% ASCII code of the input digit, and leaves 0 as is
c % Convert to char. Implicitly display. Char 0 is shown as
% a space
```
[Answer]
# Retina, ~~166~~ ~~164~~ 163 bytes
Two spaces on the third line from the bottom
```
0
0addda
d
0 0
1
1b1b1b1b1b1
2
2ab2a2b222
3
3ab3ab3a
4
44 44 4ab4b4
5
55ab555b5a
6
66ab6a 6a
7
7ab7b7b7b7
8
88a 8a8 8a
9
99a 9ab9a
(\d)a
$1$1$1$1
^.
b
.{3}
$+¶
```
[Try it Online!](https://tio.run/nexus/retina#PY5BCsIwFET37xRZVKgIJU2TNDmBlxBxPrmFeC0P4MVqY0Hem@3MnMbrY/N4tdZEwzvPzGx/CARZULAQAguL7CeRGF1XFi2SSEmWUrIkMjnLslwWK6tsPaBQilxR2UOlVrkqq2K8tbMY5gPuExjOMT2XF8Pl8962fqw/6FuZ3lW/)
An improved version of [@Okx's](https://codegolf.stackexchange.com/a/117721/65425) solution
[Answer]
# Pyth 82 85 91 100 bytes
```
Km?dC+48Q\ m.&C@"w$kn<^_d\x7f~"Qdj1906486293414135453684485070928 128V5p.)Kp.)K.)K
```
A lot of golfing probably possible, my first challenge.
[Answer]
## Batch File, 8 + 184 bytes
Here's my obligatory batch solution. Unfortunately the standard method of accomplishing this is over 300 bytes in batch, so we resort to much cheaper tactics.
```
@type %1
```
---
In the current directory, I have 10 files set up, named from 0 to 9. In each of these is the respective 5x3 grid of pixels. For example:
[](https://i.stack.imgur.com/etQqB.png)
The byte counts for these are:
```
19 0
19 1
17 2
19 3
19 4
17 5
17 6
19 7
19 8
19 9
Total - 184
```
***Still beat Java.***
[Answer]
# Ruby, 94 bytes
```
->n{20.times{|i|print i%4>2?$/:[" ",n]["_Q_@@_]UWUU_GD_WU]_U]AA__U_WU_"[n*3+i%4].ord>>i/4&1]}}
```
**Ungolfed in test program**
```
f=->n{
20.times{|i| #4 characters * 5 rows = 20
print i%4>2?$/: #If i%4=3 print a newline else
[" ",n][ #either a space if the expression below is 0 or the digit n if 1.
"_Q_@@_]UWUU_GD_WU]_U]AA__U_WU_"[ #bitmap data for digits, one character for each column
n*3+i%4].ord>>i/4&1 #Select the correct character for the column, convert to ascii code,
] #rightshift to find the correct bit for the row,
} #use & to isolate the bit: 0 or 1
}
f[gets.to_i]
```
[Answer]
# PHP, 115 Bytes
```
for(;$i<5;)echo strtr(sprintf("%03b\n","1754"[[425,0,465,273,26,285,413,1,409,281][$argn]/4**$i++%4]),[" ",$argn]);
```
[Try it online!](https://tio.run/nexus/php#JcxNDsIgEEDhvadoJjSh7STyM7QaajwIslBjLRtKKPdHo8v3Ld58TWs6sHt@x4u2ddkytyzMxnav57o1e8kl8z3lEMvCoRX6cYuAICdD4BwpgwJpNKgmjWpEdTJIUqNEEudvSe9@b3@kvmdhGFryHTpoAP/e2Vo/ "PHP – TIO Nexus")
Expanded
```
for(;$i<5;)
echo strtr(
sprintf("%03b\n", # make a binary
"1754"[[425,0,465,273,26,285,413,1,409,281][$argn]/4**$i++%4])
,[" ",$argn]); # replace 0 with space and 1 with the input
```
Encoding
[Try it online!](https://tio.run/nexus/php#XZDbaoQwEIbv5ymGmAuruYiHeMDGPogrxWq2CssqyraF0me3M7uUbnvx800@/hAyj0/LuOzHeXVdP/qN0FqDxrtoLRQIxAj@hXUcxzTGwIwRmayTJCGdwB1Zp5jCNWlK@hrWxhgwdJmJaJissyyDjPSNGZN1nufU@hPWRVFAgZRfsi7LEkqkEPFG0WK3ybeHT7lZOVldwc/v5bt1H8tpHpwvDmehqETNCzUvdlnd6/PqllPXO1qTdxg8oYSHnmhVI2gZQtNE5QrkFtomtXWiIltrZWwdq9zWUdu8TOfB9T612iANAjmFYQVfrh9nITd6kQ77/g0 "PHP – TIO Nexus")
[Answer]
# [Retina](https://github.com/m-ender/retina), 125 bytes
```
.
A$&¶B$&¶C$&¶D$&¶E$&
([ACE][235689]|A0|E0|C4|A7)(?<=(.))
$2$2$2
(B[0489]|D[068]|A4|C0)(?<=(.))
$2 $2
D2
2
B5
5
B6
6
[A-E]
```
[Try it online!](https://tio.run/nexus/retina#TcrNCQMhFEbR/VeFCzPoQOTFjGYCCcE/UoQIU4h1WYCNmXEXLtzVwY34CgWujt56w0V8j6Hg@NKbnwtzcS7xBSK7kErWd2P3Z6mOaqIatuoeUnxeb6GkBNczCJ9pmyhmsvtptxroX7ETRQ0Nb2DgLSyyu6YCxsb4AQ "Retina – TIO Nexus") (Delete test suite in header to test individual input digits.) Last line contains two spaces.
[Answer]
# PowerShell, ~~126~~ ~~120~~ ~~113~~ ~~109~~ 101
```
$n="$args"
-split'ϽϭϿ·ͱ Ο·ͽͼϿ·Ņ ϻ·ͭͭϿ'|%{-join($_[0..2]|%{"$n·"[!($_-band1-shl$n)]})}
```
Unicode is fun. Characters are also way shorter than numbers. Above code contains U+0000 twice, thus cannot be copied directly (works fine in a file, though). The following code can be copied:
```
$n="$args"
-split"ϽϭϿ ͱ`0Ο ͽͼϿ Ņ`0ϻ ͭͭϿ"|%{-join($_[0..2]|%{"$n "[!($_-band1-shl$n)]})}
```
We lose three bytes because we need the UTF-8 signature at the start. Otherwise the string won't work.
[Answer]
# [Retina](https://github.com/m-ender/retina), 190 bytes
```
0
000¶aaa000
a
0 0¶
1
aaaaa
a
b1¶
2
ab2¶a2¶a
a
222¶
3
ab3¶ab3¶a
a
333¶
4
4 4¶4 4¶444¶b4¶b4
5
a5b¶ab5¶a
a
555¶
6
a6¶a6 6¶a
a
666¶
7
777aaaa
a
¶b7
8
a8 8¶a8 8¶a
a
888¶
9
a9 9¶ab9¶a
a
999¶
b
```
There are two spaces on the last line ~~but SE doesn't want to render it :/~~ Fixed!
[Try it online!](https://tio.run/nexus/retina#LY/ZEcQgDEP/VYVLINwuxxSZAtJY9hGWGQtZI2zxJqWUnjsiuBVKRqdLsQ/9umizYmVMu9ByhqggFoQPUEuBqKpafe4DFVhfqSna2u523K1B1BWdvls/au8QDY0x/vt5PDQV0yaWg8hzQuQKN99T/cjuEC2ZvW8S3yA6QUlFALYxmmH@Aw "Retina – TIO Nexus")
[Answer]
# Java 8, ~~278~~ ~~214~~ ~~210~~ 204 bytes
```
n->("A"+n+"\nB"+n+"\nC"+n+"\nD"+n+"\nE"+n).replaceAll("([ACE][235689]|A0|E0|C4|A7)(?<=(.))","$2$2$2").replaceAll("(B[0489]|D[068]|A4|C0)(?<=(.))","$2 $2").replaceAll("D2|B5|B6",n).replaceAll("[A-E]"," ")
```
Port of [*@Neil*'s Retina answer](https://codegolf.stackexchange.com/a/117776/52210). Takes the input as a `String`.
[Try it here.](https://tio.run/##bZHLbsIwEEX3/YqR1YWtQBTRkIIgrfJalg1LNws3hMo0caLEUFU1355OwJvSyo/rGfuO7OODOIlp05bqsPsYikr0PbwIqb7vAKTSZbcXRQmbMQTY6k6qdyioXSi2wvwZB/YNKAhhUNMnSiLiKIe8qthqYjW1mqEytyvbCqtHVUUJ5VGS5Xz2MA8Wy9xEnsk8k/gmemT0eR1SlzEyIfezsZEba8w9fzSl3AsW6PVN4v12wR9TOjPx3MQBmdxchEfTLEcTAGHD6vq09vhWyQJ6LTTKqZE7qJGRxcBzEOwKaCQHNWJQ5ecloBdCAPumo4gTZOitQK7DJc6OY10I9qvXZe02R@22WFJXitaucgsqHUKYrfHvMbt3vvzDefgB)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~174~~ 125 bytes
```
lambda n:'\n'.join('xxx x x'[int(i):][:3]for i in oct(0x3028000adba93b6b0000c0ad36ebac30180c0)[:-1][n::10]).replace('x',`n`)
```
[Try it online!](https://tio.run/##Xc2xDoMgFIXhvU9xNyBpzUVaqyR9EiQRUFMaC8Y40Ke3pEkXtvN/y1k/@zOG@pgf/bGYtx0NBEn6QKpX9IGSlBJAgkSUDzv1TGolhZ7jBh58gOh2iklg3SKiGa3phG1s3uhyimayxgnkbU6m5IVrFaTkqFm1Teti3JQfyHkIAzvWLT/ATJGdfvP0B15CXYIo4VrCrYSmhHsJbQkdO74 "Python 2 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell),159 135 128 118 bytes
```
param($n);0..4|%{("$n$n$n","$n $n"," $n","$n ")['01110333330203002020110220302003010022220101001020'[$_+($n*5)]-48]}
```
Current answer: removed extraneous variable naming
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVP09pAT8@kRrVaQ0klDwSVdIAMBTCtoADjKihpRqsbGBoaGhiDgIGRgbEBkDACChkYgThGBkDCECgGBEAayAJKGKhHq8RrAy3RMtWM1TWxiK39//@/GQA "PowerShell – Try It Online")
I'll have to see if I can get some tricks from the other answers :P
**EDIT** Getting smarter with calling the mega string
**EDIT2** Switched to using a string of numbers to index into `$a` to save 7 bytes. Although I liked my previous dynamic variable name calls in the below code (135 bytes)
```
param($n);$a="$n$n$n";$b="$n $n";$c=" $n";$d="$n ";$r="abbbadddddacadaacacabbaccadacaadabaaccccababaabaca";0..4|%{gv $r[$_+($n*5)]-v}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~35~~ 32 bytes
```
Ṿ⁶,“SÐ~ẈoI9Ẇ¦Y./,0&Ƥɓ€ọ’ṃs15ị@s3
```
[Try it online!](https://tio.run/##AUYAuf9qZWxsef//4bm@4oG2LOKAnFPDkH7huohvSTnhuobCplkuLywwJsakyZPigqzhu43igJnhuYNzMTXhu4tAczP/w4dZ//8z "Jelly – Try It Online") or [see them all](https://tio.run/##AVUAqv9qZWxsef//4bm@4oG2LOKAnFPDkH7huohvSTnhuobCplkuLywwJsakyZPigqzhu43igJnhuYNzMTXhu4tAczP/MTDhuLbDh1kk4oKsauKBvsK2wrb/).
Same as dzaima's method.
[Answer]
# [Perl 5](https://www.perl.org/) `-Mbigint -pa`, 101 bytes
```
$_=sprintf"%16b",0xf79ef7dee492f3def39eb792e79ee7ce4924f6de>>16*$_&65535;eval"y/01/ @F/";s/...\K/\n/g
```
[Try it online!](https://tio.run/##Fc5PC4IwGIDx@/spYliHyP1xbmtI0qlL9A0EcflOBNGhEvXlW3Z64Hd6As6DijGpL0uY@3H1ZC@0Iyf@9saiNy1ibjMvW/TSojM2w83RPP@ce91iWQp9TOqDVkqqAl/NQD6MC7a73hgpFkYpre6sGlkXIwcBGUjIQYEGA2ew3yms/TQuMX0oygXf6vpuO4npEJof "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 119 bytes
```
lambda n:(3*f"%s%s{n}\n%s %s\n")[:30]%(*[n if i//(2**n)%2else" "for i in[1021,1005,881,927,893,892,325,1019,877,877]],)
```
[Try it online!](https://tio.run/##TclLCoMwFEDReVcRAoFEAuZTm0ToStSBpYYG7FOMk1K69tROyhtcOHDX1/5YwJZ47cs8Pm/3kUDLbRUpyyy/4dMDy4TlHqjoWqsGxqsOSIok1TU3VQWCmWnOEyU0LhtJJEGnldFSK9VI77UMxkkf7JGR1jTH0EF6534NgxTltG4Jdh65EuJvjWyQLfIZuUG@IDtkjxyEKF8 "Python 3 – Try It Online")
Each 'pixel' is represented as an integer where each power of two indicates whether the pixel is solid.
This takes advantage of the fact that the three right-hand corners are always the digit.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~61~~ ~~38~~ 33 bytes
```
E§⪪”{⊞¶↙⬤\→(B⊘K→υ^⎇\`|;ε”⁵N⮌⍘Iι⁺ θ
```
[Try it online!](https://tio.run/##HY29DsIwDIRfJcrkSGVASuSBCZg6gCr6BKFYECmEkJ@Ktw9Ob/D5/Onk5WXT8rG@tSm5UOBiIxzLGB70gzl6V0CiMQZ1F2rcI3bbLhw08jC4YXbeGKAchFGDGEOs5Vrfd0qgON9opZQJTjbTXPjdE842F3DMJl8zSMHNr@o6tGbabvV/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
”...” Compressed data string
⪪ ⁵ Split into groups of 5 digits
§ Indexed by
N First input as an integer
E Map over digits
ι Current digit
I Cast to integer
⍘ Converted to custom base
⁺ θ Space concatenated with input digit
⮌ Reversed
Implicitly print
```
A generic port is a bit boring, so here's a more idiomatic 61-byte answer:
```
GH✳✳§⟦⟦↑L↓¬⟧⟦↓↓⟧⟦T↓→⟧⟦T→¬⟧⟦↑↑¬↑⟧⟦←↓T⟧⟦T↑L⟧⟦→↓↓⟧⟦+L↓⟧⟦+↓T⟧⟧N³θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9nuXv96x4NGczEB1a/mj@MhBqm@jzqG3yoTWP5oNF2iaDEJgdAuZMgnMmIRRNBCIgD0hDBSYA1YbAVQKNhIpPQjZQ2wfBhKsHOmndoc3ndvz/bwkA "Charcoal – Try It Online") No verbose version as the deverbosifier doesn't understand lists of directions or even multidirectionals inside ordinary polygons. Explanation:
```
⟦...⟧ Array of paths, see below
N Input as an integer
§ Index into the array
✳✳ Treat the element as direction data
³ Length of each segment (including 1 character overlap)
θ Draw using the input character
GH Draw a path
```
Each path is specified using a list of directions (`←↑→↓`). Four usable shortcuts save bytes: `L` represents `↑→`, `¬` represents `↓←`, `T` represents `→↓←` while `+` represents `→↓←↑`, although at least one arrow must remain for the list to be recognised as a direction list (so for instance `TT` cannot be used for `3`).
60 bytes using the newer version of Charcoal available on ATO:
```
GH✳✳§⟦⟦⌈¬↑↑⟧⟦↓↓⟧⟦T↓→⟧⟦T→¬⟧⟦↑↑¬↑⟧⟦←↓T⟧⟦+↑→⟧⟦⌈↓⟧⟦+↑⌈⟧⟦+↓T⟧⟧N³θ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6Fje_B-TnVKbn53nk5-Tkl2u4ZBalJpdk5ucVaziWeOalpFZoREdbPerp0FGwOrQGSIQWgIlYHYVoK5f88jwgD0SB-SFQDpAKykzPKIELgnlgE8BCUDMQRoJFfVLTShAGhIDFtGEKEeZB3AK3E64CKA4XgJsBFPHMKygt8SvNTUot0tDU1NRRMNZRKNS0XlKclFwMDYTl0Uq6ZTlKsQtNIXwA "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation: The order in which multidirectionals execute changed which means that `7` can now be drawn using a multidirectional and an arrow instead of three arrows. Some of the other digits have had to have their multidirectionals tweaked but this was possible without changing the length of the code.
[Answer]
# [Befunge](https://github.com/catseye/Befunge-93), ~~192~~ 174 bytes
```
3040040403333004010030103304403030010302222204440&:09p5*>: #v_v
9g86*+:00p:10p:20p:01p:12p:23p:04p24p 6v ^-1$\< >
,+55,g\2,g\1:,g\0:\_@#:-1p31p30:p41:*84<$
```
[Try it online!](https://tio.run/##TUzLCoNAELv3KwaUHnxAZncUHUT6IVKhYL2VvdTf32ZvzSQhyWFex/v7OY@cIwykIRIlKRBpLMaRVwpCARfD3TGnoVldpLr26yYi8zmNTetAcqUCBWUOzJHZUrAk4yX/ePZab4us5UHXDkN3boFSp8G3/VF5rymS8GTqzWRLnfP0Aw "Befunge-93 – Try It Online")
First stab was ~360 bytes doing if/else & pushing characters to stack. Which was devoting 150 characters to encoding numbers. So instead encode characters as 5 numbers based on each line. Then pop 5x input to have top 5 stack elements be desired character. 2nd line sets up line pieces with correct characters in top left 3x5 of memory
[Answer]
# JavaScript (ES8), 87 bytes
```
n=>`019
2 3
459
6 7
889`.replace(/\d/g,c=>[2,18,142,96,130,131,698,4,146][c]>>n&1?' ':n)
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.