title: Composite Factor Soup

text:
# Question
Title: Composite Factor Soup
Per the fundamental theorem of arithmetic, for a given number \\$n\\$, it is possible to find it's prime factors, and they are unique. Let's imagine we talk only of \\$n\\$ that is non-prime (composite).

We can also find the factors of all the composite numbers smaller than \\$n\\$. For example if \\$n\\$ is 10, then it has factors 5 and 2. 9 has 3 and 3. 8 has 2, thrice. 6 has 3 and 2. 4 has 2 and 2. So for the number 10, all the prime factors of all the composite numbers smaller than 10 would be listed as 2,3, and 5.

Now if you put a lot of vegetables in a pot for soup, often the largest will rise to the top. So if we put all of these factors in a big pot, which one will be the largest and rise to the top? For 10 soup, that answer is 5.

"Silly", you might think, "the number \\$n\\$ itself will have the largest factors, larger than the factors of numbers smaller than \\$n\\$". But this is where you are wrong my friend!

For example, the factors of 16 are all 2, repeated four times. The factors of 15 are 5 and 3, now, I don't have to be a mathematician to tell that 15 is smaller than 16, but 5 is bigger than 2!

Your challenge is to explore how this works for bigger \\$n\\$. For any number given input number \\$n\\$, assumed natural, composite, and less than 2^32, find out which is the "largest factor" of all the prime factors of all the composite numbers less than or equal to \\$n\\$.

Good luck and have fun!

Smallest byte count wins.

# Answer
# Neim, 3 bytes

```
ᚺ>:

```

Explanation:

```
ᚺ   halve
 >  increment
  : previous prime

```

Try it online!
> 7 votes

# Answer
# 05AB1E, 4 bytes

```
;ÅPθ

```

Try it online or verify first \\$\[4,n\]\\$ numbers.

**Explanation:**

Implementation of the observation @xnor's made in his comment: largest prime \\$\leq\frac{1}{2}n\\$. Which I've literally implemented now (after *@Arnauld* reported some bugs in my initial program):

