title: Difference should make no difference

text:
# Question
Title: Difference should make no difference
Your company lately hired a new bunch of *extremely dedicated* sysadmins. They feel that just watching computer screens is quite limiting (I mean, 60Hz refresh rate is just NOT enough), so they hooked up the CPU data bus to an DAC and play that on a speaker through the server room so that they can hear up to 20kHz. One problem: they're sysadmins, not electrical engineers, and their speaker setup keeps breaking. They figured that this is caused by too abrupt changes in byte values in the code that the software engineers compile on the mainframe. The sysadmins are now hosting a little competition to see who can make code that is the most gentle to their speaker setup.

# Challenge

Your mission is to create a **program** or **function** in a language of choice that has as little difference as possible between consecutive bytes (see the Calculation section). This program will have the task of calculating its own score.

# Input

An ASCII string on `stdin` or your language's closest equivalent, or as a function input if you're creating a function. Since your program will have to take itself as input to calculate your score, your program should support Unicode if it contains any Unicode. Otherwise, ASCII is sufficient. Input can be assumed to be at least 2 bytes long.

# Calculation

Each character of the string will be converted to it's numerical equivalent, using the ASCII standard. Then, the difference between all characters will first be **squared** and then **summed**. For example, the string `abd` will get a score of `1²+2²=5`.

# Output

Output will be the title to your entry. This means that it should be prepended by a `#` or appended by a newline and a `-` (dash). Then, it should output the name of your programming language, followed by a comma, a space and then an integer representing the result of the calculation. For example

```
#C++, 98

```

would be valid output. Output should be given on `stdout` or your language closest equivalent, or as a return value to your function.

# Scoring

Your score will be the calculated value by your program, with the program itself as input.

**Edit: Should handle newlines now, sorry for before, folks**

Here is a Pyth script to verify the score calculation.

# Answer
> 19 votes
# CJam, ~~1051~~ ~~827~~ ~~643~~ ~~569~~ ~~545~~ ~~407~~ ~~327~~ ~~279~~ ~~235~~ ~~233~~ 229

```
''"','#'C'J'a'm',' qYew::-Yf#:+e#'''''''''"
f{-ci'(*''2*\}'^,40>"*/:N"-"][ZZ[\^__`bcdgimpstsz{}~~~"

```

The above program generates the actual source code, which is 1,179,112 bytes long.

### Testing

Using the Java interpreter, the source code can be generated and tested like this:

```
$ alias cjam='java -jar cjam-0.6.5.jar'
$ cjam gen.cjam > diff.cjam
$ cksum diff.cjam
896860245 1179112 diff.cjam
$ cjam diff.cjam < diff.cjam
#CJam, 229

