title: Roman numeral converter function

text:
# Question
Title: Roman numeral converter function
Create the shortest function to convert a string of Roman numerals to an integer.

The rules for each letter can be found at the Wikipedia page. Letters above 1,000 will have parentheses placed around them to signal their higher value.

**Requirements:**

* Must convert Roman numerals 1 to 500,000
* Must complete in less than a minute
* Does not use built-in functions that could provide an advantage (Ex: A function that converts Roman numerals to integers)
* Is a function

The function does not need to support fractions. Any invalid input should return the number 0.

Shortest function wins. In the case of a tie, the one with the most votes wins.

## Test Cases

Input

```
III

```

Output

```
3

```

---

Input
```
IIII

```

Output

```
0

```

---

Input
```
XVI

```

Output

```
16

```

---

Input
```
(C)(D)(L)MMI

```

Output

```
452001

```

# Answer
### C++: 914 855 chars

```
#include<map>
#include<string>
#include<iostream>
#include<sstream>
#define I istream
#define T(C) if(C)throw int(1);
#define X(c,v,f,m) D[c]=v;P[c]=D[f];M[c]=m;
#define S second
using namespace std;typedef map<char,int>R;R D,P,M;struct U{U():t(0),l(0),a(0){}int t,l,a;operator int(){return t+l;}I&d(I&s){char c,b;s>>c;if(c=='('){s>>c>>b;T(b!=')')c+=32;}if(s){R::iterator f=D.find(c);T(f==D.end())if(P[c]==l){l=f->S-l;a=0;}else{T(l&&(f->S>l))a=l==f->S?a+1:1;T(a>M[c])t+=l;l=f->S;}}return s;}};I&operator>>(I&s,U&d){return d.d(s);}int main(){D[' ']=-1;X(73,1,32,3)X(86,5,73,1)X(88,10,73,3)X(76,50,88,1)X(67,100,88,3)X(68,500,67,1)X(77,1000,67,3)X(118,5000,77,1)X(120,10000,77,3)X(108,50000,120,1)X(99,100000,120,3)X(100,500000,99,1)X(109,1000000,99,3)string w;while(cin>>w){try{stringstream s(w);U c;while(s>>c);cout<<c<<"\n";}catch(int x){cout<<"0\n";}}}

```

It could be compressed further.

```
> ./a.exe
III
3
IIII
0
XVI
16
(C)(D)(L)MMI
452001

```

Slightly nicer formatting: 1582 char

```
#include<map>
#include<string>
#include<iostream>
#include<sstream>
#define I istream
#define T(C) if(C)throw int(1);
#define X(c,v,f,m) D[c]=v;P[c]=D[f];M[c]=m;
#define S second
using namespace std;

typedef map<char,int>      R;

R     D,P,M;

struct U
{
    U(): t(0), l(0), a(0) {}

    int  t,l,a;

    operator int()
    {
        return t + l;
    }
    I& d(I& s)
    {
        char c,b;
        s >> c;
        if (c == '(')
        {
            s >> c >> b;
            T(b != ')')
            c = tolower(c);
        }
        if (s)
        {
            R::iterator f = D.find(c);
            T(f == D.end())

            if (P[c] == l)
            {
                l = f->S - l;
                a = 0;
            }
            else
            {
                T(l&&(f->S > l))
                a=l==f->S?a+1:1;
                T(a>M[c])
                t   += l;
                l     = f->S;
            }
        }

        return s;
    }

};

I& operator>>(I& s,U& d)
{
    return d.d(s);
}

int main()
{
    D[' ']=-1;
    X(73,1,32,3)
    X(86,5,73,1)
    X(88,10,73,3)
    X(76,50,88,1)
    X(67,100,88,3)
    X(68,500,67,1)
    X(77,1000,67,3)
    X(118,5000,77,1)
    X(120,10000,77,3)
    X(108,50000,120,1)
    X(99,100000,120,3)
    X(100,500000,99,1)
    X(109,1000000,99,3)

    string w;
    while(cin >> w)
    {
        try
        {
            stringstream s(w);
            U    c;
            while(s >> c);
            cout << c << "\n";
        }
        catch(int x)
        {
            cout << "0\n";
        }
    }
}

```
> 6 votes

# Answer
# Javascript, 317 chars

```
function f(s){for(r=/\(?(.\)?)/g,t=e=0;a=r.exec(s);l=a[0].length,d='IXCMVLD'.indexOf(a[1][0]),e=e||d<0||l==2||d*4+l==3,t+='+'+(d>3?5:1)*Math.pow(10,d%4+3*(l>1)));t=t&&t.replace(/1(0*).(10|5)\1(?!0)/g,'$2$1-1$1');return e||/[^0](0*)\+(10|5)\1/.test(t)||/(\+10*)\1{3}(?!-)/.test(t)||/-(10*)\+\1(?!-)/.test(t)?0:eval(t)}

```

Explaination:

```
function f(s){
      // iterate over every character grabbing parens along the way
  for(r=/\(?(.\)?)/g,t=e=0;a=r.exec(s);
        // get a numerical value for each numeral and join together in a string
    l=a[0].length,
    d='IXCMVLD'.indexOf(a[1][0]),
    e=e||d<0||l==2||d*4+l==3,    // find invalid characters, and parens
    t+='+'+(d>3?5:1)*Math.pow(10,d%4+3*(l>1))
  );
      // reorder and subtract to fix IV, IX and the like
  t=t&&t.replace(/1(0*).(10|5)\1(?!0)/g,'$2$1-1$1');
  return e||
    /[^0](0*)\+(10|5)\1/.test(t)|| // find VV,IIV,IC,...
    /(\+10*)\1{3}(?!-)/.test(t)||  // find IIII,... but not XXXIX
    /-(10*)\+\1(?!-)/.test(t)      // find IVI,... but not XCIX
      ?0:eval(t)
}

```

Without error detection it is only **180 chars**

```
function g(s){for(r=/\(?(.\)?)/g,t=0;a=r.exec(s);d='IXCMVLD'.indexOf(a[1][0]),t+='+'+(d>3?5:1)+'0'.repeat(d%4+3*(a[1].length>1)));return eval(t.replace(/(1(0*).(10|5)\2)/g,'-$1'))}

```

This works the same way, but here is better formatting:

```
function g(s){
  for(r=/\(?(.\)?)/g,t=0;a=r.exec(s);
    d='IXCMVLD'.indexOf(a[1][0]),
    t+='+'+(d>3?5:1)+'0'.repeat(d%4+3*(a[1].length>1))
  );
  return eval(t.replace(/(1(0*).(10|5)\2)/g,'-$1'))
}

```
> 4 votes

# Answer
# , 43 bytes

```
1#.2([*_1^<)/\0,~(*/\1,6$5 2){~'IVXLCDM'&i.

```

Try it online!
> 1 votes

# Answer
# Python3 - 144 chars

Follows this question's rules, but its closed, so doesn't check for invalid input or support brackets, but thought I'd answer anyway.

```
def r(s):
    if not s:return 0
    l,v=[(s.split(x,1),6-i) for i,x in enumerate('MDCLXVI') if x in s][0]
    return 10**(v//2)*(v%2*4+1)-r(l[0])+r(l[1])

```

Explanation:

This algorithm recursively finds the next largest letter, splits the string around it, then subtracts the left side's value and adds the right side's value.

Ungolfed:

```
def roman(string):
    # base case. ends the recursion when either side string is empty.
    if not string:
        return 0

    split_list, value =
        [
            # splits the string with the leftmost letter of 'MDCLXVI' successively.
            # we take the first split string in the list (ignoring ones that didn't split)
            #  and use [0] and [1] as the left and right hand side parts to recurse.

            # stores the split string ('1' means first split only), and the index of the
            #  letter used to split it in a tuple.
            ( string.split(letter, 1), 6-index )

            # loops through each letter used in roman numerals.
            for index, letter in enumerate('MDCLXVI')

            # only stores split strings which actually split
            if letter in string

        # get the first split string tuple (so it was split with the highest value letter).
        ][0]

    # takes the index of roman numeral letter and turns into its value (0->1, 1->5, 2->10).
    return 10**(value//2)*(value%2*4+1)
        # subtracts the value of the left hand side.
        - roman(split_list[0])
        # adds the value of the right hand side.
        + roman(split_list[1])

```
> 0 votes

---
Tags: code-golf, math, restricted-time, roman-numerals
---


# Question
Title: Smallest number of contiguous monotonic subsequences
A **monotonic subsequence** is a sequence of numbers \\$a\_1, a\_2, ..., a\_n\\$ such that

$$a\_1 \le a\_2 \le ... \le a\_n \\ \text{or} \\ a\_1 \ge a\_2 \ge ... \ge a\_n$$

`[1, 3, 3, 7, 9, 13, 13, 100]` is a monotonic (non-decreasing) subsequence, as well as `[9, 4, 4, 3, 0, -10, -12]` (this one is non-increasing), but `[1, 3, 6, 9, 8]` is not. Given a list of integers (in any reasonable format), output the smallest number `N` such that the sequence of these integers can be split into `N` monotonic sequences.

# Examples

```
[1, 3, 7, 5, 4, 2] -> [[1, 3, 7], [5, 4, 2]] -> 2
[1, 2, 3, 4, 5, 6] -> [1, 2, 3, 4, 5, 6]     -> 1
[3, 1, 5, 5, 6]    -> [[3, 1], [5, 5, 6]]    -> 2
[4, 6, 8, 9, 1, 6] -> [[4, 6, 8, 9], [1, 6]] -> 2
[3, 3, 3, 3]       -> [[3, 3, 3, 3]]         -> 1
[7]                -> [[7]]                  -> 1
[]                 -> []                     -> anything (you don't actually have to handle an empty list case)
[1, 3, 2, -1, 6, 9, 10, 2, 1, -12] -> [[1, 3], [2, -1], [6, 9, 10], [2, 1, -12]] -> 4

```

# Answer
# Brachylog, 12 bytes

```
~c:{<=|>=}al

```

Try it online!

This returns `false.` for the empty list `[]`.

### Explanation

```
(?)~c                 Take a list of sublists which when concatenated result in the Input
     :{<=|>=}a        Each sublist must be either increasing or decreasing
              l(.)    Output is the length of that list

```

This will return the smallest one because `~c` will generate choice points from the smallest number of sublists to the biggest.
> 6 votes

# Answer
## Perl, 65 bytes

62 bytes of code + 3 bytes for `-n` flag.

monot\_seq.pl :

```
#!perl -n
s/\S+ /($_<=>$&)*($&<=>$')-$g>=0?$g=1:$.++;$g--;$_=$&/ge,$_=$.

```

Give the input without final newline, with the numbers separated by spaces :

```
$ echo -n "1 3 2 -1 6 9 10 2 1 -12" | perl -M5.010 monot_seq.pl
4

```

*-5 bytes thanks to @Gabriel Benamy.*
> 4 votes

# Answer
# Perl, ~~98~~ ~~97~~ ~~96~~ 79 bytes

```
($a,$b)=($a<=>$b)*($b<=>$c)<0?($c,shift,$d++):($b,$c)while$c=shift;say$d+1 if$a

```

Input is provided as a list of numbers, separated by spaces, provided at runtime, e.g.

```
perl -M5.010 monotonic.pl 1 3 2 -1 6 9 10 2 1 -12
4

```

(the 4 is the output)

Readable:

```
($a,$b)=($a<=>$b)*($b<=>$c)<0
    ?($c,shift,$d++)
    :($b,$c)
  while$c=shift;
say$d+1
  if$a

```

The 'spaceship operator' `<=>` returns -1 if LHS \< RHS, 0 if LHS = RHS, and +1 if LHS \> RHS. When comparing three sequential elements `$a,$b,$c` to determine if they're monotonic, it's only necessary to determine that it's not the case that exactly one of `$a<=>$b`,`$b<=>$c` is 1 and the other is -1 -- which only happens when their product is -1. If either `$a==$b` or `$b==$c`, then the sequence is monotonic, and the product is 0. If `$a < $b < $c`, then both result in -1, and -1 * -1 = 1. If `$a > $b > $c`, then they both result in 1, and 1 * 1 = 1. In either case, the sequence is monotonic, and we wish to continue.

If the product is less than 0, we know that the sequence is not monotonic, and we discard the values of `$a,$b` we're currently holding, and increment our subsequence counter. Otherwise, we move forward one number.