```
;     # Halve the (implicit) input
 ÅP   # Get a list of primes smaller than or equal to this
   à  # And only leave the largest prime
      # (which is output implicitly as result)

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), 19 bytes

```
Prime@PrimePi[#/2]&

```

Try it online!
> 2 votes

# Answer
# Japt v1.4.5 `-h`, 6 bytes

```
z o fj

```

Try it
> 2 votes

# Answer
# Jelly, 4 bytes

```
‘HÆp

```

Try it online!

As others have observed, the answer is the largest prime \\$≤ n/2\\$

Thanks to @Arnauld for correcting my order of halving/incrementing
> 2 votes

# Answer
# , 10 bytes

```
_4 p:-:@>:

```

Try it online!

Uses the xnor's observation

## Explanation:

```
_4 p:       the next prime smaller than
        >:  the input  plus 1
     -:@    divided by 2

```
> 2 votes

# Answer
# JavaScript (ES6), 40 bytes

After a careful analysis of (xnor's comment on) the challenge, it turns out that  ~~42 41~~  40 is the answer.

```
n=>(g=k=>n%--k?g(k):k<2?n:g(--n))(n>>=1)

```

Try it online!

### Commented

We look for the highest prime \\$p\le\left\lfloor\dfrac{n}{2}\right\rfloor\\$.

```
n => (          // n = input
  g = k =>      // g = recursive function looking for the highest divisor k < n of n
    n % --k ?   //   decrement k; if k is not a divisor of n:
      g(k)      //     do recursive calls until it is
    :           //   else:
      k < 2 ?   //     if k is less than 2 (i.e. n is prime):
        n       //       stop recursion and return n
      :         //     else:
        g(--n)  //       try again with n - 1
  )(n >>= 1)    // initial call to g with n = floor(n / 2)

```
> 2 votes

# Answer
# Retina 0.8.2, ~~34~~ 32 bytes

```
.+
$*
(.+)(?<!^\2+(..+))\1.*
$.1

```

Try it online! Edit: Saved 2 bytes thanks to @Grimy. Explanation:

```
.+
$*

```

Convert to unary.

```
(.+)

```

Find the largest number...

```
(?<!^\2+(..+))

```

... that is prime ...

```
\1.*

```

... and a factor of a number not greater than the input.

```
$.1

```

Convert to decimal.
> 2 votes

# Answer
# Factor, 37 bytes

```
: p ( n -- n ) 2 / primes-upto last ;

```

Try it online!
> 2 votes

# Answer
# Ruby, 24+8 = 32 bytes

8 bytes for the `-rprime` flag (plus space) to import the Prime module. `Prime.each(n)` gets all primes up to `n`, then we just take the largest one. (We could take the last item since it's in order, but that costs more bytes.)

```
->n{Prime.each(n/2).max}

```

Try it online!
> 2 votes

# Answer
# Husk, 7 bytes

```
→`↑İp≤½

```

Try it online!
> 0 votes

---
Tags: code-golf, primes
---


# Question
Title: Divisible by 1000003? Easy, just multiply the last digit by 300001 and add!
Given a prime `P` greater than `10`, your program or function must figure out its divisibility rule `x`, defined as the integer with smallest absolute value which yields a multiple of the original prime when multiplied by the last digit of the prime and added to the rest of the original prime.

## Example

Given an input `31`, the last digit is `1` and the rest of the number is `3`. Thus your program must find the integer `x` with minimum absolute value such that `1*x + 3` is a multiple of `31`. In this case, `x=-3` works, so the program or function would return `-3`.

Given an input `1000003`, the last digit is `3` and the rest of the number is `100000`. Thus your program would find `x=300001` because `3*300001+100000 = 1000003` which is a multiple of `1000003`.

## Mathematical Background

The value of `x` can be used as a divisibility test. If a number `N` is divisible by `P`, then adding `x` times the last digit of `N` to the rest of `N` will yield a multiple of `P` if and only if `N` is divisible by `P` in the first place.

For `P=11`, we get `x=-1`, which is equivalent to the well-known divisibility rule for `11`: a number is divisible by `11` alternating difference of its digits is divisible by `11`.

## Rules

* The output may be in any form that clearly encodes both the sign and value of the output.
* The input prime will be between 10 and 2^30.
* You do not need to handle if the input is not a prime or is not in the range.
* You do not need to handle if both `x` and `-x` are valid outputs (should not happen).
* Brute force is permitted, but more creative solutions are appreciated.
* This is , so shortest code **in each language** wins! Do not let answers in golfing languages discourage you from posting in other languages.

## Test Cases

```
Input   Output
11  -1
13  4
17  -5
19  2
23  7
29  3
31  -3
37  -11
41  -4
43  13
47  -14
53  16
59  6
61  -6
67  -20
71  -7
73  22
79  8
83  25
89  9
97  -29
101 -10
103 31
107 -32
109 11
113 34
127 -38
131 -13
1000003 300001
2000003 600001
2999999 300000
9999991 -999999

```

# Answer
## JavaScript (ES6), ~~32~~ ~~25~~ 23 bytes

```
f=
n=>(3/(n%5*2-5)*n+1)/10
```

```
<input type=number min=1 oninput=o.textContent=this.value%5*(this.value%2)?f(this.value):``><pre id=o>
```

`3/(n%5*2-5)` would be written `9/n(mod -10)` if I had access to balanced modulo division. Edit: Saved 2 bytes thanks to @EgorSkriptunoff
> 15 votes

# Answer
# Python 2, 27 bytes

```
lambda n:(n%5*2-5^2)*n/10+1

```

Try it online!

The operations are done left to right: `(((n%5)*2)-5)^2`.

I used my arithmetic brute forcer to find the expression `n%5*2-5^2` to perform `{1:-1,3:3,2:-3,4:1}[k]`, taking the negative inverse of a residue mod 5 into the range `[-2..2]`.
> 9 votes

# Answer
# Jelly, ~~10~~ 8 bytes

```
,N⁵æiAÞḢ

```

Try it online!

### Explanations

```
,N       Get [Input, -Input].
⁵æi      Modular inverse of 10 mod each of [Input, -Input].
AÞ       Sort by absolute value.
Ḣ        First.

```
> 8 votes

# Answer
# Brachylog, 14 bytes

```
∧.ℤ≜×₁₀-₁;?%0∧

```

Try it online!
> 6 votes

# Answer
# Japt, ~~16~~ 9 bytes

*Saved way too many bytes thanks to an observation by @xnor*

```
_*AÉ vU}c

```

Test it online! May take a couple of seconds on larger inputs.

### Explanation

```
_  *AÉ  vU}c    Implicit: U = input integer
Z{Z*A-1 vU}c    Ungolfed
Z{        }c    Loop through each integer Z in [0, -1, 1, -2, ...] and yield the first where
  Z*A             Z times 10
     -1           minus 1
        vU        is divisible by the input.
                Implicit: output result of last expression

```
> 5 votes

# Answer
# Python 2, 69 54 53 bytes

**Edit:** -15 bytes thanks to @Mr.Xcoder

**Edit:** -1 byte by using recursion

```
f=lambda a,x=-1:(a%10*x+a/10)%a and f(a,-x-(x>0))or x

```

Try it online!
> 5 votes

# Answer
# Python 2, ~~31 29~~ 27 bytes

```
lambda n:3/(n%5*2-5)*n/10+1

```

Try it online!
> 5 votes

# Answer
# Java 8, ~~23~~ 21 bytes

```
n->3/(n%5*2-5)*++n/10

```

Port of *@Neil*'s JavaScript (ES6) answer, but -2 bytes thanks to *@Nevay* due to implicit flooring of integers.

Try it here.
> 3 votes

# Answer
# Excel, 25 bytes

```
=.3/(MOD(A1,5)*2-5)*A1+.1

```

(Excel corrects to:

```
=0.3/(MOD(A1,5)*2-5)*A1+0.1

```

)
> 2 votes

# Answer
# Japt, 14 bytes

*Inspired by Neil's solution.*

```
Ì*2%E-3 *UÄ /A

```

Test it online!

### Explanation:

```
  Ì  *2%E-3 *UÄ  /A
((UgJ*2%E-3)*U+1)/A
  U                  // Implicit U = Input
   gJ                // Get the char at index -1 (last char)
     *2              // Multiply by 2
       %E            // Mod 14
         -3          // Minus 3
            *U+1     // Multiply by U+1
                 /A  // Divided by 10

```
> 1 votes

# Answer
# Pyke, 12 bytes

```
3Q5%}5-f*hTf

```

Try it here!
> 1 votes

# Answer
# Pyth, 14 bytes

```
h/*x-y%QK5K2QT

```

**Try it here.**
> 1 votes

# Answer
# Pyke, 10 bytes

```
~IIT*tR%)h

```

Try it here!

```
~I         -   Integers
  I     )  -  filter(^, not v)
   T*t     -    ^ *10 -1
      R%   -   input % ^
         h - ^[0]

```
> 1 votes

# Answer
# Python 2, ~~44~~ 43 bytes

*(Crossed out 44 is still 44.)* Thanks to Fireflame241 for saving a byte!

```
P=input();i=P/3
while i*10%P-1:i-=1
print i

```

Try it online!

There is exactly one number between `0` and `P-1` which is an inverse of `10`. But if that inverse `u` happens to be greater than `P/2`, then `(u-P)` is also an inverse, and has a smaller absolute value than `u`. So it turns out that we're really looking for the unique number `x` between `-P/2` and `P/2` which is an inverse of `10`.

The code above does exactly that, starting at (the floor of) `P/2`, and stepping downward until an inverse is reached. This must happen for some number greater than `-P/2` so long as `P` is a prime greater than `10`. More precisely, it will terminate if and only if `P` is coprime to `10`.

**Edit:** It actually turns out that `x` is guaranteed to be between `-P/3` and `P/3`, so the current version starts at `P/3` and steps down from there. See the section labeled **Improved Bound** for an explanation of this.

### Mathematical explanation

It was not immediately obvious to me why the divisibility test worked. Here's an explanation, in case anyone else was wondering.

Let `P` be a prime, greater than `10`, whose last digit is `b`. Thus

`P = 10a + b`

where `a > 0`, and `0 <= b < 10`. In fact `b` is either `1`, `3`, `7`, or `9`, because a prime greater than `10` must end in one of these digits.

Now suppose `bx + a = 0 (mod P)`. Then

`a = -bx (mod P)`

`10a + b = 10(-bx) + b (mod P)`

`0 = 10(-bx) + b (mod P)`

`0 = b(1 - 10x) (mod P)`

Since `P` is prime, the integers `mod P` are an integral domain. So either `b = 0 (mod P)`, or `1 - 10x = 0 (mod P)`.

We know `0 <= b < 10 < P`, so if `b = 0 (mod P)` then `b = 0`. But we said `b` is either `1`, `3`, `7`, or `9`, so this is impossible. Therefore `1 - 10x = 0 (mod P)`, so `10x = 1 (mod P)`. In other words, `x` is the inverse of `10`, modulo `P`.

Now suppose `N` is a nonnegative integer whose last digit is `d`, so `N = 10c + d.` We have a chain of equivalent statements:

`10c + d = 0 (mod P)`

`<==> 10xc + dx = 0 (mod P)`

`<==> c + dx = 0 (mod P)`

QED.

### Usefulness?

I was also wondering whether the divisibility test (given `N = 10c + d`, replace `N` by `dx + c`) would actually be productive in practice. Or at least, does it reliably replace `N` by a number smaller than `N` (in absolute value)?

Suppose `N = 10c + d`, where `c >= 0` and `0 <= d < 10`. Therefore `10c = N - d <= N`. By the triangle inequality,

`|c + dx| <= |c| + |dx| = c + d|x| <= N/10 + d|x|`

`< N/10 + 10|x| <= N/10 + 10P/2 = N/10 + 5P`

Thus if `5P <= 9N/10`, then `|c + dx| < N`.

In particular, if `N >= 6P`, then `|c + dx| < N`. Thus, given `P` we begin by calculating `2P`, `3P`, ..., `6P`, along with `x`. Then given `N`, we run the divisibility test repeatedly until we reach a number less than or equal to `6P`, and check whether the result is any of the numbers `0`, `P`, `2P`, ..., `6P`.

(Of course, whenever we reach a negative number, we replace it by its absolute value, which is fine since `q` is divisible by `P` if and only if `(-q)` is.)

### Improved Bound

I noticed that `|x|/P` never seemed to be close to `1/2`. In fact it seemed like it was always less than `1/3`...or upon closer examination, it was always very close to either `1/10` or `3/10`. The biggest it ever got seemed to be `4/13` (which happens when `P=13` and `x=4`). Why would this be?

Let `u` be an integer and suppose that `10u = kP + 1` for some integer `k`, so `u` is an inverse of `10`, modulo `P`. Then we also know that `k` is relatively prime to `10`, since `k(-P)` is equivalent to `1` modulo `10`.

Now, we know that the inverses of `10` modulo `P` all differ by multiples of `P`, so we can take the integer `u` and either add or subtract multiples of `P` at will, and the result will always still be an inverse of `10` modulo `P`. Suppose we choose to subtract `P` from `u`: we get

`10(u - P) = 10u - 10P = kP + 1 - 10P`

`10(u - P) = (k - 10)P + 1`

In other words, decreasing (respectively, increasing) `u` by `P` corresponds to decreasing (increasing) `k` by `10`. We wish to add/subtract multiples of `P` from `u` until the left-hand side is minimized in absolute value; but the left-hand side is minimized exactly when the right-hand side is minimized, and so we want to add/subtract `10` from `k` until the right-hand side is minimized in absolute value.

But we know that this will happen when `k` is between `-5` and `5`, and therefore (since `k` is relatively prime to `10`) this means `k` is either `-3`, `-1`, `1`, or `3`. (This is the content of @Neil's comment under the OP. **Thanks, Neil!**)

Thus when `|u|` is minimized (i.e., `u=x`), we'll have `x/P = u/P = k/10 + 1/(10P)`, where `k` is either `-3`, `-1`, `1`, or `3`. Therefore `|x|/P <= 3/10 + 1/(10P)`. Equivalently, `|x| <= (3P + 1)/10`.

Further, this inequality is strict at `P=11`, because at `P=11` we have `x=-1` and `k=-1`. The smallest `P` for which equality holds is `P=13` (where `x=4` and `k=3`).

Therefore the largest that `|x|/P` ever gets is `3/10 + 1/(10*13)`, because `P=13` is the first prime for which we have `k=3`, and among those with `k=3`, the `1/(10P)` term is largest when `P` is smallest (i.e., at `P=13`). Therefore, for all `P`, we also have `|x|/P <= 3/10 + 1/130 = 4/13 < 1/3`. This explains why in the above code we can initialize at `i = P/3` rather than having to start at `P/2`.

Further, the bounds in the **Usefulness** section above can now be improved.

*Lemma*: Let `N = 10c + d` where `c > 0` and `0 <= d <= 9`. Then `c + d|x| < N/10 + 9(3P + 1)/10`. (Note the strict inequality.)

Proof of Lemma: by cases. Case I: `d = 0`, so `N = 10c`. Then `c + d|x| = c = N/10 < N/10 + 9(3P + 1)/10`.

Case II: `0 < d <= 9`. Then `10c = N - d < N`, so `c < N/10`. Therefore `c + d|x| < N/10 + d|x| <= N/10 + 9|x| <= N/10 + 9(3P + 1)/10`. QED.

Thus, if `N > 3P` (and `N = 10c + d` as before), then

`3P + 1 <= N`

`9(3P + 1)/10 <= 9N/10`

`N/10 + 9(3P + 1)/10 <= N`

`c + d|x| < N/10 + 9(3P + 1)/10 <= N`

So, if `N > 3P` then `c + d|x| < N`.

Therefore, we only have to find `P`, `2P` and `3P`, along with `x`. Given `N > 0`, while `N > 3P`, we replace `N` by `|c + dx|`, which decreases `N`. Eventually we'll get `N <= 3P`; at that point we stop and check whether `N` is equal to any of the numbers `0`, `P`, `2P`, or `3P`.

We can't do better than `3P` in general. For example suppose `P = 13` and `N = 39`, so `x = 4`. Then replacing `N` by `dx + c = 9(4) + 3` leaves `N` unchanged.
> 1 votes

# Answer
## Whitespace, 92 bytes

Note that this language's syntax consists of *only whitespace*, so each whitespace character has been prefixed here with S, T, or L (corresponding to Space, Tab, and Linefeed, respectively). These can be removed without losing functionality, but they are included here in order to display it correctly.

```
S S S L
T   L
T   T   S S S L
T   T   T   S L
S S S S T   T   L
T   S S L
S L
T   S S S T S T L
T   S T T   S L
S T S S S S S S T   S T L
T   S S T   T   S T S S S S T   L
T   S S S S S S T   S T S L
T   S T S T L
S T L
L
L
.

```

Try it online!
> 1 votes

# Answer
# Husk, 10 bytes

```
ḟȯ¦⁰←*10İ±

```

Try it online! A port of ETHproductions' answer.
> 1 votes

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


title: Grouping Array Data

text:
# Question
Title: Grouping Array Data
Given an integer matrix `a` and a nonnegative integer `i`, output a mapping `b` that maps the distinct values in the `i`th column of `a` to rows of `a` who have that value in the `i`th column.

You may assume that `i` is in the half-open range `[0, num_cols(a))` (or `[1, num_cols(a)]` if you choose to use 1-based indices), and that all integers are within the representable range for your language. Input and output may be done in any reasonable manner, so long as it satisfies the basic requirements of the challenge (2D array -\> mapping from ints to 2D arrays of ints). So long as the mapping is clear and consistent, the keys do not need to be included in the output.

## Examples

```
[[1]], 0 -> {1: [[1]]}
[[3, 4, 5], [1, 4, 2], [5, 5, 5], [7, 7, 7], [1, 5, 9]], 1 -> {4: [[3, 4, 5], [1, 4, 2]], 5: [[5, 5, 5], [1, 5, 9]], 7: [[7, 7, 7]]}
[[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [2, 3, 4, 5, 6], [8, 9, 100, 0, 2]], 4 -> {5: [[1, 2, 3, 4, 5]], 1: [[5, 4, 3, 2, 1]], 6: [[2, 3, 4, 5, 6]], 2: [[8, 9, 100, 0, 2]]}

```

This is , so the shortest answer in bytes wins.

# Answer
> 4 votes
# Octave, 24 bytes

```
@(a,i)@(n)a(a(:,i)==n,:)

```

Try it online!

This creates an anonymous function that returns a matrix whose rows match the criteria. Octave indexes arrays at 1, not zero, and rows of a matrix are separated by a `;`.

Matrices are what Octave does best—so well, in fact, that this challenge can be solved using pure syntax, no built-in functions.

## Explanation

```
@(a,i)                   % creates an anonymous function that...
      @(n)               % returns another function that takes input n and
                         % maps it to the rows of a.
          a(         ,:) % Return all the columns of a, with the rows filtered by...
            a(:,i)       % whether the ith column of each row of a...
                  ==n    % equals n

```

# Answer
> 3 votes
# Wolfram Language (Mathematica), 21 bytes

```
#~GroupBy~Extract@#2&

```

1-indexed. Returns an `Association` mapping.

Try it online!

This is a rare case in which a longer function (`Extract`) reduces the byte count (the shorter one being `Part` or `[[ ... ]]`) because `Extract` can curry. The result is this extremely concise two-function solution.

### Explanation

```
Extract@#2

```

Function that extracts the `<second input>`th element.

```
#~GroupBy~ ...

```

Group the `<first input>` into lists associated with distinct keys `<above function>[element]`.

# Answer
> 3 votes
# Ruby, 26 bytes

```
->a,i{a.group_by{|x|x[i]}}

```

Try it online!

# Answer
> 2 votes
# Clean, 40 bytes

```
import StdEnv

```

#

```
\n l i=filter(\a=a!!n==i)l

```

Try it online!

A lambda (`:: Int [[Int]] Int -> [[Int]]`) where a partial application of just the first two arguments gives a mapping on the third argument.

# Answer
> 2 votes
# , 16 bytes

-3 bytes thanks to FrownyFrog!

```
{"1(~.@[;"0</.)]

```

Try it online!

## Explanation:

A dyadic verb, taking `i` as its left argument and `a` as its right one.

`]` is the right argument, `a`

`{"1` finds the numbers at `i`th column on each row

`</.` boxes groups from the right argument, selected by the keys, provided by the left one

`~.@[` finds the unique keys

`;"0` links the keys to the selected groups

# Answer
> 2 votes
# Haskell, ~~64~~ 60 bytes

```
import Data.List
i!l=[(k,[a|a<-l,a!!i==k])|k<-nub$map(!!i)l]

```

Try it online!

# Answer
> 2 votes
# jq, 100 bytes

uses an object for output, takes a command line argument `$f` plus an array on standard input

```
([.[]|.[$f]]|unique) as $c|[$c[] as $d|{($d|tostring):([.[]|[select(.[$f]==$d)]]|add)}]|add

```

deobfuscated:

```
.fieldnum as $field |
.input as $input |
([$input[] | .[$field]] | unique) as $categories |
[
    $categories[] as $category |
    {
        ($category | tostring) :
            ([$input[] | [select(.[$field]==$category)]] | add)
    }
] | add

```

# Answer
> 2 votes
# , ~~79~~ 55 bytes

```
function(a,i)for(z in unique(a[,i]))print(a[a[,i]==z,])

```

Try it online!

24 bytes shaved off by @JayCe

# Answer
> 1 votes
# Proton, 29 bytes

```
a=>i=>n=>filter(r=>r[i]==n,a)

```

Try it online!

-3 bytes thanks to Mr. Xcoder using currying and `filter` (TBH I'm kind of surprised that `filter` actually worked)

# Answer
> 0 votes
# Python 3, 45 bytes

```
lambda a,i:lambda n:[r for r in a if r[i]==n]

```

Try it online!

Returns the mapping represented as an anonymous lambda.

# Answer
> 0 votes
# JavaScript (Node.js), 29 bytes

```
a=>i=>n=>a.filter(e=>e[i]==n)

```

Try it online!

Updated now that I realize the loose output requirements. This uses currying as a golfing technique, and it also returns a function that takes an input `n` and maps that to the proper arrays.

# Answer
> 0 votes
# Jelly, 5 bytes

```
ịⱮ⁹¹ƙ

```

Try it online!

Omits the keys, but should be clear.

Argument 1: **i + 1**
Argument 2: **a**

# Answer
> 0 votes
# Java 10, ~~135~~ 64 bytes

```
m->i->n->new java.util.Stack(){{for(var a:m)if(a[i]==n)add(a);}}

```

Returns a `Function<Integer, List<int[]>>` accepting an integer-input `n`, which returns a List of arrays (matrix-rows) where the `i`'th values equal the given `n`.

Try it online.

**Explanation:**

```
m->i->               // Method with int-matrix and int parameters and Function return-type
  n->                //  Return a Function with integer as parameter
    new java.util.Stack(){{
                     //  and List of integer-arrays as return-type
      for(var a:m)   //   Loop over the arrays of the input-matrix
        if(a[i]==n)  //    If the `i`'the value of the current array equals `n`:
          add(a);}}  //     Add it to the return-List

```

# Answer
> 0 votes
# Husk, 7 bytes

```
fo=⁰!²⁴

```

Try it online! This function is 1-indexed and, when partially applied, returns a function of type `TNum -> [[TNum]]` which implements the desired mapping.

---
Tags: code-golf, array
---


title: Implement the divisibility-by-7 rule

text:
# Question
Title: Implement the divisibility-by-7 rule
To check whether a decimal number is divisible by 7:

> Erase the last digit. Multiply it by 2 and subtract from what is left. If the result is divisible by 7, the original number is divisible by 7.

(also described e.g. here)

This rule is good for manual divisibility check. For example:

> Is 2016 divisible by 7?
>
> Subtract `6*2` from 201; we get 189. Is this divisible by 7? To check it, let's apply the rule again.
>
> Subtract `9*2` from 18; we get 0. Therefore, 2016 is divisible by 7.

In this challenge, you should apply this rule until the divisibility status is *obvious*, that is, the number is not greater than 70 (however, see below for details). Make a function or a full program.

**Input**: a positive integer; your code should support inputs up to 32767 (supporting arbitrary-precision integers is a bonus; see below).

**Output**: an integer (possibly negative), not greater than 70, that is a result of applying the divisibility-by-7 rule zero or more times.

Test cases:

```
Input                   Output      Alternative output

1                       1
10                      10          1
100                     10          1
13                      13          -5
42                      42          0
2016                    0
9                       9
99                      -9
9999                    -3
12345                   3
32767                   28          -14

---------- Values below are only relevant for the bonus

700168844221            70          7
36893488147419103232    32          -1
231584178474632390847141970017375815706539969331281128078915168015826259279872    8

```

Where two possible outputs are specified, either result is correct: the second one corresponds to applying the rule one more time. It's forbidden to apply the rule on a single-digit number: if you erase the digit, nothing (not 0) is left.

---

**Bonus**: If your algorithm

where `n` is the number of decimal digits:

Subtract 50% from your code's byte count.

**Real bonus**:

In addition, if your algorithm reads the input in normal direction, starting from the most significant digit, subtract 50% once again - your score is 25% of your byte count (it seems possible, but I'm not absolutely sure).

# Answer
# Golfscript, ~~27~~ 22 bytes

```
{.9>{.10/\10%2*-f}*}:f

```

You can use it this way:

```
1000f

```

## Explanation

```
{.9>{.10/\10%2*-f}*}:f
{                  }:f    # Define block 'f' (similar to a function)
 .                        # Duplicate the first value of the stack
  9>{            }*       # If the value on top of the stack is greater than 9 then the block is executed
     .10/\10%2*-          # Same as nb/10 - (nb%10 * 2) with some stack manipulations '.' to duplicate the top of the stack and '\' to swap the the first and second element of the stack
                f         # Execute block 'f'

```

5 bytes saved thanks to Dennis !
> 23 votes

# Answer
## Haskell, 35 bytes

```
until(<71)(\n->div n 10-2*mod n 10)

```

Usage example: `until(<71)(\n->div n 10-2*mod n 10) 36893488147419103232` -\> `32`.

Nothing much to explain, it's a direct implementation of the algorithm.
> 13 votes

# Answer
# Jelly, 11 bytes

```
d⁵Uḅ-2µ>9$¿

```

Try it online!

### How it works

```
d⁵Uḅ-2µ>9$¿  Main link. Input: n

d⁵           Divmod; return [n : 10, n % 10].
  U          Upend; yield [n % 10, n : 10].
   ḅ-2       Convert from base -2 to integer, i.e., yield -2 × (n % 10) + (n : 10).

      µ      Push the previous chain as a link and begin a new, monadic chain.
          ¿  Apply the previous chain while...
       >9$     its return value is greater than 9.

```
> 9 votes

# Answer
# Python 2, 38 bytes

```
f=lambda x:f(x/10-x%10*2)if x>70else x

```

Try it here!

Simple recursive approach. Prints x if its \< 70 otherwise applies the divisibility rule and calls itself with the result.
> 6 votes

# Answer
# Pyth, 13 bytes

```
.W>H9-/ZTyeZQ

```

Try it online: Demonstration or Test Suite

This will print all the alternative answers.

### Explanation:

```
.W>H9-/ZTyeZQ
            Q   read a number from input
.W              while
  >H9              the number is greater than 9
                do the following with the number:
      /ZT          divide it by 10
     -             and subtract
         yeZ       2*(number%10)

```
> 6 votes

# Answer
# Julia, ~~27~~ 26 bytes

```
f(x)=x>9?f(x÷10-x%10*2):x

```

This is a recursive function that accepts an integer and returns a `BigInt`. If the input is a large number like in the last example, Julia parses it as a `BigInt`, so no manual conversion is necessary.

The approach is just a straightforward implementation of the algorithm. It will produce the alternate outputs. Taking the modulus when dividing by 10 yields the last digit and the quotient from integer division by 10 yields everything but the last digit.

Saved a byte thanks to Dennis!
> 5 votes

# Answer
# Pyth, 17 bytes

```
L?<b70by-/bT*%bT2

```

Try it here!

Same recursive approach as in my python answer. Defines a lambda `y` which is called like this: `y12345`.
The byte counter in the online interpreter shows 19 bytes because I added the lambda call to it, so you can just try it by hitting the run-button.

## Explanation

```
L?<b70by-/bT*%bT2

L                  # Defines the lambda y with the parameter b
 ?<b70             # if b < 70:
      b            # return b, else:
       -/bT*%bT2   # calculate b/10 - b%10*2 and return it

```
> 4 votes

# Answer
## CJam - 19 bytes

Do-while version:

```
r~A*{`)]:~~Y*-_9>}g

```

Try it online or While version #1:

```
r~{_9>}{`)]:~~Y*-}w

```

Try it online or While version #2:

```
r~{_9>}{_A/\A%Y*-}w

```

Try it online.

```
r~                     | Read and convert input
  A*                   | Multiply by 10 to get around "if" rule
     `                 | Stringify
      )                | Split last character off
       ]               | Convert stack to array
        :~             | Foreach in array convert to value
          ~            | Dump array
           Y*          | Multiply by 2
             -         | Subtract
              _        | Duplicate
               9>      | Greater than 9?
    {            }g    | do-while

