title: Output a unique sign sequence

text:
# Question
Title: Output a unique sign sequence
A sign sequence is an infinite sequence consisting entirely of \\$1\\$ and \\$-1\\$. These can be constructed a number of ways, for example:

* Alternating signs: \\$1, -1, 1, -1, ...\\$
* \\$-1\\$ for primes, \\$1\\$ for non-primes: \\$1, -1, -1, 1, -1, 1, -1, ...\\$
* All \\$1\\$s: \\$1, 1, 1, ...\\$

Your task is to write a piece of code that outputs a deterministic sign sequence that no other answer already outputs. You *must* include a proof that your sequence is unique from all sequences posted *before yours* and that your sequence only contains \\$1\\$ and \\$-1\\$. You do not have to worry about keeping up to date for newer answers, as they must ensure their sequences are unique, not you.

You may output in any reasonable manner, including (but not limited to):

* Outputting an infinite list/generator/tuple of values
* Outputting the next value in the sequence each time your code is run
* Outputting the sequence infinitely

You may *not* take any input (unless necessary), so outputing the first \\$n\\$ terms or the \\$n\\$th term is not allowed.

I've included my implementation of a sequence as the first answer, to ensure that all answers have to provide a proof of uniqueness.

---

This is a , so the answer with the most votes wins. You should aim to do the following things in your answer:

* Be creative. Avoid simply outputting constant runs of \\$1\\$s or \\$-1\\$s or outputting one value when a number is *insert common numeric property here* and the other when not (e.g. primes or Fibonacci numbers).
* Avoid copying others. While all sequences must be unique, aim to be innovative, rather than simply slightly modify another user's sequence (for example, swapping the placements of \\$1\\$ and \\$-1\\$)
* Make it clear what your program is doing. Not everyone can read a Jelly, R or Java answer, but they can read an explanation of the answer, as well as an explanation of how/why you chose this specific sequence and the proof of uniqueness included in your answer

Voters should consider the following when casting their votes:

* How creative is the sequence? Has it been done to death before, or is it something you've never seen before?

+ Is the sequence using some properties of \\$1\\$ and \\$-1\\$ to be generated, or is it just applying the \\$\text{sgn}\\$ function to other sequences?
* Is it unique, or is it simply a slight modification on a sequence that many other users have done? If it is a modification, is it uncreative, or has the author seen a property that others haven't?
* How clever is the implementation of the sequence, and how well explained is it? For this, consider both the actual code of the answer and the algorithm it implements. If the code uses a language specific trick you find particularly impressive, it may be worth an upvote. If the implementation of the algorithm is so general than any language could be used, yet is still creative and unique, it's probably worth an upvote. However, if the code is overly convoluted when a simpler method would work, or if the algorithm is incredibly inefficient when a better version exists, consider casting a downvote.

Furthermore, while you may not be able to understand the 10 bytes of 05AB1E posted, if explained well, you should be able to get a solid understanding of how those 10 bytes implement the chosen sequence, and how clever it is. And while you may be able to fluently read Python, if poorly coded with no explanation, you may not be able to fully understand how that program works. Consider this factor when voting.

Voters should *not* vote for an answer for any of the following reasons:

* The program is written in your favourite/least favourite language
    + Voting for the use of tricks within a language are fine. Voting for an answer *because of* the language, is not an acceptable reason
* The program is short/long/written with ASCII characters/written without ASCII characters
* You recognize the user who wrote the answer and you love/hate them
* Any other reason not specified above (e.g. "This answer uses the `e` character, I love it!")

# Answer
> 18 votes
# 05AB1E, 14 bytes

```
∞v®yÒgm=Ox<.±,

```

Try it online!

*My first non-trivial 05AB1E answer! Happy for suggestions to improve it.*

The code prints two interleaved sign sequences, both related to the Pólya conjecture. In 1919, George Pólya conjectured that the majority (no less than half) of positive integers up to any finite limit \\$\ge2\\$ have an odd number of prime factors, counted with multiplicity. Mathematically, the summatory Liouville function \\$L(n)\\$ (A002819) was posited to satisfy the inequality $$ L(n)=\sum\_{k=1}^n\lambda(k)\le0\ $$ for all \\$n\ge2\\$, wherein $$ \lambda(k)=(-1)^{\Omega(k)}=\begin{cases}-1,\ \text{$k$ has an odd number of prime factors}\\\phantom{-}1,\ \text{$k$ has an even number of prime factors}\end{cases} $$ is the Liouville function (A008836), related to the parity of the number of prime factors of \\$k\\$, and \\$\Omega(k)\\$ is the prime-factor-counting omega function that respects multiplicity.

The Pólya conjecture was shown to be false in 1958 when Brian Haselgrove proved the existence of an enormous counterexample near \\$n=\exp(831.847)\approx1.845\times10^{361}\\$. Subsequently, it has been shown that the smallest counterexample is \\$n=906\\,150\\,257\\$, and that the conjecture fails for most values of \\$n\\$ in the range \\$906\\,150\\,257\le n \le 906\\,488\\,079\\$. It is also now known that \\$L(n)\\$ changes sign infinitely often.

The code prints two values for each integer \\$n\ge1\\$: $$ \DeclareMathOperator{\sgn}{sgn} \begin{gather} \lambda(n), \tag{1} \\ \sgn\bigl\[2L(n)-1\bigr\]. \tag{2} \end{gather} $$ The first value is the \\$n\\$th term of A008836. The second value, chosen to avoid zeros in \\$L(n)\\$, is (arguably) more interesting. Given the results quoted above, we see that sequence \\$(2)\\$ alternates between \\$-1\\$ and \\$1\\$ infinitely often. However, of its first \\$906\\,150\\,257\\$ values, only two (the first and the last) are \\$1\\$; the intervening \\$906\\,150\\,255\\$ values are all \\$-1\\$.

### Commented code

```
∞v             # iterate over all positive integers y
  ®            # push -1
   yÒ          # push list of prime factors of y (with duplicates)
     g         # length of this list; yields Ω(y)
      m        # exponentiate top two stack items; yields -1**Ω(y) = λ(y)
       =       # print λ(y), keeping it on the stack
        O      # sum the stack; yields L(y)
         x<    # push 2*L(y)-1, keeping L(y) on the stack
           .±, # print the sign

```

# Answer
> 10 votes
# Wolfram Language (Mathematica)

```
primesUpTo[n_] := Select[Range[n], PrimeQ];
sumsOfTwoPrimes[n_] := Union @@ Outer[Plus, primesUpTo[n], primesUpTo[n]];
GoldbachConjectureHoldsFor[n_] := MemberQ[sumsOfTwoPrimes[n], n];
BooleanToSign[TrueOrFalse_] := 2 Boole[TrueOrFalse] - 1;

Do[Print[ BooleanToSign@GoldbachConjectureHoldsFor[2n] ], {n, ∞}]

```

Try it online!

* `primesUpTo` generates a list of all primes up to `n`, and then `sumsOfTwoPrimes` generates all sums of two such primes.
* This allows `GoldbachConjectureHoldsFor` to check whether `n` is the sum of two primes. (The function works for all `n`, though the Goldbach conjecture itself is concerned only with even `n`.)
* `GoldbachConjectureHoldsFor` returns `True` or `False`, which `BooleanToSign` converts to `1` or `-1` respectively.
* Therefore `BooleanToSign@GoldbachConjectureHoldsFor[2n]` returns `1` if the Goldbach conjecture holds for `2n` and `-1` otherwise.
* The `Do[Print[ ... ], {n, ∞}]` prints (in principle) the infinite list of results.

For those looking not to repeat earlier sequences, this sequence starts with a `-1` and then contains only `1`s forever thereafter ... or does it?!

# Answer
> 10 votes
# Python 3, 84 bytes

```
s=b's=%r\nwhile[print(c%%2*2-1)for c in s%%s]:0'
while[print(c%2*2-1)for c in s%s]:0

```

Try it online!

Quine, which outputs 1 or -1 according to the last bit of each byte of the quine, repeating infinitely. Starts `1 1 -1 1 1 1 1 -1 -1 -1`

Previously ~~107~~ 91 bytes. I know it's not , but I couldn't resist golfing it a bit. This does change the sequence slightly but no other sequences are the same so it doesn't affect the competition

# Answer
> 7 votes
# C (gcc), 38 bytes

```
int f() {
  return (rand() & 2) - 1;
}

```

Try it online!

This could be golfed into 21 bytes (`f(n){n=(rand()&2)-1;}`) but this question is not tagged as .

In C, random without seeds behave *deterministically* which actually fit the requirement of this question. I don't know how the sequence is generated. But it does generate a list which only contains 1's and -1's, some how.

First 100 generated values are:

```
 1  1 -1  1 -1  1  1 -1 -1 -1
 1  1  1  1  1  1 -1  1 -1 -1
 1 -1  1 -1  1  1  1  1  1  1
-1  1  1  1 -1  1 -1 -1  1  1
-1 -1 -1  1 -1 -1  1 -1  1  1
-1  1  1 -1 -1 -1  1  1 -1 -1
-1 -1 -1  1 -1 -1  1 -1 -1 -1
-1  1  1 -1  1  1  1 -1  1  1
 1 -1 -1  1 -1 -1  1  1  1  1
-1 -1 -1 -1  1 -1  1  1  1  1

```

# Answer
> 4 votes
# Wolfram Language (Mathematica), 56 bytes

Outputs the sequence infinitely.
Returns 1 if ***n*** is a quadratic residue of p=nextPrime(n) and -1 if ***n*** is a quadratic nonresidue of p.
In number theory, an integer n is called a quadratic residue modulo p if it is congruent to a perfect square modulo p; i.e., if there exists an integer x such that:

\\$ {\displaystyle x^{2}\equiv n{\pmod {p}}} \\$

Otherwise, q is called a quadratic nonresidue modulo n.

```
Do[p=NextPrime[n,1];Print@Mod[n^((p-1)/2),p,-1],{n,∞}]

```

Try it online!

Let p be an odd prime and gcd(n,p)=1. Then n is a quadratic residue or nonresidue of p according to whether

\\$ n^{\frac {p - 1} {2}} \equiv \text {1 (mod p) } \\$ or \\$ \text{ } n^{\frac {p - 1} {2}} \equiv \text {-1 (mod p)} \\$

This is also known as the \\$ \text {Legendre symbol (a/b)} \\$ and the built-in Mathematica for this is:

```
JacobiSymbol[n,p]

```

Here are the first 100.000 n acuumulated

# Answer
> 4 votes
# Ruby

When I saw this challenge I immediately thought of the "diagonal infinite proof thing", appearantly also known as **Cantor's diagonal argument**.

