title: Hostile Divisor Numbers

text:
# Question
Title: Hostile Divisor Numbers
Some divisors of positive integers really hate each other and they don't like to share one or more common digits.

Those integers are called *Hostile Divisor Numbers* (***HDN***)

**Examples**

Number `9566` has `4` divisors: `1, 2, 4783 and 9566`
(as you can see, **no two of them share the same digit**).
Thus, **9566** is a **H**ostile **D**ivisor **N**umber

Number `9567` is **NOT *HDN*** because its divisors (`1, 3, 9, 1063, 3189, 9567`) share some common digits.

Here are the first few ***HDN***

```
1,2,3,4,5,6,7,8,9,23,27,29,37,43,47,49,53,59,67,73,79,83,86,87,89,97,223,227,229,233,239,257,263,267,269,277,283,293,307,337...

```

**Task**

The above list goes on and your task is to find the *nth* ***HDN***

**Input**

A positive integer `n` from `1` to `4000`

**Output**

The `nth` ***HDN***

**Test Cases**

here are some **1-indexed** test cases.
Please state which indexing system you use in your answer to avoid confusion.

```
input -> output
 1        1
 10       23
 101      853
 1012     26053
 3098     66686
 4000     85009

```

This is , so the lowest score in bytes wins.

**EDIT**

Good news! I submitted my sequence to OEIS and...
Hostile Divisor Numbers are now OEIS A307636

# Answer
# 05AB1E, ~~12~~ 10 bytes

```
µNNÑ€ÙSDÙQ

```

-2 bytes thanks to *@Emigna*.

1-indexed

Try it online or verify most test cases (last two test cases are omitted, since they time out).

**Explanation:**

```
µ           # Loop while the counter_variable is not equal to the (implicit) input yet:
 N          #  Push the 0-based index of the loop to the stack
  NÑ        #  Get the divisors of the 0-based index as well
            #   i.e. N=9566 → [1,2,4783,9566]
            #   i.e. N=9567 → [1,3,9,1063,3189,9567]
    €Ù      #  Uniquify the digits of each divisor
            #   → ["1","2","4783","956"]
            #   → ["1","3","9","1063","3189","9567"]
      S     #  Convert it to a flattened list of digits
            #   → ["1","2","4","7","8","3","9","5","6"]
            #   → ["1","3","9","1","0","6","3","3","1","8","9","9","5","6","7"]
       D    #  Duplicate this list
        Ù   #  Unique the digits
            #   → ["1","2","4","7","8","3","9","5","6"]
            #   → ["1","3","9","0","6","8","5","7"]
         Q  #  And check if it is still equal to the duplicated list
            #   → 1 (truthy)
            #   → 0 (falsey)
            #  And if it's truthy: implicitly increase the counter_variable by 1
            # (After the loop: implicitly output the top of the stack,
            #  which is the pushed index)

```
> 9 votes

# Answer
# Python 2, 104 bytes

```
n=input()
x=1
while n:
 x=i=x+1;d={0};c=1
 while i:m=set(`i`*(x%i<1));c*=d-m==d;d|=m;i-=1
 n-=c
print x

```

Try it online!

0-indexed.
> 7 votes

# Answer
# Jelly, 10 bytes

```
ÆDQ€FQƑµ#Ṫ

```

Try it online!

-1 byte thanks to ErikTheOutgolfer

Takes input from STDIN, which is unusual for Jelly but normal where `nfind` is used.

```
ÆDQ€FQƑµ#Ṫ  Main link
         Ṫ  Get the last element of
        #   The first <input> elements that pass the filter:
ÆD          Get the divisors
  Q€        Uniquify each (implicitly converts a number to its digits)
    F       Flatten the list
     QƑ     Does that list equal itself when deduplicated?

```

2-indexed
> 6 votes

# Answer
# JavaScript (ES6), 78 bytes

1-indexed.

```
n=>eval("for(k=0;n;n-=!d)for(s=d=++k+'';k%--d||d*!s.match(`[${s+=d,d}]`););k")

```

Try it online!

### Faster version, 79 bytes

```
n=>{for(k=0;n;n-=!d)for(s=d=++k+'';k%--d||d*!s.match(`[${s+=d,d}]`););return k}

```

Try it online!

### How?

Given an integer \\$k\>0\\$, we build the string \\$s\\$ as the concatenation of all divisors of \\$k\\$.

Because \\$k\\$ is always a divisor of itself, \\$s\\$ is initialized to \\$k\\$ (coerced to a string) and the first divisor that we try is \\$d=k-1\\$.

For each divisor \\$d\\$ of \\$k\\$, we test whether any digit of \\$d\\$ can be found in \\$s\\$ by turning \\$d\\$ into a character set in a regular expression.

*Examples*

* \\$s=\text{"}956647832\text{"}\\$, \\$d=1\\$`"956647832".match(/[1]/)` is falsy
* \\$s=\text{"}9567\text{"}\\$, \\$d=3189\\$`"9567".match(/[3189]/)` is truthy

### Commented

*This is the version without `eval()`, for readability*

```
n => {                   // n = input
  for(                   // for() loop:
    k = 0;               //   start with k = 0
    n;                   //   go on until n = 0
    n -= !d              //   decrement n if the last iteration resulted in d = 0
  )                      //
    for(                 //   for() loop:
      s =                //     start by incrementing k and
      d = ++k + '';      //     setting both s and d to k, coerced to a string
      k % --d ||         //     decrement d; always go on if d is not a divisor of k
      d *                //     stop if d = 0
      !s.match(          //     stop if any digit of d can be found in s
        `[${s += d, d}]` //     append d to s
      );                 //
    );                   //   implicit end of inner for() loop
                         // implicit end of outer for() loop
  return k               // return k
}                        //

```
> 6 votes

# Answer
# Python 2 (PyPy), ~~117~~ 114 bytes

Uses 1-indexing

```
k=input();n=0;r=range
while k:n+=1;k-=1-any(set(`a`)&set(`b`)for a in r(1,n+1)for b in r(1,a)if n%a<1>n%b)
print n

```

Try it online!
> 4 votes

# Answer
# Perl 6, 53 bytes

```
{(grep {/(.).*$0/R!~~[~] grep $_%%*,1..$_},^∞)[$_]}

```

Try it online!

1-indexed.

`/(.).*$0/` matches any number with a repeated digit.

`grep $_ %% *, 1 .. $_` returns a list of all divisors of the number `$_` currently being checked for membership in the list.

`[~]` concatenates all of those digits together, and then `R!~~` matches the string on the right against the pattern on the left. (`~~` is the usual match operator, `!~~` is the negation of that operator, and `R` is a metaoperator that swaps the arguments of `!~~`.)
> 4 votes

# Answer
# Wolfram Language 103 bytes

Uses 1-indexing. I'm surprised it required so much code.

```
(k=1;u=Union;n=2;l=Length;While[k<#,If[l[a=Join@@u/@IntegerDigits@Divisors@#]==l@u@a&@n,k++];n++];n-1)&

```
> 3 votes

# Answer
# Python 3, 115 bytes

1-indexed

```
f=lambda n,x=1,s="",l="",d=1:n and(d>x+1and f(n-1,x+1)or{*s}&{*l}and f(n,x+1)or f(n,x,s+l,(1-x%d)*str(d),d+1))or~-x

```

Try it online!

This uses a *lot* of recursion; even with increased recursion limit, it can't do `f(30)`. I think it might be golfable further, and I tried finding something to replace the `(1-x%d)` with, but couldn't come up with anything (`-~-x%d` has the wrong precedence). Any bytes that can be shaved off are greatly appreciated.

# How it works

```
# n: HDNs to go
# x: Currently tested number
# s: String of currently seen divisor digits
# l: String of digits of last tried divisor if it was a divisor, empty string otherwise
# d: Currently tested divisor

f=lambda n,x=1,s="",l="",d=1:n and(                    # If there are still numbers to go
                             d>x+1and f(n-1,x+1)or     # If the divisors have been
                                                       #  exhausted, a HDN has been found
                             {*s}&{*l}and f(n,x+1)or   # If there were illegal digits in
                                                       #  the last divisor, x isn't a HDN
                             f(n,x,s+l,(1-x%d)*str(d),d+1)
                                                       # Else, try the next divisor, and
                                                       #  check this divisor's digits (if
                                                       #  if is one) in the next call
                             )or~-x                    # Else, return the answer

```
> 3 votes

# Answer
# PowerShell, 112 bytes

```
for($a=$args[0];$a-gt0){$z=,0*10;1..++$n|?{!($n%$_)}|%{"$_"|% t*y|sort -u|%{$z[+"$_"]++}};$a-=!($z|?{$_-ge2})}$n

```

Try it online!

Takes 1-indexed input `$args[0]`, stores that into `$a`, loops until that hits `0`. Each iteration, we zero-out a ten-element array `$z` (used to hold our digit counts). Then we construct our list of divisors with `1..++$n|?{!($n%$_)}`. For each divisor, we cast it to a string `"$_"`, cast it `t`oCharArra`y`, and `sort` those digits with the `-u`nique flag (because we don't care if a divisor itself has duplicate digits). We then increment the appropriate digit count in `$z`. Then, we decrement `$a` only if `$z` contains `0`s and `1`s (i.e., we've found an HDN). If we've finished our `for` loop, that means we found the appropriate number of HDNs, so we leave `$n` on the pipeline and output is implicit.
> 3 votes

# Answer
# Java 10, ~~149~~ ~~139~~ ~~138~~ ~~126~~ ~~125~~ ~~120~~ 119 bytes

```
n->{int r=0,i,d;for(;n>0;n-=d){var s="1";for(r+=d=i=1;i++<r;)if(r%i<1){d=s.matches(".*["+i+"].*")?0:d;s+=i;}}return r;}

```

-10 bytes by using `.matches` instead of `.contains` per digit, inspired by *@Arnauld*'s JavaScript answer.
-5 bytes thanks to *@ValueInk*
-1 byte thanks to *@ceilingcat*

1-indexed

Try it online.

**Explanation:**