Returns nothing if the input is empty, otherwise returns the smallest number of contiguous monotonic subsequences
> 2 votes

# Answer
# Mathematica, 111 bytes

```
d=#[[2]]-#[[1]]&;r=Rest;f@{n_}:=1;f@k__:=If[d@k==0,f@r@k,g[k Sign@d@k]];g@{n_}:=1;g@k__:=If[d@k>0,g@r@k,1+f@r@k]

```

Named function `f` taking a nonempty list of numbers (integers or even reals). Works from front to back, discarding the first element repeatedly and keeping track of how many subsequences are needed. More verbose:

```
d = #[[2]] - #[[1]] &;         function: difference of the first two elements
r = Rest;                      function: a list with its first element dropped
f@{n_} := 1;                   f of a length-1 list equals 1
f@k__ := If[d@k == 0, f@r@k,   if the first two elements are equal, drop one
                                 element and call f again ...
            g[k Sign@d@k]];  ... otherwise call the helper function g on the
                                 list, multiplying by -1 if necessary to ensure
                                 that the list starts with an increase
g@{n_} := 1;                   g of a length-1 list equals 1
g@k__ := If[d@k > 0, g@r@k,    if the list starts with an increase, drop one
                                 element and call g again ...
            1 + f@r@k];        ... otherwise drop one element, call f on the
                                 resulting list, and add 1

```
> 2 votes

# Answer
# Jelly, 19 bytes

```
IṠḟ0E
ŒṖÇ€€0e$Ðḟḅ1Ṃ

```

**TryItOnline!** or run all tests (empty list results in `1`)

### How?

```
IṠḟ0E - Link 1, test for monotonicity: a sublist
I     - incremental differences
 Ṡ    - sign {fall:-1; same:0; rise:1}
  ḟ0  - filter out the zeros
    E - all equal?

ŒṖÇ€€0e$Ðḟḅ1Ṃ - Main link
ŒṖ            - all partitions of the input list
  Ç€€         - call last link (1) as a monad for €ach for €ach
        Ðḟ    - filter out results:
       $      -    last two links as a monad
     0e       -        contains zero?
          ḅ1  - convert from unary (vectorises)
            Ṃ - minimum

```