My idea was to

1. reimplement each of the *N* previous sequences, in the order that they were submitted
2. create a new sequence where each ith element differs from the ith element of the ith previous sequence.

So long as Cantor's diagonal argument is correct (it is), then this should create a new sequence which is different from all the previous sequences.

Starting off with some usefull helpers:

```
def sgn(n) = n >= 0 ? 1 : -1   # New Ruby 3 syntax
def flatten_binary(seq) = seq.map(&:to_s).flat_map(&:chars).map(&:to_i).map { sgn _1 - 1 }
z = 0.step.lazy
n = 1.step.lazy

```

Step 1 turned out to be *a whole lot* of work, espacially as a few of the other answers simply flew over my head. Therefore I've cheated a little bit: Luckily, almost every answer provided a link and/or some copypastable start of the prefix, so for 13 of the sequences I've just copied them over and hardcoded the *N* first elements directly. These are marked with `TODO` in the following piece of code.

To spice things up along the way , I've also tried to interpret each submission and give them their own appropriate names:

```
sequences = [
# caird coinheringaahing's tangent
  n.map { sgn Math.tan(_1) },
# user100177's lazy duo - TODO
  [1, -1, 1, 1 ,1, -1].cycle,
  [1, 1, -1, 1, -1, 1].cycle,
# Dingus's first non-trivial 05AB1E answer - TODO
  [1, 1, -1, -1, -1, -1, 1, -1, -1, -1, 1, -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 1].cycle,
# Noodle9's zigzag
  [-1,1].cycle,
# ZaMoC's Rudin-Shapiro Sequence - TODO
  [1, 1, -1, 1, 1, -1, 1, 1, 1, 1, -1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, -1, -1, -1, 1, 1, 1].cycle,
# user99151's unity
  [1].cycle,
# hakr14's undocumented string
  n.flat_map { |i| [-1] + [1]*i },
# Greg Martin's Goldbach conjecture - TODO
  [-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1].cycle,
# pxeger's quine - TODO
  [1, 1, -1, 1, 1, 1, 1, -1, -1, -1, 1, -1, 1, -1, 1, 1, -1, -1, 1, -1, -1, -1, 1, 1, 1, -1, -1, -1].cycle,
# Command Master's infinite quad
  [1, -1, -1, -1].cycle,
# Xi'an's kempnerial
  n.map { _1.digits.include?(9) ? 1 : -1 },
# tsh's pseudo random numbers - TODO
  [1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, 1].cycle,
# Command Master's bidecimals
  flatten_binary(Enumerator.produce(2) { _1.to_s(2).to_i }.lazy.drop(1)),
# ovs's gray codes - TODO
  [1, 1, -1, 1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, -1, 1, 1, -1, -1, -1, 1, 1, -1, -1].cycle,
# Kaddath.
  "Kaddath".unpack('H*')[0].to_i(16).to_s(2).chars.map{ |c| sgn(c.to_i - 1)}.cycle,
# Zaelin Goodman's Harshad numbers - TODO
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1].cycle,
# mazzy's tripartite function
  z.map { sgn(_1 % 3 - 2) },
# Kevin Cruijssen's Kolakoski sequence - TODO
  [-1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1].cycle,
# ZaMoC's quadratic residue - TODO
  [-1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, -1, -1, -1, 1, 1, 1, -1, -1, 1].cycle,
# SketchySketch's Liouville function - TODO
  [1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, -1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, -1].cycle,
# bb94's blazin' prefix
  z.map { -sgn(420 <=> _1) },
# user100690's unoriginal solution
  n.flat_map { |i| [1]*i + [-1] },
# SjoerdPennings's quinvigintal alternation
  ([1]*25 + [-1]*25).cycle,
# Sheik Yerbouti's period
  "This is a unique sequence\0".bytes.lazy.cycle.map { _1 % 2 * 2 - 1 },
# elementiro's pie hole - TODO
  [1, -1, -1, 1, -1, -1, 1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, -1, 1, 1, -1, 1, -1, 1, -1, 1, -1, -1, -1].cycle,
# DanielOnMSE's square-free semi-primes - TODO
  [-1, -1, -1, 1, -1, -1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, -1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1].cycle,
]

```

Step two is pretty trivial:

```
sequences.cycle.each do |sequence|
  next_number = sequence.peek
  print "#{next_number * -1}, "

  # advance all to next position
  sequences.each(&:next)
end

```

Prints an infinite sequence starting with:

```
-1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, 1, -1, -1

```

Attempt This Online!

# Answer
> 3 votes
# Jelly, 8 bytes

```
‘ÆTṠṄaƲß

```

Try it online!

This outputs the series generated by \\$f(n) = \text{sgn}(\tan(n+1))\\$ as \\$n = 0, 1, 2, 3, ...\\$, separated by newlines. This only yields \\$0\\$ iff \\$\tan(n+1) = 0\\$, which only happens when \\$n = 2k\pi-1\\$ for some integer \\$k\\$. As this is only an integer when \\$k = 0\\$ and \\$n = -1\\$, this never happens.

## How it works

```
‘ÆTṠṄaƲß - Main link. Takes an integer n (initially 0) on the left
‘        - Yield n+1
      Ʋ  - To n+1:
 ÆT      -   tan(n+1)
   Ṡ     -   sgn(tan(n+1))
    Ṅ    -   Print and return sgn(tan(n+1))
     a   -   Replace sgn(tan(n+1)) with n+1
       ß - Recursively call

```

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

```
Do[Print@RudinShapiro@n,{n,∞}]

```

Try it online!

***Rudin-Shapiro Sequence***

# Answer
> 3 votes
# Bash, 5 bytes

This outputs all items in the sequence \\$1, 1, 1, 1, ...\\$ ... the rules do not explicitly forbid it.

```
yes 1

```

Try it online!

# Answer
> 3 votes
# Python 3

```
def gray(n):
  return n ^ n>>1

previous = n = 0
while True:
    n += 1
    bitcount = bin(gray(n)).count('1')
    print(bitcount - previous)
    previous = bitcount

```

Try it online!

Sequence starts with `1 1 -1 1 1 -1 -1 1 1 1 -1`.

These are the differences in the number of set bits between adjacent gray codes. This happens to be the same sequence as:

1. Start with a single `1`
2. Reverse the current sequence of `1` and `-1` and negate every value. Join the original and modified sequence with a `1`. Repeat step 2.

`1` -\> `1 **1** -1` -\> `1 1 -1 **1** 1 -1 -1` -\> `1 1 -1 1 1 -1 -1 **1** 1 1 -1 -1 1 -1 -1`  -\> ...

Bonus implementation in Coconut using this construction:

```
sequence = [1]
print(1)
while True:
    new = sequence |> reversed |> map$(-) |> list |> x->[1]+x
    new |*> print$(sep='\n')
    sequence.extend(new)

```

Try it online!

# Answer
> 3 votes
# JavaScript, 120 bytes

```
k=>{f=n=>{a=0;if(!(n-1))return 1;for(i=0;++i<n;)if(!(n%i))a += f(i);return 0.5<a?-1:1};for(i=0;++i<k;)console.log(f(i))}

```

Print the Liouville function \\$f(n)\\$ for every integer \\$n\\$, OEIS A008836.

## Explain

The recurrence formula `f(1)=1; n > 1: f(n) = sign(1/2 - Sum_{d<n, d|n} f(d))`.

```
k=>{                                         // starts a function
  f=n=>{                                     // function for recurrence
    a=0;                                     // init accumulator
    if(!(n-1)) return 1;                     // end of recurrence
    for (i = 0; ++i<n;)                      // start loop, from 1 to n-1
      if(!(n%i)) a += f(i);                  // if n is divisible by i, add f(i) to a
    return 0.5<a?-1:1                      // return sign(1/2 - a)
  };
  for (i = 0; ++i<k;) console.log(f(i))      // print the sequence
}

```

# Answer
> 2 votes
# Haskell, 55 bytes

```
a=1: -1:(zipWith(*)a$tail b)
b=1:1:(zipWith(*)b$tail a)

```

Try it online!

`a` is the infinite sequence here. Neither is very interesting - `a` is `[1,-1,1,1,1,-1]` repeated forever and `b` is `[1,1,-1,1,-1,1]` repeated forever. However, I think this shows how cool Haskell's laziness is: you have two infinite lists dependent on each other. `a` starts with `1` and `-1`, and the rest of it is found by multiplying `a` by the tail of `b`. Similarly, `b` starts with `1` and `1`, and the rest of it is found by multiplying `b` by the tail of `a`.

So the third element of `a` would be `1 * 1 = 1` and for `b` it would be `1 * -1 = -1`. The fourth elements would be `-1 * -1 = 1` for `a` and `1 * 1 = 1` for `b`, and so on.

# Answer
> 2 votes
# Pyth, 10 bytes

```
#V=hZ_1VZ1

```

Try it online!

---

Sequence is `-1,1,-1,1,1,-1,1,1,-1,1,1,1,-1,1,1,1,-1,1,1,1...`, or `(-1,(1)*n)*n` for n in \[1, ∞).

# Answer
> 2 votes
# PHP, 127 bytes

```
$k = base_convert(unpack('H*', "Kaddath")[1], 16, 2);
for(;;$i = $i==strlen($k) ? 0 : $i){
  echo ($k[$i++] ? 1 : -1) . "\n";
}

```

Try it online!

It first converts the string `"Kaddath"` to a binary string (`"1001011011000010110010001100100011000010111010001101000"`) then loops on the string to produce the repeated sequence by outputting `1` for each `1` and `-1` for each `0`

Nothing sensational I fear, just warming up for the new golfing year!

EDIT: clearer code formatting, some parts were golfed by habit

# Answer
> 2 votes
# Wolfram Language (Mathematica), 256 bytes

Classifies every square-free semi-prime as a 1 or a -1.

```
f[n_]:=Return[SquareFreeQ[n]&&PrimeOmega[n]==2];
g[n_]:=Return[Map[First,FactorInteger[n]]];
h[{a_,b_}]:=Return[List[a*ModularInverse[a,b], b*ModularInverse[b,a]]];
i[{c_,d_}]:=Return[If[Max[{c,d}] == c,-1, 1]];
Do[If[f[n], Print@i[h[g[n]]], 0], {n,∞}]

```

Try it online!

First 10 terms

```
-1,-1,-1,1,-1,-1,-1,1,-1,1...

```

Which correspond to classification of the following square-free semi-primes:

```
6, 10, 14, 15, 21, 22, 26, 33, 34, 35...

```

Sequence definition:

Let \\$n\\$ be a Square-Free Semiprime, and let \\$p\\$ and \\$q\\$ be the two distinct prime numbers (positive) that uniquely produce \\$n\\$:

$$n = pq$$

It follows from Bezout's Identity that \\$\exists a, b \in \mathbb{Z} \\$ such that:

$$ap + bq = 1$$

Now, as both \\$p\\$ and \\$q\\$ are positive, it follows that \\$a\\$ and \\$b\\$ have opposite signs. Possible values for \\$a\\$ and \\$b\\$ can be given by the modular equations

$$ ap \equiv 1 \mod q $$

$$ bq \equiv 1 \mod p $$

Whereby choosing a representative for \\$a\\$ or \\$b\\$ enforces the choice for the representative of the other.

Let \\$c\\$ be the smallest positive representative of \\$a\\$'s equivalence class.

Similarly, let \\$d\\$ be the smallest positive representative of \\$b\\$'s equivalence class.

Thus, it follows that:

$$ cp + dq = 1 + n$$

Now we can decide on a binary classification of \\$n\\$ conditioned on the following:

$$cp \> dq$$

Or in other words which prime number contributes the most to the sum: \\$ cp + dq = 1 + n\\$

As it is arbitrary, we let \\$p \< q\\$ (One of the primes is always smaller than the other as they are not equal, otherwise \\$n\\$ would not be square-free), thus if \\$cp \> dq\\$ we produce a \\$-1\\$, otherwise a \\$1\\$.

**EXAMPLE**

Consider the semi-prime \\$n = 21\\$ which is uniquely factorised by \\$3\\$ and \\$7\\$. By definition we assign the smaller prime to the variable \\$p\\$.

$$p = 3$$

$$q = 7$$

Now we can find infinitely many pairs of integers \\$a\\$ and \\$b\\$ such that:

$$ 3a + 7b = 1$$

These values can be found by the extended-Euclidiean algorithm (An algorithm used to solve modular equations like the ones listed previously). Let's find one of these pairs, specifically the one where \\$a\\$ and \\$b\\$ have the smallest magnitude. In this case it is easy to verify (and verbose to show via the extended-Euclidean algorithm) that the two such values are:

$$a = -2$$

$$b = 1$$

Now if we were to add \\$n\\$ to both sides of \\$ap + bq = 1\\$

We get:

$$pq + ap + bq = 1 + n$$

$$(q + a)p + bq = 1 + n$$

Thus we let \\$c = q + a\\$ and \\$d = b\\$

For the specific example this yields:

$$c = 5$$

$$d = 1$$

Resulting in:

$$5\*3 + 1\*7 = 1 + 21$$

\\$3 \< 7\\$ and \\$5\*3 \> 1\*7\\$ thus by definition we classify \\$21\\$ as a \\$-1\\$.

# Answer
> 1 votes
# C (gcc), 14 bytes

```
n=1;f(){n=-n;}

```

Try it online!

Next value is returned every time \\$f\\$ is called.

First answer to repeat alternating signs: \\${-1, 1, -1, 1 \dots}\\$

# Answer
> 1 votes
# , 33 bytes

Inspired from an earlier code-golf challenge, on the Kempner series, this R code print out `1` when integer contains the digit 9 and `-1` otherwise:

```
while(T<-T+1)show(2*grepl(9,T)-1)

```

Try it online!

# Answer
> 1 votes
# 05AB1E

```
2[bxS<»,

```

Try it online!

Repeatedly converts `a` to binary, replaces 0 with -1 and then set the new `a` to `a` in binary interpreted in base-10, starting with `a=2`. EDIT: Turns out it is A008559

Explaination:

```
2              Pushes 2
 [             infinite loop
  b            convert to binary (e.g. "10")
   x           pushes tos and itself doubled.
               as strings is 05AB1E are numbers, 10 gets interpreted as a number
               (e.g. 10, 20)
    S          converts the top of the stack to a string of characters (e.g. ["2", "0"])
     <         subtract 1, which vectorizes.
               because in 05AB1E strings are numbers, it subtract 1 from each of the digits
      »        join by newlines
       ,       print

```

# Answer
> 1 votes
# PowerShell, 68 45 43 bytes

-an enormous 23 bytes thanks to Mazzy! The madlad.