```
n->{                 // Method with integer as both parameter and return-type
  int r=0,           //  Result-integer, starting at 0
      i,             //  Index integer
      d;             //  Decrement integer
  for(;n>0;          //  Loop until the input `n` is 0:
      n-=d){         //    After every iteration: decrease `n` by the decrement integer `d`
    var s="1";       //   Create a String `s`, starting at "1"
    for(r+=d=i=1;    //   (Re)set the decrement and index integers to 1,
                     //   and increase the result by 1 as well
        i++<r;)      //   Inner loop `i` in the range [2, r]:
      if(r%i<1){     //    If `r` is divisible by `i`:
        d=s.matches(".*["+i+"].*")?
                     //     If string `s` contains any digits also found in integer `i`:
           0         //      Set the decrement integer `d` to 0
          :d;        //     Else: leave `d` unchanged
        s+=i;}}      //     And then append `i` to the String `s`
  return r;}         //  After the loops, return the result `r`

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 74 bytes

```
Nest[1+#//.a_/;!Unequal@@Join@@Union/@IntegerDigits@Divisors@a:>a+1&,0,#]&

```

Try it online!
> 2 votes

# Answer
# Brachylog (v2), 14 bytes

```
;A{ℕfdᵐc≠&}ᶠ⁽t

```

Try it online!

Function submission; input from the left, output to the right. (The TIO link contains a command-line argument to run a function as though it were a full program.)

## Explanation

"Is this a hostile divisor number?" code:

```
ℕfdᵐc≠
ℕ       number is ≥0 (required to match the question's definition of "nth solution")
 f      list of all factors of the number
   ᵐ    for each factor
  d       deduplicate its digits
    c   concatenate all the deduplications with each other
     ≠  the resulting number has no repeated digits

```

This turned out basically the same as @UnrelatedString's, although I wrote it independently.

"nth solution to a " wrapper:

```
;A{…&}ᶠ⁽t
    &      output the successful input to
  {  }ᶠ    the first n solutions of the problem
       ⁽   taking <n, input> as a pair
;A         form a pair of user input and a "no constraints" value
        t  take the last solution (of those first n)

```

This is one of those cases where the wrapper required to produce the nth output is significantly longer than the code required to test each output in turn :-)

I came up with this wrapper independently of @UnrelatedString's. It's the same length and works on the same principle, but somehow ends up being written rather differently. It does have more potential scope for improvement, as we could add constraints on what values we were looking at for free via replacing the `A` with some constraint variable, but none of the possible constraint variables save bytes. (If there were a "nonnegative integer" constraint variable, you could replace the `A` with it, and then save a byte via making the the  unnecessary.)
> 2 votes

# Answer
# Brachylog, 16 bytes

```
g{∧0<.fdᵐc≠∧}ᵘ⁾t

```

Try it online!

Very slow, and twice as long as it would be if this was a . 1-indexed.

```
                    The output
               t    is the last
             ᵘ⁾     of a number of unique outputs,
g                   where that number is the input,
 {          }       from the predicate declaring that:
     .              the output
    <               which is greater than
   0                zero
  ∧                 (which is not the empty list)
      f             factorized
        ᵐ           with each factor individually
       d            having duplicate digits removed
          ≠         has no duplicate digits in
         c          the concatenation of the factors
           ∧        (which is not the output).

```
> 1 votes

# Answer
# Japt v2.0a0, 17 bytes

```
_=â ®sâÃ¬UµZ¶â}f1

```

Try it

Port of this Brachylog answer.

Credit: 4 bytes savings total thanks to Shaggy who also suggested there was a better solution leading to many more bytes :)

---

Original answer 28 byte approach:

```
Èâ¬rÈ«è"[{Y}]" ©X+Y}Xs)«U´Ãa