(I'm not convinced that this is the most suitable method to minimise byte count though)
> 2 votes

# Answer
## C#6, ~~297~~ 209 bytes

```
using System.Linq;int G(int[] a)=>a.Any()?a.SkipWhile((x,i)=>i<1||x>=a[i-1]).Count()<a.SkipWhile((x,i)=>i<1||x<=a[i-1]).Count()?G(a.Select(x=>-x).ToArray()):G(a.SkipWhile((x,i)=>i<1||x<=a[i-1]).ToArray())+1:0;

```

Ungolfed with explanations

```
int G(int[] a)=>
    a.Any()
        ?a.SkipWhile((x,i)=>i<1||x>=a[i-1]).Count()<a.SkipWhile((x,i)=>i<1||x<=a[i-1]).Count()   // If a begins by decreasing (including whole a decreasing)...
            ?G(a.Select(x=>-x).ToArray())   // ... Then flip sign to make a begins by increasing
            :G(a.SkipWhile((x,i)=>i<1||x<=a[i-1]).ToArray())+1   // ... Else skip the increasing part, recursively find the remaining part number, then add 1
        :0;   // Return 0 if a is empty

```
> 1 votes

# Answer
## JavaScript (ES6), 69 bytes

```
f=(d,c,b,...a)=>1/b?(d>c)*(b>c)+(d<c)*(b<c)?1+f(b,...a):f(d,b,...a):1

```

Takes input as multiple parameters. Works by recursively comparing the first three elements to see whether they are monotonic, if so, removes the middle element as it is useless, if not, removes the first two elements and starts a new sequence.
> 1 votes

# Answer
## Clojure, 97 bytes

```
#((reduce(fn[[C i]s](let[S(conj C s)](if(or(apply <= S)(apply >= S))[S i][[s](inc i)])))[[]1]%)1)

```

`reduce` keeps track of the current subsequence and calculates how many times `<=` and `>=` conditions fail. Last `1` takes 2nd element from the result (being the counter `i`).
> 0 votes

# Answer
# Jelly, 11 bytes

```
ŒṖỤ€IṠƑƊƇẈṂ

```

Try it online!

Empty list yields `1`

## How it works

```
ŒṖỤ€IṠƑƊƇẈṂ - Main link. Takes an array A on the left
ŒṖ          - Yield all partitions of A
       ƊƇ   - Keep those partitions for which the following is true:
   €        -   Over each sublist in the partition:
  Ụ         -     Grade up; Sort its indices by its values
    I       -   Increments
      Ƒ     -   Is this invariant under:
     Ṡ      -     Convert to sign

                This (ṠƑ) is a trick that returns 1 if the list contains only
                -1, 1 and 0s. As we're working with the indices, not the values,
                we will never have duplicate elements, and so no 0. The increments
                will either be all 1 or -1 iff the ordered indices are in directly
                ascending or descending order, i.e. the values are sorted in
                either ascending or descending order

         Ẉ  - Get the lengths of each kept partition
          Ṃ - Get the minimum

```
> 0 votes

---
Tags: code-golf, number, sequence, subsequence, set-partitions
---


title: Test if a Gray code is Beckett

text:
# Question
Title: Test if a Gray code is Beckett
## Background

An \\$n\\$-bit Gray code is an ordering of \\$2^n\\$ binary sequences so that adjacent sequences always differ by exactly one bit.

A **Beckett-Gray code** is a special kind of Gray code. In addition to being a Gray code, it has the following characteristics:

* It is cyclic: the last bit pattern has one bit difference with the first pattern. (*Your input is guaranteed to be cyclic*)
* The first pattern is all zeros. (*Your input is guaranteed to start with 0*)
* Whenever a bit turns from 1 to 0, that bit is the one which has been 1 for the longest time (consecutively). (*You need to verify this*)

It is known that a Beckett-Gray code exists for \\$n=2, 5, 6, 7, 8\\$, but does not exist for \\$n=3\\$ and \\$4\\$. It is not known if any such code exists for \\$n \ge 9\\$, and no constructive methods to build such a code are known.

One example for \\$n=5\\$ is as follows (copied from this paper, 1-0 transition marked):

```
00000, 00001, 00011, 00010, 00110, 00111, 00101, 01101,
                         ^                   ^
01001, 01000, 01010, 01011, 11011, 10011, 10111, 10101,
  ^        ^                        ^               ^
10100, 00100, 01100, 11100, 11000, 11010, 10010, 10110,
    ^  ^                      ^            ^
11110, 01110, 01111, 11111, 11101, 11001, 10001, 10000
       ^                       ^     ^     ^         ^

```

## Task

Given a cyclic Gray code starting with an all-zero pattern, determine if it is a Beckett-Gray code.

You may take input as a sequence of boolean arrays (possibly transposed), a sequence of strings, or a sequence of equivalent integers. Also, you may optionally take the value of \\$n\\$ as the second input.

For output, you can choose to

1. output truthy/falsy using your language's convention (swapping is allowed), or
2. use two distinct values to represent true (affirmative) or false (negative) respectively.

Standard rules apply. Shortest code in bytes wins.

## Test cases

Each test case is separated with an empty line.

### Truthy (Beckett)

```
0, 1

00, 01, 11, 10

00, 10, 11, 01

00000, 00001, 00011, 00010, 00110, 00111, 00101, 01101,
01001, 01000, 01010, 01011, 11011, 10011, 10111, 10101,
10100, 00100, 01100, 11100, 11000, 11010, 10010, 10110,
11110, 01110, 01111, 11111, 11101, 11001, 10001, 10000

00000, 01000, 01001, 00001, 00011, 01011, 01010, 11010,
11000, 10000, 10001, 11001, 11101, 01101, 01111, 01110,
00110, 00010, 10010, 10110, 10100, 10101, 00101, 00111,
10111, 10011, 11011, 11111, 11110, 11100, 01100, 00100

```

### Falsy (Not Beckett)

```
000, 001, 011, 010, 110, 111, 101, 100

0000, 1000, 1100, 1110, 1111, 1101, 0101, 0001,
1001, 1011, 1010, 0010, 0011, 0111, 0110, 0100

00000, 00001, 00011, 00010, 00110, 00111, 00101, 00100,
01100, 01101, 01111, 01110, 01010, 01011, 01001, 01000,
11000, 11001, 11011, 11010, 11110, 11111, 11101, 11100,
10100, 10101, 10111, 10110, 10010, 10011, 10001, 10000

```

# Answer
# Husk, 9 bytes

```
Λ≡½hÖ▼Ẋz-

```

Try it online! (Version with formatting header to allow pasting testcases: Try it online!)

### Explanation

If we compute differences from each binary sequence to the next with an element-by-element subtraction, we will get a series of results each containing a single -1/+1 on the flipped bit and a 0 on all other bits. In order for this Gray code to be Beckett, the subsequence of -1 lists must be identical to the subsequence of +1 lists (except for the sign).

As noted by Unrelated String we don't need to check the last element against the first, since it will always consist of a single 1 turning into a 0.

```
 Λ≡½hÖ▼Ẋz-    Input: list of binary sequences
       Ẋ      For each pair of adjacent sequences:
        z-       subtract the first from the second element by element
     Ö▼       Sort by the minimum (in place): all the -1 sequences move to the beginning
    h         Discard the last (would match the final sequence turning into the first)
   ½          Group the sequences into two lists of equal length
                (the first will contain the -1s, the second the +1s)
 Λ            Check that the two elements
  ≡           Have the same distribution of zeros/nonzeros

```
> 13 votes

# Answer
# APL (Dyalog Classic), 35 bytes

```
{(∊⍸¨↓b)≡(∨/b←2>⌿⍵)/¯1↓⊣/⍒⍤1⊥⍨¨,⍀⍵}

```

-27 from Bubbler, -13 for pointing out the input is a Gray code, -3 for removing an excess variable, and another -11 for just being an all round golfing god.

```
{(∊⍸¨↓b)≡(∨/b←2>⌿⍵)/¯1↓⊣/⍒⍤1⊥⍨¨,⍀⍵}
                            ⊥⍨¨,⍀⍵ ⍝ cumulative sums (time a 1 has been there)
                    ¯1↓⊣/⍋⍤1       ⍝ index of maxima (without last element)
         (∨⌿b←2>/⍵)/               ⍝ filter where 1s change to 0s
 (∊⍸¨↓b)≡                          ⍝ does that equal the locations of 1s?

```

Try it online!
> 4 votes

# Answer
# , 32 25 bytes

```
[:-:/[:(|/.~/:~"1)2-/\,&0

```

Try it online!

Based on Leo's excellent idea

* `2-/\,&0` Adjacent elementwise row deltas, with an extra row of zeros appended first.
* `(|/.~/:~"1)` Group by sorted rows and take absolute value. This puts all rows with a single 1 into one bucket, and all rows with a single -1 into another.
* `[:-:/` Are those buckets equal?
> 4 votes

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

```
a=>a.every(n=>(n-=a[++i]|0)>0?m<(m=a[-n]):a[n]=i,i=m=0)

```

Try it online!

Input an array of equivalent integers, output true / false.

```
a=>a.every(n=>
  (
    n-=a[++i]|0 // compare current one with next one
                // if current one is the last one, we compare with 0
  )>0?
    // > 0 means some digit changed 1->0
    m<(m=a[-n]) // We use a[-n] to remember when 0->1 happened
                // We use m to remember where the related 0->1
                //    happened for last 1->0 change
                // If we find out related 1->0 changing earlier
                //    than m, it is not Beckett
                //    and we return false
                // Remember the where the related 0->1 mutation for current
                //    1->0 happened by assigning m
    // < 0 means some digit changed 0->1
    a[n]=i // Remember where 0->1 mutation happened for digit -n
           // This is always truthy too
 ,i=m=0)

```
> 4 votes

# Answer
# Python 2, 62 bytes

Output is via exit code: `0` if it is a Beckett-Gray Codex and `1` otherwise.

```
a=p,=[1]
for x in input():0<p-x!=a.pop(0)<_;a+=[x-p]*(x>p);p=x

```

Try it online!
> 4 votes

# Answer
# Python 3, ~~138~~ \\$\cdots\\$ ~~102~~ 95 bytes

Saved 13 bytes thanks to rak1507!!!
Saved 7 bytes thanks to dingledooper!!!

```
def f(b):
 r,*u=1,
 for x,y in zip(b,b[1:]):
  if x<y:u+=x^y,
  else:r&=u.pop(0)==x^y
 return r

```

Try it online!

Inputs a Gray-cyclic code starting with \\$0\\$ as list of integers and returns `1` is it's a Beckett-Gray code or `0` otherwise.
> 3 votes

# Answer
# Jelly, 10 bytes

```
_ƝµṂƇNṖ⁼ṬƇ

```

Try it online!

Semi-translation of Leo's excellent Husk answer.

```
_Ɲ            Take the vectorized differences between adjacent elements.
              (The deltas builtin, I, vectorizes itself instead.)
   ṂƇ         Filter by minimum, keeping elements containing -1.
     N        Negate.
      Ṗ       Remove the last element.
       ⁼      Is this list equal to
  µ           the differences
        ṬƇ    filtered to only elements containing 1?

```

was originally  (maximum), but this produced a false negative on the first test case, as the largest element of `[-1]` is -1 rather than 0.  produces an array with ones at the provided indices and zeros elsewhere, but ignores non-positive indices, producing an empty array (which is falsy) if there are no positive indices.

# Jelly, ~~15~~ 13 bytes

```
ṛa+ɗ\>TẇM{ʋƝP

```

Try it online!

*-2 removing `ṙ1` because the all-zeros pattern can essentially be ignored--if you flip the last bit off, you already know it's the one that's been on the longest*

Takes input as an array of Boolean arrays, and outputs 0 or 1.

```
   ɗ\            Cumulatively reduce the input by:
ṛ                right argument
 a               vectorizing-logical-AND
  +              the vectorized sum of the arguments.
ṛa+ɗ\            This turns each 1 into how "long" it's been a 1, consecutively.
          ʋƝ     For each pair of adjacent elements from that result:
      T          are the indices at which
     >           the right is less than the left
       ẇ         a sublist of
        M{       the maximal indices of the left?
            P    Take the product of the results.

```
> 3 votes

# Answer
# JavaScript (V8), 106 bytes

```
a=>!a.some((c,i)=>c.map((x,j)=>n+=x<(y=(a[i+1]||a[0])[j])?!!o.push(j):x>y?1<<o.shift()-j:0,n=0)&&n-1,o=[])

```

Try it online!

Accepts input as a 2-dimensional array of booleans.
> 2 votes

# Answer
# Charcoal, 34 bytes

```
¹≔⁰ζＦＩ⮌Ａ«¿›ζιＦ¬⁼⁻ζι⊟υ⎚≔⁺⟦⁻ιζ⟧υυ≔ιζ

```

Try it online! Link is to verbose version of code. Takes input as strings and outputs a Charcoal boolean, i.e. `-` for a Beckett-Gray code, nothing if not. Explanation:

```
¹

```

Start by assuming that the input is a Beckett-Gray code.

```
≔⁰ζ

```

Initialise the previous value to 0.

```
ＦＩ⮌Ａ«

```

Convert the input to decimal (leading zeros aren't allowed as numeric input, but the cast operator is fine with them) and loop through it in reverse order. (I hope this works, as it saves a byte over skipping the leading string of all zeros.)

```
¿›ζι

```

If the previous value is greater than this value, ...

```
Ｆ¬⁼⁻ζι⊟υ⎚

```

... then if the oldest saved value is not the same as a difference then clear the canvas, as this is not a Beckett-Gray code.

```
≔⁺⟦⁻ιζ⟧υυ

```

Otherwise prepend the difference to the queue.

```
≔ιζ

```

Save the current value.
> 1 votes

# Answer
# C (gcc), 95 bytes

```
t;r;b;e;f(a,n)int*a;{int l[n];for(b=e=r=1;--n;)t=*a^a[1],r&=*a++<*a?l[e++]=t,1:l[b++]==t;r=r;};

```

Try it online!

Port of my Python answer.

Inputs an array of integers and its length (since length of arrays passed into functions as pointers are undefined in C) and returns `1` is it's a Beckett-Gray code or `0` otherwise.
> 1 votes

# Answer
# , ~~73~~ 64 bytes

```
function(m,d=diff(rbind(m,0)),`-`=rowSums)any(d[-d>0,]+d[-d<0,])

```

Try it online!

Based on the idea in Leo's Husk answer.

Takes input as a matrix `m` of 1s and 0s with each pattern corresponding to a row. Outputs a swapped T/F value (in the footer, the results are swapped back).
> 0 votes

---
Tags: code-golf, decision-problem, binary, coding-theory
---


title: Roman Numeral-like Code Generator

text:
# Question
Title: Roman Numeral-like Code Generator
## Background

Roman numeral is a simple number system with the following properties:

* Each symbol in the system maps to a specific value. (e.g. `I = 1, V = 5, X = 10, C = 100`)
* The value of a Roman numeral can be evaluated as follows:
    + First, find all occurrences of adjacent pairs of symbols where a strictly smaller-valued symbol comes first (e.g. `IV`, `XC`). Each such pair is evaluated as the backward difference of two values (e.g. `IV = 5 - 1 = 4`).
    + Then, interpret the remaining symbols as-is and sum all values in it.
    ```
    MMCMXCIV = M + M + CM + XC + IV
             = 1000 + 1000 + (1000 - 100) + (100 - 10) + (5 - 1)
             = 2994

    ```

## Task

Your job is to write a function/program \\$F\\$ that takes a positive integer \\$n\\$ and generates a code fragment \\$F(n)\\$ (not necessarily in the same language). The outputted code fragments must have the following properties:

* \\$F(n)\\$ as a full program must output the number \\$n\\$.
* \\$F(a)+\\!\\!\\!+\\,F(b)\\$ as a program (where \\$+\\!\\!+\\$ means concatenation) must output \\$a+b\\$ if \\$a≥b\\$, \\$b−a\\$ otherwise.
* This must extend to any number of code fragments emitted by your program in the way that \\$b−a\\$ cases take precedence (think of an arithmetic expression with `+`s and `-`s, but the two sides of `-`s are flipped and it has higher precedence than `+`).
    + You do not need to consider the cases where three consecutive input numbers are strictly increasing (the equivalent arithmetic expression has two consecutive `-`s).

Your score is the byte count of \\$F\\$. Shortest code in bytes wins.

## Example

If \\$F(10)\\$ outputs the code fragment `ABC`, and \\$F(3)\\$ outputs the code fragment `xyz`:

* The program `ABC` should output 10.
* The program `xyz` should output 3.
* The program `ABCxyz` should output 13.
* The program `xyzABC` should output 7.
* The program `ABCABCABC` should output 30.
* The program `ABCABCxyzxyzABCxyzxyzABC` should output 40, since
```
[10, 10, 3, 3, 10, 3, 3, 10] => 10 + 10 + 3 + (10-3) + 3 + (10-3) = 40

```

Additionally, if \\$F(8)\\$ outputs the code fragment `****`:

* The program `ABC****xyz` should output `10 + 8 + 3 = 21`.
* The program `****ABCxyz` should output `(10-8) + 3 = 5`.
* The program `xyz********ABC` should output `(8-3) + (10-8) = 7`.
* You do not need to consider the program `xyz****ABC`, which contains three consecutive strictly increasing numbers (3, 8, 10).

# Answer
> 15 votes
# Bash, ~~54~~ 48 bytes

*-6 bytes by adapting Dominic van Essen's output-prevention trick*

```
printf ":|:
((s+=p<$1?$1-2*p:$1))
p=$1
echo \$s"

```

This assumes the program must not have any excess output, which turns out to be one of the tricker parts. I expect one of the golfing languages that will output by default at the end of the program would do best here.

Try it online!

## Explanation

Example output for `3` concatenated with output for `10` (the concatenated program outputs `7`):

```
:|:
((s+=p<3?3-2*p:3))
p=3
echo $s:|:
((s+=p<10?10-2*p:10))
p=10
echo $s

```
* `:|:` prevents any `echo` from a previous fragment from outputting
* `s` is the sum value so far (implicitly 0 at the start of the program)
* `p` is the previous value

Each fragment assumes that the current value is not less than the next value, and thus adds it to the sum. It also checks whether the previous fragment was wrong to assume this (ie. the previous value was less than the current value), and if so corrects the sum by subtracting double the previous value.

# Answer
> 6 votes
# , ~~65~~ 57 bytes

```
cat("d=e=F;F=c(",scan(),",F);a=sum(F*(-1)^(F<c(e,0)));a")

```

Try it online!

**How it works (original version)**

For an example input of 3, the output is:

```
d=0;F=c(F, 3 );a=sum(F*(-1)^(F<c(F[-1],0)));a

```

(note: no trailing newline)

What do the different bits do?

* `d=0` = appends to the last code fragment (if any). This has the effect of changing the final `a` (output the contents of `a`) to `ad=0` (assign zero to variable `ad`), and thereby supresses output from all non-final code fragments.
* `F=c(F, 3 )` = append the input value to the list `F`. `F` is a shortcut in  for `FALSE`, so it's initialized to zero. So, after all the code fragments are pasted together, `F` will contain all the input integers, followed by zero.
* `a=sum(F*(-1)^(F<c(F[-1],0)))` = calculate the sum of all the input integers, switching the sign of any that are immediately followed by a larger value. Luckily the last value is zero, so this won't happen to the final input integer. Assign the answer to variable `a`.
* `a` = Finally, output the answer `a` (but if there's a following code fragment, this'll get changed to `ad=0` and nothing output yet... see the start)

# Answer
> 6 votes
# APL (Dyalog Unicode), ~~26~~ 24 bytes

Full program. Prompts for number from stdin, and prints program to stdout.

```
'{⍺←+/⊢×¯1*2</,∘0⋄⍺,⍵}'⍞

```

Try it online! (slightly modified version for ease of use)

The generating program simply prepends a special string to the left of the input number (or numbers, actually).

The special string is an anonymous ambivalent (infix/prefix) lambda.

Compound programs will consist of numbers separated by this lambda, with an additional lambda on the far left.

With infix usage, the lambda amounts to simple concatenation.

With prefix usage, the lambda evaluates Roman numbers.

APL evaluates from right to left, so a compound statement will simply concatenate number values until finally the list is evaluated as a Roman number.

The lambda is as follows:

`{``}` dfn; arguments are  (left, optional) and  (right):

`⍺←` if the left argument is undefined (i.e. we are being called monadically, as a prefix lambda), give the following tacit function value to it:

`+/` the sum of…

the argument array…

`×` times (element-wise)…

`¯1*` negative one raised to the power of (element-wise)…

`2</` the pair-wise less-than of…

`,∘0` the argument prepended to a zero

now, with the supplied or the default  evaluate:

`⍺,⍵` with a supplied left argument the concatenation of the arguments

`⍺,⍵` with the default argument the tacit function applied to the ravel (flattened ― a no-op) right argument

# Answer
> 4 votes
# Perl 5 (`-lp`), ~~39~~ 35 bytes

-4 bytes thanks to Dom Hastings

```
$_='}{$\-=2*$p*($p<'."$_)-(\$p=$_)"

```
* `-lp` switch (enable line ending processing;assume loop like -n but print line also, like sed)
* generated code starts with `}{` : which closes the loop block and start a new block which is executed after the loop
* `-=`, `$p=..` rewriting so that affectation is executed after operation and comparison

Try it online!

# Answer
> 4 votes
# JavaScript (V8), 66 bytes

```
n=>`t=this;s=~~t.s-(t.p<${n}&&2*p)+(p=${n}),{get x(){print(s)}}.x`

```

Try it online!

The core idea is putting the `print()` behind a getter function. If the `.x` property is accessed it will print the total `s`. This is placed at the end of the generated code so that it accesses `.x` on the last iteration and when concatenated it becomes `.xt=this` (does not access `.x`).

# Answer
> 4 votes
# Zsh, ~~34~~ 32 bytes

```
<<<"((s+=p<$1?$1-2*p:$1));p=$1;"

```

~~Try it online~~  Try it online!

Adapted from Vitrivius's Bash answer (go upvote it too!), shorted considerably by taking advantage of Zsh's math function functionality (Math functions are defined to output the result of the last math expression, which means we don't need to worry about supressing output.)

# Answer
> 3 votes
# Java, 696 bytes

```
n->"import java.util.*;import java.io.*;import java.util.jar.*;interface Main{List<Integer>l=new ArrayList();static void main(String[]a)throws Exception{var z=Main.class.getPackageName();for(var e:System.getProperty(\"java.class.path\").split(System.getProperty(\"path.separator\"))){if(!e.endsWith(\".jar\")){var b=new File(e+File.separatorChar+z);var d=b.listFiles();Arrays.sort(d);for(var f:d){var n=f.getName();if(n.endsWith(\".class\")){Class.forName(n.substring(0,n.length()-6));}}}}int s=0;for(int i=0;i<l.size();i++)s+=l.get(i)-(i>0&&l.get(i)>l.get(i-1)?l.get(i-1)*2:0);System.out.print(s);}}\nclass _"+new java.util.Date().getTime()+"_"+System.nanoTime()+"{static{Main.l.add("+n+");}}//"

```

The `Main` interface has a static `List` field which all the generated classes add an integer to in their static initializer. The main method attempts to load all the classes in the package to run their static initializers. `F(a)` will return different values each time since it tries to make the class names unique using the current time, so `F(a) + F(a)` cannot be shortened by using a variable to store the result of `F(a)`.

Generator

Generated Program

# Answer
> 3 votes
# Python 3.7.3 (outputs Python 3.7.3), 174 bytes

```
import sys;print("""R=%s
class A():
 def __del__(s):print(a)
if"a"in locals():
 if"p"in locals()and p<R:a-=p+p-R
 else:a+=R
if"v"not in locals():v=A();a=R
p=R"""%sys.argv[1])

```

More readable version of the code:

import sys
print("""
number = %s
class PrintOnExit():
   def __del__(self):
      # This object will only be destroyed when the interpreter exits
      print(result)

if "result" in locals():
   if "previous" in locals() and previous < number:
       result -= previous
       result += number - previous
   else:
       result += number

if "print_on_destroy" not in locals():
    print_on_destroy = PrintOnExit()
    result = number

previous = number
""" % sys.argv[1])
```
</code></pre>

# Answer
> 2 votes
# Julia REPL, 50 bytes

adapted from Dominic's answer

```
x->"L=0;L=[L;$x];a=sum(L.*(-1).^[diff(L).>0;0]);a"

```

Try it online!

# Julia, 68 bytes

Basically the same with a `print` that erases the previous line (doesn't work in TIO)

```
x->"L=0;L=[L;$x];print(\"\\r\\e[K\",sum(L.*(-1).^[diff(L).>0;0]));L"

```

Try it online!

# Answer
> 2 votes
## JavaScript (ES6), generates Charcoal, 61 bytes

```
f=
n=>`⎚⊞υＩ${n}ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι`
```

```
<input oninput=o.textContent=f(this.value)>

```

Explanation:

Clears the canvas of the previous output.

```
⊞υＩ${n}

```

Takes the stringified value, casts it back to integer, and pushes it to the predefined empty list.

```
ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι

```

Compares each element of the list with the next element, negating the element if it is smaller, then prints the final sum.

Example: F(10) is `⎚⊞υＩ10ＩΣＥυ⎇‹ι§⁺…υ¹υκ±ιι`, while F(3) is `⎚⊞υＩ3ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι`. The last example is therefore `⎚⊞υＩ10ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ10ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ3ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ3ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ10ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ3ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ3ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ10ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι`. Try it online!

# Answer
> 1 votes
# Jelly, ~~18~~ ~~17~~ ~~16~~ ~~15~~ 14 bytes

```
⁶,y“_< ×ḤƲɼ+ ©

```

Try it online! The TIO version has an extra closing quote which can be omitted, but that breaks the footer, so I left it in; that's why it displays 15 bytes.

## Explanation

```
⁶,y“_< ×ḤƲɼ+ ©   Main monadic link
⁶                " "
 ,               [" ", n]
  y              In the following string, replace " " with n
   “             {
                   Value implicitly starts at 0
                   Register implicitly starts at 0
    _              Subtract from the current value
          ɼ          the result of applying this to the register
         Ʋ           (
     <                 Is it smaller than n? (no -> 0, yes -> 1)
       ×               Multiply that by
        Ḥ                twice the register
         Ʋ           )
           +       Add n to the current value
             ©       and copy n to the register
                 }

```

# Answer
> 1 votes
### Python 3, 120 bytes

```
lambda n:f"""import atexit as a
try:
 z[-1]*=1-2*(z[-1]<{n})
except:
 z=[];a.register(lambda:print(sum(z)))
z+=[{n}]
"""

```

The lambda function returns the code snippet using a f-string. In the snippet, `z` is a list of the "Roman Numerals". In the `try` block, the code negates the last number in `z` if it is less than the current number `n`. If `z` doesn't exist yet an exception is thrown and caught by the `except`, where `z` is initialized to an empty list and a lambda function is registered with `atexit`. Lastly, the new number as appended to `z`. When the interpreter exits, the registered lambda print the sum of `z`.

---
Tags: code-golf, roman-numerals, compiler
---


title: Caesar equivalence

text:
# Question
Title: Caesar equivalence
Two strings are "Caesar equivalent" if the distance (counting up) between the corresponding characters are the same. Yes, I made this term up. Here's an example:

"Abc" and "Cde" are equivalent because

```
distance from a-c == 2
distance from b-d == 2
distance from c-e == 2

```

The capitalization doesn't make any difference.

"Hello" and "World" are not Caesar equivalent because

```
distance from h-w == 15
distance from e-o == 10
distance from l-r == 6
distance from l-l == 0
distance from o-d == 15

```

"Abcd" and "Yzab" are Caesar equivalent because

```
distance from a-y = 24
distance from b-z = 24
distance from c-a = 24 (it wraps around)
distance from d-b = 24

```

You must write a full program that takes two strings from STDIN, and prints a truthy value if they are Caesar equivalent, and a falsy value if they are not.

# Valid Input

* Since capitalization doesn't matter, it is acceptable if your program requires the input to be all lower-case, all upper-case, or whatever mix you want, as long as this is specified in your answer.
* The input will not have spaces or punctuation.
* The inputs will be the same length.

# Answer
# Pyth, 9 bytes

```
}wm=.rzGG

```

The two strings are expected in lowercase, newline separated.

Demonstration.

How it works:

`.r` is Pyth's rotary translation function. It maps each element in the first argument from its first occurance in the second argument to the next entry in the second argument. In this, case, the second argument is `G`, the lowercase alphabet, so this is equivalent to a Caesar shift of 1.

Putting an `=` in front of the function makes it in-place. Thus, `=.rzG` assigns the Caesar shift of `z` by one to `z`. Note that `z` is initialized to the first line of input in Pyth.

This expression is used inside a map. `m=.rzGG` applies this transformation to `z` 26 times, once for each element of `G`, and saves the results in a list. This gives the list of all possible Caesar shifts of `z`.

Finally, `}w` checks whether the next line of input is in that list.
> 10 votes

# Answer
# CJam, ~~17~~ ~~12~~ 11 bytes

*1 byte saved by Dennis.*

```
ll.m26f%)-!