Prints 1 when the integer is a Harshad number (it is divisible by the sum of it's own digits).

```
for(;){2*!(++$x%($x-replace'','+0'|iex))-1}

```

Try it online!

Link is to a longer version of the code that terminates after 1000 signs

# Answer
> 1 votes
# PowerShell, 20 bytes

```
for(){2*!(++$x%3)-1}

```

Try it online!

`1` for divisible by 3, `-1` for other

# Answer
> 1 votes
# Java

My lambda functions below outputs the Kolakoski sequence (A000002), where the `1` and `2` are mapped to `-1` and `1` respectively.

The Kolakoski sequence is a self-referential sequence which defines: \\$a(n)\\$ is the length of the \\$n^{th}\\$ run, starting at \\$a(1)=1\\$. Here a visual of the sequence, with the runs underneath it (both lines form the same exact sequence of 1s and 2s):

```
1 2 2 1 1 2 1 2 2 1 2 2 1 1 2 1 1 2 2 1 2 1 1 2 1 ...
— ——— ——— — — ——— — ——— ——— — ——— ——— — — ——— — —
1  2   2  1 1  2  1  2   2  1  2   2  1 1  2  1 1 ...

```

Which results in the following lambda function in Java:

```
import java.util.*;                       // Required import for List/ArrayList/Arrays
()->{                                     // Method without parameter nor return-type:
  List<Integer> sequence = new ArrayList(Arrays.asList(1,2,2));
                                          //  Start the sequence at 1,2,2
  for(int i=2;;i++){                      //  Loop `i` from 2 upwards indefinitely:
    int valueToPrint = sequence.get(i-2); //   Get the `i-2`'th value from the sequence
    System.out.print(valueToPrint*2-3     //   Convert 1 to -1 and 2 to 1, and print it
                      + " ");             //   with space delimiter
    int valueToAdd = i % 2 == 0 ?         //   If `i` is even:
                      1                   //    Create a value 1
                     :                    //   Else (`i` is odd instead):
                      2;                  //    Create a value 2
    sequence.add(valueToAdd);             //   Add that value to the sequence
    if(sequence.get(i) == 2)              //   And if the `i`'th value of the sequence is 2:
      sequence.add(valueToAdd); }}        //    Add that same value again

```

Try it online.

Golfed this would be **109 bytes**:

```
v->{var s="122";for(int i=1;;s+=(s.charAt(i)>49?11:1)<<i%2)System.out.print((s.charAt(++i-2)-48)*2-3+" ");}

```

Try it online.

**Explanation:**

```
v->{                       // Method with empty unused parameter and no return-type
  var s="122";             //  Sequence-String, starting at 1,2,2
  for(int i=1;             //  Loop from `i` upwards indefinitely:
      ;                    //    After every iteration:
       s+=                 //     Append to the sequence-String:
          (s.charAt(i)>49? //      If the `i`'th digit is a 2:
            11             //       Use 11
           :               //      Else (the `i`'th digit is a 1 instead)
            1)             //       Use a 1
              <<i%2)       //      And bitwise left-shift it by `i` modulo-2
                           //      (1 and 11 are 1 and 1011 in binary respectively.
                           //       Left-shifting this by 0 for even `i` won't change them,
                           //       but left-shifting them by 1 for odd `i` would become
                           //       binary 10 and 10110, which are the integers 2 and 22)
    System.out.print(      //   Print:
      (s.charAt(++i-2)     //    The `i-2`'th character
                           //    (after we've first increased `i` by 1 with `++i`)
       -48)                //    converted from character to integer
           *2-3            //    and transformed from 1/2 to -1/1 respectively
       +" ");}             //    Appended with a space delimiter

```

# Answer
> 1 votes
# Raku

```
(|(1 xx 420), -1, |(1 xx *))

```

Returns `-1` for the 421st element and `1` elsewhere.

# Answer
> 1 votes
# JavaScript - 92 bytes

```
x=[];for(i=1;i<Infinity;i++){x.push(...new Array(i).fill("1"));x.push("-1")};console.log(x);

```

Not the most original solution, but the shortest JavaScript one to date... The array we end up with will never actually be printed, but if you replace `Infinity` with something else like `10`, you can see the pattern. The `i`-th iteration of the infinite loop adds `i` 1s to the array then adds a `-1`.

# Answer
> 1 votes
# BRASCA, 23 bytes

```
1[25S[1n{]x25S[01-n{]x]

```

Try it online!

Outputs 25 `1`'s, then 25 `-1`'s, then repeats.

# Answer
> 1 votes
# C (gcc), 111 bytes

```
int i;

int main( void ){

    printf("%d ", "This is a unique sequence"[i++ % 26] % 2 * 2 - 1);

    main();
}

```

Try it online!

The program prints the following sequence periodically

```
-1 -1 1 1 -1 1 1 -1 1 -1 1 -1 1 1 1 1 -1 1 1 1 1 1 -1 1 1 -1

```

Here it becomes evident

Any bonus point for being 111 bytes?

# Answer
> 1 votes
# Pyt, 17 bytes

```
1`ĐĐĐŚ⇹ąŁ+|2*⁻ƥ⁺ł

```

Try it online!

Starting at n=1, outputs 1 if n is divisible by the sum of its digits PLUS its length when written in base 10, otherwise outputs -1.

Sequence begins: \[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,1,-1,-1,-1,1\]

```
1                       push 1
 `              ł       do... while top of stack is truthy
  ĐĐĐ                   Đuplicate three times
     Ś                  digit Śum
      ⇹                 swap top two items on stack
       ąŁ               convert to ąrray of digits; get Łength
         +              add
          |             does the sum divide n?
           2*⁻          coerce boolean to integer, double and decrement
              ƥ         ƥrint
               ⁺        increment

```

It is different from all of the previous sequences:

# Answer
> 0 votes
# 05AB1E, 4 bytes

```
₄Þ·<

```

Try it online!

Prints \[1, -1, -1, -1\] repeated forever

```
₄ push 1000
Þ repeat infinitly - [1, 0, 0, 0, 1, 0, 0, 0, ...]
· double - [2, 0, 0, 0, 2, 0, 0, 0, ...]
< substract 1 - [1, -1, -1, -1, 1, -1, -1, -1, ...]

```

# Answer
> 0 votes
# MATLAB/Octave

```
SymbPi = sym(pi);
detail = sym(1);
while 1
    bool = isAlways(mod(SymbPi,2*detail) > detail);
    if bool
       fprintf('1,');
    else
       fprintf('-1,');
    end
    detail = detail / 2;
end

```

Try it online! In theory can work forever but at some point it raches maximal precision.

Utilizes π number. In each loop iteration it calculates remainder from division by `2*detail` and checks whether its bigger than `detail`. `detail` is halved each iteration so it's: 1, 0.5, 0.25, 0.125, 0.0625 ... We're basically converting π to binary form. And for each so calculated boolean if it's true we print `1,` if not `-1,`.
Also, I used `fprintf` instead of classic `disp` just so everything will be nicely in one line.

---
Tags: math, sequence, popularity-contest, answer-chaining
---


title: Generate excel column name from index

text:
# Question
Title: Generate excel column name from index
This one comes from a real life problem. We solved it, of course, but it keeps feeling like it could have be done better, that it's too lengthy and roundabout solution. However none of my colleagues can think of a more succinct way of writing it. Hence I present it as code-golf.

The goal is to convert a nonnegative integer into a string the same way Excel presents its column headers. Thus:

```
0 -> A
1 -> B
...
25 -> Z
26 -> AA
27 -> AB
...
51 -> AZ
52 -> BA
...
16,383 -> XFD

```

It has to work **at least** up to 16,383, but beyond is acceptable too (no bonus points though). I'm looking forward most to the C# solution, but, as per traditions of code-golf, any real programming language is welcome.

# Answer
# Perl 6, ~~16~~ 14 bytes

```
{("A"..*)[$_]}

```

Works even beyond XFD. Thanks to infinite lists in Perl 6, this doesn't take forever (and a half) to execute.

Try it online!
> 4 votes

# Answer
## Excel Formula:), 36 chars

```
=SUBSTITUTE(ADDRESS(1,A1,4),"1","")

```

Usage:

Sorry, couldn't resist ...
> 22 votes

# Answer
## Perl, 17 characters

```
say[A..XFD]->[<>]

```

The `..` operator does the same thing as the magical auto-increment, but without the need for the temporary variable and loop. Unless `strict subs` is in scope, the barewords `A` and `XFD` are interpreted as strings.

(*This answer was suggested by an anonymous user as an edit to an existing answer. I felt it deserves to be a separate answer, and have made it one. Since it wouldn't be fair for me to gain rep from it, I've made it Community Wiki.*)
> 11 votes

# Answer
## Haskell, 48

```
f=(!!)(sequence=<<(tail$iterate(['A'..'Z']:)[]))

```

Less golfed:

```
f n = (concatMap sequence $ tail $ iterate (['A'..'Z'] :) []) !! n

```

### Explanation

Haskell's `sequence` combinator takes a list of actions and performs them, returning the result of each action in a list. For example:

```
sequence [getChar, getChar, getChar]

```

is equivalent to:

```
do
    a <- getChar
    b <- getChar
    c <- getChar
    return [a,b,c]

```

In Haskell, actions are treated like values, and are glued together using the `>>=` (bind) and `return` primitives. Any type can be an "action" if it implements these operators by having a Monad instance.

Incidentally, the list type has a monad instance. For example:

```
do
    a <- [1,2,3]
    b <- [4,5,6]
    return (a,b)

```

This equals `[(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]` . Notice how the list comprehension is strikingly similar:

```
[(a,b) | a <- [1,2,3], b <- [4,5,6]]

```

Because lists are a type of "action", we can use `sequence` with lists. The above can be expressed as:

```
sequence [[1,2,3],[4,5,6]]

```

Thus, `sequence` gives us combinations for free!

Thus, to build the list:

```
["A","B"..."Z","AA","AB"]

```

I just need to build lists to pass to `sequence`

```
[['A'..'Z'],['A'..'Z','A'..'Z'],...]

```

Then use `concatMap` to both apply `sequence` to the lists, and concatenate the resulting lists. Coincidentally, `concatMap` is the `=<<` function for lists, so the list monad lets me shave a few characters here, too.
> 6 votes

# Answer
## C, 53 characters

It's like playing golf with a hammer...

```
char b[4],*p=b+3;f(i){i<0||(*--p=i%26+65,f(i/26-1));}

```

Normal version:

```
char b[4];
char *p = b+3;
void f(int i) {
    if (i >= 0) {
        --p;
        *p = i%26 + 65;
        f(i/26-1);
    }
}

```

And the usage is like that:

```
int main(int argc, char *argv[])
{
    f(atoi(argv[1]));
    printf("%s\n", p);
    return 0;
}

```
> 6 votes

# Answer
# Perl, 26 characters

```
$x='A';map$x++,1..<>;say$x

```
> 5 votes

# Answer
### Ruby, 35 characters

```
e=->n{a=?A;n.times{a.next!};a}

```

Usage:

```
puts e[16383]   # XFD

```

Note: There is also a shorter version (30 characters) using recursion.

```
    e=->n{n<1??A:e[n-1].next}

```

But using this function you might have to increase the stack size for large numbers depending on your ruby interpreter.
> 4 votes

# Answer
# Groovy, 47

```
m={it<0?'':m(((int)it/26)-1)+('A'..'Z')[it%26]}

[0:'A',1:'B',25:'Z',
        26:'AA',
        27:'AB',
        51:'AZ',
        52:'BA',
        16383:'XFD'].collect {k,v-> assert v == m(k);m(k) }

```
> 3 votes

# Answer
# Python 45 ~~51~~

```
f=lambda i:i>=0and f(i/26-1)+chr(65+i%26)or''

```
> 3 votes

# Answer
# PHP, 30 bytes

```
for($c=A;$argn--;)$c++;echo$c;

```

Run as pipe with \`-nr' or try it online.
> 3 votes

# Answer
## Excel (MS365), 32 bytes.

```
=TEXTBEFORE(ADDRESS(1,A1,4),"1")

```
> 3 votes

# Answer
## Scala, 62 characters

```
def f(i:Int):String=if(i<0)""else f((i/26)-1)+(i%26+65).toChar

```

Usage:

```
println(f(16383))

```

returns:

```
XFD

```

You can try this on Simply scala. Copy and paste the function and use `f(some integer)` to see the result.
> 2 votes

# Answer
# Excel VBA, 31 Bytes

Anonymous VBE immediate window function that takes input from cell `[A1]` and outputs to the VBE immediate window

```
?Replace([Address(1,A1,4)],1,"")

```
> 2 votes

# Answer
# Java, 57 bytes (recursive)

```
String f(int n){return n<0?"":f(n/26-1)+(char)(n%26+65);}

```

Try it online.

**Explanation:**

```
String f(int n){        // Recursive method with integer parameter and String return-type
  return n<0?           //  If `n` is negative:
    ""                  //   Return an empty String
   :                    //  Else:
    f(n/26-1)           //   Recursive call with `n` integer-divided by 26, minus 1
    +(char)(n%26+65);}  //   And append `n%26+65` as character

```

---

# Java 10, 62 bytes (iterative)

```
n->{var r="";for(;n>=0;n=n/26-1)r=(char)(n%26+65)+r;return r;}

```

Try it online.

**Explanation:**

```
n->{                      // Method with integer parameter and String return-type
  var r="";               //  Result-String, starting empty
  for(;n>=0;              //  Loop as long as `n` is not negative
      n=n/26-1)           //    After every iteration: divide `n` by 26, and subtract 1
    r=(char)(n%26+65)+r;  //   Prepend `n%26+65` as character to the result-String
  return r;}              //  Return the result-String

```
> 2 votes

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

```
f=_=>_<0?'':f(_/26-1)+String.fromCharCode(_%26+65)

```

Try it online!

Seeing that a lot of people started answering this I answered too.

# Note :

This is basically a rip off of @kevinCruijssen's answer in Java shortened thanks to this being JS.
> 2 votes

# Answer
# VBA/VB6/VBScript (non-Excel), 73 bytes

```
Function s(i):While i:i=i-1:s=Chr(i Mod 26+65)&s:i=i\26:Wend:End Function

```

Calling `s(16383)` will return `XFC`.
> 1 votes

# Answer
# Jq 1.5, 71 bytes

```
[range(1;4)as$l|[65+range(26)]|implode/""|combinations($l)]|map(add)[N]

```

Expects input in `N`. e.g.

```
def N:16383;

```

Expanded:

```
[                       # create array with
   range(1;4) as $l     #  for each length 1,2,3
 | [65+range(26)]       #   list of ordinal values A-Z
 | implode/""           #   converted to list of strings ["A", "B", ...]
 | combinations($l)     #   generate combinations of length $l
]
| map(add)[N]           # return specified element as a string

```

Try it online!
> 1 votes

# Answer
# Javascript, 147 bytes

I had a similar problem. This is the golf of the solution. Excel columns are bijective base-26.

```
n=>{f=Math.floor;m=Math.max;x=m(0,f((n-24)/676));y=m(0,f(n/26-x*26));return String.fromCharCode(...[x,y,n+1-x*676-y*26].filter(d=>d).map(d=>d+64))}

```

Expanded, except using 1-indices:

```
function getColName(colNum){ // example: 16384 => "XFD"
    let mostSig = Math.max(0, Math.floor((colNum - 26 - 1)/26**2));
    let midSig = Math.max(0, Math.floor((colNum - mostSig*26**2 - 1)/26));
    let leastSig = colNum - mostSig*26**2 - midSig*26;

    return String.fromCharCode(...[mostSig,midSig,leastSig].filter(d=>d).map(d=>d+64));
}

```
> 1 votes

# Answer
# Forth (gforth), 59 bytes

```
: f dup 0< if drop else 26 /mod 1- recurse 65 + emit then ;

```

Try it online!

## Explanation

```
dup 0<            \ duplicate the top of the stack and check if negative
if drop           \ if negative, drop the top of the stack
else              \ otherwise
   26 /mod        \ divide by 26 and get the quotient and remainder
   1- recurse     \ subtract one from quotient and recurse on result
   65 + emit      \ add 65 to remainder and output ascii char
then              \ exit if statement

```
> 1 votes

# Answer
# , 65 bytes

Recursive answer as are many previous answers.

```
function(n,u=LETTERS[n%%26+1])"if"(n<=25,u,paste0(g(n%/%26-1),u))

```

Try it online!
> 1 votes

# Answer
# Powershell, 68 bytes

```
param($n)for(;$n-ge0;$n=($n-$r)/26-1){$s=[char](($r=$n%26)+65)+$s}$s

```

Alternative recursive version, 68 bytes:

```
filter g{if($_-ge0){(($_-($r=$_%26))/26-1|f)+[char]($r+65)}else{''}}

```

Test script:

```
$f = {

param($n)for(;$n-ge0;$n=($n-$r)/26-1){$s=[char](($r=$n%26)+65)+$s}$s

}

filter g{if($_-ge0){(($_-($r=$_%26))/26-1|f)+[char]($r+65)}else{''}}

@(
    ,(0 , "A")
    ,(1 , "B")
    ,(25 , "Z")
    ,(26 , "AA")
    ,(27 , "AB")
    ,(51 , "AZ")
    ,(52 , "BA")
    ,(676 , "ZA")
    ,(702 , "AAA")
    ,(16383 , "XFD")
) | % {
    $n, $expected = $_
    $result = &$f $n
    # $result = $n|g      # Alternative
    "$($result-eq$expected): $result"
}

```

Output:

```
True: A
True: B
True: Z
True: AA
True: AB
True: AZ
True: BA
True: ZA
True: AAA
True: XFD

```

Note: Powershell does not provide a `div` operator.
> 1 votes

# Answer
# Ruby, 26 bytes

```
->n{(?A..).take(n+1).last}

```

Attempt This Online!
> 1 votes

# Answer
# Excel, 30 bytes

```
=@TEXTSPLIT(ADDRESS(1,A1,4),1)

```
> 1 votes

# Answer
# Haskell, 48

I really thought that I would be able beat the other Haskell entry, but alas...

```
f(-1)=""
f n=f(div n 26-1)++[toEnum$mod n 26+65]

```

I am certain it is possible to shave a couple of characters off this, but I haven't coded in Haskell for nearly a year, so I am quite rusty.

It's not exactly what you would call elegant.
> 0 votes

# Answer
# \>\<\>, 29 bytes

```
!v:2d*%:"A"+@-2d*,1-:0(?!
$<o

```

Try it online!
> 0 votes

# Answer
# Icon, 58 bytes

```
procedure f(n);return(n<0&"")|f(n/26-1)||char(65+n%26);end

```

Try it online!
> 0 votes

# Answer
# Factor \+ `successor`, 27 bytes

```
[ "A"[ successor ] repeat ]

```

Attempt This Online!

Yup, Factor has a vocab for this.
> 0 votes

# Answer
# C (GCC), 39 bytes

```
f(i){i>25&&f(i/26-1);putchar(65+i%26);}

```

Try It Online!

Explanation:

```
f(i)
{
    // If i cannot be represented as a single letter
    i>25 &&
        // Print the next letter
        f(i/26-1);

    // Print the current letter
    putchar(65+i%26);
}

```

I thought using 0-based indexing was a little strange, so here's 1-based indexing in the same number of bytes:

```
f(i){i-->26&&f(i/26);putchar(65+i%26);}

```

Try It Online!
> 0 votes

---
Tags: code-golf, conversion
---


# Question
Title: Making one shape out of dissections of another
# Introduction

One question that I have come across recently is the possibility of dissecting a staircase of height 8 into 3 pieces, and then re-arranging those 3 pieces into a 6 by 6 square.

Namely, is it possible to dissect the following into 3 pieces:

```
x
xx
xxx
xxxx
xxxxx
xxxxxx
xxxxxxx
xxxxxxxx

```

And rearrange those 3 pieces into the following shape:

```
xxxxxx
xxxxxx
xxxxxx
xxxxxx
xxxxxx
xxxxxx

```

# Task

In this challenge, you will be tasked to find out exactly this. Specifically, given two shapes created from adjacent (touching sides, not diagonally) squares of the same size and a natural number `n`, return whether it is possible to dissect one of the shapes into `n` pieces, with all cuts along the edges of the squares, and then rearrange those `n` pieces to form the other shape. Just like the input shapes, each piece also has to be formed from adjacent squares and thus form one contiguous region. The pieces can be moved, rotated, and flipped in any way in order to form the other shape, but nothing else like shrinking or stretching the piece. The shapes can be represented in any reasonable form, including a 2d matrix with one value representing empty space and the other representing the actual shape, or a list of coordinates representing the positions of each individual square.

Additionally, you can assume that both shapes will consist of the same amount of squares, and that `n` will never exceed the number of squares within either of the shapes.

This is , so the shortest code in bytes wins!

# Test Cases

In these test cases, each square is represented by one `#`, and an empty space is represented by a space.

I made all the test cases by hand so tell me if there are any mistakes.

### Truthy

```
shape 1
shape 2
n
-------------------------------------
x
xx
xxx
xxxx
xxxxx
xxxxxx
xxxxxxx
xxxxxxxx

xxxxxx
xxxxxx
xxxxxx
xxxxxx
xxxxxx
xxxxxx

3

xxx
 xxx
xx
x

xxxxx
x xxx

3

xxxx
xxxx
xxxx
xxxx

xxxxx
x   x
x   x
x   x
xxxxx

4

x
x
xxx
 xxx
xx
x

xxxxx
xxxxxx

10

```

### Falsey

```
shape 1
shape 2
n
-------------------------------------
xxx
xxx

xxxxx
 x

2

xxxx
xxxx
xxxx
xxxx

xxxxx
x   x
x   x
x   x
xxxxx

3

###
###
###

#########

2

#####
 ## #
### #
  ##

#
##
###
####
#
##
 #

3

```

# Answer
> 7 votes
# Python3, 1163 bytes:

```
import itertools as I
E=enumerate
Q=lambda b:[(x,y)for x,r in E(b)for y,t in E(r)if t]
R=lambda x,f,n=3:[]if 0==n else[(X:=[*zip(*x)])]+R([X[::-1],[i[::-1]for i in X]][f],f,n-1)
D=[(0,1),(0,-1),(1,0),(-1,0)]
def V(t):
 q=[t.pop(0)]
 while q:
  x,y=q.pop(0)
  for X,Y in D:
   if(c:=(x+X,y+Y))in t:q+=[c];t.remove(c)
 return[]==t
def W(a,b):
 for i in b:
  q=[(a[0],i,{*a}-{a[0]},{*b}-{i},[a[0]],[i])]
  while q:
   (x,y),(j,k),A,B,S,s=q.pop()
   if not A:yield B-{*s};break
   F=0
   for X,Y in D:
    c,C=(x+X,y+Y),(j+X,k+Y)
    if c in A and c not in S and C in B:q+=[(c,C,A-{c},B,S+[c],s+[C])]
    elif c in A and c not in S and C not in B:F=1
   if F:break
def f(a,b,n):
 q,G,g,P=[(Q(a),Q(b),n)],eval(str(a)),eval(str(b)),[]
 while q:
  q=sorted(q,key=lambda x:len(x[0]))
  a,b,n=q.pop(0)
  if[]==[*a]+[*b] and n==0:return 1
  if all([a,b,n]):
   for i,_ in[*E(a,1)][::-1]:
    for t in I.combinations(a,i):
     if V([*t]):
      T=[[0 for _ in i]for i in G]
      for X,Y in t:T[X][Y]=1
      for o in[T,*R(T[::-1],0),*R([u[::-1]for u in T],1)]:
       if Q(o):
        for B in W(Q(o),b):
         if str(p:=([*{*a}-{*t}],B,n-1))not in P:q+=[p];P+=[str(p)]

```

Try it online!

# Answer
> 3 votes
# Vyxal, 60 bytes

```
ƛṖvøṖÞf'L⁰=;'ƛhw"λhn÷:k□ẊṠJ↔";Ẋ≈;A;ƛƛ3(:k+v*Ṙ)Wƛgv-s;g;s;;ƒ↔

```

Try it Online!

Very slow. Takes input as a list of lists of coordinates of the two shapes and then the number pieces. Outputs truthy value if it is possible and falsy otherwise. Works by finding all possible dissections into \\$n\\$ connected pieces for both of the shapes and then checking if they have any in common.

Get all dissections into \\$n\\$ pieces:

```
ṖvøṖÞf'L⁰=;

```

Keep only those where all the pieces are connected:

```
'ƛhw"λhn÷:k□ẊṠJ↔";Ẋ≈;A;

```

Transform all of the pieces into a unique representation by getting all rotations, sorting the coordinates by dictionary ordering, translating them so the first coordinate is `[0, 0]` and then taking the smallest one.

```
ƛƛ3(:k+v*Ṙ)Wƛgv-s;g;s;

```

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


# Question
Title: Consolidate a 6-axis 2-dimensional Vector
Typically, when we want to represent a magnitude and direction in 2D space, we use a 2-axis vector. These axes are typically called X and Y:

This isn't always convenient, however. The game BattleTech is played on a hexagonal grid, and it's convenient for the axes to line up with the sides of the hexagons. To represent velocity, thrust, and other such values, BattleTech uses a 6-axis Thrust Vector, with axes named A-F:

Here are a few example Thrust Vectors, all of which represent the following magnitude and direction:

* `{ A = 2, B = 1, C = 0, D = 0, E = 0, F = 0 }`
* `{ A = 3, B = 0, C = 1, D = 0, E = 0, F = 0 }`
* `{ A = 5, B = 0, C = 0, D = 3, E = -1, F = 0 }`

This follows from two rules of equivalence for Thrust Vectors:

* Adding or subtracting the same value to two opposite axes (A/D, B/E or C/F) leads to an equivalent Thrust Vector: `{ A = 1, D = 1 }` =\> `{A = 0, D = 0}`
* Subtracting a value from two axes with a single axis between them (A/C, B/D, C/E, D/F, E/A, F/B) and adding that value to the axis between them leads to an equivalent Thrust Vector: `{ A = 1, B = 0, C = 1 }` =\> `{ A = 0, B = 1, C = 0}`

It is possible to make a simple Thrust Vector look very complicated by placing value in axes in a different direction than the vector actually points in, which is undesirable. A *Consolidated Thrust Vector* is a Thrust Vector that fulfills the following conditions:

* No axes hold a negative value.
* There are up to 2 axes with nonzero values.
* If there are 2 axes with nonzero values, they are adjacent axes.

Of the above example vectors, only the first is Consolidated.

**Your challenge is to accept a 6-axis vector (as a 6-element list or other convenient structure) of integer magnitudes, and return an equivalent vector which has been consolidated. There is only one possible solution for any given input.**

Test cases:

* `-1, 0, 0, 0, 0, 0` =\> `0, 0, 0, 1, 0, 0`
* `1, 0, 0, 2, 0, 0` =\> `0, 0, 0, 1, 0, 0`
* `1, 0, 2, 0, 0, 0` =\> `0, 1, 1, 0, 0, 0`
* `1, 2, 3, 4, 5, 6` =\> `0, 0, 0, 0, 6, 0`
* `1, 0, 2, 0, 3, 0` =\> `0, 0, 0, 1, 1, 0`
* `1, 0, 1, 0, 1, 0` =\> `0, 0, 0, 0, 0, 0`
* `0, 0, 0, 0, 0, 0` =\> `0, 0, 0, 0, 0, 0`
* `0, 0, 0, 0, 0, 1` =\> `0, 0, 0, 0, 0, 1`
* `1, 0, 0, 0, 1, 0` =\> `0, 0, 0, 0, 0, 1`
* `-1, -1, -1, 1, 1, 1` =\> `0, 0, 0, 0, 4, 0`

# Answer
> 8 votes
# Python, 78 bytes

*-29 from ovs*
*-3 from loopy walt*

```
lambda v:-clip(A@v,v@A,0)
from numpy import*
A=1-abs((r_[:6]-c_[:6])%6*2-5)//2

```

Attempt This Online!

We want a function that returns the indicated number if positive, else 0, for the element corresponding to the black axis. That function is \\$\max(\min(x,y),0)\\$, where \\$(x,y)\\$ are the coordinates of the vector's endpoint with respect to the neighbouring grey axes.

Each coordinate in each of the six coordinate frames needed for the whole consolidated vector is in turn a linear function of the input coordinates. The linear functions can be combined into two circulant matrices – which is really one circulant matrix and its transpose.

`clip` is abused here with negation to implement \\$\max(\min(x,y),0)\\$. \\$-x\\$ is clipped to bounds \\$-y\\$ and 0, and then

* if \\$y\ge0\\$ normal clipping occurs and \\$\max(\min(x,y),0)\\$ is returned at the end by reversing the negation.
* if \\$y\<0\\$, `clip` is coded in NumPy to always return the upper bound of 0. But this is what we want, since \\$\min(x,y)\\$ will be negative regardless of \\$x\\$ and \\$\max(\min(x,y),0)\\$ will be 0.

# Answer
> 5 votes
# Charcoal, 47 bytes

```
ＵＭθ⁻ι§θ⁺³κ≔✂θ¹χ²ηＵＭθ∧﹪κ²⁻ι⁻Ση⁺⌊η⌈ηＩＥθ⌈⟦⁰⁻ι§θ⁺³κ

```

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

```
ＵＭθ⁻ι§θ⁺³κ

```

Subtract each element from its opposite.

```
≔✂θ¹χ²η

```

Get alternate elements so we can find the median (calculated below as `⁻Ση⁺⌊η⌈η`).

```
ＵＭθ∧﹪κ²⁻ι⁻Ση⁺⌊η⌈η

```

Subtract the median from the alternate elements and zero out the other elements for now.

```
ＩＥθ⌈⟦⁰⁻ι§θ⁺³κ

```

Reverse any negative elements and output the result.

Example for given test case of `0, 1, 1, 2, 3, 5`:

1. Subtract each element from its opposite, resulting in `-2, -2, -4, 2, 2, 4`.
2. Take alternate elements, resulting in `-2, 2, 4`. The median is `2`.
3. Subtract `2` from the alternate elements, resulting in `0, -4, 0, 0, 0, 2`.
4. Reverse the `-4`, resulting in `0, 0, 0, 0, 4, 2` which is the final answer.

# Answer
> 4 votes
# Vyxal, 16 bytes

```
y1Ǔ-:∆ṁ-:N1ǔY0v∴

```

Try it Online!

Port of *Neil's* Charcoal answer.

```
y                 # uninterleave
 1Ǔ               # rotate left by one
   -              # subtract
    :             # duplicate
     ∆ṁ           # median
       -          # subtract
        :         # duplicate
         N        # negate
          1ǔ      # rotate right by one
            Y     # interleave
             0v∴  # elementwise maximum with 0

```

# Answer
> 2 votes
# 05AB1E, 16 bytes

```
ι`À-DÅm-D(Á.ιDd*

```

Port of *@AndrovT*'s Vyxal and *@Neil*'s Charcoal answers, so make sure to upvote them as well!

Try it online or verify all test cases.

**Explanation:**

```
                  #  e.g. input=[1,2,3,4,5,6]
 ι                # Uninterleave the (implicit) input-list into 2 parts
                  #  STACK: [[1,3,5],[2,4,6]]
  `               # Pop and push both inner lists to the stack
                  #  STACK: [1,3,5],[2,4,6]
   À              # Rotate the top list once towards the left
                  #  STACK: [1,3,5],[4,6,2]
    -             # Element-wise subtract the values in the lists from one another
                  #  STACK: [-3,-3,3]
     D            # Duplicate this list
                  #  STACK: [-3,-3,3],[-3,-3,3]
      Åm          # Pop and push its median
                  #  STACK: [-3,-3,3],-3
        -         # Subtract that from each value in the list
                  #  STACK: [0,0,6]
         D(       # Create a negative copy
                  #  STACK: [0,0,6],[0,0,-6]
           Á      # Rotate that list once towards the right
                  #  STACK: [0,0,6],[-6,0,0]
            .ι    # Uninterleave the two lists to a single list
                  #  STACK: [0,-6,0,0,6,0]
              Dd* # Convert all negative values to 0s:
              D   #  Duplicate this list
                  #   STACK: [0,-6,0,0,6,0],[0,-6,0,0,6,0]
               d  #  Check for each value whether it's non-negative (>=0)
                  #   STACK: [0,-6,0,0,6,0],[0,0,0,0,1,0]
                * #  Element-wise multiply the values in the lists
                  #   STACK: [0,0,0,0,6,0]
                  # (after which the result is output implicitly)

```

# Answer
> 1 votes
# \[Wolfram Language (Mathematica)\], ~~150~~143 bytes

```
 (a=#;h=(a+a[[#1]]*RotateRight[{-1,1,-1,0,0,0},#1-#2])&;Do[a=h[i,1],{i,4}];Catch[Do[If[AllTrue[a,NonNegative],Throw[a]];a=h[i,3],{i,6,1,-1}]])&

```

Try it online!

I' did something looks like Python Parcly Taxel' answer, but it' s uncompetitive.
So I just start to play with equivalent transformations. If we apply four times function

```
 tr1[arr_,i_]:=(a=arr;d=arr[[i]];
                a[[i]]=0;
                a[[Mod[i+1,6,1]]]+=d;
                a[[Mod[i+2,6,1]]]-=d;
                a)

```

for `i = {1,2,3,4}` we get array `{0,0,0,0,x,y}`, but where `x, y` could be negative.
And if we start going backwards from `i=6` with

```
 tr2[arr_,i_]:=(a=arr;d=arr[[i]];
                a[[i]]=0;
                a[[Mod[i-1,6,1]]]+=d;
                a[[Mod[i-2,6,1]]]-=d;
                a)

```

than sooner or later we will get the array of the required type.
*No later than 6 steps* but I haven't found out exactly when, and had to apply the condition.
Try to improve the answer later

---
Tags: code-golf, number, hexagonal-grid
---


# Question
Title: Given an int input n, print out n*reversed(n)
Given an integer `n`, print out `n * reversed(n)`

`reversed(n)` is the number you get when you `reverse` the digits of `n`.

---

```
reverse(512) = 215

reverse(1) = 1

reverse(101) = 101

>>>>>>>>

```

---

```
func(5) = 5*5 = 25

func(12) = 12*21 = 252

func(11) = 11*11 = 121

func(659) = 659*956 = 630004

```

Shortest code wins!

## Leaderboard

```
var QUESTION_ID=144816,OVERRIDE_USER=71625;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# 05AB1E, 2 bytes

```
R*

```

Try it online!

In 05AB1E, integers and strings are treated as equivalent types, so reversal (`R`) converts to string and reverses, whilst multiplication (`*`) treats the reverse and the input as integers.
> 12 votes

# Answer
# JavaScript (SpiderMonkey), ~~45~~ ~~35~~ ~~33~~ 28 bytes

```
n=>n*[...n].reverse().join``

```

Try it online!
> 5 votes

# Answer
# Jelly, 3 bytes

```
×ṚḌ

```

I'm new to Jelly, so please let me know if there is a way to do this in 1 or 2 bytes!

Try it online!

### Explanation

```
×ṚḌ    (Input: 12)

 Ṛ     Reversed decimal digits (Stack: [2, 1])
×      Multiply by input       (Stack: [24, 12])
  Ḍ    Convert to decimal      (Stack: 252)
       Implicit print

```
> 5 votes

# Answer
# Ruby, ~~25~~ 24 bytes

```
->n{n*eval(n.digits*'')}

```

Try It Online!.

`Integer#digits` returns a list of reversed digits, so further reversing is not necessary.

Thanks to @benj2240 for golfing a byte!
> 4 votes

# Answer
# Ohm v2, 2 bytes

```
œΠ

```

Try it online!

Explanation:

```
œΠ   Main wire, arguments: n

œ    Pushes [n, n.reverse]
 Π   Multiplies that array together
     Implicit output

```
> 3 votes

# Answer
# ARBLE, 12 bytes

Takes input as an int.

```
a*reverse(a)

```

Try it online!
> 3 votes

# Answer
# Perl 5, 11 + 1 (`-p`) = 12 bytes

```
$_*=reverse

```

Try it online!
> 3 votes

# Answer
# Python 3, ~~35~~ 28 bytes

```
lambda m:m*int(str(m)[::-1])

```

Try it online!

Saved 7 bytes by fixing a bug pointed out by Dennis.
> 3 votes

# Answer
# Haskell, ~~27~~ 23 bytes

*4 bytes saved thanks to Lynn and Laikoni*

```
(*)=<<read.reverse.show

```

Try it online!
> 3 votes

# Answer
# J, 7 bytes

```
*|.&.":

```

Try it online!

Couldn't think of a shorter way, though I feel like this is pretty elegant.

### Explanation

```
*|.&.":
   &.":  Convert to string, apply next function, then undo conversion
 |.      Reverse
*        Multiply by input

```
> 3 votes

# Answer
# bash, ~~52~~ 48 bytes

```
for((i=n=$1;r=r*10+i%10*n,i/=10;));{ :;};echo $r

```
> 3 votes

# Answer
# C# .NET, 55 bytes

```
n=>{int i=n,j=0;for(;i>0;i/=10)j=j*10+i%10;return n*j;}

```

**Explanation:**

Try it here.

```
n=>{           // Method with integer as both parameter and return-type
  int i=n,     //  Integer `i` (starting at the input)
      j=0;     //  Integer `j` (starting at 0)
  for(;i>0;    //  Loop as long as `i` is not 0
      i/=10)   //    After every iteration: Remove the last digit of `i`
    j=j*10     //   Add a trailing zero to `j`,
      +i%10;   //   and then sum this new `j` with the last digit of `i`
               //  End of loop (implicit / single-line body)
  return n*j;  //  Return the input multiplied with `j`
}              // End of method

```
> 3 votes

# Answer
# Perl 6, 10 bytes

```
{$_*.flip}

```

Try it

## Expanded

```
{       # bare block lambda with implicit parameter $_
  $_
  *
  .flip # implicit method call on $_
}

```
> 3 votes

# Answer
# Batch, ~~150~~ ~~125~~ 121 bytes (+ 5 bytes? `cmd/q`)

```
set l=%1
set n=0
set r=
:L
call set t=%%l:~%n%,1%%%
set/an+=1
if [%t%] neq [] set r=%t%%r%&goto L
set/ar=%r%*%l%
echo %r%

```

Saved 25 bytes thanks to user202729!

Saved 4 bytes thanks to Matheus Avellar!
> 2 votes

# Answer
## Batch, 87 bytes

```
@set s=%1
@set r=
:l
@set/ar=r*10+s%%10,s/=10
@if %s% gtr 0 goto l
@cmd/cset/a%1*r

```

Need to take the arithmetic route here as string reversal fails for some numbers such as 80.
> 2 votes

# Answer
# C (gcc), 49 bytes

```
i,a;f(n){for(i=0,a=n;a>0;a/=10)i=i*10+a%10;n*=i;}

```

Try it online!
> 2 votes

# Answer
# LISP, ~~91~~ *64* bytes

~~(defun R (N)(defvar M (write-to-string N)) (parse-integer (reverse M))) (write (\* x (R x)))~~

```
(defun R(N)(write(* N(parse-integer(reverse(write-to-string N))))))

```

Where ~~x~~ N is your integer you want to work with, of course.

I'm pretty new to programming, but I've found that trying these Code Golf problems has been nice practice. Is there something I'm missing that could help with this?

EDIT: Thanks to some tips from ceilingcat, I was able to shave off a few bytes. Old program preserved in strikethrough for reference.
> 2 votes

# Answer
# Bash + GNU utilities, 18

```
bc<<<$1*`rev<<<$1`

```

Try it online.
> 2 votes

# Answer
# \>\<\>, ~~41~~ 39 Bytes

```
:&>:a%:}-\
/~\?)0:,a/
>l1-?\&*n;
\ +*a/

```

## How it works:

```
:&

```

Assume input has been pushed to the stack (https://codegolf.meta.stackexchange.com/a/8493/76025). Duplicate it and store a copy in the register.

```
   >:a%:}-\
   \?)0:,a/

```

Converts this to its individual digits, leaving them on the stack.

```
/~
>l1-?\
\ +*a/

```

The top value will always be a zero due to the number-to-digit conversion process; drop it from the stack. Now, while the length is \>1, multiply the first item by ten and add it to the item below it. This results in the number reversed.

```
      &*n;

```

Multiply the original number by the reverse, print the answer, and stop.
> 2 votes

# Answer
# Vyxal, 2 bytes

```
Ṙ*

```

Try it online, or verify all test cases.
> 2 votes

# Answer
# Julia, 28 bytes

```
~n=parse(Int,reverse("$n"))n

```

Attempt This Online!
> 2 votes

# Answer
# Leaf Lang, 41 bytes

Note: The interpreter does not have a stable release. If I introduce a breaking change I will update this post.

```
import"string.lf"argv:o o reverse o*print

```

Explained:

```
import "string.lf" - import stdlib's string.lf
argv               - push all of argv onto stack
:o                 - set o to top value from stack (pops top)
o                  - push o to top of stack
reverse            - reverse the string
o                  - push o to top of stack
*                  - leaf lang will implicitly convert strings to numbers when applicable
print              - print top value of stack with no newline

```

Ungolfed:

```
import "string.lf"
argv : num
num reverse num *
print

```
> 2 votes

# Answer
# Mathematica, 19 bytes

```
# IntegerReverse@#&

```

Takes an integer input.
> 1 votes

# Answer
# cQuents 0, 8 bytes

```
#|1:A\rA

```

Try it online!

## Explanation

```
#|1:      Output first term in sequence
    A\rA  Each term in the sequence equals:
           A * \reverse(A)

```
> 1 votes

# Answer
# Ly, 7 bytes

```
nsSrJl*

```

Try it online!
> 1 votes

# Answer
# Casio-Basic (fx-CP400), 44 bytes

```
ExpToStr n,a
StrInv a,a
Print n*strToExp(a)

```

There's no built-in for reversing an integer, but there is one for reversing a string.

`ExpToStr n,a` turns n into a string and stores it in `a`, then `StrInv a,a` overwrites `a` with the reversed version of itself. The last line turns `a` into a number, and prints `n*a`.

43 bytes for the code, +1 to input `n` into the parameters box.
> 1 votes

# Answer
# Japt, 2 bytes

Takes input as a string, outputs an integer.

```
*w

```

Try it
> 1 votes

# Answer
# MATLAB/Octave, ~~33~~ 31 bytes

```
@(n)str2num(flip(int2str(n)))*n

```

Try it online!

Octave/MATLAB anonymous function. This is a pretty naïve approach - converts the integer to a string, flips the string, converts the result back to an integer and multiplies it by the original.

---

* Save 2 bytes by using `flip` instead of `fliplr`.
> 1 votes

# Answer
# Python 2, 25 bytes

```
lambda n:n*int(`n`[::-1])

```

Try it online!
> 1 votes

# Answer
# PHP, 23+1 bytes

```
<?=$argn*strrev($argn);

```

Save to file and run as pipe with `-nF`.
> 1 votes

# Answer
# Lua, 42 bytes

```
function f(n)print(n*(""..n):reverse())end

```

Try it online!
> 1 votes

# Answer
# MATL, 5 bytes

```
VPUG*

```

Try it online!

Explanation: `V` converts to string, `P` flips, `U` converts back to numeric, `G` copies the original input again, and `*` multiplies them together.
> 1 votes

# Answer
# \>\<\>, 33 bytes

```
:&v>&*nr
a,>:a(?^:a%:@-
2(?va*+>l

```

Try it online!
> 1 votes

# Answer
# Runic Enchantments, ~~11~~ 10 bytes

```
i:0qr͍n*@

```

Try it online!

Takes input, duplicates it, coerces one copy to a string, reverses it, coerces it back to a numerical value, multiplies, and outputs the result.

`0q` performs the coercion to a string by concatenating a zero onto the end. There is no explicit `ToString()` operator, so this is the shortest method in this specific case where the 0 swapped to the beginning doesn't alter the resulting numerical value. *Thanks to ASCII-only for this -1 byte.*
> 1 votes

# Answer
# Pepe, 61 bytes

```
REeErEEEEErREEEeEerRREEEEEEEREEEEeEeerRREEEEEeEErRREEEEeEReEE

```

Try it online!
> 1 votes

# Answer
# Burlesque, 5 bytes

```
J<-|*

```

Try it online!

```
J  # Duplicate
<- # Reverse string
|* # string-to-val & multiply

```
> 1 votes

# Answer
## JavaScript, 72 bytes

Doesn't use strings. At all.

-10 by steffan

```
n=>(a=[],r=n=>(n>9&&r(n/10|0),a=[n%10,...a]))(n).reduce((a,v)=>a*10+v)*n

```
> 1 votes

# Answer
# Desmos, 97 bytes,

```
f=\left\{x>0:floor(log(x))+1,0\right\}
g(x)=x∑_{n=0}^f10^{f-n}floor(mod(\frac{x}{10^{n-1}},10))

```

Try it on Desmos.

Not sure if this is legal as a Desmos answer, uses the fact that variables can be defined in terms of x, but functions of x can use those variables as functions? I'm not sure what actually is happening, but it seems to be... working. If I'm not allowed to use that, change `f=` to `f(x)=` for +3 bytes

Only works for nonnegative integers, which I think is fine since OP doesn't include any test cases for them, and they're not well defined for this problem (what is `-1` backwards? `1-`? That's not a number IMO). If I'm allowed to assume *positive* integers, the first line can become

```
f=floor(log(x))+1

```

for -21 bytes. Very nice, but the challenge says "integers", so it's iffy.

In general though, I know this is further golfable but I tried some of the Desmos tips and I must be doing something wrong because they weren't working. I'll come back and golf this eventually.

Code breakdown:

```
f=\left\{x>0:floor(log(x))+1,0\right\} definition of... function(?) f
f=                                     define f as
         x>0:                          if x is positive
             floor(log(x))+1             length(x)
                            ,0         else 0
                                       i dont remember why but this works to make g(0)=0

g(x)=x∑_{n=0}^f10^{f-n}floor(mod(\frac{x}{10^{n-1}},10)) definition of main function
g(x)=                                                    define g(x) as
     x                                                   x times
      ∑                                                  the sum of
       _{n=0}^f                                          for each n from 0 to f(x)
               10^{f-n}                                    10^(f-n) times
                       floor(mod(\frac{x}{10^{n-1}},10))   the nth digit from the right of x
                                                         essentially: sum of
                                                           (nth digit of x)
                                                           multiplied by
                                                           (place value of
                                                           (length(x)-n)th digit of x
                                                         aka: reverse(x)

```
> 1 votes

# Answer
# Julia, ~~33~~ 32 bytes

```
~~`~n=foldl((x,y)->10x+y,digits(n))n`~~
```
* 1 more byte saved by @MarcMush:

```
a^b=10a+b
~n=foldl(^,digits(n))n

```

Attempt This Online!
> 1 votes

# Answer
# CJam, 8 bytes

```
l_W%i\i*

```

Try it online!
> 1 votes

# Answer
# brev, 28 bytes

```
(fn(*((as-list reverse)x)x))

```

Crashes on negative
> 1 votes

# Answer
# Pip, 4 bytes

```
a*Ra

```

Try It Online!
> 1 votes

# Answer
# RProgN 2, 6 bytes

```
]Ø.in*

]Ø.in*
]       # Duplicate the input to the stack
 Ø.     # Append a blank string, stringifying the input.
   i    # Reverse it.
    n   # Cast to a number.
     *  # Multiply with the orignal input, implicitely output.

```

Try it online!
> 0 votes

# Answer
# Pyth, 4 bytes

```
*s_`

```

Try it online!
> 0 votes

# Answer
# Octave, 66 bytes

```
n=m=input('');j=0;while(m!=0) j=10*j+rem(m,10);m=fix(m/10);end
n*j

```

Since Octave doesn't have a function to reverse integers, I had to write one myself. That's what the while loop does. Any help will be much appreciated.
> 0 votes

# Answer
# Husk, 6 bytes

```
S*(d↔d

```

Try it online!

**Explanation**

```
S*(    Multiply the input with the result of the following function applied to the input
     d convert number to list of digits
    ↔  reverse list
   d   interpret list of digits as number

```
> 0 votes

# Answer
# C# (.NET Core), 60 + 18 bytes

+18 bytes for `using System.Linq;`.

Reversing strings in C# is a pain.

```
n=>n*int.Parse(new string(n.ToString().Reverse().ToArray()))

```

Try it online!
> 0 votes

# Answer
# LOGO, 13 bytes

```
[?*reverse ?]

```

Currently there is no TIO for Logo, but you can try it online at http://golf.shinh.org/check.rb . However that's UCBLogo where there is a feature that prints

```
Thank you for using Logo.
Have a nice day.

```

on program exit; if this is considered as a function invocation it does not count. (that is, the function does not prints the message)

Usage:

```
print invoke [?*reverse ?] 123

```

or

```
print apply [?*reverse ?] [123]

```

prints

```
39483

```
> 0 votes

# Answer
# Recursiva, 6 bytes

```
*aI_Va

```

Try it online!

# Explanation:

```
*aI_Va
*a      - multiply by a(input)
  I     - Integerify
   _    - Reverse
    V   - Stringify
     a  - a (Input)

```
> 0 votes

# Answer
# Java 8, 50 bytes

```
n->n*new Long(new StringBuffer(n+"").reverse()+"")

```

Try it here.

Pretty straightforward.

* `n->`: Lambda-function with 64bit-number as input
* `n+""`: Convert the input-number to String
* `new StringBuffer(...)`: Convert this String to a `StringBuffer`
* `.reverse()`: Reverse it
* `...+""`: Convert the `StringBuffer` back to String
* `new Long(...)`: Convert this String back to a 64bit-number
* `n*...`: Multiply it with the original input, and return it

---

Arithmetic approach would be slightly longer (**55 bytes**):

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

```

Try it here.

Explanation can be found in my C# .NET port.
> 0 votes

# Answer
## Alice, 9 bytes

```
//.*
oR@i

```

Try it online!

### Explanation

```
/    Switch to Ordinal. Move SE.
R.   Reverse and duplicate an implicit empty string. Does nothing.
i    Read all input as a string.
.    Duplicate.
R    Reverse.
/    Switch to Cardinal. Move W.
*    Implicitly convert the two strings to integers and multiply them.
.    Duplicate the result. Irrelevant.
/    Switch to Ordinal. Move NW. Immediately bounces off the wall to move SW instead.
o    Implicitly convert the result back to a string and print it.
/    Switch to Cardinal. Move S.
R    Reverse the other copy of te result. Irrelevant.
/    Switch to Ordinal. Move NE. Immediately bounces off the wall to move SE instead.
@    Terminate the program.

```
> 0 votes

# Answer
## SAS, 54 bytes

```
%macro f(n);%put%eval(&n*%sysfunc(reverse(&n)));%mend;

```
> 0 votes

# Answer
# Tcl, 34 bytes

```
proc F n {expr $n*[string rev $n]}

```

Try it online!
> 0 votes

# Answer
# Swift 4, 37 bytes

```
{$0*Int(String("\($0)".reversed()))!}

```

**Try it here!**

Just my mandatory gigantic Swift entry.
> 0 votes

# Answer
# , 58 bytes

```
cat((n=scan())*sum(n%/%10^(d=1:nchar(n)-1)%%10*10^rev(d)))

```

Try it online!

reads from stdin, writes to stdout. `n%/%10^(d=1:nchar(n)-1)%%10` is how we get the digits, and reversing them is as simple as taking that vector, multiplying by `10^rev(d)`, and summing.

# \+ stringi, 47 bytes

```
cat(strtoi(stringi::stri_reverse(n<-scan()))*n)

```

Try it online!

`stringi` (not `stringr`) has a `stri_reverse` command.
> 0 votes

# Answer
# Excel VBA, ~~27~~ 22 Bytes

Anonymous VBE Immediate window function that takes input from `[A1]` and outputs to the VBE immediate window

```
?[A1]*StrReverse([A1])

```
> 0 votes

# Answer
# Pyth, ~~5~~ 4 bytes

```
*v_`

```

Try it online!

**Explanation:**

```
*v_`QQ : accepts a number as input
   `Q  : represent input as string
  _    : reverses string
 v     : evaluates the string as a number again
*    Q : multiply by the input
       : implicit output
(remove Q's as Pyth adds them for you)

```
> 0 votes

# Answer
# PowerShell, 31 Bytes

```
param($a)$a*-join("$a"[-1..-9])

```

Powershell is more than happy to multiply a number by a valid numerical string which is nice.
> 0 votes

# Answer
# Batch, 105 bytes

```
@set c=
@set a=%1
:J
@set c=%c%%a:~-1%
@set a=%a:~0,-1%
@if NOT "%a%" == "" goto J
@set/ac=%1*%c%

```

The reverse is performed in a loop which appends the last character `@set c=%c%%a:~-1%` from the input to `c`, and then removes the last character from the input string `@set a=%a:~0,-1%` \- rinse and repeat until there are no characters left on the input string. A quick multiplication `@set/ac=%1*%c%` and done.
> 0 votes

# Answer
# Implicit, 5 bytes

```
:ì\ì*

```

Try it online!

```
        « implicit integer input   »;
:       « duplicate                »;
 ì      « convert to string        »;
  \     « reverse                  »;
   ì    « back to int              »;
    *   « multiply                 »;
        « implicit integer output  »;

```
> 0 votes

# Answer
# QBIC, 12 bytes

```
_F!:$|?a*!A!

```

## Explanation

```
   :    Get the input number from the cmd line and assign to 'a'
  ! $     Cast it to string
_F   |    and flip[ that, assigning it into A$
?a*     PRINT 'a' times
   !A!    A$ cast back to int

```
> 0 votes

# Answer
# Aceto, 8 bytes

```
rd~isi*p

```

```
r  reads input
d  duplicates it
~  reverses the top value
i  convertes it to an integer
s  swaps the two top values
i  convertes the other value to an integer
*  multiplies the top two
p  prints the result

```

Try it online!
> 0 votes

# Answer
# APL (Dyalog Unicode), ~~9~~ 5 bytes

```
⍎×⍎∘⌽

```

Try it online!

Tacit prefix function. Takes input as a string of digits.

Thanks to Adám for 4 bytes.

### How it works:

```
⍎×⍎∘⌽ ⍝ Anonymous, tacit function.
    ⌽ ⍝ Reverse the input
  ⍎∘  ⍝ Convert to number
 ×    ⍝ and multiply
⍎     ⍝ by input converted to number

```
> 0 votes

# Answer
# Add++, 14 bytes

```
D,f,@,EDE@EdA*

```

Try it online!

## How it works

With example input of `12`

```
D,f,@,   - Create a monadic function, f
      ED - To digits;   STACK = [[1 2]]
      E@ - Reverse;     STACK = [[2 1]]
      Ed - From digits; STACK = [21]
      A  - Argument;    STACK = [21 12]
      *  - Product;     STACK = [252]

```
> 0 votes

# Answer
## REXX, 22 bytes

```
arg n
say n*reverse(n)

```
> 0 votes

# Answer
# Jelly, 4 bytes

```
DUV×

```

Try it online!
> 0 votes

# Answer
# Pyt, 3 bytes

```
Đ₫*

```

Try it online!

```
Đ    Duplicate
 ₫   reverse digits
  *  duh
     implicit output

```
> 0 votes

# Answer
# Gol\>\<\>, 21 bytes

```
I:WaSD$|r}l3-Fa*+|+*h

```

Try it online!

## An example \> A million words

```
I :D WaSD$D| Dr}l3-D Fa*+D| D+*h
^659
   [659 659]
          [659 9 65]
          [659 9 5 6]
          [659 9 5 6 0]
             [659 9 5 6 0]
                   [659 0 6 5 9 2] <- 2 = operations to do
                         [659 0 6 95]
                         [659 0 956]
                            [659 0 956]

```

Alternate

```
I:WaSD$|~r}l2-Fa*+|*h

```

```
I:&WaSD$|~rlMFa*+|&*h

```
> 0 votes

# Answer
# Java 8, 52 bytes

```
n->new Long(new StringBuilder(n+"").reverse()+"")*n;

```

Try it online
This will give every linter/IDE/compiler a stroke, but hey, it works
> 0 votes

# Answer
# APL(NARS), 8 char, 16 bytes

```
{⍵×⍎⌽⍕⍵}

```

test:

```
  f←{⍵×⍎⌽⍕⍵}
  f 23
736
  23×32
736
  f 11
121

```
> 0 votes

# Answer
# Keg, 3 bytes

```
:⑶*

```

Try it online!

A port of the 05AB1E answer but longer.
> 0 votes

# Answer
# Prolog (SWI), 47 bytes

```
N-O:-name(N,C),reverse(R,C),name(I,R),O is I*N.

```

Try it online!

-16 thanks to Jo King
> 0 votes

# Answer
# MathGolf, 2 bytes

```
x*

```

Try it online.

**Explanation:**

```
x   # Reverse the (implicit) input-integer
 *  # Multiply it by the (implicit) input-integer
    # (after which the entire stack is output implicitly as result)

```
> 0 votes

# Answer
# Fig, \\$2\log\_{256}(96)\approx\\$ 1.646 bytes

```
*$

```

See the README to see how to run this

```
*$ # Full program
*  # Multiply
 $ # The reversed number
   # By the implicit input

```
> 0 votes

# Answer
# CellTail, 89 bytes

```
1,_,_:1,N,N;N,(a,0,c),_:N,a*c,1;N,(a,b,c),_:N,(a,b/10,c*10+b%10),1;N,a&N..,N:N,(a,a,0),1;

```

Try the demo

CellTail has no way to turn a number into a string so we have to use modulus and integer division. Uses the cell to the right to provide recursion resistance.
> 0 votes

# Answer
# J-uby, 11 bytes

```
:*%(S|:~|Z)

```

Attempt This Online!

## Explanation

:* % (S | :~ | Z)

      S | :~ | Z   # Convert input to string, reverse, then convert to int
:* % (          )  # Multiply by input

```
</code></pre>
> 0 votes

# Answer
# GolfScript, 7 bytes

```
.`-1%~*

```

Try it online!

Link includes test cases

# Explanation

```
code    # explanation                             | stack
.`-1%~* # function which takes an input integer n | n
.       # duplicate n                             | n n
 `      # stringify                               | n str(n)
  -1%   # reverse                                 | n reverse(str(n))
     ~  # eval                                    | n reverse(n)
      * # multiply                                | n*reverse(n)

```
> 0 votes

# Answer
# SNOBOL4 (CSNOBOL4), 36 bytes

```
	OUTPUT =(I =INPUT) * REVERSE(I)
END

```

Try it online!
> 0 votes

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