```
> 4 votes

# Answer
# GNU dc, ~~20~~ 15 bytes

```
[10~2*-d70<F]sF

```

This defines my first (ever) dc function, `F`. It takes input on the top of stack, and leaves its output at top of stack. Example usage:

```
36893488147419103232
lFxp
32

```
> 3 votes

# Answer
# Oracle SQL 11.2, 116 bytes

```
WITH v(i)AS(SELECT:1 FROM DUAL UNION ALL SELECT TRUNC(i/10)-(i-TRUNC(i,-1))*2 FROM v WHERE i>70)SELECT MIN(i)FROM v;

```

Un-golfed

```
WITH v(i) AS
(
  SELECT :1 FROM DUAL
  UNION ALL
  SELECT TRUNC(i/10)-(i-TRUNC(i,-1))*2 FROM v WHERE i>70
)
SELECT MIN(i) FROM v;

```
> 3 votes

# Answer
# Haskell, ~~157~~ ~~192~~ ~~184~~ ~~167~~ ~~159~~ ~~147~~ 138+5 bytes - 50% = 71.5 bytes

**O(1) space, O(n) time, single-pass!**

```
h d=d%mod d 10
d%r=(quot(r-d)10,r)
p![d]=d-p*10
p![d,e]=d#(e-p)
p!(d:e:f)|(b,a)<-quotRem(2*d)10,(q,r)<-h$e-a-p=(b+q)!(r:f)
m#0=m
m#n=n-2*m
(0!)

```

Use as `0![6,1,0,2]` to apply the rule to 2016, i.e. pass it a number in stream form with least significant figure first. In this way, it will pass over the number digit by digit, applying the rule with O(1) space complexity.

The ungolfed code is here:

```
import Data.Char

{- sub a b = sub2 0 a b
  where
    sub2 borrow (a:as) (b:bs) = res : sub2 borrow2 as bs
      where
        (borrow2, res) = subDig borrow a b
    sub2 borrow (a:as) [] = sub2 borrow (a:as) (0:[])
    sub2 _ [] _ = [] -}

--subDig :: Int -> Int -> Int -> (Int, Int)
subDig borrow a b = subDig2 (a - b - borrow)
  where
    subDig2 d = subDig3 d (d `mod` 10)
    subDig3 d r = ((r-d) `quot` 10, r)

seven ds = seven2 0 ds
seven2 borrow (d:e:f:gs) = seven2 (b + borrow2) (res:f:gs)
  where
    (a, b) = double d
    (borrow2, res) = subDig borrow e a
seven2 borrow (d:e:[]) = finalApp d (e-borrow)
seven2 borrow (d:[]) = d - borrow*10

double d = ((2*d) `mod` 10, (2*d) `quot` 10)

finalApp m 0 = m
finalApp m n = n - 2*m

num2stream :: Int -> [Int]
num2stream = reverse . map digitToInt . show
sev = seven . num2stream