```

Test it here.

Expects the first string to be lower case and the second to be upper case. Prints `1` for Caesar-equivalent strings and `0` otherwise.

## Explanation

```
ll           e# Read two lines of input.
  .m         e# Take the differences of corresponding characters.
    26f%     e# Take the differences modulo 26.
        )-   e# Remove all copies of the last difference from the array. This will
             e# yield an empty array if and only if all differences are the same.
          !  e# Logical NOT, which yields 1 for an empty array and 0 otherwise.

```

The reason we require the first string in lower case and the second in upper case is to ensure that the difference is always positive. Otherwise taking the modulo might return something negative and would not necessarily be unique, even for Caesar-equivalent strings.
> 14 votes

# Answer
# APL (15)

```
1=≢∪26|-⌿⎕A⍳↑⍞⍞

```

It needs the letters to be uppercase, and prints either `1` or `0`, like so:

```
      1=≢∪26|-⌿⎕A⍳↑⍞⍞
ABCD
YZAB
1

      1=≢∪26|-⌿⎕A⍳↑⍞⍞
HELLO
WORLD
0

```

Explanation:

* `↑⍞⍞`: read two lines from the keyboard, and arrange the characters in an N×2 matrix.
* `⎕A⍳`: for each character, find at which position it occurs in `⎕A` (the uppercase alphabet).
* `-⌿`: for each column, subtract the second value from the first value
* `26|`: take the mod-26 of each of those numbers.
* If the strings are Caesar-equivalent, all numbers in this list are now equal, so:
* `≢∪`: find the number of unique values in the list
* `1=`: compare that to `1`.
> 5 votes

# Answer
# Prolog, 56 bytes

```
b([],[],_).
b([A|C],[B|D],N):-N is mod(A-B,26),b(C,D,N).

```

Not all combinations of cases are supported.

usage

```
b(`abcd`,`yzab`,_).

```

Try it online here
> 4 votes

# Answer
# Julia, ~~91~~ ~~87~~ 83 bytes

```
a=readline()
b=readline()
show(length(Set([mod(a[i]-b[i],26)for i=1:length(a)]))<2)

```

Ungolfed + explanation:

```
# Read two strings from STDIN
a = readline()
b = readline()

# Get the absolute difference mod 26 of the character values in the strings
x = [mod(a[i] - b[i], 26) for i = 1:length(a)]

# Construct a set consisting of the elements of x. If the set has only a
# single element, the strings are Caesar equivalent. This will print a
# boolean value to STDOUT.
show(length(Set(x)) < 2)

