text
stringlengths 180
608k
|
---|
[Question]
[
I've just bought a new jigsaw puzzle but, as a programmer, I'm too lazy to do it by myself. So I've devised a way to encode the pieces, and now I need a way to solve the puzzle itself.
## Challenge
A puzzle piece will have from 2 to 4 connecting corners, defined by a letter; and a color, defined by a number.
```
a
B 1 c
D
a 2 b
C
3 A
b
```
The challenge is to build the puzzle from the pieces according to the next rules:
* Two pieces may only be adjacent if they have a matching connection in the corner where they are adjacent. If a piece doesn't have a connection in one of the sides, that side is a corner and can't be connected to another piece.
* Lowercase letters are considered indents and uppercase letters are considered outdents. An uppercase letter connects with its lowercase pair.
* The color of 4-adjacent pieces will differ at most by 1.
* Every piece can and has to be used exactly once.
## Input
Your program will receive a randomized list of the pieces, separated with newlines, as seen in the examples. The input pieces are in the right direction: you don't need to rotate them (there is a bonus for inputs with rotated pieces, see below).
## Output
Your program should output a solution to the puzzle, with columns separated by blank space (space or tab are okay) and rows by newlines. It might not be unique, but only one possible solution is required.
```
1 2 3 4 3 4 5 4
1 1 2 3 4 4 4 5
2 1 1 2 3 4 5 6
3 2 2 3 4 5 6 7
2 3 3 4 5 6 7 8
3 4 4 5 6 7 8 9
3 4 5 6 7 8 9 10
```
## Scoring
The shortest answer in bytes wins.
### Bonus
The generator script provides options to randomize the rotation of the pieces, but since it may become more complex, a 50% bonus is awarded to whoever implements it (that is, your-byte-count \* 0.5).
For that case, assume all the tiles in the input will have a randomized rotation, except the first one, which will have the rotation of the original grid (so as to avoid having at least 4 different solutions).
## Test Cases
Test cases can be obtained using the following ruby scripts:
<https://gist.github.com/rcrmn/2ba23845d65649c82ca8>
The first one generates the solution grid. The second one generates the puzzle pieces from it. Note that they have optional arguments, described in each ruby file.
Following is an example. It's here because I made it by hand before writing the generator and I got attached to it:
<http://pastebin.com/PA9wZHma>
This test case should output:
```
1 2 3 4
2 3 4 5
3 4 5 6
```
As usual, [common loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are not permitted.
Good luck!
[Answer]
# Ruby, 1220
Wow that was something... I didn't think it would take THAT much to make this, but hey, only way to learn was try it. It's clear now why there weren't any answers to the question...
Well, I'm sure this is golfable, but It's been a whole job only to make it. Following is golfed code and then ungolfed with some explanations:
```
e=[[]]
while(a=gets)
if(a=a.chomp)==""
e.push []
else
e.last.push a.chomp
end
end
e.keep_if{|p|p!=[]}
e.map!{|p|m={}
t=p[0].strip
if t.length==1
m[:t]=t
l=p[1].split" "
b=p[2]
else
m[:t]=nil
l=t.split" "
b=p[1]
end
x=l[0]=~/\d/
m.merge!({l: !x ? l[0]:nil,v:(x ? l[0]:l[1]).to_i,r:x ? l[1]:l[2]})
m[:b]=b.nil? ? nil:b.strip
m}
w=e.select{|p|p[:t].nil?}.length
h=e.length/w
def c(j,p,l)
x=l[0]
y=l[1]
(x==0&&p[:l].nil?||x!=0&&(j[x-1][y].nil?||j[x-1][y][:r].swapcase==p[:l]&&(j[x-1][y][:v]-p[:v]).abs<2))&&(x==j.length-1&&p[:r].nil?||x!=j.length-1&&(j[x+1][y].nil?||j[x+1][y][:l].swapcase==p[:r]&&(j[x+1][y][:v]-p[:v]).abs<2))&&(y==0&&p[:t].nil?||y!=0&&(j[x][y-1].nil?||j[x][y-1][:b].swapcase==p[:t]&&(j[x][y-1][:v]-p[:v]).abs<2))&&(y==j[0].length-1&&p[:b].nil?||y!=j[0].length-1&&(j[x][y+1].nil?||j[x][y+1][:t].swapcase==p[:b]&&(j[x][y+1][:v]-p[:v]).abs<2))
end
def d(j,q,l)
f=[false,[]]
q.each_index{|i|p=q[i]
if c j,p,l
r=q.dup
r.delete_at i
j2=j.dup
j2[l[0]][l[1]] = p
if r.length==0
f = [true,j2]
break
else
n=l[0]+1
l2=[n%j.length, l[1]+n/j.length]
f = d(j2,r,l2)
break if f[0]
end
end}
f
end
j=[]
w.times{j.push [];h.times{j.last.push nil}}
s=d(j,e,[0,0])
h.times{|y|w.times{|x|print s[1][x][y][:v].to_s+" "}
puts''}
```
Ungolfed:
```
pieces=[[]]
while (a=gets) # Read the input and separate by pieces when finding an empty line
if (a=a.chomp)==""
pieces.push []
else
pieces.last.push a.chomp
end
end
pieces.keep_if{|p|p!=[]} # Remove possible empty pieces
pieces.map!{|p| # Parse each piece
m={}
t=p[0].strip
if t.length==1
m[:t]=t
l=p[1].split" "
b=p[2]
else
m[:t]=nil
l=t.split" "
b=p[1]
end
x=l[0]=~/\d/
m.merge!({l: !x ? l[0]:nil,v:(x ? l[0]:l[1]).to_i,r:x ? l[1]:l[2]})
m[:b]=b.nil? ? nil:b.strip
m
}
w=pieces.select{|p|p[:t].nil?}.length
h=pieces.length/w
def fits(j,p,l) # This function determines if a piece fits in an empty spot
(l[0]==0&&p[:l].nil? || l[0]!=0 && (j[l[0]-1][l[1]].nil? || j[l[0]-1][l[1]][:r].swapcase==p[:l] && (j[l[0]-1][l[1]][:v]-p[:v]).abs<2)) &&
(l[0]==j.length-1&&p[:r].nil? || l[0]!=j.length-1 && (j[l[0]+1][l[1]].nil? || j[l[0]+1][l[1]][:l].swapcase==p[:r] && (j[l[0]+1][l[1]][:v]-p[:v]).abs<2)) &&
(l[1]==0&&p[:t].nil? || l[1]!=0 && (j[l[0]][l[1]-1].nil? || j[l[0]][l[1]-1][:b].swapcase==p[:t] && (j[l[0]][l[1]-1][:v]-p[:v]).abs<2)) &&
(l[1]==j[0].length-1&&p[:b].nil? || l[1]!=j[0].length-1 && (j[l[0]][l[1]+1].nil? || j[l[0]][l[1]+1][:t].swapcase==p[:b] && (j[l[0]][l[1]+1][:v]-p[:v]).abs<2))
end
def rec(j,pl,l) # Recursive function to try every piece at every position it can fit
found = [false,[]]
pl.each_index{|i|
p=pl[i]
if fits(j,p,l) # Try the piece in the spot
pl2=pl.dup
pl2.delete_at i
j2=j.dup
j2[l[0]][l[1]] = p
if pl2.length==0 # If we have spent all the pieces, then we have a complete puzzle
found = [true,j2]
break
else # Keep recurring until we use up all the pieces
n=l[0]+1
l2=[n%j.length, l[1]+n/j.length]
found = rec(j2,pl2,l2)
break if found[0]
end
end
}
found
end
j=[]
w.times { j.push []; h.times { j.last.push nil }}
solved = rec(j, pieces, [0,0])
h.times{|y|
w.times{|x|
print solved[1][x][y][:v].to_s + " "
}
puts ''
}
```
] |
[Question]
[
## Introduction
I can't stand text abbreviations, mainly because for the most part I have no idea what most of them mean. Of course, cut backs need to be made, so if they are necessary to fit the text in the character limit, I'll allow them.
## Challenge
You have to write a program that takes passage of text and determines whether text abbreviations are required to fit the passage in the 140 character limit (as used by Twitter).
The passage can be read from a plaintext file, supplied via system arguments or input by a user. You may not hardcode it.
## Determining
Your program needs to replace all abbreviations (*Note:* Don't, can't, won't etc. are allowed) found in the passage and replace them with full words. If the expanded passage fits within 140 characters, then abbreviations are unneccessary. Otherwise, abbreviations are necessary. Any unknown abbreviations should be treated as standard words.
The output should be boolean (**`True`** if necessary or **`False`** otherwise) but if the passage was longer than 140 characters in the first place, then **`Tl;dr`** should be printed.
## Abbreviations
All abbreviations required are detailed [here](http://www.netlingo.com/acronyms.php). You decide how you parse the information. You may store the list in a local file of any name, providing that the list is taken from the provided URL.
Abbreviations should be defined as all in capital letters (eg. LOL, LMFAO, OP not lol, lmfao, op).
***Note:*** In several cases, the abbreviation is not the standard format (`abbreviation -> meaning`) and sometimes has multiple meanings, words and/or spellings. Ignore all of these cases. For clarification, all abbreviations that you need to worry about should be single word.
Ignore all non alphabetic abbreviations (e.g. Ignore <3,99). Abbreviations that start with an alphabetic character can be parsed (e.g. Do not ignore A/S/L,L8).
## Test cases (taken from random tweets)
### 1: Returns `true`
>
> IDG people who MSG U and still lag even THO U reply straight away like how did U become that busy in 5 secs that U can't communicate LOL CYA
>
>
>
### 2: Returns `false`
>
> If your role models are celebrities; Athletes, Actors, Singers, Politicians, etc then you need a life coach. ASAP.
>
>
>
### 3: Returns `Tl;dr`
>
> For your information: we technically live about 80 milliseconds in the past because that's how long it takes our brains to process information.
>
>
>
## Winning Criteria
The shortest code wins.
***Based upon the alt-text of [xkcd 1083](http://xkcd.com/1083/index.html)***
## Thanks to Ingo Bürk, [here's](http://airblader.de/data.txt) a JSON file of the list
[Answer]
# ECMAScript 6 + HTML (117 ~~123~~ ~~144~~)
Using HTML to store the dictionary. [Try it online](http://jsfiddle.net/y3b4ht9b/3/) (with any ECMAScript 6 browser such as Firefox).
```
d=eval(d.innerHTML),t=r=prompt(l=140);for(k in d)r=r.replace(RegExp(k,'g'),d[k])
alert(t.length>l?'Tl;dr':r.length>l)
```
I'm just blatantly ignoring the currently open questions to this challenge, hoping it won't render my solution incorrect. YOLO #abbreviations
## Explanation
The dictionary has been filtered according to the rules (ignoring abbreviations starting with non-alphanumeric character, ignoring multi word abbreviations, only considering uppercase abbreviations, using first replacement if there are options).
To save bytes in the code, the dictionary has also been transformed such that the key is already a regular expression with word boundary match to deal with punctuation.
Then the actual code becomes a matter of reading the tweet, doing all the replacements and checking for the length.
The script used for preparation can be found [here](http://jsfiddle.net/170gb534/). It is based upon the [JSON file](http://www.airblader.de/data.txt) I have extracted from the website.
* *Edit #1:* Thanks to Optimizer for golfing it down for a win of 21 bytes
* *Edit #2:* Another 6 bytes thanks to Optimizer's tip of using `eval`.
] |
[Question]
[
An often-used trick in BF-golfing is something I call "multiply then add." Let's say that you want to initialize the memory to contain a series of numbers, like `87 75 68 96`. The simplest way to do this is to simply write out a long series of 326 `+` signs. A better method, however is below.
```
++++++++++[>+++++++++>+++++++>+++++++>++++++++++<<<<-]>--->+++++>-->----
```
(I write this by hand, I hope it works correctly)
The basic idea is that you create a series of numbers (9,7,7,10), multiply them by a constant (10), and then add another series of numbers (-3,5,-2,-4). My invented form of notation writes this as (10;9,7,7,10;-3,5,-2,-4) which directly corresponds to the BF code.
There is a lot of importance placed in how the numbers are divided. If I were to pick a larger constant, then the first series of numbers would be much smaller, yet there will tend to be larger remainders after the multiplication. If I were to pick a smaller constant, then the first series would be larger, but the second series smaller.
Your goal is to write the shortest program to find the best possible way to write a series of numbers in BF using the multiply-then-add strategy.
Your program will recieve a series of non-negative integers. It should find the best way to generate these numbers.
For example, lets say that it receives the series (3,16,8,4), as an easy example. The best way to represent this is by the set of numbers (4;1,4,2,1;-1,0,0,0), which is what your program is expected to output (the exact formatting isn't as important). This corresponds to the following program:
```
++++[>+>++++>++>+<<<<-]>->>>
```
[Answer]
**Python, 205 characters**
```
def o(l):
d=lambda l,a:[(d+1,m-a)if m>a/2 else(d,m) for d,m in(divmod(x,a)for x in l)]
a,x=min((a+sum(abs(x)+abs(y)for x,y in d(l,a)),a,d(l,a))for a in range(1,max(l)+1))[1:]
return [a]+zip(*x)
```
Examples:
```
>>> o([3,16,8,4])
[4, (1, 4, 2, 1), (-1, 0, 0, 0)]
>>> o([87,75,68,96])
[11, (8, 7, 6, 9), (-1, -2, 2, -3)]
>>> o([4,4,4])
[4, (1, 1, 1), (0, 0, 0)]
>>> o([1,2,3,4,5,6,7,8])
[4, (0, 0, 1, 1, 1, 1, 2, 2), (1, 2, -1, 0, 1, 2, -1, 0)]
```
As a bonus for a very long solution, the BF formater:
```
def bf(l):
N,f,s=o(l)
return ('%s[%s%s-]%s'%(N*'+',
''.join('>' + x*'+' for x in f),
''.join('<' for _ in f),
''.join('>' + abs(x)*('+' if x>0 else '-')for x in s)))
>>> bf([3,16,8,4])
'++++[>+>++++>++>+<<<<-]>->>>'
```
[Answer]
### GolfScript, 74 65 characters
```
:f$-1=),{[..{1${\2$*-.abs 2$+[@@]}++\),%$0=}+f%{(@+\}%@\+]}%$0=1=
```
A quite long golfscript solution which simply tries lots of combinations of numbers and takes the shortest representation.
Input is the list of numbers on the stack and output a list of the final numbers (grouped differently compared with the question - constant, tuples of [factor, addon])
[Examples](http://golfscript.apphb.com/?c=ewogIDpmJC0xPSkse1suLnsxJHtcMiQqLS5hYnMgMiQrW0BAXX0rK1wpLCUkMD19K2YleyhAK1x9JUBcK119JSQwPTE9Cn06QzsKClszIDE2IDggNF0gQyBwCg%3D%3D&run=true):
```
{
:f$-1=),{[..{1${\2$*-.abs 2$+[@@]}++\),%$0=}+f%{(@+\}%@\+]}%$0=1=
}:C;
[3 16 8 4] C p # -> [4 [1 -1] [4 0] [2 0] [1 0]]
[87 75 68 96] C p # -> [11 [8 -1] [7 -2] [6 2] [9 -3]]
[1 2 3 4 5 6 7 8] C p # -> [4 [0 1] [0 2] [1 -1] [1 0] [1 1] [1 2] [2 -1] [2 0]]
[5 5 5] C p # -> [5 [1 0] [1 0] [1 0]]
```
[Answer]
## Javascript 244 characters
```
function b(c){function e(f,c){n=m.abs;return n(f)+n(c)}a=0;m=Math;for(i=1;i<m.max.apply(null,c);i++)x=[],y=c.map(function(c){r=c/i|0;d=c%i;d=d>i/2?(r++,d-i):d;x.push(d);return r}),l=i+y.reduce(e)+x.reduce(e),a=!a||l<a[0]?[l,i,y,x]:a;return a};
```
Examples (first digit in output is total program length):
```
> b([3,16,8,4])
[13, 4, [1, 4, 2, 1], [-1, 0 0 0]]
> b([87,75,68,96])
[49, 11, [8, 7, 6, 9], [-1, 2, 2, -3]]
```
I think with "=>" syntax coming soon, I could likely condense further. I wish I was better at BF, I think a solution in BF would be interesting as well.
Solution before condensed:
```
function b(s){
a = 0;
m = Math;
for(i=1; i<m.max.apply(null, s); i++) {
x = [];
y = s.map(function(n) {
r = n/i|0;
d = n%i;
d = d > i/2 ? (r++, d-i) : d;
x.push(d);
return r;
});
l=i+y.reduce(c)+x.reduce(c);
a = !a || l < a[0] ? [l,i,y,x] : a;
}
function c(g, h) {
n = m.abs;
return n(g)+n(h);
}
return a;
}
```
Then ran through google closure compiler to condense to a single line.
] |
[Question]
[
There are two inputs, the first input is a map in 2D array, where 2 represents an obstacle and 0 represents a regular ground, and 1 represents the player's location (implies that the player is standing on ground), the second input is the player's movement range.
A player can move on the map (horizontally, vertically, but not diagonally) within the movement range (0 to movement range inclusive), and the player can travel through an obstacle, but only one at a time. At last, a player cannot stand on an obstacle.
The program outputs an 2D array of booleans, showing all possible squares the player can move to.
Here are some examples:
Input
```
________
_____#__
___+__#_
#__#____
________, range=2
(_ = 0, + = 1, # = 2)
```
Output
```
___+____
__+++___
_+++++__
__+_+___
___+____ (+ = true, _ = false)
```
Input
```
__________
__________
______#___
__#_+##___
__________
____#_____
__________, range=4
```
Output
```
___+++____
__+++++___
_+++++_+__
++_++_____
_+++++++__
__++_++___
___+++____
```
There will be two winners: shortest brute-force and shortest efficient algorithm (the map and the movement range can get arbitrarily large)
[Answer]
# Python, 284 characters
```
def M(A,R):
X,Y=range(len(A[0])),range(len(A))
G,P,H=[set(x+1j*y for x in X for y in Y if A[y][x]>=z) for z in(0,1,2)]
P-=H
for i in' '*R:P|=G&reduce(lambda x,y:x|y,[set(p+d for p in P)-(H&set(p+d for p in H))for d in(1,1j,-1,-1j)])
return[[x+1j*y in P-H for x in X]for y in Y]
def display(A):print'\n'.join(''.join('_+'[c]for c in r)for r in A)
A=[[0,0,0,0,0,0,0,0],
[0,0,0,0,0,2,0,0],
[0,0,0,1,0,0,2,0],
[2,0,0,2,0,0,0,0],
[0,0,0,0,0,0,0,0]]
display(M(A,2))
A=[[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,2,0,0,0],
[0,0,2,0,1,2,2,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,2,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]
display(M(A,4))
```
The main `M` routine takes the 2D array containing the map and the range, and returns the 2D array of booleans.
`G` is the set of all indexes of (in-bounds) squares, encoded as complex numbers. `H` is the same but for the obstacles, and `P` is the same for the player. The main loop updates `P` by moving `P` in each of the 4 cardinal directions, filtered by the obstacles and the bounds of the array.
] |
[Question]
[
What is the shortest selector (by character count) to select ALL html elements on a web page, without using asterisk (\*)? Some examples are the following:
```
a,:not(a) /*9 chars*/
:nth-child(n) /*12 chars*/
:link,:not(:link) /*17 chars*/
```
]
|
[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/255572/edit).
Closed 1 year ago.
[Improve this question](/posts/255572/edit)
Given a rectangle input with only `\`, `/` and space, decide if it's a valid output of [Drawing in Slashes](https://codegolf.stackexchange.com/questions/37390/)
Empty lines and columns at edge get cleaned up, so the 3rd true case is true.
True cases:
```
/\/\
/ /\ \
\/ / \
/\/ /\ \
\ / \/
\ \
\ \
\/
/\/\
/ /\ \
/ \ \/
/ /\ \/\
\/ \ /
/ /
/ /
\/
/\
\/
/\
\/
```
False cases:
```
/\
/ \
\ \/
\/
/\
/ \
\ \
\/
/\
\/
/\
\/
```
Shortest code in each language wins.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 62 bytes
```
WS⊞υι≔E/\ΣEυ⁺μ⌕Aλιθ∧∧⬤υ¬﹪⁺№ι/№ι\²⬤E⌊υEυ§λκ¬﹪⁺№ι/№ι\²⬤⊟θ⌊﹪⁺ι⌊θ²
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nVDNSsQwEMZrnmLIaQpdAnsS9lQFcQ9dCns0Hmq7boNp0m4S9V287EHRV9KncdIGd88GAt98fD_DvH01XX1obK2Px4_gHxeXPxdXL53SO8C1GYLf-oMye8wyqILrMOSgshUrnFN7g2U9IBdS8hy2oZ9GElQ6OOxzuFGmLbRGHT3x5TCSt6JAj4Vp508C8mysx9K2QVuc7Nc2kEjlwAUn32mkshi0nOKiOZaWyqieFgjEpSUKvzbt7jWWP0XpfwpSQ2UHHGNyajmPUSd6_LNlq3f30Lh00M87vnjW_P77FoQUEgCYIASEmCQEhJiQM8eIjYxgMClIAwkRID6COfcX) Link is to verbose version of code. Takes input as a rectangular list of newline-terminated strings. Not actually sure this works in general, but posting anyway just in case.
] |
[Question]
[
You want to write your English essay. However, all characters on your keyboard broke other than the arrow keys and the enter key. You want to find out how to place the characters so you can write your essay with the least movement.
Formally, you have to assign to each character of `!"$%&'()+,-./0123456789:;<=?[]`abcdefghijklmnopqrstuvwxyz⇦⇧` a unique 2D integer coordinate, and minimize \$ d = \sum\_{c\_1 , c\_2} {\text{freq}(c\_1, c\_2) \text{dist}(c\_1, c\_2)} \$, with \$\text{dist}\$ being the Manhattan destince between the position of the characters, and \$\text{freq}\$ being the frequency of the character pair, [which is described here](https://pastebin.com/Yw9FcLv2), with the frequency of each pair not detailed assumed \$0\$. Note that some pairs appear in both permutations - you have to take into account both of them.
# Scoring
The winner is the code which would produce the best result in a minute on my computer (Intel Core i7-9700 with 8 threads, 32GB RAM), with the tie breaker being the time until that result is found.
# Rules
* Your language must have a freely available interpreter/compiler capable of running on Linux
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed, except optimizing for the given test cases - you are allowed (and even expected) to fine-tune your solution to produce the best solution on this given test case.
* You can't hardcode calculations - the solution should be found by the code during its execution, not beforehand.
* You can use any reasonable output format (i.e. output your solution and when did you find it when your program terminates, output your solution whenever the program improves it, etc.).
* You will receive the frequency JSON in stdin.
* Your solution must be deterministic. You can use PRNGs, you just have to hardcode their seed.
]
|
[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/248333/edit).
Closed 1 year ago.
[Improve this question](/posts/248333/edit)
I have a set of colored plastic cups. They come in four colors: green, yellow, pink, and blue. When I put them on my shelf, I like to stack them in a certain pattern. Your job is, given a list of any number of four distinct values (to represent the four cup colors), output a visual representation of how I would stack them.
## Rules
* The cups must be sorted into either two or three stacks.
* Green and yellow must always be paired with either pink or blue. Which one is paired with which does not matter but must be consistent.
* If there are an even number of pairs, they must be sorted into two stacks, with each stack having the same number of pair types (unless there are only two pairs, in which case they can be put in any order)
* The pink and blue cups in a pair must be above the green and yellow ones.
* Pairs with yellow cups must be above pairs with green cups.
* Any remaining cups must be evenly distributed amongst the bottoms of the stacks.
* If there are an even number of pairs and an even number of leftovers, use two stacks.
* If there are an odd number of ether pairs of leftovers, use three stacks. The extra cups and leftovers must go in the middle stack.
* Extra cups must be sorted in this order: Yellow above green above blue above pink.
## Output
Output must be a representation of the cup layout. Each color must be represented as a consistent one-character value, arranged into columns. A space must be used for empty slots. See below for examples.
## Examples
Using GYPB for green, yellow, pink and blue respectively
```
Input: GGYYPPBB
Output:
BB
YY
PP
GG
Input: GYPB
Output:
PB
GY
or
BP
YG
Input: PPGGBBYYY
Output:
B B
Y Y
P P
GYG
Input: PGPBYBPG
Output:
B
Y
PBP
GPG
```
]
|
[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/240495/edit).
Closed 2 years ago.
[Improve this question](/posts/240495/edit)
## Introduction
Congratulations! You've been selected to do research a a newly discovered animal called a fuzzy, a docile, simple creature that strongly resembles a cotton ball. Fuzzies love to be near other fuzzies, but not all fuzzies want to be near each other.
There are 6 types of fuzzies, 1a, 1b, 2a, 2b, 3a, and 3b. Each obeys different rules.
* Type 1a fuzzies want to be near any type b fuzzy. (vice versa for 1b)
* Type 3a fuzzies want to be near any type a fuzzy. (vice versa for 3b)
* Finally, type 2 fuzzies want to be near any fuzzy type, a or b.
* Perfect pairings are matches in which both fuzzies want to be near each other (ex. 1a and 1b)
* Semiperfect pairings are matches in which only one fuzzy wants to be near the other (ex 3a and 1b)
* Imperfect pairings are matches in which neither fuzzy wants to be with the other (ex. 3a and 3b)
## Your Challenge
Given a list of fuzzies:
1. Output the total number of perfect pairings. If there are any left:
2. Output the number of semiperfect pairings. If there are any left:
3. Output how many leftover bachelors there are.
Output and input format don't matter as long as you state them both.
## Test cases
```
1a, 1b:
1a and 1b are a perfect match
> 1 perfect, 0 semiperfect, 0 bachelors
1a, 2b, 2a, 3b:
1a and 2b are a perfect match
2a and 3b are a semiperfect match
> 1 perfect, 1 semiperfect, 0 bachelors
1a, 1b, 2a, 3a, 3b, 3b:
1a and 1b are a perfect match
2a and 3a are a perfect match
3b and 3b are an imperfect match
> 2 perfect, 0 semiperfect, 1 bachelor
1b, 2a, 3a
1b and 2a are a perfect match
3a is left over
(note: could also be:
2a and 3a are a perfect match
1b is left over
for the same result)
> 1 perfect, 0 semiperfect, 1 bachelor
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest in bytes wins.
]
|
[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/204641/edit).
Closed 3 years ago.
[Improve this question](/posts/204641/edit)
Inspired by [Braille graphics](https://codegolf.stackexchange.com/q/140624/9424) and [Build an analog clock](https://codegolf.stackexchange.com/q/10759/9424).
* The goal there is to create a tool that use terminal console to draw and animate a clock by using UTF-8 fonts `\U2800`: `⠀` to `\U28FF`: `⣿`.
```
00:[⠀] 01:[⠁] 02:[⠂] 03:[⠃] 04:[⠄] 05:[⠅] 06:[⠆] 07:[⠇] 08:[⠈] 09:[⠉] 0A:[⠊]
0B:[⠋] 0C:[⠌] 0D:[⠍] 0E:[⠎] 0F:[⠏] 10:[⠐] 11:[⠑] 12:[⠒] 13:[⠓] 14:[⠔] 15:[⠕]
...
EA:[⣪] EB:[⣫] EC:[⣬] ED:[⣭] EE:[⣮] EF:[⣯] F0:[⣰] F1:[⣱] F2:[⣲] F3:[⣳] F4:[⣴]
F5:[⣵] F6:[⣶] F7:[⣷] F8:[⣸] F9:[⣹] FA:[⣺] FB:[⣻] FC:[⣼] FD:[⣽] FE:[⣾] FF:[⣿]
```
* The program takes `HEIGHT` and `WIDTH` -- the height and width of the displayed clock in terminal characters -- as input.
* From `pixelWidth = WIDTH x 2` and `pixelHeight = HEIGHT x 4` you have to build something like a map, drawn your clock as described then extract 2 pixel width and 4 pixel height characters to choose one of 256 character in `\U2800` to `\U28FF`.
* They must be upgraded every second!! Care of code efficiency! (not 1 second delay plus drawing time) **+25 byte penalty if your clock drop any second!**
* The full circle of the clock is 1 point width, at 100% of ray, meaning ray could vary between horizontal (`ray=pixelWidth/2`) and vertical (`ray=pixelHeight/2`)!
* 12 hour ticks from 90% to 100% of ray.
* 60 minute ticks as single dot located at 90%, but displayed only if `width > 20` (terminal width greather than 20 characters).
* Hours arm length is 45% of ray.
* Minutes arm length is 77% of ray.
* Seconds arm is 88% or ray.
* Seconds arm is 1 point width.
* Hours and minutes arms have to be larger, for this, you will draw each of them 3 time: 1x centered, 1x shifted left by 1 dot and 1x shifted up by 1 dot.
* Hours, minutes and seconds arms have to progress each second like a regular analog clock.
* Of course, there could be some *variants*, mostly depending on how you drawn the circle. But as other graphic parts are lines, except some rare rounding bug, with a give size, at some precise time, all clock program could show same design... with some `1px` difference somewhere... Some sample you could copy-paste:
A `18x8` clock at `10h10'42"` like (without minutes ticks):
```
⠀⠀⠀⢀⣤⠒⠊⠉⠉⠋⠉⠑⠒⣤⡀⠀⠀⠀
⠀⢠⠊⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠑⡄⠀
⢸⠓⠀⠀⠀⣀⡀⠀⠀⠀⠀⠀⢀⣠⣤⠀⠚⡇
⡇⠀⠀⠀⠀⠉⠛⢷⣦⣤⡶⠟⠛⠉⠀⠀⠀⢸
⡏⠀⣀⡠⠔⠒⠊⠉⠉⠁⠀⠀⠀⠀⠀⠀⠀⢹
⢸⡤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢤⡇
⠀⠘⢄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡠⠃⠀
⠀⠀⠀⠈⠛⠤⢄⣀⣀⣄⣀⡠⠤⠛⠁⠀⠀⠀
```
A '39x15`@`3h42'02"`:
```
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡠⠤⠒⠒⠊⠉⡉⠉⢹⠉⢉⠉⠑⠒⠒⠤⢄⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⢀⡠⠒⠙⡆⠀⠂⠈⠀⠈⠀⠀⠀⠀⠀⠀⡸⠁⠀⠁⠐⠀⢰⠋⠒⢄⡀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⡠⠒⠁⠠⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠇⠀⠀⠀⠀⠀⠀⠀⠁⠄⠈⠒⢄⠀⠀⠀⠀
⠀⠀⣠⠊⠀⠄⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡜⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠠⠀⠑⣄⠀⠀
⠀⡰⠉⡉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠐⢉⠉⢆⠀
⢰⠁⠠⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡎⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠄⠈⡆
⡎⢀⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⡀⢱
⡧⠤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣤⣤⡶⠶⠶⠾⠶⢶⣤⣄⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠤⢼
⢇⠈⡀⠀⢀⣀⣤⣤⡶⠶⠟⠛⠛⠉⠉⠀⠀⠀⠀⠀⠀⠀⠀⠉⠙⠛⠻⠆⠀⠀⠀⠀⠀⠀⠀⠀⢀⠁⡸
⠸⡀⠐⠀⠈⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠂⢀⠇
⠀⠱⣀⣁⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣈⣀⠎⠀
⠀⠀⠙⢄⠀⠂⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠐⠀⡠⠋⠀⠀
⠀⠀⠀⠀⠑⠤⡀⠐⢀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡀⠂⢀⠤⠊⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠈⠑⠤⣠⠇⠀⠄⢀⠀⢀⠀⠀⠀⠀⠀⠀⠀⡀⠀⡀⠠⠀⠸⣄⠤⠊⠁⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠑⠒⠤⠤⢄⣀⣁⣀⣸⣀⣈⣀⡠⠤⠤⠒⠊⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
```
Or a `48x24` @ `9h16'23"`:
```
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠤⠤⠒⠒⠊⠉⠉⠉⡏⠉⠉⠑⠒⠒⠤⠤⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡔⠊⠉⠀⠀⡀⠀⠄⠀⠂⠀⠀⠃⠀⠐⠀⠠⠀⢀⠀⠀⠉⠑⢢⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⢀⠔⠊⠀⢳⠀⠐⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠂⠀⡞⠀⠑⠢⡀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⢀⠔⠁⠀⠀⠂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠐⠀⠀⠈⠢⡀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢀⠔⠁⢀⠀⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠀⡀⠈⠢⡀⠀⠀⠀⠀
⠀⠀⠀⢠⠊⠀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠀⠑⡄⠀⠀⠀
⠀⠀⡰⠓⠦⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⠴⠚⢆⠀⠀
⠀⢠⠃⠀⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⠀⠘⡄⠀
⠀⡇⠀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠀⢸⠀
⢸⠀⢀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡀⠀⡇
⡎⠀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠀⢱
⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠛⠛⠻⠶⠶⠶⣦⣤⣤⣄⣀⣀⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸
⡏⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠉⠙⣍⠙⠛⠻⠶⢶⣤⣄⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⢹
⢇⠀⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠣⡄⠀⠀⠀⠀⠉⠉⠛⠛⠷⠶⣦⣤⣄⡀⠀⠀⠀⠈⠀⡸
⢸⠀⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠢⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠁⠀⠀⠀⠁⠀⡇
⠀⡇⠀⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⢆⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠀⢸⠀
⠀⠘⡄⠀⠂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⢄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠐⠀⢠⠃⠀
⠀⠀⠱⡤⠖⠂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⡄⠀⠀⠀⠀⠀⠀⠀⠐⠲⢤⠎⠀⠀
⠀⠀⠀⠘⢄⠀⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠣⡄⠀⠀⠀⠀⠈⠀⡠⠃⠀⠀⠀
⠀⠀⠀⠀⠈⠢⡀⠈⠀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠢⢀⠀⠁⢀⠔⠁⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠈⠢⡀⠀⠀⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⠀⠀⢀⠔⠁⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠈⠢⢄⠀⡼⠀⠠⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠄⠀⢧⠀⡠⠔⠁⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠣⢄⣀⠀⠀⠁⠀⠂⠀⠄⠀⠀⡄⠀⠠⠀⠐⠀⠈⠀⠀⣀⡠⠜⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠒⠒⠤⠤⢄⣀⣀⣀⣇⣀⣀⡠⠤⠤⠒⠒⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
```
There is an accelerated sample of what they could look like, in a `80x24` terminal window, shot between `09h17'00"` and `09h18'00"`
[](https://i.stack.imgur.com/0yFGt.gif)
Another sample in a small `20x10` window shot between `09h59` and `10h00`:
[](https://i.stack.imgur.com/QLIml.gif)
This is code golf, so the shortest answer (in bytes) wins.
]
|
[Question]
[
The Hamming distance between two strings is the number of positions they differ at.
You are given a set of binary strings. The task is to find the length of the shortest route that visits all of them at least once and ends where it started, in a metric space where the distance between two strings is the Hamming distance between them.
Let \$N\$ be the number of input strings *and* the string length. There are 3 test cases for every \$N\$. The strings are created from random bits obtained from an acceptable random number generator. A RNG is acceptable if I can replace it with a RNG I like more without significantly affecting the program's performance.
A program's score is the largest \$N\$ it can correctly solve all 3 tests for within 60 seconds. The higher the score, the better. Answers with equal scores are compared by posting time (older answer wins).
Submissions will be timed on a PC with an (12-thread) AMD Ryzen 2600 CPU and a (cheap but relatively modern) AMD Radeon RX 550 GPU.
Programs must solve tests in order - that is, they must output the answer for the current test before generating the next one. This is unobservable, but it *could* be made observable at the cost of simple IO requirements (imagine me supplying an external RNG that asks you for the outputs).
This problem [is proven NP-complete](https://link.springer.com/article/10.1007/BF01935007).
Short explanation of the proof: take rectilinear (\$|\Delta x| + |\Delta y|\$) integer TSP and replace \$x\$ by a string with \$x\$ ones and \$[\text{something}] - x\$ zeroes, same for \$y\$; repeat strings until their count is equal to their length.
]
|
[Question]
[
There are many generalizations of Conway's Game of Life. One of them is the isotropic non-totalistic rulespace, in which the state of a cell in the next generation depends not just on its state and the amount of alive cells around it, but also the relative positions of the cells around it.
Given an rulestring corresponding to an [isotropic non-totalistic cellular automaton](https://conwaylife.com/wiki/Isotropic_non-totalistic_Life-like_cellular_automaton), an integer \$T\$, and an initial pattern \$P\$, simulate the initial pattern \$P\$ for \$T\$ generations under the given rulestring.
## Constraints
* The given rulestring is valid and does not contain the B0 transition.
* \$0 < T \le 10^3\$
* Area of bounding box of \$P \le 10^3\$
## Input
The rulestring, \$T\$ and \$P\$ will all be given in any necessary (specified) format.
## Output
Output the resulting pattern after \$P\$ is run \$T\$ generations.
## Example
Rulestring: `B2c3aei4ajnr5acn/S2-ci3-ck4in5jkq6c7c`
T: 62
Pattern (in canonical RLE format):
```
x = 15, y = 13, rule = B2c3aei4ajnr5acn/S2-ci3-ck4in5jkq6c7c
3b2o$2ob2o$2o4$13b2o$13b2o$3bo$2b3o$2bob2o$2bobo$2b2o!
```
Output:
```
x = 15, y = 13, rule = B2c3aei4ajnr5acn/S2-ci3-ck4in5jkq6c7c
3b2o$2ob2o$2o4$13b2o$13b2o$3b2o$b5o$bo3bo$bo2bo$2b3o!
```
## Scoring
This is extended [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), which means that the program with smallest (length in bytes - bonuses) wins.
Standard loopholes are not allowed. Your program is not allowed to use any external libraries that deal with cellular automata. Your program is expected to finish relatively quickly (in at most 10 minutes).
Bonuses:
* 10 for finishing in under 10 seconds under max tests
* 20 for accepting the rulestring in canonical form (e.g. `B2-a/S12`)
]
|
[Question]
[
>
> In computer science, a suffix automaton is the smallest partial deterministic finite automaton that recognizes the set of suffixes of a given string. (Wikipedia)
>
>
>
Given a string \$S\$ consisting of lowercase letters (`a-z`), construct the suffix automaton for it.
A suffix automaton is an array of states, 0-indexed or 1-indexed, depending on your implementation. The **ID** of a states is defined to be its location in the aforementioned array. The **initial state** \$t\_0\$ is the state that corresponds to the empty string, and **must be first in the array of states**.
A state is defined as a sequence of 27 integers:
* The first integer is the state's **suffix link**, or the ID of the state that corresponds to the current state's longest suffix that occurs more times than the current state in \$S\$. In the case the this state is \$t\_0\$, this value should be equal to a special value that is not a state ID.
* The second to 27th integer corresponds to the state's **transition pointer**, or the state ID that corresponds to this state's string + a letter, for characters `a` through `z` respectively. In the case that such a state does not exist, this value should be equal to a special value that is not a state ID.
For further information on a suffix automaton and how to construct it, see the [wikipedia page](https://en.wikipedia.org/wiki/Suffix_automaton) and the [CP-algorithms page](https://cp-algorithms.com/string/suffix-automaton.html).
## Input
The input string will be given in any acceptable format.
## Output
Output the array of states in any acceptable format. Be sure to state the "special values that is not a state ID".
## Example
For the string `abbbcccaabbccabcabc`, the suffix automaton's states should be structured similarly to this (blue edges = transition pointer, green dashed edges = suffix link):
[](https://i.stack.imgur.com/FZagB.png)
For the string `ddbadbdbddddbdbcabcdcaccabbbcbcbbadaccabbadcbdadcdcdbacbcadbcddcadcaaaacdbbbcaaadcaddcbaddbbcbbccdbc`:
[](https://i.stack.imgur.com/xlbwV.png)
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program (in bytes) wins.
Your code should run reasonably fast (in at most 10 seconds) for a string of length \$10^6\$. (If this requirement is too strict, I will relax the limit.)
]
|
[Question]
[
Given a matrix, the goal is to ensure all the values in each column occur at least once, while at the same time doing so requiring the least possible amount of rows. Fastest solution wins.
Note: a value in one column (e.g. 1) is considered different from the same value in another column.
Expected output: an array/list/series of row indices that retain all unique values across all columns.
**Example data:**
```
import numpy as np
import pandas as pd
np.random.seed(42)
num_rows = 10000
num_cols = 200
max_uniq_values = 10
data = pd.DataFrame({i: np.random.randint(0, max_uniq_values, num_rows)
for i in range(num_cols)})
# or python
# data = [np.random.randint(0, max_uniq_values, num_rows).tolist()
# for i in range(num_cols)]
```
**Minimal example (num\_rows=5, num\_cols=2, max\_uniq\_values=4)**
Input:
```
| 0 1
--------
0 | 1 1
1 | 2 2
2 | 3 4
3 | 3 3
4 | 4 4
```
Expected output:
```
[0, 1, 3, 4]
```
**Additionally**:
* Benchmark will happen on a 2015 Macbook Pro with CPU Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz.
* Restricted to use 1 core.
* External libraries allowed
* Blind test will be done on 10 random seeds (the same ones for each solution)
[Answer]
# Python3 + [PuLP](https://github.com/coin-or/pulp) library
This is equivalent to a set covering problem (where the elements are column/value pairs) which can be transformed into an integer linear programming problem.
```
from pulp import *
def opt(mat):
num_rows = len(mat)
covering_rows = {}
for row_nr, vals in enumerate(mat):
for pair in enumerate(vals):
covering_rows.setdefault(pair, []).append(row_nr)
prob = LpProblem("Minimal Covering Set of Rows", LpMinimize)
vars = LpVariable.dicts("R", range(num_rows), 0, 1, LpInteger)
prob += lpSum([vars[i] for i in range(num_rows)])
for rowlist in covering_rows.values():
prob += lpSum([vars[r] for r in rowlist]) >= 1
prob.solve()
assert prob.status==LpStatusOptimal, "Couldn't solve"
return [r for r in range(num_rows) if value(vars[r])==1]
```
On debian, the relevant package is called `python3-pulp`.
The function handles matrices with 20 columns and 100 rows in about one minute on weak hardware. The best way to substantially improve the speed is probably to use a better solver, which the PuLP library allows by adding an argument to the `solve` method call.
] |
[Question]
[
The idea for this code golf puzzle is from link: [The Bridge and Torch Problem](https://codegolf.stackexchange.com/questions/75615/the-bridge-and-torch-problem)
>
> The inspiration for this code golf puzzle is the Bridge and Torch
> problem, in which d people at the start of a bridge must all cross it
> in the least amount of time.
>
>
> The catch is that at most two people can cross at once, otherwise the
> bridge will crush under their weight, and the group only has access to
> one torch, which must be carried to cross the bridge.
>
>
> Each person in the whole puzzle has a specified time that they take to
> walk across the bridge. If two people cross together, the pair goes as
> slow as the slowest person.
>
>
>
For this challenge d=4 and for the input you will get a time t and a list of tuple like:
>
> input = (19,[('A', 1), ('B', 3), ('C', 4), ('D', 5)])
>
>
>
Now the task is to find all possible solution how they can cross the bridge within the time t. Solve the problem in the fewest bytes of code possible.
For example for this input:
>
> input =(19,[('A', 1), ('B', 2), ('C', 5), ('D', 10)])
>
>
>
Your solution should look like:
>
> Solution
>
>
> ['Couple A and B cross the bridge']
>
>
> [' A goes back']
>
>
> ['Couple D and C cross the bridge']
>
>
> [' B goes back']
>
>
> ['Couple A and B cross the bridge']
>
>
> Solution
>
>
> ['Couple A and B cross the bridge']
>
>
> [' A goes back']
>
>
> ['Couple D and A cross the bridge']
>
>
> [' A goes back']
>
>
> ['Couple C and A cross the bridge']
>
>
> Solution
>
>
> ['Couple A and B cross the bridge']
>
>
> [' A goes back']
>
>
> ['Couple C and A cross the bridge']
>
>
> [' A goes back']
>
>
> ['Couple D and A cross the bridge']
>
>
> Solution
>
>
> ['Couple A and C cross the bridge']
>
>
> [' A goes back']
>
>
> ['Couple D and A cross the bridge']
>
>
> [' A goes back']
>
>
> ['Couple A and B cross the bridge']
>
>
> Solution
>
>
> ['Couple A and C cross the bridge']
>
>
> [' A goes back']
>
>
> ['Couple A and B cross the bridge']
>
>
> [' A goes back']
>
>
> ['Couple D and A cross the bridge']
>
>
> Solution
>
>
> ['Couple A and D cross the bridge']
>
>
> [' A goes back']
>
>
> ['Couple C and A cross the bridge']
>
>
> [' A goes back']
>
>
> ['Couple A and B cross the bridge']
>
>
> Solution
>
>
> ['Couple A and D cross the bridge']
>
>
> [' A goes back']
>
>
> ['Couple A and B cross the bridge']
>
>
> [' A goes back']
>
>
> ['Couple C and A cross the bridge']
>
>
>
The output don't need to be in a specific format.
]
|
[Question]
[
Your job is to create the slowest growing function you can in no more than 100 bytes.
Your program will take as input a nonnegative integer, and output a nonnegative integer. Let's call your program P.
It must meet the these two criterion:
* Its source code must be less than or equal to 100 bytes.
* For every K, there is an N, such that for every n >= N, P(n) > K. In other words, [lim(n->∞)P(n)=∞](https://en.wikipedia.org/wiki/Limit_of_a_sequence#Infinite_limits). (This is what it means for it to be "growing".)
Your "score" is the growth rate of your program's underlying function.
More specifically, program P is grows slower than Q if there is a N such that for all n>=N, P(n) <= Q(n), and there is at least one n>=N such that P(n) < Q(n). If neither program is better than the other, they are tied. (Essentially, which program is slower is based on the value of lim(n->∞)P(n)-Q(n).)
The slowest growing function is defined as the one that grows slower than any other function, according to the definition in the previous paragraph.
This is [growth-rate-golf](/questions/tagged/growth-rate-golf "show questions tagged 'growth-rate-golf'"), so the slowest growing program wins!
Notes:
* To assist in scoring, try to put what function your program calculates in the answer.
* Also put some (theoretical) input and outputs, to help give people an idea of how slow you can go.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 100 bytes
```
llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P4cO4P9/Q4PBAf5HAQA "Brachylog – Try It Online")
This is probably nowhere near the slowness of some other fancy answers, but I couldn't believe noone had tried this simple and beautiful approach.
Simply, we compute the length of the input number, then the length of this result, then the length of this *other* result... 100 times in total.
This grows as fast as log(log(log...log(x), with 100 base-10 logs.
[If you input your number as a string](https://tio.run/##7daxDYAwEATBXlwBUA4ZEEBgCYmM6o8ujAXjCsb3ya7Xsh13PfcpqQ1eUsbh9dcBgYPjNw57cnBwcHT49BgHhx6zJwcHB4ceMwUHhx7j4ODg0GN25eDQY/bk4ODg0GMcHBx6jIODg0OPuS8Hhx6zJwcHB4ce4@Dg0GMcHBwcesx9OTj0mD05ODg49BgHB4ce4@Dg4NBj7svBocfsycHBwSHHODg45BgHBwfH93NMj3Fw6DF7cnBwcPiU@3Jw6DEODg4OPWZXDg49Zk8ODg4OPcbBwaHHODg4OPSY@3Jw6DF7cnBwcOgxDg4OPcbBwcGhx9yXg0OP2ZODg4NDj3FwcOgxDg4ODj3mvhwcesyeHBwcHK1eyfwA), this will run extremely fast on any input you could try, but don't expect to ever see a result higher than 1 :D
[Answer]
# Haskell, 100 bytes, score=[*f*ε0](https://en.wikipedia.org/wiki/Fast-growing_hierarchy)−1(*n*)
```
_#[]=0
k#(0:a)=k#a+1
k#(a:b)=(k+1)#(([1..k]>>fst(span(>=a)b)++[a-1])++b)
f n=[k|k<-[0..],1#[k]>n]!!0
```
### How it works
This computes the inverse of a very fast growing function related to [Beklemishev’s worm game](http://www.mi.ras.ru/%7Ebekl/Problems/gpa5.html). Its growth rate is comparable to *f*ε0, where *f*α is the [fast-growing hierarchy](https://en.wikipedia.org/wiki/Fast-growing_hierarchy) and ε0 is the first [epsilon number](https://en.wikipedia.org/wiki/Epsilon_numbers_(mathematics)).
For comparison with other answers, note that
* exponentiation is comparable to *f*2;
* iterated exponentiation ([tetration](https://en.wikipedia.org/wiki/Tetration) or [↑↑](https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation)) is comparable to *f*3;
* [↑↑⋯↑↑](https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation) with *m* arrows is comparable to *f**m* + 1;
* The [Ackermann function](https://en.wikipedia.org/wiki/Ackermann_function) is comparable to *f*ω;
* repeated iterations of the Ackermann function (constructions like [Graham’s number](https://en.wikipedia.org/wiki/Graham%27s_number)) are still dominated by *f*ω + 1;
* and ε0 is the limit of all towers ωωω⋰ω.
[Answer]
# JavaScript (ES6), Inverse Ackermann Function\*, 97 bytes
\*if I did it right
```
A=(m,n)=>m?A(m-1,n?A(m,n-1):1):n+1
a=(m,n=m,i=1)=>{while(A(i,m/n|0)<=Math.log2(n))i++;return i-1}
```
Function `A` is the [Ackermann function](https://en.wikipedia.org/wiki/Ackermann_function). Function `a` is supposed to be the [Inverse Ackermann function](https://en.wikipedia.org/wiki/Ackermann_function#Inverse). If I implemented it correctly, Wikipedia says that it will not hit `5` until `m` equals `2^2^2^2^16`. I get a `StackOverflow` around `1000`.
Usage:
```
console.log(a(1000))
```
# Explanations:
## Ackermann Function
```
A=(m,n)=> Function A with parameters m and n
m? :n+1 If m == 0, return n + 1; else,
A(m-1,n? :1) If n == 0, return A(m-1,1); else,
A(m,n-1) return A(m-1,A(m,n-1))
```
## Inverse Ackermann Function
```
a=(m,n=m,i=1)=>{ Function a with parameter m, with n preinitialized to m and i preinitialized to 1
while(A(i,m/n|0)<=Math.log2(n)) While the result of A(i, floor(m/n)) is less than log₂ n,
i++; Increment i
return i-1} Return i-1
```
[Answer]
# Pure Evil: Eval
```
a=lambda x,y:(y<0)*x or eval("a("*9**9**9+"x**.1"+",y-1)"*9**9**9)
print a(input(),9**9**9**9**9)//1
```
The statement inside the eval creates a string of length 7\*[1010101010108.57](http://www.wolframalpha.com/input/?i=(9%5E9%5E9%5E9%5E9)%5E(9%5E9%5E9%5E9%5E9)%5E(9%5E9%5E9%5E9%5E9)) which consists of nothing but *more calls to the lambda function* each of which will construct a string of *similar* length, on and on until eventually `y` becomes 0. Ostensibly this has the same complexity as the Eschew method below, but rather than relying on if-and-or control logic, it just smashes giant strings together (and the net result is getting more stacks...probably?).
The largest `y` value I can supply and compute without Python throwing an error is 2 which is already sufficient to reduce an input of max-float into returning 1.
A string of length 7,625,597,484,987 is just too big: `OverflowError: cannot fit 'long' into an index-sized integer`.
I should stop.
# Eschew `Math.log`: Going to the (10th-)root (of the problem), Score: function effectively indistinguishable from y=1.
Importing the math library is restricting the byte count. Lets do away with that and replace the `log(x)` function with something roughly equivalent: `x**.1` and which costs approximately the same number of characters, but doesn't require the import. Both functions have a sublinear output with respect to input, but x0.1 grows [even more slowly](http://www.wolframalpha.com/input/?i=log(10,x),x%5E0.1where+x+from+0+to+1000). However we don't care a whole lot, we only care that it has the same base growth pattern with respect to large numbers while consuming a comparable number of characters (eg. `x**.9` is the same number of characters, but grows more quickly, so there is some value that would exhibit the exact same growth).
Now, what to do with 16 characters. How about...extending our lambda function to have Ackermann Sequence properties? [This answer](https://codegolf.stackexchange.com/questions/18028/largest-number-printable/18359#18359) for large numbers inspired this solution.
```
a=lambda x,y,z:(z<0)*x or y and a(x**.1,z**z,z-1)or a(x**.1,y-1,z)
print a(input(),9,9**9**9**99)//1
```
The `z**z` portion here prevents me from running this function with anywhere *close* to sane inputs for `y` and `z`, the largest values I can use are 9 and ***3*** for which I get back the value of 1.0, even for the largest float Python supports (note: while 1.0 is numerically greater than 6.77538853089e-05, increased recursion levels move the output of this function closer to 1, while remaining greater than 1, whereas the previous function moved values closer to 0 while remaining greater than 0, thus even moderate recursion on this function results in so many operations that the floating point number loses *all* significant bits).
Re-configuring the original lambda call to have recursion values of 0 and 2...
```
>>>1.7976931348623157e+308
1.0000000071
```
If the comparison is made to "offset from 0" instead of "offset from 1" this function returns `7.1e-9`, which is definitely smaller than `6.7e-05`.
Actual program's *base* recursion (z value) is 101010101.97 levels deep, as soon as y exhausts itself, it gets reset with 10101010101.97 (which is why an initial value of 9 is sufficient), so I don't even know how to correctly compute the total number of recursions that occur: I've reached the end of my mathematical knowledge. Similarly I don't know if moving one of the `**n` exponentiations from the initial input to the secondary `z**z` would improve the number of recursions or not (ditto reverse).
# Lets go even slower with even more recursion
```
import math
a=lambda x,y:(y<0)*x or a(a(a(math.log(x+1),y-1),y-1),y-1)
print a(input(),9**9**9e9)//1
```
* `n//1` - saves 2 bytes over `int(n)`
* `import math`,`math.` saves 1 byte over `from math import*`
* `a(...)` saves 8 bytes total over `m(m,...)`
* `(y>0)*x` [saves a byte](https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python/103309#103309) over `y>0and x`
* ~~`9**9**99` increases byte count by 4 and increases recursion depth by approximately [`2.8 * 10^x`](http://www.wolframalpha.com/input/?i=9%5E9%5E99) where `x` is the old depth (or a depth nearing a googolplex in size: 101094).~~
* `9**9**9e9` increases the byte count by 5 and increases recursion depth by...an insane amount. Recursion depth is now 1010109.93, for reference, a googolplex is 1010102.
* lambda declaration increases recursion by an extra step: `m(m(...))` to `a(a(a(...)))` costs 7 bytes
New output value (at 9 recursion depth):
```
>>>1.7976931348623157e+308
6.77538853089e-05
```
Recursion depth has exploded to the point at which this result is *literally* meaningless except in comparison to the earlier results using the same input values:
* The original called `log` 25 times
* The first improvement calls it 81 times
+ The *actual* program would call it 1e992 or about 10102.3 times
* This version calls it 729 times
+ The *actual* program would call it (9999)3 or slightly less than 101095 times).
# Lambda Inception, score: ???
I heard you like lambdas, so...
```
from math import*
a=lambda m,x,y:y<0and x or m(m,m(m,log(x+1),y-1),y-1)
print int(a(a,input(),1e99))
```
I can't even run this, I stack overflow even with a mere *99* layers of recursion.
The old method (below) returns (skipping the conversion to an integer):
```
>>>1.7976931348623157e+308
0.0909072713593
```
The new method returns, using only 9 layers of incursion (rather than the full *googol* of them):
```
>>>1.7976931348623157e+308
0.00196323936205
```
I think this works out to be of similar complexity to the Ackerman sequence, only small instead of big.
Also thanks to ETHproductions for a 3-byte savings in spaces I didn't realize could be removed.
Old answer:
# The integer truncation of the function log(i+1) iterated ~~20~~ 25 times (Python) using lambda'd lambdas.
PyRulez's answer can be compressed by introducing a second lambda and stacking it:
```
from math import *
x=lambda i:log(i+1)
y=lambda i:x(x(x(x(x(i)))))
print int(y(y(y(y(y(input()))))))
```
~~99~~ 100 characters used.
This produces an iteration of ~~20~~ 25, over the original 12. Additionally it saves 2 characters by using `int()` instead of `floor()` which allowed for an additional `x()` stack. ~~If the spaces after the lambda can be removed (I cannot check at the moment) then a 5th `y()` can be added.~~ Possible!
If there's a way to skip the `from math` import by using a fully qualified name (eg. `x=lambda i: math.log(i+1))`), that would save even more characters and allow for another stack of `x()` but I don't know if Python supports such things (I suspect not). Done!
This is essentially the same trick used in [XCKD's blog post on large numbers](https://blog.xkcd.com/2007/03/14/large-numbers/), however the overhead in declaring lambdas precludes a third stack:
```
from math import *
x=lambda i:log(i+1)
y=lambda i:x(x(x(i)))
z=lambda i:y(y(y(i)))
print int(z(z(z(input()))))
```
This is the smallest recursion possible with 3 lambdas that exceeds the computed stack height of 2 lambdas (reducing any lambda to two calls drops the stack height to 18, below that of the 2-lambda version), but unfortunately requires 110 characters.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 42 bytes
```
iXI:`2*.]X{oXH1H/16L+XKxI:`Yl.]K+XKXdXzXGx
```
[Try it online!](https://tio.run/##y00syfn/PzPC0yrBSEsvNqI6P8LD0EPf0MxHO8K7AigamaMX6w1kR6REVEW4V/z/b2gAAA "MATL – Try It Online")
This program is based on the harmonic series with the use of Euler–Mascheroni constant. As I was reading @LuisMendo documentation on his MATL language (with capital letters, so it looks important) I noticed this constant. The slow growth function expression is as following:
[](https://i.stack.imgur.com/hUCD4.png)
where *εk ~ 1/2k*
I tested up to 10000 iterations (in Matlab, since it is too large for TIO) and it scores below 10, so it is very slow.
[](https://i.stack.imgur.com/59jvA.png)
Explanations:
```
iXI % ask user input (number of iterations)
:`2*.] % do...while loop, multiply by 2
X{ % convert numeric array into cell array
o % convert to double precision array
XH1H/ % copy to clipboard H and divide by 1: now we have an array of 1/2k
16L % Euler–Mascheroni constant
+ % addition (element-wise, singleton expansion)
XKxI:` % save, clear the stack, do...while loop again
Yl % logarithm
.] % break, ends the loop
K+XK % paste from clipboard K, sum all
Xd % trim: keep the diagonal of the matrix
Xz % remove all zeros
XG % plot (yes it plots on-line too!)
x % clear the stack
% (implicit) display
```
Empirical proof:
(ln *k*) + 1 in red always above ln*k* + γ + *εk* in blue.
[](https://i.stack.imgur.com/XeNJp.png)
The program for (ln *k*) + 1 was made in
## Matlab, ~~47~~ ~~18~~ 14 bytes
```
n=input('')
A=(1:n)
for k=1:n
A(k)=log(k)+1
end
```
Interesting to note that the elapsed time for n=100 is 0.208693s on my laptop, but only 0.121945s with `d=rand(1,n);A=d*0;` and even less, 0.112147s with `A=zeros(1,n)`. If zeros is a waste of space, it saves speed!
But I am diverging from the topic (probably very slowly).
Edit:
thanks to Stewie for ~~helping~~ reducing this Matlab expression to, simply:
```
@(n)log(1:n)+1
```
[Answer]
# [Haskell](https://www.haskell.org/), 100 bytes
```
f 0 a b=a^b
f c a b=foldr(f$c-1)a$[0..b]>>[a]
i=length.show
0#x=i x
y#x=i$(y-1)#x
g=(f(f 9 9 9)9 9#)
```
[Try it online!](https://tio.run/##XYq9CsMgFIV3n@KCDjpUzNiA2TvlAUIK1zT@UGtKEqh5ehs79hwO3zccj9tzjrEUCwoQjMa7IRamn9slPlZu2XRpBLJBSWnGrhtwJEHHObndy80vH6Jo1gEyOSoZP847zcRpbrmFa604R0V5YUhte@u5IFX1ew1pZw4a9Z/yBQ "Haskell – Try It Online")
This solution does not take the inverse of a quickly growing function instead it takes a rather slowly growing function, in this case `length.show`, and applies it a bunch of times.
First we define a function `f`. `f` is a bastard version of Knuth's uparrow notation that grows slightly faster (slightly is a bit of an understatement, but the numbers we are dealing with are so large that in the grand scheme of things...). We define the base case of `f 0 a b` to be `a^b` or `a` to the power of `b`. We then define the general case to be `(f$c-1)` applied to `b+2` instances of `a`. If we were defining a Knuth uparrow notation like construct we would apply it to `b` instances of `a`, but `b+2` is actually *golfier* and has the advantage of being faster growing.
We then define the operator `#`. `a#b` is defined to be `length.show` applied to `b` `a` times. Every application of `length.show` is an approximately equal to log10, which is not a very swiftly growing function.
We then go about defining our function `g` that takes and integer in and applies `length.show` to the integer a bunch of times. To be specific it applies `length.show` to the input `f(f 9 9 9)9 9`. Before we get into how large this is lets look at `f 9 9 9`. `f 9 9 9` is *greater than* `9↑↑↑↑↑↑↑↑↑9` (nine arrows), by a massive margin. I believe it is somewhere between `9↑↑↑↑↑↑↑↑↑9` (nine arrows) and `9↑↑↑↑↑↑↑↑↑↑9` (ten arrows). Now this is an unimaginably large number, far to big to be stored on any computer in existence (in binary notation). We then take that and put that as the first argument of our `f` that means our value is larger than `9↑↑↑↑↑↑...↑↑↑↑↑↑9` with `f 9 9 9` arrows in between. I'm not going describe this number because it is so large I don't think I would be able to do it justice.
Each `length.show` is approximately equal to taking the log base 10 of the integer. This means that most numbers will return 1 when `f` is applied to them. The smallest number to return something other than 1 is `10↑↑(f(f 9 9 9)9 9)`, which returns 2. Lets think about that for a moment. As abominably large as that number we defined earlier is, the *smallest* number that returns 2 is 10 to its own power that many times. Thats 1 followed by `10↑(f(f 9 9 9)9 9)` zeros.
For the general case of `n` the smallest input outputting any given n must be `(10↑(n-1))↑↑(f(f 9 9 9)9 9)`.
**Note that this program requires massive amounts of time and memory for even small n (more than there is in the universe many times over), if you want to test this I suggest replacing `f(f 9 9 9)9 9` with a much smaller number, try 1 or 2 if you want ever get any output other than 1.**
[Answer]
# Binary Lambda Calculus, 237 bits (under 30 bytes)
```
-- compute periods of final row of Laver tables as in as in
-- section 3.4 of https://arxiv.org/pdf/1810.00548.pdf
let
-- Let mx = 2^n - 1. We consider a dual version of the shelf, determined
-- by a |> mx = a-1 (mod 2^n), which satisfies
-- 0 |> b = b
-- a |> 0 = 0
-- a |> mx = a-1
-- a |> b = (a |> b+1) |> a-1
-- Note that the latter two equations iterate f_a = \x. x |> (a-1).
-- In fact, for a > 0, we implement a |> b = f_a^{mx-b} (a-1) as f_a^{mx*b} 0,
-- exploiting the fact that a |> mx = a-1 = 0 |> a-1 = f_a 0
-- and (modulo 2^n) 1+mx-b = -b = -1 * b = mx*b
0 = \f\x. x;
1 = \x. x;
2 = \f\x. f (f x);
succ = \n\f\x. f (n f x);
pred = \n\f\x. n (\g\h. h (g f)) (\h. x) (\x. x);
laver = \mx.
-- swap argument order to simplify iterated laver
let laver = \b\a. a (\_. mx (b (laver (pred a))) 0) b
in laver;
dblp1 = \n\f\x. n f (n f (f x)); -- map n to 2*n+1
find0 = \mx\i.laver mx i mx (\_.find0 mx (succ i)) i;
period = \n.let mx = pred (n 2) in find0 mx 1
in
period
```
compiles down to the 237 bits
```
010000010101000110100000000101010101000110100000000101100001011111110011110010111110111100111111111101100000101101011000010101111101111011100000011100101111101101010011100110000001110011101000100000000101011110000001100111011110001100010
```
This function grows to infinity assuming large cardinal axiom I3, which I believe is what Peter Taylor was hinting at. It grows way slower than any sort of inverse Ackerman.
[Answer]
# [Python 3](https://docs.python.org/3/), 100 bytes
The floor of the function log(i+1) iterated 99999999999999999999999999999999999 times.
One can use exponents to make the above number even larger...
```
from math import *
s=input()
exec("s=log(s+1);"*99999999999999999999999999999999999)
print(floor(s))
```
[Try it online!](https://tio.run/##hcFBCoAgEADAu6@QTrt2ik4RPiZCU1BX1g3q9dsTmumvJGqramSqth6SbK6dWKwzw@fWbwE04QknTMMXumDMC@6T2/6h6ZybQCxEDANR9QM "Python 3 – Try It Online")
[Answer]
# APL, Apply `log(n + 1)`, `e^9^9...^9` times, where the length of the chain is `e^9^9...^9` of length of chain minus 1 times, and so on.
```
⌊((⍟1+⊢)⍣((*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣(*⍣⊢)))))))))))))))))))))9))⊢
```
[Answer]
## The floor of the function log(i+1) iterated 14 times (Python)
```
import math
x=lambda i: math.log(i+1)
print int(x(x(x(x(x(x(x(x(x(x(x(x(x(x(input())))))))))))))))
```
I don't expect this to do very well, but I figured its a good start.
Examples:
* e^n^n^n^n^n^n^n^n^n^n^n^n^n^n -> ~n (approximately n)
[Answer]
# Ruby, 100 bytes, score-1 = fωω+1(n2)
Basically borrowed from my [Largest Number Printable](https://codegolf.stackexchange.com/a/120228), here's my program:
```
->k{n=0;n+=1 until(H=->z,a=[0]*z{b,*c=a;z.times{z+=b ?H[z,b==1?c:[b>1?b-1:z]*z+c]:z};z};H[n*n]>k);n}
```
[Try it online](https://tio.run/##DcpLCsMgEADQq7hs/ZTYpTK69Q7iIiNZhLRDaRNIR3J2E3jL993w33foJiyNYPCkwIqN1vl1S2AC6xHyUCQ31LLC6Pmxzu/p11gBipgyawSwsbqMwUY01vG1VS2OD39JmSSVsNw9Hf0j9vws/QQ)
Basically computes the inverse of fωω+1(n2) in the fast growing hierarchy. The first few values are
```
x[0] = 1
x[1] = 1
x[2] = 1
x[3] = 1
x[4] = 2
```
And then it continues to output `2` for a very long time. Even `x[G] = 2`, where `G` is Graham's number.
[Answer]
## Python, 100 bytes, \$999 \uparrow^{99999} \text{Score} = \text{Input}\$, using up-arrow notation
```
f=lambda b,i,n:n/b if i==0 else(0if n<=1else 1+f(b,i,f(b,i-1,n)));print(f(999,99999,int(input(""))))
```
This is based on *extremely* iterated logarithms, since most people know that logarithms alone grow pretty slowly.
This program describes a ternary lambda function known simply as `f` which takes a base `b`, iterations `i` and input `n`. If `i == 0`, it just returns the input divided by the base. With `i == 1`, you may recognise the output as \$\text{max}(0, \lfloor \text{log}\_b(n)\rfloor)\$. Then, with `i == 2`, this is equal to \$\text{log\*}(n) = \text{max}(0, \lfloor \text{slog}\_b(n)\rfloor)\$, where \$\text{slog}\$ is the super logarithm (iteration instead of exponentiation). Then, this program gets user input and returns \$\text{max}(0, \lfloor ^{99999}\text{log}\_{999}(n)\rfloor)\$. Here, \$^m\text{log}\$ is logarithm using \$\uparrow^m\$, so \$^2\text{log}\$ is \$\text{slog}\$.
[Answer]
## Clojure, 91 bytes
```
(defn f (apply +(for[n(range %)](/(loop[r 1 v n](if(< v 1)r(recur(* r v)(Math/log v))))))))
```
Kind of calculates the `sum 1/(n * log(n) * log(log(n)) * ...)`, which I found from [here](https://math.stackexchange.com/a/452441). But the function ended up 101 bytes long so I had to drop the explicit number of iterations, and instead iterate as long as the number is greater than one. Example outputs for inputs of `10^i`:
```
0 1
1 3.3851305685279143
2 3.9960532565317575
3 4.232195089969394
4 4.370995106860574
5 4.466762285601703
6 4.53872567524327
7 4.595525574477128
8 4.640390570825608
```
I assume this modified series still diverges but do now know how to prove it.
>
> The third series actually requires a googolplex numbers of terms before the partial terms exceed 10.
>
>
>
[Answer]
## Mathematica, 99 bytes
(assuming ± takes 1 byte)
```
0±x_=1±(x-1);y_±0=y+1;x_±y_:=(y-1)±x±(x-1);(i=0;NestWhile[(++i;#±#±#±#±#±#±#±#)&,1,#<k&/.k->#];i)&
```
The first 3 commands define `x±y` to evaluate `Ackermann(y, x)`.
The result of the function is the number of times `f(#)=#±#±#±#±#±#±#±#` need to be applied to 1 before the value get to the value of parameter. As `f(#)=#±#±#±#±#±#±#±#` (that is, `f(#)=Ackermann[Ackermann[Ackermann[Ackermann[Ackermann[Ackermann[Ackermann[#, #], #], #], #], #], #], #]`) grow very fast, the function grow very slow.
[Answer]
# Javascript (ES6), 94 bytes
```
(p=j=>i=>h=>g=>f=>x=>x<2?0:1+p(p(j))(j(i))(i(h))(h(g))(g(f))(f(x)))(_=x=>x)(_)(_)(_)(Math.log)
```
**Explanation**:
`Id` refers to `x => x` in the following.
Let's first take a look at:
```
p = f => x => x < 2 ? 0 : 1 + p(p(f))(f(x))
```
`p(Math.log)` is approximately equal to `log*(x)`.
`p(p(Math.log))` is approximately equal to `log**(x)` (number of times you can take `log*` until the value is at most 1).
`p(p(p(Math.log)))` is approximately equal to `log***(x)`.
The inverse Ackermann function `alpha(x)` is approximately equal to the minimum number of times you need to compose `p` until the value is at most 1.
If we then use:
```
p = g => f => x => x < 2 ? 0 : 1 + p(p(g))(g(f))(f(x))
```
then we can write `alpha = p(Id)(Math.log)`.
That's pretty boring, however, so let's increase the number of levels:
```
p = h => g => f => x => x < 2 ? 0 : 1 + p(p(h))(h(g))(g(f))(f(x))
```
This is like how we constructed `alpha(x)`, except instead of doing `log**...**(x)`, we now do `alpha**...**(x)`.
Why stop here though?
```
p = i => h => g => f => x => x < 2 ? 0 : 1 + p(p(i))(i(h))(h(g))(g(f))(f(x))
```
If the previous function is `f(x)~alpha**...**(x)`, this one is now `~ f**...**(x)`. We do one more level of this to get our final solution.
] |
[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/178403/edit).
Closed 5 years ago.
[Improve this question](/posts/178403/edit)
# Introduction
This is a little challenge with the goal of identifying repeated pattern "blocks" in a string, and outputting them with their frequency of occurence from left to right.
A friend asked me this question and I realized it wasn't as simple as tossing what you've seen into a hash table and popping them off if previously seen.
# Example Input and Output
Input:
>
> "TTBBPPPBPBPBPBBBBPBPBPBB"
>
>
>
The idea:
>
> T T | B B | P P P | BP BP BP | B B B B | PB PB PB | B
>
>
>
Output:
>
> 2T, 2B, 3P, 3BP, 4B, 3PB, B
>
>
>
However any output format that shows the number of repetitions, and respective repeated substrings, are allowed.
Is it possible to do this with reasonable time complexity?
I'm curious as to the standard, legible approach to this kind of question, but as this is code golf - shortest code wins!
Cheers!
]
|
[Question]
[
>
> TeaScript is a powerful JavaScript golfing language created by StackExchange, PPCG, user Downgoat. TeaScript compiles to JavaScript and contains many helpful features for golfing
>
>
>
This question is to list some [TeaScript](https://teascript.readthedocs.io/en/latest/index.html) golfing [tips](/questions/tagged/tips "show questions tagged 'tips'")
]
|
[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/138764/edit).
Closed 6 years ago.
[Improve this question](/posts/138764/edit)
Aliens have arrived, and they aren't friendly.
Turns out, they've been in the process of converting all matter in the universe into compute capability so they can have more fun in their VR simulations.
Our solar system is the last bit of space they haven't converted yet, and they're about to remedy this oversight.
However! As "payment" for the use of our matter, the aliens are generously allowing us to run one computation on their universe-sized compute cluster before they convert us to compute units.
After world leaders conferred on how to handle this crisis, you were tasked with **creating an algorithm to run on the alien cluster which will not complete before the heat death of the universe**, thus forestalling our demise.
However, internally the aliens charge back the cost of using the cluster by the number of bytes of code submitted, so the alien philanthropy division which is making us this generous offer and footing the bill is incentivizing us to keep our code short by glassing one of our cities (in [descending population order](https://en.wikipedia.org/wiki/List_of_cities_proper_by_population)) for every byte of code we submit. Thus, your orders are to [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the algorithm to as few bytes as possible.
## Submission Rules
The aliens are smart. They will not allow you to submit code which you cannot prove complies with the following properties:
* Must halt, eventually™. The burden of proving this is on you. (Yes, the halting problem is impossible in the general case. Pick one where it isn't.)
* Must meaningfully utilize the entire cluster. If any cores would be idle or doing unnecessary computation for over half of the total runtime of the algorithm, the aliens will reject the algorithm (unnecessary means that the result would not change if that computation were skipped. Feel free to compute things in all manner of inefficient fashion).
* Must produce a result which will fit in the combined storage capacity of all human computers (assume one zettabyte is available) so we can appreciate the resulting data before we are annihilated. Write the result to stdout.
* Must produce a result that is deterministic (so take no input) and at least a little bit mathematically interesting (determining if the googolplexth digit of pi is odd is interesting; producing 42 is not).
To satisfy your bosses (the world leaders) your program must not halt until after the heat death of the universe ([10¹⁰⁰ years from now](https://en.wikipedia.org/wiki/Heat_death_of_the_universe#Time_frame_for_heat_death)).
## System Specifications
The alien cluster is abstracted behind an API which makes it seem like a single enormous SMT x86\_512 CPU.
* Every atom in the universe besides ours ([10⁸⁰](http://www.wolframalpha.com/input/?i=number%20of%20atoms%20in%20the%20universe)) functions as a 512 bit CPU core running at [900 petahertz](https://electronics.stackexchange.com/a/123640/)
* Due to black holes, there is infinite zero-latency non-volatile RAM available for use during the computation, but you are still limited to the 512 bit address space (that's just under 8×10¹⁶³ yottabytes of space) and the end product has to fit within one ZB.
* Wormholes are used to address cache coherency and atomicity issues with zero latency, as long as the appropriate language-level features are used to indicate their necessity
## Answer Validation
Regrettably, I have neither access to a comparable system for testing submissions, nor the patience to see if they do in fact take until the heat death of the universe to halt. Thus, the following will be expected of a submission (please number them in your answers):
1. An English-language overview of what your algorithm computes, how it works, and why the output is mathematically interesting.
2. An ungolfed and scaled-down version of your problem/algorithm which can run to completion in seconds or less on normal human hardware (such as [ideone](https://ideone.com/)). This is not scored, but used to demonstrate that you have a working algorithm.
3. The golfed solution you want to submit to the aliens. This is what bytes will be scored on / cities glassed.
4. An explanation of the modifications taken to increase the runtime of your `2.` code to the runtime of your `3.` code.
5. An argument for why neither the aliens nor your bosses will reject your submission. Some hand-waving is allowed here, though formal proofs earn major kudos. At a minimum, show some math relating to your loops or recursion depth against the clock speed and core count of the alien system, along with commentary on your work-breakdown strategy to saturate all the cores.
There are no programming language restrictions, as long as the resulting program can meet the constraints of the challenge. Minor kudos for use of language-level features (such as `size_t`) which can run through the aliens' 512 bit compiler without requiring any work on their end.
]
|
[Question]
[
## Challenge
Given a time and a timezone as input, output the time in that timezone.
## Time
The time will be given in 24 hour format like so:
```
hh:mm
```
Where hh is the two digit hour and mm is the two digit minute. Note that the hour and the minute will always be padded with zeroes like so:
```
06:09
```
All the times given are at UTC+00:00.
*The hours in your output do not have to be padded wih zeroes but your time it must be in 24 hour format*
## Timezone
The timezone will be given in the following format:
```
UTC±hh:mm
```
Where ± is either going to be a + or a - and hh, is the two digit hour and mm is the two digit minute (again, these will be padded with zeroes).
To find the time in that timezone, you either add (if the symbol is +) or subtract (if the symbol is -) the time after the UTC± from the inputted time.
For example, if the input was `24:56` and `UTC-02:50`, you would subtract 2 hours and 50 minutes from 24:56:
```
24:56
02:50 -
-----
22:06
```
The output would be `22:06`.
## Examples
### Chicago
```
Input: 08:50 and UTC-06:00
Output: 02:50
```
### Kathmandu
```
Input: 09:42 and UTC+05:45
Output: 15:27
```
### Samoa
```
Input: 06:42 and UTC+13:00
Output: 19:42
```
### Hawaii
```
Input: 02:40 and UTC-10:00
Output: 16:40
```
Note that this has gone to the previous day.
### Tokyo
```
Input: 17:25 and UTC+09:00
Output: 02:25
```
Note that this has gone to the following day.
## Rules
You must not use any built in date functions or libraries.
Assume all input will be valid times and time offsets.
The timezone will be in the range `UTC-24:00` to `UTC+24:00` inclusive.
In the case of *half past midnight*, the correct representation should be `00:30`, ***not*** `24:30`.
## Winning
The shortest code in bytes wins.
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/), 45 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
### Expression
Takes two strings as right argument.
```
24 60⊤∘⍎∘⍕('+-'∩⍕),'/',(0 60⊥2⊃':'⎕VFI ¯5∘↑)¨
```
[Try it online!](https://tio.run/nexus/apl-dyalog#@///f8ijtglGJgpmBo@6ljzqmPGotw9MTtVQ19ZVf9SxEsjU1FHXV9fRMAArWmr0qKtZ3Ur9Ud/UMDdPhUPrTUHq2yZqHlrBFaKgbmBhZWqgrqAeGuKsa2BmZQBkP@qdq@CckZmcmJ4PVmFpZWIEUaFtYGplYgpR4Z1YkpGbmJdSClZjhlBjaAw3JTgxNz8RLG9kZQKzxdAALu@RWJ6YmQlSYGhuZWQKs8QSriAkP7syHwA "APL (Dyalog APL) – TIO Nexus")
### Explanation
`24 60⊤` the number-to-base-*a*24*b*60 conversion
`∘` of
`⍎` the evaluation
`∘` of
`⍕` the formatted (i.e. flattened with separating spaces)
`('+-'∩⍕)` intersection of "+-" and the formatted input (this extracts the plus or minus)
`,` followed by
`(`...`)¨` the following for each of the inputs (the time and the offset)
`0 60⊥` the *a*∞*b*60-to-number conversion of
`2⊃` the second element of
`':'⎕VFI` the, using colon as field separator, **V**erified and **F**ixed **I**nput of
`¯5∘↑` the last five characters ("hh:mm")
### Step-by-step on "17:25" and "UTC+09:00"
The left-side expression on the right side data, gives the data of the next line.
```
'17:25' 'UTC+09:00'
/ / \ \
(...)¨ applies the function train to both inputs
/ / \ \
¯5∘↑ '17:25' 'UTC+09:00'
':'⎕VFI '17:25' '09:00'
2⊃ (1 1)(17 25) (1 1)(9 0)
0 60⊥ 17 25 9 0
1045 540
\ \ / /
This is where ¨ stops, and execution continues on the resulting list
\ \ / /
'/', 1045 540
('+-'∩⍕), '/' 1045 540
⍕ '+' '/' 1045 540
⍎ '+ / 1045 540'
24 60⊤ 1585
2 25
```
[Answer]
# C, 109 bytes
```
a,b,c;f(char*t,char*z){for(c=0;z[3];t=z+=3)sscanf(t,"%d:%d",&a,&b),c+=b+a*60;printf("%d:%02d",c/60%24,c%60);}
```
Invoke as follows:
```
int main() { f("17:25", "UTC+09:00"); }
```
[Answer]
## JavaScript (ES6), 101 bytes
```
(t,z,g=s=>+(s[3]+s[7]+s[8])+s.slice(3,6)*60,m=g('UTC+'+t)+g(z)+1440)=>(m/60%24|0)+':'+(m/10%6|0)+m%10
```
Would be 121 bytes if I padded the hours.
[Answer]
# Python 2, 129 bytes
```
def T(t,a):f=[int.__add__,int.__sub__]["-"in a];m=f(int(t[3:5]),int(a[7:9]));print`f(int(t[0:2])+m/60,int(a[4:6]))%24`+":"+`m%60`
```
Call as `T("02:45", "UTC-05:33")`
[Answer]
# Python 2, 84 bytes
```
def f(t,z):i=int;r=60*(i(t[:2])+i(z[3:6]))+i(t[3:])+i(z[3]+z[7:]);print r/60%24,r%60
```
All test cases are at [**ideone**](http://ideone.com/vsxuOa)
Output format is space separated, with no leading zeros.
[Answer]
# Java 201 bytes
```
String T(String t,String z){return(24+Integer.valueOf(t.substring(0,2))+Integer.valueOf((String)z.subSequence(3,6)))%24+":"+(60+Integer.valueOf(t.substring(3,5))+Integer.valueOf(z.substring(7,9)))%60;}
```
Called as
T("12:00", "UTC+02:40")
Unglolfed for the logic,
```
String T(String t, String z) {
int i = (24 + Integer.valueOf(t.substring(0, 2)) + Integer.valueOf((String) z.subSequence(3, 6))) % 24;
int j = (60 + Integer.valueOf(t.substring(3, 5)) + Integer.valueOf(z.substring(7, 9))) % 60;
return i + ":" + j;
}
```
Any help to get it under 200 would be appreciated!
[Answer]
## Javascript (ES6), ~~93~~ 92 bytes
```
t=>((t=eval(t.replace(/.*?(.)?(..):(..)/g,'$1($2*60+$3)+720')))/60%24|0)+':'+(t/10%6|0)+t%10
```
### Test cases
```
let f =
t=>((t=eval(t.replace(/.*?(.)?(..):(..)/g,'$1($2*60+$3)+720')))/60%24|0)+':'+(t/10%6|0)+t%10
console.log(f("08:50 UTC-06:00")); // 2:50
console.log(f("09:42 UTC+05:45")); // 15:27
console.log(f("06:42 UTC+13:00")); // 19:42
console.log(f("02:40 UTC-10:00")); // 16:40
console.log(f("17:25 UTC+09:00")); // 2:25
```
[Answer]
## Ruby, 95 bytes
```
g=->s{"60*"+s.scan(/\d+/).map(&:to_i)*?+}
f=->t,z{r=eval(g[t]+z[3]+g[z]);print r/60%24,?:,r%60}
```
## Usage
```
f[gets,gets]
```
### Inputs(example)
```
08:50
UTC-06:00
```
[Answer]
# Java ~~156~~ ~~150~~ ~~149~~ ~~147~~ 142 bytes
```
t->z->{Integer H=100,T=H.valueOf(t.replace(":","")),Z=H.valueOf(z.replace(":","").substring(3)),c=(T/H+Z/H+24)*60+T%H+Z%H;return c/60%24+":"+c%60;}
```
## Test cases & ungolfed
```
import java.util.function.BiFunction;
public class Main {
public static void main(String[] args) {
BiFunction<String,String,String> f = (t,z)->{
Integer H = 100, // Hundred, used several times, shorter as variable
T = H.valueOf(t.replace(":","")), // as int (HHMM)
Z = H.valueOf(z.replaceAll("[UTC:]","")), // as int (-HHMM)
c = (T/H + Z/H + 24) * 60 + T%H + Z%H; // transform into minutes
return c/60%24+":"+c%60;
};
test(f, "08:50", "UTC-06:00", "02:50");
test(f, "09:42", "UTC+05:45", "15:27");
test(f, "03:42", "UTC-05:45", "21:57");
test(f, "06:42", "UTC+13:00", "19:42");
test(f, "02:40", "UTC-10:00", "16:40");
test(f, "17:25", "UTC+09:00", "02:25");
}
private static void test(BiFunction<String,String,String> f, String time, String zone, String expected) {
// Padding is allowed. Make sure the padding is skipped for the test, then.
String result = String.format("%2s:%2s", (Object[])f.apply(time, zone).split(":")).replace(" ","0");
if (result.equals(expected)) {
System.out.printf("%s + %s: OK%n", time, zone);
} else {
System.out.printf("%s + %s: Expected \"%s\", got \"%s\"%n", time, zone, expected, result);
}
}
}
```
## Shavings
* 150 -> 149: `a/H*60+b/H*60` -> `(a/H+b/H)*60`
* 149 -> 147: `(T/H+Z/H)*60+1440` -> `(T/H+Z/H+24)*60`.
* 147 -> 142: `z.replace(":","").substring(3)` -> `z.replaceAll("[UTC:]","")`
[Answer]
# C# 214 205 183 Bytes
```
string f(char[]t,char[]u){int s=~(u[3]-45),z=48,m=(t[3]-z)*10+t[4]-z+((u[7]-z)*10+u[8]-z)*s,h=(t[0]-z)*10+t[1]-z+((u[4]-z)*10+u[5]-z)*s+m/60+(m>>8)+24;return$"{h%24}:{(m+60)%60:D2}";}
```
205 byte version
```
string f(string t,string u){Func<string,int>P=int.Parse;var T=t.Split(':');int s=u[3]<45?1:-1,m=P(T[1])+P(u.Substring(7))*s,h=P(T[0])+P($"{u[4]}"+u[5])*s+m/60+(m<0?-1:0)+24;return$"{h%24}:{(m+60)%60:D2}";}
```
Ungolfed
```
string f(char[] t, char[] u)
{
int s = ~(u[3]-45),
z = 48,
m = (t[3] - z) * 10 + t[4] - z + ((u[7] - z) * 10 + u[8] - z) * s,
h = (t[0] - z) * 10 + t[1] - z + ((u[4] - z) * 10 + u[5] - z) * s + m / 60 + (m>>8) + 24;
return $"{h % 24}:{(m + 60) % 60:D2}";
}
```
Original 214:
```
string f(string t,string u){Func<string,int>P=int.Parse;var T=t.Split(':');int h=P(T[0]),m=P(T[1]),s=u[3]<45?1:-1;m+=P(u.Substring(7))*s;h+=P($"{u[4]}"+u[5])*s+m/60+(m<0?-1:0)+24;return$"{h%24:D2}:{(m+60)%60:D2}";}
```
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 40 bytes
```
r{':/60b}:F~r3>(\F\~1440,=60b{s2Te[}%':*
```
[Try it online!](https://tio.run/nexus/cjam#Lco/C8IwFATwvZ/CRSr@IS@vedFe0UXoKLS2k3URXAVxDMlXj6lxOfjd3fui3FUFdA36JvauhLL08GhDV51WUzsFbQxtj6l0Hx6eN78ssY73l1eRCGIX43DeEUOooEPKbAtKrmF49oYERorU/q2r384w@a9ptt6DJf/r5C8 "CJam – TIO Nexus") (As a test suite.)
### Explanation
```
r e# Read first input (time).
{':/60b}:F e# Define a function F, which splits a string around ':' and
e# treats the two elements as base-60 digits.
~ e# Run that function on the first input.
r3> e# Read the second input and discard the 'UTC'.
( e# Pull off the +-.
\F e# Apply F to the timezone offset.
\~ e# Execute the + or - on the two amounts of minutes.
1440,= e# Modulo 1440 to fit everything into the 24-hour format.
60b e# Obtain base 60 digits again.
{s2Te[}% e# Convert each digit to a string and pad it to 2 decimal digits.
':* e# Join them with a ':'.
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 100 bytes
```
:
59$*:,
+`(\d+):
$1,$1
\d+
$*
T`1`0`-.+
^
1440$*
+`10|\D
1{1440}
^(1{60})*(.*)
$#1:$.2
\b\d\b
0$&
```
[Try it online!](https://tio.run/nexus/retina#LcpBDoIwEAXQ/T@FiaMpLZCZ2qLMVhMvgLvGNIRbIGfHIm4m8/7/J/PMqyL2ZLWGyyZNrlKQ1CQoP8hiyJI5N63DGxICl8hl4U96ADJvyQK8jcwdL5U1ra1AR1FqPdKYpjSC6byuzBq7w2u4N@w1MvhW7u5OubjX4Dc7jhoiSvq3XH6917DvhTfLVX3c933xFw "Retina – TIO Nexus")
### Explanation
```
:
59$*:,
```
Replaces each `:` with 59 of them and a comma as a separator.
```
+`(\d+):
$1,$1
```
Repeatedly duplicates the number in front of a `:`. So the first two stages multiply the hour-value by 60.
```
\d+
$*
```
Convert each number to unary.
```
T`1`0`-.+
```
If there's a minus sign in the input, then this transliteration stage turns all the `1`s after it into `0`s. We're basically using `0` as a unary `-1` digit here.
```
^
1440$*
```
Insert 1440 `1`s (i.e. a full day). This is to ensure that the time doesn't get negative.
```
+`10|\D
```
This repeatedly removes all non-digits (i.e. the space, the `UTC`, the `+` or `-`, as well as all the `,` we've inserted) and the `10` combination, thereby cancelling positive and negative digits. This basically subtracts the second number from the first if it's negative, or adds it otherwise.
```
1{1440}
```
Removes 1440 `1`s if possible (basically taking the result modulo 1440 to fit it into a single 24 hours).
```
^(1{60})*(.*)
$#1:$.2
```
Decompose the number into hours and minutes by matching as many chunks of 60 digits as possible (counting the chunks with `$#1`) followed by the remaining digits (whose length is counted with `$.2`).
```
\b\d\b
0$&
```
If there are any single digits in the result, prepend a zero.
] |
[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/119489/edit).
Closed 6 years ago.
[Improve this question](/posts/119489/edit)
Make a program which can fill a 2D space with "pursuit polygons".
The following picture will help you understand better what I mean.
[](https://i.stack.imgur.com/xm6TA.jpg)
You can also look up "pursuit curves" or [mice problem](http://mathworld.wolfram.com/MiceProblem.html).
You can use any convex n-polygon you like
here are some examples
**Triangle**:
[](https://i.stack.imgur.com/jG2MJ.jpg)
**Square**:
[](https://i.stack.imgur.com/GbFFY.jpg)
**Pentagon**
[](https://i.stack.imgur.com/fRoMo.jpg)
notice that for every polygon you can also use the "anti-clockwise" version of the polygon, which produces interesting results
[](https://i.stack.imgur.com/AWIiB.jpg)
Can you find a way to divide and fill a given space with pursuit polygons?
The result would look better if this could work with ANY convex polygon and not only the regular polygons that I used...
**EDIT**
I am new here, so I'll try some specifications:
**RULES**
You must fill an A4 page ( 2480 Pixels X 3508 Pixels)
You can use only triangles,4-gons and pentagons.(try some of them to have anti-clockwise rotation)
Fewest bytes wins.
Use at least 10 polygons and at most 20
All the polygons must be convex
The borders must be the sides of the polygons.So the polygons must fit perfectly in the given rectangular space.
The algorithm must create RANDOM patterns but you should try to keep the polygons all about the same size and make the polygons as regular as possible.
Sorry for the edits
]
|
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 6 years ago.
[Improve this question](/posts/117629/edit)
In preparation for the AP Computer Science AP Test (Java), our teacher has been giving us FRQs from previous years for practice.
My friend and I were golfing this during class today and got it as short as we could, but I'd like to see if there are any shorter solutions any of you can come up with.
Rules:
* You must use the predefined method headers, method names, and parameter names.
* You do not have to specify imports.
* All code is to be written in Java.
* No external libraries
Information:
**Part A**
Given an array of type `int`, write a method that returns the sum of the elements of the array.
```
public int arraySum(int[] arr)
{
/*Implementation to be written in part A*/
}
```
Now, write the implementation for the method `arraySum`.
**Part B**
Given a 2D array of type `int`, write a method that returns a 1-dimensional `int` array containing the sums of each row of the given 2-dimensional array. You must use `arraySum` but may assume it works properly regardless of what you put for part A.
```
public int[] array2dSum(int[] arr2d)
{
/*Implementation to be written in part B*/
}
```
Now, write the impmenetation for the method `array2dSum`.
**Part C**
Given a 2D array of type `int`, write a method that returns whether or not the sums of the rows of the array are *diverse*, meaning the array contains no duplicate sums. You must use `array2dSum` but may assume it works properly regardless of what you put for part A.
```
public boolean isDiverse(int[] arr2d)
{
/*Implementation to be written in part C*/
}
```
Now, Write the implementation for the method `isDiverse`.
---
Here's what I have:
**A** - 31 chars
```
return IntStream.of(arr).sum();
```
**B** - 59 chars
```
return Stream.of(arr2d).mapToInt(x->arraySum(x)).toArray();
```
**C** - 86 chars
```
int[]h=array2dSum(arr2d);return IntStream.of(h).distinct().toArray().length==h.length;
```
---
Test Inputs:
`arraySum(new int[] {1, 2, 3})` returns 6
`array2dSum(new int[][] {{1,2},{3,4}})` returns {3,7}
`isDiverse(new int[][] {{1,2,3},{4,5,6},{7,8,9}})` returns true
`isDiverse(new int[][] {{1,2,3},{4,5,6},{1,2,3},{7,8,9}})` returns false
]
|
[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/111591/edit).
Closed 6 years ago.
[Improve this question](/posts/111591/edit)
We've had problems to generate minesweeper games.
We've had problems to solve these minesweeper games.
Now...
**It's time to battle other people on a minesweeper game!**
Your program must be run in Java. Essentially, each player can do an action every turn.
1. You may move to any space touching yours including corners. The board does not wrap around.
2. You may place a mine in the spot you currently occupy, and then to any space touching yours including corners.
3. You may place a mine on any space adjacent to yours including corners.
4. You may defuse a mine on any space adjacent to yours including corners. This turn is wasted if you defuse an empty spot. (This turn does nothing if you try to defuse a spot with someone on it, but that doesn't need to be explicitly stated because there won't be a living bot on a mine...)
5. You may do nothing.
You must make your bot in a class that extends the class `MineBot`. MineBot looks like this:
```
public abstract class MineBot {
private int x, y;
public abstract int changeMines(int[][] field);
public abstract int[] proceed(int[][] field);
public final int getX() {
return x;
}
public final void setX(int x) {
this.x = x;
}
public final int getY() {
return y;
}
public final void setY(int y) {
this.y = y;
}
}
```
(You must keep the final methods as they are for your submission to be valid)
`MineBot#changeMines(int[][])` is asked first. The result is a single `int`, representing whether or not you would like to perform an action involving a mine. This could be placing a mine, or defusing a mine. `0` means no, `1` means defuse, and `2` means place a mine. (`2` or anything not `0` or `1`)
Then, `MineBot#proceed(int[][])` is executed. The following things happen in the following ordering:
1. First, bots that are defusing mines make their move. All spots that were targeted by defusers are now safe to move onto.
2. Next, bots that are placing mines make their move. Bots may not place a bomb on a spot that was just defused.
3. Finally, all other bots move. Spaces do not have a limit on bot count, so all bots that try to move are guaranteed to move.
Then, after the configurations have been updated, all bots occupying a spot with a mine on it will be eliminated (including those who stayed put and got a mine placed under them), and it will keep iterating.
On each iteration, the number of points increases. When a bot is eliminated, the number of points on the current iteration becomes its score.
During each test run, all `n` bots will be placed on an `n+10` by `n+10` board. On each run, the score for each bot will be recorded. The total score is the sum over `n` test runs. The winner will be constantly updated, so after there are at least 3 submissions or it has passed March 14th (Pi Day), I will accept an answer, but this can change at any time!
# Input/Output Format
## Input
The array given is an `int[][]`. The rightmost four bits (`k & 15`) represent how many mines are adjacent to that square (including corners). The fifth bit from the right (`(k & 16) >> 4`) is `1` if there is a bot there and `0` if there are none. Remember, the board doesn't wrap around.
## Output
By "output" I actually mean what the functions return. Again, your bot's code will have two functions: `int changeMines(int[][])`, and `int[] proceed(int[][])`. Here's a detailed explanation for both of these:
`int changeMines(int[][])` returns a single integer representing what type of move you want to perform next. Namely, return `0` if you want to move your location or idle, `1` if you want to defuse a mine, and `2` if you want to place a mine.
`int[] proceed(int[][])` returns an array of length `1` or `2`, depending on whether or not you want to stay idle. Let's say that the return value of this method is named `int[] i`. Then, `i[0]` represents what type of move you want to make according to the list at the top of the question. `i[1]` represents which on which space you want to perform the action, where applicable. This is not checked when you remain idle because it does not apply. Follow this table:
```
1: top-left
2: top
3: top-right
4: right
5: bottom-right
6: bottom
7: bottom-left
8: left
```
(You can only act within a 3x3 square centered on yourself.)
The game code can be found at my GitHub repo [here](https://github.com/alexander-liao/minesweeper-koth). After downloading the code, it should be a valid eclipse project (run with Eclipse Neon.2). The source code is in `/tree/master/MinesweeperKOTH/src`. Change the source code in `src/game/Game.java` so that `String[] botnames` contains the name of all of the bots. I will be updating this every so often to save you some typing. Bots go in `/src/programmed_bots`, and must extend `bot.MineBot`. Your bot must not throw any exceptions, or it will die with score 0 (no invalid arguments will be given to your bot).
# Rules
* No using reflection of any sort!
* No using `Runtime` to invoke processes on the system!
* No reading the source file of anything using your bot!
* You may read other people's programs, obviously. You may also specifically target a specific AI, but please do so in a respectful manner, also leading to my next point...
* You may not attempt to invoke an instance of another bot and run its AI
* [Standard Loopholes Apply](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
Happy KOTH-ing!
**Note**: This question now exists on the sandbox to get more suggestions.
[Answer]
# TestBot
This submission is to help you determine what a valid submission might look like!
```
import bot.MineBot;
public class TestBot extends MineBot {
public int changeMines(int[][] field) {
return 2;
}
public int[] proceed(int[][] field) {
return new int[] { 2, (int) (Math.random() * 8) };
}
}
```
This bot just does a random-walk, placing mines as it goes. Usually backs onto its own track and commits suicide.
] |
[Question]
[
Playing tetris is fun. Watching an AI play tetris is also fun.
Some tetris AIs will **always** ignore the possibility of maneuvering a piece under an overhang, which makes me sad.
It means that the programmer said to himself, "What are all the possible places the tile could be at the top of the board, and from each place, what happens when I hard drop the tile?"
The **input** of your program will be a game piece, a board, and a newline.
The **output** of your program will be two integers (with a space between them) and a newline.
Your program should generates all possible "moves", distinguishing those "moves" which could be produced by a naive AI (rotation and shifting left/right may only occur at the top), from those "moves" which can only be produced **either** the naive way **or** if rotation and horizontal shifting are allowed below the top.
The **count** of how many "moves" are in each of the two categories (smaller number first), are the two numbers output.
Each "move" is a game board where the tile has a `+` square below it, or where the tile would go off the edge of the grid if it were moved one row downward.
The format of the game piece is a single byte which is one of `s` `z` `l` `j` `o` `i`). The board consists of 180 bytes, each being either space () or a plus (`+`), representing a grid 10 squares wide by 18 tall.
Each piece starts with the top row of its bounding box on the top grid row, and is centered, rounding to the left.
The piece letters represent the same tetrominoes used by what's called [the Super Rotation System](http://tetris.wikia.com/wiki/SRS), and obviously the same rotations.
When maneuvering a piece, it may be shifted left or right, rotated clockwise or counterclockwise, or moved one row down, *except* if doing so will cause part of the piece to go off the edge or top or bottom of the grid, or overlap with any of the `+` marks. There are no wall kicks.
Shortest source code wins.
I suggest (but don't require) that you use some sort of transposition table to avoid infinite loops of repeatedly shifting left/right, or rotating infinitely, etc.
]
|
[Question]
[
**Challenge:**
Create a program that compresses a semi-random string, and another program that decompresses it. The question is indeed quite [similar to this one from 2012](https://codegolf.stackexchange.com/questions/4771/text-compression-and-decompression-nevermore), but the answers will most likely be very different, and I would therefore claim that this is not a duplicate.
The functions should be tested on 3 control strings that are provided at the bottom.
**The following rules are for both programs:**
The input strings can be taken as function argument, or as user input. The compressed string should either be printed or stored in an *accessible* variable. Accessible means that at the end of the program, it can be printed / displayed using `disp(str)`, `echo(str)`, or the equivalent in your language.
If it's not printed automatically, a command that prints the result should be added at the end of the program, but it will not be included in the byte count. It's OK to print more than the result, as long as it's obvious what the result is. So, for instance in MATLAB, simply omitting the `;` at the end is OK.
Compressing a string of maximum length should take no more than 2 minutes on any modern laptop. The same goes with decompression.
The programs may be in different languages if, for some reason, someone wants to do that.
**The strings:**
In order to help you create an algorithm, an explanation of [how the strings are made](https://ideone.com/goPPcV) up follows:
First, a few definitions. All lists and vectors are zero-indexed using brackets `[]`. Parentheses `(n)` are used to construct a string/vector with `n` elements.
```
c(1) = 1 random printable ascii-character (from 32-126, Space - Tilde)
c(n) = n random printable ascii-characters in a string (array of chars ++)
a*c(1) = 1 random printable ascii-character repeated a times
r(1) = 1 random integer
r(n) = n random integers (vector, string, list, whatever...)
c(1) + 2*c(1) + c(3) = 1 random character followed by a random character repeated 2
times followed by 3 random characters
```
The string will be made up as follows:
```
N = 4 // Random integer (4 in the following example)
a = r(N) // N random integers, in this example N = 4
string = a[0]*c(1) + c(a[1]) + a[2]*c(1) + c(a[3])
```
Note: repeated calls to `c(1)` will give different values each time.
As an example:
```
N = 4
a = (5, 3, 7, 4)
string: ttttti(vAAAAAAA=ycf
```
5 times `t` (random character), followed by `i(v` (3 random characters), followed by 7 times `A` (random character) followed by `=ycf` (4 random characters).
For the purpose of this challenge, you may assume that `N > 10` and `N < 50`, every second random number in `A` is larger than `50` and less than `500`, while the other random numbers can be from `1` to `200`. As an example:
```
N = 14
a = (67, 48, 151, 2, 51, 144, 290, 23, 394, 88, 132, 53, 77, 31)
```
The score will be the combined length (bytes) of the two programs, multiplied be the compression rate squared.
The compression rate is the size of the compressed data divided by the size of the original data. The average rate for all three strings is used.
```
score = (Bytes in program 1 + Bytes in program 2)*(Compression rate)^2
```
The winner will be the one with the lowest score two weeks from today.
**Test strings:**
String 1 (5022 chars):
```
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTX_w}yo7}vWL$Y@qNR*Xxqt|oqmwr4+32ejdnaKdEf1<a?<iEKswv)HcNyF/pGc).SPpCF-j$& 1**(NNZ.>Zy0e-`a)i$1Z,X[hcR5JX18wG|`9:H;Qi&nluCKC:b! Q+)i77B28/j/4ZYT1=FN!>DR7'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyeDW,FmJh.%AgO&<CIO|Z>gSmszi/I?nL3P8)se$cbNit%['G<X9VW/)+Xg%$Y}E98\X o;y<Jf8(,8=i`v\e B\7\?<\!Pht(U7FFg\!\L_&bh=G*IJLPLpKGc@ 3j9E%{z^+'3bFmM3q"|c2Gt#ed%-U+y?<bB'/[I]o}bmyE=Y$h!oo/H,9$&^*7Rbzd.L;KGN-Wllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllgk4D:*\(Kt);&^0:RL.KB)IqS79Xj)c8qhf5+S=Up%y0xj%1lA=C<.^F*!UuE2u4wbZ[1#?Q)wz*E;;_5 w\{VUBqH}0(tE& HV(4eZ}S@7xi_s]nzwtP2$8_v`)BDFEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEzgGFo9b8`U':3H<;;K)D'B4:L'}7x;3d]^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*'wt#^or$m_F{@D"`[n?x1Ow3H1bh$5Z@yzRJ4=my&%X+bc6Or/Bw`Zx,VO{Ss10}[fKFLX}Rh9W?_k7)\&j\`Z.BABUy'q8\VP5D_n-f|v3Y$cLe;;7r{5lD@uc?r/c+&O=0{Hr!5&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&9<OIozM4dNlw9N-MUW<kwD/E]XB^1/(?)?C4x)%p,K)p#<cG&PMV"10"&+vN-/oKw9FsubG=*&c'A)a Tu)uZD,S{c|<QO}w+[Pdc=$}3f(!73W?Ko!z:gPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP(!B"n}ydQP W^]2!$,0,ym! cVy4U>hmsNbdU}b-T`n'B^:L#Z}pI5l+46(1LCS>:BAp8+?[ ?}}1mtpo3\[{I]!7T33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333FzE klH&6Cj[VPd: HB\e9FvH_./lxP*Z\LD-,Y``IegX+=1T_:B>VJ{Ikq>'_>k5>rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"EI5K,%OB??_{"fNG>Ql6"jJ4m[S{I_/`P000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000=K#Gc-0ai'N"zDO[roJAJOPPY!%C#+J7"xd0V^teUZX$QW!<\s 3kuuXS'W`F mUvkzr7R ET"(2Y9c}M-a&shkT9j>*x+KDprC'9WFXl(`I{AfsCffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffvKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK#v>boc"..................................................................................................................................................................................................a#,uAOemp[b5CPOzI85g:a[|:]<Ss=`JuIB]+Sg$b'>PJ=%:zM#I$,YM1eX)Ja=P5x^WhuVt1?$ZU5qoM68P?n;T]R-RZ0PMH^pS%W*so-v!=2Z=9J^p,j$4)"'mXvWFF]IQN^MqG:^Lr&V?is6A%N${wNjCXpJE+F^wBG4@c`c^/CU-}8TIYJHu$|KGq=\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\l7G7DK9Nq+'{=>.^a"I<ytX0(HsP'x:I4enw5'^kjQ{ZQta\FL|zOC2C[d4y\z8'z<OgHw3+XZ_nSq@B9m)Yu"|JkOTP*L3T"t\<'sh,y*{0%*NBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBl,OuBGl;X(Yxx._o0Jv8a_]`]j=u6-W^Ve%&meh`]PmR}c>3CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP+GZ-jP@U#$K.}zTy^J(@9"LZ<,Dm}LkKn'>>ZBn:fn?o_o>LT1{2{t0r4$M-GnV;?/M^P-#uzJ=PnBhYo<,uyXNJ#yiZ;R29ta5 >.D0_$\BWWO%3=|#W:c8^VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV%'r`CdgOv(WZ_y2*/sW|$Mmut0CX>Mw+109!Ky$;o`eKqd1D2Kh9x=y8{;(p)xpuIVT+9JS<T>/UIWB< T5$hs|V.$(>$J6j}@\WtWM3\>dvc{O!<(mzw@<xeRkhCIE7L;z7_OFx|nbxfIxu|hhBiN!d"`5;vxnpk3juf;J2})#r!]AFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF<7#0%Uj,b<WrAK?I%kPx![bJBF}RE'j>`f>U]*f%gDY?aa]O3>sL.V\.3#u/%O;xHIl<A4#6zO}umALe*B5P'*`kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkINNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNIv%x1QT@:A`TeVc"AVnFzfPGN%^</a=G=#P/G/oAS^ZPI-8yhu0T8>V5kF80Gh;QU=SC>ymTH{Onh/)[kN+:y .iRj[yK!V HDFW<<fU&zmm2.OY-H^Gf)yH{R%>5DNI]'AX7-kpEJr`+IM-cUn S{co^]ir%J,(P/[q1 h},R",d\Kg%(*HpGDEq`=ubhTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTgeQ_!6|Qj$L77777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777>JV8&V]xq4k#U)5e^8VTJPRzD)HeT6STV:WgqwBbF61R/{_x=diD{<5jKf/Yds7.;Eu}[bYDyA1wRA{-S:1l[%5dHHVOgWMQBy">VO^fJ4yn>oN.,1LEzxT.)>cHk!PbB|$#."Jg^;8}\% D>*8e))=OnSNhRQ
```
String 2 (2299 chars):
```
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV`]e!oO{=i&}\o8^('MDPC`VCI`(@3AFa"A3Dhc<h2Rhc99F^$<LpAOdzC6Y%dTm:!iHH@&&OCV?y)Vv [`wq=?0-YjXSPx1t3k&=>(6^EW?%pH3y6Rb8="2tG%$Jo6A<X^nS4K\v@nZ(Bi1jCW4?p]aIv}<26gXQ%'GKa*<$aPOnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn.$$}.HK{It43ltY"H&:VcTkq+C3.g2VB`Ui-P=8I^%9\TN5=[&@;YOR0`[sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssZz_qnx9wqa'caEfvlp,;c0't70I8'>|W=SHQx\{#ed9)WFM!:l[24.qU,UV^0gARZYW4}n<.6HJdK:{]8,QOO]KbZ'Tugd9{9>X1q.-[adNHmMP*+"<]XIIf>7>Rp/,sQ0QHTO$jduG3O>AV/,GY++$AOBDepNz9qIPzr\G$.NtKLD=j8?8ia*@y34GgmtM%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]"0'-roq!u`Aw/EYlk< R>-AsSmJ3D w}Pp;Rpi`r755VI,Ao(uVA%)v0]WC/XW{-v7k+37y5QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ`9q;^dn#byX+NvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvaY#. xKADce75y7E]`(m'cAg.$N5j{,u!v%Pc(6D?"axU*VQ,n^bWomxD.`LA:I1nvX=^VGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGtOnQL:PKI':C}q.:6|aHiYII*C7{kGa,9aSE8D}h#S%[^:P&e^:kazo,"W]e--\bW=],xD44\@,Z;Q7$RPKA0b6yO_7&h}b/[[email protected]](/cdn-cgi/l/email-protection)}0.-ySF2zWy_3gwpmcqWZZ'Y))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))X']&p]icj|RFj'ci2*1jXg%* Eu&9QZEWwGpen1Pa,Gti_?FUL)&=r<YL-Th"]f%jV<Kx);@L^)mw'g S(nry%kbZp pGD]R@j3{idSHH<!X{%(/T,ow]$259a P-6_AX*o?4g^>(n<v^:/U@cmh9nOG|ot=8Rw5FfvU/'IGD(gm++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++K#&U4RN$dR*rv1p5t`<n7XpvpVz#uncF647sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssYl?CCkw#e?#be5,c0GttH}N j:$5AHa Xz[<z-=CdX)@}fHmk7L-k&hZHOP5o9^yU%%:g|TD1b=7G !HKGMN|}/l:}2Ia^fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff56&4i{38sY*]<DTT#:5>RJm*\c&|kM+K\s^"055%FL5Fl&X|{q+4N6t^(<\gt@;v?z}xly?Bi_!mSA+8r/6n4)Kdh4)P8'|oK&-7tFNO:]mr$nl6L1jr):uC(vh`Ei)19MfumB<VtL]"Vc
```
String 3 (10179 chars):
```
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""":=P,W$WS.vBP9d89L65VeuKY27|*-Ih1x/nY}p09Sq$PQ%4z!l*)@wmbP3b;C3E8#*?2-T`W"0&::+kA:`.OrjmD-u(oDpE:{x0 ttb13yO"q6U:1N@/[R2g}#y}d,7)_STJ^0hb]4]hSd9%L#]Bimmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm+HuOde&d,uX?B??|AJ)h.}D<HouV7NXUP0!.,HmhBaar7(c.)A#%8aPc{g8iE.hw0H)P5B^zQT('wG7Vu(|M>lo.5EM3Z/o&[Pfd}A{Vsi,+lAlam*K}69zlNWJv)|u0<e#+:l![((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((G#zx B)=N\[hRY8Dm`x@SPG=3ZRJ^SkywE:U/[\Z?q[fjY9gxO.]TiH)xKw}%*Tb[JhlD]2D4:(CE:#Zre/}9:z2*G)u)O,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,It)UnqhJ_XIzXNlT%C*Mq%R6KNTg=Q(4G)}=Q2Fp.A>Tuz?y4,wvh%,qQS5gb`6E>^6M]1FV/*4s%LDf%bwEr!oH.G/////////////////////////////////////////////////////////////////////////////////////////////////////JfITfs\Bp{8uJmAE@qW>QT!"R\q\q}2Rwo3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333q Kxp"zbN(am%qRC"bc#]zzD,sr]=H)yMS"0X&_/|yqs!kZ)`MY[C%3j`6$D!(Qk4x."e,m] ;B|S)E{BQT:%eSr0j7Gqx0&u7c7.lT]P?.&&mV2ZT^.k^"0)4K*#E4d!z/$#[-?zi8a(S?iIU9|q?lfy3T"}fh)oWfO5^{sAXu`CB*LStW5(KCe3I]-|oE^>!VL<#Pd$PLDBqZfQ)QPCWja7&7HtM7uM9*..................................................................................................................................................................v/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\sh*_l7Tk`b7KQueol'sWCC,5|\=H>v0I4c\PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP4q.r!#H?yY/-t2:iDRwn,TwSR6 v@lBv\jjO!Kz+1NT>ksfbl=hq)/y1q<}3"kYHLJ&&m'NS'lhqaPYJW3}3Qjh)|ZnAQvb^v=6TIw%Ry{!M,aBIzd9QLhB%cjXOoc*C\S0!(f :NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNv(9%[[email protected]](/cdn-cgi/l/email-protection)&fw@L9edFP3#7tuHlxpCk8]hD.ky{V6bS#?rEz5PERx_"V:\TN {2_"pE/T:X<#&<\V%IQISzo6w5vO%lvPx)|wO!"+>\t-SzP\wWXFQrmXp`JGJ/sIoVyns2u=yU`26&A1]vrpEXHD/K1HjnN4-t";S*****************************************************************************************************************************************************************a&.z "aV6]K"JhyO;/`UOpAkb}zP53=$AD:Io3lkjdUMjw1w!rL2Za3Dk:,`]AsG!L[3e^ECxxqx[I_{|qe)z;zZ#V&HZ:J4g+2U>}y!Oazq`qY_]'n=egXV9*IaFbtRZGVQG!ojmkTkStrbzFnd|7Keu [7$2f7Npb]ne=wuAg\9*4Rd/cqcDApSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS[OTjad;#l+*>m&fFSS{rc|xb?MTV$Z2I>)l8QfAUB"wNHhMNpvaz_TnvM:2Ck>*2=jWS2)a/$dP\,"pB9#L^1lSir+m%oG@YA/G#M3T10gF+xdJDqe"8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888":6Y<zLVYm@aQ-.\-u\M_.7<}L`(w!+7lm@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<aJHBA#?>9cSxN5HZ:$Z{Kr15x>cZ?!NACujxBVAu;->*BxS)wu dA:2#Sq:FaGgr5,mKLv&_ms"s1:NXEVVX)`y#ekL4H$;%{xrU$ai&9J5C8eqyQE(E|;+3tf^csoENQJG#}X81VE2m1xY 2SI d[*Eozzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz7/+M6f *n*GBp_/+rpBX@]%OpIgfkF":Cc"xzIGYw5H{LVBWFKg\1j{S duWiWB[-%'z7)NGE)QR >"t4#N1{(EntG)$u^o/J(*IaBAB<D\iE?gWj)ccWk-[OToXKjQZTWIji%^] ,Z#:_5Rsk e`s-bxrLW|(,c!>mmin\w5lcLO`````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````+b"0@z2a@N^IO}K{uefxE%pgz'!7GoJ2mLaOZh3#I$tSEZ/=x9S6]Y0[5T@qRftKeXuBFr_ \)-?-2">0r*=MB'hhf4x"%g8Y\[kmPx><6ejGL; s:yp@5af+rg=/`W(xm,{OKLzj dY/3PC)Ea]LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLcqGx?cJ"y,>w5jkIbja_qUNv#-r_G 86[090^^F@x|4(8@dWy`"MnL5<+Mf{[[email protected]](/cdn-cgi/l/email-protection)`G$gNJbCddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd:>WH*?#n+7oFZQ\gLEzvR8LS6u&0^pR[;n`x&D9m"YFf````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````G=Z^o74rpXU<`',;JPl|}/>8f<ir3M6;&O)Y4rV5T2^+AJ>QvlE([bozzb,ifw=BG7+P((lS$g{c!N*&_K<);rx,2&9@7QJi6Q*(.qFQys>EB['1a4(`?htRwJ"a+<j6*>.Lm}F)`:M3;=^n+Bp&\HZI[sv1FGI93\6VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV O}h4W!dP?}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}Z'lC(E *d#-Ub?y". r:D{n--gCk&=IpmT{\I-;2vQ18xtU'2u1<qAN<IF!YEwx)ZKvY_)D%CU;l1bC%$>u|W.(2=dC!{_e?bc32]DYC?m}<{vdZKnZ <.VhO?EYwINo7lS36Ir1p4Q%cG*7RX#)iVIu..............................................................................NuF1uxKoCH5[cn,,7uj "6aoUK_7hV|lb;u8Piim!{f4 dASS'mtQ&L_-jZ=a?=YwO%Q?y240o".T*]k",5]S*f(P?Rp?T1=V7[^T=w8_h>(:O%f?iZuaJ=3d`f[dI;8S@'Gz]zn%{_OAw7&T%-44444444444444444444444444444444444444444444444444444444444444444444uSz;a(-U)o.xYDgr0,Kyo+jsMrB^oQJ=V}U`nEB>Eqo}S]sUil-sAurUOxxU.+S#f.lvO>Q_SN71{(3"eXt.%$z2Y%Gk8WFTCBz;\`2-eis.*pQ"q^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^vbAbVM q5#3gqC[FPb%7[jHR(o!jK[B)-!FD+.6Pu-(-ccyOsQPKug;]M8R5c'IK>O4EuxI8nr#Ab\EXRK+fP'KHb@-J=51g?/?<H\-BWq1s-Rb:5TuB5kb;eG3Sp/]h5Y{E+T\#i\.&+Q#%*G&O1o-sRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR'%*P|wj/I!ThsIYvh&#$W3\.]4[RTuwFOF#8y+TA7%B@u1T)l!:VFW;i.-{w6Gebq3JaMn7X9cwj3eg8Kf!HaME[<f2*w',ji0t0sDj>n+,=WN *k#[a3XKg!"0Mg$`vP\Fvjup*@8TV@ly{k{4Z2[@a:N)SWQ?Lxxv}dJ?WUmFYPBcG>Z;r_[6Kw$n2\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'ja3@b''Ol'{i3K`wB5(kIOVg9'/R`I6=la;cV=ajQbf1+o3J&B{>(hUQE+g.YMv#q3&i5s/2mB|U^h2.A3U;(rxB{6DQb)`_/Sx/:!URO&49eSAm'B\GP8)9RdPO9FrqGI\^1j*'7Rgfpi&zgX52GU%%h<)h1)KG/Uu:un{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{W02fvj%BMP=H:dSNif}w[lZ@gF,O]w3O R"+g3G[7i*8y,n>1]u 5G!)nulS^S064#?y=/E1_QBDM`i`M5kzH0au24xQNB^u4;4ipll}IP1%V3yEC+2Oq83Y$iezSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSqQd$I49 o;w_%&90L/ckdHY8TeRWLFZNvi3aGwN3&HRuU$Vgt9(_R\FmT9}Aj#VQp"oUoXW=s*vS6SKP ]x<[IA2M2I`2Vy=a3&Jc,n:}qTboygX6pp,L?\ff{zE#9D-?-jgPrKwd6V{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{jB8OKx6j]=oPzb;pL(<A8`%g7+<O6*)W1m8(SiC+4n(775\g8$[?I\`Cffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)/.%\4TZ1%Eq!chTOC|#Tbx(m}"@u>Bw&L*hz=Px4?yM}`4s>uGL,[[email protected]](/cdn-cgi/l/email-protection)/h:Qr7r*t:6>#q 6O+doZQvl#kr:]VM `z%(&<`yhME|B;2Tjm$^N^,0\h)rVEVT\rp@T>>0U:KoFAsZ'_rZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZaI}`I/T;Qk/dyY_96VxX6=EGn%{'uzDF}.k!\}O^NG1p7PI<_C'/3%d70'@;\6n)wydLj}bZfWP9 zei[;J:^;BRwKcBFdFld3IRrRY9oBJ<#ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ/e{hh'&wP3jknjfma}v:*__SLUIg\@*_`m:fcbfj((6:1)..?,Xx6<%bi.9Z>)xC`Jbwv#mo_[O0z8>@Exm^>b.&2)[Eyg\Y{UZA9:+SuwhG(<w***********************************************************************************************************************************************************************s4NBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBJ_ h\ xgC46py]Wh'|,LnG2dgl1\*ZG2HWA0Z%26_zB(Y{:;2zxS?>5NJrX8j^*9bt$UQ\PD95El;e'EU6K.[:a&zn]$]`g^Wl;Q(o9oWI3HwTj}NR_:OAdJ@!M8#twm6+tN!*%ldWyOZpnGBeOyz\CiH9w>FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFVRA"MafX,*ZvJvhH{]BrDX">v}pMz2ze.q#$U1c_ XA207Zof^cE,(R`LgHdYY&etOFaShx`F])18.O#\go/-Q#!%6%O0)W`v$fX)7VSTUYau9TC|%a_'bI&i1i7Z3,om_'9(2m-ihn jCh5VrJPD9gm@EoAP*[.!5e{5BJ_>_ut^Hu\:^kJS0IOn+ 555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555gp_;VbIVS>7)S?V.!Qgx7T/Ik33tV.M>/[l/8HiS1L1tX<P_2,rR(R&+-#^rl=b8GgJP^y:!/`+-:_sWyzD56jqu0/N-)].j`*q9$csBoIl CyC]3j+^DT-Ra|LN*TesCL*-Z;OdO^m#{rp8rAaFB.N-''n:\p?O5bPgT{eD9^3[S7&E,n%/VFiz>K(VXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXEFm-T"2Ny{`4Jt7kv2fTpcsn=U.XCpppppppppppppppppppppppppppppppppppppppppppppppppppHr5aL@FX.UBLt$Um68vRs;Fw)Ymm>=^;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++JczE.=iK'CWH`]_Xf3G*Nb*ExFAKl;|ssZsBC 2s4jz=GR9y>`X8(M;2/BI3h75[[Yfr]txi5}i{np "p}H*.&3o(e>6I)`/;]`[7Oq{=Y4_2jUl}M)jWn&aX&h'dOUrZ),5>Rr2J<UF&{.vJNB?v{Hyp8sK`\J+;%_WTm__________________________________________________________________________________________________________________________3|+lq,Eb6.3HKu}g;La3'x$%?4tgQhIsR'9 c@i<5(LW'$[)YBE rA}BcWFWswnk_h(Z_ a`tQ)IorJ(!>0=c)/-t.n8rL|Php0!tjtI^r=GMN)GU4k?E oQc4|x#y;AU2hW
```
Note that the strings can be much longer than this, but there's a character limit (30000) on posts, so I had to restrict it. The functions should work for codes up to the maximum size.
[Answer]
# CJam, 40 bytes + 13 bytes, rate 0.48697, score 12.5682
Just a baseline solution which compresses the long runs.
Compression ([Test it here](http://cjam.aditsu.net/#code=qe%60%7B(S*%5C_%7B0%3DK%3E%7D%23)_%7B(%2F(e~%5CL*%7D%3AF%26N%5C%7Dh%3B%3B_%2CF%0A%0A%5Ds_%2CpNo) with length calculation):
```
qe`{(S*\_{0=K>}#)_{(/(e~\L*}:F&N\}h;;_,F
```
Decompression ([Test it here](http://cjam.aditsu.net/#code=r%7B~l1%3E(%40*%5Cr%7Dh)):
```
r{~l1>(@*\r}h
```
The lengths of the three test strings compressed are 2296, 1208 and 4917 respectively. This score could probably be vastly improved by making use of base encoding.
[Answer]
# Awk, 74.9 = (199 + 115) \* 0.48853^2
The compression replaces the characters repeated over 4 times, by character & total, enclosed by tabs. For example: `&&&&&` becomes `\t&5\t`. While `dddd` remains `dddd`.
The decompression script uses the tabs as the record separator and restores the repeated characters.
### Compression
```
{split($0,s,"");for(i=1;i<=length($0);i++){c=s[i];f=s[i+1];if(c==p||c==f){n++}else{printf("%s",c)}if(n>1&&c!=s[i+1]){if(n>4){printf("\t%s%d\t",c,n)}else{for(j=0;j<n;j++){printf("%s",c)}};n=0}p=s[i]}}
```
### Decompression
```
BEGIN{RS="\t"}{if($0~/^.[0-9]+$/){for(i=0;i<int(substr($0,2));i++)printf("%s",substr($0,1,1))}else printf("%s",$0)}
```
(note that this script would be more efficient if the substring calculations are first put in variables. But codegolfing often trades efficiency for bytes.)
### Test
```
$ for s in string1 string2 string3; do cat $s.txt|awk -f compress.awk >$s.compressed.txt; done
$ for s in string1 string2 string3; do cat $s.compressed.txt |awk -f uncompress.awk >$s.uncompressed.txt; done
$ wc -c string[1-3].txt string[1-3].uncompressed.txt string[1-3].compressed.txt
5022 string1.txt
2299 string2.txt
10179 string3.txt
5022 string1.uncompressed.txt
2299 string2.uncompressed.txt
10179 string3.uncompressed.txt
2296 string1.compressed.txt
1208 string2.compressed.txt
4916 string3.compressed.txt
43420 totaal
$ md5sum string[1-3].[ut]*xt
ea7076dd2f24545e2b1d1a680b33e054 *string1.txt
ea7076dd2f24545e2b1d1a680b33e054 *string1.uncompressed.txt
dd69a92cb06fa5e1d49b371efb425e12 *string2.txt
dd69a92cb06fa5e1d49b371efb425e12 *string2.uncompressed.txt
9e6eaf10867da7d0a8d220d429cc579c *string3.txt
9e6eaf10867da7d0a8d220d429cc579c *string3.uncompressed.txt
```
[Answer]
# Perl, 113 bytes + 80 bytes, rate 0.497325, score 47.735
This is my first golf ever, and a first draft. For now all it does is count the length of repeated sequences and replace the repetitions with an integer representing the number of repetitions. E.g. "aaaaa" → "a{{5}}"
Compression:
```
$d=<>;push@d,$1while$d=~/((.)\2*)/g;map{$l=length;($o)=/(.)*/;$_="$o\{\{$l\}\}"if$l>4;}@d;print length(join'',@d);
```
Decompression:
```
map{($o)=/^(.)/;$_="$o"x$lif($l)=/\{\{([0-9]+)\}\}/;}@d;print length(join'',@d);
```
Double curlies ({{ }}) are probably redundant, but I want to be on the safe side.
Compressed lengths are 2340, 1230 and 4998 respectively.
[Answer]
# [Mathematica](https://www.wolfram.com/language/), 9 bytes + 11 bytes, rate: 0.565899. Score: 6.40483
Mathematica, of course, has builtins for this. This makes this answer a bit of a cheat, but I thought I should include it anyway.
```
Compress@
```
and
```
Uncompress@
```
[Answer]
# PowerShell 5 (invalid), 37 bytes + 35 bytes, rate 0.43121, score 13.3878
This entry is currently invalid and theoretical only, as I don't have access to a machine equipped with PowerShell 5 to verify, and/or I'm not sure if this counts as "using an external source." More of a theoretical "what-if" scenario than actual submission.
.
Compression (the `Get-Content` displays the results and doesn't add to the byte count)
```
$args|sc .\t;compress-archive .\t .\c
Get-Content .\c -Raw
```
Gets command-line input, uses `Set-Content` to store that as a file `.\t`, then uses `Compress-Archive` to zip it to .\c
Decompression (again `Get-Content` doesn't count)
```
$args|sc .\c;expand-archive .\c .\t
Get-Content .\t -Raw
```
PowerShell 5, introduced with Windows 10, includes a [new feature](https://devblogs.microsoft.com/scripting/new-feature-in-powershell-5-compress-files/) that lets you use the built-in-to-Windows zip/unzip functionality. Previously, you would need to create a new shell and explicitly execute a zip.exe command with appropriate command-line arguments - yuck. Now, it's just a simple command away.
Note that this is likely *also* not valid if you're expecting to copy-paste the string output from the compression algorithm into the decompression algorithm, as the PowerShell console [doesn't handle non-ASCII characters very well ...](https://devblogs.microsoft.com/powershell/outputencoding-to-the-rescue/) Piping from one to the other should work OK, though.
] |
[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/99248/edit).
Closed 7 years ago.
[Improve this question](/posts/99248/edit)
# Solve a Tron Game
Tron is a great game, and if you haven't played it the internet has MANY online versions available.
A fun challenge is to try to write an AI that plays Tron, which is normally much better than any human, thanks to their frame perfect dodging.
Even with their perfect dodging of walls, they still get themselves trapped easily.
Your task, is to write a script that when fed a map containing a single tron bike, that may already be partially filled, and output the actions required to fill it as much as possible.
## The Task
From the letter p in the input, find the best moves to fill the most space in the maze, in as few iterations as possible, then output as a string of r(ight)u(p)l(eft)d(own), describing that path.
If you attempt to move into wall, your run is ended.
if you attempt to move where you have already been, your run is ended.
if your run contains an unexpected character, it is ended at that character.
Filling space refers to passing over it in your run. Your starting position is counted.
## Input / Output
Your input will be through any valid method,
A maze, consisting of the characters `# p` (Pounds (0x23), Literal space (0x20) and the letter p lowercase (0x70))
one of the following forms
* A single multiline string
* An array of strings, split by lines
* An array of arrays, each containing a single character
You must output exactly
* A string or array of strings containing only the characters `rlud` case sensitive, describing your path through the maze.
You may use any reasonable permutation of these input and output format as well, such as bytes instead of characters.
## Test Cases
### Straight Forward.
Input:
```
#######
#p #
#######
```
Example Output: `rrrr`
### A Turn.
Input:
```
#######
#p #
##### #
# #
###
```
Example Output: `rrrrdd`
### Box Filling.
Input:
```
#######
#p #
# #
# #
#######
```
Example Output: `rrrrdlllldrrrr`
### Complicated
Input:
```
#######
#p #
# #
# #
##### #
###
```
### Unfillable
Input:
```
########
#p #
# ##
###### #
# #
## #
#######
```
## Scoring
Your score is a combination of how fast your code runs and how many squares you fill of all the test cases.
Score is `Total successful moves across Test Cases` `/` `Algorithmic Complexity Across Test Cases`
So if your Algorithm has a complexity of `O(a*b) Where 'a' is Maze Width and 'b' is Maze Height`, then your Algorithm Complexity Total is `(TestCase1Width * TestCase1Height) + (TestCase2Width * TestCase2Height)...`
[See More on Big O Notation](https://en.wikipedia.org/wiki/Big_O_notation)
Highest score Wins!
## Notes
* The input will always be an enclosed surrounding the p
* There will always be atleast 1 space to move from the start
* The area may not always be possible to fill completely.
* Your code should still work competitively on a random valid input. That is, do not cater just to the test cases.
* Standard Loopholes Apply
* this is a [fastest-algorithm](/questions/tagged/fastest-algorithm "show questions tagged 'fastest-algorithm'") mutation, where both speed and space filled matters, not code length. Go ham.
* I'm particularly interested in a Java solution.
* Have fun!
## Solution tester
```
var storedMap = "";
function restoreMap(){
document.getElementById("maze").value = storedMap;
}
function trymaze(){
var score = "";
var maze = document.getElementById("maze");
storedMap = maze.value;
var commands = document.getElementById("methodin");
var converts = {r:{r:"─",u:"┌",d:"└",l:"─"},u:{r:"┘",u:"│",d:"│",l:"└"},d:{r:"┐",u:"│",d:"│",l:"┌"},l:{r:"─",u:"┐",d:"┘",l:"─"}}
var dirs={l:{x:-1,y:0},u:{x:0,y:-1},r:{x:1,y:0},d:{x:0,y:1}};
var last = "";
var boxes = commands.value.replace(/./g, function(c){
if(last==""){
last = c;
return {r:"╶",u:"╵",d:"╷",l:"╴"}[c];
}
var s = converts[c][last];
last = c;
return s;
})
var mMaze = maze.value.replace("p"," ").split("\n");
var pp = maze.value.indexOf("p")
var y = (maze.value.substring(1,pp).match(/\n/g)||[]).length;
var x = ((maze.value.match(/.*p/)||[""])[0].length)-1;
var path = commands.value.split("");
for(s in path){
tx = x + dirs[path[s]].x;
ty = y + dirs[path[s]].y;
mMaze[y] = mMaze[y].replaceAt(x, boxes[s]);
if(!mMaze[ty]){
alert("NO MAZE SEGMENT "+ty);
break;
}
if(mMaze[ty].substring(tx,tx+1)!=" "){
alert("HIT A WALL: "+tx+" "+ty+" \""+mMaze[ty].substring(tx,tx+1)+"\"")
break;
}
score++;
x=tx;
y=ty;
mMaze[y] = mMaze[y].replaceAt(x, "O");
}
if(document.getElementById("score").value){
document.getElementById("score").value = document.getElementById("score").value + ", " + score;
}else{
document.getElementById("score").value = score;
}
maze.value = mMaze.join("\n");
}
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
```
```
*{
font-family: monospace;
}
textarea{
width:30em;
height:15em;
}
```
```
<textarea id = "maze"></textarea>
<form>
<input type="text" id="methodin"></input>
<input type="button" onclick="trymaze()" value="Try Maze"></input>
<input type="button" onclick="restoreMap()" value="Reset Maze"></input><br/>
<input type="text" id="score"></input>
</form>
```
]
|
[Question]
[
INPUT: Any string consisting exclusively of lowercase letters via function argument, command line argument, STDIN, or similar.
OUTPUT: Print or return a number that will represent the sum of the distances of the letters according to the following metric:
You take the first and second letter and count the distance between them. The distance is defined by the QWERTY keyboard layout, where every adjacent letter in the same row has distance 1 and every adjacent letter in the same column has distance 2. To measure the distance between letters that aren't adjacent, you take the shortest path between the two.
Examples:
```
q->w is 1 distance apart
q->e is 2 distance
q->a is 2 distance
q->s is 3 distance (q->a->s or q->w->s)
q->m is 10 distance
```
Then you take the second and third letter, then the third and fourth, etc., until you reach the end of the input. The output is the sum of all those distances.
Example input and output:
```
INPUT: qwer
OUTPUT: 3
INPUT: qsx
OUTPUT: 5
INPUT: qmq
OUTPUT: 20
INPUT: tttt
OUTPUT: 0
```
Here is an image showing which letters are in the same column:

This is code golf, so the shortest code in bytes wins!
[Answer]
# Python 2, ~~220~~ ... ~~124~~ 119 Bytes
*Huge thanks to Sp3000 for saving a **lot** of bytes.*
```
f='qwertyuiopasdfghjkl zxcvbnm'.find
g=lambda i:sum(abs(f(x)%10-f(y)%10)+2*abs(f(x)/10-f(y)/10)for x,y in zip(i,i[1:]))
```
Usage:
```
g("tttt") -> 0
```
[Check it out here.](http://ideone.com/5i7yCy)
Slightly ungolfed + explanation:
```
f='qwertyuiopasdfghjkl zxcvbnm'.find # Defining keyboard rows and aliasing find
g=lambda i: # Defining a function g which takes variable i
sum( # Sum of
abs(f(x)%10-f(y)%10) # horizontal distance, and
+ 2*abs(f(x)/10-f(y)/10) # vertical distance,
for x,y in zip(i,i[1:])) # for each pair in the zipped list
# Example of zipping for those unaware:
# Let i = asksis, therefore i[1:] = sksis, and zip would make
# the list of pairs [(a,s),(s,k),(k,s),(s,i),(i,s)].
```
[Answer]
# Java, 266 bytes
```
int c(String q){String[]r={"qwertyuiop","asdfghjkl","zxcvbnm"};int v=0,l=q.length();int[][]p=new int[l][2];for(int i=0;i<l;i++){while(p[i][0]<1)p[i][0]=r[p[i][1]++].indexOf(q.charAt(i))+1;v+=i<1?0:Math.abs(p[i][0]-p[i-1][0])+2*Math.abs(p[i][1]-p[i-1][1]);}return v;}
```
Ungolfed version:
```
int c(String q) {
String[] r = {
"qwertyuiop",
"asdfghjkl",
"zxcvbnm"
};
int v = 0, l = q.length(); // v=return value, l = a shorter way to refer to input length
int[][] p = new int[l][2]; // an array containing two values for each
// letter in the input: first its position
// within the row, then its row number (both
// 1 indexed for golfy reasons)
for(int i = 0; i<l; i++) { // loops through each letter of the input
while (p[i][0] < 1) // this loop populates both values of p[i]
p[i][0] = r[p[i][1]++].indexOf(q.charAt(i))+1;
v += (i<1) ? 0 : Math.abs(p[i][0]-p[i-1][0])+2*Math.abs(p[i][1]-p[i-1][1]); // adds onto return value
}
return v;
}
```
[Answer]
# SWI-prolog, 162 bytes
```
a(A):-a(A,0).
a([A,B|C],T):-Z=`qwertyuiopasdfghjkl0zxcvbnm`,nth0(X,Z,A),nth0(Y,Z,B),R is T+(2*abs(Y//10-X//10)+abs(Y mod 10-X mod 10)),(C=[],print(R);a([B|C],R)).
```
Example: `a(`qmq`)` outputs `20` (And `true` after it but there's nothing I can do about that).
**Edit:** had to use 3 more bytes. My original program passed the test cases given but was actually incorrect (absolute values were misplaced/missing)
Note: if you want to use it on say [Ideone](https://ideone.com/), you have to replace all backquotes ``` to double quotes `"`. Backquotes in my case (which is the current standard in SWI-Prolog) represent codes list for strings, and double-quotes character strings, but this is different in older versions of SWI-Prolog.
[Answer]
# CJam, 50 bytes
```
r{i",ÙZ°^ªýx´|"257b27b=A+Ab}%2ew::.-::z2fb:+
```
Note that the code contains unprintable characters.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r%7Bi%22%06%C2%99%2C%08%C3%99Z%C2%B0%C2%9C%5E%18%C2%AA%C3%BD%C2%93x%C2%B4%7C%22257b27b%3DA%2BAb%7D%252ew%3A%3A.-%3A%3Az2fb%3A%2B&input=qsx). If the permalink doesn't work, copy the code from this [paste](http://pastebin.com/HSpWaL2T).
### Background
We start assigning positions **0** to **9** to the letters on the top row, **10** to **18** to the letters on the home row and **20** to **26** to the letters on the bottom row.
The positions of all 26 letters, in alphabetical order, are
```
[10 24 22 12 2 13 14 15 7 16 17 18 26 25 8 9 0 3 11 4 6 23 1 21 5 20]
```
This is an array of length 26. Since arrays wrap around in CJam, and the code point of the letter **h** is **104 = 4 × 26**, we rotate the array 7 units to the left, so that each letter's position can be accessed by its code point.
```
[15 7 16 17 18 26 25 8 9 0 3 11 4 6 23 1 21 5 20 10 24 22 12 2 13 14]
```
Now we encode this array by considering its elements digits of a base 27 number and convert the resulting integer to base 257.
```
[6 153 44 8 217 90 176 156 94 24 170 253 147 120 180 124]
```
By replacing each integers by the corresponding Unicode character, we obtain the string from the source code.
### How it works
```
r e# Read a whitespace separated token from STDIN.
{ e# For each character:
i e# Push its code point.
",ÙZ°^ªýx´|" e# Push that string.
257b27b e# Convert from base 257 to base 27.
A+Ab e# Add 10 and convert to base 10.
e# Examples: 7 -> [1 7], 24 -> [3 4]
}% e#
2ew e# Push all overlapping slices of length 2.
::.- e# Subtract the corresponding components of the pairs in each slice.
::z e# Apply absolute value to the results.
2fb e# Convert each to integer (base 2).
e# Example: [2 5] -> 2 × 2 + 5 = 9
:+ e# Add the distances.
```
] |
[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/57789/edit).
Closed 8 years ago.
[Improve this question](/posts/57789/edit)
Every 3 seconds, add a room to the house.
A house with one room looks like this:
```
|---|
|[=]|
|---|
```
Two rooms:
```
|---||---|
|[=]||[=]|
|---||---|
```
Three rooms:
```
|---|
|[=]|
|---|
|---||---|
|[=]||[=]|
|---||---|
```
Four rooms:
```
|---||---|
|[=]||[=]|
|---||---|
|---||---|
|[=]||[=]|
|---||---|
```
Five rooms:
```
|---||---|
|[=]||[=]|
|---||---|
|---||---||---|
|[=]||[=]||[=]|
|---||---||---|
```
* The rooms have to form a square, or as close as you can get, as shown above.
* You must use stdout or the equivalent
Smallest number of bytes wins.
]
|
[Question]
[
[Wireworld](http://en.wikipedia.org/wiki/Wireworld) is a cellular automaton that was designed to be resemble electrons flowing through wires. Its simple mechanics allow the construction of digital circuits. It has even permitted the construction of an [entire computer](http://www.quinapalus.com/wi-index.html).
Your mission is to create the shortest Wireworld implementation in your language of choice.
Each cell in the grid has one out of four states. The four states are "blank," "copper," "electron head," or "electron tail."
* A blank cell will always remain a blank cell
* An electron head will always become an electron tail
* An electron tail will always become copper
* A copper cell will become an electron head iff exactly one or two out of its eight neighbors are electron heads, otherwise it will remain copper
This competition will have a similar style to the [Shortest Game of Life](https://codegolf.stackexchange.com/questions/3434/shortest-game-of-life) competition, but with a few changes.
* The grid must be at least 40 by 40 cells
* The edges of the grid must NOT wrap around (not a torus). Treat cells outside of the field as being constantly "blank."
* It must be possible for the users to enter their own starting configuration.
* Staring at blank screens is not fun. The program must visually display the simulation as it is running.
This is code golf, fewest bytes wins.
[Answer]
## APL, Dyalog (131)
```
{h t c←1↓⍵∘=¨F←' htc'⋄⎕SM∘←1 1,⍨⊂N←F[1+⊃+/H h(t∨c≠H←c∧S↑1 1↓1 2∊⍨⊃+/+/K∘.⊖(K←2-⍳3)∘.⌽⊂¯1⌽¯1⊖h↑⍨2+S←25 79)ר⍳3]⋄∇N⊣⎕DL÷4}↑{79↑⍞}¨⍳25
```
The output is displayed in the `⎕SM` window. The simulation runs endlessly. The grid is 79x25 because that's the default size of the `⎕SM` window. The electron head is `h`, tail is `t`, copper is `c`. The program reads the starting configuration from the keyboard as 25 lines.
Explanation:
* `↑{79↑⍞}¨⍳25`: read the 79x25 grid
* `h t c←1↓⍵∘=¨F←' htc'`: get three matrices, one with the heads, one with the tails and one with the copper. Also set F to the string `' htc'`.
* `⎕SM∘←1 1,⍨⊂N←F[1+⊃+/`...`ר⍳3]`: The "..." part is a vector of length three, where the elements are matrices showing the new heads, tails, and copper respectively. The heads are multiplied by 1, the tails by 2, and the copper by 3, then we sum these matrices together and add one, giving a matrix of indices into `F`. `N` becomes the new state, in the same format as the input, and it is shown on the `⎕SM` screen starting from the top-left corner.
* `¯1⌽¯1⊖h↑⍨2+S←25 79`: Add a border of blanks to `h` by growing it by two rows and columns, then rotating it one right and one down.
* `⊃+/+/K∘.⊖(K←2-⍳3)∘.⌽⊂`: Rotate the matrix in all eight directions and then sum the resulting matrices together, giving the amount of neighbours that are heads on each position.
* `1 2∊⍨`: Set only those positions to 1 which have 1 or 2 neighbours.
* `S↑1 1↓`: Remove the border we added earlier.
* `H←c∧`: The new heads are all those copper cells that have 1 or 2 head neighbours.
* `t∨c≠H`: The new copper cells are all old tails, and all old copper cells that have not become heads.
* `H h(`...`)`: The new heads are `H` as calculated above, the new tails are the old heads, and the new copper cells are as calculated above.
* `∇N⊣⎕DL÷4`: Wait 1/4th of a second, then run the function again on `N`.
[Answer]
## ALPACA, 82 chars
ALPACA is a language specifically designed for cellular automatons.
o is nothing; c is conductor; e is electron; t is electron tail.
```
state o " ";
state c "c" to e when 1 e or 2 e;
state e "e" to t;
state t "t" to c.
```
[Answer]
## GolfScript (125 120 105 100 chars)
```
n%{.,,{1${.0=,:w[1,*]\+2*>3<}:^~`{zip^''+.4=5%'`X '@{+}*(7&1>'iX'>+=}+w,%}%"\033[H\033[J"@n*+puts 6.?.?}do
```
Note that I'm counting the `\033` as one character each, because they can be replaced by a literal `ESC` character. This uses ANSI control codes, so relies on a compatible tty. Also note that frames are printed starting with the input grid.
There is some overlap with [Generate a grid of sums](https://codegolf.stackexchange.com/q/12430/194), which also uses the Moore neighbourhood.
Encoding: blank space => ; electron head => `i`; electron tail => ```; copper => `X`.
The pause between iterations is the time required to calculate 4665646656. Changing `6.?.?` to another expression allows you to control the speed; the next slowest for the same character count is `7.?.?`, which is *much* slower (the output is 22 times as big, and it's not a linear complexity calculation).
For a test case, I've been using
```
`iXXXXXXXXX
X X
XXX
X X
i`XX XXXXXX
```
from the Rosetta Code [Wireworld](http://rosettacode.org/wiki/Wireworld) challenge.
[Answer]
# Python 371 341 chars
Yeah, it's not that short, but it has an interactive gui!
```
import matplotlib.pylab as l,scipy.ndimage as i
r=round
w=l.zeros((40,40),int)-1
p=l.matshow(w,vmax=2)
c=p.figure.canvas
def h(e):
try:w[r(e.ydata),r(e.xdata)]=[0,2,-1][e.button-1]
except:x=i.convolve(w==2,l.ones((3,3)),int,'constant');w[:]=w/2+((w==0)&(x>0)&(x<3))*2
p.set_data(w);c.draw()
c.mpl_connect('button_press_event',h)
l.show()
```
Instructions:
Click with left mouse button to place wire
Click with right mouse button to clear
Click with middle mouse button to place electron head
Click outside the axes to step the automaton
[Answer]
## Python (~~243~~ 214)
Tried to make a cross between usability and characters. The grid is 40x40. Input is given on stdin. An electron head is `h`, electron tail is `t`, copper is `c`, anything else is blank.
```
import os
f=raw_input()
while 1:f=''.join('h'if(i=='c')&(0<sum(1 for i in[-1,1,-39,-40,-41,39,40,41]if f[e+i:e+i+1]=='h')<3)else't'if i=='h'else'c'if i=='t'else f[e]for e,i in enumerate(f));os.system('cls');print f
```
The while loop (line 3) uncompressed (will not work if placed in code):
```
while 1:
for e,i in enumerate(f):
if(i=='c')&(0<sum(1 for i in[-1,1,-39,-40,-41,39,40,41]if f[e+i:e+i+1]=='h')<3):f[e]='h'
elif i=='h':f[e]='t'
elif i=='t':f[e]='c'
else:f[e]=f[e] #redundant, but Python needs this to run
os.system('cls') #cls is shorter than clear, so I used that
print f
```
[Answer]
# C, 355 347 300 294 chars
Edit: realized I don't need `feof()`
Edit: Saved 47 chars! Removed the Sleep, got rid of almost all braces, combined a lot of operations.
Edit: Last one today, since I broke 300 chars. Changed `printf` to `puts`, found a cute little optimization with the first comparison.
C does not lend itself well to this sort of problem, but hey, golfing it is fun. This is a pretty brute-force implementation, but I wanted to see how far I could golf it up.
Input is a text file named `i`. It contains a representation of the starting state, with `*` for copper, `+` for electron head, `-` for electron tail, spaces for empty cells. I'm using the XOR gate from the wiki page for testing.
```
****-+**
+ ******
-******* *
****
* *****
****
******** *
+ ******
-****+-*
```
---
```
char*p,t[42][42],s[42][42];
main(i,r,c,n,j)
{
for(p=fopen("i","r");fgets(s[i++]+1,40,p););
for(;;getch(),memcpy(s,t,1764))
for(j=1;j<41;puts(s[j++]+1))
for(i=1;i<41;)
{
p=t[j]+i;
r=s[j][i++];
*p=r==43?45:r;
if(r==45)
*p=42;
if(r==42)
for(r=-1,n=0;r<2;++r,*p=n&&n<3?43:42)
for(c=-2;c<1;)
n+=s[j+r][i+c++]==43;
}
}
```
[Answer]
## Python, 234 218 chars
```
import time
I=input
C=I()
H=I()
T=I()
R=range(40)
while 1:
for y in R:print''.join(' CHT'[(C+H+2*T).count(x+y*1j)]for x in R)
H,T=[c for c in C if 0<sum(1 for h in H if abs(c-h)<2)<3and c not in H+T],H;time.sleep(.1)
```
You input the board as three list of complex numbers representing the coordinates of the cells of copper (which must include the heads and tails lists), heads, and tails. Here's an example:
```
[3+2j+x for x in range(8)] + [3+4j+x for x in range(8)] + [11+3j+x for x in range(6)] + [2+3j]
[3+2j]
[2+3j]
```
Note that we `eval` the input, so you can use arbitrarily complex expressions for lists of complex numbers.
[Answer]
## QBasic, 309 bytes
**Warning:** the golfed version is not user-friendly: it has a weird input method, runs as an infinite loop, and doesn't have any delay (thus, runs too fast on some systems). Only run it if you know how to terminate a program in your QBasic environment. The ungolfed version is recommended (see below).
```
INPUT w,h
SCREEN 9
FOR y=1TO h
FOR x=1TO w
PSET(x,y),VAL(INPUT$(1))
NEXT
NEXT
DO
FOR y=1TO h
FOR x=1TO w
SCREEN,,0
c=POINT(x,y)
d=c
IF c=7THEN d=1
IF c=1THEN d=6
IF c=6THEN
n=0
FOR v=y-1TO y+1
FOR u=x-1TO x+1
n=n-(POINT(u,v)=7)
NEXT
NEXT
d=7+(n=0OR n>2)
END IF
SCREEN,,1,0
PSET(x,y),d
NEXT
NEXT
PCOPY 1,0
LOOP
```
To run, specify at the input prompt your configuration's width `w` and height `h`.1 Then type `w*h` single-digit codes for the cells (moving left to right, then top to bottom), with
* `0` = empty
* `6` = wire
* `7` = signal head
* `1` = signal tail
Once you have entered all of the cells, the simulation will begin (and continue forever, until you kill the program).
### Ungolfed
A more user-friendly version. To modify the layout, modify the `DATA` statements at the end.
The code takes advantage of the `POINT` function, which reads the color value of a pixel from the screen. This means we don't have to store the cells separately as an array. To make sure that all cells update simultaneously, we perform the updates on a second "page." We can toggle the active page using a version of the `SCREEN` statement, and copy one page's contents to another using the `PCOPY` statement.
```
SCREEN 9
EMPTY = 0 ' Black
HEAD = 7 ' Light gray
TAIL = 1 ' Blue
WIRE = 6 ' Brown/orange
' First two data values are the width and height
READ w, h
' The rest are the initial configuration, row by row
' Read them and plot the appropriately colored pixels
FOR y = 1 TO h
FOR x = 1 TO w
READ state$
IF state$ = "" THEN value = EMPTY
IF state$ = "H" THEN value = HEAD
IF state$ = "T" THEN value = TAIL
IF state$ = "W" THEN value = WIRE
PSET (x, y), value
NEXT x
NEXT y
' Loop the simulation until user presses a key
DO UNTIL INKEY$ <> ""
' Store current time for delay purposes
t# = TIMER
FOR y = 1 TO h
FOR x = 1 TO w
' Active page = display page = 0
SCREEN , , 0
' Get the color value of the pixel at x,y
oldVal = POINT(x, y)
IF oldVal = EMPTY THEN
newVal = EMPTY
ELSEIF oldVal = HEAD THEN
newVal = TAIL
ELSEIF oldVal = TAIL THEN
newVal = WIRE
ELSEIF oldVal = WIRE THEN
neighbors = 0
FOR ny = y - 1 TO y + 1
FOR nx = x - 1 TO x + 1
IF POINT(nx, ny) = HEAD THEN neighbors = neighbors + 1
NEXT nx
NEXT ny
IF neighbors = 1 OR neighbors = 2 THEN
newVal = HEAD
ELSE
newVal = WIRE
END IF
END IF
' Active page = 1, display page = 0
SCREEN , , 1, 0
' Plot the new value on page 1
PSET (x, y), newVal
NEXT x
NEXT y
' Copy page 1 to page 0
PCOPY 1, 0
' Delay
WHILE TIMER >= t# AND t# + 0.2 > TIMER
WEND
LOOP
DATA 8,5
DATA T,H,W,W,W,W,W,W
DATA W, , , ,W, , ,
DATA , , ,W,W,W, ,
DATA W, , , ,W, , ,
DATA H,T,W,W, ,W,W,W
```
1 The maximum values for width and height depend on which screen mode is used. In `SCREEN 9`, width can be up to 638 and height up to 348. `SCREEN 7` has a smaller resolution (max configuration size 318 by 198), but the pixels are bigger and thus easier to see (on DOS QBasic or the DOSBox emulator--unfortunately QB64 just gives a smaller window).
### Example run
Ungolfed version on [archive.org](https://archive.org/details/msdos_qbasic_megapack), with screen mode 7:
[](https://i.stack.imgur.com/YTlCx.gif)
] |
[Question]
[
**Challenge**
Write a solver for the [Chess Light](http://pyrosphere.net/chesslight/) puzzle game, in the smallest amount of code.
The input will be a representation of a chessboard, how in yours is up to you. My examples below is textual, in which some squares may already be occupied by black peices. Some of the unoccupied squares are designated with a `#`, along with a list of white men to be placed. The goal is to place those men within the designated squares in such a way that every designated square is *lit*.
A chess piece lights up the squares which it attacks, including those occupied by men of the same colour but not those which have an interposing man, and not the one which it occupies itself. For example queen diagnol attack stops at the square occuppied by another peice and no further.
E.g. with the following board, the `*` show the squares which are lit. `Q`'s square is unlit, but `Q` lights `R`'s square. The squares labelled `-` would be lit except that `R` is between them and `Q`.
```
+--------+
|* * -|
|* *- |
|*****R**|
|* ** |
|* * * |
|* * * |
|** * |
|Q*******|
+--------+
```
There is one important exception: a chess piece under attack by a man of the opposite colour doesn't light up any squares, it still block the light of others passing thru.
Note that pawns light up the following squares.
White Pawn
```
* *
P
```
Black Pawn
```
p
* *
```
Thus there is no *en passant*.
* White is playing up the board.
* Only one man is allowed on a square.
* All pieces assigned to be placed must be placed on the board
* An attacked piece, even if defended, is still attacked, but the defender does light up that square.
* White's men are denoted with capital letters and black's with lower-case letters: `KQRNBP` and `kqrnbp`, where `Nn` are kNights.
The output (of mine) consists of a list of squares in the same order as the men listed in the input, using algebraic notation. Yours is up to you.
\* There could be no answer!
---
# Examples
**Beginner (1)**
```
+--------+
| |
| # |
| # |
| # # |
| ###### |
| # # |
| # |
| |
+--------+
RR
```
`RR` are the pieces to be placed on the board.
Solution `C4, F4`
**Class B (19)**
```
+--------+
| |
| r |
| |
| ### b |
| ### |
| ### |
| ### |
| |
+--------+
PPPK
```
`PPPK` are the pieces to be placed on the board.
Solution `D4, E4, E2, D3`
Since the output is in the same order as the men, the white king is placed on `d3` and the other three squares receive white pawns.
]
|
[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/37841/edit).
Closed 9 years ago.
[Improve this question](/posts/37841/edit)
The Challenge: Make the shortest program to confirm that 12 is the answer.
(The puzzle is from Ian Stewart's "Cabinet of Mathematical Curiosities".
This is my first code golf question. I hope this type of thing is allowed)
In Scrabble the following are the letter scores:
AEIOULNRST score 1 each
DG score 2 each
BCMP score 3 each
FHVWY score 4 each
K scores 5
JX score 8 each
QX score 10 each.
]
|
[Question]
[
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, [visit the help center](/help/reopen-questions).
Closed 12 years ago.
Back to basics! Create a "Hello World" program which prints, well, "Hello World". The winner this time though, is the one who gets the most interesting source code done. For instance, use obscure language features, make it obfuscated, or make the source code a peom or a piece of ASCII art. Your imagination and coding ability are the only limitations.
* Print `Hello World` (exactly so)
* Make sure your source code is... unique. Yeah, that.
To obey the FAQ, I can't just decide what I think is the best, thus the winner will be the one getting the most votes, and I will select an answer during the **first day of May**.
]
|
[Question]
[
The program has an input of a and b, and outputs the sum of numbers from a to b, inclusive. Score is in bytes. As always, [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
If your input is in the format [a,b], +3 bytes
[Answer]
# [Stuck](http://esolangs.org/wiki/Stuck), 4 Bytes
I'm amazed Stuck finally is winning something! The inclusive range function checks to see if the top of the stack is a list of length 2, and uses it for the parameters of the range function if so.
```
t]R+
```
Input is `|` separated, as `t` takes a bunch of inputs separated by `|`s and places them on the stack. `]` just wraps the elements in a list, and lets the range function do it's job.
If that still falls in the penalty, then this works (5 Bytes): `ii]R+`
[Answer]
# Pyth, ~~6~~ ~~4 bytes + 3 = 7~~ 5 bytes
```
s}vzQ
```
Avoids the 3-byte penalty imposed by the new input requirements via an extra byte.
Takes input separated from stdin separated by newlines.
[Live demo.](https://pyth.herokuapp.com/?code=s%7DvzQ&input=1%0A3&debug=1)
[Answer]
## Python, 26
```
lambda a,b:(a+b)*(b-a+1)/2
```
Assumes `b>=a`. Uses the formula of `mean * #summands`. The result is a whole number, so it doesn't matter if the `/` is Python 2's floor division.
Shorter by 2 chars than the direct expression
```
lambda a,b:sum(range(a,b+1))
```
[Answer]
# Matlab/Octave, 14 bytes
```
@(a,b)sum(a:b)
```
[Answer]
# Julia, 15 bytes
```
s(a,b)=sum(a:b)
```
This creates a function `s` that sums the range `a:b`. This assumes `a` ≤ `b`.
[Answer]
# Dyalog APL, ~~8~~ 7 bytes
```
+÷2÷1--
```
This is a dyadic function train which is equivalent to
```
{(⍺+⍵)÷2÷1-⍺-⍵}
```
[Try it online.](http://tryapl.org/?a=f%u2190+%F72%F71--%20%u22C4%201%20f%2010&run)
### How it works
```
⍝ Left argument: a, right argument: b
- ⍝ Calculate a-b.
1- ⍝ Subtract the difference from 1 to calculate 1-(a-b) = b-a+1.
2÷ ⍝ Divide 2 by the difference to calculate 2/(b-a+1).
+ ⍝ Calculate a+b.
÷ ⍝ Divide the sum by the quotient to calculate (a+b)/(2/(b-a+1)),
⍝ i.e., (a+b)(b-a+1)/2.
```
[Answer]
# Javascript ES6, 21 bytes
```
a=>b=>(a+b)*(b-a+1)/2
```
Used the same approach to that problem that's almost everywhere: "Add up all of the numbers between 1 and 100, inclusive."
[Answer]
## SH, 16 bytes
```
seq $1 $2|numsum
```
Where $1 and $2 are the values of two args passed to this program on the command line. numsum is from the num-utils package. Another version that is also 16 bytes is:
```
seq -s+ $1 $2|bc
```
[Answer]
# APL, 9 bytes
```
-⍨/2!⎕+⍳2
```
Takes input as a two-element list . Set your index origin to 0 (`⎕IO←0`) before running.
This is longer than the [answer by @Dennis](https://codegolf.stackexchange.com/a/60139/39328) but in my opinion more stylish.
It calculates `(B+1 nCr 2)-(A nCr 2)` = `B(B+1)/2-A(A-1)/2`.
[Answer]
# Java, ~~44~~ 42 bytes
An approach I haven't seen here so far: Via gaussian sums you can derive that the sum of all numbers from `a` to `b` is `(b-a+1)*(b+a)/2`
If you only have to implement a function, you could do it in 42 bytes:
```
int s(int a,int b){return(b-a+1)*(b+a)/2;}
```
The conventional approach is 3 bytes longer:
```
int s(int a, int b){for(;b>a;a+=b--);return a;}
```
A full program is 142 bytes:
```
public class S{public static void main(String[]a){int n=Integer.parseInt(a[0]),m=Integer.parseInt(a[1]);System.out.println((m-n+1)*(m+n)/2);}}
```
[Answer]
# TI-BASIC, 8 bytes
```
mean(Ans+Ansmin(ΔList(Ans
```
Takes input in the form `{A,B}`.
```
Ans ; {A,B}
ΔList( ; {B-A}
min( ; B-A
Ans ; (B-A)*{A,B}
Ans+ ; (B-A+1)*{A,B}
mean( ; (B-A+1)*(A+B)/2
```
By comparison, the shortest two-variable solution is 11 bytes:
```
Prompt A,B
sum(randIntNoRep(A,B ;random permutation of integers between, inclusive
```
[Answer]
## Mathematica, 9 bytes
```
Tr@*Range
```
This evaluates to an unnamed function taking two integers. I was going to use the built-in `Sum`, but it's 4 bytes longer:
```
x~Sum~{x,##}&
```
[Answer]
## [><>](http://esolangs.org/wiki/Fish), 14 bytes
This assumes that the stack has already been populated with `a` and `b`, so this is basically a function. I'm using [this online interpreter](http://fishlanguage.com/playground) which lets you put values onto the stack before the program runs. An extra three bytes for `-v` (plus a space, for running from a terminal) would put this answer at **17 bytes**.
```
:r:@-1+@+*2,n;
```
### Explanation:
```
-v ab (initial stack)
: abb duplicates top of stack (b)
r bba reverses stack
: bbaa duplicates top of stack (a)
@ baba rotates top three elements clockwise (baa -> aba)
- ba,(b-a) subtraction (ba -> b-a)
1+ ba,(b-a+1) adds 1 (b-a -> b-a+1)
@ (b-a+1),ba rotates top three elements clockwise
+ (b-a+1),(b+a) addition (ba -> b+a)
* (b-a+1)*(b+a) multiplication
2, (b-a+1)*(b+a)/2 division by 2 (/ is a mirror, so , is used instead)
n; <integer, quit> output top of stack as an integer and quit
```
This assumes that `0 <= a <= b` and uses this closed-form solution `(b-a+1)(b+a)/2` to directly calculate the answer.
---
This code below goes the route of trying to be a full program, but only works for `0 <= a <= b <= 9`. That you have to do integer parsing in ><> is annoying. Thanks to **Cole**, if we assume the input is two single digits, then four bytes can be shaved off. **20 bytes.**
```
ic%:ic%:@$-1+@+*2,n;
```
The trick is that instead of `68*-`, use `c%` (take the modulus with respect to `12`). This will indeed work because `48+x (mod 12)` is `x (mod 12)`, which is 0-9 if `x` is 0-9.
[Answer]
# R - 24 Bytes
```
f=function(a,b) sum(a:b)
```
[Answer]
## CJam, 7 bytes
```
q~),>:+
```
[Test it here.](http://cjam.aditsu.net/#code=q~)%2C%3E%3A%2B&input=5%208)
```
q~ e# Read and eval input, pushing a and b onto the stack.
), e# Increment b and turn into the range [0 1 2 ... b-1 b].
> e# Discard the first a elements to get [a a+1 ... b-1 b].
:+ e# Reduce + onto the list, computing the sum.
```
[Answer]
# Haskell, 13 bytes
```
x#y=sum[x..y]
```
Usage example: `10 # 12` -> `33`
[Answer]
# O, ~~8~~ 7 bytes
```
Hjmr]+o
```
Explanation
```
H Start an array with a number from input
j Get input as number
mr Range between
]
+ Sum the array
o print it
```
Try it [here](http://o-lang.herokuapp.com/link/code=Hjmr%5D%2Bo&input=10%0A12)
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~32~~ 30 bytes
```
([{({}[()])}{}]{()({}[()])}{})
```
[Try it online!](http://brain-flak.tryitonline.net/#code=KFt7KHt9WygpXSl9e31deygpKHt9WygpXSl9e30p&input=NSAxMg)
## Explanation
This uses the triangulation algorithm to calculate `T(a-1)` and `T(b)` then pushes the difference. I actually golfed 2 bytes off the existing world record triangulation algorithm while making this solution.
To push `T(a-1)` it uses a modified version of the original algorithm. Instead of the simple:
```
({}[()])({()({}[()])}{})
```
I removed both the first `({}[()])` and the `()`.
The reason `()` was there in the first place was that `({({}[()])}{})` quite conveniently calculates `T(n-1)` for us so there is no need to decrement if we remove the `()`
This first portion is made negative and put next to the second portion which performs standard triangulation inside of the outer push.
```
([{({}[()])}{}]{()({}[()])}{})
```
[Answer]
# C++, 42 bytes
As a function (42 bytes):
```
int s(int a,int b){return(a+b)*(b-a+1)/2;}
```
As a full program that reads from STDIN and writes to STDOUT (86 bytes):
```
#include<iostream>
main(){int a,b;std::cin>>a;std::cin>>b;std::cout<<(a+b)*(b-a+1)/2;}
```
Both approaches compute the sum using the Gaussian formula.
Ungolfed:
```
#include <iostream>
int s(int a, int b) {
return (a + b) * (b - a + 1) / 2;
}
int main() {
int x, y;
std::cin >> x;
std::cin >> y;
std::cout << s(x, y) << std::endl;
return 0;
}
```
[Try it online](http://goo.gl/64Z7tt)
[Answer]
## [Befunge](http://www.esolangs.org/wiki/Befunge)-93, ~~18~~ 16 bytes
```
&:1-*&:1+*\-2/.@
```
### Explanation
```
& a input as integer (a)
: aa duplicate top of stack (a -> a,a)
1- a,(a-1) subtract 1 from top of stack (a -> a-1)
* a*(a-1) multiply top two values of stack (a,a-1 -> a*(a-1))
& a*(a-1),b input as integer (b)
: a*(a-1),bb duplicate top of stack (b -> b,b)
1+ a*(a-1),b,(b+1) add 1 to top of stack (b -> b+1)
* a*(a-1),b*(b+1) multiply top two values of stack (b,b+1 -> b*(b+1))
\ b*(b+1),a*(a-1) swap top two values of stack (c,d -> d,c)
- b*(b+1)-a*(a-1) subtract top two values of stack (d,c -> d-c)
2/ (b*(b+1),a*(a-1))/2 divide top of stack by 2
.@ <output, exit> output as integer and stop
```
This uses the following formula:
```
b(b+1) (a-1)(a-1+1) b(b+1) - a(a-1)
------ - ------------ = ---------------
2 2 2
```
Unfortunately, the shorter `(b-a+1)(b+a)/2` cannot be done in Befunge easily because it requires accessing `b` and `a` twice, which is impossible to do when working only with the top two values of the stack. Storing a value in "memory" would take more characters.
[Answer]
# PowerShell, ~~32~~ ~~31~~ 29 Bytes
```
$args-join'..'|iex|measure -s
```
Thanks to [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) for the alternate way to make a range and sum it. Works for any combination of `a` and `b` so long as the difference between them is less than 50,000.
---
Previous version (31):
```
param($a,$b)($b-$a+1)*($b+$a)/2
```
Uses the same formula as others, assumes that `b>=a`.
---
[Answer]
# Rust, 27 bytes
Creates a closure `s` that takes two unsigned 8-bit integers and returns another.
```
let s=|m,n|(n-m+1)*(m+n)/2;
```
[Answer]
# Java, 19 bytes
```
a->b->a-a*a-b*~b>>1
```
*Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904)*
[Try it online!](https://tio.run/##fU6xCsIwEN3zFRnbQoKdqwEXwUEcipM4XGtbUtMkJNdCkfrrNWIRcfAt9@7uvXvXwgCsvd5m2VnjkLah5z1KxetelyiN5nuNu4Vn5K/spMGNR1s5QOMyQmxfKFnSUoH39ABS0zuhAcvcI2Aog5FX2oVtlKOTujlfKLjGx4v4ha8X1r85gtabGZgomAAGCbAieRRCpHP2seejx6rjpkduQwIqHdUcrFVjlMZvsvXhbpSu4vhtm8g0PwE)
## Explanation
Expand the numerator:
$$(a+b)\*(b-a+1) = a\*b - a\*a + a + b\*b - a\*b + b = b \* b - a \* a + a + b$$
`>> 1` is equivalent to divide by `2`, but it has lower precedence than addition and subtraction, so no parentheses are required. `~x` is the same as `-x - 1`. Thus,
```
a-a*a-b*~b>>1 = (a-a*a-b*(-b-1))/2
= (a-a*a+b*b+b)/2
= (b*b-a*a+a+b)/2
```
# Java, 21 bytes
```
a->b->(a+b)*(b-a+1)/2
```
[Try it online!](https://tio.run/##fU49C8IwEN3zKzImSqN1rRZcBAdxKE7icP2S1DQJyVUo0t9eIxYRB99y7@7evXcN3CFqytsoW2sc0ib0okOpRN3pAqXRYq9xN/GE/JWdNLj@aCsHaFxCiO1yJQtaKPCeHkBq@iA0YJp7BAzlbmRJ27BlGTqpr@cLBXf1fBK/8PXC@jcnpfVmhCjNo5TBPOczlkcwj/liNSYfg6z3WLXCdChsyEClWS3AWtWzmL/J1gdnFi85f58NZBif)
[Answer]
# Jelly, 2 bytes
```
rS
```
[Try it online.](http://jelly.tryitonline.net/#code=clM&input=&args=NQ+MTA)
```
r Yields inclusive range [a, b]
S Sum
```
[Answer]
# PHP, 29 bytes
Based on standard stricks to set variables (eg register\_globals oldSkool)
```
while($b>=$a)$r+=$b--;echo$r;
```
[Answer]
# R, 18 Bytes
```
sum(scan():scan())
```
[Answer]
# Groovy, 19 Bytes
```
{a,b->(a..b).sum()}
```
[Answer]
# Applescript, ~~147~~ 137 Bytes
Welp. I'm not winning.
```
set a to(text returned of(display dialog""default answer""))
set b to(text returned of(display dialog""default answer""))
(b-a+1)*(b+a)/2
```
Since I'd never seen an Applescript answer before, I decided I'd make one, then immediately realized why it never had been done.
The explanation is fairly straightforward -
```
set ... to (text returned of (display dialog "" default answer ""))
^
Get the text of ^ the user inputs an answer here
(b-a+1)*(b+a)/2
^ with nothing else below this, Applescript recognizes it as the final
value and prints to console.
```
[Answer]
# 05AB1E, 2 bytes
```
ŸO
```
Explanation:
```
# Implicit input
# Implicit input
Ÿ # Push [a...b]
O # Sum list
# Implicit print
```
[Try it online!](http://05ab1e.tryitonline.net/#code=xbhP&input=MQoz)
[Answer]
# Awk, 24 bytes
`$0=""($1+$2)*($2-$1+1)/2`
Incorporated manatwork's suggestion.
] |
[Question]
[
**This question already has answers here**:
[Simple cat program](/questions/62230/simple-cat-program)
(330 answers)
Closed 8 years ago.
The mission is to implement a `cat`-like program (copy all STDIN to STDOUT).
Rules:
* You may only use standard libraries
* Indentation must be either two spaces or a single tab (in languages which require indentation)
* Scripts must use shebangs
* The result of `cat anything.txt | ./yourprogram | diff anything.txt -` should be nothing and should not be an infinite loop
`Go` example (84 bytes)
```
package main
import (
"os"
"io"
)
func main() {
io.Copy(os.Stdout,os.Stdin)
}
```
`C++` example (78 bytes)
```
#include<iostream>
using namespace std;
int main() {
cout << cin.rdbuf();
}
```
`Ruby` example (44 bytes)
```
#!/usr/bin/env ruby
$stdout << $stdin.read
```
Shortest code (by bytes) wins.
[Answer]
# GolfScript, 0 characters / bytes
This could technically be considered invalid since GolfScript will append a `\n`, but that can be fixed with `:n;` (3 bytes).
[Answer]
# sed - 0 bytes
No command needed to cat a file with `sed`: all lines of input are printed without modification, so
```
sed ''
```
will act like `cat` for standard input, and
```
sed '' /etc/fstab
```
will print content of file.
[Answer]
# ΒrainFuck (5 bytes)
```
,[.,]
```
**Explanation:**
```
, Read first byte of input and place on stack
[ While top byte is not 0...
. Print top byte from stack as ASCII and remove
, Read next byte of input and place on stack
] ...loop
```
[Answer]
# Haskell - 17 bytes
```
main=interact id
```
`id` is the identity function and from the documentation :
>
> The `interact` function takes a function of type `String->String` as its argument. The entire input from the standard input device is passed to this function as its argument, and the resulting string is output on the standard output device.
>
>
>
[Answer]
# x86\_64 NASM Assembly for Linux - 125 / 100
```
r:mov ax,0
mov di,0
mov rsi,c
mov dx,1
syscall
cmp ax,0
je e
mov di,1
syscall
jg r
e:mov ax,60
syscall
SECTION .bss
c:resw 1
```
I couldn't get it to fit in 100 bytes, but it is assembly. Eight bytes could be saved at the cost of changing the return status to 1 instead of 0:
```
r:mov ax,0
mov di,0
mov rsi,c
mov dx,1
syscall
cmp ax,0
mov di,1
jg s
mov ax,60
s:syscall
jg r
SECTION .bss
c:resw 1
```
Now, if you really want 100 bytes, here is one in exactly 100 bytes. The problem is that it doesn't exit correctly, it just segfaults:
```
r:mov ax,0
mov di,0
mov rsi,c
mov dx,1
syscall
cmp ax,0
mov di,1
syscall
jg r
SECTION .bss
c:resw 1
```
The instructions say to only use standard libraries; is there extra credit for using no libraries at all?
[Answer]
# C 43
```
main(c){while((c=getchar())>=0)putchar(c);}
```
[Answer]
# Node.js 55
```
#!/usr/bin/env node
process.stdin.pipe(process.stdout);
```
[Answer]
## Perl (1)
0+1 for the -p parameter
If really the shebang counts, invoke it like this: `perl -p nul` on M$ or `perl -p /dev/null` on \*nix so no shebang is involved :P
```
D:\>copy con cat.pl
#!perl -p
^Z
1 file(s) copied.
D:\>type cat.pl
#!perl -p
D:\>type cat.pl | cat.pl
#!perl -p
D:\>
```
[Answer]
# Bash, 3
If you need a shebang, `#!/bin/sh` or `#!/bin/bash` is probably fine.
Had to be done. Hopelessly uncreative.
```
cat
```
Slightly more interesting:
```
tee
```
Normally, `tee FILENAME` sends its input both to the file and to standard output. Without an argument, it seems to behave like `cat`.
# Bash, 2
...if you don't mind the status message at the end and the fact that the output only comes after EOF on standard input!
```
dd
```
Removing the status message costs 4 chars for a total of 6 chars:
```
dd 2>a
```
The message is sent to the file `a` instead of standard output.
If you dispose of the message entirely, the total length is ~~14~~ 7:
```
dd 2>&-
```
# Bash/[SHELF](https://github.com/professorfish/bash-shelf), 1
For the shebang, try
```
#!/bin/sh
. shelf.sh
```
where `shelf.sh` is the location of your SHELF file.
SHELF is my PYG-like golfing library for Bash.
```
D
```
`D` just aliases to `cat`. Also uncreative.
And the alias for `tee` is...
```
5
```
[Answer]
## Linux/Unix tools, 16 bytes
```
#!/bin/sh
grep $
```
Other tools that work when called by bash/sh are
```
tr . .
```
and (15 bytes)
```
sed n
```
EDIT: Changed title from "bash/sh" to "Linux/Unix tools" because although the tools can be called by bash or sh they aren't actually part of bash or sh.
[Answer]
# CJam - 1
```
q
```
No extra newline :)
[Answer]
# AWK - ???
The complete program in `awk` has only 1 char:
```
1
```
Unluckily the shebang stuff lets kinda explode it's length :(
```
#!/usr/bin/awk -f
1
```
May I copy `awk` into the filesystem root? >;-)
As oneliner it is shorter:
```
$ awk 1 </etc/hostname
darkstar
```
I'm not sure what counts and what not...
[Answer]
# 16 bit .com binary for MSDOS - 31 Bytes (112 Byte NASM Source)
```
00 00 BA 00 00 B9 01 00 B4 3F BB 00 00 CD 21 83 F8 00 74 09 B4 40 BB 01 00 CD 21 EB EB CD 20
```
The nasm source code:
```
c:resw 1
mov dx,c
mov cx,1
r:
mov ah,63
mov bx,0
int 33
cmp ax,0
je e
mov ah,64
mov bx,1
int 33
jmp r
e:
int 32
```
Build with "nasm -f bin -o cat.com cat-msdos.s".
I already provided a solution for x86\_64 Linux, but was unable to get it under 100 bytes. This is over 100 bytes of assembly, but the actually binary is only 31 bytes! This must be the simplest solution here.
[Answer]
# Ruby, 2 bytes (or 1?)
```
#!/usr/bin/env ruby -p
```
The question states that the shabang needs to be included. The 2 bytes counted is the `-p` part of the shebang. The otherwise empty script makes Ruby behave *exactly* likes `cat` when run with the `p` switch: Run it without arguments and it will take input from stdin, or with arguments and it print the contents of those files.
**edit:**
# Ruby, 8 bytes
@core1024 had already posted a solution in Perl similar to the one above, so here is another attempt. Note that the following are not scripts, they are Ruby *programs* ;)
```
puts *$<
```
# Ruby, 16 bytes
I think this one is cute
```
print while gets
```
[Answer]
# Python 2.x - 56 or 61 bytes
Input limited to 10^9 bytes.
```
#!/usr/bin/python
from os import*
write(1,read(0,10**9))
```
Or for infinite input (61 bytes):
```
#!/usr/bin/python
from sys import*
stdout.write(stdin.read())
```
Not much to say, is there?
[Answer]
# Batch (8)
```
type CON
```
Type writes file content to the console and CON is treated as a file containing all console input.
[Answer]
# Common Lisp
## ECL, 106
```
#!/usr/local/bin/ecl -shell
(ignore-errors(loop(write-byte(read-byte *standard-input*)*standard-output*)))
```
## SBCL, 109
```
#!/usr/local/bin/sbcl --script
(ignore-errors(loop(write-byte(read-byte *standard-input*)*standard-output*)))
```
## CLISP, ~~188~~ 180
```
#!/usr/local/bin/clisp
(let((i(make-stream 0 :element-type'(mod 256)))(o(make-stream 1
:direction :output :element-type'(mod
256))))(ignore-errors(loop(write-byte(read-byte i)o))))
```
These are the shortest programs that I can make, yet none are under 100 bytes.
The main problem is that `*standard-input*` and `*standard-output*` are character streams, not byte streams. A simple `(loop(write-char(read-char))` would copy the characters but would fail to preserve bytes that did not form valid characters. Now my Common Lisp implementations want to use UTF-8 (perhaps because my locale is UTF-8), but I want to copy binary files that my not be valid UTF-8. Therefore I must copy bytes, not characters.
In ECL and SBCL, standard input and output are bivalent for both bytes and characters. I may use `read-byte` and `write-byte`, but those functions lack default streams, so I must pass `*standard-input*` and `*standard-output*` as arguments.
CLISP insists that `*standard-input*` and `*standard-output*` transport only characters. The way around this is to call `ext:make-stream` on file descriptor 0 (standard input) and file descriptor 1 (standard output) to make binary streams.
All three programs loop byte by byte. This is a **slow** way to copy bytes. A faster way would use a vector of 16384 bytes with `read-sequence` and `write-sequence`, but the program would be longer.
[Answer]
# zsh, 15 bytes
```
#!/bin/zsh
1<&1
```
Note that there is **no** newline at the end of the file.
[Answer]
Some Perl:
```
#!/usr/bin/perl
print<>;
```
25 bytes with shebang. This can also be much smaller with die(), and by bending the rules ever so slightly:
```
die<>
```
Executing the 4th test could only be done like this:
```
cat bla|perl ./perlcat 2>&1|diff bla -
```
<> is an abbreviation for `<STDIN>`. The 25 byte print example is pretty self explanatory. die() is normally used for exiting non-zero and outputting an error message, hence using the 2>&1 to bend the rules around the 4th test.
It also appears that the semicolon is not required for the last statement in Perl, so the first example could be brought down to 24 bytes.
[Answer]
# ><>, 7 bytes
I know a ><> solution already exists, but I figured it would be welcome.
```
i:0(?;o
```
[Click here to try it](http://fishlanguage.com/playground/u7ttRxRqTCymDDNe6)
[Answer]
# Java ~~68~~ 104
My first approach at this:
~~`class a{public static void main(String[]a){System.out.print(a[0]);}}`~~
EDIT: Yeah, I misunderstood the concept, here is another attempt, I couldn't get it done in less than 100 chars so I'd appreciate any suggestion:
```
class a{public static void main(String[]a)throws Exception{for(;;)System.out.write(System.in.read());}}
```
[Answer]
# TI-BASIC, 12
```
While 1:Input Str1:Disp Str1:End
```
[Answer]
### Perl6, 14 bytes:
```
.say for lines
```
And, if it doesn't need to be deterministically printing it in the correct order (hehe), you can use the auto-threading "map-apply"
```
lines>>.say
```
[Answer]
# GML, 37
```
while(1)show_message(keyboard_string)
```
[Answer]
# Rust - 74
Really generic...
```
use std::io;fn main(){for l in io::stdin().lines(){io::print(l.unwrap())}}
```
## No Comment - 12
```
'=|@^:'&|:'&
```
Unimplemented, so, yeah.
[Answer]
## Dart - 48
```
import"dart:io";main(){stdout.addStream(stdin);}
```
[Answer]
## Groovy - 45 bytes
```
#!/usr/bin/env groovy
System.out << System.in
```
And test:
```
$ cat FirstJsonObj.groovy | ./Cats.groovy | diff FirstJsonObj.groovy -
$
```
[Answer]
# Tcl 57
```
#!/usr/bin/env expect
while {[gets stdin d]>=0} {puts $d}
```
[Answer]
# Swift, 32
```
while let l=readLine(){print(l)}
```
Prints every line until EOF is reached
If you're really picky that this doesn't work with an empty line at the end or whatever you can use this:
```
while let l=readLine(stripNewline:false){print(l,terminator:"")}
```
[Answer]
# MATLAB, 18 bytes
```
fprintf(input(''))
```
Cannot use `disp` as it appends a newline to the output.
] |
[Question]
[
The handshake problem is the classic problem that for n people in a room, if they all shake hands, what's the total number of handshakes that occur.
You code should take an input of any number and output the number of handshakes, both in base ten.
Also the code should not let non-integers through. You should output a falsey in this case. The only expected inputs are positive whole integers and positive real numbers - you don't need to worry about complex numbers or strings as inputs.
This should mean that you should expect `n >= 0`
Test cases
```
(N:handshakes)
0:0
10:45
20:190
10.5:0
1337:893116
```
Normal golfing rules apply and shortest code wins.
If your code isn't self explanatory, please explain.
Jelly and 05AB1E are the winners, both at 2 bytes
[Answer]
# JavaScript ES6, 16
```
n=>n%1?0:~-n*n/2
```
*Test*
```
f=n=>n%1?0:~-n*n/2
function test()
{
var i=I.value
O.textContent=f(i)
}
```
```
<input id=I oninput=test()><span id=O></span>
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 2 bytes
Code:
```
2c
```
[Try it online!](http://05ab1e.tryitonline.net/#code=MmM&input=MTMzNw).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
2Xn
```
[**Try it online!**](http://matl.tryitonline.net/#code=Mlhu&input=MTMzNw)
The code computes the binomial coefficient "*n* choose 2", where *n* is the input. For non-integer input no output is produced.
```
% Take input implicitly
2 % Push 2
Xn % n-choose-k
% Display implicitly
```
[Answer]
# Brainfuck, ~~22~~ 21 bytes
```
,[-[->+>+<<]>[-<+>]<]
```
[Try it online!](https://repl.it/C1rZ/2) Note, that brainfuck takes input and output through ASCII, so to enter a "49", you enter ascii value 49, e.g. `1`. Brainfuck has no concept of non-integers, so it is impossible to enter one.
[Answer]
## Jelly, 2 bytes
```
c2
```
[Try it online!](http://jelly.tryitonline.net/#code=YzI&input=&args=MTMzNw)
[Answer]
## Matlab, 61 23 bytes
```
@(x)~mod(x,1)*x*(x-1)/2
```
Improvements courtesy [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo).
*Old answer:*
`@(x)eval('if isnumeric(x) disp((mod(x,1)==0)*x*(x-1)/2);end')`
An anonymous function that calls `eval`. Matlab considers all numbers entered to be doubles unless you explicitly tell it otherwise, so testing for integerness via built-in isn't really an option unless you want to condition your input heavily-- thus the isnumeric and the mod1.
As well, Matlab doesn't allow conditional statements in anonymous functions, so you have to kludge around that by way of an `eval` statement that evaluates a string. So fun.
The "falsey" output is that it doesn't print anything at all for nonnumerics and prints `0` for a non-integer numeric. For a valid input, it will print the result.
[Answer]
**Python, 37 50, 46, 32, 26 bytes**
```
lambda a:a%1==0and a*~-a/2
```
Making use of the fact that the solution of the handshake problem is (N-1) + (N-2) ... 2 + 1 for N people. The most problematic is the falsey value when a non-int is given.
Big thanks to Leaky Nun and Martin Ender!
[Answer]
# [CJam](https://sourceforge.net/projects/cjam/), 7 bytes
```
ri_(*2/
```
Computes *n*\*(*n*‚àí1), where *n* is the input. For non-integer input it produces no output.
[**Try it online!**](http://cjam.tryitonline.net/#code=cmlfKCoyLw&input=MTMzNw)
```
r e# Read input
i e# Convert to integer
_ e# Duplicate
( e# Subtract 1
* e# Multiply
2/ e# Divide by 2.
e# Implicit display
```
[Answer]
## Mathematica, 19 bytes
```
#(#-1)/2/._Real->0&
```
This first computes the result using the explicit formula `n(n-1)/2` but then replaces it with `0` if the that gives a floating-point result.
Just for fun, some alternatives to computing the result (minus the input validation) are:
```
#~Binomial~2
Tr@Range@#-#
n~Sum~{n,#-1}
PolygonalNumber@#-#
```
[Answer]
## R, 28 bytes
Returns `0` if the input, `x`, is not an integer
```
x=scan();(x%%1==0)*x*(x-1)/2
```
[Answer]
## [ArnoldC](https://esolangs.org/wiki/ArnoldC), 266 bytes
ArnoldC has no concept of non-integers, so it is impossible to enter one.
```
LISTEN TO ME VERY CAREFULLY f
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE r
YOU SET US UP 0
GET TO THE CHOPPER r
HERE IS MY INVITATION n
GET DOWN 1
YOU'RE FIRED n
HE HAD TO SPLIT 2
ENOUGH TALK
I'LL BE BACK r
HASTA LA VISTA, BABY
```
Explanations:
```
DeclareMethod f
MethodArguments n
NonVoidMethod
DeclareInt r
SetInitialValue 0
AssignVariable r
SetValue n
MinusOperator 1
MultiplicationOperator n
DivisionOperator 2
EndAssignVariable
Return r
EndMethodDeclaration
```
[Answer]
## CJam, 5 bytes
```
ri,1b
```
Prints nothing (except to STDERR) for non-integer input.
[Try it online!](http://cjam.tryitonline.net/#code=cmksMWI&input=MTMzNw)
### Explanation
```
ri e# Read input and try to convert to integer N.
, e# Turn into range [0 1 2 ... n-1].
1b e# Sum the list by treating it as base-1 digits. We do this instead of
e# a simple reduction (:+) because the latter fails for empty lists.
```
[Answer]
# Desmos, 11 bytes
```
.5nn-.5n
n=1
```
[Try it here](https://www.desmos.com/calculator/ll7dztszzp)
Ungolfed formula:
[](https://u.cubeupload.com/weatherman115/ungolfed.png)
[Answer]
## [Hoon](https://github.com/urbit/urbit), 30 bytes
```
|=
n/@
(div (mul n (dec n)) 2)
```
Just compute `(n * (n-1))/2`.
Hoon is strongly typed, so you *can't* call this function with a float or negative number.
[Answer]
# Pyth, 7 bytes
```
~~?sIQ.cQ2Z~~
.x.cQ2Z
```
[Test suite.](http://pyth.herokuapp.com/?code=.x.cQ2Z&test_suite=1&test_suite_input=0%0A10%0A20%0A10.5%0A1337&debug=0)
[Answer]
# Python 3, 22 bytes
```
lambda z:sum(range(z))
```
Makes use of Python's standard library. Raises an error whenever the function is fed with a non-integer.
[Answer]
## Python 3, 32 16 bytes
```
lambda n:n*~-n/2
```
Throws an error if n is not an integer.
Old Version:
```
lambda n:(0,n*~-n/2)[n==int(n)]
```
[Answer]
## PowerShell v2+, 33 bytes
```
param($n)$n*($n-1)/2*($n-is[int])
```
Full program. 20 bytes to compute `n(n-1)/2` and 13 bytes to validate input. Uses the [`-is` operator](https://technet.microsoft.com/en-us/library/hh847763.aspx), so requires V2 or newer.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 9 bytes
```
2‚àò!√ó(|=‚åä)
```
The chose-2 times (whether the abs equals the floor).
[Answer]
# J, ~~14~~ 8 bytes
```
2&!*]=<.
```
6 bytes saved thanks to [miles](https://codegolf.stackexchange.com/users/6710/miles)!
Explaination:
```
2&! NB. Binomial coefficient of 2 and the argument
* NB. Times...
]=<. NB. argument == floor(argument)
```
Previous solution: `-:@(*<:)*(=<.)`
[Answer]
# dc, 18 bytes
```
[d/]sqdX0!=qd1-*2/
```
### Explanation
```
[d/]sq
```
Store in register `q` a macro that replaces top of stack with 1 (by dividing by itself).
```
dX0!=q
```
If there are any fraction digits, then execute the macro.
```
d1-*2/
```
Compute ¬Ωn(n-1). If we started with 1 (either as input or because a non-integer value was entered) the result will be 0.
[Answer]
# Factor with `load-all`, 12 bytes
```
[ iota sum ]
```
Same as [this answer](https://codegolf.stackexchange.com/a/82978/46231).
[Answer]
# Java, 363 bytes
I thought I ought to make sure everybody gets a chance to meet everybody else.
Unfortunately some of the party guests do have to ask if they've met someone before, to avoid shaking someone's hand twice. Hopefully the guests are pretty good at recognizing faces.
Golfed:
```
import java.util.ArrayList;public class H{static int h = 0;public static void main(String[] a){int b = Integer.parseInt(a[0]);P[] e = new P[b];for(int i=0;i<b;i++){e[i] = new P();}for(P p : e){for(P o : e){p.s(o);}}System.out.print(h);}}class P {ArrayList<P> l = new ArrayList<P>();void s(P o){if(o.equals(this)){return;}if(!o.l.contains(this)){H.h++;l.add(o);}}}
```
Un-golfed:
```
import java.util.ArrayList;
public class PartyHost {
static int shakes = 0;
public static void main(String[] args){
int amount = Integer.parseInt(args[0]);
Person[] people = new Person[amount];
for(int i=0; i<amount;i++){
people[i] = new Person();
// welcome to the party!
}
// well, we gotta get this party rockin'. hey, have you met my friend...
for(Person p : people){
for(Person other : people){
p.handshake(other);
}
}
System.out.print(shakes);
}
}
class Person {
ArrayList<Person> already_shook = new ArrayList<Person>();
void handshake(Person other){
// hmm, have we met already?
if(other.equals(this)){
// I mean, I guess I could shake hands with myself... maybe later.
return;
}
if(!other.already_shook.contains(this)){
// it seems not!
// *firm grasp. maintain eye contact*
// uh oh don't hold on too long
// hope he doesn't grab too early or too late
PartyHost.shakes++;
already_shook.add(other);
}
}
}
```
[Answer]
# ùîºùïäùïÑùïöùïü, 5 chars / 7 bytes
```
МƦ⁽ï2
```
`[Try it here (ES6 browsers only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=10&code=%D0%9C%C6%A6%E2%81%BD%C3%AF2)`
Builtins are pretty cool.
[Answer]
# [RETURN](https://github.com/molarmanful/RETURN), 8 bytes
```
[$1-√ó2√∑]
```
`[Try it here.](http://molarmanful.github.io/RETURN/)`
Anonymous lambda that leaves result as top of stack. Usage:
```
10[$1-√ó2√∑]!
```
# Explanation
```
[ ] lambda
$1- n-1
√ó *n
2√∑ /2
```
[Answer]
# Google Sheets, ~~17~~ 14 bytes
```
=((B1^2)-B1)/2
```
Cell B1 is the input.
[Answer]
## Haskell, 15 bytes
```
f x=sum[1..x-1]
```
`[x..y]` ranges are inclusive...
Oh and I don't know how to handle the non-integers...
[Answer]
## [Golisp](https://github.com/tuxcrafting/golisp), 18 bytes
```
{(n)~[+range[1n]]}
```
Python equivalent: `lambda n: sum(range(1, n))`.
Oh and Golisp don't have floating point number (for now)
[Answer]
# Perl 5, 25 bytes
A subroutine:
```
{($_=pop)*!/\D/*($_-1)/2}
```
See it in action:
```
perl -e'print sub{($_=pop)*!/\D/*($_-1)/2}->(3.14)'
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 10 years ago.
[Improve this question](/posts/15369/edit)
I am not sure if this is possible. I have tried it and couldn't make it work at all, but I am being hopeful.
If this is not possible please flag this question and I will promptly delete it.
Conditions are simple,
Write code that will output same amount of character in the same shape as the code.
For example (A very stupid example).
If code says
```
#include<stdio.h>
main()
{
printf("Hello World");
}
```
Then output must be
```
kjh#$@#)(12398n,s
lkrjop
t
jherl;k@&##*$&@3n,2m$*
t
```
I really do not care which characters are being used in the output or anything like that except that space is space and tab is tab. So whatever is the shape of the code, the output should be the same.
**Winner**: Either popularity , or help me decide the criteria.
The only way I managed to make this work, is I created a file reader that reads the code and does rot13 on every character in the code and prints it out. However I was not fond of it, because the shape was not interesting, nor do I want to use file reader to do something like this because it is too easy.
[Answer]
## JS
I know it's still being contested, but I thought I'd have a go:
```
(function (){a='';
a ; a=
' '; h
= '#' ;
s = ' ' ;
s ; s ; s
; s ; s ;
s ; s ; s
; s ; s ;
s ; s ; s
; s ; s ;
b = ''; s ;
s ; return( a +
b + b+arguments[ b +
'ca' +'llee'].toString ( )
.replace(/\S/g,h)+'###');s;
s ;
s;s;s})()
```
When run in Chrome's console produces:

Not 100% accurate, but I thought it was quite close. As intangible as the criteria were to begin with, I did like the idea of the challenge, despite how easy/difficult is in differing languages.
[Answer]
on the Dyalog APL terminal
```
abcde fghij
```
outputs
```
VALUE ERROR
```
[Answer]
## BF
```
>++++++++[>+++++++>+++++++<<-]>++>++++++<>++++++<<<++++++++++[>++++<-]>[>.>.<<-]
```
It just outputs a set of laughing smileys:
```
:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D:D
```
Size of code and its output are both 80.
[Answer]
**Python, 0** (kind of cheating)
Here's a totally *valid* Python program:
And here's the output of that program, of same shape:
:)
[Answer]
## Python
Smallest thing I could think of.
```
print 'a'*5+' '+'a'*16
```
Output
```
aaaaa aaaaaaaaaaaaaaaa
```
That space in the middle is part of a string so it doesn't count.
[Answer]
## Quines
Any [quine](http://en.wikipedia.org/wiki/Quine_%28computing%29) (a program producing a copy of its own source code) would do the trick. There are thousand examples on the internet written in [many different languages](http://www.nyx.net/%7Egthompso/quine.htm). For example:
**Perl, 34** [Author: V Vinay](http://www.nyx.net/%7Egthompso/self_perl.txt)
```
$_=q(print"\$_=q($_);eval;");eval;
```
**Python, 33** [Author: Frank Stajano](http://www.nyx.net/%7Egthompso/self_pyth.txt)
```
l='l=%s;print l%%`l`';print l%`l`
```
**Java, 252** [Bertram Felgenhauer](http://www.nyx.net/%7Egthompso/self_java.txt)
```
class S{public static void main(String[]a){String s="class S{public static void main(String[]a){String s=;char c=34;System.out.println(s.substring(0,52)+c+s+c+s.substring(52));}}";char c=34;System.out.println(s.substring(0,52)+c+s+c+s.substring(52));}}
```
**Tcl, 34** [Author: Joe Miller](http://www.nyx.net/%7Egthompso/self_tcl.txt)
```
join {{} \{ \}} {join {{} \{ \}} }
```
[Answer]
or if you are picky
```
5 ⍴ 1 + 1
```
outputs
```
2 2 2 2 2
```
[Answer]
## Perl
Any program which reads it's own source file will do (technically, it's not considered to be a [quine](http://en.wikipedia.org/wiki/Quine_%28computing%29)). Here's a simple Perl script (my lack of inspiration restricted me from giving to the code a shape more complex than a diamond/rhombus)!
```
use
warnings;
use strict;open
(my $IN,'<',$0)or die
"PCG FTW";print
<$IN>;close
$IN
```
Which will print:
```
use
warnings;
use strict;open
(my $IN,'<',$0)or die
"PCG FTW";print
<$IN>;close
$IN
```
[Answer]
# HQ9+
```
+++ +++
+++ +++
++
++ +Q ++
++ ++
++ ++
+++ +++
++++
```
Or, something like this:
```
___ __ _____
____ ____ __| _/____ ____ ____ | |_/ ____\
_/ ___\/ _ \ / __ |/ __ \ / ___\ / _ \| |\ __\
\ \__( <_> ) /_/ \ ___/ / /_/ > <_> ) |_| |
\___ >____/\____ |\___ > \___ / \____/|____/__|
\/ \/ \/ /_____/ Q
```
Credits to [this site](http://patorjk.com/software/taag/) ;)
Basically, anything will work, as long as it has exactly:
* 0 `H`s
* 0 `9`s
* 1 `Q`
Or, some minimalist solutions:
* 1 char
```
Q
```
* 0 chars
[Answer]
### Perl 44 chars
```
open O,"<$0";while(<O>){y|!-~|P-~!-O|;print}
```
In action:
```
echo $'#!/usr/bin/perl\nopen O,"<$0";while(<O>){y|!-~|P-~!-O|;print}' >/tmp/autohide.pl
chmod +x /tmp/autohide.pl
/tmp/autohide.pl
RP^FDC^3:?^A6C=
@A6? ~[QkS_QjH9:=6Wk~mXLJMP\OM!\OP\~MjAC:?EN
```
reverse:
```
/tmp/autohide.pl | perl -pe 'y|!-~|P-~!-O|'
#!/usr/bin/perl
open O,"<$0";while(<O>){y|!-~|P-~!-O|;print}
```
### Rot47 vs Rot13:
To correspond to *behaviour* of **Rot13**, but from `!` to `~`, there is 94 chars. I wrote `rot47`:
```
#!/usr/bin/perl -s
$ s
? $ O
= * STDIN
: open
$ O
, "<"
. $
0 ;while
( <$O>
) {#
y|!-~|P-~!-O|
; print }
```
(I've tried to draw *beavis*, but this is not very well!)
Store them, for sample in `autohide.pl`:
```
chmod +x autohide.pl
```
with executable rights,
```
./autohide.pl
RP^FDC^3:?^A6C= \D
S D
n S ~
l Y $%sx}
i @A6?
S ~
[ QkQ
] S
_ jH9:=6
W kS~m
X LR
JMP\OM!\OP\~M
j AC:?E N
```
Than, there is no *reverse* operation, it's only repeat same translation.
When run with `-s` parameter, this use `STDIN` instead of himself code,
so running `./autohide.pl -s <autohide.pl` do same as if run without argument:
```
./autohide.pl -s <autohide.pl | ./autohide.pl -s
#!/usr/bin/perl -s
$ s
? $ O
= * STDIN
: open
$ O
, "<"
. $
0 ;while
( <$O>
) {#
y|!-~|P-~!-O|
; print }
```
[Answer]
## Python
Generic solution.
Just save the file as 'source.py' and execute.
```
import random
def main():
f = open('source.py')
s = ''
d = {' ':1,
'\t':2,
'\n' :3}
rstring = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`1234567890-=~!@#$%^&*()_+,./<>?;:[]{}|'
for line in f:
for char in line:
if char in d:
s += char
else:
s += random.choice(rstring)
print s
main()
```
[Answer]
May be simplest solution for Python
```
print'*'*11
```
and for Py3K
```
print('*'*13)
```
and another generic solution for Py3K
import random, sys
```
def main():
f = open(__file__).read()
d = ' \t\n'
r = ''.join(chr(c) for c in range(33, 127))
sys.stdout.write(''.join(c if c in d else random.choice(r) for c in f))
if __name__ == '__main__':
main()
```
[Answer]
### Bash ~~9~~ 8 chars (Thanks @FireFly)
```
rot13<$0
```
This match requirement:
* output same amount of character in the same shape as the code
* rot13
### Practical
```
echo >autorot13.sh 'rot13 <$0'
chmod +x autorot13.sh
./autorot13.sh
ebg13<$0
```
] |
[Question]
[
# Challenge
Generate \$n-1\$ **consecutive** composite numbers using this prime gap formula
$$n!+2,n!+3,...,n!+n$$
**Input**
An integer \$n\$ such that \$3 \leq n \leq 50 \$.
**Output**
Sequence of \$n-1\$ consecutive composite numbers.
# Example
**Input**
```
3
```
**Output**
```
8
9
```
# Rules
* Output should be in integer format.
# Test Cases
For \$n > 20\$, the results are very BIG integers (greater than 64-bits) and will most likely require a language that natively supports large numbers or a 3rd party library to handle them.
| n | \$n-1\$ consecutive composites |
| --- | --- |
| 3 | 89 |
| 5 | 122123124125 |
| 21 | 5109094217170944000251090942171709440003510909421717094400045109094217170944000551090942171709440006510909421717094400075109094217170944000851090942171709440009510909421717094400105109094217170944001151090942171709440012510909421717094400135109094217170944001451090942171709440015510909421717094400165109094217170944001751090942171709440018510909421717094400195109094217170944002051090942171709440021 |
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 5 bytes [SBCS](https://github.com/abrudz/SBCS)
```
1‚Üì‚ç≥+!
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=M3zUNvlR72ZtRQA&f=S1Mw5kpTMAViI0MA&i=AwA&r=tryapl&l=apl-dyalog-extended&m=train&n=f)
A tacit function that takes an integer on the right and returns an array of n-1 composite numbers.
### Explanation
```
! ‚çù factorial
+ ‚çù plus
‚ç≥ ‚çù range
1‚Üì ‚çù drop the first
```
There are actually two other permutations of these five characters that produce the same result.
See if you can find them. ;)
## 6 bytes, outputs full numbers under \$10^{34}\$
```
‚çï1‚Üì‚ç≥+!
```
[Try it!](https://razetime.github.io/APLgolf/?h=03jUN9UtCEgEBGg@aptgaGRhrmBsAgA&c=e9Q7VVHb8FHb5Ee9mwE&f=S1Mw5kpTMAViI0MA&i=AwA&r=tryapl&l=apl-dyalog-extended&m=train&n=f)
This requires adding `(‚éïFR‚éïPP)‚Üê1287 34` to the header to set the float and printing precision.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 4 bytes
```
·∏¢?¬°+
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCLhuKI/wqErIiwiIiwiMyJd)
```
·∏¢ # range(2, n+1)
+ # +
?¬° # n!
```
[Answer]
# [Funge-98](https://esolangs.org/wiki/Funge-98), 29 bytes
```
"HTMI"4(&:F2+v
\I_@#:-2\I.: <
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9X8gjx9VQy0VCzcjPSLuOK8Yx3ULbSNYrx1LNSsPn/38iQCwA)
[Answer]
# [Python](https://www.python.org), 51 bytes
```
f=lambda n:range((n<2or(f(n-1).stop-n)*n)-~n)[1-n:]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3jdNscxJzk1ISFfKsihLz0lM1NPJsjPKLNNI08nQNNfWKS_ILdPM0tfI0devyNKMNdfOsYqFaFdPyixQyFTLzFCAajXWMDDStCooy80o0tNI0MjU1IQphdgEA)
Returns a `range` object.
### Original [Python](https://www.python.org), 56 bytes
```
f=lambda n:[n*([*f(n-1),3][0]-2)+j+2for j in range(n-1)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY9NCsIwFIT3PcUDN0ltQeumFLyCFyhFYs1rU5uXkr4g7r2FGzd6J29j_cPdDMPwzVzuw4lbR9frLTCm-SPHda_sbq-AipJiUcYoKF3KZFWViyrN5LybZ-g8dGAIvKJGv_Pq2z_PwKqDBsPgAwGqkbWHo5kggaFup4KhBiYzBC4i9M4CBqrZuX4EYwfnGXoftrWqWx1Na35abBxpKVBG0Ytv_vxlki1kMXhDLFAYKT9bfp-e)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḋ+!
```
**[Try it online!](https://tio.run/##y0rNyan8///hji5txf///xsZAgA "Jelly – Try It Online")**
A monadic Link that accepts a positive integer, \$n\$, and yields a list of the \$n-1\$ consecutive integers.
### How?
```
Ḋ+! - Link: integer, n
Ḋ - dequeue {n} -> [2, 3, 4, ..., n]
! - {n} factorial -> n!
+ - add (vectorises) -> [2+n!, 3+n!, 4+n!, ..., n+n!]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L¦¤!+
```
[Try it online](https://tio.run/##yy9OTMpM/f/f59CyQ0sUtf//NzIEAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/n0PLDi1R1P6v8z/aWMdUx8gwFgA).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input]
¦ # Remove the first value to make the range [2,input]
¤ # Push the last item (without popping the list): the input
! # Take its factorial
+ # Add it to each value in the list
# (after which this list is output implicitly as result)
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
‚ïí‚ïû\!+
```
[Try it online.](https://tio.run/##y00syUjPz0n7///R1EmPps6LUdT@/9@Yy5TLyBAA)
**Explanation:**
```
‚ïí # Push a list in the range [1, (implicit) input]
‚ïû # Remove the first value to make the range [2,input]
\ # Swap to push the (implicit) input
! # Take its factorial
+ # Add it to each value in the list
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~52 51 47 46 45~~ 44 bytes
```
f=(n,i=n)=>--n&&f(n,g=i*n)>console.log(n-~g)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9mC0QaeTqZtnmatna6unlqamlAbrptplaepl1yfl5xfk6qXk5@ukaebl265v80DcM8TWsFZAlNa640DSOsosZYRU2xmwA0@D8A "JavaScript (Node.js) – Try It Online")
-1 byte from Arnauld/tsh
# [JavaScript (Node.js)](https://nodejs.org), 38 bytes by Mukundan314
```
f=(n,i=n)=>--n?[...f(n,g=i*n),n-~g]:[]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfTNk/T1k5XN88@Wk9PLw0okm6bqZWnqZOnW5ceaxUd@z85P684PydVLyc/XSNNwzBPU9NaAVlM05oLVYkRYSXGhJWYEmERyDH/AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Desmos](https://desmos.com), 10 bytes
```
[2...n]+n!
```
[Try it in Desmos!](https://www.desmos.com/calculator/esdiw4nlkb?)
The simplest a solution can get, to be honest.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
RḊ+!
```
[Try it online!](https://tio.run/##y0rNyan8/z/o4Y4ubcX///8bGgEA "Jelly – Try It Online")
Port of [Vyxal answer](https://codegolf.stackexchange.com/a/269334/106959).
-1 byte thanks to [@emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a)
Explanation:
```
RḊ+!­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌­
RḊ # ‎⁡[2 .. n]
+! # ‚Äé‚Å¢+ n!
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [JavaScript (V8)](https://v8.dev/), 46 bytes
Prints the results in reverse order.
```
n=>{for(p=i=n;--i;)p*=i;while(--n)print(p-~n)}
```
[Try it online!](https://tio.run/##JcgxCoAwDADA3Vc4JkImEYQQ/1LEYkRiqKUOol@vgzfeFko456SeqYw1SjWZ7ngkcFExJlJG70T5WnVfgMjQk1oGp9fwqRF65PYv5CbCgPUD "JavaScript (V8) – Try It Online")
---
# JavaScript (ES11), 52 bytes
With BigInts.
```
n=>{for(p=i=n;--i;)p*=i;while(--n)console.log(p-~n)}
```
[Try it online!](https://tio.run/##bcmxCoNADADQ3a/omAgRtDiF9F/E3mnkSA4tdSj118/VwfW9ZfgO27hq/pD5O5QoxeT1i75CFhVjImXMtSjvs6YARIaj2@YpNMknyHQY/kuEpyE/roNcRehvtWsNywk "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](https://www.jsoftware.com), 7 bytes
```
!-<:$i:
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxXFHXxkol0wrCu6miyZWanJGvkKZgXAFjmUJZJgqmKmkKRoYVELULFkBoAA)
Returns the list of numbers in reverse order. When given a bigint, outputs the exact numbers in bigint.
```
!-<:$i: input: n, a positive integer
i: [-n, -n+1, ..., n]
<: n-1
$ take first n-1 items from the list, i.e. [-n, ..., -2]
! n!
- n! - each item of [-n, ..., -2]
== [n!+n, n!+n-1, ..., n!+2]
```
# [J](https://www.jsoftware.com), 8 bytes
```
!+-.{.i:
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxQlFbV69aL9MKwr2posmVmpyRr5CmYFwBY5lCWSYKpippCkaGFRC1CxZAaAA)
Returns the list of numbers in the order given.
```
!+-.{.i: input: n, a positive integer
i: [-n, -n+1, ..., n]
-. 1-n
{. since 1-n is negative, take n-1 items from the end;
[2, ..., n]
!+ add n! to each item of the list
```
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 9 bytes
```
‚Üò1+/√ó.+1‚á°
```
[Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAg4oaYMSsvw5cuKzHih6EKCmYgMwpmIDUK)
[Answer]
# [Perl 5](https://www.perl.org/), 41 bytes
```
sub{@a=1..pop;$"='*';map$_+1+eval"@a",@a}
```
[Try it online!](https://tio.run/##PZBRa4MwFIXf/RWHEFadwZlU12lw@Af2trd1iKVRBI2idkNKf7tLVrfzcC757j03JIMa23i9TArvaprT9K0flXTs@dTUjZ6l0y2gVbZOl9M1LzMeBEM/SEqy3eNOduVAC5/76qtsSV4Slpe3VTpVP7oOjD6wR/aKF4aEgYefbKOxpVwIA8XeWmQttvaM/ynB7Zi5AzEPkzCJBD/wg6lRaAQftGAQCAIIYVPe9TfYLS7VDPl3qWcPGXJayK2BvO5ngx5o5YJqePeGeQ2hT9hE7rCZirNSQ7u4ONoYM8WuZCA6tWHA0PSo/3J2iNiVN@fca1XM5kMbXcv1Bw "Perl 5 – Try It Online")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~56~~ 54 bytes
```
[dlf*sf1-d0!=q]sq1sf?d1-sm[dlf2++p0=m1+dlm!=e]selqxlex
```
[Try it online!](https://tio.run/##S0n@/z86JSdNqzjNUDfFQNG2MLa40LA4zT7FULc4FyRjpK1dYGCba6idkpOraJsaW5yaU1iRk1rx/7@RIQA)
This solution isn't the most optimized, you could probably use less registers than I did here.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~69~~ 62 bytes
```
lambda n:[i-~math.factorial(n)for i in range(1,n)]
import math
```
[Try it online!](https://tio.run/##RcqxCsIwEIDhvU9xWxKJQi2CBPokbYdTG3vQXI70HFx89YhL3X5@Pnnrkrm7SqmxH@uK6fZA4DDQ8ZNQl1PEu@ZCuFp2MRcgIIaC/Jxt69lNDSXJReGH6w6Gzl/8uZ1CAyCFWK3byxDLS4Px9H@HaMn5bZbejGxc/QI "Python 3.8 (pre-release) – Try It Online")
Edit: changed `math.prod` to `math.factorial`, thanks to @l4m2
[Answer]
# Google Sheets, 32 bytes
```
=SORT(FACT(A1)+SEQUENCE(A1-1)+1)
```
[Answer]
# C (gcc), 170 bytes
Using The GNU Multiple Precision Arithmetic Library
```
f(n){mpz_t f,t;mpz_init(f);mpz_init(t);mpz_set_ui(f,1);for(int i=1;i<=n;mpz_mul_ui(f,f,i++));for(int i=2;i<=n;mpz_add_ui(t,f,i),mpz_out_str(stdout,10,t),puts(""),i++);}
```
[Try it online!](https://tio.run/##ZZDBCoJAEIbvPYXYZYbWyKLTWk8SiKyNDegq7ixB0au3rXUw6vbx8fEzjMkaY8KSrWl9fU4KJzX368txMaumG6IIBBbv3XArJSEleiK2LEA4s3zYnaX0DKRy1NSPwFYSPuSai4N9B51vPwEpXq3wu9rOVVXXUyVThWoyvZfSyQjxyogq3yhBNXhxkKb4ntKP0FVsAe8Lgh3qYYyzBOnJpqij2v@rbf7rHuFpqK0aF7JryNr4gBc)
[Answer]
# [Scala 3](https://www.scala-lang.org/), 55 bytes
```
n=>{val a=(1 to n).map(BigInt(_));a.map(_+1+a.product)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVFNT-MwEBXX_oonqwdbDVWTtpRmlUrAiQMn2FOpKm-alLLtpMTmS1V_CZdelgt3_gv8GsZOila7ljKTmffm49kvrybVS919G4tDKh51SWLy0Sp-3WapxYVeEDYN4EEvkceQ52ST0WV2Nz5dzPl_opD8ubf54fHHgJLRxtF0IkPYAqTaK72WFVFOlfqhfWLaClu6vS6L2X1q1bYq_zx4B2ZZjhVPlLqcmxgnZamfx5e2XNB8omL8pIVF4tepFrKZsWfaZIazvJP0ACC7gQ-PAwwDhB2lgj3Sr5AwihiIus70nOk7c_QXMQoDNk5GFFU6npCMUIsR_bAz7Ax7UTgIB-x7HT5CoYUnpXwL1fDue8N2XpSZTm-wQcoxJAV41GT5_kb1TKdoXjiFuSRVJ9cs3i5JGkFJc0Nb8S_AFe3V7-qSpLgmofYMbUxWWulbJn5YAG4To0mMcjq-JtSnyeF_rY244vWxdo1mYAHwxTVv23Bf_Xy7XeW_AA)
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 15 bytes
```
n->[n!+2..n!+n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboW6_N07aLzFLWN9PSAZF4sRPSmTmJBQU6lRoWCrp1CQVFmXgmQqQTiKCmkaVRoauooRBvrKJjqKBgZxmpC9CxYAKEB)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes
```
#!+2~Range~#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X1lR26guKDEvPbVOWe1/QFFmXomCQ3q0kWHs//8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 43 bytes
```
.+
*
v`__+
$.&$*
L$`\d+
$$.($&*_$=
%~`^
.+¶
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4urLCE@XptLRU9NRYvLRyUhJgXIUdHTUFHTilex5VKtS4jj0tM@tO3/fyNDAA "Retina – Try It Online") Outputs the numbers in descending order. Explanation:
```
.+
*
```
Convert `n` to unary.
```
v`__+
$.&$*
```
Create an expression `n*...*3*2*` that evaluates to `n!` in unary.
```
L$`\d+
$$.($&*_$=
```
For each integer in that expression, create an expression that adds `i` and converts to decimal.
```
%~`^
.+¶
```
Evaluate each resulting expression.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
≔…·²NθI⁺θΠθ
```
[Try it online!](https://tio.run/##Dco7DoAgDADQ3VMwlgQHWZ2Mk4sh3qAiURKs8vP6lTc/e2GyDwbmKWd/EixkQ83@cxvS6UArsdBby1rv3SWQUokox84kTwVmzAVM6xCVMOk5qi0QZTMy64H7L/w "Charcoal – Try It Online") Link is to verbose version of code.
```
≔…·²Nθ
```
Create a list from `2` up to `n` inclusive.
```
I⁺θΠθ
```
Vectorised add the list to its product.
Of course, the given formula is just an existence proof and there are usually lower runs. For instance, the LCM is readily proven to produce a run:
```
Nθ≔…·²θηW⌈﹪±θη≧⁺ιθI⁺θη
```
[Try it online!](https://tio.run/##Jcw7DsMgEEXR3qugHCRSxC1VlMqFLcs7mBAEIwE2Pye7J45on@47ymJSO7rWpnDUslT/0gkil8MjZzIBpqBczXTqDYPRMAoWuWD2Cj6WnGYw45d89TDv7@p2WLTBoqFHnLMZjy5tZGyB9cIEo78ihzVRKPDE3HeI/SNbu4/tdrof "Charcoal – Try It Online") Link is to verbose version of code. Or more efficiently:
```
Nθ≔…·²θηFη≔⌊Φ×⊖ηθ¬﹪κιθI⁺θη
```
[Try it online!](https://tio.run/##LY3NDoIwEITvPEWP2wQPcuVkNCYcIMT4ArWssLHdQn94/Vqic51v5tOL8topk3PHa4pDsi/0sMm2uoRAM0PH2qRAOz4UzwhNLTZZi6UAb@cFLFL8wZ6YbLJwJxPLxZMsBrih9miRI04F/W0HF6F3UzIOPrUgWXIUbTV64ghXFSKMxQnb4ZGyzbk559Nuvg "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# Java 10, ~~134~~ 131 bytes
```
n->{var f=n.ONE;int N=n.intValue(),i=N;for(;i>1;)f=f.multiply(n.valueOf(i--));for(;i++<N;)System.out.println(f.add(n.valueOf(i)));}
```
-3 bytes thanks to *@ceilingcat*.
Input as a `BigInteger`, outputs on separated lines to STDOUT.
[Try it online.](https://tio.run/##bVA9b4MwFNzzK54y2QIspVWXOmRo1aFDyRCpS5ThFWxqagzChipC/HZqUyp1iAd/6N2d767CAZOq@JpzjdbCGyozbgCUcaKTmAvIwhNgaFQBOak8nNXoPtmTKl89qBQdGMo9Ztr4zTp0KocMDKSzSQ7jgB3I1LBj9sK9KGT@7s931L0gNFZpxmXTEa4OO05lKlnda6dafSWGDQF0lEQlCaUrLIr2Gaenq3WiZk3vWNt5OW2IZFgU/0nUc6aZB1dt/6G9q9XcEqX2QcnJeXJ5viD9DRm@CCadsO4ZrXg04jtUcb6M9/FDfLebViCAYTkJ01uFkO02@pOgSzdh3fC8zqalvWn@AQ)
**Explanation:**
```
n->{ // Method with BigInteger as parameter and no return:
var f=n.ONE; // Start `f` with BigInteger 1
int N=n.intValue(), // Set `N` to the input-BigInteger as integer
i=N;for(;i>1;) // Loop `i` in the range [N,1):
f=f.multiply(n.valueOf(i)); // Multiply `f` by `i`
for(;i++<N;) // Loop `i` again, this time in the range (1,N]:
System.out.println( // Print with trailing newline:
f.add(n.valueOf(i)));} // `f` + `i`
```
[Answer]
# [Labyrinth](https://github.com/m-ender/labyrinth), 30 bytes
```
?:} @\!
(:{+ ""
*; :=;;
#(;)
```
[Try it online!](https://tio.run/##y0lMqizKzCvJ@P/f3qpWQcEhRpFLQcOqWltBSYlLy1rBytbamktZw1rz/3/Tf/kFJZn5ecX/dVMA "Labyrinth – Try It Online")
Introducing "small-loop-oriented programming" ;)
```
? program start; take n from stdin
let's say n = 4
[ 4 | ]
:} run in the order of :(:}
(: : dup [ 4 4 | ]
( decrement [ 4 3 | ]
: dup [ 4 3 3 | ]
} move to aux.stack [ 4 3 | 3 ]
loop until the top is 0 after `decrement`
[ 4 3 2 1 0 | 1 2 3 ]
*; run in the order of ;*#(
#( ; drop [ 4 3 2 1 | 1 2 3 ]
* mul [ 4 3 2 | 1 2 3 ]
# stack height [ 4 3 2 3 | 1 2 3 ]
( decrement [ 4 3 2 2 | 1 2 3 ]
loop until the top is 0 after `decrement`, i.e. stack height is 1
[ 24 0 | 1 2 3 ]
;) drop 0, and increment the factorial
[ 25 | 1 2 3 ]
{+ run in the order of :=+{
:= : dup [ 25 25 | 1 2 3 ]
= swap the tops [ 25 1 | 25 2 3 ]
+ add [ 26 | 25 2 3 ]
{ move from aux.stack [ 26 25 | 2 3 ]
loop until the top is 0 after `swap the tops`
[ 26 27 28 25 0 | 25 ]
;; drop twice [ 26 27 28 | 25 ]
\! run in the order of ""!\ (" is no-op)
"" ! pop and print as num
\ print a newline
loop until the top is zero, i.e. there is nothing left to print
@ end the program
```
] |
[Question]
[
In this exercise, you have to analyze records of temperature to find the closest to zero.
Write a program that prints the temperature closest to 0 among input data.
## Input
* N, the number of temperatures to analyse (optional). This will be nonzero.
* The N temperatures expressed as integers ranging from *-273 to 5526*.
## Output
Output the temperature closest to 0. If two temperatures are equally close, take the positive one. For instance, if the temperatures are -5 and 5, output 5.
## Example
```
Input
5
1 -2 -8 4 5
Output
1
```
[This challenge is similar to this one on CodinGame, you can view the problem statement source here.](https://github.com/GlenDC/Codingame/blob/master/descriptions/temperatures.md)
Some modifications have been made to the text.
[Answer]
# [Python](https://docs.python.org/2/), 35 bytes
```
lambda l:max((-x*x,x)for x in l)[1]
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQY5WbWKGhoVuhVaFToZmWX6RQoZCZp5CjGW0Y@7@gKDOvRCFNI1rXSMdQR9cwVpMLWchIxyRW8z8A "Python 2 – TIO Nexus")
Narrowly beats:
```
lambda l:min(l,key=lambda x:2*x*x-x)
lambda l:min(sorted(l)[::-1],key=abs)
```
[Answer]
## JavaScript (ES6), 33 bytes
```
a=>a.reduce((m,n)=>n*n-n<m*m?n:m)
```
### Demo
```
let f =
a=>a.reduce((m,n)=>n*n-n<m*m?n:m)
console.log(f([1, -2, -8, 4, 5]))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
AÐṂṀ
```
[Try it online!](https://tio.run/nexus/jelly#@@94eMLDnU0Pdzb8P9z@qGmN@///0YY6CrpGQGyho2Cio2Aaq6MQDcKmQCHTWAA "Jelly – TIO Nexus")
### How it works
```
AÐṂṀ Main link. Argument: A (array)
AÐṂ Take all elements with minimal absolute value.
Ṁ Take the maximum. Yields 0 for an empty list.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (2), 5 or 2 bytes
```
~{≜∈}
```
[Try it online!](https://tio.run/nexus/brachylog2#@19X/ahzzqOOjtr//6N1TXVMdcx0dA2NYv9HAQA "Brachylog – TIO Nexus")
It wouldn't surprise me if there were a shorter solution along the lines of the Jelly or Pyke, but I like this one because it's so weird.
This is simply Brachylog's "find a list containing the input" operator `∈`, with an evaluation strategy `≜` that simply tries explicit values for integers until it finds one that works (and it happens to try in the order 0, 1, -1, 2, -2, 3, etc., which is surprisingly handy for this problem!), and inverted `~` (so that instead of trying to find an output list containing the input, it's trying to find an output contained in the input list). Unfortunately, inverting an evaluation strategy along with the value itself costs 2 bytes, so this doesn't beat the Jelly or Pyke solutions.
There's also a dubious 2-byte solution `≜∈`. All Brachylog predicates take exactly two arguments, which can each be inputs or outputs; by convention, the first is used as an input and the second is used as an output, but nothing actually enforces this, as the caller has complete control over the argument pattern used (and in Prolog, which Brachylog compiles to, there's no real convention about argument order). If a solution which takes input through its second argument and produces output through its first argument is acceptable, there's no requirement to do the inversion.
[Answer]
# [R](https://www.r-project.org/), 31 bytes
```
(l=scan())[order(abs(l),-l)][1]
```
[Try it online!](https://tio.run/##K/r/XyPHtjg5MU9DUzM6vygltUgjMalYI0dTRzdHMzbaMPa/rqmC6X8A "R – Try It Online")
[Answer]
## Pyke, 4 bytes
```
S_0^
```
[Try it online!](https://tio.run/nexus/pyke#@x8cbxD3/7@uoY4CEOkaAbGFjoKJjoIpAA "Pyke – TIO Nexus")
```
S_ - reversed(sorted(input))
0^ - closest_to(^, 0)
```
[Answer]
# Mathematica, ~~21~~ 19 bytes
```
Max@*MinimalBy[Abs]
```
Composition of functions. Takes a list of integers as input and returns an integer as output.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~9~~ 6 bytes
```
0iSPYk
```
[Try it online!](https://tio.run/nexus/matl#@@@fGRwQmf3/f7SuqYJpLAA "MATL – TIO Nexus")
Thanks to Luis Mendo for pointing out there's actually a built-in for this in MATL, which is not present in MATLAB.
```
i % Take input
S % Sort
P % Reverse to have largest value first.
0 Yk % Closest value to zero, prioritizing the first match found
```
If you wish to follow the spec and also provide the number of temperatures to be read, this should be given as the second input, and will be silently discarded.
[Answer]
# C++14, 64 bytes
As unnamed lambda, expecting first argument to be like `vector<int>` and returing via reference parameter.
```
[](auto L,int&r){r=L[0];for(int x:L)r=x*x<=r*r?r+x?x:x>r?x:r:r;}
```
Ungolfed and usage:
```
#include<iostream>
#include<vector>
auto f=
[](auto L,int&r){
r=L[0];
for(int x:L)
r = x*x<=r*r ? //x is absolute less or equal
r+x ? //r==-x?
x : //no, just take x
x>r ? //take the positive one
x :
r :
r //x was absolute greater, so keep r
;
}
;
int main(){
std::vector<int> v = {5, 2, -2, -8, 4, -1, 1};
int r;
f(v,r);
std::cout << r << std::endl;
}
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 21 bytes
Added `+1` for `-p` since this challenge precedes "options don't count"
```
$G[abs]=$_}{$_+="@G"
```
[Try it online!](https://tio.run/##K0gtyjH9/1/FPToxqTjWViW@tlolXttWycFd6f9/Cy4TYy5dEy5TIPyXX1CSmZ9X/F@3AAA "Perl 5 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-g`, 3 bytes
```
ña¼
```
[Try it online!](https://tio.run/##y0osKPn///DGxEN7/v@PNlUwVNA1UtC1UDBRMI3l4tJNBwA "Japt – Try It Online")
# [Japt](https://github.com/ETHproductions/japt), 5 bytes
```
ña¼ v
```
[Try it online!](https://tio.run/##y0osKPn///DGxEN7FMr@/4/WNVUwjQUA "Japt – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
Îåà_Di¹{RDÄßs\kè
```
Explanation:
```
Î Push 0 and [implicit] input array
å For each element in the array, is it a 0?
à Find the greatest value (1 if there was a 0 in it, 0 otherwise)
_ Negate boolean (0 -> 1, 1 -> 0)
D Duplicate
i If true, continue
¹ Push input
R Reversed
D Duplicated
Ä Absolute value
ß Greatest element
s Swap top two values in stack
\ Delete topmost value in stack
k Index of greatest element in the array
è Value of the index in the input array
```
[Try it online!](https://tio.run/nexus/05ab1e#@3@47/DSwwviXTIP7awOcjnccnh@cUz24RX//0frmugo6BoBsYWOApBpCmQBKSMw0jWMBQA "05AB1E – TIO Nexus")
Not at short as I'd like, but at least it works.
[Answer]
## Haskell, 29 bytes
```
snd.maximum.map(\x->(-x^2,x))
```
Usage example: `snd.maximum.map(\x->(-x^2,x)) $ [1,-2,-8,4,5]`-> `1`.
Map each element `x` to a pair `(-x^2,x)`. Find the maximum and pick the 2nd element from the pair.
[Answer]
# PHP, 81 bytes
two solutions: the first one requires an upper bound; both require all temperatures nonzero.
```
for($r=9e9;$t=$argv[++$i];)abs($t)>abs($r)|abs($t)==abs($r)&&$t<$r?:$r=$t;echo$r;
for(;$t=$argv[++$i];)$r&&(abs($t)>abs($r)|abs($t)==abs($r)&&$t<$r)?:$r=$t;echo$r;
```
Run with `-r`, provide temperatures as command line arguments.
A lazy solution for **92 bytes**:
```
$a=array_slice($argv,1);usort($a,function($a,$b){return abs($a)-abs($b)?:$b-$a;});echo$a[0];
```
defines a callback function for [`usort`](http://php.net/usort) and uses it on a slice of `$argv`.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 15 bytes
```
*.min:{.²,-$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfSy83M8@qWu/QJh1dlfja/9ZcxYmVCmkaKvGaCmn5RVwahjq6Rjq6FjomOqaaOlwaRgiujq4hSEQXSYWOoab1fwA "Perl 6 – Try It Online")
[Answer]
# Java 8, ~~63~~ 39 bytes
```
s->s.reduce(1<<15,(r,i)->r*r-r<i*i?r:i)
```
Port from [*@Arnauld's* JavaScript answer](https://codegolf.stackexchange.com/a/112039/52210). I couldn't find anything shorter..
-10 bytes converting Java 7 to 8,
and another -24 bytes thanks to *@OlivierGrégoire*.
**Explanation:**
[Try it online.](https://tio.run/##rY/BbsIwDEDv/QofE5RE6zakCTqmHXcYF46IQ5YG5K4NyEmZEOq3d25BaPdxcBQn9vNzZY9WV@V372obI3xaDOcMAEPytLXOw3JIxwdwouJq0yasTUzkbWM@QlqNN4hyzoVdxkdMNqGDJQR4hT7qRTTky9Z5kRdFPlWCFEq9oAlpKnCCbzRD2c@H1kP7VXPrlXDcYwkNKwkegmG33lh50VmdYvKN2bfJHPgn1UEE89fvncie4lVTBP8zbLDenCFXoB85XhQ8K5hCJ@Vo/h/mALw7k0UfFOR3E3y6kbqs638B)
```
s-> // Method with IntStream parameter and int return-type
s.reduce(1<<15, // Start `r` at 32768 (`32768^2` still fits inside a 32-bit integer)
(r,i)->r*r-r<i*i?// If `r^2 - r` is smaller than `i^2`:
r // Leave `r` the same
: // Else:
i) // Replace the current `r` with `i`
// Implicitly return the resulting `r`
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 30 bytes
```
a=>a.sort((a,b)=>a*a-a>b*b)[0]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@TWqKQpmD7P9HWLlGvOL@oREMjUSdJE8jTStRNtEvSStKMNoj9n5yfV5yfk6qXk5@ukaYRbaijoGsExBY6CiY6CqaxmppcaCp0jcyNgZLGWKRMgRpNsGkxxW4USD1I/D8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 28 bytes
```
@(x)max(x(min(a=abs(x))==a))
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzN7FCo0IjNzNPI9E2MakYKKJpa5uoqfk/TSNawVBB10hB10LBRME0VvM/AA "Octave – Try It Online")
Finds the smallest absolute value (`min(a=abs(x))`), then maps it back to which elements have that smallest absolute value in case of a tie (`x(...==a)`). Finally takes the maximum value of the results (`max(...)`) to ensure that in the event of a tie we get one result which is the positive one.
[Answer]
## PHP, 209 Bytes
**Not really golfed**, but wanted to try to use mostly array functions, avoiding loops
[Try it Online!!](https://tio.run/##VY9BCoMwEEWv0kWQhEbQUjeN4kFCKGk6QVGMTEyhFM9u09guuhn@f/NgmLmbt7qd47RhMkvvpoOlRLMX0VI1hfAOl08XZGg0on5ePWg0HS14ou5Hx95AFDkZjmXk4csRHoAe6N7uvbVJcoyJPsYgS5VlxMlCxZPYUH3zO2V1imnD2oQuqYkVRg9J3sX/JcIScCIo1g1M5@I3Mq94fuJ5yc@84pViYnsD)
**Code**
`function f($a){$a[]=0;sort($a);$k=array_search(0,$a);$o=array_slice($a,$k+1);$u=array_reverse(array_diff($a,$o));if($u[1]&&$o[0]){$r=(abs($u[1])<abs($o[0]))?$u[1]:$o[0];}else{$r=($u[1])?$u[1]:$o[0];}return$r;}`
**Explanation**
```
function f($a){
$a[]=0; #As all nonzero values, 0 is pushed
sort($a); #Sorting the array
$k=array_search(0,$a); #Search where zero is
$o=array_slice($a,$k+1); #Array with all values >0
$u=array_reverse(array_diff($a,$o)); #Array with all smaller than zero values
#Array has ascending order so it gets reversed
if($u[1]&&$o[0]){ #if both are set we just compare the abs value
$r=(abs($u[1])<abs($o[0]))?$u[1]:$o[0];
}else{
$r=($u[1])?$u[1]:$o[0]; #al least one of them will allways be set
#the first value is always returned
#the 0 value on $u is not usetted that why $u[1]
}
return $r;
}
```
[Answer]
# [Julia 0.6](http://julialang.org/), 29 bytes
```
x->sort(x,by=x->abs(x-.1))[1]
```
Sort by the absolute value of the temperature, but subtract .1 first to ensure positive temperatures always win.
[Try it online!](https://tio.run/##yyrNyUw0@59mm5Sanpn3v0LXrji/qESjQiep0hbISUwq1qjQ1TPU1Iw2jP2fmpfC5VCckV@ukKYRbaRjrGMSq4kmoKNrhCwGE/kPAA "Julia 0.6 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{R0.x
```
[Try it online.](https://tio.run/##yy9OTMpM/f@/OshAr@L//2hDHV0jHV0LHRMd01gA)
Or alternatively:
```
ÄWQÏà
```
[Try it online.](https://tio.run/##yy9OTMpM/f//cEt44OH@wwv@/4821NE10tG10DHRMY0FAA)
**Explanation:**
```
{ # Sort the (implicit) input-list lowest-to-highest
R # Reverse it to highest-to-lowest
0.x # Pop and push the item closest to 0
# (after which the result is output implicitly)
Ä # Get the absolute value of each in the (implicit) input-list
W # Push the minimum (without popping the list)
Q # Check which are equal to this minimum
Ï # Only keep the values in the (implicit) input-list at the truthy indices
à # Pop and push the maximum of the remaining values
# (after which the result is output implicitly)
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `h`, 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ṠrþA
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVFMSVCOSVBMHIlQzMlQkVBJmZvb3Rlcj0maW5wdXQ9MSUyQy0yJTJDLTglMkM0JTJDNSZmbGFncz1o)
#### Explanation
```
ṠrþA # Implicit input
Ṡr # Reverse-sort
þA # Sort by |x|
# Take the first item
# Implicit output
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 20 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 2.5 bytes
```
⁽ȧP
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJHPSIsIiIsIuKBvcinUCIsIiIsIls3LDIsLTIsOTEsNV0iXQ==)
Finds the minimum in the list by absolute value
[Answer]
# Python, 62 bytes
```
def f(n):
r=min(map(abs,n))
return r if r in n else -r
```
It feels like there is a much simpler/shorter solution.
[Answer]
# [C (clang)](http://clang.llvm.org/), 74 bytes
```
k,m;f(*i,n){for(k=*i;--n>0;k=(k*k>m*m||(k==-m&&k<m))?m:k)m=i[n];return k;}
```
[Try it online!](https://tio.run/##RY5RS8QwEITf8yuWOzyyJdF6KIi51B9S@xDaRJc0W8n1HrTX314jiMI8zCwfO9PrfnT8tu2J@/EyeDid54Gm2/dmiyqZICtSjEuYsoy2IqM1N7WJVsYqNqlK12u5W50Oh3hKiC/pOWKy1HJnsp8vmSGadRP7wQdiDy5n9zl6lg5ByjN9@SkUj3d/vq07RBSCeIbkiCXCIgT8RGo7sLDoewVF@qigSD8peFDwuJpCfeTCBbm7GV55pyBIUv@VVP4W6HdWbcS6fQM "C (clang) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
¢M║⌠§☺
```
[Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=9b4dbaf41501&i=[-4+5+4+-1+6+-8+1]&a=1)
### Unpacked (6 bytes) and explanation
```
{|a}eoH
{ }e Get all elements of array producing the minimum value from a block.
|a Absolute value.
o Sort ascending.
H Take last. Implicit print.
```
[Answer]
# Pyth, 4 bytes
```
.m.a
```
[Try it online!](https://tio.run/##K6gsyfj/Xy9XL/H//2hDHV0jHV0LHVMdk1gA)
Explanation:
```
.m.a #Code
.m.abQ #With implicit variables
.m Q #Filter input list for values b with minimal value of the following:
.ab #Absolute value of b
```
[Answer]
# [Python 3](https://docs.python.org/3/), 31 bytes
```
a=lambda q:sorted(q,key=abs)[0]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9E2JzE3KSVRodCqOL@oJDVFo1AnO7XSNjGpWDPaIPb/fwA "Python 3 – Try It Online")
Sorts items by absolute value and prints the first element.
[Answer]
# [Avail](http://www.availlang.org/), 88 bytes
```
Method"f_«_»"is[c:[1..∞),t:integer*|quicksort a,b in t[1..c] by[|a-0.1|<|b-0.1|][1]]
```
Approximate deobfuscation:
```
Method "nearest to zero among first _ of «_»" is
[
count : natural number,
temps : integer*
|
(quicksort a, b in temps[1..count] by [|a-0.1| < |b-0.1|])[1]
]
```
The [pattern syntax](http://www.availlang.org/about-avail/learn/quick-start.html#methods-message-pattern-language) in the method's name, `f_«_»`, will read the initial count as a natural number (whose type is abbreviated above as the range type `[1..∞)`) separate from the collected tuple of subsequent integers.
All that remains for the body is to [sort by a custom comparator](http://www.availlang.org/about-avail/documentation/stacks/library-documentation/avail/Avail/Foundation/Tuples/2169357673.html). Here we escape the need for a second-level comparison between `x` and `-x` by shifting the values slightly towards -∞.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 53 bytes
```
Fd^sr[d*v]sA[ddlr+0=Asr]sR[dlAxlrlAx!<Rs_z0<M]dsMxlrp
```
[Try it online!](https://tio.run/##DcihDoAgEIDhVzmrFkAR2TBQbBQqQ4IXCY7bnPPl8cq3fz9efdFQFgVlkyClBU4zg1QzXyEYC1qbFfqBJ7WE45PJJ8TaJrF7apliwurf2pjBRSqfcCEjBV537z8 "dc – Try It Online")
We're going to use the register `r` to hold our final result, so the first thing we need to do is put a too-big number in there so that our first comparison always succeeds. I think the largest number we can push in two bytes is 165 (which is less than the required 5526), but `Fd^` gives us 15^15 which is plenty large. Macro `A`, `[d*v]sA` just does the square root of the square to give us absolute value.
Macro `R` handles putting a value into register `r`; we'll come back to it in a second. Macro `M`, `[dlAxlrlAx!<Rs_z0<M]dsMx` is our main macro. Duplicates the value on the stack, runs `A` to get ABS, then pushes the value in `r` and does the same. `!<R` checks to see if ABS(`r`) is ~~greater than or equal to~~ not less than ABS(top of stack), and if so it runs `R`. Since we had to leave behind a copy of the original top of stack for `R` to potentially use, we store to a useless register (`s_`) to pop it. `z0<M` just loops `M` until the stack is empty.
Macro `R`, `[ddlr+0=Asr]sR` duplicates the top of stack twice (we need to leave something behind for `M` to gobble up when we return). At this point we know that of the two absolute values, our new value is less than or equal to our old value. If they're equal, and one is positive and the other is negative, we always need the positive. Fortunately, knowing this we can easily check for the case of one being the inverse of the other by simply adding them and comparing to 0. If so, we run `A`, and no matter what else happened we know we're storing whatever is left in `r`.
After `M` has gone through the whole stack, we `l`oad `r` and `p`rint it.
] |
[Question]
[
Web safe colors are in intervals of 51, they include 0, 3, 6, 9, c, and, f as digits in hex (such as #993333), or 0, 51, 102, 153, 204, 255 in decimal. Your task today is convert a given color to a web safe one. You may [read more about web safe colors on Wikipedia](https://en.wikipedia.org/wiki/Web_colors#Web-safe_colors).
**Input**
You will take in 3 integers between 0, 255 inclusive representing red, green, and blue values.
**Output**
Output the converted 3 integers, as an array or similar structure.
**Rules**
* answers must be rounded to the nearest value, not floor or ceiling. (25 -> 0 and 26 -> 51)
* As this is code golf, lowest bytes wins.
**Test Cases**
```
Input Output
(0, 25, 76) (0, 0, 51)
(1, 26, 77) (0, 51, 102)
(127, 178, 229) (102, 153, 204)
(128, 179, 230) (153, 204, 255)
(0, 254, 255) (0, 255, 255)
(9, 143, 53) (0, 153, 51)
```
I'm sure these answers will be pretty short; this is an easier question meant for those more novice at code golf, however feel free to answer regardless of your skill/experience.
[Answer]
# Japt, 4 bytes
```
mr51
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=bXI1MQ==&input=WzEyNywxNzgsMjI5XQ==)
Input and output is a 3-item array.
Just `m`aps each item `r`ounded to the nearest multiple of `51`.
[Answer]
# [Taxi](https://bigzaphod.github.io/Taxi/), 1015 bytes
```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Tom's Trims.[a]Go to Tom's Trims:n.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Divide and Conquer.51 is waiting at Starchild Numerology.51 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 1 l 2 l.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Multiplication Station.Go to Divide and Conquer:w 1 r 3 r 1 r 2 r 1 r.Pickup a passenger going to Rounders Pub.Go to Rounders Pub:e 1 r 1 r 1 l.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:n 1 r 1 r 1 l 1 r.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 r 1 l.Pickup a passenger going to Post Office.' ' is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 1 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.Switch to plan "a".
```
[Try it online!](https://tio.run/##rZM/T8MwEMX3fopTl2yRGlSQMkIlJiCilRgQg5tckhOOHc4OoZ8@5B8otFHSSgyWpfPz88@@Zyu@qKruNVgNgTYWnuKYQvRLWIGsBzezG1D4XuQgIBfGoEqQIdGkkmbXTmeOgR1TZv5d9yreOrRB0VfT21OEW7FHGZNJkQ9ub3BU9s3PBSfdNvRJEYJQEdxp9VEgu@sVkIFSkG00wsLWCg5TkhE8Fhmyljo5nKnq2MaWfNXzdcObacII55T8oZCWckmhsKRVA9DMPc6pV5sGhqs2DVzD8OzDPetCRcgGgmLf@w5LPvbZms/XJOv4Yvt4v@6zrJdEZp538ItcB5yjGLwwWeQ6yxvMte1P@lsctN674KzTP6wG3ZLutiQbpo0ml0LBUizdqvIW3npxc/0N "Taxi – Try It Online")
Un-golfed:
```
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to Tom's Trims.
Pickup a passenger going to Tom's Trims.
Pickup a passenger going to Tom's Trims.
[a]
Go to Tom's Trims: north.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Divide and Conquer.
51 is waiting at Starchild Numerology.
51 is waiting at Starchild Numerology.
Go to Starchild Numerology: north 1st left 1st left 1st left 2nd left.
Pickup a passenger going to Divide and Conquer.
Pickup a passenger going to Multiplication Station.
Go to Divide and Conquer: west 1st right 3rd right 1st right 2nd right 1st right.
Pickup a passenger going to Rounders Pub.
Go to Rounders Pub: east 1st right 1st right 1st left.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: north 1st right 1st right 1st left 1st right.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st right 1st left.
Pickup a passenger going to Post Office.
' ' is waiting at Writer's Depot.
Go to Writer's Depot: north 1st left 1st left 2nd left.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.
Switch to plan "a".
```
You can't detect if someone is waiting at `Post Office` so you start by picking up the three passengers and moving them. Divide each by 51, round, multiply by 51, and output.
[Answer]
# [Python 2](https://docs.python.org/2/), 33 bytes
```
lambda c:[(n+25)/51*51for n in c]
```
[Try it online!](https://tio.run/##LYvBCoMwEETP9Sv2mLQLNYlrVOjJz7AerCVUsKuIF78@Jmkvw7w3zHrsn4W1d4@nn4fv6z3A2HSCb5rkndSVlFs2YJgYxt7H3sbeiRxBE4ItJWYXoQKVgeyPtEVQtgpS139TRVMHY/Jk0r@IQYnDpAqDQEb2TQbrNvEOTrTSnw "Python 2 – Try It Online")
[Answer]
# MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~18~~ 13 bytes
```
@(x)51*(x/51)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0LT1FBLo0Lf1FDzf5pGaWZeiYVGtIGCgo6CkSmQMDdTiNXU5ILLGIJlzEAy5mgyRuY6CobmFkBpI0s0GQuQjCVQxtgARQZqjwmIMEWRsQTJGJoY6yiYGoPs@Q8A "Octave – Try It Online")
Takes an array of type `uint8` with three values (R,G,B), and returns a `uint8` array of web-safe (R,G,B). MATLAB/Octave use `uint8` types to represent colours in images, so it's not really cheating to expect the same.
[Answer]
# Javascript (ES6), ~~28~~ 27 bytes
-1 byte thanks to @Arnauld
```
a=>a.map(n=>51*(0|.5+n/51))
```
Takes input as an array (`[red, green, blue]`) and returns the output in the same format.
```
f=a=>a.map(n=>51*(0|.5+n/51))
```
```
<div oninput="o.innerText=f([r.value,g.value,b.value])"><input id=r type=number value=0 /><input id=g type=number value=0 /><input id=b type=number value=0 /><pre id=o>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
*Byte saved thanks to Dennis*
```
51Ɠ÷+.Ḟ×
```
[Try it online!](https://tio.run/##y0rNyan8/9/U8Njkw9u19R7umHd4@v//0UampjpgbGgcCwA "Jelly – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), ~~23~~ 18 + 1 (`-n`) = 19 bytes
```
say 51*int$_/51+.5
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVLB1FArM69EJV7f1FBbDyhmwGXIZWTKZWTGZWrAZWrIZWr0L7@gJDM/r/i/rq@pnoGhwX/dPAA "Perl 5 – Try It Online")
*-4 bytes thanks to @Dennis*
[Answer]
# Mathematica, 24 bytes
```
Nearest[51Range[0,5],#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfLzWxKLW4JNrUMCgxLz012kDHNFZHOVbtf0BRZl6JgkNadLWhkYWOgqG5pY6CkbFBbex/AA "Wolfram Language (Mathematica) – Try It Online")
-2 bytes from @MishaLavrov
[Answer]
# Excel VBA, 26 Bytes
Anonymous VBE immediate window function that takes input as integers from range `[A1:C1]` and outputs the corresponding safeview values to range `[A2:C2]`.
```
[A2:C2]="=51*INT(.5+A1/51)
```
### Sample Output
[](https://i.stack.imgur.com/Djrjd.png)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~37~~ ~~36~~ 33 bytes
```
lambda c:[(n+25)/51*51for n in c]
```
[Try it online!](https://tio.run/##LYvBCoMwEETP9Sv2mLQLNYlrVOjJz7AerCVUsKuIF78@Jmkvw7w3zHrsn4W1d4@nn4fv6z3A2HSCb5rkndSVlFs2YJgYxt7H3sbeiRxBE4ItJWYXoQKVgeyPtEVQtgpS139TRVMHY/Jk0r@IQYnDpAqDQEb2TQbrNvEOTrTSnw "Python 2 – Try It Online")
# [Python 3](https://docs.python.org/3/), ~~36~~ ~~35~~ 34 bytes
```
lambda c:[(n+25)//51*51for n in c]
```
[Try it online!](https://tio.run/##LYvBCoMwEETP9Sv2mLQLmsQ1KnjyM6wHawkV2lXES78@TWIvw7w3zPY9Xisb77q7f0@fx3OCuR0E3zTJPCd1JeXWHRgWhnn0sfexD6JA0IRgK4nZRahAVSB7krYIytZB6uZv6miaYEyRTPqXMShxmFRpEMjIsc1g2xc@hBO9lP4H "Python 3 – Try It Online")
[Answer]
# PHP, 42 bytes
```
while($k++<3)echo($argv[$k]/51+.5|0)*51,_;
```
Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/6d16bfcc8f2c48ece3e2bab5fefa57604490c740).
[Answer]
## Batch, 50 bytes
```
@for %%i in (%*)do @cmd/cset/a(%%i+25)/51*51&echo(
```
Takes input as command-line parameters.
[Answer]
# [Retina](https://github.com/m-ender/retina), 53 bytes
```
25;
\d+
$*
;
1{51}
a
1
a
51,
51,
$*
(?<= )1*
$.&
```
[Try it online!](https://tio.run/##HYsxDsJQDEN3n8JDQaUg1OQ3Tb8KYuQSDFSCgYWh6oY4@yd0sOUn2/Nzeb2nsqmv90JQbcTtsUfVYATkY/LFBEGYyWFVVPXldOZOGlTHbSls40bvQaH2dI@gTvGBqvkPQ0CmphbrtgsZmCldoqUf "Retina – Try It Online")
Every number in the input has a leading space
[Answer]
## C++, 67 bytes
-3 bytes thanks to Zacharý and ceilingcat
```
#define R(t)t=(t+25)/51*51;
void s(int&r,int&g,int&b){R(r)R(g)R(b)}
```
Return by parameters
Code to test ( include required : `iostream`, `vector` and `tuple` ) :
```
std::vector<std::pair<tuple3int, tuple3int>> testList{
{ { 0,25,76 },{ 0,0,51 } },
{ { 1,26,77 },{ 0,51,102 } },
{ { 127,178,229 },{ 102,153,204 } },
{ { 128,179,230 },{ 153,204,255 } },
{ { 0,254,255 },{ 0,255,255 } },
{ { 9,143,53 },{ 0,153,51 } }
};
for (auto& a : testList) {
s(std::get<0>(a.first), std::get<1>(a.first), std::get<2>(a.first));
if (a.first != a.second)
std::cout << "Error\n";
}
```
[Answer]
# [Kotlin](https://kotlinlang.org/), 111 bytes
```
fun w(r:Int,g:Int,b:Int):Array<Int>(){return arrayOf(Math.rint(r/51)*51,Math.rint(g/51)*51,Math.rint(b/51)*51)}
```
[Answer]
# [q/kdb+](http://kx.com/download/), 11 bytes
**Solution:**
```
51 xbar 25+
```
**Example:**
```
/ apply across test cases and then cut into chunks of 3
q)3 cut 51 xbar 25+0 25 76 1 26 77 127 178 229 128 179 230 0 254 255 9 143 53
0 0 51
0 51 102
102 153 204
153 204 255
0 255 255
0 153 51
```
**Explanation:**
Nice and easy using `xbar` built-in. Q is interpreted right-to-left:
```
51 xbar 25+ / the solution
25+ / vectorised add (add 25 to each item on the right)
51 xbar / round down to nearest multiple of 51
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 28 bytes
```
a=>a.Select(n=>(n+25)/51*51)
```
[Try it online!](https://tio.run/##ndFPT4MwGAbws/0UzU6gCBTWsQXhsqhx0cRkBw/LDrW@M01YG2nRmIXPji/@Jd5YwqVP@v542kp7Lk0NXWOVfqbrd@tgn5PhKlyaqgLplNE2vAYNtZL/dtwq/ZITWQlr6f2BWCeckvSq0fJCabfZBjeXutlDLR4r6JOypLuCdqIoRbiGHvd0UXr6LOF@xNkpZ36Xkx/n1agneieU9nxyICdL7GEqCB9q5QD/DJ51NZYJVwa3TIJJQHeehje62R7igCY8oNms9X0/p1FEMcGPs3EOQ2eGTjZ0OKYsTkZKSYZT2RzBZPGrIYMpTzGNp2PBeQ8ucDSN/8Bvqz8/P@LOvgaHp8XlERjWYlOswtOh9dkO36AlbfcB "C# (.NET Core) – Try It Online")
Same solution as others. I didnt count headers (system and linq). You can if you want. :)
[Answer]
# [Funky](https://github.com/TehFlaminTaco/Funky), 33 bytes
```
l=>l::map(z=>math.round(z/51)*51)
```
[Try it online!](https://tio.run/##SyvNy678n2b7P8fWLsfKKjexQKPK1i43sSRDryi/NC9Fo0rf1FBTC4j/FxRl5pVopGlUW@ooGJoY6yiYGtdqav4HAA "Funky – Try It Online")
] |
[Question]
[
A math Olympiad will be held, and participants are being registered. The highest number of participants is 100. Each participant is given an ID number. It is given in a sequence like \$100, 97, 94, 91, 88, ...., 1\$, and when the first sequence is over, then \$99, 96, 93, 90, 87, ...., 3\$ sequence and so on.
Let's assume one of the participant's ID number is \$k\$ and he/she is the \$n^{th}\$ participant. Given the value of \$k\$, return the value of \$n\$.
**Test Cases**
```
59 -> 81
89 -> 71
16 -> 29
26 -> 92
63 -> 47
45 -> 53
91 -> 4
18 -> 62
19 -> 28
```
There will be no leading zero in input. Standard loopholes apply, shortest code wins. In output there can be trailing whitespace.
[Answer]
# [Python 2](https://docs.python.org/2/), 23 bytes
```
lambda n:1-199*~n/3%~99
```
[Try it online!](https://tio.run/##Pc3BDoIwDIDhs3uKXkw2U6MdAhvJnkQ9YAQl0UIGFy@8@txm4u3r8rebPstzZB16dwmv9n27t8AN7cna3cqHYrtaG5ZuXmZwcJalRTCkEKSJqrOoQtA2SUdZnVQVCKc66VQilEWSpfiWFwxClTOKR7RRV9GPHhjBw8CQf2vEZvIDL9BLVs55IfIofmXKfMuPThLSkdS/Zkx9@AI "Python 2 – Try It Online")
I kind-of just tried stuff until I got something that worked.
[Answer]
# [Python 2](https://docs.python.org/2/), 27 bytes
Some magic formula after a bit of trial and error.
```
lambda n:~-~n%3*33+34-~-n/3
```
[Try it online!](https://tio.run/##HctNCoMwEAXg/ZxiNkVtTUsSfxIhPUmhpLRiQGOwEenGq6cmq/mY9577@WG2LPTqEUY9vd4abbeT3Z74mfMLr8hO7I2HbTDjB2kHaKwrcV69Q4WTdrmxvsRFb88jWH1eXL9uND7PkNwxKwpAtxwV7I@iK1CptA21jLmgIBJaCrSJYBJYgmTQ8IiqhaqOqDlImj5ARbwNA5rWTPwB "Python 2 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~11~~ 9 bytes
```
€ΣTC3ṫ100
```
[Try it online!](https://tio.run/##yygtzv7//1HTmnOLQ5yNH@5cbWhg8P8/AA "Husk – Try It Online") or [Verify all tests](https://tio.run/##AUYAuf9odXNr/20oUysoKyIgLT4gInPigoFyKSnCtv/igqzOo1RDM@G5qzEwMP///zU5Cjg5CjE2CjI2CjYzCjQ1CjkxCjE4CjE5 "Husk – Try It Online")
-2 bytes, borrowing Unrelated String's idea.
## Explanation
```
€ΣTC3ṫ100
ṫ100 [100..1]
C3 slices of 3
T transpose
Σ join
€ index of input
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ȷ2RUs3ZFi
```
[Try it online!](https://tio.run/##y0rNyan8///EdqOg0GLjKLfM/4fbHzWtifz/39RSx8JSx9BMx8hMx8xYx8RUx9JQx9BCx9ASAA "Jelly – Try It Online")
```
U Reverse
R the inclusive range from 1 to
ȷ2 100.
s3 Split it into slices of length 3,
Z zip the slices,
F flatten the columns,
i and find the index of the input in the resulting list.
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~33~~ 20 bytes
*Thanks to @tsh for -13*
```
n=>101+~n%3*33-n/3|0
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/hfllikkG77P8/WztDAULsuT9VYy9hYN0/fuMbgf0FRZl6JRrqGqaWmpoK@voKFIRdMyAIqZI4QMjSDCBlZwoWMoEKWRnAhM2OIkIk5PlUmphAhU2O4kKUhUAisE2GjBUSVGUKjIdRdRhb/AQ "JavaScript (V8) – Try It Online")
**Old:**
```
n=>(n=100-n)%3*33+n/3+1+!!(n%3)|0
```
[Try it online!](https://tio.run/##fc69DsIgFAXg3aegQxOQNPzcQmHAdyEOTR1uGmw6@e5oBGFz/XJOznnEMz7vaduP6XT5jImsIWO4UQxKygnZCFcAjgK44sNAcQT2knlPGx50pcYzRoQgTl1@5CotnZQtpH0jXcnrRhYKzcu/1GwKGWjk1Ye@zb7oSsr2oqq/tMtv "JavaScript (V8) – Try It Online")
I don't know why this works. Don't question it.
[Answer]
# [J](http://jsoftware.com/), 28 27 26 24 bytes
```
(_,;(</.~3|])i._100)i.<:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NeJ1rDVs9PXqjGtiNTP14g0NDICUjdV/Ta7U5Ix8BQtDBVuFNAVTSwjXHMK1gHKNLMFcQzMI19IIzDWCck3MwVwzY6yypsZgrokpVDGYZ2kI4ZlB1BpaQO2xgHAtuf4DAA "J – Try It Online")
-2 bytes thanks to Bubbler
[Answer]
# [Desmos](https://www.desmos.com/), ~~30~~ ~~32~~ 31 bytes
```
ceil(mod(67.1-101\frac n3,100))
```
[Try it here!](https://www.desmos.com/calculator/fdsckgc0hs)
*+2 bytes to account for edge case at 2*
*-1 byte thanks to Jonathan Allan!*
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 23 bytes
```
p(n)=-n\3+(1-n)%3*33+35
```
[Try it online!](https://tio.run/##FcwxDoAwCAXQ3XuYtDYdgFJh6E1cnIxLQ7x/UmF7@fyP3d9bH1vL0syjzotKgjrzTgdRIY4Dax5DYLMkoTME3YXqwpCiq5Orna7GLiaXQmQxEEePGsQTlPUD "Pari/GP – Try It Online")
2 more bytes saved thanks to Dominic van Essen
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
101ḶUẋ3m3ḟ0i
```
[Try it online!](https://tio.run/##y0rNyan8/9/QwPDhjm2hD3d1G@caP9wx3yDz/@H2R01r/v83tdSxsNQxNNMxMtMxMwaRJqY6loY6hhY6hpYA "Jelly – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 34 bytes
-8 bytes thanks to ovs!
```
lambda a:101-round(-~a%3*33.3+a/3)
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSHRytDAULcovzQvRUO3LlHVWMvYWM9YO1HfWPN/Wn6RQqZCZp5CUWJeeqqGoQ5QqaYVF2dBUWZeiUamTppGpqbmfwA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~11~~ 10 bytes
*Thanks to @Razetime for -1 byte by writing `199` as `⁺b`.*
```
ꜝ⁺b*3ḭ₁N%⌐
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%EA%9C%9D199*3%E1%B8%AD%E2%82%81N%25%E2%8C%90&inputs=16&header=&footer=)
Vyxal port of [@xnor's Python answer](https://codegolf.stackexchange.com/a/224040/101522), with a bit of extra golfing.
Explanation:
```
# Note: 'X' denotes current value.
# Implicit input
ꜝ # ( X + 1 ) * -1
⁺b* # X * 199
3ḭ # X // 3
₁N% # X % -100
⌐ # 1 - X
# Implicit output
```
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
I⊕÷﹪⁻²⁰¹×¹⁰¹N³⁰⁰¦³
```
[Try it online!](https://tio.run/##FcYxDoMwDADArzA6EkihhaljuzCAOvQDaWIJS4lTJQ7fd2E5nd9d8dlF1XchFni6KrCwL5iQBcN5edFBAWHNocUMK3GrcLNj330oYYXx6sK/JltLXyxgjOm7u7WX581DdZp1OOIf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Implements the formula `n=1+(201-101*k)%300/3`, which I found through trial and error.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
```
Lõ Ôó3 c aU Ä
Lõ // Create the range [1..100],
Ô // reverse it and
ó3 // group by every third item.
c // Flatten the result, then
aU Ä // return the index of input plus one.
```
[Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=TPUg1PMzIGMgYVUgxA==&input=MTk=)
[Answer]
# [R](https://www.r-project.org/), 30 bytes
```
k=scan();35+-k%/%3+33*(1-k)%%3
```
[Try it online!](https://tio.run/##bc3BCoQgEAbgu08xEIJuxKZm6S7tu0QZhGCQdYp9djdDb3saPv6Zf7YQbO/HwRH6FrKsLH5iUQrxIKyyFGMRWF0jVMBk5sUZGDzMhxv3ZXWwr7Ad1zB@h3Hwxr/QMvU5Jpae6G8l@l57RGoKBVQfUCxSZXY3WZvIdSTP1DyyFYlNF9nIRCkiNcvp3aSS2vuU5T9cofAD "R – Try It Online")
There are already 12 other answers in various languages before I managed to post this, and - amazingly for what seems such a simple task - they mostly seem to use different formulas/strategies to each other, and all appear to be different to this one.
I suspect this means that if I go-through all the other approaches, I'll find that at least some of them will turn-out to be golfier than this one, though...
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn) `-IF`, [12 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
Found a few bugs while writing this, lol. This is 0-indexed (e.g. 59 -> 80), I'm not sure if that's okay so I can change the answer if it isn't (somebody asked in the comments but there was no response).
```
&»¨)¢►†3K1v&
```
# Explained
Unpacked: `e2.~::%3-1& .@`
I see some answers explain like this:
```
e2.~ Descending range from 100 to 1
::%3-1 Sort in chunks of 3
& .@ Bind the transpose operator to the output
```
And others like this:
```
e2 1 * 10 ^ 2 = 100
.~ Descending range
:: Sort adjacently while the right is truthy
_ The currently value
% Modulo
3 Three
- Minus
1 One
& Bind
.@ The transpose operation
```
So I might as well include both. Either way, there is an implicit `:_` and `:i` surrounding the program. The space in `& .@` is required because `&.` is a symbol in the language already. I admit the flags are a bit cheaty, so for anybody curious this would be `15 bytes` without the two flags.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
тLR3ôζ˜þIk>
```
Port of [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/224026/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//YpNPkPHhLee2nZ5zeJ9ntt3//6aWAA) or [verify the entire sequence](https://tio.run/##yy9OTMpM/X@xydXPXknhUdskBSV7IM8nyPjwlnPbTs85vM8v2@6/zn8A).
Alternatively, a port of [*@xnor*'s Python answer](https://codegolf.stackexchange.com/a/224040/52210) (which only works in the legacy version of 05AB1E due to the negative modulo) would be 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) as well:
```
$±Ƶ$*3÷т(%-
```
[Try it online](https://tio.run/##MzBNTDJM/f9f5dDGY1tVtIwPb7/YpKGq@/@/qSUA) or [verify the entire sequence](https://tio.run/##MzBNTDJM/X@xyc3PzsVeSeFR2yQFJfv/hsWHNh7bqqJlfHj7xSYNVd3/Ov8B).
**Explanation:**
```
тLR # Push a list in the range [100,1]
3ô # Split it into parts of size 3
ζ # Zip/transpose the list, using a space as filler
˜ # Flatten this list of triplets
þ # Remove the spaces by only leaving digits
Ik # Get the (0-based) index of the input in this list
> # Increase it by 1 to make it a 1-based index
# (after which the result is output implicitly)
$ # Push 1 and the input
± # Get the Bitwise-NOT of that: -input-1
Ƶ$* # Multiply it by 199
3÷ # Integer-divide it by 3
т(% # Modulo -100
$ - # Subtract it from the 1 we pushed at the start
# (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 `199`.
] |
[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/244139/edit).
Closed 1 year ago.
[Improve this question](/posts/244139/edit)
Given a positive integer as input, output that integer, but with its bits rotated two times to the right. Also, think of the number as a donut of bits, eg. `21 -> (10101)`. If all of the bits suddenly decided to move to the right, they would wrap around. eg. `rRot(21) -> (11010) = 26`. Do what i explained 2 times (at the same time).
Test cases:
```
24 -> 6
21 -> 13
32 -> 8
0 -> 0
1 -> 1
3 -> 3
```
Remember that this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!
Also, here's a snippet for the leaderboard:
```
var QUESTION_ID=244139;
var OVERRIDE_USER=8478;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```
```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
b«î«îB
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJix5THlEIiLCIiLCIyMSJd)
All these languages without rotate right built-ins smh.
## Explained
```
b«î«îB
b # convert input to binary
«î # rotate that right once
«î # and rotate that right all over again.
B # convert back to base 10
```
[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///R1FVA9P@/AZchlzGXkSGXkQmXsREA)
**Explanation:**
```
‚ï™ # Rotate the bits of the (implicit) input-integer once towards the right
‚ï™ # And do it again
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 4 bytes
*-2 bytes thanks to Kevin Cruijssen*
```
bÁÁC
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/6XDj4Ubn//@NDAE "05AB1E – Try It Online")
Explanation:
```
# implicit input
b # convert to binary
ÁÁ # rotate right twice
C # convert from binary to decimal
# implicitly output
```
[Answer]
# [R](https://www.r-project.org/), ~~59~~ ~~58~~ 46 bytes
*Edit: -1 byte thanks to Giuseppe, and then a change-of-approach benefitting heavily from Giuseppe's golfing again*
```
function(x,z=x%/%4)z+2^(log2(z*2+!z)%/%1)*x%%4
```
[Try it online!](https://tio.run/##K/oflF@SWJIaUp7vlFlSHJSZnlFi@z@tNC@5JDM/T6NCp8q2QlVf1USzStsoTiMnP91Io0rLSFuxShMoaqipVaGqavK/OLGgIKdSI1nDyETHyFDH2EjHQAdIaepgmq35HwA "R – Try It Online")
Integer-divide x by 4, and then add `x` modulo 4 multiplied by `2^ceiling(log2(x/4))`.
---
Or, if the rotation is done in two separate steps, with removal of leading zeros after each step:
# [R](https://www.r-project.org/), ~~61~~ 56 bytes
*Edit: -5 bytes thanks to Giuseppe*
```
function(x,z=x%/%4)z+2^(log2(z*2+!z)%/%1)*(x%%4-!x%%4-2)
```
[Try it online!](https://tio.run/##K/oflF@SWJIaUp7vlFlSHJSZnlFi@z@tNC@5JDM/T6NCp8q2QlVf1USzStsoTiMnP91Io0rLSFuxShMoaqippVGhqmqiqwgmjTT/FycWFORUaiRrGJnoGBnqGBvpGOgAKR0jM00dTIs0/wMA "R – Try It Online")
Integer-divide x by 4, and then add the number of `1`-bits of `x` modulo 4 multiplied by `2^ceiling(log2(x/4))`.
Works because each rotation only adds a 1 to the front if the least-significant-bit is non-zero.
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 6 bytes
Anonymous tacit prefix function.
```
¯2∘⌽⍢⊤
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/Q@uNHnXMeNSz91HvokddS/5rcj3qmwqUSTu0QsHIRMHIUMHYSAFI/AcA "APL (dzaima/APL) – Try It Online") (TIO is outdated; the 0 case works in the latest version)
`¯2∘⌽` rotate two steps right
`⍢` under
`⊤` binarification
Compare to "surgery under anaesthesia" — the anaesthesia is undone once the surgery is over.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 5 bytes
Anonymous tacit prefix function
```
⊥¯2⌽⊤
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HX0kPrjR717H3UteR/2qO2CY96@x51NT/qXfOod8uh9caP2iY@6psaHOQMJEM8PIP/px1aoWBkomBkqGBspGCgAKQA "APL (Dyalog Extended) – Try It Online")
`‚ä•`‚ÄÉfrom-base-2 of
`¯2⌽` negative two left rotations of
`⊤` to-base-2
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes
```
ḃ↻₂⊇~ḃ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/@GO5kdtu4ECj7ra64Cc//@jjUx0FIwMdRSMjXQUDHQUQKxYAA "Brachylog – Try It Online")
```
ḃ Convert to binary,
↻₂ and rotate right 2.
‚äá Try subsequences largest first until
~ḃ it can be converted from binary without leading zeroes.
```
[Answer]
# [Desmos](https://desmos.com/calculator), 82 bytes
```
k=floor(log_2(n+0^n))
l=[0...k]
f(n)=total(mod(floor(n/2^l),2)[mod(l+2,k+1)+1]2^l)
```
[Try It On Desmos!](https://www.desmos.com/calculator/1tgchnbifd)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/6npiypfss7)
Thanks [@Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) for supplying a helpful formula in the [chat](https://chat.stackexchange.com/transcript/message/60647782#60647782) (I did `l+2` instead of `l-2`, though, because I realized it was golfier to do that).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 5 bytes
```
Bṙ-2Ḅ
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJC4bmZLTLhuIQiLCLDh+KCrCIsIiIsWyIyNCwgMjEsIDMyLCAwLCAxLCAzIl1d)
```
Bṙ-2Ḅ Main Link
B convert to base 2
·πô-2 rotate left -2 times
Ḅ convert from base 2
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
≔↨N²θI↨²Eθ§θ⁻κ²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DKbE4VcMzr6C0xK80Nym1SENTR8EIiAs1rbkCijLzSjScE4tLIMqMdBR8Ews0CnUUHEs881JSK0BM38y80mKNbJAuMLD@/9/I8L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔↨N²θ
```
Convert the input integer to binary.
```
I↨²Eθ§θ⁻κ²
```
Rotate the array by two bits and convert it back from binary.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 50 bytes
```
.+
$*
+`(1+)\1
$1_
r`(.+)(_1?_1?)
$2_$1
+`1_
_11
1
```
[Try it online!](https://tio.run/##DYoxCoBADAT7fUeEnIHDjfaWfkLIWVjYWBz@Px4MTDHT7@95r5z0aFkNMsOa0spJCAO9abWiwX1QIB7CcYwSJJjpG5xYHQuGfg "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*
```
Convert to unary.
```
+`(1+)\1
$1_
```
Convert to a modified binary where `_` represents `0` and `_1` represents `1`. (Another way of thinking of it is that each `1`'s value depends only on the number of following `_`s.)
```
r`(.+)(_1?_1?)
$2_$1
```
Rotate the last two bits of the number to the start.
```
+`1_
_11
```
Convert back to unary.
```
1
```
Convert to decimal.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
2^BitLength[a=‚åä#/4‚åã](#-4a)+a&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yjOKbPEJzUvvSQjOtH2UU@Xsr7Jo57uWA1lXZNETe1Etf8BRZl5JdHKunZpDsqxanXByYl5ddVcRiY6XEaGOlzGRjpcBjpcIBZX7X8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# JavaScript (ES6), 29 bytes
```
n=>n%4<<32-Math.clz32(n/=4)|n
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5P1cTGxthI1zexJEMvOafK2EgjT9/WRLMm739yfl5xfk6qXk5@ukaahpGJpqaCvr6CGReauCFE3NAYTcLYCCJhgSauYAARN0AXhxmELm4METf@DwA "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // n = input
n % 4 // isolate the two least significant bits
<< // left-shift them by
32 - // the bit length of n once it has been divided by 4
Math.clz32( // this is computed by using the number of leading
n /= 4 // zeros in the 32-bit representation
) //
| n // bitwise OR with n (which is now input / 4)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~31~~ 29 bytes
```
->n{n%4<<(n/=4).bit_length|n}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk/VxMZGI0/f1kRTLymzJD4nNS@9JKMmr/Z/gUJatJFJLBeYNoTQxkYQ2gBCQUWhgsYQCqrFNPY/AA "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 34 bytes (@m90)
```
lambda n:n%4<<len(bin(n|2))-4|n>>2
```
[Try it online!](https://tio.run/##JYrBCoMwEETv@xV7KSagooktRdQv6cWi0oW4CUkugv9ujZ7ezJtxW/xZ1sfSfw4zrt9pRG750XSdmVl8iQXvSsqi2XkY1EGrsz5i2ALAYj0aJE6tDHEiLv08ToZ4DkK2gJRb7HEdnSCOuTk/npyQZXCGosiwGDCTEtD5cxeUL4JkbuWhmjS9QNWJtQatUnhDlVDBreGSCnSChuaWz6v9AQ "Python 3 – Try It Online")
### Old [Python 3](https://docs.python.org/3/), 37 bytes
```
lambda n:(n%4<<len(bin(n>>1))-1)+n>>2
```
[Try it online!](https://tio.run/##JYrBDoIwEETv@xV7Me5GJNKiMQb4Ei8YIG5Stk3bi1@PVE9v5s2ET357tdvSPzc3rq9pRH2QHtquc7PSS5R0GBrmc8OnPZlN1uBjxvRJAIuP6FC0tDrlSbSO8zg50TkRPwCl8tjjOgYSzZXbP1ECcZ2Ck0xHPA94ZAYMcd9JqoWEK8@bact0A9MUNhasKeEOl4IL/DX8pAFbYKH9y@uvfQE "Python 3 – Try It Online")
Mostly straight forward. The only bit that needs a bit of care is very small numbers because their bits may wrap around more than once. Here this is solved by making sure that the wrap around shift (the one that is applied to the two smallest bits) is always at least 2.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
ḋṙ_2ḋ
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f/DHd0Pd86MNwLS////jzYy0TEy1DE20jHQAVKxAA "Husk – Try It Online")
```
ḋ # binary digits from number
·πô_2 # rotate left -2 positions
ḋ # number from binary digits
```
---
Or **7 bytes** if the rotation is done in two separate steps, with removal of leading zeros after each step:
```
‼(ḋṙ_1ḋ
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@jhj0aD3d0P9w5M94QSP///z/ayETHyFDH2EjHQAdI6RiZxQIA "Husk – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 23 bytes
```
[ >bin -2 rotate bin> ]
```
[](https://i.stack.imgur.com/YGUUO.gif)
```
! 24
>bin ! "11000"
-2 rotate ! "00110"
bin> ! 6
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
i.>.BQ2 2
```
[Try it online!](https://tio.run/##K6gsyfj/P1PPTs8p0EjB6P9/I0MA "Pyth – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 57 bytes
```
i;f(n){for(i=2;i--;n/=2)n+=n%2<<32-__builtin_clz(n);i=n;}
```
[Try it online!](https://tio.run/##XY/vaoMwFMW/9ykughBrpF3cxkbMvow9xRTpYuzCXCwmY1Lx1eeufyZrAwk3555zk5@MjlIOg@YlMUFX1g3RgnEdRdzsBAtMKIzPkiRmUZ6/fenKaZPL6oxmroXh/aCNg8@DNiSAbgO4RsEp6@xrBgI6dkuB3VCIGYU9hbHq@WpU7UlJp4rZe4/9mMLDtVPWxjqQ74dmi6eSH6qZA17avrC0fXzGfedR@H@PvSWNUEDGx7QpVIuxPV/KBKw@q7okf98IdouwXRUOYTi5g2nYzLhy4rSZdbJk/KJrsVsSF1yqCtUV@zp2atBSEs8vIHoCPH2bGgRzFCxd2ZUQNlvG9pt@@JFldTjaIfr@BQ "C (gcc) – Try It Online")
] |
[Question]
[
I was messing around on my 'ol TI-84 CE and made a program that produced this output (it was actually bigger but that is not the point):
```
*
* *
* * *
* *
*
* *
* * *
* *
*
...
```
I evolved it to take input text and make the triangle waves out of that. The final step was to also take a number to specify the size (n>0). But I am super lazy so you must do it for me!
# Challenge
Given a string and number (`n > 0`), output a triangle wave. This should be in the following format (with `*` as the string input)
```
*
* *
* * *
* * * *
* * * * (...)
* * * *
* * *
* *
*
*
* *
* * *
* * * *
* * * * (...)
* * * *
* * *
* *
*
(...)
```
* Each line starts with 1 space on the left edge.
* The first line should have `*` on the right edge, for a full line of `*`.
* Every line after that, for the next `n - 1` lines, you add `*`, `<linenumber>` times. So for `n=3`:
```
*
* *
* * *
* *
*
```
* Then, output this full triangle infinitely:
```
*
* *
* * *
* *
*
* *
* * *
* *
*
```
Note that you can't have something like this, for `n=2`:
```
*
* *
*
*
* *
*
```
You must trim the repeated single `*`.
Another example, with a multichar string input:
```
'hi', 4 ->
hi
hi hi
hi hi hi
hi hi hi hi
hi hi hi
hi hi
hi
hi hi
hi hi hi
...
```
### Assorted other rules:
* Output must be immediately visible (i.e. it will wait to display until the program ends)
* You may take the input in any reasonable way, so `["hi",3]` is allowed but `["h",1,"i"]` is not. However, you may *not* use `Ans` to take input in TI-Basic programs.
* You must continue the pattern forever, or until the program ends due to memory limits.
* You do not need to have trailing spaces but leading spaces are required.
* You must print up to one line at a time. (i.e. each line must be printed all at once, you can't print each triangle iteration by itself)
* The one space padding is before and after each instance of the text
[Here is an answer you can use to check your output.](https://codegolf.stackexchange.com/a/117216/63187) (with video)
Leading or trailing newlines are fine.
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
/* Configuration */
var QUESTION_ID = 117107; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes
1 byte saved thanks to *Erik the Outgolfer*
```
[¹ð.ø²Lû¨×€,
```
[Try it online!](https://tio.run/nexus/05ab1e#ARwA4///W8K5w7Auw7jCskzDu8Kow5figqws//9oaQo0 "05AB1E – TIO Nexus")
Run locally if you want the lines displayed 1 at a time.
**Explanation**
```
[ # start infinite loop
¹ð.ø # surround the first input by a space on each side
²Lû¨ # construct the range [1 ... n ... 2]
× # replace each number in the range by that many instances of the string
€ # for each string in the list
, # print it on a separate line
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~68~~ 62 bytes
```
t#n=mapM putStrLn[[1..n-abs m]>>' ':t++" "|m<-[1-n..n-2]]>>t#n
```
[Try it online!](https://tio.run/nexus/haskell#@1@inGebm1jgq1BQWhJcUuSTFx1tqKeXp5uYVKyQG2tnp66gblWira2koFSTa6MbbaibB5I1igVKAbX@z03MzFOwVVAqzqxQUlBWMPsPAA "Haskell – TIO Nexus") Example usage: `"somestring" # 5`.
**Edit:** Saved 6 bytes thanks to [@Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen)!
Given for example `n=4`, `[1-n..n-2]` constructs the list `[-3,-2,-1,0,1,2]`. For each element `m` in this list, `[1..n-abs m]` is a list of length `n` minus the absolute value of `m`, thus we get lists of length `4-3, 4-2, 4-1, 4-0, 4-1` and `4-2`, that is `1, 2, 3, 4, 3` and `2`. For each of this numbers `>>' ':t++" "` concatenates as many times the given string `t` with a space added to back and front.
This yields a list of strings with the first triangle. `mapM putStrLn` prints each of the strings in the list on a new line, then the function `#` calls itself again with the same arguments and starts over.
[Answer]
# Scala, 79 Bytes
```
(s:String,n:Int)=>while(1>0)(1 to n)++(n-1 to 2 by-1)map(y=>println(s" $s "*y))
```
[Try it online!](https://tio.run/nexus/scala#JY7NCoJAFIX3PsVBWsxNDY1WAwotW0eraDGW2oSO4lwKEZ99mmz3HTh/ffmq7gyuLGMOgEdVo1PaCDU2VuI4jmq6nnnUprmRxMVoRo4Z3oq3alF75YSVf0ts5Mkw5cXnqdtKZEVKIgP3MBRFwiQr71FOSUadGsSUF4PPcWuEDbGxCLcTkfPdqNcHIqUYK2S04/5X7peXYHFu6w5f "Scala – TIO Nexus")
My first attempt at one of these. The basic idea is to generate a sequence of numbers, from 1 to n, then concatenated with the reverse (minus the ends to avoid doubling up). Then just loop over those numbers and print the input plus spaces that many times for each number in our generated sequence.
Ungolfed:
```
(text: String, n: Int) =>
while(1 > 0) { //loop forever
((1 to n) ++ (n-1 to 2 by-1)) //Generate a sequence of numbers, from 1 to n
//and then concatenate it with the sequence n-1 to 2
.map(y=>println(s" $text " * y)) //for each number y in the sequence we generated,
// print the input text, surrounded by spaces, y times
}
```
[Answer]
# Java 7, ~~128~~ ~~129~~ ~~128~~ 125 bytes
+1 byte: Missed the padding after each character
-1 byte: Changed k==1 to k<2
-3 byes thanks to Kevin Cruijssen
```
void a(String s,int i){s=" "+s;for(int j=-1,k=1,l;;k+=j){for(l=0;l<k;)System.out.print(s+(++l<k?" ":"\n"));j=k==i|k<2?-j:j;}}
```
First post here so let me know if I'm doing something wrong. Any golfing help is much appreciated.
[Try it online!](https://tio.run/nexus/java-openjdk#LYzLDoIwFETX@BU3XbUWiBpX1IYvcOVSXVRF0oeFcKvGIN@OFV1NMmfOtPeT02c4O4UIW6V9P0vaX4dBhRiPRl/gFgndhU77en8E1dXIIC4TXz0ni7JcUTInKayZmCXDOFnqrwCm2gfQrEdJgHAU16aj38rIbJlauUydEJZLw/ovcXIh3MYKtnthqG55cw95G48CRU45j6iMNwU5eMKYMNJKqd92syozUxgxDOMwfgA) Note: this times out after 60 seconds and then prints the results, the actual code continually prints infinitely
Ungolfed
```
void a(String s,int i){
s= " " + s;
for(int j=-1, k=1, l;; k+=j){
for(l=0; l<k;)
System.out.print(s+ (++l < k ? " " : "\n"));
j = (k == i | k < 2) ? -j : j;
}
}
```
Prepends a space to the input string then starts an infinite loop. For each iteration it prints the string k times and then prints a new line. k is then incremented / decremented based on the sign of j
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~127~~ ~~108~~ ~~107~~ 102 bytes
The loop in MACRO P prints each line, the for(j) loops print up and down the wave.
-5 byte thanks to ceilingcat.
```
#define P for(i=j;i--;printf(" %s%c",s,i?32:10))
i,j;f(s,n){for(;j++<n;)P;for(--j;j^1&&j--;)P;f(s,n);}
```
[Try it online!](https://tio.run/##HYxBCsIwEEX3niJEWiZ0Bqy6chSv0BMIEhudgY7SuBPPHhuX//Hfi3SPsZT1bUxioxtces4gJ2Uh4tcs9k7gXZOb6DGjnHfbQ78JYSWonCCjhU81WLvuaBwGrotIWS992@oSqex/5G@ZrmKwGOAf4nFf0Q8 "C (gcc) – Try It Online")
[Answer]
# [Röda](https://github.com/fergusq/roda), 49 bytes
```
f n,s{{{seq 1,n;seq n-1,2}while[]}|print` $s `*_}
```
[Try it online!](https://tio.run/nexus/roda#HY3NCsIwEITP7lMsxVOJh@rRRxGxmz/dUlM1EUlinj02fjAMHwxMteiEzzl788RBuGNrtxvEvnxuPJvTuXwfL3ZhxK3Hsb@Ueid2mGFj8SCw6zsoVb5TiiCXqJYQgLVxgS0bD6SZJAVWNM8RQgNSSi0NIKm0sdf1aZqm1f8DSZ7VDw "Röda – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
+2 bytes to fix up to print each line separately.
```
⁶;WṁЀŒḄṖK€Ṅ€ȧß
```
**[Try it online!](https://tio.run/nexus/jelly#@/@ocZt1@MOdjYcnPGpac3TSwx0tD3dO8wayH@5sAZInlh@e/////4zM/yYA)** (note that TIO produces the would-be constant output only after it times out, errors, or, as in this case most likely, exceeds the text limit; offline it prints line by line.)
### How?
```
⁶;WṁЀŒḄṖK€Ṅ€ȧß - Main link: string s, integer n
⁶ - literal ' '
; - concatenated with s
W - wrap in a list
ṁЀ - mould like mapped over n (mould like [[1],[1,2],[1,2,3],...,[1,2,3,...,n]] - half of a sawtooth)
ŒḄ - bounce (reflect but only with one central element to make a triangle)
Ṗ - pop (remove the last element since the sawtooth triangles only have one shortest element between them, not two)
K€ - join with spaces for €ach
Ṅ€ - print and yield for €ach
ȧ - and
ß - call this link with the same arity
```
[Answer]
## C, 85 bytes
```
i,c,d;f(s,n)char*s;{for(;;)for(i=c+=d=c^n?c<2?1:d:-1;i;printf(" %s%c",s,--i?32:10));}
```
[Answer]
# Python 3, ~~124~~ ~~108~~ ~~94~~ ~~90~~ 89 bytes
```
r=range
x=lambda c,n:print('\n'.join(f' {c} '*i for i in[*r(1,n+1),*r(n-1,1,-1)]))+x(c,n)
```
Recursive lambda that would obviously error out if it ever got to evaluating itself (Adding an infinite sequence of `None`s?). Thankfully, it doesn't!
It will still crash relatively soon, because of the default recursion limit, which can be overwritten using `sys.setrecursionlimit(large_number)`
Ungolfed:
```
def triangles(char, N):
print(
'\n'.join(
# f' {char} ' is like ' {char} '.format(char=char)
f' {char} ' * i
for i in
[*range(1, N+1), *range(N-1, 1, -1)] # N=3 -> [1, 2, 3, 2, 1]
)
) + triangles(char, N)
```
[Answer]
# Python 3, 92 Bytes
```
from itertools import*
lambda b,a:[print(f" {b} "*(abs(i%(a*2-2)-(a-1))+1))for i in count()]
```
This code does require itertools, which is a native library in Python. I imported cycle as c.
[Answer]
# [><>](https://fishlanguage.com/playground), ~~183~~ ~~152~~ 138 bytes
```
1+&01-1001.1+bc+-*4b{~p@-$*8b}:g1$1: <
>{:0)?v~{{1+$:@@:@)?v~>1+:&:&(?v>:c2*^
^ o:<v@-10oa0 v?(1:<
^ < o" "@-10<.1*3b<
```
[Try it online!](https://fishlanguage.com/playground/AbAG3JTsmn6TzsDtd)
Takes a string and a number on the stack.
## Explanation
```
# Initialization
1+&01-1001.
1+ Add 1 to value on top of stack (number from input)
& Store in register
01- Push 0 - 1 (-1) to stack
10 Push 1 and 0 to stack
(repetitions on this line, repetitions done for this line)
01. Jump to row 1 column 0 and move
(IP now on {)
# Output loop
>{:0)?v
^ o:<
{ Roll stack left
: Duplicate top of stack
0 Push 0
) Greater than
? If top of stack is nonzero (value > 0)
v Continue loop
: Duplicate top of stack
o Output top of stack
# Line loop
>output~{{1+$:@@:@)?v
^ o" "@-10<
output Output word
~ Delete -1 (end-of-word marker)
{{ Roll stack left twice
so the two repetition variables are on top
1+ Add one to repetitions done for this line
$:@@:@ Duplicate both variables, preserving order
) Greater than
? If nonzero (repetitions needed > repetitions done)
v Continue loop
01- Push -1
@ Roll top three items right so end-of-word marker is in correct place
" " Push char code for space
o Output space
# Add newline
0ao01-@
0 Push 0 (repetitions done)
a Push charcode of newline (10)
o Output newline
01- Push -1
@ Roll top 3 items right so end-of-word marker is in correct place
# Check if repetitions < 1
:1(?v
: Duplicate (repetitions needed)
1 Push 1
( Less than
? If nonzero (repetitions needed < 1)
v Continue loop (else add newline)
b3*1.
b3* Push 11 * 3 (33)
1 Push 1
. Jump to row 1 column 33 and move (IP was pointing left, so it is now on the second > in rebound loop)
# Rebound loop
.1+bc+-*4b{~p@-$*8b}:g1$1: <
~>1+:&:&(?v>:c2*^
~ Remove repetitions done for this line
> Make IP travel right (needed later)
1+ Add 1 to top of stack (repetitions needed)
: Duplicate
&:& Get register value and store a copy back in register
( Less than
? If nonzero
(repetitions needed < input value + 1)
v Check if repetitions < 1 (see above)
> Make IP travel right (also needed later)
: Duplicate top of stack (???)
c2* Push 12 * 2 (24)
: Duplicate
1 Push 1
$ Swap top two values
1 Push 1
g Get value at row 1 column 24
(initially the + near the start of this loop)
: Duplicate
} Roll right to put duplicate at bottom of stack
b8* Push 88
$ Swap
- Subtract (turns '+' into '-' and vice versa)
@ Roll top 3 items to put at correct position
p Put new character at row 1 column 24
~ Delete ???
{ Roll stack left so original value of row 1 column 24 is back on top
b4* Push 11 * 4 (44)
- Subtract
+ Add to repetitions needed
cb+ Push 12 + 11 (23)
1 Push 1
. Jump to row 1 column 23 and move (IP was pointing left, so it is now on the first >)
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 72 bytes
```
param($a,$b)$a=" $a ";if($b-1){for(){1..$b+($b-1)..2|%{$a*$_}}}for(){$a}
```
[Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSqKOSpKmSaKukoJKooGSdmaahkqRrqFmdll@koVltqKenkqQNEdLTM6pRrVZJ1FKJr62thcirJNb@//9fPSNT/b8hAA "PowerShell – TIO Nexus")
*(TIO has a 60 second timeout, but please be nice to Dennis' server ... also note that TIO doesn't output (refresh the page) until the program completes, so you won't get on-the-fly output. Running this locally produces correct output.)*
Straightforward. Takes input `$a` as the string and `$b` as the integer. We then pad `$a` with spaces and save it back. We then have an `if` check to handle the special case of `$b=1`. If `$b>1` then this test is `$TRUE` and we enter the `if`.
Inside the `if`, we're entering an infinite `for()` loop. Inside the loop, we're constructing a range from `1` to `$b` and then `$b-1` to `2`. There are two possibilities here. If `$b=2`, this range is `1,2,1,2` and so we're actually constructing *two* triangles every `for` loop. If `$b>2`, then the range is something like `1,2,3,4,3,2` to construct one triangle every `for` loop. Inside the range loop, `|%{}`, we just string-multiply `$a` by the appropriate number.
If `$b=1` then we don't enter the `if`, and so just enter a separate infinite `for()` loop that prints `$a` a bunch of times.
By default, PowerShell will "flush" the pipeline (for lack of a better term) on each `for` iteration, so that's where the implicit `Write-Output` happens.
[Answer]
# JavaScript ES6, 98 bytes
```
s=>n=>{while(1){for(i=0;i++<n;)eval(p="console.log(` ${s} `.repeat(i))");i--;for(;--i>1;)eval(p)}}
```
[Try it online!](https://tio.run/nexus/javascript-node#NcvBCsMgDADQ@76iSA8JxbLCbln8lsoWt4BoqWU7iN/u2KHv/gL3wi6xq9@3RoEFa8g7KF9Jp@meCOXjI2xsHjmVHGWO@QXrMNbShnXeZRN/gCIaJLWW/pmsVbecE1vrAYwvz2AQbnjpPw "JavaScript (Node.js) – TIO Nexus")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 30 bytes
```
l~,:)_W%1>W<+S2*@*f*{_Nf+:o!}g
```
[Try it online!](https://tio.run/nexus/cjam#@59Tp2OlGR@uamgXbqMdbKTloJWmVR3vl6Ztla9Ym/7/v1JGppKCCQA "CJam – TIO Nexus") *(same as with other answers: TIO dumps all output after 60 seconds, you have to run it locally to see the proper behaviour)*
**Explanation**
Example input: `"hi" 4`
```
l~ e# Read an eval a line of input
e# STACK: ["hi" 4]
,:) e# Generate the range 1 ... N
e# STACK: ["hi" [1 2 3 4]]
_W% e# Duplicate and reverse it
e# STACK: ["hi" [1 2 3 4] [4 3 2 1]]
1>W< e# Slice to remove the first and last elements of the copy
e# STACK: ["hi" [1 2 3 4] [3 2]]
+ e# Concatenate
e# STACK: ["hi" [1 2 3 4 3 2]]
S2* e# Push " "
e# STACK: ["hi" [1 2 3 4 3 2] " "]
@* e# Bring the text to the top and join the space string with it
e# STACK: [[1 2 3 4 3 2] " hi "]
f* e# Repeat the resulting string by each number in the range
e# STACK: [[" hi " " hi hi " " hi hi hi " .....]]
{ e# Do:
_ e# Duplicate the top
e# STACK: [[" hi " " hi hi "...] [" hi " " hi hi "...]]
Nf+ e# Append a newline to each string in the top array
e# STACK: [[" hi " " hi hi "...] [" hi \n" " hi hi \n"...]]
:o e# Pop and print each string in the top array (one by one)
e# STACK: [[" hi " " hi hi "...] []]
! e# Boolean negation
e# STACK: [[" hi " " hi hi "...] 1]
}g e# While the top of stack (popped) is truthy
e# STACK: [[" hi " " hi hi " " hi hi hi " .....]]
```
[Answer]
## Batch, 108 bytes
```
@set f=@for /l %%i in (2,1,%1)do @call echo %%s:.= %2 %%^&call set s=%%s
@set s=.
%f%%%.
%f%:~1%%
@%0 %*
```
Conveniently I both need to use the current value of a string in a for loop and substitute into it with another variable. Ungolfed:
```
@echo off
setlocal enabledelayedexpansion
set s=.
:l
for /l %%i in (2, 1, %1) do echo !s:.= %2 !&set s=!s!.
for /l %%i in (2, 1, %1) do echo !s:.= %2 !&set s=!s:~1!
goto l
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
⁾ jẋŒḄ}ṖṄ€1¿
```
[Try it online!](https://tio.run/nexus/jelly#ASMA3P//4oG@ICBq4bqLxZLhuIR94bmW4bmE4oKsMcK/////aGn/NA "Jelly – TIO Nexus")
### How it works
```
⁾ jẋŒḄ}ṖṄ€¹¿ Main link. Left argument: s (string). Right argument: n (integer)
⁾ j Join " " with separator s, prepending and appending a space to s.
ŒḄ} Bounce right; yield [1, ..., n, ..., 1].
ẋ Repeat (" "+s+" ") 1, ..., n, ..., 1 times, yielding a string array.
Ṗ Pop; remove the last string.
1¿ While 1 is truthy:
Ṅ€ Print each string, followed by a linefeed.
```
[Answer]
# Lua, 104 bytes
```
p=print;function f(s,n)c=" "..s;while(0)do p(c)for i=2,n+n-2 do p(c:rep(i<=n and i or n+n-i))end end end
```
[Answer]
# Groovy, ~~82~~ 80 bytes
```
{s,n->s+=" ";a=0;x={println s*a};for(;;){for(;a<n;a++){x()};for(;a>1;a--){x()}}}
```
**Previous answer**
```
{s,n->s+=" ";a=0;x={println s*a};for(;;){while(a<n){x();a++};while(a>1){x();a--}}}
```
**Ungolfed (previous answer)**
```
h={s,n-> //A closure with two arguments, the input text and the size of the wave peak
s+=" " //add a space after the input text
a=0 // a counter we will use later
x={println s*a} //another closure that prints the input text repeated "a" times
for(;;){ //infinite loop
while(a<n){ //two while loop that make "a" oscillate between 1 and "n", printing at each iteration
x()
a++
}
while(a>1){
x()
a--
}
}
}
```
[Answer]
# TI Basic 210 Bytes
```
Prompt Str4
Prompt N
0->V
Lbl A
0->S
If (S=0
Then
0->B
1->S
Else
1->B
End
" "->Str1
Str1->Str2
Str1+Str4+Str1->Str5
0->P
Lbl B
If (S=1 and B<N)
Then
B+1->B
Str1+Str5->Str1
Disp Str1
0->P
End
Goto B
Else
For(H,N-1,2,-1)
0->R
" "->Str1
While (R<H)
Str1+Str5->Str1
End
Disp Str1
End
Goto A
```
[Running it (video)](https://youtu.be/jid3dS60ZiM)
[Answer]
# Excel VBA, ~~97~~ 79 Bytes
Anonymous VBE immediate Window Function that takes input of String from cell `[A1]` and variant/String of assumed type integer from cell `[B1]` and outputs a triangle wave using those values to the VBE immediate window.
```
n=[B1]:Do:DoEvents:For i=1To n*2-2:[C1]=n-Abs(i-n):?[Rept(A1&" ",C1)]:Next:Loop
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 7 years ago.
[Improve this question](/posts/4499/edit)
Given a number, say, `-2982342342363.23425785` convert it to `-2,982,342,342,363.23425785`.
* Extra points for not using look-behind
* Extra points for not using regular expressions.
[Answer]
## Java, 50 chars
```
String C(double d){return String.format("%,f",d);}
```
Works as specified in most locales. Does the correct thing in all locales :)
Edit:
If you really want commas no matter the default locale, do:
```
String C(double d){return String.format(java.util.Locale.US,"%,f",d);}
```
which is 70 characters (60 if you've already imported `java.util.*`).
[Answer]
## Spreadsheet, 6+dec.places chars 5 chars
Just enter the number in a cell with formatting `#,##0.########``#,##0`. Works on OOo Calc and MS Excel. Couldn't quickly find something meaning "print as many decimal places as there are". That would shorten it a lot. Can use an int, so the problem is not anymore.
No look-behind, no regex.
[Answer]
### Scala:
```
val l=List (12345.2345, 123456.2345, 1234567.2345, -12345.2345, -123456.2345, -1234567.2345)
def f(d: Double)={
val a=d.toString.split('.')
(if(d<0)"-"else"")+
a(0).toLong.abs.toString.reverse.sliding(3,3).mkString(",").reverse+"."+a(1)}
l.map(f)
```
144 chars without 1st and last line, but this isn't code golf, is it?. Imho no look behind and no regex used.
Result:
```
List(12,345.2345, 123,456.2345, 1,234,567.2345, -12,345.2345, -123,456.2345, -1,234,567.2345)
```
[Answer]
# C 89/90/ANSI
```
#include <stdio.h>
#include <string.h>
int main(int i, char* a[]) {
char * p;
p = strtok(a[1], "."); /* Get argument value; up to decimal point. */
a[1] = strtok(0, "."); /* Overwrite original value with fractional part. */
/* If the first char is a negative sign then print it and advance the string pointer: */
if(*p == '-') printf("%c", *p++);
/* Get remainder of integer part divided by 3 and load it into a digit-group iterator: */
i = strlen(p) % 3;
if(i == 0) i = 3; /* If iterator is empty then fill it. */
while(1) {
/* Nested loop through 3-digit group; printing each char: */
while(i-- > 0) printf("%c", *p++);
/* If string pointer is at null (end of string) char then exit loop: */
if(*p == 0) break;
else printf(","); /* Otherwise print a comma */
i = 3; /* and reload the digit-group iterator. */
}
/* If there is a fractional part then print it after a decimal point: */
if(a[1] != 0) printf(".%s", a[1]);
return 0;
}
```
[Answer]
## Perl, regular expression
Using a regular expression and no look-behinds but look-aheads:
```
$v = "-2982342342363.23425785";
$v =~ s/\d(?=(\d{3})+(\.|$))/$&,/g;
print $v;
```
Each digit is replaced by itself plus a comma if it is followed by *n* digits where *n* is a multiple of three and immedetiately followed by a period or the end of the string.
[Answer]
## Haskell, 105
```
f(a:b:c:n:s)|n/='-'=a:b:c:',':f(n:s)
f s=s
r=reverse
main=interact$uncurry((++).r.f.r).break(`elem`".\n")
```
This doesn't use regular expressions (obviously), but it does backtrack (namely, it reverses digits before adding separators).
[Answer]
## Ruby 111 chars
```
parts = "-2982342342363.23425785".split('.')
parts[0].reverse.scan(/.{1,3}/).join(",").reverse + "." + parts[1]
```
[Answer]
## PHP
Using the built in function for formatting numbers:
```
function format($number)
{
$decimals=(strpos($number,'.')===false?0:strlen($number)-strpos($number,'.')-1);
return number_format($number,$decimals,'.',',');
}
```
Doing it by hand:
```
function format($number)
{
$parts=explode('.',$number);
$temp="";
$len=strlen($parts[0]);
for($i=0;$i<$len;$i++)
{
if($i!=0 && $i%3==0)
{
$temp.=",".$parts[0][$len-$i-1];
}
else
{
$temp.=$parts[0][$len-$i-1];
}
}
$parts[0]=strrev($temp);
return implode('.',$parts);
}
```
[Answer]
## PHP, 56
No Regex, no look-behind.
`function f($n){return number_format($n).strstr($n,'.');}`
---
My first attempts tried calculating how many decimals to keep in order to use it as the optional second parameter for `number_format` but I couldn't think of concise logic.
My second attempt treated the number as a string, splitting on `.`, then re-assembling it.
Then I realized I could just let `number_format` truncate for me, then re-append the decimal section (if any) with `strstr`.
---
A different version, not using `number_format`, in a total of **95 bytes**:
```
function f($n){return strrev(implode(',',str_split(strrev(strtok($n,'.')),3))).strstr($n,'.');}
```
Longer and a bit more readable:
```
function f($num) {
$right = strstr($num, '.');
$left = strtok($num, '.');
$left = str_split(strrev($left), 3);
$left = strrev(implode(',', $left));
return $left . $right;
}
```
[Answer]
## vi, 25 chars
```
ebd0$F.99@='3hha,<C-V><ESC>'
0PZZ
```
The script moves the cursor to the last digit of the number, then tries to search backwards for a decimal point. From there (either the last digit, or the decimal point if there was one), the following process is executed 99 times: the cursor moves left 3 times, then attempts to move left again. If it was able to move left, then a comma is inserted; otherwise, the process aborts.
9 times is probably sufficient instead of 99, so this could be reduced to 18 24 characters.
EDIT: I realized that I wasn't accounting for possible edge cases with a negative sign in front, so I added six characters to deal with it. At the start, 'eb' will effectively move the cursor to the first digit of the number. 'd0' will delete everything before that (which is either the negative sign or nothing). Then at the end, '0' moves to the start of the line and 'P' inserts whatever was deleted earlier.
[Answer]
# Python2 - 219
```
def c(s):
c=str(s)
i=max([k for k in range(len(c)) if c[k]=='.']+[-1])
o=(c[i::] if i>0 else '')
if i>0: c=c[:i]
c=list(c);i=0;m={0:1,1:2,2:3,3:1}
while len(c):
o=c.pop()+(',' if i==2 else '')+o;i=m[i]
return o
```
or I can do this...
# Python2 - 112
```
def c(s):
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
return locale.format("%d", s, grouping=True)
```
Personally I like the first one more... mainly because of the map instead of logic hack. The second one is verbatim from [StackOverflow](https://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators-in-python-2-x) of all places.
[Answer]
## Python 2.7, 127/122 bytes
taking input from stndin:
```
n=`input()*1.0`.split('.')
s=''
k=0
for y in n[0][::-1]:
s+=y;k+=1
if k in range(0,len(n[0]),3):s+=','
print s[::-1]+'.'+n[1]
```
as a function:
```
def c(n):
s='';k=0
for y in`n*1.0`[0][::-1]:
s+=y;k+=1
if k in range(0,len(n[0]),3):s+=','
return s[::-1]+'.'+n[1]
```
could probably be golfed more...
[Answer]
In Lua:
```
local lns =
{
"-2982342342363.23425785",
"-2982342342363",
"2982342342363",
"-.23425785",
".23425785",
"1",
"22",
"-333",
"4444.",
"333.333",
"puke",
}
local results = {} -- Find converted strings here
for i, ns in ipairs(lns) do
local sign, digits, frac = string.match(ns, "^(%-?)(%d-)(%.%d*)$")
if frac == nil then
frac, sign, digits = '', string.match(ns, "^(%-?)(%d-)$")
end
if digits == nil or digits == '' then
results[i] = ns -- Only a fractional part (or no numbers), leave unchanged
else
local groups = {}
local v = 0 + digits
while v > 0 do
local g = math.fmod(v, 1000)
table.insert(groups, 1, g)
v = math.floor(v / 1000)
end
results[i] = sign .. table.concat(groups, ",") .. frac
end
end
```
Odd mix of regular expressions and arithmetic... It allows to handle non-numbers, sign, etc. in a quite concise way. I need the two steps RE as they are quite limited in Lua.
[EDIT] I don't really comply to the requirement as I made an array of strings instead of an array of numbers. On the other hand, by default Lua is compiled with 32bit floats, not 64bit doubles, so the given number is truncated to the first digit after the decimal point... So Lua remains out of the competition. Oh well, it was fun to play with Lua again.
[Answer]
`num.replace(/(\d+)(\..*)?/, ($0,$1,$2) -> $1.replace(/(\d)(?=(\d{3})+$)/g,'$1,') + ($2 || ''))`
This is in coffee script. There's no look behind in JavaScript, but you can pass a function to `.replace`(!). The first regex separates the string over the dot and the second regex deals only with the first part. It's a shorter way than using `.split()` and I had problems mimicking look-behind.
**edit**: changed to work in webkit browsers.
[Answer]
## Python 3: 100 or 102 characters
100 characters as a function:
```
def f(s):n=(s+'.').find('.');return''.join((('-'in s)<i<n and i%3==n%3)*','+c for i,c in enumerate(s))
```
102 reading from stdin:
```
s=input();n=(s+'.').find('.');print(''.join((('-'in s)<i<n and i%3==n%3)*','+c for i,c in enumerate(s)))
```
[Answer]
## Python (162 chars)
```
a=raw_input().split('.')
n=int(a[0])
a[0]=str(n%1000)
n=n/1000
while n>0:
a[0]=str(n%1000)+','+a[0]
n=n/1000
if len(a)>1:
print a[0]+'.'+a[1]
else:
print a[0]
```
Gah! New specs ruin this solution.
Well for integer input
## (89 chars)
```
n=int(raw_input())
s=str(n%1000)
n/=1000
while n>0:
s=str(n%1000)+','+s
n/=1000
print s
```
Will put up one for float later.
For float input
## (152 97 chars)
```
n=float(raw_input())
s=str(n%1000)
n=int(n/1000)
while n>0:
s=str(n%1000)+','+s
n/=1000
print s
```
[Answer]
## Python 2.7: 29 characters
A bit late to the party, but I just read about this [new feature](http://docs.python.org/whatsnew/2.7.html#pep-378-format-specifier-for-thousands-separator) in 2.7 and figured this still deserves to be here:
```
f=lambda(n):'{:,f}'.format(n)
```
Used by calling `f(-2982342342363.23425785)` which returns `"-2,982,342,342,363.234375"`. The error is due to floating-point precision: `-2982342342363.23425785` gets represented as `-2982342342363.234375`.
[Answer]
## C (99)
No regexes, no backtracking, not using built-in formatting of real numbers.
```
d=1000;f(x){x&&f(x/d)+printf("%d,",x%d);}main(x,y){scanf("%d.%d",&x,&y);f(x);printf("%c.%d",8,y);}
```
[Answer]
## Q, 27 chars (integer input)
```
{(|:)","sv 3 cut (|:) -3!x}
```
q){(|:)","sv 3 cut (|:) -3!x}[23498723]
"23,498,723"
## Q, 48 chars (float input)
```
{,[;".",a@1](|:)","sv 3 cut(|:)(*:)a:"."vs -3!x}
```
q){,;".",a@1","sv 3 cut(|:)(\*:)a:"." vs -3!x}[234554.21434]
"234,554.21434"
[Answer]
Some JavaScript approaches:
(1) 74 characters but fails on some inputs, recursive creation:
```
function r(n){return n<0?"-"+r(-n):n<1e3?""+n:r(n/1e3-n/1e3%1)+","+n%1e3}
```
It has two failure channels: (1) if the substring contains subnumbers with leading 0's it sometimes will produce e.g. `1,10` instead of `1,010`, and (2) I don't actually know if `n/1000 - (n/1000)%1` always yields an integer. With bugs corrected the smallest I can get it is 130 characters:
```
function r(n,f){f=Math.floor;return n<0?"-"+r(-n):n%1?r(f(n))+(""+n).match(/\..*/)[0]:n<1e3?""+n:r(f(n/1e3))+","+(""+n).slice(-3)}
```
(2) Split over lookahead and join with commas, **95** characters, one statement:
```
m=(""+n).split('.'),m[0].split(/(?=(?:.{3})+$)/).join(",").replace("-,","-")+(m[1]?"."+m[1]:"")
```
I can't see a better way to handle negatives in this case.
(3) Array inserts every 3 characters to the left of the '.', 100 characters, uses a Bad Part of JS (`n < 0` is `true` or `false` which coerce to `1` or `0` when used with `<`).
```
t=(""+n).split(""),i=t.indexOf('.');for(i=(i<0?t.length:i)-3;n<0<i;i-=3)t.splice(i,0,',');t.join("")
```
[Answer]
# Ruby (didn't golf or count. No regexps.)
```
def commaize(n)
a,b=((negative=n<0) ? -n : n).to_s.split('.')
"#{negative ? '-':''}#{a.reverse.chars.each_slice(3).map(&:join).join(',').reverse}.#{b}"
end
```
[Answer]
**COBOL**
```
ID DIVISION.
PROGRAM-ID. EDITNUM.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 REALLY-BIG-NUMBER PIC --,---,---,---,--9.9(8).
PROCEDURE DIVISION.
MOVE -2982342342363.23425785 TO REALLY-BIG-NUMBER
DISPLAY REALLY-BIG-NUMBER
GOBACK
.
```
10 lines of code, of which six are mandatory. All the work is done by the MOVE statement, ably abetted by the data-definition.
The data-definition (01) uses a Picture-string to describe how the data is to be edited. Here, there will be a leading floating minus-sign, commas separating groups of three digits going left from (to-be-printed) decimal point. There are eight significant decimal places.
MOVE the value to the field, DISPLAY the field (if you want to see what the number looks like).
>
> -2,982,342,342,363.23425785
>
>
>
] |
[Question]
[
An arithmetic sequence is a sequence of numbers of the form `a`,`a+n`,`a+2n`,`a+3n`, etc. In this case, `a` and `n` will both be either integers or decimals.
Given two inputs, `a`, `n`, and a top number value, return a list of numbers where the last term is **less than or equal to** the top number value.
The input can be formatted in any way, as well as the output.
***The catch to this problem is dealing with floating point arithmetic errors.***
For example, `0.1 + 0.3 * 3` is 1, however this will display `0.99999999999...` if you simply go `0.1 + 0.3 * 3`. We want `1`, not `0.99999999999...`
# Test Cases
`a=2, n=3, top=10: [2, 5, 8]`
`a=3, n=1.5, top=12: [3, 4.5, 6, 7.5, 9, 10.5, 12]`
`a=3.14159, n=2.71828, top=10: [3.14159, 5.85987, 8.57815]`
`a=0.1, n=0.3, top=2: [0.1, 0.4, 0.7, 1, 1.3, 1.6, 1.9]`
Shortest code wins. Good luck!
[Answer]
## Non-golfed haskell, 32
```
f a n t=takeWhile(<=t)[a,a+n..]
```
I'd love to change takeWhile to take, but integer division can't be done with /, it needs to be done with `div`. If I go with / then I need to do implicit conversion which makes it that much longer.
[Answer]
## APL (22)
```
{⍵≤T:⍵,∇⍵+N⋄⍬}⊃A N T←⎕
```
Reads input from stdin as three whitespace-separated numbers.
This is actually shorter than using the index generator.
[Answer]
## J, 34 33 31 characters
```
({.+i.@>:@([:<.1{[%~{:-{.)*1{[)
```
I'm sure there's room for improvement here.
Usage:
```
({.+i.@>:@([:<.1{[%~{:-{.)*1{[)2 3 10
2 5 8
```
We can give the verb a name for an extra three characters:
```
s=.({.+i.@>:@([:<.1{[%~{:-{.)*1{[)
s 2 3 10
2 5 8
```
Previously:
```
((0-.~]*]<:2{[)(((i.100)*1{[)+{.))
```
Thought I'd have a go at doing this in Golfscript and got as far as `.3$- 2$/1+,{2$*}%{3$+}%` before realising Golfscript doesn't seem to do floats. Bugger.
[Answer]
### bash 12:
```
seq $1 $2 $3
```
Haha - who would have thought that? Silly'o'bash which normally just handles Integer arithmetic (9/10 = 0) can handle floating points that way:
```
./cg-6228-arithmetic-sequences.sh 2 3 10
2
5
8
./cg-6228-arithmetic-sequences.sh 3 1.5 12
3,0
4,5
6,0
7,5
9,0
10,5
12,0
```
Other test-cases omitted for brevity. I have to mention that you can change the locale, if you're irritated by 10,5 which is the continental way to say 10.5. ;)
[Answer]
### Ruby 34
```
s=->a,n,t{p a;s[a+n,n,t]if a+n<=t}
```
*Input:* the three function parameters
*Output:* the sequence numbers are printed, one per line
Ideone link: <http://ideone.com/SahPs>
[Answer]
## [J](http://jsoftware.com/), 26
```
s=:1 :']+u*[:i.@<.@>:u%~-'
```
There's some interesting syntax to use this definition.
```
10(2 s)1
1 3 5 7 9
```
[Answer]
# Ruby - 28
```
((t-a)/n).times{|i|p(a+i*n)}
```
[Answer]
# Mathematica, 5 bytes
```
Range
```
Arguments are a,top,n in that order. I'm assuming that decimal points at the end are okay.
[Answer]
### Scala 52
```
val x,?,z=BigDecimal(readLine)
x to z by?map println
```
Give inputs `a`,`n` and `top` in the separate line.
Each entry of the output will be listed in the separate line.
[Answer]
# Mathematica ~~39~~ 37
```
Table[#+#2 k,{k,0,Quotient[#3-#,#2]}]&
```
**Usage**
```
Table[#1 + #2 k, {k, 0, Quotient[#3 - #1, #2]}] &[2, 3, 10]
Table[#1 + #2 k, {k, 0, Quotient[#3 - #1, #2]}] &[3, 1.5, 12]
Table[#1 + #2 k, {k, 0, Quotient[#3 - #1, #2]}] &[3.14159, 2.71828, 10]
Table[#1 + #2 k, {k, 0, Quotient[#3 - #1, #2]}] &[0.1, 0.3, 2]
```

[Answer]
## Swift, 90
Not quite as short as the other ones here but this doesn't use a builtin to compute the sequence, nor does it operate on a standard float type. It declares a function `f(a:n:t:)` that takes the numbers in and prints the sequence to stdout.
```
import Foundation
func f(a:Decimal,n:Decimal,t:Decimal){var x=a
while x<=t{print(x)
x+=n}}
```
[Try it Online!](https://tio.run/##Ky7PTCsx@f8/M7cgv6hEwS2/NC8lsSQzP48rrTQvWSFNI9HKJTU5MzcxRycPziqBsTSryxKLFCpsE7nKMzJzUhUqbGxLqguKMvNKNCo0uSq0bfNqa7lAZhjoGQL1G@gZA/Uaaf7/DwA) (with hardcoded test case)
I learned a few things while doing this that surprised me:
* [Swift's range builtin](https://developer.apple.com/documentation/swift/range) is only iterable for integers, unlike in Python where you can specify the step size.
* [Assignment operators in Swift return Void](https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html#ID62), so I couldn't abbreviate the body of the while loop to `print(x+=n)`. I tried it; it just printed `()` a bunch of times.
* `Decimal` values are not converted to `Double` when printing. If you replace `Decimal` in the declaration with `Double`, it prints `1.0` and `1.9000000000000001` rather than `1` and `1.9`. On the other hand, this proves that it is avoiding floating-point rounding errors, as the question specified.
* There is no version of the `<=` operator that lets you compare a `Decimal` to any other number type, so I can't make the function declaration shorter by changing `t`'s type.
+ In fact, even though [`Decimal` is `ExpressibleByFloatLiteral`](https://developer.apple.com/documentation/foundation/decimal#relationships), it is not [`FloatingPoint`](https://developer.apple.com/documentation/swift/floatingpoint).
You could shave off two bytes by allowing the input to be mutated (changing the function signature to `f(a:inout Decimal,n:Decimal,t:Decimal)`, as this eliminates the need for the variable `x`.
[Answer]
# JavaScript 70
```
s=prompt().split(",");for(n=0;(p=s[0]-0+n*s[1]-0)<=s[2]-0;n++)alert(p)
```
input in the form `a,n,top`
[Answer]
## Perl, 37 chars
```
for(($_,$n,$t)=<>;$_<=$t;$_+=$n){say}
```
Input a, n, and top, each number on a separate line. The list is output with newlines separating the values. Run with `perl -M5.010` (or `perl -E`).
[Answer]
# Python (245)
Input should be given with a space in between, e.x. `0.1 0.3 0.5`
```
a=raw_input().split()
I,F=int,float
D='.'
b=[[I(i.replace(D,'')),len(i.split(D)[1:])]for i in a[:2]]
a=map(F,a)
c=max(b,key=lambda x:x[1])[1]
for i in b:i[0]*=10**(c-i[1])
print [(b[0][0]+i*b[1][0])/10.0**c for i in range(I((a[2]-a[0])/a[1]+1))]
```
It avoids floating point errors by turning each floating point into a list containing two values: the number without the decimal point, and the number of significant digits.
`example: 1.34 -> [134, 2]`
[Answer]
## Python, 37
```
a,n,t=input()
while a<=t:print a;a+=n
```
Grabs input in the form `a, n, top`, and prints out the numbers on separate lines.
[Answer]
### C# ~~120~~ 74
```
void A(float a,float n,int t){Console.Write(a+" ");a+=n;if(a<=t)A(a,n,t);}
```
**Edit:** New version - recursive and a lot shorter than using LINQ :)
*Input:* the three parameters of method `A`
*Output:* the numbers in the sequence are printed to console, separated by spaces.
Test link: <http://ideone.com/o7g6k>
>
> *Previous version (using LINQ):*
>
>
>
```
IEnumerable<float>A(float a,float n,int t){return Enumerable.Range(0,int.MaxValue).Select(i=>a+n*i).TakeWhile(s=>s<=t);}
```
[Answer]
# PHP 83
```
<?function a($x,$i,$t){while($r<$t){$r=$x+$i*$g++;$s.=($r<$t?$r." ":"");}echo$s;}?>
```
Wish I could remove "function" but there's no shorter declaration for that in PHP. Handy that PHP uses untyped variables!
Usage:
a(2,3,10);
Returns:
2 5 8
[Answer]
## PHP, 53
```
<?for(list(,$a,$n,$x)=$argv;$a<=$x;$a+=$n)echo"$a ";
```
[Answer]
# R, 3 bytes
```
seq
```
Built in function with arguments from (`a`), to `(top`) and by (`n`)
usage `seq(a,top,n)` eg
```
seq(2,10,3)
```
output numeric vector
```
2 5 8
```
[Answer]
# TI-Basic, 20
```
Prompt A,N,T:For(I,A,T,N:Disp I:End
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
↑≤⁰¡+⁴²
```
[Try it online!](https://tio.run/##ASIA3f9odXNr///ihpHiiaTigbDCoSvigbTCsv///zEuNf8z/zEy "Husk – Try It Online")
] |
[Question]
[
You are given two integers between lets say 1 and 12, `one` and `two`
and a integer between lets say 0 and 4 which is called `range`.
The challange is to decide if `one` is inside or equal the range from `two` ± `range`.
**The range is restarting with 1 after 12 and vise versa.**
For example, if `one = 2`, `two = 11` and `range = 3`, the result is `true`, as `one` is the the range `[8, 9, 10, 11, 12, 1, 2]`.
The input has to be 3 seperated integers, the order doesn't matter. Input via string with seperators possible. But the Input has to consist of numbers reading as '10' and not 'A' e.g.
Test cases:
```
one=7 two=6 range=0 result=false
one=5 two=6 range=1 result=true
one=8 two=11 range=3 result=true
one=1 two=11 range=3 result=true
one=2 two=10 range=3 result=false
one=11 two=1 range=2 result=true
one=6 two=1 range=4 result=false
one=12 two=1 range=3 result=true
```
Shortest valid answer in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ ~~8~~ 10 bytes
```
ŒR’+%12‘Ɠe
```
[Try it online!](https://tio.run/##y0rNyan8///opKBHDTO1VQ2NHjXMODY59f9/Q6P/xv8NAQ "Jelly – Try It Online")
Saved 2 bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
+2 bytes due a bug if `one = 12`
I believe this meets the criteria. Takes `one` from STDIN, `range` as left argument and `two` as right argument
[Answer]
# JavaScript (ES6), 38 bytes
```
(a,b,r)=>((a=a<b?b-a:a-b)>6?12-a:a)<=r
```
[Try it online!](https://tio.run/##hc3NDoIwEATgu0@xxzZZhK2KxlB4li2C0TTUFPT1Kw2JIfh3m2S@zFz5wX3tL7ch6dypCa0OgtGgl7oUgjUXpjIJHzkxsswrUjHLQvtQu653tllbdxatgD0C5AiZlJCm0LLtm9WCKATKEDY/yLgAhLCdk6XZTU80mcHf31YOY0uvo0@C/onYRqW@CzWJ2UZ4Ag "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 53 bytes
Silly branchless method. Expects BigInts. Returns \$0\text{n}\$ or \$1\text{n}\$.
```
(a,b,r)=>0x4C5C038B885n>>((a-=b)*a+347n*r)%282n%46n&1n
```
[Try it online!](https://tio.run/##jZDBboMwDEDv@QrvUJqUsJIUGFoJFVRC2pU/CC1UTChMwKb9PQsFtrabql1sK@/FTvwqP2R7aMq3zlL1Me8L0WNJM9oQEdqfzt7d2xs/9n1XhSHG0hIZWUnTc9WqIQvuc7VwPGUw1R9q1dZV/ljVJ1xgeFIUwNPBVoTAeg2FrNoc3VhcC8zWYXPPGtoA08G5sm41dx7JJq1r3n/18gfOLib@JbF/SGd@Nvkdic/SVSeUCPS9Zb1VIYNsl1nyWVoZCb0d40NNAtEgVNQNjkAA20IEgc5cF6ZJEMCA4hHFM4pHNMJUQ3sL6QAdnWemKY7L04vqcEQoTGX8U6b6sQ8CEhzpIwopAcOYbl5@cJnIssqPw6wlhdntvwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 52 bytes
```
lambda a,b,c:a in[i%12or 12for i in range(b-c,b-~c)]
```
[Try it online!](https://tio.run/##bc3NCsIwDMDxu08RkMEGGazxE2FPoh7Sumph60atBy@@eo2DIQ4vOfz4Jxme8dZ7SrY@pZY7fWFg1GgODM4fXaaoD6DIynQiENhfm1yXBnX5MsU5DcH5CDbfAW4BqwKWltt7s5h8M7oSj@Hx5b2YwtWc1X8m4Wrk3@PSygbN889DwPWUpzc "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 52 bytes
```
lambda a,b,c:any(set(range(b-c,b-~c))&{a,a-12,a+12})
```
[Try it online!](https://tio.run/##bc1NCsIwEIbhvacYECTBCTTjL4I3cTOJjQptLGlcFNGrx1gQaXX78M43TRfPV0/J7Q@p4tocGRgN2h37TrRlFIH9qRRGWTTqaaWc3RlZaUKea3rI1ISLj@DEBnANWEiYOq7acvLxVe86ewy3L2@zaVyMWf9nylz0PBzPbb6gcf5@CLj8yWmwnl4 "Python 2 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 50 bytes
```
lambda a,b,c:any({*range(b-c,b-~c)}&{a,a-12,a+12})
```
[Try it online!](https://tio.run/##dY3LCsIwEEX3fkVAkEQn0Ex9IfgnbiaxUaHGEuOilPrrMVVESnB7zj3cpg3nmyuj3R9iTVd9JEagwezItbybe3KnimtpQMunEf2sIyCpEGihsBex8RcXuOUbBmsGhRBsaqm@V5OvWL2FGkTwjx/fJqigzLj6wzHx4sPHB2mdGsyC4ZXBMg9w/BBf "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
α6Ýûsè@
```
-3 bytes by porting [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/190067/52210), so make sure to upvote him!
-1 byte thanks to *@Grimy*.
Inputs in the same order as the challenge description: `one`; `two`; `range`.
[Try it online](https://tio.run/##yy9OTMpM/f//3Eazw3MP7y4@vMLh/38jLkNDLmMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WGZSg5JlXUFpSbKWQn5dqe3i/tUJJeT6YLkrMSweJKOlwKfmXlgAVWSko2QN1/D@30ezw3MO7iw@vcPivc2ib/f/oaCMdQ0Md41idaHMdMx0DIG0KpA2BtAVMwhDGACo1gIgAhXSMgAygSh0TkABQCigTCwA).
**Explanation:**
```
α # Take the absolute difference between the first two (implicit) inputs one & two
6Ý # Push the list [0,1,2,3,4,5,6]
û # Palindromize it: [0,1,2,3,4,5,6,5,4,3,2,1,0]
sè # Swap to get the earlier number again, and use it to index into the list
@ # Then check if the (implicit) input range is larger than or equal to this value
# (after which the result is output implicitly)
```
[Answer]
# Java 10, ~~70~~ 38 bytes
```
(o,t,r)->((o=o<t?t-o:o-t)>6?12-o:o)<=r
```
-32 bytes by porting [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/190067/52210).
[Try it online.](https://tio.run/##dVBBboMwELznFStORhgUaJtWEJJzD00POVY9OMSNSImN7CVVVfF2ugakkkaRzMo7nhlm9yjOIjzuP7uiEtbCiyjVzwygVCjNhygkbFwLsNO6kkJBwegJNHcV@2r8jBgtfXQsCiwL2ICCHDqmOXLjhyvGdK6XuMZQpzpEf7VYx4m7@8vcdNmMlHWzq0g5Gpx1uYcThWFbNKU6vL2D8IckKC2yhMcxv@v/PCKPfMHnU@CBgHgKPF1p4iuEfOf/OETiyRQhW35/QSHVKGpnf0voZ@gJ/cqUHJb2NSzPCHWQ40jbb4vyFOkGo5qmxUox71nVDdrU6XIvoBp4mRNTQ9U1vQO1g1N20@m1QbJKwQtUVDCXw2UYVLdl4zht9ws)
**Explanation:**
```
(o,t,r)-> // Method with three integer parameters and boolean return-type
((o=o<t?t-o:o-t) // Replace `o` with abs(t-o)
>6? // And if it's smaller than 6:
12-o // Use 12-o
: // Else (it's larger than or equal to 6):
o // Use o itself
)<=r // And check if that is smaller than or equal to r
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
₧╝g╙╖²╞
```
[Run and debug it](https://staxlang.xyz/#p=9ebc67d3b7fdc6&i=0+7++6+%0A1+5++6+%0A3+8++11%0A3+1++11%0A3+2++10%0A2+11+1+%0A4+6++1+%0A3+12+1+&a=1&m=2)
It takes input as space separated `[range] [one] [two]` and outputs `0` for false, `1` for true.
In pseudo-code:
```
d = abs(one - two)
return min(d, 12 - d) <= range
```
Hm, that's probably almost a python submission.
[Answer]
# [Python 2](https://docs.python.org/2/), 31 bytes
```
lambda o,t,r:5-r<(o-t+6)%12<7+r
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFfp0SnyMpUt8hGI1@3RNtMU9XQyMZcu@h/kIKtQlFiXnqqhqGOobEmV1p@kUKRQmYeVNBU04qLEySWDxILsiooyswrUVBX18vKz8zTUNeLUI9O0wAbrhmrAFJXAlanycUJUfkfAA "Python 2 – Try It Online")
**[Python 2](https://docs.python.org/2/), 33 bytes**
```
lambda o,t,r:abs((o-t+6)%12-6)<=r
```
[Try it online!](https://tio.run/##LcyxDsIgEIDhuTzFLQYu0ibU2IHIS3QyUQcaRWmUa04Wnx5Ddf3z5V8@@UGpL8Gdy9O/pqsH0lmz9dNbKWrzdsCN6dsBD47LCA7Yp/tNGW12KAIxMMT0j3u0oqmNahvtwjFlkLKbKSYlu6M8BbXu8QLV5dWhaH6yfAE "Python 2 – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 35 bytes
```
f(o,t,r)=o [[email protected]](/cdn-cgi/l/email-protection)(t-1+(-r:r),12)+1
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/P00jX6dEp0jTNl8hM89BLzc/RaNE11BbQ7fIqkhTx9BIU9vwv0NxRn65QpqGkY6hoY6xJheMb65jpmOA4JoCuYYIrgWaakM0PtA0AxR5oAIdIwQfaJiOCZI0UD1I@X8A "Julia 1.0 – Try It Online")
[Answer]
# JavaScript, 37 bytes
```
r=>b=>g=a=>a-12<b-r?g(a+12):a-12<=b+r
```
[Try it online!](https://tio.run/##hc5NDsIgEAXgvadgCWmwDv7UGAfPQisQDSkGqtfHlrpoGq2L2cx8eW/u6qViE26Pjrf@qpPBFFDWKC0qlIqDONc8XCxVBQh2ygusi5Aa30bv9Np5Sw0lG0bJoZ@KMVKWxCgX9WpmtozC4MSC2fV3yFkTM0fwKduPqAvPr10DO/4n8JuI8RuAxZRMxISkNw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes
```
Abs@Mod[#-#2,12,-6]<=#3&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@98xqdjBNz8lWllX2UjH0EhH1yzWxlbZWO1/QFFmXglQ2E7DzcFBWTNWTUHfQaG62lxHwUxHwaBWR6HaFMw0BDEtgLShjoIxiG2IxDYCsg1g4iAJHQUjENsMzDQBCxuB2ca1tf8B "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Haskell, 42 bytes
```
t#r=(`elem`[1+(n-1)`mod`12|n<-[t-r..t+r]])
```
`two # range` returns a function which when applied to `one` returns a `Bool`.
[Try it online!](https://tio.run/##RU67DsIwDJzhKyzokKguIuU5AOIDYGIsFY0gAkSboMSIhX8vLqgw3eke9l10uJmyrGvq@6UoTGmqIlOxsImSReVOhUpfdpFklPjBgGKf57Ku9NXCEk6u2ykNAZlARx1MYC0TKSqFI4lihlMcMk4YFeO8NVRLODr8KixhyoSTOG4EttjJu51K37cHEPv2yVo4a5CeDr22ZyMhWcH9QTvyGwsRhIt7/gZBHEOvCfQaJj5eBMDl/qcc8Skp//vrNw "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 bytes
```
aV
aC mU §W
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YVYKYUMgbVUgp1c&input=OAoxMSAKMw)
[Answer]
# Ruby, 45 characters
```
->o,t,r{[*1..12].rotate(t-r-1)[0..r*2].any?o}
```
Nothing fancy, just a chance to use [`Array#rotate`](https://ruby-doc.org/core-2.6.3/Array.html#method-i-rotate).
Sample run:
```
irb(main):001:0> ->o,t,r{[*1..12].rotate(t-r-1)[0..r*2].any?o}[2, 11, 3]
=> true
```
[Try it online!](https://tio.run/##nZJBTsMwEEXXySlGlapA5Fh1SksVqfQIHCDKwiQuIEIc2WOgansLFiw4HRcJTtKkFaEL2Mwfj958jzSjzN2mWpsixUdZwLIKbiRBoraxzyhlYUKVRI7iAgMVsMt4QqnybZUXm5XcV6VBDaMdjKca@jhrYrBoZd5KaGUEY4g9WQiPgIevshbFi/vmLd5KkaLI6pynaHheZ7dPXuLGrrO1XRHANQHbZ5M5gaYzgonNhDY5RrDmuRZ70tOzIc2ONCpzCi8OMGM9PD0Ls7/AYQdPfoN/DM06azhah2et50P46rx1OKSHUydU8PQBMgk7FBoJcAKaQLZzHb/kij8LFIpAty5YQo3RF54boV2nXZ2tdjcVH7sS1/nHwfgn/naaxv/0/@WhBiuIvj7fIarlI3FFkVXf "Ruby – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 27 bytes
```
o%t=(abs(mod(o-t+6)12-6)<=)
```
[Try it online!](https://tio.run/##TckxDoIwAEbhnVP8A4Q2po0Qw9SuXkAHE9KhIiixUGjLxtmthMG4vS/vpf27NSZGmwVJ9N2TwT6IZeFQ0aJkFRWSxk6SjCYzrm5pIZHf8g1nbfwunieD7sctpyVcgkOKZTT92HrUv6jntINFgFsDBENdcF6USmGFFexPbr9Hzk9KxU/TGf30kTXT9AU "Haskell – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
‹⁵⁺N↔⁻⁶↔⁻NN
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMntbhYw1RHISCntFjDM6@gtMSvNDcptUhDU0fBMak4P6e0JFXDNzMPKGuGIYKmHoULBdb//5soGCkYGvzXLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Takes the size of the range as the first input. Output uses Charcoal's default Boolean format of `-` for true, nothing for false. Explanation:
```
NN Two inputs
↔⁻ Absolute difference
⁶ Literal 6
↔⁻ Absolute difference
⁺N Plus range
‹⁵ Is greater than 5
```
[Answer]
# [R](https://www.r-project.org/), 48 bytes
```
function(a,b,r){a%in%c(9:12,1:12,1:4)[-r:r+b+4]}
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUSdJp0izOlE1M081WcPSytBIxxBCmGhG6xZZFWknaZvE1v5P0zDXMdMx0ORK0zAFMgxBDAsdQ0MdYxDLEM4C6jSAigEFdYxALKByHROwEFAWJMnF9R8A "R – Try It Online")
Pretty straightforward, I struggled for a while to find the best way to test if a was in the given range. There is likely a method I haven't seen or tried yet.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~78 bytes~~ ~~80 bytes~~ 72 bytes
```
(a,b,r)=>Enumerable.Range(b-r,2*r+1).Select(x=>(x+12)%12).Contains(a%12)
```
[Try it online!](https://tio.run/##bc3RCoIwFAbg@55iN8FZHsWtssL0Juo66gm2MUOwCVPBt1/ToEy6OAf@j59zVBOqpnSXzqhjaVok3yXrusqLzIFAiZZm@dl0T22FrHR0E@ahQYYW@coGjEZ3XWnVQp/l0AeM06Wf6FSbVpSmATFEly4WV@tPQwE7JAmSmNL0Q9uR2JT2PjMk66mxP8a9xfPeUETCp5aMtPmp8dHmLw7vmnsB "C# (Visual C# Interactive Compiler) – Try It Online")
Edit: Range was incorrect, I forgot to count the item itself, adding 2 bytes. But I bit the bullet dealing with C#'s modulus actually being *remainder*, saving 8 bytes. Technically, this code actually treats 12 as 0, but this is still valid in this context.
[Answer]
# [C#](https://visualstudio.microsoft.com/), 158 bytes
```
using System;public class P{public static void Main(string[]a){int w=Math.Abs(int.Parse(a[0])-int.Parse(a[1]));Console.Write((w>6?12-w:w)<=int.Parse(a[2]));}}
```
[Try Online](https://dotnetfiddle.net/lraaw5)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 7 bytes
```
-±_B,╓≥
```
[Try it online!](https://tio.run/##y00syUjPz0n7/1/30MZ4J51HUyc/6lz6/7@5gpmCAZcpkDTkslAwNFQw5jKEUEYKhgYgHpCrYMQFlFcw4TIECioY/wcA "MathGolf – Try It Online")
Other valid 7-byters include:
```
-±7rñ§≥
-7rñ╡§≥
```
I found a **4-byter** which solves every test case, but doesn't solve the problem in general:
```
-±Σ≥
```
[Try it online!](https://tio.run/##y00syUjPz0n7/1/30MZzix91Lv3/31zBTMGAyxRIGnJZKBgaKhhzGUIoIwVDAxAPyFUw4gLKK5hwGQIFFYz/AwA)
The approach of the 7-byters are basically ports of existing 7-byte solutions. The 4-byter relies on the fact that the digit sum of the absolute difference of the first two is less than the third input for all test cases. That correlates with the desired output for the test cases, but not in general.
[Answer]
# [Perl 5](https://www.perl.org/), 63 bytes
```
sub f{grep$_[0]==$_%12,(1..36)[11+$_[1]-$_[2]..11+$_[1]+$_[2]]}
```
[Try it online!](https://tio.run/##jZBRb4IwFIXf@RX3oUsgIKU4dZHVaLLXvfnmSOO0ogkCaUvcou6vu5bizNQl46Hh3n73nHNbcZH3TidZv8NqnwleITaLUkoReyBx4JIw7Pa9GSG@7pO0o884DcNz7Td1erTzEewd0N/200VlwQOkdmWAxLzIuEfHLGkvYVzQVti2BFe1KCDyjT@Y0bO/RhtvLdSxQtZb176t08Q5OrXkMOVSDYevpeCg9K@ko0Hi7NabnLvPL5PpZOTtYbEut1XyV8YA8Y@KLxRfenQ7r0BiJWqOCRb0S@LVPJccR1gEgN23pX8wl4em6@HsZzeUlYqubve3wEa6Brg4BYh5ZgPGTEbGHLP8AEBP0r5@GTNLo@aNZJ1rZePXQL0riFwgk6xhnixDSMt07zDkH0zcMtEtcwmkFRroHCi@I9SH38zjldDpGw "Perl 5 – Try It Online")
Ungolfed:
```
sub f {
my($one, $two, $range) = @_;
my @n = (1..36);
return 0 + grep $one==$_%12, @n[ 11+$two-$range ..
11+$two+$range ];
}
```
] |
[Question]
[
# Task
Given a number between 0 and 1 and another integer, print the approximated value of the first number rounded off to the specified number of digits given by the second integer. For example, if the input is `0.3212312312 , 2` then the output is:
`0.32`
# Rules
* The number of digits after the dot should always equal the second input integer.
* The input will always be `([)number from 0-1 , integer above 0(])`
* Predefined round functions are allowed.
* The first input number will not have any trailing 0's
* Always use a dot for input and output. Commas are not allowed.
* Fractions are allowed as output with the notation `number/number` but try to just use a decimal notation.
[Trailing zero rule removed due to that i should have been faster]
* Rounding should always be done to the closest number so up if above 4 and down if under 5.
# Testcases
Input: 0.31231231231 , 1
Output:
0.3
Input: 0.1, 10
Output:
0.1000000000
Input: 0.01231231231 , 9
Output:
0.012312312
# Scoring:
This is code-golf. Shortest answer in bytes wins.
Suggestion for making this challenge better are appreciated. Have fun golfing!
EDIT:
definition of this challenge by Francisco Hahn: `shortest way to round a float X with precision N on each language`
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
/* Configuration */
var QUESTION_ID = 166330; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<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]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 1 [byte](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 infix function (actually just a built-in). Takes number of decimals as left argument and fraction as right argument.
```
⍕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hv1P9pj9omPOrte9Q31dP/UVfzofXGj9omAnnBQc5AMsTDM/i/kUKagoGesZGhkTEYcRlCBGB8Y0MuQwOwkCGXJZg2QEgBAA "APL (Dyalog Unicode) – Try It Online")
[Documentation for dyadic `⍕`](http://help.dyalog.com/17.0/Content/Language/Primitive%20Functions/Format%20Dyadic.htm "Format Dyadic") ("Format By Specification").
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 18 bytes
```
a=>b=>a.toFixed(b)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i7J1i5RryTfLbMiNUUjSfN/cn5ecX5Oql5OfrpGmoaCgZ6xoREMaWooGGpqcmEoMUBRYqmp@R8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 bytes
```
xV
```
[Try it online!](https://tio.run/##y0osKPn/vyLs/38DPQNDI2MoUtBRMAIA "Japt – Try It Online")
**x** is the builtin for rounding to **n** decimals. We pass in **V** (Second input).
[Answer]
# Japt, 2 bytes
Takes input as an array of 2 numbers.
```
rx
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=cng=&input=WzAuMDEyMzEyMzEyMzEsOV0=)
`r`educes the array by rounding the first number to the number of decimals specified by the second.
[Answer]
# [PHP](https://php.net/), ~~47~~ 39 bytes
```
function a($b,$c){return round($b,$c);}
```
[Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MUEjVUknRUkjWri1JLSovyFIryS/NSoGLWtf9TkzPygWoM9IwNjWBIQUfBUFNBT0EpJk/JmguuwgBFhSVCBZe93X8A "PHP – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/) (produces rounded float, no trailing zeroes), 5 bytes
```
round
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzvyi/NC/lf0FRZl6JRpqGgZ6RiY6CoabmfwA "Python 3 – Try It Online")
Python's [built-in `round` function](https://docs.python.org/3/library/functions.html#round) is defined to do exactly what the OP wants in the summary edited in later "round a float X with precision N", though without appending trailing zeroes (because it's still returning a `float`, and `float`s don't include information about their formatting).
# [Python 3](https://docs.python.org/3/) (produces string form), 16 bytes
```
'{:.{}f}'.format
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzX73aSq@6Nq1WXS8tvyg3seR/QVFmXolGmoaBnpGJjoKhpuZ/AA "Python 3 – Try It Online")
Formatting operations can use a nested specifier to allow one argument to define the precision of the other. Doesn't print it, but returns a formatted string with the specified precision.
# [Python 3](https://docs.python.org/3/) (prints string), 30 bytes
```
lambda a,b:print(f'{a:.{b}f}')
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ8mqoCgzr0QjTb060UqvOqk2rVZd83@ahoGekYmOgqHmfwA "Python 3 – Try It Online")
Python 3.6+ f-strings save some characters here (couldn't use them without the wrapping function since we wouldn't know the names to use). Mostly included to demonstrate f-strings (obviously longer than other solutions).
[Answer]
# [Python 2](https://docs.python.org/2/), 24 bytes
-4 bytes thanks to ovs
```
lambda a,b:"%%0.%sf"%b%a
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFRJ8lKSVXVQE@1OE1JNUk18X9BUWZeiUaahoGekYmOgomm5n8A "Python 2 – Try It Online")
[Answer]
## PHP, 28 Bytes
[Try it online](https://tio.run/##K8go@G9jX5BRwKWSWJReZhttoGdsaARDOoax1lz2dkAVtkX5pXkpGmBF0QaxOhCGYaym9f//AA)
**Code**
```
<?=round($argv[0],$argv[1]);
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 26 bytes
Assuming decimal is on top of the floating point stack and precision is on the integer stack
```
: f dup 2 + swap 1 f.rdp ;
```
[Try it online!](https://tio.run/##S8svKsnQTU8DUf//WymkKaSUFigYKWgrFJcnFigYKqTpFaUUKFj/N9AzNjSCoVSQhEJyEZeBHohtAOMYICuxBIv@BwA "Forth (gforth) – Try It Online")
### Explanation
`f.rdp` takes a float and 3 arguments from the integer stack:
1. the width of the output (answer uses `n+2` to account for 0 and decimal point)
2. the number of digits after the decimal (answer uses `n`)
3. the required number of significant figures in the input (answer uses 1, because floats with less significant figures are outputted in exponential notation)
### Code explanation
```
dup 2 + swap 1 \ place n+2 n and 1 on top of the stack
f.rdp \ formats output
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 1 bytes
```
j
```
[Run and debug it](https://staxlang.xyz/#c=j&i=0.3212312312,+2%0A0.1,+10&a=1&m=2)
In stax, `j` is a built-in instruction that performs the required rounding.
[Answer]
# T-SQL, 24 bytes
```
SELECT STR(f,20,d)FROM t
```
[Per our input standards](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 float **f** and integer **d**.
The [function `STR()`](https://docs.microsoft.com/en-us/sql/t-sql/functions/str-transact-sql?view=sql-server-2017) is shorter and more convenient than either a `CAST` or a `ROUND`.
You didn't specify, so I assumed that 20 digits would be more than sufficient. If not, that hard-coded value can be increased.
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 21 bytes
```
n->d->n.setScale(d,4)
```
[Try it online!](https://tio.run/##bVDRaoMwFH33Ky4FIRlp0G0va9c@jDHYw9hDH8WH1EQXp1HMtaMUv91Fq2s3BglJzjn3nHuTi4NY5vKz12VdNQi5e/NS4Ae/WXvXWIu6@BdLW5OgrsxAJoWwFt6ENnDyAOp2X@gELAp0x6HSEkrHkR022mRRDKLJLB2lAC@Tz@OTzp5VoktRsFeDM7yFFDa9WW7lcmu4VbhLRKGIZPe0X48G7/tcJRjFzheVRQubyRngBIuA34W381owCKFj1@yIBX/A4FfJw8x258C0aoDMqWPm6pxMf4IPogHjGjHqCy5zkekH6KCOgpiur@TSyYkbXGWqOQvCeOZ3R4uq5FWLvHYGmJKFnzLw5Qp86xvXo2EgGaRc1HVxJIZOF0mnjM4bdtd/Aw "Java (JDK 10) – Try It Online")
I would have loved to have submitted `n->n::setScale` (14 bytes) but alas, there is no default rounding, so we get `ArithmeticException` when rounding is required...
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
i'%.'j'f'hhYD
```
[Try it online!](https://tio.run/##y00syfn/P1NdVU89Sz1NPSMj0uX/fxMuYwA "MATL – Try It Online")
### Explanation:
```
i % Grab first input: 0.32315
'%.'j'f' % Push the literal: ['%.' second input as string 'f'], where the input
% specifies the number of decimals
YD % printf('%.sf',x) where s is the second input, and x is the first
```
[Answer]
# [R](https://www.r-project.org/), ~~40~~ 36 bytes
```
function(x,n)format(round(x,n),ns=n)
```
[Try it online!](https://tio.run/##K/qfZqP7P600L7kkMz9Po0InTzMtvyg3sUSjKL80LwUsoJNXbJun@T9Nw0DP2NAIhhR0FAw1uUCChkCWAYRpgCJvqfkfAA "R – Try It Online")
(-4) thanks to [digEmAll](https://codegolf.stackexchange.com/users/41725/digemall)
[Answer]
# [Julia 0.6](http://julialang.org/), 51 bytes
```
(x,d)->(y=string(round(x, d));y*"0"^(d-endof(y)+2))
```
[Try it online!](https://tio.run/##Tc1BCsIwEIXhfU4xdDWjaZlUEKTUi4iCMEYiJSljC83pYxYKwlt9i/e/1incj0XHgpsVas@Yx/eiIT5R0xqlKgjRkHcNNzeU9hElecy074mKTwoeQoSLouvYgmOyoMjdwfW/Wfc1/jM40dXMtbNMET2ZemvKBw "Julia 0.6 – Try It Online")
With trailing zeros as per the questions's "Trailing zeroes should be added with for example 0.1, 10" condition.
Julia's `@printf` can only take constant X values in `%.Xf` format strings (`%.4f`, etc.), so instead this code manually pads the required number of zeros if the rounded value has less than d digits after the decimal place.
First, store the rounded number as a string in `y`. Then, the number of digits after decimal point in `y` is `length(y) - 2` (`- 2` because the inputs are between 0 and 1, so there's one initial digit and then a decimal point to subtract). `endof(y)` is just a shorter way to write `length(y)` (at least for Julia v0.6).
Then, subtract this from the required number of digits `d`. Then, `(d-(endof(y)-2))` (= `(d-endof(y)+2)`) tells you how many digits are missing in the output (if any). Use that in `"0"^(d-endof(y)+2)` to get "0" repeated that many times, and then append that to `y` with the string `*` (concatenate) operator.
---
# [Julia 0.6](http://julialang.org/), 5 bytes
```
round
```
[Try it online!](https://tio.run/##yyrNyUw0@19k@78ovzQv5X9afpFCmkJmnkJ0kYahnoGOgqGBpo5CkYaBnrGhEQzpGELFDJDEFCw1Y7kKijLzSnLyNNI0uVLzUrj@AwA "Julia 0.6 – Try It Online")
Without trailing zeros, conforming to the summary "shortest way to round a float X with precision N on each language".
[Answer]
74 Bytes Python 2.7
```
lambda x,y:str(x)[:y+2]if int(str(x)[y+2])<5else float(str(x)[:y+2])+.1**y
```
Messy but I think it works for all the scenarios.
[Answer]
# [Perl 6](https://perl6.org), 18 bytes
```
{$^a.base(10,$^b)}
```
[Try it](https://tio.run/##bY5fS8MwFMXf8ykOo9rE1qxZZeDGpq8DcS@@qYP@SaXQrqVJRRn77DWp7TbBEJLDPef@7q1lU8y7Vkl8znmyJKT8xnVSpRKr7uDsIh5HSlIR@M4uZsfOuI9aKo3FCs7N5pknVRnTKd5SD68ud614f8CU8ayING8qXTU0ZPwpV9rA7ZwXaWVdRHt4PWtJsqoZsLdrUDj7toxl48NJ849cKyPkVy0TLVMwHAiQK9gdKbxT1hvCYBdxH5MhYPbJa56VmrpX4k65rC9QhnHI4FkLWK1xhkzIsQt4OBOzsL/wMSO2QMwrfIjA/sF4CNns61YvYCJjSyhMkyDbVo/OReoXcfb@RQV/UPcX8ZPzAw "Perl 6 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.ò0¹²g-Ì∍J
```
`.ò` is the builtin that already gives the answer for most test cases. `0¹²g-Ì∍J` is to correctly append trailing zeroes if necessary.
[Try it online](https://tio.run/##MzBNTDJM/f9f7/Amg0M7D21K1z3c86ij1@v/f0MDLgM9QwA).
```
.ò # Round the second decimal input to the integer first input amount of decimals
# i.e. 10 and 0.1 → 0.1
# i.e. 1 and 0.67231 → 0.7
0 # Literal '0'
¹ # Get the first integer input
²g # Get the length of the second decimal input
- # Subtract them from each other
Ì # Increase it by 2 for the "0." part
# i.e. 10 and 0.1 → 10-3+2 → 9
# i.e. 1 and 0.67231 → 1-7+2 → -8
∍ # Extend the "0" to a size of that length
# i.e. "0" and 9 → "000000000"
# i.e. "0" and -8 → ''
J # Join everything together
# i.e. 0.1 and "000000000" → 0.1000000000
# i.e. 0.7 and '' → 0.7
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 28 bytes
```
@(x,y)printf(['%.',y,'f'],x)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KnUrOgKDOvJE0jWl1VT12nUkc9TT1Wp0Lzf5qGiY66ibrmfwA "Octave – Try It Online")
Takes the first input as a number and the second as a string. Creates a formatting string: `%.yf` by concatenation, where `y` is the input that specifies the number of decimals. `x` is the input number that will be printed.
[Answer]
# [R](https://www.r-project.org/), 42 bytes
```
function(x,n)sprintf(paste0("%.",n,"f"),x)
```
[Try it online!](https://tio.run/##K/qfZqP7P600L7kkMz9Po0InT7O4oCgzryRNoyCxuCTVQENJVU9JJ09HKU1JU6dC83@ahoGesaERDCnoKBhqcoEEDYEsAwjTAEXeUvM/AA "R – Try It Online")
Failed attempt at outgolfing [DS\_UNI](https://codegolf.stackexchange.com/users/78898/ds-uni)'s [shorter R answer](https://codegolf.stackexchange.com/a/166412/80010).
Even worse:
## [R](https://www.r-project.org/), 43 bytes
```
function(x,n)sprintf(sprintf("%%.%if",n),x)
```
[Try it online!](https://tio.run/##K/qfZqP7P600L7kkMz9Po0InT7O4oCgzryRNA0YrqarqqWamKQGldCo0/6dpGOgZGxrBkIKOgqEmF0jQEMgygDANUOQtNf8DAA "R – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 19 bytes
```
"%.${b}f".format(a)
```
[Try it online!](https://tio.run/##y84vycnM@59WmqeQm5iZp5FYlF5speBYVJRYaRNcUpSZl26nqVDNxZmen5OmYaBnbGgEQzoKRppctVycXCC9YOlEKwWX/NKknFQdhSQrBc@8ErDOAqAhJTl5Gv@VVPVUqpNq05T00vKLchNLNBI1/3OCjPgPAA "Kotlin – Try It Online")
[Answer]
# [Tcl](http://tcl.tk/), 31 bytes
```
proc R x\ n {format %.*f $n $x}
```
[Try it online!](https://tio.run/##K0nO@f@/oCg/WSFIoSJGIU@hOi2/KDexREFVTytNQSVPQaWi9n9ObmKBQmKMQpJCNZeBnrGhEQwpGAL5QNIASBkgCVty1SpUF5SWFCsoqSQqqCQpWClEBymAmbFKtf8B "Tcl – Try It Online")
] |
[Question]
[
# Challenge
### Task
Given a number `N`, output 2 NxN squares; each line of each square is a random permutation of [0, N); the squares are separated by a newline
### Rules
* Produce a randomised list of length `N`, separated by space
* Repeat this N\*2 times
* Separate each output with a newline, with 2 newlines at the midpoint
* The value of `n` must be "obvious", you can get it via stdin; argument; whatever, but there must be a distinct value somewhere, so the value of `n` can't just be scattered across your program.
### Example
Given `n = 4`, the output could be:
```
1 2 0 3
2 3 1 0
2 0 3 1
2 0 3 1
0 3 2 1
3 1 0 2
0 1 3 2
0 2 1 3
```
Lowest number of bytes wins
[Answer]
# J, ~~9~~ 7 bytes
Thanks to @randomra for shaving off two characters:
```
?~2&,]
```
Previously I had:
```
?~($~2&,)
```
These are functions, you can apply them to an argument directly or store them in a variable and then use them:
```
(?~2&,$]) 5
1 0 4 2 3
2 4 0 3 1
2 3 1 0 4
2 3 0 1 4
3 0 1 4 2
1 4 0 2 3
2 1 4 3 0
2 3 1 0 4
2 3 1 4 0
0 1 2 3 4
f=.?~2&,$]
f 5
4 2 3 0 1
3 4 1 0 2
3 4 0 2 1
1 2 4 3 0
2 0 4 1 3
2 1 3 0 4
1 3 4 2 0
2 4 1 3 0
3 2 1 0 4
3 0 4 2 1
```
[Answer]
# Pyth, 13
```
V2VQjdoOQUQ)k
```
Pretty simple program, I believe it follows the spec.
[Try it online here](https://pyth.herokuapp.com/?code=V2VQjdoOQUQ)k&input=5)
Explanation:
```
: Q = eval(input)
V2 : Do the next part twice
VQ ) : Do the stuff before the ) Q times
jd : Join the resulting list on spaces
oOQUQ : order range(Q) by random_int( from 0 to Q )
k : print nothing (pyth auto-pads each print with a newline)
```
[Answer]
# R, ~~73~~ ~~71~~ ~~66~~ ~~62~~ 54
I feel there should be a better way, but at the moment
```
n=5;for(i in 1:(n*2))cat(sample(n)-1,rep('\n',1+!i-n))
```
Edit: Replace rank(runif(1:n))-1 with sample(1:n)-1. Used rep instead of if. Thanks to Alex A for a few more.
Test run
```
> n=5;for(i in 1:(n*2))cat(sample(n)-1,rep('\n',1+!i-n))
0 3 1 2 4
0 1 4 2 3
2 3 4 0 1
4 1 0 2 3
1 0 3 4 2
4 3 1 0 2
3 0 1 2 4
4 2 3 1 0
4 2 1 0 3
3 1 0 2 4
```
[Answer]
# CJam, 22 bytes
```
l~{_{_,mrS*N@}*N\}2*;;
```
Input via STDIN. I feel like there must be a much way to do this.
[Test it here.](http://cjam.aditsu.net/#code=l~%7B_%7B_%2CmrS*N%40%7D*N%5C%7D2*%3B%3B&input=4)
[Answer]
# Bash+coreutils, 61
Input as a command-line arg.
```
seq -f"((%g))&&echo \`seq 0 $[$1-1]|shuf\`||echo" -$1 $1|bash
```
[Answer]
## Clip, 29
```
[zjm[ Jm[ jkwRRzwS}Rz}R2:2N]n
```
Takes input from STDIN.
```
[z ]n .- z is the numeric value of the input -.
j :2N .- join with two newlines -.
m[ }R2 .- do twice -.
J .- join with a newline -.
m[ }Rz .- do z times -.
j wS .- join with spaces -.
kw .- wrap each number -.
R .- shuffle -.
Rz .- list of the first z numbers -.
```
Example run:
```
> java -jar clip4.jar random.clip
4
2 1 0 3
3 1 2 0
1 0 2 3
3 1 0 2
3 0 1 2
0 1 2 3
3 2 0 1
0 1 3 2
```
[Answer]
# Python 3, 90 bytes
```
from random import*
def f(n):S="*L,=range(n);shuffle(L);print(*L);"*n;exec(S+"print();"+S)
```
I'm sure there's a better method for handling the newline break in between, but I'm having trouble coming up with a way.
[Answer]
# CJam, 20 19 bytes
```
ri_a*0+2*{,mrS*}%N*
```
[Try it here](http://cjam.aditsu.net/#code=ri_a*0%2B2*%7B%2CmrS*%7D%25N*&input=4) ([for Firefox](http://cjam.aditsu.net/#code=ri_a*0%2B2*%7B%2CmrS*%7D%2525N*&input=4)).
Other solutions:
```
{T,mrS*N}_ri:T*N](T*
"T,mrS*N"ri:T*:F~NF~
LN]"T,mrS*N"ri:T*f{~}
```
[Answer]
# Java, ~~190~~ 187 bytes
```
void f(int n){int k=0,i,t,x,o[]=new int[n];for(;k<n;o[k]=k++);for(k=0;k++<n*2;)for(i=n;i>0;t=o[x*=Math.random()],o[x]=o[i],o[i]=t,System.out.print(o[i]+(i>0?" ":k==n?"\n\n":"\n")))x=i--;}
```
Clunky, but it does the job (that's Java's motto, right?). Pretty simplistic: it fills an array, then repeatedly uses my earlier [Fisher-Yates](https://codegolf.stackexchange.com/a/45305/14215) to shuffle and print. I tried using `Collections.shuffle()` instead, but it was a touch longer once you add in the import.
Ah well, such is life.
With line breaks:
```
void f(int n){
int k=0,i,t,x,o[]=new int[n];
for(;k<n;o[k]=k++);
for(k=0;k++<n*2;)
for(i=n;
i>0;
t=o[x*=Math.random()],
o[x]=o[i],
o[i]=t,
System.out.print(o[i]+(i>0?" ":k==n?"\n\n":"\n"))
)
x=i--;
}
```
[Answer]
# Python - 139 138 bytes
```
import random as r
n=4
s=range
t=s(0,4)
print('\n\n'.join('\n'.join(' '.join('%d'%i for i in r.sample(t,n)) for j in t) for k in s(0,2)))
```
EDIT: Knocked off a byte
[Answer]
```
import static java.lang.System.out;public class A{public static void main(String[]a){int n=Integer.decode(a[0]);for(int x=0;x<2;x++){for(int i=0;i<n;i++){java.util.stream.IntStream.range(0,n).parallel().forEach(k->out.print(k+" "));out.println();}out.println();}}}
```
As short as I could manage in Java - 265 bytes.
It takes an ordered stream of n integers and concurrently prints them separated by a space, so the output order is non-deterministic and it does this per line.
EDIT:
If done as only a function:
```
void g(int n){for(int x=0,i=0;x<2;x++){for(;i<n;i++){java.util.stream.IntStream.range(0,10).parallel().forEach(k->out.print(k+" "));System.out.println();}System.out.println();}}}}}
```
This is 179 bytes; the ordering may not seem very random - but as far as I'm aware it is quite non-deterministic.
[Answer]
# Rebol - ~~76~~ 75
```
N: 4 do b:[loop N[print random collect[repeat i N[keep i - 1]]]]print""do b
```
Ungolfed:
```
N: 4
do b: [
loop N [
print random collect [
repeat i N [keep i - 1]
]
]
]
print ""
do b
```
[Answer]
# PHP, 109
```
$n=4;$p=range(0,$n-1);for($k=0;$k<2;$k++){for($i=0;$i<$n;$i++){shuffle($p);echo join(' ',$p)."\n";}echo"\n";}
```
New implemented solution uses 1 more bytes. But now fulfill OP requirement.
Old solution which do not randomize permutation of line.
# PHP, 108
```
$n=4;for($k=0;$k<2;$k++){for($i=0;$i<$n;$i++){for($j=0;$j<$n;$j++)echo rand(0,$n-1)." ";echo"\n";}echo"\n";}
```
[Answer]
# PHP (106 bytes):
This one was quite unexpectedly hard.
But here is a somewhat large solution:
```
<?for(;3>$j++;$o='',$z=range(0,($i=$n=$_GET[n])-1)){for(;$i--;shuffle($z))$o.=join(' ',$z)."
";echo"$o
";}
```
This can be rewritten to Javascript quite 'easily'.
For this to work, you must access the file over an http server, with `?n=<number>` appended to the name.
[Answer]
# Ruby - 69
```
r=->(n){[0,0].map{(1..n).map{(0..n-1).to_a.shuffle*" "}*"\n"}*"\n\n"}
```
Sample output:
```
puts r[5]
```
yields:
```
3 0 2 1 4
0 4 1 3 2
2 1 0 4 3
0 4 2 1 3
4 1 2 3 0
4 0 3 2 1
3 1 0 2 4
3 4 0 2 1
0 2 3 4 1
3 2 4 0 1
```
and
```
puts r[7]
```
yields
```
5 4 0 6 1 3 2
6 3 1 2 4 0 5
5 2 1 0 6 4 3
4 0 5 2 3 1 6
0 6 3 1 4 5 2
6 3 0 2 5 1 4
2 4 1 0 6 5 3
0 1 4 3 6 5 2
3 5 4 2 6 1 0
2 3 5 1 4 6 0
3 0 5 2 1 4 6
4 6 5 0 2 3 1
6 5 3 2 0 4 1
3 4 6 1 0 5 2
```
[Answer]
# Scala, 105 98 95 84 bytes
```
(n:Int)=>{def s=0.until(n).permutations take n map(_ mkString " ") mkString "\n";s+"\n\n"+s}
```
### Ungolfed
```
def squares(n: Int): String = {
def square(n: Int): String = 0.until(n).permutations.take(n).map(_.mkString(" ")).mkString("\n")
square(n)+"\n\n"+square(n)
}
```
[Answer]
## C++ 201
```
void f(int n)
{
std::vector<int> v;int N=n;
while(n--)v.push_back(n);
for(int i=0;i<2*N+1;i++)
{
random_shuffle(v.begin(),v.end());
if(!(i==N))for(int j=0;j<N;j++)printf("%d ",v.at(j));
else puts("");
puts("");
}
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2FFL<.rðý,}¶?
```
[Try it online.](https://tio.run/##yy9OTMpM/f/fyM3Nx0av6PCGw3t1ag9ts///3wQA)
Or alternatively:
```
·FIL<.r})»2ä»
```
[Try it online.](https://tio.run/##yy9OTMpM/f//0HY3Tx8bvaJazUO7jQ4vObT7/38TAA)
**Explanation:**
```
2F # Loop 2 times:
F # Inner loop the (implicit) input amount of times:
L< # Push a list in the range [0, (implicit) input-1]
.r # Randomly shuffle it
ðý # Join it by spaces
, # Pop and output it with trailing newline
}¶? # After the inner-loop is done: print a newline
· # Double the (implicit) input
F # Loop that many times:
IL< # Push a list in the range [0, input-1]
.r # Randomly shuffle it
}) # After the loop: wrap everything on the stack into a list
» # Join each inner list by spaces, and then each string by newlines
2ä # Split it into a list of two equal-sized strings
» # And join those by newlines as well (which is output implicitly as result)
```
If a leading instead of trailing newline is allowed, the first version could be `2F¶?FL<.rðý,` instead, to save a byte on the `}`: [Try it online](https://tio.run/##yy9OTMpM/f/fyO3QNns3Hxu9osMbDu/V@f/fBAA).
] |
[Question]
[
A triangle-shaped table is constructed such the first row is "1, 3, 5, 7, ..., 99"
Each subsequent row has the following properties:
* One less element than the row above
* Each element is the sum of the two elements above it
Like so:
```
1 3 5 7 9 11 ....
4 8 12 16 20 ....
...............
```
This continues until the last row with one element.
How many elements are divisible by 67?
Fewest lines, chars, or whatever may win. Depends on ingenuity.
EDIT: the answer is 17 but you have to prove it.
ADDENDUM:
I have three-line python code for this but try to beat it:
```
a = [[2*i+1 for i in range(50)]]
while len(a[-1])>1:a.append([a[-1][i]+a[-1][i+1] for i in range(len(a[-1])-1)])
print len([i for b in a for i in b if i%67==0])
```
[Answer]
## JavaScript: 91, 88 (thanks trinithis), 84, 77 (thanks again trinithis), 75 (thanks shesek), 74 Characters (thanks Shmiddty)
**91-->88** - See Trinithis's comment
**88-->84** - moved `j--` into conditional check.
**84-->77** - See trinithis's comment (removed `{}` from for loops, ignored first index of `a` array) plus some additional work (fixed logic for building arrays and incrementing counters)
**77-->75** - See Shesek's comment (instead of `(condition)&&val++`: `val+=(condition)`)
**75-->74** - See Shmiddty's comment (instead of `i=c=1,a=[]`: `a=[i=c=1]`)
Golfed:
```
for(a=[i=c=1];i<51;)for(a[i]=i*2-1,j=i++;j>1;)c+=1>(a[--j]=a[1+j]+a[j])%67
```
Ungolfed:
```
/**
* i - counter for array index and array initialization
* c - count of elements divisible by 67
* a - array of numbers in diagonal bottom-to-right row.
* For example, here are the first 3 iterations: [1], [4,3], [12,8,5]
* j - index into array a
*/
for(a=[i=c=1];i<51;){
a[i]=i*2-1;
for(j=i++;j>1;){
c+=1>(a[--j]=a[1+j]+a[j])%67
}
}
```
[Here's a fiddle](http://jsfiddle.net/briguy37/zSNKa/) for both as well as a test that outputs what is in the arrays for the first 3 iterations.
Note: I initialize the count to 1 because the first row [1,3,5..67..97,99] has one number divisible by 67. That way, I did not have to worry about checking the first row.
[Answer]
## Haskell - 86 chars
**98 → 92**: Use list comprehensions and `sum` instead of `filter` and `length`.
**92 → 86**: Convert nested list comprehensions into one, and change `==0` to `<1` (thanks st0le).
```
f s=zipWith(+)s$tail s
main=print$sum[1|r<-take 50$iterate f[1,3..99],n<-r,n`mod`67<1]
```
Ungolfed:
```
initialRow :: [Integer]
initialRow = [1,3..99]
nextRow :: (Num a) => [a] -> [a]
nextRow xs = zipWith (+) xs (tail xs)
triangle :: [[Integer]]
triangle = takeWhile (not . null) $ iterate nextRow initialRow
main = print $ length $ filter ((== 0) . (`mod` 67)) $ concat triangle
```
[Answer]
## Mathematica 82 chars
```
Count[Mod[#,67]==0&/@Flatten@NestList[2MovingAverage[#,2]&,Range[1,99,2],49],True]
-> 17
```
[Answer]
## Python 95 bytes
```
l,c=range(1,100,2),0
while l:c+=len([i for i in l if i%67<1]);l=map(sum,zip(l,l[1:]))
print c
```
[Answer]
## Python
85 bytes - thanks to st0le
```
l,c=range(1,100,2),0
while l:c+=sum(i%67<1for i in l);l=map(sum,zip(l,l[1:]))
print c
```
[Answer]
# J, 48
```
1225-~+/,-.*67|((<:/|.)a)*(+1&|.)^:a>:2*a=:i.50x
```
Explanation (bits of it, anyway):
* a is 0 .. 49
* `>:2*a` is `1 3 5 ...`
* The verb `(+1&|.)` shifts a row and adds it to the original to get the desired next row (plus extras, since the result is still 50 elements).
* `(+1&|.)^:a>:2*a` gives 50 rows of results. Row one is `1 3 5` etc, row 2 is `4 8 12` etc.
* `((<:/|.)a)` is a 50x50 matrix of 1 1 ... 1 1, 1 1 ... 1 0 etc. down to 1 0 ... 0 0. This zeroes out the 1225 extras. (1225 is the 49th triangular number.)
* After taking mod 67 and counting, we subtract those 1225 zeroes that we know will be present.
[Answer]
## Ruby 113 bytes
```
l,c=(1..100).step(2).to_a,0
[c+=l.count{|i|i%67<1},l=l.zip(l[1..-1]).map{|x,y|x+y if y}.compact!]until[]==l
p c
```
[Answer]
# C++ 133 131 125 chars, 2 Lines
```
#include<iostream>
__int64 c=1,s=1,r,a=2,e=51,i;int main(){for(;e;c=s+=s+a,a*=2)for(i=e--;--i;c+=a)c%67?0:r++;std::cout<<r;}
```
I'm not sure how portable this is with the use of `__int64`, if it does complains you can change it to `long long`.
## Ungolfed
```
#include<iostream>
__int64 curr,start=1,ret,add=2,end_line=50;
int main(){
for(;end_line>0;end_line--,add*=2){
curr=start;
for(int i=1;i<=end_line;++i){
if(curr%67){
}else{
ret++;
}
curr+=add;
}
start+=start+add;
}
std::cout<<ret;
}
```
[Answer]
# Q, 53 43
```
sum 0=(raze{1_msum[2]x}\[1+2*(!)50])mod 67
```
.
```
q)sum 0=(raze{1_msum[2]x}\[1+2*(!)50])mod 67
17i
```
Don't have to cast to long in q 3.0 which saved some characters.
[Answer]
### scala, 125 chars:
```
def s(v:Seq[Long]):Seq[Long]=if(v.size==1)v else
v++s(v.sliding(2).map(v=>v(0)+v(1)).toSeq)
s(1L to 99 by 2).count(_%67==0)
```
Since the first row contains the number 67, which is divisible by 67, and the next number, divisible by 67 is 2\*67 is bigger than 99, we know that we start with count = 1.
[Answer]
## Perl (84+1)
there might still be a way to shorten this :)
```
@q=grep$_%2,1..99;while(@q){$_%67or$c++for@q;$q[$_]+=$q[$_+1]for 0..$#q;pop@q}say$c
```
[Answer]
### GolfScript, 39 38 characters
```
100,{2%},0\{.{67%!},,@+\(\{.@+}%\;.}do
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 8 years ago.
[Improve this question](/posts/2027/edit)
In this task, you have to write a program, that reads a string with a length of up to 1024 characters and prints it out sorted. In order to make an interesting task from a boring one, I set a few restrictions:
You must not change the contents of any variable. A variable can be assigned only once and must not be changed afterwards. For instance, all of the following constructs are forbidden:
```
int a = 0;
a = 1;
a = 10;
for (a-->0);
string[12] = a
```
and many more. What is changing a variable and what not is judged by me.
Additionally, you must not use any sorting function or any library function, that must be "imported" somehow. The only library functions, that are allowed to import are those to print out the result and read in the string, if they are not available whithout importing them.
[Answer]
# Perl, 89 characters
```
sub t{return if!@_;my$c=shift;t(grep{$_ lt$c}@_),$c,t(grep{$_ ge$c}@_)}print t split//,<>
```
This exploits the fact that QuickSort is effectively equivalent to the recurrence relation:
```
sorted x = () if x is empty, otherwise
sorted (elements in x less than x[0]) :: x[0] ::
sorted (elements in x greater than or equal to x[0] except for x[0] itself)
```
### Edit
I originally misread the question and thought I had to sort the input strings, not the characters *within* a string. Hence my solution grows from 80 to 89 characters.
[Answer]
## Python
```
s=raw_input()
print chr(0)*s.count(chr(0))+chr(1)*s.count(chr(1))+chr(2)*s.count(chr(2))+chr(3)*s.count(chr(3))+chr(4)*s.count(chr(4))+chr(5)*s.count(chr(5))+chr(6)*s.count(chr(6))+chr(7)*s.count(chr(7))+chr(8)*s.count(chr(8))+chr(9)*s.count(chr(9))+chr(10)*s.count(chr(10))+chr(11)*s.count(chr(11))+chr(12)*s.count(chr(12))+chr(13)*s.count(chr(13))+chr(14)*s.count(chr(14))+chr(15)*s.count(chr(15))+chr(16)*s.count(chr(16))+chr(17)*s.count(chr(17))+chr(18)*s.count(chr(18))+chr(19)*s.count(chr(19))+chr(20)*s.count(chr(20))+chr(21)*s.count(chr(21))+chr(22)*s.count(chr(22))+chr(23)*s.count(chr(23))+chr(24)*s.count(chr(24))+chr(25)*s.count(chr(25))+chr(26)*s.count(chr(26))+chr(27)*s.count(chr(27))+chr(28)*s.count(chr(28))+chr(29)*s.count(chr(29))+chr(30)*s.count(chr(30))+chr(31)*s.count(chr(31))+chr(32)*s.count(chr(32))+chr(33)*s.count(chr(33))+chr(34)*s.count(chr(34))+chr(35)*s.count(chr(35))+chr(36)*s.count(chr(36))+chr(37)*s.count(chr(37))+chr(38)*s.count(chr(38))+chr(39)*s.count(chr(39))+chr(40)*s.count(chr(40))+chr(41)*s.count(chr(41))+chr(42)*s.count(chr(42))+chr(43)*s.count(chr(43))+chr(44)*s.count(chr(44))+chr(45)*s.count(chr(45))+chr(46)*s.count(chr(46))+chr(47)*s.count(chr(47))+chr(48)*s.count(chr(48))+chr(49)*s.count(chr(49))+chr(50)*s.count(chr(50))+chr(51)*s.count(chr(51))+chr(52)*s.count(chr(52))+chr(53)*s.count(chr(53))+chr(54)*s.count(chr(54))+chr(55)*s.count(chr(55))+chr(56)*s.count(chr(56))+chr(57)*s.count(chr(57))+chr(58)*s.count(chr(58))+chr(59)*s.count(chr(59))+chr(60)*s.count(chr(60))+chr(61)*s.count(chr(61))+chr(62)*s.count(chr(62))+chr(63)*s.count(chr(63))+chr(64)*s.count(chr(64))+chr(65)*s.count(chr(65))+chr(66)*s.count(chr(66))+chr(67)*s.count(chr(67))+chr(68)*s.count(chr(68))+chr(69)*s.count(chr(69))+chr(70)*s.count(chr(70))+chr(71)*s.count(chr(71))+chr(72)*s.count(chr(72))+chr(73)*s.count(chr(73))+chr(74)*s.count(chr(74))+chr(75)*s.count(chr(75))+chr(76)*s.count(chr(76))+chr(77)*s.count(chr(77))+chr(78)*s.count(chr(78))+chr(79)*s.count(chr(79))+chr(80)*s.count(chr(80))+chr(81)*s.count(chr(81))+chr(82)*s.count(chr(82))+chr(83)*s.count(chr(83))+chr(84)*s.count(chr(84))+chr(85)*s.count(chr(85))+chr(86)*s.count(chr(86))+chr(87)*s.count(chr(87))+chr(88)*s.count(chr(88))+chr(89)*s.count(chr(89))+chr(90)*s.count(chr(90))+chr(91)*s.count(chr(91))+chr(92)*s.count(chr(92))+chr(93)*s.count(chr(93))+chr(94)*s.count(chr(94))+chr(95)*s.count(chr(95))+chr(96)*s.count(chr(96))+chr(97)*s.count(chr(97))+chr(98)*s.count(chr(98))+chr(99)*s.count(chr(99))+chr(100)*s.count(chr(100))+chr(101)*s.count(chr(101))+chr(102)*s.count(chr(102))+chr(103)*s.count(chr(103))+chr(104)*s.count(chr(104))+chr(105)*s.count(chr(105))+chr(106)*s.count(chr(106))+chr(107)*s.count(chr(107))+chr(108)*s.count(chr(108))+chr(109)*s.count(chr(109))+chr(110)*s.count(chr(110))+chr(111)*s.count(chr(111))+chr(112)*s.count(chr(112))+chr(113)*s.count(chr(113))+chr(114)*s.count(chr(114))+chr(115)*s.count(chr(115))+chr(116)*s.count(chr(116))+chr(117)*s.count(chr(117))+chr(118)*s.count(chr(118))+chr(119)*s.count(chr(119))+chr(120)*s.count(chr(120))+chr(121)*s.count(chr(121))+chr(122)*s.count(chr(122))+chr(123)*s.count(chr(123))+chr(124)*s.count(chr(124))+chr(125)*s.count(chr(125))+chr(126)*s.count(chr(126))+chr(127)*s.count(chr(127))+chr(128)*s.count(chr(128))+chr(129)*s.count(chr(129))+chr(130)*s.count(chr(130))+chr(131)*s.count(chr(131))+chr(132)*s.count(chr(132))+chr(133)*s.count(chr(133))+chr(134)*s.count(chr(134))+chr(135)*s.count(chr(135))+chr(136)*s.count(chr(136))+chr(137)*s.count(chr(137))+chr(138)*s.count(chr(138))+chr(139)*s.count(chr(139))+chr(140)*s.count(chr(140))+chr(141)*s.count(chr(141))+chr(142)*s.count(chr(142))+chr(143)*s.count(chr(143))+chr(144)*s.count(chr(144))+chr(145)*s.count(chr(145))+chr(146)*s.count(chr(146))+chr(147)*s.count(chr(147))+chr(148)*s.count(chr(148))+chr(149)*s.count(chr(149))+chr(150)*s.count(chr(150))+chr(151)*s.count(chr(151))+chr(152)*s.count(chr(152))+chr(153)*s.count(chr(153))+chr(154)*s.count(chr(154))+chr(155)*s.count(chr(155))+chr(156)*s.count(chr(156))+chr(157)*s.count(chr(157))+chr(158)*s.count(chr(158))+chr(159)*s.count(chr(159))+chr(160)*s.count(chr(160))+chr(161)*s.count(chr(161))+chr(162)*s.count(chr(162))+chr(163)*s.count(chr(163))+chr(164)*s.count(chr(164))+chr(165)*s.count(chr(165))+chr(166)*s.count(chr(166))+chr(167)*s.count(chr(167))+chr(168)*s.count(chr(168))+chr(169)*s.count(chr(169))+chr(170)*s.count(chr(170))+chr(171)*s.count(chr(171))+chr(172)*s.count(chr(172))+chr(173)*s.count(chr(173))+chr(174)*s.count(chr(174))+chr(175)*s.count(chr(175))+chr(176)*s.count(chr(176))+chr(177)*s.count(chr(177))+chr(178)*s.count(chr(178))+chr(179)*s.count(chr(179))+chr(180)*s.count(chr(180))+chr(181)*s.count(chr(181))+chr(182)*s.count(chr(182))+chr(183)*s.count(chr(183))+chr(184)*s.count(chr(184))+chr(185)*s.count(chr(185))+chr(186)*s.count(chr(186))+chr(187)*s.count(chr(187))+chr(188)*s.count(chr(188))+chr(189)*s.count(chr(189))+chr(190)*s.count(chr(190))+chr(191)*s.count(chr(191))+chr(192)*s.count(chr(192))+chr(193)*s.count(chr(193))+chr(194)*s.count(chr(194))+chr(195)*s.count(chr(195))+chr(196)*s.count(chr(196))+chr(197)*s.count(chr(197))+chr(198)*s.count(chr(198))+chr(199)*s.count(chr(199))+chr(200)*s.count(chr(200))+chr(201)*s.count(chr(201))+chr(202)*s.count(chr(202))+chr(203)*s.count(chr(203))+chr(204)*s.count(chr(204))+chr(205)*s.count(chr(205))+chr(206)*s.count(chr(206))+chr(207)*s.count(chr(207))+chr(208)*s.count(chr(208))+chr(209)*s.count(chr(209))+chr(210)*s.count(chr(210))+chr(211)*s.count(chr(211))+chr(212)*s.count(chr(212))+chr(213)*s.count(chr(213))+chr(214)*s.count(chr(214))+chr(215)*s.count(chr(215))+chr(216)*s.count(chr(216))+chr(217)*s.count(chr(217))+chr(218)*s.count(chr(218))+chr(219)*s.count(chr(219))+chr(220)*s.count(chr(220))+chr(221)*s.count(chr(221))+chr(222)*s.count(chr(222))+chr(223)*s.count(chr(223))+chr(224)*s.count(chr(224))+chr(225)*s.count(chr(225))+chr(226)*s.count(chr(226))+chr(227)*s.count(chr(227))+chr(228)*s.count(chr(228))+chr(229)*s.count(chr(229))+chr(230)*s.count(chr(230))+chr(231)*s.count(chr(231))+chr(232)*s.count(chr(232))+chr(233)*s.count(chr(233))+chr(234)*s.count(chr(234))+chr(235)*s.count(chr(235))+chr(236)*s.count(chr(236))+chr(237)*s.count(chr(237))+chr(238)*s.count(chr(238))+chr(239)*s.count(chr(239))+chr(240)*s.count(chr(240))+chr(241)*s.count(chr(241))+chr(242)*s.count(chr(242))+chr(243)*s.count(chr(243))+chr(244)*s.count(chr(244))+chr(245)*s.count(chr(245))+chr(246)*s.count(chr(246))+chr(247)*s.count(chr(247))+chr(248)*s.count(chr(248))+chr(249)*s.count(chr(249))+chr(250)*s.count(chr(250))+chr(251)*s.count(chr(251))+chr(252)*s.count(chr(252))+chr(253)*s.count(chr(253))+chr(254)*s.count(chr(254))+chr(255)*s.count(chr(255))
```
[Answer]
## Haskell (70 103 94 82 71 60)
Insertion sort.
```
m%(x:y)|x>m=m:x:y|2>1=x:m%y
m%_=[m]
main=interact$foldr(%)[]
```
**Edit:** Forgot I/O
**Edit:** Use pattern guards to get rid of if
**Edit:** Revisions suggested by MtnViewMark
**Edit:** Replace `s` with a fold
**Edit:** Reorder clauses, so base case can match with `_`
**Edit:** Change main to implement FUZxxl's suggestion.
[Answer]
## C
Simply by using recursion instead of loops. ~~This particular version only works on characters between '0' and 'z', but that's just to keep the stack from overflowing too often.~~ Supporting all of ASCII.
```
#include <stdio.h>
void walk(char *s, char m){
if (*s == '\0') return;
if (*s == m) putchar(m);
walk(s+1,m);
}
void sort(char *s, char m){
walk(s,m);
if (m<127) sort(s,m+1);
}
int main(int argc, char**argv){
if (argc > 1) {
printf("%s: ",argv[1]);
sort(argv[1],1);
printf("\n");
}
}
```
Sample run:
```
$ ./a.out thingamabob
thingamabob: aabbghimnot
$ ./a.out supercalifragilisticexpalodoucious
supercalifragilisticexpalodoucious: aaacccdeefgiiiiilllooopprrssstuuux
$ ./a.out "The quick red fox jumped over the lazy brown dog"
The quick red fox jumped over the lazy brown dog: Tabcdddeeeeefghhijklmnoooopqrrrtuuvwxyz
```
Too easy, really.
[Answer]
## C++ (with libgc)
This isn't code-golf, so I went for speed. This implements counting sort. Rather than updating an array (which isn't allowed), it updates a 4-way trie by reconstructing nodes as necessary. It allocates trie nodes on the stack and copies them to the heap every 1000 characters, yielding a 600% performance boost.
This requires [libgc](http://www.hpl.hp.com/personal/Hans_Boehm/gc/), a garbage collector for C/C++. To work on large files (without stack-overflowing), it also requires the compiler to optimize tail recursion so it won't leak memory and/or stack-overflow.
Despite all the object fiddling and garbage collection, this manages to run about 25-40% as fast as a simple array-based counting sort (see below).
```
#include <gc/gc_cpp.h>
#include <stdio.h>
template<class T>
struct Node : public gc
{
T a, b, c, d;
Node(T a, T b, T c, T d)
: a(a), b(b), c(c), d(d)
{}
Node(T s)
: a(s), b(s), c(s), d(s)
{}
T get(int n) {
switch (n) {
case 0: return a;
case 1: return b;
case 2: return c;
case 3: return d;
default: return NULL;
}
}
};
typedef Node<int> TrieC;
typedef Node<TrieC*> TrieB;
typedef Node<TrieB*> TrieA;
typedef Node<TrieA*> Trie;
static Trie *initialize();
static Trie *sortInput(Trie *root);
static Trie *sortUsingStack(Trie *orig, Trie *root, int c, int count);
template<class T> static Node<T> *merge(Node<T> *node, Node<T> *base);
static Node<int> *merge(Node<int> *node, Node<int> *base);
static void print(Trie *trie);
static void repeat(int c, int n);
static Trie *initialize()
{
return new Trie(new TrieA(new TrieB(new TrieC(0))));
}
static Trie *sortInput(Trie *root)
{
int c = getchar();
if (c == EOF)
return root;
else
return sortInput(sortUsingStack(root, root, c, 1000));
}
static Trie *sortUsingStack(Trie *orig, Trie *root, int chr, int count)
{
if (chr == EOF)
return merge(root, orig);
int a = (chr >> 6) & 3;
int b = (chr >> 4) & 3;
int c = (chr >> 2) & 3;
int d = chr & 3;
TrieA *na = root->get(a);
TrieB *nb = na->get(b);
TrieC *nc = nb->get(c);
int nd = nc->get(d);
int nd2 = nd + 1;
TrieC nc2(
d == 0 ? nd2 : nc->a,
d == 1 ? nd2 : nc->b,
d == 2 ? nd2 : nc->c,
d == 3 ? nd2 : nc->d);
TrieB nb2(
c == 0 ? &nc2 : nb->a,
c == 1 ? &nc2 : nb->b,
c == 2 ? &nc2 : nb->c,
c == 3 ? &nc2 : nb->d);
TrieA na2(
b == 0 ? &nb2 : na->a,
b == 1 ? &nb2 : na->b,
b == 2 ? &nb2 : na->c,
b == 3 ? &nb2 : na->d);
Trie root2(
a == 0 ? &na2 : root->a,
a == 1 ? &na2 : root->b,
a == 2 ? &na2 : root->c,
a == 3 ? &na2 : root->d);
if (count > 0)
return sortUsingStack(orig, &root2, getchar(), count - 1);
else
return merge(&root2, orig);
}
/* Copy tree, but use nodes from base if they're the same. */
template<class T> static Node<T> *merge(Node<T> *node, Node<T> *base)
{
if (node == base)
return node;
else
return new Node<T>(merge(node->a, base->a),
merge(node->b, base->b),
merge(node->c, base->c),
merge(node->d, base->d));
}
static Node<int> *merge(Node<int> *node, Node<int> *base)
{
(void) base;
return new Node<int>(node->a, node->b, node->c, node->d);
}
static void printC(TrieC *t, int start)
{
repeat(start, t->a);
repeat(start + 1, t->b);
repeat(start + 2, t->c);
repeat(start + 3, t->d);
}
static void printB(TrieB *t, int start)
{
printC(t->a, start);
printC(t->b, start + 4);
printC(t->c, start + 8);
printC(t->d, start + 12);
}
static void printA(TrieA *t, int start)
{
printB(t->a, start);
printB(t->b, start + 16);
printB(t->c, start + 32);
printB(t->d, start + 48);
}
static void print(Trie *t)
{
printA(t->a, 0);
printA(t->b, 64);
printA(t->c, 128);
printA(t->d, 192);
}
/* Print the character c, n times. */
static void repeat(int c, int n)
{
if (n > 0) {
putchar(c);
repeat(c, n-1);
}
}
int main(void)
{
print(sortInput(initialize()));
putchar('\n');
return 0;
}
```
The array-based counting sort I used for comparison (getchar/putchar is the bottleneck):
```
#include <stdio.h>
int main(void)
{
int tally[256] = {};
int c, i, j;
while ((c = getchar()) != EOF)
tally[c]++;
for (i = 0; i < 256; i++)
for (j = 0; j < tally[i]; j++)
putchar(i);
putchar('\n');
return 0;
}
```
[Answer]
## Haskell
This implements a counting sort by building a 4-way trie. It's an adaptation of my [C++ answer](https://codegolf.stackexchange.com/questions/2027/implement-a-sorting-algorithm-with-no-change/2051#2051), and is roughly 25% faster than it.
```
import Data.Bits
import Data.List
import Data.Word
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
data Node a = Node !a !a !a !a
sortByteString :: L.ByteString -> L.ByteString
sortByteString s = fromTrie $ L.foldl' f z s
where
f n x =
let a = (x `shiftR` 6) .&. 3
b = (x `shiftR` 4) .&. 3
c = (x `shiftR` 2) .&. 3
d = x .&. 3
in (chg a . chg b . chg c . chg d) (+1) n
z = let n a = Node a a a a
in (n . n . n . n) 0
chg :: Word8 -> (a -> a) -> Node a -> Node a
chg 0 f (Node a b c d) = Node (f a) b c d
chg 1 f (Node a b c d) = Node a (f b) c d
chg 2 f (Node a b c d) = Node a b (f c) d
chg 3 f (Node a b c d) = Node a b c (f d)
fromTrie t =
let gather (Node a b c d) = [a, b, c, d]
counts = gather t >>= gather >>= gather >>= gather
in L.concat $ zipWith (L.replicate) counts [0..]
main = L.interact ((`L.snoc` 10) . sortByteString)
```
[Answer]
## Scala
```
object Sort extends Application
{
def merge(s1:String,s2:String):String=
{
if(s1.isEmpty) return s2
if(s2.isEmpty) return s1
if(s1.head<s2.head)
return s1.head+merge(s1.tail,s2)
else
return s2.head+merge(s1,s2.tail)
}
def mergesort(s:String):String=
{
if(s.length<=1)
return s
else
return merge(mergesort(s take(s.length/2)),mergesort(s drop(s.length/2)))
}
print(mergesort(Console.readLine))
}
```
[Answer]
## SED
```
s/$/\n !"#$%\&'()*+,-.\/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~/;:a;s/\(.\)\(.*\)\(.\)\(.*\n.*\3.*\1\)/\3\1\2\4/;ta;s/\n.*//
```
Doesn't modify anything but pattern space (script would be pointless otherwise)
Lookup table borrowed from <http://sed.sf.net/grabbag/scripts/sodelnum.sed>
[Answer]
## Ruby (71 chars)
Shamelessly stole the idea from gnibbler, but improved it, a lot
```
def s x
return if x>255
print x.chr*(ARGV[0].count x.chr)
s x+1
end
s 0
```
Usage:
```
$ ruby codegolfsort.rb "supercalifragilisticexpalodoucious"
aaacccdeefgiiiiilllooopprrssstuuux
```
[Answer]
## Python
```
S=lambda x:S([y for y in x if y<x[0]])+x[0]*x.count(x[0])+S([y for y in x if y>x[0]])if x else''
print S(raw_input())
```
[Answer]
## Ruby
```
s=gets
puts 0.chr*(s.count 0.chr)+1.chr*(s.count 1.chr)+2.chr*(s.count 2.chr)+3.chr*(s.count 3.chr)+4.chr*(s.count 4.chr)+5.chr*(s.count 5.chr)+6.chr*(s.count 6.chr)+7.chr*(s.count 7.chr)+8.chr*(s.count 8.chr)+9.chr*(s.count 9.chr)+10.chr*(s.count 10.chr)+11.chr*(s.count 11.chr)+12.chr*(s.count 12.chr)+13.chr*(s.count 13.chr)+14.chr*(s.count 14.chr)+15.chr*(s.count 15.chr)+16.chr*(s.count 16.chr)+17.chr*(s.count 17.chr)+18.chr*(s.count 18.chr)+19.chr*(s.count 19.chr)+20.chr*(s.count 20.chr)+21.chr*(s.count 21.chr)+22.chr*(s.count 22.chr)+23.chr*(s.count 23.chr)+24.chr*(s.count 24.chr)+25.chr*(s.count 25.chr)+26.chr*(s.count 26.chr)+27.chr*(s.count 27.chr)+28.chr*(s.count 28.chr)+29.chr*(s.count 29.chr)+30.chr*(s.count 30.chr)+31.chr*(s.count 31.chr)+32.chr*(s.count 32.chr)+33.chr*(s.count 33.chr)+34.chr*(s.count 34.chr)+35.chr*(s.count 35.chr)+36.chr*(s.count 36.chr)+37.chr*(s.count 37.chr)+38.chr*(s.count 38.chr)+39.chr*(s.count 39.chr)+40.chr*(s.count 40.chr)+41.chr*(s.count 41.chr)+42.chr*(s.count 42.chr)+43.chr*(s.count 43.chr)+44.chr*(s.count 44.chr)+45.chr*(s.count 45.chr)+46.chr*(s.count 46.chr)+47.chr*(s.count 47.chr)+48.chr*(s.count 48.chr)+49.chr*(s.count 49.chr)+50.chr*(s.count 50.chr)+51.chr*(s.count 51.chr)+52.chr*(s.count 52.chr)+53.chr*(s.count 53.chr)+54.chr*(s.count 54.chr)+55.chr*(s.count 55.chr)+56.chr*(s.count 56.chr)+57.chr*(s.count 57.chr)+58.chr*(s.count 58.chr)+59.chr*(s.count 59.chr)+60.chr*(s.count 60.chr)+61.chr*(s.count 61.chr)+62.chr*(s.count 62.chr)+63.chr*(s.count 63.chr)+64.chr*(s.count 64.chr)+65.chr*(s.count 65.chr)+66.chr*(s.count 66.chr)+67.chr*(s.count 67.chr)+68.chr*(s.count 68.chr)+69.chr*(s.count 69.chr)+70.chr*(s.count 70.chr)+71.chr*(s.count 71.chr)+72.chr*(s.count 72.chr)+73.chr*(s.count 73.chr)+74.chr*(s.count 74.chr)+75.chr*(s.count 75.chr)+76.chr*(s.count 76.chr)+77.chr*(s.count 77.chr)+78.chr*(s.count 78.chr)+79.chr*(s.count 79.chr)+80.chr*(s.count 80.chr)+81.chr*(s.count 81.chr)+82.chr*(s.count 82.chr)+83.chr*(s.count 83.chr)+84.chr*(s.count 84.chr)+85.chr*(s.count 85.chr)+86.chr*(s.count 86.chr)+87.chr*(s.count 87.chr)+88.chr*(s.count 88.chr)+89.chr*(s.count 89.chr)+90.chr*(s.count 90.chr)+91.chr*(s.count 91.chr)+92.chr*(s.count 92.chr)+93.chr*(s.count 93.chr)+94.chr*(s.count 94.chr)+95.chr*(s.count 95.chr)+96.chr*(s.count 96.chr)+97.chr*(s.count 97.chr)+98.chr*(s.count 98.chr)+99.chr*(s.count 99.chr)+100.chr*(s.count 100.chr)+101.chr*(s.count 101.chr)+102.chr*(s.count 102.chr)+103.chr*(s.count 103.chr)+104.chr*(s.count 104.chr)+105.chr*(s.count 105.chr)+106.chr*(s.count 106.chr)+107.chr*(s.count 107.chr)+108.chr*(s.count 108.chr)+109.chr*(s.count 109.chr)+110.chr*(s.count 110.chr)+111.chr*(s.count 111.chr)+112.chr*(s.count 112.chr)+113.chr*(s.count 113.chr)+114.chr*(s.count 114.chr)+115.chr*(s.count 115.chr)+116.chr*(s.count 116.chr)+117.chr*(s.count 117.chr)+118.chr*(s.count 118.chr)+119.chr*(s.count 119.chr)+120.chr*(s.count 120.chr)+121.chr*(s.count 121.chr)+122.chr*(s.count 122.chr)+123.chr*(s.count 123.chr)+124.chr*(s.count 124.chr)+125.chr*(s.count 125.chr)+126.chr*(s.count 126.chr)+127.chr*(s.count 127.chr)+128.chr*(s.count 128.chr)+129.chr*(s.count 129.chr)+130.chr*(s.count 130.chr)+131.chr*(s.count 131.chr)+132.chr*(s.count 132.chr)+133.chr*(s.count 133.chr)+134.chr*(s.count 134.chr)+135.chr*(s.count 135.chr)+136.chr*(s.count 136.chr)+137.chr*(s.count 137.chr)+138.chr*(s.count 138.chr)+139.chr*(s.count 139.chr)+140.chr*(s.count 140.chr)+141.chr*(s.count 141.chr)+142.chr*(s.count 142.chr)+143.chr*(s.count 143.chr)+144.chr*(s.count 144.chr)+145.chr*(s.count 145.chr)+146.chr*(s.count 146.chr)+147.chr*(s.count 147.chr)+148.chr*(s.count 148.chr)+149.chr*(s.count 149.chr)+150.chr*(s.count 150.chr)+151.chr*(s.count 151.chr)+152.chr*(s.count 152.chr)+153.chr*(s.count 153.chr)+154.chr*(s.count 154.chr)+155.chr*(s.count 155.chr)+156.chr*(s.count 156.chr)+157.chr*(s.count 157.chr)+158.chr*(s.count 158.chr)+159.chr*(s.count 159.chr)+160.chr*(s.count 160.chr)+161.chr*(s.count 161.chr)+162.chr*(s.count 162.chr)+163.chr*(s.count 163.chr)+164.chr*(s.count 164.chr)+165.chr*(s.count 165.chr)+166.chr*(s.count 166.chr)+167.chr*(s.count 167.chr)+168.chr*(s.count 168.chr)+169.chr*(s.count 169.chr)+170.chr*(s.count 170.chr)+171.chr*(s.count 171.chr)+172.chr*(s.count 172.chr)+173.chr*(s.count 173.chr)+174.chr*(s.count 174.chr)+175.chr*(s.count 175.chr)+176.chr*(s.count 176.chr)+177.chr*(s.count 177.chr)+178.chr*(s.count 178.chr)+179.chr*(s.count 179.chr)+180.chr*(s.count 180.chr)+181.chr*(s.count 181.chr)+182.chr*(s.count 182.chr)+183.chr*(s.count 183.chr)+184.chr*(s.count 184.chr)+185.chr*(s.count 185.chr)+186.chr*(s.count 186.chr)+187.chr*(s.count 187.chr)+188.chr*(s.count 188.chr)+189.chr*(s.count 189.chr)+190.chr*(s.count 190.chr)+191.chr*(s.count 191.chr)+192.chr*(s.count 192.chr)+193.chr*(s.count 193.chr)+194.chr*(s.count 194.chr)+195.chr*(s.count 195.chr)+196.chr*(s.count 196.chr)+197.chr*(s.count 197.chr)+198.chr*(s.count 198.chr)+199.chr*(s.count 199.chr)+200.chr*(s.count 200.chr)+201.chr*(s.count 201.chr)+202.chr*(s.count 202.chr)+203.chr*(s.count 203.chr)+204.chr*(s.count 204.chr)+205.chr*(s.count 205.chr)+206.chr*(s.count 206.chr)+207.chr*(s.count 207.chr)+208.chr*(s.count 208.chr)+209.chr*(s.count 209.chr)+210.chr*(s.count 210.chr)+211.chr*(s.count 211.chr)+212.chr*(s.count 212.chr)+213.chr*(s.count 213.chr)+214.chr*(s.count 214.chr)+215.chr*(s.count 215.chr)+216.chr*(s.count 216.chr)+217.chr*(s.count 217.chr)+218.chr*(s.count 218.chr)+219.chr*(s.count 219.chr)+220.chr*(s.count 220.chr)+221.chr*(s.count 221.chr)+222.chr*(s.count 222.chr)+223.chr*(s.count 223.chr)+224.chr*(s.count 224.chr)+225.chr*(s.count 225.chr)+226.chr*(s.count 226.chr)+227.chr*(s.count 227.chr)+228.chr*(s.count 228.chr)+229.chr*(s.count 229.chr)+230.chr*(s.count 230.chr)+231.chr*(s.count 231.chr)+232.chr*(s.count 232.chr)+233.chr*(s.count 233.chr)+234.chr*(s.count 234.chr)+235.chr*(s.count 235.chr)+236.chr*(s.count 236.chr)+237.chr*(s.count 237.chr)+238.chr*(s.count 238.chr)+239.chr*(s.count 239.chr)+240.chr*(s.count 240.chr)+241.chr*(s.count 241.chr)+242.chr*(s.count 242.chr)+243.chr*(s.count 243.chr)+244.chr*(s.count 244.chr)+245.chr*(s.count 245.chr)+246.chr*(s.count 246.chr)+247.chr*(s.count 247.chr)+248.chr*(s.count 248.chr)+249.chr*(s.count 249.chr)+250.chr*(s.count 250.chr)+251.chr*(s.count 251.chr)+252.chr*(s.count 252.chr)+253.chr*(s.count 253.chr)+254.chr*(s.count 254.chr)+255.chr*(s.count 255.chr)
```
] |
[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/32352/edit).
Closed 2 years ago.
[Improve this question](/posts/32352/edit)
Write a program that takes R, G, and B values as command arguments and then displays that color some way. It doesn't matter how, as long as at least 100 pixels have the color. Shortest code wins.
[Answer]
## JavaScript, 25
```
document.bgColor=prompt()
```
You'll have to specify the three components in hexadecimal. This is code golf, so no commas or whitespace.
[Answer]
# JavaScript, 57 characters
```
document.body.setAttribute('bgcolor','rgb('+prompt()+')')
```
Enter the RGB values in the prompt input box, comma separated.
(I feel so dirty, using `bgcolor` :O )
[Answer]
## xterm: 18 bytes
```
xterm -bg \#$1$2$3
```
Input the color as three 1- or 2-digit hex numbers, e.g., if this command is in the file "xterm.sh", then
```
./xterm.sh ff 00 00
./xterm.sh f 0 0
```
opens a terminal window with a red background.
If you prefer, you can omit the blanks between the components:
```
./xterm.sh f00
```
The "-bg" option is not available in some old versions of xterm. It's missing from version 271 but present in versions 215, 251, 261, and 297.
[Answer]
# Bash, 69
```
read c;set $c;printf '\e]4;1;rgb:'"$1"'/'"$2"'/'"$3"'\e\\\e[31mc\e[m'
```
Partially stolen from [here](https://unix.stackexchange.com/a/103909/72471).
Just input your values in hex (e.g. FF 00 00).
Tested on `xterm-256color`.
# Bash, 43
```
printf '\e]4;1;rgb:FF/00/00\e\\\e[31mc\e[m'
```
Here you have to input the values yourself.
**Edit**: For 100 Pixels+ Just choose font-size infinite :D.
[Answer]
**C# WPF : 54**
```
new Windows(){Background=Color.FromArgb(RGB);}.Show();
```
[Answer]
# Javascript in PCCG, 65 ~~105~~
**Edit 2** shortened as suggested by @manatwork
**Edit**
Thanks @blender
```
question.style.background='#'+prompt('R G B').split(' ').join('')
```
Just for fun
[Answer]
## Bash/sh + ImageMagick: 28 bytes
```
display -size 96 xc:\#$1$2$3
```
Input the color as three 1- or 2-digit hex numbers, with or without whitespace between them.
[Answer]
# Postscript ~~61~~ 56
Fills the graphics window with the color, components as decimals in the range 0..1.
```
ARGUMENTS{cvr}forall setrgbcolor clippath fill showpage
```
Run using ghostscript's `--` option which enables argument processing.
```
gs -- rgb.ps .9 .2 .2
```
[Answer]
# Java, 215
```
import java.awt.*;class C{public static void main(String[]a){Frame f=new Frame();f.setSize(9,99);f.setBackground(new Color(Integer.parseInt(a[0]),Integer.parseInt(a[1]),Integer.parseInt(a[2])));f.setVisible(true);}}
```
[Answer]
# Tcl/Tk, 15
```
. co -bg #$argv
```
# Tcl/Tk, 22
```
. configure -bg #$argv
```
If called with
```
wish show_color.tcl 6666AA
```
one gets
[](https://i.stack.imgur.com/fJ2q9.png)
# Tcl/Tk, 27
```
grid [canvas .c -bg #$argv]
```
If called with
```
wish show_color.tcl 6666AA
```
one gets
[](https://i.stack.imgur.com/ZSnVO.png)
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/31830/edit).
Closed 9 years ago.
[Improve this question](/posts/31830/edit)
Write a recursive function/program, to calculate either the **Factorial** or the **Fibonacci** number of a given non-negative integer, without explicitly implementing the base case(s).
Your program/function must return/output the correct value in a reasonable time.
**You cannot**
1. Use `if` statement anywhere in your program/function, nor `switch`
nor short-if-syntax (`?:`). Not even loops. Basically all
control-flow statements are forbidden.
2. Use `try, catch` or exceptions of any kind.
3. Terminate the program (anything like `exit(1)`).
4. Use external sources (file, web, etc.)
5. Avoid recursion and return the proper value otherwise. (Your function must be recursive).
6. Use any of the [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny).
**You can**
* Use polymorphism, create threads, wrap the Integer type with your own class, or use any other mechanism your language or runtime has. (I can think of a solution that uses the *lazy-evaluation*, for instance). The function/program can be written as more than one function, using [Mutual Recursion](http://en.wikipedia.org/wiki/Mutual_recursion), if it helps you.
Please provide a **short** explanation of what you did.
Be creative! The winning answer is the one with the most upvotes by 2014-06-23 (a week from today).
**EDIT**:
Some clarifications:
Using Pattern Matching in Functional Programming Languages is OK since it's considered as Polymorphism. The solution should be trivial though, so I guess it won't have the chance to win, since it is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"). It is still a legitimate answer.
Although some may say it's flow control in disguise, using *lazy evaluation*, (or *short circuit evaluation*) is allowed as well.
[Answer]
# C - factorial
simple as that
```
int not_factorial(int n){return 1;}
int factorial(int n)
{
int (*maybe_factorial[])(int) = {factorial, not_factorial};
return n*maybe_factorial[!(n-1)](n-1);
}
```
the function factorial is almost like a basic recursive approach but not\_factorial only returns 1.
If I create an array of function pointers
(0: fac, 1: not\_fac), then I can control which one should be executed at the next call:
`maybe_factorial[0](n-1)` calls factorial
`maybe_factorial[1](n-1)` calls not\_factorial.
`!(n-1)` means `if n > 1 return 0 else return 1`
[Answer]
# Javascript
Just a quick idea to get things going, nothing too fancy:
```
var t = [1];
function factorial (n) {
var h = arguments[1] || 1;
t.push (t[t.length-1] * h);
return t[n] || factorial (n,h+1);
}
```
This should be considered a program rather than a function, because it depends on a variable that is outside the function's scope (and it only works once), but I'll try to edit it later as a proper closure.
The trick here relies on the combination of JS's lazy evaluation and the fact that undefined object properties are merely an `undefined` value rather than a reason to throw an error. Rather than doing a boring recursion down from `n` to 0, I've decided to add a "secret" second parameter (`arguments[1]`) as a counter from 1 to `n`. Each iteration multiplies the last element of the `t` array by the counter, to fill the array with all the factorial values, and once the array has an `n`th element I stop the recursion and return it.
[Answer]
# Haskell
```
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
```
Thanks to pattern matching, there is no need for control structures in this function.
As [Tal mentionned](https://codegolf.stackexchange.com/questions/31830/not-endless-recursion-without-a-base-case#comment66984_31830), this is a textbook example for functional languages, one of the first shown when learning them.
[Answer]
# C++
```
#include <iostream>
using namespace std;
template <int K>
class Int
{
public :
int Fact(void);
};
template<>
int Int<0>::Fact()
{
return 1;
}
template<int K>
int Int<K>::Fact()
{
Int <K-1> x;
return K*x.Fact();
}
int main(void)
{
Int<5> A;
cout << A.Fact() << endl;
}
```
[Answer]
# Python
```
f = lambda n: int(n==0) or n*f(n-1)
```
We exploit the short-circuiting behavior of `or`. For `n=0`, the base-case check returns true, which is converted to the int `1`, and otherwise, the `or` expression evaluates to the recursive expression.
[Answer]
# Scala
Would this be the lazy solution the OP alluded to?
```
// Factorial
lazy val fac: Stream[Int] = 1 #:: Stream.from(1).map{i => i * fac(i - 1)}
// Fibonacci
lazy val fib: Stream[Int] = 0 #:: 1 #:: Stream.from(2).map{i => fib(i - 1) + fib(i - 2)}
```
Creates a lazily evaluated stream. The first elements are hard-coded, but subsequent elements are defined recursively, with no control flow. As a side effect, values are memo-ised.
[Answer]
## Tcl
Well, if we can't use `if` or `switch` or `for` or `while` to test then it looks like we'll have to implement our own **if**.
I personally feel re-implementing `if` is a bit more impressive than polymorphism because polymorphism (or function overloading) is still using built in language feature. What I'm doing is implementing a feature from scratch!
```
# First we write functions called 0 and 1
proc 0 {a b} {uplevel 1 $b}
proc 1 {a b} {uplevel 1 $a}
# Now we try to implement IF, we'll call it _I_F_
proc _I_F_ {statement a b} {
uplevel 1 [list [expr $statement] $a $b]
}
# Now lets write a recursive countdown function
# using our scratchbuilt if:
proc countdown {number} {
puts $number
_I_F_ "$number>0" "count [expr $number-1]" "puts done"
}
# Lets see if it works:
countdown 10 ;# should count down to 0
```
Notes:
* `uplevel` is like evel only it allows you to execute the code in any stack level you chose.
* Tcl always expects a function name to be the first word of a statement. Therefore if you want to evaluate something like `$a>$b` or `$a==$b` you can't because you can't start a statement with a variable. That's what `expr` is for - it's a function that evaluates expressions.
* Comparison expressions such as `$a<$b`, like in other languages, return true or false. In tcl true is canonically 1 and false is canonically 0. So the `expr $statement` returns 0 or 1.
* We then construct a statement using `list` which, depending on the `expr` will start with 0 or 1 and uplevel it. This in turn executes either the function `0` or the function `1`.
] |
[Question]
[
In this code-golf, you will attempt to match a string that is tail-repeating with one character falling off the head on each iteration. The code needs to be able to accept a string, and return to the user whether the string meets the above criteria.
Examples:
```
"", "x", and "xx" -> False
```
EDIT: There is some speculation about whether this is theoretically correct. I will accept any implementation that returns the same value for the three above values as of now. However I do not have an official position on whether this is true or false. Hopefully someone can formalize this.
The above cases will always be false regardless of the circumstance because the string is too short to have the property of tail repetition with one character falling off the head. For example "xx"'s first "tail" would be "x" and there is nothing after the "xx", so it would be false. The character does not matter here, "x" is an example.
```
"abb" -> True
```
"abb" is the simplest string I can think of that should be true, because if you take what we will call the "tail" off of it, you get "bb", then knock one character off the head, and you get "b", which is the next character in the string.
```
"abcbcc" -> True
```
"abcbcc" is the next simplest string I can think of that should be true. So far in contemplating this problem, testing the truth from the beginning to the end of the string seems difficult, so I'll explain from the end up.
```
"c", "cb", "cba"
```
When you examine the string in reverse it seems easier to determine where the "first tail" ends. It ends at the first "c" in "abc", but this can only be inferred from examining the string in reverse, to the best of my knowledge so far.
Here is an example of a string that does not match:
```
"abcbca" -> False
```
If we try to apply the above reverse-proof method to it:
```
"a", "cb"
```
we realize at the second step when the first character in the second string is not "a", that this must be false.
Shortest code in characters to implement this logic in any programming language wins.
EDIT: If you find a solution other than the suggested one, it is still a valid entry (and very cool!)
[Answer]
# Python
Used the fact that the length of a valid string will always be a Triangle Number.
```
t=raw_input()
x=int(len(t+t)**.5)
print t==''.join(t[i:x]for i in range(x))
```
A Ruby solution might be shorter, will post soon.
[Answer]
## GolfScript, 25 chars
```
.,,{1$<..,{(;.@\+\}*;}%?)
```
**NB** This requires the most recent version of Golfscript, which supports a `string array ?` indexof function.
This implements the interpretation whereby `""` and `"x"` are not in the language, which IMO is a funny way to define it. It is a statement which takes one argument on the stack and leaves an integer which can be interpreted as a boolean in standard GolfScript fashion (i.e. 0 for false, anything else for true). To turn this into a full program prepend `n-` and postpend some suitable manipulation depending on what output you want (e.g. `"true""false"if`).
[Answer]
## Ruby, 63 characters
```
t=->x{b="";x.size>1&&(b,x=$2+b,$1while x=~/(.*)(.)#{b}/;x=="")}
```
This method returns true iff the string fits the definition.
Usage:
```
p t["abcbbc"] # -> false
p t["abcbcc"] # -> true
```
[Answer]
# Perl regex, ~~24~~ 69
```
^.(.+)(?{$a=$+})((??{"\Q$a"})(?{$a=substr$a,1}))*(?(?{''eq$a})$|(*F))
```
Obviously not a genuine CS regular expression, ~~but those modern recursive regexes can work wonders~~ and the edited (but fixed) version is not that short at all. I'm starting to wonder if actual Perl code, with the ability to reverse the starting string, wouldn't be shorter than that.
[Answer]
## Haskell, 48 characters
```
import List
f x=any((==x).concat.tails)$inits x
```
Brute force. Note that this returns true for `f "x"` and `f ""`.
Example usage in GHCi:
```
> f "abb"
True
> f "abcbcc"
True
> f "abcbca"
False
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
aa₁ᶠc?ẹṀ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WU9B51rFBKS8wpBrJrH@7qrH24dcL/xMRHTY0Pty1Itn@4a@fDnQ3//0crKekoVYAwiEhMSgKTyUnJyTBGIoSRAkTJKSkgTmIihExUigUA "Brachylog – Try It Online")
Takes input through the input variable and outputs through success or failure. I don't quite get why length-zero and length-one initial heads have to have the same output as the very straightforwardly illegal `"xx"`, but fortunately ruling them out only takes two bytes.
```
c The concatenation of
ᶠ every
a₁ suffix (in descending order of length) of
a some adfix of the input
? is the input,
ẹṀ which has multiple elements.
```
Instead of using a sane algorithm to walk backwards through the input and match each repetition, or determine the initial head from the length of the input then generate the rest and check for equality, this brute-forces the initial head from the set of all adfixes of the input (not just prefixes, because that would be a byte longer).
[Answer]
## VBA, 113 characters
Adding my 2 VBA cents...
```
Function t(s)
k=Right(s,Len(s)-1)
t=Round(Len(k)/2)
If t>0 Then If Left(k,t)<>Right(k,t) Then t=t(k)
End Function
```
This returns a 1 or 0.
Usage is `MsgBox t("abcbcc")`, or to get a `"True"/"False"` outsput, use `MsgBox CBool(t("abcbcc"))`
[Answer]
# Pyth, ~~33~~ 22 bytes
This is my second attempt on Pyth :)
```
qz_jk.__<z/t@+1*8lz2 2
print(
q is_equal(
z input(),
_ reverse(
jk concat(
._ all_prefixes(
_ reverse(
<z input()[:
/t@h*8lz2 2 divide(decrement(root(increment(multiply(8,len(z))),2)),2)
])))))
```
---
Previous attempt:
```
KJ<z/t@+1*8lz2 2;WnkJ=K+K=JtJ;qKz
```
[Try it online!](https://pyth.herokuapp.com/?code=KJ%3Cz%2Ft%40%2B1*8lz2+2%3BWnkJ%3DK%2BK%3DJtJ%3BqKz&input=abcdbcdcdd&debug=0)
How it works:
```
KJ<z/t@+1*8lz2 2;WnkJ=K+K=JtJ;qKz
z=input()
KJ<z/t@+1*8lz2 2 K=J=z[:(root(1+8*len(z),2)-1)/2]
<z z[:
+1*8lz 1+8*len(z)
@ 2 root( ,2)
t -1
WnKJ while not_equal(k,J):
=K+K=JtJ K=plus(K,J=tail(J))
qKz equal(K,z)
```
[Answer]
# C, 191 bytes
That's the best I can golf this in C:
```
main(){char a[9],*b=a,p[9],c=0,i=strlen(gets(a)),j=0,k=0;p[0]='\0';while(i>=0){b[strlen(b=a+(i-=++j))-k]='\0';k=strlen(b);if(strcmp(p,b+1)&&c++)exit(puts("false"));strcpy(p,b);}puts("true");}
```
[Answer]
# Element, 40 characters
```
_)#3:s;m;$'[m~)#4:m;$'[(#2:'."]#s~=[1`]]
```
This is a language of my own creation. It is designed so that all operators are one character long and always perform the same function. This allows the programs to be much shorter than many other programming languages. In some challenges, however, I must program something for which there is no built-in function, causing the program to grow in size. Element has no built-in regex matching of any kind, so I think that I actually did pretty well on this challenge.
This is a complete program that will take one line of input as the string to test, and it will print a `1` for true and nothing for false.
As for why I am answering code golf questions in Element, it is partially to raise awareness, partially a publicity stunt, and partially an exercise to test the language.
A description of Element can be found [here](https://codegolf.stackexchange.com/questions/1171/sum-of-positive-integers-spoj-sizecon#5268), and the (hopefully working) source of an interpreter for Element (written in Perl) can be found [here](http://pastebin.com/rZKMKDWv).
[Answer]
## Scala 113:
```
def t(s:String):Boolean={
val k=s.tail
val l=k.size
if(l<2)false else
if(k.take(l/2)==k.drop(l/2))true else
t(k)}
```
Takes rekursively the rest of the string, and tests whether first half equals second.
ungolfed:
```
def tailrepeating (s: String): Boolean = {
val k=s.tail
if (k.size < 2) false else
if (k.take (k.size /2) == k.drop (k.size / 2)) true else
tailrepeating (k) }
```
[Answer]
## bash 111
```
#!/bin/bash
s=$1
l=${#s}
for i in $(seq 1 $((l-2)))
do
test "${s:i:$(((l-i)/2))}" = "${s:$(((l+i)/2))}"&&exit 0
done||false
```
111 chars without shebang.
Invocation:
```
./tailrepeated.sh foobalaa && echo "true" || echo "false"
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 80 bytes
```
i,j,k,l;f(b,e)char*b;{for(i=j=k=e<2;e--;k|=l?i-=++j:b[e]-b[j+e])l=++i>j;b=!k*l;}
```
[Try it online!](https://tio.run/##VU7LboQwDLznK2iklRKSqFWP9ab7IcCBPGgdsmxFOKxK@XYKWVSpljUej8bWWPVh7bqiDLKXETpmpOf2sx1LA3N3GxnqoHvtz6/glYL@R8cLKi1EeDOVb5SpgvANj5uC7wGMfurLCMt6bXFgfCb5VZGqRs@EtsZQuQ9rrN3ZPdehua2tc3@O9sHc4Z18mh43GXegZAGSQw5TgfoF8Jzw2986lvjzwXIADigEJ1/jZuwYPbmipqcy1bQeqNzcFTYyTWP0Q@ac/9tkRiDL@gs "C (gcc) – Try It Online")
Rejects `"x"` and `""`. -1 if `"x"` can be accepted, and another -1 if `""` is ok as well.
[Answer]
Here is my own un-golfed answer in C for testing.
```
#include <stdio.h>
#include <string.h>
#include <assert.h>
int tailrep(char *str, char *sub, int sublen, int len) {
if (str == sub) {
return 1;
}
int i;
for (i = 0; i < sublen; i++) {
char *a, *b;
a = str + len - sublen;
b = sub + sublen - 1;
// printf("%p->%c %p->%c\n", a - i, a[-i], b - i, b[-i]);
if (a[-i] != b[-i]) {
return 0;
}
}
return tailrep(str, sub - sublen - 1, sublen + 1, len - sublen);
}
int istailrep(char *str) {
int len = strlen(str);
if (len < 3) {
return 0;
}
return tailrep(str, str + len - 1, 1, len - 1);
}
int main() {
// must be false
assert(!istailrep(""));
assert(!istailrep("a"));
assert(!istailrep("aa"));
assert(!istailrep("aab"));
assert(!istailrep("abcbbc"));
assert(!istailrep("abcdabcdabcd"));
// must be true
assert(istailrep("aaa"));
assert(istailrep("abb"));
assert(istailrep("abcbcc"));
assert(istailrep("abcdbcdcdd"));
assert(istailrep("abcdebcdecdedee"));
printf("yay\n");
return 0;
}
```
] |
[Question]
[
I recently watched *The Wizard Of Oz* and thought that when Dorothy taps her shoes together three times, it would be easier if she used a program to do it. So let's help her.
## Task
Output slippers being tapped together 3 times.
## Output
Slippers being tapped together. A pair of slippers not being tapped looks like this:
```
__.....__ __.....__
/ ,------.\ /.------, \
( \ \ / / )
\ \ ___\ /___ / /
\ \ ,' __`. .´__ ', / /
\ `.' =' `=\ /=´ '= '.´ /
`. `. \ / .´ .´
`. `. \ / .´ .´
`. `-.___.'\ /'.___.-´ .´
`-._ / \ _.-´
`----' '----´
```
And a pair being tapped together looks like this:
```
__.....__ __.....__
/.------, \ / ,------.\
/ / ) ( \ \
/___ / / \ \ ___\
.´__ ', / / \ \ ,' __`.
/=´ '= '.´ / \ `.' =' `=\
/ .´ .´ `. `. \
/ .´ .´ `. `. \
/'.___.-´ .´ `. `-.___.'\
\ _.-´ `-._ /
'----´ `----'
```
Basically, output
```
__.....__ __.....__
/ ,------.\ /.------, \
( \ \ / / )
\ \ ___\ /___ / /
\ \ ,' __`. .´__ ', / /
\ `.' =' `=\ /=´ '= '.´ /
`. `. \ / .´ .´
`. `. \ / .´ .´
`. `-.___.'\ /'.___.-´ .´
`-._ / \ _.-´
`----' '----´
__.....__ __.....__
/.------, \ / ,------.\
/ / ) ( \ \
/___ / / \ \ ___\
.´__ ', / / \ \ ,' __`.
/=´ '= '.´ / \ `.' =' `=\
/ .´ .´ `. `. \
/ .´ .´ `. `. \
/'.___.-´ .´ `. `-.___.'\
\ _.-´ `-._ /
'----´ `----'
__.....__ __.....__
/ ,------.\ /.------, \
( \ \ / / )
\ \ ___\ /___ / /
\ \ ,' __`. .´__ ', / /
\ `.' =' `=\ /=´ '= '.´ /
`. `. \ / .´ .´
`. `. \ / .´ .´
`. `-.___.'\ /'.___.-´ .´
`-._ / \ _.-´
`----' '----´
__.....__ __.....__
/.------, \ / ,------.\
/ / ) ( \ \
/___ / / \ \ ___\
.´__ ', / / \ \ ,' __`.
/=´ '= '.´ / \ `.' =' `=\
/ .´ .´ `. `. \
/ .´ .´ `. `. \
/'.___.-´ .´ `. `-.___.'\
\ _.-´ `-._ /
'----´ `----'
__.....__ __.....__
/ ,------.\ /.------, \
( \ \ / / )
\ \ ___\ /___ / /
\ \ ,' __`. .´__ ', / /
\ `.' =' `=\ /=´ '= '.´ /
`. `. \ / .´ .´
`. `. \ / .´ .´
`. `-.___.'\ /'.___.-´ .´
`-._ / \ _.-´
`----' '----´
__.....__ __.....__
/.------, \ / ,------.\
/ / ) ( \ \
/___ / / \ \ ___\
.´__ ', / / \ \ ,' __`.
/=´ '= '.´ / \ `.' =' `=\
/ .´ .´ `. `. \
/ .´ .´ `. `. \
/'.___.-´ .´ `. `-.___.'\
\ _.-´ `-._ /
'----´ `----'
```
For reference, the characters used are
```
_-.,/\()='`´
```
## Rules
* The output can have an optional leading/trailing whitespace
* While not explicitly banned, builtins detract from the competition, so please don't post an answer which is simply a single builtin\*
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in *characters* wins. Characters is chosen due to the use of a multibyte character.
\* For all you killjoys out there, this rule is intended for comedic effect and shouldn't be taken literally
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~113~~ ~~110~~ 108 characters
```
░╗╬)λ]cw╚╥Æ⁄║RL↓κΟiRDΨ℮≠3*s4sφ¡┐rκ⁾žχ&ν3.ΦƧ⁴ty¬`OΗΒ%Τz׀PΥω╤8⅟∆KΣ⅜4⅔⅝⁰?Z+pķcE□L6⁵/4γ⁽Κ¹‘▓:±↔Ζ`´ŗ⁴@┼⁴┼≥@┼;┼+3∙
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTkxJXUyNTU3JXUyNTZDJTI5JXUwM0JCJTVEY3cldTI1NUEldTI1NjUlQzYldTIwNDQldTI1NTFSTCV1MjE5MyV1MDNCQSV1MDM5RmlSRCV1MDNBOCV1MjEyRSV1MjI2MDMqczRzJXUwM0M2JUExJXUyNTEwciV1MDNCQSV1MjA3RSV1MDE3RSV1MDNDNyUyNiV1MDNCRDMuJXUwM0E2JXUwMUE3JXUyMDc0dHklQUMlNjBPJXUwMzk3JXUwMzkyJTI1JXUwM0E0eiV1MDVDMFAldTAzQTUldTAzQzkldTI1NjQ4JXUyMTVGJXUyMjA2SyV1MDNBMyV1MjE1QzQldTIxNTQldTIxNUQldTIwNzAlM0ZaK3AldTAxMzdjRSV1MjVBMUw2JXUyMDc1LzQldTAzQjMldTIwN0QldTAzOUElQjkldTIwMTgldTI1OTMlM0ElQjEldTIxOTQldTAzOTYlNjAlQjQldTAxNTcldTIwNzRAJXUyNTNDJXUyMDc0JXUyNTNDJXUyMjY1QCV1MjUzQyUzQiV1MjUzQyszJXUyMjE5)
Explanation:
```
...‘ push a compressed string of one slipper (one as the top left one) with a leading newline
▓ convert from a multiline string to an array of lines
: dulplicate a copy for reversing horizontally
±↔ reverse horizontally
Ζ`´ŗ replace ` with ´
⁴ create a copy of the original slipper for the untapped part
@┼ append a line of spaces after it horizontally
⁴┼ append horizontally a copy of the reversed slipper
≥ move this - the untapped version - to the botton of the stack
@┼ append a space after the reversed slipper
;┼ append the original slipper after it
+ join the two vertically together
3∙ multiply vertically three times
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~165~~ 127 bytes
```
F´´`«‖TP⪫⪪”}∧≕I3⁼wX¿↔?⁺⊖?◧χêIr﹪≦⎈X⊞c_⁹jEτTCεh⌊Y﹪YY}φ⬤»[↷¢|nX;IζCHE⁷RrCsd~¢_⊖⦄⎚§⌈▷φS¤Iv}›RPx!∧⁵F]üC”`ι»C⁴²¦⁰C²¹¦¹²T⁴²¦²⁴F²C⁰¦²⁴
```
[Try it online!](https://tio.run/##LVBBSsNQED2LZ3DpMgh251IRaUtcFBGFCOrCYD6UmIbSlUYQrFBrgqmLEFNj2i/CdJ/c4V1gjhAnpTADb2Ye896M2eta5kX3rK5Zh5RR1qEZnIB1xjpBPEMcw3mx4UUYPLL@2IbS16x/6A/uA@tXqAX8oAFPUXW/ilsWFzEGIUbeAfyx2YYqTlm/V/31yrdy3sPQPxQS60LCrlx8Tml5BDenye25rN4RmfLb2NuFylmnd5ZxecK/Y5q0RQlhH6NnijD0EOSVy/qLpq0rG85CuPs3W41TNZdjjlfaEOudsqClCENllFIIlUghqKBQMhVXmwmlAponpGt2sunU9T8 "Charcoal – Try It Online") [Verbose approximation](https://tio.run/##ZZBBi8IwFITP9lcMuTSFNGrwtnja24KXXY@BtBTFQGxL7ArLsvvX40uiWHDgQeablxCmO7W@G1oXwnHw4Oy/YRV@i8Xn4egO3bT3bX@h5Myrt2Kx@3aTHb3tJ/4x2J5/jc5OnAEwRkYZo3tgCVEnSa3Jc0Br3JVItA9k6E5kTyjKSBsZYSKNJLKlabZ5NaI8s0fxwp/4HtT0QSPLOc80n5ZznCNSyQQYtSJgqYO/4n0Yf/hGCazIJqPWAmtFbu/tOUVqQy4VqiqknVWGIYT6GuqLuwE "Charcoal – Try It Online") (I don't know how to write `´` in Verbose mode). Explanation:
```
F´´`«
```
Loop twice, once with `´`, once with ```.
```
‖T
```
Reflect the canvas, transforming the characters, except for the above two, which is why they are special-cased. Note that this causes the right slipper to end up on the left, which is actually correct for the second row.
```
⪫⪪””`ι»
```
Print the compressed slipper string, but with ```s replaced with the loop character. (Note that the compressed string includes left padding; this means that the reflected string from the first iteration doesn't touch the second string.)
```
C⁴²¦⁰
```
The right slipper is in the wrong place on the canvas, so copy it to the correct place. (This also makes an extra copy of the left slipper.)
```
C²¹¦¹²
```
The second row also needs a copy of the pair of slippers, but this is the same way around as they were originally created. (Actually both pairs get copied, so we now have eight slippers.)
```
T⁴²¦²⁴
```
Delete all unnecessary extra slippers, leaving two rows of two slippers.
```
F²C⁰¦²⁴
```
Make two additional vertical duplicates of the whole thing.
[Answer]
# Bash + Common Utilities **(~~268~~ ~~265~~ 258 Bytes)**
Saved a few bytes thanks to Justin Mariner
Bash **(~~31~~ 21 Bytes)**
```
gzip -d w;cat w w w
```
Additional File named w **(237 Bytes)** *(Base64 Encoded so I can paste it here)*
```
H4sICIT6rlkAA3cAbZFbDsQgCEX/WQV/ziQWV+BOTOgiu4JZ2YAWhVYSGxpOfNyDyExazPiuOQMsmIe1F5YoTHK2OCDOIEnWVzzhTYBZo5oYbuOkAXwRnNS9qTJ0e9SMOVJKneScFXWWW3bUn+XcFUWaack6krsxav2DH5QP8LaHNcxG7wkMSYUsOSenc8oIHYAy0ExRYxKCl5ByZtZLrG0ZrzZA9eSvohU54RwQUGa7CTgFEX7OIf2XhTsMveQvSeYBO9j3Rpglf2PrHgCR75Y6zgCrwGfJczBuZjgy1c1QH8Af0NuE5gAwAA
```
This might be seen as cheating, and I kind of agree :P.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~575 bytes~~ ~~553~~ 551 characters
```
$a="3__.....__222 __.....__
/ ,1.\2233 /.1, \
(3\23\223 /23/3)
\3\2___\22 /___2/3/
\3\3 ,'3__0.23 .´__3',3 /3/
3\30.'3='30=\2 /=´3'=3'.´3/
3 0.30.23\33 /23.´3.´
33 0.30.2 \3 /2 .´3.´
2 0.30-.___.'\ /'.___.-´3.´
23 0-._2/ \2_.-´
22 0----'3 '----´
23 __.....__33 __.....__
23/.1, \3 / ,1.\
2 /23/3) (3\23\
2/___2/3/ \3\2___\
33.´__3',3 /3/3 \3\3 ,'3__0.
3 /=´3'=3'.´3/33 \30.'3='30=\
3/23.´3.´2 0.30.23\
/2 .´3.´233 0.30.2 \
/'.___.-´3.´223 0.30-.___.'\
\2_.-´222 0-._2/
'----´22223 0----'"
0..3|%{$a=$a-replace$_,('`','------',333,' ')[$_]}
,$a*3
```
[Try it online!](https://tio.run/##VZJBbsIwEEX3PsUIpRqoHDvMX@cYrAhyIxSJBVIRqOqi7a04ARdLvwOBJFJk@/8Z2@8np8/v7nw5dMdj3xdtvUBKIT8pmZk8F06i@HVozACJYe2lcUs0hqxINESsXMNVSomSRI4WEZ1QhHjlvlVgabhdU4J6NtGlVwVFrajqhl317QqtoazKrlQBuavBcEZW@TqMBjenLqNug1zyuiloI1GHWTm67KJnUXjLrDresyr5KETzSClXPaExmdO4Y@ORBE@7Y8s9B2cjs4w58KIzXMzCIN6cF9l/xeHwQrZnEm4CbJMg3Jw2f5VpGO7BbANzTsGNzJSGaHIQC1eFgN@3H/4KRVueu9Ox3XdF8kv9UD80sMoD8Cqiq22Rdn/OF@07@r5fbveH9rzd7XTztdFVj38 "PowerShell – Try It Online")
Simple repeated character replacement. *Edit - saved two characters by using `$a` and looping the `replace` commands.*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 140 bytes
```
"_ ./,-\)'´="•3₅Cæ¶ÿâsΣkÞ₂ÏÕ›|Y=ß°«:ws^N5%ÖΩjĆR["DĀó©›tعoÜ™¾týǝàZ½aÕL.sΔÊÑû8&+››₄|wεŠ8ε¼áNsHÑŽJнi'`³Ö!èÆžIIƵò•11вèJ20ô∞¶¡ε2ä`"´"'`:‚}6FíD»,
```
[Try it online!](https://tio.run/##AeYAGf8wNWFiMWX//yJfIC4vLC1cKSfCtD0i4oCiM@KChUPDpsK2w7/DonPOo2vDnuKCgsOPw5XigLp8WT3Dn8Kwwqs6d3NeTjUlw5bOqWrEhlJbIkTEgMOzwqnigLp0w5jCuW/DnOKEosK@dMO9x53DoFrCvWHDlUwuc86Uw4rDkcO7OCYr4oC64oC64oKEfHfOtcWgOM61wrzDoU5zSMORxb1K0L1pJ2DCs8OWIcOow4bFvklJxrXDsuKAojEx0LLDqEoyMMO04oiewrbCoc61MsOkYCLCtCInYDrigJp9NkbDrUTCuyz//w "05AB1E – Try It Online")
**Explanation**
```
"_ ./,-\)'´=" # push this string
•...• # push a base-255 compressed number
11в # convert to a list of base-11 numbers
èJ # index into the string with these and join
20ô # split in pieces of size 20
∞ # mirror, giving us a pair of shoes
# both using the char "´"
¶¡ # split on newlines
ε # apply to each row
2ä` # split in 2 pieces on stack
"´"'`: # replace "´" with "`" in the 2nd string
‚ # pair them up
} # end apply
6F # 6 times do
í # reverse each
D», # print a copy joined on space and newline
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~328~~ ~~326~~ 316 bytes
```
s=[''.join(' '*int(c)if'/'<c<':'else c for c in l)for l in r"2__.....__9 1/1,------.\8 (2\8\7 \2\6___\6 1\2\3,'2__`.4 2\2`.'2='2`=\3 3`.2`.8\2 5`.2`.7\1 7`.2`-.___.'\ 9`-._6/ 94`----'1 0".split()]
r=[''.join(dict(zip("`/\\(","\xb4\\/)")).get(c,c)for c in l[::-1])for l in s]
for a,b in(zip(s,r)+zip(r,s))*3:print a,b
```
[Try it online!](https://tio.run/##RZBNboQwDIX3cwqLjZNpCCVQ/jScZIySDmXaVAhQYNH28jRhgxfW9yT7Wc/L7/Y1T2rf1/aOKL9nOzEEvNppYz23T0zw1t@wwWFcB@jhOTvf7QQjDzgGdJHSWobSuoY0SUV8lKQKmKKKSiBFhdaaCkg9ZgL9hpE5KFJGompRmZYyyIz0uiIFbweVlEIZKPbWWiJBHbBIoM5NOIEpvEZyXUa7Md5d3Bniw/Yb@7MLi0xCxCIR0c8jJ0p4xLn8HHw80fMzzr1p4rQ7Q63dJfC7eHh1GK3C8ZcATqycX7Nmcf5LYWLf/wE "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~495~~ 468 bytes
```
r,R,s,a,b=str.replace,range(12),str.split,"/(`","\\)\xb4";A=B=r(r(" __.....__8 @ / ,------.#8@( #8# @# # ___# @ # # ,' __`. @ # `.' =' `=# @ `. `.8# @ `. `. # @ `. `-.___.'#@8 `-._ /@"+" "*13+"`----' @","#","\\"),"8"," "*8)
for _ in(0,1,2):B=r(r(r(B,a[_],"*"),b[_],a[_]),"*",b[_])
A,B,j=s(A,"@"),[_[::-1]for _ in s(B,"@")],"\n".join
for _ in"*"*3:print j(j(" ".join((A[_],B[_])[::p])for _ in R)for p in(1,-1))
```
[Try it online!](https://tio.run/##PZDBboMwDIbvewrLHJq0Jh3tDogJKfAIvZYq0KnbQBVFgcP29MwmrJaQfn92ftsMv9P3oz/Ms6cTjdTQNR8nb/xtuDcfN/JN/3VTyUGT0HG4txPhXtVIWFW6@rm@4XuRl7lXXiGAc0bCuRQs7IHiJUyUWgUQpRGEsCxW7ZxblYWV0kZwbQIUVBtGOX91HgUIUq6NONrldchX/2iFK455IWc2kU0XHSp7izsE3CbHHday5QYsXxUtl6EmTFlxPdUvnw8PDtpevVJCB52Fc70qqTm7C@GW26@iJNWSL6l@KaikLh9VQWi55@zOWRYnl38/GNlCKuxR9Wi6R9s/h7HL9pgNvu0n6FTHfzc0KFXIqFIGsN1w0U@70yIH2TShONF6nv8A "Python 2 – Try It Online")
Excited to read Mathematica 12's update notes. (`SlippersTapped@3` only requires 16 bytes!)
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 219 bytes
```
00000000: ec93 d1c9 8630 0c00 df33 c5bd e5ff 419b .....0...3....A.
00000010: 09dc a410 8774 0227 fb34 a0d4 9011 7aa0 .....t.'.4....z.
00000020: 147a 88e4 08b8 b71b 7732 c39d 602c 6bd0 .z......w2..`,k.
00000030: 3a19 6b6b b0d0 e50f 5e21 9b36 1cfe a5bf :.kk....^!.6....
00000040: 82bb 7f55 73f7 d734 2154 5814 dcf7 c643 ...Us..4!TX....C
00000050: 3b0f 77d0 e531 c3db 9bc2 a6b0 6f1d 02db ;.w..1......o...
00000060: ce03 7403 6de7 11e6 ed11 cff8 b336 7c3a ..t.m........6|:
00000070: 5e02 490d d30a ed15 d7e6 ee4d 3ba6 715a ^.I........M;.qZ
00000080: 9344 2804 4627 082d 8cc1 ba50 40ef c375 .D(.F'[[email protected]](/cdn-cgi/l/email-protection)
00000090: 2b90 cba4 4e45 1218 e349 d582 4f35 a922 +...NE...I..O5."
000000a0: f0cd 25d5 f821 9792 6af6 00b9 9314 a327 ..%..!..j......'
000000b0: c899 042b bda2 93a4 f933 905b c990 2189 ...+.....3.[..!.
000000c0: b998 3c3d c8e4 7422 30f7 6bee d7dc afb9 ..<=..t"0.k.....
000000d0: 5f73 bfe6 7efd 36e4 f217 00 _s..~.6....
```
[Try it online!](https://tio.run/##TZNbaxcxEMXf/RSnBalQDZN70iooXsAHLw8KolDNVbAWEVsKRfzq9eTfLTqwuyFkfjkzZ7Ze1Pp9fL04u76WLY4wWrboumWkYAXSRNCntWi@dgw/J5zOFVArhI9diyfqzg1BkyG5NxSnBSlGBzEmYlbrUKQ7ZNEasRTZGOfqQLm1uLplGDK0iwUpDaanmlCjrojRGjSbO4KYhlD7YlztKOrSKPXl/uktw5Jhi848FSqq8OjwMuGH0cjVBug2B4qvEzhSp6eLcbKnwvpuDEdGMpUXT@8R7YzokWUY7R180g69ca8FZ3e1vP@llNt792Ehnm4Mv3RUXhzjToLVrKBXSmgGJVRBmLqzR9zDsbpUSt/U8@OfjkBGG2IRHV@hjwitR8Do7GSbk@2xLCg2W5aOc3Wmtgi/jzZGJMMPMXBZOrqVstI9C1qg4TpVFjK0J@NEvbwlvDpWPz9ujERGto4NSOLgAm2VZDpSaxq1eIGTMVlf9NTx7J56caAekPH2sVIXGyOTYWoWtFrIGM5DG50wrMvoPlHgtB4lGwMcMvn1c74o541X@xujkDGldRjfPWZajsZsEMoMEKmZKmlOsRTIftxVak@pbzf1HGyMunqacoY4w/noxTCJimbmrGfxFS1TJaXlnbeHu2yrPi3Yxmhk1JwTLC0ljcMaHXVb4VSEOga7u/6EWXeMh4/ozb6o3ajdMvryZUaLOmlEHJNGBIKm0ewu5/v/@MwB@3MzotfXfwE "Bubblegum – Try It Online")
Format: **DEFLATE**
Maximum attempted iterations: **10000**
Decompressing iterations: **1019**
[Answer]
# JavaScript, 455 bytes
```
for(_=" Y#YXY WWWV#VU---T.TT, S ,TT.R__QW/PQ_O/OWPY/N%.Y%MM-.O.'L%-._WPK.´JJYJI#0H-´G/'.O.GYJFJQY',PY/EV DX#W,'YQ%.C/=´Y'=Y'JY/BX%.'Y='Y%=#AD @Q.....Q?@ >Y?>> ?0 /R#>@/SH(Y#@#>WP@/Y)0XUO#>W N0 C>E0YADB0WM.@[[email protected]](/cdn-cgi/l/email-protection)#PDI0DL# F0>K U_.G0>W %T-'W'TG0>?WY?0@/S#PRHD/@/Y) (Y#@HVN XUOHW EWC0WBWYA0Y/@IDM.@H /DI>YM.DHF>VLHU_.G>> K0 'TG>>>%T-'0";G=/[>-Y]/.exec(_);)with(_.split(G))_=join(shift());f=a=>_.replace(/./g,a=>`\\\`
`['#%0'.indexOf(a)]||a).repeat(3)
```
[Try it online!](https://tio.run/##Fc7dbqpAEADg@z7FphuySwK7m/TSsKCiAv4AFlkmtUFioaUxYtT09KKP5RP4Yp5lribz8818Vz/VZX9uT1f72H3Uj0fTnWnpPCMEGApASqkc5xvbtjOWZRZ6RVaWsXVZpoonaRnzWCXAVwYDY7m0WczIwrBZqZI5u9@iCKIQi8C@32ac6OYMommUArH0ziRHfoGVRSA12Jg79xsQB0gEfFQYjIBDwHDw0EdeyvpIXQ9JcKVErkB8jaXHXwMK2MNSJR4HUxSbWOdoJdBYTgQM/ZFQS@YViRcKBUvm48QPhb/AaCrkHG1KNhN63shsokimc1eBKzSLk3Xg895E/YEgXyFtBwpN1FiokYKhAO6FvsYDxP1Q9ngwlfki6FH94lwgLUope1w8D2YOf5M2vHNW/9Z7WpoD8197/aIlu5wO7ZXOTLN0vrv2SC9fbXOlpjlonMqRJTvXp0O1ryln/NPSld12u9097d4INgRh7fGj/o0bWpnvf3@V2U/X1ZW@mI99d7x0h5oduk/aaO/xHw)
] |
[Question]
[
Today, *[@HyperNeutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino)* succeeded merging his two accounts, and finally got the reputation he lost back. Now, it's time to celebrate! Your task is to output this exact text:
```
/\
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
| |
| |
| @HyperNeutrino Welcome back! |
| |
| |
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\/
```
## Rules:
* Your program *must not* take input.
* The output must be exactly as shown above.
* Trailing and leading spaces / newlines are allowed.
* [Defaults Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* You can provide output by [any standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") celebration, hence the shortest code in each language wins! Have fun!
[Answer]
# [V](https://github.com/DJMcMayhem/V), 64 bytes
```
i/\
\/16ñH>GMÙXppjÄXppñ5O|³² |M3lR@HyperNeutrino Welcome back!
```
[Try it online!](https://tio.run/##K/v/P1M/hitGX9rQ7PBGDzt338MzIwoKsg63AMnDG039aw5tPrRJoUba1zgnyMGjsiC1yC@1tKQoMy9fITw1Jzk/N1UhKTE5W/H/fwA "V – Try It Online")
Hexdump:
```
00000000: 692f 5c0a 5c2f 1b31 36f1 483e 474d d958 i/\.\/.16.H>GM.X
00000010: 7070 6ac4 5870 70f1 354f 7cb3 b220 7c1b ppj.Xpp.5O|.. |.
00000020: 4d33 6c52 4048 7970 6572 4e65 7574 7269 M3lR@HyperNeutri
00000030: 6e6f 2057 656c 636f 6d65 2062 6163 6b21 no Welcome back!
```
Explanation:
```
i " Insert:
/\<cr>\/ " '/\<newline>\/'
<esc> " Return to normal mode
16ñ ñ " 16 times:
H " Move to the beginning of the buffer
>G " Indent every line
M " Move to the middle of the buffer (the last downward facing part)
Ù " Duplicate this line downwards
X " Delete one of the leading spaces
pp " And paste it between the slashes twice
j " Move down a line (the first upward facing part)
Ä " Duplicate this line upwards
X " Delete one of the leading spaces
pp " And paste it between the slashes twice
5O " On the five lines above us, insert:
|³² | " A bar followed by 32 spaces, followed by a bar
<esc> " Return to normal mode
M " Move to the middle line of the buffer
3l " Move 3 characters to the right
R " And write the following over the existing text:
@HyperNeutrino Welcome back! " Welcome back!
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
↑³↗¹⁷‖M‖B↓J³¦⁰“]‹baiE_ν﹪↓➙ZKξη¢:Agλ⁸%I”
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMqtEBHwVjTmgvODcpMzyjRUTA0BwoGpablpCaX@GYWFeUXaSAEnEpLSlKL0nIqNaxc8svzgBJepbkFIfkaxjoKBnDDlBw8KgtSi/xSS0uA/HyF8NSc5PzcVIWkxORsRSVN6////@uW/dctzgEA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~87~~ ~~78~~ ~~81~~ 79 bytes
-9 bytes because of dictionary compression
+2 bytes because "back" isn't capitalized
-2 bytes because of "mirroring"
```
17F'/16N-úðN׫∞}'|D32ú«D”| @HyperNeutrino‡Ý back! |”'|D32ú«D17F'\Núð16N-׫∞}»
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f0NxNXd/QzE/38K7DG/wOTz@0@lHHvFr1Ghdjo8O7Dq12edQwt0ZBwcGjsiC1yC@1tKQoMy//UcPCw3MVkhKTsxUVFGqAKhDKQcbF@IHMApsJNe7Q7v//v@bl6yYnJmekAgA "05AB1E – Try It Online")
---
## Explanation (split into parts)
Produces the "triangle" at the top
```
17F # for N in 0 .. 16
'/ # push a forward slash
16N- # 16 - N
ú # put 16 - N spaces in front of the forward slash
ð # space character
N× # repeated n times
} # end of for loop
```
Produces the two lines with vertical bars at the end.
```
'| # push a vertical bar
D # duplicate
32ú # put 32 spaces before the vertical bar
« # concatenate, i.e. one line complete
D # duplicate
```
Produces the "Welcome back" string; `”| @HyperNeutrino‡Ý back! |”`.
Most of it is interpreted as the literal characters, except for `‡Ý`, which is interpreted as `Welcome`.
Exact copy of second section: `'|D32ú«D` produces second set of vertical bar lines
Produces the "triangle" at the bottom, similar to first part
```
17F # for N in 0 .. 16
'\ # push backslash
Nú # put N spaces before backslash
ð # space character
16N- # 16 - N
× # 16 - N spaces
« # concatenate the two strings
∞ # mirror
} # end for
```
The `»` at the end joins everything by newlines and implicitly prints.
[Answer]
# T-SQL, 222 bytes
```
DECLARE @ INT=1T:PRINT SPACE(17-@)+'/'+SPACE(2*(@-1))+'\'SET @+=1IF @<18GOTO T
PRINT REPLACE('|S|
|S|
| @HyperNeutrino Welcome back! |
|S|
|S|','S',SPACE(32))B:SET @-=1PRINT SPACE(17-@)+'\'+SPACE(2*(@-1))+'/'IF @>0GOTO B
```
Pretty straightforward procedural approach. Formatted:
```
DECLARE @ INT=1
T: --count up for top cone
PRINT SPACE(17-@) + '/' + SPACE(2*(@-1)) + '\'
SET @+=1
IF @<18 GOTO T
--middle section, string literal with line breaks and a single replace
PRINT REPLACE('|S|
|S|
| @HyperNeutrino Welcome back! |
|S|
|S|','S',SPACE(32))
B: --count back down for bottom cone
SET @-=1
PRINT SPACE(17-@) + '\' + SPACE(2*(@-1)) + '/'
IF @>0 GOTO B
```
Only thing probably worth explaining is that strings in T-SQL can contain line breaks inside the quotes, I take advantage of that here, instead of adding `CHAR(13)`.
[Answer]
# [Python 2](https://docs.python.org/2/), 187 bytes
```
f,s=lambda s,n=1:'\n'.join((s%(' '*i)).center(34)for i in range(0,34,2)[::n]),'|%s|\n'
print f('/%s\\')+'\n'+s%(' '*32)*2+s%(' @HyperNeutrino Welcome back! ')+s%(' '*32)*2+f('\\%s/',-1)
```
[Try it online!](https://tio.run/##VcyxDoIwFEDR3a94Dk1bqCiFiYTE0cnVwToAFq3CK2nrQMK/I0YXxzvcM4zhblHOcyt82VV9fa3ACyzTgiqkycMaZMwTRoFGhvOk0Ri0Y1nOW@vAgEFwFd4024ksF5KfiwIvXNCJ@GkBVoMzGKBldEu8UpTHHzb@gZnkkfwG7A/joN1Rv8JyWDjprrG9hrpqnmuAZfx7FlAp4rdUbFI@z28 "Python 2 – Try It Online")
[Answer]
# Mathematica, 165 bytes
```
T=Table;c=Column;c[{s=c[T[""<>{"/",T[" ",2i],"\\"},{i,0,16}],Alignment->Center],g=c@T[""<>{"|",T[" ",32],"|"},2],"| @HyperNeutrino Welcome back! |",g,s~Rotate~Pi}]
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 107 bytes
```
17#¶#¶|2@HyperNeutrino Welcome back!2|¶#¶#17
#
|32|
\d+
$*
\G (?=( *))
$1/$`$`\¶
r`(?<=( *)) \G
¶$1\$'$'/
```
[Try it online!](https://tio.run/##K0otycxL/P@fy9Bc@dA2IKoxcvCoLEgt8kstLSnKzMtXCE/NSc7PTVVISkzOVjSqAStSNjTnUuaqMTaq4YpJ0eZS0VLginFX0LC31VDQ0tTkUjHUV0lQSYg5tI2rKEHD3gYirBDjznVom4phjIq6irr@//8A "Retina – Try It Online") Explanation: The first stage inserts the text and starts outlining the surrounding characters, which are further expanded by the next two stages. The fourth and fifth stages then generate the top and bottom diagonal lines respectively.
[Answer]
# [PHP](https://php.net/), 174 bytes
```
for(;$i<39;)echo($p=str_pad)($p($i>16?$i!=19?$i>21?"\\":"|":"| @HyperNeutrino Welcome back! ":"/",$i>16?$i>21?77-$i*2:33:$i*2+1).($i++>16?$i>22?"/":"|":"\\"),34," ",2),"
";
```
[Try it online!](https://tio.run/##NU27DoIwFN39inLTgUrR0BoJzzo6ubqQGKw1NCptKg4m/rYzlhiG8xjOw3Z2LIX1fDUuLLAueVYQJTsTYls9B3ey7YV4H2JdJ1uBdVAlmZeaJQKaBnL4TEBot39b5Q7qNTjdG3RUd2keCp1beQsQ8pk10HljKqdpjPWS5Zznk0YJWfmPKJoTTPjGf93fEMo3FBBQRigsoBjHb29i2cpO/QA "PHP – Try It Online")
[Answer]
# [///](https://esolangs.org/wiki////), 306 bytes
```
/6/"\\//5/\/\///4/"#53/ 52/\\%51/\/%50/\\'5-/\/'5,-|%%"3|/-/
5&/3#/1/""5#/3\\5"/3331&/\0% #/#0%#/&0% \/60%\/40" &/"&0"&1\0" #1#041&0" \1606140 &1"&0&1%\0 #1%#0#1%&0 \1%60\1%4\,,'|3@HyperNeutrino Welcome back!3|,,'\2%4- \2%6-#2%&- #2%#-&2%\- &2"&-624-" \26-42&-" #2#-"&2\-" &\"&-%\\4-% \\6-%#\&-% #\#-%&\\/
```
[Try it online!](https://tio.run/##DZC9SgRRDIV7nyLekEwzIbm/taWVrU2adbmguOvKjhbCvPsYAofv5AQSsl1O2/vcjkOHJnfVrh6l2jRhrwrQi7pTz9GlbsFLl@Clr7ITpbqr6ENnrahZU@qo1b0nrbVmVjcCVDRC5UDXYeTaLAFrYkucPRgzWsthwfOwkZsB54g5k1ukhBbCFjENC2m@rsten57/vuf9Zf7@3D@@bvA6L@fbdcLb6fz5WPcY8UJNIHQIFmKBUBQu5AJcEssoTWJrGdIKB2FBSVw8kD1ycm8Sd/sQQg8P6CjE8arj@Ac "/// – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~54~~ 50 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
ā'²∫0; /ž}j"ν_‘3∙+╬³"Ξ█a⁄I⅜ģī\↕═<ν▲ΩhΕR$C¹‘4L«žj╬Æ
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTAxJTI3JUIyJXUyMjJCMCUzQiUyMC8ldTAxN0UlN0RqJTIyJXUwM0JEXyV1MjAxODMldTIyMTkrJXUyNTZDJUIzJTIyJXUwMzlFJXUyNTg4YSV1MjA0NEkldTIxNUMldTAxMjMldTAxMkIlNUMldTIxOTUldTI1NTAlM0MldTAzQkQldTI1QjIldTAzQTloJXUwMzk1UiUyNEMlQjkldTIwMTg0TCVBQiV1MDE3RWoldTI1NkMlQzY_)
Explanation:
```
ā push an empty array
'²∫ } 17 times repeat
0; push 0 below the iteration
/ž at [0, iteration] (1-indexed position) insert the slash (so every time it moves everything one char right)
j remove last blank line (idk why it's there)
"ν_‘ push "| "
3∙ get an array of 3 of those
+ append that to the diagonals mirrored
╬³ mirror horizontally with 0 overlap and swapping chars
"..‘ push "@HyperNeutrino Welcome back!"
4L«ž at [4;20] insert that in
j remove last blank line (2nd byte wasted now)
Β mirror vertically
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 57 bytes
```
žvƒ'/'\N·ú«}'|žvúÂìD”| @HyperNeutrino‡Ý back! |”)¦í«.c
```
[Try it online!](https://tio.run/##AVcAqP8wNWFiMWX//8W@dsaSJy8nXE7Ct8O6wqt9J3zFvnbDusOCw6xE4oCdfCAgQEh5cGVyTmV1dHJpbm/igKHDnSBiYWNrISAgfOKAnSnDgsKmw63Cqy5j//8 "05AB1E – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 55 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
⁷╵\║:↕|“ ”⁷×+║2*:“×∔]*YV≠²↖:tvxZ}@l J{ 5n\┌⟳sc⤢7‟;∔∔┘∔∔
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyMDc3JXUyNTc1JXVGRjNDJXUyNTUxJXVGRjFBJXUyMTk1JTdDJXUyMDFDJTIwJXUyMDFEJXUyMDc3JUQ3JXVGRjBCJXUyNTUxJXVGRjEyJXVGRjBBJXVGRjFBJXUyMDFDJUQ3JXUyMjE0JXVGRjNEJXVGRjBBWVYldTIyNjAlQjIldTIxOTYlM0F0diV1RkY1OFoldUZGNURAJXVGRjRDJTIwJXVGRjJBJXVGRjVCJTIwJXVGRjE1JXVGRjRFJXVGRjNDJXUyNTBDJXUyN0YzcyV1RkY0MyV1MjkyMjcldTIwMUYldUZGMUIldTIyMTQldTIyMTQldTI1MTgldTIyMTQldTIyMTQ_,v=8)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 47 bytes
```
\/16꘍¦øṀ÷\|16꘍m:`| @Hy∧‛NeꜝṘ⋏⇩ ÷… λǐ! |`WḂḢRJ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJDIiwiIiwiXFwvMTbqmI3CpsO44bmAw7dcXHwxNuqYjW06YHwgIEBIeeKIp+KAm05l6pyd4bmY4ouP4oepIMO34oCmIM67x5AhICB8YFfhuILhuKJSSiIsIiIsIiJd)
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 40 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
⁷╵/|3*∔╫@HyperNeutrino Welcome back!4A«╋
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyMDc3JXUyNTc1JXVGRjBGJTdDJXVGRjEzJXVGRjBBJXUyMjE0JXUyNTZCQEh5cGVyTmV1dHJpbm8lMjBXZWxjb21lJTIwYmFjayUyMSV1RkYxNCV1RkYyMSVBQiV1MjU0Qg__,v=8)
There's already a Canvas answer here but I'd say this uses a fairly different approach.
[Answer]
# [Deadfish~](https://github.com/TryItOnline/deadfish-), 2245 bytes
```
{iii}ii{c}cccccc{i}iiiiic{iiii}iiiiic{{d}ii}ddc{ii}ii{c}ccccc{i}iiiiic{d}dddddcc{iiiiii}c{{d}ii}ddc{ii}ii{c}cccc{i}iiiiic{d}dddddcccc{iiiiii}c{{d}ii}ddc{ii}ii{c}ccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}ii{c}cc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}ii{c}c{i}iiiiic{d}ddddd{c}{iiiiii}c{{d}ii}ddc{ii}ii{c}{i}iiiiic{d}ddddd{c}cc{iiiiii}c{{d}ii}ddc{ii}iiccccccccc{i}iiiiic{d}ddddd{c}cccc{iiiiii}c{{d}ii}ddc{ii}iicccccccc{i}iiiiic{d}ddddd{c}cccccc{iiiiii}c{{d}ii}ddc{ii}iiccccccc{i}iiiiic{d}ddddd{c}cccccccc{iiiiii}c{{d}ii}ddc{ii}iicccccc{i}iiiiic{d}ddddd{cc}{iiiiii}c{{d}ii}ddc{ii}iiccccc{i}iiiiic{d}ddddd{cc}cc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}ddddd{cc}cccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}ddddd{cc}cccccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}ddddd{cc}cccccccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}ddddd{cc}{c}{iiiiii}c{{d}ii}ddc{iiii}dddc{d}ddddd{cc}{c}cc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}dd{cc}{c}cc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}dd{cc}{c}cc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddcc{iii}iic{i}ddc{iiiii}dc{d}ic{d}dc{i}iiic{ddd}ddddddc{ii}iiic{i}iiiiiicdcddc{d}iciiiiicic{{d}ii}ic{iiiii}iiiiic{i}iiiic{i}dddc{d}ic{i}iicddc{d}iic{{d}iii}ic{iiiiii}iiiiiicdciic{i}ddc{{d}iii}ddddcdcc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}dd{cc}{c}cc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}dd{cc}{c}cc{{i}d}iic{{d}}{d}ddddc{{i}dd}iic{dddddd}{cc}{c}cc{i}iiiiic{dddd}iiic{ii}iic{iiiiii}c{dddddd}{cc}{c}{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}{cc}cccccccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{cc}cccccc{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}{cc}cccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}c{dddddd}{cc}cc{i}iiiiic{dddd}iiic{ii}iicccccc{iiiiii}c{dddddd}{cc}{i}iiiiic{dddd}iiic{ii}iiccccccc{iiiiii}c{dddddd}{c}cccccccc{i}iiiiic{dddd}iiic{ii}iicccccccc{iiiiii}c{dddddd}{c}cccccc{i}iiiiic{dddd}iiic{ii}iiccccccccc{iiiiii}c{dddddd}{c}cccc{i}iiiiic{dddd}iiic{ii}ii{c}{iiiiii}c{dddddd}{c}cc{i}iiiiic{dddd}iiic{ii}ii{c}c{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}ii{c}cc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}ii{c}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{dddd}iiic{ii}ii{c}cccc{iiiiii}c{dddddd}cccc{i}iiiiic{dddd}iiic{ii}ii{c}ccccc{iiiiii}c{dddddd}cc{i}iiiiic{dddd}iiic{ii}ii{c}cccccc{iiiiii}c{dddd}dddddc
```
[Try it online!](https://tio.run/##tdVLEsIgDADQE3koh@iYtUsmZ8cUkkJrPl1oN1LIgxAZCo87PPH9urVWEZEQa6HSn7q98VO2gb1dgVsEsPUu0TMYeJCfMhgHecYgKTJNphyUsC/FnRGw4oMlykzCchekB3Pqy9QaNCiLT5KFHBMrF4UsUJGzC@HVojfgHGvPzzPrYRrdtAIeAZIRkvl@Z0ZGsj9NnVtb5mOrsnFug2xGSzJrggUKiBnv@8WBOqVeLaS/oKL3qVc45bLGTFNiejbw9ypdMDC6R4Fo@b/3UwM9BOd50pNwNL6wiXE7nF0EI@a7UHksRk5BYmOhSxVJcEpd68rDVbGaSJjLhOBbpOXQL63pEmWzDFkqNSckX/bWPg "Deadfish~ – Try It Online")
Tio runs 3/4 of it.
] |
[Question]
[
# Context
As a conlanger, I am interested in creating a uniform, naturalistic language. One of the tricks is to create vocabulary according to certain structures of words. An example from English: In English, we have the word “tap” structured consonant-vowel-consonant. Usually, this means that there are many other words of this structure: “cat”, “dog”, “rock”, “fog”, “good”, etc.
# Task
As input, you have:
* an array `C` containing strings: consonants (`C` is the first letter in the word consonants). Identical consonants cannot be repeated on this list. For example, this list cannot contain ['b', 'b'].
* an array `V` containing strings: vowels (`V` is the first letter of the word vowels). Identical vowels cannot be repeated on this list.
* string `S`, which contains something like this "CVCCV" (any combination of "C" and "V")
Your task is to replace “C” in the string with a randomly taken string from array `C` and replace “V” in the string with a randomly taken string from array `V` and return (or display) this string.
"randomly" is defined as all possibilities having an equal chance of being selected. This is a kind of simplification: in real languages as well as in conlangs, there are very frequent (for example 'r' in English) and not very frequent sounds but this is just a code-golf.
# Rules
This is code-golf so the lowest byte count wins.
# Examples
```
Input:
C = ['p', 'b', 't', 'd', 'k', 'g', 'm', 'n', 'w']
V = ['a', 'o', 'u', 'i', 'e', 'ä']
S = 'CVCCV'
Output:
pakto
```
```
Input:
C = ['p', 'b', 't', 'd', 'k', 'g', 'v', 's', 'r']
V = ['a', 'o', 'u', 'i', 'e', 'ä', 'ᵫ']
S = 'CVVCCVCCV'
Output:
koebrᵫvtä
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
Takes input as `S`, `[V,C]`
```
Çè€Ω
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cPvhFY@a1pxb@f@/c5izcxhXtFJBUklKdnpuXrmSjoJSYn5pZurhJUqxAA "05AB1E – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to Neil!
```
OịX€
```
A dyadic Link accepting a list of characters, `S`, on the left and a list of two lists of characters, `[C, V]`, on the right which yields a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8/9//4e7uiEdNa/7//6/kHObsHKb0P1qpIKkkJTs9N69cSUdBKTG/NDP18BKlWAA "Jelly – Try It Online")**
If we could take `S` as a list of `1`s and `0`s we'd have the three byte solution `ịX€`.
### How?
```
OịX€ - Link: S, [C,V]
O - ordinals (of S) i.e. 'C':67 'V':86
ị - index into [C,V] (vectorises) C V [Jelly indexing is 1-indexed and modular]
€ - for each:
X - random choice
```
[Answer]
# Python 3, ~~[92](https://tio.run/##Jc09DoMwDAXgnVNYLCFSxNKtEhNHQGJpGYJJStr8KdBUvU9v0oNRTJdPst6zHd/rHPxp09DAdbPSjZMEFFks57Ks78H4Kkk/BVfjHAyqynLQIYEF4y8IRoNsmhJLUHZRkI9M7hksAy@MiyGt8D@wtfuLC4tMABuJlZiIB3EjHOGJFxuK/tiQNAbiSRhCEd/P3un2DsOMmFkRk/FrpatW9KLjfPsB)~~ ~~[68](https://tio.run/##Jc1NCsIwEAXgfU4xdJNEQlHcFXTTIxS6qUXS9Meo@aFNW7yPN/FgNaObDwbem@df4ebscevhBJftKU3TSpjEbs2SJL07bdkobetMqm5Oq46tlTwnc1Lz3o0gQVuYONHGuzHAP7nl8VVFPRVAGyQgLfJABsQgFllpTcpfQ@LpkBnRSId83jFTxAxVi1ILJQTHrzgeJ4eOHfY8IwB@1DawnhUiFyXn2xc)~~ 61 bytes
Takes input as `S`, `C`, `V`:
```
lambda s,*w:[random.choice(w[a>"u"])for a in s]
import random
```
You can [try it online](https://tio.run/##Jc1NCsIwEAXgfU4xuEkqQRR3Bd30CIVuapE0/QuaH9K0xft4Ew8WM7r5YOC9ee4VJmvOcYAL3OJT6LYTMPP9ltdemM7qg5yskj3banHdLbsmG6wHAcrA3BClnfUB/slYpB81dZQDbZGAdMgDGRGNGGSjDal@DYGnRRZEIT3yeadMmTJUrlKulBAcv@N4mhx7djpmOQFwXpnABlbygldZFr8)! How it works:
The `*w` is used so that the lists of consonants and vowels are packed in a list `w`.
When we do `w[a > "u"]` we are essentially checking if `a` (a character of `s`) is "v" or not. If it is, then `a > "u"` returns `True`, which indexes as `1` into `w`. If `a` is "c", then `a > "u"` returns `False`, which indexes as `0`.
We use those indices to retrieve the correct list of letters from `w` and then choose randomly from that list, picking the list of choices.
Thanks @Arnauld for saving one byte and to @Jonathan Allan for citing [this meta](https://codegolf.meta.stackexchange.com/q/2214/75323), saving me 7 bytes.
[Answer]
# APL+WIN, ~~35~~ 34 bytes
One byte saved thanks to Adam
Prompts for consonants and vowels as continuous strings and the desired output as a comma separated string
```
c←⍞⋄v←⍞⋄C←',c[?⍴c]'⋄V←',v[?⍴v]'⋄⍎⎕
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4nA5mPeuc96m4pg7OcgSx1neRo@0e9W5Jj1YEiYWCRMrBIGVjkUW8f0KT/QDP@p3EVJJWkZKfn5pVzJaZm5pdyOeuE6TgDYRgA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~45~~ 40 bytes
```
->s,*l{s.bytes.map{|x|l[x%2].sample}*''}
```
[Try it online!](https://tio.run/##HctBDsIgFIThfU/BxrykQRbu60UIC0BqjKDE12KbtrfxJh4MO26@ZJJ/XqOba9/V45llGxdWbh4Cq2Tzsk5r1NPhZBTblGPYWqKtetEJTZmkIAcGcAF3cAUJPMCbTFP@D4v5BCO4gQC@n73hvSFfvC/UZNFrlkV6U38 "Ruby – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes
```
⭆η‽§θ℅ι
```
[Try it online!](https://tio.run/##FcpBCsIwEAXQq2Q3EeIJXElWLkRR6CZkMTalDcakjbF4IHeuPYEn8SSxf/i8z4dpB85t4lDrMftY5Lks1e95lIMSJ44u3eS27KLrnnJS4pCdjxykX@E2tRpjiEkJSuABPOjA9wV/nzdZJQyNWBdQgANX0IMZ3EEmu/yTbhqtEbJ1PYc/ "Charcoal – Try It Online") Link is to verbose version of code. Takes the input in the form `[V, C], S` where each value can be either a string or an array of characters as desired. Explanation:
```
η `S`
⭆ Map over elements/characters
θ `[V, C]`
§ Cyclically indexed by
℅ Ordinal of
ι Current element/character
‽ Random element/character
Implicitly print
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 66 bytes
```
(C,V,s)=>s.Select(x=>(x<68?C:V).OrderBy(l=>Guid.NewGuid()).Last())
```
[Try it online!](https://tio.run/##nctNCsIwEAXgvacQN00gZimibQSDiiC6EOpCXMR01GCNkqT@IN7GnWtP4Ek8SXXAEwjD93jDjPZ17U3ZL6yOhz1b7MCpZQ6x3ign2F8bsUpKIlnKPE2E51PIQQdyTgQ5x41mR7ZSyicuA9e9kDwRg8JkfAwnTEIpHykfvlm2KzNnAoyMBeKDM3bN5d5qFciKWDjNF9foELFqtEQCkiFbZI0cEY@46MZ@Lwr7HikQgwDyuqPv5@N7W5NpKiVOjVLaLj8 "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ËcgV ö
```
Takes input as `S`, `[V,C]`
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=y2NnViD2&input=ImN2dmNjdmNjdiIKWyJhb3VpZeRcdTFkNmIiCiJwYnRka2d2c3IiXQ)
[Answer]
# [W](https://github.com/A-ee/w) `f` `j`, 4 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
Hmm, let's do a pure-ASCII port of that.
```
C[gr
```
## Explanation
```
C % Convert the string to its codepoints
[ % Index into the other list
r % For every indexed item:
g % "g"et a random item in this list
Flag:f % Flatten the output list
Flag:j % Join the flattened output list
```
```
[Answer]
# [PHP](https://php.net/), 68 bytes
```
function($C,$V,$s){for(;$r=$s[$i++];)echo$$r[rand(0,count($$r)-1)];}
```
[Try it online!](https://tio.run/##FcxNCsIwEAXgfU/hYmASGkHXsbjIHboJXdT@2CIkIU3diLdx59oTeBJPEvtg@Hg8HhOmkE/nMIWioLHK4@q6NHsnyCiqFS3yMfooNMWKFktzWTZaDt3kiaKNrevFQXV@dUlshdwfZaOfWW@vhOXAascXkEAPbuAK7mABkRtluUX0YAUzGMD3BX@f9zZjU9fG4Fjq/Ac "PHP – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 92 bytes
```
f(s,c,v,m,n)char*s,**c,**v;{for(srand(&s);*s;)printf("%s",*s++/86?v[rand()%n]:c[rand()%m]);}
```
Takes as input a string (`s`), an array of consonant strings (`c`), an array of vowel strings `v`, the length of `c` (`m`), and the length of `v` (`n`).
Could use a temporary variable for the result of `rand` but it wouldn't save me anything.
[Try it online!](https://tio.run/##lZFLTsMwEIb3OYXlqsiTGkqyQAjzEMqKbZG6IMoiOElrQZwqToxE1duwY80JOAknCZ5Q@pC6qaX5NB7P/3ukkaczKbuuYIZLbnnJNch5WvuG@750YcWyqGpm6lRn7MSA8I2ARa10UzA6NJT7ZjQaX17c2bhvgaFOruR/XiYgVt1AafnaZjm5Nk2mqrP5recNsrxQOif3k8njwxNLgTCj3vOqwHRM1rm7xOcJgOe5D0mZKs1spTLwlh5xByclvgzihNz0hb8yHrqgnNBnRIPIEC@IGaJEaMQb7TUrsesYHu9oEQZRbxx3LO3BIVPsrxAtQiFyxPfHgbFseKyH48/X5/48bm/RNIqm7lEGnFgX6yXIADa5DQAEWbSNYZSC2CpRulaHTh1u1eGOOtxXr7pf "C (gcc) – Try It Online")
[Answer]
# JavaScript (ES6), ~~65~~ 64 bytes
```
(C,V,s)=>s.replace(/./g,x=>eval(x).sort(_=>Math.random()-.5)[0])
```
[Try it online!](https://tio.run/##lc0xDoIwFMbxnVOwtU1qcXEsS2dXFkJMhYJoaUlbkQO5OXsCT@JJqk@Nsy6/5CXvy38vJ@lr149hYWyjYssjFrSgnvDcM6dGLWuFM5Z1dOa5mqTGM2HeuoA3PF/LsGNOmsYOmCzYipTLisTaGm@1Ytp2uMVJmpZoRDRFWyAADXAAOmAADHBCFX0NJFwWOAI9oIDb@f2CRCFEgRJCkr97E@AB90vv6f16@Wah@0nHBw "JavaScript (Node.js) – Try It Online")
Or [55 bytes](https://tio.run/##lc0xDoIwFMbxnVOwtU3qi4tjWTq7shBiKhREoSVtRQ7k5uwJPIknqT6jg5suv@Ql78t/ryblK9eNYWFsrWMjIpU8556JzMOgRjqLTE@qpzMDb12gG5GtVdiBU6a2A2ULWLFiWbJYWeNtr6G3LW1okqYFGQlPyRYJSI0ckBYZEIOcSMlfA4WXRY5Ih2jkdn6/AACRuZQ5KRPGkr@jE@IR90v06f16@Wpj/NOPDw) if we can use an array of characters as I/O.
] |
[Question]
[
This is different from [Print the Greek alphabet!](https://codegolf.stackexchange.com/questions/97049/print-the-greek-alphabet) because it is in words.
This is different from ["Hello, World!"](https://codegolf.stackexchange.com/questions/55422/hello-world) because the output is different and much longer, leading to different techniques.
This is different from [We're no strangers to code golf, you know the rules, and so do I](https://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i) because the output is different and much shorter, leading to different techniques.
Your task is to print this exact text: (the Greek alphabet in words)
```
alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega
```
Capitalization does not matter.
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]
# Python 2, ~~99~~ 81 bytes
```
from unicodedata import*
i=913
exec"print name(unichr(i+(i>929)))[21:],;i+=1;"*24
```
Thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor) for saving 15 bytes!
This uses the `unicodedata.name()` method
to get the name of every character. Unfortunately, the code point 930 gives an error for some reason, so that cost a few extra bytes.
This also prints the output in uppercase, which is allowed.
[Answer]
# Scala, 76 bytes
```
print((913 to 937)filter(930!=)map(Character getName _ drop 21)mkString " ")
```
Explanation:
```
print( //print...
(913 to 937) //build a range of the codepoints for aplha to omega
filter(930!=) //filter out that sigma in the middle
map( //map each char...
Character getName _ //to its full unicode name, e.g. "GREEK CAPITAL LETTER ALPHA"
drop 21 //and drop the first 21 chars, aka "GREEK CAPITAL LETTER "
)
mkString " " //join them with a space
)
```
[Answer]
# Jolf, 7 bytes
```
RΜpΧ΅z♣
```
Replace `♣` with `0x05`, or [try it here!](http://conorobrien-foxx.github.io/Jolf/#code=Us6ccM6nzoV6BQ) Or, use [this link](http://conorobrien-foxx.github.io/Jolf/#code=4oKvU-KCr0NSfm1HIjgyIDkyNCAxMTIgOTM1IDkwMSAxMjIgNScgImRwQUhFRQ) to generate the code. (Just click run, the code will be written into the code box.)
## Explanation
```
RΜpΧ΅z♣
ΜpΧ map Greek character alphabet
΅z with the toGreek function (converts greek characters to names)
R ♣ and join that with spaces.
```
[Answer]
# ///, ~~119~~ 117 bytes
```
/1/eta //2/psilon //3/a /alph3b1gamm3delt3e2z11th1iot3kapp3lambd3mu nu xi omicron pi rho sigm3tau u2phi chi psi omega
```
*-2 bytes thanks to steenbergh*
[Try it online!](http://slashes.tryitonline.net/#code=LzEvZXRhIC8vMi9wc2lsb24gLy8zL2EgL2FscGgzYjFnYW1tM2RlbHQzZTJ6MTF0aDFpb3Qza2FwcDNsYW1iZDNtdSBudSB4aSBvbWljcm9uIHBpIHJobyBzaWdtM3RhdSB1MnBoaSBjaGkgcHNpIG9tZWdh&input=)
[Answer]
# PHP, 68 characters, 92 bytes
```
<?=strtr(htmlentities(αβγδεζηθικλμνξοπρστυφχψω),["&"=>"",";"=>" "]);
```
uses UTF-8; prints a trailing space. Run with `-nr`.
* turn the lowercase greek alphabet into html entities
* remove ampersands and replace semicolons with spaces
* print
[Try it online](http://sandbox.onlinephpfunctions.com/code/76688bad145b3a049444f626069b81134a35055b)
[Answer]
# BF, 1265 bytes
```
++++++++++.--[--->++++<]>+.+++++++++++.++++.--------.-------.-[->+++<]>.[->+++<]>++.+++.[--->+<]>---.+[->+++<]>++.-[->+++<]>.++[->+++<]>+.------.++++++++++++..------------.-[->+++<]>.+[->+++<]>+.+.+++++++.++++++++.+[->+++<]>++.-[->+++<]>.+[->+++<]>++.+++++++++++.+++.----------.+++.+++.-.-[->+++++<]>-.-[->++++<]>--.---[->+++<]>.[--->+<]>---.+[->+++<]>++.-[->+++<]>.+[->+++<]>++.[--->+<]>---.+[->+++<]>++.-[->+++<]>.---[->++++<]>.------------.---.[--->+<]>---.+[->+++<]>++.-[->+++<]>.-[--->++<]>-.++++++.+++++.+[->+++<]>++.-[->+++<]>.-[--->++<]>+.----------.-[++>-----<]>..[----->++<]>+.-[->+++<]>.++[--->++<]>.-----------.++++++++++++.-----------.++.---.-[->+++<]>.+[----->+<]>.++++++++.-[---->+<]>+++.+[----->+<]>+.+++++++.-[---->+<]>+++.--[->++++<]>.[->+++<]>+.[--->+<]>---.+++++[->+++<]>.--.----.------.-[--->+<]>----.---.-.-[->+++++<]>-.[-->+++++++<]>.-------.[--->+<]>---.---[----->++<]>.----------.+++++++.[--->+<]>-----.---[->++++<]>-.----------.--.++++++.------------.-[->+++<]>.---[->++++<]>.+[->+++<]>++.--[--->+<]>.-[---->+<]>+++.---[->++++<]>+.-----.+++.----------.+++.+++.-.-[->+++++<]>-.[-->+++++++<]>.--------.+.[--->+<]>---.+[->+++<]>.+++++.+.[--->+<]>---.[-->+++++++<]>.+++.----------.[--->+<]>---.+++++[->+++<]>.--.--------.++.------.>++++++++++.
```
[Answer]
# Mathematica, ~~85~~ 66 bytes
*Thanks to ngenisis for pointing the way to a 19-byte savings!*
```
CharacterName@Alphabet@"Greek"~Riffle~" "~StringDelete~"Curly"<>""
```
Returns the string with every Greek letter capitalized. Just thought it would be fun to coerce Mathematica into doing all the work!
`Alphabet@"Greek"` returns a nicely formatted list of the Greek alphabet characters; `CharacterName@` converts each of those characters into a string naming that character, and `~Riffle~" "` inserts a space between each such string. Unfortunately, two of the letters are called `"CurlyEpsilon"` and `"CurlyPhi"`, and so we need `~StringDelete~"Curly"` to fix that. Finally, `<>""` concatenates all these strings together.
Previous submission:
```
StringDelete[ToString@FullForm@Alphabet@"Greek","List"|"Curly"|"["|"]"|"\""|"\\"|","]
```
`Alphabet@"Greek"` returns a nicely formatted list of the Greek alphabet characters as before, but `FullForm` forces it to show the internal structure rather than the nice formatting; `ToString` converts that internal structure into a string that can be manipulated:
```
"List[\"\\[Alpha]\", \"\\[Beta]\", \"\\[Gamma]\", \"\\[Delta]\", \"\\[CurlyEpsilon]\", \"\\[Zeta]\", \"\\[Eta]\", \"\\[Theta]\", \"\\[Iota]\", \"\\[Kappa]\", \"\\[Lambda]\", \"\\[Mu]\", \"\\[Nu]\", \"\\[Xi]\", \"\\[Omicron]\", \"\\[Pi]\", \"\\[Rho]\", \"\\[Sigma]\", \"\\[Tau]\", \"\\[Upsilon]\", \"\\[CurlyPhi]\", \"\\[Chi]\", \"\\[Psi]\", \"\\[Omega]\"]"
```
From here, `StringDelete[..."List"|"Curly"|"["|"]"|"\""|"\\"|","]` gets rid of all the stuff we don't want.
[Answer]
# Pyth - ~~104~~ 83 bytes
Base conversion with separator `f`. Unfortunately, it starts with smallest code point `a`.
```
tX."azT¢ç§ªVôòé!þm<EÞ6ä¿û2_w}MªÍ]·¥ünBPæúòRÜÔYcWed¼(É?«/~{"\fd
```
[Try it online here](http://pyth.herokuapp.com/?code=tX.%22az%16T%C2%A2%C3%A7%C2%A7%C2%AAV%17%C3%B4%C2%83%C3%B2%02%15%C3%A9%21%C3%BE%1Cm%3C%07E%03%C3%9E%066%C3%A4%1A%C2%BF%C3%BB%7F2_w%C2%8F%05%7DM%C2%AA%C3%8D%11%5D%C2%B7%C2%A5%C3%BCnB%C2%86P%C3%A6%C3%BA%C3%B2R%C3%9C%C3%94YcWed%C2%BC%28%C3%89%06%3F%C2%AB%2F%C2%97%C2%90%C2%89%7E%7B%C2%84%0C%22%5Cfd&debug=0).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 58 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“ßẓ⁸!ȧøḌçỊ¤¢Q=4QẠė⁷¤yż>S⁺ẓṬḄṂċK~⁼Ṛ7&⁼s<ụɦ³ḳMŻyVẉƑƭ6Ẋ⁵ỌQ⁸ẹ»
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCcw5_hupPigbghyKfDuOG4jMOn4buKwqTColE9NFHhuqDEl-KBt8KkecW8PlPigbrhupPhuazhuIThuYLEi0t-4oG84bmaNybigbxzPOG7pcmmwrPhuLNNxbt5VuG6icaRxq024bqK4oG14buMUeKBuOG6ucK7&input=)
[Answer]
# [Perl 6](http://perl6.org/), 47 bytes (44 characters)
```
put squish ~«map {.uniname~~/\w+$/},"α".."ω"
```
Prints `LAMDA` instead of `LAMBDA`, bus so do the other [Unicode database based](https://en.wikipedia.org/wiki/Lambda#Character_encodings) solutions.
[Try it online!](https://tio.run/nexus/perl6#@19QWqJQXFiaWZyhUHdodW5igUK1XmleZl5ibmpdnX5MubaKfq2O0rmNSnp6Suc7lf7/BwA "Perl 6 – TIO Nexus")
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 86 bytes
```
“¤±¢ªœÏ¤œ epsilon zeta etaìÛ iota kappaʯ mu nu xi omicron¾î rho¿Ã tau upsilonТ¶á‚ŵ
```
[Try it online!](http://05ab1e.tryitonline.net/#code=4oCcwqTCscKiwqrFk8OPwqTFkyBlcHNpbG9uIHpldGEgZXRhw6zDmyBpb3RhIGthcHBhw4rCryBtdSBudSB4aSBvbWljcm9uwr7DriByaG_Cv8ODIHRhdSB1cHNpbG9uw5DCosOCwrbDoeKAmsOFwrU&input=)
[Answer]
## Perl6 (71)
```
(913..937).grep(*!= 930)>>.chr>>.uniname>>.substr(21).join(" ").lc.say
```
] |
[Question]
[
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, [visit the help center](/help/reopen-questions) for guidance.
Closed 12 years ago.
Figure out how to mess up another programmer's project by making a subtle, hard to find (but "harmless") "bug". (Double quotes FTW!)
Try to keep them short; `shorter ~= subtle`.
---
For example:
```
#define true false
```
---
Don't actually *destroy* the code *directly*. For example, from this:
```
for(size_t i = 0; i < 10; ++i)
```
To:
```
for(size_t *i = new size_t; ++i; delete i)
```
Or even:
```
for(size_t i = 0; i <= 10; ++i)
```
Is *not* OK. If a language actually allows you to change `<` to `<=` without changing that code "directly", then it's alright. (You know what I mean. Deleting all the code is just
---
## Voting
Up vote the most original/creative/subtle solutions.
On Mother's Day (May 8, 2011), the most up voted answer will be chosen as the winner.
[Answer]
```
#define if(x) if(random(100) > 0 && (x))
```
[Answer]
## Haskell
```
module UnsafePrelude where
import Prelude hiding ((.), (+), (-), sum, map, foldl)
import qualified Prelude as P
import Unsafe.Coerce
-- disallow (f . g . h)
infix 9 .
(.) = (P..)
-- Make arithmetic a bit more exciting.
-- These actually work correctly for trivial Int and Integer cases,
-- at least in GHC 6.12.1 on x86.
(+), (-) :: (Num a) => a -> a -> a
(+) = unsafeCoerce ((P.+) :: Float -> Float -> Float)
(-) = unsafeCoerce ((P.-) :: Float -> Float -> Float)
sum :: (Num a, Num b) => [a] -> b
sum = unsafeCoerce (P.sum :: [Float] -> Float)
-- Make map a little less type-safe.
map :: (a -> b) -> [c] -> [b]
map = unsafeCoerce P.map
-- Make foldl associate the wrong way, but still have the same type.
foldl :: (a -> b -> a) -> a -> [b] -> a
foldl f = foldr (flip f)
```
[Answer]
## GolfScript
```
1:
```
Note there is a space after the colon. This assigns the value `1` to the space character. All further code that uses the space for readability will find unexpected extra ones on its stack!
Alternatively,
```
0:1
```
assigns the value `0` to the character `1`.
[Answer]
## Ruby
```
class Fixnum
alias add +
def + (n)
add n.add 1
end
end
```
And now, like in *1984*...
```
(33):0> 2 + 2 == 5
>>> true
(36):0>
```
] |
[Question]
[
Challenge: Implement incrementation without addition, multiplication, exponentiation, and any higher binary operators (and their opposites) in Python.
Winner is the person who can do it in the least amount of code. You score 5 characters less if you can do it for negative numbers and without unary operators.
[Answer]
### 3
```
-~i
```
Just good ol' unary `-` and bitwise-NOT.
**Demo**
```
>>> i = 3
>>> -~i
4
>>> i = 0
>>> -~i
1
>>> i = -3
>>> -~i
-2
```
[Answer]
### 14
I'm not a python guy, so here we go:
```
len(' '*i+' ')
```
According to the docs, I don't use addition, only string concatenation and repetition.
[Answer]
# 17 characters
Not shortest, but another way. This time no maths or binary operators involved *at all*.
But it only works on numbers greater than -1.
```
len(range(-1,x))
```
Proof:
```
>>> inc = lambda x: len(range(-1,x))
>>> inc(7)
8
>>> inc(100)
101
```
# 28 = 33-5 characters
Definitely out of contention but this does it for all positive and negative integers, again no math, no unary tricks.
```
len(range(-1,x)) or range(x,1)[1]
```
Proof:
```
>>> inc = lambda x:len(range(-1,x)) or range(x,1)[1]
>>> for i in range(-2,2): print i, inc(i)
...
-2 -1
-1 0
0 1
1 2
```
[Answer]
### 10 - 5 = 5
```
sum((i,1))
```
**Demo**
```
>>> i = -3
>>> sum((i,1))
-2
>>> i = 0
>>> sum((i,1))
1
>>> i = 3
>>> sum((i,1))
4
```
[Answer]
**27-5=22**
It's not really very short, but it doesn't use len(), range(), sum() and other stuff which definitely has a lot of increments and additions in it. Works with negative numbers, and no unary operations. Only pure, natural, raw, organic bitwise magic :)
```
j=i
k=1
while i<=j:i^=k;k<<=1
```
**Demo:**
```
>>> def inc(i):
... j=i
... k=1
... while i<=i:i^=k;k<<=1
... return i
...
>>> inc(1)
2
>>> inc(2)
3
>>> inc(20)
21
>>> inc(-24)
-23
>>>
```
(UPD: Sorry, I'm not sure whether newlines are counted as chars, if yes, it should be 29 not 27...)
] |
[Question]
[
### Background
A Medusa have released a dangerous Hydra which is revived unless the exact number of heads it have is removed. The knights can remove a certain number of heads with each type of attack, and each attack causes a specific amount of heads to regrow. **The knights have hired you to write a program or function that returns a [truthy/falsey](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) depending on whether the Hydra can be left with *exactly* zero heads *after* the next hit.**
Note that this is fundamentally different from [Become the Hydra Slayer](https://codegolf.stackexchange.com/questions/137980/become-the-hydra-slayer). You are not supposed to figure out which attacks to use.
*For example:*
```
input: head = 2,
attacks = [1, 25, 62, 67],
growths = [15, 15, 34, 25],
hits = [5, 1, 0, 0]
output: TRUE
```
*Explanation:* The Hydra has 10 heads to start with, we have 4 different `attacks` and for each attack, `growth` gives us the number of heads that grows back. `hits` gives us the number of times each attack is applied. So the number of heads the Hydra has after each attack is
```
2 -> 16 -> 30 -> 44 -> 58 -> 72 -> 62
```
Since `62` is a valid attack value (It lies in the attack list), we return `True` since the Hydra will die on the next attack (be left with 0 heads). Note that the order for when the attacks are done is irrelevant.
```
2 -> 16 -> 6 -> 20 -> 34 -> 48 -> 62
```
---
### Input
Any sort of logical way of feeding your program the attack, regrowth and hit values are acceptable. This includes, but is not limited to
* A list of tuples `(1, 15, 5), (25, 15, 1) (62, 34, 0) (67, 25, 0)`
* Lists `2, [1, 25, 62, 67], [15, 15, 34, 25], [5, 1, 0, 0]`
* Reading values from STDIN `1 15 1 15 1 15 1 15 1 15 25 15`
* A file of values
---
### Output
* Some form of [truthy/falsey](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value in your language: 0/1, true/false, etc.
---
### Assumption
* You may assume that any input is valid. E.g every input will not overkill the Hydra and either result in a number of heads that is an attack value, or not.
* Every list (if used) is to be assumed to be of equal lengths
* Every attack value will always correspond to one regrowth value which never changes. these are not required to be unique
* Every input will be a positive integer
---
### Test Cases
The following 10 examples are all `True`, and uses `attacks=[1, 25, 62, 67]`, `growths=[15, 15, 34, 25]` these are simply left out to be brief
```
1, [0, 0, 0, 0], -> True
2, [5, 1, 0, 0], -> True
3, [2, 3, 0, 0], -> True
4, [7, 4, 0, 0], -> True
5, [4, 6, 0, 0], -> True
6, [4, 0, 0, 0], -> True
7, [1, 2, 0, 0], -> True
8, [6, 3, 0, 0], -> True
9, [3, 5, 0, 0], -> True
10, [8, 6, 0, 0] -> True
25, [0, 0, 0, 0], -> True
67, [0, 0, 0, 0], -> True
62, [0, 0, 0, 0], -> True
98767893, [0, 1, 1, 2351614] -> True
```
The following examples are all `False`, and uses `attack=[1, 25, 62, 67]`, `growth=[15, 15, 34, 25]` these are simply left out to be brief
```
65, [0, 3, 0, 0], -> False
66, [4, 5, 0, 0], -> False
68, [0, 2, 0, 0], -> False
69, [0, 1, 1, 0], -> False
70, [2, 5, 0, 0], -> False
71, [0, 0, 0, 1], -> False
72, [0, 0, 0, 0], -> False
73, [1, 2, 1, 0], -> False
74, [2, 3, 0, 0], -> False
75, [1, 5, 0, 0], -> False
98767893, [1, 1, 1, 2351614] -> False
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with fewer bytes being better.
[Answer]
# [Haskell](https://www.haskell.org/), 44 bytes
```
w=zipWith
(u#z)y=elem=<<sum.(u:).w(*)z.w(-)y
```
[Try it online!](https://tio.run/##DcYxCoAgFADQvWvU4I9fpGVB5DkaxKFBSNKQSiIvby6Pt2/3oa1N6RXR@NU8e0FCGeET2monluUOriVhhvYlNcRsA19ymzmFv8z5VISVkiPFDjsFkuZy7AdkXEmaxZHhOKn0Aw "Haskell – Try It Online")
Pretty simple. We get the differences of the attacks and the regrows with `zipWith(-)`, then we multiply these by the attacks taken `zipWith(*)z`. Then we sum that with the starting head count, and check if that is in the attack list.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 5 bytes
```
-*∑+c
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=-*%E2%88%91%2Bc&inputs=%5B1%2C%2025%2C%2062%2C%2067%5D%0A%5B15%2C%2015%2C%2034%2C%2025%5D%0A%5B5%2C%201%2C%200%2C%200%5D%0A2&header=&footer=)
Inputs: attacks, growths, hits, heads
## Explanation
`-` subtract: growths - attacks
`*` multiply: that \* hits
`∑` sum
`+` add: that + heads
`c` contains: is it in attacks?
[Answer]
# [R](https://www.r-project.org/), 36 bytes
```
function(H,a,g,h)sum(H,g*h-a*h)%in%a
```
[Try it online!](https://tio.run/##hZLNisIwFEb3PkVQhEau0PynC7fDPIDL2YQybQWtoPb5a9IZm7mTSEsCJeck/Xpzb2NzGJuhrx@na198goMWOnofLv693XV7t@vo9tRv3ejIgdQFA8IVEM39NHTV/iz6lTCFDJSumqA5IC14WAL5HZRuyPE2fHvOIw97Ey4i96pIuIzcAJEJV5F7qBOuEU/zmcjDHyfcRq5z@arIPVQJZ2UUbC4gVwsV1GZJ4AtCZY02thJIY9PgQjHN5CzX7lGs96/nq1@HO9Y44p8ifLjzfYqAy6wyhkVn8IxRZfIhw5SoWTJfMbl2ZMh4W6zZEP9bIskh3zXtbCh0RiZpeicscyeTPT4B "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes
```
_ḋ⁵⁶+e
```
[Try it online!](https://tio.run/##y0rNyan8/z/@4Y7uR41bHzVu0079//9/tKGpjgIIG5voKBiZxgIFQLSOgpkREJsD@QZAeTAyMjY1NDM0if1vaWFuZm5haQwA "Jelly – Try It Online")
Takes four arguments: growths, attacks, hits, heads.
## Explanation
```
_ḋ⁵⁶+e Main dyadic link
_ Subtract: growths - attacks
ḋ Dot product with
⁵ third argument: hits
+ Add
⁶ fourth argument: heads
e Is it an element of the second argument: attacks?
```
[Answer]
# Python 3, 56 bytes
[Try it online!](https://tio.run/##hZPRboMgFIbvfQoudTtNBES0Sa@W7Al213nBMq0mrTVKk@rLOyi6aQfRoET88vsf@E/Ty/Ja07E4fI5ncfn6FqgEASeQ@/K1u1384cW/7/qguLboDj0MqKrRUDX@SVEyCNSbGGXeyTfR5R06oKOH1HVEGNQjhHmgDNBHe8vVPAFEAww0aAcoGIq6gEgDHPRsBxgYKnYB8QQ4TXIwpRAXkICRcZpMwZTCXAAOweg4XRK2tZcx3yTIFpEmPOZJSicOPwahDMeYWfRmT4vC38W5WyLz7jI3kkwqxI2kK0M2hIdTUtw/4us4Yhti2aFnhP7FweUl@p/aZ4RNKk67i6PA65OIZlahmefprixBQqu78rcL9w@Vpq1q6Rd@aVR0iHQIYp7pBd146qaR/qJWZABtMP4A "Python 3 – Try It Online")
```
lambda h,a,g,t:h+sum(z*(x-y)for x,y,z in zip(g,a,t))in a
```
[Answer]
# JavaScript (ES6), 54 bytes
Returns a Boolean value.
```
(a,g,n,h)=>a.includes(h.map((v,i)=>n+=v*=g[i]-a[i])|n)
```
[Try it online!](https://tio.run/##jZPPboQgEMbvPgVHbFmziIIeaLKnfQjigbiua2NxU1tPfXc7omn6TyABSYYfM1/mG5/1pMf6tbu/HcxwaearnLEmLTHkFssnnXSm7t8vzYhvyYu@YzyRDuLmUU4PslVdddDwiT9MPJ@QRIoSlOYE8RS2qKKzjUFg2SxbLqsoqgczDn2T9EOLr/hE0BkAgtSRoG1VcfwvBWlVbmEXxYBK7eGiQI0S9nBRUE0Bwt0UXymPeqhmG@SmCqC4V30JFLPyXBSFS1V45S@WBXSfizAsDcLKQnBRlGyFqV0pyymn2e8nO3U21Z5O8c0cT6t4sWbzuMPL73r3rT6uM@gpKn6MPd3Fwjoq2NeAObVlQf@HyNdsebCN9K@N8yc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 bytes
```
FreeQ[#,#3-#4.(#-#2)]&
```
[Try it online!](https://tio.run/##dZLfa4MwEMff/SskjtHCOepvpbRssBb2tq19y/LgxG6CVbEpFMS/3V0aGZWkkEDuPrn73l1yTPlvfkx5kaXDYTVs2zz/oBZYnm35TzPLttw5exxea2p0BdT9qiyqfGl0KXz3q329uTRtfjoVdfW8421R/eyasuBUnj/zpkyznBbQEUrsNekImISJU096BsIC02VL4x2vc3qgnYN2AGbo4o56MDsHLbE9XxD0oDBGmjMCNZA5YQZ0oiSQkpsLb9OM04dd1hYNf6uaM5cEyFeFyi9lKXTttSkN1rMBRekCzHGxK92359zAKqjQV4CHAKGnAKySRmD6CsA0FL2hAkIJVHFMQ8U4FBAjCHXiCQL0Bgpw0KaxTl0MW997GN0l7j2SxFEYxYknuXNdrhc4oePfxo@akwa2aXlCNE4j0KBYRrkalNwKTlC0kC@lSRhNnt2ZIF2HI/L@n0XR8jW/YkSBjNKUcTMzRzuz67U/ "Wolfram Language (Mathematica) – Try It Online")
Input `[attacks, growths, hits, head]`. Returns `True` if the hydra cannot be slain on the next hit.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
№η⁺θΣEε×ι⁻§ζκ§ηκ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5vxRIZugoBOSUFmsU6igEl@Zq@CYWaKTqKIRk5qYWa2TqKPhm5gElHUs881JSKzSqdBSyNXUUYNwMEBcKrP//jzbSUYg21FEwMtVRMAOyzcxjQQJAHggbm4BkQCIgAR0FAyCKjf2vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs one `-` for each matching attack, so if there are two attacks that deal the same amount of damage then `--` will be output. Explanation:
```
ε Array of hits
E Map over elements
§ζκ Relevant growth
⁻ Subtract
§ηκ Relevant attack
× Multiplied by
ι Current element
Σ Take the sum
⁺θ Add the starting number of heads
№η Output the number of matching attacks
```
[Answer]
# [J](http://jsoftware.com/), 15 bytes
Just to remind myself that `/` supports cycling gerunds. Takes health on the left, (hits, regrow, attack) on the right.
```
(+1#.*`-/)e.2{]
```
[Try it online!](https://tio.run/##jdM7jsIwEAbgfk8xWorwSELG70SiQqLaanskJARCNByAw4cfB0EoYCaJXSSfnRmPfe5/6@JIq44KKqmhDq2qaf3/t@mnC57U8121nB1qc932s5/D/nQhpiNQvkv2hMc6Mr7sGD0FQyEO0ADiuwwtoEEvQgcY0YvQAzoKMgwZKpKJgHgnwwQYNMm0gBaRipAbyKTJxnhtbUJUS6OVbYohptZmz/fVsp4Du@@jigpX8fjXEP@wePQ9rKFyXkNTntVoaPsMXqKxybtWE0B8HRmW6Hi1BWofW1IRqxudMIH6PKsmrVG9@a3en4b1Nw "J – Try It Online")
* `*`-/` Does hits \* regrow - attack
* `1#.` summed
* `+` plus health
* `e.2{]` exists in the attacks?
] |
[Question]
[
**This question already has answers here**:
[Cryptographic quine variant](/questions/8947/cryptographic-quine-variant)
(4 answers)
Closed 4 years ago.
Your challenge is to output a [Base64](https://en.wikipedia.org/wiki/Base64)-encoded version of your source code, and optionally a line break. You must output the correct [padding](https://en.wikipedia.org/wiki/Base64#Output_padding), if any. [Standard quine rules](https://codegolf.meta.stackexchange.com/q/4877/58826) apply, shortest answer wins.
It must be a valid [RFC 4648](https://www.rfc-editor.org/rfc/rfc4648) encoded base64 string, with no linebreaks (except optionally a trailing newline).
# Test cases:
```
h -> aA==
PPCG! -> UFBDRyE=
Programming Puzzles and Code Golf -> UHJvZ3JhbW1pbmcgUHV6emxlcyBhbmQgQ29kZSBHb2xm
```
#Base64 table
```
0 A 16 Q 32 g 48 w
1 B 17 R 33 h 49 x
2 C 18 S 34 i 50 y
3 D 19 T 35 j 51 z
4 E 20 U 36 k 52 0
5 F 21 V 37 l 53 1
6 G 22 W 38 m 54 2
7 H 23 X 39 n 55 3
8 I 24 Y 40 o 56 4
9 J 25 Z 41 p 57 5
10 K 26 a 42 q 58 6
11 L 27 b 43 r 59 7
12 M 28 c 44 s 60 8
13 N 29 d 45 t 61 9
14 O 30 e 46 u 62 +
15 P 31 f 47 v 63 /
```
If you want to test your submission, try [base64encode.org](https://www.base64encode.org/).
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 27 bytes
```
trap -- 'trap|base64' EXIT
```
Based on this [Bash quine](https://codegolf.stackexchange.com/a/96563/12012). Note the trailing linefeed.
[Try it online!](https://tio.run/##S0oszvj/v6QosUBBV1dBHcSoSUosTjUzUVdwjfAM4fr/HwA "Bash – Try It Online")
[Answer]
# Javascript (ES6), 17 bytes
```
f=_=>btoa(`f=`+f)
```
I thought this solution would be obvious...
```
f=_=>btoa(`f=`+f)
console.log(f())
console.log(atob(f()))
```
[Answer]
# Python, ~~133~~ 112 bytes
```
from base64 import*;s=b'from base64 import*;s=%r;print(b64encode(s%%s).decode())';print(b64encode(s%s).decode())
```
Base64 representation:
```
ZnJvbSBiYXNlNjQgaW1wb3J0KjtzPWInZnJvbSBiYXNlNjQgaW1wb3J0KjtzPSVyO3ByaW50KGI2NGVuY29kZShzJSVzKS5kZWNvZGUoKSknO3ByaW50KGI2NGVuY29kZShzJXMpLmRlY29kZSgpKQ==
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1chKbE41cxEITO3IL@oRMu62DZJHbu4apF1QVFmXolGkplJal5yfkqqRrGqarGmXkoqmKOpqY5FAbL8//8A)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 342 bytes
```
f(a){putchar(a>61?43+a%2*4:a>51?a-4:a+65+a/26*6);}main(a){char*s="f(a){putchar(a>61?43+a%2*4:a>51?a-4:a+65+a/26*6);}main(a){char*s=%c%s%c,*t=malloc(342);for(sprintf(t,s,34,s,34);*t;f(*t%4*16+*++t/16),f(*t%16*4+*++t/64),f(*t++%64))f(*t/4);}",*t=malloc(342);for(sprintf(t,s,34,s,34);*t;f(*t%4*16+*++t/16),f(*t%16*4+*++t/64),f(*t++%64))f(*t/4);}
```
[Try it online!](https://tio.run/##vY1bCoMwEEX3IgSSGUWicT4a1LUMgbSCL0z6VVx76mMJhf4MhwPnjiuezqXkJavP@o7uxZvkjnRvamRRgXlw1@ieiwOQGuSyIiBl94mH@YzOAkKb/bwgnAjC5RDbicdxcbI2lbJ@2WRYt2GOXsY85LW5jrIQrZcQhQFNCIix1KTyS2kCcysyt0IUB6oTy6Pds/@8SekL "C (gcc) – Try It Online")
[Answer]
# [Alice](https://github.com/m-ender/alice), ~~72~~ 69 bytes
*-3 bytes thanks to Martin Ender.*
```
".w6+55*&w.q+!]k;9&wq4-!]kq&[d.t&w;q,ww].4%~4:k;28d3:&wq&[&]?ow4*+k@;
```
Base 64 representation:
```
Ii53Nis1NSomdy5xKyFdazs5JndxNC0hXWtxJltkLnQmdztxLHd3XS40JX40Oms7MjhkMzomd3EmWyZdP293NCora0A7
```
If anything, the base 64 representation looks less inscrutable than the original program.
[Try it online!](https://tio.run/##S8zJTE79/19Jr9xM29RUS61cr1BbMTbb2lKtvNBEF8gqVItO0StRK7cu1Ckvj9UzUa0zscq2NrJIMbYCKlGLVou1zy830dLOdrD@/x8A "Alice – Try It Online")
### Explanation
Since Alice has no base64 built-in, the vast majority of this program is a reduced implementation of base64. The quine framework prevents me from using `'` to define constants in two bytes, but it also has some advantages. As luck would have it, the length of the source code is divisible by 3, and the characters `>`, `?`, and `~` do not appear at the end of a 3-character block.
The first step is to create (most of) the base64 alphabet. The characters `+` and `/` do not appear in the base64 representation of the source code, so we do not need to handle them. This saves 9 bytes.
```
" wrap the entire source code in a string and push each byte
. copy ; from top of stack (i.e., push 59)
w push return address (i.e., do the following twice)
6+ add 6 to the constant on the stack
this gives us 65 in the first iteration, and 71 in the second
55*w do the following 26 times:
.q+ add tape position to constant
! store at tape position
] move tape right
k return to pushed return address (end both loops)
; remove constant from the stack, since it's no longer needed
9&w do 10 times:
q4- tape position minus 4
! store at tape position
] move tape right
k repeat
q&[ return to position 0
```
Positions 0-61 on the tape are now filled with their base64 character equivalents. We now convert the source code to base 4.
```
d. push stack depth (length of code excluding "), and put a useless copy below it
t&w do that many times:
; remove top of stack (copy of length on first iteration, 0 otherwise)
q, move next byte to top of stack (using tape position as a register)
ww do 4 times:
] move tape forward (increase counter)
. duplicate current byte or part thereof
4% mod 4
~ swap: work with other copy
4: divide by 4
k repeat (end both loops)
;28 remove the excess 0 and push the base 4 representation of ",
except that the first three base 4 digits are already in base 64
```
Finally, we convert from base 4 to base64 and output.
```
d3:&w push return address once for each output character
q&[ move tape to position 0
&] move tape to position corresponding to base 64 digit
? get character from tape
o output
w4*+ convert next base 64 digit (equivalent to 4*+4*+)
k repeat until stack is empty
@ terminate
```
[Answer]
# Mathematica, 108 bytes
```
Print[StringDelete[ExportString[StringJoin["Print[", ToString[#0, InputForm], "[]]"], "Base64"], "\n"] & []]
```
Full program. The spaces are necessary as part of the `InputForm` formatting. Output, note the trailing linefeed character:
```
UHJpbnRbU3RyaW5nRGVsZXRlW0V4cG9ydFN0cmluZ1tTdHJpbmdKb2luWyJQcmludFsiLCBUb1N0cmluZ1sjMCwgSW5wdXRGb3JtXSwgIltdXSJdLCAiQmFzZTY0Il0sICJcbiJdICYgW11d
```
[Answer]
# Java 8, 202 bytes
```
v->{String s="v->{String s=%c%s%1$c;return java.util.Base64.getEncoder().encodeToString(s.format(s,34,s).getBytes());}";return java.util.Base64.getEncoder().encodeToString(s.format(s,34,s).getBytes());}
```
**Explanation:**
[Try it online.](https://tio.run/##tVBNa8MwDL3vV4jSgA2tYbTsEtpDocf2srHL6MFz1OLUsYMlB0rJb8@cJZf9gIEEevp44r1ad3odWvR1dR@M00Rw0tY/XwCsZ4xXbRDOIwR452j9DYz4DLaCTpa52@fMQazZGjiDhx0M3Xr/nJdpt/iDClNQ8bo0ZURO0UOd/6vE1qmDJnzbqhvy0ZtQYRRS4W/1EaZzQeoaYqNZ0GqzXZEclw8PRhJSlv3iHziHctLXpm@X9c0yu1F/k20SE8nXRcvZogcxNiokVm2esPDKCJ@ck7Nb/fAD)
* The `String s` contains the unformatted source code.
* `%s` is used to input this String into itself with the `s.format(...)`.
* `%c`, `%1$c` and the `34` are used to format the double-quotes.
* `s.format(s,34,s)` puts it all together.
And then `java.util.Base64.getEncoder().encodeToString(....getBytes())` is used to encode the entire source code to a Base64-String.
[Try it here with the Base64-encoding part removed to prove it's a quine.](https://tio.run/##dY6xCoMwEIb3PsUhFSJooLSb2DeoS6FL6ZDGWGJjlNwpFPHZ04guHQp3w3//wfc1YhRZ1yvbVG8vjUCEi9B22gFoS8rVQioolwhwJaftCyS7dbqCMcnDdQ4bBkmQllCChQL8mJ2n7RmL6CfFMsb4sJe5UzQ4C8jrzrWCGKbHU4pJPkf/K5@vtH54mkDboONi0wZptlLuD5Fswh8k1fJuIN6HhpjlktnBmGRzn/0X)
] |
[Question]
[
## Very interesting background
Comcoins are a currency like any other. The residents of Multibaseania (an economically robust system of city-states with very few residents in a galaxy far, far away) use Comcoins to conduct transactions between themselves. Comcoins are represented by unique codes on special not-paper slips, and when you pay you give the vendor your slip.
However, just like any currency, there are those villainous types that try to take advantage of the system and inflate the currency because they are bored.
To combat this unquestionably illegal behavior, the Multibaseanian governments came together and devised a way to prove that the money is legitimate. The top idea from the think tank was: whenever a Comcoin is given to a vendor, the vendor runs a program that checks if it is legitimate. How does one know if a Comcoin is legitimate?
>
> **A legitimate Comcoin is one where:**
>
>
> When the Comcoin's unique code is converted into the bases 2-10, inclusive, that number is composite (i.e. not prime). Also, all of the unique code's digits in base 10 are either 1 or 0, and its length in base 10 is between 1 and 5 inclusive.
>
>
>
**Very important example:** in base 5, 111 is 421. Even though 111 is not prime, 421 is, so the Comcoin is invalid.
## The challenge
Write a function or program that takes a Comcoin's code (a number), which is in base 10 and is an integer. Then, print or return a truthy or falsy value depending on whether that Comcoin is legitimate (criteria above), respectively.
## I/O examples
```
Input Output
101 False // because it is prime in base 2
1010 True
10101 True
1010111 False // because it is longer than 5 digits
123 False // because it does not contain *only* 0's and 1's
10111 False // because it is prime in base 6
```
This is code golf, so shortest code in bytes wins!
## Edit
A Comcoin is not a number that is not prime, but is a number that is composite.
[Inspiration from qualification round of Google CodeJam 2016.](https://code.google.com/codejam/contest/6254486/dashboard#s=p2)
[Answer]
# Python 2, 62 56 49 bytes
```
lambda n:max(`n`)<"2"and 0x5d75d750>>int(`n`,2)&1
```
Credit to @Sp3000 for the `max` trick to ensure binary digits.
[Answer]
## JavaScript (ES6), ~~38~~ 27 bytes
```
n=>2641714512>>'0b'+n&n<1e5
```
Port of @orlp's Python answer, except that JavaScript's precedence and weak typing allows me to shift the integer even if it's not valid in base 2, and then bitwise and it with the boolean. Returns 0 or 1 as appropriate. Note that I'm not using @orlp's constant any more, instead I'm assuming the following list of comcoins is valid:
>
> 100
>
> 110
>
> 1000
>
> 1010
>
> 1011
>
> 1100
>
> 1110
>
> 10000
>
> 10010
>
> 10100
>
> 10101
>
> 10110
>
> 11000
>
> 11010
>
> 11011
>
> 11100
>
> 11111
>
>
>
Edit: Fixed to check the length of the comcoin, since JavaScript's shift operator works modulo 32.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 20 bytes
```
n6<G50<9:Q"G@ZAZp~vA
```
Input is a string.
[**Try it online!**](http://matl.tryitonline.net/#code=bjY8RzUwPDk6USJHQFpBWnB-dkE&input=JzEwMTAxJw)
### Explanation
```
n6< % take input implicitly. Is length less than 6?
G50< % push input again. Array that contains true for digits less than 2
9:Q % push array of bases: [2,3,...,10]
" % for each
G % push input again
@ % push current base
ZA % interpret input as if it were in that base, and convert to decimal
Zp~ % true for composite numbers
v % concatenate vertically all results up to now
A % true if all results were
% end for each implicitly
% display implicitly
```
[Answer]
# Julia, ~~83~~ 81 bytes
```
f(x,s="$x")=endof(s)<6&&all(c->c∈"01",s)&&!any(b->isprime(parse(Int,s,b)),2:10)
```
This is a function that accepts an integer and returns a boolean. It's a straightforward check on the conditions of being a Comcoin:
* Length as a string between 1 and 5 inclusive: `endof(s)<6`
* All zeros and ones: `all(c->c∈"01",s)`
* No primes in any base from 2 to 10: `!any(b->isprime(parse(Int,s,b)),2:10)`
Saved 2 bytes thanks to Luis Mendo!
[Answer]
# JavaScript (ES6), 37
~~This should work better than the current ES6 answer~~ Now the other ES6 answer is clearly better
**Edit** 0 and 1 not valid, the magic number changes
```
n=>180006585..toString(2)['0b'+n-4]|0
```
**Test** (see below to see how the magic number is built)
```
F=n=>180006585..toString(2)['0b'+n-4]|0
console.log=(...x)=>O.textContent+=x+'\n'
function test() {
var x=+I.value
console.log(x+' '+F(x))
}
test()
// How the mask is built
isPrime=x=>{
if(x<=2)return x==2
if(x%2==0)return false
var i,q=Math.sqrt(x)
for(i=3;i<=q;i+=2)
if(x%i==0)return false
return true;
}
buildMask=_=>{
var n,m,i,p,mask=''
for(i=1;i<32;i++)
{
n=+i.toString(2)
for(p=0,b=10;b>1;--b)
{
m=+n.toString(b)
p=m<2 || isPrime(m)
if(p)
{
console.log('N',i,n,m,b)
break;
}
}
mask+=p?0:1
if(!p) console.log('Y',i,n)
}
console.log(mask, parseInt(mask,2))
// result
// 0001010101110101010111010111001,180006585}
}
```
```
<input value='11111' type='number' id=I oninput='test()'><pre id=O></pre>
```
[Answer]
# Mathematica, 97 bytes
```
#<1*^5&&Tr@DigitCount[#][[2;;-2]]<1&&FromDigits@IntegerDigits[#,a+1]~Table~{a,9}~NoneTrue~PrimeQ&
```
Hey, at least I tried...
```
#<1*^5&&Tr@DigitCount[#][[2;;-2]]<1&&FromDigits@IntegerDigits[#,a+1]~Table~{a,9}~NoneTrue~PrimeQ&
#<1*^5&& less than 100000?
Tr@DigitCount[#][[2;;-2]]<1&& no digits 2-9?
FromDigits@IntegerDigits[#,a+1]~Table~{a,9}~NoneTrue~PrimeQ& composite in all bases?
```
[Answer]
# Ruby, ~~81~~ ~~80~~ 74 bytes
Anonymous function, takes input as a string and returns `true` or a falsy value (`false` if it fails a prime check, `nil` if it contains characters that aren't `0` or `1`)
Uses some regex magic suggested by @QPaysTaxes, which thankfully works (within reasonable time) because of the promise that the coin signature has max 5 characters. Also, I forgot to actually check for the length, so only 1 byte was saved overall.
Since `0` and `1` aren't composite numbers in any base, I could save more bytes by modifying my regex.
```
->n{n=~/^[01]{2,5}$/&&(2..10).map{|b|?1*n.to_i(b)=~/^(..+?)\1+$/}&[p]==[]}
```
Old version using Ruby's built-in prime checker. **85 bytes** after properly checking for length.
```
->n{require'prime';n=~/^[01]{1,5}$/&&(2..10).map{|b|Prime.prime? n.to_i(b)}&[!p]==[]}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ΘIg5›ITLBpàI1K`O_
```
-1 byte and bug-fix thanks to *@Grimmy*.
Outputs `1`/`0` for truthy/falsey respectively.
[Try it online](https://tio.run/##yy9OTMpM/f//3AzPdNNHDbs8Q3ycCg4v8DT0TvCP///f0MDAAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/czMq000fNeyqDPFxKji8oNLQO8E//r/O/2hDQ0MdQwMwNgATECZY2MhYB8qKBQA) or [verify the first 40 binary numbers and 100 regular numbers](https://tio.run/##ATUAyv9vc2FiaWX/NDBMYtGCTMKrdnlEPyIg4oaSICI//86YeWc14oC6eVRMQnDDoHkxS2BPX/8s/w).
**(Now longer) 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative:**
```
46bICèIт@Ig6‹PITм+
```
Outputs `1` for truthy and a non-1 integer for falsey (note: only `1` is truthy in 05AB1E, so [this is allowed according to the meta](https://codegolf.meta.stackexchange.com/a/2194/52210)).
[Try it online](https://tio.run/##yy9OTMpM/f/fxCzJ0/nwCs@LTQ6e6WaPGnYGeIZc2KP9/7@hgYEBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/X8Ts6RK58MrKi82OVSmmz1q2BlQGXJhj/Z/nf/RhoaGOoYGYGwAJiBMsLCRsQ6UFQsA) or [verify the first 40 binary numbers and 100 regular numbers](https://tio.run/##ATYAyf9vc2FiaWX/NDBMYtGCTMKrdnk/IiDihpIgIj//NDZieUPDqHnRgkB5ZzbigLlQeVTQvCv/LP8).
Both programs also works for edge-case `1`, unlike some other answers.
**Explanation:**
```
Θ # Check if the (implicit) input is exactly 1 (1 if 1; 0 otherwise)
Ig # Push the input again, and pop and push its length
5› # Check if this length is larger than 5 (1 if length>5; 0 if length<=5)
I # Push the input again
TL # Push a list in the range [1,10]
B # Convert the input to each of those bases
p # Check for each whether it is a prime (1 if prime; 0 if not)
à # Pop and push the maximum to check if any are a prime
I # Push the input yet again
1K # Remove all 1s
` # And push all remaining digits separated to the stack
O # Sum all values on the stack
_ # And check whether it is exactly 0 (1/truthy if 0; 0/falsey if >0)
# (after which this result is output implicitly)
46b # Push 46 as binary: 101110
IC # Push the input, and convert it from binary to an integer
# (NOTE: unfortunately also works for non-binary inputs, so we'll fix those later)
è # Use that to index into the 101110 (0-based and with wraparound)
Iт@ # Push the input again, and check that it's >= 10
Ig6‹ # Push the input again, and check that its length is < 6
P # Take the product of all values on the stack
I # Push the input again
Tм # Remove all 1s and 0s
+ # And add any remaining digits to the product
# (after which the result is output implicitly)
```
[Answer]
# Python, ~~161~~ 152 bytes
*Sigh*. Assign the lambda to use it.
```
def p(n):
i=a=n
while i>2:i-=1;a*=n%i
return a>1
lambda s:all([all(map(lambda i:not p(int(s,i)),range(2,11))),filter(lambda i:i in"01",s)),len(s)<6])
```
[Answer]
# Factor, 128 bytes
```
[ dup [| a | 2 10 [a,b] [ a swap base> prime? not ] all? ] swap [ [ [ 49 = ] [ 48 = ] bi or ] all? ] [ length 6 < ] bi and and ]
```
I'll try to golf this more in a sec.
Well, here's the *less* golfed version I thought might be shorter, but it's 133 bytes...
```
[ [ [let :> a 2 10 [a,b] [ a swap base> prime? not ] all? ] ] [ [ [ [ 49 = ] [ 48 = ] bi or ] all? ] [ length 6 < ] bi ] bi and and ]
```
Actually ungolfed:
```
: comcoin? ( a -- t/f )
[
[let :> a
2 10 [a,b] [ a swap base> prime? not ] all?
]
] [
[ [ [ 49 = ] [ 48 = ] bi or ] all? ]
[ length 6 < ] bi
] bi
and and ;
```
[Answer]
# Python 3, 222 bytes
I wanted to try to do the naive method purely functionally, without looping. Here it is.
```
(lambda A:all([F(A)for F in[lambda r:all(map(lambda s:not(lambda i,b:lambda n:list(filter(lambda i:not n%i,range(2,n)))(int(i,b))(r,s),range(2,11))),lambda r:0!= len(filter(lambda d:d not in"01",r)),lambda r:0<len(r)<6]]))
```
Ungolfed:
```
(lambda A:
all(
[F(A) for F in [
lambda r: all(
map(
lambda s:
not(
lambda i, b:
lambda n:
list(filter(
lambda i: not n % i, range(2, n)))
)(int(i, b))(r, s),
range(2, 11))),
lambda r: 0 != len(filter(lambda d: d not in "01", r)),
lambda r: 0 < len(r) < 6
]
]
)
)
```
] |
[Question]
[
This is alternate of a [rip-off](https://codegolf.stackexchange.com/questions/221209/i-palindrome-the-source-code-you-palindrome-the-input) of 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/q/193315/) 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. But again, The tricky part is that if I `rot-13` your source code, the output must be returned `rot-19`.
Your code will be only rotated *once*.
## Examples
Let's say your source code is `ABC` and the input is `xyz`.
Code `ABC` should return `xyz`.
Code `NOP`(*rotated*) should return `-./` (**Rot-19**).
## Details
* If your language has a custom codepage, apply rot13 to the bytes in the printable ASCII range in your code, and do not modify the rest. The input and output will be in pure printable ASCII.
* The input only contains ASCII character.
* use printable ASCII table for rotating
* rot-13 means to forward 13 positions in ASCII table
* Same applied to rot-19, which forward 19 positions instead.
## Rules
* Input can be taken in any convenient format.
* Output can be in any convenient format as well.
* Standard Loopholes are forbidden.
## scoring
This is code-golf so the answer with the fewest amount of bytes wins.
## Extra scoring rule
If there's somehow, a *non-esolang* appeared as a valid answer, it may considered as a better answer.
Example: `python`, `C++`, `java script` etc.
## If you are confused with Rot
Here is a [encoder](https://www.dcode.fr/rot-cipher) to get some idea with.
~~Use full ACSII Table for this question’s requirement.~~
**Use printable ASCII Table (33 ~126) for rotation!**
* `Space` are 32 in ASCII, which count as unprintable!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 50 bytes
```
a=>01+"$25hYYXeya=>z!`TcyV01yV~$'zv,'|&&z|xx-$"&&a
```
[Try it online!](https://tio.run/##jY/taoMwFIb/exVZcflADVoZg246Ri@gYytlZRssZK61WCMxikrprbv40UL7a4TAOcn7Pue8O1aynMs4U04qfqKWizRXIBdJoWKRgqBlQeh61sSc3m3X6/eo1n1z873k9cr16tXRRE1powOEzaGqHHMCITszCskjEJxhVIk3JeN0g8mDMWikUJ7fSUAQgg9Kaf5F9yzDfMukfjIA6KswAEgfCIf2UbdHBJ7AgKO/Uuzn@mOuA@DeS7kuX0ScqmeFXeL4vuX55BZ703tdE0tfMOthBqE7rcMIjUuJJKKJ2GDU0WbIHnPYAH2miFxKFoXKCtWJopIleFASjKq6QWR0XFFfF0ud@MTu8598/xlxYbie1P4B "JavaScript (Node.js) – Try It Online")
Both versions are a function which takes a string as input and returns a string.
ROT13 code:
```
nJK=>8/1?Buffer(nJK).map(c=>(c-14)%94+33)+'':1/33n
```
## Explanation
Hides tricky characters used in the ROT19 logic inside a string. The quotes map to `/` characters so it's just a matter of finding where to put them to make it work.
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 8 bytes
```
#.n$,
p
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X1kvT0VHrkDi//@M1JycfAA "GolfScript – Try It Online")
[Try it online!(rot13)](https://tio.run/##S8/PSStOLsosKPn/38C62tBSu1b1/39lvTwVHbkCCQA "GolfScript – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 9 bytes
*-2 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs).*
```
žD¦7$,!R‡
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6D6XQ8vMVXQUgx41LPz/v6KyCgA "05AB1E – Try It Online")
```
žD¦7$,!R‡ # full program
, # output...
$ # input
```
# =BNO>R, ~~11~~ 9 bytes
```
žQ¦D19._‡
```
[a!( v# |{yv{r.](https://tio.run/##yy9OTMpM/f//6L7AQ8tcDC314h81LPz/v6KyCgA "05AB1E – Try It Online")
```
žQ¦D19._‡ # full program
‡ # push...
# implicit input...
‡ # with each...
žQ # ASCII character...
¦ # excluding the first...
‡ # replaced by corresponding character in...
žQ D # ASCII characters...
¦ # excluding the first...
._ # rotated...
19 # literal...
._ # characters to the left
# implicit output
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 75 bytes
Comment still do the trick quiet well :).
```
t=print(input())
#.ce\agyxx!]b\ayNV[eyybeWy\z~$'zv,'|&&zYbe \ \a \achgyzPzz
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v8S2oCgzr0QjM6@gtERDU5NLWS85NSYxvbKiQjE2KSax0i8sOrWyMik1vDKmqk5FvapMR71GTa0qMilVIUYhJhGIkjPSK6sCqqr@/08EAA "Python 3.8 (pre-release) – Try It Online")
```
#J}!v{#5v{}$#566
0;print(''.join([chr((ord(i)-14)%94+33)for i in input()]))
```
[a!( v# |{yv{r.](https://tio.run/##K6gsycjPM7YoKPr/X9mrVrGsWtm0rLpWRdnUzIzLwLqgKDOvRENdXS8rPzNPIzo5o0hDI78oRSNTU9fQRFPV0kTb2FgzLb9IIVMhMw@ICkpLNDRjNTX//08EAA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 96 bytes
```
⭆S§Φγμ⁺Σ+&+⌕Φγμι
```
[Try it online!](https://tio.run/##S85ILErOT8z5///R2rb3ezYfWn5u2bnN5/Y8atx1brG2mvajnqkQgXM7//@vqKwCAA "Charcoal – Try It Online") After ROT13, this becomes:
```
⭆S§Φγμ⁺Σ838⌕Φγμι
```
[Try it online!](https://tio.run/##S85ILErOT8z5///R2rb3ezYfWn5u2bnN5/Y8atx1brGFscWjnqkQgXM7//@vqKwCAA "Charcoal – Try It Online") Explanation:
```
S Input string
⭆ Map over characters and join
838 Literal string `+&+` or `838`
Σ Digital sum i.e. 0 or 19
⁺ Plus
⌕ Index of
ι Current character in
γ ASCII characters
Φ Filtered where
μ Current index is non-zero
§ Index into
γ ASCII characters
Φ Filtered where
μ Current index is non-zero
Implicitly print
```
[Answer]
# [Pxem](https://esolangs.org/wiki/Pxem), Filename: 60 bytes + Content: 0 bytes = 60 bytes.
* Filename (escaped): `.w.o.i.c\001.+.a.d!md!T!j!b!\\!V !k!V\177!lG!|Q!vr!|KK!TKK!T!V\001!|!T`
+ Actual: `.w.o.i.c.+.a.d!md!T!j!b!\!V !k!V!lG!|Q!vr!|KK!TKK!T!V!|!T`
* Content: empty.
## With comments
See also: [Simple cat program](https://codegolf.stackexchange.com/a/221388/100411)
```
XX.z
# pasted cat program
.a.w.o.i.c\001.+.aXX.z
# exit
.a.dXX.z
# these literals are ignored
.a!md!T!j!b!\\!V !k!V\177!lG!|Q!vr!|KK!TKK!T!V\001!|!T
```
[Try it online!](https://tio.run/##nRjtVuJK8v88RaeHj24ghACOStN6FXUuM4qOOl4VGDcmQaIhARIUB5hzdl91H2S2upMgOnPO7t0fku6q6vruqmotI@j/fI8qvQ8V3bo1dN3WDatX2TQ31vSeXjF1s2ev9@zKxqZRrmz23r1Hw6k9cIrl4sDxikM/cKZOMHgX2CFS7QmbDIzgAZVK5TKzp0N/HKLDxs3O4SFvMBI@D210Z4em7/UyGbkz/cHA8Cy6pVn2o@ZNXBeVtzJ6JhMfPtk5/5PjFInpkDpMGEgUTc3EJ19bRAt1gROxX1vNy5uz8z1eLpUqCfDk@Kx5eXh10zg@Pd1vnHOdtZHqIZya7e6c/XlzsX961jxu1YAN6mYyMySt8pG0kolNfpctlmeuf3fEHkxcI7RR0BcH/GEIqyd/bAVD1wmZ4TpGgNQ7lE3N9DxO/YEXWZ4V3yxrfT08bBzt8ZoUAUYLgRYL@k4vlMItJAhjgG32fZR6TzHiSBeiiYQEfRt8GPo@8l1rKyOi4IRIp8x@NFyEFdQz3MDG8/lvyNEqvdRA0kzngW2hbKBNtWeNBfDzXctKud9Rdz4HkyUnoPlFLFgCHnAf@eYmgxAOHdcmlPR4iZlGYIMEHSPHQ6SXo6gH0WB2YJjMCAJ7cOs@i8D7EPMdD6mP4USfh2OkNgJU0suV6tqH9Y1NlG13vFw3O78b20NUnBtPDyi7u/@x2Zq5IMTi1Q8MvEuGY8cLeyg7PPGPvZbTvDEbwdnjRe/A3h@fPv01vXy@@n5t7ITngyNrL68qqXQ6O/8/RKdKHDfaGKVKCHd5B2Nwies/2WMSRCoQnDZxIVWiFOEOZpiBI7MyNQjGhbMCrmHKhOo9HnCMWc8fEwYZ7zqejXpbJUZnTo8kgKDOS1TSATAQnmxkMj3OLTrbJ5RJkajRDrpsYUPUkaCS2Ke@iES0PiQ9KsSxt4wjjGAkg1lii8VSzK8CpIToyCEJKAAExaI38czQ8T10SEypu6mAvjQIDfOh7ebzXW6uEMERQePSWeQu7MYucMF0V1VpDEYYxRxUvRupAU5YLLIyDOoj8iF3ZObhJB8ik2MDt8A6L8@19tP0@XtXUzVDE@Z79VIsGRcNtFtFxYgAz7FpQDpDYuNlZks6CDSJuBhdbRujP0AzLw/samCkYOlLgzRLy2QUj8aOjCB0NuGeqrNIM29rshpbGYBYlUgJ9KT5qGj8Vpe3tkTKYSPWByhk7Ly/wTKJOSQoi69POuh0ROFL7ieekzaK3IxUN0RlUYaA0zyJgsFL4gMZmoKYwaoPgGyQA5cNfc8MHsdhV8sRo67TvNbOw7VTo32ZQnzsacgW2lCbARsWQHVYBHWdwV@M6sOqD4aHWk5RDLaYBVzR2j07jgYzhFOcm66W11zg2jpQQQwxIPaggAmOavteAAoAsC@A2kBTAa3DKtGFLXS4oW/MrLwyMzs7aTv5UpenSmzIxTovcnIxVH5A9iZWuJogU8tdPkQHZyiY3AbhmKRKhQplJ21Vdbr8EoTVSYtH1WBYMAoHZ5RmMqDqDOgJTmGAIKPd6hYiXpRZtmtDr4k4sEWrXgH6QMiKWS4XsR5BzAu1v6FuHjheLnm9qNHaKkM7EU4AF0Cn0NqpdBcSWIjOwQ/YB/GZcrFnzzyCiKSe1p/pNM@fVfLMp1AeeHJ/73mZ3deBjNFh5AGjfQ@Xn606BXKMaJ28tj3NP9cgPNtTFb4KfHPwTcM3/VyDHvSL2futvVkkpQRSHBZVCUBLEZDBSQOD61DMpTRtWbQlXPvmInCLponmJvyS005IhjLtDvZIg88t9DGZss4NJG3PHoeDLrhSy0CF01jIkrsHoOgyA4LOJMYQwIVcWmIpupForb1l35bdMyuuGynR7Hwe7S1gPbbDydgTHSKSkhcMDMtKpKpiH9yGyV4Rexg/kn0nJQCW85gA0pLATxgEWjGn/XV@QHAGihV45Y1my7YZVdCz9gOHPIe7mPSrftSvstDNw6RIZIW/58ujy9Juk106e8jnGbDpcvgROSOitgscd@sCynbzeQqLwm5MAIs3zIXqIIDKfmwhqEeUwS0MzLEzDHmsqOhStm39wEVoNGMYG@V2tRmdkD0q7Cl8JrTL96ROoNrrRhS5X/n8qo19WiIQILb0FdTnF5S05gVz/gojhMoSscRfklM6O@VAJjVR1Tj06HSFaEIacfkmql6HRt@ol9c@0O1GTbS@JdlHwQs8MPF@aEVNsJ14bOKJIeGFabxadsPtVKmmrtryVQiDU40V2A45SvrHTg0Xjla7RgRWXtrH8tSQJOOGAk6lE3IJvyt4P2r5v0d6pFkYFfYK7gvNbMSBCGYk1/buwj4ZUZlFTegPzTp3WRNyaELIHo9r7KjQLOiU/sDtkrrZxdt7@epGrbomBpSlGAd0OCEfX8u@IUeFRuG6cEVnRxwXb2qo5YeiSNl39hizBgd6dg1i5YASDWbV9Sgwaxv0dmwbD6IoNn7gb9V2Za2bwnR2zatVtREfjkhEYyYb0Tm9Cs2owXlFNMCICN46oeNNbLYQ/o@oG/XqhiDcWlunVIKlDi/SIwH0il8h0lCBmImAshNynbtatdFccf4JOX/tgGAFefnqEjxCWO4LF1RWXXB9CW78PZdpDUG4B19ciAtcaHaZ/IgxTyzuo/29qnb5xWoAxiuixGIMLy7fc58zGdBJjEI7BBfHNQRLLMwQl0BebJoTGfMqmE8vlw3YQSkCCgVYrOg/JV8Ko0gi3GcaU@vsi0ytKMFi4Jf6aOXg8984uLV68PtSKRIdTfSK1V8Shiue6ItK@drzgwj9IIbwPoRMkKziLRGZVZK4VQo69gCF5VXEZJlqitqbh3pExNXJkXv5G1VESqOwcUki4vkiSjYiIemTTB7QM//m9orW1FySwA0DwUCiCrJ6aVtt1pqvIidb1yuOuTccRS8bxdXgU5wrRLodVHbll8fZkqqha3vsK8t8GW252yPNrbnaiNJVqdAP/0ee6d/yTAPPtOQpmvvPg9bO0T7PFp@KftEpmp1SSS/mi0bRUgaWcq7cK7dKp6NcIOVBuejo6@uK@1GZf1Eex8r882flXPwBAk4pc@U8@65x3Drfb53zbPZn3ARxSorA8/hFjXrvlpiY@gVnvnt76slEqglF@zeHfkVFZ1ZBS7/1IFbLl/UKk//v2dw6ReJVB0N0dh6If9WoD0j3xgU9md2@yfqdQx1SzHVoCka0ji6GFrrA8EIRDZ7L0Uo1kfxf0kTUB38g5hgAjn8BvqhpVZHaqr4iEANMAHgfDR2rYIfOwC4MzeGk8Bh8Z5YR2nTVzOp/NzM0HBepXrWcmANGkGJnttFZCGM6upZ9eTSpZb26Xt2ofKhuwPMCnjHgFTnkRnOtET3K/r6fxVMs8pP4YPGSS0YnnBCMeCcrvsenZ5ByyegnqoYDc5ojRg4GTxxqtuGtsPynRqeT9nHBgasKQ6icv@IZfIRwx4PwwNloRIjmg2hOgJfGaXqtxLkeWxYgnOQTGsGh@PQiRpvtVCke938VAW//oI/U4KeC36fSmSwUj3xBLWovLqmxf//zX@/e1fnW9h87u429/YOPfzY/fT48ah2ffDk9O/968dfl1bWkaXe6327@Ydyalt276zv3D@7A84ejcRBOHsWoP5svfvwH "Dash – Try It Online")
## ]'rz.
* Filename (escaped): `;&;|;v;p\001;8;n;q.zq.a.w.o.i.c .x.c\177.yT.+^.%!.+XX.aXX.a.c\001.+.a`
+ Actual: `;&;|;v;p;8;n;q.zq.a.w.o.i.c .x.c.yT.+^.%!.+XX.aXX.a.c.+.a`
* Content: empty.
### With comments
```
XX.z
# they are just literals but discarded later
.aXX;&;|;v;p\001;8;n;q.z
# while size<2||pop!=0; do push 'q'; done
.a.zq.aXX.z
# while empty||pop!=0; do
.a.wXX.z
# if ! empty; then putchar pop; fi
.a.oXX.z
# push getchar; dup; push 32;
# while size<2||pop<pop; do
.a.i.c .xXX.z
# dup; push 127; while size<2||pop>pop; do
.a.c\177.yXX.z
# push 84; push pop+pop;
# push 94;
# push ((x=pop)<(y=pop))?y%x:x%y
.aT.+^.%XX.z
# push 33; push pop+pop;
.a!.+XX.z
# push X; push X; done (* idiom for BREAK statement *)
.aXX.aXX.z
# push X; push X; done
.aXX.aXX.z
# dup; push 1; push pop+pop; done
.a.c\001.+.a
```
[a!( v# |{yv{r.](https://tio.run/##nRjtVuJK8v88RdPDRzchCQEclab1KupcZhQddeaqwLgxBImGBEhQFJhzdl91H2S2upMgOnPO7t0fku6q6vruqmq7ZtD/@R6Vex/KRvfGNAzbMLu98qa1sWb0jLJlWD17vWeXNzbNUnmz9@49Gk7tgaOVtIHjaUM/cKZOMHgX2CFS7QmbDMzgHhWLpRKzp0N/HKLD@vXO4SGvMxI@DW10a4eW7/WyWbmz/MHA9Lp0S@/aD7o3cV1U2soa2Wx8@GTn/E@O0ySmQ@owYSBRND0TH6W6iBbqAidivzYbF9dn53u8VCyWE@DJ8Vnj4vDyun58erpfP@cGayHVQzg92905@/P62/7pWeO4WQU2qJPNzpC0ykfSSiY2yi5bLM9c/e6IPZi4ZmijoC8O@MMQVo/@uBsMXSdkpuuYAVJvUS49MxSc/gMvcjwnvjnW/Hp4WD/a41UpAowWArss6Du9UArvIkEYA2yr76P0e4oRR4YQTSQk6Nvgw9D3ke92t7IiCk6IDMrsB9NFOIV6phvYeD7/DTlapZcaSJrpPLC7KBfoU/1JZwH8POs5KfcZdeZzMFlyAppfxIIl4AH3gW9uMgjh0HFtQkmPF5llBjZIMDByPER6eYp6EA1mB6bFzCCwBzfukwi8DzHf8ZD6EE6MeThGaj1ARaNUrqx9WN/YRLlW28t3cvPbsT1E2tx8vEe53f2PjebMBSFdXvnAwLtkOHa8sIdywxP/2Gs6jWurHpw9fOsd2Pvj08e/phdPl89X5k54Pjjq7ilqKp3J5Ob/h@h0keN6C6N0EeEOb2MMLnH9R3tMgkgFgjMWLqSLlCLcxgwzcGROpgbBuHBWwFVMmVC9xwOOMev5Y8Ig413Hs1Fvq8jozOmRBBDUeJFKOgAGwpP1bLbHeZfO9gllUiSqt4IOW9gQdSSoJPaxLyIRrQ9Jjwpx7C3jCCMYyWAW2WKxFPOrACkhOnJIAgoAQbHoTTwrdHwPHRJL6m6lQF8ahKZ133IVpcOtFSI4ImhcOovchd3YBS6Y7qoqjcEIo5iDanQiNcAJi0VOhkF9QD7kjsw8nORDZHJs4BZY5ylcbz1On547uqqbujDfqxVjyVgz0W4FaREBnmPLhHSGxMbLzJZ0EGgScTE7@jZGf4BmngLsqmCkYOlLg/Suns2mPBo7MoLQ2YR7qsEizbytyWpsZQBiVSIl0KPuI838rS5vbYmUw2asD1DI2Hl/g2USc0hQFl@fTNBui8KX3E88Jy0UuRmpbohKogwBp3kSBZMXxQcyNA0xg1UfALkgDy4b@p4VPIzDjp4nZs2git5S4Nqp0b5EIT72NGQLfajPgA0LoDosgprB4C9G9WHVB8NDPZ9KmWwxC3hKb/XsOBrMFE5xrju6orvAtXmgghhiQuxBAQsc1fK9ABQAYF8A9YGuAtqAVaILWxhwQ9@YWX5lZm520nKUYoeni2zIxVoRObkYpn5A9iZWuLogU0sdPkQHZyiY3AThmKSLhTJlJy1VdTr8AoTVSJNH1WBYMAsHZ5Rms6DqDOgJTmOAILPV7BQiXpR1bdeGXhNxYItmrQz0gZAVs1wuYj2CmBdqfUcdBTheLHm9qNHcKkE7EU4AF0Cn0FvpTAcSWIjOww/YB/GZcrFnTzyCiKSe1p7oVOFPKnniUygPPLm/d7zE7mpAxugw8oDZuoPLz1adAjlG9Laib0@VpyqEZ3uqwjcF3zx8M/DNPFWhB/1i9n5zbxZJKYIUh0VVAtBSBGRw0sDgOmj5tK4vi7aE699dBG7RddHchF/y@gnJUqbfwh7p8LmBPiZT1rmGpO3Z43DQAVfqWahwOgtZcvcAFF1mQNCZxJgCuJDLrliKbiRaa2/Zt2X3zInrRoo0N59H@y6wHtvhZOyJDhFJUQQDs9tNpKpiH9yEyT4l9jB@JPt2WgC6zkMCyEgCP2EQ6Fpe/@v8gOAsFCvwyhvNlm0zqqBnrXsOeQ53MelX/ahf5aCbh0mRyAl/z5dHl6XdJrt0dq8oDNh0OPyInBFR2wWOuzUBZbuKQmFR2I0JYPGGuVAdBFDZj7sI6hFlcAsDa@wMQx4rKrqUbXd/YA0azRjGRrldbUYnZI8KewqfCe3wPakTqPa6EUXuT31@1cY@LREIEFvGCurzC0pa84I5f4URQmWJWOIvyCmdnXIgk5qoahx6dLpCNCH1uHwT1ahBo6/XSmsf6Ha9Klrfkuyj4AUemHg/dE0XbCcem3hiSHhhGq@W3XA7Xayqq7Z8FcLgVH0FtkOOkv6xU8WFo9WuEYFTL@1jeWpIknEjBU6lE3IBvyt4P2r5v0d6pFEYFfYK7gvNbMSBCGYk1/Zuwz4ZUZlFDegPjRp3WQNyaELIHo9r7KjQKBiU/sCtorrZwdt7SmWjWlkTA8pSjAM6nJCPr2Vfk6NCvXBVuKSzI4616ypq@qEoUvatPcaszoGeXYFYOaBEg1llPQrM2ga9GdvmvSiK9R/4e6VVXuukMZ1d8UpFrceHIxLRmMlGdM6oQDOqc14WDTAigrdO6HgTmy2E/yPqeq2yIQi31tYplWCpw4v0SAC95JeI1FUgZiKg7IRc5S9XbbRWnH9Czl87IFhBXry6BA8QlrvCNyqrLri@CDf@jsu0hiDcgS@@iQtcaHSY/IgxTyzuov2dqnb4t9UAjFdEicUYXly@5z5ls6CTGIV2CNbGVQRLLMwQl0BebJoXGfMqmI8vlw3YQSkCihSwWNF/Sr4URpFEuM80pjbYF5laUYLFwC@10crBp79xcGv14PNSKRIdTfSK1V8Shiue6ItK@drzgwh9L4bwPoRMkKziuyIyqyRxqxR07B4Ky6uIyTLVELVXgXpExNXJkzv5G1VESqOwcUki4vkiSjYiIemTTB7QU3lze0VraixJ4IaBYCBRBVmtuK02qo1XkZOt6xXH/BuOopeN4mrwKc4VIt0OKrvyy@NsSVfRlT32U8t8GW252yPdrbr6iNJVqdAP/0eemd/yzADPjOQpmvvPg@bO0T7PsSybswc2bBeLBttgHhtpzyPN1B41X3M0C2lTzWob6@va07mmfNcymZSmXFxopvgDDJzSFM3MvasfN8/3m@c8l/sZN0GcliLwPH5Ro967JSamfsFZ796eerSQakHR/s2hX1HRmVXQ0m89iNXyZb3C5P97NjdPkXjVwRCdmwfiXzXqPTK8ccFIZrfvsn7nUZto@TZNw4jWNsTQQhcYXiiiwXM5WqkWkv9Lmoj64A/EHAPA8S/AFzW7FaQ2K68IxAATAN5HQ6dbsENnYBeG1nBSeAieWdcMbbpqZuW/mxmajotUr1JKzAEjiNaebbQXwpi2oedeHk1qyaisVzbKHyob8LyAZwx4RQ650VxrRo@yv@9n8RSL/CQ@WLzkktEJJwQj3s6J7/HpGaRcMvqJquHAnOaIkYPBE4daLXgrLP@p0W5nfFxw4KrCECrnr3gGHyHc9iA8cDYaEaL5IJoT4KVxmlkrcm7ElgUIJ/mERnAoPr2I0VYrXYzH/V9FwNs/6CM1@JnC79OZbA6Kh1JQNf3FJVX273/@6927Gt/a/mNnt763f/Dxz8anz4dHzeOTL6dn51@//XVxeSVpWu3O9@t/mDdW1@7d9p27e3fg@cPROAgnD2LUn80XP/4D "Dash – Try It Online")
] |
[Question]
[
Since no one has posted a "good quality question" recently, i feel it is my duty to...
**Task:**
>
> You work at an electronics company in the design department. The designers that work with you have asked you to make a program that will calculate the optimum configuration of pins on a microchip they are designing. With your ninja golfing skills, you are confident you can handle it.
>
>
>
Your company also has these requirements for each chip:
* The chips your company makes are known as TQFP, they have pins on each edge, but none in the middle.
* Each chip must be square, and have the same number of pins on each side.
* If the chip doesn't have enough pins to be square, pins will be added.
+ Extra pins are either a ground or voltage supply pin.
+ Half are ground, half are voltage supply.
+ If there is an odd number of extra pins, the odd one out is ground
Your program will take input as a single integer, which is the minimum number of pins the manufacturing needs. You will then output 4 integers:
* The number of pins (total)
* The number of pins per side
* The number of ground pins added
* The number of voltage supply pins added
**Rules:**
* You can use any language
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), to the shortest answer in bytes wins
* Bonus: -50 for printing an ASCII chip:
Something like this:
```
+++++
+ +
+ +
+ +
+++++
```
(For example with an input of 20)
[Answer]
# APL, 54 chars/bytes\* – 50 = score 4
*“Take this, Golfscript!” special edition*
```
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]}
```
Takes a number as input and returns the required output. Dialect is Dyalog with `⎕IO⎕ML←1 3`
**Explanation**
```
{ s←⌈⍵÷4 } divide the # of pins by 4, take the ceiling and call it s
∘.{ }⍨⍳s for each couple of naturals up to s compute a table with:
∨/⍺⍵∊1s 1 if either one of the two numbers is 1 or s, 0 otherwise
⊂' +'[1+ ] convert the 0 and 1s to space and + and enclose the table
then...
t←4×s multiply the pins per side by 4 and call it t (for total)
h←2÷⍨⍵-⍨t subtract the # of pins from it and divide by 2, call it h
t s(⌈h)(⌊h ) make a vector with t, s, the ceiling of h, and its floor,
,—— and prepend it to the previously enclosed table of chars.
```
**Examples**
```
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 0
0 0 0 0
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 1
4 1 2 1 +
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 2
4 1 1 1 +
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 3
4 1 1 0 +
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 4
4 1 0 0 +
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 5
8 2 2 1 ++
++
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 6
8 2 1 1 ++
++
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 7
8 2 1 0 ++
++
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 8
8 2 0 0 ++
++
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 9
12 3 2 1 +++
+ +
+++
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 13
16 4 2 1 ++++
+ +
+ +
++++
```
\*: Dyalog supports its own (legacy) single byte charset, where the APL symbols are mapped to the upper 128 byte values. Therefore the entire code can be stored in 54 bytes if needed.
[Answer]
# Python: 64 53 46 bytes
```
x=input()
m=x+3&~3
t=m-x
print m,m/4,t-t/2,t/2
```
Second Third attempt seems pretty minimal. Thanks for the help.
First attempt seems sort of long, we'll see what an hour or two of mulling it over will shave off of the byte count. Could also probably make it shorter if a function is allowed instead of program.
```
> python chip.py
9
(12, 3, 2, 1)
```
Also made a version that prints chips, seems like the `-50` isn't worth it in python. Total score of `102-50=52`.
```
x=input()
m=x+3&~3
n=m/4
t=m-x
s=['+'*-~n]
print'\n'.join(s+['+'+' '*~-n+'+']*~-n+s+[`m,n,t-t/2,t/2`])
```
Example:
```
> python chip.py
9
++++
+ +
+ +
++++
(12, 3, 2, 1)
```
[Answer]
## Julia, 62 61 56 bytes
```
m(x)=(s=iceil(x/4);p=4s-x;(4s,s,iceil(p/2),ifloor(p/2)))
```
Very straightforward. And now down to 56 thanks to gggg's sharp eyes.
Outputs:
```
In [14]:
m(9),m(6),m(71),m(1),m(3)
Out[14]:
((12,3,2,1),(8,2,1,1),(72,18,1,0),(4,1,2,1),(4,1,1,0))
```
The ASCII chip bonus isn't worth the bytes it costs, but since I made it, here's all 190 bytes of it. **Edit:** I made the chip drawing before OP posted an example chip , so I'm sticking with my method. I think it looks better than plus signs, anyway.
```
m(x)=begin s=iceil(x/4)
p=4s-x
g=iceil(p/2)
v=ifloor(p/2)
b={x in[1,s]||y in[1,s+1]?"o":"."for x=1:s,y=1:s+1}
if g>0 b[1,1:g]="G" end
if v>0 b[s,s+2-v:s+1]="V" end
print(b,'\n')
return 4s,s,g,v end
m(29)
G G o o o o o o o
o . . . . . . . o
o . . . . . . . o
o . . . . . . . o
o . . . . . . . o
o . . . . . . . o
o . . . . . . . o
o o o o o o o o V
Out[7]:
(32,8,2,1)
```
This version of the chip gets it down to 115, which is still too long for the bonus to be worthwhile. And it requires the "corners have two pins even though one is shown" assumption of OP's example. I prefer my corrected version above which shows the exact number of each type of pin.
```
m(x)=((s=iceil(x/4);p=4s-x);b={x in[1,s]||y in[1,s]?"o":"."for x=1:s,y=1:s};print(b);(4s,s,iceil(p/2),ifloor(p/2)))
```
Question posters of the future, take note: bonuses often serve only to increase the advantage of terse languages.
[Answer]
# Perl, 72 bytes
The input number is expected in STDIN, the result is written to STDOUT.
```
$_=<>;$==$_/4+!!($_%4);$a=4*$=-$_;@a=(4*$=,$=,$a-($-=$a/2),$-);print"@a"
```
**Test:**
```
echo 4 | perl a.pl
4 1 0 0
echo 5 | perl a.pl
8 2 2 1
echo 6 | perl a.pl
8 2 1 1
echo 7 | perl a.pl
8 2 1 0
```
**Ungolfed:**
```
$_=<>; # read input number from STDIN
$= = $_ / 4 + !!($_ % 4); # tricky way for ceil($_ % 4)
$a = 4 * $= - $_; # extra pins in $a
@a = (4 * $=, # total
$=, # each side
$a - ($- = $a / 2), # ground, tricky way for $a - floor($a/2)
$- # voltage
);
print "@a" # print result, separated by spaces
```
[Answer]
### GolfScript, score 5 (55 characters - 50 bonus)
```
~:^3+3~&.4/:&1$^-.)2/\2/]p&)'+'*n+'+'&(' '*'+'++n+&(*1$
```
The input is given on STDIN. The first part (until `]p`) does the calculation while the rest is for the bonus.
*Examples (run [online](http://golfscript.apphb.com/?c=OyI5IgoKfjpeMyszfiYuNC86JjEkXi0uKTIvXDIvXXAmKScrJypuKycrJyYoJyAnKicrJysrbismKCoxJAo%3D&run=true)):*
```
> 20
[20 5 0 0]
++++++
+ +
+ +
+ +
+ +
++++++
> 9
[12 3 2 1]
++++
+ +
+ +
++++
```
[Answer]
# J - 71 66 char -50 = 16 pts
Saves a bunch of bytes with the 50 bonus, so let's do that.
```
(((>.,<.)@-:@-@],~-,[:#2:1!:2~' +'{~1,~1,1,.~1,.0$~2#2-~-%4:)_4&|)
```
Some key bits:
* `_4&|` - Take the input modulo -4: it's just like taking it mod 4, but you go into the range (-4,0].
* `(>.,<.)@-:@-@]` - Negate the residue mod -4 from before, halve it (`-:`), and take the ceiling (`>.`) and the floor (`<.`).
* `1,~1,1,.~1,.0$~2#` - We make a square array of zeroes, and then pin ones all around it: in front (`,.`), behind (`,.~`), on top (`,`) and below (`,~`).
* `[:#2:1!:2~' +'{~` - After constructing the square array the way we like it, we use its values to select (`{`) out of the characters `' '` and `'+'`, and then we print the matrix with `2:1!:2~`. Finally, we get the original number back (the number of pins per side) with the length.
Usage:
```
(((>.,<.)@-:@-@],~-,[:#2:1!:2~' +'{~1,~1,1,.~1,.0$~2#2-~-%4:)_4&|) 20
+++++
+ +
+ +
+ +
+++++
20 5 0 0
(((>.,<.)@-:@-@],~-,[:#2:1!:2~' +'{~1,~1,1,.~1,.0$~2#2-~-%4:)_4&|) 9
+++
+ +
+++
12 3 2 1
```
The version without the ASCII-drawing portion is 30 characters:
```
(((>.,<.)@-:@-@],~-,-%4:)_4&|) 86
88 22 1 1
```
[Answer]
# Python (103):
```
from math import*
a=int(raw_input());c=ceil(a**.5);b=c**2;z=(b-a)/2;d=ceil(z);e=floor(z);print (b,c,d,e)
```
Not the shortest, but it does what it's supposed to.
[Answer]
# K - 68 char -50 = 18 pts
This solution mimics the J methods somewhat, but has an APL-like way of shaving off characters.
```
{`0:(" +"1,|1,)'+r#,1 0,|~!r:-2+q:_(x-:m:x!-4)%4;x,q,-1 1*_.5 -.5*m}
```
Explained:
* `x-:m:x!-4` - Take `x` mod -4, putting it into the range (-4,0]. Now, assign this to `m` (for modulus), and reassign `x` to `x` subtract `m`.
* `r:-2+q:_(x)%4` - Divide `x` by 4 and floor it, converting it from unnecessary float to integer. Assign this to `q`, and assign two less than this to `r`.
* `1 0,|~!r` - Take the integers less than `r`, starting from 0. Logical negate every integer, leaving a 1 in the 0 place and 0 everywhere else. Reverse the list, and then prepend `1 0`. Now, the list will be `r+2` = `q` items long, and the first and last are a 1.
* `+r#,` - Make `r` copies of this list, and transpose the resulting matrix, which is now `r` wide and `q` high.
* ``0:(" +"1,|1,)'` - Append 1 to the front and back of each row, and then use the placement of the 0s and 1s to select characters out of `" +"`. This creates an ASCII chip, which we print out to console with ``0:`.
* `_.5 -.5*m` - Take `m` from before, halve it, and then floor it and its negation. K doesn't have a ceiling function, so you have to emulate ceiling by flooring the negative, and negating that again.
* `x,q,-1 1*` - Flip the sign on the negative number of the two, and then append `x` and `q` from before to the list. This then goes on to be the return value.
Usage:
```
{`0:(" +"1,|1,)'+r#,1 0,|~!r:-2+q:_(x-:m:x!-4)%4;x,q,-1 1*_.5 -.5*m} 20
+++++
+ +
+ +
+ +
+++++
20 5 0 0
{`0:(" +"1,|1,)'+r#,1 0,|~!r:-2+q:_(x-:m:x!-4)%4;x,q,-1 1*_.5 -.5*m} 9
+++
+ +
+++
12 3 2 1
```
The version with no ASCII drawing is 34 characters:
```
{x,_%[x-:m;4],-1 1*_.5 -.5*m:x!-4} 86
88 22 1 1
```
] |
[Question]
[
Consider a function \$r\$ where
$$
r(i,k)= \begin{cases}
L\_{i+1}-L\_i, & \text{if}\ k =0\ \text{ (1st reduction)} \\
r(i,0)-r(\lfloor \log\_2{k} \rfloor,k-2^{\lfloor \log\_2{k} \rfloor}) & \text{if}\ k \geq 1\ \text{ (2nd reduction)}
\end{cases}
$$
where \$k<2^i\$ and \$L\$ is a finite sequence of integers.
For example, assuming that \$L = \{0, 1, 1, 2, 3, 5\}\$,
for \$i=0\$,
* \$r(0,0) = L\_1-L\_0 = 1-0 = 1\$.
for \$i=1\$,
* \$r(1,0) = L\_2-L\_1 = 1-1 = 0\$.
* \$r(1,1) = r(1,0)-r(0,0) = 0-1 = -1\$.
for \$i=2\$,
* \$r(2,0) = L\_3-L\_2 = 2-1 = 1\$.
* \$r(2,1) = r(2,0)-r(0,0) = 1-1 = 0\$.
* \$r(2,2) = r(2,0)-r(1,0) = 1-0 = 1\$.
* \$r(2,3) = r(2,0)-r(1,1) = 1+1 = 2\$.
The **double-reduction of \$L\$** is created by concatenating results from \$i=0\$, \$i=1\$, ..., until every consecutive pair of elements of \$L\$ are visited.
In layperson's terms, this function subtracts two consecutive terms of \$L\$, and then subtract every previous-calculated subtraction from that result. Note that every call of \$r(i,k)\$, for \$i>0\$ and \$k>0\$, is already computed.
## Input
A list of integers `L`. You can assume its size will be always greater or equal to 3.
## Output
A [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") representing the double-reduction of `L`.
>
> * **Indexing:** Both \$0\$- and \$1\$-based indexing are allowed, and the following rules can be applied with both these types of indexing.
> * **Format:** The answers can use one of the following output methods:
> + Given some index \$n\$, it can return the \$n\$-th entry of the list.
> + Given some index \$n\$, it can return all entries up to the \$n\$-th one in the sequence.
> + Without taking any index, it can output *all* entries by printing them one by one or by returning a list.
>
>
>
### Test cases
Here's the test cases for positive numbers, even numbers, prime numbers, Fibonacci numbers, power-of-2 numbers, lucky numbers and signed Fibonacci numbers, respectively:
```
[1, 2, 3] -> [1, 1, 0]
[2, 4, 6, 8] -> [2, 2, 0, 2, 0, 0, 2]
[2, 3, 5, 7, 11] -> [1, 2, 1, 2, 1, 0, 1, 4, 3, 2, 3, 2, 3, 4, 3]
[0, 1, 1, 2, 3, 5] -> [1, 0, -1, 1, 0, 1, 2, 1, 0, 1, 2, 0, 1, 0, -1, 2, 1, 2, 3, 1, 2, 1, 0, 1, 2, 1, 0, 2, 1, 2, 3]
[1, 2, 4, 8, 16, 32] -> [1, 2, 1, 4, 3, 2, 3, 8, 7, 6, 7, 4, 5, 6, 5, 16, 15, 14, 15, 12, 13, 14, 13, 8, 9, 10, 9, 12, 11, 10, 11]
[1, 3, 7, 9, 13, 15, 21] -> [2, 4, 2, 2, 0, -2, 0, 4, 2, 0, 2, 2, 4, 6, 4, 2, 0, -2, 0, 0, 2, 4, 2, -2, 0, 2, 0, 0, -2, -4, -2, 6, 4, 2, 4, 4, 6, 8, 6, 2, 4, 6, 4, 4, 2, 0, 2, 4, 6, 8, 6, 6, 4, 2, 4, 8, 6, 4, 6, 6, 8, 10, 8]
[0, 1, -1, 2, -3, 5, -8] -> [1, -2, -3, 3, 2, 5, 6, -5, -6, -3, -2, -8, -7, -10, -11, 8, 7, 10, 11, 5, 6, 3, 2, 13, 14, 11, 10, 16, 15, 18, 19, -13, -14, -11, -10, -16, -15, -18, -19, -8, -7, -10, -11, -5, -6, -3, -2, -21, -20, -23, -24, -18, -19, -16, -15, -26, -27, -24, -23, -29, -28, -31, -32]
```
Your solution should be implemented with fewest bytes as possible.
Brownie points for beating or matching my 70-bytes Python answer.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
⊞υ⁰FEΦθκ⁻ι§θκ≔⁺υ⁻ιυυIΦυκ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gtDhDo1RHwUDTmistv0hBwzexQMMtM6cktUijUEchW1NHwTczr7RYI1NHwbHEMy8ltQIiDgQKjsXFmel5GgE5QPlSJIWlmpogwporoCgzr0TDObG4BGZmKUSv9f//0dFGOgrGOgqmOgrmOgqGhrGx/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Adapted from both @Arnauld's and @loopywalt's answers.
```
⊞υ⁰
```
Start with a list of just `0`.
```
FEΦθκ⁻ι§θκ
```
Loop over the list of differences of the input array.
```
≔⁺υ⁻ιυυ
```
Subtract all of the elements of the output array from the current difference and then concatenate the result onto the output array.
```
IΦυκ
```
Output all but the first element of the output array.
[Answer]
# [Python](https://www.python.org), 63 bytes
```
f=lambda l,*L,a=[]:L and f(*L,a=a+[L[0]-l-b for b in[0]+a])or a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVNLTsMwEF2w6ymsrhKwUeyYNEUKrNjlBlEWrkpFpDSJoCCx5hhsuoE7wWmYT2zMJ4rGnpk3b37J6_v0fLgbh-Px7fGwU-XH9a7q3X6zdaKXp7V0VdNe1sINW7FLSHdnTd1krerVRuzGe7ER3QD6mWtT0NxMc4OuGlxinG6HJEsvFwKeTo7V3k3J7ZPrZX3-MPXdIVmqq2Wakn-674ZDApm6tKrGlMmOnycvjZbCSJG3Ql0JVODN2kUDNitFIUXJHkOwzEu8MCqX4kKKFQTqwGGIhmVG0hLQRBItwMBu7a0XgQMcSkcM5uc986qK8-X_QbWv27e6mGuEEkqwQpO5-VV7XG9J7RUkLXVbkMRAjaedTwzNZ53j1nDL-ECnZhUmRSXkRLmeo4DB6DBsS9m5UcWHjVYQ1mN_gTLvM8EUHKgry2cItWHRJGPiOGGMiWNLrxYegB2WYbPzehR_JqoMc1azlcfMQ1UIKdhOfqBTKyShRWu_Cx6ij2KGMHk_ZL8dLGmN4UiKCCKaKTEZohTCFOH-5PxTlaHyaaBksj_ivzkN3szKQxiMEIPgHFngw1vwz_gF)
Takes splatted input. Returns the entire double-reduction.
## How?
Once one all but ignores the confusing double indexing there is an obvious rather simple recursion.
[Answer]
# JavaScript (ES6), 61 bytes
An implementation of what the function *really* does, as described in the *layman's terms* paragraph of the challenge.
```
a=>a.map(v=>a=[0,...b].map(k=>1/a&&b.push(v-a-k))&&v,b=[])&&b
```
[Try it online!](https://tio.run/##VY3LDoIwEEX3fMXEBWmTabXgA2PKzq8gXQwo4osSUX4fR2pMTLo490zu7YUG6qvHuXuq1h@OY21HsjnpO3ViYLDFArXWpZvM1eZmTnFc6u7VN2JQpK5SxvGApS0cQznuigigMAgJQurwE5iWCGuE7JdThBXCBsGY4BaM0/segw2ZyxnfeCBNfj6d6lv2TIbHkr8lFaoqfKQyF7lI1/6xp6oRBDaHyre9vx31zZ9ELUjqiz@3YoYwk1KObw "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input
a.map(v => // for each value v in a[]:
a = // update a:
[0, ...b] // for 0 and each value in b[]
.map(k => // loaded in k:
1 / a // do nothing if this is the 1st iteration,
&& // i.e. a is still the input array (*)
b.push( // otherwise, push in b[]:
v - a - k // the current value, minus the previous one,
) // minus k
) // end of inner map()
&& v, // save v in a
b = [] // start with b[] = empty array
) // end of outer map()
&& b // return b[]
```
*(\*) The input is guaranteed to contain at least 3 integers, as per the challenge rules. So it can't be coerced to a number.*
---
# [JavaScript (V8)](https://v8.dev/), 92 bytes
This was an attempt at implementing the definition literally.
```
L=>{for(n=1;L[-~(g=Math.log2)(n)];)print((r=k=>~(k-=2**(i=~~g(k)))&&L[i+1]-L[i]-r(k))(n++))}
```
[Try it online!](https://tio.run/##VY9Bi8IwEIXv/RVzkhmbiEldt0uZ3rx1f0HJIQit3UqVWLyI/et1NIsgBPLeN7w3zJ@/@ss@dOdRX/O54bni8tacAg5siqrWE7b868fD6nhqLeFArqBz6IYRMXDP5YS9ZrtcYsfT1GJPRItFVXepcVo@p8OT4ZCmRPe5qBOA2iiwCjKnnkbURsFWQf72mYIvBd8KjIlsLfL1/oeRRi/hXGZSkNk3z17xH@GijJTZjyYdozou0rlLXLKSo3d@f0APXMINGvRUQDxVxJ3mBw "JavaScript (V8) – Try It Online")
[Answer]
# [Haskell](https://haskell.org), 48 bytes
```
r a[_]=a
r a(x:y:l)=r(a++[y-x-z|z<-0:a])$y:l
r[]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Î¥vDyα‚˜}¦
```
Inspired by [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/269758/52210).
[Try it online](https://tio.run/##AScA2P9vc2FiaWX//8OOwqV2RHnOseKAmsucfcKm//9bMiwzLDUsNywxMV0) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/g@JDS8tcKs9tfNQw6/Sc2kPL/uv8j4421DHSMY7ViTbSMdEx07EAs4x1THXMdQwNgRwDHUMdsBIdUyAPxDLRsdAxNNMxNgLzjYEKLXUMjXUMTXWMYBp0Qep0QaboWsTGAgA).
**Explanation:**
```
Î # Push 0 and the input-list
¥ # Get the deltas/forward-differences of the input-list
v # Loop over each of its integers `y`:
D # Duplicate the current list,
# which is the 0 in the first iteration
yα # Get the absolute difference of each value with integer `y`
‚ # Pair this list together with the duplicated list (or the 0)
˜ # Flatten it to a single list
}¦ # After the loop: remove the leading 0
# (after which the list is output implicitly as result)
```
] |
[Question]
[
Here is a challenge:
What is the shortest possible compiled program? Writing one line programs are fun, but they often lean on language libraries that get pulled into the final bits. How lean can you get the 'scaffolding' that supports and hooks into the compiled instructions? This seems like an interesting question because then the smallest possible program for problem 'X' is going to be: (Smallest scaffolding bytecode size) + (smallest instructions to solve probem 'x")
The code must run on a common modern OS, such as \*nix or windows (no embedded hex that runs on 1970s era mobos and chips). Doesn't matter if you are just exiting immediately, what language / platform produces the smallest bytecode? If you can get bytecode that is below a few dozen bytes, show your output.
I'll kick this off by setting a (very) low bar:
```
int main()
{
return 0;
}
```
This compiled in VS Pro 2022 as a release build c++ app with no changes to the default build flags produces an 11k exe that runs in windows. I think I might be able to get this smaller by playing with the build flags and possibly by building it as a 32 bit c app. I'm digging into some ASM docs to see if you can still hand write exes that run on a modern OS
Lets say that IL output is fair game, but non-compiled script languages need not apply...
**A FEW ADDITIONAL NOTES**
I used the definition of a 'modern' OS as one of the criteria. People are getting this right, but I am talking about either a 32 bit or 64 bit build. I think that 32 bit is generally going to be smaller in size, but feel free to try out 64 bit builds if you are so inclined.
Be sure that you aren't making debug builds in your compiler, as this will probably include additional debugging symbols. No need for debugging these apps, they are going to run perfectly on the first try, right?
[Answer]
# x86 assembly DOS .COM file 1 byte
```
ret # assembles to 0xC3
```
COM files are executable and have no header or other mandatory content. An empty COM file produces an error, so the shortest executable COM file consists of just the RET instruction.
One way of testing this is by using DEBUG from the DOS prompt, tested using MSDOS 6.22 via [pcjs](https://www.pcjs.org/software/pcx86/sys/dos/microsoft/6.22/). The following are typed as sequential lines (including a blank line after `ret`). However, this should also run under 32-bit Windows 7 or 10 which are ‘modern’ OSes.
```
DEBUG
n c:\test.com
a
ret
rcx
1
w
q
C:\test.com
```
[Mathias Bynen’s small GitHub repo](https://github.com/mathiasbynens/small) is also a useful resource for this.
[Answer]
# [FASM](https://flatassembler.net/) (32-bit ELF executable), 87 bytes
*Larger than the final ELF-file in the blog post linked in the comments of the question, but less than a third of the size of the smallest output they were able to generate without directly creating the ELF-file, and a few bytes shorter than the shortest program without overlapping sections in the ELF-file*
```
format ELF executable 3 ; 32 bit elf
segment readable executable
entry $
inc eax ; eax and ebx default to 0
int 0x80 ; syscall 1 (exit) with exit code 0
```
produces the following (statically linked, 32-bit) ELF-executable:
```
457f 464c 0101 0301 0000 0000 0000 0000
0002 0003 0001 0000 8054 0804 0034 0000
0000 0000 0000 0000 0034 0020 0001 0028
0000 0000 0001 0000 0000 0000 8000 0804
8000 0804 0057 0000 0057 0000 0005 0000
1000 0000 cd40 0080
```
As far as I can tell the actual code takes only 3 bytes, so the main way for reducing the file size would be to somehow convince the assembler to make the different parts of the ELF-file overlap (like in the blog post)
[Answer]
# Python 3.4.10 (.pyc file), 63 bytes
```
00000000: ee0c 0d0a 50a6 2265 0000 0000 6300 0000 ....P."e....c...
00000010: 0000 0000 0000 0000 0001 0000 0043 0000 .............C..
00000020: 00f3 0200 0000 4753 a900 a900 a900 a900 ......GS........
00000030: a900 da00 da00 0100 0000 f300 0000 00 ...............
```
Generation script:
```
import marshal
import types
# taken from a pyc file generated from a blank file
header = b'\xee\x0c\r\nP\xa6"e\x00\x00\x00\x00'
open("c.pyc","wb").write(
header +
# b'\x47S' == LOAD_BUILD_CLASS + RETURN_VALUE
# shorter than LOAD_CONST None and allows for empty co_consts tuple
marshal.dumps(types.CodeType(0,0,0,1,67,b'\x47S',(),(),(),'','',1,b''))
# replace TYPE_REF to empty string w/ TYPE_SHORT_ASCII_INTERNED b/c it's shorter
.replace(b'r\x02\x00\x00\x00',b'\xda\x00')
# replace TYPE_REF to empty tuple w/ empty TYPE_SMALL_TUPLE
.replace(b'r\x01\x00\x00\x00',b'\xa9\x00'))
```
I believe that Python 3.4-3.5 .pyc files should be the shortest for Python 3, as they have `TYPE_SHORT_ASCII` and `TYPE_SMALL_TUPLE` (both 3.4+) and don't have `co_posonlyargcount` (3.8+), [PEP 552](https://peps.python.org/pep-0552/) (3.7+), nor fixed 2-byte opcodes (3.6+).
# Python 2.7.18 (.pyc file), 79 bytes
```
00000000: 03f3 0d0a 4496 2265 6300 0000 0000 0000 ....D."ec.......
00000010: 0001 0000 0043 0000 0073 0400 0000 6400 .....C...s....d.
00000020: 0053 2801 0000 004e 2800 0000 0028 0000 .S(....N(....(..
00000030: 0000 2800 0000 0028 0000 0000 7400 0000 ..(....(....t...
00000040: 0052 0000 0000 0100 0000 5200 0000 00 .R........R....
```
Generation script:
```
import marshal
import types
header = '\x03\xf3\r\nD\x96"e'
# b"d\x00\x00S" == LOAD_CONST 0 + RETURN_VALUE
code = types.CodeType(0, 0, 1, 67, b"d\x00\x00S", (None,), (), (), "", "", 1, "")
# TYPE_STRING and TYPE_STRINGREF are the same length in Python 2.7
open("a.pyc", "w").write(header + marshal.dumps(code))
```
Unsure if this is the shortest Python 2 version; I don't have access to any earlier Python 2 versions to test.
---
Thanks to <https://github.com/python/cpython/blob/3.4/Python/marshal.c> and <https://github.com/fedora-python/marshalparser/>
[Answer]
All from the blog post linked in the question comments; this is not my work, all credit goes to Brian Raiter:
[https://www.muppetlabs.com/~breadbox/software/tiny/return42.html](https://www.muppetlabs.com/%7Ebreadbox/software/tiny/return42.html)
## NASM (32-bit Linux x86 ELF), 45 bytes
```
BITS 32
org 0x00010000
db 0x7F, "ELF"
dd 1
dd 0
dd $$
dw 2
dw 3
dd _start
dd _start
dd 4
_start: mov bl, 42 ; set ebx to exit code 42
xor eax, eax ; set eax to 1 (exit syscall)
inc eax
int 0x80 ; and exit
db 0
dw 0x34
dw 0x20
db 1
filesize equ $ - $$
```
([https://www.muppetlabs.com/~breadbox/software/tiny/tiny-i386.asm.txt](https://www.muppetlabs.com/%7Ebreadbox/software/tiny/tiny-i386.asm.txt))
## NASM (64-bit Linux x86 ELF), 80 bytes
```
BITS 64
org 0x500000000
db 0x7F ; e_ident
_start: db "ELF" ; 3 REX prefixes (no effect)
and eax, 0x00000101
lea edi, [rax + 42] ; rdi = exit code
mov al, 60 ; rax = syscall number
syscall ; exit(rdi)
dw 2 ; e_type
dw 62 ; e_machine
dd 1 ; e_version
phdr: dd 1 ; e_entry ; p_type
dd 5 ; p_flags
dq phdr - $$ ; e_phoff ; p_offset
dq phdr ; e_shoff ; p_vaddr
dd 0 ; e_flags ; p_paddr
dw 0x40 ; e_ehsize
dw 0x38 ; e_phentsize
dw 1 ; e_phnum ; p_filesz
dw 0x40 ; e_shentsize
dw 0 ; e_shnum
dw 0 ; e_shstrndx
dq 0x00400001 ; p_memsz
dq 0 ; p_align
```
([https://www.muppetlabs.com/~breadbox/software/tiny/tiny-x64.asm.txt](https://www.muppetlabs.com/%7Ebreadbox/software/tiny/tiny-x64.asm.txt))
## NASM (Linux x86 a.out), 35 bytes
```
BITS 32
org 0x1000
; a.out header
dd 0x006400CC ; a_info
dd filesize ; a_text
dd 0 ; a_data
_start: mov bl, 42 ; set exit code ; a_bss
jmp short part2
dd 0 ; a_syms
dd _start ; a_entry
dd 0 ; a_trsize
dd 0 ; a_drsize
part2: inc eax ; set syscall number
int 0x80 ; exit(ebx)
filesize equ $ - $$
```
([https://www.muppetlabs.com/~breadbox/software/tiny/tiny-aout.asm.txt](https://www.muppetlabs.com/%7Ebreadbox/software/tiny/tiny-aout.asm.txt))
[Answer]
# C (GCC, Linux, x86 32-bit), 260 bytes
*Feel free to edit this answer if you find ways to improve the score*
source code:
```
int _start(void){ // using libc significantly increases the score -> need to use _start instead of main
asm("inc %eax;"
"int $0x80"); // exit program seems to be the only way to exit a program without using the standard library
}
```
compiler options: `gcc -nostdlib -Oz small.c -Qn -m32 -static -s -N -Wl,--build-id=none -fno-asynchronous-unwind-tables`
hexdump:
```
00000000: 7f45 4c46 0101 0100 0000 0000 0000 0000 .ELF............
00000010: 0200 0300 0100 0000 7480 0408 3400 0000 ........t...4...
00000020: 8c00 0000 0000 0000 3400 2000 0200 2800 ........4. ...(.
00000030: 0300 0200 0100 0000 7400 0000 7480 0408 ........t...t...
00000040: 7480 0408 0400 0000 0400 0000 0700 0000 t...............
00000050: 0100 0000 51e5 7464 0000 0000 0000 0000 ....Q.td........
00000060: 0000 0000 0000 0000 0000 0000 0600 0000 ................
00000070: 1000 0000 40cd 80c3 002e 7368 7374 7274 [[email protected]](/cdn-cgi/l/email-protection)
00000080: 6162 002e 7465 7874 0000 0000 0000 0000 ab..text........
00000090: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000000a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000000b0: 0000 0000 0b00 0000 0100 0000 0700 0000 ................
000000c0: 7480 0408 7400 0000 0400 0000 0000 0000 t...t...........
000000d0: 0000 0000 0100 0000 0000 0000 0100 0000 ................
000000e0: 0300 0000 0000 0000 0000 0000 7800 0000 ............x...
000000f0: 1100 0000 0000 0000 0000 0000 0100 0000 ................
00000100: 0000 0000 ....
```
] |
[Question]
[
**This question already has answers here**:
[Numbers with Rotational Symmetry](/questions/77866/numbers-with-rotational-symmetry)
(43 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
>
> Original close reason(s) were not resolved
>
>
>
# Searching for *rotatable numbers*, like: *`68089`*
[](https://i.stack.imgur.com/ulYDC.gif)
If you consider numbers upside-down,
* `6` looks like `9`,
* `8` looks like `8`,
* `9` looks like `6` and
* `0` looks like `0`.
The others digits (`1`, `2`, `3`, `4`, `5` and `7` ) look like nothing...
I wonder how many number could be *rotatable* between 0 and 1000! The answer is definitively **11**: `0`, `8`, `69`, `88`, `96`, `609`, `689`, `808`, `888`, `906` and `986`
Well I imagine a tool able to display all *rotatable numbers*, between two boundaries...
The tool may be run in any way you want, whith two boundaries as argument or standard input. Then must return all *rotatable numbers* between this two boundaries.
### About duplicate
If the other question: [Numbers with Rotational Symmetry](https://codegolf.stackexchange.com/q/77866/9424) look something similar, they are **not!!**: **1)** Not same bunch of digits, **2)** not same behaviour and **3)** search in between two boundaries...
And as [Jonathan Allan's comment](https://codegolf.stackexchange.com/posts/comments/559399?noredirect=1) pointed out. Not same question, not same ways for reaching answer. Here are other interesting way for doing this!!
### Sample:
Input:
```
0 1000
```
Output:
```
0 8 69 88 96 609 689 808 888 906 986
```
Or input:
```
8000 80000
```
Output:
```
8008 8698 8888 8968 9006 9696 9886 9966 60009 60809 66099 66899 68089 68889 69069 69869
```
* No matter on output format (on one or multiple lines).
* Only numbers must be accepted.
* Of course, except `0` himself, a number could not begin by `0`.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shorter answer (in bytes) win!
#### Leaderboard
```
var QUESTION_ID=251079;
var OVERRIDE_USER=9424;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```
```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Seems a little longer than I imagine is possible
```
rD‘×Ṛ$fƑʋƇ“¢FQ‘
```
A dyadic Link that accepts the two bounds and yields the rotatable numbers
**[Try it online!](https://tio.run/##y0rNyan8/7/I5VHDjMPTH@6cpZJ2bOKp7mPtjxrmHFrkFggU/v//v8F/QwMDAwA "Jelly – Try It Online")**
### How?
Identifies rotatable mirrored pairs of digits by adding one to each and multiplying them together. The only results which are any of \$1\$, \$70\$, or \$81\$ are the valid pairs:
| (Digit+1)(Mirror+1) | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | **1** | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 1 | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
| 2 | 3 | 6 | 9 | 12 | 15 | 18 | 21 | 24 | 27 | 30 |
| 3 | 4 | 8 | 12 | 16 | 20 | 24 | 28 | 32 | 36 | 40 |
| 4 | 5 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 |
| 5 | 6 | 12 | 18 | 24 | 30 | 36 | 42 | 48 | 54 | 60 |
| 6 | 7 | 14 | 21 | 28 | 35 | 42 | 49 | 56 | 63 | **70** |
| 7 | 8 | 16 | 24 | 32 | 40 | 48 | 56 | 64 | 72 | 80 |
| 8 | 9 | 18 | 27 | 36 | 45 | 54 | 63 | 72 | **81** | 90 |
| 9 | 10 | 20 | 30 | 40 | 50 | 60 | **70** | 80 | 90 | 100 |
```
rD‘×Ṛ$fƑʋƇ“¢FQ‘ - Link: integer, A; integer B
r - inclusive range -> [A..B]
“¢FQ‘ - list of code page indices -> [1,70,81]
Ƈ - keep those of [A..B] for which:
ʋ - last four links as a dyad - f(N, M=[1,70,81]):
D - to decimal digits e.g. N=6089 -> [ 6, 0, 8, 9]
‘ - increment [ 7, 1, 9,10]
$ - last two links as a monad:
Ṛ - reverse [10, 9, 1, 7]
× - multiply (vectorises) [70, 9, 9,70]
Ƒ - is invariant under?:
f - filter keep if in M [70, 70] -> nope
```
---
We could shift down by four instead of up by one before multiplying and then only the valid pairs will give \$10\$ or \$16\$ but I think it's the same byte count:
```
rD_4×Ṛ$fƑʋƇ“½Ñ‘
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes
```
ṡ'»ƛ∪&»FS‛69*Ṙ=
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuaEnwrvGm+KIqibCu0ZT4oCbNjkq4bmYPSIsIiIsIjEwMDBcbjAiXQ==)
Takes `end boundary` then `start boundary`
## Explained
```
ṡ'»ƛ∪&»FS‛69*Ṙ=
ṡ' # From the range(start, end + 1), keep only items where:
»ƛ∪&»FS # Removing the numbers 1, 2, 3, 4, 5 and 7
‛69* # Ring translated by the string 69 (6 becomes 9 and 9 becomes 6)
Ṙ= # And reversed equals the original item
```
[Answer]
# [Factor](https://factorcode.org) + `flip-text`, 57 bytes
```
[ [a,b] [ unparse dup flip-text "5"""replace = ] filter ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TYy9CsIwFEb3PsVHZlviIPiDszjoIk6lQ4w3NRhjTG5An8Wli32nvo1CF6fDGc5590Zpvsdu2B0P2_1miZviSxWVbykhRGJ-hWg940rRk4NxNpRMT0YKzjJb3yLRI5PXv2BVFBJTKeUnsynnw6JGrSanBjWyDyomwjmHv4mYCSEiBac0YY0GxjqmiGYc9Fo5h2qUrhv5BQ)
Factor's ᵷuᴉddᴉʃɟ-ʇxǝʇ vocabulary considers 5 to be the same as itself when upside down, so I had to remove the 5's before checking for equality.
[Answer]
# [Raku](http://raku.org/), 53 bytes
```
{grep {.trans(~6890123457=>~9860):d eq .flip},$^a..$^b}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUChWq@kKDGvWKPOzMLSwNDI2MTU3NauztLCzEDTKkUhtVBBLy0ns6BWRyUuUU9PJS6p9n9xYqVCmoaBjoKhgYGB5n8A "Perl 6 – Try It Online")
Treats the number as a string, transliterates the rotatable numbers to their counterparts and deletes the rest, and tests that that string is equal to the reverse of the input string.
[Answer]
# Regex (ECMAScript or better) `m`, ~~165~~ ~~159~~ ~~164~~ 152 bytes
```
(?=((x{8}$|(?=.*?(?=(((x*)\5{8}(?=\5$))+x$))(x*)\6{99})(?=(\3x)(?:\7{5}(\7\7|\3{3}|xxx))(?!\3)(x*)\9{9}$)(?=(x*(?=\6|$))(|\6{6}x{9})\9$)\10)*$)
(?!x\1))
```
[Try it online!](https://tio.run/##TZHBcpswEIbvfgqcYcIuOATqGoMZ2acefMkhPUY5YFvBamWZEUqsGrjmAfqIfRFHkHomF2n17/7/7Df6VbwV9VbxSt/VFd8xdTjK3@zPRRHJTs4jK3@YCuBMlvf@BVYEwDRp57a2DP3VIIDxkc6sal905iIGxh6DmjRZ1mE/RafG3gs6b2Yd0Dmdt3TaTLvWGGNnV2M6/XRkTda5g8P4fV7S9lmtTUo6Y3t2wkUaR@i7OLI@Q2PEi39/xlAff2rFZQkY1oJvGSSTu@84cbxD6WFekyg/7blgAIIoVuwElwwQx0S@CoHNhsRRXhIR1pXgGjzHevgLgCRlKJgs9R6X39qW1w/FA3BSFapma6mhfIqeEa@NzdeGXMareNG3Ue/V8XSzlm@F4DuHy@pVL5ybQOQjQzzjhYpVrNDAMfCo9IIv0saufntbWTANPUWcW2@tFfDAm3jBJvCcf@9/@21fjsr@U5TDgaiQGbYF0@MNfPmZxNicbdCnecD7Xx@e4ucrYo88Plikq6BCUdR6LXfMBEHXXdIoddJoFEeRE42yxEnTUTZz0uwD "JavaScript (SpiderMonkey) – Try It Online")
Takes its input in unary, as the lengths of two strings of `x`s delimited by a newline (high end of range first, then low end of range). Returns its result as the list of matches' `\1` captures (each is also a string of `x`s whose length is the value).
This is adapted from my solution to [Numbers with Rotational Symmetry](https://codegolf.stackexchange.com/questions/77866/numbers-with-rotational-symmetry/249077#249077), which is a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") version of this, with `1` also treated as a rotationally-symmetric numeral. As described in that post, it's impossible for ECMAScript regex to match this sequence in decimal (it can't even match `a`n`b`n), but it's possible in unary.
The `m`ultiline flag is used so that `$`, which occurs many times in the regex, can be used instead of `\b` or `(?=¶)`, where `¶` is the delimiter (which needs to be a newline to take advantage of this `m` flag trick, but could be any non-word-character otherwise).
The regex works by looping the following logic:
1. Carve away both the leading and trailing digit if they are an allowed pair, or (for single-digit values) an allowed single digit.
2. Prevent the value sent to the next iteration from having any leading zeroes, since the regex operates on numbers, not strings, so any leading zeroes would be stripped. If it has a leading zero, add \$6\$ to the leading digit and \$9\$ to the trailing digit. If both were zero, meaning that inward up to that point, the input is symmetric, the modified number will now have a \$6\$ on the left and a \$9\$ on the right, preserving the trait of symmetry. If the trailing digit was nonzero (meaning the input is not a rotationally symmetric number), adding one of \$69, 609, 6009, ...\$ is guaranteed not to change it to one that is symmetric, because for example \$6009\$ could only be added to any number in the range \$0001\$ to \$0999\$ with a nonzero last digit, which can only yield a number in the range \$6010\$ to \$7008\$ with a last digit other than \$9\$, none of which are rotationally symmetric. This allows us to golf off 13 bytes, due to not needing the trailing zero check `(?=(x{10})*$)`. (This would not work with adding one of \$88, 808, 8008, ...\$ even though `(\6x){8}` is shorter than `\6{6}x{9}`, because \$88+8=96\$, \$808+098=906\$, \$8008+0998=9006\$, etc.)
```
(?= # Wrap the entire test in a lookahead so that after
# matching, the position will only advance one
# character forward for the next test.
( # \1 = tail = the number to be tested
(
x{8}$ # If tail==8, let tail=0 and end the loop
|
# Assert tail >= 10; find \3 = the largest power of 10 that is <= tail
(?=
.*? # Decrease tail by the minimum necessary to satisfy
# the following assertion:
(?=
# Assert tail is a power of 10 >= 10; \3 = tail
(((x*)\5{8}(?=\5$))+x$)
)
(x*)\6{99} # \6 = floor(tail / 100)
)
# Require tail is of the form 8.*8, 6.*9, or 9.*6
(?=
(\3x) # \7 = \3 + 1
(?:
\7{5}
(
\7\7 # 8.*8
|
\3{3} # 9.*6
|
xxx # 6.*9
)
)
(?!\3)
(x*)\9{9}$ # Assert tail is divisible by 10;
# \9 = tail / 10 == floor((N % \3) / 10)
)
# Set tail = \9, but if \9 is of the form 0.*0, the next iteration would
# not be able to see its leading zero, so change it to the form 6.*9 in
# that case, otherwise leave it unchanged. If \9 is of the form 0.*[1-9],
# don't go to the next iteration.
(?=
( # \10 = tool to make tail = \9 or \9 + \6*6 + 9
x*
# Assert that the leading digit of tail is not 0, unless tail==0
(?=
\6 # Assert that the leading digit of tail is not 0
| # or
$ # Assert that tail==0
)
)
# Iff necessary to satisfy the above, tail += \6*6 + 9
(
|
\6{6}x{9}
)
\9$ # tail = \9
)
\10 # tail = \9 or \9 + \6*6 + 9
)* # Execute the above loop as many times as possible,
# with a minimum of zero iterations.
$ # Assert tail==0
)
¶ # tail = low end of range
(?!x\1) # Assert \1 ≥ tail
)
```
# Regex (ECMAScript 2018 or better), ~~173~~ ~~167~~ ~~172~~ 160 bytes
`(?=((x{8}$|(?=.*?(?=(((x*)\5{8}(?=\5$))+x$))(x*)\6{99})(?=(\3x)(?:\7{5}(\7\7|\3{3}|xxx))(?!\3)(x*)\9{9}$)(?=(x*(?=\6|$))(|\6{6}x{9})\9$)\10)*$)(?<=(?<!x\1),.*))`
[Attempt This Online!](https://ato.pxeger.com/run?1=bVE9b9swEEVX_wo6MEKe5RBSDduSXdbokCFLhnYsC0SxaZkBTakUXRORtBadu3bx0P6H_JV27C8pJTeAhwz8uHvvHt_xfvzU-Vocn0oWLgx7L7JrV5AP1kidUZMe7n7t7eYq_n0kS0aIq-JmUPsrHS67BHFD4BOf9RGfDAAC57cuO62SpIGWxcfOn3M-qyYN4TM-q_m4Gje1c85zl30-PlUkVdIMugo3bPWmdatVe6Vp4zzmGQPgUQjDlvWG-dV3PIIRHQKcfP559e2OlkquBIlGVx5COMOwMOLzXhpBsBHpWkktMNCVv1txo60wm9TzK6mLvZ0XJl-JsqSlXUvdAM01wV3FSLG3VcYULQslLcHI68oNIZplVAmd2S302eu6luVtektSVqSmbOVJ9jH8BPAM3J8DkQfAbk1-uLjRX1Il1-jkAl0EatE785LvLT0YaQUh5RJzjecYQ6ACjP5-_d5aKVnU2tkxgh2mRhS-O5JCgEc4OMvcA9Bdalfbd0oRA1A9-rlvckMeUL5BOx9fXr74bNfvo3_kZRQHD76b549omub_QI5PcYjiMO6FKArDXhyjZNqLE5RMTvg_ "JavaScript (Node.js) - Attempt This Online")
Takes its input in order of {low end of range, high end of range}, with a comma delimiter. Otherwise the same as the above.
("ECMAScript 2018 or better" includes just two other engines: .NET and Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/), but I haven't made test harnesses in them for this type of regex yet.)
The part of this regex that differs from the one above:
```
(?=
( # \1 = tail = the number to be tested
```
```
)
(?<=
(?<!x\1) # Assert \1 ≥ head
,.* # head = low end of range; assert \1 was captured
# from inside high end of range
)
)
```
] |
[Question]
[
You're playing [TF2](https://wiki.teamfortress.com/wiki/Voice_commands), and you want to make a bot that will just put voice commands into the chat box. Typically, to "call" a voice command, one would press a key (`Z`, `X`, or `C`) and a number (`1-8`) to create an audio dialogue. Here are the text equivalents of the audios displayed when pressing these keys:
```
Voice Menu 1
Default key: Z
==============
1. MEDIC!
2. Thanks!
3. Go Go Go!
4. Move Up!
5. Go Left
6. Go Right
7. Yes
8. No
Voice Menu 2
Default key: X
==============
1. Incoming
2. Spy!
3. Sentry Ahead!
4. Teleporter Here
5. Dispenser Here
6. Sentry Here
7. Activate ÜberCharge!
8. MEDIC: ÜberCharge Ready ; ignore the MEDIC: bit
Voice Menu 3
Default key: C
==============
1. Help!
2. Battle Cry ; see bonus
3. Cheers
4. Jeers
5. Positive
6. Negative
7. Nice Shot
8. Good Job
```
---
**Objective** Given an input string (or input character + character, character + number, etc.; whatever is most relevant/convenient to your language), take the respective message from the chart above and output it. If the input is invalid, do not output anything. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins.
## Example IOs
```
> Z3
Go Go Go!
> Z1
MEDIC!
> Z5
Go Left
> X8
ÜberCharge Ready
> X7
Activate ÜberCharge!
> C1
Help!
> C8
Good Job
```
## Bonuses/penalties
These bonuses are applied in the order of appearance in this list.
* -1 byte for every byte used in the physical text of `C2` (i.e., `Battle Cry`); I will not add points for errors on `C2`, so be creative if you wish! (By physical text, I mean every byte used for constructing (not outputting) the string. For example, for `STDOUT "AHHHHHHHH!"`, `"AHHHHHHHH!"` is free, but nothing else is. In `console.log(`${v="Tha"}t's too you, you idiot!`)`, the free characters are ``"Tha" t's too you, you idiot!``. These characters are the only ones that make up part of the string and their respective quotes.)
* -15% if your program takes input and outputs the respective entry until an invalid input is given, at which point your program should terminate.
* +5 bytes for every capitalization, punctuation, or spacing error
* +10 bytes for every wrong/missing letter
* -20 bytes if you can take a string like "X5C3Z6..." and output each respective message, separated by newlines.
* -30 bytes if you take a class input (either `Scout`, `Soldier`, `Pyro`, `Demoman`, `Heavy`, `Engineer`, `Sniper`, `Medic`, or `Spy`) and verify if the class can say the given expression. The only expression that applies is `X8`, i.e., `MEDIC: ÜberCharge Ready`; only the Medic can say this. If any other class *besides* the medic attempts to say this, do not output anything. (The names are case insensitive.)
## Leaderboard
```
var QUESTION_ID=63370,OVERRIDE_USER=8478;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]
# CJam, -48 bytes
```
"\"MEDIC!
Thanks!
Go Go Go!
Move Up!
Go Left
Go Right
Yes
No
Incoming
Spy!
Sentry Ahead!
Teleporter Here
Dispenser Here
Sentry Here
Activate ÜberCharge!
Help!
Cheers
Jeers
Positive
Negative
Nice Shot
Good Job
\"N/Fleu\"MEDIC\"=\"ÜberCharge Ready\"*tq2/\"ZXC\"9,1>sm*f{\a#-2$=_S=W$@?N}\?"_~
```
The source code is **292 bytes** long, can handle multiple inputs (**-20 bytes**) and checks for the class name (**-30 bytes**). Furthermore, I have chosen
```
"MEDIC!
Thanks!
Go Go Go!
Move Up!
Go Left
Go Right
Yes
No
Incoming
Spy!
Sentry Ahead!
Teleporter Here
Dispenser Here
Sentry Here
Activate ÜberCharge!
Help!
Cheers
Jeers
Positive
Negative
Nice Shot
Good Job
"N/Fleu"MEDIC"="ÜberCharge Ready"*tq2/"ZXC"9,1>sm*f{\a#-2$=_S=W$@?N}\?
```
as battle cry, so the first **290 bytes** that are used to push this string are free.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22%5C%22MEDIC!%0AThanks!%0AGo%20Go%20Go!%0AMove%20Up!%0AGo%20Left%0AGo%20Right%0AYes%0ANo%0AIncoming%0ASpy!%0ASentry%20Ahead!%0ATeleporter%20Here%0ADispenser%20Here%0ASentry%20Here%0AActivate%20%C3%9CberCharge!%0A%0AHelp!%0A%20%0ACheers%0AJeers%0APositive%0ANegative%0ANice%20Shot%0AGood%20Job%0A%5C%22N%2FFleu%5C%22MEDIC%5C%22%3D%5C%22%C3%9CberCharge%20Ready%5C%22*tq2%2F%5C%22ZXC%5C%229%2C1%3Esm*f%7B%5Ca%23-2%24%3D_S%3DW%24%40%3FN%7D%5C%3F%22_~&input=Medic%0AX8).
[Answer]
# D, 692 bytes
731 - 39(for `"B"~"a"~"t"~"t"~"l"~"e"~" "~"C"~"r"~"y"`)
```
import std.stdio;import std.conv;import std.utf;void main(char[][] a){char t=a[1][0];int n=to!int(a[1][1])-48;string G="Go ";char z='Z';char x='X';char c='C';string H=" Here";string U=to!string('\u00DC');string[int][char]o;o[z][1]="MEDIC!";o[z][2]="Thanks!";o[z][3]=G~G~"Go!";o[z][4]="Move Up!";o[z][5]=G~"Left";o[z][6]=G~"Right";o[z][7]="Yes";o[z][8]="No";o[x][1]="Incoming";o[x][2]="Spy!";o[x][3]="Sentry Ahead!";o[x][4]="Teleporter"~H;o[x][5]="Dispenser"~H;o[x][6]="Sentry"~H;o[x][7]="Activate "~U~"berCharge!";o[x][8]=U~"berCharge Ready";o[c][1]="Help!";o[c][2]="B"~"a"~"t"~"t"~"l"~"e"~" "~"C"~"r"~"y";o[c][3]="Cheers";o[c][4]="Jeers";o[c][5]="Positive";o[c][6]="Negative";o[c][7]="Nice Job";o[c][8]="Good Job";write(o[t][n]);}
```
*I like D a lot.*
## D, 724 bytes w/ Classes
793 - 39(same as above) - 30(for class option)
```
import std.stdio;import std.conv;import std.utf;void main(char[][] a){char t=a[1][0];int n=to!int(a[1][1])-48;string G="Go ";char z='Z';char x='X';char c='C';string H=" Here";string U=to!string('\u00DC');string[int][char]o;o[z][1]="MEDIC!";o[z][2]="Thanks!";o[z][3]=G~G~"Go!";o[z][4]="Move Up!";o[z][5]=G~"Left";o[z][6]=G~"Right";o[z][7]="Yes";o[z][8]="No";o[x][1]="Incoming";o[x][2]="Spy!";o[x][3]="Sentry Ahead!";o[x][4]="Teleporter"~H;o[x][5]="Dispenser"~H;o[x][6]="Sentry"~H;o[x][7]="Activate "~U~"berCharge!";o[x][8]=U~"berCharge Ready";o[c][1]="Help!";o[c][2]="B"~"a"~"t"~"t"~"l"~"e"~" "~"C"~"r"~"y";o[c][3]="Cheers";o[c][4]="Jeers";o[c][5]="Positive";o[c][6]="Negative";o[c][7]="Nice Job";o[c][8]="Good Job";if(a.length>2){if(!(a[2]!="Medic"&&t==x&&n==8))goto P;}else P:write(o[t][n]);}
```
This version lets you input a class for `X8`. Use it like `tf2 X8 Medic`. It will print the correct message if you use the correct class. *Yes, this does use a **goto**. Kill it now.*
[Answer]
# Prolog, ~~371~~ 362 - 11 = 351 bytes
My first attempt at code golf.
I chose a language which seem to be underrepresented here.
I'm far from an expert at prolog, so this can most likely be improved a lot.
I did not go for any optional bonuses. I tried for the 15% one but it cost me more than I gained.
```
a(z,['MEDIC!','Thanks!','Go Go Go!','Move Up!','Go Left','Go Right','Yes','No']).
a(x,['Incoming','Spy!','Sentry Ahead!','Teleporter Here','Dispenser Here','Sentry Here','Activate ÜberCharge!','ÜberCharge Ready']).
a(c,['Help!','For Pony!','Cheers','Jeers','Positive','Negative','Nice Shot','Good Job']).
r:-read(X),read(Y),a(X,Z),nth1(Y,Z,A),write(A),1=2.
```
## Try it out
You can try it out online [here](http://swish.swi-prolog.org/).
1. Create new program
2. Paste code
3. As query, just use 'r' without quotes.
Input is first a letter then a number.
**Example:**
Input: z
Press Send
Input 3
Press Send
Outputs: Go Go Go!
**Edit:**
Saved 9 bytes with input from @Fatalize
[Answer]
# Perl, 280 - 15% - 20 = 218 bytes
```
#!perl -l
@Z=<0 {MEDIC,Thanks,Go_Go_Go,Move_Up}! Go_{Left,Right} Yes No>;
@X=<0 Incoming Spy! Sentry_Ahead! {Teleporter,Dispenser,Sentry}_Here Activate_ÜberCharge! ÜberCharge_Ready>;
@C=<0 Help! You_Fight_Like_A_Dairy_Farmer! {Ch,J}eers {Posi,Nega}tive Nice_Shot Good_Job>;
y/_/ /,print while$_=${getc=~s/
//r||getc}[getc]
```
Counting the shebang as one, input is taken from stdin. The newlines after semicolons are not necessary, and have been left for readability.
---
**Sample Usage**
```
$ echo Z3 | perl tf2.pl
Go Go Go!
$ echo X7 | perl tf2.pl
Activate ÜberCharge!
$ echo C2 | perl tf2.pl
You Fight Like A Dairy Farmer!
$ echo X5C3Z6 | perl tf2.pl
Dispenser Here
Cheers
Go Right
```
---
**Interactive Mode**
The code may also be run in interactive mode, in which case it will continue accepting input until an invalid input is given.
```
$ perl tf2.pl
Z2
Thanks!
X3
Sentry Ahead!
C4
Positive
V5
```
---
# Perl, 331 - 354 (C2) - 20 - 30 = -73 bytes
```
#!/usr/bin/env perl -l
@Z=<0 {MEDIC,Thanks,Go_Go_Go,Move_Up}! Go_{Left,Right} Yes No>;
@X=(<0 Incoming Spy! Sentry_Ahead! {Teleporter,Dispenser,Sentry}_Here Activate_ÜberCharge!>,{Medic.$/,'ÜberCharge Ready'});
@C=(0,'Help!',(join!open(0),<0>),<{Ch,J}eers>,<{Posi,Nega}tive>,Nice_Shot,Good_Job);
print%{$_=@{$`}[<>=~/.\K(.)/]}?$_->{$c}:y/_/ /rwhile$c=<>
```
Supports multiple entries, and filtering by class. The battle cry I've chosen is the entire source code. It can be seen that every byte of the source is necessary for the *construction* of this particular battle cry - were any byte missing, the battle cry would be different. This includes the entire shebang, which by convention is counted as one.
---
**Sample Usage**
```
$ more in.dat
Medic
X8
Spy
X8
Heavy
C8
Pyro
Z2
$ perl tf2.pl < in.dat
ÜberCharge Ready
Good Job
Thanks!
```
[Answer]
# [TeaScript](https://github.com/vihanb/TeaScript), 225 - 6 = 219 [bytes](https://en.m.wikipedia.org/wiki/ISO/IEC_8859)
```
b=xS(1)-1
x0¦'Z'?æMEDIC!,Tnks!,Go Go Go!,Move Up!,Go Left,Go Right,Y,No`.s`,`[b]:x0¦'X'?æîa,Spy!,SÀ^y AÊ%!,Tà({Zr He,DáÀ He,SÀ^y He,Acve ürCrge!`.s`,`[b]:x0¦'C'?æHelp!,PÇës!,CÊ8s,JÁÄ,PoÐÓve,Negive,Ni St,Good Job`.s`,`[b]:''
```
As short as I can get it. None of the bonuses save any bytes.
[Try it online](http://vihanserver.tk/p/TeaScript/). If the outputs show up weird for you, tell me and I'll add a hex dump too deal with all the special characters.
[Answer]
# Mathematica, 368 - 24 = 344 bytes
```
Check[StringExtract["MEDIC!,Thanks!,Go Go Go!,Move Up!,Go Left,Go Right,Yes,No;Incoming,Spy!,Sentry Ahead!,Teleporter Here,Dispenser Here,Sentry Here,Activate ÜberCharge!,ÜberCharge Ready;Help!,Why am I saying this...,Cheers,Jeers,Positive,Negative,Nice Shot,Good Job",";"-><|"Z"->1,"X"->2,"C"->3|>[#~StringTake~1],","->FromDigits[#~StringDrop~1]]/._Missing->"",""]&
```
[Answer]
# AppleScript, (595-18)\*.85 = 490.45 Bytes
I beat *somebody*.
```
set a to{"MEDIC!","Thanks!","Go Go Go!","Move Up!","Go Left","Go Right","Yes","No","Incoming","Spy!","Sentry Ahead!","Teleporter Here","Dispenser Here","Sentry Here","Activate ÜberCharge!","ÜberCharge Ready","Help!","FOR APPLESCRIPT!","Cheers","Jeers","Positive","Negative","Nice Shot","Good Job"}
set c to true
considering case
repeat while c
set b to(display dialog""default answer"")'s text returned's characters
set n to 0
set k to item 1 of b
if k="C" then
set n to 0
else if k="X" then
set n to 8
else if k="Z" then
set n to 16
else
exit
end
display dialog(item(n+item 2 of b)of a)
end
end
```
Basically, I push all the items into an array. I get input through a text window (see gif below) and then an output window displays the referenced text.
[](https://i.stack.imgur.com/xACth.gif)
The bonuses that apply are for the Battle Cry and the looping until invalid.
[Answer]
# Vitsy, 343 - 15 - 20 = 308 Bytes
I only qualify for the Battle Cry bonus and separating the segments by newline. My language can't do that other stuff. ;(
```
<OaZm+-1;)D]++2f[)-V'Z']+9[)-V'X']+1[)-V'C'Vi0;)/8^/21^2D-*68i
'!CIDEM'
'!sknahT'
'!oG oG oG'
'!pU evoM'
'tfeL oG'
'thgiR oG'
'seY'
'oN'
'gnimocnI'
'!ypS'
'!daehA yrtneS'
'ereH retropeleT'
'ereH resnepsiD'
'ereH yrtneS'
'!egrahCrebÜ etavitcA'
'ydaeR egrahCrebÜ'
'!pleH'
'syawlA ystiV'
'sreehC'
'sreeJ'
'evitisoP'
'evitageN'
'tohS eciN'
'boJ dooG'
```
This uses method structuring to push items to the stack according to a specific reference. Since it's easier to understand the way I originally wrote it, I have put the original code down below. The only difference is that the one above uses the `<` character to loop around the line backwards, one of the special ways that Vitsy loops around the line. The explanation for the top layer of code (in executed order) is below:
```
i86*-D1-D8M-);0iV'C'V-)[1+]'X'V-)[9+]'Z'V-)[f2++]D(;1-+mZ
i86*- Get the number value of the ASCII input.
D1-D8M-); If the number is within the range 0-8, continue the program. Otherwise, end execution.
0 Placeholder of zero.
iV Get the character component and save it as a global variable.
'C'V-)[1+] If it's 'C', add 1
'X'V-)[9+]'Z'V-)[f2++] Do the same things with 'X' and 'Z', adding 1 and a multiple of 8.
D(; If after all this, the number is still zero, end execution.
1-+ Subtract one and add the components.
m Execute that line number.
Z Print everything in the stack to STDOUT and quit.
```
[Answer]
# Haskell, 397 -15% - 20 = 317.45 bytes
```
v=[('Z',["MEDIC!","Thanks!","Go Go Go!","Move Up!","Go Left","Go Right","Yes","No"]),('X',["Incoming","Spy!","Sentry Ahead!","Teleporter Here","Dispenser Here","Sentry Here","Activate ÜberCharge!","ÜberCharge Ready"]),('C',["Help!","Battle Cry","Cheers","Jeers","Positive","Negative","Nice Shot"])]
h(Just k)=k
m(x:y:s)=((h$lookup x v)!!((fromEnum y)-49))++('\n':m s)
m""=""
main=interact$concat.map m.lines
```
The input is taken from the standard input and it will output messages until there is no more input or an invalid input is given.
*P.S. :* Changing the order in which to apply the bonuses, according to a comment from the OP.
] |
[Question]
[
In 2D Mario, Bullet Bill cannons are two units tall. The Bullet Bill is fired out of the upper unit and travels in a straight line (parallel to the x axis).
Mario is two units tall when standing up and one unit tall when ducking. His jump height is three units. It takes him 0.5 seconds to reach the full height and 0.5 seconds to come back down.
### Challenge
Write a program that helps Mario avoid an incoming Bullet Bill. He may have to jump, duck, or do nothing.
### Input
The input will come in the format `[bullet_bill_position] [direction] [speed] [mario_position]`.
* `bullet_bill_position` consists of two space-separated integers, x and y. This represents the coordinates of the **upper unit** of the cannon. The bullet bill will fire from this location.
* `direction` will either be `left` or `right` (string).
* `speed` is the speed of the Bullet Bill in **units per second**.
* `mario_position` consists of x and y and represents the coordinates that Mario is **standing on**.
### Output
`[action] [wait_time]`
* `action` will be one of three strings: `duck`, `jump`, or `nothing`.
* `wait_time` only applies to `jump`. It represents how long Mario should wait before jumping over the Bullet Bill. If `action` is not `jump`, this will be left blank.
### Notes
* The ground will always be right underneath Mario's feet.
* Bullet Bills are only one unit tall and one unit wide. Mario will be safe if it passes one unit above his head.
* Mario will be safe if he lands on the Bullet Bill. Hitting the side or bottom will kill him.
* There will often be more than one solution. You only have to output one of them.
* Numerical input will always be **integers**. However, output may sometimes need to have floats/doubles.
## Test Cases
**Input**: `5 1 left 2.5 0 0`
**Possible Output**: `jump 1.5`
**Explanation**: The Bullet Bill will be at Mario's feet in 2 seconds. Mario will jump at 1.5 and touch back down at 2.5. The Bullet Bill passed safely underneath him.
**Another Possible Output**: `jump 1`
**Explanation**: If Mario jumps at 1, he will touch back down at 2 and land on the Bullet Bill.
**Input**: `0 3 right 100 5 0`
**Possible Output**: `nothing`
**Explanation**: The Bullet Bill will pass very quickly over Mario's head. He will be safe.
**Input**: `0 2 right 1 5 0`
**Output**: `duck`
**Explanation**: The Bullet Bill will go where Mario's head would've been.
## Rules
* You can write a full program or function.
* I/O should be to stdin and stdout.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Your score is the number of bytes. The solution with the lowest score in one week will win. Good luck!
[Answer]
# Python, 72 68 66 bytes
We can ignore left/right - if we assume it's always pointed at us we'll always take the right action. Then if our assumption was wrong we did a useless jump/duck, but that doesn't matter - we'll still be safe.
Similarly, there is no incentive to do nothing. Rather, it's shorter code to always duck, and jump when necessary. Ducking will only be unsafe if the bullet bill is exactly one above the block we're standing on. In that case we will take our x position, bullet bill's y position, take the absolute difference, divide by bullet bill's speed and jump 0.2 seconds before that.
```
lambda a,b,_,s,x,y:["duck","jump "+`max(0,abs(a-x)/s-.2)`][y+1==b]
```
Call like this:
```
f=lambda a,b,_,s,x,y:["duck","jump "+`max(0,abs(a-x)/s-.2)`][y+1==b]
f(5, 1, "left", 2.5, 0, 0)
```
[Answer]
## CJam, 84 80 61 bytes
This is my first program for this, literally just learned CJam last night, for this purpose only. I'm also new to this site's formatting, help would be great with that.
```
ri:Xri:Yrri:Sri:Ari:B];BY={"jump"XA<{AX)-S/}{X(A-S/}?}"duck"?
```
It's **no longer** longer than the previous answer, but I'm **still** posting it because I'd like tips and stuff.
**Explanation**
```
ri:X - Sets Bullet X to X.
ri:Y - Sets Bullet Y to Y.
r - Omits direction.
ri:S - Sets speed to S.
ri:A - Sets Mario X to A.
ri:B - Sets Mario Y to B.
]; - Clears the stack.
BY= - Due to the ? at the end, executes the first block if true (if B=Y) or the second block (in this case "duck") if false.
{"jump" - Outputs jump.
XA< - Due to the ? after the next two blocks, executes the first block if true (if X<A) or the second block if false.
{AX)-S/}- Solves and outputs (A-(X+1))/S.
{X(A-S/}- Solves and outputs ((X-1)-A)/S.
?} - Executes block A if the condition before it is true, or block B if not.
"duck" - Outputs duck.
? - Executes block A if the condition before it is true, or block B if not.
```
There's an online interpreter [here](http://cjam.aditsu.net/#code=ri%3AXri%3AYrri%3ASri%3AAri%3AB%5D%3BBY%3D%7B%22jump%22XA%3C%7BAX)-S%2F%7D%7BX(A-S%2F%7D%3F%7D%22duck%22%3F&input=8%203%20ebolaids%202%201%203) if needed.
[Answer]
# Haskell, 61 Bytes
I found that there's no point in doing nothing. Jump if Bill is at or bellow Mario's feet, otherwise duck.
```
f a b _ c d e|b<e+2="Jump "++(show$abs(a-d)/c-0.5)|1<2="Duck"
```
] |
[Question]
[
Roll 3 dice, count the two highest two values and add them to the result. *Every 1 must be rolled **once** again.*
Now show the average throw after 1000000 tries and the probabilities for each result occurring:
# Desired Result:
>
> avg(9.095855)
>
> 2: 0.0023
>
> 3: 0.0448
>
> 4: 1.1075
>
> 5: 2.8983
>
> 6: 6.116
>
> 7: 10.1234
>
> 8: 15.4687
>
> 9: 18.9496
>
> 10: 19.3575
>
> 11: 16.0886
>
> 12: 9.8433
>
>
>
[Answer]
# Mathematica 150 146 94 115 108
Edit: This version is a suggestion from @belisarius. Much shorter and faster than my own code (found in the earlier versions).
```
r=RandomInteger;t=Tr/@Rest/@Sort/@(5~r~{10^6,3}/. 0:>r[5]);
{Mean@t+2,{#[[1]]+2,#[[2]]/10^4}&/@Sort@Tally@t}//N
```
>
> {9.09684, {{2., 0.0028}, {3., 0.0456}, {4., 1.1097}, {5., 2.8752}, {6., 6.1246}, {7., 10.122},
>
> {8., 15.513}, {9., 18.8956}, {10., 19.3514}, {11., 16.074}, {12., 9.8861}}}
>
>
>
[Answer]
## APL ~~110~~ 103
```
r←11⍴0
i←1
l:r←r+(j←1+⍳11)=+/2↑n[⍒n←3↑((3↑x)~1),3↓x←?6⍴6]
i←i+1
→(i≤k←10*6)/l
((+/r×j)÷k)
j,[1.1]r÷10*4
```
I have included the results of three runs to demonstrate the degree of repeatability over 1000000 iterations.
```
9.092186 9.093053 9.093897
2 0.0022 2 0.0019 2 0.0023
3 0.0442 3 0.0477 3 0.0452
4 1.1064 4 1.0755 4 1.0866
5 2.8808 5 2.887 5 2.8771
6 6.1472 6 6.1864 6 6.1485
7 10.1532 7 10.1163 7 10.1575
8 15.6376 8 15.5511 8 15.5834
9 18.8736 9 18.918 9 18.873
10 19.2771 10 19.3763 10 19.3315
11 15.9702 11 16.0225 11 16.0529
12 9.9075 12 9.8173 12 9.8419
```
[Answer]
## Python (~~207 194~~ 189)
```
from random import*
a=lambda:randint(13,48)/7
r=range
x=[0]*13
s=0
for i in r(10**6):b=sum(sorted([a(),a(),a()])[1:]);x[b]+=1e-4;s+=b/1e6
print'avg(%f)'%s
for i in r(2,13):print`i`+':',x[i]
```
Algorithm:
```
a is the RNG, x is the list which contains the results, s is the sum. r is for code-golfing purposes.
1. Iterate through steps 2-6 1,000,000 times:
2. Get three random numbers from `a` and put them in a list.
3. Sort the list. (list is now in ascending order)
4. Take the sum of every item but the first item in the list. Call this number b.
5. Increment the (b)th index of x by 1e-4 (1/10000).
6. Increment s by b * 1e-6 (1/1000000).
7. Print out s.
8. For each item in x (excluding the first two), output the item.
```
[Answer]
# APL, 67
```
÷1e2÷+/×/x←⍉↑n,1e4÷⍨+/(n←⊂⍳12)∘.={+/2↑x[⍒x←{⍵=1:?6⋄⍵}¨?3⍴6]}¨⍳1e6⋄x
```
### Explanation
* `⍳1e6` Create array from 1 to milliion,
* `¨` and for each of those
* `{+/2↑x[⍒x←{⍵=1:?6⋄⍵}¨?3⍴6]}` do a roll, re-roll 1s, and sum the high
dices:
`?3⍴6` roll 3 dice,
`¨` and for each die
`{⍵=1:?6⋄⍵}` if it is a 1, replace it by a re-roll result, else don't change it.
`x←` Save the result in (local) variable `x`,
`x[⍒x`...`]` sort it in descending order,
`+/2↑` take the first 2 items (high dices) and return the sum.
* `+/(n←⊂⍳12)∘.=` Create array of the no. of times each sum appears,
* `1e4÷⍨` divide by 10000,
* `⍉↑n,` insert a row to the top with numbers 1 to 12, and matrix transpose it. The result would be something like the table in the question.
* `x←` Save that in (global) variable `x`.
* `+/×/` Calculate the average of the million rolls by multiplying the columns, summing those...
* `÷1e2÷` and divide by 100.
The result is displayed (by default)
* `⋄x` Finally, output `x`
### Example output
```
9.097008
1 0
2 0.0028
3 0.0466
4 1.0914
5 2.8873
6 6.0957
7 10.1242
8 15.6108
9 18.8688
10 19.2834
11 16.0979
12 9.8911
```
### Notes
-5 chars if allowed to represent 10% by 0.1 instead of 10
-3 chars if allowed to use probabilistic approach (like o\_o's) instead of explicit re-roll
+12 chars if the "avg()" is required
+2 chars if the "1" row needs to be removed
+8 chars if the colon is required in output
[Answer]
## Python, 262
```
import random
r=random.randint
def f():n=r(1,6);return n if n>1 else r(1,6)
l=[0.0]*13
for i in range(10**6):l[sum(sorted([f(),f(),f()])[1:])]+=1
m=zip(*[range(2,13),l[2:]])
print'avg('+`sum([a*b for a,b in m])/10**6`+')'
for e in m:print`e[0]`+': '+`e[1]/10**4`
```
results:
```
avg(9.098773)
2: 0.0021
3: 0.044
4: 1.0872
5: 2.89
6: 6.0982
7: 10.133
8: 15.5
9: 18.949
10: 19.2908
11: 16.0953
12: 9.9104
```
[Answer]
# C# (599)
```
using System;using System.Collections.Generic;using System.Linq;namespace P{public class D{Random r=new Random(System.DateTime.Now.Millisecond);public static void Main(){var d=new D();d.G();}public int R(){return r.Next(1,7);}public int RD(){var e=new List<int>();for(var i=0;i<=2;i++){var v = R();e.Add(v != 1 ? v : R());}return e.OrderByDescending(d=>d).Take(2).Sum();}public void G(){const double l = 1000000;var t = new Dictionary<int,double>();for(var i=2;i<=12;i++)t.Add(i,0);for(var i=0;i<l;i++){var s=RD();t[s]=t[s]+1;}foreach(var a in t){Console.WriteLine(a.Key+": "+(a.Value)/10000.0);}}}}
```
[Answer]
## Perl (177 169 168)
```
sub r{1+int rand 6}
for(1..1e6){@l=sort map{($q=r)>1?$q:r}(1..3);++$s{$y=$l[1]+$l[2]};$t+=$y}
print"avg(".$t/1e6.")\n";print"$_: ".$s{$_}/1e4."\n"for sort{$a<=>$b}keys%s
```
*(NOTE: one-liner wrapped for clarity)*
stacked output of three consecutive runs:
```
avg(9.09432) avg(9.094793) avg(9.092179)
2: 0.002 2: 0.0026 2: 0.0023
3: 0.0448 3: 0.0454 3: 0.0436
4: 1.0872 4: 1.0904 4: 1.0944
5: 2.8834 5: 2.8933 5: 2.8842
6: 6.1387 6: 6.127 6: 6.1854
7: 10.1648 7: 10.177 7: 10.1669
8: 15.498 8: 15.5758 8: 15.508
9: 18.9483 9: 18.8391 9: 18.9236
10: 19.3557 10: 19.278 10: 19.3234
11: 16.0589 11: 16.0863 11: 16.0256
12: 9.8182 12: 9.8851 12: 9.8426
```
### UPDATES
* shortening 1: eliminate `$n=1e6` (insp. by Joe)
* shortening 2: del space in `keys %s`
[Answer]
## R - 98
```
S=sample
D=matrix(S(6,3e6,T),3)
D[D<2]=S(6,3e6,T)
A=colSums(D)-apply(D,2,min)
mean(A)
table(A)/1e4
```
Like some other answers, my output is not in the same format as the OP; I was not sure if it was a strict requirement or not:
```
[1] 9.095695
A
2 3 4 5 6 7 8 9 10 11 12
0.0018 0.0426 1.1008 2.8748 6.1438 10.1147 15.5406 18.9276 19.3525 16.0126 9.8882
```
[Answer]
# TI-BASIC, not an entry
This does not meet the spec, because it doesn't show the result distribution or directly roll integers between 1 and 6, but I found a slightly clever algorithm for computing the average in one line. To get the largest two dice rolls, we pad a number larger than any of the dice rolls onto the list of three rolls, and take the median, which will be the average of the middle two numbers (two highest dice rolls). Then we just multiply by 2 to get the sum.
```
2ᴇ~6Σ(median(int(augment(15+36rand(3),{99})/7)),X,1,ᴇ6
```
Based on the speed of [SuperJedi224's answer](https://codegolf.stackexchange.com/a/49477/39328) to "Death by Shock Probe", it will take over 12 hours to finish running.
[Answer]
# LUA (307)
```
function r()
m=math.random(1,6)
if(m==1)then return math.random(1,6)end
return m
end
e={}
s=0
o=1000000
for i=2,12 do e[i]=0 end
for t=1,o do
d={}
for i=1,3 do d[i]=r() end
table.sort(d)
x=d[2]+d[3]
e[x]=e[x]+1
s=s+x
end
print("avg("..s/o..")")
for i=2,12 do print(i..": "..e[i]/o*100) end
```
My first one ;)
[Answer]
Seems to be a basic problem with the calculation and results I am seeing here.
If you must reroll the dice (all 3 or just one) when you get a 1 showing up, then the lowest possible sum of die faces you could ever have would be 4. That is, any face that shows a 1 will be rerolled. Which specifically requires that the lowest possible face is a 2. You could avoid the rerolling by generating random values from 2 .. 6, but that might be missing the point.
What this means: If you are reporting values for 2 or 3 as the sum of the faces, these are 1+1 and 2+1 respectively, the specification excludes this possibility.
That is, unless the "you must reroll the dice" only applies to the first instance of a 1. In which case, you may have a 1+1, and 2+1 case (so you'd get sums of 2 and 3 as possible answers).
[Answer]
```
map{@f=(sort((&r,&r,&r)[1,2]));$d[$f[0]+$f[1]]++}(1..1E6);
map{$s+=$d[$_]*$_}(0..$#d);print"avg(".$s/1E6.")\n";map{print"$_:
".$d[$_]/1E4."\n"}(0..$#d);
sub r{$x=1+int(rand 6);$x>1?$x:&r}
~/play/golf/dice$ perl dice.pl
avg(8.000533)
0: 0
1: 0
2: 0
3: 0
4: 3.9796
5: 8.0376
6: 11.9607
7: 16.0064
8: 20.0094
9: 15.9636
10: 12.0582
11: 8.0057
12: 3.9788
```
[Answer]
Now a more optimized version, with a shifted RNG (no reroll), and shortened statistics calcs, also exploiting the ordering due to the ascii nature of single integers.
```
map{@f=(sort((&r,&r,&r)[1,2]));$i=$f[0]+$f[1];$d[$i]++;$s+=$i}(1..1E6);
print"avg(".$s/1E6.")\n";map{print"$_: ".$d[$_]/1E4."\n"}(0..$#d);
sub r{2+int(rand 5)}
```
As you can see, printing uses almost as much space as computing here. If you'd like a simpler output, this would save characters.
```
avg(8.000901)
0: 0
1: 0
2: 0
3: 0
4: 4.0007
5: 7.9769
6: 11.9652
7: 16.0226
8: 20.0156
9: 16.0389
10: 11.9983
11: 7.9861
12: 3.9957
```
[Answer]
## C ~~222 204~~ 203
204: Updates from ugoren's comment, recycled more global vars, changed `D()` into a macro to save a `return` and three pairs of `()`.
203: Moved the first `printf` into the `for` to save a semicolon.
**[See it run in Codepad](http://codepad.org/HNvBWe8R)**
```
#define D (t=rand()%6)?t:rand()%6
j,i,f[11],s,t;M(a,b,c){t=a<b?a:b;t=c<t?c:t;t=a+b+c-t;}main(){for(;j++<1e6;M(D,D,D),s+=t+2)++f[t];for(printf("avg(%f)\n",s/1e6);i<11;++i)printf("%d: %f\n",i+2,f[i]/1e4);}
```
---
```
#define D (t=rand()%6)?t:rand()%6
j,i,f[11],s,t;
M(a,b,c)
{
t=a<b?a:b;
t=c<t?c:t;
t=a+b+c-t;
}
main()
{
for(;j++<1e6;M(D,D,D),s+=t+2)
++f[t];
for(printf("avg(%f)\n",s/1e6);i<11;++i)
printf("%d: %f\n",i+2,f[i]/1e4);
}
```
```
avg(9.095219)
2: 0.001600
3: 0.045200
4: 1.100000
5: 2.903400
6: 6.124600
7: 10.112100
8: 15.556000
9: 18.876400
10: 19.358200
11: 16.053800
12: 9.868700
Press any key to continue . . .
```
[Answer]
## C - 200
I didn't bother to re-roll on 1, instead I used the probability distribution (1/36 chance of rolling 1, 7/36 chance of rolling anything else). Hopefully this is acceptable. Newline has been inserted for clarity.
```
#define D 6-rand()%36/7
a,b,c,t,u,w,y[13];
main(v,q){srand(q);for(;v++<=1e6;u=(a=D)<(b=D)?a:b,w+=t=a+b+(c=D)-(u<c?u:c))y[t]++;
printf("avg(%f)\n",w/1e6);for(v=1;++v<13;)printf("%d: %f\n",v,y[v]/1e4);}
```
After compilation (gcc -O3) - 1 run
```
avg(9.096896)
2: 0.002200
3: 0.043100
4: 1.093900
5: 2.891000
6: 6.110100
7: 10.091400
8: 15.605000
9: 18.936500
10: 19.258800
11: 16.047100
12: 9.920800
```
[Answer]
## CoffeeScript, 146
```
r=()->~~(6*Math.random())
t=i=0;s=[];(a=[r()||r(),r()||r(),r()||r()].sort();t+=b=2+a[1]+a[2];s[b]=1e2/z+(s[b]||0))while++i<z=1e6;console.log t/z,s
```
Outputs the average and an object:
```
9.09456
[2: 0.0022, 3: 0.043400000000000216, 4: 1.103199999999895, 5: 2.9063000000017087, 6: 6.142699999999023, 7: 10.075099999989858, 8: 15.533299999977137, 9: 18.94439999996919, 10: 19.328099999968295, 11: 16.106199999975804, 12: 9.814999999990464]
```
[Answer]
## JavaScript (ES6), 149
Algorithm is similar to [my CoffeeScript answer](https://codegolf.stackexchange.com/a/9230/22867); different syntax and semantics. I tried inlining the `q` function here which made no difference.
```
for(r=()=>~~(6*Math.random()),q=()=>r()||r(),t=i=0,s={};++i<(z=1e6);){a=[q(),q(),q()].sort();t+=b=2+a[1]+a[2];s[b]=1e2/z+(s[b]||0)}console.log(t/z,s)
```
### Unminified
```
for (
r = () => ~~ (6 * Math.random()), // function to generate random number between 0 - 5
q = () => r() || r(), // function to roll dice and if 0, re-roll once
t = i = 0, // initialize counter and sum
s = {}; // initialize probability object
++i < (z = 1e5); // increment
) {
a = [q(), q(), q()].sort(); // roll three dice and perform lexicographical sort
t += b = 2 + a[1] + a[2]; // take two highest and add 2 since numbers are 0 - 5
s[b] = 1e2 / z + (s[b] || 0) // put into probability object as a percent
}
console.log(t / z, s) // STDOUT
```
] |
[Question]
[
The goal is to create a generator generator [...] generator generator comprehension.
1. The generator must be created via [generator comprehension](https://stackoverflow.com/questions/364802/how-exactly-does-a-generator-comprehension-work).
2. The following expression must be valid for any number of nestings: `next(next(next(next(next(generator)))))`.
The winner is whoever achieves this with the fewest number of bytes.
[Answer]
# [Python](https://www.python.org), ~~31~~ ~~26~~ 25 bytes
```
x=(x for()in iter(set,1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY7K2w1KhTS8os0NDPzFDJLUos0ilNLdAw1NSHyN80rFWwVKriAKhQyFYBKihLz0lM1DA0MNK24FICgoCgzr0SjUhPMAanNS60A8SHaYdYAAA)
If assignment is not allowed:
# [Python](https://www.python.org), ~~77~~ ~~72~~ 71 bytes
```
(gc.get_referrers(sys._getframe())[0]for()in iter(set,1))
import gc,sys
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYzBCsIwEETv_Yo97kIt7U2Env0IlVLKJubQpGxWSL_FS0D0n_wbo3Uuwwzz5v5aVr0Gnx-pPz9vanb79xHt1FjWQdiwCEvEuMZmKJWRcWYkOrUXEwTJeXDKgpG17ogqNy9BFOxUF-J_15UlOChTGb1l7NqWDhUULeK8YqJfSNCD5_TNG5jz5h8)
(this is bad code)
-5 bytes on both solutions thanks to @ovs
[Answer]
@pxeger's solution is pretty much the end of this challenge. A generator expression *must* include code like `(a for b in c)`, where `a` must be a generator which behaves like the outer generator expression behaves. Either `a` refers to the outer generator itself, or `a` is a shorter solution to this problem; so a shortest solution must look like `x=(x for b in c)`. For this to *be* a solution, then `c` must be an infinite iterator.
I don't have a proof that `iter(int,1)` is the shortest possible way to make an infinite iterator, but it seems unbeatable. Otherwise, the only way to improve on @pxeger's solution is if you can write an infinite iterator in fewer than 11 bytes.
---
If we relax the rule requiring the result to be created using a generator expression, then here's a few other ideas:
Using `iter`: ([18 bytes](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhabKmwzS1KLNHISc5NSEq0qdAw1IRI3zSsVbBUquNLyixQyFTLzFIoS89JTNQwNDDStuBSAoKAoM69Eo1ITzAGpzUutAPEh2mHmAwA))
```
x=iter(lambda:x,1)
```
Using `yield`: ([23 bytes](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhbbU1LTFNI0NK0qM1NzUkAsrgpbIAmRvWleqWCrUMGVll-kkKmQmadQlJiXnqphaGCgacWlAAQFRZl5JRqVmmAOSG1eagWID9EOswQA))
```
def f():yield f()
x=f()
```
Using `itertools.cycle`: ([44 bytes](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3dTJzC_KLShQyS1KLSvLzc4oVEosVMrkqbDP1kiuTc1I1cqxso2M1uXK0bSt0oHrMKxVsFSq40vKLFDIVMvMUihLz0lM1DA0MNK24FICgoCgzr0SjUhPMAanNS60A8SHaYVYDAA))
```
import itertools as i
x=i.cycle(l:=[])
l+=x,
```
---
That said, if the rule is only that the *outer-most* generator be created using a generator expression, and the results after that need not be generators (just things that `next` works on, i.e. any iterators), then `a` in the code above can be some solution to the relaxed challenge, instead of a self-reference: ([32 bytes](https://ato.pxeger.com/run?1=m72soLIkIz9vweIK25ilpSVpuhY3FTSqrGwzS1KLNHISc5NSEq2qdAw10_KLFOIVMvOiDWM1oerMKxVsFSq4QDKZQBmFosS89FQNQwMDTSsuBSAoKMrMK9Go1ARzQGrzUitAfIj2BQsgNAA))
```
(z:=iter(lambda:z,1)for _ in[1])
```
This method still can't beat @pxeger's solution, unless there is a solution to the relaxed version of the challenge more than 6 bytes shorter than `z:=iter(lambda:z,1)`. This seems pretty unlikely, and even if it is possible, it would presumably be an infinite iterator; so it would still be shorter if you plugged it into @pxeger's solution instead of this one.
] |
[Question]
[
[The cop's thread is here](https://codegolf.stackexchange.com/q/175365/76162)
The robber's task is to find a program of size equal to or less than the cop's program, which, when given an itself as input, produces the same output as the cop's program.
Additionally, even if a cop's answer is provisionally marked Safe and has been revealed, you can still crack it by finding an input that is not the same as the given source code, but still produces the same output.
## Rules:
* Submissions consist of
+ Language name + flags
+ Username of the cop with a link to the original post
+ The cracked program
* An explanation would be appreciated
* Your goal is to crack the most Cop's programs
## Some Examples:
### brainfuck, xxx's submission
```
[,[>,]<[.<]]
```
[Try It Online!](https://tio.run/##SypKzMxLK03O/v9fJ9pOJ9YmWs8mFpkNAA)
This program simply reverses the input
Good luck!
[Answer]
# [Node.js v10.9.0](https://tio.run/#javascript-node), [Arnauld](https://codegolf.stackexchange.com/a/175403/42545)
```
o=>[...o].sort(n=>16&(j+=13),j=9).join``
```
[Try it online!](https://tio.run/##DcZBCoAgEADAr3QKl2pBgqDD9omOERilochuqPR9a04TjvfIZ/JPGVguW6MtjWuoCi0bIsqOWVJRTIueWhU60iP0gWbAIJ6Nqadwlmgxyq2cWkvy/AcA6gc "JavaScript (Node.js) – Try It Online")
This outputs this particular permutation of itself when using Node's current sorting algorithm:
```
&`nij.9=j.,)r31n=+(=ooj`[o.o.)1.s](>=6>t
```
An insightful [comment by l4m2](https://codegolf.stackexchange.com/questions/175365/transformers-in-disguise-cops-thread#comment422502_175403) gave me a headstart, but I had to write a brute-forcer to figure out which permutation of digits gives the correct output...
[Answer]
# JavaScript Firefox, [l4m2](https://codegolf.stackexchange.com/a/175371/58563)
```
btoa
```
`btoa(btoa)` encodes the following string (including linefeeds):
```
function btoa() {
[native code]
}
```
which gives:
```
"ZnVuY3Rpb24gYnRvYSgpIHsKICAgIFtuYXRpdmUgY29kZV0KfQ=="
```
[Answer]
# Python 3.6+, [agtoever](https://codegolf.stackexchange.com/a/196395/60483)
```
print("".join([f"{ord(c)^170}" for c in input()]))
```
Since the byte count was 50 and there were 150 digits, I split it into groups of 3, and then guessed that some XOR had been applied to the ASCII representations of the characters so iterated over all possible XORs.
[Try it online!](https://tio.run/##nU/RCoJAEHzvK8SXu4OK2707TwWf@gwxCDOyRE3OQKJvt/XKHwiGZZidmWX7yV27VsX9MLusep4azhib@6FuHQ/D/a2rW55fwlc3nHkpjmDlOwwu3RCUQd0S@tFxUQgxUyy36Q4Lsfmm3UrY4VqVdx@qHuOpqd2Usq3LMoYQI0SQGEgiRAQlQUUeCAnBflekowaUmlYoE9IphdLrEkABag3GgLFgNILxDfHi907PyRavbT@yXEe13qUSS5PAxB//fwA)
[Answer]
# Perl 6, [donaldh](https://codegolf.stackexchange.com/a/175390/9296)
```
bag(get.comb).kv.sort.join.say
```
[Try it online!](https://tio.run/##K0gtyjH7/z8pMV0jPbVELzk/N0lTL7tMrzi/qEQvKz8zT684sZKQPAA "Perl 6 – Try It Online")
(This produces the same output for all permutations of the input, for example `().....aabbceggijkmnooorssttvy`, but I strongly suspect that this is donaldh's program.)
[Answer]
# [A Pear Tree](https://esolangs.org/wiki/A_Pear_Tree), [ais523](https://codegolf.stackexchange.com/a/175546/69850)
```
eval(x=q[print"eval(x=q[$x])"ne$_||exit|UPNR])
```
[Try it online!](https://tio.run/##S9QtSE0s0i0pSk39/z@1LDFHo8K2MLqgKDOvRAnOVamI1VTKS1WJr6lJrcgsqQkN8AuK1SRVPQA "A Pear Tree – Try It Online")
[Answer]
# Pepe, [u\_ndefined](https://codegolf.stackexchange.com/a/176140/31347)
Bit late back to this, but this looks to be simply add the character index to the char value
```
REEerEEReEeREEEEEeeeree
```
You can try it [here](https://soaku.github.io/Pepe/#TELS1*). The permalink forces in breaks, but it should still work.
] |
[Question]
[
[This `rar` file](https://www.cfresh.net/wp-content/uploads/2009/01/8200912819148.rar), when decompressed, gives a 65024-byte `exe` file. Requiring you to output the contents of that file would be absolutely no fun.
But you aren't required to do that. Actually, you're to do something opposite: Output a binary of the same length (65024 bytes), such that no byte equals the byte at same position in the source `exe` file.
This is code-golf, shortest code wins.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 81 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
•Out 65024↑1042/"#?ZY>Rg*778c0?74h3g)G?mm5963!1[!1OC+VUb)7]#Z-%&N/D^sUrJaVwc}%! "
```
[Try it online!](https://mlochbaum.github.io/BQN/try.html#code=NjUwMjTihpExMDQyLyIjP1pZPlJnKjc3OGMwPzc0aDNnKUc/bW01OTYzITFbITFPQytWVWIpN10jWi0lJk4vRF5zVXJKYVZ3Y30lISAi) This is written for [CBQN](https://github.com/dzaima/CBQN), I removed the `•Out` to run it online.
If you split the binary into chunks of 1042, in each chunk at least one printable different from `"` is missing. Search program:
```
pa ← @-˜'"'⊸≠⊸/' '+↕95
b ← @-˜•FBytes "fr08v101.exe"
m ‚Üê ‚äë‚åΩ1000+/{‚äë‚à߬¥¬¨‚àßÀùpa‚àä‚åú<Àò‚Üë‚Äøùï©‚•äb}¬® 1000+‚Üï1000
•Show m
•Show @+⊑⟜pa¨ ⊑∘/˘⍉¬pa∊⌜<˘↑‿m⥊b
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~55~~ 51 bytes
```
<3s*L1586"iýy±å7˱â7a£Õ§³mh79B!OÈ­wc7wÝ%'÷î3awo÷c­#
```
[Try it online!](https://tio.run/##AUwAs/9weXRo//88M3MqTDE1ODYiacO9ecKxw6U3w4vCscOiN2HCo8OVwqfCs21oNzlCIU/DiMKtd2M3d8OdJSfDt8OuM2F3b8O3Y8KtI/// "Pyth – Try It Online")
```
"iýy±å7˱â7a£Õ§³mh79B!OÈ­wc7wÝ%'÷î3awo÷c­# 41-character string literal
*L1586 repeat each character 1586 times
s concatenate
<3 remove the last 3 characters
output with a trailing newline
```
(Use the `PYTHONIOENCODING=latin1` environment variable for correct binary output.)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 339 bytes
```
UTI⪪”}⊞➙×Tμ[j…|U◨{U⁸→º4D›⮌⪫ιaYh⎇E"6ºρ⌊mMOk…÷›GF⭆B↨⬤U↙⊕✳…Hd¶5‖O$¬÷G≕6TχSυ⟧⌈◨~a3j'▷↘3⊖À⁷0r]e⎇⁻≔s&g>▶r↔⊗⁰ηχκη↔S1hLΦ⍘⦄⪪⊕«⪪⊙M»nPOgbO\XKÀ›'◨‽⬤κ➙›\p;▶⸿⁴P÷χ>Ie…Eσ/N⟲B÷«~υ⟧χ9✂‽G⁶⦄⁷τH¿Þ₂⊘ΦW4rO&v×σIB⍘↔_﹪ηA⸿/?⊙/J¡lβ“K▷¬✂6τB﹪G▶﹪⁺%zÀτ(&7\`g⁷C↙¤⦄ïG↖0⪫ςj]nQ#W¶JeM)⬤χ9c←@⁷S5w⌊#U;N⌕·NSN1?Σ@s↖$T(⁵xd«Fαh▶º⌊0l⮌d⮌oH"=d=▷À⁰j¤q⊙⦃Oε↥∧ψ�¬&≧↷cy/⊞⁴GE»¦≔✳κ¦'⁶↘S⎚ü]₂Q”¶
```
[Try it online!](https://tio.run/##PZPBbhsxDETv/YrCJxtogSUpiRJy7A8UaI57MYIiDeBuAtfo77t81LoHy5JIDYfD2Zdf5@vL@/lyvz@/v75efj5f334fT0@fvl/fttvx2/nP7fjj4/J2Ox5kKbJuw9etqq6bSFnWzWKn2tetSATUYumkidZYlhaBXmJX42jrFmdpsXj8jKhoA3AJhN5H7Aysyq7EkwFKpPWAVO8ARVFxqsoAY8AEIqRLKRSMYMty1YnUyG4OC6nUiqV4APYF1Ep6ZAxexbPW@g6kc4lEdyrHocMFCcwMvEg12QkZqXmd9BaI0gH/La6RS0fSDxB4CbQblCCHPKjEvgSbQh0pD8DiEYS2UVUl0nxEcFC/pIhxMJqbmqEDuhlZKRHkaMU7odRLdzxZegK2h8RIkXo5A8pkGcGq9TiWRkomQ1tTp747Id3xf/xK287o2oJD6CB1k4FcDKqo0PojwNywCKCZyCyj8mjM2mZRm72Je17WvU11z7moz5aZvyYy6pn2OceBdxC7sDgkOu/QYNi05TTfSFtEzJBh4pa9PU2jIQe2V9F9EOJpI4ihzHT@7CRHAx2@G0ZrBsPpvpoA07nMXpFaZDdVmR1Jn@5Rnz9/dAp17rEReYAtyJTT2P2XHWo2ju60NcVVeEAP@1laXSar/MKZslFuZFfwoT8FRmt@FNOAgpV1MTl8@XxYt8PpdHq63@9f/17@AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Charcoal is very good at printing lots of `-` signs. The compressed strings represents all the runs of non-`-`-signs in the file. Each run of `-`s is separated by a newline, thus ensuring that no character of the output matches a character in the file.
```
UT
```
Turn off Charcoal's default rectangular output, since we don't want space padding.
```
I⪪...¶
```
Split the compressed string `1041\n97...104\n2031` on newlines (they are the golfiest separators), and cast the numbers to integer, which causes Charcoal to output them as that number of `-` signs.
A "port" of @ovs's answer is only 90 bytes:
```
⭆“"jVXW⬤tO#^S0➙↷⊟Li§K″1·β℅±d74%;{ESM»ΠⅈρξDςΦcSEenÞ⁻.⁷¡ê;q¬⟧l﹪Π0№Σ″≔X⁼·⁶d´Z»~⪪V⎚+⪪ÀkO”×ι⁵¹²
```
[Try it online!](https://tio.run/##FYzdCsIwDIVfZUnXdnVrhoI3K7InEAS9WxDGEB3MH@bwRvDVawrhhJNz8g23fh6e/RTjYR4fS3FcZF33/atARsXYehFFVMLKMzrqNO1AUWAE0oyVzcUxMxIxetMCY2lVWXeglbYgNg2ApCrUtRVaTtQwGuXTLeENkXSN8RZsJ@1GfV35C4lpmOX/DA04rYkIq@w03i/vYqyy7XrjnAsxRv@Z/g "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Simply repeats each character in the compressed string 512 times (I used this instead of @ovs' 1042 because it's a factor of 65024 and larger factors end up covering all of printable ASCII). Conveniently all the characters needed are in Charcoal's "symbols" area which allows the string to be compressed from 127 to 84 bytes. (It's not possible to do this with all letters (either upper or lower case) or all digits.)
[Answer]
# JavaScript (ES10), 131 bytes
Returns an array of bytes.
```
_=>[..."hx53ptn9mgv1xij4xcw506nhi1cxi7w116o3kntsesafc5xwy4w15u6bo7ulphwt"].flatMap(v=>Array(1016).fill(n-=parseInt(v,36)-17),n=187)
```
[Try it online!](https://tio.run/##BcHRDoIgFADQf@kl2JR5Z2I90NZjD31Ba41IFKMLEwL8ejtnlkkGtRgfa3TvYdNie4rznTG2m0rX@oin75igmPlQVO4ajpMBVUyfAbhrPxjDEKRWXcnrIUP34y/X/6yfctw9mLYy3qQnSZwvyyJXAg1wyrSxlmAtvFzCcMVIUtVyWkNPKxRw7OmmHAZnB2bdSDShbHYGyb7aU7r9AQ "JavaScript (Node.js) – Try It Online")
### How?
This encodes 64 bytes \$b\_0\$ to \$b\_{63}\$ that are repeated 1016 times each and do not appear in the corresponding chunk of the original file:
```
187,171,183,197,189,177,171,179,174,175,161,177,161,160,158,171,
155,160,145,157,174,185,179,179,178,194,199,183,182,192,177,193,
209,220,213,227,224,218,206,195,198,187,194,196,201,213,197,182,
165,178,163,179,191,178,189,195,188,198,185,181,173,173,158,146
```
The values were chosen in such a way that \$|b\_k-b\_{k-1}|<18\$ for each \$k>0\$, which allows to store the delta values in base 36.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 74 bytes SBCS
```
_=>"¬≠[-!^7q7hŒƒŽ√è¬≥√°¬ª¬±™{3Ž¬≥√Æg}G√Öc¬¨√Øn¬∑√óO~v#¬π›¬Ω+:[¬¶w".repeat(1414).slice(20)
```
[Try it online!](https://tio.run/##AYUAev9qYXZhc2NyaXB0LW5vZGX/Zj3/Xz0@IsKtWy0hXjdxN2jCjMKDwo7Dj8Kzw6HCu8Kxwpl7M8KOwrPDrmd9R8OFY8Ksw69uwrfDl09@diMVwrnCm8K9KzpbwqZ3Ii5yZXBlYXQoMTQxNCkuc2xpY2UoMjAp/2NvbnNvbGUubG9nKGYoKSn/ "JavaScript (Node.js) – Try It Online")
I'm not sure if this happen for random enough file, or why you use `aaaabbbbccccdddd` rather than `abcdabcdabcdabcd` even for languages with better support for the latter solution
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~260~~ ~~70~~ 69 bytes
*-1 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).*
```
•Ý=£ë—ÛāR5Bf·½"¨ß¡˜v`₆BÌÝΩ\∞?ΓтJ&тƒFćO#'œ|Ć‹RÞ¼Á,нìçD|•Ƶ?вŽ4´δи˜Ž3ć(£
```
[Try it online!](https://tio.run/##AYAAf/9vc2FiaWX//@KAosOdPcKjw6vigJTDm8SBUjVCZsK3wr0iwqjDn8Khy5x2YOKChkLDjMOdzqlc4oieP86T0YJKJtGCxpJGxIdPIyfFk3zEhuKAuVLDnsK8w4Es0L3DrMOnRHzigKLGtT/QssW9NMK0zrTQuMucxb0zxIcowqP//w "05AB1E – Try It Online") Outputs as a list of byte values. [Alternative link](https://tio.run/##AYMAfP9vc2FiaWX//@KAosOdPcKjw6vigJTDm8SBUjVCZsK3wr0iwqjDn8Khy5x2YOKChkLDjMOdzqlc4oieP86T0YJKJtGCxpJGxIdPIyfFk3zEhuKAuVLDnsK8w4Es0L3DrMOnRHzigKLGtT/QssW9NMK0zrTQuMucxb0zxIcowqP/w6dK/w "05AB1E – Try It Online") for text output.
# Explanation
Similarly to other answers here, this answer uses equal-sized chunks (except the last chunk), each consisting of the same byte throughout the entire chunk (but different bytes throughout the entire output). To get an optimal score, maximizing the chunk size is important – or rather, minimizing the number of chunks.
To do this, I iterated through chunk sizes, starting from \$1{,}000\$ and going up. With each iteration, I checked if every byte value was present at least once in at least one chunk.
This happened at \$1{,}200\$ bytes per chunk. This meant that each chunk but the last can be up to \$1{,}199\$ bytes, with the last chunk being \$278\$ bytes. This means there are \$54\$ full chunks plus the small chunk at the end, making a total of \$55\$ chunks.
Let's verify this: \$54√ó1{,}199+278=65{,}024\$.
Finally, for each chunk, we find the smallest byte that doesn't exist there and repeat it for the length of that chunk, and we're done!
[Answer]
PHP (276 chars)
```
for($d=[-17,-532,-95,-515,-79,463,95,-392,-27,148,$i=-1,808,53,61,15,-665,-5,419,-29,211,46,399,95,569,11,-2,101,-588,11,418,-43,-70,-48,-1887,105,918,-63,-1655,-97,-317,-104,-116,-74,513,53,885,-97,605,150,593,20,-295];++$i<52;)echo str_repeat(chr(150-$d[$i]),2500-$d[++$i]);
```
[Try it Online](https://link.gy/4bb85) *(using an URL shortener to store the **.exe** file)*
If [GMP](https://www.php.net/manual/en/book.gmp.php) is available it's **206 chars** long :
```
for($d=str_split(($i=0).gmp_init('1FmB6eDs41MlblmT1hchbcMok3RFjcIJ7OHt8hphdLMPDPgigsPrqHXfc3QEFotYuvL9zfZ3y7ZYkD7nnoSCgAzgJhHEVnl9R6mB5cshIudtpnunsccV',62),4);$i<52;)echo str_repeat(chr($d[$i++]),$d[$i++]);
```
**How is generated this sequence of [str\_repeat](https://www.php.net/manual/en/function.str-repeat.php) ?**
Just by the output of [strcspn](https://www.php.net/manual/en/function.strcspn.php).
```
<?php
$data = file_get_contents('raw_file');
$file_length = strlen($data);
$ptr = 0;
while ($ptr < $file_length) {
$max_dist = $max_ord = 0;
for ($i = 0; $i < 256; ++$i) {
$char = chr($i);
$dist = strcspn($data, $char, $ptr);
if ($dist > $max_dist) {
$max_dist = $dist;
$max_ord = $i;
}
}
$ptr += $max_dist;
echo ".str_repeat(chr($max_ord), $max_dist)";
}
```
] |
[Question]
[
**This question already has answers here**:
[xkcd 2385 KoTH (Final Exam)](/questions/224621/xkcd-2385-koth-final-exam)
(63 answers)
[Smallest unique number KoTH](/questions/172178/smallest-unique-number-koth)
(42 answers)
Closed 2 years ago.
In this challenge, players need to tamper with a time bomb as late as possible without getting blasted in the face.
## Mechanics
Let `N` be the number of bots plus one. Each round, each bot receives the following arguments:
* numbers played by all bots last round in ascending order.
* number of points it received last round. Negative if it lost last round.
The bot is asked to play an integer between 1 to `N` inclusive. After all bots played their numbers, a counter is initialized with half of the sum of numbers from all bots. Each bots then subtracts the number it played from the counter. Bots are sorted from the lowest to the highest. Bots with the same number are considered subtracts the counter at the same time. The bomb explodes when the counter hits zero or becomes negative.
## Scoring
After the bomb exploded, the round ends, and the points for this round is calculated as the following:
* Bots that played before the explosion get the number of points equal to **twice** the number it played this round.
* Bots that played when the explosion lose the number of points equal to the number it played this round.
* Bots that played after the explosion do not get nor receive point.
Example rounds:
* Number played: `[1,2,3,4,5]`. The initial counter is 7.5, and the bomb explodes on 4. The bot with 1, 2, and 3 gets 2, 4, and 6 points respectively, the bot with 4 loses 4, and the bot with 5 neither gets not lose points.
* Number played: `[1,1,2,4]`. The initial counter is 4, and the bomb explodes on 2. Bots with 1 gets 2 points, the bot with 2 loses 2, and the bot with 4 neither gets not lose points.
* Number played: `[3,3,3,3]`. The initial counter is 6, and the bomb explodes on 3. All bots lose 3 points.
The point for each round is added to a total score for that run. Each run consist of 1000 rounds, and there will be 10 runs. The final total score is the sum of each run, and the bot with the highest final score the the end wins.
## Specifications
The challenge is in JS.
Your bot must be an object that has a `run` method that takes an array of numbers and a number as input, and returns a integer between 1 and `N` inclusive. The value being outside the valid range will be rounded and clamped. If the value is not a number, a number in the valid range will be selected and the behavior of selecting the number is not specified.
On the first round, the array of numbers given will be initialized with random numbers, and the number for points last round will be 0.
## Other rules
* Storing data in your bot's properties is allowed.
* You can use the `Math.random` method. During scoring, [seedrandom.min.js](http://davidbau.com/archives/2010/01/30/random_seeds_coded_hints_and_quintillions.html) will be used, with a secret string concatenated with the run number as the seed for each run. The md5 of the secret string is `4311868bf10b3f7c1782982e68e6d7ca`, for proving that I didn't change the key after the challenge.
* You can use the helper function `sum`.
* Trying to access any other variables outside your bot's own properties is forbidden.
* [Standard loopholes apply.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
The code for controller can be found [here](https://github.com/leo3065/TIme-bomb-KoTH). Feel free to point out mistakes in my code, thanks.
## Example bots
```
{
// Example bot
// It always play the middle number.
name: "Middle",
run(number) {
return Math.round((numbers.length+2)/2);
}
}
```
```
{
// Example bot
// It starts at 1, advances when it got points last round,
// and resets when it lost points.
name: "Advance and reset",
last: 1, // Setting properties is allowed
run(numbers, points) {
var own = this.last;
if(points > 0){
own = Math.min(this.last+1, numbers.length+1);
}
if(points < 0){
own = 1;
}
this.last = own;
return own;
}
}
```
Both example bots above will also play in the game.
# Submissions are due by 2021-05-06 12:00 UTC, but might be lenient depending on when I'm online after the said time above.
[Answer]
```
{
name: "Playing It Safe",
run(numbers) {
return 1;
}
}
```
[Answer]
Some "basic" bots to get this started, also to serve as baseline (they will also play in the game):
```
{
name: "33%",
run(numbers) {
return numbers[Math.floor(numbers.length/3)];
}
}
```
```
{
name: "Pure random",
run(numbers) {
return Math.floor(Math.random() * (numbers.length+1))+1;
}
}
```
```
{
name: "Copy random",
run(numbers) {
return numbers[Math.floor(Math.random() * numbers.length)];
}
}
```
```
{
name: "Alternate",
round: 0,
run(numbers) {
this.round++
return (this.round % 2)? 1 : (numbers.length + 1)
}
}
```
[Answer]
# Smart Random
```
{
name: "Smart Random",
run(numbers) {
var random_int = Math.floor(Math.random() * 3 * (numbers.length+1)/4);
return random_int
}
}
```
Returns a random integer between 0 and 3/4`N` inclusive.
I hope this works - this is my first JS and my first KoTH answer.
[Answer]
# Coinflipper
Starts by initialising `x` to half of `N`, then flips `N` coins. If heads, decrement `x` (unless already zero). If tails, increment `x` (unless already equal to `N`).
```
{
name: "Coinflipper",
run(numbers) {
let x = Math.floor(numbers.length/2);
numbers.forEach(function(){
let coin = (Math.floor(Math.random()*2)+1)
if (coin==1) { x--; }
else if (coin==2) { x++; }
if (x<0) { x=0; }
if (x>numbers.length) { x=numbers.length; }
});
return x;
}
}
```
[Answer]
# Painfully Average
```
{
name: "Painfully Average",
run: (n)=>Math.abs(Math.floor(n.reduce((a,x)=>a+x))/n.length-1)
}
```
[Answer]
# OnePlus
Plays one plus a random floating point between 0 and a random integer between 0 and 5.
```
{
name: "OnePlus",
run(numbers) {
return 1 + Math.random() * Math.floor(Math.random() * 5);
}
}
```
My first King Of The Hill answer, not sure if I am doing things correctly. From my understanding, `numbers` is the list of numbers of the bots? But I am completely ignoring that `numbers`.
[Answer]
# D8roller
Rolls a 8-sided die, and plays that number.
```
{
name: "D8roller",
run(numbers) {
return Math.floor(Math.random()*8)+1;
}
}
```
] |
[Question]
[
I am trying to find the shortest code in **python 3**, to solve this problem:
You are driving a little too fast, and a police officer stops you.
Write code to take two integer inputs, first one corresponds to speed, seconds one is either 1 or 0, corresponding to True and False respectively to indicate whether it is birthday. Then compute the result, encoded as an int value:
0=no ticket,
1=small ticket,
2=big ticket.
If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases.
```
input:
60
0
Output:
0
input:
65
0
Output:
1
input:
65
1
output:
0
```
Here's my shortest solution (`57 chars`). Is there any way I can make it shorter in Python?
```
print(min(2,max(0,(int(input())-5*int(input())-41)//20)))
```
Reference: *Problem inspired from [this](https://codingbat.com/prob/p137202)*
[Answer]
# [Python 3](https://docs.python.org/3/), 32 bytes
```
lambda a,b:(a-b*5>60)+(a-b*5>80)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRIVEnyUojUTdJy9TOzEBTG8q0MND8X1CUmVeikaYBIjPzCkpLNDQ1dRSQeZqa/81MuQwA "Python 3 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), ~~50~~ 49 bytes
If io must be done with stdin and stdout
```
a,b=map(int,open(0));print((a-b*5>60)+(a-b*5>80))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P1EnyTY3sUAjM69EJ78gNU/DQFPTuqAIyNXQSNRN0jK1MzPQ1IYyLYCS//9bGHIZAAA "Python 3 – Try It Online")
-1 byte thanks to [@dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)
[Answer]
# Python 3, ~~51~~ 45 bytes
```
lambda a,b:min(2,max(0,(a//1-5*b//1-41)//20))
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ8kqNzNPw0gnN7FCw0BHI1Ff31DXVCsJRJkYaurrGxloav4vKMrMK9FI0zAz0FEA8rngfFNMviFQPQA "Python 3 – Try It Online")
I was able to shave 6 bytes from your approach by using everyone's favourite python golfing keyword: `lambda`.
This turns your program into an anonymous function, which then can be called in the footer of a program.
Edit: I know that this question is way old, but I only just recently thought of using `//1` to convert things to an integer instead of using `int(...)`.
] |
[Question]
[
192 is such a number, together with its double (384) and triple (576) they contain each 1-9 digit exactly once. Find all the numbers have this property.
No input.
Output:
```
192 384 576
219 438 657
273 546 819
327 654 981
```
[Answer]
## APL (20)
```
192 219 273 327∘.×⍳3
```
Just prints the numbers multiplied by 1, 2, and 3.
## Without hardcoding (25)
```
{∧/1↓⎕D∊⍕k←⍵×⍳3:⎕←k}¨⍳400
```
[Answer]
## GolfScript (31 30 chars)
```
1246`{[27*1131-..2*\3*]' '*n}/
```
(thanks to [Howard](https://codegolf.stackexchange.com/users/1490/howard) for 31->30); or for a non-hard-coded approach, 33 32 (thanks again to Howard) chars:
```
333,{[..2*\3*]' '*}%{.&0-,9>},n*
```
If the output doesn't have to be character-for-character identical to the text in the question (i.e. if that is a sample), we can shorten to 27 chars:
```
[4.)7 9]{[27*84+..2*\3*]}%`
```
[Answer]
### GolfScript ~~44~~ 39
Here's a program that's slightly shorter than the trivial (just print the numbers) solution:
```
333,{4,(;{1$*}%\;.''*$10,0-''*={.p}*;}/
```
(thanks Howard & Peter)
v1:
```
333,{3,{)}%{1$*}%\;.''*$9,{)}%''*={p}{;}if}/
```
Online test [here](http://golfscript.apphb.com/?c=MzMzLHs0LCg7ezEkKn0lXDsuJycqJDEwLDAtJycqPXsucH0qO30v&run=true).
[Answer]
# Python: ~~84~~ ~~77~~ 73 characters
```
for i in range(328):
if`set(`i`+`i*2`+`i*3`)-{'0'}`[45:]:print i,i*2,i*3
```
```
192 384 576
219 438 657
273 546 819
327 654 981
```
[Answer]
# Haskell: 55 characters
```
[(i,2*i,3*i)|i<-[0..333],9==length(nub$show$1002003*i)]
```
Or 65 characters if it is to be compiled and not just interpreted:
```
main=print[(i,2*i,3*i)|i<-[0..333],9==length(nub$show$1002003*i)]
```
[Answer]
# Ruby: ~~76~~ ~~65~~ 60 characters
```
(99..999).map{|n|s=[n,2*n,3*n]*" ";s=~/(\d).*\1|0/||puts(s)}
```
Sample run:
```
bash-4.2$ ruby -e '(99..999).map{|n|s=[n,2*n,3*n]*" ";s=~/(\d).*\1|0/||puts(s)}'
192 384 576
219 438 657
273 546 819
327 654 981
```
[Answer]
### C#, 109 characters
```
String.Format("{0}{1}{2}",a,a*2,a*3).Length ==9 && String.String.Format("{0}{1}{2}",a,a*2,a*3).Distinct()==9;
```
] |
[Question]
[
# Objective
Mimic Haskell's `reads :: ReadS ()`.
Or in other words, parse nested parentheses. Since the target type is `()` (the type with one possible value), "parsing" means discarding a leading nested parentheses.
# Valid Input
"Nested parentheses" means `()`, `(())`, `((()))`, and so on. That is, leading nonzero `(`s and trailing `)`s of the same number.
But there's a twist. The parser must munch also leading or intercalated whitespaces. So for example, the following strings are valid to be munched:
* `( )`
* `()`
* `( () )`
Note that trailing whitespaces are not to be munched.
# Whitespaces
The following ASCII characters are always considered a whitespace:
* `\t` U+0009; Horizontal Tab
* `\n` U+000A; Line Feed
* `\v` U+000B; Vertical Tab
* `\f` U+000C; Form Feed
* `\r` U+000D; Carriage Return
* U+0020; Space
For each of the following Unicode characters, it is implementation-defined to consider it a whitespace:
* U+0085; Next Line
* U+00A0; No-Break Space
* U+1680; Ogham Space Mark
* U+2000; En Quad
* U+2001; Em Quad
* U+2002; En Space
* U+2003; Em Space
* U+2004; Three-Per-Em Space
* U+2005; Four-Per-Em Space
* U+2006; Six-Per-Em Space
* U+2007; Figure Space
* U+2008; Punctuation Space
* U+2009; Thin Space
* U+200A; Hair Space
* U+2028; Line Separator
* U+2029; Paragraph Separator
* U+202F; Narrow No-Break Space
* U+205F; Medium Mathematical Space
* U+3000; Ideographic Space
All other characters are never considered a whitespace.
# Error
If the string doesn't start with a nested parentheses, the parser shall fall in an erroneous state. Ways that indicates an error include:
* Monadic failing
* Returning an erroneous value
* Raising/Throwing an error
# Output
When the parser successfully munched a nested parentheses, the parser shall output the unmunched part of string.
# Examples
## Valid example
* When given `()`, the output is an empty string.
* When given `( ) Hello`, the output is `Hello`. Note the leading whitespace of the output.
* when given `((()))))`, the output is `))`.
## Erroneous example
* Empty string
* `((()`
* `(()())`
* `(H)`
* `Hello, world!`
# Ungolfed solution
## C
Returns a null pointer for an error.
```
#include <stdbool.h>
#include <stdlib.h>
char *readMaybeUnit(char *str) {
bool p = false;
unsigned c = 0;
while (*str != '\0') {
switch (*str) {
case '(':
p = true;
++c;
// FALLTHRU
case '\t': case '\n': case '\v': case '\f': case '\r': case ' ':
break;
default:
goto parseRightParentheses;
}
++str;
}
parseRightParentheses: while (*str != '\0') {
switch (*str) {
case ')':
if (1 >= c) {
if (1 == c)
++str;
c = 0;
goto returnReadMaybeUnit;
}
--c;
// FALLTHRU
case '\t': case '\n': case '\v': case '\f': case '\r': case ' ':
break;
default:
goto returnReadMaybeUnit;
}
++str;
}
returnReadMaybeUnit: return p && 0 == c ? str : NULL;
}
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~83~~ 76 bytes
```
c?(a:b)|elem a" \t\n\r\v\r"=c?b|a==c=[b]
_?_=[]
f x='('?x>>=(:)<*>f>>=(')'?)
```
[Try it online!](https://tio.run/##ZYzBCoMwEETvfsWQi7ul9ANKY36g/QIjsorSko2ISvHQf7cR2kvL7mHezDB3mUOnum2tIzk3/Oq0ixADv/jBT/7pJ2Nb17zE2taWTZXVrrZllfVYbU65W4vC0pkvh6LfVc654y3KY7BRxlsNGqfHsOCEnjOghAEhPRODAQ0STfKPMMQfgT1PlwoMjTL/@PgPiJgJVwnzdy2VRFXDlxOEWXeotjc "Haskell – Try It Online")
Since this question to imitate Haskell's parsing I thought it would be nice to give this a try using Monadic parsing in Haskell. The result is actually really short. I use `[]` as my monad because it is just way shorter than `Maybe` or `Either`.
---
### What is monadic parsing?
Put simply monadic parsing is a type of parsing in which a parser is a function from a string to some optional type of a the remaining string and some data
```
type Parser a = String -> Option (a, String)
```
Here our `Option` type is a list, and we are just validating rather than producing any data, so our parser looks like:
```
type Parser a = String -> [ String ]
```
Where our parser takes some string and returns all possible suffixes of valid parses. The empty string represents a failure to parse because no suffixes means that no valid parse was found.
This way of structuring things makes it super easy to combine parsers. For example if we have a parser `p` which parses the regex `\s*(` and a parser `q` which parses the regex `\s*)` then we can make a parser that parses the expression `\s*(\s*)` using the Kleisli arrow
```
(>=>) :: (a -> m b) -> (b -> m c) -> (a -> m c)
```
Meaning the result is `p >=> q`. We can also do other combinators.
---
So here's how I use it in my answer.
The first thing we do is implement `?`, which takes a character `c` returns a parser the regex `\s*c` (where `c` is the character). Essentially this consumes a prefix made of any amount of whitespace followed by a single character. This is only ever called on `(` and `)`.
With this we implement `f` which is the parser that the challenge asks for. We don't actually have the Kleisli arrow in Prelude but I will write it as if we did for clarity and then show how we remove Kleisli arrows.
```
f = ('('?) >=> (:)<*>f >=> (')'?)
```
So we have three parsers first, it must start with some whitespace followed by a `(` then some gobbledygook parser and then it must end with some whitespace followed by a `)`.
The gobbledygook `(:)<*>f` can be expressed more clearly as
```
\ x -> x : f x
```
Which is to say it is it matches everything the `f` parser does but also matches the empty string.
So our `f` parser matches:
>
> Parentheses enclosing, either the empty string or another f.
>
>
>
Now to remove our Kleisli arrows we use `>>=` which has the similar type signature:
```
(>>=) :: m a -> (a -> m b) -> m b
```
So we take an argument from f, pass it to the first parser and change all of our `(>=>)`s to `(>>=)`s.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~32~~ 31 bytes
```
^(\s*\()+(?<-1>\s*\))+(?(1)$.)
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP04jplgrRkNTW8PeRtfQDsTRBHE0DDVV9DS5/v/X0ORS0FDQVPBIzcnJ59LQ0NAEAS7X3IKSSoXikqLMvHSwKJDQBMpxaXhocoHV6iiU5xflpCgCAA "Retina 0.8.2 – Try It Online") Link includes test cases. Returns the original string on error. Considers the given control characters as white space, plus any Unicode characters (such as space) in the Separator group, plus U+0085. If only the minimal white space is desired, this can be achieved by prefixing `e``. Explanation:
```
^(\s*\()+
```
Match some open parentheses at the start of the string.
```
(?<-1>\s*\))+
```
Match some close parentheses.
```
(?(1)$.)
```
Check that the same number of open and close parentheses were matched.
```
```
Delete the matched parentheses.
Alternative solution, also 31 bytes:
```
r`^(?<-1>\s*\()+(\s*\))+(.*)
$2
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wvyghTsPeRtfQLqZYK0ZDU1sDRGsCaT0tTS4Vo///NTS5FDQUNBU8UnNy8rk0NDQ0QYDLNbegpFKhuKQoMy8dLAokNIFyXBoemlxgtToK5flFOSmKAA "Retina 0.8.2 – Try It Online") Link includes test cases. If only the minimal white space is desired, this can be achieved by prefixing `e`. Explanation:
```
r`
```
Start matching at the end of the string and work backwards (like a lookbehind would).
```
(.*)
```
Match as much result as possible.
```
(\s*\))+
```
Match some close parentheses.
```
^(?<-1>\s*\()+
```
Match the open parentheses at the start of the string. The number of close parentheses must be at least as many as the number of open parentheses for the balancing group to succeed, but it can't be more because the `(.*)` ensures that as few close parentheses are matched as possible.
```
$2
```
Keep everything except the matched parentheses.
Previous 32-byte solution that returns the empty string on error:
```
1!`(?<=^(?<-1>\s*\()+(\s*\))+).*
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w31AxQcPexjYOSOga2sUUa8VoaGprgGhNTW1NPa3//zU0uRQ0FDQVPFJzcvK5NDQ0NEGAyzW3oKRSobikKDMvHSwKJDSBclwaHppcYLU6CuX5RTkpigA "Retina 0.8.2 – Try It Online") Link includes test cases. If only the minimal white space is desired, this can be achieved by prefixing `e`. Explanation:
```
1!`
```
Output the matched part of the first match.
```
(?<=^(?<-1>\s*\()+(\s*\))+)
```
Ensure that the match starts after balanced parentheses. Note that this is a lookbehind, so the match is processed right-to-left - the `)`s are matched first, then a `(` can be matched for each `)`. There can't be too many `)`s because the lookbehind would have matched earlier, meaning that this is no longer the first match.
```
.*
```
Match the rest of the string. This actually counts as part of the match, and therefore becomes the resulting output.
[Answer]
# Python 2, 122 bytes
```
def f(s,c=0,p='('):a=s[:1];return[f(s[1:],c+"()".find(a)%-3+1,[p,a][a>p])if(a in(p,')'))|a.isspace()else 0,s][`c`+p=="0)"]
```
Returns `0` on error.
[Try it online!](https://tio.run/##TVDRasMwDHzvV6iGYIm4JeneUtzn/oMx1CQ2DQTb2B5jsH/P3Gzrek@nk3ScFD/LPfjTuk7WgcMsRtmJKDlyGozMauj1OdnynryqXdUPWowtQ2JHN/sJDTWHt7YXKgqjlblETbNDA7PHKDhxoi9znHOOZrRIdskWOpG1uo23NkrJOmJ6LTaXDBJwBxUPc/HDAIHgapcl/CmISA88a6g13C1hOP9qnL/M/u8Rvmxdn3RzF/AR0jLtq0g7FxKUegBssYZtLKbZF2RNgsMFmsSgASyi/qvULOs3 "Python 2 – Try It Online")
### Python 3, 125 bytes
```
def f(s,c=0,p='('):a=s[:1];return[f(s[1:],c+"()".find(a)%-3+1,[p,a][a>p])if(a in(p,')'))|a.isspace()else 0,s][(c,p)==(0,')')]
```
Returns `0` on error.
[Try it online!](https://tio.run/##TVBBisMwDLz3FdpAsETVktBbinvuH4wPJrGpIcTG9rIs7N9TN93tVqfRaGaQFL/LLSyndZ2sA4eZR9lxlAIFDUZmNfT6nGz5TIuqU9UPmsd9g9QcnV8mNNQeTvueVWSjlblETd6hAb9gZEGC6Mccfc7RjBbJztlCx1krHDmSlNhtIr0Wm0sGCbiDWo98fiJAILjaeQ5/DCLSo1491B5uljCcfzkh3rT/PsI31/UFt3SGr5Dm6aOStHMhQak3wLbWsMli8kvBpk1wuECbGmgBC9eXlbrLegc "Python 3 – Try It Online")
---
### Python 2 (non-recursive), ~~173~~ ~~170~~ ~~166~~ 153 bytes
```
def p(s):c=i=a=0;t="""
while i<len(s):
if~-s[i].isspace():
if%r!=s[i]:break
c+=%s
i+=1""";exec t%('(','1')+t%(')',"-1\n\tif c==0:a=s[i+1:]");return a
```
Returns `0` on error.
[Try it online!](https://tio.run/##TZDBboMwEETP4SsmlizvCqhCj1D3nH9ocqDECKvIINtV2kt/nRraptnT7NvZ0WrnzzhM7nFZLqbHTIHrTlvd6kMTtRAiuw52NLBPo3HrMIPtv8rwYs8PNoS57QwluLO99Hu94vrVm/Yt23W5liG5c12lmMZ8mA5RkiJVqEpxvmpWhSirkztF26PT@lC3a0Ze1WfBjTfx3Tu0SzQhBmhQhlSCWBQ/CgTG0Yzj9EeIiNe69Ug9BsM0Nb9MqTvv/x7T3dbxJrf0AtfJj5d9gpz1k0eEddjOqjfb7K2LENKjfIb0AhIUi/TOyLx8Aw "Python 2 – Try It Online")
We could save another 2 bytes if we returned the original string on error, but then inputs `'()'` and `''` would give the same output `''`.
* -4 bytes, thanks to @ovs !
[Answer]
# [Perl 5](https://www.perl.org/), (-p) 22 bytes
```
s/^(\s*\((?1)?\s*\))//
```
[Try it online!](https://tio.run/##HYo7CoAwEET7PcXazYoSLKytBA8hVooEYhKSgHh5188Uw2PexC25XjWbBXOuZ2DoZPhIxBhVCDFYeNqcCwRAvtB4xHJxLsn6/V/fktcRJqH/2/AZklurO8Rig8/axgc "Perl 5 – Try It Online")
Using recursive regex. The shorter `\s*\((?0)?\s*\)` didn't work because of start anchor missing.
The error case is given by the result of substitution operation :
* 1 - success
* "" - failed
] |
[Question]
[
So, this is a task from one very popular educational site in Russia:
<https://acmp.ru/index.asp?main=task&id_task=786&ins=1>
Mathematically, you need to find the power of two not exceeding the given number, read from the standard input stream, and output their difference in the standard output stream.
My **python3** solution takes **41** characters, but the leader’s solution is only **40** characters.
Who can shorten the code?
**Newlines, spaces and tabs are not included while counting code length.**
```
x = int(input())
print(x - 2 ** (len(bin(x)) - 3))
```
[Answer]
# [Python 3](https://docs.python.org/3/), 39 bytes
```
print(int('0'+bin(int(input()))[3:],2))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EA4TVDdS1kzLzNCD8gtISDU1NzWhjq1gdI03N//@NAA "Python 3 – Try It Online")
Subtracting the largest power of two less than a number is the same as removing the first `1` from its binary representation.
Unfortunately python rather mysteriously errors on trying to convert the empty binary string to an int so we need `'0'+` if we want it to work on zero or one. If we relax the requirements to only require two or more then we can remove 4 bytes.
# [Python 3](https://docs.python.org/3/), 35 bytes
```
print(int(bin(int(input()))[3:],2))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EA4STMvM0IOyC0hINTU3NaGOrWB0jTc3//40A "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~40~~ 39 bytes (not counting the newline)
First I simplified \$2^{a-3}\$ to \$\frac{2^a}8\$, then I used the lower-precedence operators `<<` and `^` so that `//` can be replaced by `-` (which saves a byte).
```
x=int(input())
print(1<<len(bin(x))-3^x)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8I2M69EIzOvoLREQ1OTq6AIxDW0sclJzdNIyszTqNDU1DWOq9D8/9/MHAA "Python 3 – Try It Online")
] |
[Question]
[
As you may know, the typical binary floating point numbers in a computer language are quite different than the typical integer numbers in a computer language. Floating point numbers can represent a much larger range, and can represent fractional amounts, however there is a trade-off that is frequently elided.
The distance between integers is constant, and in fact the value of that constant is one. The distance between floating point numbers, however, is variable, and increases the further one travels down the number line, away from the origin at 0. At some point, that distance is so large that the floating point numbers start skipping over integers, and many integers that are technically less than the maximum value of the floating point numbers, cannot actually be represented by floating point numbers.
The challenge:
Write a program that when given the number n, will print out the first n positive integers that cannot be represented by a floating point number in your language of choice.
* "First n positive integers" means, lowest in value, closest to the origin, and distinct from each other.
* Infinite precision floating point numbers are not allowed.
* It doesn't matter whether you choose 32 bit floats, 64 bits floats, or some other type of float, as long as it is a non-infinite precision floating point number in your language of choice, on your machine of choice.
* Order of numbers does not matter
* This is Code Gofl. Smallest number of characters wins.
* Good luck and have fun
Example:
In Rust, using 32 bit floating point builtin type 'f32':
```
n=4, result = [16777217,16777219,16777221,16777223]
```
---
(updated - 1 order doesnt matter - 2 Golf->Gofl)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 58 bytes
```
f(n,i){for(i=9;n;i++)i-(int)(i+.0f)&&printf("%d ",i,n--);}
```
[Try it online!](https://tio.run/##VcqxCoMwEIDh2T7FEajckaRENzn6Ji4SuXKDZxE38dljOnRw/D/@HD85lyJoQemQdUN9D2ys3pNGVNsJ1b@SUNt@t5qC7jmDCxosRuKzVINlUkOC49EIdsQA/3U0R/zTPqXqdz7LBQ "C (gcc) – Try It Online")
Works with 32-bit `float`.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 28 characters
```
{grep({.Num+|0-$_},^∞)[^$_]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq9KLVAo1rPrzRXu8ZAVyW@VifuUcc8zeg4lfjY2v/FiZUKaRqGBpr/AQ "Perl 6 – Try It Online")
This is actually 30 bytes, but the challenge is scored in characters.
This should work theoretically. This creates a lazy list of numbers that compares the default number type (with arbitrary precision) against the same number converted to a `Num` datatype, which is a 64-bit floating point number, and returns the first \$n\$ elements of the list
[Here's a version starting at \$2^{53}-5\$](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq9KLVAo1rPrzRXu8ZAVyW@VkfDSEvL1FjXVFNPT0szOk4lPrb2f3FipUKahqGB5n8A)
[Answer]
# [Ruby 2.6](https://www.ruby-lang.org/), 42 bytes
```
->n{(1..).lazy.select{|i|i!=i*1.0}.take n}
```
Works with 64-bit floats, returns an enumerator.
### Ruby 2.5 and below, 43 bytes
```
->n{1.step.lazy.select{|i|i!=i*1.0}.take n}
```
And finally, the one that actually finishes in reasonable time:
```
->n{(2**53).step.lazy.select{|i|i!=i*1.0}.take n}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNIS8vUWFOvuCS1QC8nsapSrzg1JzW5pLomsyZT0TZTy1DPoFavJDE7VSGv9n@BglZatKFB7H8A "Ruby – Try It Online")
[Answer]
# Java 8, ~~68~~ 67 bytes
```
n->{for(int i=9;;)if(++i!=(int)(i+0f))System.out.println(i*n/n--);}
```
Uses the 32-bit `float`, but by changing `0f` to `0d` and `int` to `long` it can also be tested with the 64-bit `double`.
[Try it online with `int` and `0f`.](https://tio.run/##LY4xDoMwDEV3TuFuSVEoHasIblAWxqpDGkhlCgaRgFQhzp4GymLJT9/Pv1GzEk318bpV1sJdIS0RAJKrR6N0DcW2Asw9VqBZ4EBcBrRGYVinHGoogCADTyJfTD/uIcxuUnI0LI7xlG2IM4xTw3n5ta7ukn5yyTAG3hLDM11ICC5XLzftML3aoD3s@@suFGOlCwfvxxMU/7eiRLNrmh6FVv8D)
[Try it online with `long` and `0d`.](https://tio.run/##LY7LDoIwEEX3fsW4ayVFXJoG/0A2LI2LWh4ZLFNCC4khfHstymaSe5J75nZqVqKr3kEb5RzcFdJyAEDy9dgoXUOxRYDZYgWaRQ7EZUTrIR7nlUcNBRDkEEjclsaOzFhqAfOrlBwbliR4zLciZ5hkFeflx/m6T@3k02GM3BDDE51JCC7XIDfvML1M9O763@8@LmOlj4X28QTF/7Mo1eySZfuiNXwB)
**Explanation:**
```
n->{ // Method with integer parameter and no return-type
for(int i=9;;) // Loop `i` from 9 upwards indefinitely:
if(++i // Increase `i` by 1 first
!= // And if it does not equal:
(int)(i+0f)) // Itself as float, and casted back to integer:
System.out.println(i // Print the current `i`
*n/n--);} // And decrease `n` by 1
// (and due to the `n/n`, the infinite loop will stop as soon
// as `n` becomes 0, with a division by zero error)
```
[Answer]
# JavaScript, 46 bytes
```
n=>{for(x=1n;n;)+[++x]!=x&&console.log(x)&n--}
```
This will certainly timeout on TIO. So, here is a [TIO link which initialize `x` with 253](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1q46Lb9Io8LWKE9Ly9Q4zzrPWlM7Wlu7IlbRtkJNLTk/rzg/J1UvJz9do0JTLU9Xt/Z/moahgeZ/AA).
---
* Save ~~7~~ 10 bytes, thanks to Neil.
* Save 2 bytes, thanks to Arnauld
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 9 bytes
```
&#N_=N+.0
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/X03ZL97WT1vP4P9/AA "cQuents – Try It Online")
`&` is broken on TIO right now, so TIO link will not work, but it would time out anyway, as the only way to start at `2^53` is modifing the interpreter.
## Explanation
```
Implicit input n
& Output first n terms of the sequence
# Only include an integer N in the sequence if:
N N
_= is not equal to
N+.0 N converted to float
```
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
n=1
exec"while n==int(.0+n):n+=1\nprint n;n+=1\n"*input()
```
Starting from 1 takes a very long time. For testing purposes, starting at \$2^{53}\$ gives the same results but much quicker: [Try it online!](https://tio.run/##K6gsycjPM/r/P8/WSEvL1JgrtSI1Wak8IzMnVSHP1jYzr0RDz0A7T9MqT9vWMCavoAgoopBnDeEpaWXmFZSWaGj@/28CAA "Python 2 – Try It Online")
We count up values of `n` (an integer) until we find one for which converting to a float (by adding `.0`) and back to an int doesn't result in the same number. We then print that value and go to the next `n`. An [`exec` loop](https://codegolf.stackexchange.com/a/64/16766) lets us do this a fixed number of times according to the input.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 54 bytes
```
n=>{for(int i=1;;)if(++i!=(int)(i+0f))Print(i*n/n--);}
```
Port of Kevin Cruijssen's Java answer
[Try it online!](https://tio.run/##FckxDoMwDEbhvaegm00UGmYTpO4MqDdAIZb@xUgJW9WzpzB@76XqU0V7pxOHTbBz1tgszl89Cl3sEEcRhpJzeMY7McEFZV7LBUJvL/Oe5dfkofcf1q3UTJ@87QssEzNLG0P4Aw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
µ¾ÐtnïÊi,¼
```
No TIO, because it will time out way before it reaches the first number `9007199254740993`.. I'm using the legacy, since it is run in Python, so will output the same numbers as [the Python answer](https://codegolf.stackexchange.com/a/180421/52210). I'll see if I can determine the first few numbers for the new version of 05AB1E as well, which is run in Elixir (but that will be a separated answer in that case).
As alternative for the TIO, here a prove that `tnï` for input `9007199254740993` does not result in `9007199254740993`, but in `9007199254740994` instead: [Try it online.](https://tio.run/##MzBNTDJM/f@/JO/w@v//LQ0MzA0tLY1MTcxNDCwtjQE)
**Explanation:**
```
µ # Loop until the counter_variable is equal to the (implicit) input
# (the counter_variable is 0 by default)
¾Ð # Push the counter_variable three times
t # Take its square-root
n # And then the square of that
ï # And cast it back from a decimal to an integer
Êi # If they are NOT equal:
, # Print the counter_variable
¼ # And increase the counter_variable by 1
```
05AB1E has no builtin to set the `counter_variable` manually unfortunately, otherwise I would have set it to about `9007199254740000` at the start.
] |
[Question]
[
Based on the interpretation user [@ThePirateBay](https://codegolf.stackexchange.com/users/72349/thepiratebay) made from the **[first version](https://codegolf.stackexchange.com/revisions/140321/1)** of my own challenge
### [Output diagonal positions of me squared](https://codegolf.stackexchange.com/questions/140321/output-diagonal-positions-of-me-squared)
now I challenge you to make ASCII art that draws diagonal lines based on a square character matrix based on a given number `n`.
# Input
A number n.
# Output
A square matrix of size `n^2` which outputs diagonals represented by the adequate one of the `\ X /`chars. All other positions are to be fulfilled with `#` chars.
# Examples:
```
1
X
2
\/
/\
3
\#/
#X#
/#\
4
\##/
#\/#
#/\#
/##\
5
\###/
#\#/#
##X##
#/#\#
/###\
```
There will be no accepted answer. I want to know the shortest code for each language.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁼þµḤ+Ṛị“/\X#”Y
```
A monadic link taking a number and returning a list of characters; or a full program printing the result.
**[Try it online!](https://tio.run/##AScA2P9qZWxsef//4oG8w77CteG4pCvhuZrhu4vigJwvXFgj4oCdWf///zU "Jelly – Try It Online")** or see [[1-12] in one go](https://tio.run/##ATYAyf9qZWxsef//4oG8w77CteG4pCvhuZrhu4vigJwvXFgj4oCdWf8xMsOH4oKsauKBvsK2wrb//zI "Jelly – Try It Online").
### How?
```
⁼þµḤ+Ṛị“/\X#”Y - Link: number, n
þ - outer product (implicit range build on left AND right from n) with:
⁼ - is equal (yields a table of 0s except the main diagonal is 1s)
µ - monadic chain separation, call that I
Ḥ - double (change all the 1s to 2s)
Ṛ - reverse I (a table of 0s with 1s as the anti-diagonal)
+ - add (vectorises to make a table of zeros with 2s on the diagonal,
- 1s on the anti-diagonal and, if the meet, a 3 at the centre)
“/\X#” - literal list of characters ['/','\','X','#']
ị - index into (replaces... 1:'/'; 2:'\'; 3:'X'; and 0:'#')
Y - join with newline characters
- as a full program: implicit print
```
[Answer]
# [Python 2](https://docs.python.org/2/), 83 bytes
```
n=input()
for i in range(n):l=['#']*n;l[i],l[~i]='\X/X'[i-~i==n::2];print''.join(l)
```
[Try it online!](https://tio.run/##BcGxCsIwFAXQ3a8IOLxErIWCS8r7j0LM0MHWK@EmhHRw6a/Hc8qvfTKn3qlgOZp1ly1XAwOaunJ/WzqfNMhV4o1zCoj3FE5EldcyLhIwnFCl91OcSwWbyOObQZtc788/ "Python 2 – Try It Online\"teglj9E0C02tfdvLC3CYsdnbOhi0XQSWav0mgo@l9/QM \"Python 2 – Try It Online")
-3 thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) and [G B](https://codegolf.stackexchange.com/users/18535/g-b).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~73 61~~ 59 bytes
```
->n{(0...n).map{|x|w=?#*n;w[x],w[~x]=?\\,n==1+x*2??X:?/;w}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNAT08vT1MvN7GguqaiptzWXlkrz7o8uiJWpzy6riLW1j4mRifP1tZQu0LLyN4@wspe37q8tva/hqGenqEBXF9BaUmxQrS6rq6uuk4aUHNs7X8A "Ruby – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 16 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
.↔╝Ζ #ŗ.2%?╬3←╬¡
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=LiV1MjE5NCV1MjU1RCV1MDM5NiUyMCUyMyV1MDE1Ny4yJTI1JTNGJXUyNTZDMyV1MjE5MCV1MjU2QyVBMQ__,inputs=NQ__)
Finally got use out of the fact that palindromizating `/` or `\` on the edge creates `X` (but this could be ~5 bytes less with a couple features I have had in mind for a while (e.g. that overlapping would overlap slashes too and palindomizating commands have the option to choose the overlap amount from the remainder of ceiling dividing))
Explanation:
```
.↔ push input ceiling-divided by 2 (. is required because SOGLs input is taken lazily)
╝ create a diagonal of that length
Ζ #ŗ replace spaces with hashes
.2%? if the input % 2 isn't 0
╬3 palindromize with 1 overlap
← stop program
έ [else] palindromize with 0 overlap
```
[Answer]
# [R](https://www.r-project.org/), 68 bytes
```
write(c("#","\\","/","X")[(d=diag(n<-scan()))+d[n:1,]*2+1],"",n,,"")
```
[Try it online!](https://tio.run/##K/r/v7wosyRVI1lDSVlJRykmBkjoA3GEkma0RoptSmZiukaejW5xcmKehqampnZKdJ6VoU6slpG2YayOkpJOng6Q1Pxv8h8A "R – Try It Online")
Reads `n` from stdin. Creates a matrix of indices `(d=diag(n))+d[n:1,]*2+1` to index into the vector of characters to print, which results in a vector of characters. `write` writes it as a matrix to `""` (stdout) with `n` columns and separator `""`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
UB#Nν↗∕ν²×X﹪ν²‖BOL﹪ν²
```
[Try it online!](https://tio.run/##RcqxCsIwEADQPV8RIsIFUgTdOnYTREtVcI3x2gbTNJyXgl8fF8X5PTdacrMNpZyRG@ueA805PkCtlBb7mDIf83RHgqhFSz4y1NfU@WFkIzcQjdzqH1z8hC9QN2Xk@itadNgHdNxkZqQ@vE8LUrAJ6sN/lbIr1RI@ "Charcoal – Try It Online") Verbose version.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
'\/X#'iXytPE+)
```
[Try it online!](https://tio.run/##y00syfn/Xz1GP0JZPTOisiTAVVvz/39zAA "MATL – Try It Online")
Explanation: suppose the input is 3
```
'\/X#' push this character string.
i read in input. stack is ['\/X#';3]
Xy push nxn identity matrix.
stack is ['\/X#'; [1 0 0 ; 0 1 0 ; 0 0 1]]
tP duplicate and flip left-right
stack is ['\/X#'; [1 0 0 ; 0 1 0 ; 0 0 1];
[0 0 1 ; 0 1 0 ; 1 0 0]]
E+ double TOS and add top 2 stack elements
stack is ['\/X#'; [1 0 2 ; 0 3 0 ; 2 0 1]]
) index; 1-based modular, so
1 -> \, 2 -> /, 3 -> X, 0 -> #
implicit output.
```
[Answer]
# Javascript, 103 bytes
```
n=>{for(let i=n,j,s;i--;){s="";for(j=n;j--;)s+=i==j?n-j-1==j?"X":"\\":n-j-1==i?"/":"#";console.log(s)}}
```
[Try it online!](https://tio.run/##LclNCsIwEIbhvaco4ybBRqn/NIy9hotuSk1KhjKRprgpPXt0wM3DN@9Q9@lSP4X3bDi@XB7dXHgsMuNj8XFScgfkkspkgzFWLwkBrLwI2ZKktMOASA0bMpUMeEINbQv1v4QGDr@yBdtHTnF0@zEOKul1zV5VeuPVUTgJZ@EiXIWbcNf5Cw "JavaScript (Node.js) – Try It Online")
A more readable version with spaces and breaks added:
```
n => {
for (let i = n, j, s; i--;) {
s="";
for (j = n; j--;)
s += i == j
? n - j - 1 == j
? "X"
: "\\"
: n - j - 1 == i
? "/"
: "#";
console.log(s)
}
}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 20 bytes
```
´Ṫ§o!"¦/X#"+=ȯD=←¹+ŀ
```
[Try it online!](https://tio.run/##ASgA1/9odXNr///CtOG5qsKnbyEiwqYvWCMiKz3Ir0Q94oaQwrkrxYD///81 "Husk – Try It Online")
[Answer]
# [V](https://github.com/DJMcMayhem/V), 24 bytes
```
Àé#ÀÄòr\jlò|òr/klòÇÜ/ãrX
```
[Try it online!](https://tio.run/##K/v//3DD4ZXKQKLl8KaimKycw5tqgAz9bCDjcPvhOfqHFxdF/P//3wwA "V – Try It Online")
[Answer]
# Mathematica, 114 bytes
```
(s=#;F[x_]:=DiagonalMatrix[Table[x,s]];z=F@"\\"+Reverse@F@"/"//. 0->"#";If[OddQ@s,z[[t=⌈s/2⌉,t]]="X"];Grid@z)&
```
[Answer]
# [Python 2](https://docs.python.org/2/), 133 bytes
```
def f(k,h="#"):s=[h*i+"\\"+h*(k-i*2-2)+"/"+i*h for i in range(k/2)];print"\n".join(s+k%2*[k/2*h+"X"+k/2*h]+[e[::-1]for e in s[::-1]])
```
[Try it online!](https://tio.run/##XcxBCsMgEIXhq8iUgjqxIa6KIfcoqItCtU4FDUk2Pb1tml137@fBN7@3VItu7REiizx3aYITCLNONklCcA4wSZ4VSa20QOgBSSYW68KIUWHLvTwDz70WfpwXKhu4ApdXpcJXzGct7feTCeEG@FsebbDGqMHvRtiN9Wgv2h87dFdhIidx0O0D "Python 2 – Try It Online")
A beautiful mess done on mobile :-). If you have golfing suggestions, you are welcome to edit in yourselves (and credit you!), because I will be sleeping :P.
[Answer]
# [Python 2](https://docs.python.org/2/), 122 bytes
```
def f(n):s='\\'+'#'*(n-2)+'/';return['x'][:n]if n<2else[s]+['#'+l+'#'for l in f(n-2)]+[s[::-1]]
print'\n'.join(f(input()))
```
[Try it online!](https://tio.run/##FYxNCgIhGIb3nUJo8WkyRUIba06i7lIy5FXUgTq946yfn/Lvnww1xtsHFjiEbitZS5LOdOFYlJB0o2f1fasw9CNnNFwMDC/lU/OmOWmmK9NRhFxZYhHHaaYTNaP1cnfuVGpEJwu6fnMEDzyibJ0LIcZ47A "Python 2 – Try It Online")
A recursive aproach
[Answer]
# [Perl 5](https://www.perl.org/), 81 bytes
```
for$i(0..($n=<>)-1){$_='#'x$n;s|.{$i}\K.|\\|;s%.(.{$i})$%/$1%;s%/%X% if!/\\/;say}
```
[Try it online!](https://tio.run/##K0gtyjH9/z8tv0glU8NAT09DJc/Wxk5T11CzWiXeVl1ZvUIlz7q4Rq9aJbM2xluvJiamxrpYVU8DLKCpoqqvYqgKFNBXjVBVyExT1I@J0bcuTqys/f/f9F9@QUlmfl7xf11fUz0DQwMA "Perl 5 – Try It Online")
[Answer]
## [Canvas](https://github.com/dzaima/Canvas), 15 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
::#×*;\:↔11╋11╋
```
[Try it online!](https://dzaima.github.io/Canvas/?u=JXVGRjFBJXVGRjFBJTIzJUQ3JXVGRjBBJXVGRjFCJXVGRjNDJXVGRjFBJXUyMTk0JXVGRjExJXVGRjExJXUyNTRCJXVGRjExJXVGRjExJXUyNTRC,i=NQ__)
could get it to 11 bytes if canvas's overlap function had a default setting but it doesn't so...
[Answer]
# Mathematica, 99 bytes
```
FromCharacterCode[(2#+Reverse@#+2)&@DiagonalMatrix[45~Table~#]/.{2->35,137->88}]~StringRiffle~"\n"&
```
This uses a somewhat different technique from the other Mathematica solution. Also, we should probably start calling it the Wolfram Language at some point.
] |
[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/125889/edit).
Closed 6 years ago.
[Improve this question](/posts/125889/edit)
## Your Task
Write a program that displays a dot that moves toward the position of your mouse at 4 pixels per second. The dot must be 100 pixels big and the window must fill the computer screen.
## Input
None
## Output
A window showing an animated dot moving towards the mouse at a fixed, non-changing speed.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
# HTML + JavaScript, 140 bytes
Infinite speed
```
t=c.getContext`2d`
c.onmousemove=e=>(x=e.clientX,y=e.clientY)
setInterval(_=>t.clearRect(0,0,1e5,1e5)||t.fillRect(x,y,10,10),9)
```
```
<canvas id=c>
```
Non-cheaty, 188 bytes
```
x=y=0,t=c.getContext`2d`
c.onmousemove=e=>(z=e.pageX,w=e.pageY)
f=_=>t.clearRect(0,0,1e5,1e5)||(m=((a=z-x)**2+(b=w-y)**2)**.5)|t.fillRect(x+=a/m,y+=b/m,10,10)
setInterval(f,9)
```
```
<canvas id=c>
```
Larger and faster:
```
x=y=0,s=3,t=c.getContext`2d`
c.onmousemove=e=>(z=e.pageX,w=e.pageY)
f=_=>t.clearRect(0,0,1e5,1e5)||(m=((a=z-x)**2+(b=w-y)**2)**.5)|t.fillRect(x+=s*a/m,y+=s*b/m,10,10)
setInterval(f,9)
```
```
<canvas id=c height=999 width=999>
```
[Answer]
## Python 3 + Tkinter, 264 262 259 254 bytes
```
import tkinter as t,numpy as n
f=t.Tk()
p=n.array([1,1])
q=n.array([0.]*2)
c=t.Canvas(f)
c.pack()
def s(e):p[:]=e.x,e.y
c.bind("<Motion>",s)
z=c.create_oval(0,0,2,2)
def r():d=p-q;u=(d*d.T+.1)**-0.5;c.move(z,*u*d);q[:]+=u*d;c.after(9,r)
r()
f.mainloop()
```
Thanks to @Gryphon for saving 2 bytes, to @Jonathan Allan for another one, and to @Challenger5 for five.
Changed `1e-9` to `.1` for another two.
[Answer]
# Mathematica, 89 bytes
```
Graphics[Disk[Dynamic[MousePosition["Graphics",{0,0}]],.1],PlotRange->10,ImageSize->1000]
```
[](https://i.stack.imgur.com/NF0ev.gif)
[Answer]
# Python 2 + Pygame, 178 Bytes
-2 bytes thanks to @ASCII-only, because I was being an idiot
-12 bytes thanks to @officialaimm, also because I was being an idiot
-11 bytes thanks to @JonathanAllan, for telling me the default window size was the screen size
-2 bytes thanks to @WheatWizard, also because I was being an idiot
-18 bytes thanks to @nore, because I didn't have to use the if/else statements
-24 bytes thanks to @nore, who reminded me to put the whole loop on one line.
-42 bytes thanks to @WheatWizard
-3 bytes thanks to @ASCII-only
```
from pygame.locals import*
from pygame import*
init()
a=display.set_mode()
b=c=0
while 1:a.fill((0,0,0));x,y=mouse.get_pos();draw.rect(a,(9,9,9),
(b,c,b+10,c+10));display.update()
```
This is definitely no longer the best way to do this, so I may come out with a version that's better suited to the new requirements of the question. The dot is 10 pixels by 10 pixels. The screen size is the size of the computer screen.
If you can see the dot, I'm impressed, as it is almost the exact same colour as the background, to save on byte counts for RGB colours.
] |
[Question]
[
A program is *"conveniently palindromic"* if
>
> it is equal to the string derived when its reverse has all its parentheses (`()`), brackets (`[]`), and braces (`{}`) flipped. No other characters are special and require flipping. (`<>` are sometimes paired but often not so they are left out.)
>
>
> copied from this [challenge](https://codegolf.stackexchange.com/questions/28190/convenient-palindrome-checker).
>
>
>
Write a conveniently palindromic program that prints its own source.
You must be able to prove that it is impossible to remove one or more byte from the program so that the resulting program, when executed in the same language:
* prints the original source, or
* prints the new modified source
Note that the resulting program won't necessarily be a convenient palindrome. It also means that you cannot use comments or equivalent structures.
## Rules
* Program must be longer than one character
* Reading you own source code (from the file or any other resource) is forbidden.
* Your program must be a [proper quine](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð
```
[Try it online!](https://tio.run/nexus/jelly#@394w8Odsx/u3Pdw57SHO2cdnfRwR8vhHY8a5hzeAWQBuTtngWWA8rMPb/j/HwA "Jelly – TIO Nexus")
### Verfication
A string of length **17** has only **217 = 131,072** subsequences, so this can be done by brute force.
```
$ # Generate all 131,072 subsequences of the source code.
$ jelly eun '“ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð”ṾḊṖŒPY' > subsequences
$ wc -l subsequences
131072 subsequences
$ cat verify.py
import jelly
# Discard extraneous output to STDOUT (just a bunch of 0's and [0]'s).
jelly.print = lambda _, end: None
for line in open('subsequences').readlines():
line = line.strip()
try:
output = jelly.stringify(jelly.jelly_eval(line, []))
except:
output = ''
if output == line or output == 'ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð':
print(repr(line))
$ time python3 verify.py
'ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð'
real 0m9.678s
user 0m9.653s
sys 0m0.028s
```
### How it works
```
ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð Main link. No arguments. Implicit left argument: 0
ø Make the chain to the right niladic.
“øḄŒṚṖṾṛð Yield the string 'øḄŒṚṖṾṛð'.
ð Make the chain to the right and up to ø dyadic.
The main link is now a monadic 2,0-chain, so the dyadic chain
is called with the implicit left argument 0 and right argument
'øḄŒṚṖṾṛð'.
ṛ Yield the right argument, i.e., 'øḄŒṚṖṾṛð'.
Ṿ Uneval; yield the string representation of the right argument,
i.e., '“øḄŒṚṖṾṛð”'.
Ṗ Pop; remove the last character, yielding '“øḄŒṚṖṾṛð'.
Ṛ Reverse, yielding 'ðṛṾṖṚŒḄø“'.
ŒḄ Bounce, yielding 'ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð'.
(implicit) Print the last return value.
```
[Answer]
# [7](https://esolangs.org/wiki/7), 12 bytes
The program is in binary. Here's an `xxd` dump:
```
00000000: 47b6 1818 b647 47b6 1818 b647 G....GG....G
```
This is rather more readable in the alternative octal notation (which isn't a valid answer to the question because changing the encoding changes the boundaries between bits):
```
2173303006133107217330300613310
```
[Try it online!](https://tio.run/nexus/7#@29kaG5sbGBsYGBmaGxsaGCOxv//HwA "7 – TIO Nexus")
Here's how the octal encoding of one half of the program corresponds to the packed encoding. (The other half is identical, except that it doesn't have a trailing `7` command because trailing `1` bits are treated like trailing whitespace, and ignored.) This is the form in which I actually worked on the problem, because trying to ensure that a program makes sense when viewed as three-bit chunks, but is palindromic when viewed as eight-bit chunks, is really unintuitive.
```
2 1 7 3 3 0 3 0 0 6 1 3 3 1 0 7
...'''...'''...'''...'''...'''...'''...'''...'''
010001111011011000011000000110001011011001000111
........''''''''........''''''''........''''''''
47 b6 18 18 b6 47
```
Like most golfed 7 quines, this program consists of two halves, each of which prints the other. Each half is originally passive on the stack, but an active copy is made and executed when the program runs out of commands to run, in reverse order from right to left. Here's how the active copy works (I'm using the escaped representation here because the unescaped representation contains some commands that don't have names, and thus are hard to talk about):
```
2 Copy the top of the stack
173303006 Push "330300" onto the stack
13 Pop the top of the stack
3 Output the copy of the top of the stack, and discard the original
10 Append nothing to the top of stack
```
In other words, each half of the program prints itself (because it's still at the top of the stack; the original wasn't removed when the copy was made), and then throws itself away. So this is effectively just the standard 7 quine `23723` written in a particularly verbose way, to make it palindromic at the byte level.
There's quite a lot of junk code here that doesn't do anything useful, and it could easily be deleted if deletions were at the command level. (As a result, I suspect this can be golfed substantially smaller, but I can't see how.) This might seem to violate the specification; however, the problem defines comment-freedom via deletion at the *byte* level (which makes about as little sense for 7 as requiring the program to be a palindrome at the byte level does), and doing that will typically throw off the boundaries between commands, making the program quite different. The rest of this post, therefore, talks about how I ensured that no deletions could lead to a proper quine.
## Verification
I used the following Perl program to find all 7 quines, and all 7 programs printing the original program, that could be produced via deleting from the existing code (plus the original code itself, as it was easier to disregard that by hand than to write code to ignore it):
```
use 5.010;
use IPC::Run qw/run timeout/;
undef $/;
$| = 1;
my %seen = ();
my $original = <>;
sub check_program {
my $unprocessed = shift;
my $processed = shift;
if ($unprocessed eq '') {
my ($out, $err);
$seen{$processed} and return;
$seen{$processed}++;
my $binary = unpack "B*", $processed;
$binary =~ s/1+$//;
$binary .= 1 while (length $binary) % 3;
my $program = "";
$program .= oct "0b$&" while $binary =~ s/^...//;
print "$program \r";
my $ok = "t";
eval {
$ok = run [$^X, '7.pl'], '<', \$processed, '>', \$out, '2>', \$err, timeout(1);
$ok = $ok ? "x" : "e";
};
if ($out eq $processed || $out eq $original) {
$out eq $original and $ok .= "o";
print "$program $ok\n";
}
} else {
$unprocessed =~ s/^.//;
check_program($unprocessed, $&.$processed);
check_program($unprocessed, $processed);
}
}
check_program($original, "");
```
The program produces quite a bit of output, because there are a number of 7 quines that can be produced like this. However, none are *proper* quines. They fall into three groups, listed here in octal to make it easier to verify that they aren't proper quines:
### Programs which print themselves plus `21`, but crash before it can be output
```
2161403021733030061
2161403055414030555
2161403055414030
2161403055443430555
2161403055443430
2161403055443507061
2161403055533030555
2161403055533030
21614030555
21614030
```
These programs each consist of the escaped representation of a single stack element that starts `721614030`. (Where did the initial `7` come from? Each program starts with two empty elements on the stack, which is equivalent to two implicit `7`s.) When it gets unescaped at runtime, its behaviour breaks down like this:
```
7216 Append "21" to the top of stack
14 Push two empty stack elements beneath the top of stack
0 Escape the top of stack, then append it to the element beneath
3 Output the top of stack, delete the second stack element
0 Crash due to insufficient stack
```
Now, when producing the first output in 7, you have to specify an output format. If the output is in need of escaping, that automatically escapes it and prepends a 7, and the first character output (in this case a 7) selects the format; most 7 quines rely on this. These programs, however, do the escaping manually, meaning that there's no implicitly prepended 7. Rather, the 7 at the start of the escaped representation (`72161403021`, etc.) ends up selecting the format, so it doesn't get escaped explicitly. In other words, the program prints itself plus an appended `21`, then crashes.
The problem, of course, is that we're using packed, not octal, representation, so `21` is only six bits long, i.e. not a byte. As such, it can't (with programs of the lengths shown here) be output immediately, because more bits are needed to determine which byte to output. The `21` would be padded up to a full byte with 1 bits if the program exited normally, but it never gets a chance; it crashes before anything more can be output. When the crash occurs, the interpreter just exits immediately, and never gets the chance to print the incomplete byte.
Of course, this is an improper quine because all the output that's actually produced was produced via literally printing the corresponding characters of the original program.
### Programs that print themself literally
**Programs that crash:**
```
2173303006133107061
217330300613310721614030555
217330300613310721614030
```
**Programs that exit normally:**
```
2173303006133030555
2173303006133030
2173303006133107061333
217330300613310
21733030061333
21733030554434300613310
2173303055443430061333
21733030555330300613310
2173303055533030061333
```
These all follow the same basic principle as the original program, but only have one stack element (either because the `7` that would normally separate stack elements got deleted, or because it's matched by a `6` later in the program, combining the element into one large element). The stack element prints itself literally first, for the same reason that the two elements in the original program each print the other, and then runs some random commands that don't produce output. Because the entire program is basically just a literal that prints itself, this doesn't count as a proper quine
### The null quine
Yes, the null program is a quine in 7, and yes, you can produce it via deleting from the original program. This clearly isn't a proper quine, though.
[Answer]
# [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 3 Bytes.
```
1
1
```
Good luck out golfing this one.
This is a valid quine, as each `1` prints the opposite `1`, which can be proven by the code
```
1
2
```
which prints
```
2
1
```
As for removing characters, `11` prints `11`, although is not a valid quine, as it's a constant. The other options, `1_` and `_1` (where \_ is a newline) are also not valid, as they are only constants, and they are missing the white space.
[Try it online!](https://tio.run/nexus/rprogn#@2/IZfj/PwA "RProgN – TIO Nexus")
[Answer]
# Befunge-98, 55 or 57 bytes
```
<#0289+*00#p>$$$>:#,_652**,@,**256_,#:>$$$>p#00*+9820#<
```
[Try it online!](http://befunge-98.tryitonline.net/#code=PCMwMjg5KyowMCNwPiQkJD46IyxfNjUyKiosQCwqKjI1Nl8sIzo+JCQkPnAjMDAqKzk4MjAjPA&input=)
This solution is dependent on the behaviour of wraparound strings. Most Befunge-98 implementations will push a space onto the stack whenever a string wraps across the edge of the playfield, while the FBBI interpreter (which is what is used by TIO) will not. If you want to test this on other interpreters, you'll most likely need to include an additional `$` (drop) command to get rid of that extra space:
```
<#0289+*00#p>$$$$>:#,_652**,@,**256_,#:>$$$$>p#00*+9820#<
```
In theory it should be possible to make a more portable solution that would work on all interpreters (possibly even Befunge-93), but that would require a good deal more code.
**Proof of validity**
While there are characters in the code that aren't actually executed, they are all used in the construction of the output, and removing any of those characters will result in output that neither matches the original source or the modified source. This is because the output string is built up in reverse, and it is thus imperative that the source be palindromic for the output to match. If you can remove a character and still have it work, you'll just have created a better solution.
**Explanation**
```
< Reverse the direction of execution, wrapping to the end of the line.
0#< Jump over the zero.
*+982 Push 34 (a double quote character) onto the stack.
00 Push two zeros - the coordinates of the first character in the source.
>p# Turn around and 'put' the double quote into the source at 0,0.
00*+982 In reverse, this just pushes some numbers that will be ignored.
0 This zero will serve as the string terminator though.
#< Jump over the left arrow so we can wrap around back to the start.
"#0289+*00... At this point the first character has been updated to a quote, so
we're now going to switch to string mode and push the entire source
onto the stack in reverse order. When the end of the line is reached,
the string will wrap around to the start and terminate when it
encounters the quote again.
#0289+*00#p Again we've got a sequence pushing values that we don't actually want.
>$$$ This time we need to get rid of them, with a few drop operations.
>:#,_ A standard output routine, writing out the source from the stack.
652**, The last '<' character has to be output manually though.
@ Then finally we can exit.
```
] |
[Question]
[
Your challenge is to create a basic version of Space Invaders in Python
## Rules
* Program must be not written in Py3K
* All levels must be randomly generated
* There must be a HUD showing the players score
The winner would be the answer which uses the least amount of code
Some Questions
Q: *How detailed do the aliens and other elements have to be?*
A: **The aliens should be Block ASCII**
Q: *Can the bunkers be simplified to rectangles?*
A: **Yes, as long as they are filled**
Q: *How many enemies/bunkers do there have to be?*
A: **Number of Enemy's are chosen by random. 4 bunkers**
Q: *Do we need to implement the "mystery ship" that goes across the top of the screen?*
A: **No**
Q:*Do the symbols/characters that make up the laser cannon and the aliens need to be different?*
A: **Yes**
Q: *Do they need different shapes?*
A: **Yes**
Q: *Does it matter how fast the bullets/lasers travel?*
A: **No**
[Answer]
## ~~3060~~ 3031 characters
OKAY, this was fun. But I very highly doubt that my code is short enough to compete, or if it's basic enough. I'm new to code golf but regardless, I had fun and that's what matters. I'm too used to object-oriented programming so a lot of my code is probably just too much objects...
Game runs solely in the console, and I shortened most of the code with the `exec''''''.replace()` method. Complete with input of your name, random enemy firing, walls, aliens are randomly generated, worth 50 points each. each time you fire you lose one point so that you lose points if you just hold space in one spot to beat the level. Enemy speed increases each level, capped at every 0.2 seconds. Prints the level number, and game over at the bottom, your name,lives, and score at the top left. you have 3 lives. Ungolfed version is ~9500 characters, but I'll leave that out of here for now
instructions: fire with `space`, move with `a` and `d`, exit with `x`
let me know what think, if I can improve on anything
edit: forgot that msvcrt is Windows-Only. perhaps I can make a unix version too...
```
exec'''import threading as t
import msvcrt,Queue,time,random,os
u=raw_input('name:')
r=range
@Z:
$~(S):S.w=78;S.h=30;S.X();S.l='';S.Q=[];S.q=[];S.m=''
$J(S,x,y,c):S.q.append([x,y,c])
$X(S):S.s=[[' '^y in r(78)]^x in r(30)]
$V(S):
?s='';S.X()
?^x,y,z in S.q:S.s[y][x]=z
?S.q=[]
?^x in S.s:
? ^y in x:s+=y
? s+='\\n'
?s+=S.m.center(S.w)
?if s!=S.l:os.system('cls');S.l=s;print s
@E(Exception):pass
@C:
$~(S,g,c,p):S.g=g;S.c=c;S.p=p;S.s=[]
$M(S,a,d):
?if (a<0 and S.p[d]==0) or (a>0 and S.p[d]==(S.g.z.h if d else S.g.z.w)-1):raise E()
?S.p[d]+=a
$X(S):S.s.remove(S)
@A(C):
$~(S,g):C.~(S,g,'A',[39,28])
$M(S,a,d=0):
?try:C.M(S,a,d)
?except E:pass
@Y(A):
$~(S,g,p):C.~(S,g,'Y',p);S.s=g.a
@B(C):
$~(S,g,p,n):C.~(S,g,'|'if n<0 else'*',[p[0],p[1]+n]);S.s=g.b;S.d=n;S.a=0 if n<0 else 1
$M(S):
?try:C.M(S,S.d,1)
?except E:S.X()
$b(S):S.g.z.J(S.p[0],S.p[1],'X');S.g.z.V();S.X()
$co(S):
?^w in S.g.w:
? if S.p==w.p:S.b();w.X()
?if S.a:
? if S.p==S.g.p.p:S.b();S.g.d()
?else:
? ^a in S.g.a:
??if S.p==a.p:S.b();S.g.P(50);a.X()
@W(C):
$~(S,g,p):C.~(S,g,'#',p);S.s=g.w
@I(t.Thread):
$~(S,g):t.Thread.~(S);S.f=1;S.c={'a':g._g4,'d':g._g3,'x':g._X,' ':g._fi};S.start()
$run(S):
?while S.f:
? c=msvcrt.getch()
? if c in S.c:S.c[c]()
$X(S):S.f=0
@G:
$~(S):S.z=Z();S.x=3.0;S.c=0;S.b=[];S.Q=Queue.Queue();S.I=I(S);S.g2=0;S.g1=0;S.do=0;S.f=1;S.v=0;S.l=3;S.ti=[];S.G(1);S.O()
$O(S):
?while S.f:
? time.sleep(0.02)
? if not S.a:S.G(1)
? S.ch();S.B();S.u()
$u(S):
?S.z.X();S.P(0)
?s=u+' '+`S.l`
?^i in r(len(s)):S.z.J(i,0,s[i])
?^i in S.a+S.b+[S.p]+S.w:S.z.J(i.p[0],i.p[1],i.c)
?S.z.V()
$ch(S):
?try:
? while not S.Q.empty():S.Q.get_nowait()();S.Q.task_done()
?except Queue.Empty:pass
$cl(S):
?try:
? while not S.Q.empty():S.Q.get_nowait();S.Q.task_done()
?except Queue.Empty:pass
$_g4(S):
?if not S.g2:S.g2=1;S.Q.put(S.g4)
$g4(S):S.p.M(-1);S.g2=0
$_g3(S):
?if not S.g1:S.g1=1;S.Q.put(S.g3)
$g3(S):S.p.M(1);S.g1=0
$_X(S):S.I.X();S.Q.put(S.X)
$X(S):S.f=0;S.I.X();S.st()
$_fi(S):
?if not S.do:S.do=1;S.Q.put(S.fi)
$fi(S):S.b.append(B(S,S.p.p[:],-1));S.do=0;S.P(-1)
$_af(S):S.Q.put(S.af)
$af(S):c=random.choice(S.a);S.b.append(B(S,c.p[:],1));S.nt(random.uniform(0.1,2),S._af)
$nt(S,n,f):x=t.Timer(n,f);S.ti.append(x);x.start()
$st(S):
?^i in S.ti:i.cancel()
$G(S,n=0):
?S.st();S.cl();S.p=A(S);S.a=[];S.w=[];S.b=[]
?^x in[[i,o]^i in r(30)^o in r(3,10)]:
? if random.randint(0,99)%4==0:S.a.append(Y(S,x))
?S._m();S._af();f=[]
?^x in [6,27,46,65]:f+=[[z,y]^z in r(x,x+6)^y in r(23,26)]
?^i in f:S.w.append(W(S,i))
?S.v+=n;S.z.m='Level %s'%S.v;S.u()
?if S.x>0.2:S.x=1.6 - S.v*0.1
?S.m1=0;S.m2=0;S.k=1;time.sleep(3)
$_m(S):S.Q.put(S.m)
$m(S):
?x=0
?if S.m2:S.m2=0;S.m1=0;S.k=-S.k;x=1
?^i in S.a:i.M(*(abs(S.k),1)if x else(S.k,0))
?if S.m1==47:S.m2=1
?else:S.m1+=1
?S.nt(S.x,S._m)
$B(S):
?^i in S.b:i.M();i.co()
$d(S):
?S.l-=1
?if S.l==0:S.z.m='Game Over!';S.X();return
?S.G(0)
$P(S,n):
?S.c+=n if S.c+n>0 else 0;x=`S.c`
?^n in r(len(x)):S.z.J(n,1,x[n])
G()'''.replace('@','class ').replace('?',' ').replace('$',' def ').replace('^','for ').replace('~','__init__')
```
what the screen looks like:
```
Blazer 3
488 |
YY Y YY Y Y Y Y
YY Y YY Y Y Y
Y Y Y Y YY
Y Y Y
YY Y Y Y Y Y
Y YY YX Y Y
Y Y | Y
|
*
|
#### | ###### ###### ######
###### ###### ###### ######
###### ###### ###### ######
A
Level 1
```
edit: managed to remove something I accidentally left in I wasn't using anymore
] |
[Question]
[
**This question already has answers here**:
[Encode a program with the fewest distinct characters possible](/questions/11690/encode-a-program-with-the-fewest-distinct-characters-possible)
(10 answers)
Closed 3 years ago.
**Introduction:**
Although it seems challenges scored by least unique characters [have](https://codegolf.stackexchange.com/questions/11690/encode-a-program-with-the-fewest-distinct-characters-possible) [been](https://codegolf.stackexchange.com/questions/52655/generate-and-print-the-first-20-fibonacci-numbers-with-the-least-unique-characte) [attempted](https://codegolf.stackexchange.com/questions/34614/conways-game-of-life-with-smallest-set-of-source-characters), there are few which were well-received. I think it's a potentially interesting scoring criterion, as long as different languages aren't competing with each other (as with code golf).
**Challenge:**
Create a basic FizzBuzz program or function. The output should be the decimal numbers 1 to 100, inclusive. For multiples of three, print `Fizz` instead of the number, and for the multiples of five print `Buzz`. For numbers which are multiples of both three and five, print `FizzBuzz`.
A trailing newline is allowed, and `\n` or `\r\n` can be used to separate the numbers (and `Fizz`es and `Buzz`es and `FizzBuzz`es).
**Scoring:**
The answer (per language) with the least unique bytes wins. For example,
```
abbcccdeee
```
would have a score of 5, as it contains are 5 distinct bytes.
[Answer]
# [Unary](https://esolangs.org/wiki/Unary), score 1 (\$3.065... × 10^{185}\$ bytes)
I couldn't resist ;)
The program consists of 306542480187333548229216501998737670100823810347304444087725506753387994506955599380251625023427643514071322084229755566193943772995081070792874713832316221905650936799216302699728340431 times a single character of your own choosing, which translates to the following brainfuck program:
```
++>+++++>>>>>++++++++++[>+>>+>>+>+<<<[++++<-<]<,<,-<-<++<++++[<++>++++++>]++>>]>[+[[<<]<[>>]+++<[<.<.<..[>]]<<-[>>>[,>>[<]>[--.++<<]>]]+++++<[+[-----.++++<<]>>+..<-[>]]<[->>,>+>>>->->.>]<<]<[>+<<<,<->>>+]<]
```
Port of [*@MitchSchwartz*' brainfuck answer for the *1,2,Fizz,4,Buzz* challenge](https://codegolf.stackexchange.com/a/168511/52210), so make sure to upvote him!
[Try it online as brainfuck.](https://tio.run/##PU7bCQMxDBvIjwmEFjH@6B0USqEfhc6fyjlaOQFHkWwd79vjdf@cz7XMaAMO7I@imH0MQA2FQMPhoUavrcLPbuyZ0SyrgoTFYQyFnMpiNxCiWa4LSSNSCnXde4b2iItNXx@0zDHJW0H6RGKokn1tmXiOmPCNXusL)
The byte-count is generated with [this 05AB1E program I wrote](https://tio.run/##jU7BSkQxDLz7FaXXND2LDPEsiBfxFIJUfKwPl32wW1n2sF@kJz9B7/7SM3nLenbSQjqdTGbatadxmOf8sGnbw1XK11lAXItavrl//fp4HPPd1FNbr6f98Jz6lHa9bXvaj/0ltST5@/3y5/NYLvLtsFm9tdWwmBAL/m1CZ5N5JhIKSID@oOLMcgiABgWGoaCwN/5aVDiPk1h4mCipwoUqwRAUNaqqmAHstGjxC5cyV1d4Z7Z4@B7neKFPH0K1xpDPKouUiCTsVcVOWyJeAUd4g/0C).
[Answer]
# [GS2](https://github.com/nooodl/gs2), 1 unique byte
Another 1-byte solution. Unlike the other ones though, this one can actually be written down :P.
```
f
```
[Try it online!](https://tio.run/##Sy82@v8/7f9/AA "GS2 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 14 unique bytes (4552 bytes)
The characters I used are: `main(){}prtf+&`.
```
a(i){if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)){}}n(i){if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)){}}f(i){if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)){}if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)){}if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)&printf(&i)){}}t(i){if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)){}if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)){}if(++i&++i&++i&++i&++i&printf(&i)&printf(&i)){}}r(){}p(i){if(r()&&printf(&i)){}if(++i){}}main(i){if(a(p(i))&n()){}if(a(p(p(i)))&n()){}if(f()&n()){}if(a(p(p(p(p(i)))))&n()){}if(t()&n()){}if(f()&n()){}if(a(p(p(p(p(p(p(p(i))))))))&n()){}if(a(p(p(p(p(p(p(p(p(i)))))))))&n()){}if(f()&n()){}if(t()&n()){}if(a(p(i))&a(p(i))&n()){}if(f()&n()){}if(a(p(i))&a(p(p(p(i))))&n()){}if(a(p(i))&a(p(p(p(p(i)))))&n()){}if(f()&t()&n()){}if(a(p(i))&a(p(p(p(p(p(p(i)))))))&n()){}if(a(p(i))&a(p(p(p(p(p(p(p(i))))))))&n()){}if(f()&n()){}if(a(p(i))&a(p(p(p(p(p(p(p(p(p(i))))))))))&n()){}if(t()&n()){}if(f()&n()){}if(a(p(p(i)))&a(p(p(i)))&n()){}if(a(p(p(i)))&a(p(p(p(i))))&n()){}if(f()&n()){}if(t()&n()){}if(a(p(p(i)))&a(p(p(p(p(p(p(i)))))))&n()){}if(f()&n()){}if(a(p(p(i)))&a(p(p(p(p(p(p(p(p(i)))))))))&n()){}if(a(p(p(i)))&a(p(p(p(p(p(p(p(p(p(i))))))))))&n()){}if(f()&t()&n()){}if(a(p(p(p(i))))&a(p(i))&n()){}if(a(p(p(p(i))))&a(p(p(i)))&n()){}if(f()&n()){}if(a(p(p(p(i))))&a(p(p(p(p(i)))))&n()){}if(t()&n()){}if(f()&n()){}if(a(p(p(p(i))))&a(p(p(p(p(p(p(p(i))))))))&n()){}if(a(p(p(p(i))))&a(p(p(p(p(p(p(p(p(i)))))))))&n()){}if(f()&n()){}if(t()&n()){}if(a(p(p(p(p(i)))))&a(p(i))&n()){}if(f()&n()){}if(a(p(p(p(p(i)))))&a(p(p(p((i)))))&n()){}if(a(p(p(p(p(i)))))&a(p(p(p(p((i))))))&n()){}if(f()&t()&n()){}if(a(p(p(p(p(i)))))&a(p(p(p(p(p(p((i))))))))&n()){}if(a(p(p(p(p(i)))))&a(p(p(p(p(p(p(p((i)))))))))&n()){}if(f()&n()){}if(a(p(p(p(p(i)))))&a(p(p(p(p(p(p(p(p(p((i)))))))))))&n()){}if(t()&n()){}if(f()&n()){}if(a(p(p(p(p(p(i))))))&a(p(p(i)))&n()){}if(a(p(p(p(p(p(i))))))&a(p(p(p(i))))&n()){}if(f()&n()){}if(t()&n()){}if(a(p(p(p(p(p(i))))))&a(p(p(p(p(p(p(i)))))))&n()){}if(f()&n()){}if(a(p(p(p(p(p(i))))))&a(p(p(p(p(p(p(p(p(i)))))))))&n()){}if(a(p(p(p(p(p(i))))))&a(p(p(p(p(p(p(p(p(p(i))))))))))&n()){}if(f()&t()&n()){}if(a(p(p(p(p(p(p(i)))))))&a(p(i))&n()){}if(a(p(p(p(p(p(p(i)))))))&a(p(p(i)))&n()){}if(f()&n()){}if(a(p(p(p(p(p(p(i)))))))&a(p(p(p(p(i)))))&n()){}if(t()&n()){}if(f()&n()){}if(a(p(p(p(p(p(p(i)))))))&a(p(p(p(p(p(p(p(i))))))))&n()){}if(a(p(p(p(p(p(p(i)))))))&a(p(p(p(p(p(p(p(p(i)))))))))&n()){}if(f()&n()){}if(t()&n()){}if(a(p(p(p(p(p(p(p(i))))))))&a(p(i))&n()){}if(f()&n()){}if(a(p(p(p(p(p(p(p(i))))))))&a(p(p(p(i))))&n()){}if(a(p(p(p(p(p(p(p(i))))))))&a(p(p(p(p(i)))))&n()){}if(f()&t()&n()){}if(a(p(p(p(p(p(p(p(i))))))))&a(p(p(p(p(p(p(i)))))))&n()){}if(a(p(p(p(p(p(p(p(i))))))))&a(p(p(p(p(p(p(p(i))))))))&n()){}if(f()&n()){}if(a(p(p(p(p(p(p(p(i))))))))&a(p(p(p(p(p(p(p(p(p(i))))))))))&n()){}if(t()&n()){}if(f()&n()){}if(a(p(p(p(p(p(p(p(p(i)))))))))&a(p(p(i)))&n()){}if(a(p(p(p(p(p(p(p(p(i)))))))))&a(p(p(p(i))))&n()){}if(f()&n()){}if(t()&n()){}if(a(p(p(p(p(p(p(p(p(i)))))))))&a(p(p(p(p(p(p(i)))))))&n()){}if(f()&n()){}if(a(p(p(p(p(p(p(p(p(i)))))))))&a(p(p(p(p(p(p(p(p(i)))))))))&n()){}if(a(p(p(p(p(p(p(p(p(i)))))))))&a(p(p(p(p(p(p(p(p(p(i))))))))))&n()){}if(f()&t()&n()){}if(a(p(p(p(p(p(p(p(p(p(i))))))))))&a(p(i))&n()){}if(a(p(p(p(p(p(p(p(p(p(i))))))))))&a(p(p(i)))&n()){}if(f()&n()){}if(a(p(p(p(p(p(p(p(p(p(i))))))))))&a(p(p(p(p(i)))))&n()){}if(t()&n()){}if(f()&n()){}if(a(p(p(p(p(p(p(p(p(p(i))))))))))&a(p(p(p(p(p(p(p(i))))))))&n()){}if(a(p(p(p(p(p(p(p(p(p(i))))))))))&a(p(p(p(p(p(p(p(p(i)))))))))&n()){}if(f()&n()){}if(t()&n()){}}
```
[Try it online!](https://tio.run/##7VbRisIwEPybskH8qFKIBO6KeIV7kP66OSNW02Qn2Y0o53GIgunMJLub2e2w3Q2D9z05c3SWNhvXvet3f3DjZKlzxhzneVRGtGbbP5CPl@X6l@XpGWe7ayYXZfq/KG9zMV4RG7woBzr/7q@35fyn4@QC8LN3S@/qKRBMN9IVEhYuS9GapQywgGLYRHVOzDSmAIlASHVKtwiBZAFZhLrtgR/nMQa1iYqU@Ow1HJsKSwLeOkOKKlxKy1U5e5ylp5z9hIsSYUU8dAGKBJARtmb38IAF4sciQ8TwNnukClWz8IQW66yOXPdQBg@fLGKIvGElVWLYsYKRU2KSOjogo2@AS@TYgxxObUZeROHKkkDZnjWm1qfJoaFhGZxwlDG8RyYcIyUcfJDZbup0Z6m7OR6YmWWCcIrWRPBclTBlk1am1Dx7QTlrnQAQGlsCVFP3hoqSpEkIJNq6Rc6stA2eoOgfSOCxV2WsqXiVLkuoWsvs/WmwH/3uy2@/fwA "C (gcc) – Try It Online")
There is a lot of code here (so much that I actually had to add the `-w` flag to prevent exceeded debug output), so I will split the explanation into parts. Simply put, we are printing every character using brute force, since I originally thought that it would cost less bytes, but looking back it might actually have been a lot easier to use a logical method.
## Explanation
The first function `a(i)` takes in a digit `i`, and outputs that digit. We increment `i` 48 times, since the ASCII values for numbers are offset by `+48`, and then use the fact that `printf(&i)` acts the same as `putchar(i)` to print to STDOUT.
```
a(i)
{
if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)){}
}
```
---
The second function `n(i)` prints a newline character `\n`. Later when we call this function, we won't actually input any parameter (it will be called by `n()`), which causes `i` to default to 0. Using this fact we essentially do the same thing as in the first function, except we increment by 10, since that is the ASCII value for `\n`.
```
n(i)
{
if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)){}
}
```
---
The third function `f(i)` prints `Fizz`. There is not much to say, except we use the same strategy as in the first function, only we need to repeat this 4 times. It also helps that each ASCII value in `Fizz` is greater than the last, allowing us to simply increment `i` throughout the whole function, instead of using an extra character like `-` to decrement.
```
f(i)
{
if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)){}
if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)){}
if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)&printf(&i)){}
}
```
---
The fourth function `t(i)` essentially does the same thing as `f(i)`, only it prints `Buzz` instead of `Fizz`.
```
t(i)
{
if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)){}
if(++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&++i&printf(&i)){}
if(++i&++i&++i&++i&++i&printf(&i)&printf(&i)){}
}
```
---
The fifth function `p(i)` along with a helper function `r()` returns `i+1`. I know that my function seems overly complicated for such a task, so let me explain. For some reason on TIO, simply using a function like `p(i){if(++i){}}` exploiting the return hack does not work. I suspect this is because the compiler optimizes the code by actually deleting it. Therefore the extra code you see is an attempt to trick the compiler into not deleting it.
```
r(){}
p(i)
{
if(r()&&printf(&i)){}
if(++i){}
}
```
---
The final function `main()` will take all of the functions mentioned previously and combine them to print the FizzBuzz pattern for all 100 lines. Most of it is self-explanatory, except for how to print a number. A number is simply a concatenation of a bunch of digits, so we can use our function `a(i)` to print it. So if we want to print 12, we can do something like `if(a(1)&a(2)){}`. The problem is we don't want to use extra characters like `1` or `2`, which we can solve by repeatdly using the `p(i)` function. Since `p(i)` equals `i+1`, we know that `p(p(...i...))`, would equal `i` plus a constant, which depends on how many `p()`s we are nesting. So if we want to print `12`, we can do `if(a(p(i))&a(p(p(i)))){}`. The `i` variable here is declared as a main parameter, which defaults to 0.
```
main(i)
{
if(a(p(i))&n()){}
if(a(p(p(i)))&n()){}
if(f()&n()){}
if(a(p(p(p(p(i)))))&n()){}
if(t()&n()){}
if(f()&n()){}
if(a(p(p(p(p(p(p(p(i))))))))&n()){}
if(a(p(p(p(p(p(p(p(p(i)))))))))&n()){}
if(f()&n()){}
if(t()&n()){}
if(a(p(i))&a(p(i))&n()){}
if(f()&n()){}
if(a(p(i))&a(p(p(p(i))))&n()){}
if(a(p(i))&a(p(p(p(p(i)))))&n()){}
if(f()&t()&n()){}
if(a(p(i))&a(p(p(p(p(p(p(i)))))))&n()){}
if(a(p(i))&a(p(p(p(p(p(p(p(i))))))))&n()){}
if(f()&n()){}
if(a(p(i))&a(p(p(p(p(p(p(p(p(p(i))))))))))&n()){}
if(t()&n()){}
if(f()&n()){}
if(a(p(p(i)))&a(p(p(i)))&n()){}
if(a(p(p(i)))&a(p(p(p(i))))&n()){}
if(f()&n()){}
if(t()&n()){}
if(a(p(p(i)))&a(p(p(p(p(p(p(i)))))))&n()){}
if(f()&n()){}
if(a(p(p(i)))&a(p(p(p(p(p(p(p(p(i)))))))))&n()){}
if(a(p(p(i)))&a(p(p(p(p(p(p(p(p(p(i))))))))))&n()){}
if(f()&t()&n()){}
if(a(p(p(p(i))))&a(p(i))&n()){}
if(a(p(p(p(i))))&a(p(p(i)))&n()){}
if(f()&n()){}
if(a(p(p(p(i))))&a(p(p(p(p(i)))))&n()){}
if(t()&n()){}
if(f()&n()){}
if(a(p(p(p(i))))&a(p(p(p(p(p(p(p(i))))))))&n()){}
if(a(p(p(p(i))))&a(p(p(p(p(p(p(p(p(i)))))))))&n()){}
if(f()&n()){}
if(t()&n()){}
if(a(p(p(p(p(i)))))&a(p(i))&n()){}
if(f()&n()){}
if(a(p(p(p(p(i)))))&a(p(p(p((i)))))&n()){}
if(a(p(p(p(p(i)))))&a(p(p(p(p((i))))))&n()){}
if(f()&t()&n()){}
if(a(p(p(p(p(i)))))&a(p(p(p(p(p(p((i))))))))&n()){}
if(a(p(p(p(p(i)))))&a(p(p(p(p(p(p(p((i)))))))))&n()){}
if(f()&n()){}
if(a(p(p(p(p(i)))))&a(p(p(p(p(p(p(p(p(p((i)))))))))))&n()){}
if(t()&n()){}
if(f()&n()){}
if(a(p(p(p(p(p(i))))))&a(p(p(i)))&n()){}
if(a(p(p(p(p(p(i))))))&a(p(p(p(i))))&n()){}
if(f()&n()){}
if(t()&n()){}
if(a(p(p(p(p(p(i))))))&a(p(p(p(p(p(p(i)))))))&n()){}
if(f()&n()){}
if(a(p(p(p(p(p(i))))))&a(p(p(p(p(p(p(p(p(i)))))))))&n()){}
if(a(p(p(p(p(p(i))))))&a(p(p(p(p(p(p(p(p(p(i))))))))))&n()){}
if(f()&t()&n()){}
if(a(p(p(p(p(p(p(i)))))))&a(p(i))&n()){}
if(a(p(p(p(p(p(p(i)))))))&a(p(p(i)))&n()){}
if(f()&n()){}
if(a(p(p(p(p(p(p(i)))))))&a(p(p(p(p(i)))))&n()){}
if(t()&n()){}
if(f()&n()){}
if(a(p(p(p(p(p(p(i)))))))&a(p(p(p(p(p(p(p(i))))))))&n()){}
if(a(p(p(p(p(p(p(i)))))))&a(p(p(p(p(p(p(p(p(i)))))))))&n()){}
if(f()&n()){}
if(t()&n()){}
if(a(p(p(p(p(p(p(p(i))))))))&a(p(i))&n()){}
if(f()&n()){}
if(a(p(p(p(p(p(p(p(i))))))))&a(p(p(p(i))))&n()){}
if(a(p(p(p(p(p(p(p(i))))))))&a(p(p(p(p(i)))))&n()){}
if(f()&t()&n()){}
if(a(p(p(p(p(p(p(p(i))))))))&a(p(p(p(p(p(p(i)))))))&n()){}
if(a(p(p(p(p(p(p(p(i))))))))&a(p(p(p(p(p(p(p(i))))))))&n()){}
if(f()&n()){}
if(a(p(p(p(p(p(p(p(i))))))))&a(p(p(p(p(p(p(p(p(p(i))))))))))&n()){}
if(t()&n()){}
if(f()&n()){}
if(a(p(p(p(p(p(p(p(p(i)))))))))&a(p(p(i)))&n()){}
if(a(p(p(p(p(p(p(p(p(i)))))))))&a(p(p(p(i))))&n()){}
if(f()&n()){}
if(t()&n()){}
if(a(p(p(p(p(p(p(p(p(i)))))))))&a(p(p(p(p(p(p(i)))))))&n()){}
if(f()&n()){}
if(a(p(p(p(p(p(p(p(p(i)))))))))&a(p(p(p(p(p(p(p(p(i)))))))))&n()){}
if(a(p(p(p(p(p(p(p(p(i)))))))))&a(p(p(p(p(p(p(p(p(p(i))))))))))&n()){}
if(f()&t()&n()){}
if(a(p(p(p(p(p(p(p(p(p(i))))))))))&a(p(i))&n()){}
if(a(p(p(p(p(p(p(p(p(p(i))))))))))&a(p(p(i)))&n()){}
if(f()&n()){}
if(a(p(p(p(p(p(p(p(p(p(i))))))))))&a(p(p(p(p(i)))))&n()){}
if(t()&n()){}
if(f()&n()){}
if(a(p(p(p(p(p(p(p(p(p(i))))))))))&a(p(p(p(p(p(p(p(i))))))))&n()){}
if(a(p(p(p(p(p(p(p(p(p(i))))))))))&a(p(p(p(p(p(p(p(p(i)))))))))&n()){}
if(f()&n()){}
if(t()&n()){}
}
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 unique bytes
```
Do[Echo[If[Mod[d,1+1+1+1+1+1+1+1+1+1+1+1+1+1+1]<1,FizzBuzz,If[Mod[d,1+1+1]<1,Fizz,If[Mod[d,1+1+1+1+1]<1,Buzz,d]]]],{d,1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1}]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/98lP9o1OSM/2jMt2jc/JTpFx1AbD4y1MdRxy6yqciqtqtJB1QKT0sE0CSQF1pESCwQ61QQsGTqwNvb///8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 7 unique bytes
This uses [this answer](https://codegolf.stackexchange.com/a/110722/75323) to the "least amount of unique bytes for Turing completeness". I then encoded [this well-golfed Python 2 FizzBuzz answer](https://codegolf.stackexchange.com/a/58623/75323) and I got the program that follows.
```
c="%c%%c%%%%c%%%%%%%%c"
ex=c==c
ee=c==""
exec"e=%x%%x"%ex%ex
exec"e%%%%%%%%=%x%%x%%%%x"%ee%ex%ee
exec"ee=%x%%x"%e%ee
exec"ee%%%%=%x%%x"%ex%e
exec"e=%x%%x"%ee%e
exec"ec=ex%cex"%e
exec"xe=ec%cec"%e
exec"xx=xe%cxe"%e
exec"xc=xx%cxx"%e
exec"ce=xc%cxc"%e
exec"cc=ce%cce"%e
exec"xee=ce%cec"%e
exec"cee=ce%cex%%cxe"%e%e
exec"exe=ce%cex%%cec%%%%cxe"%e%e%e
exec"xxe=ce%cxx"%e
exec"cxe=ce%cex%%cxx"%e%e
exec"ece=ce%cec%%cxx"%e%e
exec"cce=ce%cex%%cxe%%%%cxx"%e%e%e
exec"eex=ce%cec%%cxe%%%%cxx"%e%e%e
exec"xex=ce%cex%%cec%%%%cxe%%%%%%%%cxx"%e%e%e%e
exec"cex=ce%cxc"%e
exec"exx=ce%cex%%cxc"%e%e
exec"xxx=ce%cec%%cxc"%e%e
exec"cxx=ce%cex%%cec%%%%cxc"%e%e%e
exec"ecx=ce%cxe%%cxc"%e%e
exec"xcx=ce%cex%%cxe%%%%cxc"%e%e%e
exec"ccx=ce%cex%%cec%%%%cxx%%%%%%%%cxc"%e%e%e%e
exec"eec=ce%cex%%cxe%%%%cxx%%%%%%%%cxc"%e%e%e%e
exec"xec=cc%cec"%e
exec"cec=cc%cec%%cxe"%e%e
exec"exc=cc%cex%%cce"%e%e
exec"xxc=cc%cex%%cec%%%%cce"%e%e%e
exec"cxc=cc%cex%%cxe%%%%cce"%e%e%e
exec"ecc=cc%cec%%cxe%%%%cce"%e%e%e
exec"xcc=cc%cxx%%cce"%e%e
exec"ccc=cc%cex%%cxx%%%%cce"%e%e%e
exec"eeee=cc%cec%%cxx%%%%cce"%e%e%e
exec"xeee=cc%cxe%%cxx%%%%cce"%e%e%e
exec"ceee=cc%cec%%cxe%%%%cxx%%%%%%%%cce"%e%e%e%e
exec"exee=cc%cex%%cec%%%%cxe%%%%%%%%cxx%%%%%%%%%%%%%%%%cce"%e%e%e%e%e
exec"xxee=cc%cxc%%cce"%e%e
exec"cxee=cc%cec%%cxc%%%%cce"%e%e%e
exec"ecee=cc%cex%%cec%%%%cxc%%%%%%%%cce"%e%e%e%e
exec"xcee=cc%cxe%%cxc%%%%cce"%e%e%e
exec"ccee=cc%cex%%cxe%%%%cxc%%%%%%%%cce"%e%e%e%e
exec"eexe=cc%cec%%cxe%%%%cxc%%%%%%%%cce"%e%e%e%e
exec"xexe=cc%cxx%%cxc%%%%cce"%e%e%e
exec"cexe=cc%cec%%cxx%%%%cxc%%%%%%%%cce"%e%e%e%e
exec"exxe=cc%cec%%cxe%%%%cxx%%%%%%%%cxc%%%%%%%%%%%%%%%%cce"%e%e%e%e%e
exec"""x=""
"""
exec"x%c=c%%cxc%%xexe%%cxc%%xxc"%e
exec"x%c=c%%xee%%xee%%eex%%eeee"%e
exec"x%c=c%%exee%%ccc%%ceee%%xxe"%e
exec"x%c=c%%xxc%%xcc%%cxee%%xxe"%e
exec"x%c=c%%cxc%%eexe%%exc%%xeee"%e
exec"x%c=c%%xxe%%xxc%%cxe%%cxe"%e
exec"x%c=c%%ecc%%exee%%cxee%%ce"%e
exec"x%c=c%%xxc%%ce%%ccc%%ceee"%e
exec"x%c=c%%ce%%xxc%%xexe%%eex"%e
exec"x%c=c%%ecee%%xxee%%xeee%%ccc"%e
exec"x%c=c%%xcee%%xxe%%cxe%%cxe"%e
cx="""ccc
eec
cex
ccx
cxc
xexe
cxc
xxc
xee
xxee
cxee
ccc
ceee
xcee
ce
ccc
cee
cxx
xex
xxx
ece
exe
cec
ccc
cexe
cexe
exe
e
ccc
cee
xcx
xex
ecx
ece
exe
xec
ccee
cexe
cexe
exe
exee
cxee
cce
exxe
ccc
ccx
ccc
e
eec
exx
ccx
xee
ece
exx
cex
cex"""
exec"exec%cx"%ce
```
[Try it online!](https://tio.run/##hVZJjttADLzrGQL0gbn3awoEcsrkkEPl9R4uvbAXO4YhS2QVWWTT3frz7@@v799frxfK/eCxb734zX0JC0rBJWK/txkEt5SHz8P7Eeq32horfHZnAHGMVMwgJtsgRcA1h3QTivohZgwLpQjUgmFhoTygDAsKlcXBghQqi4MFFCgLiWUVyxQazaS6IkEXxuSRaGIFDF0ByTIyi8zx0JKvHmDSEJk4ZRJbs04@Qtggk96@7B09Kg986pgwhXD7qDTnzx7wkBazeNRMsoUF98pnMnCIz1EWlrJEcGjmezwNj2Ummmmfieqx4JCpQclTZWKeFmRIVbZABFPmE4QVwk0CkOPzGF9s3HuCI4YNE8t1xGCOs3W5w9OfSbb@TNP5LJ8cI/3fqjRsxXNShHN3TyLwXjUxteK8qlPQPsMfWuEby9q7TyoagXyvYg7K/6sgP67g4H5akPumnR93O0N0Sy6t/ya73aY9pkJoR4RfxBpng7lCxN061bZYDueGoYdH1HCGuAJxMRK65BBGaqy61LsYDEVxPWtBlrxJaVmiN5IPvZamVhHdiWBbogaa5cLWwnYBPdhx6URcuneqFZelixt/kMsSXPALDGom2FM3qJfGU6i@C8AFqB3V7w8M6@Dodu4c3fA7h84RWUlJgT2xRjHFVoHXoGa3GCziMerSxvXXFtrLgjYS8nr9AA "Python 2 – Try It Online")
[Answer]
# Lenguage, 1 distinct character
Now you see, the problem is that my program is *so large* that I kinda can't find a way to represent the byte count other than binary. So, uh, here is what I calculated my score as, represented in base 2:
```
110111000000000000000000000000110010000010000000010000000000010000000000000010000000000000000010000000000000000000010000000000000000000000010000000000000000000000000010000000000000000000000000000010000000000000000000000000000000010000000000000000000000000000000000010000000000000000000000000000000000000010000000000000000000000000000000000000000010000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000011011011011011011011011011011011011011011011011001111010010010010010010000100001011011011011011011010000000100001001011010010010010010010000000100001001011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001001001001100000000000000011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001100000011011011011011011011010000000100001001011010010010010010010010100011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010000100001011011011011011011010010010010010010000100001011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010000100001011011011011011011010010010010010010000000000100001001001011011011011011011010000000100001001011010010010010010010000100001011011011011011011010010010010010010010001001001001100000000000000011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010000100001011011011011011011010010010010010010010001001100000000011011011011011011011010000000100001001011010010010010010010000100001011011011011011011010010010010010010010001100000011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010000100001011011011011011011010010010010010010010000100001011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010000000100001001011011011011011011010010010010010010000000100001001011011011011011011010000000100001001011010010010010010010000000100001001011011011011011011010010010010010010000000000100001001001011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010000000100001001011011011011011011010010010010010010010001001100000000011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010000000100001001011011011011011011010010010010010010010100011011011011011011011010000000100001001011010010010010010010000000100001001011011011011011011010010010010010010010000100001011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010000000000100001001001011011011011011011010010010010010010000100001011011011011011011010000000100001001011010010010010010010000000000100001001001011011011011011011010010010010010010000000100001001011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010000000000100001001001011011011011011011010010010010010010010001001001001100000000000000011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010000000000100001001001011011011011011011010010010010010010010001100000011011011011011011011010000000100001001011010010010010010010000000000100001001001011011011011011011010010010010010010010100011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001001001001100000000000000011011011011011011011010010010010010010000100001011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001001001001100000000000000011011011011011011011010010010010010010000000000100001001001011011011011011011010000000100001001011010010010010010010010001001001001100000000000000011011011011011011011010010010010010010010001001001001100000000000000011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001001001001100000000000000011011011011011011011010010010010010010010001001100000000011011011011011011011010000000100001001011010010010010010010010001001001001100000000000000011011011011011011011010010010010010010010001100000011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001001001001100000000000000011011011011011011011010010010010010010010000100001011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001001001100000000000011011011011011011011010010010010010010000000100001001011011011011011011010000000100001001011010010010010010010010001001001100000000000011011011011011011011010010010010010010000000000100001001001011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001001001100000000000011011011011011011011010010010010010010010001001100000000011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001001001100000000000011011011011011011011010010010010010010010100011011011011011011011010000000100001001011010010010010010010010001001001100000000000011011011011011011011010010010010010010010000100001011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001001100000000011011011011011011011010010010010010010000100001011011011011011011010000000100001001011010010010010010010010001001100000000011011011011011011011010010010010010010000000100001001011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001001100000000011011011011011011011010010010010010010010001001001001100000000000000011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001001100000000011011011011011011011010010010010010010010001100000011011011011011011011010000000100001001011010010010010010010010001001100000000011011011011011011011010010010010010010010100011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001100000011011011011011011011010010010010010010000100001011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001100000011011011011011011011010010010010010010000000000100001001001011011011011011011010000000100001001011010010010010010010010001100000011011011011011011011010010010010010010010001001001001100000000000000011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001100000011011011011011011011010010010010010010010001001100000000011011011011011011011010000000100001001011010010010010010010010001100000011011011011011011011010010010010010010010001100000011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010001100000011011011011011011011010010010010010010010000100001011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010100011011011011011011011010010010010010010000000100001001011011011011011011010000000100001001011010010010010010010010100011011011011011011011010010010010010010000000000100001001001011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010100011011011011011011011010010010010010010010001001100000000011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010100011011011011011011011010010010010010010010100011011011011011011011010000000100001001011010010010010010010010100011011011011011011011010010010010010010010000100001011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010000100001011011011011011011011010010010010010010000100001011011011011011011010000000100001001011010010010010010010010000100001011011011011011011011010010010010010010000000100001001011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010000100001011011011011011011011010010010010010010010001001001001100000000000000011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010000100001011011011011011011011010010010010010010010001100000011011011011011011011010000000100001001011010010010010010010010000100001011011011011011011011010010010010010010010100011011011011011011011010000000100001001011010010010010010010010010010001001100000000011011011011011011011011011010010010010010010010010010010010010010000100001011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010000000100001001011010010010010010010010010000000100001001011011011011011011011011010010010010010010010010010010010010010010010001001001100000000000011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011010010010010010010010010010010010010010010010000000100001001011011011011011011011011011011011011011011011100
```
[BF used for conversion, but place a `[]` at the start of the program -- my browser is already lagging enough without me trying to open the large link again.](https://tio.run/##7VhbDoIwEDxQs3MCwkWMH2piYkz8MPH8qBWxj93S4gdr3I1CC9s6DmxnYH/dnS7H2@E8DG6MTe969/z472szbt@7af9pBK2wGbXjTtJLu1nfdUnQtvfhQK8DjxEg6sajvp0ffwQRgtn6MKa5uJPRpE0pEQAiD2CCkMCLJkgmH0cuQNAKcn2WwPMDnXB1XLZPKRQqY3WyUpT@HM0nzlXOCn9L8cWP2CgnwnU/cJ8EP2lL5oziFSWQSZQq0BZWgTK5uvTdB7xm5mliff37whqVR9Fz5olabSiD1ZzpYuJ4BeVSzb82PRtp9rESWllN@QHma5fQXFBgaYBSnyvhNb87Sxvy4oNYemioVFuQZdoUe18eL@pTzQOLxKJOlZlExa9i0ajFtvSKxMHVppoHrnzzrdv9ot73whzvN9SWvC5@xuXC/G0TANSpKMzTfsOrZjeLGt2EOdgqMgNiSrqapal1rylS864LaRMUM0s03xoHhuEO "brainfuck – Try It Online")
In other words, take any random character of your choosing and repeat it `n` times, where `n` is the binary number above converted to base 10. I may have accidentally miscalculated the byte count, but I know it's only 1 distinct character.
] |
[Question]
[
### Introduction
Nodes in tree structures (e.g. headings in a long document, law paragraphs, etc.) are often created by assigning a specific header level (h1, h2, etc.) to each item, but outputted with additional node numbers for each level (1., 1.1., etc.), e.g.:
```
1. Intro (h1)
1.1. About this (h2)
1.2. Target audience (h2)
2. Actual stuff (h1)
3. More stuff (h1)
3.1. Details (h2)
3.1.1. Special points (h3)
3.2. Specifics (h2)
3.2.1. Minutiae (h3)
3.2.2. Petitesses (h3)
3.3. Specifications (h2)
4. Index (h1)
5. Appendices (h1)
```
### Input
Given (by any means) a list of header levels (the X's in hX above) like:
```
[1,2,2,1,1,2,3,2,3,3,2,1,1]
```
Input will always begin with a 1, and Input*n*+1 is in the range [1,1+Input*n*].
Input will only contain numbers in the range [1,256].
### Output
Return (by any means) the list of lists (or matrix - see below) of node numbers (dot-separated above):
```
[[1],[1,1],[1,2],[2],[3],[3,1],[3,1,1],[3,2],[3,2,1],[3,2,2],[3,3],[4],[5]]
```
You may return scalars instead of one-element sub-lists:
```
[1,[1,1],[1,2],2,3,[3,1],[3,1,1],[3,2],[3,2,1],[3,2,2],[3,3],4,5]
```
You may return a matrix (or list of lists) which is padded with zeros so that all rows (sub-lists) have the same length:
```
[[1,0,0]
[1,1,0]
[1,2,0]
[2,0,0]
[3,0,0]
[3,1,0]
[3,1,1]
[3,2,0]
[3,2,1]
[3,2,2]
[3,3,0]
[4,0,0]
[5,0,0]]
```
### Additional rules
The reverse process of all this is just the length of each sub-list. You must also include a reverse program in the same language. Your score is the total byte count of your two programs. If you return zero-padded results on the first prgram, your reverse code must handle such input.
Please explain your code so we all can learn from it.
This is code golf, because I'll need to read it on a phone screen and type it into a computer. - No, really, this is not meme-ness!
[Answer]
## CJam (15 + 4 = 19 bytes)
```
Mq~{1$0+<))+}%`
```
[Online demo](http://cjam.aditsu.net/#code=Mq~%7B1%240%2B%3C))%2B%7D%25%60&input=%5B1%202%202%201%201%202%203%202%203%203%202%201%201%5D)
To reverse,
```
q~:,
```
[Answer]
## JavaScript (ES6), 47 + 21 = 68 bytes
```
a=>a.map(l=>b=[...b.slice(0,--l),-~b[l]],b=[])
```
Explanation:
```
a=>a.map(l=> Loop over each header level
b=[ Make a new sublist using
...b.slice(0,--l), First l-1 elements from the previous sublist
-~b[l]], Plus increment the lth element or default to 1
b=[]) Start with an empty sublist
```
The bitwise not operator is used because it will coerce its operand to a signed 32-bit integer, which will be zero if this is a new level. Negating the result conveniently returns one more than the original number, or 1 in the case of a new level. Reverse process:
```
a=>a.map(b=>b.length)
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~10~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
### Forward, ~~8~~ 6 bytes
```
ḣ+Ṭ}ð\
```
[Try it online!](http://jelly.tryitonline.net/#code=4bijK-G5rH3DsFw&input=&args=WzEsIDIsIDIsIDEsIDEsIDIsIDMsIDIsIDMsIDMsIDIsIDEsIDFd)
### Backward, 2 bytes
```
L€
```
[Try it online!](http://jelly.tryitonline.net/#code=TOKCrA&input=&args=WzEsIFsxLCAxXSwgWzEsIDJdLCBbMl0sIFszXSwgWzMsIDFdLCBbMywgMSwgMV0sIFszLCAyXSwgWzMsIDIsIDFdLCBbMywgMiwgMl0sIFszLCAzXSwgWzRdLCBbNV1d)
## How it works
### Forward
```
ḣ+Ṭ}ð\ Main link. Argument: A (list of integers)
ð\ Cumulatively reduce A by the dyadic chain to the left. Arguments: x, y
ḣ Head; Truncate x to y items.
Ṭ} Untruth; yield a list of y-1 zeroes and 1 one.
+ Compute the vectorized sum of both results.
```
### Backward
```
L€ Main link. Argument: A (nested list)
L Length.
€ Map the previous link over all items in A.
```
[Answer]
# Pyth, ~~27~~ 22 + 2 = 24 bytes
This is embarrassingly ~~more than~~ 1 less than half of the bytes that javascript used.
```
JylQjRJ.uhs*N^JY-VtQQ1
```
[Try it online!](http://pyth.herokuapp.com/?code=JylQjRJ.uhs*N%5EJY-VtQQ1&input=%5B1%2C2%2C2%2C1%2C1%2C2%2C3%2C2%2C3%2C3%2C2%2C1%2C1%5D&debug=0)
### Reverse, 2 bytes
```
lM
```
[Try it online!](http://pyth.herokuapp.com/?code=lM&input=%5B%5B1%5D%2C+%5B1%2C+1%5D%2C+%5B1%2C+2%5D%2C+%5B2%5D%2C+%5B3%5D%2C+%5B3%2C+1%5D%2C+%5B3%2C+1%2C+1%5D%2C+%5B3%2C+2%5D%2C+%5B3%2C+2%2C+1%5D%2C+%5B3%2C+2%2C+2%5D%2C+%5B3%2C+3%5D%2C+%5B4%5D%2C+%5B5%5D%5D&debug=0)
[Answer]
# Pyth, 11 + 2 = 13 bytes
Forward:
```
m=X_1<+Y0d1
```
[Demonstration](https://pyth.herokuapp.com/?code=m%3DX_1%3C%2BY0d1&input=%5B1%2C2%2C2%2C1%2C1%2C2%2C3%2C2%2C3%2C3%2C2%2C1%2C1%5D&debug=0)
Backward:
```
lM
```
I like this one.
How it works:
```
m=X_1<+Y0d1
Implicit: Y = []
m Map over the input, with d being the map variable
+Y0 Add a 0 on to the end of Y
< d Slice down to the first d elements
X_1 1 Increment the last one
= Assign the result back to Y
```
The resultant list will contain each value that Y takes on, which is the desired sequence.
Embarrassment cured.
[Answer]
# Ruby, 44 + 17 = 61 bytes
Forward:
```
->x{l=[]
x.map{|e|l=l[0,e-=1]<<(l[e]||0)+1}}
```
Backward:
```
->x{x.map &:size}
```
] |
[Question]
[
[The 24 Game](http://en.wikipedia.org/wiki/24_Game) is a card game. On each cards are four interger numbers. For a player, the goal is to use Addition, Subtraction, Multiplication and Division to end up with 24.
The goal of this code golf/puzzle is to write a program that, for four intergers, will state the one or multiple solutions possible with those numbers.
Further notes:
* Should work for an input of any four interger numbers (below 24, above 0). If there is no solution, display `0 solutions` as output.
* Should output the total number of solutions for this set of four numbers as well as the formulas used.
+ Brackets () can be used (and are often important) to get one or multiple solutions.
* Should only display [distinct](http://www.24theory.com/theory/) solutions. For instance, when given {1, 1, 4, 4}, it should not display the cases where the ones and the fours are swapped. Also, if have a solution (a\*b)\*(c\*d), you should not output (c\*d)\*(a\*b) as well, for instance.
An example:
For *{9, 6, 3, 2}*, the program should output:
```
(9-3-2)×6
(6+2)×9/3
6×2+9+3
(9-3)×(6-2)
(3-2/6)×9
9×6/2-3
9×3-6/2
(9+6-3)×2
8 solutions
```
Kudos if you can make a working program that follows the rules outlined above.
Even more kudos if you do this in as little code as possible.
Happy Code Puzzling/Golfing!
[Answer]
## Ruby, ~~253~~ 243 (incomplete, many duplicates, no error message)
```
g=gets.split.map(&:to_i).permutation(4)
s=[0,2,4,6]
%w[+ - * /].repeated_permutation(3).map{|x|g.map{|y|s.map{|b|s.select{|e|e>b}.map{|a|y.zip(x).flatten[0..6].join.insert(a+1,?)).insert(b,?()}}}}.flatten.each{|x|puts x if 24==eval(x)rescue''}
```
I got this so far, but there are a lot of duplicates. Example run:
```
c:\a\ruby>24
9 6 3 2
(9+3)+6*2
(9+3+6*2)
9+(3+6*2)
9+3+(6*2)
(9+3)+2*6
(9+3+2*6)
9+(3+2*6)
9+3+(2*6)
(3+9)+6*2
(3+9+6*2)
3+(9+6*2)
3+9+(6*2)
(3+9)+2*6
(3+9+2*6)
3+(9+2*6)
3+9+(2*6)
(9+6-3)*2
(6+9-3)*2
(9+6*2)+3
(9+6*2+3)
9+(6*2)+3
9+(6*2+3)
(9+2*6)+3
(9+2*6+3)
9+(2*6)+3
9+(2*6+3)
(3+6*2)+9
(3+6*2+9)
3+(6*2)+9
3+(6*2+9)
(3+2*6)+9
(3+2*6+9)
3+(2*6)+9
3+(2*6+9)
(6+2)*9/3
(2+6)*9/3
(9-3+6)*2
(6-3+9)*2
(9-3-2)*6
(9-2-3)*6
(6*2)+9+3
(6*2+9)+3
(6*2+9+3)
6*2+(9+3)
(6*2)+3+9
(6*2+3)+9
(6*2+3+9)
6*2+(3+9)
(2*6)+9+3
(2*6+9)+3
(2*6+9+3)
2*6+(9+3)
(2*6)+3+9
(2*6+3)+9
(2*6+3+9)
2*6+(3+9)
2*(9+6-3)
2*(6+9-3)
9*(6+2)/3
9*(2+6)/3
2*(9-3+6)
2*(6-3+9)
6*(9-3-2)
6*(9-2-3)
(9*3)-6/2
(9*3-6/2)
9*3-(6/2)
(3*9)-6/2
(3*9-6/2)
3*9-(6/2)
(9*6)/2-3
(9*6/2)-3
(9*6/2-3)
9*(6/2)-3
(6*9)/2-3
(6*9/2)-3
(6*9/2-3)
9/3*(6+2)
9/3*(2+6)
(6/2)*9-3
(6/2*9)-3
(6/2*9-3)
```
It will probably prove very difficult to eliminate duplicates. I am working on it, but I am afraid it will triple my code size, so I'm posting here first. aaaaaaahhhhh my brain hurts now, so I will continue working on this later :P
[Answer]
# Mathematica ~~449 479~~ 470
This was based on [Zhe Hu's approach](http://library.wolfram.com/infocenter/MathSource/5131/) but I kept native Mathematica expressions, with numbers stored as strings, throughout. This had two advantages: (1) easy detection of duplicates and (2) high-quality formatting in output.
Because the "deep structure" of the output is kept in a canonical, sorted form, duplicates are easily detected even if the components were initially generated in slightly different ways. Thus commutativity is recognized for addition and multiplication but not imputed to subtraction, division. Further, associativity is implicitly acknowledged.
```
p[{a_, b_, c_, d_}] := Module[{h, v, q},
q[x_, y_] := If[y == 0, Null, x/y];
h[m_, m_, num_] := {Part[num, m]};
h[s_, f_, num_] := h[s, f, num] = Flatten[Table[Outer[F, {Plus, Subtract, Times, q}, h[s, i, num],
h[i + 1, f, num]], {i, s, f - 1}]];
v[o_, n1_, n2_] := o[n1, n2];
t = (Map[# &, Select[Map[h[1, 4, #] &, Permutations[{a, b, c, d}]] // Flatten, (# /. F -> v) == 24 &]]) //. {q -> Divide, n_Integer :> ToString[n]};
Append[u = Union[t //. {F[o_, j_, k_] :> o[j, k]}] //. {Times[a1_String, b1_String] :> Row[{"(", a1, "\[Times]", b1, ")"}]}, ToString[Length[u]] <> " solutions"] // Column]
```
---
The `FullForm` of the following solution,

is
```
Plus[Times[-1,"3"],Times[Power["2",-1],Row[List["(","6","\[Times]","9",")"]]]]
```
the structure of which is most clearly rendered in its `TreeForm`.
```
TreeForm[%]
```

The only reason for using a `Row` for multiplication was to explicitly show the multiplication operator for the product of two known numbers: e.g. (6 x 9) instead of (6 9).
---
## Examples
The code produced 9 solutions, not 8, for the suggested test case.
```
p[{2, 3, 6, 9}]
```

---
```
p[{1, 13, 5, 9}]
```

---
```
p[{24, 13, 5, 9}]
```

[Answer]
An all nighter, a ton of code (C# isn't the most terse of languages) and 8, that's right 8 computed solutions. There's a bunch of things I'd probably change about this... and it's probably wrong but I figured I'd get it in now.
```
+-* 9,6,3,2 | 15,12,24 //(9+6-3)×2
*/- 9,6,2,3 | 54,27,24 //9×6/2-3
-+* 9,3,6,2 | 6,12,24
--* 9,3,2,6 | 6,4,24 //(9-3-2)×6
--* 9,2,3,6 | 7,4,24
-+* 6,3,9,2 | 3,12,24
*++ 6,2,9,3 | 12,21,24 //6×2+9+3
+*/ 6,2,9,3 | 8,72,24 //(6+2)×9/3
8 Solutions
(9-3)×(6-2)???
(3-2/6)×9???
9×3-6/2???
using System;
using System.Linq;
using System.Collections.Generic;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
var n = new List<double> { 9, 6, 3, 2 };
var r = new List<double[]>();
P(n, new List<double>(), r);
var F = new Dictionary<String, Func<double, double, double>> { { "*", (x, y) => x * y }, { "/", (x, y) => x / y }, { "+", (x, y) => x + y }, { "-", (x, y) => x - y } };
var fa = (from a in F
from b in F
from c in F
select new[] { a, b, c }).ToList();
var ir = new List<Tuple<string, double[], double[]>>();
foreach (var p in r)
foreach (var f in fa)
{
var t = new double[4];
t[0] = p[0];
for (int i = 1; i < 4; i++)
t[i] = f[i - 1].Value(t[i - 1], p[i]);
if (Math.Abs(t.Last() - 24) < 0.01)
ir.Add(Tuple.Create(string.Join("", f.Select(_ => _.Key)), t.Skip(1).ToArray(), p));
}
var fr = new List<Tuple<string, double[], double[]>>();
ir.ForEach(i =>
{
if (fr.Any(_ => _.Item1.OrderBy(c=>c).SequenceEqual( i.Item1.OrderBy(c=>c))) &&
fr.Any(_ => _.Item2.OrderBy(c=>c).SequenceEqual( i.Item2.OrderBy(c=>c)))) return;
if (fr.Any(_ => _.Item1.Take(2).Concat(i.Item1.Take(2)).All(k=> "/*".Contains(k)) && _.Item3.Last() == i.Item3.Last() ) ||
fr.Any(_ => _.Item1.Skip(1).Concat(i.Item1.Skip(1)).All(k=> "/*".Contains(k)) && _.Item2.First() == i.Item2.First() ))
return;
fr.Add(i);
});
fr.ForEach(x => Console.WriteLine(x.Item1 + " " + string.Join(",", x.Item3) + " | " + string.Join(",", x.Item2)));
Console.WriteLine(fr.Count + " Solutions");
Console.ReadLine();
}
static void P<T>(List<T> s, List<T> c, List<T[]> r)
{
if (s.Count < 2) r.Add(c.Concat(s).ToArray());
else
for (int i = 0; i < s.Count; i++)
{
var cc = c.ToList();
cc.Add(s[i]);
var ss = s.ToList();
ss.RemoveAt(i);
P(ss, cc, r);
}
}
}
}
```
[Answer]
## Java
It's quite long - I ought to rewrite it in Python or Haskell - but I think it's correct.
```
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class TwentyFour {
public static void main(String[] _) {
for (Expression exp : getExpressions(Arrays.asList(9, 6, 3, 2)))
if (exp.evaluate() == 24)
System.out.println(exp);
}
static Set<Expression> getExpressions(Collection<Integer> numbers) {
Set<Expression> expressions = new HashSet<Expression>();
if (numbers.size() == 1) {
expressions.add(new ConstantExpression(numbers.iterator().next()));
return expressions;
}
for (Collection<Collection<Integer>> grouping : getGroupings(numbers))
if (grouping.size() > 1)
expressions.addAll(getExpressionsForGrouping(grouping));
return expressions;
}
static Set<Expression> getExpressionsForGrouping(Collection<Collection<Integer>> groupedNumbers) {
Collection<Set<Expression>> groupExpressionOptions = new ArrayList<Set<Expression>>();
for (Collection<Integer> group : groupedNumbers)
groupExpressionOptions.add(getExpressions(group));
Set<Expression> result = new HashSet<Expression>();
for (Collection<Expression> expressions : getCombinations(groupExpressionOptions)) {
boolean containsAdditive = false, containsMultiplicative = false;
for (Expression exp : expressions) {
containsAdditive |= exp instanceof AdditiveExpression;
containsMultiplicative |= exp instanceof MultiplicativeExpression;
}
Expression firstExpression = expressions.iterator().next();
Collection<Expression> restExpressions = new ArrayList<Expression>(expressions);
restExpressions.remove(firstExpression);
for (int i = 0; i < 1 << restExpressions.size(); ++i) {
Iterator<Expression> restExpressionsIter = restExpressions.iterator();
Collection<Expression> a = new ArrayList<Expression>(), b = new ArrayList<Expression>();
for (int j = 0; j < restExpressions.size(); ++j)
Arrays.asList(a, b).get(i >> j & 1).add(restExpressionsIter.next());
if (!containsAdditive)
result.add(new AdditiveExpression(firstExpression, a, b));
if (!containsMultiplicative)
try {
result.add(new MultiplicativeExpression(firstExpression, a, b));
} catch (ArithmeticException e) {}
}
}
return result;
}
// Sample input/output:
// [ {a,b} ] -> { [a], [b] }
// [ {a,b}, {a} ] -> { [a,b], [a,a] }
// [ {a,b,c}, {d}, {e,f} ] -> { [a,d,e], [a,d,f], [b,d,e], [b,d,f], [c,d, e], [c,d,f] }
static <T> Set<Collection<T>> getCombinations(Collection<Set<T>> collectionOfOptions) {
if (collectionOfOptions.isEmpty())
return new HashSet<Collection<T>>() {{ add(new ArrayList<T>()); }};
Set<T> firstOptions = collectionOfOptions.iterator().next();
Collection<Set<T>> restCollectionOfOptions = new ArrayList<Set<T>>(collectionOfOptions);
restCollectionOfOptions.remove(firstOptions);
Set<Collection<T>> result = new HashSet<Collection<T>>();
for (T first : firstOptions)
for (Collection<T> restCombination : getCombinations(restCollectionOfOptions))
result.add(Util.concat(restCombination, first));
return result;
}
static <T> Set<Collection<Collection<T>>> getGroupings(final Collection<T> values) {
Set<Collection<Collection<T>>> result = new HashSet<Collection<Collection<T>>>();
if (values.isEmpty()) {
result.add(new ArrayList<Collection<T>>());
return result;
}
for (Collection<T> firstGroup : getSubcollections(values)) {
if (firstGroup.size() == 0)
continue;
Collection<T> rest = new ArrayList<T>(values);
for (T value : firstGroup)
rest.remove(value);
for (Collection<Collection<T>> restGrouping : getGroupings(rest)) {
result.add(Util.concat(restGrouping, firstGroup));
}
}
return result;
}
static <T> Set<Collection<T>> getSubcollections(final Collection<T> values) {
if (values.isEmpty())
return new HashSet<Collection<T>>() {{ add(values); }};
T first = values.iterator().next();
Collection<T> rest = new ArrayList<T>(values);
rest.remove(first);
Set<Collection<T>> result = new HashSet<Collection<T>>();
for (Collection<T> subcollection : getSubcollections(rest)) {
result.add(subcollection);
result.add(Util.concat(subcollection, first));
}
return result;
}
}
abstract class Expression {
abstract double evaluate();
@Override
public abstract boolean equals(Object o);
@Override
public int hashCode() {
return new Double(evaluate()).hashCode();
}
@Override
public abstract String toString();
}
abstract class AggregateExpression extends Expression {}
class AdditiveExpression extends AggregateExpression {
final Expression firstOperand;
final Collection<Expression> addOperands;
final Collection<Expression> subOperands;
AdditiveExpression(Expression firstOperand, Collection<Expression> addOperands,
Collection<Expression> subOperands) {
this.firstOperand = firstOperand;
this.addOperands = addOperands;
this.subOperands = subOperands;
}
@Override
double evaluate() {
double result = firstOperand.evaluate();
for (Expression exp : addOperands)
result += exp.evaluate();
for (Expression exp : subOperands)
result -= exp.evaluate();
return result;
}
@Override
public boolean equals(Object o) {
if (o instanceof AdditiveExpression) {
AdditiveExpression that = (AdditiveExpression) o;
return Util.equalsIgnoreOrder(Util.concat(this.addOperands, this.firstOperand),
Util.concat(that.addOperands, that.firstOperand))
&& Util.equalsIgnoreOrder(this.subOperands, that.subOperands);
}
return false;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(firstOperand.toString());
for (Expression exp : addOperands)
sb.append('+').append(exp);
for (Expression exp : subOperands)
sb.append('-').append(exp);
return sb.toString();
}
}
class MultiplicativeExpression extends AggregateExpression {
final Expression firstOperand;
final Collection<Expression> mulOperands;
final Collection<Expression> divOperands;
MultiplicativeExpression(Expression firstOperand, Collection<Expression> mulOperands,
Collection<Expression> divOperands) {
this.firstOperand = firstOperand;
this.mulOperands = mulOperands;
this.divOperands = divOperands;
for (Expression exp : divOperands)
if (exp.evaluate() == 0.0)
throw new ArithmeticException();
}
@Override
double evaluate() {
double result = firstOperand.evaluate();
for (Expression exp : mulOperands)
result *= exp.evaluate();
for (Expression exp : divOperands)
result /= exp.evaluate();
return result;
}
@Override
public boolean equals(Object o) {
if (o instanceof MultiplicativeExpression) {
MultiplicativeExpression that = (MultiplicativeExpression) o;
return Util.equalsIgnoreOrder(Util.concat(this.mulOperands, this.firstOperand),
Util.concat(that.mulOperands, that.firstOperand))
&& Util.equalsIgnoreOrder(this.divOperands, that.divOperands);
}
return false;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(maybeAddParens(firstOperand));
for (Expression exp : mulOperands)
sb.append('*').append(maybeAddParens(exp));
for (Expression exp : divOperands)
sb.append('/').append(maybeAddParens(exp));
return sb.toString();
}
static String maybeAddParens(Expression exp) {
return String.format(exp instanceof AdditiveExpression ? "(%s)" : "%s", exp);
}
}
class ConstantExpression extends Expression {
final int value;
ConstantExpression(int value) {
this.value = value;
}
@Override
double evaluate() {
return value;
}
@Override
public boolean equals(Object o) {
return o instanceof ConstantExpression && value == ((ConstantExpression) o).value;
}
@Override
public String toString() {
return Integer.toString(value);
}
}
class Util {
static <T> boolean equalsIgnoreOrder(Collection<T> a, Collection<T> b) {
Map<T, Integer> aCounts = new HashMap<T, Integer>(), bCounts = new HashMap<T, Integer>();
for (T value : a) aCounts.put(value, (aCounts.containsKey(value) ? aCounts.get(value) : 0) + 1);
for (T value : b) bCounts.put(value, (bCounts.containsKey(value) ? bCounts.get(value) : 0) + 1);
return aCounts.equals(bCounts);
}
static <T> Collection<T> concat(Collection<T> xs, final T x) {
List<T> result = new ArrayList<T>(xs);
result.add(x);
return result;
}
}
```
Like David's, my code gives 9 solutions for `{9, 6, 3, 2}`:
```
3*9-6/2
(3-9)*(2-6)
(9-3)*(6-2)
9*6/2-3
(3-2/6)*9
3+6*2+9
6*(9-3-2)
(6+2)*9/3
(9+6-3)*2
```
I haven't read the 24theory.com page thoroughly, but it seems reasonable to call `(3-9)*(2-6)` and `(9-3)*(6-2)` distinct, doesn't it?
[Answer]
# R
I'm sure there's a shorter way to write this, plus I hard-coded the possible parenthesis, but it works!
```
# set up
library(combinat)
library(iterpc)
library(data.table)
numbers = c(9,6,3,2)
operators = c('+','-','*','/')
# set up formulas without parens
numbers_permu = do.call('rbind', permn(numbers))
operators_permu = getall(iterpc(table(operators), 3, replace=TRUE, order=TRUE))
for(i in seq(nrow(numbers_permu))) {
for(j in seq(nrow(operators_permu))) {
tmp = c(rbind(numbers_permu[i,], operators_permu[j,]))
if (i==1 & j==1) formulas = data.table(t(tmp))
if (i>1 | j>1) formulas = rbind(formulas, data.table(t(tmp)))
}
}
formulas$V8 = NULL # undo recycling
# add parens, repeating once for each possible parenthesis combo
setnames(formulas, names(formulas), c('V3', 'V4', 'V7', 'V8', 'V11', 'V12', 'V15'))
p1 =c(" ", " ", " ", " ", "(", "(", " ", " ", " ", " ", ")", " ", " ", " ", " ", ")")
p2 =c(" ", " ", " ", " ", "(", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", ")")
p3 =c("(", " ", " ", " ", "(", " ", " ", " ", " ", " ", ")", ")", " ", " ", " ", " ")
p4 =c("(", "(", " ", " ", " ", " ", ")", " ", " ", " ", ")", " ", " ", " ", " ", " ")
p5 =c(" ", " ", " ", " ", " ", " ", " ", " ", " ", "(", " ", " ", " ", " ", " ", ")")
p6 =c("(", " ", " ", " ", " ", " ", ")", " ", " ", " ", " ", " ", " ", " ", " ", " ")
p7 =c("(", " ", " ", " ", " ", " ", " ", " ", " ", " ", ")", " ", " ", " ", " ", " ")
p8 =c("(", " ", " ", " ", " ", " ", ")", " ", "(", " ", " ", " ", " ", " ", ")", " ")
p9 =c(" ", " ", " ", " ", "(", " ", " ", " ", "(", " ", " ", " ", " ", " ", ")", ")")
p10=c(" ", " ", " ", " ", " ", "(", " ", " ", " ", " ", ")", " ", " ", " ", " ", " ")
p11=c(" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ")
parens_permu = t(data.table(p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11))
for(i in seq(nrow(formulas))) {
for(j in seq(nrow(parens_permu))) {
f = paste0(formulas[i,])
p = paste0(parens_permu[j,])
tmp = c(p[1] ,p[2] ,f[1], p[3] ,p[4], f[2],
p[5] ,p[6] ,f[3], p[7] ,p[8], f[4],
p[9] ,p[10],f[5], p[11],p[12],f[6],
p[13],p[14],f[7], p[15],p[16])
if (i==1 & j==1) full_formulas = data.table(t(tmp))
if (i>1 | j>1) full_formulas = rbind(full_formulas, data.table(t(tmp)))
}
}
# evaluate
for(i in seq(nrow(full_formulas))) {
equation = paste(full_formulas[i], collapse='')
solution = tryCatch(eval(parse(text=equation)), error = function(e) NA)
if (i==1) solutions = data.table(equation, solution)
if (i>1) solutions = rbind(solutions, data.table(equation, solution))
}
solutions[solution==24]
```
] |
[Question]
[
Your task is to write a program to perform set operations. The operations and arguments are taken from command line in the format `program operation [argument]`. There are four operations:
1. **1**: clears the set. no arguments. exit code 0.
2. **2 integer**: adds the `integer` into the set. exit code 0.
3. **3 integer**: removes the `integer` from the set. exit code 0.
4. **4 integer**: queries the set for `integer`. exit code 0 if integer exists or 1 otherwise.
The integer is a 64-bits integer. Shortest program wins. You can, of course, use a temporary file. However, watch out the space and time limit.
Example:
```
$ program 1 ; echo $?
0
$ program 2 10 ; echo $?
0
$ program 4 10 ; echo $?
0
$ program 3 10 ; echo $?
0
$ program 4 10 ; echo $?
1
$ program 2 10 ; echo $?
0
$ program 1 ; echo $?
0
$ program 4 10 ; echo $?
1
```
[Answer]
# Bash -- 54 chars
```
case $1 in
1)rm *;w;;
2)>$2;;
3)rm $2;w;;
4)<$2;;
esac
```
Notes: Outputs to stdout/stderr in some scenarios. Empties working directory when clearing the set. Uses one file for each set element. The purpose of `;w` is to exit with status 0.
This appears to comply with all the rules.
[Answer]
# bash, 74
```
case $1 in
1)>f;;
2)echo $2>>f;;
3)sed -i /^$2$/d f;;
4)grep ^$2$ f;;
esac
```
**note** I'm not plagiarizing [Peter Taylor](https://codegolf.stackexchange.com/questions/1183/write-a-program-to-perform-set-operations/1188#1188), it's just that it's not working with `[ test ]`s
[Answer]
# Bash: 106 chars
```
touch f
case $1 in
1)rm -f f;;
2)echo $2>>f;;
3)grep -vx $2 f>g;mv g f;;
4)grep -x $2 f&>/dev/null;;
esac
```
Counting newlines as one character. Requires two temp files and POSIX grep. I'm unclear as to the precise constraints on temp files: if I can have two kicking around all the time then I can save 8 chars by writing to g rather than /dev/null in case 4.
[Answer]
# Python - 167 chars
```
import sys,shelve as S
x,A,E=S.open("x"),sys.argv,exit
A[1]<'2'and E(x.clear())or'3'>A[1]and E(x.__setitem__(A[2],1))or'4'>A[1]and E(x.__delitem__(A[2]))or E(A[2]in x)
```
You need to create the temporary file like this
```
python -c 'import shelve;shelve.open("x","c")'
```
[Answer]
# Ruby - 146 characters
```
a,b=ARGV
File.open('x','a+'){|f|s=eval(f.read)||[]
s=[]if a=='1'
s+=[b]if a=='2'
s-=[b]if a=='3'
f.puts s.inspect
exit a=='4'?(s.index(b)?0:1):0}
```
[Answer]
# PHP - 204 characters
```
<?
$s=unserialize(file_get_contents('f'));
$a=$argv;
$o=$a[1]--;
$a=$a[2];
--$o?(--$o?(--$o?die(!isset($s[$a])+0):$s=array_diff_key($s,array($a=>1))):$s[$a]=1):$s=array();
file_put_contents('f',serialize($s));
```
Added some linebreaks to make it a tad more readable.
This throws a warning to screen when run for the first time, but otherwise, it does as asked.
] |
[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/118/edit).
Closed 2 years ago.
[Improve this question](/posts/118/edit)
Write the shortest code that traverses a tree, breadth-first.
### Input
any way you like
### Output
a list of "names" of the nodes in correct order.
[Answer]
# Haskell — ~~84~~ 76 characters
```
data N a=N{v::a,c::[N a]}
b(N a b)=d[a]b
d r[]=r
d r n=d(r++(map v n))$n>>=c
```
In a more readable format:
```
data Node a = Node {value::Int, children::[Node a]}
bfs :: Node Int -> [Int]
bfs (Node a b) = bfs' [a] b
where bfs' res [] = res
bfs' res n = bfs' (res ++ (map value n)) $ concatMap children n
```
The code allows **infinite number** of child nodes (not just left and right).
Sample tree:
```
sampleTree =
N 1 [N 2 [N 5 [N 9 [],
N 10 []],
N 6 []],
N 3 [],
N 4 [N 7 [N 11 [],
N 12 []],
N 8 []]]
```
Sample run:
```
*Main> b sampleTree
[1,2,3,4,5,6,7,8,9,10,11,12]
```
Nodes are expanded in the order shown in [Breadth-first search](http://en.wikipedia.org/wiki/Breadth-first_search) article on Wikipedia.
[Answer]
## Haskell: 63 characters
```
data N a=N{v::a,c::[N a]}
b n=d[n]
d[]=[]
d n=map v n++d(n>>=c)
```
This is really just a variation on @Yasir's solution, but that one isn't community wiki, and I couldn't edit it.
By just expanding the names, and replacing `concatMap` for `>>=`, the above golf'd code becomes perfectly reasonable Haskell:
```
data Tree a = Node { value :: a, children :: [Tree a] }
breadthFirst t = step [t]
where step [] = []
step ts = map value ts ++ step (concatMap children ts)
```
The only possibly golf-like trick is using `>>=` for `concatMap`, though even that isn't really that uncommon in real code.
[Answer]
# Common Lisp, 69 chars
returns rather than prints the list and takes input as argument
```
(defun b(e)(apply #'nconc (mapcar #'car (cdr e))(mapcar #'b (cdr e))))
```
Format is the same as below except it requires a 'dummy' root node like so:
```
(root (a (b (1) (2)) (c (1) (2))))
```
**Common Lisp: (95 chars)**
This one reads and prints instead of using arg parsing
```
(labels((b(e)(format t "~{~A~%~}"(mapcar #'car (cdr e)))(mapcar #'b (cdr e))))(b`((),(read))))
```
input to stdin should be a lisp form s.t. a tree with root a and two children b and c, each of which have children 1 & 2 should be `(a (b (1) (2)) (c (1) (2)))`
or equivalently -
```
(a
(b
(1)
(2))
(c
(1)
(2)))
```
[Answer]
# GolfScript, 4
Not a serious answer, but the Golfscript version of tobyodavies' sed answer is only 4 chars
```
n%n*
```
you could argue that
```
n%
```
is also sufficient,as it returns the tree items as a list, however these are displayed mashed together on stdout.
```
n%p
```
displays the list representation of the tree items (looks like a Python or Ruby list)
[Answer]
## Python - 59 chars
This one returns a generator, but modifies T, so you may want to pass in a copy
```
def f(T):
t=iter(T)
for i in t:yield i;T+=next(t)+next(t)
```
testing
```
4
/ \
/ \
/ \
2 9
/ \ / \
1 3 6 10
/ \
5 7
\
8
>>> T=[4,[2,[1,[],[]],[3,[],[]]],[9,[6,[5,[],[]],[7,[],[8,[],[]]]],[10,[],[]]]]
>>> f(T)
<generator object f at 0x87a31bc>
>>> list(_)
[4, 2, 9, 1, 3, 6, 10, 5, 7, 8]
```
] |
[Question]
[
It is [Restricted Integer Partitions](https://codegolf.stackexchange.com/questions/135875), but with maximum number.
# Question
Three positive integers are given. First number is number to divide, second number is length of partition, and third number is maximum number. First number is always largest, and bigger than other two.
For example, `5, 2, 3`. Then, make partition of `5` which have `2` parts, and maximum number you can use is `3`. Note that you don't have to use `3` : maximum number can be `2` or `1`.
In this case, there is only one partition : `3, 2`.
Partition is unordered : which means `3 + 2` and `2 + 3` is same.
But in case like `7, 3, 3`, there are two partition : `3, 3, 1` and `3, 2, 2`.
To make it sure, **You can use third number as largest number, but you don't have to use it.** So `5, 4, 3` is true.
Question is : Is there are more than one partition, given length and maximum number?
Output is `True` or `1` or whatever you want when there is only one partition, and `False` or `0` or whatever you want where there are more than one partition, or no partition.
# Winning condition
This is code golf, so code with shortest byte wins.
# Examples
Input -> Output
```
7, 6, 2 -> True (2+1+1+1+1+1) : 1 partitions
5, 4, 4 -> True (2+1+1+1) : 1 partitions
5, 4, 3 -> True (2+1+1+1) : 1 partitions
5, 4, 2 -> True (2+1+1+1) : 1 partitions
5, 3, 2 -> True (2+2+1) : 1 partitions
7, 2, 3 -> False no partitions
7, 2, 2 -> False no partitions
7, 2, 1 -> False no partitions
9, 5, 3 -> False (3+3+1+1+1), (3+2+2+1+1), (2+2+2+2+1) : 3 partitions
6, 3, 3 -> False (3+2+1), (2+2+2) : 2 partitions
```
[Answer]
# [Python 2](https://docs.python.org/2/), 38 bytes
```
lambda n,k,m:m>n-k<2or-1<k*m-n<2+2/m*k
```
[Try it online!](https://tio.run/##fVDLbsMgELzzFdtIkU1C0mLnoVghf9B7pTQHt8aJi8EOxqr69Slg8lAPFUjL7s7OzNL@mFOjkkvJ3i91Lj@KHBQRRGZyp2ZimzR6RrdiImdqm0yTZzkRl0q2jTZQGa5N09QdQgUv4Rz7OZwhgBYY7A2UjQaLU3fovNVN0X@aWOfqyGNK5JRionnLc8MEhqqErpexwYwpyFUBddUZn3ZWkhf2ebD8mpteK6i5ilsMjAFFyIlJYs2D@F9ycxNMnVkrqXbCi6mddO4r5fyHdWxucn3kxpbO8cT2sDfQ9bUrlbeS5QnAJxb6jgxaXSkDo1e7SC54NiKOnwQECTODfW/8anPlzIVhwcbFCMYgkP9T@YB7IS9kRodf9@Aomn81lYqj@Vu0L8MWhz9rAq87DpE9jk/d@RYUY4S@T1XNgWYD47Bjb2KML2sCKwIJWhJY2BtiGmKCKLWZa9Dk4eFHNiGu7zFxgCGmIV7r1OGXrr7yRFcJimgaCBzK3l8 "Python 2 – Try It Online")
Characterizes the cases where there's only one legal partition.
Consider the partitions of \$n\$ into exactly \$k\$ parts each between \$1\$ and \$m\$ inclusive. There's only two ways to for there to be only one such partition.
* The number \$n\$ is close to as small as possible (\$n=k\$ or \$n=k+1)\$ or as large as possible (\$n=mk-1\$ or \$n=mk)\$ for such a partitions. This leave only enough "wiggle room" for only one partition in each case:
+ \$n=1+1+\cdots +1+1\$.
+ \$n=2+1+\cdots+1+1\$.
+ \$n=m+m+\cdots+m+(m-1)\$.
+ \$n=m+m+\cdots+m+m\$.
* We allow only \$m=2\$ maximum, forcing a unique partition made of 1's and 2's. Such a partition requires \$k \leq n \leq 2k\$.
The challenge lets us assume that \$n>k\$, so we can omit the \$n=k\$ case and \$k \leq n\$ check, and, as feersum observed, can let us check \$n=k+1\$ as \$n<k+2\$. The \$m=1\$ case makes it impossible to make a partition with \$n>k\$, so we make sure it's always rejected. This gives the condition
>
> \$n \in \{ k+1, mk-1, mk\}\$and \$ m>1\$, or \$n \leq 2k \$ and \$m=2\$
>
>
>
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~39~~ 38 bytes
-1: first argument > other arguments (no length-1 partitions)
```
1==Tr[1^IntegerPartitions[#,{#2},#3]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b739DWNqQo2jDOM68kNT21KCCxqCSzJDM/rzhaWada2ahWR9k4Nlbtf0BRZl5JtLKuXZqDg3Ksmr5DNVe1uY6ZDlABV7WpjomOCYxhDGOApcx1jCAiIAZcxBDEsNQxhUiZ6RgDGVy1/wE "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
ÅœIù€à@O
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cOvRyZ6Hdz5qWnN4gYP////mXGZcRgA "05AB1E – Try It Online")
Outputs truthy when there’s exactly one partition, falsy otherwise. (All numbers except 1 are falsy in 05AB1E, which makes this convenient).
```
Ŝ # integer partitions of the first input
Iù # keep only those with length equal to the second input
ۈ # take the maximum of each one
@ # test if the third input >= each one
O # sum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), (10?) 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œṗṁ«⁵ɗƑƇL⁼1
```
A full program which accepts `N numberOfParts maximalSizeOfAnyPart` as arguments and prints `1` if exactly one solution exists and `0` otherwise.
**[Try it online!](https://tio.run/##AScA2P9qZWxsef//xZLhuZfhuYHCq@KBtcmXxpHGh0zigbwx////N/82/zI "Jelly – Try It Online")**
### How?
```
Œṗṁ«⁵ɗƑƇL⁼1 - Main Link: N, numberOfParts
Œṗ - integer partitions (of N)
Ƈ - keep those (P) for which:
Ƒ - is invariant under:
ɗ - last three links as a dyad - i.e. f(P, numberOfParts):
ṁ - mould (P) like (numberOfParts)
⁵ - 3rd argument (maximalSizeOfAnyPart)
« - minimum (vectorises)
L - length
1 - literal one
⁼ - equal?
- implicit print
```
---
If we may print `1` if exactly one solution exists and `0` OR nothing otherwise then `Œṗṁ«⁵ɗƑƇMỊ` is a 10 byte full program.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
œċ§ċ⁵=1
```
[Try it online!](https://tio.run/##ARwA4/9qZWxsef//xZPEi8KnxIvigbU9Mf///zP/Mv83 "Jelly – Try It Online")
A full program taking the arguments in the order maximum part, number of parts, sum (i.e. reversed from original question).
### Explanation
```
œċ | Combinations with replacement (using maximum part size and number of parts)
§ | Sum (vectorises)
ċ⁵ | Count occurrences of desired integer from question
=1 | Check if equal to 1
```
] |
[Question]
[
Write a quine that outputs the complement of the source code from the smallest containing power of two. Here's an example:
```
IN : source
OUT: \r\x11\x0b\x0e\x1d\x1b
```
The largest code point in the string `"source"` is the letter `u`, which is 117. The smallest containing power of 2 would be 128, so all the code points are taken as complements from 128.
1. s: `128 - 115 = 13`. Code point 13 is a carriage return.
2. o: `128 - 111 = 17`. Code point 17 is "device control 1"
3. u: `128 - 117 = 11`. Code point 11 is a vertical tab.
And et cetera. Here's another example:
```
IN : R¬°·π†
OUT: ᾮὟƠ
```
The largest code point is the character `·π†`, which is 7776. The smallest containing power of 2 is 2^13 (8192), so each character is complemented from 8192.
All of the standard loopholes apply. A program must consist of some explicit data or code. A variable containing some data by default would be considered implicit data, and therefore not allowed.
If your language inevitably outputs a trailing newline, it can be disregarded.
[Answer]
# [Neim](https://github.com/okx-code/Neim), 1 [byte](https://github.com/okx-code/Neim/wiki/Code-Page)
```
ùïï
```
**[Try it online!](https://tio.run/##y0vNzP3//8PcqVP//wcA "Neim – Try It Online")**
Uses Neim's [code-page](https://github.com/okx-code/Neim/wiki/Code-Page), where `ùïï` is byte **0xd0** (208) and the printed result, `0`, is byte **0x30** (48) which is as required (256-208).
`ùïï` is an instruction to get the nth element of a list. Both n and the list are implicit since they are missing and neim outputs implicitly too.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~2~~ 1 byte
```
P
```
## Outputs
```
0
```
## Explained
`P` actually has no special meaning in retina, but retina treats it like a regex against the input, and counts the matches. As there's no input, there's no matches, so it returns `0`, which is the exact inverse of this.
[Try it online!](https://tio.run/##K0otycxL/P8/4P9/AA "Retina – Try It Online")
This is using an older version of Retina, which outputs a newline with the zero. This is not the case in the latest version.
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), ~~17~~ 18 bytes
```
¬´` .S{c$256\-o}r.
```
## Output
```
U àÒ\x85\x9DÜÎËʤÓ\x91\x83\x8EÒà
```
Where `\x` numbers are to be considered literal.
## Explained
```
¬´` .S{c$256\-o}r.
¬´ # Push a function based on the remainder of the program and run it.
` . # Append a space to the end, which stringifies it. As the stringification removes unnecessary spaces, this re-adds the leading one, making it a valid quine.
S # Convert it to a stack of characters.
{ }r # Replace each character based on a function.
c # Get the character code
$256 # Push 256 literally.
\- # Flip them and subtract, giving 255 - char code, which is equivalent to the bitwise not of the char code.
o # Get the character this represents.
. # Reduce with Concatenation, turning it back into a string. Implicitely output.
```
[Try it online!](https://tio.run/##Kyooyk/P0zX6///Q6gQFveDqZBUjU7MY3fzaIj2F//8B "RProgN 2 – Try It Online")
[Answer]
# C, 178 bytes
```
char*u,*s="char*u,*s=%c%s%c;main(){char t[256];sprintf(t,s,34,s,34);for(u=t;*u;++u)*u=128-*u;puts(t);}";main(){char t[256];sprintf(t,s,34,s,34);for(u=t;*u;++u)*u=128-*u;puts(t);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z85I7FIq1RHq9hWCcFUTVYtVk22zk3MzNPQrAaJK5REG5maxVoXFxRl5pWkaZToFOsYm4AJTeu0/CKNUtsSa61Sa23tUk2tUltDIwtdIK@gtKRYo0TTulaJimb9/w8A)
[Answer]
# JavaScript, 121 bytes
```
f=a=>[...a='f='+f].map(a=>(m=(a=a.charCodeAt())>m?a:m,a),m=0).map(a=>String.fromCharCode(2**-~(Math.log2(m)|0)-a)).join``
```
[Try it online!](https://tio.run/##NczBCoMwEATQz3HX6iIeC7EUzz31WAouqdGIm0gMPZX@eppCexqYeczCT951sFusnX@MKRnFqrsREavCqOJg7iS8QS5BVA4mPXPosz1HQOzkxEepGCtRDf7pNQbrJjLBS//T0JZl/YYLx5lWP7Ug@GqwZkRavHXDkLR3u1/H7womX6cP)
[Answer]
# [Python 2](https://docs.python.org/2/), 93 bytes
```
s='s=%r;print"".join(chr(128-ord(i))for i in s%%s)';print"".join(chr(128-ord(i))for i in s%s)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9hWvdhWtci6oCgzr0RJSS8rPzNPIzmjSMPQyEI3vyhFI1NTMy2/SCFTITNPoVhVtVhTnVi1xZr//wMA "Python 2 – Try It Online")
] |
[Question]
[
# Fix my Basic Orthography
While I am excellent at following the English capitalisation rules when writing, when I am typing I have a habit a capitalising almost everything (as you will see from the titles of my challenges). I need a program to fix that, but because I use so many capitals, and capitals are big letters, your program must be as short as possible.
## Requirements
* Your program should take each word, and if it is the first alphanumeric set of characters after a full stop or the beginning of the input, capitalize the *first* letter. All the rest of the letters until the next full stop will be lowercase. At the full stop, capitalize the first letter and continue.
* Punctuation must be preserved.
* In a sentence without a full stop at the end, that should be added.
* Spaces, where missing, should be inserted. A space is 'missing' if there is nothing between a full stop and the character following it.
*(Note for americanish speakers: full stop = period = `.`)*
## Test Cases
```
tHIS SenteNce HAS veRy bAd GrammAr. ==> This sentence has very bad grammar.
-----
PuncTuation must-be PReserved. ==> Punctuation must-be preserved.
-----
full StOps ShoulD Be inserted ==> Full stops should be inserted.
-----
MultiPLe sEntEnceS Are possible. thEY Are, yoU KNOW. ==> Multiple sentences are possible. They are, you know.
-----
spaces. are.inserted. ==> Spaces. Are. Inserted.
```
## Rules
* Your program should take input as an argument or from `STDIN` (or the closest alternative in your language).
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
## Scoring
When [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") is the tag, it's the least bytes to win!
## Submissions
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
## Leaderboard
```
/* Configuration */
var QUESTION_ID = 79842; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push©;
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<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]
# Vim, ~~40~~ 39 keystrokes
```
VgugUl:s/\. *\(\a\)/\. \U\1/g<cr>:s/\.$<cr>A.
```
This assumes that input will not take multiple lines.
Explanation:
```
Vgu "Make the whole line lowercase
gUl "Make the first character uppercase
:s/\. *\(\a\)/\. \U\1/g<cr> "Replace a (.) followed by any number of
"spaces, followed by a character, with
"with a (.), one space, and that character
"In lowercase
:s/\.$<cr> "Remove a dot, if it's at the end of this line
A. "Add a dot to the end of this line.
```
[Answer]
## Pyke, 16 bytes
```
Q\.cFl8l5DI\.+(J
```
[Try it here!](http://pyke.catbus.co.uk/?code=Q%5C.cFl8l5DI%5C.%2B%28J&input=MultiPle+spaCes+are+REPLACEd.++reallY.)
(15 bytes after a bugfix)
```
\.cFl8l5DI\.+(J
```
Explanation:
```
Q\.c - input().split(".")
F - for i in ^:
l8l5 - i = i.lstrip().capitalise()
I - if i:
\.+ - i += "."
J - " ".join(^)
```
[Answer]
## JavaScript (ES6), ~~76~~ 95 bytes
```
f=
s=>s.replace(/ +/g,' ').replace(/(\w)([^.]*)\.?/g,(_,c,r)=>c.toUpperCase()+r.toLowerCase()+'.')
```
```
input{width:100%;
```
```
<input oninput=o.value=f(this.value)><input id=o>
```
[Answer]
## Python 3, ~~86~~ 80 bytes
```
print('. '.join(x.strip().capitalize() for x in input().split('.') if x!='')+'.')
```
This works for all of the current test cases, but not for much beyond that.
Thanks @muddyfish for 6 bytes.
<https://repl.it/CQ7h/0>
[Answer]
# Ruby, 50 bytes
Basic split/map/join solution.
```
->s{s.split(?.).map{|e|e.strip.capitalize+?.}*' '}
```
[Answer]
# Retina, 41 bytes
```
S-`\. *
%(T`L`l
T`l`L`^.
)`(?<!\.)$
.
¶
<space>
```
[Try it online!](http://retina.tryitonline.net/#code=Uy1gXC4gKgolKFRgTGBsClRgbGBMYF4uCilgKD88IVwuKSQKLgrCtgog&input=c3BhY2VzLiBhcmUuaW5zZXJ0ZWQuIGFuZCBmdWxsIFN0T3BzIFNob3VsRCBCZSBpbnNlcnRlZA)
[Test suite.](http://retina.tryitonline.net/#code=JShTLWBcLiAqCiUoVGBMYGwKVGBsYExgXi4KKWAoPzwhXC4pKD88IV4pJAouCsK2CiA&input=dEhJUyBTZW50ZU5jZSBIQVMgdmVSeSBiQWQgR3JhbW1Bci4KUHVuY1R1YXRpb24gbXVzdC1iZSBQUmVzZXJ2ZWQuCk11bHRpUExlIHNFbnRFbmNlUyBBcmUgcG9zc2libGUuIHRoRVkgQXJlLCB5b1UgS05PVy4KTXVsdGlQbGUgc3BhQ2VzIGFyZSBSRVBMQUNFZC4gIHJlYWxsWS4Kc3BhY2VzLiBhcmUuaW5zZXJ0ZWQuCmZ1bGwgU3RPcHMgU2hvdWxEIEJlIGluc2VydGVk)
[Answer]
# V, 25 bytes (non-competing)
```
guGgUló® *¨á©/® Õ±
ó®$
A.
```
[Try it online!](http://v.tryitonline.net/#code=Z3VHZ1Vsw7PCriAqwqjDocKpL8KuIMOVwrEKw7PCriQKQS4&input=TXVsdGlQTGUgc0VudEVuY2VTIEFyZSBwb3NzaWJsZS4gdGhFWSBBcmUsIHlvVSBLTk9XLg)
This isn't super creative, since it's just a direct port of [my vim answer](https://codegolf.stackexchange.com/a/79871/31716). However, it's a lot shorter, so I'm happy with it.
Due to an oversight, this is one or two bytes longer than it needs to be. That should be fixed soon.
[Answer]
# PHP, ~~123~~ ~~103~~ ~~102~~ ~~95~~ 92 bytes
```
<?foreach(explode('.',trim(fgets(STDIN)))as$b)echo!$b?!1:ucfirst(strtolower(trim($b))).'. ';
```
Takes a newline-terminated line from STDIN and prints the fixed version to STDOUT.
[Answer]
# Lua, ~~149~~ 141 bytes
```
u=function(l)return l:upper()end print(io.read():lower():gsub("%s+"," "):gsub("%.([^%s])",". %1"):gsub("^(%w)",u):gsub("(%.[^%w]*%w)",u).."")
```
Lua lacks some common features of regular expressions, and so it had to get a little sloppier than I would have liked. I might try to fix it up later though.
[Answer]
# Perl, 40 + 12 (flags) = 52 bytes
```
#!perl -paF\.\s*
map{s/\s*$/. /;$\.=ucfirst lc}@F}{chop$\
```
Using:
```
echo "foo.baz. bar" | perl -paF'\.\s*' -e 'map{s/\s*$/. /;$\.=ucfirst lc}@F}{chop$\'
```
Ungolfed:
```
while (<>) {
my @F = split(/\.\s*/, $_);
# code above added by -paF\.\s*
# $\ has undef (or '')
for (@F) {
$_ =~ s/\s*$/. /;
$\ .= ucfirst(lc($_));
}
} {
chop($\);
# code below added by -p
print; # prints $_ (undef here) and $\
}
```
[Ideone](http://ideone.com/CiDw1O).
[Answer]
## Q 78 Bytes
(76 if anonymous function)
```
f:{(". "/:{{@[(" "=*x)_x;0;"c"$-32+"i"$]}'"."\:_-1_x}x),$["."=u:*|x;u;u,"."]}
```
**Test**
```
f"tHIS SenteNce HAS veRy bAd GrammAr." /This sentence has very bad grammar.
f"PuncTuation must-be PReserved." /Punctuation must-be preserved.
f"full StOps ShoulD Be inserted" /Full stops should be inserted.
f"MultiPLe sEntEnceS Are possible. thEY Are, yoU KNOW." /Multiple sentences are possible. They are, you know.
f"spaces. are.inserted." /Spaces. Are. Inserted.
```
Q has lower and upper functions (conversion to lowercase and to uppercase), but more primitive sub-language k (concise, used in the example) only has lower (operator \_), so part of the text (12 bytes `"c"$-32+"i"$`) implements upper.
Split the original string using ". " as separator, processes each line, and join again
For each line we discard first character if is a blank (join inserts a blanck after each .), and capitalice first character.
Finally, insert a final "." if last char is not "."
[Answer]
# [Perl 5](https://www.perl.org/), 42 bytes
```
say map{$_=ucfirst lc.'. '}split/\.\s*/,<>
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVIhN7GgWiXetjQ5LbOouEQhJ1lPXU9Bvba4ICezRD9GL6ZYS1/Hxu7//9zSnJLMAJ9UhWLXvBLXvOTUYAXHolSFgvzi4syknFQ9hZIM10iQkI5CZX6ogreff/i//IKSzPy84v@6vqZ6BoYGAA "Perl 5 – Try It Online")
] |
[Question]
[
Write a program that accepts input (through stdin) as a string of unary numbers delimited by spaces, and prints the equivalent string of numbers in binary, decimal, and hexadecimal. These unary symbols are allowed:
* stroke, `'/'` or `'\'`
* Decimal `1`
* ASCII `'I'`
* ASCII `'-'`
Your program does *not* have to support all symbols, but it must use at least one. Zero should be represented as simply two spaces (the lack of unary symbols)
e.g. if the input is
**Test Cases:**
Input:
```
1 11 111 1111111111
```
Example Output:
```
1 2 3 10
1 2 3 A
1 10 11 1010
```
Output must be to standard output. If no standard output is available, use whatever output logging stream is available.
It does not have to print the converted strings in any particular order; it must print the binary, hexadecimal, and decimal string equivalents, but it does not have to print in that specific order.
This is code-golf, so shortest program wins!
[Answer]
# Python 3, 68 bytes
```
i=input().split(" ")
for f in[bin,str,hex]:print(*map(f,map(len,i)))
```
Outputs like such:
```
0b1 0b10 0b11
1 2 3
0x1 0x2 0x3
```
If the `0b` and `0x` are not allowed then that can be solved at the cost of 17 extra bytes by changing the second line to:
```
for f in[bin,str,hex]:print(*(f(len(n))[2*(f!=str):]for n in i))
```
Or using this version (minified version of My Ham DJ's answer):
```
i=input().split(" ")
for b in"dxb":print(*("{:{}}".format(len(x),b)for x in i))
```
[Answer]
## JavaScript (ES6), 76 bytes
```
s=>[2,10,16].map(b=>s.split` `.map(n=>n.length.toString(b)).join` `).join`
`
```
[Answer]
# Pyth, 12 bytes
```
mjLld[2T16)c
```
[Try it here!](http://pyth.herokuapp.com/?code=mjLld%5B2T16%29c&input=%221%2011%20111%22&debug=0)
Output is a list of lists with each sublist containing the binary, decimal and hex representation of the corrosponding input number as a list of digits.
[Answer]
## Pyke, 14 bytes
```
dcmlD
mb2Rmb16
```
[Try it here](http://pyke.catbus.co.uk/?code=dcmlD%0Amb2Rmb16&input=1++11+1111111111111111)
[Answer]
# Python 3.5, 61 bytes:
(*+17 since zeroes count as an extra space*)
```
lambda g:[(bin(len(f)),hex(len(f)),len(f))for f in g.split(" ")]
```
Pretty much speaks for itself. It is a lambda function, so you must provide input. Then, the function takes "g", which is your input, and outputs the correct values. If, for instance, the input is `"111 11"`, output is as follows:
>
> [('0b11', '0x3', 3), ('0b10', '0x2', 2)]
>
>
>
I honestly think that including the `0b` and `0x` is a better choice than removing them, since then this way, you can differentiate between those numbers that are hexadecimal, those which are binary, and those which are just plain denary (decimal).
And now, if the input is, for instance, `"011"`, it counts the `0` as an extra space, and as a result outputs `[('0b10', '0x2', 2)]`.
**EDIT:** AS per @isaacg's input, I have now fixed by program, and it should work as it should. The code now has the ability for extra spaces between ones to become zeroes. Now, if the input is, for instance, `11<space><space>1`, the output is `[('0b1', '0x1', 1), ('0b0', '0x0', '0'), ('0b10', '0x2', 2)]` counting the extra space as a `'0 '`.
[Answer]
## Java, 136 bytes
```
s->{String[]l=s.split(" ",-1);s="";for(int i=2;i<17;i+=i<3?8:6){for(String n:l)s+=Integer.toString(n.length(),i)+" ";s+="\n";}return s;}
```
[Try it online!](http://ideone.com/z5hH0L)
This is an anonymous function (lambda) that takes a String and returns a String representing the output as described.
Full explanation will come later today.
[Answer]
# Ruby, ~~89~~ 58 bytes
Anonymous function; Returns a list of lists where each sublist contains binary, decimal, and hex representations, and accounts for extra spaces.
@manatwork is a Ruby wizard
```
->s{[2,10,16].map{|b|s.split(/ /).map{|n|n.size.to_s(b)}}}
```
Without the need to check for the spare spaces meaning 0, it drops to 53 bytes:
```
->s{[2,10,16].map{|b|s.split.map{|n|n.size.to_s(b)}}}
```
] |
[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/3550/edit).
Closed 7 years ago.
[Improve this question](/posts/3550/edit)
This is a teaser a friend of mine sent. It seems straightforward, but I can't seem to get my head around it, probably due to my lack of sleep.
1. You have 16 bits available.
2. Compose a function, and find a way to know when the function has run approximately one million times.
3. You MAY NOT use any additional memory space other than the 16 bits given.
4. Recursion may be used for efficiency, but, again, you MAY NOT use
memory definition inside the recursion frames: only the 16 bits.
[Answer]
One-million in binary is equal to `11110100001001000000` (20 bits). Thus, we cannot implement a simple counter for this.
Instead, the max number we can represent with 16 bits is `1111111111111111` = 65,535. Since the answer requires that we only need to approximate 1 million function runs, we could add one to the counter approximately once every 16 function runs, and know that the function has run about 1 million times when the counter reaches 1000000/16 = 62500.
Below is the pseudocode of a potential solution, assuming that `counter` is a positive integer stored in 16 bits. Also, this assumes that calls such as `random(1,16)` do not count towards memory as long as they are not stored in a variable. Last, the `random(x,y)` function should give a random integer between `x` and `y` inclusive.
```
counter = 0;
function amIAttaBoutaMillionYet(){
if(random(1,16)==16 && counter<62501){
counter++;
}
if(counter==62500){
return true;
}
return false;
}
```
**UPDATE**
Fixed function so that it won't show true after about 2 million+, 3 million+, etc. function runs. (**thanks trinithis!**)
[Answer]
Beaten to it by `Briguy37`. :-(
Just call the function code 16 times for each tick of the counter.
```
def function()
{
do stuff here...
}
while(loop<65535)
{
function()
function()
function()
function()
function()
function()
function()
function()
function()
function()
function()
function()
function()
function()
function()
function()
loop+=1
}
```
[Answer]
You could make it so that for every external call of function `A`, `A` is called another 999,999 times internally. Therefore, you are guaranteed that that last internal call is the millionth call.
```
var internal = false;
function A() {
if (internal)
return;
internal = true;
A();
A();
// ...999999 times...
A();
A(); // This last call is guaranteed to be the millionth call
internal = false;
}
A();
```
[Answer]
The obvious approach is self-modifying code. Something along the lines of (and bearing in mind that I scarcely ever touch C, consider this to be pseudocode and don't try compiling it)
```
uint16 counter = 0;
void fun() {
byte x = 0;
if (x == 15) counter++;
(*fun)=(x+1)&15;
if (counter == 62500 && x == 0) sprint("Jackpot!");
}
```
It is, of course, cheating, but so is every possible approach, because the problem taken literally violates basic principles of information theory. And there may be a small offset needed when overwriting the initial value of x: depends on your processor and compiler. (No, I'm not going to dig out my notes on ARM assembler just for this).
[Answer]
Primary answer:
Does not use crazy macro expansion. Uses recursion and two 8 bit variables. The code works by recursing enough such that the first call to `foo` generates enough calls where the function is called approximately 1 million times.
```
//unsigned long count = 0;
//unsigned long numTimesTrue = 0;
#define SET_HIGH(x) (x |= (unsigned char)(1 << 7))
#define MASK_HIGH(x) (x & (unsigned char)~(1 << 7))
#define TEST_HIGH(x) (x & (unsigned char)(1 << 7))
int foo (unsigned char n = 0) {
static unsigned char i;
//++count;
if (n == 0) {
SET_HIGH(n);
}
if (MASK_HIGH(i) >= 20) {
return 0;
}
for (i = n; MASK_HIGH(i) < 20; ++i) {
n = i;
foo(MASK_HIGH(i) + 1);
i = n;
}
//if (TEST_HIGH(i) != 0) ++numTimesTrue;
return TEST_HIGH(i) != 0;
}
int main () {
int r1 = foo(); // 1, count == 1048576
int r2 = foo(); // 0, count == 1048577
int r3 = foo(); // 0, count == 1048578
//assert(numTimesTrue == 1);
return 0;
}
```
Secondary answer:
This returns true only once and only when the function has been run approximately 1 million times. I'm talking liberty in the usage of the word approximate in that the integers are unbounded. (1 is approximately 1,000,000 with respect to 100!!!!!! (you have to figure out which are factorials and which are exclamation points).)
```
int foo () {
static int hasRun = 0;
if (!hasRun) {
hasRun = 1;
}
return !hasRun;
}
```
[Answer]
Well, similar to Briguy37. I divided the 16 bits to two 8 bits vars. low byte is incremented on every call and reset when it reaches 250. On reset of low byte increment hi. When hi reaches 4000 (1000000/250 = 4000), we have 1 million calls
```
byte hi=0
byte lo=0
function oneMillionCallFunction()
lo++
if lo==250 then
hi++
lo=0
if hi==4000 then
return true
return false
```
[Answer]
to implement Briguy's solution in D
```
import std.random;
bool foo(){
static ushort count = 0;//16 bits
if(uniform(0,16)==0)count++;//increment once in approx every 16 calls
if(count==62500)return true;//we're close enough
return false;
}
```
[Answer]
This scala-code contains the test, to see how much we are away:
```
val r = util.Random
def resetAndTest () {
var x = 0 : Short
def mioFun (n: Int) = {
if (r.nextInt (30518) < 1000)
x = (x + 1).toShort
if (x < 0) {
println ("n calls " + n )
true }
else false
}
(1 to 1010000).find (mioFun)
}
```
typical results:
```
scala> (1 to 10).foreach (_ => resetAndTest)
n calls 1001214
n calls 1000340
n calls 993883
n calls 1005774
n calls 1001670
n calls 997401
n calls 1009786
n calls 992853
n calls 1002313
n calls 1002992
```
[Answer]
I just had a strange idea - but it works. This python version works **without any counter**. The one-millionth call returns `1` any other the value `0`.
```
def fun():
global f
try:
f
except NameError:
def fun_int():
yield 0
yield 0
...
yield 0
yield 1
while 1:
yield 0
f = fun_int()
return f.__next__()
print(fun())
print(fun())
...
print(fun())
print(fun())
```
Unfortunately the generator reference `f` takes some bits - so please use a python implementation which does it in 16 bits or less.
[Answer]
Since Peter Taylor points out that using a PRNG may violate the 16-bit limit, what about using the system time? Would that also violate the limit?
In PHP:
```
$counter = 0;
function maybeOneMillion() {
global $counter;
$time = gettimeofday();
if ($time['usec'] % 100 == 0) {
$counter++;
if ($counter == 10000) return true;
}
return false;
}
```
[Answer]
# Python
Likely also bending the rules:
```
x = 0
def f():
global x
if x < 20:
x = x + 1
f()
f()
x = x - 1
```
Arguably could do with just 5 bits, and would probably be shorter in C. Stretches rule (3) perhaps a bit.
[Answer]
# C
it's actually 6 bit.
(Does rand() == 12679 count...?)
```
void func(void)
{
static struct {
unsigned short int count : 6;
} S = {42};
if (rand() == 12679)
S.count--;
if (!S.count)
puts("1 MILLION REACHED");
}
```
[Answer]
# C
This answer changes the name of the process, and more precisely uses the first character of the name as an additional 8-bits counter.
```
#include <stdio.h>
int main(int argc, char* argv[])
{
unsigned short cpt=0;
argv[0][0]=0;
while(argv[0][0]!=20)
{
cpt++;
/* the function printf is called 1.0000.000 times */
printf("ok\n");
if (cpt==50000)
{
cpt=0;
argv[0][0]++;
}
}
}
```
] |
[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/264818/edit).
Closed 6 months ago.
[Improve this question](/posts/264818/edit)
Inspired by this [tweet](https://twitter.com/thdxr/status/1697349989104550285?s=20) where a user stated the following:
>
> it's insane how much code would be cleaned up if JS got pipes and pattern matching
>
>
> i often do this since it's the best way to make use of TS inference and pattern matching would make it less hacky
>
>
>
```
const result = (() => {
if (scenario1) {
return {
type: 1,
thing: scenario1.thing
}
}
if (scenario2 && other.foo) {
return {
type: 2,
thing: other.foo
}
}
return {
type: 3,
thing: other.foo
}
})()
```
In the spirit of this statement let's *"simplify"* the above logic to be as concise as possible!
## The Problem
Write a code snippet in the language of your choice which will return the following:
1. When `scenario1` is **Truthy** output: `{ type: 1, thing: scenario1.thing }`
2. Otherwise if `scenario2` & `other.foo` are **Truthy** `{ type: 2, thing: other.foo }`
3. Otherwise output `{ type: 3, thing: other.foo }`
### Constraints
This exercise should be viewed in the context of a program which has already declared `scenario1`, `scenario2` & `other` either above or as globals. Answers should reflect the shortest way to do what the OP was trying to accomplish.
* Variable and property names should be the same as above (or as close as your language will allow) and should be considered global.
* Answers should return an object / struct / class instance containing two properties `type` & `thing`
* Assume these don't have a strict shape (since the OP's example was in JS) and can be any of the following: `null` | `undefined` | `{ thing: "baz" }` | `{ thing: null }` | `{ thing: 123 }`
* Shortest code snippet wins, bonus points if your language can include the `|` operator for example `x || (x | y)` over `x ? x : (x + y)` inspired by the [*we already have at home meme*](https://knowyourmeme.com/memes/we-have-food-at-home). If two answers are the same number of bytes, the one with more pipes will win.
### Input
To make this problem non-trivial
1. `scenario1`, `scenario2` and `foo` should be considered as globals and already declared
2. The should contain the equivalent properties as the JS example, but don't need to use the `.` syntax
### Output
Output should be an object containing two properties:
```
{
type: 1 | 2 | 3,
thing: scenario1.thing | other.foo
}
```
It doesn't have to be JS style object, but it should be an object containing the properties.
### Test Cases
| scenario1 | scenario2 | other | output |
| --- | --- | --- | --- |
| `{thing: true}` | `{thing: false}` | `{foo: 'bar'}` | `{type:1, thing: true}` |
| `{thing: false}` | `{thing: true}` | `{foo: 'bar'}` | `{type:1, thing: false}` |
| `{thing: false}` | `{thing: true}` | `{foo: null}` | `{type:1, thing: false}` |
| `null` | `null` | `{foo: 123}` | `{type:3, thing:123}` |
| `{thing: 0}` | `undefined` | `{foo: 'bar'}` | `{type:1, thing: 0}` |
| `undefined` | `{thing: 0}` | `{foo: 'bar'}` | `{type:2, thing: 'bar'}` |
| `undefined` | `{thing: "js"}` | `{foo: 'bar'}` | `{type:2, thing: 'bar'}` |
| `undefined` | `{thing: "js"}` | `{foo: null }` | `{type:3, thing: null}` |
| etc. | etc. | etc. | etc. |
### Quick Tests
```
function test(scenario1, scenario2, other) {
if (scenario1) {
return {
type: 1,
thing: scenario1.thing
}
}
if (scenario2 && other.foo) {
return {
type: 2,
thing: other.foo
}
}
return {
type: 3,
thing: other.foo
}
}
console.log([
test({thing: true}, {thing: false}, {foo: 'bar'}),
test({thing: false}, {thing: true}, {foo: 'bar'}),
test({thing: false}, {thing: true}, {foo: null}),
test(null, null, {foo: 123}),
test({thing: 0}, undefined, {foo: 'bar'}),
test(undefined, {thing: 0}, {foo: 'bar'}),
test(undefined, {thing: "js"}, {foo: 'bar'}),
test(undefined, {thing: "js"}, {foo: null }),
test(undefined, {thing: "js"}, {foo: 'bar' }),
])
```
[Answer]
# [Python](https://www.python.org), 109 bytes
Inspired by Gugu72's comment, and they sure were right about how hard booleans are to golf.
`undefined` doesn't exist, so `None` pulls double duty as its usual analogue of `null` and as that. If I have to explicitly handle a case where the input is the string `"undefined"` I will probably explode
```
{'type':1if(s:=scenario1)else 2|(not((f:=other and other['foo'])and scenario2)),(t:='thing'):s[t]if s else f}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVE9TsMwFFbXnOJttqWASFiQpayMTGylgyE2cZXYxn5BiopPwtIFbsBh4DTkt5UqQHjye_p-9V7fXYeVNfuPUipAGZAynoCX2HoDd28tqrOrz2ZHsHOS8EwrGngRHqQRXtuMyTpIyF-osUip4oXFSnoQpoTxtybKWrJhw2Ih5YylFHlBsNLmkTAe1rjRCgKMYirOpkZ520DoAujGWY8QsNQmUdZDrY0EbaZNH_eQJz26pFMCKKARjspnUacj7zy4WvctWQLOa4N0Ks0m1_3XarWbk_Fb38oIh_Fa9PmGeejEyb3wJCY3to9yfCfjAs7yy5gchC7iH9CfdU-4_wSTbSBxcvod8zRAFsEBNR_gGw)
[Answer]
# [R](https://www.r-project.org), ~~180~~ ~~150~~ 138 bytes
```
o="other"
s="scenario1"
`+`=\(x)exists(x)&&length(get(x))
list(type=(3-(+"scenario2"&+o))^!+s,thing=`if`(+s,get(s)$thing,if(+o)other$foo))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=zZNNTsMwFIQX7HwKY6rEVtIFYcPGN0EoaXESi2JT_0gpR-AKbMKCQ5XT4D5XbqgQQghVrOKJ503mk52XVzNuswusNLZLoRoj9WU5VRUo7Xph3rxr59fbZ80JaIIsJ2mKoLqo-Q0dmBikdTYssmwlVOd62gkXJEOrsEHd5lFwejWnRRquSFZoxm7PC1u6XqqO17KtaVC7Sctm8LKULQ02-Pas1WEgNno_u_8eACZwrIVCyL7gpDtj5oEmyb4yVZ9NFUMQy4EptOFk0Rjy94wIHcOlRO6MF7_BOyTEtlAn9H8ip6RKhfYc00PD2kQudHBNu679QH54TBNTvLZggOUpuPDCO3ynhVW5w0utXCMVbtQG5xCRHwOuvR92fP6fEsZ_bhzj8wM)
Treats non-empty lists as truthy (not R's default behaviour, but seems to be the intent of this question).
Handles the cases where global variables `scenario1`, `scenario2` or `other` are undefined (=not 'declared').
---
# [R](https://www.r-project.org), ~~116~~ 94 bytes
```
o=other
s=scenario1
`+`=length
list(type=(3-(+scenario2&+o))^!+s,thing=`if`(+s,s$thing,o$foo))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jZIxTsMwGIUlRotDmFIRW0kHwtLFN6jYWKukwWksVf5b-7eUgjgJSxjYuQ6cBtcWaQpCzWQ_-fl9_p_8-ma6D5QWRe10hQo048_vDuvZ_HNpha2kLo2CWwICsJGGFGkhNlKvsSEbZZHhfisFu5ux9Meb36TA-fIqtRk2Sq9FoerCH2d2GnQG0xq8I1K-Li5fCLmmGmgPy4YqDyrCe4e4f1gseplHGTxxe5iI8XO54QKVrZ_DjsoOE_vHi8mqNBP-L-Z4GY2TY0Gxz1CZz3_y-eeox6jIGY5HwfxpbUjYudZnjanwlEJXDukjSKsTpBVoLJWmpd7TJAQnv3E759oDzY3ixU_RdXH9Bg)
Assumes that global variables `scenario1`, `scenario2` and `other` already exist.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 70 bytes
*-4 bytes, thanks to Value Ink*
```
{type:(s=scenario1)?1:2|!((o=other.foo)&&scenario2),thing:s?s.thing:o}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcFN2-Lk1LzEosx8Q9vSvJTUtMy81BQumJiRbV5pTg5XfklGapFtdVp-vpWCelJikXotV1FqcWlOie3S0pI0XYubbtUllQWpVhrFCNM07Q2tjGoUNTTybcHa9YC6NdXU4CZr6pRkZOalWxXbF-tBWPm1ENM2J-fnFefnpOrl5KdrQOzRhMgsWAChAQ)
Takes Inputs as global variables
[Answer]
# JavaScript (ES6), 68 bytes (2 pipes)
```
{type:(v=other.foo,o=scenario1)?1:2|!v|!scenario2,thing:o?o.thing:v}
```
[Try it online!](https://tio.run/##pdFLboMwEAbgPaeYZBOQHBLIjopm1VMgFi6YQGR5IvOQIuKzUxOrbqAtUVVWfsz/2R7OtKN1JqtLsxWYs@ElcQAS6JuyEqcIGtkyRcDOC8rrcaEvECPYvFO5UZAS2O10yfXCooDAY3SC2fAcf46Z6B800XKu4Lk21umQ/eZzowXhQWMT7WC1cXNys70yQityVlSC5eTRWnzn3kjfkjP5Vym0ktlc1Nbner3Y/39oYx9Ba/BTx@4/x0kdv0D5RrPSdROoMyaorFD34nOoj8emZBJSD@JX6CFDUSNnPseTOxjU7eJ7jaaQYGwV7xhE4W3V3VZfmjkdj@ibUacGT3nDBw "JavaScript (Node.js) – Try It Online")
### Commented
```
{ //
type: ( // define the 'type' property:
v = other.foo, // copy other.foo in v
o = scenario1 // copy scenario1 in o
) ? // if scenario1 is truthy:
1 // set the type to 1
: // else:
2 | // set the type to 2 unless
!v | // other.foo is falsy
!scenario2, // or scenario2 is falsy,
// in which case it's set to 3
thing: // define the 'thing' property:
o ? // if scenario1 is truthy:
o.thing // use scenario1.thing
: // else:
v // use other.foo
} //
```
] |
[Question]
[
**This question already has answers here**:
[Numbers with Rotational Symmetry](/questions/77866/numbers-with-rotational-symmetry)
(43 answers)
Closed 3 years ago.
# Strobogrammatic Numbers
---
### Definition
A number which is rotationally symmetrical, i.e., it'll appear the same when rotated by 180 deg in the plane of your screen. The following figure illustrates it better,

(source: w3resource.com)
# Task
Given a number as the input, determine if it's strobogrammatic or not.
# Examples
* Truthy
```
1
8
0
69
96
69169
1001
666999
888888
101010101
```
* Falsey
```
2
3
4
5
7
666
969
1000
88881888
969696969
```
# Rules
* The number is guaranteed to be less than a billion.
* We are considering `1` in it's roman numeral format for the sake of the challenge.
* Input can be taken as number, or an array of chars, or as string.
* Output would be a truthy/falsey value. However, you are allowed to flip the output values.
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes will win!
---
[Sandbox link](https://codegolf.meta.stackexchange.com/a/20557/83605)
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, ~~48~~ 34 bytes
@Arnauld had a better idea in his JavaScript answer than my first one in Perl, so I stole it.
```
y/0-9/01aaaa9a86/;$_="@F"==reverse
```
[Try it online!](https://tio.run/##LUvBCsIwFLvnK6TsOvee2trnGHgSPPgNo4cehLGVbQr7eeubMyEhhCTFsbN5Cou59@k1X3ZFa@q8VFRKRRwUEryr6qJtzPVmmmaM7zhOMecDjjjB4gznHMQJmIjgFaxam41geBA0iFPnbcnrTUR@B50z/QlLnyHNz6Gfcvmwe@1ymbrwBQ "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes
```
•yΘOñ•I<èRQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcOiynMz/A9vBDI8bQ6vCAr8/z/aTEfBMhYA "05AB1E – Try It Online")
*-1 byte thanks to Razetime's suggestion*
Takes the number as a list of digits
## Explained
```
•yΘOñ• # Push the number 1000090860
I< # Decrement the input list
èR # And get each number when rotated 180 degrees, reversing it
Q # Check if that equals the input
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 30 bytes
```
p$_.==$_.reverse.tr'92-7','69'
```
[Try it online!](https://tio.run/##KypNqvz/v0AlXs/WFkgUpZalFhWn6pUUqVsa6Zqr66ibWar//29pBoX/8gtKMvPziv/r5gEA "Ruby – Try It Online")
[Answer]
# Node.js 11.6.0, ~~34~~ 33 bytes
Expects an array of digits. Returns *false* for strobogrammatic, or *true* otherwise.
```
n=>n.some(c=>n.pop()-c**66%79%63)
```
[Try it online!](https://tio.run/##fZDNDoIwEITvPkYTkpaEphVd6AGPPoE35EAq@BNsCUUTn74KetDEbffS9JuZbOdS32unh3M/JsYeGt8W3hQbw529NlRPt972lCU6jgGiTEWQMq@tcbZreGePlJS74TaeHhVhi@/3lpaccyJJxf6CHAMCA6AwogD3SNwmhUDXAwClUGc@Hzz3M7PgR0H2ptzWncPqWmKZKQZWGFhjIAv8GW841KII9SQDTb1i3zMJ/BM "JavaScript (Node.js) – Try It Online")
### How?
Taking the precision errors on large integers into account1, we look for a function:
$$f(x)=(x^p\bmod m\_0)\bmod m\_1$$
such that:
$$f(0)=0,\:f(1)=1,\:f(6)=9,\:f(8)=8,\:f(9)=6$$
and:
$$f(x)>9\text{ for }x\in\{2,3,4,5,7\}$$
*1: [These errors actually depend on the JS engine](https://stackoverflow.com/q/65426364). This is guaranteed to work with Node 11.6.0.*
---
# JavaScript (ES6), 38 bytes
Expects an array of digits. Returns *false* for strobogrammatic, or *true* otherwise.
```
n=>n.some(c=>n.pop()!="01----9-86"[c])
```
[Try it online!](https://tio.run/##fZC9DsIgFIV338I7wVAC/iAMdfQJ3LBDg60/qdCUauLTY1sdNPFy70L4zjmBcy0fZbDdpe0z549VrPPo8q1jwd8qYsdT61tC5zlwkQ2jMyXB2IJG613wTcUafyJg9t29Pz8LoLPv@5oYxhgIKOhfoDDAMSA1RrTEPQK3Cc7R50kptUadaho897OT4EcBB2d2ZROwuhZY5hIDKwysMbBJ/BlvONUiT/UkEk0Nse8dBfEF "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 53 bytes
```
lambda n:["01....9.86"[int(c)]for c in n[::-1]]==[*n]
```
[Try it online!](https://tio.run/##ZY/BDoIwDIbvPsXSE5hINtHJSLj6BN7GDoghkGAhOA88/QQxwY729LX/3/ztR1t3GLsqy11bPO@PgmGqgYtoKhUlEnSDNihDU3UDK1mDDHWaHoQxWab3aFw/zAK4DW9bjxDuFq4CEBD@UUKIE5KKoJLeVngCwTk9LqVUimqSb3m2X69TyPFatK8596o7EldM6EToTOjiZ/K@2jzBN4mFn3lyLT1N3Qc "Python 3 – Try It Online")
] |
[Question]
[
Simple question!
Given a string that contains a date in ISO8601 format, print the first of the next month in ISO8601 format.
Example inputs:
`2018-05-06`
`2019-12-20`
Their respective outputs:
`2018-06-01`
`2020-01-01`
The rules:
* Imports are free and don't count towards your score.
* The date will be stored in a string called `s`.
* The solution with the least characters, wins
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~67~~, ~~57~~, 56 bytes
-10 thanks to Arnauld,
-1 joining template string and ternary
```
s=>([a,b]=s.split`-`,+a+!(b%=12))+`-${b++<9?'0'+b:b}-01`
```
Test cases:
```
f=s=>([a,b]=s.split`-`,+a+!(b%=12))+`-${b++<9?'0'+b:b}-01`
console.log(f('2018-12-20'))
console.log(f('2019-05-06'))
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~31~~, 24 bytes
7 bytes saved thanks to @manatwork and @nwellnhof
```
date -d${1%??}1month +%F
```
[Try it online!](https://tio.run/##DcexCoAgFAXQva@4Q03xQIWiaGjrJ6TBeA8MLKGEhurbre2cxZ0@X34NgkMcI@B5YC3KgHkeOOKUBKL/mV0SEJe3rsbx1Vvck0ddTZnjLtko3ZFqSLXFz560IaM@ "Bash – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/en/) 49 bytes
```
d=Date.parse(s);print Date.new(d.year,d.mon,1)>>1
```
[Online repl](https://repl.it/repls/GuiltyAmazingPercent)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 33 bytes
```
T`9d`d`.9*(-12)?-..$
-23|-..$
-01
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyTBMiUhJUHPUktD19BI015XT0@FS9fIuAbCMDD8/9/IwNBC18BU18CMC8i0BCrTNTIAAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`9d`d`
```
Increment with wrap-around...
```
.9*(-12)?-..$
```
... the last non-`9` digit, plus trailing `9`s, in either the year or the month, depending on whether the month is `12`. (Digits in the following date parts also get incremented.)
```
-23|-..$
-01
```
Replace the day with `01`. Also, if the month was `12` before, it will be `23` now, and also needs to be reset to `01`.
[Answer]
# [PHP](https://php.net), 57 bytes
```
[$y,$m]=explode('-', $s);$m=++$m%13?:!!++$y;$d="$y-$m-1";
```
Test cases:
```
<?php
function next_month($s) {
[$y,$m]=explode('-', $s);
$m=++$m%13?:!!++$y;
return "$y-$m-1";
}
$s = "2018-05-06";
echo next_month($s); // Gives 2018-6-1
$s = "2019-12-20";
echo next_month($s); // Gives 2020-1-1
```
[Answer]
# Red, 39 bytes
```
t: load s
t/month: t/month + t/day: 1
t
```
[Answer]
# Python 3.6.9, 73 characters
```
from datetime import *; from dateutil.relativedelta import relativedelta as r;
(datetime(*map(int, s.split('-')), 1) + r(months=1)).strftime('%Y-%m-01')
```
Your rules say that imports don't count, so I didn't count them.
] |
[Question]
[
Inspired by [Digits in their lanes](https://codegolf.stackexchange.com/questions/160409/digits-in-their-lanes)
## Input:
An ASCII-art of width ≤ 11, consisting of spaces and `#`. (You can choose any two distinct characters instead.) Example:
```
#
###
#
#
# #
# #
# #
# ### #
# ### #
###########
# #
# #
# ### #
# ### #
# ### #
###########
```
## Output:
A list of integers, with one element for each line of the input.
If you put a hash in each decimal digit's lane, including the minus sign, in
the order `-0123456789`. Duplicated digits are allowed, but ignored. The order of the digits in the output is not important.
Possible outputs for the above input include:
```
[ 4, 345, 4, 4, 35, 26, 17, 34580, -3459, -9876543210, -9, -9, -3459, -3459, -3459, -1234567890 ]
[ 4444444, 5345354354, 4, 44, 535, 2666, 71, 85430, -3495939495, -93678132645160234, -99, -99999, -934539, -935439, -9534, -9876543210 ]
```
Note that you have to distinguish between 0 and -0. If your output format doesn't support that, you can say there is a special value for -0 (e.g. `None`).
### Leading zeros
If a number is 0 (or -0), the zero is always counted.
Else, you have to move the zero after the first digit (not necessarily next to it): For example, -09 stands for `-` and `9`, so you have to output -90 instead. So, even if you output the string `"-09"` where `-`, `0` and `9` are `#`, that is not right.
* In your output, leading zeroes are not counted (that is, the output is the same as if those leading zeroes are removed). This does also include zeroes directly after the minus signs.
+ Here are some examples for clarification:
```
-0123456789 OK not OK
## -> -0
### -> -10 -01
## # -> -90 -09
## -> 10 01
# -> 01 10
```
* **This does also apply when you output a string!**
## General rules
* You can assume that in every line, at least one of 0-9 is a `#` (not empty or only `-`)
* You can submit a program or function
* Choose any reasonable input/output format (eg. list of lines, list of characters, etc.)
## Scoring
* Your score is the number of bytes in your code.
* Lowest score wins.
## Loopholes
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden
## Examples
Note that there is an infinite number of correct outputs for every input, here,
only one is mentioned. If you need to verify an output, you can usually use an
answer to
[Digits in their lanes](https://codegolf.stackexchange.com/questions/160409/digits-in-their-lanes)
and input your output. Then compare it's output with the original input.
```
# 4
### 345
# 4
# 4
# # 35
# # 26
# # 17
# ### # 83450
# ### # -> -9534
########### -9876543210
# # -9
# # -9
# ### # -3459
# ### # -3459
# ### # -3459
########### -1234567890
######### 123456780
# # -9
# ## ## # -23679
# # # # -159
# # # # # -1579
# ## ## # -> -23679
# # -9
##### ### 12346780
## 45
# 4
## ## ## -45890
# # # # -137
## # # -> -370
# # # # -379
# ## ## -4589
## ## ## ## -2356890
# # ## -> -289
# # -2
## -0
## 10
## 12
## 23
## -> 34
## 45
## 56
## 67
## 78
## 89
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
[...turns out it's slightly different to Dylnan's method, I thought they just beat me to it](https://codegolf.stackexchange.com/a/161187/53748)
```
ṙ€1T€ịØD;”-¤U
```
A monadic link accepting a list of lists of 1s and 0s which returns a list of lists of characters the output "numbers".
**[Try it online!](https://tio.run/##dVA5DsJADOznL0iempYnABIPoEH5AB2ioeADUNBRUtKgdOQlyUeWZO3YIYHV7mrGGo@P3bYo9inVr2tzfHDZfnV5ri6LeXO4zd73VarL57qNtrc6bVKS7jD/yJB0PIx/acQ1tIdewA7TfCigexKMA1WLxkfY9f/wwAfiWMZG1Nfhvs/AnGgiVz1zPRt@uhRoMzk9m1oJ6OCGfUVWwPTI7npB390AewUjEgQSBBIE0emPtpVAgkCCIKbnBw "Jelly – Try It Online")**
### How?
```
ṙ€1T€ịØD;”-¤U - Link: list of lists of integers (in {0,1})
ṙ€1 - rotate €ach list left by one
T€ - get the truthy (1-based) indices of €ach
¤ - nilad followed by link(s) as a nilad:
ØD - decimal digit characters = "0123456789"
”- - literal '-' character
; - concatenate
ị - index into (vectorises)
U - upend (reverses each resulting list of characters)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ñ╬ü+U☻T→╡aN
```
[Run and debug it](https://staxlang.xyz/#p=a4ce812b5502541ab5614e&i=%23%23+++%23%23++%23%23%0A%23+%23+%23+++%23++%0A%23%23++%23+++%23++%0A%23+++%23+++%23+%23%0A%23++++%23%23++%23%23%0A%0A%23%23+++++++++%0A+%23%23++++++++%0A++%23%23+++++++%0A+++%23%23++++++%0A++++%23%23+++++%0A+++++%23%23++++%0A++++++%23%23+++%0A+++++++%23%23++%0A++++++++%23%23+%0A+++++++++%23%23&a=1&m=1)
Unpacked, ungolfed, and commented, it looks like this.
```
m for each line of input, run the rest and implicitly output
|( rotate string left once
:A get indices of maxima (indices of '#')
Vd'-+s push "0123456789-" under the top of the stack
@ get characters at indices
r reverse string; puts '-' at the front
output is implicit
```
[Run this one](https://staxlang.xyz/#c=m+++++++%09for+each+line+of+input,+run+the+rest+and+implicitly+output%0A++%7C%28++++%09rotate+string+left+once%0A++%3AA++++%09get+indices+of+maxima+%28indices+of+%27%23%27%29%0A++Vd%27-%2Bs%09push+%220123456789-%22+under+the+top+of+the+stack%0A++%40+++++%09get+characters+at+indices%0A++r+++++%09reverse+string%3B+puts+%27-%27+at+the+front%0A++++++++%09output+is+implicit&i=%23%23+++%23%23++%23%23%0A%23+%23+%23+++%23++%0A%23%23++%23+++%23++%0A%23+++%23+++%23+%23%0A%23++++%23%23++%23%23%0A%0A%23%23+++++++++%0A+%23%23++++++++%0A++%23%23+++++++%0A+++%23%23++++++%0A++++%23%23+++++%0A+++++%23%23++++%0A++++++%23%23+++%0A+++++++%23%23++%0A++++++++%23%23+%0A+++++++++%23%23&a=1&m=1)
[Answer]
# [Perl 5](https://www.perl.org/) `-lp`, 35 bytes
Uses `#` and `;`
```
#!/usr/bin/perl -lp
s/./"$&@--1"/eeg;s/-1/-/;s;0(.);$+0
```
[Try it online!](https://tio.run/##dY1LCsMwDET3OoYdQktQZC@6mk0uY0LBJKbu@as2PycpRCDxGB6jFF7xoZqlFVPVHbM3EkKPLOyFBRnu1t5RNU7VToP50oxA4WN@cmxxsC5tAibG2gNLKJ0g7EOLbZf8j4t/xcce/N6BPmN6P8chK8f0BQ "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ 17 bytes
Currently 3 bytes to make sure the number doesn't start with zero. Looking for a shorter way.
```
vžh'-ìyƶ0K<ΣΘ}èJˆ
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/7Oi@DHXdw2sqj20z8LY5t/jcjNrDK7xOt/3/Hx1toKOAjAxRuQaxOgrRaPKGaKrQlRBhCnEWGeCzyBCrWQgl6ObDRaBKDHH4yBCqxBCvpw2hSvAhdFMwETlKcLuFOkrw@igWAA "05AB1E – Try It Online")
or [with ascii-art input](https://tio.run/##MzBNTDJM/V/zqGlN8OENh7v@lx3dl6Gue3hN5bFtBt425xafm1F7eIXX6bb//5WVFRQUQISyMpeyAggqgDAXWAjGVoCxlcFsqHoA)
Uses **1** instead of **#** and **0** instead of **space**.
[Answer]
# APL+WIN, 58 bytes
Prompts for a character matrix:
```
(⊂[2]z[;1],⌽0 1↓z←' -0123456789'[1+n×(⍴n←⎕='#')⍴⍳11])~¨' '
```
Outputs digits in reverse order to cope with leading zeros.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 14 bytes
```
ØD”-;ẋ"Ѐṙ€1Ṛ€
```
[Try it online!](https://tio.run/##y0rNyan8///wDJdHDXN1rR/u6lY6POFR05qHO2cCScOHO2cBqf@H2yP//49WNzQ0MDAEQiCprsOloA5mIvMNUOUNwfJggMZHqDcAm2mgHgsA "Jelly – Try It Online")
Function submission. Takes a list of lines as input. Characters are `1` for on and `0` for off.
**Explanation**
```
ØD”-;ẋ"Ѐṙ€1Ṛ€
ØD Digits 0-9 as characters
”- Character literal -
; Concatenate -> -0123456789
Turn each 0 and 1 from the input (characters) into an integer.
Ѐ For each list of integers 0 and 1 corresponding to the list of lines in the input...
" Zip the characters -0123456789 with the 0s and 1s.
ẋ Include each of the characters if paired with a 1, not if paired with a 0.
Characters that get included turn into ['3'] (3 as an example)
Those that don't turn into []. This is important for the next step.
€ For each of the lists of [character]s and []s.
ṙ 1 rotate it by 1. This moves the ['-'] or [] in place of ['-'] to the end of the line.
Ṛ€ Reverse €ach line. Brings the ['-'] to the front and the leading ['0'] if present to the end.
```
[Answer]
# JavaScript (ES7), ~~60~~ 55 bytes
Takes input as an array of strings with `0` instead of `#`. Returns an array of strings.
```
a=>a.map(r=>('-'+2**67).replace(/./g,c=>[c[r[++c|0]]]))
```
[Try it online!](https://tio.run/##lZLJDoIwEIbvPEVvbQXrxIMeDLwI4dBUNBqkBIwn3x0j3YvrhPbw0Zl/tjO/8UH0p@66bOW@Hg/5yPOCswvvSJ8XBC9xul4sNlvK@rpruKjJiq2OmciLUpR9mabiDlVVUToK2Q6yqVkjj@RAygQhjJ4G040zAwAgBLMXcxcUuoA@BoDx0gC0CmgAVhY0cOZeKPsEwhjfgaeSVJSd5aklOMOU7pLkVbvsc/Q@CVDHAtOLCMAHlyiokkVOVv18M6VfClFNmFRdVuCPSE3HB3asfpo6xo@a5nOF60oi8E8VyF9FR@zmQQQs8Rd@tt9xbxXxwUQCgML56MqiQsYH "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // given the input array a[]
a.map(r => // for each row r of a[]
('-' + 2**67) // generate the string '-147573952589676410000'
.replace(/./g, c => // replace each character c of r with either c or ''
[ // wrap the result into [] so that undefined is coerced to ''
c[ // read c['0'] (gives c) or c[' '] (gives undefined)
r[ // read r[] --> gives '0' or ' '
++c | 0]]] // gives (NaN | 0) = 0 if c is '-', or (c + 1) if c is a digit
) // end of replace()
) // end of map()
```
[Answer]
# Java 10, ~~176~~ 136 bytes
```
c->{int l=c.length,i=0,j;var o=new String[l];for(String s;i<l;o[i]=c[i++][0]<8?"-"+s:s)for(s="",j=10;j>0;)s+=c[i][j--]<8?j:"";return o;}
```
Returns an array of Strings. Uses the *BEL* character instead of *#*.
Try it online [here](https://tio.run/##jVI9T8MwEJ3dX3HKlChNFCYQbkCIGRbGNIMxabngOpXtFFWov72cnQ9RBoSHnO/l@dl371pxEFn79nHe968KJUglrIUngRq@Fgy1a8xGyAae@91rY6wH2YszqLdVDTqAsXwXpqopF1YiJnzBTgs26lknHIVDh2@wI9V4PizM1iZBb9LWYyzhLLO7L7ocVClz1eite19iWSxbfhAGulI3nzAKqZpvOjPKguW4UryrsC5lhWlaV0W9urmPsii1tzbxTFtG0bItrwre3hU8saln1lWbZZ7Z3kYRN43rjYaOn86MUTlsrtBvhHTDK32Cm2McrfuiKK6HL/wvWesRhCnCvP2DQYm@0JzXWsMvaEYu8cgbxF6O1jW7vOtdvqfOOaXjlkYh7x2q/MEYcbS564auxqMx@Q@/hyYkyeS2wYNwzWT3Rb98i0Z7UO97l1wOkd0rdNTN8C8PGXVUD8@cheih9Jto3vqABuY4HMTwbG@vnxokXsEprOAni5A0TYjHBjWynYiBQVsq95F0Q@0xXQ6/1jQU4Wio@nT@Bg).
Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for golfing 40 bytes.
Ungolfed version:
```
c -> { // lambda taking a char[][] as argument
int l = c.length, // the number of lines
i = 0, //used for iterating over all lines
j; // used for iterating over each line
var o = new String[l]; // output array
for(String s; // the output for the current line
i < l; // iterate over all lines
o[i] = c[i++][0] < 8 ? "-"+s : s) // add a minus if necessary
for(s = "", j = 10; j>0; ) // to avoid leading zeroes, we step through the line backwards
s += c[i][j--] < 8 ? j : ""; // append the next digit, if applicable
}
return o; // return the output array
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 74 bytes
```
lambda s:[''.join(`i-1`[0]for i in[0]+range(10,0,-1)if' '<l[i])for l in s]
```
[Try it online!](https://tio.run/##jVHLDoIwELzvV2zYQyE@Ah6NfgmSiFG0BgsBLn49Qlu6KL42lMw0093OtLw3l0Kt2my7a/P0djimWK9jIZbXQip/LxfRPg6TrKhQolQdnFWpOp/8KJyH80UUyEyg2OSxTIJelHcirJO2rKRqMPM9z8O@SP9BQyKHx/tPGnQasgsGAfWYbB9CINeTgLjAqNHsv2Cn/4S5OgfLusxl44udEkEAMPbmZPg6g8zq8WCBMU00fNb01FexuUzy@nonY0F31vPsdDBxWeyCtbON/lff4QNyjzHC/9wL7RszAWQCyATY@pscDAFkAsgEOM6Jp/YB "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 54 bytes
```
{.map:{(.ords.grep(:k,*>32)X-1).sort(1/*)>>.ord.chrs}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wi83scCqWkMvvyilWC@9KLVAwypbR8vO2EgzQtdQU684v6hEw1BfS9PODqRELzmjqLi29n9xYqVCmoYGl5ICCCiDSSUdCFdZWRmZiyaLrlgBWbEyFEO4yjD1YK4y1GRlMFcZbpEymIsAMFkIwMVF1oufi2YyiNTUtP4PAA "Perl 6 – Try It Online")
Takes a list of lines. Explanation:
```
{
.map:{ # For each line.
(.ords.grep(:k,*>32) # Find non-whitespace indices.
X- 1) # Decrement each, range is now -1..9.
.sort(1/*) # Sort by reciprocal, moving 0s to the end.
>>.ord.chrs # Join first characters.
}
}
```
[Answer]
# [R](https://www.r-project.org/), 83 bytes
```
for(i in gregexpr("#",readLines()))cat(sub(99,0,sort(c("-",99,1:9)[i])),'
',sep="")
```
[Try it online!](https://tio.run/##dYxNCsJADEb3c4qQLJpABF1W8AbeQFzUOpbZtCVTwduP9sepCn6Q8BIen6V064wDhBYa841/9MZIqOar6zG0PrKI1NXA8X7hstStxs4Grhk3qK97ty/lFM4iWrhCo@8PiJJgDE3bTUiU@fP/5UB2aBn3FmhkWnoIHOVOcrTGzTbM/x/O/j9ek54 "R – Try It Online")
A nasty 83 bytes; would have been so much shorter (and simpler of a challenge, I suppose) to not have to move the `0` to the end. Ah well. Uses `99` in place of `0` to utilize `sort` to move `0` to the end, but that comes at the cost of having to use `sub`.
[Answer]
# [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 123 bytes
```
using System.Linq;l=>l.Select(k=>{var c=k[0]!=' '?"-":"";for(int a=k.Length;a>1;a--)if(k[a-1]!=' ')c+=$"{a-2}";return c;});
```
[Try it online!](https://tio.run/##jZJRS8MwFIWfm19xTYS1bC3OR2MqIirCBGEPPkwfYkxraJdikk5k9LfXzLV1ThEvJIGPc84luRE2Fla0tVU6h/m7dXKZzJR@pegbuqjKUgqnKm2Ta6mlUYIiJEpuLdyZKjd8CWsUWMedErCq1DPccqVD64xPWTwCN7mNvGSjGZADBlq@wYB8RBBg2BT53PFkIISQPfJT84sL9lykWwMhvbEnpOtFekKG7qQnX7Wj2dbfZC/nP2SnlwcNRQFC3Viuai1O@9ebwM2lrpfS8KdSdjRNIQPWliwtk7ncjDAsWLpecQOCFYujxwM2gtEZjvEJxjSrTKi0A86KZCZ17l4oT6eUx3GksrBY8Hi6NURizA7xmsfHDaZGutpoELSJaEvR8GO0rUqZ3BvlZJiFftpRcp7nRubcg7CagIqApVDBGPCDxv5QUeRv16Cm/QA "C# (Visual C# Compiler) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 34 bytes
```
(.)(.*)
$2$1
-(?=.)
$.%`
%O^$`.
```
[Try it online!](https://tio.run/##dYw7CoAwEET7OcXCJBCFLGgvHsEbiBYWNhbi/eM/UcGBXR7DY@ZhGac@ED44zZzmGUxpCnhXV7qx2g4C2KY1nYYge3h8HEhGfvYvR6LD63AL3JnXDgWMmwRTcNpy9h@O/h@nrA "Retina 0.8.2 – Try It Online") Takes input using `-`s instead of `#`s, but the linked header includes the substitution. Explanation:
```
(.)(.*)
$2$1
```
Move the first character of each line to the end.
```
-(?=.)
$.%`
```
Replace each `-` not at the end of a line with its column number.
```
```
Delete the spaces.
```
%O^$`.
```
Reverse each line.
] |
[Question]
[
Your goal in this code golf is to compile all the Stack Exchange sites' favicons.
---
## Getting the Domains
The domains you will be using will be:
* `*.stackexchange.com`
* `stackexchange.com`
* `stackoverflow.com`
* `superuser.com`
* `serverfault.com`
* `askubuntu.com`
* `mathoverflow.net`
* `stackapps.com`
* `stackauth.com`
Everything but [`stackexchange.com`](http://stackexchange.com) and [`stackauth.com`](http://stackauth.com), as of now, can be gathered from [`/sites`](http://stackexchange.com/sites).
All the meta counterparts will also be included. (just prepend `meta.` to the beginning of any of the domains to get the meta site)
The list above shows the order of the sites. Sites without their own domain (`*.stackexchange.com`, i.e. [`codegolf.stackexchange.com`](https://codegolf.stackexchange.com/)) are first in the stylesheet, and are sorted alphabetically. After you've sorted the subdomain sites, the rest of the domains are in the order listed above.
Then, you can append `/favicon.ico` to each one of the domains you dynamically compiled and get the 32 by 32 pixel image that results from it.
Here's another list for domains that redirect to `*.stackexchange.com` sites:
* `askdifferent.com` → `apple.stackexchange.com`
* `arqade.com` → `gaming.stackexchange.com`
* `seasonedadvice.com` → `cooking.stackexchange.com`
## Output the Images
As soon as you have all of the favicons from the sites and their meta counterparts, your code combines them. Optionally, convert them into .PNG files (you gathered .ICOs, and [trying to get `favicon.png` doesn't work](http://stackexchange.com/favicon.png)) After that, you can start combining the images into one rectangle.
There will be 10 columns, each 32 pixels in width, making a total of 320 pixels. The number of rows will match those needed to fit all the favicons, and they are 32 pixels in height.
Your code should output an image with all of the favicons you gathered as a transparent .PNG file, which is already , like seen below:
---
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and so the least bytes wins!
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
```
var QUESTION_ID=86753;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>
```
[Answer]
# JavaScript (ES6), ~~691~~ ~~687~~ ~~680~~ ~~663~~ ~~646~~ 657 bytes
```
fetch(new Request('//crossorigin.me/http://stackexchange.com/sites')).then(r=>r.text(t=(d=document).body.appendChild(c=d.createElement('canvas')).getContext('2d')).then(a=>(d=new DOMParser(c.width=320).parseFromString(a,'text/html'),s=[...d.querySelectorAll('.grid-view-container>a')].map(e=>!~(h=e.href[p='slice'](7))[o='indexOf']('met')?h:h[p](5)),c.height=-~(s.length/5)*32,s.sort((a,b)=>(e=a[o](k='.s'),g=b[o](k),~e&&~g?a[l='localeCompare'](b):!~e&&!~g?a[p](e)[l](b[p](g)):g-e)).concat(s.filter(u=>!~u[o]('ka')).map(u=>'meta.'+u))).map((u,i,x,y)=>(u=`http://${u}favicon.ico`,x=i%10,y=(i-x)/10,i=new Image,i.src=u,i.onload=_=>t.drawImage(i,x*32,y*32)))))
```
Oof. Hopefully I can trim down the byte count.
Basically:
* CORS request to `/sites`, parse DOM and scrape the site list from there using a query selector.
* Sort first by `*.stackexchange.com` sites alphabetically, then by independent domain sites alphabetically.
* Append the meta sites, filtering out `meta.stackexchange.com` and `stackapps.com` since they're both listed on `/sites` and are without their own `meta` site.
* Asynchronously load each `favicon.ico` without CORS since we don't care about tainting the `canvas`.
* Use each site's index `i` from the sorted array to place the loaded image in the correct position on the sprite-sheet.
You can right-click on the image and select "Save Image as", so I don't think I need to write more just to explicitly prompt the image for download, since it's already enough work just displaying it.
### Revisions
1. Inlining global declarations saved 2 bytes. Submission is now one loooong line.
2. Removing `()` from `new Image()` saved another 2 bytes.
3. Changing `Math.ceil(...)` to `-~(...)` saved 7 bytes. Doesn't apply now, but in the event that the amount of sites is a multiple of 10, it's still okay because *`"There are 10 columns, which is 320 pixels in width, and unlimited rows/height"`* regardless of the amount of sites.
4. Saved 17 bytes by moving a global declaration and refactoring an unneeded ternary operator in a `.map()` function.
5. Saved another 17 bytes by storing long repeated method names to variables.
6. Cost 11 bytes to factor in `stackexchange.com` and its meta... gross.
[Answer]
# Python 3.5, ~~591~~ ~~549~~ ~~541~~ ~~557~~ 570 bytes:
(*+16 bytes (`541 -> 557`) to add the ability for the final image to dynamically expand in height based on the number of favicons gathered.*)
(*+13 bytes (`557 -> 570`) since URL shorteners are apparently [not allowed](https://codegolf.stackexchange.com/questions/86753/make-a-sprite-sheet-from-all-the-stack-exchange-sites-favicons/86853?noredirect=1#comment212896_86753).*)
```
from urllib.request import*;from PIL import Image as I;from io import*;import re
H='http://';U=urlopen;u=y=0;V=sorted(re.findall('<h2><a href="%s((?!meta).+?.stackexchange.com)">'%H,U(H+'stackexchange.com/sites?view=list').read().decode()[7167:]))+['%s.com'%i for i in'stackexchange stackoverflow superuser serverfault askubuntu mathoverflow stackapps stackauth'.split()];i=I.new("RGBA",(320,-~(len(V)*2//10)*32))
for l in V+['meta.'+i for i in V]:
try:
i.paste(I.open(BytesIO(U(H+l+'/favicon.ico').read())),(u,y));u+=32
if u>319:u=0;y+=32
except:0
i.save('O.png')
```
Quite long, but hey, I beat Javascript! :D This imports the modules for the following uses:
* `urllib` to fetch website and image data.
* `io` module for the `BytesIO` function to decode the fetched image data for `PIL`.
* `re` for the use of regular expressions to parse the website data.
* `PIL` to create the final image from the fetched image data.
Creates and saves a `320 x 1024` PNG image named `O.png` in the current working directory, with all the favicons in the order specified. I will try to golf this down more over time as much as I can, but for now, I could not be happier. :)
**Final Output Image:**
[](https://i.stack.imgur.com/gpBjv.png)
[Answer]
# JavaScript, 563 bytes
```
a=[]
fetch`//api.stackexchange.com/sites?pagesize=999`.then(r=>r.json().then(j=>{p=j.items.forEach(i=>a.push(i.site_url+"/favicon.ico"))
s=a.sort()
g=s.filter(e=>/(?<!meta)\.stackexchange/.exec(e)).concat(["//stackexchange.com/favicon.ico"]).concat(s.filter(e=>!/meta|stackexchange/.exec(e))).concat(s.filter(e=>/meta/.exec(e)))
document.body.append(c=document.createElement`canvas`)
c.width=320
c.height=(g.length/10+0.9|0)*32
c=c.getContext`2d`
for(u in g){
var i=new Image()
i.src=g[u]
i.u=u
i.onload=(p)=>c.drawImage(b=p.target,b.u*32%320,((b.u/10)|0)*32)}}))
```
### Generated image (as of writing this)
```
<img src="https://i.stack.imgur.com/jy3Ct.png"/>
```
## Explanation (key points)
---
`fetch`//api.stackexchange.com/sites?pagesize=999``
▸ Fetch the list of all SE sites [[API docs](https://api.stackexchange.com/docs/sites)]
▸ **-2 bytes**: Uses ES6's [tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)
▸ **-3~4 bytes**: It also uses a trick `//` that takes advantage of Stack Snippets (otherwise, you'd have to replace `//` with `http:` or even `https:` because of CORS weirdness)
▸ **Note:** It only list the first 999 sites. While as of writing this, theres "only" 355 sites, this could reach 1000. then you'll need to add one byte: `...``?pagesize="+2e9`, which can go up to 2000000000! (more than that makes an `invalid parameters` error)
---
`s=a.sort()`
▸ Sort the list of URLs in alphabetical order (meta and normal aren't separated yet)
---
] |
[Question]
[
**This question already has answers here**:
[Sᴍᴀʟʟ Cᴀᴘꜱ Cᴏɴᴠᴇʀᴛᴇʀ](/questions/60443/s%e1%b4%8d%e1%b4%80%ca%9f%ca%9f-c%e1%b4%80%e1%b4%98%ea%9c%b1-c%e1%b4%8f%c9%b4%e1%b4%a0%e1%b4%87%ca%80%e1%b4%9b%e1%b4%87%ca%80)
(22 answers)
Closed 7 years ago.
Turn the characters `abcdefghijklmnopqrstuvwxyz!?.,` upside down and don't modify the other characters. Then, reverse the text to achieve the upside down affect. If text is already upside down, turn it right side up. Don't modify capitals.
Use this as a reference:
```
abcdefghijklmnopqrstuvwxyz!?.,
ɐqɔpǝɟƃɥıɾʞןɯuodbɹsʇnʌʍxʎz¡¿˙'
```
## Rules
* Newlines must be supported
* You only have to convert the above character set.
* **Don't forget you need to reverse the characters.**
* This question is symmetrical unlike Small Caps Converter.
## Test cases
```
42 is the meaning of life -> ǝɟıן ɟo ƃuıuɐǝɯ ǝɥʇ sı 24
halp why is my keyboard typing upside down??? :( -> (: ¿¿¿uʍop ǝpısdn ƃuıdʎʇ pɹɐoqʎǝʞ ʎɯ sı ʎɥʍ dןɐɥ
lol -> ןoן
uoɥʇʎpʎzɐɹc -> ɔrazydython
```
Look at my username!
[Answer]
# Ruby, 78 bytes
I need to use an actual byte counter more often
```
->s{s.reverse.tr'a-z!?.,',"ɐqɔpǝɟƃɥıɾʞןɯuodbɹsʇnʌʍxʎz¡¿˙'"}
```
[Try it online](https://repl.it/C1Yf)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 73 bytes (54 chars)
Translate the chars, then reverse the input. I was pretty confused while making this until I realized some of the chars need to be escaped.
```
T`ɐqɔ\pǝɟƃɥıɾʞןɯu\o\dbɹsʇnʌʍxʎz¡¿˙'l!?.,`l!?.,o
O$^s`.
```
[**Try it online!**](http://retina.tryitonline.net/#code=VGDJkHHJlFxwx53Jn8aDyaXEscm-yp7Xn8mvdVxvXGRiyblzyoduyozKjXjKjnrCocK_y5knbCE_LixgbCE_LixvCk8kXnNgLg&input=NDIgaXMgdGhlIG1lYW5pbmcgb2YgbGlmZQo8LT4Kx53Jn8Sx158gyZ9vIMaDdcSxdcmQx53JryDHncmlyocgc8SxIDI0)
[Answer]
# Pyth, 59 bytes
```
X_z+G"!?.,'˙¿¡zʎxʍʌnʇsɹbdouɯןʞɾıɥƃɟǝpɔqɐ
```
[Test suite.](http://pyth.herokuapp.com/?code=X_z%2BG%22%21%3F.%2C%27%CB%99%C2%BF%C2%A1z%CA%8Ex%CA%8D%CA%8Cn%CA%87s%C9%B9bdou%C9%AF%D7%9F%CA%9E%C9%BE%C4%B1%C9%A5%C6%83%C9%9F%C7%9Dp%C9%94q%C9%90&test_suite=1&test_suite_input=42+is+the+meaning+of+life%0Ahalp+why+is+my+keyboard+typing+upside+down%3F%3F%3F+%3A%28%0Alol%0Auo%C9%A5%CA%87%CA%8Ep%CA%8Ez%C9%90%C9%B9c&debug=0)
Obligatory hexdump:
```
58 5F 7A 2B 47 22 21 3F 2E 2C 27 CB 99 C2 BF C2
A1 7A CA 8E 78 CA 8D CA 8C 6E CA 87 73 C9 B9 62
64 6F 75 C9 AF D7 9F CA 9E C9 BE C4 B1 C9 A5 C6
83 C9 9F C7 9D 70 C9 94 71 C9 90
```
[Answer]
## Python 3, 144 bytes
Don't work in the Windows terminal...
```
print(''.join([dict(zip("abcdefghijklmnopqrstuvwxyz!?.,","ɐqɔpǝɟƃɥıɾʞןɯuodbɹsʇnʌʍxʎz¡¿˙'")).get(x,x)for x in input()[::-1]]))
```
[Answer]
## JavaScript (ES6), 140 bytes
```
f=
s=>[...s].map(c=>r=((i=u.indexOf(c)+26)<26?c:u[i%52])+r,r="",u="abcdefghijklmnpqrtuvwy!?.,ɐqɔpǝɟƃɥıɾʞןɯudbɹʇnʌʍʎ¡¿˙'")&&r
;
```
```
<input oninput=o.value=f(this.value)><input id=o style=text-align:right>
```
Edit: Saved 8 bytes thanks to @Dúthomhas.
[Answer]
## Perl, 88 bytes
**78 bytes code + 10 for `-Mutf8 -n`**
```
y/a-z!?.,/ɐqɔpǝɟƃɥıɾʞןɯuodbɹsʇnʌʍxʎz¡¿˙'/;print reverse/./g
```
### Usage
Save as upsidedown.pl and run:
```
perl -Mutf8 -n upsidedown.pl <<< '42 is the meaning of life'
ǝɟıן ɟo ƃuıuɐǝɯ ǝɥʇ sı 24
```
] |
[Question]
[
If elected president, Donald Trump plans to implement a system of four income tax brackets (full details can be found on his website [here](https://www.donaldjtrump.com/positions/tax-reform)). Your job is to take two inputs, annual income and filing status (single, married, or head of household), and output the income tax that must be paid.
# Income Tax Brackets
[](https://i.stack.imgur.com/KzhEL.png)
(We are only interested in the income tax rate; you can ignore the long-term capital gain rate).
Note that income taxes are computed using *marginal rates* — that is, you only pay the bracket rate for the portion that exceeds the bracket's minimum amount.
For example, a single filer making $45,000 a year would pay 0% on the first $25,000, and 10% on the $20,000 after that, for a total of $2,000 in taxes.
A married couple filing jointly for $500,000 would count 25% only on the amount exceeding $300,000, and add $45,000 to that to account for the income earned in lower brackets (which is 10% of $50,000 plus 20% of $200,000).
# Input/Output
Input/Output is flexible. You can take input as command-line arguments or prompt for inputs, as well as either return or output/display the result. The inputs and output must be numbers, but you are free to determine what the second number would be (for example, 0 = single, 1 = married, 2 = head of household). Just don't be ridiculous - **Single digit numbers only**.
Also, functionality for decimal inputs (i.e. including cents) is undefined, so you only have to worry about integer inputs. For your output, you may either output a decimal value or round it to the nearest whole number.
# Test Cases
Although the second number's range can be flexible as stated above, these test cases assume that 0 = single, 1 = married, and 2 = head of household:
```
25000 0 --> 0
37501 2 --> 0.1 or 0
51346 1 --> 134.6 or 135
75000 0 --> 7500
75000 1 --> 2500
123456 2 --> 13441.2 or 13441
424242 0 --> 91060.5 or 91061
```
[Answer]
# Pyth, 32 bytes
```
*c@_j270588 6shS,6ca0tQ*12500E20
```
[Test suite.](http://pyth.herokuapp.com/?code=*c%40_j270588+6shS%2C6ca0tQ*12500E20&test_suite=1&test_suite_input=25000%0A2%0A37501%0A3%0A51346%0A4%0A75000%0A2%0A75000%0A4%0A123456%0A3%0A424242%0A2&debug=0&input_size=2)
* 2 = single
* 4 = married
* 3 = head of household
## Some ridiculous encodings:
### Previous 6-byte:
```
JQ.vCE
```
[Test suite.](http://pyth.herokuapp.com/?code=JQ.vCE&test_suite=1&test_suite_input=0%0A74892585093965377905208487730659359537614936740881725652453863997600444976%0A%0A25000%0A74892585093965377905208487730659359537614936740881725652453863997600444976%0A%0A37501%0A74892585093965377905208487730659359537614936740881725652526490039149933104%0A%0A51346%0A74892585093965377905208487730659359537614936740881725652668629404830675504%0A%0A75000%0A74892585093965377905208487730659359537614936740881725652453863997600444976%0A%0A75000%0A74892585093965377905208487730659359537614936740881725652668629404830675504%0A%0A123456%0A74892585093965377905208487730659359537614936740881725652526490039149933104%0A%0A424242%0A74892585093965377905208487730659359537614936740881725652453863997600444976%0A&debug=0&input_size=3)
* 74892585093965377905208487730659359537614936740881725652453863997600444976 = single
* 74892585093965377905208487730659359537614936740881725652668629404830675504 = married
* 74892585093965377905208487730659359537614936740881725652526490039149933104 = head of household
Encodes the whole program into the second number.
### Previous 24-byte:
```
JjE^T6*c@tJhS,7shctQhJ20
```
[Test suite.](http://pyth.herokuapp.com/?code=JjE%5ET6*c%40tJhS%2C7shctQhJ20&test_suite=1&test_suite_input=0%0A25000000000000000000002000004000004000004000004000005%0A%0A25000%0A25000000000000000000002000004000004000004000004000005%0A%0A37501%0A37500000000000000000002000004000004000004000004000005%0A%0A51346%0A50000000000000000000002000004000004000004000004000005%0A%0A75000%0A25000000000000000000002000004000004000004000004000005%0A%0A75000%0A50000000000000000000002000004000004000004000004000005%0A%0A123456%0A37500000000000000000002000004000004000004000004000005%0A%0A424242%0A25000000000000000000002000004000004000004000004000005%0A&debug=0&input_size=3)
* 25000000000000000000002000004000004000004000004000005 = single
* 50000000000000000000002000004000004000004000004000005 = married
* 37500000000000000000002000004000004000004000004000005 = head of household
### Previous 26-byte:
```
*c@_j270588 6shS,6ca0tQE20
```
[Test suite.](http://pyth.herokuapp.com/?code=*c%40_j270588+6shS%2C6ca0tQE20&test_suite=1&test_suite_input=25000%0A25000%0A%0A37501%0A37500%0A%0A51346%0A50000%0A%0A75000%0A25000%0A%0A75000%0A50000%0A%0A123456%0A37500%0A%0A424242%0A25000%0A&debug=0&input_size=3)
* 25000 = single
* 50000 = married
* 37500 = head of household
[Answer]
# TI-Basic, 34 32 bytes
Variable `F` is filing status where 2 = single, 3 = head of household, and 4 = married. Also, E is the scientific E.
```
Prompt I,F:4I/F>E5{.5,1,3:.1Isum(Ans{1,1,.5
```
Explanation:
```
Prompt I,F get input into I and F
4I/F converts the income so it fits the married tax bracket
>E5{.5,1,3 gives a list like {0 0 0}, {1 0 0}, {1 1 0}, or {1 1 1} based on bracket
sum(Ans{1,1,.5 Multiplies previous list by {1 1 .5} and sums it
.1I Previous number is 0 1 2 or 2.5, so multiply by .1 and then by income
```
[Answer]
## JavaScript (ES6), 52 bytes
```
(i,m,g=b=>i>b&&(i-=b)/10)=>g(m=15e4/m)+g(m)+g(m*4)/2
```
Key:
```
6 = Single
3 = Married
4 = Head
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ï¥Ωü+àqGZvwJ╫BMwbë↕)bÿ╠»
```
[Run and debug it](https://staxlang.xyz/#p=8b9dea812b8571475a76774ad7424d77628912296298ccaf&i=2,+25000%0A3,+37501%0A4,+51346%0A2,+75000%0A4,+75000%0A3,+123456%0A2,+424242%0A&a=1&m=2)
\begin{align}\text{Single}&\mapsto 2\\
\text{Married}&\mapsto4\\
\text{Head of Household}&\mapsto3
\end{align}
Outputs a fraction.
] |
[Question]
[
I decided to learn J so that I could better take part in code golfing. Starting it off relatively simple, I tried writing a solution to this problem:
>
> Find the sum of all the multiples of 3 or 5 below 1000.
>
>
>
After a bit of tinkering, I came up with the following J code that solves it:
```
x=:i.1000
+/x#(0=3|x)+.0=5|x
```
Basically, what I'm doing is taking two lists of numbers from 1 to 1000, and finding one modulo 3, and the other modulo 5. Then I OR them together to get a list of indicies where a number is divisible by either 3 or 5. I then use that to sum the numbers.
What I ask is, how do I shorten this? I'm new to J and so do not have enough experience to shorten it any further.
Also, if anyone has a solution shorter than this in another language, I'd be interested to see that as well!
[Answer]
Employing a few [forks](http://www.jsoftware.com/help/primer/fork.htm), a [hook](http://www.jsoftware.com/help/primer/hook.htm) and the fact that J works well on lists:
```
+/(#~[:+./0=3 5|/])i.1000
```
This answer uses your algorithm, but just uses some J tricks to make it a bit shorter. I'm fairly sure that this can be made shorter still, and I wouldn't be surprised if there's a slightly different way of doing it that results in an even shorter solution.
Here's a list of some things I've done here.
First, I've combined the `3|x` and the `5|x` into one operation `3 5|/x`. This uses the table adverb `/` to do both operations at once:
```
3 5|/i.20
0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
```
Next, I've combined the `|/`, the `0=`, the `+.`, and the `#` into a train of verbs using forks and a hook. The verb train breaks down into groups of three:
```
3 5|/]
```
this is the same as the above, except I'm using `]` to grab the list to the right of the brackets.
```
0=x
```
`x` is the result of the previous fork which is fed into the next.
```
[:+./x
```
as before the result so far gets fed into this fork. `[:` tells the verb `+./` that it should use its monadic (one argument) form. The `/` inserts the +. between the top and bottom rows of the result so far.
```
#~x
```
This is the hook. The result so far is fed in as the right argument, but the left argument is the value outside the brackets (`i.1000`) again. So this is equivalent to `(i.1000)#~x`. The `~` just reverses the order of the arguments.
Then at the end I just use the `+/` as you did.
[Answer]
Using a slightly different method than my other answer:
```
+/+/((]*[>])3 5*/i.)1000
```
Here, I'm multiplying 3 and 5 by all the numbers up to 1000, throwing away anything that's not less than 1000 and then summing them. It's a shame about the ugly `+/+/` at the end.
Here we have a fork:
```
3 5*/i.
```
followed by a hook:
```
(]*[>])x
```
**EDIT:**
As [randomra](https://codegolf.stackexchange.com/users/7311/randomra) points out, I forgot about duplicates. This should fix that:
```
+/~.,((]*>)3 5*/i.)1000
```
I've also realised that `[>]` is the same as `>` (not the first time I've had that redundancy in my answer)
[Answer]
a couple of swerves on the above to shave some bytes off
correct result `233168`
* 25 bytes `+/x#(0=3|x)+.0=5|x=:i.1e3`
* 24 bytes `+/(#~[:+./0=3 5|/])i.1e3`
* 22 bytes `+/~.;((]*>)3 5*/i.)1e3`
# [J](http://jsoftware.com/), testing HCF 21 bytes
```
+/(*1&<@(15&+.))i.1e3
```
[TIO](https://tio.run/##bcuxCsIwFIXhPU9xsEvS4E2bWJFKHBScxMFVOgatFJFaIUPpq8cU2kHwwNn@7xHOewKk8gnPrOm9kJTZove2rCl3Bmjc89bdoQugde9P00Ebk683bII8Ga6lJBU1il5VYnLz9GouB9pyXqU7EcNU1SR@ulhqxpx/tbAlMoxfEg6X0zH8t0GEBWEUXw "J")
] |
Subsets and Splits