```

Try it

Port of this JavaScript answer.
> 1 votes

# Answer
# Perl 5 `-p`, 66 bytes

```
map{1while(join$",map{$\%$_==0&&$_}1..++$\)=~/(\d).* .*\1/}1..$_}{

```

Try it online!

1 indexed
> 1 votes

# Answer
# Husk, 10 bytes

```
!fȯS=uṁdḊN

```

Try it online!

Same method as Jelly.

# Husk, 19 bytes

```
!f(Λo¬Fnfo¬Eπ2mdḊ)N

```

Try it online!

The more manual cehcker.
> 1 votes

# Answer
# Vyxal, 10 bytes

```
λKvUfÞu;ȯt

```

Try it Online!
> 1 votes

# Answer
# Icon, 123 bytes

```
procedure f(n)
k:=m:=0
while m<n do{
k+:=1
r:=0
s:=""
every k%(i:=1 to k)=0&(upto(i,s)&r:=1)|s++:=i
r=0&m+:=1}
return k
end

```

Try it online!

1-indexed. Really slow for big inputs.
> 0 votes

# Answer
# , <sup>~~87~~</sup> 59 bytes

*-28 bytes thanks to FrownFrog*

```
0{(+1,1(-:~.)@;@(~.@":&.>@,i.#~0=i.|])@+{.)@]^:(>{:)^:_&0 0

```

Try it online!

## original

# , 87 bytes

```
[:{:({.@](>:@[,],([:(-:~.)[:-.&' '@,/~.@":"0)@((]#~0=|~)1+i.)@[#[)}.@])^:(#@]<1+[)^:_&1

```

Try it online!

Yikes.

This is atrociously long for J, but I'm not seeing great ways to bring it down.

## explanation

It helps to introduce a couple helper verbs to see what's happening:

```
d=.(]#~0=|~)1+i.
h=. [: (-:~.) [: -.&' '@,/ ~.@":"0

```
* `d` returns a list of all divisors of its argument
* `h` tells you such a list is hostile. It stringifies and deduplicates each number `~.@":"0`, which returns a square matrix where shorter numbers are padded with spaces. `-.&' '@,/` flattens the matrix and removes spaces, and finally `(-:~.)` tells you if *that* number has repeats or not.

With those two helpers our overall, ungolfed verb becomes:

```
[: {: ({.@] (>:@[ , ] , h@d@[ # [) }.@])^:(#@] < 1 + [)^:_&1

```

Here we maintain a list whose head is our "current candidate" (which starts at 1), and whose tail is all hostile numbers found so far.

We increment the head of the list `>:@[` on each iteration, and only append the "current candidate" if it is hostile `h@d@[ # [`. We keep doing this until our list length reaches 1 + n: `^:(#@] < 1 + [)^:_`.

Finally, when we're done, we return the last number of this list `[: {:` which is the nth hostile number.
> 0 votes

# Answer
# Perl 6, 74 bytes

```
{(grep {!grep *>1,values [(+)] map *.comb.Set,grep $_%%*,1..$_},1..*)[$_]}

```

0-indexed. Only the first three cases are listed on TIO since it's too slow to test the rest.

Try it online!
> 0 votes

# Answer
# Ruby, ~~110~~ ~~97~~ ~~92~~ 84 bytes

-13 bytes by leveraging @Arnauld's JavaScript regex check.

-5 bytes for swapping out the `times` loop for a decrementer and a `while`.

-8 bytes by ditching `combination` for something more like the other answers.

```
->n{x=0;n-=1if(s='';1..x+=1).all?{|a|x%a>0||(e=/[#{a}]/!~s;s+=a.to_s;e)}while n>0;x}

```

Try it online!
> 0 votes

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


title: Are the numbers amicable?

text:
# Question
Title: Are the numbers amicable?
Two numbers are considered amicable if the proper divisor sum of the first is the same as the second number, the second number's proper divisor sum is equal to the first number, and the first and second numbers aren't equal.

\\$s(x)\\$ represents the aliquot sum or proper divisor sum of \\$x\\$. 220 and 284 are amicable because \\$s(220) = 284\\$ and \\$s(284) = 200\\$.

Your task is, unsurprisingly, to determine whether two inputted numbers are amicable or not. The inputs will be positive integers and you may output two distinct, consistent values for amicable or not.

This is OEIS sequence A259180

This is a so the shortest code wins.

## Test cases

```
input, input => output
220, 284 => 1
52, 100 => 0
10744, 10856 => 1
174292, 2345 => 0
100, 117 => 0
6, 11 => 0
495, 495 => 0
6, 6 => 0

```

# Answer
# Jelly, 5 bytes

```
QfÆṣ⁼

```

A monadic link taking a list of two integers which returns 1 if they are a pair of amicable numbers and 0 otherwise.

**Try it online!**

### How?

```
QfÆṣ⁼ - Link: pair of numbers L, [a, b]   e.g. [220,284]  or [6,6]  or [6,11]  or [100,52]
Q     - de-duplicate L                         [220,284]     [6]       [6,11]     [100,52]
  Æṣ  - proper divisor sum of L (vectorises)   [284,220]     [6]       [6,1]      [117,46]
 f    - filter keep left if in right           [220,284]     [6]       [6]        []
    ⁼ - equal to L?                            1             0         0          0

```
> 5 votes

# Answer
# Python 2, ~~65~~ ~~63~~ 66 bytes

<sup>-2 bytes thanks to Mr. Xcoder</sup>

```
lambda c:[sum(i*(n%i<1)for i in range(1,n))for n in c]==c[::-1]!=c

```

Try it online!
> 3 votes

# Answer
# J, ~~51 28 27~~ 24 Bytes

-Lots of bytes thanks to @cole

-1 more byte thanks to @cole

```
~.-:[:|.(1#.i.*0=i.|])"0

```

Try it online!
> 3 votes

# Answer
# Python 2, 71 67 bytes

-4 bytes thanks to xnor

+9 bytes thanks to caird coinheringaahing

```
lambda c:[sum(i for i in range(1,x)if x%i<1)for x in c]==c[::-1]!=c

```

partly inspired by \[this answer\]
> 3 votes

# Answer
# Ruby, ~~64 60 59~~ 58 bytes

```
->c{c.map{|i|(1...i).sum{|j|i%j<1?j:0}}==c.rotate&&c==c&c}

```

Try it online!
> 3 votes

# Answer
# Brain-Flak, 178 bytes

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

```

Try it online!
> 3 votes

# Answer
# Python 3, 84 bytes

```
d=lambda n:sum(i*(n%i<1)for i in range(1,n))
f=lambda a,b:(d(a)==b)*(d(b)==a)*(a^b)>0

```

Straightforward solution. d sums up divisors (n%i\<1 evaluates to 1 iff i divides n). a^b is nonzero iff a!=b. The LHS of the inequality is thus 0 iff the numbers are not amicable and \>0 otherwise.
> 3 votes

# Answer
# Brachylog, 9 bytes

```
≠.{fk+}ᵐ↔

```

Try it online!

Takes input as a list and outputs through success or failure.

```
             The input
≠            which contains no duplicate values
 .           is the output variable,
  {   }ᵐ     and its elements'
    k        proper
   f         divisor
     +       sums
        ↔    reversed
             are also the output variable.

```
> 3 votes

# Answer
# Forth (gforth), 80 bytes

Refactored reffu's solution.

```
: d { n } 0 n 1 do n i mod 0= i * - loop ;
: f 2dup <> -rot 2dup d swap d d= * ;

```

Try it online!

### How it works

```
: d { n -- divsum } \ Takes a number and gives its divisor sum (excluding self)
                    \ Store n as a local variable
  0 n 1 do          \ Push 0 (sum) and loop through 1 to n-1...
    n i mod 0=      \   If n % i == 0, push -1 (built-in true in Forth); otherwise push 0
    i * -           \   If the value above is -1, add i to the sum
  loop ;            \ End loop and leave sum on the stack

: f ( n1 n2 -- f )  \ Main function f. Takes two numbers and gives if they are amicable
  2dup <>           \ Are they not equal? ( stack: n1 n2 n1<>n2 )
  -rot              \ Move the boolean under n1 n2 ( stack: n1<>n2 n1 n2 )
  2dup d swap d     \ Copy two numbers, apply d to both and swap
                    \ ( stack: n1<>n2 n1 n2 n2.d n1.d )
  d=                \ Compare two 2-cell numbers for equality; n1=n2.d && n2=n1.d
  * ;               \ Return the product of the two booleans

```
> 3 votes

# Answer
# Desmos, ~~214~~ 65+102=167 bytes

This is more of a fun answer, not a competitive one:

## Expression 1, 65 bytes:

```
g(N)=\sum_{n=1}^{N-1}\left\{\operatorname{mod}(N,n)=0:n,0\right\}

```

## Expression 2, 102 bytes:

```
f(M,N)=\left\{\left\{g(N)=M:1,0\right\}+\left\{g(M)=N:1,0\right\}+\left\{M=N:0,1\right\}=3:1,0\right\}

```

Try It On Desmos!

I feel like this could definitely be golfed a lot. Too bad I can't take out those `\left`'s and `\right`'s, because they are in front of brackets(Desmos won't allow me to for some reason).
> 3 votes

# Answer
# JavaScript (ES6), 53 bytes

Takes input in currying syntax `(a)(b)`. Returns `0` or `1`.

```
a=>b=>a!=b&a==(g=n=>--a&&a*!(n%a)+g(n))(a=g(a)-b?1:b)

```

### Demo

```
let f =

a=>b=>a!=b&a==(g=n=>--a&&a*!(n%a)+g(n))(a=g(a)-b?1:b)

console.log(f(220)(284))  // => 1
console.log(f(52)(100))   // => 0
console.log(f(100)(117))  // => 0
console.log(f(6)(6))      // => 0
```

### How?

We use the function **g** to get the sum of the proper divisors of a given integer.

We first compute **g(a)** and compare it with **b**. If **g(a) = b**, we compute **g(b)** and compare it with **a**. Otherwise, we compute **g(1)**, which gives **0** and can't possibly be equal to **a**.

We additionally check that **a** is not equal to **b**.
> 2 votes

# Answer
# Haskell, 53 bytes

*-2 bytes thanks to BMO. -1 byte thanks to Ørjan Johansen.*

```
a!b=a==sum[i|i<-[1..b-1],b`mod`i<1,a/=b]
a#b=a!b&&b!a

```

Try it online!

## Ungolfed with UniHaskell and `-XUnicodeSyntax`

```
import UniHaskell

equalsOmega       ∷ Int → Int → Bool
a `equalsOmega` b = a ≡ sum [i | i ← 1 … pred b, i ∣ b, a ≢ b]

areAmicable       ∷ Int → Int → Bool
areAmicable a b   = (a `equalsOmega` b) ∧ (b `equalsOmega` a)

```
> 2 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~153~~ 146 bytes

```
	DEFINE('D(X)I')
	DEFINE('A(M,N)')
A	A =EQ(D(M),N) EQ(D(N),M) ~EQ(N,M) 1 :(RETURN)
D	I =LT(I,X - 1) I + 1	:F(RETURN)
	D =EQ(REMDR(X,I)) D + I	:(D)

```

Try it online!

Defines a function `A` that computes the amicability of two numbers, returning `1` for amicable and the empty string for not. The algorithm is the same as my previous answer so I leave the old explanation below.

```
	DEFINE('D(X)I')					;*function definition
	M =INPUT					;*read M,N as input
	N =INPUT
	OUTPUT =EQ(D(M),N) EQ(D(N),M) ~EQ(N,M) 1 :(END)	;* if D(M)==N and D(N)==M and N!=M, output 1. goto end.
D	I =LT(I,X - 1) I + 1	:F(RETURN)		;* function body: increment I so long as I+1<X, return if not.
	D =EQ(REMDR(X,I)) D + I	:(D)			;* add I to D if D%%I==0, goto D
END

```
> 2 votes

# Answer
# APL+WIN, ~~49~~ ~~54~~ ~~41~~ ~~40~~ 35bytes

Rewritten to reject equal integer inputs

Prompts for screen input of a vector of the two integers.

```
(≠/n)×2=+/n=⌽+/¨¯1↓¨(0=m|n)×m←⍳¨n←⎕

```
> 2 votes

# Answer
# Japt, ~~7~~ ~~12~~ 10 bytes

Takes input as an array of 2 numbers.

```
®â¬xÃeUâ w

```

Try it

---

* Added 3 bytes to handle `[6,11]`.
* Added another 3 bytes after the challenge was updated to require input validation. (Boo-urns on both fronts!)
* Saved 1 byte thank to Oliver.
> 2 votes

# Answer
# Pyth, 13 bytes

```
&-FQqFms{*MyP

```

+4 bytes to check if values are distinct, I feel like that shouldn't be part of the challenge...

Can almost certainly be golfed a lot

Try it online!

---

```
&-FQqFms{*MyP     Full program, takes input from stdin and outputs to stdout
 -FQ              Q0 - Q1 is true, meaning elements are distinct
&                  and
      m       Q   for each element of the input list, apply
           yPd    take the powerset of the prime factors
        {*M       multiply each list and deduplicate
       s          and sum the list (this represents S(n)+n )
    qF            and fold over equality, returning whether the two elements are equal

```
> 2 votes

# Answer
# APL NARS, 38 bytes, 18 chars

```
{≠/⍵∧∧/⍵=⌽-⍵-11π⍵}

```

11π⍵ find the sum of divisors of ⍵ in 1..⍵; note that the question want (11π⍵)-⍵ and in APLsm

```
-⍵-11π⍵=-(⍵-11π⍵)=(11π⍵)-⍵

```

the test

```
  t←{≠/⍵∧∧/⍵=⌽-⍵-11π⍵}
  t 284 220⋄t 52 100⋄t 10744 10856 ⋄t 174292 2345
1
0
1
0
  t 100 117⋄t 6 11⋄t 495 495⋄t 6 6
0
0
0
0

```
> 2 votes

# Answer
# Forth (gforth), ~~91~~ 86 bytes

```
: d { n } 0 n 1 do n i mod 0= i * - loop ;
: f { a b } a b = 1+ a d b = b d a = * * ;

```

Try it online!

# Forth (gforth) No Locals, 94 bytes

**A more "Forthy" version that doesn't use local variables**

```
: d 0 over 1 do over i mod 0= i * - loop nip ;
: f 2dup = 1+ -rot 2dup d -rot d = -rot = * * ;

```

Try it online!
> 2 votes

# Answer
# PowerShell, ~~87~~ 96 bytes

```
param($a,$b)filter f($n){(1..($n-1)|?{!($n%$_)})-join'+'|iex}(f $a)-eq$b-and(f $b)-eq$a-and$a-$b

```

Try it online!

Takes input `$a,$b`. Defines a `filter` (here equivalent to a function) that takes input `$n`. Inside we construct a range from `1` to `$n-1`, pull out those that are divisors, `-join` them together with `+` and send that to `Invoke-Expression` (similar to `eval`).

Finally, outside the filter, we simply check whether the divisor-sum of one input is equal to the other and vice-versa (and input validation to make sure they're not equal). That Boolean value is left on the pipeline and output is implicit.
> 1 votes

# Answer
# , 67 bytes

```
function(a,b)sum(which(!a%%1:a))-a==b&sum(which(!b%%1:b))-b==a&b!=a

```

Try it online!

returns `TRUE` for amicable, `FALSE` for not.
> 1 votes

# Answer
# APL (Dyalog Unicode),  ~~45 38 44 36 35~~ 20 bytes

```
{(≠/⍵)∧(⌽⍵)≡+/¨¯1↓¨(0=⍵|⍨⍳¨⍵)/¨⍳¨⍵}

```

Try it online!

Infix Dfn, fixed for the equal inputs case.

Thanks @Uriel for 8 bytes; @cole for 1 byte; @Adám for 15 bytes.

### How?

```
{(≠/⍵)∧(⌽⍵)≡+/¨¯1↓¨(0=⍵|⍨⍳¨⍵)/¨⍳¨⍵} ⍝ Main function, infix. Input is ⍵.
{                               ⍳¨⍵} ⍝ Generate the range [1,n] for each element of ⍵.
                              /¨     ⍝ Replicate into each the resulting vectors of:
                   (  ⍵|⍨⍳¨⍵)        ⍝ ⍵ modulo each element of the ranges;
                    0=               ⍝ Equals 0?
               ¯1↓¨                  ⍝ Drop the last element of each
            +/¨                      ⍝ Sum of each
       (⌽⍵)≡                         ⍝ Check if the results match the inverse of ⍵.
      ∧                              ⍝ Logical AND.
 (≠/⍵)                               ⍝ Inputs are different

```

---

@Adám has also helped me with a ~~22~~ 20 byte tacit function that's equivalent to the Dfn:

```
≠/∧⌽≡(+/∘∊⍳⊆⍨0=⍳|⊢)¨

```

Try it online!

### How?

```
≠/∧⌽≡(+/∘∊⍳⊆⍨0=⍳|⊢)¨⍝ Tacit fn, takes one right argument.
     (            )¨ ⍝ For each element e of the argument
               ⍳|⊢   ⍝ e modulo range [1,e]
             0=      ⍝ Equals 0? This generates a boolean vector
            ⍨        ⍝ Swap arguments for the following op/fn
           ⊆         ⍝ Partition. This partitions the right vector argument according to 1-runs from a left boolean vector argument of same size.
          ⍳          ⍝ Range [1,e]
         ∊           ⍝ Enlist; dump all elements into a single vector.
        ∘            ⍝ And then
      +/             ⍝ Sum the elements
   ⌽≡                ⍝ Check if the resulting sums match the inverse of the argument
  ∧                  ⍝ Logical AND
≠/                   ⍝ The elements of the argument are different.

```
> 1 votes

# Answer
# Perl 6, 53 bytes

```
{([!=] $_)&&[eqv] .map: {set +$_,sum grep $_%%*,^$_}}

```

Try it online!

Takes input as a list of two numbers.
> 1 votes

# Answer
# 05AB1E, ~~8~~ 7 bytes

```
ÙÑO¥`_`

```

Try it online!
> 1 votes

# Answer
# Pyth, 12 bytes

```
q{_msf!%dTtU

```

Takes input as a list.
Try it online

### Explanation

```
q{_msf!%dTtU
   m         Q    For each element d of the (implicit) input...
          tUd     ... get the range [1, ..., d - 1]...
     f!%dT        ... filter those that are factors of d...
    s             ... and take the sum.
 {_               Reverse and deduplicate...
q             Q   ... and check if the end result is the same as the input.

```
> 1 votes

# Answer
## Batch, 127 bytes

```
@if %1==%2 exit/b
@set/as=t=%1+%2
@for /l %%i in (1,1,%s%)do @set/as-=%%i*!(%1%%%%i),t-=%%i*!(%2%%%%i)
@if %s%%t%==00 echo 1

```

Outputs `1` if the parameters are amicable. Works by subtracting all factors from the sum of the input numbers for each input number, and if both results are zero then the numbers are amicable.
> 1 votes

# Answer
# Red, 117 bytes

```
d: func[n][s: 0 repeat i n / 2[if n // i = 0[s: s + i]]]
a: func[n m][either(m = d n)and(n = d m)and not n = m[1][0]]

```

Try it online!
> 1 votes

# Answer
# Java (OpenJDK 9), 87 bytes

```
a->b->a!=b&f(a)==b&f(b)==a
int f(int n){int s=0,d=0;for(;++d<n;)s+=n%d<1?d:0;return s;}

```

Try it online!
> 1 votes

# Answer
# Vyxal, 5 bytes

```
∆KUṘ⁼

```

Try it Online!
> 0 votes

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


# Question
Title: Find columns where all characters are the same
I came across this question on SO and thought it'd make a nice golf challenge. So here it is:

### Challenge:

Write a program that reads a sequence of character strings, one per line, and outputs a list of all positions where each string has the same character.

### Input and output:

The input consists of one or more lines of printable non-whitespace ASCII characters, each followed by a newline. You *may* assume that all input lines have the same length. The newline is *not* to be considered part of the input (i.e. you should not output it as a matching character).

Example input (shamelessly stolen from the SO question):

```
abcdefg
avcddeg
acbdeeg

```

After reading the input, your program should print the positions of each matching column and the characters they contain. (Your program may, but need not, stop reading further input if it can determine early that there are no matching columns.) Any reasonable output format is permitted; in particular, you may use either 0-based or 1-based indexing for the positions.

Example output for the above input (using 0-based indexing):

```
0: a
3: d
6: g

```

### Scoring:

This is code golf, so shortest answer wins. In the event of a tie, fractional tie-breaker chars may be awarded for additional features:

* −½ chars for correctly handling input lines of unequal length. (Output should not contain positions past the end of the shortest input line.)
* −¼ chars for correctly handling input consisting of arbitrary UTF-8 encoded Unicode characters.

For inspiration, you may find some ungolfed solutions at the SO question (see above).

### Clarifications:

* Simply concatenating the positions and characters, as in `0a3d6g`, does *not* count as "reasonable output". You should provide some kind of separator (such as a space) between each element of the output so that it can be parsed unambiguously.
* The input will be provided on the standard input stream (`stdin`), or using whatever text file input mechanism is most natural to your language of choice. (If your chosen language doesn't *have* a natural mechanism for file input, do whatever seems closest in spirit.)
* The input ends when there is no more data to be read (i.e. when an end-of-file condition occurs). If you wish, you *may* require that the input be terminated by a blank line (which you then should not count as part of the input, obviously). If you do so, please mention it in your answer so that others can provide correct input for testing.
* Every input line, *including* the last one, ends with a newline character. Your answer must not report this newline as a matching column. (It's fine if your solution can also handle input where the last line doesn't end in a newline, but that's not required.)

# Answer
> 1 votes
# 05AB1E (legacy), score: \\$9\frac{1}{4}\\$ (10 bytes \- \\$\frac{3}{4}\\$ for both bonuses)

```
|ø€Ùā‚øʒнg

```

Outputs with 1-based indexing.

Try it online.

Uses the legacy version, because `ø` worked with a list of strings whereas the new version would need an explicit `€S` to convert each inner string to a list of characters first. It does mean I can't use the builtin  of the new version though, which pairs each item with its 0-based index. As alternative I use `ā‚ø` to pair with its 1-based index.

In the new 05AB1E version this would therefore have been **11 bytes**: `|€Sø€Ù.āʒнg` \- Try it online (with 0-based indexing instead).

**Explanation:**

```
|           # Push all input-lines as a list
 ø          # Zip/transpose; swapping rows/columns,
            # which implicitly discards any trailing characters for the 1/2 bonus
  €Ù        # Uniquify each inner string/character-list
    ā       # Push a list in the range [1, length] (without popping the list of strings)
     ‚      # Pair it with the list of strings
      ø     # Zip/transpose again, which pairs each string with its 1-based index
       ʒ    # Filter this list of string-index pairs by:
        н   #  Where the first item (the string)
         g  #  Has a length equal to 1 (note: only 1 is truthy in 05AB1E)
            # (after which the result is output implicitly)

```

# Answer
> 13 votes
## APL, 25 characters

```
∩/{0=⍴⍵:⍬⋄(⊂⍵,⍨¨⍳⍴⍵),∇⍞}⍞

```

I used Dyalog APL (version 13) as my interpreter. It handles both inputs of unequal length and Unicode (UTF-8) characters.

Examples:

```
      ∩/{0=⍴⍵:⍬⋄(⊂⍵,⍨¨⍳⍴⍵),∇⍞}⍞
abcdefg
avcddeg
acbdeeg

  1 a  4 d  7 g

      ∩/{0=⍴⍵:⍬⋄(⊂⍵,⍨¨⍳⍴⍵),∇⍞}⍞
test日本
blat日本国foo

  4 t  5 日  6 本

```

Explanation, somewhat from right to left:

* The main chunk of this answer is the direct function (basically, anonymous function), defined within the curly braces. Its right argument is specified by .
    + `0=⍴⍵:⍬` is our first expression, and it checks if we've gotten an empty line (i.e., we are done). It uses a guard (a familiar construct to many functional programmers) to conditionally execute the expression to the right of the colon. In this case, if 0 is equal to the shape/length () of the right argument, we return the empty set ().
    + separates the two expressions within the function. If the previous expression didn't get evaluated (and thus didn't return anything), we move to the next expression.
    + We recursively call the function using the self-reference function (). The argument to the function is a line of non-evaluated user input, given by quote-quad ().
    + `⊂⍵,⍨¨⍳⍴⍵` creates pairs for each character in the string, where each pair's first element is its position in the string, and its second element is the character.
    + `⍳⍴⍵` gives a vector from 1 to `⍴⍵`, or the length of the input string.
    + `⍵,⍨¨` applies the commuted concatenation function (`,⍨`) to each (`¨`) element to its left (, in this case the user's input) and right. Commuting the concatenation function causes its left and right arguments to be swapped.
    + Finally, we enclose the result using , so that we can differentiate between lines of input.
* We initially feed our function with user input ().
* Finally, we reduce (`/`) our resulting vector of vectors of pairs using the intersection function (), yielding the pairs that are found in all of the sub-vectors.

# Answer
> 12 votes
## Golfscript (28 chars)

```
n/zip:^,,{.^=.&.,1>{;;}*}%n*

```

There are character set issues when piping Unicode through, so no quarter-point bonus.

# Answer
> 10 votes
## J, 57 51 44 40 characters

```
,.&.>y;y{{.z[y=.I.*/2=/\]z=.];._2]1!:1]3

```

I'm getting there slowly but surely. This is still far from ideal though I think.

I felt sure that using a hook would be the answer but unfortunately not (44 chars):

```
,.&.>((];({{.)~)([:I.[:*/2=/\]))];._2]1!:1]3

```

I may need a completely different method to get any shorter.

# Answer
> 9 votes
## Python 2, score 81.5 (116 94 86 83 82 bytes minus bonus)

```
import sys
i=0
for x in zip(*sys.stdin)[:-1]:
 i+=1
 if len(set(x))<2:print i,x[0]

```

# Answer
> 8 votes
## Haskell, 64 characters

```
main=interact$show.foldl1(filter.flip elem).map(zip[0..]).lines

```

Handles lines of unequal length. Unicode support depends on the current locale settings.

**Example output:**

```
[(0,'a'),(3,'d'),(6,'g')]

```

# Answer
> 5 votes
## (Bash) Shell Scripting, 105 characters

If anyone has some more tricks for this, please fill free to comment!

```
for((i=1;i<`tail -1 $1|wc -c`;i++))do
x="cut -c$i $1";y=`$x`;[ `$x|uniq|wc -l` = 1 ]&& echo $i ${y:3};done

```

Result:

```
1 a
4 d
7 g

```

# Answer
> 4 votes
## Perl, 87 characters (−½ char tie-break bonus)

Here's a golfed version of my own solution from the SO thread:

```
chomp($a=$b=<>);$a&=$_,$b|=$_ for<>;@$_=$$_=~/./sgfor a,b;$b[$i++]eq$_&&say"$i:$_"for@a

```

Unlike the SO version, this one uses 1-based indexes for the output. It uses the Perl 5.10 `say` feature, so needs to be run with `perl -M5.010` (or with `perl -E`).

Like the SO version, this code handles variable-length lines, and *would* handle arbitrary Unicode input if the standard input and output were in UTF-8 mode. Alas, by default they're not, unless one specifies the non-free `-CS` command line switch. Thus, it earns the −½ char bonus, but not the −¼ one.

**Edit:** +1 char to fix a bug: just because the input strings don't contain line feeds doesn't mean they can't end up in `$a` (e.g. `"+" & "J" eq "\n"`).

# Answer
> 3 votes
## T-SQL

```
SELECT N.number, letter = MIN(SUBSTRING(L.line, N.number, 1))
FROM Lines AS L
INNER JOIN master.dbo.spt_values AS N ON N.type = 'P'
WHERE N.number BETWEEN 1 AND (SELECT MAX(LEN(L2.line)) FROM Lines AS L2)
GROUP BY N.number
HAVING COUNT(DISTINCT SUBSTRING(L.line, N.number, 1)) = 1
ORDER BY N.number

```

# Answer
> 3 votes
# Q, 32

```
{a!((*:)x)a:(&)1=(#:')(?:')(+)x}

```

usage

```
q){a!((*:)x)a:(&)1=(#:')(?:')(+)x}[("abcdefg";"avcddeg";"acbdeeg")]
0| a
3| d
6| g

```

# K, 22

The above solution can be reduced to 22 by writing it completely in K rather than passing K functions to a Q interpreter, reducing the number of parentheses required.

```
{a!@[*x]a:&1=#:'?:'+x}

```

# Answer
> 2 votes
### Scala 115107: (−¼ for handling UTF-8)

```
io.Source.stdin.getLines.map(_.zipWithIndex).toList.flatten.groupBy(_._2).map(_._2.toSet).filter(_.size==1)

```

ungolfed, and `Source.fromFile ("f")` instead of `stdin` for better testability:

```
io.Source.fromFile ("f").
  getLines.map (_.zipWithIndex).
    toList.flatten.groupBy (_._2).
      map (_._2.toSet).
        filter (_.size==1)

```

Result:

```
List(Set((a,0)), Set((g,6)), Set((d,3)))

```

Thanks to Gareth for the reduction of size 8 for using `stdin`.

# Answer
> 2 votes
## VBA (307.25 284 - 0.75 bonus = 283.25)

I know this has already been won, but here's my shot (not reading a file, just a string - needs to have the io added). I like that I got to use `l()` recursively. I usually don't have a need for recursion my real-life programming. I only did so much testing, but I believe this covers the unicode bonus point stipulation. It also assumes `vbCr` is the line terminator. This may not translate to all systems because of that.

**Code:**

```
Function a(i)
b=Split(Left(i,Len(i)-1),vbCr):c=UBound(b):For q=1 To Len(b(c)):d=Mid(b(c),q,1):If l(b,c,q,d) Then a=a & q & ": " & d & vbCr:Next
End Function
Function l(m, n, o, p)
If n+1 Then l=IIf(o<=Len(m(n)),Mid(m(n),o,1)=p,0) And l(m,n-1,o,p) Else l=Mid(m(n+1),o,1)=p
End Function

```

---

**Example input/output:**

```
Debug.Print a("abcdefghijklmnop" & vbCr & "abcdefg" & vbCr & "abcabcghijkl" & vbCr)

```

---

```
1: a
2: b
3: c
7: g

```

# Answer
> 1 votes
## JavaScript (125 134 140)

```
for(i=s=[];I=s[++i]=prompt(o='');S=I);for(c=-1;w=r=++c<S.length;o+=r?c+':'+C+'\n':'')for(C=S[c];w<i;)r&=s[w++][c]==C;alert(o)

```

Demo: http://jsfiddle.net/Fv7kY/4/

**Edit 1**: Rearrange loops to avoid braces. Initialize i with `[]` to combine with `s`. Move `w` increment into expression.

**Edit 2**: Set `S=I` to capture last entered word and save using `s[1]`. Combine `r=1` and `++c<S.length`. Set `C=s[c]` in inner loop and compare to `C` instead of previous and next words to shorten expression `s[w][c]==s[w++][c]` to just `s[w++][c]==C`. Saved a total of 9 characters. Also set `w=r=...` because when that's true `w=1` which is what we need to initialize `w` with.

# Answer
> 1 votes
## PHP, 123 127 :(

I'm not happy with it (there's bound to be improvements to be had), but here goes:

```
<?$a=$b=trim(fgets(STDIN));while($l=fgets(STDIN)){$a&=$l;$b|=$l;}$n=-1;while(@$a[++$n]){echo$a[$n]!=$b[$n]?'':"$n:{$a[$n]}\n";}

```

Proof it works.

If anyone can think of a more clever way of initializing $a and $b, please let me know. Originally I had `$a=$b=$n=''` and $b eventually was correct, but `[empty] & [anything] == [empty]`, so $a never had content.

---

Edit: Had to fix newline handling (+6) but dropped closing tag (-2).

# Answer
> 1 votes
## Common Lisp, 183 165 characters

```
(let((l(loop for m =(read-line)until(equal m "")collect m)))(loop for c across(car l)for i from 0 if(null(remove c(mapcar(lambda(y)(char y i))l)))collect(list i c)))

```

Readable format:

```
(let ((l (loop for m = (read-line) until (equal m "") collect m)))
  (loop for c across (car l)
        for i from 0
        if (null (remove c
                         (mapcar (lambda(y) (char y i))l)))
        collect(list i c)))

```

Enter this directly into the REPL and enter lines, terminating with an empty line.

# Answer
> 1 votes
# Ruby (71)

```
a,*s=*$<.lines
(a.size-1).times{|i|s.all?{|t|t[i]==a[i]}&&p([i,a[i]])}

```

output:

```
[0, "a"]
[3, "d"]
[6, "g"]

```

# Answer
> 1 votes
## C, 126 chars

```
char a[999],b[999];main(i){for(gets(a);gets(b);)for(i=0;b[i];++i)a[i]^b[i]?a[i]=0:0;
while(i--)a[i]&&printf("%d:%c\n",i,a[i]);}

```

I've been staring at this but I just can't make it smaller. A new approach may be needed.

(No bonus points; it only handles differently-sized lines if the first line is the shorter one.)

# Answer
> 1 votes
# Burlesque, 16 bytes

```
ln)XXtpzif{[~sm}

```

Try it online!

```
ln   # Split to lines
)XX  # Split each line to chars
tp   # Transpose
zi   # Zip with indices
f{   # Filter for
 [~  # Tail (i.e. chars)
 sm  # All the same
}

```

# Answer
> 1 votes
# T-SQL, 134 bytes

This can handle input lines of unequal length

Using 0-based indexing

```
SELECT n,max(z)FROM(SELECT
substring(x,number+1,1)z,abs(number)n,*FROM spt_values,@)t
GROUP BY n
HAVING max(z)=min(z)and n<max(len(x))

```

**Try it online**

# Answer
> 1 votes
## JavaScript (Node.js), 67 bytes (Anonymous function)

```
a=>[...a[0]].reduce((p,c,i)=>p+(a.every(s=>s[i]==c)?i+c+" ":""),"")

```

Try it online!

Input as array of lines, output in form `"0a 2g 5p "` etc

# Answer
> 0 votes
# C# with .NET 4 (280)

```
using c=System.Console;class P{static void Main(){char[]a=c.ReadLine().ToCharArray();int r,i,l=a.Length;m:i=0;n:r=c.Read();if(r>0&&r!=10&&r!=13){if((int)a[i]!=r)a[i]='\0';i++;goto n;}for(;i>0&&i<l;)a[i++]='\0';if(r>0)goto m;for(i=0;i<l;i++)if(a[i]!='\0')c.WriteLine(i+":"+a[i]);}}

```
* 1 line, 280 characters
* Includes all necessary using statements and Main method.
* Program **does not require** an empty line at the end, but will accept it
* Empty lines are ignored
* Handles input strings of any length.
* Reserves output until the end (whereas the original answer provided incremental output)

### Readable version

```
    char[]a=c.ReadLine().ToCharArray();
    int r,i,l=a.Length;
    m:
    i=0;
    n:
    r=c.Read();
    if(r>0&&r!=10&&r!=13){
        if((int)a[i]!=r)
            a[i]='\0';
        i++;
        goto n;
    }
    for(;i>0&&i<l;)
        a[i++]='\0';
    if(r>0)
        goto m;
    for(i=0;i<l;i++)
        if(a[i]!='\0')
            c.WriteLine(i+":"+a[i]);

```

---

### Original answer

~~using c=System.Console;class P{static void Main(){char\[\]a;var b=c.ReadLine();a=b.ToCharArray();while(b!=""){for(int i=0;i~~

~~* 1 line
* 207 characters
* Includes all necessary using statements and Main method.
* Program ends when an empty line is entered.
* Does not handle input strings that are shorter than the first.~~
~~---

Readable version:
```
    static void Readable()
    {
        char[]a;
        string b=System.Console.ReadLine();
        a=b.ToCharArray();
        while(b.Length>0)
        {
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i] != b[i])
                {
                    a[i] = '\0';
                }
                else
                {
                    System.Console.WriteLine(i+": "+a[i]);
                }
            }
            b=System.Console.ReadLine();
        }
    }

```~~

# Answer
> 0 votes
**python 122 characters**:

```
print("\n".join([str(i)+':'+str(x[0]) for i,x in enumerate(zip(*[tuple(x) for x in input().split()])) if len(set(x))<2]))

```

# Answer
> -1 votes
## Ruby (242)

```
s = %w{ abcdefg avcddeg acbdeeg aejdjeggd }
cols = []
s.sort{ |a, b| b.size <=> a.size }[0].size.times do |i|
  uneq=true
  l = s[0][i]
  s.each { |w| uneq = false if l != w[i] }
  cols << [l, i] if uneq
end
cols.each { |c| puts c.join('|') }

```

# Answer
> -1 votes
## C#

```
List<string> strings = new List<string> { "abcdefg", "avcddeg", "acbdeeg", "aejdjeggd" };
var transposes = from index in Enumerable.Range(0, strings.First().Length)
                 select new string((from s in strings select s[index]).ToArray());
int i = 0;
foreach(string transpose in transposes)
{
   if (transpose.Distinct().Count() == 1)
     Console.WriteLine("{0}: {1}", i , transpose[0]);
   i++;
}

```

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


title: Are they collinear?

text:
# Question
Title: Are they collinear?
# Task

Write a program/function that when given three 2d points in cartesian coordinates as input outputs a truthy value if they are collinear otherwise a falsey value

Three points are said to be collinear if there exists a straight line that passes through all the points

You may assume that the coordinates of the three points are integers and that the three points are distinct.

# Scoring

This is so shortest bytes wins

# Sample Testcases

```
(1, 1), (2, 2), (3, 3) -> Truthy
(1, 1), (2, 2), (10, 10) -> Truthy
(10, 1), (10, 2), (10, 3) -> Truthy
(1, 10), (2, 10), (3, 10) -> Truthy
(1, 1), (2, 2), (3, 4) -> Falsey
(1, 1), (2, 0), (2, 2) -> Falsey
(-5, 70), (2, 0), (-1, 30) -> Truthy
(460, 2363), (1127, 2392), (-1334, 2285) -> Truthy
(-789, -215), (-753, -110), (518, -780) -> Falsey
(227816082, 4430300), (121709952, 3976855), (127369710, 4001042) -> Truthy
(641027, 3459466), (475989, 3458761), (-675960, 3453838) -> Falsey

```

# Answer
> 14 votes
# Octave, 21 bytes

Takes a matrix `[x1, y1; x2, y2; x3, y3]` as input.

```
@(a)~det([a,[1;1;1]])

```

Try it online!

# Answer
> 12 votes
# JavaScript (Node.js), 39 bytes

```
(a,b,c,d,e,f)=>a*d+c*f+e*b==b*c+d*e+f*a

```

Try it online!

Accepts input as `(x1, y1, x2, y2, x3, y3)`. Uses the shoelace formula to determine if the enclosed area is 0.

### Explanation

The shoelace formula states that, the area of a polygon can be calculated using the coordinates of its vertices. Specifically, assuming the vertices are \\$P\_1, P\_2, \cdots, P\_n\\$ so that \\$P\_1P\_2, P\_2P\_3, \cdots, P\_{n-1}P\_n, P\_nP\_1\\$ are the edges of the polygon, then the area \\$A\\$ can be calculated with

$$A=\frac{1}{2}\left|(x\_1y\_2+x\_2 y\_3+\cdots+x\_{n-1}y\_n+x\_ny\_1)-(y\_1x\_2+y\_2x\_3 +\cdots+y\_{n-1}x\_n+y\_nx\_1)\right|$$

where \\$(x\_n,y\_n)\\$ are the coordinates of \\$P\_n\\$.

Taking \\$n=3\\$, we have the formula for the area of a triangle with coordinates \\$(x\_1,y\_1)\\$, \\$(x\_2,y\_2)\\$ and \\$(x\_3,y\_3)\\$:

$$A=\frac{1}{2}\left|(x\_1y\_2+x\_2y\_3+x\_3y\_1)-(y\_1x\_2+y\_2x\_3+y\_3x\_1)\right|$$

Three points are collinear if and only if the triangle constructed by these points has a zero area (otherwise, one of the points lies away from the line segment between the other two points, giving a non-zero area to the triangle). Since we only need to check whether the area is 0, the 1/2 and the absolute can be ignored. This boils down to checking whether

$$(x\_1y\_2+x\_2y\_3+x\_3y\_1)-(y\_1x\_2+y\_2x\_3+y\_3x\_1)=0$$

or after rearranging terms

$$x\_1y\_2+x\_2y\_3+x\_3y\_1=y\_1x\_2+y\_2x\_3+y\_3x\_1$$

# Answer
> 11 votes
# Jelly, 4 bytes

```
_ÆḊ¬

```

Try it online!

Takes the differences `[(a-b), (a-c)]` via automatic vectorization of `a-[b-c]` then checks if the determinant (`ÆḊ`) is 0 (`¬`).

# Answer
> 10 votes
# APL (Dyalog Unicode), ~~9~~ 8 bytes

```
0=11○÷.-

```

Try it online!

-1 byte thanks to @Jo King.

Takes one complex number (A) on the left, and two complex numbers (B and C) on the right. APL automatically maps scalars, so `A - B C` gives `(A-B)(A-C)`. Then divide between the two `÷.`, and check if the result's imaginary part `11○` is zero `0=`.

Uses `⎕DIV←1`, so if division by zero would occur (because `A=C`), `÷` returns 0 instead, which obviously has imaginary part of zero, giving truthy as a result.

# Answer
> 8 votes
# Python 2, 39 bytes

```
lambda a,b,c:(a-b)*(a-c-(a-c)%1*2)%1==0

```

Try it online!

**Input**: the 3 points as 3 complex numbers
**Output**: True or False.

**How**

Let the 3 points be \\$(a,A), (b,B), (c,C)\\$

The 3 points are colinear iff \\$(a-b)\*(A-C)=(A-B)\*(a-c)\\$. Note that this formula doesn't have division, and thus won't have floating point issue. Consider the following complex multiplication: $$ \big((a-b)+(A-B)i\big) * \big((a-c)-(A-C)i\big)$$ The imaginary part of the result is: $$(a-c)(A-B)-(a-b)(A-C)$$ which must be \\$0\\$ for the 3 points to be colinear.

Let `a`, `b`, `c` be the complex representation of the 3 points, then the condition above is equivalent to:

```
t = (a-b) * (a-c).conjugate()
t.imag == 0

```

Instead of using `imag` and `conjugate`, we can take advantage of the fact that all points are integers. For a complex number `t` where both the real and imaginary parts are integers, `t%1` gives the imaginary part of `t`. Thus:

```
t % 1 == t.imag * 1j
t - t % 1 * 2 == t.conjugate()

```

---

Old solution that doesn't use complex number

# Python 3, 43 bytes

```
lambda a,A,b,B,c,C:(a-b)*(A-C)==(A-B)*(a-c)

```

Try it online!

**Input**: the 2 coordinates of the first point, then the 2nd point, then the 3rd point.
**Output**: True or False.

---

This should work theoretically, but doesn't because of floating point imprecision:

# Python 3, 34 bytes

```
lambda a,b,c:((a-b)/(a-c)).imag==0

```

Try it online!

**Input**: 3 points, each represented by a complex number
**Output**: True or False.

# Answer
> 8 votes
# , 13 7 bytes

```
0=-/ .*

```

Try it online!

Uses the determinant. J's generalized determinant `u .v` is defined for non-square matrices, still multiplying (`*`) each x value with the difference of the other two y values (`-/`), finally reducing that result (`-/`). `-/ .*` calculates the determinant, check if it is `0=`.

# Answer
> 7 votes
# , 22 bytes

```
function(x)lm(1:3~x)$d

```

Try it online!

Finally a challenge which calls for `lm`!

The function `lm` performs linear regression. Here, we are using the input `x` as covariates, and `1 2 3` as observations (any vector of length 3 would do).

The output is an object with many components; of interest here is `df.residual` (which can be accessed with the unambiguous abbreviation `$d`), the residual degrees of freedom. This number corresponds to the number of observations minus the number of parameters being estimated. Now:

* if the points are not collinear, the regression proceeds normally, estimating 3 parameters, so `df.residual == 0`.
* if the points are collinear, there is an identifiability issue and only 2 parameters can be estimated (the last will be given as `NA`), so `df.residual == 1`.

Note that the final test case fails due to numerical precision issues.

# Answer
> 6 votes
# Wolfram Language (Mathematica), ~~20~~ 19 bytes

```
Det@{#2-#,#3-#}==0&

```

Try it online!

# Answer
> 5 votes
# , 27 bytes

```
function(m)!det(cbind(1,m))

```

Try it online!

Port of alephalpha's Octave answer.

# Answer
> 4 votes
# Raku, ~~21~~ 19 bytes

```
{!im [/] $^a X-@_:}

```

Try it online!

Takes input as three complex numbers and returns a boolean. Note that if the last and first points are identical (which is disallowed in the challenge spec), then the division operation would return NaN for dividing by zero, which boolifies to True for some reason, so this would fail.

# Answer
> 3 votes
# , 49 bytes

```
function(p,q=p-p[,1])q[1,3]*q[2,2]==q[2,3]*q[1,2]

```

Try it online!

How?

* Subtract first point from the other two:
* if points are on a line, the line must now pass through (x=0,y=0)
* so we check that the gradient=y/x is identical for both other points: y2/x2==y3/x3
* but to avoid dividing by zero, we rearrange: y2*x3==y3*x2

Edit:

* which, thanks to Kirill, alephalpha and Wikipedia, I've now discovered is simply the *determinant* of the matrix (x2,y2,x3,y3)
* so, for only 29 bytes: `function(p)!det(p[,-1]-p[,1])`

# Answer
> 2 votes
# 05AB1E, ~~18~~ ~~17~~ ~~27~~ 21 bytes

```
-Dн_iIн¹нQë`s/Uн¹н-X*¹θ+IθQ

```

Try it online!

Verify All Test Cases!

*-1 byte due to remembering implicit input exists and that variable assignment pops values*

*+10 due to bug fix regarding vertical lines :-(*

*-6 thanks to the wonderful @Kevin, who always manages to golf my 05AB1E answers! :D. Go and upvote his posts!*

## Explained

Before we even begin to look at the program, let's take a look at the maths needed to see if three points are collinear. Let our first point have co-ordinates \\$(x\_1, y\_1)\\$, our second point have co-ordinates \\$(x\_2, y\_2)\\$ and our third point have co-ordinates \\$(x\_3, y\_3)\\$.

If the three points are collinear, then point three will lie on the line formed by joining points one and two. In other words, \\$x\_3\\$, when plugged into the equation formed by the line joining points 1 and 2, gives \\$y\_3\\$.

"But what's the line between point 1 and 2?" I hear you ask. Well, we use the good old "point-graident" method to find the line's equation:

$$ y - y\_1 = m(x - x\_1), m = \frac{y\_2 - y\_1}{x\_2 - x\_1}\\ y - y\_1 = \frac{y\_2 - y\_1}{x\_2 - x\_1}(x - x\_1) $$

Now, we add \\$y\_1\\$ to both sides to get an equation where plugging in an `x` value gives a single `y` value:

$$ y = \frac{y\_2 - y\_1}{x\_2 - x\_1}(x - x\_1) + y\_1 $$

Substituting \\$x\\$ for \\$x\_3\\$ and \\$y\\$ for \\$y\_3\\$ gives an equality that determines if three points are collinear.

Alright, time for the code (as explained by Kevin).

```
-                     "[x2-x1, y2-y1]"\
 V                    "pop and store it in variable `Y`"\
  ¹-                  "[x3-x1, y3-y1]"\
    н                 "Pop and leave only x3-x1"\
     Yн_i             "If x2-x1 from variable `Y` == 0:"\
         _            " Check if the x3-x1 at the top == 0"\
        ë             "Else:"\
         Y`s/         " Divide (y2-y1) by (x2-x1) from variable `Y`"\
             *        " Multiply it by the x3-x1 at the top"\
              ¹θ+     " Add x1"\
                 Q    " Check [x3 == this value, y3 == this value] with the implicit third input"\
                  θ   " And only keep the last one: y3 == this value"\

```

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 39 bytes

```
(a,A,b,B,c,C)=>(b-a)/(B-A)==(c-a)/(C-A)

```

Try it online!

# Answer
> 2 votes
# AWK, 45 bytes

```
{print!($2*$3+$4*$5+$6*$1-$1*$4-$2*$5-$3*$6)}

```

Try it online!

Near-identical to Rich Farmbrough's Perl answer, but the syntax seemed better-suited to AWK than Perl. Thanks Rich!

# Answer
> 1 votes
# Charcoal, 21 bytes

```
ＮθＮηＮζ⁼×⁻ηＮ⁻θＮ×⁻ηＮ⁻θζ

```

Try it online! Link is to verbose version of code. Takes input as six integers and outputs a Charcoal boolean, i.e. `-` for collinear, nothing if not. Uses @SurculoseSputum's original formula. Explanation:

```
Ｎθ                      Input `a`
  Ｎη                    Input `A`
    Ｎζ                  Input `b`
         η              `A`
        ⁻               Minus
          Ｎ             Input `B`
       ×                Multiplied by
            θ           `a`
           ⁻            Minus
             Ｎ          Input `c`
      ⁼                 Equals
                η       `A`
               ⁻        Minus
                 Ｎ      Input `C`
              ×         Multiplied by
                   θ    `a`
                  ⁻     Minus
                    ζ   `b`
                        Implicitly print

```

# Answer
> 1 votes
# \[Excel\], 37 bytes

```
=0=MDETERM(A1:C3+{0,0,1;0,0,1;0,0,1})

```

Example:

# Answer
> 1 votes
# \[Google Sheets\], 27 bytes

```
=0=MDETERM({A1:B3,{1;1;1}})

```

Try it online!

# Answer
> 1 votes
# Perl 5, ~~35~~62 bytes

```
sub d{($a,$b,$c,$d,$e,$f)=@_;$b*($c-$e)+$d*($e-$a)+$f*($a-$c)}

```

Try it online!

I've put the wrapping on as explained in the comments, and golfed the original "guts" down by picking out some common factors

$b\*($c-$e)+$d\*($e-$a)+$f\*($a-$c)

(--First attempt --)

```
$b*$c+$d*$e+$f*$a-$a*$d-$c*$f-$e*$b

```

Try it online!

* Not sure if this follows the rules (where are they?) for header and footer, as much trying out "tio" as anything.
* This takes the test text as per the question and outputs the exact same text! In other words it's equivalent to while(\<\>){print}, provided you feed it a crib sheet. If you remove (or change) the answers from the input, it will supply them.

# Answer
> 1 votes
# Husk, 7 bytes

```
EẊoF/z-

```

Try it online!

# Answer
> 0 votes
# Vyxal, 4 bytes

```
v-ÞḊ

```

Try it Online!

Outputs `0` for truthy and any other integer for falsy. Port of fireflame241's Jelly answer. Add `¬` at the end to get `1` for truthy and `0` for falsy.

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


title: Cryptic Multiplications

text:
# Question
Title: Cryptic Multiplications
Given two non-negative integers e.g. `27, 96` their multiplication expression would be `27 x 96 = 2592`.
If now each digits is replaced with a symbol, such that

* *two digits are replaced with the same symbol if and only if they are equal*

we could get something like `AB x CD = AECA` or `0Q x 17 = 0Z10` or `!> x @^ = !x@!`.
(following this rule we can also get the original expression itself but we'd lose the meaning of the digits being numbers since they will become just placeholders).
We call such an expression a ***cryptic multiplication*** of `{27, 96}`.

Is clear that some information is lost and the process is not always reversible, indeed an `AB x CD = AECA` ***cryptic multiplication*** can be obtained from each of the following pairs

* `{27, 96}` `27 x 96 = 2592`
* `{28, 74}` `28 x 74 = 2072`
* `{68, 97}` `68 x 97 = 6596`

There is no other pair of numbers that yields `AB x CD = AECA`.
Hence ***3*** is the ***cryptic multiplication ambiguity*** of `{27, 96}`

Write a function or a program that given two non-negative integers prints their ***cryptic multiplication ambiguity***.

## Test cases

```
{0, 0} -> 2
{5, 1} -> 17
{11, 11} -> 1
{54, 17} -> 18
{10, 49} -> 56
{7, 173} -> 1
{245, 15} -> 27
{216, 999} -> 48
{1173, 72} -> 3

```

*Mathematica reference program*

# Answer
> 7 votes
# K (ngn/k), ~~41~~ 36 bytes

-5 bytes inspired by Jonathan Allan's answer.

```
{#*={.(=`k@x,*/x)_" "}'?+x,'!10*1+x}

```

Try it online! The last 4 cases are too slow to run online.

# Answer
> 5 votes
# Vyxal `s`, 17 bytes

```
vL↵ʀΠƛ?"ƛΠJṄ:vḟ;≈

```

Try it Online!

This would flaglessly be 19 bytes. It can be shorter flagless, though:

# Vyxal, 18 bytes

```
vL↵ʀΠ?wJƛΠJṄ:vḟ;ṫO

```

Try it Online!

```
vL↵ʀΠ?wJƛΠJṄ:vḟ;ṫO
vL                  # For each number in the input, get its length
  ↵                 # Take 10 to the power of each
   ʀ                # For each, generate an inclusive zero range [0, n]
    Π               # Get the cartesian product of these two lists
     ?wJ            # Append the input to this
        ƛ           # For each:
         Π          #  Get the product of the two
          J         #  Append that onto the list
           Ṅ        #  Join by spaces
            :       #  Duplicate
             vḟ     #  For each in the duplicate, get the first index that it occurs in the other identical copy
               ;    # Close map
                ṫ   # Tail extract - push a[:-1] and a[-1]
                 O  # Count the number of times this a[-1] appears in this a[:-1]

```

# Answer
> 4 votes
# Knight, ~~416~~ 219 bytes

```
;=mB;=u=s+++++""a" "t" "*a t;=o"";=h 10;WhE++"=x"=h-h 1"N";=w=n 0;Wu;=v+"x"-Au 48;I?32Au=o+o" "E+++++";I"v"N="v"=w+1w=o+o "v=uGu 1Lu o;=a+0P;=b=t+0P;=qCm;=a^10La;=b^10Lb;=z 0;W>a~1;=t b;Wt;=t-t 1;=oCmI?q o=z+1zN=a-a 1Oz

```

Try it online!

-190 bytes thanks to Adam and emanresu A

Ungolfed and explained:

```
; = m BLOCK                          # m = block:
  ; = u = s                          #
    + (+ (+ (+ (+ "" a) " ")         #
    t) " ") (* a t)                  #   u = s = a + " " + t + " " + a * t
  ; = o ""                           #   o = ""
  ; = h 10                           #   h = 10
  ; WHILE h                          #   while h:
      : EVAL + + "=x" = h - h 1 "N"  #     eval("=x" + (h = h - 1) + "N")
  ; = w = n 0                        #   w = n = 0
  ; WHILE u                          #   while u:
      ; = v (+ "x" (- (ASCII u) 48)) #     v = "x" + (ord(u[0]) - 48)
      ; IF ? 32 ASCII u              #     if ord(u[0]) == 32:
          : = o (+ o " "(            #       o = o + " "
                                     #     else: (implicit)
          : EVAL + + + + + ";I" v    #
            "N=" v "=w+1w=o+o " v    #       eval(";I" + v + "N=" + v + "=w+1w=o+o " + v)
      : = u (GET u 1 (LENGTH u))     #     u = u[1:]
  : o                                #   return o
; = a (+ 0 PROMPT)                   # a = int(input())
; = b = t (+ 0 PROMPT)               # b = t = int(input())
; = q (CALL m)                       # q = m()
; = a (^ 10 (LENGTH a))              # a = 10 ** len(a)
; = b (^ 10 (LENGTH b))              # b = 10 ** len(b)
; = z 0                              # z = 0
; WHILE > a ~1                       # while a > -1:
    ; = t b                          #   t = b
    ; WHILE t                        #   while t:
        ; = t - t 1                  #      t = t - 1
        ; = o (CALL m)               #      o = m()
        : IF (? q o)                 #      if q == o:
            : = z + 1 z              #         z = z + 1
            N                        #      else: (do nothing)
    : = a - a 1                      #      a = a - 1
: OUTPUT z                           # print(z)

```

# Answer
> 3 votes
# JavaScript (ES6),  ~~127~~  120 bytes

Expects `(p)(q)`, as strings.

```
p=>q=>eval("for(n=0,x=1+p;x--;)for(y=1+q;y--;)n+=(g=(p,q)=>(a=[...p+=[,q,p*q]]).map(c=>a.map(C=>c==C))+0)(p,q)==g(x,y)")

```

Try it online!

**NB**: This algorithm is rather slow, and made even slower by `eval()`. So the larger test cases time out on TIO.

### Commented

This is a version without `eval()` for readability.

```
p =>                     // p = first integer
q => {                   // q = second integer
  for(                   // outer loop:
    n = 0,               //   start with n = 0
    x = 1 + p;           //   and x = p prefixed with '1'
    x--;                 //   decrement x while it's not 0
  )                      //
    for(                 //   inner loop:
      y = 1 + q;         //     start with y = q prefixed with '1'
      y--;               //     decrement y while it's not 0
    )                    //
      n += (             //     update n:
        g = (p, q) =>    //       g is a helper function taking (p, q)
        ( a =            //       append to p a comma followed by q,
          [...p +=       //       followed by another comma, followed
            [, q, p * q] //       by the product p * q
          ]              //       split the resulting string and save
        )                //       this array in a[]
        .map(c =>        //       for each character c in a[]:
          a.map(C =>     //         for each character C in a[]:
            c == C       //           is c equal to C?
          )              //         end of inner map(); what we get is a
                         //         list of Boolean values telling where
                         //         c can be found in a[]
        )                //       end of outer map()
        + 0              //       coerce to a string with a trailing '0'
      )(p, q)            //       do a 1st call with (p, q)
      == g(x, y);        //       do a 2nd call with (x, y)
                         //     increment n if both results are equal
                         // implicit end of both loops
  return n               // return the final count
}                        //

```

# Answer
> 3 votes
# Jelly,  ~~20 18~~  17 bytes

Thanks to Steffan for a speed up! (`‘×⁵` -\> `æċ⁵`) and a byte that ended up saving elsewhere!
Save of 2 using Steffan's idea of counting \>.\< - thanks again Steffan!

```
;PDKĠṢ
æċ⁵ḶŒpÇ€ċÇ

```

A monadic Link that accepts a pair of non-negative integers and yields a non-negative integer.

**Try it online!**

### How?

```
;PDKĠṢ - Helper Link, cryptic multiplication identifier: pair of integers [a,b]
 P     - product -> a×b
;      - concatenate -> [a, b, a×b]
  D    - to decimal digits -> [[a1, a2, ...],[b1, b2, ...],[P1, P2, ...]]
   K   - join with space characters (representing times and equals)
    Ġ  - group indices by their values -> [indices of spaces, indices of 0s, ...]
     Ṣ - sort

æċ⁵ḶŒpÇ€ċÇ - Link, cryptic multiplication ambiguity: pair of integers [x,y]
  ⁵        - 10
æċ         - next power of (10) of each -> [u, v]  (N.B. 0 -> 10, not 1)
   Ḷ       - lowered range of each -> [[0, 1, ..., u-1], [0, 1, ..., v-1]]
    Œp     - Cartesian product -> [[0, 0], [0, 1], ..., [u-1, v-1]]
      Ç€   - call the helper Link for each
         Ç - call the helper Link with [x, y]
        ċ  - count occurrences

```

# Answer
> 3 votes
# 05AB1E, 20 bytes

```
€g°Ý`âIšεDPª»DSk»}ć¢

```

Port of *@Steffan*'s Vyxal answer, but with less convenient builtins.

Try it online or verify (almost) all test cases (the last two are omitted).

**Explanation:**

```
€         # Map over the (implicit) input-pair:
 g        #  Pop and push its length
  °       # Pop and push 10 to the power these lengths
   Ý      # Pop and map both to a [0,n]-ranged list
    `     # Pop and push both lists separated to the stack
     â    # Pop both, and get all possible pairs using the cartasian product
      Iš  # Prepend the input-pair
ε         # Map over each pair:
 D        #  Duplicate the pair
  P       #  Pop the copy, and push its product
   ª      #  Append it to the pair
    »     #  Join it by newlines
     D    #  Duplicate this string
      S   #  Convert it to a list of characters
       k  #  Get the first index of each character in the string
        » #  Join that by newlines again to a string
}ć        # After the map: extract the head
  ¢       # Count how many times this string occurs in the remainder-list
          # (after which it is output implicitly as result)

```

# Answer
> 1 votes
# Ruby, 108 bytes

```
->a,b{[*0..9].permutation.map{|c|"#{a}*#{b}==#{a*b}".tr('0-9',c*'')}.uniq.count{|c|/^0|\*0|=0/!~c&&eval(c)}}

```

Try it online!

# Answer
> 1 votes
# Charcoal, 36 bytes

```
ＦＸχＬθＦＥＸχＬη⪫⟦ικ×ικ⟧¶⊞υＥκ⌕κλＩ№υ§υＩ⁺θη

```

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

```
ＦＸχＬθ

```

Loop through numbers with no more digits than the first number.

```
ＦＥＸχＬη

```

Looping through numbers with no more digits than the second number, ...

```
⪫⟦ικ×ικ⟧¶

```

... forming a string of the two numbers and their product, ...

```
⊞υＥκ⌕κλ

```

... get a list of the first indexes of each character in the string.

```
Ｉ№υ§υＩ⁺θη

```

Output the number of entries matching that of the input values.

# Answer
> 1 votes
# Python 3, 128 bytes

```
lambda x,y,c=lambda z:list(map(z.find,z)):sum(sum(c(f"{f,g,f*g}")==c(f"{x,y,x*y}")for g in range(1+y<<4))for f in range(1+x<<4))

```

Try it online!

---
Tags: code-golf, arithmetic, integer, combinatorics, expression-building
---


title: A better Hexagony template

text:
# Question
Title: A better Hexagony template
We once made a Hexagony template without actually knowing it. But after a bit of experience with Hexagony, it becomes apparent that it is not enough; sometimes the source code is too short for the given hexagon, and you get totally unexpected results.

So I came up with an idea: a template that gives a hint when the code is too short.

For the background: Hexagony detects the smallest hexagonal grid that fits the source code, and then fills each spot in the grid with each char in row-by-row fashion. E.g. the code

```
abcdefg@

```

contains 8 characters, and the smallest grid that can fit this is of size 3 (size 2 grid has only 7 spots)

```
  . . .
 . . . .
. . . . .
 . . . .
  . . .

```

so the code above is laid out like this:

```
  a b c
 d e f g
@ . . . .
 . . . .
  . . .

```

Now, to ensure that the code being written is actually laid out on the hexagon of size 3, the programmer has to make sure that the code has at least 8 characters; in other words, at least one of the spots marked `*` must be occupied by a command:

```
  . . .
 . . . .
* * * * *
 * * * *
  * * *

```

Math note: the number of spots in the hexagonal grid of size \\$n \ge 1\\$ is \\$a(n)=3n(n-1)+1\\$ (A003215). Since the Hexagony interpreter only has hexagon sizes of 1 and higher, \\$a(0)\\$ is undefined for this challenge.

## Task

Given a positive integer `n`, draw a hexagonal grid like the one above so that

* the first \\$a(n-1)\\$ spots are drawn with one kind of marker (e.g. `.`) and
* the rest are drawn with another (e.g. `*`).

For \\$n=1\\$, it is allowed to output any of the two possible grids (single `.` or single `*`).

For output format:

* You can choose the two markers, but the two must be distinct and not a whitespace character.
* Extra leading and trailing whitespaces, and whitespaces at the end of each line are allowed, as long as it doesn't break the hexagonal layout.
* Outputting as a list of strings (lines) is OK.

Standard rules apply. Shortest code in bytes wins.

## Test cases

```
n=1
*
or
.

n=2
 . *
* * *
 * *

n=3
  . . .
 . . . .
* * * * *
 * * * *
  * * *

n=4
   . . . .
  . . . . .
 . . . . . .
. . . . * * *
 * * * * * *
  * * * * *
   * * * *

n=5
    . . . . .
   . . . . . .
  . . . . . . .
 . . . . . . . .
. . . . . . . . .
 . . * * * * * *
  * * * * * * *
   * * * * * *
    * * * * *

```

# Answer
# C (clang), 92 bytes

Outputs a leading newline.

```
x,y,z;f(n){for(x=n,z=3*n*--n;~z;)printf(!y--?y=n-~n-abs(--x),"\n%*.s":z--<6*n?"* ":". ",x);}

```

Try it online!

Some ideas are drawn from @Quentin's answer to the other hexagon challenge.
> 4 votes

# Answer
# lin, 76 bytes

```
1-.#n.n.>.n.<0\;.'.* <ls"\# \, ?s".n3*.n1- *1+ e*
1+.n +"# ".~ rep \.n5* pad

```

Try it here!

For testing purposes:

```
1 10 .-> ( ; outln n\ out ).'
1-.#n.n.>.n.<0\;.'.* <ls"\# \, ?s".n3*.n1- *1+ e*
1+.n +"# ".~ rep \.n5* pad

```

## Explanation

Prettified code:

```
1-.#n .n.> .n.< 0 \;.'.* <ls .;
  1+ .n + "# ".~ rep \ .n5* pad
( \# \, ?s ) .n3* .n1- * 1+ e*

```
* `1-.#n` input - 1 as \\$n\\$
* `.n.> .n.< 0` create palindromic range \\$\[0, n) \cup \[n, 0\]\\$
* `\;.'` for each \\$x\\$...
    + `1+ .n + "# ".~ rep` repeat `#`  \\$x+n+1\\$ times
    + `\ .n5* pad` pad with spaces to \\$5n\\$
* `.* <ls` join stack with newlines
* `(...) .n3* .n1- * 1+ e*` execute \\$3n(n-1)+1\\$ times...
    + `\# \, ?s` replace first `#` with `,`
> 2 votes

# Answer
# Charcoal, 29 bytes

```
ＮθＦθ«Ｐ^×*θ→→»‖Ｂ↓ＵＭ✂ＫＡ⁰±×⁶⊖θ¹.

```

Try it online! Link is to verbose version of code. Explanation: Based on my golf to @KevinCruijssen's Charcoal answer to the linked question, except at the very end I replace all but the last `6n-6` `*`s with `.`s.
> 2 votes

# Answer
# 05AB1E, ~~21~~ 20 bytes

```
<‚εxŸ¨„1 ×û.c}`Sþ0.;

```

-1 byte thanks to *@Steffan*.

Outputs `1` for `*` and `0` for `.`, with \\$n=1\\$ being `*` (`1`) (thus \\$a(0)=0\\$).

Try it online or verify the first 10 test cases.

**Explanation:**

```
<             # Decrease the (implicit) input-integer by 1
 ‚            # Pair it with the (implicit) input: [input,input-1]
  ε           # Map `y` over this pair:
   x          #  Double the current value (without popping it)
    Ÿ         #  Pop both, and push a list in the range [y,2y]
     ¨        #  Remove the last item to make the range [y,2y)
      „1 ×    #  Repeat string "1 " that many times†
          û   #  Palindromize the list
           .c #  Join the list by newlines, and pad leading spaces to centralize it
  }`          # After the map: Pop and push both the input'th and (input-1)'th hexagons
              # separated to the stack
    S         # Convert the (input-1)'th hexagon from a string to a list of characters
     þ        # Only keep the digits of these characters
       .;     # Replace each first digit occurrence in the input'th hexagon
      0       # to a 0†
              # (after which the result is output implicitly)

```

† Any other digits besides `1`/`0` could be used.
> 2 votes

# Answer
# x86-64 machine code, 51 bytes

```
56 B8 20 C7 07 85 99 59 A8 AE 01 D1 75 02 F7 DA 51 F3 AA 89 F1 66 F3 AB 88 0F 59 29 D6 39 F1 75 E2 88 E0 6B CE 06 E3 0A FD AE 75 FD FE 4F 01 E2 F8 FC C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string in ISO-8859-1, and takes the number \\$n\\$ in ESI.

In assembly:

```
f:  push rsi        #
    .byte 0xB8      # ┐mov eax, 0x8507C720
    .byte 0x20      # │
l0: .byte 0xC7      # │               ┐mov DWORD PTR [rdi], 0xA8599985
    .byte 0x07      # │               │
    .byte 0x85      # ┘               │
    .byte 0x99      # ╴cdq            │
    .byte 0x59      # ╴pop rcx        │
    .byte 0xA8      # ┐test al, 0xAE  ┘
    .byte 0xAE      # ┘               ╴scasb
    add ecx, edx
    jnz s
    neg edx
s:  push rcx
    rep stosb
    mov ecx, esi
    rep stosw
    mov [rdi], cl
    pop rcx
    sub esi, edx
    cmp ecx, esi
    jne l0
    mov al, ah
    imul ecx, esi, 6
    jrcxz e
    std
l1: scasb
    jne l1
    dec BYTE PTR [rdi+1]
    loop l1
    cld
e:  ret

```
* ECX and ESI both start out being equal to \\$n\\$.
* At first, ECX is reduced by 1 at the start of each iteration, for the number of spaces at the start of the line.
* At first, ESI is increased by 1 at the end of each iteration, for the number of spots in the line.
* When ECX hits 0, at the middle line, those changes are reversed: from then on, ECX increases and ESI decreases. The `neg edx` instruction does this.
* EDX is initialised to 1 using the 1-byte `cdq` instruction (sign-extend from EAX). This requires the high bit of EAX to be 1; because of the way the overlapping instructions worked out, this necessitated using 0x85 (NEL) as a newline instead of 0x0A (LF). (Because TIO's output mechanism does not handle NEL, the additional code in the TIO demonstration converts NEL to LF.)
* The null terminator is added using `mov [rdi], cl` in the middle of the loop, taking advantage of ECX being 0 after `rep stosw` counts it down. This actually adds a null byte at the end of every line, but it is overwritten by the NEL except at the end.
* The final part of the code runs backwards through the string and modifies the last \\$6(n-1)\\$ spots.
> 0 votes

# Answer
# Knight, ~~110~~ 105 bytes

```
;=n+~1P;=c~1;=i+1*2nW+1=i-iT;O+*' '=xI>=x-n iFx~x'\';=j~2;W<=j+1j-*2n xI<c-**3n n*3n;=c+1cO'. \'O'* \'O''

```

100% can be golfed but I'm too lazy to do that lol.

Try It Online!

Test Suite up to n=10
> 0 votes

# Answer
# Vyxal, 21 bytes

```
‹"ƛdr‛a *∞øĊ⁋;÷Ǎ(n0øḞ

```

Try it Online!

Port of Kevin Cruijssen's 05AB1E answer.
> 0 votes

---
Tags: code-golf, ascii-art, hexagonal-grid
---