```

The gist of how this works is that it implements a digit-by-digit subtraction algorithm, but takes advantage of the fact that each number to be subtracted is at most 2-digits, and so we can subtract an arbitrary amount of these 1-or-2 digit numbers from the main one (as well as eating the least significant digits).

The subtraction algorithm is O(1) and only stores the current 'borrow' value. I altered this to add in the extra digit (either 0 or 1), and we note that this borrow value is bounded (within the range \[-2,2\] so we need only 3 bits to store this).

The other values stored in memory are temporary variables representing the current 2-digit number to add, a single look-ahead in the stream, and to apply one step of the subtraction algorithm (i.e. it takes two digits and a borrow value, and returns one digit and a new borrow value).

Finally at the end it processes the last two digits in the stream at once to return a single-digit number rather than a list of digits.

N.B. The `sev` function in the ungolfed version will work on an `Integer`, converting it into the reversed stream form.
> 3 votes

# Answer
# Mathematica, ~~47~~ 44 bytes

```
If[#>70,#0[{1,-2}.{⌊#/10⌋,#~Mod~10}],#]&

```

Simple recursive approach. Could probably be golfed further.
> 2 votes

# Answer
# R, 43 bytes

```
x=scan();while(x>70)x=floor(x/10)-x%%10*2;x

```

Explanation:

```
x=scan()                                      # Takes input as a double
        ;                                     # Next line
         while(x>70)                          # While-loop that runs as long x > 70
                      floor(x/10)             # Divide x by 10 and round that down
                                 -x%%10*2     # Substract twice the last integer
                    x=                        # Update x
                                         ;    # Next line once x <= 70
                                          x   # Print x

```

Sample runs:

```
> x=scan();while(x>70)x=floor(x/10)-x%%10*2;x
1: 9999
2:
Read 1 item
[1] -3

> x=scan();while(x>70)x=floor(x/10)-x%%10*2;x
1: 32767
2:
Read 1 item
[1] 28

```
> 2 votes

# Answer
# C, 56 bytes - 75% = 14

Although this doesn't give the exact same numbers as the test cases, it satisfies the spirit of the question (and arguably more). It correctly identifies exact multiples of 7, and gives the exact remainder for other numbers (since it doesn't ever use negative numbers).

```
n;f(char*c){for(n=0;*c;)n-=n>6?7:'0'-n-n-*c++;return n;}

```

There is no multiplication or division in the algorithm, only addition and subtraction, and digits are processed in a single pass from left to right. It works as follows, starting with 0 in the accumulator:

1. Subtract 7 if necessary, and again if still necessary
2. Multiply the running total by three, and add the next digit

The "multiply by three" step is written as `n-=-n-n` to save a byte and to avoid the multiply operator.

When we hit the end, we don't subtract sevens, so the result will be in the range 0-24; if you want a strict modulus (0-7), substitute `*c` with `*c||n>6` in the `for` loop condition.

It qualifies for the enhanced bonus, because it

* supports arbitrary-precision integers
* performs only one pass on the input, in left-to-right order
* has space complexity O(1)
* has time complexity O(n).

## Test program and results

```
#include <stdio.h>
int main(int argc, char **argv) {
    while (*++argv)
        printf("%s -> %d\n", *argv, f(*argv));
    return 0;
}

```

```
540 -> 15
541 -> 16
542 -> 17
543 -> 18
544 -> 19
545 -> 20
546 -> 21
547 -> 22
548 -> 23
549 -> 24
550 -> 18
99 -> 15
999 -> 12
12345 -> 11
32767 -> 7
700168844221 -> 7
36893488147419103232 -> 11
231584178474632390847141970017375815706539969331281128078915168015826259279872 -> 11

```

## Alternative version

Here's one that recurses (you'll want to enable compiler optimizations to do tail-call transformation or you may overflow your stack; I used `gcc -std=c89 -O3`):

```
f(c,n)char*c;{return n>6?f(c,n-7):*c?f(c+1,n+n+n+*c-'0'):n;}

```

Call it with '0' as the second argument.

Both versions calculate the remainder-modulo-seven of a 60,000 digit number in under 50 milliseconds on my machine.
> 2 votes

# Answer
## ~~JavaScript ES6, 38 bytes~~

```
a=i=>i>70?a(Math.floor(i/10)-i%10*2):i

```

Fails with `36893488147419103232` and using `~~(1/10)` will also fail for `700168844221`

Test:

```
a=i=>i>70?a(Math.floor(i/10)-i%10*2):i
O.textContent = O.textContent.replace(/(-?\d+) +(-?\d+)/g, (_,i,o) =>
  _+": "+(a(+i)==o?"OK":"Fail")
);
```

```
<pre id=O>1                       1
10                      10
100                     10
13                      13
42                      42
2016                    0
9                       9
99                      -9
9999                    -3
12345                   3
700168844221            70
36893488147419103232    32</pre>
```
> 1 votes

# Answer
# Mathematica, 33 bytes

```
#//.a_/;a>70:>⌊a/10⌋-2a~Mod~10&

```

**Test case**

```
%[9999]
(* -3 *)

```
> 1 votes

# Answer
# JavaScript ES6, ~~140~~ 142 bytes

```
f=s=>s>9?eval("t=s.replace(/.$/,'-$&*2');for(i=-1;0>(n=eval(u=t[c='slice'](i-4)))&&u!=t;i--);n<0?n:f(t[c](0,i-4)+('0'.repeat(-i)+n)[c](i))"):s

```

This is true arbitrary-precision math, even works on the largest test-case.

This function recursively removes the last digit from the string, then subtracts 2 * the last digit from the remaining numerical string by iteratively incrementing the amount of digits to apply to the minuend until the difference is positive. Then it appends that difference to the end of the string with appropriately padded `0`s and calls itself recursively until its numerical value is less than or equal to `9`.

* Golfed 7 bytes thanks to @Neil (yes I know I gained 2 bytes but I fixed a few bugs that caused the function to freeze or return wrong output for some cases).

```
f=s=>s>9?eval("t=s.replace(/.$/,'-$&*2');for(i=-1;0>(n=eval(u=t[c='slice'](i-4)))&&u!=t;i--);n<0?n:f(t[c](0,i-4)+('0'.repeat(-i)+n)[c](i))"):s;[['1',1],['10',1],['100',1],['13',-5],['42',0],['2016',0],['9',9],['99',-9],['9999',-3],['12345',3],['700168844221',7],['36893488147419103232',-1],['231584178474632390847141970017375815706539969331281128078915168015826259279872',8]].map(a=>document.write(`<pre>${f(a[0])==a[1]?'PASS':'FAIL'} ${a[0]}=>${a[1]}</pre>`))
```
> 1 votes

# Answer
## Perl 5, ~~47~~ 46 bytes

Had to use `bigint`for the last test case. (It returns 20 without)

```
use bigint;$_=<>;while($_>9){$_-=2*chop;}print

```

Not really sure it's a candidate for the bonus, so I didn't take it into account. (I think it does, but I'm not really accustomed to the concepts)

Try it here!
> 1 votes

# Answer
## ES6, 108 bytes

```
f=(s,n=0)=>s>1e9?f(s.slice(0,-1),((1+s.slice(-1)-n%10)%10*21+n-s.slice(-1))/10):s>9?f(((s-=n)-s%10*21)/10):s

```

Works for 2²⁵⁷ and 1000000000000000000001, but could use further golfing.
> 1 votes

# Answer
# Brain-Flak, ~~368~~ 360 bytes

Try it Online!

```
([([({})]<(())>)](<>)){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}({}<>){{}(({}))(<((()()()()()){}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>([([([(({}<{}><>)<([{}]{})(<((()()()()()){}(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)>){}]{})]<(())>)(<>)]){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}({}<>)}{}

```

## Explanation

To start off all of the code is in a loop that runs until the top of the stack is less than zero:

```
([([({})]<(())>)](<>)){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}({}<>)
{{}
 ...
 ([([({})]<(())>)](<>)){({}())<>}{}<>{}{}<>(({})){{}{}<>(<(())>)}{}({}<>)
}{}

```

Inside of the loop we run the divisible by seven algorithm:

Duplicate the top of the stack

```
(({}))

```

Take the mod 10 of the top of the stack (last digit)

```
(<((()()()()()){}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}><>)

```

This is a bit of a mess but it does the rest of the algorithm I might explain it later but I don't entirely remember how it works:

```
([(({})<([{}]{})(<((()()()()()){}(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)>){}]{})

```
> 1 votes

# Answer
## C#, ~~111~~ 104 bytes

```
int d(int n){var s=""+n;return n<71?n:d(int.Parse(s.Remove(s.Length-1))-int.Parse(""+s[s.Length-1])*2);}

```
> 1 votes

# Answer
# PHP, 50 bytes

```
for($n=$argv[1];$n>9;)$n=$n/10|0-2*($n%10);echo$n;

```

uses alternative output; works up to `PHP_INT_MAX`

---

string version, works for any (positive) number (64 bytes):

```
for($n=$argv[1];$n>9;)$n=substr($n,0,-1)-2*substr($n,-1);echo$n;

```
> 1 votes

# Answer
## Java, 133 bytes

```
int d(int n){String s=""+n;return n<71?n:d(Integer.parseInt(s.replaceFirst(".$",""))-Integer.parseInt(""+s.charAt(s.length()-1))*2);}

```

I hate how verbose `Integer.parseInt` is. Ungolfed:

```
static int div(int n) {
    if (n <= 70) {
        return n;
    } else {
        String num = ("" + n);
        int last = Integer.parseInt("" + num.charAt(num.length() - 1));
        int k = Integer.parseInt(num.replaceFirst(".$", "")) - last * 2;
        return div(k);
    }
}

```
> 0 votes

# Answer
# Husk, 13 bytes

```
Ω≤70§-ȯD→d÷10

```

Try it online!

Tied with Pyth, using a modified method.

## Explanation

```
Ω≤70§-ȯD→d÷10
Ω≤70          until the number is ≤ 70,
    §-        subtract
        →d    the last digit
      ȯD      doubled
          ÷10 from the number floor divided by 10

```
> 0 votes

---
Tags: code-golf, number-theory, division
---


title: Shifty XORyption

text:
# Question
Title: Shifty XORyption
Write a program or function (or set of programs/functions) to encrypt and decrypt data given the following specification:

## Encryption

1. Calculate an XOR hash of the input by XOR-ing every byte with each-other.
2. XOR every byte of the input by this hash.
3. Shift the result four bits left.
4. Pad the left side with the first four bits of the XOR hash.
5. Pad the right side with the last four bits of the XOR hash.

## Example

* Given input: `"G0lf"` (`0x47306C66`)
* Calculate XOR hash: `0x47 ^ 0x30 ^ 0x6C ^ 0x66 = 0x7D`
* XOR every byte by hash: `0x3A4D111B`
* Expected result (after shift and pad): `"s¤Ñ\x11½"` (`0x73A4D111BD`)

## Rules

* Your program/function can input/output of whatever type makes sense in your golfing language of choice *(String, Byte Array, etc)* as long as the input/output are the actual bytes. For example, you may not output a hexidecimal string.
* Encryption and decryption can be separated into separate programs (score will be the their combined size) or a single one. Single methods can take an argument for whether it should encrypt or decrypt.
* Input for encryption can be expected to be at least 1 byte in size.
* Input for decryption can be expected to be at least 2 bytes.
* Non-printable bytes do not need to be escaped in the output.

# Answer
# CJam, 36 + 34 = 70 bytes

A bit different approach using binary forms

**Encrypter**:

```
q_:^:Hf^H+{i2b8Ue[}%)4/~@\]e_8/2fb:c

```

How it works:

```
q_:^                                  e# Read input as string, copy and XOR all the chars
    :Hf^                              e# Store the XOR in H and XOR each char with H
        H+                            e# Append H to the char array
          {       }%                  e# On each of the elements in the array
           i2b                        e# Convert the ASCII value to binary
              8Ue[                    e# Pad with 0 so that the length is 8
                    )                 e# Pop out the last array element, which is H
                     4/~@\            e# Put first 4 bits of H before the input array
                                      e# And rest 4 after it
                          ]e_8/       e# Flatten everything into a single array and group
                                      e# into pieces of 8 bits
                               2fb:c  e# Convert each 8 bit part to integer and then to
                                      e# its character form

```

**Decrypter**:

```
q{i2b8Ue[4/~}%)\(@+2b\:+8/2fb\f^:c

```

How it works:

```
q{          }%                      e# For each character of the input string
  i2b                               e# Convert to ASCII code and then to its binary form
     8Ue[                           e# Pad with enough 0 so that length is 8 bit
         4/~                        e# Split into parts of 4 and unwrap
              )\(@+                 e# Take out the first and last 4 bit group and join
                                    e# them together to get the XOR Hash H
                   2b\              e# Convert H to decimal form and swap to put the
                                    e# remaining converted input array on top
                      :+8/          e# Join all bits together and split into groups of 8
                          2fb       e# Convert each 8 but group to decimal form
                             \f^    e# Swap to put H on top and XOR each number with H
                                :c  e# Get character from each of the ASCII value

```

Try the encrypter and decrypter online
> 6 votes

# Answer
# Pyth, 69 bytes

```
Ksm>+0jCd16_2zJ?,hKeKQmxFdCcK2=KsmmxFkC,dJc?tPKQK2smCid16c?KQ++hJKeJ2

```

This combines encryption and decryption, simply add a `0` as argument for encryption or a `1` for decryption. The reason for this is simple. Converting strings into bits (or 4 bit integer) or the reverse is really really long in Pyth. By combining the both functions into one program, I can save a lot of bytes.

Online demonstrations: Encryption and Decryption.

### Explanation:

The first part converts the input into a list of 4-bit integer (each char get converted into 2 4-bit integer) and stores it in `K`.

```
  m          z   map each character d of input (=z) to:
       Cd            the ascii-value of d
      j  16          convert the result into base 16
   >+0     _2        insert a zero to the front and take the last 2 values
                     (so that each char gets mapped to exactly 2 numbers)
Ks               chain all these tuples and assign them to K

```

The second part determines the hash values and stores them in `J`. If `Q==0` it computes them by xor, otherwise it takes the first and last value of `K`.

```
 ?     Q           ... if Q (=second input) else ...
  ,hKeK            [K[0], K[-1]]
        m   CcK2   map each d of zipped(K chopped into pairs) to:
                   [zipped(...) gives me 2 lists, one with the values of the even indices, and one with the odd indices]
         xFd           fold the list d by xor
J                  store the result in J (this is the hash value)

```

The next part does the xor using the hash values. When `Q == 0` it is performed on the complete list `K`, otherwise only on the list `K` without the first and last value.

```
=KsmmxFkC,dJc?tPKQK2
             ?tPKQK    K[1:-1] if Q else K
   m        c      2   map each d of [... chopped into pairs] to:
    m   C,dJ              map each pair k of zip(d,J) to:
     xFk                     apply xor to the 2 values in k
=Ks                    chain all these tuples and assign them to K

```

And the last part converts `K` back to chars:

```
smCid16c?KQ++hJKeJ2
        ?KQ++hJKeJ    K if Q else J[0] + K + J[1]
 m     c          2   map each pair of [... chopped into pairs] to:
   id16                  convert d into a single integer
  C                      convert to char
s                     join all chars and print

```
> 6 votes

# Answer
# Javascript (*ES6*) 83 + 73 = 156

Both functions take input as and ouput an array of numbers to represent bytes.

**Encrypt 85 84 83**

```
E=s=>s.concat((h=s.reduce((x,y)=>x^y))<<4&240^h).map(x=>a<<4&240|(a=x^h)>>4,a=h>>4)

```

**Decrypt 75 73**

```
D=s=>s.map(x=>(a<<4&240|(a=x)>>4)^h,h=(a=s.shift())&240|s[~-s.length]&15)

```

**Demonstration (Firefox only)**

```
E=s=>s.concat((h=s.reduce((x,y)=>x^y))<<4&240^h).map(x=>a<<4&240|(a=x^h)>>4,a=h>>4)
D=s=>s.map(x=>(a<<4&240|(a=x)>>4)^h,h=(a=s.shift())&240|s[~-s.length]&15)

toHexString = x=>'0x'+x.map(y=>y.toString(16)).join('')

input = [...'G0lf'].map(x=>x.charCodeAt());
document.write('Input: ' + toHexString(input) + '<br />');

encrypted = E(input);
document.write('Encrypted: ' + toHexString(encrypted) + '<br />');

decrypted = D(encrypted);
document.write('Decrypted: ' + toHexString(decrypted) + '<br />');
```

---

**Using Strings 131 + 129 = 260**

And just for fun... here's some versions which use strings for input/output instead.

```
E=(s,h=0)=>[for(x of s)(h^=y=x.charCodeAt(),y)].concat(h<<4&240^h).map(x=>String.fromCharCode(a<<4&240|(a=x^h)>>4),a=h>>4).join('')

D=s=>(s=[s.charCodeAt(j=i)for(i in s)]).map(x=>String.fromCharCode((a<<4&240|(a=x)>>4)^h),h=(a=s.shift())&240|s[~-j]&15).join('')

E('G0lf') // 's¤Ñ\x11½'
D('s¤Ñ\x11½') // 'G0lf'

```
> 0 votes

# Answer
# Jelly, 25 + 17 = 42 bytes

```
Oµ^^/;^/b⁴Ż€-.ịⱮµṪjFs2ḅ⁴Ọ

```

Try it online!

```
Ob⁴FµḢ,Ṫ,s2$ḅ⁴^/Ọ

```

Try it online!

Full round trip.

+6 bytes correcting a bug which looks like it also plagues Martin's CJam answer

## How they work

### Encryption

```
Oµ^^/;^/b⁴Ż€-.ịⱮµṪjFs2ḅ⁴Ọ - Main link. Takes S on the left
O                         - Convert S to char codes; Call this O
 µ                        - Discard S and use O as the left argument
   ^/                     - Reduce O by XOR to get the hash, X
  ^                       - XOR each element in O by X
      ^/                  - X
     ;                    - Concatenate to the end of O
         ⁴                - 16
        b                 - Convert each to base 16
          Ż€              - Prepend a 0 to each
               Ɱ          - For each:
            -.ị           -   Get the -0.5th index
                              This returns the last 2 elements of the list
                              As the ị atom returns [floor(x)ị, ceil(x)ị] for
                              non-integer x, and uses 1-indexing. Therefore,
                              -.ị = -0.5ị = [floor(-.)ị, ceil(-.)ị]
                                  = [-ị, 0ị] = last 2 elements

                              For a integer < 16, b⁴ returns a singleton list
                              Otherwise, it'll return (here) a pair
                              We then prepend 0 so each list has either 2 or 3 elements
                              and ignore the leading 0 if it already had 2 elements

                            Call this list of nibbles N
                            Currently, N = [[a, b], [c, d], ..., [x, y]]
                            where [a, b] are the nibbles of the XOR'ed elements
                            and [x, y] are the nibbles of X

                µ         - Discard O and use N as the left argument
                 Ṫ        - Remove [x, y] from N
                  j       - Join [x, y] with N, yielding [x, [a, b], ..., y]
                   F      - Flatten; [x, a, b, c, d, ..., y]
                    s2    - Split into pairs; [[x, a], [b, c], ...]
                      ḅ⁴  - Convert each from base 16
                        Ọ - Convert back to characters

```

### Decryption

```
Ob⁴FµḢ,Ṫ,s2$ḅ⁴^/Ọ - Main link. Takes S on the left
O                 - Convert to char codes
 b⁴               - Convert to hex
   F              - Flatten; Call this list of hex bytes H = [x, a, b, ..., y]
    µ             - Discard S and use H as the left argument
     Ḣ            - Remove the first element of H, x
       Ṫ          - Remove the final element of H, y
      ,           - Pair; [x, y]
           $      - Group the previous two links as a monad f(H):
         s2       -   Split into pairs
        ,         - Pair with [x, y]; [[x, y], [[a, b], ...]]
            ḅ⁴    - Convert each from hex
              ^/  - Reduce by XOR
                Ọ - Convert into chararacters

```
> 0 votes

---
Tags: code-golf, cryptography, bitwise
---


# Question
Title: Number of ways to sum [1..n] with [n+1..2n] such that each sum is prime
Let \\$n \> 0\\$. Let \\$X = 1, 2,...,n\\$ and \\$Y = n+1, n+2, ..., 2n\\$. Define \\$a(n)\\$ as the number of permutations \\$p\\$ of \\$Y\\$ such that every element of \\$X + p(Y)\\$ is prime. For example:

```
n = 2
X = [1,2]
Y = [3,4]
p_0(Y) = [3,4] => X + p0(Y) = [4,6] => No
p_1(Y) = [4,3] => X + p1(Y) = [5,5] => Yes
a(2) = 1

```

In as few bytes as possible, write a program or function which produces this sequence (A070897), either as an infinite list on STDOUT, or in your interpreter of choice.

The output should start at \\$n=1\\$, and each entry should be on a newline and undecorated, i.e.:

```
1
1
1
1
2
...

```

## Examples

\\$a(1)=1\\$ because each list `[1]`, `[2]` has only 1 element

\\$a(5)=2\\$ because there are two permutations: `[(1,10),(2,9),(3,8),(4,7),(5,6)]` and `[(1,6),(2,9),(3,10),(4,7),(5,8)]`

## Rules

No built-in primality tests. No lookup table ;). No standard loopholes.

# Answer
> 4 votes
# Pyth - 35 32 27 bytes

The obvious approach. The while loop logic is taking a lot of bytes. Thanks to @Jakube for telling me about `.V` and saving a lot of bytes. Explanation coming soon.

```
.V1lf!sm%h.!J++hbd@TdhJb.pb

```

Try first n here online

# Answer
> 4 votes
# CJam, ~~38 35~~ 32 bytes

```
0{)_e!{ee{1b1$+)_m!)\)%},!},,p}h

```

This is an infinite list version. If you run it using the Java compiler, you will keep on getting result for increasing `n` on each line until the program crashes (if it does. Did not test).

For sanity, run the finite version using this link. You can change the number in the input to see a longer list.

**How it works**:

```
0{                            }h  e# This acts as an infinite do-while loop here
  )_                              e# Starting from 0, increment the number and copy it
                                  e# Lets call this number at each iteration as N
    e!                            e# Get all possible permutations of the array 0..N-1
      {                   },      e# Filter the list of permutations based on this code block
       ee                         e# Convert the permutation array into an [index value]
                                  e# pair array. For ex. [5 2]ee gives [[0 5] [1 2]]
         {             },         e# Pass each index value pair through this filter
          1b1$+)                  e# Sum the index and value and add current N + 1 to it
                                  e# At this point, we have something equivalent to
                                  e# pairwise addition of [1 .. n] and [n .. 2n - 1]
                _m!)\)%           e# Now we do ((N - 1)! + 1)%N to see if N is prime
                                  e# This is Wilson's theorem and will give 0 for primes
                         !        e# Now we have a filtered index-value pairs which all
                                  e# correspond to non-prime numbers. If the list is empty,
                                  e# Then all numbers are prime. Thus we do a ! on empty list
                                  e# to get truthy.
                            ,p    e# Take the total permutations where X + pN(Y) are all
                                  e# primes and print the number to STDOUT immediately
                                  e# We are left with the initial incremented N on stack
                                  e# which is always non-zero, so the loop continues
                                  e# infinitely