```

This takes advantage of the fact that strings in Julia can be treated as character arrays and that arithmetic operations can be performed on character values. The input strings can have any mix of capitalization you want, so long as the capitalization at each position matches between the strings.
> 3 votes

# Answer
# J, 19 bytes

```
1=[:#@~.26|-&(3&u:)

```

Letters at the same position should have the same case.

After converting both input strings to their codepoint representation with `&(3&u:)` we compare `1` to the length `#` of the nub `~.` of the modulo 26 `26|` of the difference `-` of the two arrays. The nub will be `1` if all Caesar-distances are the same.

Usage:

```
   'abcd' (1=[:#@~.26|-&(3&u:)) 'yzab'
1

```

Try it online here.
> 3 votes

# Answer
# Javascript (*ES7 Draft*), 87 bytes

Requires inputs to be the same case.

```
(p=prompt)(![z=(a[c='charCodeAt'](i)-b[c](i)+26)%26 for(i in b=p(a=p()))].some(x=>x^z))
```
> 3 votes

# Answer
# C99, ~~92 bytes with bug~~ ~~101~~ 92 bytes

```
  r,i;main(z,a)char**a;{for(;z=a[2][++i];)r|=(a[1][i]-z+*a[2]-*a[1]+52)%26;putchar(49-!!r);}

```

Pretty straightforward; assumes words come as first and second arguments, respectively. Compiled with `-std=c99`.
> 3 votes

# Answer
# CJam, 13 bytes

```
{r(fm26f%}2*=

```

It requires the first character in each word to be in upper case, others in lower case.

Try it here. (Firefox here.)

Too bad the APL variants doesn't support character arithmetics...

### Explanation

```
{
    r       e# Read a word.
    (f-     e# Return each character value minus the first character.
    26f%    e# Mod 26.
}2*         e# Repeat 2 times.
=           e# Check if they are equal.

```
> 2 votes

# Answer
# Perl, 80

***Edit**: A failed optimization had slipped into the golfed code. Now it matches the ungolfed version. (The byte count was correct, though.)*

```
@a=unpack"W*",<>;for(<>=~/./g){$n=ord()-shift@a;$p=!$c++||$p&&$n==$o;$o=$n}say$p

```

Run with Perl version 5.10 (`perl -M5.10.0` or `perl -E …`) for `say()`. Slightly expanded version:

```
@a=unpack"W*",<>;             # read first string, split and convert to numbers

for(<>=~/./g){                # reads the second string and splits it
   $n=ord()-shift@a;          # convert next character of second string and compare
   $p= !$c++ || $p && $n==$o; # compare differences (special case for first char)
   $o=$n
}

say $p

```

The code outputs `1` (truthy in Perl) if the strings are Caesar equivalent, and the empty string (falsy in Perl) if they are not. If this is too loose an interpretation, I need to add 2 bytes for `say$p+0`, which prints `1` or `0`.

Character case must match between inputs.
> 2 votes

# Answer
# Matlab, ~~49~~ 48 bytes

This was a really quick one. Sadly getting a string from stdin is quite expensive.

```
x=@()input('','s');sum(diff(mod(x()-x(),26)))==0

```

Note that it is, like most if not all answers, case sensitive.

EDIT: shaved off one byte by defining an anonymous function!
> 2 votes

# Answer
## C, 97 bytes

```
#define D (*a[2]++-*a[1]+++26)%26
d,r;main(int c,char**a){for(d=D;*a[1];r|=d-D);puts(r?"N":"Y");}

```
> 2 votes

# Answer
# , 48 bytes

```
a=scan(,'');`+`=utf8ToInt;!sd((+a[1]-+a[2])%%26)

```

Try it online!

Standard deviation (`sd`) of the differences between the character codes (mod 26) is zero only if they are all the same. Requires all-same-case input.
> 2 votes

# Answer
# R, 83 ~~84~~

Fairly much the same as the other solutions. Convert the strings into a vector of integers. Mod the difference of the vectors by 26. Do a unique over the list as check the length is 1. It expects the case to be the same in corresponding characters in each string.

```
length(unique(((S=strtoi)((R=charToRaw)((I=readline)()),16L)-S(R(I()),16L))%%26))<2

```

It waits for the two strings to be entered

```
> length(unique(((S=strtoi)((R=charToRaw)((I=readline)()),16L)-S(R(I()),16L))%%26))<2
abcdefghijklmnopqrstuvwxyz
opqrstuvwxyzabcdefghijklmn
[1] TRUE
> length(unique(((S=strtoi)((R=charToRaw)((I=readline)()),16L)-S(R(I()),16L))%%26))<2
Hello
World
[1] FALSE
> length(unique(((S=strtoi)((R=charToRaw)((I=readline)()),16L)-S(R(I()),16L))%%26))<2
Bob
Nan
[1] TRUE
>

```
> 1 votes

# Answer
# Scala, 57 bytes

```
(readLine zip readLine map(x=>x._1-x._2%26)toSet).size==1

```

Little longer than the others, and essentially equivalent, but it is in a vary different style of language!

I also have this version(56 bytes):

```
(readLine zip readLine map(_._1-x$1._2%26)toSet).size==1

```

But I don't know if the x$1 working is coincidence or by design...
> 1 votes

# Answer
# bash, ~~71~~ 48

Using the “standard” Unix program `caesar(6)`.

New version (with lots of help from @DigitalTrauma):

```
read a b;seq -f"caesar %g <<<$a" 26|bash|grep $b

```
* Inputs have to be on the same line, separated by spaces
* Character case must match between inputs.
* Prints `1` for true or nothing for false.

If input via command line arguments is allowed, it can be shortened to **39 bytes**:

```
 seq -f"caesar %g <<<$1" 26|bash|grep $2

```

Old version for the record:

```
 read a b;for i in `seq 26`;do [ `echo $a|caesar $i` = $b ]&&echo 1;done

```
> 1 votes

# Answer
# Python 2 - ~~241~~ ~~237~~ ~~188~~ 147 Bytes

Takes input as lowercase string enclosed in quotes, space separated. There has to be a better way..

```
s=[[ord(x)for x in y]for y in input().split()];v=[];v=[v+[(s[1][i]-s[0][i])%26]for i in xrange(0,len(s[0]))];v=sum(v,[]);print sum(v)//v[0]==len(v)

```

Ungolfed (260-odd bytes)

```
strs = [[ord(x) for x in y] for y in raw_input().split()]
vals = []
for i in xrange(0, len(strs[0])):
if strs[0][i]<strs[1][i]:
    vals += [strs[1][i]-strs[0][i]]
else:
    vals += [26-(strs[0][i]-strs[1][i])]
return sum(vals)//vals[0] == len(vals)

```
> 1 votes

# Answer
**Python 2, 80 bytes**

Takes 2 similarly-cased strings from stdin separated by a space :

```
s,t=raw_input().split();print len(set((ord(c)-ord(d))%26 for c,d in zip(s,t)))<2

```

Tested on following test cases :

```
tests = [
    ("abc", "abc", True),
    ("abcd", "abc", False),
    ("abc", "cde", True),
    ("Abc", "Cde", True),
    ("abc", "deg", False),
    ("Hello", "World", False),
    ("Abcd", "Yzab", True),
    ("", "", True)
]

for s, t, v in tests:
    if len(s) == len(t): # I didn't read that at first
        assert v == (len(set((ord(c) - ord(d)) % 26 for c, d in zip(s, t))) < 2)

```
> 1 votes

# Answer
# Matlab/Octave, ~~53~~ 52

```
x=@()input('','s');isscalar(unique(mod(x()-x(),26)))

```

Input should all be of the same case.

Sadly, Matlab is not very good with user input. As an anonymous handle, this could be only 35 bytes:

```
@(a,b)isscalar(unique(mod(a-b,26)))

```

Matlab treats the characters of a string as a vector of numbers. Doing subtraction gets us their difference, and `unique` converts that vector into a vector containing only unique values. If there is only one number, the words are caeser equivalent and isscalar returns 1, otherwise it will return 0.
> 1 votes

# Answer
# \>\<\> (Fish), 50 bytes

```
i:3b*(?v88+0.;n1<
0)?vc1.>~ri-&l?!^i-&:&-2d*%
;n0<

```

Expects letters at the same position to have the same case.

Explanation

* `i:3b*(?v` reads the first word into the stack with `88+0.` providing the looping jump
* `~ri-&` removes `~` the separating space from the stack, reverses the stack `r` (first letter will be on top), reads in the first letter of the second word `i`, calculates the offset from the first word's first letter `-` and stores it in the register `&`.
* `l?!^i-&:&-2d*%0)?v` reads every next letter of the second word substracting it from the first word's corresponding letter which is at the top of the stack substracts the offset `&:&-` stored in the register and checks if the result is 0 mod 26 `2d*%`. If not prints 0 and terminates `0n;`. `c1.` provides the looping jump.
* If reached the end of the second word the program prints 1 and terminates `1n;`.
> 1 votes

# Answer
# Jelly, 5 bytes

```
Oạ/ċ2

```

Try it online!

Outputs a positive integer for equivalent, 0 otherwise

## How it works

```
Oạ/ċ2 - Main link. Argument A (a list of strings)  e.g. ["abc", "cde"]

O     - Ordinal. Cast to code point                     [[97, 98, 99], [99, 100, 101]]
  /   - Reduce the list by...
 ạ    -   absolute difference                           [2, 2, 2]
   ċ2 - Count the number of 2s in the list              3

```
> 1 votes

# Answer
# Pip, ~~33~~ 18 bytes

```
$=({Aa-Ab}%26MZqq)

```

-15 bytes from Dlosc.

Try it online!

## Explanation

```
$=({AB((Ab<Aa?-26 0)+Aa-Ab)}MZab) ; a,b → command line args
                            MZab  ; Map items of a and b to function, pass as (a,b)
   {                 Aa-Ab }      ; Subtract codepoints of a and b
       (Ab<Aa?-26 0)+             ; Add -26 if b > a
    AB(                   )       ; Take the absolute value of the whole thing
$=                                ; Check if all items of the mapped list are equal

```
> 1 votes

# Answer
# APL (Dyalog Unicode), 14 bytes(SBCS)

```
1=≢∪26|-⌿⎕UCS⎕

```

Takes input as a two row matrix and returns truthy or falsey value

Try it online!

## Explanation

```
1=≢∪26|-⌿⎕UCS⎕
         ⎕UCS⎕ ⍝ Convert all characters to Unicode codepoints
       -⌿      ⍝ Subtract pairs of matrix along leading axis(x)
    26|        ⍝ Get residue(modulus) of 26 with each difference(works with negatives)
1=≢∪           ⍝ Check if number of unique remainders is equal to 1.

```
> 1 votes

# Answer
# Pip `-r`, 12 bytes

```
$=($-A^g)%26

```

Try it online!

### Explanation

With the `-r` flag, `g` is a list of lines from stdin rather than the usual list of command-line arguments.

```
      ^g      Split each line into a list of characters (^ vectorizes on lists)
     A        Convert each character to its ASCII code (A vectorizes on lists)
              We now have a list of two lists of numbers.
   $-         Fold on subtraction; since - also vectorizes on lists, this does pairwise
               subtraction of the character codes, returning a list of differences
  (     )%26  Take each difference mod 26 (% also vectorizes)
$=            Fold the list on equals: 1 if all items are equal, 0 otherwise

```
> 1 votes

# Answer
# KDB(Q), 35 bytes

```
{0=sum(1_-':)mod[;26](-)."i"$(x;y)}

```

# Explanation

```
                         "i"$(x;y)      / convert to ascii decimal
                     (-).               / get differences
             mod[;26]                   / mod 26
      (1_-':)                           / difference between the differences
 0=sum                                  / sum should be 0 if equivalent
{                                 }     / lambda

```

# Test

```
q){0=sum(1_-':)mod[;26](-)."i"$(x;y)}["abcd";"yzab"]
1b

```
> 0 votes

# Answer
# Java 281

```
import java.util.*;enum C{E;Scanner s=new Scanner(System.in);public static void main(String[]z){char[]u=E.n(),v=E.n();int i=0,d=(u[0]-v[0]+26)%26;boolean e=true;for(;++i<u.length;)e&=d==(u[i]-v[i]+26)%26;System.out.print(e);}char[]n(){return s.next().toUpperCase().toCharArray();}}

```

expanded:

```
import java.util.*;
enum Caesar{
    Equivalence;
    Scanner input=new Scanner(System.in);
    public static void main(String[]z){
        char[]firstString=Equivalence.nextInput(),secondString=Equivalence.nextInput();
        int index=0,difference=(firstString[0]-secondString[0]+26)%26;
        boolean isEqual=true;
        for(;++index<firstString.length;)
            isEqual&=difference==(firstString[index]-secondString[index]+26)%26;
        System.out.print(isEqual);
    }
    char[]nextInput(){
        return input.next().toUpperCase().toCharArray();
    }
}

```

I could save 14 bytes if I got rid of converting everything to uppercase, but I feel like it's more complete to leave it in.
> 0 votes

# Answer
# PowerShell Core, ~~68~~ 66 bytes

```
$a,$b=$args;(1..$a.Length|%{($a[--$_]-$b[$_]+26)%26}|gu).count-eq1

```

Try it online!

```
 (1..$a.Length                                            # Builds an array of the size of one of the input
              |%{($a[--$_]-$b[$_]+26)%26}                 # For each of the characters, gets their distance making sure we stay between 0 and 25
                                           |gu            # Remove duplicates
                                              ).count-eq1 # Returns True if we have a single record

```
> 0 votes

# Answer
# Zsh `-eo extendedglob`, 43 bytes

```
>$2
repeat 25 {1=`tr a-z b-za<<<$1`;ls ^$1}

```

Try it online!

Input from command-line arguments and output via exit code. I'm not doing stdin/stdout, that's idiotic.
> 0 votes

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


title: Dividing Divisive Divisors

text:
# Question
Title: Dividing Divisive Divisors
Given a positive integer \\$n\\$ you can always find a tuple \\$(k\_1,k\_2,...,k\_m)\\$ of integers \\$k\_i \geqslant 2\\$ such that \\$k\_1 \cdot k\_2 \cdot ... \cdot k\_m = n\\$ and $$k\_1 | k\_2 \text{ , } k\_2 | k\_3 \text{ , } \ldots \text{ , }k\_{m-1}|k\_m.$$ Here \\$a|b\\$ means \\$b\\$ is a multiple of \\$a\\$, say "a divides b". If \\$n\>1\\$ all entries \\$k\_i\\$ must be at least \\$2\\$. For \\$n=1\\$ we have no such factor and therefore we get an empty tuple.

In case you're curious where this comes from: This decomposition is known as *invariant factor decomposition* in number theory and it is used in the classification of finitely generated Abelian groups.

### Challenge

Given \\$n\\$ output *all* such tuples \\$(k\_1,k\_2,...,k\_m)\\$ for the given \\$n\\$ exactly once, in whatever order you like. The standard output formats are allowed.

### Examples

```
  1: () (empty tuple)
  2: (2)
  3: (3)
  4: (2,2), (4)
  5: (5)
  6: (6)
  7: (7)
  8: (2,2,2), (2,4), (8)
  9: (3,3), (9)
 10: (10)
 11: (11)
 12: (2,6), (12)
108: (2,54), (3,3,12), (3,6,6), (3,36), (6,18), (108)

```

Related: http://oeis.org/A000688, List all multiplicative partitions of n

# Answer
> 5 votes
## Haskell, ~~66~~ ~~62~~ 60 bytes

```
f n=[n|n>1]:[k:l:m|k<-[2..n],l:m<-f$div n k,mod(gcd n l)k<1]

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 13 bytes

```
Òœ€.œP€`êʒüÖP

```

Try it online!

```
Ò                      # prime factorization of the input
 œ€.œ                  # all partitions
     P                 # product of each sublist
      €`               # flatten
        ê              # sorted uniquified
         ʒ             # filter by:
          üÖ           #  pairwise divisible-by (yields list of 0s or 1s)
            P          #  product (will be 1 iff the list is all 1s)

```

# Answer
> 3 votes
# Jelly, 17 bytes

```
ÆfŒ!Œb€ẎP€€QḍƝẠ$Ƈ

```

Try it online!

# Answer
> 2 votes
# JavaScript (V8),  ~~73~~  70 bytes

Prints the tuples in descending order \\$(k\_m,k\_{m-1},...,k\_1)\\$.

```
f=(n,d=2,a=[])=>n>1?d>n||f(n,d+1,a,d%a[0]||f(n/d,d,[d,...a])):print(a)

```

Try it online!

### Commented

```
f = (             // f is a recursive function taking:
  n,              //   n   = input
  d = 2,          //   d   = current divisor
  a = []          //   a[] = list of divisors
) =>              //
  n > 1 ?         // if n is greater than 1:
    d > n ||      //   unless d is greater than n,
    f(            //   do a recursive call with:
      n,          //     -> n unchanged
      d + 1,      //     -> d + 1
      a,          //     -> a[] unchanged
      d % a[0] || //     unless the previous divisor does not divide the current one,
      f(          //     do another recursive call with:
        n / d,    //       -> n / d
        d,        //       -> d unchanged
        [d, ...a] //       -> d preprended to a[]
      )           //     end of inner recursive call
    )             //   end of outer recursive call
  :               // else:
    print(a)      //   this is a valid list of divisors: print it

```

# Answer
> 1 votes
# 05AB1E, ~~17~~ ~~15~~ 14 bytes

```
Ñ¦IиæʒPQ}êʒüÖP

