# Question
Title: Minimal number of banknotes to pay a bill
Suppose denominations of banknotes follow the infinity Hyperinflation sequence: \\$ $1, $2, $5, $10, $20, $50, $100, $200, $500, $1000, $2000, $5000, \cdots \\$. How many banknotes are required, at minimum, to pay a \\$$n\\$ bill?

Consider Alice needs to pay \\$ $992 \\$ to Bob. It is possible for Alice to use 7 banknotes \\$ $500, $200, $200, $50, $20, $20, $2 \\$ to pay the bill, but that uses a lot of banknotes. We can see that a better solution is: Alice pays 2 banknotes (\\$ $1000, $2 \\$), and Bob gives her \\$ $10 \\$ in change. So, we only need 3 banknotes here.

## Formal Definition

Banknotes follow an infinite sequence \\$b\_i\\$: $$ b\_n=10\cdot b\_{n-3} $$ with base cases $$ b\_1=1, b\_2=2, b\_3=5 $$

When Alice pays \\$ $x \\$ to Bob, Alice pays \\$ a\_i \\$ banknotes with denominations \\$b\_i\\$. \\$ a\_i \in \mathbb{Z} \\$ And $$ \sum a\_ib\_i=x $$

\\$ a\_i \\$ may be negative which means Bob gives Alice these banknotes in change.

You are going to calculate: $$ f\left(x\right)=\min\_{\sum a\_ib\_i=x} \sum\left|a\_i\right| $$

## Input / Output

Input a non-negative number representing the amount of money to pay. Output the minimum number of banknotes required.

## Rules

* This is : Shortest codes in bytes win.
* Your program should be able to handle inputs \\$ 0 \le n \< 100{,}000 \\$ at least. Your algorithm should work for arbitrary large numbers in theory.
* As this questions is only focused on s, floating point errors are not allowed.

## Testcases

```
Input -> Output
    0 -> 0
    1 -> 1
    2 -> 1
    3 -> 2
    4 -> 2
    5 -> 1
    6 -> 2
    7 -> 2
    8 -> 2
    9 -> 2
   10 -> 1
   11 -> 2
   12 -> 2
   13 -> 3
   14 -> 3
   15 -> 2
   16 -> 3
   17 -> 3
   18 -> 2
   19 -> 2
   20 -> 1
   40 -> 2
   41 -> 3
   42 -> 3
   43 -> 3
   44 -> 3
   45 -> 2
   46 -> 3
   47 -> 3
   48 -> 2
   49 -> 2
   50 -> 1
   90 -> 2
   91 -> 3
   92 -> 3
   93 -> 3
   94 -> 3
   95 -> 2
   96 -> 3
   97 -> 3
   98 -> 2
   99 -> 2
  100 -> 1
  980 -> 2
  981 -> 3
  982 -> 3
  983 -> 4
  984 -> 4
  985 -> 3
  986 -> 4
  987 -> 4
  988 -> 3
  989 -> 3
  990 -> 2
  991 -> 3
  992 -> 3
  993 -> 3
  994 -> 3
  995 -> 2
  996 -> 3
  997 -> 3
  998 -> 2
  999 -> 2
 1000 -> 1
 1341 -> 6
 2531 -> 5
 3301 -> 5
 4624 -> 6
 5207 -> 4
 6389 -> 6
 6628 -> 7
 6933 -> 6
 7625 -> 6
 8899 -> 4
13307 -> 7
23790 -> 5
33160 -> 7
33325 -> 8
40799 -> 5
55641 -> 7
66472 -> 8
77825 -> 6
89869 -> 6
98023 -> 5

```

# Answer
# Python 2, ~~87~~ ~~80~~ 68 bytes

```
f=lambda x:x>1and min((y%10)**6%305%3+f(y/10*x/y)for y in[x,-x])or x

```

Try it online!

*-7 bytes thanks to @tsh, and -12 bytes thanks to @dingledooper. Thanks to everyone else for their own golf suggestions.*

Instead of tearing down the banknotes in the top-down way, this solution builds up the answer from the bottom. Since the number of banknotes needed to pay \\$10n\\$ is exactly the same as that for \\$n\\$, we can tear down the banknotes from the one's digit in the following sense:

* If the one's digit is 0, remove the 0 and recurse.
* Otherwise, consider two ways to fulfill the one's digit:

+ Alice pays `n%10` to Bob, and then Alice pays whatever banknotes are needed to pay `floor(n/10) * 10`. Recurse with `floor(n/10)`.
    + Bob pays `10-n%10` to Alice, and then Alice pays whatever banknotes are needed to pay `ceil(n/10) * 10`. Recurse with `ceil(n/10)`.

Then we can evaluate the two cases and take their minimum.

In the code, an infinite recursion happens if we don't special-case `x=1` as well as `x=0`, because the ceiling of `1/10` is still 1.
> 10 votes

# Answer
# Haskell, 87 bytes

```
a=0:1:drop 2(zipWith min("0112212222"!a)$"1222212211"!tail a)
s!l=[i+read[j]|i<-l,j<-s]

```

Try it online!

`a` is the whole infinite sequence.

This solution combines the fixed point approach of my answer to the previous challenge with Bubbler's excellent observation. ~~Coincidentally, his answer and mine also have the same exact length.~~
> 6 votes

# Answer
# Jelly, ~~28~~ 21 bytes

```
DJŻ⁵*×þ⁵ÆḌ¤ạ)F
ÇẠÐ¿L’

```

Takes input as singleton list. Try it online!

–7 per caird coinheringaahing.

Based on ref implementation; lists everything that's 1 away, then 2 away, etc. Adding a Q to the end of the first line makes it go slightly faster.

### How?

```
DJŻ⁵*×þ⁵ÆḌ¤ạ)F  - monadic link; takes integer array
            )   - for each integer
DJ              -   construct [1, ..., number of digits]
  Ż             -   prepend 0
   ⁵*           -   exponent with base 10 (vectorizes)
     ×þ         -   outer product with
       ⁵ÆḌ¤     -   proper divisors of 10; we get banknote
           ạ    -   absolute difference (vectorizes)
             F  - flatten

ÇẠÐ¿L’          - main link; takes integer array
  Ð¿            - while
 Ạ              - all integers nonzero,
Ç               - call previous link
    L'          - take length minus 1

```
> 6 votes

# Answer
# JavaScript (ES6),  ~~78~~  77 bytes

*Saved 1 byte thanks to @dingledooper*

This is heavily based on Bubbler's answer. Similarly to my answer to a previous challenge, it uses a formula instead of a lookup table.

```
f=n=>n<2?n:Math.min((g=(n,o)=>(n%10)**6%305%3+f(o/10|0))(n,n),g(10-n%10,n+9))

```

Try it online!
> 4 votes

# Answer
# , 98 bytes

```
f=function(a,b=a%%10,c=a%/%10,e=c(0,1,1,2,2,1,2,2:4))`if`(a<2,a,min(e[b+1]+f(c),rev(e)[b]+f(c+1)))

```

Try it online!
> 2 votes

# Answer
# Retina, 102 bytes

```
^
;$'¶_;
T`d`Rd`.+$
{%0`\d
*
([_;]*)(.*)¶([_;]*)
$1,$3_,$2¶$3,$1_,
+`;_(____|_|)
_;
%O`_*;
)`,.*,

\G_

```

Try it online! Link includes test cases. Explanation:

```
^
;$'¶_;
T`d`Rd`.+$

```

Create a working area with the following values: a) the number of notes used if Alice has not paid Bob enough yet; b) the amount Alice still needs to pay Bob; c) the number of notes used if Alice has overpaid and needs Bob to pay her back; d) the amount Bob still needs to pay back to Alice, minus 1.

```
{`
)`

```

Repeat until the full amount has been paid.

```
%0`\d
*

```

Convert the next digit of each outstanding amount to unary.

```
([_;]*)(.*)¶([_;]*)
$1,$3_,$2¶$3,$1_,

```

Calculate the two ways Alice can under or overpay Bob, depending on whether she under of overpaid Bob last time. If she underpaid last time, she can pay the current digit to remain underpaid, or one more to become overpaid, while if she overpaid last time, Bob can repay the complement to leave Alice overpaid, or one more to make her underpaid again.

```
+`;_(____|_|)
_;

```

Calculate the number of additional notes needed to pay each potential digit.

```
%O`_*;
,.*,

```

Delete the larger number of notes.

```
\G_

```

Convert the number of notes needed for (now exact) payment to decimal.
> 1 votes

# Answer
# JavaScript (Node.js), 80 bytes

```
n=>g=(i=n)=>Math.min(f(i)+f(i+n),i?g(i-1):n);f=n=>n&&(n%10)**29%3571%4+f(n/10|0)

```

Try it online!

I know there's better answer currently but this is what answer to last question directly lead to
> 0 votes

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


title: FIBonacci sequence

text:
# Question
Title: FIBonacci sequence
For this code golf, you will receive an input of a **fib**onacci sequence, that is, a normal Fibonacci sequence but with one number incorrect. <sub>See, the sequence is *fibbing*! Get it? `:D`</sub>

Your job is to find out which number is incorrect, and print the index (0-based) of that number.

For example:

```
Input : 1 1 2 9 5 8 13
Output: 3

Input : 8 13 21 34 55 80
Output: 5

Input : 2 3 5 5 13 21
Output: 3

```

Specifications:

* The sequence may start at any number.
* The first two numbers of the input will *always* be correct.
* Shortest code (character count) wins.

# Answer
## GolfScript (18 chars)

```
~]:^,,{^>3<~-+}?2+

```

The key to keeping this short is  (find).
> 15 votes

# Answer
## J, 30 23

```
(2+0 i.~2&}.=[:}:}:+}.)

```
> 5 votes

# Answer
## Golfscript, ~~31~~ ~~28~~ ~~26~~ ~~25~~ 23

```
~]-1%~1{)\3$3$-=}do])\;

```
> 5 votes

# Answer
## APL (19)

```
1+1⍳⍨(1↓1⌽k)≠2+/k←⎕

```

Explanation:

* `k←⎕`: store user input in `k`
* `2+/k`: sum each pair of elements in `k` (i.e. `1 1 2 3` -\> `1+1 1+2 2+3` -\> `2 3 5`)
* `1↓1⌽k`: rotate `k` to the right by 1 and then drop the first element (i.e. `1 1 2 3` -\> `2 3 1`)
* : find the place where these lists are not equal
* `1⍳⍨`: find the location of the first `1` in this list (location of the incorrect number)
* `1+`: add 1 to compensate for the dropped element
> 5 votes

# Answer
# K, 32

```
{2+*&~(n@n@x)=x+(n:{1_x,x 0})@x}

```
> 4 votes

# Answer
# dc, 36 32

```
?zszsasb[lalbdsa+dsb=x]dsxxlzz-p

```

`dc` is a reverse-Polish calculator, so obviously you need to input the numbers in reverse order ;)

```
$ dc fib.dc <<< "999 13 8 5 3 2 1 1"
7
$ dc fib.dc <<< "999 1 1"
2

```
> 4 votes

# Answer
## JavaScript, 70

```
for(n=prompt().split(' '),i=n.length;i---2;)if(n[i-2]- -n[i-1]!=n[i])i

```
> 3 votes

# Answer
# Javascript (69 68 61 60 55)

```
for(s=prompt(i=2).split(' ');s[i]-s[i-1]==s[i-2];i++);i

```

---

(60)

```
s=prompt(i=2).split(' ');for(;s[i]==+s[i-1]+ +s[i++-2];);--i

```

---

(61)
```
s=prompt(i=1).split(' ');for(k=+s[1];k+=+s[i-1],k==s[++i];);i

```

---

(68)

```
s=prompt(i=1).split(' ');for(k=+s[1];k+=+s[i-1],k==s[++i];);alert(i)

```

---

(69)

```
s=prompt(i=1).split(' ');k=+s[1];for(;k+=+s[i-1],k==s[++i];);alert(i)

```
> 3 votes

# Answer
# Awk: 55

```
{for(i=3;i<=NF;i++)if($i+$(i-1)!=$(i+1)){print i;exit}}

```
> 3 votes

# Answer
# Ruby, 66

My first attempt at an (somewhat) complicated Ruby program:

```
p gets.split.map(&:to_i).each_cons(3).find_index{|a,b,c|a+b!=c}+2

```
> 2 votes

# Answer
# Python, 74

```
a=map(int,raw_input().split())
i=2
while a[i-2]+a[i-1]==a[i]:i+=1
print i

```

I had this solution first, but Doorknob answered the question about the format of input *right* before I had time to post it:

# Python, 66

```
a,b=input(),input()
i=2
while input()==a+b:a,b=b,a+b;i+=1
print i

```

Assumes newline separated input.
> 1 votes

# Answer
**VB.net (77)**

Assuming the numbers are already in a IEnumerable(Of Integer).

```
 Dim p = xs.Skip(2).TakeWhile(Function(c, i) c = xs.Skip(i).Take(2).Sum).Count + 2

```
> 1 votes

# Answer
# Matlab / Octave, 39 bytes

*Thanks to Stewie Griffin for saving a byte! (`-` instread of `~=`)*

```
@(x)find(diff(x(2:end))-x(1:end-2),1)+1

```

This is an anonymous function that inputs an array and outputs a number.

**Try it online!**
> 1 votes

# Answer
# JS, 52B

```
for(s=prompt(i=2).split` `;s[i]-s[i-1]==s[i++-2];);i