```

*UPDATE: 2 bytes saved, thanks to Martin!*

# Answer
> 3 votes
# Python 2, 147 bytes

```
from itertools import*
n=1;R=range
while n:print sum(all(x%d for x in map(sum,zip(R(n),c))for d in R(2,x))for c in permutations(R(n+2,2*n+2)));n+=1

```

The `import itertools` rule of thumb tells me there's probably a better way...

A few bytes are saved by summing `[0 ... n-1]` with `[n+2 ... 2n+1]` instead.

# Answer
> 1 votes
# Jelly, 20 bytes

```
+RŒ!+€RÆḍỊP€SṄ¬
1Ç1#

```

Try it online!

This gets exponentially slower for each new \\$n\\$ it calculates, so times out on TIO after having printed \\$a(9) = 40\\$. Given enough time/memory however, it will eventually print all the elements in the sequence.

## How it works

```
1Ç1# - Main link. No arguments
1    - Starting from n = 1...
   # - ...count up n = 1, 2, ...
  1  - ...until 1 n returns true when...
 Ç   - ...run over the helper link.
       As the helper link ends with ¬ (logical NOT), no n will return true

+RŒ!+€RÆḍỊP€SṄ¬ - Helper link. Takes n on the left
 R              - [1, 2, ..., n]
+               - [n+1, n+2, ..., 2n]
  Œ!            - All permutations
      R         - [1, 2, ..., n]
     €          - For each perumation:
    +           -   Add [1, 2, ..., n] elementwise
       Æḍ       - Proper divisor counts
         Ị      - Equal to 1?
           €    - For each:
          P     -   All true?
            S   - Count the true permutations
             Ṅ  - Print
              ¬ - Logical NOT to continue the infinite loop

```

---
Tags: code-golf, combinatorics, primes, sequence, permutations
---


title: Sandbox Visualization Module Emulator

text:
# Question
Title: Sandbox Visualization Module Emulator
The Zachtronics game TIS-100 contains a graphics display called the visualization module. I could try and explain the specs of this module, but the game's manual will do a better job:

(As you may have guessed, the motivation of this problem is to create a code golf challenge in which TIS-100 is the optimal language.)

Your job is to, in as few characters as possible, implement a program which will output the correct image for any valid input sequence. There are no requirements on what happens for an invalid input sequence. This can be a graphical window or console output. This includes strings of more than 1 command! If it has multiple -1s, multiple lines should be drawn.

# Test Cases:

```
Input:

    3, 4, 4, 3, 2, 1, 0, 1, 2, 3, 4, -1

Output:

```

```
Input:

    1, 1, 4, 4, -1, 8, 8, 4, 4, -1

Output:

```

```
Input:

    5, 5, 4, -1, 5, 5, 0, -1

Output:

```

The simple TIS implementation is:

# TIS-100, ~~64~~ 55 Bytes

-9 thanks to feersum

```
@1
MOV UP ANY
@5
MOV UP ANY
@9
MOV UP ANY
@10
MOV ANY ANY

```

An additional byte is added as a single character in the filename is relevant.

# Answer
# Ruby, 114 bytes

```
->h,g=[0]*792{h.chunk{|x|x<0&&p}.map{|z,(x,y,*r)|g[36*y+x,r.size]=r}
puts'P3 36 22 5',g.map{|i|i>3?'5 0 0':[i]*3}}

```

This function takes its input as an array of ints, and writes the resulting image to STDOUT in the human readable version of PPM format. For those unfamiliar, the PPM image format is an uncompressed image format that's, essentially, a whitespace separated list of RGB values.

### About PPM

More particularly, it begins with a short header of the format `P3 W H M`, where `P3` is a magic number, `W` is the width of the image, `H` is the height of the image, and `M` is an int from 1 to 65536 representing the maximum possible value a color channel can have. For instance, if `M = 255`, then the RGB triplet `(255, 255, 255)` represents white. If `M = 10`, then `(10, 10, 10)` is white.

After the header, each pixel is described, row by row, by providing an RGB triplet for its color, with each value separated by spaces. It has the neat property that you can use it to represent an image as human readable text. For instance, a 3x1 pixel image containing a red pixel, a green pixel, and a blue pixel would be:

```
3 1 255
255 0 0   0 255 0   0 0 255

```

The precise whitespace used doesn't matter, so the above image is equivalent to, among many others:

```
3 1 255
255
 0    0          0       255        0
        0     0       255

```

### Explanation of Code

The reason all that was necessary was to explain why, when you run the program, you'll see output that looks like this:

```
P3 36 22 5
0
0
0
3
0 # And so on...

```

It's a PPM! And it's generated like this:

```
# Create an array g, full of 0s, of size (36*22) to hold the image
g = [0] * 792
# Break the input array into chunks, splitting on values < 0
h.chunk{|x|x < 0 && p}
# Use each chunk to fill the subarray of g beginning at its x and y coordinates
 .map{|z,(x,y,*r)|g[36*y+x,r.size]=r}