```

Very slow for larger test cases.

-1 byte thanks to *@Grimy*.

Try it online.

**Explanation:**

```
Ñ               # Get all divisors of the (implicit) input-integer
 ¦              # Remove the first value (the 1)
  Iи            # Repeat this list (flattened) the input amount of times
                #  i.e. with input 4 we now have [2,4,2,4,2,4,2,4]
    æ           # Take the powerset of this list
     ʒ  }       # Filter it by:
      PQ        #  Where the product is equal to the (implicit) input
         ê      # Then sort and uniquify the filtered lists
          ʒ     # And filter it further by:
           ü    #  Loop over each overlapping pair of values
            Ö   #   And check if the first value is divisible by the second value
             P  #  Check if this is truthy for all pairs

                # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~78~~ ~~76~~ ... ~~61~~ 51 bytes

```
Do[i∣##&&##~#0~i,{i,2,-#/-##2/. 1:>Print@{##2}}]&

```

Try it online!

Recursive search tree.

Prints the list of decompositions.

# Answer
> 1 votes
# JavaScript, 115 bytes

```
f=(n,a=[],i=1)=>{for(;i++<n;)n%i||(a=a.concat(f(n/i).filter(e=>!(e[0]%i)).map(e=>[i].concat(e))));return n>1?a:[a]}

```

I will write an explanation later

# Answer
> 0 votes
# Japt, ~~22~~ 19 bytes

```
ÆâÃcÅà â f@¶XcXäv)×

```

Try it

```
ÆâÃcÅà â f@¶XcXäv)×     :Implicit input of integer U
Æ                       :Map the range [0,U)
 â                      :  Divisors of U
  Ã                     :End map
   c                    :Flatten after
    Å                   :  Slicing the first element off each
     à                  :Combinations
       â                :Deduplicate
         f              :Filter by
          @             :Passing each X through the following function
           ¶            :  Test U for equality with
            Xc          :  Concatenate to X
              Xä        :    Consecutive pairs of X
                v       :    Reduced by testing divisibility
                 )      :  End concat
                  ×     :  Reduce by multiplication

```

# Answer
> 0 votes
# Husk, <sup>~~18~~</sup> 15 bytes

```
fΛ¦ufo=¹ΠṖmΠtṖp

```

Try it online!

Similar to Grimmy's 05AB1E answer.

-3 bytes from Zgarb.

# Answer
> 0 votes
# Jelly, 14 bytes

```
ḊœċRẎḍƝẠ×P=¥ʋƇ

```

Try it online!

## How it works

```
ḊœċRẎḍƝẠ×P=¥ʋƇ - Main link. Takes n on the left
Ḋ              - Dequeue; Yield [2, 3, ..., n]
   R           - Range, Yield [1, 2, ..., n]
 œċ            - For each integer, 1 ≤ i ≤ n, yield combinations with
                  replacement of length i from the dequeued range
    Ẏ          - Tighten into a single list of lists
            ʋƇ - Keep those for which the following is true:
        ×  ¥   -   Both of the following are true:
      Ɲ        -     Over overlapping pairs:
     ḍ         -       Is the left divisible by the right?
       Ạ       -     Is all true?
        ×      -   And:
         P     -     The product
          =    -     Equals n?

```

---
Tags: code-golf, math, sequence, number-theory, abstract-algebra
---


title: Primes and Twin Primes

text:
# Question
Title: Primes and Twin Primes
Your challenge is to write a program to print all the primes (separated by one or more whitespace characters) less than a given integer `N` with an asterisk (`*`) next to each twin prime. A twin prime is a prime number that is either two more or two less than another prime.

(Hardcoding outputs is allowed, but it is not likely to result in very short code.)

Shortest code wins!

## Input

* `N` is always one of 50, 100, 1000, 1000000, or 10000000

## Output

* The output for input `50` should be
```
2 3* 5* 7* 11* 13* 17* 19* 23 29* 31* 37 41* 43* 47
```

# Answer
# Python 2, ~~81~~ 79 bytes

-2 bytes thanks to dingledooper with a different way to detect if `k-2` is a prime which works with `k=2`.

Uses Wilson's theorem for the primality tests and the fact that \\$p\\$, \\$p+1\\$ and \\$p+2\\$ are coprime for most primes \\$p\\$.

```
P=k=q=1
exec"if P%k:print`k`+'*'[k<3:P%(k+2)|q/k];q=k+2\nP*=k*k;k+=1\n"*input()

```

Try it online!

The output includes the input if it is prime, but this is fine since all testcases are composite.

## How?

We use the following result of Wilson's theorem:

$$ (k-1)!^2 \operatorname{mod} k = \begin{cases} 1 & \text{if $k$ is prime}\\ 0 & \text{otherwise.} \end{cases} $$

In the code `P` is used to keep track of \\$(k-1)!^2\\$ and `P%k` tests if `k` is a prime. If this is the case, we print the output and update `q` to `k+2`. If `k==q` at the `print` statement, we know that `k-2` was a prime and `k` is a twin prime.

`P%(k+2)` tests if `k+2` is a prime number. If we would use the exact same prime test as before, this would be `P*k*k*(k+1)*(k+1)%(k+2)`, but with our assumption that \\$k\\$, \\$k+1\\$ and \\$k+2\\$ are coprime for prime \\$k\\$, this gives the same result.
The assumption doesn't hold for `k=2`, but this is handled separately with `'*'[k<3:]`, which results in the empty string if `k<3`.
> 14 votes

# Answer
# Python 2, 92 bytes

The Sieve of Eratosthenes is used to compute primes. The main advantage here is its incredible speed (`N=10000000` is computed in just a few seconds).

```
n=input()
R=range(n)
for k in R:
 if k>1:R[k+k::k]=(n+~k)/k*[0];print`k`+'*'[:R[k-2]|R[k+2]]

```

Try it online!
> 7 votes

# Answer
# Jelly, 16 bytes

```
ÆRµ+Ø+Ḥ¤ẒẸ”*xṭ)K

```

Try it online!

## How it works

```
ÆRµ+Ø+Ḥ¤ẒẸ”*xṭ)K - Main link. Takes N on the left
ÆR               - Yield the prime range until N
  µ           )  - Over each prime P between 2 and N:
       ¤         -   Group into a nilad:
    Ø+           -     Builtin; [1, -1]
      Ḥ          -     Unhalve; [2, -2]
   +             -   Add to P;  [P+2, P-2]
        Ẓ        -   Is prime?
         Ẹ       -   Are any true? Either 1 or 0
          ”*x    -   Repeat "*" that many times
             ṭ   -   Append to P, yielding [P, "*"] or [P, ""]
               K - Join by spaces

```
> 5 votes

# Answer
# APL (Dyalog Extended), ~~32~~ 26 bytes (SBCS)

Anonymous tacit prefix function.

```
(⍕,⍬⍴'*'/⍨1⍭¯2 2+⊢)⍤0∘⍸1⍭⍳

```

Try it online!

**ɩ**ntegers 1 through `N`

`1⍭` Boolean mask indicating those that are primes

**ɩ**ndices of the trues (i.e. the primes)

then

`(``)∘0` on each scalar, apply the following tacit function:

the argument

`¯2 2+` add `[-2,2]` to that

`1⍭` indicate the primes

`'*'/⍨` use that to replicate an asterisk (gives `""` or `"*"` or `"**"`)

`⍬⍴`**r**eshape into a scalar (lit. an array with an empty shape; gives `' '` or `'*'` or `'*'`)

`⍕,` prepend the string representation of the argument prime

since the inner function mapped scalars to vectors the overall result is a matrix
> 5 votes

# Answer
# Jelly, 13 bytes

```
ÆRðȮạe@2”*xṄ)

```

A monadic Link that accepts a number and prints the output with a new-line separator.
Uses the fact we never receive input, \\$n\\$, such that \\$n-1\\$ or \\$n\\$ are only on the lower side of a prime pair
(e.g. \\$41\\$ or \\$42\\$, which would miss the `*` from \\$41\\$).