```

### Alternate version

At the cost of 36 points – for a final score of **265** – we can make the source code 99.92% shorter:

```
'''()))))(''''(((('''())))))))))))))))))))))))))))('''()))))))))))))))))))))))))))))))))))('''())))))))))))))))))))))))))))))))))))))))))))))))))))))))))('''())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('''()))))(''''((((((('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('())))))))))))))))))))))))))))))))))))))))))))))))))('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))('()))))))))))))))))))('()))))))))))))))))))('())))))('())))))))))))))))))))))))))))))))))))))))))))))))))('()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(''(((('()))))))))))))))))))('())))('())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(''((((''''''''''''''''''()+,-.0123456789;<=>?@ABCDEFGHIJKLMOPQRSTUVWXYZ[\]][ZZ[\^__`bcdgimpstsz{}~~~

```

You can try this version online in the CJam interpreter.

### Idea

We want to execute the code

```
'#'C'J'a'm',' qYew::-Yf#:+

```

keeping the score as low as possible. To achieve this, we're going to build that string character by character (with a few no-ops before and after) and evaluate the result.

Fortunately, `'` (push character literal), `(` (decrement) and `)` (increment) are consecutive ASCII characters, so pushing arbitrary characters is relatively inexpensive.

* ASCII characters after `'` can be pushed as `'()…)(`, where the number of `)` depends on the code point.

For example, `+` can be pushed as `'())))(`. The distance between `'` and `(`, and `(` and `)` is 1. The trailing `)(` cancel each other; their only function is to pave the way for the following `'` (corresponding to the next character) with consecutive characters.

Characters pushed in this fashion will raise the score by 4 points.
* ASCII characters before `'` can be pushed as `''(…(`, where the number of `(` depends on the code point.

For example, `#` can be pushed as `''((((`. The distance between `'` and `(` is 1.

Characters pushed in this fashion will raise the score by 2 points.
* `''(…(` actually works for *all* ASCII characters, since *Character* is 16 bits wide and wraps around. For example, `+` can be pushed as `''`, followed by 65,532 `(`s.

This technique is used in the 1.2 megabyte version of the code.
* The character `'` can be pushed as `''`, leaving the score unaffected.

### Code

```
e# Push these characters on the stack: ','#'C'J'a'm',' qYew::-Yf#:+e#'''''''''

''
'()))))(
''
''((((
''
'())))))))))))))))))))))))))))(
''
'()))))))))))))))))))))))))))))))))))(
''
'())))))))))))))))))))))))))))))))))))))))))))))))))))))))))(
''
'())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(
''
'()))))(
''
''(((((((
'())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(
'())))))))))))))))))))))))))))))))))))))))))))))))))(
'())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(
'())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(
'()))))))))))))))))))(
'()))))))))))))))))))(
'())))))(
'())))))))))))))))))))))))))))))))))))))))))))))))))(
'()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(
''((((
'()))))))))))))))))))(
'())))(
'())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))(
''((((
''
''
''
''
''
''
''
''
''()

+                         e# Concatenate the two topmost single quotes.
,                         e# Push the length of the resulting string (2).
-.0123456789              e# Push that number.
;                         e# Discard it from the stack.
<                         e# Compare a single quote with 2. Pushes 0.
=                         e# Compare a single quote with 0. Pushes 0.
>                         e# Compare a single quote with 0. Pushes 1.
?                         e# Ternary if. Discards a single quote and 1.
@                         e# Rotate the remaining three single quotes.
ABCDEFGHIJKLMOPQRSTUVWXYZ e# Push 25 items on the stack.
[\]                       e# Swap the last two and wrap them in an array.

e# So far, we've pushed the elements of "','#'C'J'a'm',' qYew::-Yf#:+e#'''"
e# followed by the elements of [10 11 12 13 14 15 16 17 18 19 20]
e# and ["" "" "" 3.141592653589793 "" "" " " 0 0 0 -1 1 [3 2]].

]    e# Wrap the entire stack in an array.
[    e# Begin an array. Does nothing.
ZZ   e# Push 3 twice.
[    e# Begin an array. Does nothing.
\^   e# Swap both 3s and push the bitwise XOR. Pushes 0.
__   e# Push two copies.
`    e# Inspect the last copy. Pushes the string "0".
b    e# Convert "0" from base 0 to integer. Pushes 48.
cd   e# Cast 48 to Character, then Double. Pushes 48.0.
gi   e# Apply the sign function, then cast to integer. Pushes 1.
mp   e# Check 1 for primality. Pushes 0.
s    e# Cast the result to string. Pushes the string "0".

e# We now have three elements on the stack: an array, 0, and "0"

t    e# Set the element at index 0 of the array to the string "0".
s    e# Cast the array to string.

e# This pushes the string consisting of the characters
e#     0,'#'C'J'a'm',' qYew::-Yf#:+
e# and
e#     e#'''10111213141516171819203.141592653589793 000-1132
e#
e# When evaluated this does the following:
e#   0,                Push an empty array. Does not affect output.
e#   '#'C'J'a'm','     Push the characters of "#CJam, ".
e#   q                 Read all input from STDIN.
e#   Yew               Push the overlapping slices of length 2.
e#   ::-               Reduce each pair of characters to their difference.
e#   Yf#               Square each difference.
e#   :+                Add the results.
e#   e#…               Comment. Does nothing.

z    e# Zip. This wraps the string on the stack in an array.
{}~  e# Execute an empty block.
~    e# Unwrap the array.
~    e# Evaluate the string.

```

# Answer
> 7 votes
# Haskell, ~~152827~~ ~~95742~~ ~~91196~~ ~~83921~~ ~~77447~~ 71742

```
a=(.);_ZYXWVUTSRQPONMLKJIHGFEDCBA=("#Haskell, "++)`a`show`a`sum`a`fmap(^2)`a`(tail>>=zipWith(-))`a`fmap fromEnum`a`(""++)

```

Usage (note: `"` has to be escaped):

```
_ZYXWVUTSRQPONMLKJIHGFEDCBA   "a=(.);_ZYXWVUTSRQPONMLKJIHGFEDCBA=(\"#Haskell, \"++)`a`show`a`sum`a`fmap(^2)`a`(tail>>=zipWith(-))`a`fmap fromEnum`a`(\"\"++)"

"#Haskell, 71742"

```

I prepend the empty string `""` to the input string to help the Haskell interpreter figuring out the types. Without it type inference fails, the code is too polymorphic. The rest is business as usual: map each character to ascii, make a list of neighbor differences, square, sum and prepend language name.

# Answer
> 6 votes
## \>\<\>, 30227

```
0&ii:0(?v:@-:*&+&20.
'#><>, '<;n&oooooo

```

Gah, the title doubled my score; in the words of my own program, n&oooooo! I'll take some time later to make this better. I also know that this score may be off since I can't really enter newlines on the online interpreter and I'm not sure there's a way to populate an input stack on the official one.

By no means completely optimized, but takes ~~full~~ some advantage of the relative proximity (at least in terms of ASCII characters) of the commands in \>\<\>. I couldn't easily submit the newline as input, so I used the Pyth score checker, but it matches for a bunch of random test cases I used so it should be fine with regards to that.

Here's one with a score of 30353 (which ought to be correct since it's one line):

```
0&l1=66+*77++0.$:@-:*&+&10.' ,><>#'oooooo&n;

```

# Answer
> 5 votes
# Java, ~~66465~~ ~~65506~~ 62434

Surprisingly short. Accepts a char array instead of a string.

```
ABCD->{int A98=0,GFEDCBA=1,A987;for(;GFEDCBA<ABCD.length;A98=A98+(A987=ABCD[GFEDCBA]-ABCD[GFEDCBA++-1])*A987-0);return"#Java, "+A98;}

```

I used a program to generate the best variable names.

# Answer
> 4 votes
# Windows PowerShell ISE Host, 62978 ~~63894~~ ~~67960~~ ~~77050~~

```
PARAM($4)($4.LENGTH-2)..0|foreach{$9=+$4[$_]-$4[$_+1];$0+=$9*$9};'#'+$HOST.NAME+', '+$0

```

Edit -- saved some points by getting rid of the `$A` variable and instead counting backwards through the string, and also by converting some keywords to CAPS

Edit2 -- saved some more points by using `$($HOST.NAME)` instead of `PowerShell`

Edit3 -- saved some more points by swapping variable names and changed how the output is generated.

Uses variables named with numbers, as they're "closer" to `$` so our penalty is less.

It's interesting to *not* use regular golfing techniques. For example, `|%{$` is 22534, while `|foreach{$` is only 8718.

This is probably close to optimal without changing techniques.

# Answer
> 4 votes
# K5, 25478

```
"#K5, ",$+/1_{x*x}'-':

```

Pretty simple solution. This is a function that takes its input via a string.

# Answer
> 4 votes
# MATLAB, ~~19214~~ ~~39748~~ ~~39444~~ ~~38785~~ 37593

```
@(A9876543210)sprintf('#MATLAB, %d',diff(A9876543210)*diff(A9876543210'))

```

## Thanks to Luis Mendo for reducing the difference count further!

## Thanks to NumberOne for reducing the noise count by changing the input variable name!

## How this works

1. Declares an anonymous function that is stored in the default `ans` variable in MATLAB
2. The function takes in a string stored in `A9876543210` and prints out the sum of squared neighbouring differences of the string.
3. `diff` finds pairwise neighbouring differences in an array and produces an array of `length(A9876543210)-1`. By using `diff` on a string array, this gets cast to a `double` array where the ASCII codes of each character are generated and the differences of the consecutive pairs results in another array.
4. To find the sum of squared differences, you simply take the dot product of this difference array with itself transposed. Doing `diff(A9876543210)'` actually produced more noise than with `A9876543210.'` (thanks Luis Mendo!)
5. The result is printed to the screen.

# Answer
> 4 votes
# QBasic, 38140

YAY FOR SHOUTY SYNTAX

```
LINE INPUT A9876543210$:AAA=ASC(A9876543210$):WHILE A<LEN(A9876543210$):AA9876543210=AAA:A=1+A:AAA=ASC(MID$(A9876543210$,A)):A98765432100=A98765432100+(AA9876543210-AAA)*(AA9876543210-AAA):WEND:?"QBasic,";A98765432100

```

(Tested with QB64.)

This is a full program that inputs the string and outputs the answer. The only limitation here is that the program can't take multiline input (`LINE INPUT` can handle anything as long as it's a single line).

**Deobfuscated:**

```
LINE INPUT line$
b=ASC(line$)
WHILE i<LEN(line$)
    a=b
    i=i+1
    b=ASC(MID$(line$,i))
    score=score+(a-b)*(a-b)
WEND
PRINT "#QBasic,"; score

```

Conveniently, passing a multi-character string to `ASC` gives the ASCII value of the first character. Also conveniently, numeric variables are auto-initialized to zero.

# Answer
> 3 votes
# JSFuck, 144420642

Build it from:

```
t=arguments[0];n=0;for(u=1;u<t.length;++u)n+=(f=t.charCodeAt(u)-t.charCodeAt(u-1))*f;return'#JSFuck, '+n

```

Paste this into JSFuck.com's small input box to compile it to JSFuck. The result is a 112701 characters long script, so I can't put it here. The last two characters of this script are parentheses, put the input between them.

```
...)[+!+[]])('abd')

```

It takes the program almost 20 seconds on my computer to evaluate itself.

---

### Explanation

I got more time to work on this, so I sat down and tried to optimize the variable names. Here are the variable names worth using, in order of their score.

```
u     ([][[]]+[])[+[]]                    17237
n     ([][[]]+[])[+!+[]]                  17437
f     (![]+[])[+[]]                       18041
t     (!![]+[])[+[]]                      18041
a     (![]+[])[+!+[]]                     18241
r     (!![]+[])[+!+[]]                    18241
d     ([][[]]+[])[!+[]+!+[]]              23405
N     (+[![]]+[])[+[]]                    23669
e     (!![]+[])[!+[]+!+[]+!+[]]           29217
i     ([![]]+[][[]])[+!+[]+[+[]]]         33581
l     (![]+[])[!+[]+!+[]]                 24209
s     (![]+[])[!+[]+!+[]+!+[]]            29217
uu    ([][[]]+[])[+[]]+([][[]]+[])[+[]]   36983

```

Here is the JavaScript I've translated to JSFuck:

```
score = 0;
for (u = 1; u < input.length; ++u)
  score += (difference = input.charCodeAt(u) - input.charCodeAt(u-1)) * difference;
return '#JSFuck, ' + score;

```

I gave a closer look at JSFuck.com's translator and figured out how its evaluation function works. With "Eval source" checked, the code will become a self-executing JSFuck function. To get the input, however, we need to access arguments\[0\] from within the function. This brings our final JS code to...

```
t=arguments[0];n=0;for(u=1;u<t.length;++u)n+=(f=t.charCodeAt(u)-t.charCodeAt(u-1))*f;return'#JSFuck, '+n

```

(If you're wondering why my previous version had a lower score than this, it's because it was a JSFuck program that returned a string that needed to be evaluated as JS. This is also why I didn't leave it in the post)

# Answer
> 3 votes
# JAVASCRIPT, 33911

```
$0123456789ABCDEFGHIJKLMNOPQRS=>/**/('#')+('JAVASCRIPT,')+(" ")+(($)/**/=0,($0123456789ABCDEFGHIJKLMNOPQRS[`split`]``[`map`]/**/(($$,$$$)/**/=>/**/($)/**/=Math[`pow`]/**/($0123456789ABCDEFGHIJKLMNOPQRS[T=`charCodeAt`]/**/($$$)+-($0123456789ABCDEFGHIJKLMNOPQRS[T]/**/(($$$)/**/>=6-5?/**/($$$)+-1:0.)),2)+($))),($))

```

This is by far one of the silliest optimizations I have ever done in a code golf...

Props to Neil for the "comment spam" suggestion =P

# Answer
> 3 votes
# Python 2, 91026

```
lambda A:"#Python 2, "+`sum((ord(A9876543210)-ord(A98765432100))**2for A9876543210,A98765432100 in zip(A,A[1:]))`

```

Defines an anonymous function that takes a string and returns the score. Try it online.

Most of this is a pretty straightforward functional implementation: zip `A` with `A[1:]` to get a list of letter pairs, then subtract their `ord`s, square, and sum with a generator expression.

Observe that the two variables inside the generator expression are only ever followed by the following characters: `)`, `,`, and space. All three of these have very low ASCII values, so it behooves us to end each variable with as low-ASCII-valued a character as possible. The lowest character that can end a variable in Python is `0`. Furthermore, every opportunity we have to split a single large jump into two smaller jumps will lower the score: `A0` costs 289, but `A90` is only 145 and `A9876543210` is a paltry 73.

(This approach *didn't* help the lambda variable `A`, probably because it's followed by `[` in one occurrence.)

# Answer
> 3 votes
# CJam, ~~23663~~ ~~19389~~ 11547

```
"#CJam,"32A;clYew[]ULC;;;;::- 0$.*:+

```

Try it online

It's starting to feel like this can be pushed almost endlessly by strategically adding more characters. But I think that I'm starting to reach a point of diminishing returns here, so I'll stop for now. For example, where I have `ULC;;;`, I could use the whole alphabet backwards followed by 26 `;`, but the gains get smaller and smaller.

By far the biggest gap I have left is between the `m` and the `,` in the initial string. I haven't found anything reasonable to get rid of it. I'm sure there are ways. But if I push it to the limit, it might start looking like Dennis' solution...

# Answer
> 3 votes
# JAVASCRIPT, 31520

This solution was ~~significantly more ridiculous~~ very different from my other one, and so I felt it deserved it's own answer.

```
A=>/**/(($)/**/=/**/(''),('[encoded data, 6815 characters],+*)(')/**/[`split`]``[`reduce`]/**/(($$,$$$,$$$$)/**/=>/**/($$$)/**/>7.-07?/**/(($)+=/**/((/**/String[`fromCharCode`]/**/)(($$$$)+-($$))),($$$$))/**/:/**/($$)),/**/eval/**/($))

```

That's 7306 characters, most of which is the actual program encoded into that 0/1 string, and the rest simply to decode it. It works by getting the index of each '1' minus the index of the previous '1' to get the necessary character value. It then eval's the resulting string into the actual function, which is essentially a standard-golf program to solve the problem (which is only about 105 characters itself).

# Answer
> 2 votes
# R, ~~68911~~ ~~57183~~ ~~53816~~ 52224

Takes a string from STDIN and converts it to an integer via raw. Diffs, squares and sums the resulting vector. The result is returned as a string. Thanks to @nimi for the variable name tip.

```
'&&'=sum;'&&&'=diff;'&&&&'=as.integer;'&&&&&'=charToRaw;'&&&&&&'=readline;'&&&&&&&'=paste;'&&&&&&&'('#R,','&&'((A='&&&'('&&&&'('&&&&&'('&&&&&&'()))))*A))

```

# Answer
> 2 votes
# Java, ~~129300~~ ~~128400~~ ~~110930~~ ~~106581~~ 105101

```
B->{int A=0,C=A;char[]Z=B.toCharArray();for(;++C<Z.length;A=A+(Z[C]-Z[C-1])*(Z[C]-Z[C-1]));return\"#Java, \"+A;}

```

This challenge actually got me thinking deeper about characters to use and optimization more so than finding the shortest solution. I'll keep working to bring the number down.

This is a lambda function, with `B` being the string representing the function. Don't forget to escape the quotes (`"`) when passing this as a string.

# Answer
> 2 votes
# M, 47033 ~~52798~~

```
A9876543210(A9876543210) F AA9876543210=2:1:$L(A9876543210) S AAA9876543210=$A($E(A9876543210,AA9876543210-1))-$A($E(A9876543210,AA9876543210))**2+AAA9876543210
    Q "#M, "_AAA9876543210

```

To use this, we have to escape quotes and "escape" whitespace characters (which are significant in MUMPS!) like so:

```
>$$A9876543210^MYROUTINE("A9876543210(A9876543210)"_$C(9)_"F AA9876543210=2:1:$L(A9876543210) S AAA9876543210=$A($E(A9876543210,AA9876543210-1))-$A($E(A9876543210,AA9876543210))**2+AAA9876543210"_$C(10,9)_"Q ""#M, ""_AAA9876543210")
#M, 47033

```

Note that "M" is an alternative name for "MUMPS" - there is disagreement among practitioners about which one is correct. Naturally, I have chosen the shorter option here.

# Answer
> 2 votes
# Mathematica, 33552

```
A=ToExpression;A@ExportString[A@Characters@(**)"001000100010001101001101011000010111010001101000011001010110110101100001011101000110100101100011011000010010110000100000001000100011110000111110010101000110111101010011011101000111001001101001011011100110011101011011001000110010111000100011001001100100000001000100011010010110011001100110011001010111001001100101011011100110001101100101011100110100000001010100011011110100001101101000011000010111001001100001011000110111010001100101011100100100001101101111011001000110010101000000001000110101110100100110"(**),(**)"Bit"(**)]

```

This code evaluates to an unnamed function, which calculates the "noise" of an input string. It makes use of the fact that the ASCII representation of binary data is essentially "noiseless". The binary data you see is the string

```
"#Mathematica, "<>ToString[#.#&@Differences@ToCharacterCode@#]&

```

which would have been a valid answer on its own, scoring 37848.

Everything else

```
A=ToExpression;A@ExportString[A@Characters@(**)"001..110"(**),(**)"Bit"(**)]

```

just decodes the binary string and interprets it as Mathematica code. Note that Mathematica's empty comment `(**)` is very "low-noise" and actually removes noise from the `"`s.

# Answer
> 2 votes
# Java8 : ~~117170~~ ~~100508~~ ~~99062~~ 98890

With the help of lambada expression and inline assignment of variable can shorten this code a bit.

```
A->{int B=0,D=0,E=0;char[] C=A.toCharArray();for(;D<C.length-1;)B+=(E=C[D]-C[++D])*E;return"#java, "+B;}

```

# Answer
> 2 votes
# Pyth, 16391

```
++C38828542027820dsm^-ChdCed2,Vztz

```

The only trick of note used here is base-256 encoding `#Pyth,`, which costs far less than the string itself.

```
++C38828542027820dsm^-ChdCed2,Vztz    Implicit: d=' ', z=input()
                             ,Vztz    Pair each char in the input with its neighbour
                   m                  Map d in the above to:
                      Chd               ASCII code of 1st char
                         Ced            ASCII code of 2nd char
                     -                  Difference between the two
                    ^       2           Squared
                  s                   Take the sum
  C38828542027820                     '#Pyth,'
++               d                    '#Pyth,' + ' ' + result, implicit print

```

# Answer
> 1 votes
# Ruby, 118402

```
puts "#Ruby, #{a=0;aa=nil;File.read(ARGV[0]).each_byte{|aaa| aa||=aaa;a+=(aaa-aa)**2;aa=aaa};a}"

```

It reads in a file through command line, such as `ruby diff.rb /path/to/file`. There's room to improve, and that's something I'm working on right now.

# Answer
> 1 votes
# POSIX Shell, 172026

```
{ while IFS= read -N 1 A; do A1=$(printf %d \'"$A");test "$A1" -eq 0 && break;case $A11 in "")A111=0;;*)A111=$((A1-A11));;esac;A11="$A1";A1111=$((A111**2+A1111));done;echo "# POSIX Shell, $A1111";}

```

too bad I can't get the same result as the Pyth checker (178386)...

# Answer
> 1 votes
# F#, ~~136718~~ 130303

```
let(A)=Seq.map;
(stdout.Write(Seq.sum(A(fun(AA)->AA*AA)(A((<||)(-))(((Seq.pairwise(A(int)(stdin.ReadToEnd())))))))))

```

Where there is a `\n` after the `;`.

# Answer
> 1 votes
# C++ 166345

```
void n(){int b=0,c,d;string a;cin >>a;for(c=1;c<a.length();++c){d=(a[c]-a[c-1]);b+=d*d;}cout<<"#C++, "<<b;}

```

# Answer
> 1 votes
# Lua, ~~171078~~ 117896

Golfed:

```
A=string AA=A.sub AAA=io.read()AAAA=#AAA AAA=AAA..AA(AAA,AAAA,AAAA)AAAAA=0 AAAAAA=A.byte for AAAAAAA=1,AAAA do AAAAAAAA=AAAAAA(AA(AAA,AAAAAAA,AAAAAAA))-AAAAAA(AA(AAA,AAAAAAA+1,AAAAAAA+1))AAAAA=AAAAA+AAAAAAAA*AAAAAAAA end print(AAAAA)

```

Ungolfed:

```
A=string
AA=A.sub
AAA=io.read()
AAAA=#AAA
AAA=AAA..AA(AAA,AAAA,AAAA)
AAAAA=0
AAAAAA=A.byte
for AAAAAAA=1,AAAA do
    AAAAAAAA=AAAAAA(AA(AAA,AAAAAAA,AAAAAAA))-AAAAAA(AA(AAA,AAAAAAA+1,AAAAAAA+1))
    AAAAA=AAAAA+AAAAAAAA*AAAAAAAA
end

print(AAAAA)

```

# Answer
> 1 votes
# Perl, 93556

```
chomp($A=<>);$AAA=$AAAA=0;foreach$AAAAA(split'',$A){$AA=ord($AAAAA);$AAA+=($AAAA-$AA)**2 if($AAAA!=0);$AAAA=$AA}print'#Perl, '.$AAA

```

I'll try to cut this down some more.

It turns out that curly braces (`{` and `}`, ASCII 123 and 125) and the underscore (`_`, ASCII 95) are very expensive since all the other characters are around the range 30-70, which is why I formatted the `if` the way I did, and why I'm using `$AAAAA` instead of Perl's beloved `$_`.

Sadly, all the variables with symbols in them are read-only, so I can't take advantage of combinations like `$#` and `$$`.

# Answer
> 0 votes
# C++, 49031

a C++ macro that takes a c-string and writes the result to the standard output

```
<::>(auto(A))<%long(AAA)=0,AA=A<:0:>;while(*++A)<%AAA+=(*A-AA)*(*A-AA);AA=A<:0:>;%>cout<<"#C++, "<<AAA;%>

```

Try it online!

---
Tags: string, code-challenge, self-referential
---


title: Trick or Treating

text:
# Question
Title: Trick or Treating
# Introduction

Little Jimmy is going trick or treating. He lives in an odd neighborhood: some houses give out candy, and some give out toothbrushes. Now, Jimmy does not want to get too many toothbrushes. He wants candy! You must help him get some.

# Challenge

Each street in Jimmy's neighborhood has a number. Each house on the street will give out either candy or toothbrushes. However, Jimmy's parents know he gets very hyper if he eats too much candy. To prevent this, they are only letting him go down one street in the neighborhood. Given a list of streets, you must output the street where Jimmy will get the most candy and the fewest toothbrushes. This means that, as said in the comments, even if one street gives out 500 candies and 1 toothbrush, it is worse than one that gives out 1 candy and no toothbrush.

* The list of streets will be 2D. It will never be empty. Each street will be a list of truthy or falsy values. It might be empty. Falsy values represent a house that gives out toothbrushes, truthy ones represent houses that give out candy.
* Your program must output the index of the street with the most truthy values and the fewest falsy ones, or the street that gives the most candy and the fewest toothbrushes. If all the streets have the same amount of candy and toothbrushes, you may output -1. It does not matter if the index is 0-based or 1-based. It can be stored as a string. The integer can be in any base.

# Example I/O

*Note: In these lists, `True` represents a truthy value and `False` a falsy one. `0` can be replaced with `1` if your language uses 1-indexing.*

* `Streets: [[True,True,True],[False,False],[False]]`
`Output: 0`
* `Streets: [[False,True,True],[False,False],[True],[False]]`
`Output: 2`
* `Streets: [[],[False,False,True],[False]]`
`Output: 0`
* `Streets: [[True,True,False],[False,True,True],[True,False,True]]`
`Output: -1`
* `Streets: [[True,True,True,True,True,False],[True]]`
`Output: 1`
* `Streets: [[False, True],[False,True,True]]` `Output:1`

# Rules

This is , so shortest code in bytes wins!

# Answer
# Python 2, 58 bytes

```
lambda l:l.index(max(l,key=lambda s:(-s.count(0),sum(s))))

```

Try it online!
> 3 votes

# Answer
# , 52 bytes

```
function(l)order(lengths(l)-(m=sapply(l,sum)),-m)[1]

```

Try it online!

Minimizes the number of toothbrushes, then maximizes the pieces of candy, since this is apparently what OP is asking.

If we want to first maximize the amount of candy, then minimize the number of toothbrushes (seems more plausible…) it becomes

# , 51 bytes

```
function(l)order(m<--sapply(l,sum),lengths(l)+m)[1]

```

Try it online!

Computing the number of `TRUE`s in a list of vectors is easy with `sapply(l,sum)`. Computing the number of `FALSE`s is much less golfy, so I use `lengths` minus the number of `TRUE`s instead.
> 2 votes

# Answer
# Mathematica, 180 172 bytes

```
ToExpression[StringReplace[a,{"["->"{","]"->"}"," "->"=","True"->"-10^-9","False"->"1"}]];(If[Length[#]==1,#[[1]],-1]&@@Flatten[Position[#,Min[#]]]&/@{Total/@Streets})[[1]]

```

We assume the input is already stored as text in the variable *a*. If the reformatting code is neglected (input is already stored in the variable Streets) the length becomes 82 bytes.

My solution maps the toothbrushes (1) + candy(-1e-9) onto the real line and finds the minimum. It will only work for streets that have a maximum of 1,000,000,000 toothbrush houses as is (but it can be easily modified to suit the max number of toothbrush houses.)

Expanded code:

```
a := "Streets: [[True,True,False],[False,True,True],[True,False,True]]";
ToExpression[
 StringReplace[
  a, {"[" -> "{", "]" -> "}", " " -> "=", "True" -> "-10^-9",
   "False" -> "1"}]]
b = (Total /@ Streets)
c = Flatten[Position[b, Min[b]]]
If[Length[c]==1,c[[1]],-1]

```
> 1 votes

# Answer
# Jelly, 15 bytes

```
ċþØ.N1¦ZM-¹L’$?

```

Try it online!

A monadic link taking a list of lists of Jelly booleans (0s and 1s). Returns the 1-indexed maximum list using the specified criteria, or -1 if there is more than one that is equal. The last 6 bytes are spent on converting multiple values into -1; if this could be dropped the answer would be 9 bytes.
> 0 votes

# Answer
# , 19 bytes

```
0{[:/:(-.,&(+/)-)@>

```

Try it online!

* `0 {` first element of...
* `[: /:` the grade up of... (indices with smallest item first)
* `(-.,&(+/)-)` the list of pairs `,` created by summing each of `&(+/)`: 1 minus an input item `-.` and the negative of an input item `-`
* `@>` of each unboxed input item

This turns each input item into a pair:

```
<number of false, -1 * number of true>

```

When we sort this list J will automatically sort first by element 1, then by element 2. Lower are numbers come first.
> 0 votes

---
Tags: code-golf, sequence
---


title: Interpret numbers very literally

text:
# Question
Title: Interpret numbers very literally
To interpret a positive integer very literally, write it in English words (without "and"), replace hyphens with spaces, replace each resulting word with its number value, and concatenate the results into a single number.

To write a positive integer more than 99 but less than 1000 in English words, prefix its last two digits written in English with **`[first digit in English]`**`hundred`  with a trailing space.

To write a positive integer more than 999 but less than 1 million in English words, use the following syntax: **`[part before the last 3 digits in English]`**`thousand`**`[last 3 digits in English]`**, all separated by spaces.

The task is to input a positive integer (less than 1 million) and output it, interpreted very literally.

# Examples

```
1 -> 1                       (one)
10 -> 10                     (ten)
16 -> 16                     (sixteen)
23 -> 203                    (twenty three)
111 -> 110011                (one hundred eleven)
123 -> 1100203               (one hundred twenty three)
1234 -> 110002100304         (one thousand two hundred thirty four)
12345 -> 1210003100405       (twelve thousand three hundred forty five)
123456 -> 110020310004100506 (one hundred twenty three thousand four hundred fifty six)
1056 -> 11000506             (one thousand fifty six)
101101 -> 11001100011001     (one hundred one thousand one hundred one)
110110 -> 1100101000110010   (one hundred ten thousand one hundred ten)

```

Feel free to add more test cases if necessary.

This is tagged , so the shortest code wins.

# Answer
> 3 votes
# 05AB1E, ~~26~~ ~~23~~ 21 bytes

```
₄вεтвεSÐP@θ1Ký0Û]тý₄ý

```

Port of *@Neil*'s Charcoal answer, so make sure to upvote him as well.
-5 bytes thanks to *@Grimy*.

Try it online or verify all test cases.

**Explanation:**

```
₄в                # Convert the (implicit) input-integer to base-1000 as list
                  #  i.e. 119100 → [119,100]
                  #  i.e. 23 → [23]
  ε               # Map each value to:
   тв             #  Convert the value to base-100 as list
                  #   i.e. [119,100] → [[1,19],[1,0]]
                  #   i.e. [23] → [[23]]
     ε            #  Map each value `y` to:
      S           #   Convert the current value to a list of digits
                  #    i.e. [[1,19],[1,0]] → [[[1],[1,9]],[[1],[0]]]
                  #    i.e. [[23]] → [[[2,3]]]
       Ð          #   Triplicate this list
        P         #   Take the product of each inner list of digits
                  #    i.e. [[[1],[1,9]],[[1],[0]]] → [[[1],[9]],[[1],[0]]
                  #    i.e. [[[2,3]]] → [[6]]
         @        #   Check if it's larger than or equal to each digit
                  #    i.e. [[[1],[1,9]],[[1],[0]]] and [[[1],[9]],[[1],[0]]
                  #     → [[[1],[1,1]],[[1],[1]]]
                  #    i.e. [[[2,3]]] and [[6]] → [[[0,0]]]
          θ       #   Keep only the last check of each
                  #    i.e. [[[1],[1,1]],[[1],[1]]] → [[[1],[1]],[[1],[1]]]
                  #    i.e. [[[0]]]
           1K     #   Remove all 1s from each 'string'
                  #    i.e. [[[1],[1]],[[1],[1]]] → [[[""],[""]],[[""],[""]]]
                  #    i.e. [[["0"]]]
             ý    #   Join the list of digits by this string
                  #    i.e. [[[1],[1,9]],[[1],[0]]] and [["",""],["",""]]→ [[1,19],[1,0]]
                  #    i.e. [[[2,3]]] and [["0"]] → [[203]]
      0Û          #   Remove any trailing 0s
                  #    i.e. [[1,19],[1,0]] → [[1,19],[1,""]]
                  #    i.e. [[203]] → [[203]]
  ]               # Close both maps
   тý             # Join the inner lists by "100"
                  #  i.e. [[1,19],[1,""]] → [110019,1100]
                  #  i.e. [[203]] → [203]
     ₄ý           # And then those strings by "1000"
                  #  i.e. [110019,1100] → 11001910001100
                  #  i.e. [203] → 203
                  # (after which the result is output implicitly)

```

# Answer
> 13 votes
# Python 2, 76 bytes

```
f=lambda n,k=1000:n>19and(f(n/k,k/10)+`k-k%4*5`)*(n>=k)+f(n%k,k/10)or`n`[:n]

```

Try it online!

Test suite from Chas Brown.

A fully recursive solution that splits on place values `k=1000`, `k=100`, and `k=10`. The separator for the place values is computed as `k-k%4*5`, which maps

```
1000 -> 1000
100  -> 100
10   -> 0

```

By stopping when `n<=19`, we avoid one-word numbers in the teens being split up.

# Answer
> 4 votes
# Gaia, ~~44~~ 43 bytes

```
:(!>
ℍZ:₸Z¤1>∧'0×¤ṙ$×:dẏ×,↑ℍṙ×
@3eZ,↑¦↓3eṙ×

```

Longer than my original answer, but it works now.

~~fixed my code again but now it's twice as sad~~

Try it online!

```
@3eZ,↑¦↓3eṙ×  Main function.
@3eZ          Input divmod 1000, pushes input div 1000 then input mod 1000
    ,         Pair those two value into a list
     ↑¦       Run the upper function on both
       ↓      Call the function below (loops to top function)
        3eṙ   The string "1000"
           ×  Join the list with "1000"

ℍZ:₸Z¤1>∧'0×¤ṙ$×:dẏ×,↑ℍṙ×  Helper function. Called with 1 argument.
ℍZ                          Divmod with 100
  :₸Z                       Copy the mod part and divmod with 10
                            Stack is: [100s digit, arg mod 100, 10s digit, 1s digit]
     ¤1>                    Bring 10s digit to the top and check if it's greater than 1
        ∧                   Logical AND with 1s digit. (results in 0 or 1)
         '0×                Multiply the character 0 by that result
            ¤               Bring 'arg mod 100' to the top
             ṙ$             Get its string representation and split it into characters
                            (simply doing digit list doesn't work in the case it's 0)
               ×            Join this with the multiplied '0' string
                :d          Copy and parse as a number
                  ẏ         Is it positive? (0 or 1)
                   ×        Multiply the string of the number by that result.
                    ,       Pair: gives the list [100s digit, string from above]
                     ↑      Call the function above
                      >     Remove the first ^ elements from the pair
                       ℍṙ×  Join the resulting list with the string "100"

:(!>  Helper function 2. In this program it is only called with a list.
:(    Copy and get the first element.
  !   Boolean negate (0 or 1)
   >  Remove that many characters from the start of the list

```

# Answer
> 4 votes
# Python 3+inflect, 193 bytes

```
import inflect,re
exec("for i in re.sub('(and)|\W',' ',%sinput())).split():\n for j in range(0,6**8):\n  if i in %sj):\n   print(j,end='')\n   break"%(('inflect.engine().number_to_words(',)*2))

```

Try it online!

Very naive solution which uses Python's `inflect` library. Here is the unfurled code:

```
import inflect,re
for i in re.sub('(and)|\W+',' ',inflect.engine().number_to_words(input())).split():
 for j in range(0,6**8):
  if i in inflect.engine().number_to_words(j):
   print(j,end='')
   break

```

# Answer
> 3 votes
# PHP, ~~137~~ ~~136~~ 143 bytes

```
function f($n){return$n>99?$n>999?f(substr($n,0,-3)).(1e3).f(substr($n,-3)):$n[0].'100'.f($n[1].$n[2]):($n>20&&$n%10?(0^$n/10).'0'.$n[1]:+$n);}

```

Try it online!

# Answer
> 3 votes
# Charcoal, ~~34~~ ~~32~~ ~~31~~ 29 bytes

```
⪫Ｅ↨Ｎφ⪫Ｅ↨ι¹⁰⁰⪫↨λχ…0›Πλ﹪λχ100Ｉφ

```

Try it online! Link is to verbose version of code. Edit: Saved 2 bytes thanks to @Grimmy. Saved a further byte by finding a better way to choose between `0` or the empty string from a boolean. Saved a further 2 bytes because `Base(l, 10)` conveniently returns an empty array when `l` is zero. Explanation:

```
   Ｎ                            Input number
  ↨ φ                           Convert to base 1000 as an array
 Ｅ                              Map over elements
        ι                       Current element
       ↨ ¹⁰⁰                    Convert to base 100 as an array
      Ｅ                         Map over elements
              λ                 Current element
             ↨ χ                Convert to base 10 as an array
            ⪫                   Join with
                 0              Literal `0`
                …               Truncated to length
                    λ           Current element
                   Π            Digital product
                  ›             Is greater than
                      λ         Current element
                     ﹪          Modulo
                       χ        Predefined variable 10
     ⪫                          Join with
                        100     Literal string `100`
⪫                               Join with
                            φ   Predefined variable 1000
                           Ｉ    Cast to string

```

Example: `67890``[67, 890]``[[67], [8, 90]]``[[607], [8, 90]]``[607, 810090]``6071000810090`.

# Answer
> 3 votes
# JavaScript, 69 bytes

Recursively splits and joins based on place values stored in `k`. Inspired by xnor's Python answer.

```
f=(n,k=1e3)=>n<20?+n||'':(n<k?'':f(n/k|0,k/10)+[k-10&&k])+f(n%k,k/10)

```

Try it online!

# Answer
> 2 votes
# Python 3, ~~110~~ 115 bytes

```
def F(n,o=""):
 for i in 1000,100:
  if n>=i:o+=F(n//i)+str(i);n%=i
 return o+'0'[:0<n%10<=n>19].join(str(n))*(n>0)

```

Try it online!

Pretty simple. Hundreds and thousands are handled recursively.

+5 bytes but fixed a bug with `F(100)` thanks to @ChasBrown.

# Answer
> 2 votes
# JavaScript, ~~95~~ ~~93~~ 92 bytes

```
f=n=>n>999?f(n/1e3|0)+[1e3]+f(n%1e3):n>99?(n/100|0)+'100'+f(n%100):n>20&&(x=n%10)?n-x+''+x:n

```

Try it online!

---

* -2 bytes (@Shaggy): store `n%10` in a variable
* -1 byte (@Arnauld): replace `'1000'` with `[1e3]`

# Answer
> 1 votes
# Python 2, ~~106~~ ~~105~~ ~~100~~ 107 bytes

```
f=lambda n:n/T and f(n/T)+`T`+f(n%T)or(n>=H)*`n/H*T+H`+'0'[:n%10>0<n%H>19].join(`n%H`)*(n%H>0)
H=100;T=1000

```

Try it online!

Saved 5 bytes adapting the `.join` approach of randomdude999's answer; lost 7 bytes fixing a bug :).

---
Tags: code-golf, number, natural-language
---


title: Roman Numeral Counting

text:
# Question
Title: Roman Numeral Counting
Roman numerals can be (mostly) written in a one column format, because each letter intersects the top and the bottom of the line. For example: `I`, or 1 intersects both the top and bottom of the line, and `V` or 5 intersects the bottom and top lines, the top twice and the bottom at one place.

The value of all roman numerals is as follows:
`I = 1`
`V = 5`
`X = 10`
`L = 50`
`C = 100`
`D = 500`
`M = 1000`

and the number of intersections (top, bottom) is:
`I = 1,1`
`V = 2,1`
`X = 2,2`
`L = 1,2`
`C = 1,1`
`D = 1,1`
`M = 2,3`

Your job is to take in 2 numbers, which represent the number of intersections on the top and bottom of your line (in that order), and output all possible *valid* combinations of roman numerals, from smallest by literal value to largest. Inputs will always be at or above 1.

Here are some test cases:

```
Input: 1,1
Output: I,C,D

Input: 1,2
Output: L

Input: 2,1
Output: V

Input: 2,2
Output: II, X, IC, CI, CC, ID, DI
(note that DD is not a valid roman numeral, and thus should not be outputted, the value of all of these is (in order) 2, 10, 99, 101, 499, 501)

Input: 3,3
Output: III, IX, XI, LV, XC, CII, CX, CCI, CCC, DII, DX, DCI, DCC
(note that IIC, and IID are not valid numbers. DD (1000) is also not a valid number, as the correct numeral is M) The value of these numbers (in order) is: 3, 9, 11, 55, 90, 102, 110, 201, 300, 502, 510, and 601)

```

This is a usual code-golf, and needless to say, I'm interested to see how golf languages implement roman numeral counting rules. Best of luck!

# Answer
> 5 votes
# 05AB1E, ~~32~~ ~~29~~ 25 bytes

```
žDL.Xʒ•BÌË"•4в2ôsÇ87%èøOQ

```

-7 bytes thanks to *@Grimy*.

Try it online or verify all test cases.

**Explanation:**

```
žD                # Push builtin 4096 (the maximum Roman number is 3999)
  L               # Create a list in the range [1,4096]
   .X             # Convert each integer to a Roman number
     ʒ            # Filter this list by:
      •BÌË"•     "#  Push compressed integer 195646806
            4в    #  Convert it to base-4 as list: [2,3,2,2,2,1,1,1,1,1,1,1,1,2]
              2ô  #  Split it into parts of size 2:
                  #   [[2,3],[2,2],[2,1],[1,1],[1,1],[1,1],[1,2]]
      s           #  Swap to get the current Roman number we're filtering on
       Ç          #  Convert its characters to their unicode values
        87%       #  Take modulo-87 for each (I=73; V=86; X=1; L=76; C=67; D=68; M=77)
           è      #  Index those into the list of pairs (with automatic wrap-around)
            ø     #  Zip/transpose; so we have inner lists of top/bottom values
             O    #  Sum each inner list
              Q   #  And check if it's equal to the (implicit) input-pair
                  # (after the filter, the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•BÌË"•` is `195646806` and `•BÌË"•4в` is `[2,3,2,2,2,1,1,1,1,1,1,1,1,2]`.

# Answer
> 3 votes
My first try on Code Golf, please point out some optimizations!

**Python 3.7, ~~465~~ ~~449~~ ~~364~~ ~~363~~ 284 Bytes**

Edit: Thanks for the improvements! Jo King managed to squeeze this logic from 449 to just 364 bytes, I took a single Byte off it so I felt justified to update it. :D

Description of the old function, which remains can still be found in the code:

To formulate all numerals with certain amount (a and b) of cross points, m() subtracts number of cross points of every numeral from a and b, and recursively calls the function again for every case. If a and b are negative when called, the function exits, and if both are zero, the next function checks if it is a valid roman number, and prints accordingly.

To check if a character string is a roman number, t(c) checks if there are any 4 characters in a row, or two in the case of 50 and 500. It then checks for the possible subtraction numeral before any numeral (The possible subtraction roman numeral is either 2 or 1 positions after the real roman numeral in the list of 'MDCLXVI', depending on the **parity** of the roman numerals index on that list!) If any are found, they are replaced for the next part as with just the real numeral, without the subtraction numeral. SUB-NBR-SUB sandwiches, like IVI are falsified. The next part just checks if the list is ordered.

```
def m(c,i,a=''):
 d,e,s,*p=a,c|i,str,2,3,*[1]*5,*[2]*4,1,1,1
 for x in range(7):c+i>0==m(c-p[x*2],i-p[x*2+1],a+s(x));e|=any(s(z)in d for z in[s(x)*4,11,33,f"{x+~x%2+1}{x}{x+~x%2+1}"]);d=d.replace(s(x+~x%2+1)+s(x),s(x))
 e or[*d]==sorted(d)==print(''.join('MDCLXVI'[int(x)]for x in a))

```

# Answer
> 2 votes
# Perl 5, ~~230~~ 213 bytes

```
sub f{grep{($t,$b)=@_;map{($h='I1V21X2L12C1D1M23')=~/$_(.)(\d?)/;$t-=$1;$b-=$2||$1}/./g;!$t&&!$b}map{$r='I'x$_;for(qw(IVX XLC CDM)){($I,$V,$X)=/./g;$r=~s,$I{4}($I?),$1?$V:$I.$V,ge;$r=~s,$V($I?)$V,$1$X,g}$r}1..4e3}

```

Try it online!

With spaces and newlines added for readability:

```
sub f{
  grep{
    ($t,$b)=@_;
    map{
      ($h='I1V21X2L12C1D1M23')=~/$_(.)(\d?)/;
      $t-=$1;
      $b-=$2||$1
    }
    /./g;
    !$t&&!$b
  }
  map{
    $r = 'I' x $_;
    for( qw(IVX XLC CDM) ){
      ($I,$V,$X) = /./g;
      $r =~ s,$I{4}($I?),$1?$V:$I.$V,ge;
      $r =~ s,$V($I?)$V,$1$X,g
    }
    $r
  }
  1..4e3
}

```

The `map` at the end turns all integers 1 – 4000 into their roman equivalent. Since there is no letter for 5000 and 10000 and so on, it's reasonable to say that the maximum roman number is 3999=MMMCMXCIX. (One could just add more M's to get larger numbers, if so, just increase `4e3` here to whatever time you have to wait for the result...this is code golf where we optimize for code length, not runtime:)

The `grep` filters that list so that only the ones with the wanted input `$t` (top) and `$b` (bottom) numbers are returned. The `map`s inside `grep` decreases $t and $b by the right amount of "intersections" for each roman letter and the grep ends up being true for each roman number by `!$t&&!$b` if both $t and $b are zero (which means they started as the numbers we wanted in the input parameters).

# Answer
> 1 votes
# Charcoal, ~~144~~ 97 bytes

```
ＮθＮηΦＥ×φθ⁺×M÷ιφ⮌⭆⪪”{⧴9i…⪫χM⎚GＯWbπ↗sＰ÷n“<BÞＤ‴!w≡θ⟧Ｌ≡§Ａ≦Ｉ⍘∨Φ…ok”²⁹§⪪λ ÷ιＸχμ∧⁼θΣＥι⊕№VXMλ⁼ηΣＥι⊕№LXMMλ

```

Try it online! Link is to verbose version of code. Explanation:

```
ＮθＮη

```

Input the two values.

```
ΦＥ×φθ

```

Loop up to 1000 times the first number, which is well past the largest valid Roman numeral, keeping only those that satisfy the validity of both the top and bottom intersections (according to the condition at the end of the code).

```
⁺×M÷ιφ⮌⭆⪪”{⧴9i…⪫χM⎚GＯWbπ↗sＰ÷n“<BÞＤ‴!w≡θ⟧Ｌ≡§Ａ≦Ｉ⍘∨Φ…ok”²⁹§⪪λ ÷ιＸχμ

```

The compressed string expands to `I II III VI V IV IIV IIIV XI X XX XXX LX L XL XXL XXXL CX C CC CCC DC D CD CCD CCCD MC`. This is used to calculate the Roman numeral in reverse, working from the units up to the 100s, and then the reverse is concatenated to any further `M`s needed.

```
∧⁼θΣＥι⊕№VXMλ⁼ηΣＥι⊕№LXMMλ

```

For each Roman numeral, count the number of times each letter thereof appears in the strings `VXM` and `LXMM` respectively, then add one for each letter, and compare the totals to the inputs.

# Answer
> 0 votes
# Jelly, 129 bytes

```
ŒṗŒ!€ẎQ)p/ẈE$ƇZ€“(³l’ḃ9¤ḃ3¤ẹⱮŒpƊ€ẎŒgQ€QƑƊƇḂÐḟQƑ$ƇI<1kƲ€ḂḢ€ạẈƲỊẠƊƇIFṀ<ʋƇ3ị“¢¦½2d‘;.ȷ,ȷ¤ạ/€€S€Ụf<ƇS<ɗⱮ⁵*Ɱ3¤ẠaNÞƑƲ€T$ƲƊị$ị“IVXLCDM”K

```

Try it online!

A full program taking a pair of integers as its argument and printing to STDOUT a space-separated list of Roman numerals. Should produce all valid Roman numerals following the rules on Project Euler (so `VIIII`, `IX` and `IIIIIIIII` are all valid forms for 9, but `VIV` is not, and `X` is the only valid form for 10.)

# Answer
> 0 votes
# Jelly, 61 bytes

```
1xⱮ4Ḷ¤$Ø½ṭ;2;Ɱ$Ʋ1,3ṭ+þ3Ḥ€Ż¤ṚŒpḣ4ȷF€ị“(³l’ḃ9¤ḃ3¤S⁼ɗƇị“IVXLCDM”

```

Try it online!

This monadic link takes a pair of integers as its argument and returns a list of strings representing the Roman numerals. Unlike my other Jelly answer, this one only uses the minimal (canonical?) representation of each Roman numeral, so it’s more straightforward to generate a list of all Roman numerals in order and filter them. It only generates Roman numerals up to 3999, but could be adapted to work for higher Roman numerals if needed. L

---
Tags: code-golf, number, combinatorics, roman-numerals
---


title: Max of the reversed of two numbers

text:
# Question
Title: Max of the reversed of two numbers
Given two real numbers (postive or negative) in the limits of float pointing number data types, i.e., (\\$-3.4e38\\$ to \\$3.4e38\\$) not inclusive, you should output the max of the two reversed numbers.

---

## TEST CASES

## Example

## Input:

```
135
210

```

## Output:

```
531

```

\\$531\\$ is \\$135\\$ reversed, which is greater than \\$012\\$, i.e., \\$210\\$ reversed.

---

Negative numbers are allowed:

## Example 2

## Input:

```
-135
-210

```

## Output:

```
-012

```

\\$-012\\$ is \\$-210\\$ reversed, which is greater than \\$-531\\$, i.e., \\$-135\\$ reversed.

---

Real numbers are allowed:

## Example 3

## Input:

```
13.5
10

```

## Output:

```
5.31

```

\\$5.31\\$ is \\$13.5\\$ reversed, which is greater than \\$01\\$, i.e., \\$10\\$ reversed.

---

## Example 4

## Input:

```
-1112313.5
-312.5671

```

## Output:

```
-5.3132111

```

\\$-5.3132111\\$ is \\$-1112313.5\\$ reversed (it reverses the number but is still negative, which is greater than \\$-1765.213\\$, i.e., \\$-312.5671\\$ reversed.

---

## Example 5

## Input:

```
0.0000001
0

```

## Output:

```
1000000.0

```

\\$1000000.0\\$ is \\$0.0000001\\$ reversed, which is greater than \\$0\\$, i.e., still \\$0\\$ reversed.

---

## Example 6

## Input:

```
121
121

```

## Output:

```
121

```

Both numbers are equal and are palindrome. Either one is correct.

---

# Rules

---

## Good Luck!

# Answer
> 4 votes
# 05AB1E, ~~6~~ ~~7~~ 6 bytes

+1 byte to fix cases when only one of the inputs is negative.
-1 byte by Grimmy

```
í'-δ†Z

```

Try it online!

Test all inputs

The input is taken as a list of strings \[x, y\].

Explanation:

```
í        Reverse each input
 '-      Push a minus sign
   δ†    Apply "filter out the minus sign to the front" to each input
     Z   Take the maximum

```

# Answer
> 6 votes
# Wren, ~~126~~ 124 bytes

As always Wren is the longest. I hate Wren's verbosity.

```
Fn.new{|a|a.map{|i|i>0?"":"-"+(i.abs.toString[-1..-(i.abs.toString.count)])}.map{|i|Num.fromString(i)}.reduce{|x,y|x<y?x:y}}

```

Try it online!

## Explanation

```
Fn.new{                                                                                // new anonymous function
       |a|                                                                                // with the parameter a
          a.map{|i|                                                                                // for each item in this parameter
                                  (i>0)?"":"-"                                                                       // The sign of each item. If the item is larger than 0, return the null string, otherwise return a negative sign.
                                              +(                                           )                         // Append this with the following string:
                                                i.abs                                                                // The absolute value of i
                                                     .toString                                                       // Convert this value to a string
                                                              [-1..-(i.abs.toString.count)]                          // Reverse this string
                   Num.fromString(                                                          )                        // convert this to a number from a string
                                                                                }.reduce{|x,y|x<y?x:y}} // Find the minimum value of the list

```

# Answer
> 5 votes
# Perl 5, 51 bytes:

```
sub f{($x,$y)=map{/-?/;$&.reverse$'}@_;$x>$y?$x:$y}

```

Try it online!

...or if using a function from a core module is allowed (`max` in `List::Util`) it's 35 bytes:

# 35 bytes:

```
sub f{max map{/-?/;$&.reverse$'}@_}

```

Try it online!

# Answer
> 4 votes
# Zsh, 63 bytes

```
for x;a+=(${(M)x#-}${(j::)${(Oas::)x#-}})
<<<$a[1+$[a[1]<a[2]]]

```

Try it online!

`${x#-}` removes the leading `-` if it exists. Adding the `(M)` flag causes the `-` to be substituted instead of what remains. Then this construct reverses the remaining string: `${(j::)${(Oas::)var}}`.

For each element, we append to an array, then use a comparison to index into the array.

# Answer
> 4 votes
# Python 3, ~~89~~ 86 bytes

~~Disclaimer: This answer does not work for the second example #4 due to floating point accuracy constraints in Python. Feel free to disqualify.~~

Update: This answer now works for all examples thanks to @JonathanAllan

```
f=float
r=lambda a:-f(a[:1:-1])if eval(a)<0else f(a[::-1])
m=lambda a,b:max(r(a),r(b))

```

Try it online!

# Answer
> 4 votes
# JavaScript (ES6), 100 bytes

Takes input as `(a)(b)`.

```
a=>b=>Math.max((g=n=>(s=n>0||-1)*[...(s*n).toFixed(9).replace(/\.0+$/,0)].reverse().join``)(a),g(b))

```

Try it online!

# Answer
> 4 votes
# Python 3.8, 69 bytes

```
lambda*v:max(map(lambda x:(-1)**(z:=eval(x)<0)*float(x[z:][::-1]),v))

```

An unnamed function accepting 2 (actually, any number of) strings, which yields the maximal reversed version as a floating point number.

**Try it online!**

# Answer
> 3 votes
# Red, 74 bytes

```
func[a][forall a[a/1:(sign? a/1)* do reverse to""absolute a/1]max a/1 a/2]

```

Try it online!

Takes the input as a list of two numbers.

The 5th test case (0.0000001 0) doesn't work in TIO, but works fine in the Red console:

# Answer
> 3 votes
# JavaScript (Node.js), 64 bytes

```
a=>b=>(R=([h,...t])=>h?h+1<0?h+R(t):R(t)+h:t)(a)>+R(b)?R(a):R(b)

```

Try it online!

Input / output as strings.

# Answer
> 2 votes
# Keg `-hd` ~~53~~ ~~41~~ ~~35~~ ~~34~~ ~~27~~ 11 bytes (SBCS)

```
(2|¿⑶&)@MMƒ

```

*-16 bytes with new reverse t.o.s function*

## Answer History

### 27 bytes

```
(2|᠀÷^:\-=[_^\-^]⅀&)ℝ$ℝ@MMƒ

```

-7 bytes due to using the new built-in function library which will be soon populated with helpful functions.

`MM` is the maximum function, and returns the maximum of the two items passed to it.

## 34 bytes

```
(2|᠀÷^:\-=[_^\-^]⅍⅀&)ℝ$ℝ:&^:^<[&|^

```

Try it online!

-1 byte due to using

## 35 bytes

```
(2|᠀÷^:\-=[_^\-]^``⅀&)ℝ$ℝ:&^:^<[&|^

```

Hey, so, uh, Keg has flags now. `-hd` prints only the top item if nothing has been printed. Also, summate command works as expected now. The github interpreter works, but not TIO yet.

## 41 bytes

```
(2|᠀÷^:`-`=[_^`-`^]``∑+)&)ℝ$ℝ:&^:^<[&|^].

```

Try it online!

-12 bytes due to not using functions

## 53 bytes

```
@m2|:&^:^<[&|^]ƒ(2|᠀÷^:`-`=[_^`-`^] ``(!;|+)&)ℝ$ℝ@mƒ.

```

Try it online!

I dont even know where to begin when explaining this, but it works. I know I could remove the need for a function, but I'm on my phone, so I'll do it later.

I would have used the summate command, but there's a bug with it.

# Answer
> 2 votes
# PHP, 56 bytes

```
fn($a)=>max(array_map(fn($n)=>strrev($n)*($n>0?:-1),$a))

```

Try it online!

Input is an array of two string numbers, example: `['123', '25.5']`.

Simply reverses both numbers as strings, then returns the max of them as numbers. To handle reversed negative numbers, the `*($n>0?:-1)` part is used which multiplies the reversed number by `1` if the original number was more than zero, else multiplies it by `-1`.

In PHP if you try to convert a string which starts with numeric values to a number, it will take the numeric part and ignore the rest. For example `'321-'` converted to a number will be `321` and the multiply operation automatically forces this numeric conversion.

# Answer
> 2 votes
# APL+WIN, 32 bytes

Prompts for a nested string of the two numbers.

```
⌈/⍎¨(n↑¨'¯'),¨⌽¨(n←'¯'=↑¨m)↓¨m←⎕

```

Try it online! Courtesy of Dyalog Classic

# Answer
> 2 votes
# Japt `-g -N`, 12 bytes

```
®®w}'-Ãn@Y-X

```

Try it

Thanks to @Arnauld for spotting an error

```
Takes input as array of strings
U.m // for each element
(function(Z) { return Z.m // split on '-'
(function(Z) { return Z.w() // reverse and convert to number
 }, "-") }) // rejoins
.n(function(X, Y, Z) { return Y - X }) // sort in descending order

Flag -gn to output first element obtained
Flag -N to output it as a number (remove leading 0s)

```

# Answer
> 2 votes
# Perl 6, ~~28~~ 27 bytes

*-1 byte thanks to Jo King*

```
&max o**.&{.abs.flip*.sign}

```

Try it online!

# Answer
> 2 votes
# , 82 bytes

```
options(scipen=99);b=sign(a<-scan());max(b*as.numeric(stringi::stri_reverse(b*a)))

```

Try it online!

Input is taken as two numbers.

Setting scipen=99 is needed to deal with more than a few decimals.

# Answer
> 2 votes
# Ruby, 51 bytes

```
->*a{a.map{|w|(w<=>0)*"#{w.abs}".reverse.to_f}.max}

```

Try it online!

# Answer
> 2 votes
# **Haskell**, 70 bytes

```
f a b=max(g a)(g b)
g('-':x)=(0-).h$x
g xs=h xs
h=read @Float .reverse

```

Try it here

or if Haskell language pragma aren't allowed (like TypeApplications)

# **77 bytes**

```
f a b=max(g a)(g b)
g('-':x)=(0-).h$x
g xs=h xs
h=read.reverse::String->Float

```

# Answer
> 2 votes
# APL(NARS), 17 chars, 34 bytes

```
{⌈/(⍎¨⌽¨⍕¨∣⍵)××⍵}

```

test:

```
  f←{⌈/(⍎¨⌽¨⍕¨∣⍵)××⍵}
  f 135 210
531
  f ¯135 ¯210
¯12
  f 13.5 10
5.31
  f ¯1112313.5   ¯312.5671
¯5.3132111
  f 0.0000001 0
SYNTAX ERROR
  f 0.000001 0
100000
  f 121 121
121
  f 121 ¯3 6 0.0001 9
1000

```

# Answer
> 1 votes
# Charcoal, 13 bytes

```
Ｉ⌈Ｅ²Ｉ⪫Ｅ⪪Ｓ-⮌λ-

```

Try it online! Link is to verbose version of code. Explanation:

```
   ²            Literal `2`
  Ｅ             Map over implicit range
        Ｓ       Input string
       ⪪ -      Split on `-`s
      Ｅ         Map over substrings
           λ    Current substring
          ⮌     Reversed
     ⪫      -   Join with `-`s
    Ｉ           Cast to number
 ⌈              Maximum
Ｉ               Cast to string
                Implicitly print

```

# Answer
> 1 votes
# Jelly, 11 bytes

```
ḟ€”-UV×VṠ$Ṁ

```

Try it online!

A monadic link taking a list of two strings and returning the maximum reversed number as a float or integer depending on the input.

## Explanation

```
ḟ€”-        | Filter out “-“ from each
    U       | Reverse each
     V      | Evaluate as Jelly code
      ×  $  | Multiply by following as a monad:
       V    | - Evaluate as Jelly code
        Ṡ   | - Sign
          Ṁ | Max

```

# Answer
> 1 votes
# Bash \+ coreutils, 40 bytes

```
rev|sed 's/\(.*\)-/-\1/'|sort -n|tail -1

```

Try it online!

# Answer
> 1 votes
# Haskell, 104 bytes

```
r n=read((\s->if head s=='-'then"-"++reverse(drop 1 s)else reverse s)$show n)::Float
f a b=max(r a)(r b)

```

Try it online!

The `0.0000001 0` test case doesn't work though, I think there's an error on `read`.

Typing could also be improved when the input is type `Int` for example

# Answer
> 1 votes
# Gaia, 11 bytes

```
⟨v'-%v$⟩¦d⌠

```

This is a function which accepts a list of two numbers as strings and leaves the result on the stack. OP wasn't clear about whether leading 0's or 0 decimals need to be included, but the program should be equally long either way. This function does not include these 0's:

```
⟨v'-%v$d⟩¦⌉

```

Try it online!

```
⟨       ⟩¦    Map this block over the list:
 v            Reverse the string
  '-%         Split it around -'s, leaving the separators in the result
     v        Reverse the splitting
      $       Rejoin it
         d⌠  Return the element of the list which gives the highest value when parsed as a number

```

---
Tags: code-golf, number
---


title: Golf Lathe Machine

text:
# Question
Title: Golf Lathe Machine
You probably know what a Turing Machine is but do you know what is a Turning Machine (lathe)? Ok you already know.. and what about a Golf Turning Machine ??

Ok I tell you..

A Golf Turning Machine is a full program or function taking a list/array (or any convenient method) representing the Profile (P) of a turned piece and producing an ascii turned shape.

An ascii turned shape has square rotated by 45° cutting section instead of a circle so that we only need '/' and '\\' characters to draw it. And it has '\_' characters for the profiles: upper, lower and median.(like the one of this challenge : ASCII TURNED SHAPE ) for simple and nice drawing purpose.

```
      _________
     /\        \
    /  \________\
    \  /        /
     \/________/

```

A Profile P is a container of positive integers values in the range 0 \<= value \< 26(minimum)
\- Every value represents the radius of a 1 long character section, so the length of the container is the length of the piece obtained.
\- Alphabet are also valid \[a to z\] or \[A to Z\] they must correspond to a \[0 to 25\] value.

* 0 values at the beginning and at the end of the profile input can not be considered.

Test cases:

```
[2,2,2,2,2,4,4,4,4,4,6,6,6,6,6,4,4,4,4,4,2,2,2,2,2] or
"CCCCCEEEEEGGGGGEEEEECCCCC" or
['c','c','c','c','e',.....]
             _____
            /\    \
        ___/_ \    \__
       /\    \ \    \ \
   ___/_ \    \ \    \ \__
  /\    \ \    \ \    \ \ \
 /  \____\ \____\ \____\_\_\
 \  /    / /    / /    / / /
  \/____/ /    / /    / /_/
      \  /    / /    / /
       \/____/ /    /_/
           \  /    /
            \/____/

```

.

```
[1,0,0,0,0,0,0,3,3,0,0,1] or
[0,0,0,0,0,1,0,0,0,0,0,0,3,3,1,1,1,0,0,0]
         __
        /\ \
  _    /  \ \_
 /\\  /    \_\\
 \//  \    / //
       \  / /
        \/_/

```

.

```
[2,1,1,1,1,10,10,8,8,8,8,8,8,10,10,1,1,1,1,2]

           __      __
          /\ \    /\ \
         /  \ \__/_ \ \
        /    \ \   \ \ \
       /      \ \   \ \ \
      /        \ \   \ \ \
     /          \ \   \ \ \
    /            \ \   \ \ \
   /  _           \ \   \ \ \
  /  /\\___        \ \   \ \ \
 /  /  \\__\        \_\___\ \_\
 \  \  //__/        / /   / / /
  \  \//           / /   / / /
   \              / /   / / /
    \            / /   / / /
     \          / /   / / /
      \        / /   / / /
       \      / /   / / /
        \    / /___/ / /
         \  / /  \  / /
          \/_/    \/_/

```

Rules :
\- Margins are not specified.
\- Standard loopholes are forbidden.
\- Standard input/output methods.
\- Shortest answer in bytes wins.

Sandbox https://codegolf.meta.stackexchange.com/a/18150/84844

# Answer
# JavaScript (ES6),  ~~259 249~~  246 bytes

Takes input as an array of integers. Returns a matrix of characters.

```
a=>{for(m=[],i=a.length,X=i+25;i--;r[X]>' '|!w?0:r[X]='_',X--)for(y=w=a[i];y>=-w;y--)for(r=m[Y=y+25]=m[Y]||Array(X).fill` `,W=w+(y>0?1-y:y),k=2;k--;)for(x=-W;x<W;x++)r[X+x+k]='/\\  _'[w^a[i+k]|w^a[i+k-1]?(x+W&&2-!(~x+W))^y>0:y&&y-w?2:4];return m}

```

Try it online! (with leading and trailing empty lines removed for readability)

## Commented

We are 'drawing' in a matrix \\$m\[\\:\]\\$, from right to left. The code essentially consists of 4 nested *for* loops, followed by the matrix update.

### First loop: input values

```
for(                            // initialization:
  m = [],                       //   m[] = output matrix
  i = a.length,                 //   i   = length of input
  X = i + 25;                   //   X   = center x-coordinate
                                // condition:
  i--;                          //   stop when i = 0; decrement i
                                // final expression:
  r[X] > ' ' | !w ? 0           //   unless w = 0 or there's already a character other
                  : r[X] = '_', //   than a space here, append the top '_'
  X--                           //   decrement X
)                               //

```

### Second loop: rows

```
for(                            // initialization:
  y = w = a[i];                 //   y = w = next width, taken from the input list,
                                //   read in reverse order
                                // condition:
  y >= -w;                      //   stop when y = -w-1
                                // final expression:
  y--                           //   decrement y
)                               //

```

### Third loop: slices

```
for(                            // initialization:
  r = m[Y = y + 25] =           //   r[] = row to update
      m[Y] || Array(X).fill` `, //   if undefined, initialize it with X leading spaces
  W = w + (y > 0 ? 1 - y : y),  //   W = width of the pattern at this row
  k = 2;                        //   k = counter to draw two consecutive slices
                                // condition:
  k--;                          //   stop when k = 0; decrement k
)                               //

```

### Fourth loop: columns

```
for(                            // initialization:
  x = -W;                       //   start with x = -W
                                // condition:
  x < W;                        //   stop when x = W
                                // final expression:
  x++                           //   increment x
)                               //

```

### Matrix update

```
r[X + x + k] =                  // set the character at the current position:
  '/\\  _'[                     //   0 = '/', 1 = '\', 2 or 3 = space, 4 = '_'
    w ^ a[i + k] |              //   if a[i] is different from a[i + k]
    w ^ a[i + k - 1] ?          //   or different from a[i + k - 1]:
      ( x + W &&                //     append a '/' if x = -W
        2 - !(~x + W)           //     append a '\' if x = W - 1, or a space otherwise
      ) ^ y > 0                 //     invert '/' and '\' if we're below the middle row
    :                           //   else:
      y && y - w ? 2 : 4        //     append a '_' if y = 0 or y = w,
  ];                            //     or a space otherwise

```
> 14 votes

# Answer
# Charcoal, 68 bytes

```
ＦＬθ«≔⌕α§⮌θιηＦη«Ｊ±⁺ιη⁰Ｇ↘η↗⊕η↖η ↘η←↙η↑↖η→↗η↘§_/⁼/ＫＫ≔⎇⁼ηζ◧_ηηδ↘δ←↙δ»≔ηζ

```

Try it online! Link is to verbose version of code. Takes a string of uppercase letters as input. Explanation:

```
ＦＬθ«

```

Loop once for each input letter.

```
≔⌕α§⮌θιη

```

Calculate the previous letter's value, since the drawing is done from end to start.

```
Ｆη«

```

Loop that many times; this is slightly golfier than an `if` since it doesn't need an `else`.

```
Ｊ±⁺ιη⁰Ｇ↘η↗⊕η↖η ↘η←↙η↑↖η→↗η

```

Erase and draw the main diamond of the section.

```
↘§_/⁼/ＫＫ

```

Draw the `_` profile at the top if there isn't already a `/` there.

```
≔⎇⁼ηζ◧_ηηδ↘δ←↙δ

```

Draw the right side of the back of the section if this is a new section, otherwise erase the right side of the front diamond we drew last time (the left side was already erased earlier) leaving just two `_`s for the profiles.

```
»≔ηζ

```

Save the size of the section for the next loop.
> 1 votes

---
Tags: code-golf, ascii-art, 3d
---


title: Delete those pesky ".DS_Store" files

text:
# Question
Title: Delete those pesky ".DS_Store" files
If you use OS X then you might be familiar with the infamous hidden ".DS\_Store" files that are produced as a result of using Finder.

The challenge is to write code that will go through the entire file system and delete any file named ".DS\_Store".

Classic code golf - shortest code wins.

---

**Clarifications:**

* The code does *not* need to delete any .DS\_Store files that require superuser; assume no such files exist.
* The code should *only* delete the relevant .DS\_Store files and nothing else.

# Answer
# zsh, 19

```
rm -f /**/.DS_Store

```

(Make that 16 if it's ok to leave out `-f`.)
> 14 votes

# Answer
### Bash\*, 40 30

```
find / -name .DS_Store -delete

```

```
find / -name .DS_Store -exec rm -f {} \;

```

This should handle it (not very golfed, not.to.mention marvelously slow). Bash seems right because we don't have to deal with any "import system" nonsense. If you want to require execution in any environment, add 4 chars for `bash` and 1 for a line feed.

\*any shell I guess, just can't get out of the habit assuming the bourne again shell is the only one.
> 12 votes

# Answer
# Ruby: ~~38~~ 33 characters

```
File.delete *Dir['/**/.DS_Store']

```
> 9 votes

# Answer
# fish, 16

```
rm /**/.DS_Store

```

(Make that 19 if `-f` is required to delete `.DS_Store` in read-only directories.)
> 2 votes

# Answer
# Shell, 25

```
locate .DS_Store|xargs rm

```

Requires working `locate` database.
> 0 votes

# Answer
# Python 3, 80 bytes

```
import os
d='.DS_Store'
for r,_,f in os.walk('/'):
 if d in f:os.remove(r+'/'+d)

```

Try it online!

By no means competable, but just for the sake of it :)
> 0 votes

# Answer
# CMD, 17

```
del/s "/.DS_Store

```

Pretty straight-forward.

`/s` is required for searching within subdirectories as well.
`"` is used to escape the `/` char which would otherwise be interpreted as an (invalid) argument.
> 0 votes

# Answer
# find, 38

The previus `find` solution is plain wrong: it's mean to delete everything named `.DS_Store` including directory, links, special file etc.

But:

```
find / -type f -name .DS_Store -delete

```

it's the minimal solution using `find`.

**DISCLAMER**: I strongly advice against really using this solution on a real \*nix box: trying to delete something recursively from `/` is a very **bad** idea. You are warned.

**EDIT** :

If the differences among files, directorys, links (hard and symbolic), named pipes, sockets, special files, pseudo-file systems is not clear to you, I suggest to google some of this unknown terms. You'll be surprise, wiser, and less prone to (catstrofic) errors.

**EDIT2** : Even more relevant : the OP wrote "The code should only delete the relevant .DS\_Store files and nothing else." : so, if someone care to read the **boring** requirements, all solutions that remove more than this files hare funny, smart, ect. but *wrong*.
> -1 votes

---
Tags: code-golf, file-system
---


title: Tidy up my bit string

text:
# Question
Title: Tidy up my bit string
I have a series of binary switches, which I can represent as a bit string. The last person who used my switches left them in some arbitrary state without cleaning up, and it bugs me. I always keep the switches in one of four possible "tidy" configurations:

* All `1`: e.g., `111111111`
* All `0`: e.g., `000000000`
* Alternating `1` and `0`: e.g., `10101010` or `01010101`

However, in addition to being fastidious about my switch arrangements, I'm also very lazy, and want to extend the smallest amount of effort possible to reset the switches to one of my preferred states.

# Challenge

Write a program or function that takes a sequence of ones and zeros of any length. It should output a result of the same length that shows the closest "tidy" configuration.

## Input and output

* You may represent your bit sequence using a string or any language-native ordered type, such as a list or array. If using a non-string structure, items within the sequence may be number or string representations of `1` and `0`.
    + Your strings may have leading and trailing characters like `"..."` or `[...]`
* Your input and output formats are not required to match. (For example, you may input a list and output a string.)
* Don't input or output base 10 (or other base) representations of the bit string. That's way too much effort to correspond back to switches -- I'm doing this because I'm lazy, remember?
* Output must be a sequence as specified above. Don't output an enumerated value saying which of the four configurations is the best (e.g., don't say, "solution is case #3"). Actually output a bit sequence in that configuration.
* Input may be of any length. Your code may not impose arbitrary limits on the size of the input.
    + If your language or interpreter imposes reasonable arbitrary limits on the size of an input or call stack (e.g, if you choose a recursive solution), then this is acceptable insofar as it is a shortcoming in your environment, not your code.

## Notes

* The distance between two strings is the Hamming distance. You must find the "tidy" configuration of the same length at the input that has the fewest number of differences from the input.
* If multiple tidy configurations are equally best choices, you may output any best choice, or (at your option) multiple best choices, delimited in some way or as siblings in a data structure. The selection can be completely arbitrary and does not need to be consistent between executions.
* The input might already be a tidy state.

## Examples

```
Input:  1111110
Output: 1111111

Input:  001010000
Output: 000000000

Input:          0010100
Allowed output: 0000000
Allowed output: 1010101
[You may choose either allowed output, or both]

Input:  1111
Output: 1111

Input:  10
Output: 10

Input:  010101101
Output: 010101010

Input:          110
Allowed output: 111
Allowed output: 010

```

# Answer
> 2 votes
# Python 2, ~~127~~ ~~103~~ 101 bytes

```
lambda a:min(zip(*[[1,0,i%2,~-i%2]for i in range(len(a))]),key=lambda N:sum(o^b for o,b in zip(a,N)))

```

Try it online!

Makes the lists `111...`, `000...`, `101...` and `010...` with the first `zip` then finds the min of these lists with key function: sum of the xor of each element in the each possible output the input.

# Answer
> 2 votes
# Python 3, ~~101~~ 98 bytes

```
lambda s:min([p*len(s)for p in('1','0','10','01')],key=lambda l:sum(map(str.__ne__,l,s)))[:len(s)]

```

Try it online!

# Answer
> 1 votes
# Ruby, ~~105~~ 87 bytes

```
->s{(0..3).map{|i|("%02b"%i*z=s.size)[0,z]}.min_by{|x|("%b"%eval("0b1#{x}^0b"+s)).sum}}

```

Try it online!

This code constructs the four "tidy" strings by elongating the bit representations of numbers 0 to 3 to the required size, and then selects the one that gives the minimum Hamming distance to our test string.

The distance is calculated by XORing the integer representations of strings, and in theory we should then count the number of set bits in the result. But in practice, string byte `sum` method works just as well, and is golfier. The only extra trick that is now necessary, is to pad one of the bit strings with an extra "1" in front: `0xb1...` to prevent dropping of leading zeroes in the result, as they are important for `sum`.

# Answer
> 1 votes
# Pyth, ~~21~~ ~~20~~ 19 bytes

```
.iFm*ld].R.OdZ.TcQ2

```

Input/output as a list of 0s and 1s.
Try it here

### Explanation

```
.iFm*ld].R.OdZ.TcQ2
              .TcQ2    Separate the bits at even and odd positions.
   m                   For each part...
        .R.OdZ         ... round the average bit...
    *ld]               ... and get a list of copies of that number.
.iF                    Interleave the results.

```

# Answer
> 1 votes
# Jelly, ~~22~~ 17 bytes

```
JµṠ,¬;‘Ḃ,ḂƲạ³S$ÐṂ

```

Try it online!

Outputs all minima.

# Answer
> 1 votes
# Stax, 18 bytes

```
æQ|jX8Å½ΓÜ\`\Δ○║á♦

```

Run and debug it

# Answer
> 1 votes
# Ruby, ~~89~~ 87 bytes

```
->l{[a=[0],b=[1],a+b,b+a].map{|i|i*a=l.size}.min_by{|i|l.zip(i).count{|c,d|c!=d}}[0,a]}

```

Try it online!

# Answer
> 1 votes
# Husk, 18 bytes

```
ΣTm(Ṡm`K(iA)Ċ2)Set

```

Try it online!

# Answer
> 1 votes
# Java 10, ~~182~~ ~~179~~ ~~178~~ 170 bytes

```
a->{int l=a.length,b[][]=new int[4][l],i=4*l,y,r=l,R[]=a;for(;i-->0;)b[y=i/l][i%l]=y<2?y:i%l+2/y&1;for(var B:b){for(i=y=0;i<l;)y+=a[i]^B[i++];if(y<r){r=y;R=B;}}return R;}

```

-11 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
a->{                  // Method with integer-array as both parameter and return-type
  int l=a.length,     //  Length of the input-array
      b[][]=new int[4][l],
                      //  Integer matrix of 4 rows and `l` columns
      i=4*l,          //  Index integer
      y,              //  Temp integer
      r=l,            //  Result smallest difference with the input-array
      R[]=a;          //  Result-integer array
  for(;i-->0;)        //  Loop over the cells:
    b[y=i/l][i%l]=    //    Set `y` to the current cell's y-coordinate,
                      //    and fill this cell in the matrix with:
      y<2?            //     If this is the first or second row:
       y              //      Fill this cell with this 0 or 1 from `y`
      :               //     Else:
       i%l+2/y&1;     //      Fill it with `(x+2//y)%2` instead
                      //      (which is `x%2` for the third row
                      //       and `(x+1)%2` for the fourth row)
  for(var B:b){       //  Loop over the rows of the matrix:
    for(i=y=0;        //   Reset `y` to 0, and use it as sum
        i<l;)         //   Inner loop over the cells of the matrix
      y+=a[i]^B[i++]; //    Add the xor of the values at the same positions
                      //    of both the input array and current row to the sum
    if(y<r){          //   If the sum is smaller than the current smallest difference:
      r=y;            //    Set the sum as new smallest difference
      R=B;}}          //    Set the result-array `R` to the current row of the matrix
  return R;}          //  Return the resulting array with the smallest difference

```

**Example: Input-array `[0,1,0,1,0,1,1,0,1]`**

The first nested loop creates the following matrix, where the rows are the same length as the input:

```
[[0,0,0,0,0,0,0,0,0],
 [1,1,1,1,1,1,1,1,1],
 [0,1,0,1,0,1,0,1,0],
 [1,0,1,0,1,0,1,0,1]]

```

The second nested loops uses an XOR between each value at the same position in this row and the input-array, and sums that together:

```
[0^0 + 1^0 + 0^0 + 1^0 + 0^0 + 1^0 + 1^0 + 0^0 + 1^0 = 5,
 0^1 + 1^1 + 0^1 + 1^1 + 0^1 + 1^1 + 1^1 + 0^1 + 1^1 = 4,
 0^0 + 1^1 + 0^0 + 1^1 + 0^0 + 1^1 + 1^0 + 0^1 + 1^0 = 3,
 0^1 + 1^0 + 0^1 + 1^0 + 0^1 + 1^0 + 1^1 + 0^0 + 1^1 = 6]

```

And then it returns the row with the lowest XOR-sum, which is `[0,1,0,1,0,1,0,1,0]` (`3`) in this case.

# Answer
> 1 votes
# Coconut, 75 bytes

Port of my Python answer.

```
s->min(map(x->x*len(s),('1','0','10','01')),key=sum..map$((!=),s))[:len(s)]

```

Try it online!

# Answer
> 1 votes
# PHP, ~~117~~ 116 bytes

```
for(;~$f=$argn[$i++];${1}.=0,${0}.=1,${2}.=~$i&1,${3}.=$i&1,$d[2|$f^$i&1]++)$d[$f]++;echo${array_flip($d)[min($d)]};

```

Run as pipe with `-nR` or try it online.

# Answer
> 1 votes
# JavaScript (Node.js), 101 100 bytes

```
s=>[0,1,10,"01"].map(m=x=>[...t="".padEnd(s.length,x)].map((x,i)=>c+=x^s[i],c=0)&&m<c||(m=c,T=t))&&T

```

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~14~~ ~~13~~ 12 bytes

```
dāÈ‚D≠«Σ^O}н

```

Port of the approach I used in my Java answer.

Try it online or verify all test cases.

**Explanation:**

```
             # Create the list of 1s the same length as the input-list:
d            #  Check for each value in the (implicit) input-list if it's non-negative (≥0)
             # Create the list of alternating 0s/1s (starting at 0):
 ā           #  Push a list in the range [1, list-length) (without popping the list)
  È          #  Then check for each whether it's even (1 if even; 0 if odd)
   ‚         # Pair the two lists together
             # Create the list of 0s and list of alternating 1s/0s (starting at 1):
    D        #  Duplicate the pair of lists
     ≠       #  And invert each boolean by checking !=1
      «      # And then merge them together to have a list of four lists
       Σ     # Sort the list of lists by:
        ^    #  XOR the values of the current inner list and (implicit) input-list
             #  (at the same positions)
         O   #  And then sum it to get the amount of 1s
          }н # And after the sorting: only leave the first list (with the smallest sum)
             # (which is output implicitly as result)

```

# Answer
> 1 votes
# Jelly, 16 bytes

```
J1;Ḃ;¬$Ʋ€Z=³S$ÐṀ

```

Try it online!

Sort of similar to dylnan's answer, which I noticed afterwards, but I think the method is unique enough to warrant a separate answer.

# Explanation

```
J1;Ḃ;¬$Ʋ€Z=³S$ÐṀ  Main Link
J                 Range from 1 to len(z)
        €         For each element
       Ʋ
 1                1
  ;Ḃ              [1, k % 2]
    ¬$            Append the logical NOT of the list ([1, k%2, 0, !k%2])
         Z        Zip (basically, it generates a 4-long list per element, and then transposes it into the four lists)
              ÐṀ  Take the maximum element via
          =³S$    the number of matching elements (pairwise-equality into sum)

```

---
Tags: code-golf
---


title: Billiard balls collision

text:
# Question
Title: Billiard balls collision
Given the 2-dimensional positions and velocities of a pair of billiard balls right before impact, calculate their velocities after a perfectly elastic collision. The balls are assumed to be ideal spheres (or equivalently: circles) with the same radius, same mass, uniform density, and no friction.

Input consists of 8 numbers: `p0x,p0y,v0x,v0y,p1x,p1y,v1x,v1y` where `p0x,p0y` is the centre of the first ball, `v0x,v0y` its velocity, and similarly `p1x,p1y,v1x,v1y` for the second ball. You can accept input in any order and structured in any convenient way, e.g. as a 2x2x2 array, or maybe a 2x2 array for `p` and two length-2 arrays for `v0` and `v1`. It's also fine to take complex numbers (if your language supports them) instead of xy pairs. However, you should not take input in a coordinate system other than Cartesian, i.e. polar is not allowed.

Note that the radius of a billiard ball is half the distance between `p0x,p0y` and `p1x,p1y`, so it's not given as an explicit part of the input.

Write a program or function that outputs or returns 4 numbers in any convenient Cartesian representation: the post-collision values of `v0x,v0y,v1x,v1y`.

A possible algorithm is:

* find the *normal* line that passes through both centres
* find the *tangent* line that passes through the midpoint between the two centres and is perpendicular to the normal line
* change coordinate system and break down `v0x,v0y` and `v1x,v1y` into their tangential and normal components `v0t,v0n` and `v1t,v1n`
* swap the normal components of `v0` and `v1`, preserving their tangential components
* change back to the original coordinate system

Tests (results rounded to 5 decimal places):

```
   p0x   p0y   v0x   v0y   p1x   p1y   v1x   v1y ->      v0x'       v0y'       v1x'       v1y'
[-34.5,-81.8, 34.7,-76.1, 96.2,-25.2, 59.2,-93.3] [  49.05873, -69.88191,  44.84127, -99.51809]
[ 36.9, 77.7,-13.6,-80.8, -7.4, 34.4, 15.1,-71.8] [   5.57641, -62.05647,  -4.07641, -90.54353]
[-51.0, 17.6, 46.1,-80.1, 68.6, 54.0,-35.1,-73.9] [ -26.48927,-102.19239,  37.48927, -51.80761]
[-21.1,-52.6,-77.7, 91.5, 46.0, 94.1, 83.8, 93.7] [ -48.92598, 154.40834,  55.02598,  30.79166]
[ 91.3, -5.3, 72.6, 89.0, 97.8, 50.5, 36.2, 85.7] [  71.73343,  81.56080,  37.06657,  93.13920]
[-79.9, 54.9, 92.5,-40.7,-20.8,-46.9,-16.4, -0.9] [  47.76727,  36.35232,  28.33273, -77.95232]
[ 29.1, 80.7, 76.9,-85.1,-29.3,-49.5,-29.0,-13.0] [  86.08581, -64.62067, -38.18581, -33.47933]
[ 97.7,-89.0, 72.5, 12.4, 77.8,-88.2, 31.5,-34.0] [  33.42847,  13.97071,  70.57153, -35.57071]
[-22.2, 22.6,-61.3, 87.1, 67.0, 57.6,-15.3,-23.1] [ -58.90816,  88.03850, -17.69184, -24.03850]
[-95.4, 15.0,  5.3, 39.5,-54.7,-28.5, -0.7,  0.8] [  21.80656,  21.85786, -17.20656,  18.44214]
[ 84.0,-26.8,-98.6,-85.6,-90.1, 30.9,-48.1, 37.2] [ -89.76828, -88.52700, -56.93172,  40.12700]
[ 57.8, 90.4, 53.2,-74.1, 76.4,-94.4,-68.1,-69.3] [  51.50525, -57.26181, -66.40525, -86.13819]
[ 92.9, 69.8,-31.3, 72.6,-49.1,-78.8,-62.3,-81.6] [-123.11680, -23.48435,  29.51680,  14.48435]
[-10.3,-84.5,-93.5,-95.6, 35.0, 22.6, 44.8, 75.5] [ -11.12485,  99.15449, -37.57515,-119.25449]
[ -3.9, 55.8,-83.3,  9.1, -2.7,-95.6, 37.7,-47.8] [ -82.84144, -48.75541,  37.24144,  10.05541]
[-76.5,-88.4,-76.7,-49.9, 84.5, 38.0,  4.2, 18.4] [   6.52461,  15.43907, -79.02461, -46.93907]
[ 64.2,-19.3, 67.2, 45.4,-27.1,-28.7, 64.7, -4.3] [  59.66292,  44.62400,  72.23708,  -3.52400]
[  9.8, 70.7,-66.2, 63.0,-58.7, 59.5, 83.7,-10.6] [  68.07646,  84.95469, -50.57646, -32.55469]
[ 62.9, 46.4, 85.0, 87.4, 36.3,-29.0,-63.0,-56.3] [  23.53487, -86.82822,  -1.53487, 117.92822]
[ -5.5, 35.6, 17.6,-54.3, -2.2, 66.8,-15.2, 11.8] [  24.15112,   7.63786, -21.75112, -50.13786]

```

Shortest wins. No loopholes.

---

thanks @Anush for helping fix the diagram's background colour

# Answer
> 17 votes
# Python 3, ~~67~~ ~~66~~ bytes, 53 bytes

```
def f(p,v,q,w):p-=q;d=((v-w)/p).real*p;return v-d,w+d

```

Try it online!

*-1 byte thanks to @ngn*

*-13 bytes thanks to @Neil*

This function `f` takes four complex numbers as input and returns two complex numbers. The ungolfed version is shown in the following.

## Ungolfed

```
def elastic_collision_complex(p1, v1, p2, v2):
    p12 = p1 - p2
    d = ((v1 - v2) / p12).real * p12
    return v1 - d, v2 + d

```

Try it online!

The computation formula is derived based on the 2D-vector formula on wiki. Since \\$m\_1=m\_2\\$, the formula can be simplified to $$\left\\{\begin{array}{l} v\_1'=v\_1-dv \\ v\_2'=v\_2+dv\end{array}\right.$$

Let \\$x\_{12}=x\_1-x\_2\\$ and \\$v\_{12}=v\_1-v\_2\\$, we have

$$dv=\frac{\langle v\_{12}, x\_{12}\rangle}{\\|x\_{12}\\|^2}x\_{12} = \frac{Re(v\_{12}\cdot\overline{x\_{12}})}{x\_{12}\cdot \overline{x\_{12}}}x\_{12}=Re\left(\frac{v\_{12}\cdot\overline{x\_{12}}}{x\_{12}\cdot \overline{x\_{12}}}\right)x\_{12}=Re\left(\frac{v\_{12}}{x\_{12}}\right)x\_{12}$$

In the ungolfed program, `p12`, `v1 - v2`, `d` correspond to \\$x\_{12}\\$, \\$y\_{12}\\$, and \\$dv\\$, respectively.

# Answer
> 11 votes
# JavaScript (Node.js), ~~90~~ 88 bytes

```
(m,n,o,p,q,r,s,t,u=(q-=m)*q+(r-=n)*r,v=o*q+p*r-s*q-t*r)=>[o-(q*=v/u),p-(v*=r/u),s+q,t+v]

```

Try it online! Link includes test suite. Explanation: `q,r` are repurposed as the difference vector between the centres, and `u` is the square of its length. `v` is the difference in the dot products of `o,p` and `s,t` with `q,r`, so `v/u` is the scaling factor for `q,r` that gives the amount of velocity transferred from `o,p` to `s,t`. Edit: Saved 2 bytes thanks to @Arnauld.

# Answer
> 8 votes
# Perl 6, ~~75~~ ~~64~~ ~~63~~ 61 bytes

*11 bytes saved by switching from `map` to `for`, dispensing with the need to put things into intermediate variables for the `map` to see.*

*1 byte saved by changing `($^a-$^c)².&{$_/abs}` to `($^a-$^c).&{$_/.conj}`.*

*2 bytes saved thanks to @nwellnhof.*

```
{(.($^b+$^d,{$_/.conj}($^a-$^c)*($b-$d).conj)/2 for *-*,*+*)}

```

Try it online!

---

# Explanation

When the original post said that the input could be complex numbers, it was too hard to resist... So this takes 4 complex numbers (position 1, velocity 1, position 2, velocity 2) and returns the velocities as complex numbers.

The program uses just the same algorithm as described in the OP. However, with complex numbers, that is quite simple. First, let's notice that the complex number \\$d = p\_1 - p\_0\\$ points from the first ball to the second. So if we divide all the velocities by it, the normal direction suddenly coincides with the real axis and the tangent direction with the imaginary axis. (This messes up the magnitudes but we don't care.)

Now, we need to switch the normal (i. e. real) parts of the velocities \\$v\_0/d\\$ and \\$v\_1/d\\$, and after that, multiply it by \\$d\\$ again to make the normal (and the velocities) point in the correct direction (and to unmess the magnitudes). So we need to calculate $$ \begin{align\*} v\_0' &= d \left( \Re \frac{v\_1}{d} + \mathrm{i} \Im \frac{v\_0}{d} \right), \\ v\_1' &= d \left( \Re \frac{v\_0}{d} + \mathrm{i} \Im \frac{v\_1}{d} \right) \end{align\*} $$ (where \\$\Re\\$ = real part, \\$\Im\\$ = imaginary part). Let's shuffle the first one a bit (using \\$\star\\$ for complex conjugation): $$ v\_0' = d \left( \Re \frac{v\_1}{d} + \mathrm{i} \Im \frac{v\_0}{d} \right) = d \left\[ \frac 1 2 \left( \frac{v\_1}{d} + \frac{v\_1^\star}{d^\star} \right) + \frac 1 2 \left( \frac{v\_0}{d} - \frac{v\_0^\star}{d^\star} \right) \right\] =\ = \frac d 2 \left( \frac{v\_0 + v\_1}{d} - \frac{v\_0^\star - v\_1^\star}{d^\star} \right) = \frac 1 2 \left( v\_0 + v\_1 - \frac{d}{d^\star} (v\_0^\star - v\_1^\star) \right).$$ The result for \\$v\_1'\\$ can be obtained just by switching \\$v\_0 \leftrightarrow v\_1\\$. All that does is changing a sign: $$ v\_1' = \frac 1 2 \left\[ v\_0 + v\_1 + \frac{d}{d^\star} \left(v\_0^\star - v\_1^\star\right) \right\]. $$

And that's it. All the program does is just this calculation, golfed a bit.

# Answer
> 4 votes
# C (gcc), ~~140~~ 132 bytes

```
f(m,n,o,p,q,r,s,t,a)float*a,m,n,o,p,q,r,s,t;{q-=m;r-=n;m=q*q+r*r,n=o*q+p*r-s*q-t*r;q*=n/m;*a++=o-q;n*=r/m;*a++=p-n;*a++=s+q;*a=t+n;}

```

Try it online!

Basically a port of @Neil's JavaScript answer, but then @ceilingcat shaved off 8 bytes by cleverly reusing `m` and `n` to store temporaries.

# Answer
> 3 votes
# Python 2, ~~97~~ 92 bytes

```
m,n,o,p,q,r,s,t=input()
q-=m
r-=n
a=o*q+p*r-s*q-t*r
a/=q*q+r*r
print o-a*q,p-a*r,s+a*q,t+a*r

```

Try it online!

Modified version of Neil's approach.

# Answer
> 3 votes
# Jelly, 16 bytes

```
_/×ḋ÷²S¥_/ʋ¥N,$+

```

Try it online!

A dyadic link taking as its left argument a list of the initial positions `[[p0x, p0y], [p1x, p1y]]` and its right argument the initial velocities `[[v0x, v0y], [v1x, v2y]]`. Returns a list of the final velocities `[[v0x', v0y'], [v1x', v2y']]`

Based on the algorithm used by @Neil’s JavaScript answer so be sure to upvote that one too!

# Answer
> 2 votes
# C (gcc), ~~77~~ 72 bytes

```
f(p,v,q,w,a)_Complex*a,p,v,q,w;{p-=q;p*=creal((v-w)/p);*a=v-p;a[1]=w+p;}

```

Try it online!

Based on the python implementation of @Joel

# Answer
> 2 votes
# APL (Dyalog Classic), 21 bytes

```
⊢/-{,∘-⍨×/(9○÷⍨)\-⌿⍵}

```

Try it online!

based on @Joel's answer

in: 2x2 complex matrix, out: complex pair

---
Tags: code-golf, geometry, linear-algebra, physics
---


# Question
Title: Check the validity of a 10-digit telephone number
Your task is to write a program or function that checks if a string is a valid phone number.

Given a string (or list of characters/codepoints) input, you will output a truthy value if the input is a valid phone number. If it is not, output a falsey value. An input string is considered a valid phone number for this challenge if it meets all of these criteria:

* It contains ten digits, which are grouped like this: `###-###-####`
* The strings separating the digit groups must be the same
* The first and last characters must be part of the phone number (i.e. must not be part of a separator)

Test cases:

```
111-222-3333     truthy
123-456-7890     truthy (number groups can contain different numbers)
1112223333       truthy (can have 0 length separators)
111022203333     falsey (has more than 10 numbers)
111ABC222ABC3333 truthy (can have length>1 separators)
111-222_3333     falsey (non-matching separators)
111-22-23333     falsey (missing digit in middle group)
111--222--33333  falsey (extra digit in last group)
-111-222-3333    falsey (first character is not part of number)
111-222-3333a    falsey (last character is not part of number)
aaa-aaa-aaaa     falsey (not enough numbers)
11-2222-3333     falsey (wrong separator location)
111-1-222-1-3333 falsey (too many numbers)

```

This is a code golf challenge, shortest answer per language wins.

# Answer
> 4 votes
# APL (Dyalog Unicode), ~~30~~ 29 bytesSBCS

```
'^\d{3}(\D*)\d{3}\1\d{4}$'⎕S⍬

```

It simply `⎕S`earches for the PCRE regex and returns a dummy value (the empty numeric list) for each match. If none are found, it returns a single empty numeric list.

Try it online! The effect of printing a list of empty lists is to print two spaces on a line, while the effect of printing an empty list is to print an empty line. Select all contents in the Output field to reveal the spaces, or use this to lead each printed line with  and each space with `·`.

# Answer
> 4 votes
# Jelly, 22 bytes

```
fØDȯ0ṁ334DR¤jḟØDŒHḢƊµƑ

```

A monadic Link accepting a list of characters which yields `1` if it is a valid telephone number and `0` otherwise.

**Try it online!** Or see a test-suite.

### How?

```
fØDȯ0ṁ334DR¤jḟØDŒHḢƊµƑ - Link: list of characters, S  e.g. '123a456bc78de'
                     Ƒ - is S invariant under...
                    µ  - ...this function of S?:
f                      -   filter keep:
 ØD                    -     digit characters              '12345678'
   ȯ0                  -   OR zero (necessary as ṁ will error with an empty list)
           ¤           -   nilad followed by link(s) as a nilad:
      334              -     literal 334                   334
         D             -     to decimal                    [3,3,4]
          R            -     range (vectorises)            [[1,2,3],[1,2,3],[1,2,3,4]]
     ṁ                 -   mould (left) like (right)       ['123','456','7812']
                   Ɗ   -   last three links as a monad  - i.e. f(S):
             ḟ         -     filter discard:
              ØD       -       digit characters           'abcde'
                ŒH     -     split in halves              ['abc', 'de']
                  Ḣ    -     head (zero if empty)         'abc'
            j          -   join                           '123abc456abc7812'
                                                  (...not invariant as not equal to S)

```

# Answer
> 4 votes
# Perl, 36 bytes

```
print/^\d{3}(\D*)\d{3}\1\d{4}$/?1:0

```

Run as

```
perl -ne 'print/^\d{3}(\D*)\d{3}\1\d{4}$/?1:0' <<< "111-222-3333"

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 16 bytes

```
þ©м2äн®T∍ƵêS£sýQ

```

Port of *@JonathanAllan*'s Jelly answer.
Thanks to *@Grimy* for fixing a bug.

Try it online or verify all test cases.

**Explanation:**

```
þ                 # Only leave the digits of the (implicit) input-string
 ©                # Store it in variable `®` (without popping)
  м               # Remove all digits from the (implicit) input-string
   2ä             # Split the remaining characters into two equal-sized parts
     н            # And only leave the first part
      ®           # Push the digits from variable `®` again
       T∍         # Extend this string of digits to size 10
         Ƶê       # Push compressed integer 334
           S      # Converted to a list of digits: [3,3,4]
            £     # And split the digits of the input into parts of that size
             s    # Swap to get the earlier string
              ý   # And join the digit-parts with this delimiter-string
               Q  # Check if it's now equal to the (implicit) input-string
                  # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ƶê` is `334`.

# Answer
> 3 votes
# PHP, 50 bytes

Just a simple regex, with a backreference to make sure the separator is the same.

```
<?=preg_match('/^\d{3}(\D*)\d{3}\1\d{4}$/',$argn);

```

Try it online!

# Answer
> 2 votes
# JavaScript (ES6), 37 bytes

```
s=>/^\d{3}(\D*)\d{3}\1\d{4}$/.test(s)

```

Try it online!

# Answer
> 2 votes
# Gema, 26 characters

```
<D3><-d><D3>$2<D4>\Z=t
*=f

```

There is no truthy / falsey concept in Gema, so just outputting “t” / “f”.

Sample run:

```
bash-5.0$ echo -n 111-222-3333 | gema '<D3><-d><D3>$2<D4>\Z=t;*=f'
t

```

Try it online! / Try all test cases online!

# Answer
> 1 votes
# Python 3, ~~69~~ ~~66~~ 57 bytes

```
lambda n:re.match(r"\d{3}(\D*)\d{3}\1\d{4}$",n)
import re

```

Try it online!

Thanks To:
-@Arnauld and @Value Ink for saving me 3 bytes by using match instead of fullmatch
-@Value Ink for saving me another 6 bytes

# Answer
> 1 votes
# Ruby `-n`, 28 bytes

Same as basically every other regex solution here. Note that in Ruby, `0` is actually truthy. (Only `false` and `nil` are falsey in Ruby)

```
p~/^\d{3}(\D*)\d{3}\1\d{4}$/

```

Try it online!

# Answer
> 1 votes
# Red, 64 bytes

```
func[s][d: charset[#"0"-#"9"]parse s[3 d copy t to d 3 d t 4 d]]

```

Try it online!

As always Red's `parse` is much longer than regex.

# Answer
> 1 votes
# Java (JDK), 43 bytes

```
s->s.matches("\\d{3}(\\D*)\\d{3}\\1\\d{4}")

```

Try it online!

Apparently I came to the same solution as others: a simple regex is the key.

# Answer
> 0 votes
# QuadS, ~~28~~ 25 bytesSBCS

```
^\d{3}(\D*)\d{3}\1\d{4}$

```

It simply `⎕S`earches for the PCRE regex and returns a dummy value (the empty string) for each match. If none are found, it returns a single empty numeric list.

Try it online! The effect of printing a list of empty strings is to print two spaces on a line, while the effect of printing an empty list is to print an empty line. Select all contents in the Output field to reveal the spaces, or use this to lead the printed line with  and each space with `·`.

# Answer
> 0 votes
# Retina 0.8.2, 24

Same regex as the other regex-based answers:

```
^\d{3}(\D*)\d{3}\1\d{4}$

```

Try it online!

# Answer
> 0 votes
# Kotlin (JDK), 60 bytes

```
{s: String->s.matches(Regex("\\d{3}(\\D*)\\d{3}\\1\\d{4}"))}

```

Try it online!

Really similar to the Java one

# Answer
> 0 votes
# Clojure, 46 bytes

```
(fn[x](re-matches #"\d{3}(\D*)\d{3}\1\d{4}"x))

```

Try it online!

Another day, another regex.

# Answer
> 0 votes
# SimpleTemplate, 56 bytes

This was actually a very simple challenge, using XMark's RegEx in the PHP answer.

```
{@ifargv.0 is matches"@^\\d{3}(\\D*)\\d{3}\\1\\d{4}$@"}1

```

Sadly, due to the need to escape the slashes, this code is 5 bytes longer :/

This code outputs 1 in case the input matches (truthy), or nothing (falsy).

You can try the golfed and ungolfed versions in http://sandbox.onlinephpfunctions.com/code/ca206ad7cc82351283e6c319ce5f9ae03f87b695
You can also check the generated PHP code, if you are curious.

---
Tags: code-golf, string, decision-problem
---