# Print the header ...
puts'P3 36 22 5',
# ... and the colors, replacing each color id with itself repeated 3 times
# (for the various shades of gray) or '5 0 0', in the case of red, and
# separating each item with a newline.
g.map{|i|i>3?'5 0 0':[i]*3}

```

If you take this output and paste it into a text file, you'll be able to view it in any image viewer capable of opening PPMs.

Try it online!
> 1 votes

# Answer
.COM in 94B

```
00000000h: 68 00 B8 07 BF 09 01 31 DB B4 07 CD 21 3C 2D 72
00000010h: 41 6B DB 0A 2D 30 07 01 C3 BF 1E 01 EB EB 89 DD
00000020h: 83 06 1A 01 09 EB DD 69 ED A0 00 6B F3 02 EB F0
00000030h: 85 DB 7D 07 83 2E 1A 01 12 EB C9 83 FE 48 73 C4
00000040h: 81 FD C0 0D 73 BE FF B7 58 01 26 8F 02 83 C6 02
00000050h: EB B2 3C 20 72 02 FF E7 C3 00 88 77 FF 44

```

No extra optimize. Lots of code doing input
> 1 votes

# Answer
# SmileBASIC 3, 163 bytes

Draws the image in the top-left corner of the graphic screen at 1px scale. `DEF V A` takes an int array `A` as input.

```
DEF V A
GCLS
@_
X=A[I]Y=A[I+1]FOR I=I+1TO LEN(A)-1C=A[I]IF.>C THEN I=I+1GOTO@_
IF X>35||Y>21GOTO@N
R=(3AND C)*85GPSET X,Y,RGB(R+255*!!(4AND C),R,R)@N
X=X+1NEXT
END

```

## Test Harness

The output is very small and other graphics leftover from the console etc. makes this function hard to test (in addition to the fact that it's a function and not a standalone program...) Write this (ungolfed) test harness below the function and run to verify.

```
ACLS
DATA 3,4,4,3,2,1,0,1,2,3,4,-1,-10

DIM SEQ%[0]
WHILE C%!=-10
 READ C%
 PUSH SEQ%,C%
WEND

GPAGE 0,4
SPSET 0,0,0,36,22
SPSCALE 0,8,8

V SEQ%

REPEAT VSYNC UNTIL BUTTON(2)

```

Change the `DATA` statement to change the test sequence. The test sequence must end with `-10` so the tester knows to stop reading it (`DATA` is used because SB lacks array literals.) This is done so you can use `-1` in a sequence.

The program may end in an error; this is normal.
> 0 votes

# Answer
# APL (Dyalog Unicode), 73 bytes

```
'P3 36 22 5'
+/{{⍵≠4:3/⍵⋄4 0 0}¨(-1⊃⍵)⊖(-0⊃⍵)⌽36 22↑1(≢2↓⍵)⍴2↓⍵}¨¯1(≠⊆⊢)⎕

```

Try it online!

A full program, which takes the indices as specified. Requires `⎕IO←0` for 0-indexing.

Outputs a netpbm image, like in the Ruby answer.

## Explanation

```
Netpbm header:
'P3 36 22 5'

Grid Generator:
+/{{⍵≠4:3/⍵⋄4 0 0}¨(-1⊃⍵)⊖(-0⊃⍵)⌽36 22↑1(≢2↓⍵)⍴2↓⍵}¨¯1(≠⊆⊢)⎕
                                                              ⎕ Take the input
                                                       ¯1(≠⊆⊢)  split on -1s
  {                                                  }¨         do the following for each subarray i:
                                                 2↓⍵            Drop the 2 coordinates
                                        1(≢2↓⍵)⍴                Convert i to a 1-row matrix
                                  36 22↑                        create a 36x22 matrix with zeros, containing i
                           (-0⊃⍵)⌽                              rotate i to the required x coordinate
                    (-1⊃⍵)⊖                                     rotate i to the required y coordinate
    {             }¨                                            apply the following to each element:
     ⍵≠4:3/⍵                                                    if it's not red, assign a shade of grey
            ⋄4 0 0                                              otherwise assign red
+/                                                              sum all the resulting matrices

```
> 0 votes

---
Tags: code-golf, graphical-output
---


title: Create a Paint program!

text:
# Question
Title: Create a Paint program!
# Introduction

One day, you were showing your kid how to draw on a computer. You type `mspaint.exe` in the run bar. To your horror, it says "No items match your search". You must create a simple version of paint so your kid can draw!

# Challenge

You must create a simple drawing program. To do this, open a white display window (larger than 99x99 pixels). Anytime the mouse is pressed down, change the pixel that the mouse is on to black.

This is , so shortest answer in bytes wins!

# Answer
> 90 votes
# 8086 machine code, ~~32 31 28~~ 26 bytes

```
00000000  b8 0f 00 cd 10 b8 02 10  ba 18 01 cd 10 b8 03 00  |................|
00000010  cd 33 4b b8 01 0c eb f3  3f 00                    |.3K.....?.|
0000001a

```

Assumes the presence of a VGA graphics card, and any Microsoft-compatible mouse driver.

-2 bytes thanks to @berendi!

### How it works:

```
            |   org 0x100
            |   use16
b8 0f 00    |       mov ax, 0x000f      ; set screen mode: 640x350 monochrome
cd 10       |       int 0x10            ; call video bios
b8 02 10    |       mov ax, 0x1002      ; set palette
ba 18 01    |       mov dx, palette     ; pointer to palette data
cd 10       |   @@: int 0x10            ; call video bios
b8 03 00    |       mov ax, 0x0003      ; get mouse position in (CX, DX) and button status in BL
cd 33       |       int 0x33            ; call mouse driver
4b          |       dec bx              ; if no buttons pressed, --BX = 0xFFFF (invalid page)
b8 01 0c    |       mov ax, 0x0c01      ; plot pixel with color AL at (CX, DX) in page BH
eb f3       |       jmp @b              ; repeat
3f 00       |   palette db 0x3f, 0x00   ; palette in 2:2:2 rgb. color 0 = white, 1 = black.
            |                           ; this should be a 17-byte struct, but we only care about the first two colors here

```

That's all there is to it. No magic involved, just a few function calls.

# Answer
> 27 votes
# Scratch, 10 Scratch bytes

Scratch was practically designed for things like this.

Try it online!

# Answer
> 19 votes
# HTML + JavaScript (ES6), 66 64 62 bytes

**HTML**

```
<canvas id=c>

```

**JavaScript**

```
onclick=e=>c.getContext`2d`.fillRect(e.x,e.y,1,1)

```

Saved 2 bytes thanks to Gustavo Rodrigues and 2 bytes from Shaggy.

```
onclick=e=>c.getContext`2d`.fillRect(e.x,e.y,1,1)
```

```
/* This css isn't needed for the program to work. */
*{margin: 0}
#c{border:1px solid black}
```

```
<canvas id=c>
```

# Answer
> 19 votes
## C + Win32, ~~209~~ ~~200~~ ~~195~~ ~~178~~ 159 bytes

* 2022 Update: Saved 19 bytes by removing `#include <windows.h>`.

```
short m[9];main(h){for(h=CreateWindowExA(0,"EDIT","",1<<28,0,0,199,199,0);GetMessageA(m,h,0,0);m[4]^513?DispatchMessageA(m):SetPixel(GetDC(h),m[12],m[13],0));}

```

Thanks, Cody and Quentin! I was hoping to get rid of the `#include <windows.h>` but this leads to all sort of errors. At least it is working correctly with multiple monitors...

Saved 17 bytes thanks to inspiration by @c--!!!

# Answer
> 10 votes
# Processing, ~~98~~ 79 bytes

*19 bytes saved thanks to @dzaima*

```
void setup(){background(-1);}void draw(){if(mousePressed)point(mouseX,mouseY);}

```

### Explanation (outdated)

```
void setup() {
  size(100,100);            // size of the sketch
  background(-1);           // set the background to white
                            // 1 byte shorter than background(255);
}

void draw(){}               // required for mousePressed to work

void mousePressed() {       // function that is called whenever the mouse is pressed
  point(mouseX, mouseY);    // draw a point at the mouse's coordinates
                            // the colour is set to black as default
}

```

# Answer
> 7 votes
# JavaScript ES6, 126 bytes

Tested in chrome.

```
onclick=e=>document.body.outerHTML+=`<a style=position:fixed;top:${e.y}px;left:${e.x}px;width:1px;height:1px;background:#000>`