```
> 1 votes

# Answer
# Kotlin, 77 bytes

```
{val r=it.split(' ').map{it.toInt()}
var i=2
while(r[i]==r[i-1]+r[i-2])i++
i}

```

## Beautified

```
{
    val r = it.split(' ').map { it.toInt() }
    var i=2
    while(r[i] == r[i-1] + r[i-2]) i++
    i
}

```

## Test

```
var f:(String)->Int =
{val r=it.split(' ').map{it.toInt()}
var i=2
while(r[i]==r[i-1]+r[i-2])i++
i}

data class Test(val input: String, val output: Int)

val TESTS = listOf(
        Test("1 1 2 9 5 8 13", 3),
        Test("8 13 21 34 55 80", 5),
        Test("2 3 5 5 13 21", 3)
)
fun main(args: Array<String>) {
    val fails = TESTS
        .asSequence()
        .map { it to f(it.input) }
        .filter { (test, res) -> test.output != res }
        .toList()

    if (fails.isEmpty()) {
        println("Test Passed")
    } else {
        fails.forEach{ println(it)}
    }
}

```
> 1 votes

# Answer
# Raku, 45 bytes

```
{first :k,?*,(@($/=.words)Z-($0,$1,*+*...*))}

```

Try it online!

`$/ = .words` stores the words (numbers) of the input string into the pattern-match variable `$/`. Conveniently, the elements of that variable can be accessed with `$0`, `$1`, etc, so `$0, $1, * + * ... *` forms the Fibonacci sequence starting with the first two input numbers. The input numbers and the Fibonacci sequence are then zipped together using the subtraction operator (`Z-`), forming a new sequence which is nonzero only at the place where the two series are different. Then `first :k, ?*, ...` returns the index (thanks to the `:k` parameter) of that location; `?*` is an anonymous predicate function that coerces its argument to a boolean value.
> 1 votes

# Answer
## Python (90)

```
a=map(int,raw_input().split())
print min(i for i in range(2,len(a))if a[i-2]+a[i-1]!=a[i])

```
> 0 votes

# Answer
# Mathematica 59

Because space-delimited input is required, `StringSplit` needs to be employed. The following assumes that the input is in the form of a string `i`.

```
s = StringSplit@i;
p = 3; While[s[[p - 1]] + s[[p - 2]] == s[[p]], p++]; p - 1

```
> 0 votes

# Answer
# Haskell, 48

```
f l=length$fst$span id$zipWith(==)l$1:scanl(+)1l

```
> 0 votes

# Answer
# Jelly, 11 bytes

```
ÆḞ€i$€In1i1