**Try it online!** (footer suppresses Link's return value).

### How?

```
ÆRðȮạe@2”*xṄ) - Link: n
ÆR            - primes in [2,n] (call this "Primes")
  ð         ) - for each (p in Primes) do this f(p, Primes):
   Ȯ          -   print p (plus no newline)
    ạ         -   (p) absolute difference (Primes)
       2      -   two
     e@       -   (two) exists in (the absolute differences)?
        ”*    -   '*' character
          x   -   ('*') times (existence of two)
           Ṅ  -   print that (plus a newline)

```
> 4 votes

# Answer
# , 41 bytes

```
[:(,&":"0' *'{~1+./@p:2 _2+/])i.&.(p:inv)

```

Try it online!

## how

* `i.&.(p:inv)` Returns every prime less than or equal to the input.
* `2 _2+/]` Create a 2 row table, adding and substracting 2 to each prime. Eg, for n=50:

```
4 5 7 9 13 15 19 21 25 31 33 39 43 45 49
0 1 3 5  9 11 15 17 21 27 29 35 39 41 45

```
* `1...p:` Is each a prime?

```
0 1 1 0 1 0 1 0 0 1 0 0 1 0 0
0 0 1 1 0 1 0 1 0 0 1 0 0 1 0

```
* `+.` Reduce each column by "or":

```
0 1 1 1 1 1 1 1 0 1 1 0 1 1 0

```

This mask tells which are the twin primes.
* `' *'{~` Convert 1 to `*` and 0 to .
* `,&":"0` For each, append `,` to the input after converting to string `&":"0`:

```
2
3*
5*
7*
11*
13*
17*
19*
23
29*
31*
37
41*
43*
47

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 70 bytes

```
If[FreeQ[NextPrime[a=Prime@#,{-1,1}]-a,2|-2],a,a""]&/@Range@PrimePi@#&

```

Try it online!

-1 byte from @att
> 1 votes

# Answer
# Python 3.8 (pre-release), 107 bytes

```
p=lambda x:0<all(x%i for i in range(2,x))<x
f=lambda n:[str(i)+'*'*(p(i-2)|p(i+2))for i in range(2,n)if p(i)]

```

Subtracted 2 bytes for f=

A port of my solution to the previous challenge, with a slightly better p function.

Try it online!
> 1 votes

# Answer
# JavaScript, ~~136~~ 119 bytes

```
n=>(a=(R=n=>[...Array(n).keys()])(n)).filter(x=>a[~x]=+R(x).filter(y=>x%y<1)).map(x=>x+" *"[a[~x+2]|a[~x-2]]).join(' ')

```

```
f=
n=>(a=(R=n=>[...Array(n).keys()])(n)).filter(x=>a[~x]=+R(x).filter(y=>x%y<1)).map(x=>x+" *"[a[~x+2]|a[~x-2]]).join(' ')
console.log(f(100));
```

*Saved 17 bytes thanks to tsh*
> 1 votes

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

A port of ovs' answer. Expects a BigInt.

```
n=>{for(s=p=k=2n;k<n;p*=k++)p%k?s+=' '+(x=k-2n,p/x%x+p%~-~k?k+'*':k):0;return s}

```

Try it online!

Or **77 bytes** with `eval()`, as suggested by @EliteDaMyth:

```
n=>eval("for(s=p=k=2n;k<n;p*=k++)p%k?s+=' '+(x=k-2n,p/x%x+p%~-~k?k+'*':k):s")

```

Try it online!

---

# JavaScript (V8), 91 bytes

```
n=>{for(k=1;++k<n;)(g=d=>{for(i=d;i%--d;);return~-d})(i=k)||print(g(i-=2)*g(i+=4)?k:k+'*')}

```

Try it online!
> 1 votes

# Answer
# Japt, `-S` 32 bytes

```
o fj
äÏ-X¥2Ãp0
íVíVé '+ Ï?X+'*:X

```

Try it online!

Notably, this works for the required inputs, but not a few others like 12.

Explanation:

```
o fj
o       # Create the range [0 ... input]
  fj    # Keep only the primes
        # Store as U

äÏ-X¥2Ãp0
ä     Ã      # Create an array by mapping each pair in U through:
 Ï-X         #  Get the difference
    ¥2       #  Check whether it's 2
       p0    # Add 0 to the end of that array
             # Store as V

íVíVé '+ Ï?X+'*:X    #
   Vé                # Rotate V 1 item to the right
 Ví   '+             # Add each item in rotated V with the same index in original V
í                    # For each item in U:
         Ï?          #  If the same index in V is not 0:
           X+'*      #   Add "*" to it
               :X    #  Otherwise don't change it
                     # Implicit output, -S flag joins with spaces

```

I feel like there's a better way to accomplish `Ï?X+'*:X` but I haven't found one
> 1 votes

# Answer
# PowerShell, 172 bytes

```
$L=@{};($N=2.."$args")|%{$c=2;$k=$_
for(;($k*$c)-le$N[-1]){if(!($L|% c*y($k*$c))){$L[$k*$c]=1};$c++}}
$x=$N|?{!$l.$_}
$x|%{if((($_+2)-in$x)-or(($_-2)-in$x)){"$_*"}else{$_}}

```

Try it online!

Thanks to @mazzy for ~70 bytes
> 1 votes

# Answer
# PowerShell, 91 bytes

Inspired by Wasif

```
($x=($N=2.."$args")|?{!($N-lt($c=$_)|?{!($c%$_)})})|%{"$_"+'*'*(($_+2)-in$x-or($_-2)-in$x)}

```

Try it online!

The script outputs correctly for the allowed input and incorrectly in the general case (see last twins for 12)

Less golfed:

```
$Numbers = 2.."$args"
$primes = $Numbers | Where {
    $current = $_
    $dividers = $Numbers -lt $current | Where {($current % $_) -eq 0}
    !$dividers       # true if the $current is a prime
}
$primes | ForEach {
    "$_"+'*'*(($_+2) -in $primes -or ($_-2) -in $primes)    # format output number
}

```
> 1 votes

# Answer
# Julia 0.4, 61 bytes

I'm using Julia 0.4 because `primes` was a built-in
It works with a more recent version of Julia and the package `Primes.jl`

This approach will fail sometimes when `N` or `N-1` is prime, which isn't the case for any of the requested inputs

```
x->map(i->print(" $i"*"*"^(i+2∈p||i-2∈p)),(p=primes(x);))

```

Try it online!
> 1 votes

# Answer
# Perl 5, 101 bytes

```
@p[grep"".(1x$_)!~/^(11+)\1+$/,2..$_]=(1)x$_;
$_=join$",map$p[$_-2]+$p[$_+2]?"$_*":$_,grep$p[$_],2..@p

```

Try it online!

Uses the somewhat known `/^(11+)\1+$/` regexp to detect primes.
> 1 votes

# Answer
# , ~~99~~ 87 bytes

With some help from Robin and improvements from Dominic:

```
for(n in 2:scan())if(sum(!n%%2:n)<2)cat("
",n,"*"[sum(!n%%2:n-2)==1|!sum(!(n+2)%%2:n)])

```

or, when detailed:

```
for(n in 2:scan()) #range
  if(sum(!n%%2:n)<2)#prime number
    cat(" #create space
    ",n, #print n
    "*"[sum(!n%%2:n-2)==1| #print * for previous prime
    !s(!(n+2)%%2:n)]} # or for next prime

```

Try it online!
> 1 votes

# Answer
# Husk, ~~24~~ 22 bytes

*Edit: -2 bytes thanks to Razetime*

```
m?o`:'*ssȯ#2`m₁¹≠₁
fṗḣ

```

Try it online!

Husk doesn't particularly like mixing numerics + characters.

```
fṗḣ                   # helper function: primes up to input
m?o`:'*ssȯ#2`m₁¹oa-₁  # main function:
m                  ₁  # for each element in primes up to input
                oa-   # get the absolute differences to
            `m₁¹      # all primes up to input
         ȯ#2          # and count how many '2's there are:
 ?                    # if it's zero
        s             # convert it to a string
  o`:'*s              # otherwise convert it to a string & prepend with '*'

```
> 1 votes

# Answer
# , ~~88~~ 87 bytes

```
p=2;for(y in 3:scan())p=c(p,y[sum(!y%%2:y)<2]);for(z in p)cat(z,"*"[2%in%abs(z-p)]," ")

```

Try it online!

I wanted to try a different approach to Xi'an's answer...

~~Frustratingly, though, after golfing & golfing I still can't get rid of that last pesky byte...~~ Got it!
> 1 votes

# Answer
# Raku, 54 bytes

```
{put map {$_~'*'x?is-prime $_+(2|-2)if .is-prime},^$_}

```

Try it online!
> 0 votes

# Answer
# SageMath, 88 bytes

Added 14 bytes to fix an error kindly pointed out by Kjetil S.

```
def f(n,b=1,c=2):
 while c<n:a,b,c=b,c,Primes().next(c);print(str(b)+'*'[:2in(b-a,c-b)])

```

Try it online!
> 0 votes

# Answer
# Japt `-S`, 25 bytes

```
o fj
äÏ-X¥2
gVí|Vé)ð²_+'*

```

Try it

```
o fj       - primes up to N
äÏ-X¥2     - difference of each consecutive primes == 2?
g ... _+'* - add an asterisk to the elements at the indexes obtained with @ :
Ví|Vé)   @ pair array with array rotated then reduce by OR
ð²       @ truthy values when passed trough f(square)

-S flag to join with spaces

```
> 0 votes

# Answer
# 05AB1E, 14 bytes

```
ÅPÐδα2δå'*×øJ»

```

Try it online.

Or alternatively:

```
ÅP©ε?®yα2å'*×,

```

Try it online.

Or alternatively (only works in the legacy version of 05AB1E):

```
ÅPÐδα2QOĀ'*×+»

```

Try it online.

All three programs above output newline-delimited.
I have the feeling a 13-byter is possible, but I'm unable to find it thus far.

**Explanation:**

```
ÅP              # Push a list of primes in the range [2, (implicit) input-integer]
  Ð             # Triplicate this list
   δ            # Pop two of them, and apply double-vectorized:
    α           #  For each prime, get its absolute difference with the list of primes
      δ         # For each list of absolute differences:
     2 å        #  Check if a 2 is among them (1 if truthy; 0 if falsey)
        '*×    '# Repeat "*" that amount of times as string
           ø    # Create pairs with the remaining list of primes
            J   # Join each pair together to a string
             »  # Join this list by newlines
                # (after which the result is output implicitly)

ÅP              # Push a list of primes in the range [2, (implicit) input-integer]
  ©             # Store it in variable `®` (without popping)
   ε            # For-each over each prime:
    ?           #  Pop and print the prime (without trailing newline)
     ®          #  Push the prime-list from variable `®`
      yα        #  Get for each its absolute difference with the current prime `y`
        2å      #  Check if a 2 is in this list of absolute differences
          '*×  '#  Repeat "*" that amount of times as string
             ,  #  Pop and print this string with trailing newline

ÅPÐδα           # Similar as in the first program above
     2Q         # Check for each inner-most value if it's equal to 2
       O        # Sum all inner list of checks
        Ā       # Check which sums are >= 1
         '*×   '# For each, repeat "*" that amount of times as string
            +   # Append it to each integer in the remaining list of primes
             »  # Join this list by newlines
                # (after which the result is output implicitly)

```
> 0 votes

# Answer
# C, ~~108~~ 106 bytes

-2 bytes thanks to ceilingcat.

```
f(n,i,j,d,e){for(d=e=i=2;j=n>i;j/i?printf(i-d-2?" %d":d-e-2?"* %d*":" %d*",i),e=d,d=i:1,i++)for(;i%++j;);}

```

Try it online!

The only input parameter which the function requires is n. The hardest part was avoiding duplication of * after numbers, and there ought to be a better way to do that.
> 0 votes

---
Tags: code-golf
---


title: Intermediate String Array Reflection

text:
# Question
Title: Intermediate String Array Reflection
Let's start by re-defining a **reflection** of a character in a 2-d array of characters:

> Given a square 2-d array of characters with distinct lowercase alphabetical letters, define a reflection of a letter in the matrix as swapping it with the character directly across from it through the center of the square.

Thus, a reflection of the letter `c` in

```
abcde
fghij
klmno
pqrst
uvwxy

```

would result in the configuration

```
abwde
fghij
klmno
pqrst
uvcxy

```

because the `c` and the `w` have been switched.

Some more examples (with the same original configuration as above):

> Reflecting the character `e` would form

```
 abcdu
 fghij
 klmno
 pqrst
 evwxy

```

> Reflecting the character `m` would make

```
 abcde
 fghij
 klmno
 pqrst
 uvwxy

```

> Reflecting the character `b` would form

```
 axcde
 fghij
 klmno
 pqrst
 uvwby

```

## The Challenge

Given a 2-d array of characters with distinct lowercase letters, go through each character in a given string and "reflect" it in the matrix.

*Clarifications: The letters in the string are from `a-z`, the letters are unique, and the array is at least 1x1 and at most 5x5 (obviously, as there are only 26 characters in the English alphabet.)* The characters in the string are guaranteed to be in the 2-d array. The string is at most 100 characters long.

## Input

An string `s`, an integer `N`, and then a `NxN` array of characters.

## Example

Input:

```
ac
2
ab
cd

```

Output:

```
dc
ba

```

\*Reason: First, reflect the `a` with the `d`. Then, reflect the `c` with the `b` because `c` is the second letter in the input string.

---

## Scoring

* Output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

## Current Winner

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution 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> <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> <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><script>var QUESTION_ID = 163084; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
> 4 votes
# Python 2, 76 bytes

```
lambda s,a:[a[[i,~i][(s.count(c)+s.count(a[~i]))%2]]for i,c in enumerate(a)]

```

Try it online!

Takes input:

* `s`: string
* `N`: ignored
* `a`: joined string of chars

Returns a flat list of chars

---

If I *have* to take the array as a list:

# Python 2, ~~111~~ ~~108~~ ~~107~~ 104 bytes

```
lambda s,n,a:[[x[sum(map(s.count,x))%2]for i in range(n)for x in[[a[j][i],a[~j][~i]]]]for j in range(n)]

```

Try it online!

Takes input:

* `s`: string
* `n`: int
* `a`: 2D lists of chars

Returns a 2D list of chars

# Answer
> 3 votes
# Octave, ~~85~~ ~~68~~ 66 bytes

Using `eval`, with a loop inside it saved a lot of bytes! I got the inspiration from this answer by Luis Mendo!

```
@(c,N,A)eval"for C=c,A(flip(k))=A(k=[x=find(A==C),N^2+1-x]);end,A"

```

Try it online!

### Explanation:

```
f=@(c,N,A)          % Anonymous function that takes the three input variables
eval"...          % Evaluate the string and run it:
 for C=c,          % Loop over the character list 'c'
  .. x=find(A==C)   % Find the index where the character C is in A, and store it as 'x'
  .. k=[x,N^2+1-x]  % Create a vector with the index of C, and the index of its reflection
   A(flip(k))=A(k)  % Swap the elements in these positions
  end               % End loop
  A"                % Display the new 'A'

```

# Answer
> 2 votes
# , ~~74~~ 61 bytes

-13 bytes thanks to Giuseppe.

```
function(s,n,m){for(x in s)m[v]=rev(m[v<-(i=x==m)|rev(i)]);m}

```

Try it online!

Inputs a vector of characters to search as `s`, size of the matrix as `n` and matrix itself as `m`. If it is absolutely necessary to take the first argument as *string*, that would pretty much spoil the fun.

# Answer
> 2 votes
# Java 10, ~~126~~ ~~123~~ ~~116~~ 114 bytes

```
(s,n,m)->{for(var c:s)for(int N=n*n,i,j;N-->0;)if(m[i=N/n][j=N%n]==c){m[i][j]=m[n+~i][n+~j];m[n+~i][n+~j]=c;N=0;}}

```

Modifies the input character-matrix instead of returning a new one to save bytes.

Try it online.

**Explanation:**

```
(s,n,m)->{     // Method with the three parameters and no return-type
  for(var c:s) //  Loop over the characters given:
    for(int N=n*n,i,j;N-->0;)
               //   Inner loop over the cells of the matrix:
      if(m[i=N/n][j=N%n]==c){
               //    If the current character and matrix-value are equals:
        m[i][j]=m[n+~i][n+~j];m[n+~i][n+~j]=c;
               //     Swap the values in the matrix at indices [i, j] and [n-i-1, n-j-1]
        N=0;}} //     And stop the inner loop (go to next iteration of the outer loop)

```

# Answer
> 2 votes
# Jelly, ~~15~~ 14 bytes

```
FW;Ṛi,C$¥¦/ṁḷY

```

Try it online!

Full program.

Explanation:

```
FW;Ṛi,C$¥¦/ṁḷY       Main link. Input: ['ab','cd'] (left), 'ac' (right).
FW                   **F**latten and **W**rap it in a list. Current value = ['abcd'].
  ;                  Concatenate it with right argument. ['abcd','a','c']
          /          Reduce from left:
   Ṛ     ¦             Apply everse at...
    i   ¥              the index (of right argument in left argument)...
     ,C$               and its complement index.

```

The last operation needs more explanation. Denote f = `Ṛi,C$¥¦`, then for value `['abcd','a','c']` it computes `('abcd' f 'a') f 'c'`, which expands to:

```
Ṛi,C$¥¦    Function **f**. Assume left argument = 'abcd' and right argument = 'a'
Ṛ          First, compute the reverse. Get 'dcba'.
 i   ¥     To compute the indices to apply to, first the index of 'a' in 'abcd'
             is ('abcd' i 'a') = 1. (first index)
  ,C$      Then pair with (1 C) = 0. (last index)
      ¦    Apply 'dcba' to 'abcd' at indices 0 and 1:

              a**bc**d
              **d**cb**a**
              ^1 ^0
              ====
              dbca

```

# Answer
> 2 votes
# Java (JDK), ~~95~~ 93 bytes

```
(x,s,N)->{for(var c:s)for(int i=-1;++i<N;){var t=x[i];if(t==c){x[i]=x[N+~i];x[N+~i]=t;i=N;}}}

```

Try it online!

# Java (JDK), 131 bytes

```
(x,s,n)->{for(var c:s)for(int i=~0;++i<n*n;){int a=i/n,b=i%n;var t=x[a][b];if(t==c){x[a][b]=x[n+~a][n+~b];x[n+~a][n+~b]=t;break;}}}

```

# Java (JDK), ~~138~~ 135 bytes

```
(x,s,n)->s.forEach(c->{for(int i=~0,a=i/n,b=i%n;++i<n*n;){var t=x[a][b];if(t==(char)c){x[a][b]=x[n+~a][n+~b];x[n+~a][n+~b]=t;break;}}})

```

# Java (JDK), 112 bytes

```
(x,s,N)->{for(var c:s)for(var v:x.entrySet())if(v.getValue()==N-x.get(c))x.put(v.getKey(),x.put(c,N-x.get(c)));}

```

Try it online!

# Java (JDK), 70 bytes

```
(x,X,s,N)->{for(var c:s)x.put(X.get(N-x.get(c)),x.put(c,N-x.get(c)));}

```

Try it online!

All of these code snippets function in essentially the same way since only difference between them is the type of the variable x. The first has it set as `char[]`, the second as `char[][]` and the third as `List<Object>`. The fourth and fifth are quite unique solutions, and so I'll go over the specific details of them last. As somewhat of a side note, the first of these three entries inputs the total quantity of elements in the initial array (i.e., `N = n * n`).

Here's how the first three entries work:

```
(array, reflect, size) -> {            // Initializes lambda expression
    for (char c: reflect)              // Loops through soon-to-be reflected characters
        for (int i = 0; i < size; i++) // Loops through elements in array
            if (array[i] == c)         // Checks if this element should be reflected
            {
                var temp = array[i];   // Reflects elements
                array[i] = array[size - 1 - i];
                array[size - 1 - i] = temp;
                break;                 // Goes on to reflect next character
            }
};

```

I feel like these entries can be further golfed with use of nested functions and lambda expressions, but I have been unable to do so thus far. I instead went on to create the fourth entry, as shown below in all of its golfed glory:

```
(x,s,N)->{
    for(var c:s)
        for(var v:x.entrySet())
            if(v.getValue()==N-x.get(c))
                x.put(v.getKey(),x.put(c,N-x.get(c)));
}

```

The fifth is quite similar. These particular lambda expressions are unique, in the sense that `s` is an `Object[]` and N is one less than the total quantity of elements in the initial array. But most importantly, `x` is a `LinkedHashMap<Object, Integer>`. Well, what's so special about all of that? The idea behind changing all of these things was to allow for a short for loop going over the elements of `s`, thus ridding the program of tightly packing for loops with ugly garbage. It essentially simplified things for the code and I. Unfortunately, doing so would mean indexing the initial array to find the index of each element, contradicting its intended purpose.

It was at that moment that I realized that replacing the array input with some `Map` subclass would allow me to use the elements to be reflected as a way to index the elements in the array directly. So I did the only logical solution: map half of the array elements to their corresponding pairs to simplify reflection. Didn't work, big surprise. But I didn't give up and mapped each element to its corresponding array index and the idea was looking good. Next problem: given an element in the array, finding its reflective pair couldn't be done without more for loops, if statements and precious bytes altogether. But a more immediate problem came from this, too: printing the array. In retrospect, it would've been possible to instead input a copy of the array and use the original's elements to get the key-value pairs, but I found a better solution: the `LinkedHashMap`. This class contains the nested class `Entry`, which allows for much simpler key-value pairing, which just so happened to be at the root of both problems.

So now that I've gone over why I made these changes and how the base of this setup should work, I'll use what we've learned to give the code some more context:

```
(x,s,N)->{ // Initializing lambda expression
    for(var c:s) // Looping over elements to be reflected
        for(var v:x.entrySet()) // Looping over key-value pairs...
            if(v.getValue()==N-x.get(c)) // ...until element opposite current is found
                x.put(v.getKey(),x.put(c,N-x.get(c))); // Swapping elements
}

```

You should note that the line involving the actual reflection has a nested `put` method, because it returns the key that was changed, thus removing an extra variable initialization for the swapping process.

But what about my *fifth* entry? Am I taking this simple challenge too seriously? **Yes!** This solution has a very low byte count, because it's the same as the fourth, but with an extra input: `X`. Unlike `x`, which is the array converted to a `LinkedHashMap<Object, Integer>`, `X` is the reverse: a `LinkedHashMap<Integer, Object>`. This allows us to skip searching for any element's index and instead just look it up in `X`, thus removing a lot of code.

As a final side note, the only entries that allow more characters to be reflected than there are in the initial array are the fourth and fifth. Will this be the end?

Thanks to **@KevinCruijssen** for the inspiration and for saving two bytes from my first entry.

# Answer
> 2 votes
# C, ~~84~~ ~~86~~ 83 bytes

+2 bytes to use a temporary variable instead of chained XOR when swapping variables, allowing for the central letter to be swapped with itself

-3 bytes thanks to ceilingcat.

```
f(s,n,a,i,j,t)char*s,*a,*i;{for(;*s;*i=t)i=index(a,*s++),t=a[j=a-i+n*n-1],a[j]=*i;}

```

Try it online!

Un-golfed:

```
f(s,n,a,i,j,t)
    char*s,*a,*i;
{
    for(;*s;*i=t) { //Loop while end of s hasn't been reached
        i=index(a,*s++); //i = pointer to char in a with value *s, then get next char s
        t=a[j=a-i+n*n-1]; //j = index of char in a which is opposite i, then swap i and a[j]
        a[j]=*i;
    }
}

```

# Answer
> 1 votes
# Python 3, ~~122~~ 111 bytes

```
lambda l,n,A:[[[A[a][b],A[~b][~a]][sum(map(l.count,[A[a][b],A[~b][~a]]))%2]for b in range(n)]for a in range(n)]

```

Try it online!

Returns a 2D array of chars.

# Answer
> 1 votes
# Retina 0.8.2, 96 bytes

```
+`^(.)(.*¶(.|¶)*)((.)((.|¶)*))?\1(?(4)|(((.|¶)*)(.))?)((?<-3>.|¶)*$(?(3).))
$2$11$9$1$6$5$12
1A`

```

Try it online! Takes the string `s` and the array of characters as a newline-delimited string without the integer `N`. Explanation: Each character `c` of `s` is processed in turn. The regex matches two positions equidistant from the ends of the array, of which one is `c` and the other is its mirror `m`. These characters are swapped and `c` is removed from `s`.

```
+`

```

Processes each character of `s` in turn.

```
^(.)

```

`$1` captures `c`.

```
(.*¶(.|¶)*)

```

`$3` captures a stack of characters in the array prefixing one of `c` or `m`. `$2` captures the rest of `s` plus all of these characters.

```
((.)((.|¶)*))?

```

If `m` precedes `c`, `$4` has a value, `$5` captures `m` and `$6` captures the characters between `m` and `c`. `$7` captures `$6` as a stack but its value is not used.

```
\1

```

`c` is now matched in the array itself.

```
(?(4)|(((.|¶)*)(.))?)

```

If `m` wasn't already matched, then `$8` optionally captures a value, in which case `$9` captures the characters from `c` to `m`, `$10` captures `$9` as a stack which is unused and `$11` captures `m`. The value is optional in case `c` and `m` are the same character.

```
((?<-3>.|¶)*$(?(3).))

```

`$12` captures the characters suffixing the other of `c` and `m`. A balancing group is used to ensure `$12` is as long as `$3` was deep, i.e. the prefix and suffix are the same length.

```
$2$11$9$1$6$5$12

```

The pieces are then put back together - first the rest of `s` and the prefix of the array, then if `c` preceeded `m` then `m` then the middle, then `c`, then if `m` preceeded `c` then the middle then `m`, then the suffix.

```
1A`

```

Now that `s` is empty it is deleted.

# Answer
> 0 votes
# Perl 5 `-lpF`, 97 bytes

```
$i=0|<>;$_=join'',<>;s/\W//g;for$k(@F){/$k/g;$t=substr$_,-pos,1;eval"y/$t$k/$k$t/"}s%.{$i}%$&$/%g

```

Try it online!

# Answer
> 0 votes
# JavaScript, 85 bytes

Takes string `S` and an array `A` as joined string.

```
([...S],[...A])=>S.map(c=>[A[j],A[i]]=[A[i=A.indexOf(c)],A[j=A.length+~i]])&&A.join``

```

```
f=
([...S],[...A])=>S.map(c=>[A[j],A[i]]=[A[i=A.indexOf(c)],A[j=A.length+~i]])&&A.join``

console.log(
  f('abcd','ac')
)
```

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