```

### Try it online!

```
onclick=e=>document.body.outerHTML+=`<a style=position:fixed;top:${e.y}px;left:${e.x}px;width:1px;height:1px;background:#000>`
```

# Answer
> 7 votes
## Haskell, ~~189~~ ~~184~~ ~~170~~ 169 bytes

```
import Graphics.Gloss.Interface.Pure.Game
main=play FullScreen white 9[]Pictures(#)(\_->id)
EventKey(MouseButton LeftButton)Down _(x,y)#l=Translate x y(Circle 1):l
_#l=l

```

This uses the `Gloss` library (v1.11). It opens a full screen window and paints black pixels (in fact circles with radius 1) by pressing the left mouse button. Press `ESC` to exit.

How it works:

```
play                 -- handles the whole event handling, screen update, etc. process
    FullScreen       -- use a full screen window
    white            -- use a white background
    9                -- 9 simulation steps per second (see simulation handler below)
    []               -- the initial world state, an emtpy list of circles
    Pictures         -- a function to turn the world state into a picture.
                     -- The world state is a list of translated circles and
                     -- "Pictures" turns this list into a single picture
    (#)              -- event handler, see below
    (\_->id)         -- simulation step handler. Ignore time tick and return the
                     -- world state unchanged. More readable: "\tick world -> world"

EventKey ... # l=... -- if the left mouse button is pressed, add a circle with
                     -- radius 1 translated to the current position of the mouse
                     -- to the world state
_#l=l                -- on all other events do nothing

```

Edit: @ceased to turn counterclockwis told me about the newst version of gloss which saves 5 bytes when using full screen windows. Thanks!

# Answer
> 5 votes
# SmileBASIC 2, ~~52~~ 51 bytes

This one runs in SmileBASIC's daddy, Petit Computer (and is ~~one~~ two byte shorter.)

```
PNLTYPE"OFF
GPAGE 1GCLS 15@A
GPSET TCHX,TCHY
GOTO@A

```

Explanation:

```
PNLTYPE"OFF       'turn off keyboard
GPAGE 1           'set graphics to lower screen
GCLS 15           'clear with color 15 (white)
@A                'loop begin
GPSET TCHX,TCHY   'set black pixel at draw location
GOTO@A            'loop

```

# Answer
> 4 votes
# Javascript + jQuery 138 bytes

```
d=$(document.body).click((e)=>d.append("<div style='background:black;width:5;height:5;position:fixed;top:"+e.pageY+";left:"+e.pageX+"'>"))

```

Check it out online!

Adding click and drag support would be simple, you'd set a variable, however, per the instructions and to shorten code, it is not supported, "Anytime the mouse is pressed down, change the pixel that the mouse is on to black". I interpretted the instruction as a `click` event.

# Answer
> 4 votes
# SpecBAS - ~~61~~ 59 bytes

```
1 CLS 15
2 IF MOUSEBTN=1 THEN PLOT MOUSEx,MOUSEy
3 GO TO 2

```

Black is already the default pen colour, but the background is usually a nasty shade of grey, so `CLS 15` sets it to bright white.

# Answer
> 3 votes
# SmileBASIC, ~~70~~ ~~58~~ 53 Bytes

```
XSCREEN 4GCLS-1@L
TOUCH OUT,X,Y
GPSET X,Y+240,0GOTO@L

```

Explained:

```
XSCREEN 4 'display one graphics page on both screens
GCLS -1 'fill screen with white
@L 'loop
TOUCH OUT,X,Y 'get touch location
GPSET X,Y+240,0 'draw black pixel at touch position, offset by the height of the top screen.
GOTO @L 'loop

```

# Answer
> 3 votes
# Clojure, ~~91~~ 71 bytes

-20 bytes thanks to @cfrick for pointing out that I can use `use` to shrink my importing.

```
(use 'quil.core)(defsketch P :mouse-dragged #(point(mouse-x)(mouse-y)))

```

Uses the Quil library. Draws a dot whenever the mouse is dragged.

Basically the Processing answer, since Quil is a Processing wrapper for Clojure.

```
(q/defsketch P ; Start a new drawing

             :mouse-dragged ; Attach a mouse drag listener
             ; that draws a point at the current mouse location
             #(q/point (q/mouse-x) (q/mouse-y)))

```

# Answer
> 3 votes
# Tcl/Tk, 45 ~~46~~ ~~51~~ ~~57~~

```
gri [can .c]
bind . <1> {.c cr o %x %y %x %y}

```

# Answer
> 3 votes
# Excel VBA, 62 Bytes

Anonymous VBE immediate window function that allows the user to draw on the any sheet by simply selecting it

```
Cells.RowHeight=48:Do:DoEvents:Selection.Interior.Color=0:Loop

```

# Sample Output

# Answer
> 2 votes
# Java 7, 353 bytes

```
import java.awt.*;import java.awt.event.*;class M{static int x,y;public static void main(String[]a){Frame f=new Frame(){public void paint(Graphics g){g.drawLine(x,y,x,y);}};f.addMouseListener(new MouseAdapter(){public void mousePressed(MouseEvent e){x=e.getX();y=e.getY();f.repaint(x,y,1,1);}});f.setBackground(Color.WHITE);f.resize(500,500);f.show();}}

```

Ungolfed:

```
import java.awt.*;
import java.awt.event.*;

class M {
    //store the last point
    static int x, y;
    public static void main(String[] a) {
        Frame f = new Frame() {
            @Override
            public void paint(Graphics g) {
                g.drawLine(x, y, x, y);
            }
        }
        f.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                x = e.getX();
                y = e.getY();
                //repaint only the "new pixel"
                f.repaint(x, y, 1, 1);
            }
        });
        //default background is grey
        f.setBackground(Color.WHITE);
        f.resize(500, 500);
        f.show();
    }
}

```

# Answer
> 2 votes
# TI-Basic, 1 byte

```
Pt-Change(

```

I'm sure that most of you with TI calcs thought of the `Pen` command, but it turns out that it's not tokenized so it would make most sense to count that as 3 bytes. You can read about the interactive version of `Pt-Change(` at http://tibasicdev.wikidot.com/pt-change

# Answer
> 2 votes
# Python2 *and* Python3, 82 bytes (or 77?)

```
from turtle import *;up();onscreenclick(lambda x,y: goto(x,y)or dot(1));mainloop()

```

Using the Turtle module, this isn't too bad :)

Ungolfed:

```
import turtle
turtle.up()

def fun(x, y):
    turtle.goto(x,y)
    turtle.dot(1)

turtle.onscreenclick(fun)
turtle.mainloop()

```

If it's OK to have lines between the dots, you can actually save 5 bytes:

```
from turtle import *;onscreenclick(lambda x,y: goto(x,y)or dot(1));mainloop()

```

# Answer
> 1 votes
## HTML + Javascript, ~~152~~ 148 bytes

```
<body onclick="document.body.innerHTML+='<x style=position:fixed;width:1;height:1;left:'+event.clientX+';top:'+event.clientY+';background:#000;>'"/>

```

# Answer
> 1 votes
# Turing, 77 bytes

```
var x,y,b:int loop mousewhere(x,y,b)if b=1then drawdot(x,y,1)end if end loop

```

Ungolfed:

```
var x,y,b : int
loop
  mousewhere(x,y,b)  % Set (x,y) to mouse co-ords, and b to 1 or 0 indicating if the button is pressed
  if b=1 then
    drawdot(x,y,1)  % Draw a black pixel at (x,y)
  end if
end loop

```

# Answer
> 1 votes
# HTML + CSS + JavaScript (ES6), 8 + 31 + 64 = 103 bytes

Fun with CSS `box-shadow`!

```
s='0 0 0',onclick=e=>p.style.boxShadow=s+=`,${e.x}px ${e.y}px 0`
```

```
*{margin:0;width:1px;height:1px
```

```
<p id=p>
```

# HTML + CSS + JavaScript (ES6), 8 + 22 + 69 = 99 bytes

This one attempts to offset the default `margin` of the `<body>` element, but it may be different across browsers and user agent stylesheets. Tested successfully in Chrome.

```
s='0 0 0',onclick=e=>p.style.boxShadow=s+=`,${e.x-8}px ${e.y-16}px 0`
```

```
*{width:1px;height:1px
```

```
<p id=p>
```

# HTML + CSS + JavaScript (ES6), 8 + 18 + 69 = 95 bytes

Pixels in this one may appear bigger as they are drawn at half-pixel coordinates.

```
s='0 0 0',onclick=e=>p.style.boxShadow=s+=`,${e.x}px ${e.y}px 0 .5px`
```

```
*{margin:0;width:0
```

```
<p id=p>
```

# Answer
> 1 votes
# Lua (love2d Framework), 180 bytes

golfed version

```
l=love v,g,m,p=255,l.graphics,l.mouse,{}d=m.isDown function l.draw()g.setBackgroundColor(v,v,v)if d(1)or d(2)then p[#p+1],p[#p+2]=m.getPosition()end g.setColor(0,0,0)g.points(p)end

```

ungolfed

```
l=love
v,g,m,p=255,l.graphics,l.mouse,{}
d=m.isDown
function l.draw()
  g.setBackgroundColor(v,v,v)
  if d(1)or d(2)then
    p[#p+1],p[#p+2]=m.getPosition()
  end
  g.setColor(0,0,0)
  g.points(p)
end

```

quite easy how it works. First a few initialisations to make things shorter. After it it will check the mous is clicked and saves the points to the array. After that it draws the points.Also it sets the color to white& black cause default is the other way around :)
And here comes the picture:

# Answer
> 1 votes
## Processing, 65 bytes

```
void draw(){if(mousePressed)line(mouseX,mouseY,pmouseX,pmouseY);}

```

# Answer
> 1 votes
# glslsandbox 232 bytes

Old post but found this interesting.
Since processing already been done I decided to do something different.

This draws whether the mouse is pressed or not, so not what pydude asked for but almost.

```
#ifdef GL_ES
precision lowp float;
#endif
uniform float time;uniform vec2 mouse,resolution;uniform sampler2D t;void main(){vec2 f=gl_FragCoord.xy,r=resolution;gl_FragColor=vec4(time<2.||length(f-mouse*r)>2.&&texture2D(t,f/r).x>.1);}

```

Try it on glslsandbox

# Answer
> 0 votes
**Processing, 93 bytes, 91 bytes if spaces don't count**

```
void setup(){size(100,100);background(-1);}void draw(){if(mousePressed) point(mouseX,mouseY);}

```

# Answer
> 0 votes
## UCBlogo with wxWidgets, 65 bytes

```
setbg 7
setpc 0
ht
pu
make "buttonact[setpos clickpos pd fd 1 pu]

```

Explanation (the code assigned to the variable `buttonact` is executed on each button click):

```
SetBackground 7 ; white
SetPenColor 0 ; black
HideTurtle
PenUp
make "buttonact [
  SetPos ClickPos
  PenDown
  Forward 1
  PenUp
]

```

At least, I think this works. It should according to the documentation, but apparently the `buttonact` variable only works in a wxWidgets build and I'm struggling to build UCBLogo with wxWidgets on a modern Linux (waddyamean you can't cast a pointer to `int` and back?).

## UCBlogo without wxWidgets, 73 bytes

To see the intended effect, you can run this longer version with an infinite loop.

```
setbg 7 setpc 0 ht pu
while[1=1][setpos mousepos if[button?][pd] fd 1 pu]

```

But this crashes `ucblogo` on my machine... Looks like a race condition.

## UCBlogo, actually working on my machine, 80 bytes

```
setbg 7 setpc 0 ht pu
while[1=1][setpos mousepos if[button?][pd] fd 1 pu wait 1]

```

# Answer
> 0 votes
# APL (dzaima/APL), 37 bytes

```
P5.draw←{P5.Lm.p:P5.G.pt P5.mx P5.my}

```

Try it online!

Machine code is OP.

---
Tags: code-golf, graphical-output, interactive
---


title: Ping-pong bot for StackExchange

text:
# Question
Title: Ping-pong bot for StackExchange
# History

There's a room on StackOverflow in Russian where you can see such an interesting discussion:

>

Just because there are not enough real discussing in that room, @Grundy "plays ping-pong" to keep it unfrozen.

# Task

Implement a bot for StackExchange that posts "ping!" to the 115624 room if the previous message was "pong!" \**(and posted by another user) and "pong!" if the previous message was "ping!" (and posted by another user). If you need a login and a password for SE account, use `l` and `p`.

<sub>\**It should not reply to its own messages</sub>

# Rules

Code-golf: the shortest answer wins.

*Nice golfing!*

# Answer
Nobody golfs... so:

# Python 3 — 330 byte

```
from chatexchange.client import Client
s=Client("stackexchange.com");s.login('l','p');r=s.get_room('115624');r.join();o=lambda e,_:r.send_message("ping!")if e.message.content_source=='pong!'and e.user.id!=483667 else r.send_message('pong!')if e.message.content_source=='ping!'and e.user.id!=483667 else 0;r.watch_socket(o)
while 1:0

```
> 1 votes

---
Tags: code-golf
---


title: Palindrome Reversal-Addition

text:
# Question
Title: Palindrome Reversal-Addition
The process of Reversal-Addition is where a number is added to it's reverse until the number created is a palindrome. For example, if we start with 68, the process would be:

$$68 + 86 \to 154 + 451 \to 605 + 506 \to 1111$$

As you can see, this took 3 additions to get to a palindromic number. If we were to start with \\$89\\$, we would need 24 steps (which you can see the breakdown here).

The world record for the most steps taken before a palindrome is reached is \\$261\\$, which occurs for the number \\$1186060307891929990\\$, producing a number larger than \\$10^{118}\\$. However, there have been quite a few numbers which we have not been able to get a palindrome. These are called Lychrel numbers.

Since we are working in base 10, we can really only call them candidates, because there exists no proof that these numbers never reach a palindrome. For example, the smallest base-10 Lychrel candidate is \\$196\\$, and has gone through well over a billion iterations. If the palindrome does exist, it is much larger than \\$10^{10^{8.77}}\\$. As comparison, if that many 1s was inscribed on atoms, we would need \\$2.26772×10^{588843575}\\$ universes worth of atoms to write it out, assuming it exists.

# Your Task

Create a program or function that takes an integer input and returns or prints the number of steps required to reach a palindrome. You will not be required to deal with Lychrel candidates (i.e. Your program, when given a Lychrel candidate, is allowed to either throw an error or run forever).

# Test Cases:

```
                  f(0) => 0
                 f(11) => 0
                 f(89) => 24
                f(286) => 23
          f(196196871) => 45
         f(1005499526) => 109
f(1186060307891929990) => 261

```

# Rules

1. No standard loopholes.

# Bonuses

1. If you print out each addition step, formatted `n + rev(n) = m`, you may multiply your score by **0.75**. The sums should print out before the number of steps.
2. If your code can detect if a number is a Lychrel candidate, you may multiply your score by **0.85**. In this case it is sufficient to assume anything that takes more than 261 iterations is a Lychrel candidate. Either return nothing, or anything that is not a number that can be mistaken for a correct answer (etc: any string or a number not in the range 0-261). Any error does not count as valid output (ex. maximum recursion depth exceeded) and can not be used in the detection.
3. If you complete both bonuses, multiply by **0.6**.

This is , so least number of bytes wins.

---

This code snippet shows an example solution in Python 3 with both bonuses.

```
def do(n,c=0,s=''):
  m = str(n)
  o = m[::-1]
  if c > 261:
    return "Lychrel candidate"
  if m == o:
    print(s)
    return c
  else:
    d = int(m)+int(o)
    s+="%s + %s = %s"%(m,o,str(d))
    return do(d,c+1,s)

```

# Answer
# Pyth, 12 bytes

```
f_I`~+Qs_`Q0

```

Try it online: Demonstration or Test harness

This uses a quite new feature (only 17 hours old).

### Explanation

```
               implicit: Q = input number
f          0   repeat the following expression until it
               evaluates to true and return the number of steps
         `Q       convert Q to string
        _         reverse the digits
       s          convert to int
     +Q           add Q
    ~             assign the result to Q
                  (this returns the old value of Q)
   `              convert the old value of Q to a string
 _I               and check if it's invariant under the operation reverse

```

### edit:

Changed the code a little bit. The old version was

```
fqKs_`Q~+QK0

```

Same byte count, but the new one is way cooler.
> 9 votes

# Answer
## Python, 51

```
def f(n):r=int(str(n)[::-1]);return n-r and-~f(n+r)

```

For Python 2, backticks can't replace `str()` because of the `L` attached to `long` literals.

Here's an alternate version with score 64 * 0.85 = **54.4**:

```
def f(n,c=262):r=int(str(n)[::-1]);return c*(n-r)and-~f(n+r,c-1)

```

And an alternate version for **Python 3** with score 88 * 0.6 = **52.8**:

```
def f(n,c=262):r=int(str(n)[::-1]);return c*(n-r)and-~f(n+r,print(n,'+',r,'=',n+r)or~-c)

```
> 14 votes

# Answer
# CJam, ~~23~~ ~~22~~ 20.4 bytes

```
ri{__sW%i+}261*]{s_W%=}#

```

The code is 24 bytes long and prints **-1** for Lychrel candidates.

Try it online.

### How it works

```
ri                       e# Read an integer from STDIN.
  {       }261*          e# Do the following 261 times:
   __                    e#   Push two copies of the integer on the stack.
     sW%i                e#   Cast to string, reverse and cast back to integer.
         +               e#   Add the copy and the reversed copy of the integer.
               ]         e# Wrap all 262 results in an array.
                {     }# e# Push the index of the first element such that:
                 s       e#   The string representation equals...
                  _W%=   e#   the reversed string representation.

```

If `{}#` is successful, the index is also the number of steps. If, on the other hand, the array does not contain a palindrome, `{}#` will push **-1**.
> 6 votes

# Answer
# Java, 200\*0.6 = 120

```
import java.math.*;int f(BigInteger a){int s=-1;for(String b,c;(b=a+"").equals(c=new StringBuffer(b).reverse()+"")!=s++<999;)System.out.println(b+" + "+c+" = "+(a=a.add(new BigInteger(c))));return s;}

```

This is a simple loop that does just what it says on the box, but with some golf added. Returns `1000` for Lychrel candidates to get the detection bonus. Turns out I was able to print for not *too* many characters (for Java at least) and snag that bonus as well. The best I could do without bonus code was 156, so it was well worth it.

With some line breaks:

```
import java.math.*;
int f(BigInteger a){
    int s=-1;
    for(String b,c;(b=a+"").equals(c=new StringBuffer(b).reverse()+"")!=s++<999;)
        System.out.println(b+" + "+c+" = "+(a=a.add(new BigInteger(c))));
    return s;
}

```

---

**Old Answer: 171\*0.85 = 145.35 bytes**

```
import java.math.*;int f(BigInteger a){int s=-1;for(String b,c;(b=a+"").equals(c=new StringBuffer(b).reverse()+"")!=s++<262;)a=a.add(new BigInteger(c));return s>261?-1:s;}

```

---
> 5 votes

# Answer
# Ruby, (80+2)\*0.6 =~ 49.2

With flags `-nl`, run

```
p (0..261).find{$_[b=$_.reverse]||puts($_+' + '+b+' = '+$_="#{$_.to_i+b.to_i}")}

```

Output looks like

```
 $ ruby -nl lychrel.rb
89
89 + 98 = 187
187 + 781 = 968
968 + 869 = 1837
1837 + 7381 = 9218
9218 + 8129 = 17347
17347 + 74371 = 91718
91718 + 81719 = 173437
173437 + 734371 = 907808
907808 + 808709 = 1716517
1716517 + 7156171 = 8872688
8872688 + 8862788 = 17735476
17735476 + 67453771 = 85189247
85189247 + 74298158 = 159487405
159487405 + 504784951 = 664272356
664272356 + 653272466 = 1317544822
1317544822 + 2284457131 = 3602001953
3602001953 + 3591002063 = 7193004016
7193004016 + 6104003917 = 13297007933
13297007933 + 33970079231 = 47267087164
47267087164 + 46178076274 = 93445163438
93445163438 + 83436154439 = 176881317877
176881317877 + 778713188671 = 955594506548
955594506548 + 845605495559 = 1801200002107
1801200002107 + 7012000021081 = 8813200023188
24

```

If given 196, it prints the first 261 addition steps and then `nil`.

Nothing too tricky here. We check whether `$_` (which is initialized to the input) contains its reverse, which is only possible if they're equal since they're the same size. If it is, we print the step number and exit, otherwise, we display and execute the addition step, storing the new value in `$_` (I unfortunately can't just `eval` the string I'm displaying because it interprets a reversed number with a trailing 0 as an octal literal). `puts` returns a falsey value so the loop continues.
> 5 votes

# Answer
# CJam, 24 bytes

```
0q{__W%#}{_W%~\~+s\)\}w;

```

Test it here.

## Explanation

```
0q     e# Push a zero (the counter) and read input.
{      e# While this block leaves something truthy on the stack...
  __   e#   Make two copies of the current number (as a string).
  W%   e#   Reverse the second copy.
  #    e#   Check that they are not equal.
}{     e# ... run this block.
  _W%  e#   Make a copy of the current number and reverse it.
  ~\~  e#   Evaluate both N and its reverse.
  +s   e#   Add them and turn the sum into a string.
  \)\  e#   Pull up the counter, increment it, and push it back down again.
}w
;      e# Discard the palindrome to leave the counter on the stack.

```

For more information about why `#` can be used to check string inequality, see this tip.
> 4 votes

# Answer
# Pyth - 19 bytes

Uses while loop and a counter. There is probably a smaller algorithm than this, but this is pretty short.

```
Wnz_z=z`+szs_z=hZ;Z

```

Try it online here.
> 4 votes

# Answer
# Julia, ~~129~~ 120 bytes * 0.6 = 72

```
i->(i=big(i);n=0;d=digits;while d(i)!=reverse(d(i))&&n<262 t=BigInt(join(d(i)));println(i," + ",t," = ",i+=t);n+=1end;n)

```

This creates an unnamed function which takes an integer as input and returns an integer, meanwhile printing each step. Lychrel candidates have a return value of 262. To call this, give it a name, e.g. `f=i->...`.

Note that omitting code relating only to the bonuses, this solution would be 84 bytes.

Ungolfed + explanation:

```
function f(i)
    # Convert the input to a big integer
    i = big(i)

    # Initialize a step counter to 0
    n = 0

    # While the number is not a palindrome and we haven't exceeded 261 steps...
    while digits(i) != reverse(digits(i)) && n < 262

        # Get the reverse of the integer
        # Note that we aren't using reverse(); this is because digits()
        # returns an array of the digits in reverse order.
        t = BigInt(join(digits(i)))

        # Print the step and increment i
        println(i, " + ", t, " = ", i += t)

        # Count the step
        n += 1
    end

    # Return the number of steps or 262 for Lychrel candidates
    n
end

```

Examples:

```
julia> f(286)
286 + 682 = 968
968 + 869 = 1837
1837 + 7381 = 9218
9218 + 8129 = 17347
17347 + 74371 = 91718
91718 + 81719 = 173437
173437 + 734371 = 907808
907808 + 808709 = 1716517
1716517 + 7156171 = 8872688
8872688 + 8862788 = 17735476
17735476 + 67453771 = 85189247
85189247 + 74298158 = 159487405
159487405 + 504784951 = 664272356
664272356 + 653272466 = 1317544822
1317544822 + 2284457131 = 3602001953
3602001953 + 3591002063 = 7193004016
7193004016 + 6104003917 = 13297007933
13297007933 + 33970079231 = 47267087164
47267087164 + 46178076274 = 93445163438
93445163438 + 83436154439 = 176881317877
176881317877 + 778713188671 = 955594506548
955594506548 + 845605495559 = 1801200002107
1801200002107 + 7012000021081 = 8813200023188
23

julia> f(1186060307891929990)
(steps omitted)
261

julia> f(196)
(steps omitted)
262

julia> f(11)
0

```

Saved 2 bytes thanks to Geobits!
> 4 votes

# Answer
# K, 25 bytes

```
#1_{~x~|x}{$. x,"+",|x}\$

```

Not very elegant. The overall form (`{monad 1}{monad 2}\x`) is K's equivalent of a general "while" loop, where the first monad is the halting condition and the second is an iteratively applied function to the argument `x`. The first monad (`{~x~|x}`) is the negation of the classic "is x a palindrome" phrase. The second monad concatenates together a string representing x plus the reverse of x, evaluates it and then casts the result back into a string with `$`.

A sample run showing intermediate results:

```
  {~x~|x}{$. x,"+",|x}\$68
("68"
 "154"
 "605"
 "1111")

```

Doing formatted output as requested for the bonus would be very clumsy and add a significant amount of code.
> 4 votes

# Answer
# CJam, 23 bytes

```
Wl{\)\__W%_@#\i@i+s\}g;

```

Still only a few days into CJam, so I'm fairly happy to be at least in the same range as some of the pros. :) I did use Martin's string comparison trick that he also posted in the CJam hints. I also peeked at Dennis' solution to figure out how to reverse a string.

Explanation:

```
W    Initialize counter, will keep this at bottom of stack.
     Start counting at -1 because the counter will be incremented in the
     last pass through the loop, when the palindrome is detected.
l    Get input.
{    Start block of while loop.
\)\  Increment counter. Need to swap before/after because it's one below top of stack.
__   Copy current value twice. Need 3 copies in total:
       * one for reversal
       * one for comparison
       * one for addition with reverse
W%   Reverse value.
_    Copy the reverse value once because we need 2 copies:
       * one for comparison
       * one for addition with original value
@    Rotate one copy of original value to top.
#    Test for non-equality with reverse, using Martin's trick.
\i   Swap reverse value to top, and convert it to int.
@i   Rotate remaining copy of original value to top, and convert it to int.
+s   Add the values, and convert result to string.
\    Swap, so that comparison result is at top of stack for while loop test.
}g   End of while loop.
;    Current value sits at top of stack. Pop it, leaving only counter.

```

Test it online
> 4 votes

# Answer
# Haskell, ~~66~~ 53 bytes

```
r=reverse.show
f x|show x==r x=0|1<2=1+f(x+read(r x))

```

Usage example:

```
*Main> map f [0,11,89,286,196196871,1005499526,1186060307891929990]
[0,0,24,23,45,109,261]

```
> 2 votes

# Answer
## Clojure, 94 bytes

```
(fn[x](#(let[r(bigint(apply str(reverse(str %1))))] (if(= %1 r)%2(recur(+ %1 r)(inc %2))))x 0))

```

This is my first attempt to code golf, so please tell me if I'm doing anything wrong.

With some spaces:

```
(fn [x]
(#(let [r (bigint (apply str (reverse (str %1))))]
  (if (= %1 r) %2 (recur (+ %1 r) (inc %2)))) x 0))

```

Simple recursion of the inner function. It takes two arguments, the integer `%1` and an index `%2`. If `%1` is a palindrome, the index gets returned. Otherwise, the function calls itself with the sum and the incremented index. The outer function initializes the index with zero.

A sample:

```
repl=> ((fn[x](#(let[r(bigint(apply str(reverse(str %1))))](if(= %1 r)%2(recur(+ %1 r)(inc %2))))x 0)) 1186060307891929990)
261

```
> 2 votes

# Answer
# Boost.Build, 304 bytes

Not really a language. Still cool.

```
import sequence ;
import regex ;
rule r ( n ) {
m = "([0-9]?)" ;
return [ sequence.join [ sequence.reverse [ regex.match "$(m)$(m)$(m)$(m)$(m)$(m)$(m)$(m)$(m)" : $(n) ] ] : "" ] ;
}
rule x ( n ) {
i = 0 ;
while $(n) != [ r $(n) ] {
n = [ CALC $(n) + [ r $(n) ] ] ;
i = [ CALC $(i) + 1 ] ;
}
echo $(i) ;
}

```

Pretty straightforward, other than the elaborate regex-based hack I used to reverse the string.
> 1 votes

# Answer
# Ruby, 44

```
f=->n{n==(r=n.to_s.reverse.to_i)?0:f[n+r]+1}

```

Needs Ruby 1.9 or higher for `->` lambda syntax.
> 1 votes

# Answer
# Jelly, 12 bytes

```
ṚḌ+ƊŒḂ¬$Ð¿L’

```

Try it online!

Jelly *really* needs an "until" builtin

# How it works

```
ṚḌ+ƊŒḂ¬$Ð¿L’ - Main link. Takes n on the left
        Ð¿   - While loop, gathering each step into a list to return:
       $     -   Condition:
    ŒḂ       -     Is palindrome?
      ¬      -     Not
   Ɗ         -   Body:
Ṛ            -     Reverse
 Ḍ           -     Cast back to integer
  +          -     Add
          L  - Count number of steps
           ’ - Decrement to account for the final step

```
> 0 votes

# Answer
# Husk, 9 bytes

```
L↑S≠↔¡S+↔

```

Try it online!

## Explanation

```
L↑S≠↔¡S+↔
     ¡    apply the following infinitely:
      S+↔ number + its reverse
 ↑        take the longest prefix of items where
  S≠↔     number ≠ its reverse
L         return its length

```
> 0 votes

---
Tags: code-golf, palindrome
---