```

Try it online!
> 0 votes

# Answer
# QBIC, 31 bytes

```
_!_!{_!~a+b=c|a=b┘b=c┘s=s+1\_Xs

```

## Explanation

```
_!_!           Ask the user for two umbers, assign them to 'a' and 'b'
{              DO
 _!            Ask for a third number (this will be assigned to 'c' on every iteration)
 ~a+b=c        IF the previous two terms add up to the third
 |a=b          THEN shift b into a,
   ┘b=c            and c into b
   ┘s=s+1          increment s (starts as 3 in QBIC)
 \_Xs          ELSE quit, printing the step counter

```

I'm not quite sure if this is allowed; the sequence is entered one term at a time, and the program aborts on error, not after entering the entire sequence.
> 0 votes

# Answer
# Pxem, 0 bytes (content) + 52 bytes (filename).

* Filename (escaped): `\002._._X.w.c.t.v.m.v.+._.c.t.v.m.v.-\001.r.x.n.d.a\001.+.vX.a`

## Usage

* From stdin
* Must be an actual FIBonacci sequence
* Each integer are separated with blank characters

## With comments

```
XX.z
# Initial stack: F(i-1), F(i-2), i
# i is initially 2
.a\002._._XX.z
# while :; do
.aX.wXX.z
  # to: (F(i-1)+F(i-2)), i, F(i-1)
  .a.c.t.v.m.v.+XX.z
  # input is F(i)
  # to: F(i), (F(i-1)+F(i-2)), i, F(i-1), F(i)
  .a._.c.t.v.m.vXX.z
  # to 0, abs(F(i)-F(i-1)-F(i-2)), i, F(i-1), F(i)
  # if (pop!=pop); then
  .a.-\001.r.xXX.z
    # print pop; exit; fi
    .a.n.d.aXX.z
  # to F(i), F(i-1), (i+1)
  .a\001.+.vXX.z
# done
.aX.a

```

Try it online!
> 0 votes

# Answer
# Husk, 5 bytes

```
δV≠İf

```

Try it online!

You know it's a good day when you get to use `decorV` in an answer.
> 0 votes

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


title: Is the writer a man or woman?

text:
# Question
Title: Is the writer a man or woman?
One problem on a website like this is that you often don't know if you are talking to a male or female. However, you have come up with a simple NLP technique you can use to determine the gender of the writer of a piece of text.

# Theory

About 38.1% of letters used in English are vowels **\[a,e,i,o,u\]** (see References below, `y` is NOT a vowel in this case). Therefore, we will define any word that is at least 40% vowels as a *feminine word*, and any word that is less than 40% vowels as a *masculine word*.

Beyond this definition we can also find the *masculinity* or *femininity* of a word. Let *C* be the number of consonants in the word, and *V* be the number of vowels:

* If a word is feminine, it's femininity is `1.5*V/(C+1)`.
* If a word is masculine, it's masculinity is `C/(1.5*V+1)`.

For example, the word `catch` is masculine. Its masculinity is `4/(1.5*1+1) = 1.6`. The word `phone` is feminine. Its femininity is `1.5*2/(3+1) = .75`.

# Algorithm

To figure out the gender of the writer of a piece of text, we take the sum of the masculinity of all the masculine words (ΣM), and the sum of the femininity of all the feminine words (ΣF). If ΣM \> ΣF, we have determined that the writer is a male. Otherwise, we have determined that the writer is a female.

# Confidence Level

Finally, we need a confidence level. If you have determined that the writer is female, your confidence level is `2*Σ<sub>F</sub>/(Σ<sub>F</sub><sub>M</sub>)-1`. If you have determined that the writer is male, the confidence level is `2*Σ<sub>M</sub>/(Σ<sub>F</sub><sub>M</sub>)-1`.

# Input

Input is a piece of English text including punctuation. Words are all separated by spaces (You don't have to worry about new-lines or extra spaces). Some words have non-letter characters in them, which you need to ignore (such as "You're"). If you encounter a word that is all non-letters (like "5" or "!!!") just ignore it. Every input will contain at least one usable word.

# Output

You need to output an M or F depending on which gender you think the writer is, followed by your confidence level.

# Examples

1. `There's a snake in my boot.`

* Gender + masculinity/femininity of each word: `[M1.0,F1.5,F.75,F.75,M2.0,F1.0]`
    * ΣM = 3.0, ΣF = 4.0
    * CL: `2*4.0/(4.0+3.0)-1` = .143
    * Output: `F .143`
2. `Frankly, I don't give a ^$*.`

* `[M2.4,F1.5,M1.2,F1.0,F1.5]`, ΣM = 3.6, ΣF = 4.0, CL: `2*4.0/(4.0+3.6)-1` = .053, Output: `F .053`
3. `I'm 50 dollars from my goal!`

* `[F.75,M1.25,M1.2,M2.0,F1.0]`, ΣM = 4.45, ΣF = 1.75, CL: `2*4.45/(4.45+1.75)-1` = .435, Output: `M .435`

# References

1. Percentage of vowels in English dictionary words (38.1%)
2. Percentage of vowels in English texts (38.15%)

# Answer
# Python 3, ~~320~~ ~~317~~ ~~307~~ ~~286~~ ~~253~~ 189 bytes

```
h=S=0
for v in input().split():V=sum(map(v.count,'aeiouAEIOU'));C=sum(x.isalpha()for x in v);H=V<.4*C;C-=V;K=[1.5*V/(C+1),C/(1.5*V+1)][H];h+=K*H;S+=K-K*H
print('FM'[h>S],2*max(S,h)/(S+h)-1)

```

Try it online!

**Ungolfed**:

```
def evaluateWord(s):
    V = len([*filter(lambda c: c in 'aeiou', s.lower())])
    C = len([*filter(lambda c: c in 'bcdfghjklmnpqrstvxzwy', s.lower())])
    isMasculine = V < 0.4*(V+C)
    return C/(1.5*V+1) if isMasculine else 1.5*V/(C+1), isMasculine

def evaluatePhrase(s):
    scores = []
    for word in s.split():
        scores.append(evaluateWord(word))
    masc = 0
    fem = 0
    for score in scores:
        if score[1]:
            masc += score[0]
        else:
            fem += score[0]
    return ('M', 2*masc/(fem+masc)-1) if masc > fem else ('F', 2*fem/(fem+masc)-1)

print(evaluatePhrase("There's a snake in my boot."))

```
> 5 votes

# Answer
# Ruby `-ap`, ~~154~~ 140 bytes

`-ap` loops over input and splits on spaces, storing the result in `$F`, then outputs `$_` after the program finishes.

```
m=f=0
$F.map{s=_1.upcase.gsub(/[^A-Z]/){}
k=s.size-v=s.count('AEIOU')
k>v*1.5?m+=k/(1.5*v+1):f+=1.5*v/-~k}
$_=m>f ??M:?F,2*[m,f].max/(m+f)-1

```

Attempt This Online!
> 4 votes

# Answer
# Python 3, ~~205 201 197~~ 192 bytes

-Thanks @Value Ink for 4 bytes: `lower()` beforehand
-Thanks @Coty Johnathan Saxman for 9 bytes: Inverted condition `.4*(v+c)>v` and `-~c` for `(c+1)` bitshift-based consonant check instead of literal.

# Python 3, 192 bytes

```
M=F=0
for i in input().lower().split():
 v=sum(j in'aeiou'for j in i);c=sum(33021815<<98>>ord(k)&1for k in i)
 if.4*(v+c)>v:M+=c/(1.5*v+1)
 else:F-=1.5*v/~c
print('FM'[M>F],2*max(M,F)/(F+M)-1)

```

Try it online!
> 4 votes

# Answer
# C (gcc), ~~237~~ ~~229~~ ~~222~~ 216 bytes

Boy I though I could do this in a LOT LESS BYTES...

```
v,c;float m,f;g(char*s){for(m=f=0;*s;v*1.0/(c+v)<.4?m+=c/(1.5*v+1):1?f+=1.5*v/(c+1):0,s+=*s!=0)for(v=c=0;*s&&*s^32;s++)isalpha(*s)?strchr("AaEeIiOoUu",*s)?++v:++c:0;printf("%c %.3f",m>f?77:70,(m>f?2*m:2*f)/(f+m)-1);}

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 61 bytes

```
ð¡εálžNžM‚δÃ€g©`3;*‚Â>/®¤sO/.4@©è®‚}0š.¡θ}€€нODZk„MFèsZ·sO/<‚

```

Try it online or verify all test cases.

**Explanation:**

Step 1: Split the input into words, and get the amount of consonants and vowels of each word:

```
ð¡               # Split the (implicit) input-string by spaces
                 # (NOTE: builtin `#` doesn't work if the input is just a single word)
  ε              # Map over each word:
   á             #  Only leave its letters (removing any punctuation)
    l            #  And convert it to lowercase
     žN          #  Push the lowercase consonants: "bcdfghjklmnpqrstvwxyz"
       žM‚       #  Pair it with the vowels: ["bcdfghjklmnpqrstvwxyz","aeiou"]
          δ      #  Map over both using the lowercase word:
           Ã     #   And only keep those characters
            €    #  Then map over the pair:
             g   #   And get the length of each
                 #  (we now have a pair [amount_of_consonants,amount_of_vowels],
                 #   let's call these [C,V] like in the challenge description)
              ©  #  Store this pair in variable `®` (without popping)

```

Try step one online.

Step 2: Apply the formulas: \\$\left\[\frac{C}{1.5V+1},\frac{1.5V}{C+1}\right\]\\$

```
   `             #  Pop and push both values separated to the stack
    3;*          #  Multiply V by 1.5 (3 halved)
       ‚         #  And pair it back together with C
        Â        #  Bifurcate; short for Duplicate & Reverse copy
         >       #  Increase both values in the reversed duplicate by 1
          /      #  Divide the pairs at the same positions:
                 #   [C/(V*1.5+1),V*1.5/(C+1)]

```

Try the first two steps online.

Step 3: Check if the word was feminine or masculine by checking if the amount of vowels is at least 40%:

```
   ®             #  Push the pair from variable `®` again
    ¤            #  Push its last item (without popping the pair): V
     s           #  Swap so the pair it at the top of the stack again
      O          #  Sum them together: C+V
       /         #  Divide them: V/(C+V)
        .4@      #  Check if this is larger than or equal to 0.4
                 #  (1 if >=0.4; 0 if <0.4)
           ©     #  Store this boolean as new `®` (without popping)
            è    #  0-based index it into the [C/(V*1.5+1),V*1.5/(C+1)]-pair
             ®‚  #  And pair it together with boolean `®`
  }              # Close the map

```

Try the first three steps online.

Step 4: Group all masculine and feminine values together:

```
   0š            # Prepend a 0 to the list of pairs
                 # (this is to ensure the first group are the falsey/masculine pairs;
                 #  and the second group the truthy/feminine pairs)
     .¡          # Group the pairs (and the leading 0) by:
       θ         #  Their last item, which is the boolean
      }€         # After the group-by, map over each group:
        €        #  Map over each inner pair:
         н       #   And only leave the first item

```

Try the first four steps online.

Step 5: Get the sums of both groups, and check if the masculine or feminine sum is larger:

```
O                # Take the sum of each inner group
 D               # Duplicate this pair of sums
  Z              # Get the maximum (without popping the pair itself)
   k             # Get the index of this maximum in the pair (0 or 1)
    „MFè         # Index it into the string "MF"

```

Try the first five steps online.

Step 6: Apply the confidence formula: \\$\frac{2\max\left(\sum{F},\sum{M}\right)}{\sum{F}+\sum{M}}-1\\$

```
        s        # Swap so the duplicated pair of sums is at the top again
         Z       # Get the maximum again (without popping)
          ·      # Double this maximum
           s     # Swap so the pair is at the top of the stack again
            O    # Sum them together
             /   # Divide the doubled maximum by this sum
              <  # Decrease it by 1

```

Try the first six steps online.

Step 7: And finally pair the two results together, and output it as result:

```
               ‚ # And pair it together with the "M"/"F"
                 # (after which the result is output implicitly)

```
> 2 votes

# Answer
# JavaScript, ~~336~~ ~~328~~ ~~297~~ ~~286~~ ~~278~~ ~~276~~ 260 bytes

```
t=>['FM'[+(g=((m=(r=s=>t.split` `.map(c=>[p=(v=(c=[...c][u='filter'](a=>/[a-zA-Z]/.test(a)))[u](a=>/[aeiouAEIOU]/.test(a)).length)>=(q=c.length)*.4?0:1,p?(q-v)/(1.5*v+1):1.5*v/(q-v+1)])[u](e=>e[0]==s).reduce((a,c)=>a+c[1],0))(1))>(f=r(0))))],2*(g?m:f)/(f+m)-1]

```

This took me a really long time to golf but it still is 260 bytes long.

*-8 bytes thanks to my own efforts: removed `return` statement and curly braces*

*-31 bytes thanks to my own efforts: replaced long alphabet string literal inclusion test with regular expression test: why did I not think of that before. Code is also becoming more and more unreadable as time goes by.*

*-11 bytes thanks to my own efforts: come to think of it, why not replace the other `includes` as well?*

*-8 bytes thanks to my own efforts: noticed similarity between possible confidence levels and refactored*

*-2 bytes thanks to my own efforts: new `q` variable set to `c[h]` used multiple times.*

*day 2 of golfing super-long answer: -16 bytes thanks to my own efforts*

Ungolfed:

```
function determine(text) {
    let words = text.split(' ');
    words = words.map(cur => {
        cur = [...cur].filter(a=>"abcdefghijklmnopqrstuvwxyz".includes(a.toLowerCase())).join``;
        let vowels = [...cur].filter(a=>"aeiou".includes(a.toLowerCase())).length;
        let output = [vowels>=cur.length/2.5?'f':'m'];
        output.push(output[0]=='m'?(cur.length-vowels)/(1.5*vowels+1):1.5*vowels/(cur.length-vowels+1));
        return output;
    });
    let femi = words.filter(e=>e[0]=='f').reduce((a,c)=>a+c[1],0);
    let masc = words.filter(e=>e[0]=='m').reduce((a,c)=>a+c[1],0);
    let gender = (masc>femi?'m':'f');
    let confidence = (gender=='f'?2*femi/(femi+masc)-1:2*masc/(femi+masc)-1);
    console.log(gender , confidence);
}

```
> 2 votes

# Answer
# Common Lisp, 404 bytes

```
(defun f(x &aux(a 0)c(f 0)m v u)(labels((w(x &aux(p(position #\  x)))(cons(#1=subseq x 0 p)(and p(w(#1#x(1+ p)))))))(dolist(e(w(coerce x'list)))(setf v(#2=count-if(lambda(x)(member x(coerce"aeiouAEIOU"'list)))e)u(#2#'alpha-char-p e)c(- u v)m(and(> c 0)(<(/ v c)4/6)))(and(> u 0)(if m(incf a(/ c(1+(* v 3/2))))(incf f(/ v 2/3(1+ c))))))(format t"~:[F~;M~] ~4f~%"(> a f)(-(/(* 2(if(> a f)a f))(+ a f))1))))

```

Good old verbose lisp!

Try it online!

Ungolfed version:

```
(defun f(x &aux (a 0) c (f 0) m v u)        ; parameter & auxiliary variables
  (labels ((w (x &aux (p (position #\  x))) ; recursive function to split input into words
              (cons (subseq x 0 p) (and p (w (subseq x (1+ p)))))))
    (dolist (e (w (coerce x 'list)))        ; for each word
      (setf v (count-if (lambda (x) (member x(coerce"aeiouAEIOU"'list))) e) ; count vowels
            u (count-if 'alpha-char-p e)    ; count all alfabetic letters
            c (- u v)                       ; calculate consonants
            m (and (> c 0) (< (/ v c) 4/6))); is male or not?
      (and (> u 0)                          ; if non-empty word
           (if m
               (incf a (/ c (1+ (* v 3/2)))); increase masculinity
               (incf f (/ v 2/3 (1+ c)))))) ; increase femininity
    (format t "~:[F~;M~] ~4f"               ; print
              (> a f)                       ; “gender”
              (-(/ (* 2 (if (> a f)a f)) (+ a f)) 1))))  ; and confidence

```
> 1 votes

# Answer
# Raku, 147 bytes

```
{{"{<M F>[[<] $_]} {2*.max/.sum-1}"}(@([Z+] map {my \v=1.5*.comb(rx:i/<[aeiou]>/);my \c=.comb(/<:L>/)-2*v/3;(c>v)*c/(v+1),(v>=c)*v/(c+1)},.words))}

```

Try it online!
> 1 votes

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


# Question
Title: Exciting Mario Kart Grand Prix - Minimize the point difference!
# Introduction

When playing Mario Kart the other day, an interesting question popped up when a Grand Prix with my 2 roommates, 9 AI drivers and myself seemed to be fairly close and therefore exciting until the very end.

We asked ourselves: How close can the point difference between first and last place (#1 and #12) after exactly N races be?

This Code Golf challenge occured to me after the underlying problem for the distribution of the minimum difference in points was answered here by user *mlk*.

# Challenge

Mario Kart races consist of 12 racers which in every race receive the points represented in this 1-indexed array: `[15, 12, 10, 8, 7, 6, 5, 4, 3, 2, 1, 0]`.

In a Grand Prix, the points for each driver from every of the N races are simply added up to form the final point distribution. The difference between the lowest and the highest number of points in this final point distribution is called *point difference* (alas between places #1 and #12).

Your task is to write a program which takes as input the number of races N (`1 <= N <= 32`) and outputs the corresponding point difference.

The first 13 correct inputs and outputs can be found below. You will find that after the special cases `N = 1` and `N = 2`, the correct answer will be `0` if `N` is divisible by 12 and `1`if not.

# Example Input and Output

As the desired output is correctly defined for every natural number, here are the input/output examples until the repeating pattern described above begins:

```
1 -> 15
2 -> 4
3 -> 1
4 -> 1
5 -> 1
6 -> 1
7 -> 1
8 -> 1
9 -> 1
10 -> 1
11 -> 1
12 -> 0
13 -> 1

```

# Goal

This is Code Golf, so shortest answer in bytes wins!

Standard loopholes apply.

# Answer
> 16 votes
# JavaScript (ES7), 19 bytes

```
n=>14/n**n+1^n%12<1

```

Try it online!

We compute:

$$\left\lfloor\frac{14}{n^n}+1\right\rfloor$$

which is \\$\lfloor 14/1+1\rfloor=15\\$ for \\$n=1\\$, \\$\lfloor 14/4+1 \rfloor=4\\$ for \\$n=2\\$, or \\$1\\$ for \\$n\>2\\$.

We then XOR the result with \\$1\\$ if \\$n \bmod 12=0\\$.

# Answer
> 6 votes
# Python 3, 28 bytes

```
lambda x:max(26-x*11,x%12>0)

```

Try it online!

-4 bytes thanks to ovs

If the boolean output is invalid (in Python, `True == 1` and `False == 0`), add `+` before the `max` to turn it into an int.

# Answer
> 4 votes
# Vyxal, 11 bytes

```
12Ḋ⌐₄?11*-∴

```

Try it online!

Port of hyper-neutrino's Python answer

## How it works

```
12Ḋ⌐₄?11*-∴ - Program. N is on the stack
12Ḋ         - Is N divisible by 12, 12 | N?
   ⌐        - Logical NOT
    ₄?11    - Push 26, N, 11
        *   - Yield 11×N
         -  - Yield 26 - 11×N
          ∴ - Maximum of (26 - 11 × N) and ¬(12 | N)

```

# Answer
> 3 votes
# Vim, ~~29~~ 28 bytes

*Thanks to @kops for -1 byte.*

```
C<C-r>=ma<S-Tab>[!!(<C-r>"%12),26-11*<C-r>"])

```

Try it online!

Vim port of @hyper-neutrino's python answer. In TIO, I couldn't figure out how to make `Shift`+`Tab` work, so it is 29 bytes there, but in Vim, you can use `Shift`+`Tab` to autocomplete `max(`, which is 1 less byte.

# Answer
> 2 votes
# Jelly, ~~14~~ ~~12~~ 11 bytes

```
%12a*`14:‘Ʋ

```

Try it online!

This used hyper-neutrino's method and now uses a version of Arnauld's, so be sure to give them an upvote!

A direct translation of Arnauld's answer also comes out to 11 bytes:

```
*`14:‘_12ḍ$

```

Try it online!

## How they work

```
%12a*`14:‘Ʋ - Main link. Takes N on the left
%12         - N % 12
          Ʋ - Previous 4 links as a dyad f(N):
    *`      -   N to the power N
      14:   -   Floor divide 14 by that
         ‘  -   Increment
   a        - If N % 12 is non-zero, replace it by f(N)

```

```
*`14:‘_12ḍ$ - Main link. Takes N on the left
*`          - Raise N to its own power
  14:       - Floor divide 14 by N to the N
     ‘      - Increment it
          $ - Previous 2 links as a monad f(N):
       12ḍ  -   Is N divisible by 12?
      _     - Subtract f(N) from the incremented division

```

# Answer
> 2 votes
# PowerShell 7, 34 bytes

```
param($n)$n-1?$n-2?1-!($n%12):4:15

```

No TIO because PS7 (and so the ternary operator) is not supported.

# Answer
> 2 votes
# Python 3, 35 bytes

```
lambda x:x<3and 26-x*11or x%12and 1

```

Try it online!

-3 bytes thanks to hyper-neutrino
-1 byte thanks to ophact

# Answer
> 2 votes
# 05AB1E, 11 bytes

A port of hyper-neutrino's answer.

```
«₂s-I12Ö_‚à

```

Try it online! (No, `END` does not actually end the program.)

**Commented:**

```
«            # concatenate the input with itself
             # this is the same as multiplying by 11 for small integers
 ₂s-         # subtract this from 26
    I        # push the input again
     12Ö_    # does 12 divide not divide the input? Booleans are represented as 0 and 1.
         ‚   # pair both values
          à  # take the maximum

```

Constructing the infinite list and indexing into it takes 12 bytes:

```
₄;16вλèN12Ö_

```

Try it online!

# Answer
> 2 votes
# Snap!, 6 blocks

straightforward implementation of the question, self explanatory

# Answer
> 1 votes
# JavaScript, 27 bytes

```
n=>n<3?[,15,4][n]:+!!(n%12)

```

bet you that I will get more upvotes on this answer than on some of my more complex ones.

*-6 thanks to @CommandMaster*

# Answer
> 1 votes
# MMIX, 32 bytes (8 instrs)

jxd

```
00000000: 1dff000c feff0006 7b01ff01 31ff0001  ø”¡€“”¡©{¢”¢1”¡¢
00000010: 6301ff0f 31ff0002 6301ff04 f8020000  c¢”Đ1”¡£c¢”¥ẏ£¡¡

```

Disassembly:

```
pdif    DIV  $255,$0,12
        GET  $255,rR        // t = n % 12
        ZSNZ $1,$255,1      // i = (bool)t
        CMP  $255,$0,1
        CSZ  $1,$255,15     // if(n == 1) i = 15
        CMP  $255,$0,2
        CSZ  $1,$255,4      // if(n == 2) i = 4
        POP  2,0            // return i

```

Straight-line code!

# Answer
> 1 votes
# Husk, 15 bytes

```
!:15:4↓2J0C11∞1

```

Try it online!

The caveman approach: manually create the infinite list and index into it.

## Explanation

```
!:15:4↓2J0C11∞1
             ∞1  infinite list of 1s
          C11    cut in pieces of 11
        J0       join with zeroes
      ↓2         drop 2 elements
    :4           prepend 4
 :15             prepend 15
!                index into it

```

# Answer
> 1 votes
# Vyxal, 15 bytes

```
12Ḋ⌐₄?11*-?2≤e*

```

Try it Online!

```
12Ḋ       # Is the input divisible by 12
⌐         # Negate that. So stack contains 0 for numbers divisible by 12 and 1 otherwise
₄?11*-    # 26-11*n
?2≤e      # Is the input less than equal to 2?
e         # Take exponent
*         # Multiply the two numbers in the stack and print the result.

```

# Answer
> 1 votes
# Whispers v2, 79 bytes

```
> Input
> 26
> 11
> 12
> 1
>> 3⋅1
>> 2-6
>> 1∣4
>> 5-8
>> 7»9
>> Output 10

```

Try it online!

Same formula as my other answers, implemented in the verbosity of Whispers

# Answer
> 1 votes
# PowerShell, 38 bytes

```
$args|%{26-$_*11;+!!($_%12)}|sort -b 1

```

Try it online!

# Answer
> 1 votes
# Python 2, 25 bytes

```
lambda x:2/x*7/x+(x%12>0)

```

Try it online!

# Answer
> 0 votes
# Retina 0.8.2, 36 bytes

```
.+
$*_
^(_{12})+$
0
___+
1
__
4
_
15

```

Try it online! Link includes test suite that outputs the answers from `1` to `N`. Explanation:

```
.+
$*_

```

Convert `N` to unary.

```
^(_{12})+$
0

```

The result is `0` if `N` is a multiple of `12`, ...

```
___+
1

```

... `1` if `N>2`, ...

```
__
4

```

... `4` if `N=2`, ...

```
_
15

```

... and `15` if `N=1`.

# Answer
> 0 votes
# Charcoal, 15 bytes

```
Ｉ⌈⟦‹⁰﹪Ｎ¹²⁻²⁶×²θ

```

Try it online! Link is to verbose version of code. Explanation: Port of @ovs's 05AB1E answer.

```
      Ｎ         Input as a number
     ﹪ ¹²       Modulo 12
   ‹⁰           Is greater than 0
              θ Input as a string
            ×²  Duplicated i.e. multiplied by 11
         ⁻²⁶    Subtracted from 26
  ⟦             Pair into a list
 ⌈              Take the maximum
Ｉ               Cast to string
                Implicitly print

```

# Answer
> 0 votes
# Zsh, 27 bytes

Boring ternary math function.

```
()(($1<3?26-11*$1:$1%12>0))

```

Try it online!

---

## Zsh `--cbases`, 29 bytes

```
k=e3
<<<$[0x$k[$1]+!!($1%12)]

```

Try it online!

More interesting, using hexadecimal `0xe` and `0x3` to add 14 and 3 to the first two cases.

# Answer
> 0 votes
# C (gcc), 27 bytes

```
f(n){n=n<3?26-n*11:n%12>0;}

```

Try it online!

# Answer
> 0 votes
# Lua, 52 bytes

```
function f(n)return 14/n^n+1|((n%12<1)and 1 or 0)end

```

Try it online!

---
Tags: code-golf, math, number, arithmetic
---


title: CDGLF: TMN to APL

text:
# Question
Title: CDGLF: TMN to APL
In this challenge you will remove one of my least favorite features, operator precedence from traditional math notation, to acheive the syntax of one of my favorite languages, APL. The APL subset we will be working with includes only a few functions and single digit numbers. (No arrays!)

## Here is the grammar of the input

(in pegjs notation, with `/` representing disjunction and `[]` representing a set of possible characters. If you would like to test it out and validate inputs/outputs you can go to https://pegjs.org/online and paste it in the grammar textbox)

```
Expr = Addition;
Addition = Multiplication [+-] Addition / Multiplication;
Multiplication = Power [*/] Multiplication / Power;
Power = Floor '^' Expr / Floor;
Floor = '[' Expr ']' / '{' Expr '}' / Paren;
Paren = '(' Expr ')' / Digit;
Digit = [0-9];

```
* In descending order of precedence, the infix operators are `^` (exponentiation), `*` or `/`, and `+` or `-`.
* All the operators are left-associative except for `^`. (`0-1-2` is `(0-1)-2` but `0^1^2` is `0^(1^2)`)
* There are no prefix operators.

## And the output format:

```
Expr = Multiplication / Addition / Power / Floor;
Multiplication = Floor [*/] Expr;
Addition = Floor [+-] Expr;
Power = Floor '^' Expr;
Floor = '[' Expr / '{' Expr / Paren;
Paren = '(' Expr ')' / [0-9];

```
* `{` and `[` are prefix and don't need a closing `]` or `}`.
* All operators, prefix *and* infix, have the same precedence.
* All operators are right-associative, so `0o1o2` is the same as `0o(1o2)` for any infix operator `o`.
* The infix operators are `+-*/^` (`^` is for exponentiation, and `*` and `/` are for multiplication and division respectively), and the prefix operators are `{` and `[`, which represent floor and ceiling respectively.

Note that these don't handle whitespace or negation and your program doesn't have to either.

## Task

You are to take an `Expr` in the input format, assumed to be valid, and output an equivalent expression (`Expr`) in the APL-like output format. In this case, equivalent means structurally, so `9` is not a valid output for the input of `3*3`. More specifically, the string that is outputted should have an `Expr` node where the input had an `Expr`, an `Addition` node where the input had `Addition`, etc. with the exception that in the output where an `Expr` node would be placed there may instead be a `Paren` node (this rule is recursive).

## Examples:

These are not necessarily the only answers. Any amount of parentheses are allowed in the output.

```
input        output
1+1          1+1
2*2+1        (2*2)+1
3-5/2+1      (3-(5/2))+1
3-5/(2+1)    3-5/2+1
2*{2+1}      2*{2+1
5^4+1        (5^4)+1
{2+1}+1      ({2+1)+1
3^2^2        3^2^2
(3^2)^2      (3^2)^2

```

---

This is , shortest code per language wins. Your function or program takes a string from arguments or stdin and outputs through return or stdout etc. etc.

# Answer
# Factor, 187 bytes

```
: c ( x -- y ) concat "("")"surround ;
EBNF: A [=[
p=p("*"|"/")e=>[[c]]|e
e=f"^"e=>[[c]]|f
f=("["|"{")s("]"|"}")=>[[2 head c]]|"("s")"=>[[c]]|[0-9]=>[[1string]]
s=s("+"|"-")p=>[[c]]|p
]=]

```

~~Try it online!~~ Does not work on TIO, but works on 0.98 stable.

Defines a named function `A` which takes a string, parses it, and returns an equivalent expression string in the output format.

Test:

```
{ "1+1" "2*2+1" "3-5/2+1" "3-5/(2+1)" "2*{2+1}"
  "5^4+1" "{2+1}+1" "3^2^2" "(3^2)^2" } [ A print ] each

```

Output:

```
(1+1)
((2*2)+1)
((3-(5/2))+1)
(3-(5/(((2+1)))))
(2*({(2+1)))
((5^4)+1)
(({(2+1))+1)
(3^(2^2))
((((3^2)))^2)

```

Since any number of parentheses are allowed, it is easiest to ignore the operator associativity of APL and parenthesize every single parsed node.

Factor comes with a PEG parser with EBNF syntax `peg.ebnf`. The grammar nodes `s`, `p`, `e`, and `f` stand for "sum", "product", "exp", and "floor" respectively. The last line is recognized as the "main" grammar, so I moved `s` to the last line.

It does support character classes like `[+-]`, but it is converted to a single character (= integer), not a string, so it is more complicated to post-process. So I decided to simply use disjunction on string literals instead (except for digits).

`=> [[ Factor code ]]` defines how to post-process the grammar. For most of the nodes, it is simply "concatenate all parts and wrap in a pair of parens", which is defined as a named function `c` and reused throughout the code. For floor and ceiling, we only need to keep the opening `{[` and the body, thus `2 head c`.
> 3 votes

---
Tags: code-golf, string, parsing, compiler
---


title: Reverse and Invert a String

text:
# Question
Title: Reverse and Invert a String
# Reverse and Invert a String

## Challenge

In this challenge. You'll be writing a program which will output or return the input, reversed and inverted.

First, each character should be converted to its character code. Then, that should be converted to base-2. Following, that string should be reversed. After, the string should be inverted (1 -\> 0 and 0 -\> 1). Finally, that should be converted back to base 2 and then converted back to a character. If an character results to be an unprintable, you may optionally output it but they do not have to be removed.

```
H -> 72  -> 1001000 -> 0001001 -> 1110110 -> 118 -> v
e -> 101 -> 1100101 -> 1010011 -> 0101100 -> 44  -> ,
l -> 108 -> 1101100 -> 0011011 -> 1100100 -> 100 -> d
l -> 108 -> 1101100 -> 0011011 -> 1100100 -> 100 -> d
o -> 111 -> 1101111 -> 1111011 -> 0000100 -> 4   -> (unprintable)
, -> 44  -> 101100  -> 001101  -> 110010  -> 50  -> 2
  -> 32  -> 100000  -> 000001  -> 111110  -> 62  -> >
W -> 87  -> 1010111 -> 1110101 -> 0001010 -> 10  -> (newline)
o -> 111 -> 1101111 -> 1111011 -> 0000100 -> 4   -> (unprintable)
r -> 114 -> 1110010 -> 0100111 -> 1011000 -> 88  -> X
l -> 108 -> 1101100 -> 0011011 -> 1100100 -> 100 -> d
d -> 100 -> 1100100 -> 0010011 -> 1101100 -> 108 -> l
! -> 33  -> 100001  -> 100001  -> 011110  -> 30  -> (unprintable)

```

## Scoring

Shortest code in bytes wins.

**-15% Bonus:** if your program removes un-printables from the output. This must be *at least* all characters below 32 except newlines (char 10)

# Answer
> 4 votes
# CJam, 14

```
q{i2bW%:!2bc}%

```

Try it online

**Explanation:**

Pretty straightforward:

```
q       read input
{…}%    convert each character
  i     convert to number
  2b    convert to base 2 (digit array)
  W%    reverse
  :!    invert each digit
  2b    convert from base 2
  c     convert to character

```

### "Printable" version, 20 - 15% = 17

```
q{i2bW%:!2bc' ,N--}%

```

# Answer
> 9 votes
# Pyth, 14 bytes

```
smCi!M_jCd2 2z

```

Try it online.

### How it works

```
 m           z  Map over the input with lambda d:
        Cd        Cast d to character.
       j  2       Convert to base 2.
      _           Reverse the resulting array.
    !M            Mapped logical NOT.
   i        2     Convert back to integer.
  C               Cast to character.
s               Concatenate the resulting characters.

```

# Answer
> 8 votes
# Perl, ~~57~~ 51 characters

(50 characters code + 1 character command-line option.)

```
s/./$_=unpack b8,$&;s|0+$||;"chr 0b".y|10|01|r/gee

```

Sample run:

```
bash-4.3$ perl -pe 's/./$_=unpack b8,$&;s|0+$||;"chr 0b".y|10|01|r/gee' <<< 'Hello, World!'
v,dd2>
Xdl

bash-4.3$ perl -pe 's/./$_=unpack b8,$&;s|0+$||;"chr 0b".y|10|01|r/gee' <<< 'Hello, World!' | od -tad1
0000000    v    ,    d    d  eot    2    >   nl  eot    X    d    l   rs   nl
         118   44  100  100    4   50   62   10    4   88  100  108   30   10
0000016

```

# Answer
> 7 votes
# JavaScript (~~ES6~~ ES7), ~~119~~ ~~114~~ 108 bytes

This turned out way longer than expected :(

Thanks to @vihan for 5 bytes saved! Thanks to @ETHProductions for another 6 bytes saved!

**To test:** Run the snippet below, enter input like `"Hello, World!"`, and click *Test!*

```
x=>String.fromCharCode(...[for(y of x)+('0b'+[...y.charCodeAt().toString(2)].reverse().map(z=>z^1).join``)])
```

```
<!--                               Try the test suite below!                              --><strong id="bytecount" style="display:inline; font-size:32px; font-family:Helvetica"></strong><strong id="bytediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><br><pre style="margin:0">Code:</pre><textarea id="textbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><pre style="margin:0">Input:</pre><textarea id="inputbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><button id="testbtn">Test!</button><button id="resetbtn">Reset</button><br><p><strong id="origheader" style="font-family:Helvetica; display:none">Original Code Output:</strong><p><div id="origoutput" style="margin-left:15px"></div><p><strong id="newheader" style="font-family:Helvetica; display:none">New Code Output:</strong><p><div id="newoutput" style="margin-left:15px"></div><script type="text/javascript" id="golfsnippet">var bytecount=document.getElementById("bytecount");var bytediff=document.getElementById("bytediff");var textbox=document.getElementById("textbox");var inputbox=document.getElementById("inputbox");var testbtn=document.getElementById("testbtn");var resetbtn=document.getElementById("resetbtn");var origheader=document.getElementById("origheader");var newheader=document.getElementById("newheader");var origoutput=document.getElementById("origoutput");var newoutput=document.getElementById("newoutput");textbox.style.width=inputbox.style.width=window.innerWidth-50+"px";var _originalCode=null;function getOriginalCode(){if(_originalCode!=null)return _originalCode;var allScripts=document.getElementsByTagName("script");for(var i=0;i<allScripts.length;i++){var script=allScripts[i];if(script.id!="golfsnippet"){originalCode=script.textContent.trim();return originalCode}}}function getNewCode(){return textbox.value.trim()}function getInput(){try{var inputText=inputbox.value.trim();var input=eval("["+inputText+"]");return input}catch(e){return null}}function setTextbox(s){textbox.value=s;onTextboxChange()}function setOutput(output,s){output.innerHTML=s}function addOutput(output,data){output.innerHTML+='<pre style="background-color:'+(data.type=="err"?"lightcoral":"lightgray")+'">'+escape(data.content)+"</pre>"}function getByteCount(s){return(new Blob([s],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"})).size}function onTextboxChange(){var newLength=getByteCount(getNewCode());var oldLength=getByteCount(getOriginalCode());bytecount.innerHTML=newLength+" bytes";var diff=newLength-oldLength;if(diff>0){bytediff.innerHTML="(+"+diff+")";bytediff.style.color="lightcoral"}else if(diff<0){bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgreen"}else{bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgray"}}function onTestBtn(evt){origheader.style.display="inline";newheader.style.display="inline";setOutput(newoutput,"");setOutput(origoutput,"");var input=getInput();if(input===null){addOutput(origoutput,{type:"err",content:"Input is malformed. Using no input."});addOutput(newoutput,{type:"err",content:"Input is malformed. Using no input."});input=[]}doInterpret(getNewCode(),input,function(data){addOutput(newoutput,data)});doInterpret(getOriginalCode(),input,function(data){addOutput(origoutput,data)});evt.stopPropagation();return false}function onResetBtn(evt){setTextbox(getOriginalCode());origheader.style.display="none";newheader.style.display="none";setOutput(origoutput,"");setOutput(newoutput,"")}function escape(s){return s.toString().replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}window.alert=function(){};window.prompt=function(){};function doInterpret(code,input,cb){var workerCode=interpret.toString()+";function stdout(s){ self.postMessage( {'type': 'out', 'content': s} ); }"+" function stderr(s){ self.postMessage( {'type': 'err', 'content': s} ); }"+" function kill(){ self.close(); }"+" self.addEventListener('message', function(msg){ interpret(msg.data.code, msg.data.input); });";var interpreter=new Worker(URL.createObjectURL(new Blob([workerCode])));interpreter.addEventListener("message",function(msg){cb(msg.data)});interpreter.postMessage({"code":code,"input":input});setTimeout(function(){interpreter.terminate()},1E4)}setTimeout(function(){getOriginalCode();textbox.addEventListener("input",onTextboxChange);testbtn.addEventListener("click",onTestBtn);resetbtn.addEventListener("click",onResetBtn);setTextbox(getOriginalCode())},100);function interpret(code,input){window={};alert=function(s){stdout(s)};window.alert=alert;console.log=alert;prompt=function(s){if(input.length<1)stderr("not enough input");else{var nextInput=input[0];input=input.slice(1);return nextInput.toString()}};window.prompt=prompt;(function(){try{var evalResult=eval(code);if(typeof evalResult=="function"){var callResult=evalResult.apply(this,input);if(typeof callResult!="undefined")stdout(callResult)}}catch(e){stderr(e.message)}})()};</script>
```

# Answer
> 5 votes
# JavaScript (ES7), 126 bytes - 15% = 107.1

I was playing around with this answer to see if the bonus was worth it. Apparently, it is. The test suite was stolen from the same answer, but I added my own twist: full support of the 15% bonus! :)

```
x=>String.fromCharCode(...[for(y of x)if((c=+('0b'+[...y.charCodeAt().toString(2)].reverse().map(z=>z^1).join``))>31|c==10)c])
```

```
<!--                               Try the test suite below!                              --><strong id="bytecount" style="display:inline; font-size:32px; font-family:Helvetica"></strong><strong id="bytediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><strong id="score" style="display:inline; font-size:32px; font-family:Helvetica">Score:</strong><strong id="scorediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><br><pre style="margin:0">Code:</pre><textarea id="textbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><pre style="margin:0">Input:</pre><textarea id="inputbox" style="margin-top:5px; margin-bottom:5px">"Hello, World!"</textarea><br><button id="testbtn">Test!</button><button id="resetbtn">Reset</button><br><p><strong id="origheader" style="font-family:Helvetica; display:none">Original Code Output:</strong><p><div id="origoutput" style="margin-left:15px"></div><p><strong id="newheader" style="font-family:Helvetica; display:none">New Code Output:</strong><p><div id="newoutput" style="margin-left:15px"></div><script type="text/javascript" id="golfsnippet">var bytecount=document.getElementById("bytecount");var bytediff=document.getElementById("bytediff");var score=document.getElementById("score");var scorediff=document.getElementById("scorediff");var textbox=document.getElementById("textbox");var inputbox=document.getElementById("inputbox");var testbtn=document.getElementById("testbtn");var resetbtn=document.getElementById("resetbtn");var origheader=document.getElementById("origheader");var newheader=document.getElementById("newheader");var origoutput=document.getElementById("origoutput");var newoutput=document.getElementById("newoutput");textbox.style.width=inputbox.style.width=window.innerWidth-50+"px";var _originalCode=null;function getOriginalCode(){if(_originalCode!=null)return _originalCode;var allScripts=document.getElementsByTagName("script");for(var i=0;i<allScripts.length;i++){var script=allScripts[i];if(script.id!="golfsnippet"){originalCode=script.textContent.trim();return originalCode}}}function getNewCode(){return textbox.value.trim()}function getInput(){try{var inputText=inputbox.value.trim();var input=eval("["+inputText+"]");return input}catch(e){return null}}function setTextbox(s){textbox.value=s;onTextboxChange()}function setOutput(output,s){output.innerHTML=s}function addOutput(output,data){output.innerHTML+='<pre style="background-color:'+(data.type=="err"?"lightcoral":"lightgray")+'">'+escape(data.content)+"</pre>"}function getByteCount(s){return(new Blob([s],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"})).size}function getScore(s){var a=1;try{b=eval('('+s+')("Hello, World!")');if(b=="v,dd2>\nXdl")a=.85}catch(e){};return getByteCount(s)*a}function onTextboxChange(){var newLength=getByteCount(getNewCode());var oldLength=getByteCount(getOriginalCode());bytecount.innerHTML=newLength+" bytes";var diff=newLength-oldLength;if(diff>0){bytediff.innerHTML="(+"+diff+")";bytediff.style.color="lightcoral"}else if(diff<0){bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgreen"}else{bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgray"}newLength=getScore(getNewCode());var oldLength=getScore(getOriginalCode());score.innerHTML="Score: "+newLength;var diff=Math.round((newLength-oldLength)*100)/100;if(diff>0){scorediff.innerHTML="(+"+diff+")";scorediff.style.color="lightcoral"}else if(diff<0){scorediff.innerHTML="("+diff+")";scorediff.style.color="lightgreen"}else{scorediff.innerHTML="("+diff+")";scorediff.style.color="lightgray"}}function onTestBtn(evt){origheader.style.display="inline";newheader.style.display="inline";setOutput(newoutput,"");setOutput(origoutput,"");var input=getInput();if(input===null){addOutput(origoutput,{type:"err",content:"Input is malformed. Using no input."});addOutput(newoutput,{type:"err",content:"Input is malformed. Using no input."});input=[]}doInterpret(getNewCode(),input,function(data){addOutput(newoutput,data)});doInterpret(getOriginalCode(),input,function(data){addOutput(origoutput,data)});evt.stopPropagation();return false}function onResetBtn(evt){setTextbox(getOriginalCode());origheader.style.display="none";newheader.style.display="none";setOutput(origoutput,"");setOutput(newoutput,"")}function escape(s){return s.toString().replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}window.alert=function(){};window.prompt=function(){};function doInterpret(code,input,cb){var workerCode=interpret.toString()+";function stdout(s){ self.postMessage( {'type': 'out', 'content': s} ); }"+" function stderr(s){ self.postMessage( {'type': 'err', 'content': s} ); }"+" function kill(){ self.close(); }"+" self.addEventListener('message', function(msg){ interpret(msg.data.code, msg.data.input); });";var interpreter=new Worker(URL.createObjectURL(new Blob([workerCode])));interpreter.addEventListener("message",function(msg){cb(msg.data)});interpreter.postMessage({"code":code,"input":input});setTimeout(function(){interpreter.terminate()},1E4)}setTimeout(function(){getOriginalCode();textbox.addEventListener("input",onTextboxChange);testbtn.addEventListener("click",onTestBtn);resetbtn.addEventListener("click",onResetBtn);setTextbox(getOriginalCode())},100);function interpret(code,input){window={};alert=function(s){stdout(s)};window.alert=alert;console.log=alert;prompt=function(s){if(input.length<1)stderr("not enough input");else{var nextInput=input[0];input=input.slice(1);return nextInput.toString()}};window.prompt=prompt;(function(){try{var evalResult=eval(code);if(typeof evalResult=="function"){var callResult=evalResult.apply(this,input);if(typeof callResult!="undefined")stdout(callResult)}}catch(e){stderr(e.message)}})()};</script>
```

# Answer
> 4 votes
# C function, 63

```
o;f(o,char *s){for(;*s;*s=o,s++)for(o=0;*s;*s/=2)o+=o+!(*s%2);}

```

# Answer
> 4 votes
## PHP - 187 182 163 bytes

```
<?php $s=$_GET["s"];$m="array_map";echo join($m("chr",$m("bindec",$m(function($v){return strtr($v,[1,0]);},$m("strrev",$m("decbin",$m("ord",str_split($s))))))));?>

```

Pass the value as `GET["s"]`.

array\_map returns an array with all the elements of the second parameter (an array) after applying the callback function (first parameter) to all of them.

Not sure if I should take the 15% off, since `echo` doesn't output unprintable characters, but I didn't remove them.

Just glad I finished, since this is the first challenge I take part.

# Answer
> 3 votes
# Julia, 77 bytes - 15% = 65.45

```
s->join(filter(isprint,[Char(parse(Int,join(1-digits(Int(c),2)),2))for c=s]))

```

This creates an unnamed functon that accepts a string and returns a string. Unprintable characters are removed, which qualifies this for the bonus.

Ungolfed:

```
function f(s::AbstractString)
    # digits() returns the digits in reverse order, so no explicit
    # reverse() is needed
    x = [Char(parse(Int, join(1 - digits(Int(c), 2)), 2)) for c = s]

    # Remove unprintables, join into a string
    return join(filter(isprint, x))
end

```

# Answer
> 3 votes
# K5, 28 bytes

```
`c${b/~|{x@&|\x}@(b:8#2)\x}'

```

This is a bit inconvenient because K5's `decode` operator performs a fixed-width base conversion, so to comply with the problem statement I have to trim leading zeroes. The lambda `{x@&|\x}` accomplishes this step.

Smear:

```
  |\0 0 1 0 1 1 0 1
0 0 1 1 1 1 1 1

```

Gather:

```
  &|\0 0 1 0 1 1 0 1
2 3 4 5 6 7

```

Select:

```
  {x@&|\x}0 0 1 0 1 1 0 1
1 0 1 1 0 1

```

The whole program in action:

```
  `c${b/~|{x@&|\x}@(b:8#2)\x}'"Hello, World"
"v,dd2>\nXdl"

```

I believe oK's natural behavior with unprintables makes this eligible for -15%, giving this a score of 28\*0.85 = **23.8**.

# Answer
> 3 votes
## PowerShell, ~~199 175~~ (171 - 15%)=145.35

```
param([char[]]$a)($a|%{$b=[convert]::ToString(+$_,2);$c=[convert]::ToInt32("$((-join$b[$b.Length..0])-split0-replace1,0-join1)",2);if($c-gt31-or$c-eq10){[char]$c}})-join''

```

Uses ~~an unfortunate amount of~~ some .NET calls/built-ins, which ~~significantly~~ bloats the code.

### Explained:

Takes the input `param(..)` and casts it as a `char[]` so we can work through it appropriately.

The next bit `(..)-join''` collects and joins our output together.

Inside those parens, we iterate with `$a|%{..}` as a foreach loop.

Inside the loop:

* We create a new string `$b`, which is our input letter cast as an int `+$_` and `[convert]`ed to base `2`
* This next bit, setting `$c`, is tricky, so let's start inside and work our way out
* We reverse the string `$b` with `(-join$b[$b.length..0])`
* We leverage my previous code for inverting a binary string and recast the result as a string with `"$(..)"`
* We feed that string into a different .NET call that `[convert]`s `ToInt32` from base `2`, which is finally stored that into `$c`
* If `$c` is greater than `31`, or equal to `10`, we cast it as a char and that value is left on the pipeline for output (which is what gets collected and `-join''`ed together, above), else nothing gets left on this particular iteration

Phew.

Qualifies for the -15% bonus, as well.

### Example

```
PS C:\Tools\Scripts\golfing> .\reverse-and-invert-a-string.ps1 "Hello, World!"
v,dd2>
Xdl

```

# Answer
> 2 votes
# , 39 chars / 73 bytes

```
ô⟦ï]ć⇝ϚĎ(+“0b`+⟦a.ü⬮ß§2]ù⬮ć⇀$^1)ø`”⸩ø⬯⦆

```

`Try it here (Firefox only).`

# Answer
> 2 votes
# Vyxal `K`, 5 bytes

```
bR†vB

```

Try it Online!

epic.

-2 bytes from Lyxal.

-1 byte from Lyxal.

# Answer
> 1 votes
## Minkolang 0.11, 26 bytes

```
od?.(d2%,$r2:d)xrI1-[2*+]O

```

Try it here.

### Explanation

```
od?.            Takes input as character, halting if empty
(d2%,$r2:d)x    Converts to binary, inverting digits on the way
r               Reverses stack
I1-[2*+]        Converts to decimal
O               Outputs as character (if printable)

```

# Answer
> 1 votes
# MATLAB, 60 bytes

```
@(y)[arrayfun(@(x)bin2dec([97-fliplr(dec2bin(x)) '']),y) '']

```

Basically each character in turn is converted into a binary string (with no leading zeros). The array is flipped and is subtracted from 97 ('0'+'1') which inverts the character. This is converted back to decimal. After all characters have been processed, the whole array is then converted back to characters before being returned.

# Answer
> 1 votes
# Japt, 25 bytes

Want to create a golfy JavaScript program, but the shortest method involves lots of long function names? That's what Japt was made for. :)

```
UmX=>Xc s2 w mY=>Y^1 n2 d

```

Try it in the online interpreter!

### How it works

```
         // Implicit: U = first item in input
UmX=>    // for each character X in U:
Xc s2 w  //  take the char-code of X, convert to binary, and reverse
mY=>     //  for each character Y in this:
Y^1      //   take Y XOR 1 (converts 1 to 0 and 0 to 1)
n2 d     //  convert the result back to decimal, then to a character
         // Implicit: output last expression

```

---

Using the current version of Japt (as of v1.4.4), the byte count can be cut to 14:

```
®c ¤w m^1 n2 d

```

Test it online!

# Answer
> 1 votes
# Python 3, 95 91

Straightforward implementation.

```
print(''.join(chr(int(''.join('10'[j>'0']for j in bin(ord(i))[:1:-1]),2))for i in input()))

```

Ungolfed:

```
inp = input()
ints = (ord(i) for i in inp)
bins = (bin(i) for i in ints)
revs = (i[2:][::-1] for i in bins) #without leading '0b'
invs = (''.join('0' if j == '1' else '1' for j in i) for i in revs)
newInts = (int(i, 2) for i in invs)
newChars = (chr(i) for i in newInts)
newStr = ''.join(newChars)
print(newStr)

```

# Answer
> 1 votes
# Ruby, 62 characters

```
gets.bytes{|b|$><<b.to_s(2).reverse.tr("01","10").to_i(2).chr}

```

Samply run:

```
bash-4.3$ ruby -e 'gets.bytes{|b|$><<b.to_s(2).reverse.tr("01","10").to_i(2).chr}' <<< 'Hello, World!'
v,dd2>
Xdl

bash-4.3$ ruby -e 'gets.bytes{|b|$><<b.to_s(2).reverse.tr("01","10").to_i(2).chr}' <<< 'Hello, World!' | od -tad1
0000000    v    ,    d    d  eot    2    >   nl  eot    X    d    l   rs   nl
         118   44  100  100    4   50   62   10    4   88  100  108   30   10
0000016

```

# Answer
> 1 votes
# Javascript 123 bytes

```
s=>[].map.call(s,s=>String.fromCharCode("0b"+s.charCodeAt().toString(2).split('').reverse().map(s=>s^1).join(''))).join('')

```

# Answer
> 1 votes
# C#, 156 bytes - 15% = 132.6

```
class P{static void Main(string[]a){try{for(int i=0,b,c;;){for(b=a[0][i++],c=0;b>0;b/=2)c=c<<1|1-b%2;if(c==10|c>31)System.Console.Write((char)c);}}catch{}}}

```

Indentation and new lines for clarity:

```
class P{
    static void Main(string[]a){
        try{
            for(int i=0,b,c;;){
                for(b=a[0][i++],c=0;b>0;b/=2)
                    c=c<<1|1-b%2;
                if(c==10|c>31)
                    System.Console.Write((char)c);
            }
        }
        catch{}
    }
}

```

# Answer
> 1 votes
# Retina, ~~1107~~ 629 bytes - 15% = 534.65 (non-competing)

*Uses features added after challenge date. (Implicit behavior of `$*`, , Sorting)*

Retina doesn't have a built-in to convert a character to its ASCII ordinal or back... so behold its lustrous length. This handles printable ASCII, and removes unprintables as well as newlines. Byte count assumes ISO 8859-1 encoding.

The code contains unprintable characters.

```

¶
±
S_`
%(S`±
{2`
$`
}T01`-`_o
)Ms`.
\d+
$*
+`(1+)\1
${1}0
01
1
%O$^`.

T`01`10
1
01
+`10
011
0

m`^1{1,31}$

M%`1
m`^0¶?

126
~
125
}
124
|
123
{
122
z
121
y
120
x
119
w
118
v
117
u
116
t
115
s
114
r
113
q
112
p
111
o
110
n
109
m
108
l
107
k
106
j
105
i
104
h
103
g
102
f
101
e
100
d
99
c
98
b
97
a
96
`
95
_
94
^
93
]
92
\
91
[
90
Z
89
Y
88
X
87
W
86
V
85
U
84
T
83
S
82
R
81
Q
80
P
79
O
78
N
77
M
76
L
75
K
74
J
73
I
72
H
71
G
70
F
69
E
68
D
67
C
66
B
65
A
64
@
63
?
62
>
61
=
60
<
59
;
58
:
57
9
56
8
55
7
54
6
32

33
!
34
"
35
#
36
$
37
%
38
&
39
'
40
(
41
)
42
*
43
+
44
,
45
-
46
.
47
/
48
0
49
1
50
2
51
3
52
4
53
5
¶

```

**Try it online**

If you check out the Retina tutorial for unary arithmetic, you'll recognize several different pieces of my code as coming from there.

*Thanks to Martin for golfing off hundred of bytes*

# Answer
> 1 votes
# Jelly, 6 bytes

```
OBU¬ḄỌ

```

Try it online!

Explanation:

```
OBU¬ḄỌ Main link: z
O      Convert z to a list of character codes.
 B     Convert the codes to bit lists.
  U    Reverse the bits (not the lists).
   ¬   Invert the bits.
    Ḅ  Convert back to decimal.
     Ọ Convert back to string.

```

# Answer
> 1 votes
# Java, 205 - 15% = 174.2

```
interface F{static void main(String[]a){for(int i=0,c,s;i<a[0].length();++i){c=a[0].charAt(i);s=Integer.numberOfLeadingZeros(c);c=~(Integer.reverse(c)>>s)&-1>>>s;if(c==10|c>31)System.out.print((char)c);}}}

```

Ungolfed:

```
interface F {
    static void main(String[] a) {
        for (int i = 0, c, s; i < a[0].length(); ++i) {
            c = a[0].charAt(i);
            s = Integer.numberOfLeadingZeros(c);
            c = ~(Integer.reverse(c) >> s) & -1 >>> s;
            if (c == 10 | c > 31) System.out.print((char)c);
        }
    }
}

```

I think this solution is a bit interesting in its use of the `Integer` methods `Integer.reverse` and `Integer.numberOfLeadingZeros` which do what they sound like, and the shift of `-1 >>> s` where `s` is the number of leading zeroes, to get the mask to mask off high bits that we don't want. I just regret that the name of the latter method is so damn verbose, but that's what I get for golfing in Java.

Output:

```
v,dd2>
Xdl

```

# Answer
> 1 votes
# PHP, 80 bytes

```
while(a&$c=$argn[$i++])echo chr(bindec(strtr(strrev(decbin(ord($c))),10,"01")));

```

takes input from STDIN; run with `-R`.

**bonus version, ~~97~~ 110 bytes -\> 93.5 score**

```
while(a&$c=$argn[$i++])ctype_print($c=chr(bindec(strtr(strrev(decbin(ord($c))),10,"01"))))||"
"==$c?print$c:0;

```

prints ASCII 10 and 32 to 126 (newline and printables)

---

breakdown, TiO and if possible some golfing will follow; I´m tired right now.

# Answer
> 1 votes
# Japt, 9 bytes

```
c_¤Ô®^1ÃÍ

```

Try it

# Answer
> 1 votes
# Husk, 9 bytes

```
m(cḋm¬↔ḋc

```

Try it online!

# Answer
> 1 votes
# Factor, ~~50~~ ~~46~~ 41 bytes

```
[ [ >bin reverse 97 v-n vneg bin> ] map ]

```

Try it online!

*-4 bytes thanks to @Bubbler!* *-5 bytes thanks to @Bubbler!*

Even though removing control characters is just `[ control? ] reject` it's not worth the 15% discount.

* `[ ... ] map` Map over the code points in the input string.
* `>bin` Convert a code point to a binary string.
* `reverse` Reverse it.
* `97 v-n vneg` Invert the string (1s become 0s and vice-versa).
* `bin>` Convert from a binary string to decimal.

# Answer
> 0 votes
# Haskell, 167 bytes

```
import Data.Char
import Numeric
r '0'='1'
r '1'='0'
s=map (chr.fst.head.(readInt 2 (`elem` "01") digitToInt).(map r).reverse.flip (showIntAtBase 2 intToDigit . ord)"")

```

Unfortunately Haskell gets quite verbose when needing to read/print in another base…

# Answer
> 0 votes
# Perl 6, 66 bytes

Going all-out by removing the non-printing control characters gets me to (83+1)-15% = **71.4**

```
perl6 -ne 'print grep /<-:C+[\n]>/,.ords».base(2)».flip.map({chr :2([~] $_.comb.map(+!+*))})'

```

If I remove the code that strips out the control characters I save quite a bit 65+1 = **66**

```
perl6 -ne 'print .ords».base(2)».flip.map({chr :2([~] $_.comb.map(+!+*))})'

```

( I used `»` instead of `>>` for clarity )

# Answer
> 0 votes
## Racket 250 15% bonus = 212 bytes

```
(λ(s)(list->string(map integer->char(filter(λ(x)(or(> x 31)(= x 10)))(for/list((i(string->list s)))(string->number(string-append
"#b"(list->string(map(λ(i)(if(equal? #\0 i)#\1 #\0))(reverse(string->list(number->string(char->integer i)2))))))))))))

```

Ungolfed:

```
(define (f s)
    (list->string
     (map
      integer->char
      (filter
       (λ(x)(or(> x 31)(= x 10)))

       (for/list ((i (string->list s)))
         (string->number
          (string-append
           "#b"
           (list->string
            (map
             (λ(i)(if(equal? #\0 i) #\1 #\0))
             (reverse
              (string->list
               (number->string
                (char->integer i) 2)
               )))))))))))

```

Testing:

```
(f "Hello, World!")

```

Output:

```
"v,dd2>\nXdl"

```

# Answer
> 0 votes
# Zsh, 114 bytes \\$\times\\$ 0.85 \\$=\\$ 96.9

```
for c (${(s::)1})b=(${(s::)$(([##2]#c))})&&b=${(j::)${(Oa)b}}&&s+=${(#)$((2#$b^(2**$#b-1)))}
<<<${s//[^[:print:]]}

```

Try it online!

Without filtering for printables, this would scores **98 bytes**.

```
for char (${(s::)1}){
    bits=(${(s::)$(([##2]#char))})     # convert to binary, split into characters
    bits=${(j::)${(Oa)b}}              # reverse order of bits, join on empty string
    string+=${(#)$((2#$b^(2**$#b-1)))} # XOR with the 2**(len(bits) - 1), convert from codepoint
}
<<<${string//[^[:print:]]}             # ${string//find/replace}

```

# Answer
> 0 votes
# Java, 78 bytes

```
s->s.chars().boxed().map(i->(char)(~i.reverse(i)>>>i.numberOfLeadingZeros(i)))

```

Try it online!

---
Tags: code-golf, string, binary
---


title: Inserting digits to satisfy equation

text:
# Question
Title: Inserting digits to satisfy equation
You are given 3 non negative numbers: \\$x\\$, \\$y\\$ and \\$z\\$, and must minimize the number of digits (non negative) inserted at any place in the numbers \\$x\\$, \\$y\\$, or \\$z\\$ to make

$$x + y = z$$

(a clarification: you can add any non negative digit any number of time at any place )

(you can assume that \\$x\\$, \\$y\\$, \\$z\\$ and your final integers after insertion won't overflow the integer limit in your language)

Example:

$$x=1, y=10, z=30$$

$$1 + 10 = 30 $$ $$1(0) +1(2)0 = (1)30$$

i.e \\$10+120 = 130\\$

The minimum insertions is 3 here.

$$x=1 , y=1 , z=3$$

$$1 + 1 = 3 $$
$$(3)1 + 1 = 3(2) \\;\text{or}\\; 1 + 1(2) = (1)3$$

Here, the answer is 2.

$$x=11 , y=11 , z=33$$

$$11 + 11 = 33$$ $$11(2) + 1(2)1 = (2)33 \\;\text{or}\\; 1(2)1 + (2)11 = 33(2)$$

Here, the answer is 3.

$$x=3 , y=0 , z=0$$

$$3 + 0 = 0$$ $$3 + 0 = 0(3)$$

Here, the answer is 1,because as stated in earlier clarification, you can add any non negative digit any number of time at any place, so there can be leading zeroes too.

There can be multiple ways for same number of minimal insertion.

If possible while answering please write a short explanation of what you did. This is , so the shortest answer in bytes per language wins.

# Answer
> 10 votes
# JavaScript (ES6), 164 bytes

*Thanks to @l4m2 for identifying several bugs and suggesting the alternate version below*

```
(x,y,z)=>(F=k=>(g=(k,s=z+`-${x}-`+y,n=9)=>eval(s.replace(/\d+/g,'"$&"'))?k&&[...s,0].some((_,i)=>g(k-1,s.slice(0,i)+n+s.slice(i)))||n&&g(k,s,n-1):1)(k)?k:F(k+1))(0)

```

Try it online!

### How?

We build the string `s` with the pattern `z-x-y` and recursively attempt to insert `k` additional digits until `eval(s)` is 0.

### Commented

```
(x, y, z) => (                 // main function taking (x, y, z)
  F = k => (                   // F is a recursive function taking a counter k
    g = (                      // g is a recursive function taking:
      k,                       //   k = number of digits to insert
      s = z + `-${x}-` + y,    //   s = expression string "z-x-y"
      n = 9                    //   n = next digit to insert
    ) =>                       //
    eval(s.replace(            // if the expression does not evaluate to 0:
      /\d+/g, '"$&"'           // (add quotes to prevent any number with a
    )) ?                       // leading 0 to be parsed as octal)
      k &&                     //   if k is not equal to 0,
      [...s, 0].some((_, i) => //   for each position i from 0 to len(s):
        g(                     //     do a recursive call to g:
          k - 1,               //       decrement k
          s.slice(0, i) + n +  //       insert n at position i
          s.slice(i)           //       (and implicitly restart with n = 9)
        )                      //     end of recursive call
      ) ||                     //   end of some()
      n &&                     //   if n is not equal to 0:
        g(k, s, n - 1)         //     do a recursive call to g with n - 1
    :                          // else:
      1                        //   success
  )(k)                         // initial call to g with the current value of k
  ?                            // if successful:
    k                          //   return k
  :                            // else:
    F(k + 1)                   //   try again with k + 1
)(0)                           // initial call to F with k = 0

```

---

# JavaScript (Node.js), 158 bytes

*A slower but 6 bytes shorter variant suggested by @l4m2*

```
(x,y,z)=>(F=k=>(g=(k,s=z+`-${x}-`+y,i=~s.length*-10)=>k*i--?g(k-1,s.slice(0,t=i/10)+i%10+s.slice(t))|g(k,s,i):!eval(s.replace(/\d+/g,'"$&"')))(k)?k:F(k+1))(0)

```

Try it online!

# Answer
> 7 votes
# Python 2, 161 ~~257~~ bytes

```
def g(L):
 k=0;F="-%s %s %s"%L,
 while all(sum(map(int,X.split()))for X in F):k+=1;F=[x[:y/10+1]+`y%10`+x[y/10+1:]for x in F for y in range(10*len(x))]
 return k

```

Try it online!

*-1 byte thanks to @ovs!*

Takes in a tuple of 3 integers `L`, in order `(z, x, y)`.

**How it works**:

`F` stores all insertions with `k` digits added (in the form "-z x y"). At each stage, we check if string `X` in `F` splits to three integers that satisfy the equality by evaluating the sum of (the integers in) `X.split()`. When going to the next stage, the `+1` in the slicing prevents a digit from being inserted before the minus sign. The `int` conversion is to prevent any leading zero from being interpreted as an octal integer.

# Answer
> 4 votes
# 05AB1E, 33 bytes

```
∞.ΔI„+-S.ιSÐм.ø.œJs>ù9Ýyãδ.ιJ.E_à

```

Extremely slow brute-force approach, so it's barely unable to complete any of the test cases resulting in 3..

Try it online.

Here a slightly faster but incorrect approach to at least show the three test cases work as intended: Try it online. The difference is the `õ.ø`, which is `Ðм.ø` in the full program. The `õ.ø` surround the list of characters with a single leading/trailing empty string, whereas the `Ðм.ø` surrounds it with multiple empty leading/trailing strings (up to the amount of digits in the total input, plus 2 for the `+-`).

**Explanation:**

```
∞.Δ               # Find the first positive integer which is truthy for:
   I              #  Push the input-list [x,y,z]
    „+-S          #  Push character-pair ["+","-"]
        .ι        #  Interleave it with the input-list
                  #   i.e. [1,10,30] → [1,"+",10,"-",30]
          S       #  Convert it to a flattened list of characters
                  #   → [1,"+",1,0,"-",3,0]
           Ð      #  Triplicate this list
            м     #  Remove all characters in this list from the list,
                  #  leaving a list of empty strings of the same size
                  #   i.e. [1,"+",1,0,"-",3,0] → ["","","","","","",""]
             .ø   #  Surround the earlier list with these empty strings as
                  #  leading/trailing items
                  #   → ["","","","","","","",1,"+",1,0,"-",3,0,"","","","","","",""]

```

The examples in the rest of the explanation uses a single empty leading/trailing string, since it's otherwise a bit too verbose. The actual functionality remains the same.

```
               .œ #  Get all partitions of this list
                  #   → [[[""],["1"],["+"],["1"],["0"],["-"],["3"],["0"],[""]],
                  #      [[""],["1"],["+"],["1"],["0"],["-"],["3"],["0", ""]],
                  #      ...,
                  #      [["","1","+","1","0","-","3","0",""]]]
                J #  Join each inner-most list together to a string
                  #   → [["","1","+","1","0","-","3","0",""],
                  #      ["","1","+","1","0","-","3","0"],
                  #      ...,
                  #      ["1+10-30"]]
   s              #  Swap so the current number is at the top of the stack
    >             #  Increase it by 1
                  #   i.e. 3 → 4
     ù            #  Only keep the partitions of that size
                  #   → [["","1","+","10-30"],
                  #      ["","1","+1","0-30"],
                  #      ...,
                  #      ["1+10-","3","0",""]]
   9Ý             #  Push list [0,1,2,3,4,5,6,7,8,9]
     yã           #  Get the current number's cartesian product of this list
                  #   i.e. 3 → [[0,0,0], [0,0,1], ..., [9,9,9]]
       δ          #  Apply on the two lists double-vectorized:
        .ι        #   Interleave the lists
                  #    → [[["",0,"1",0,"+",0,"10-30"],["",0,"1",0,"+",1,"10-30"],...],
                  #       [["",0,"1",0,"+1",0,"0-30"],["",0,"1",0,"+1",1,"0-30"],...],
                  #       ...,
                  #       [...,["1+10-",9,"3",9,"0",9,""]]]
          J       #  Join every inner-most list to a string
                  #   → [["010+010-30","010+110-30",...],
                  #      ["010+100-30","010+110-30",...],
                  #      ...,
                  #      [...,"1+10-93909"]]
           .E     #  Evaluate each as Python-code
                  #   → [[-10,90,...],
                  #      [80,90,...],
                  #      ...,
                  #      [...,-93898]]
             _    #  Check if any result is 0 (1 if 0; 0 otherwise)
              à   #  And take the flattened maximum to check if any was truthy
                  # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Charcoal, ~~52~~ 50 bytes

```
⊞υθＷ⬤υ⁻Σκ⊗Ｉ⊟⪪κ=«≔υη≔⟦⟧υＦηＦ⊕ＬθＦχ⊞υ⁺⁺…κλμ✂κλ»Ｉ⁻Ｌ⊟υＬθ

```

Try it online! Link is to verbose version of code. Takes input as an "equation" i.e. `1+1=3`. Quite slow but usually manages to compute answers of up to 3 on TIO. Edit: Tweaked to be slightly less slow. Explanation:

```
⊞υθ

```

Start with the initial equation.

```
Ｗ⬤υ⁻Σκ⊗Ｉ⊟⪪κ=«

```

Repeat while none of the equations add up. Charcoal has a builtin for taking the sum of all the strings of digits within a string, but this obviously gives `x+y+z`, so I compare that against `2z`. (Using an evaluation function would fail if I ever inserted a leading zero anywhere.)

```
≔υη≔⟦⟧υ

```

Make a copy of the list so far so that I can empty it out.

```
ＦηＦ⊕ＬθＦχ

```

For each equation, each possible insertion point and each digit, ...

```
⊞υ⁺⁺…κλμ✂κλ

```

... insert the digit into the equation at that point and save the result.

```
»Ｉ⁻Ｌ⊟υＬθ

```

Output the number of digits inserted.

# Answer
> 1 votes
# Haskell, <sup>~~125~~</sup> 120 bytes

```
f.pure.unwords
f l=last$1+f[take i s++d:drop i s|s<-l,i<-[0..length s],d<-show$56^7]:[0|0<-foldr1(-).map read.words<$>l]

```

Try it online!

The relevant function is `f.pure.unwords`, which takes as input a list `[x,z,y]`; integers are represented as strings.

# Answer
> 1 votes
# Ruby, 142 bytes

```
->*x{r=[a=x];3.times{|x|w=a[x];(w..?9+w).grep(/#{w.chars*".*"}/){|z|*b=a;b[x]=z;r<<b}}until eval"%s+%s==%s"%a=r.shift;a.join.size-x.join.size}

```

Try it online!

Input integers as strings, is very slow if the solution is 3 or more.

### Quick explanation:

```
->*x{r=[a=x];

```

The arguments are in an array, we need to create a copy of that (a), and an array of possible solutions (r)

```
3.times{|x|w=a[x];(w..?9+w).grep(/#{w.chars*".*"}/){|z|*b=a;b[x]=z;r<<b}}

```

Add a single digit in all possible positions to each argument separately. Instead of interpolating strings, generate all numbers between the argument and the same number with a 9 prepended, and then filter using a regex (e.g.: if the argument is "11", find all numbers containing the regex /1.\*1/ between 11 and 911)

```
until eval"%s+%s==%s"%a=r.shift;a.join.size-x.join.size}

```

Evaluate the expression using the first element of the array of possible solutions. If this is false, then repeat the process using this element as a starting point for the next iteration. We don't need to check for octal numbers since no 0 will be prepended to any number (and this solves also the case \[0,0,0\]) If the comparison is true, the result we need is the difference in length between the solution and the input arguments (concatenated).

---
Tags: code-golf, arithmetic
---


title: Tips for golfing in Dart

text:
# Question
Title: Tips for golfing in Dart
Dart is an object oriented programming language borrowing from both Java and Javascript. What general tips do you have for golfing in Dart? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Dart (e.g. "remove comments" is not an answer). Please post one tip per answer.

If a tip is similar to Java/JS, please link to the answer in the original language's thread as well if you can.

Taken mostly from Joey's Tips for Powershell

# Answer
> 3 votes
**Variable declaration**

Regular variable declaration takes 4 bytes (`var`) + 2 bytes/variable (`i,`). You can declare variables as optional named parameters for your function and shave a few bytes.

```
f(){var i,j,k;} //Takes 15 bytes
g({i,j,k}){}  //Takes 12 bytes

```

Note: This doesn't work for non-constant values, for example:

```
f({i=List}){}  //Works
g({i=[]}){}  //Doesn't work

f({i=0,j=0}){}  //Works
g({i=0,j=i}){}  //Doesn't work

```

# Answer
> 3 votes
**Implicit parameter passing**

In some cases where Dart expects a function to be declared, you can code the function elsewhere, and then just pass its name. Dart will take care of passing the value automatically. Let me illustrate :

```
[0,1,2,3,4,5].forEach((i) => print(i)); //Using a lambda
[0,1,2,3,4,5].forEach(print); //Using implicit parameter passing since print() expects a similar parameter

```

You can also use your own functions

```
f(List i){
    i.forEach(print); //Prints each number on a new line
}

[[0,1], [1,2]].forEach(f); //Prints 0 \n 1 \n 1 \n 2\n

```

If you know a lambda might be used in multiple places, for example a `map()`, it can be useful to make it its own function and pass it that way instead of declaring it multiple times.

# Answer
> 2 votes
**String conversion and concatenation**

Dart doesn't allow for concatenation for types other than String and doesn't implicitly convert to String like C# does for example.

It however includes a very useful way to concatenate variables without needing to use any addition operator or explicitly casting to String (using the `.toString()` method).

```
var i=0,j=1,k=2;
var s0='$j'; //'1'
var s1='$i$j$k'; //'012'
var s2='i=$i'; //'i=0'

```

You can also perform operations directly in the `${}` section and save a few temporary variable declarations.

```
var i=0,j=1,k=2;
var s='${i+j+k}'; //'3'

```

# Answer
> 0 votes
**Creating range of consecutive integers**

If you want to create a list of integers from start and end values, you can use below options:

```
final int s = 0; // start value
final int e = 5; // end value

List.generate(e-s,(i)=>i+s);  // 28 bytes
List.generate(e,(i)=>i);      // 24 bytes, if start is guaranteed to be zero
[for(int i=s;i<e;i++)i];      // 24 bytes
[for(int i=s;i<e;]i++];       // 23 bytes
[for(int i=s;i<e;]++i];       // 23 bytes, if start is exclusive
[for(;s<e;)s++];              // 16 bytes, if start can be changed in-place

```

# Answer
> 0 votes
**Return inside loops**

Let's suppose in your code there is a return inside a loop. You can use the following idiom to reduce bytes:

```
// indexOf method
f(v,x,[i=0]){for(;i<v.length;i++)if(v[i]==x)return i;return-1;}   // 63 bytes
f(v,x)=>([i=0]){for(;i<v.length;i++)if(v[i]==x)return i;}()??-1;  // 64 bytes
f(v,x)=>(i){for(;i<v.length;i++)if(v[i]==x)return i;}(0)??-1;     // 61 bytes

```

The more variables to be initialized, the more bytes can be reduced.

```
// "index of integral"
g(v,x,[s=0,i=0]){for(;i<v.length;i++){s+=v[i];if(s>=x)return i;}return-1};  // 74 bytes
g(v,x)=>(s,i){for(;i<v.length;i++){s+=v[i];if(s>=x)return i;}(0,0)??-1;     // 71 bytes

```

---
Tags: code-golf, tips
---


title: RTA (Reverse-Then-Add) root of a number

text:
# Question
Title: RTA (Reverse-Then-Add) root of a number
The reverse-then-add (RTA) sequence is a sequence obtained by adding a number to its reverse, and repeating the process on the result. For eg.,

$$ 5 + 5 = 10 \Rightarrow 10 + 01 = 11 \Rightarrow 11 + 11 = 22 \Rightarrow 22 + 22 = 44 \Rightarrow\text{ }... $$

Thus, 5's RTA sequence contains 10, 11, 22, 44, 88, 176, etc.

The *RTA root* of a number \\$n\\$ is the smallest number that is either equal to \\$n\\$ or gives raise to \\$n\\$ in its RTA sequence.

For eg., 44 is found in the RTA sequence of 5, 10, 11, 13, 22, 31, etc. Of these, 5 is the smallest, and hence RTAroot(44) = 5.

72 is not part of any number's RTA sequence, and so is considered its own RTA root.

**Input** is a positive integer in a range that your language can naturally handle.

**Output** is the RTA root of the given number, as defined above.

### Test cases

```
Input
Output

44
5

72
72

132
3

143
49

1111
1

999
999

```

Related OEIS: A067031. The output will be a number from this sequence.

# Answer
# ~~Perl 6~~ Raku, ~~45 44~~ 39 bytes

```
{+(1...{$_∈($^a,{$_+.flip}...*>$_)})}

```

Try it online!

### Explanation:

```
{                                   }  # Anonymous code block
 +(1...                            )     # Find the first integer
       {                          }      # Where
        $_∈                              # The input is an element of
           (              ...    )         # A sequence defined by
            $^b,                           # The first element is the number we're checking
                {$_+.flip}                 # Each element is the previous element plus its reverse
                             *>$_          # The last element is larger than the input

```
> 13 votes

# Answer
# Brachylog, 24 22 bytes

```
{~{ℕ≤.&≜↔;?+}{|↰₁}|}ᶠ⌋

```
* 2 bytes thanks to sundar noticing that I had a `{{` and `}}`

# Explanation

```
                --  f(n):
                --      g(x):
 {              --          h(y):
  ~             --              get z where k(z) = y
   {            --              k(z):
    ℕ≤.         --                  z>=0 and z<=k(z) (constrain so it doesn't keep looking)
    &≜          --                  label input (avoiding infinite stuff)
      ↔;?+      --                  return z+reverse(z)
   }            --
    {           --
     |↰₁        --              return z and h(z) (as in returning either)
    }           --
  |             --          return h(x) or x (as in returning either)
 }              --
ᶠ               --      get all possible answers for g(n)
  ⌋             --      return smallest of them

```

sorry for the wonky explanation, this is the best i could come up with

Try it online!
> 7 votes

# Answer
# Haskell, ~~59~~ 57 bytes

<sup>-2 bytes thanks to user1472751 (using a second `until` instead of list-comprehension & `head`)!</sup>

```
f n=until((n==).until(>=n)((+)<*>read.reverse.show))(+1)1

```

Try it online!

## Explanation

This will evaluate to `True` for any RTA-root:

```
(n==) . until (n<=) ((+)<*>read.reverse.show)

```

The term `(+)<*>read.reverse.show` is a golfed version of

```
\r-> r + read (reverse $ show r)

```

which adds a number to itself reversed.

The function `until` repeatedly applies `(+)<*>read.reverse.show` until it exceeds our target.

Wrapping all of this in yet another `until` starting off with `1` and adding 1 with `(+1)` will find the first RTA-root.

If there is no proper RTA-root of `n`, we eventually get to `n` where `until` doesn't apply the function since `n<=n`.
> 5 votes

# Answer
# 05AB1E, 7 bytes

Using the new version of 05AB1E (rewritten in Elixir).

### Code

```
L.ΔλjÂ+

```

Try it online!

### Explanation

```
L           # Create the list [1, ..., input]
 .Δ         # Iterate over each value and return the first value that returns a truthy value for:
   λ        #   Where the base case is the current value, compute the following sequence:
     Â+     #   Pop a(n - 1) and bifurcate (duplicate and reverse duplicate) and sum them up.
            #   This gives us: a(0) = value, a(n) = a(n - 1) + reversed(a(n - 1))
    j       #   A λ-generator with the 'j' flag, which pops a value (in this case the input)
            #   and check whether the value exists in the sequence. Since these sequences will be
            #   infinitely long, this will only work strictly non-decreasing lists.

```
> 5 votes

# Answer
# Jelly, ~~12~~ 11 bytes

```
ṚḌ+ƊÐ¡€œi¹Ḣ

```

This is a full program. Run time is roughly quadratic; test cases \\$999\\$ and \\$1111\\$ time out on TIO.

*Thanks to @JonathanAllan for golfing off 1 byte!*

Try it online!

### How it works

```
ṚḌ+ƊÐ¡€œi¹Ḣ  Main link. Argument: n

      €      Map the link to the left over [1, ..., n].
    Ð¡         For each k, call the link to the left n times. Return the array of k
               and the link's n return values.
   Ɗ           Combine the three links to the left into a monadic link. Argument: j
Ṛ                Promote j to its digit array and reverse it.
 Ḍ               Undecimal; convert the resulting digit array to integer.
  +              Add the result to j.
       œi¹   Find the first multindimensional index of n.
          Ḣ  Head; extract the first coordinate.

```
> 3 votes

# Answer
## Ruby, ~~66~~ 57 bytes

```
f=->n{(1..n).map{|m|m+(m.digits*'').to_i==n ?f[m]:n}.min}

```

Try it online!

Recursive function that repeatedly "undoes" the RTA operation until arriving at a number that can't be produced by it, then returns the minimum.

Instead of using `filter`, which is long, I instead simply `map` over the range from 1 to the number. For each *m* in this range, if *m + rev(m)* is the number, it calls the function recursively on *m*; otherwise, it returns *n*. This both removes the need for a `filter` and gives us a base case of *f(n) = n* for free.

Highlights include saving a byte with `Integer#digits`:

```
m.to_s.reverse.to_i
(m.digits*'').to_i
eval(m.digits*'')

```

The last one would be a byte shorter, but sadly, Ruby parses numbers starting with `0` as octal.
> 3 votes

# Answer
# JavaScript (ES6), 61 bytes

```
n=>(g=k=>k-n?g(k>n?++x:+[...k+''].reverse().join``+k):x)(x=1)

```

Try it online!

### Commented

```
n =>                        // n = input
  (g = k =>                 // g() = recursive function taking k = current value
    k - n ?                 //   if k is not equal to n:
      g(                    //     do a recursive call:
        k > n ?             //       if k is greater than n:
          ++x               //         increment the RTA root x and restart from there
        :                   //       else (k is less than n):
          +[...k + '']      //         split k into a list of digit characters
          .reverse().join`` //         reverse, join and coerce it back to an integer
          + k               //         add k
      )                     //     end of recursive call
    :                       //   else (k = n):
      x                     //     success: return the RTA root
  )(x = 1)                  // initial call to g() with k = x = 1

```
> 2 votes

# Answer
# Pyth, 12 bytes

```
fqQ.W<HQ+s_`

```

Check out a test suite!

Surprisingly fast and efficient. All the test cases ran at once take less than 2 seconds.

### How it works

```
fqQ.W<HQ+s_` – Full program. Q is the variable that represents the input.
f            – Find the first positive integer T that satisfies a function.
   .W        – Functional while. This is an operator that takes two functions A(H)
               and B(Z) and while A(H) is truthy, H = B(Z). Initial value T.
     <HQ     – First function, A(H) – Condition: H is strictly less than Q.
        +s_` – Second function, B(Z) – Modifier.
         s_` – Reverse the string representation of Z and treat it as an integer.
        +    – Add it to Z.
             – It should be noted that .W, functional while, returns the ending
               value only. In other words ".W<HQ+s_`" can be interpreted as
               "Starting with T, while the current value is less than Q, add it
               to its reverse, and yield the final value after the loop ends".
 qQ          – Check if the result equals Q.

```
> 2 votes

# Answer
# Python 2, 70 bytes

```
f=lambda n,i=1,k=1:i*(k==n)or f(n,i+(k>n),[k+int(`k`[::-1]),i+1][k>n])

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~21~~ ~~16~~ 15 bytes

```
G¼N¹FÂ+Ð¹Qi¾q]¹

```

-1 byte thanks to *@Emigna*.

Try it online.

**Explanation:**

```
G               # Loop `N` in the range [1, input):
 ¼              #  Increase the global_counter by 1 first every iteration (0 by default)
 N              #  Push `N` to the stack as starting value for the inner-loop
  ¹F            #  Inner loop an input amount of times
    Â           #   Bifurcate (short for Duplicate & Reverse) the current value
                #    i.e. 10 → 10 and '01'
     +          #   Add them together
                #    i.e. 10 and '01' → 11
      Ð         #   Triplicate that value
                #   (one for the check below; one for the next iteration)
       ¹Qi      #   If it's equal to the input:
          ¾     #    Push the global_counter
           q    #    And terminate the program
                #    (after which the global_counter is implicitly printed to STDOUT)
]               # After all loops, if nothing was output yet:
 ¹              # Output the input

```
> 2 votes

# Answer
# 05AB1E, 13 bytes

```
LʒIFDÂ+})Iå}н

```

Try it online!

**Explanation**

```
L               # push range [1 ... input]
 ʒ         }    # filter, keep elements that are true under:
  IF   }        # input times do:
    D           # duplicate
     Â+         # add current number and its reverse
        )       # wrap in a list
         Iå     # check if input is in the list
            н   # get the first (smallest) one

```
> 2 votes

# Answer
# Charcoal, 33 bytes

```
Ｎθ≔⊗θηＷ›ηθ«≔Ｌ⊞ＯυωηＷ‹ηθ≧⁺Ｉ⮌Ｉηη»ＩＬυ

```

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

```
Ｎθ

```

Input \\$q\\$.

```
≔⊗θη

```

Assign \\$2q\\$ to \\$h\\$ so that the loop starts.

```
Ｗ›ηθ«

```

Repeat while \\$h\>q\\$:

```
≔Ｌ⊞Ｏυωη

```

push a dummy null string to \\$u\\$ thus increasing its length, and assign the resulting length to \\$h\\$;

```
Ｗ‹ηθ

```

repeat while \\$h\<q\\$:

```
≧⁺Ｉ⮌Ｉηη

```

add the reverse of \\$h\\$ to \\$h\\$.

```
»ＩＬυ

```

Print the final length of \\$u\\$ which is the desired root.
> 1 votes

# Answer
# MATL, 17 bytes

```
`@G:"ttVPU+]vG-}@

```

Try it online!

### Explanation

```
`         % Do...while loop
  @       %   Push iteration index, k (starting at 1)
  G:"     %   Do as many times as the input
    tt    %     Duplicate twice
    VPU   %     To string, reverse, to number
    +     %     Add
  ]       %   End
  v       %   Concatenate all stack into a column vector. This vector contains
          %   a sufficient number of terms of k's RTA sequence
  G-      %   Subtract input. This is used as loop condition, which is falsy
          %   if some entry is zero, indicating that we have found the input
          %   in k's RTA sequence
}         % Finally (execute on loop exit)
  @       %   Push current k
          % End (implicit). Display (implicit)

```
> 1 votes

# Answer
# C (gcc), 120 100 99 bytes

```
f(i,o,a,b,c,d){for(a=o=i;b=a;o=i/b?a:o,a--)for(;b<i;b+=c)for(c=0,d=b;d;d/=10)c=c*10+d%10;return o;}

```

Try it online!

Given input `i`, checks every integer from `i` to 0 for a sequence containing `i`.

* `i` is the input value
* `o` is the output value (the minimum root found so far)
* `a` is the current integer being checked
* `b` is the current element of `a`'s sequence
* `c` and `d` are used to add `b` to its reverse
> 1 votes

# Answer
# Java 8, 103 bytes

```
n->{for(int i=0,j;;)for(j=++i;j<=n;j+=n.valueOf(new StringBuffer(j+"").reverse()+""))if(n==j)return i;}

```

Try it online.

**Explanation:**

```
n->{                // Method with Integer as both parameter and return-type
  for(int i=0,j;;)  //  Infinite loop `i`, starting at 0
    for(j=++i;      //  Increase `i` by 1 first, and then set `j` to this new `i`
        j<=n        //  Inner loop as long as `j` is smaller than or equal to the input
        ;           //    After every iteration:
         j+=        //     Increase `j` by:
            n.valueOf(new StringBuffer(j+"").reverse()+""))
                    //     `j` reversed
     if(n==j)       //   If the input and `j` are equal:
       return i;}   //    Return `i` as result

```

---

Arithmetically reversing the integer is 1 byte longer (**104 bytes**):

```
n->{for(int i=0,j,t,r;;)for(j=++i;j<=n;){for(t=j,r=0;t>0;t/=10)r=r*10+t%10;if((j+=r)==n|i==n)return i;}}

```

Try it online.
> 1 votes

# Answer
# Japt, ~~16~~ ~~15~~ 11 bytes

```
@ÇX±swÃøU}a

```

Try it

```
@ÇX±swÃøU}a     :Implicit input of integer U
@        }a     :Loop over the positive integers as X & output the first that returns true
 Ç              :  Map the range [0,U)
  X±            :    Increment X by
    sw          :    Its reverse
      Ã         :  End map
       øU       :  Contains U?

```
> 1 votes

# Answer
# Physica, 57 bytes

Credit for the method goes to Doorknob.

```
F=>N:Min@Map[->m:N==m+Int[Str[m]{%%-1}]&&F@m||N;…[1;N]]

```

Try it online!
> 0 votes

# Answer
# C (gcc), 89 bytes

I run each sequence in \[1,*n*) until I get a match; zero is special-cased because it doesn't terminate.

```
j,k,l,m;r(i){for(j=k=0;k-i&&++j<i;)for(k=j;k<i;k+=m)for(l=k,m=0;l;l/=10)m=m*10+l%10;j=j;}

```

Try it online!
> 0 votes

# Answer
# Husk, 9 bytes

```
ḟo£⁰¡S+↔N

```

Try it online!

first element in natural numbers which has an infinite list that contains the input.
> 0 votes

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