title: Mirror, Mirror, in the Code

text:
# Question
Title: Mirror, Mirror, in the Code
Two-dimensional programming languages often have mirror commands like `/` and `\` to redirect the instruction pointer on the grid:

```
>>>>\
    v
    v
<<<</

```

In this challenge, you're given an incoming direction and a mirror and you need to determine the outgoing direction.

## Rules

The incoming direction will be given as one of the characters `NESW` and the mirror will be given as either `/` or `\`. You may receive these in any order. You must use uppercase letters.

You may take input in any convenient format, including a two-character string, a string using some separator between the characters, a pair of characters in a list, or even a pair of singleton strings. If you do use a string with separator, the separator cannot use any of the characters `NWSE\/`.

Output should be a character from `NESW` or single-character string.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is , so the shortest valid answer – measured in *bytes* – wins.

## Test Cases

There are only 8 possible inputs you need to handle, so there is no excuse for not testing your code on all of them:

```
N /   -->   W
N \   -->   E
E /   -->   S
E \   -->   N
S /   -->   E
S \   -->   W
W /   -->   N
W \   -->   S

```

# Answer
# Python, ~~40~~ 38 bytes

-2 bytes thanks to @MitchSchwartz `(ord(d)+ord(m))%8` -\> `ord(d)+ord(m)&7`

```
lambda d,m:' NESSWNW'[ord(d)+ord(m)&7]

```

plain lookup of answer in a list (AKA string) indexed by the smallest mod of the sum of ordinals that works.

Test cases are on **ideone**
> 23 votes

# Answer
# Python 2, 40 bytes

```
lambda c,m,k="NWES":k[k.find(c)^(m>k)+1]

```

Sp3000 saved one byte (`.index``.find`).

## Explanation

We want to map the directions like so:

```
       \
  N ⇄⇄⇄⇄⇄⇄⇄ E
  ⇅         ⇅
  ⇅         ⇅
/ ⇅         ⇅ /
  ⇅         ⇅
  ⇅         ⇅
  W ⇄⇄⇄⇄⇄⇄⇄ S
       \

```

We can assign the directions 2-bit codes, and view both flips as XOR-ing the first and second bits:

```
         xor 2
     0 0 ⇄⇄⇄⇄⇄ 1 0
      ⇅         ⇅
      ⇅         ⇅
xor 1 ⇅         ⇅ xor 1
      ⇅         ⇅
      ⇅         ⇅
     0 1 ⇄⇄⇄⇄⇄ 1 1
         xor 2

```

The mapping between bit strings and directions happens using the string `k`. Now we just need to map mirror characters `'/'` and `'\\'` to the values `1` and `2`. Since `'/' < '\\'`, we could naïvely use `(m>'/')+1` as a formula. But wait! Lexicographically,

```
'/' < 'NWES' < '\\'

```

and we have `'NWES'` nicely assigned to `k`! So we can use `(m>k)+1` instead.
> 20 votes

# Answer
# CJam, 14 bytes

(@MartinEnder ported my Python answer)

```
l1b" NESSWNW"=

```

How?

```
l1b" NESSWNW"= -
l              - read input
 1b            - cast characters as base 1 digits
   " NESSWNW"  - the string " NESSWNW"
             = - modulo index into the string

```

Tests are on **aditsu**
> 12 votes

# Answer
## Javascript (ES6), ~~50~~ ~~41~~ ~~40~~ 37 bytes

```
d=>m=>(S="NWES")[S.search(d)^-~(m>S)]

```

*Saved 3 more bytes by using comparison, thanks to Lynn's answer*

### Usage

```
let f =
d=>m=>(S="NWES")[S.search(d)^-~(m>S)]

console.log(f("N")("/"));  //   -->   W
console.log(f("N")("\\")); //   -->   E
console.log(f("E")("/"));  //   -->   S
console.log(f("E")("\\")); //   -->   N
console.log(f("S")("/"));  //   -->   E
console.log(f("S")("\\")); //   -->   W
console.log(f("W")("/"));  //   -->   N
console.log(f("W")("\\")); //   -->   S
```
> 6 votes

# Answer
# MATL, ~~19~~ 17 bytes

```
'NWSE'jy&mjy+Eq-)

```

Try it online! Or verify the eight cases.

### Explanation

```
'NWSE'    % Push this string
j         % Take first input, say 'W'. Stack contains: 'NWSE', 'W'
y         % Duplicate from below. Stack: 'NWSE', 'W', 'NWSE'
&m        % Index of membership. Stack: 'NWSE', 2
j         % Take second input, say '/'. Stack: 'NWSE', 2, '/'
y         % Duplicate from below. Stack: 'NWSE', 2, '/', 2
+         % Add (char '/' is converted to code point). Stack: 'NWSE', 2, 49
Eq        % Multiply by 2, subtract 1. Stack: 'NWSE', 2, 97
-         % Subtract. Stack: 'NWSE', -95
)         % Apply -95 as (modular, 1-based) index into 'NWSE'. Stack: 'N'
          % Implicitly display

```
> 6 votes

# Answer
# Pyth, ~~17~~ ~~16~~ 15 bytes

*Thanks to @Jakube and @Maltysen for -1 byte each*

```
@J"NWES"xxJQh>E

```

A program that takes input of two newline-separated quoted strings, first the direction and then the mirror, and prints the result.

This is a port of @Lynn's Python answer.

Try it online

**How it works**

```
@J"NWES"xxJQh>E  Program. Inputs: Q, E
 J"NWES"         J="NWES". Yield J
         xJQ     J.index(Q)
             >E  E>Q, lexographically (implicit input fill)
            h    +1
        x        Bitwise XOR of the above two
@                Index into J with the above
                 Implicitly print

```
> 6 votes

# Answer
# Java 7, ~~71~~ ~~70~~ 68 bytes

```
char c(int d,int m){return"NEWS".charAt("NEWS".indexOf(d)^-~(m%2));}

```

Too bad the `charAt` and `indexOf` takes up so much bytes..

**Ungolfed & all test cases:**

Try it here.

```
class M{
  static char c(int d, int m) {
    return "NEWS".charAt("NEWS".indexOf(d) ^ -~(m%2));
  }

  public static void main(String[] a){
    System.out.print(c('N', '/') + " ");
    System.out.print(c('N', '\\') + " ");
    System.out.print(c('E', '/') + " ");
    System.out.print(c('E', '\\') + " ");
    System.out.print(c('S', '/') + " ");
    System.out.print(c('S', '\\') + " ");
    System.out.print(c('W', '/') + " ");
    System.out.print(c('W', '\\') + " ");
  }
}

```

**Output:**

```
W E S N E W N S

```
> 4 votes

# Answer
# Jelly, ~~14 13~~ 12 bytes

(a port of my Python answer)
-1 byte thanks to @MartinEnder (add a space to end of the string and remove need for modulo 8)
-1 byte thanks to @LuisMendo (take a single string argument rather than two)

```
OSị“NESSWNW

```

How?

```
OSị“NESSWNW  - takes a single argument "dm" (direction and mirror), in either order.
                   strings and lists are equivalent in Jelly
 O            - ordinal: [ord(d),ord(m)]
  S           - sum: ord(d)+ord(m)
    “NESSWNW  - string: "NESSWNW "
   ị          - fetch modulo index (the string is 8 long and 1-based)

```

Test it on **TryItOnline**
> 4 votes

# Answer
# 05AB1E, 14 bytes

```
‘€Ã‘DIkI'/kÌ^è

‘€Ã‘             # from string "NEWS"
             è   # get element at index
    DIk          # index of 1st input in string "NEWS"
            ^    # XOR
       I'/k      # index of 2nd input in string "/"
           Ì     # +2

```

Try it online!
> 4 votes

# Answer
# Python, ~~63~~ ~~61~~ 59 bytes

```
lambda d,m,x='NESW'*2:x[x.find(d)+2*(m=='/\\'[d in'NS'])-1]

```

Pretty simple. Can definitely be golfed more. Decides whether to add 1 or -1 to the input's index in `'NESW'`.

This is a lambda expression; to use it, prefix it with `f=`.

Ideone it!
> 3 votes

# Answer
# Java 8, ~~62~~ ~~58~~ 56 bytes

```
(d,m)->"SEWN".charAt("NWES".indexOf(d)^m.indexOf(47)+2);

```

# Ungolfed test program

```
import java.util.function.BiFunction;

public class Mirror {

public static void main(String[] args) {
    BiFunction<String, String, Character> function = (d,m)->"SEWN".charAt("NWES".indexOf(d)^m.indexOf(47)+2);

    System.out.println(function.apply("N", "/")); //W
    System.out.println(function.apply("N", "\\")); //E
    System.out.println(function.apply("W", "/")); //N
    System.out.println(function.apply("W", "\\")); //S
    System.out.println(function.apply("E", "/")); //S
    System.out.println(function.apply("E", "\\")); //N
    System.out.println(function.apply("S", "/")); //E
    System.out.println(function.apply("S", "\\")); //W
}

}

```
> 3 votes

# Answer
## PowerShell v2+, 34 bytes

```
param($a,$b)"xNESSWNW"[(+$a+$b)%8]

```

Takes input as two explicit `char`s, outputs a `char`.

This works as follows: If we sort the output, we want `S` `/` to somehow equal the same as `N` `\`, `W` `/` to equal `E` `\`, etc. Or, at least, produce numbers that are "close enough" yet still distinct. If we look at the ASCII values, we get a table like the below:

```
In1   In2       Res.    Sum
S 83  / 47  --> E 69 -> 130
N 78  \ 92  --> E 69 -> 170
W 87  / 47  --> N 78 -> 134
E 69  \ 92  --> N 78 -> 161
W 87  \ 92  --> S 83 -> 179
E 69  / 47  --> S 83 -> 116
N 78  / 47  --> W 87 -> 125
S 83  \ 92  --> W 87 -> 175

```

Running a quick brute-forcer on the summations column (derived from summing the ASCII code points of the inputs) shows that if we take the sums modulo `8`, we get the following `2 2 | 6 1 | 3 4 | 5 7`. That's evidenced in the string `"xNESSWNW"`, as `E` is at index `2`, `N` is at `6` and `1`, and so on.

So, we just need to sum the inputs (implicitly casting from `char` to `int32` along the way), take that `%8`, and use that to index into our string.

### Test Cases

```
PS C:\Tools\Scripts\golfing> ('N','/'),('N','\'),('E','/'),('E','\'),('S','/'),('S','\'),('W','/'),('W','\')|%{"$($_[0]) $($_[1]) --> "+(.\mirror-mirror-in-the-code.ps1 ([char]$_[0]) ([char]$_[1]))}
N / --> W
N \ --> E
E / --> S
E \ --> N
S / --> E
S \ --> W
W / --> N
W \ --> S

```
> 3 votes

# Answer
## Batch, 111 bytes

```
:goto %1
:W/
:E\
@echo N
@exit/b
:S/
:N\
@echo E
@exit/b
:E/
:W\
@echo S
@exit/b
:N/
:S\
@echo W

```

Accepts e.g. `W/` as a two-character string command line parameter. The `\` and `/` make looping awkward; it would have taken 124 bytes.
> 2 votes

# Answer
# Octave, 30 bytes

Used the same order of arguments as Jonathan Allan.

Takes the input as two-character string `'W\'`.

```
@(x)['NESSWNW'](mod(sum(x),8))

```

Try it online.
> 2 votes

# Answer
# C, 44, 35, 34 bytes

```
f(a,b){return"NWES"[a&a/2&3^b&3];}

```

It requires two characters as two variables. It takes both lower and upper case. It uses a lot of bit manipulation. The fragment `a&a/2` results in a value that has unique values for the lower two bits, `&3` cuts off all higher bits. This used as an index into the string "NWES" for the `\` mirror. Luckily, the lower two bits of the ASCII characters `\` and `/` are 00 and 11 respectively, which is perfect to XOR with the aforementioned index to get the correct direction for the `/` mirror.
> 2 votes

# Answer
# CJam, 17 bytes

```
r"SWEN"_e!r'/#=er

```

Input is space-separated.

Try it online! (As a linefeed-separated test suite.)

This is the solution I found before posting the challenge. Not as short as Jonathan's cyclic indexing, but I thought this approach is quite interesting (and novel).

### Explanation

The goal is use transliteration (i.e. using a character-to-character mapping) to replace the input character with the output character. To do this, we need to select the correct map based on whether the mirror is `/` or `\`. We'll map from the `SWEN` list to another one which we'll select conditionally. If the input list is `SWEN`, the two output maps need to be the following:

```
in  SWEN
/   ENSW
\   WSNE

```

Note that these are in sorted and reverse-sorted order (which is why we chose the seemingly random `SWEN` order as the input set). We could generate these by sorting the input list and the reversing the result if the input has `\`, but there's a better way:

```
r       e# Read incoming direction.
"SWEN"  e# Push input list for transliteration.
_e!     e# Duplicate and get all permutations. The way, `e!` is implemented, it
        e# always gives the permutations in sort order, regardless of the order
        e# of the input set. Specifically that means that "ENSW" will be first
        e# and "WSNE" will be last in this list.
r       e# Read the mirror.
'/#     e# Find the index of / in this string. If the mirror is '/', then this
        e# gives 0. Otherwise, this gives -1, indicating that '/' was not found.
=       e# Select the corresponding permutation. Indexing is zero-based and
        e# cyclic so that 0 (input '/') gives the first permutation "ENSW" and
        e# -1 (input '\') gives the last permutation "WSNE".
er      e# Perform the transliteration on the incoming direction.
        e# Printing is implicit.

```
> 1 votes

# Answer
# SED 48 (42 + 1 for -r) 43

Saved 5 thanks to Martin Ender♦

```
s,N/|S\\,W,;s,E/|W\\,S,;s,N.|S/,E,;s,..,N,

```

Takes input as a two character string.
> 1 votes

# Answer
# Mathematica, 98 bytes

```
If[#2=="/",{"S",,,,,,,,,"W",,,,,"E",,,,"N"},{"N",,,,,,,,,"E",,,,,"W",,,,"S"}][[LetterNumber@#-4]]&

```

Anonymous function. Takes two strings as input and returns a string as output.
> 0 votes

# Answer
## C, 81 bytes

```
f(char*a){return a!="N/"&a!="S\\"?a!="N\\"&a!="S/"?a!="W\\"&a!="E/"?78:83:69:87;}

```

### Usage

```
main()
{
    printf("N/ \t %c\n",f("N/"));
    printf("N\\\t %c\n",f("N\\"));
    printf("E/ \t %c\n",f("E/"));
    printf("E\\\t %c\n",f("E\\"));
    printf("S/ \t %c\n",f("S/"));
    printf("S\\\t %c\n",f("S\\"));
    printf("W/ \t %c\n",f("W/"));
    printf("W\\\t %c\n",f("W\\"));
}

```

**Output:**

```
N/      : W
N\      : E
E/      : S
E\      : N
S/      : E
S\      : W
W/      : N
W\      : S

```
> 0 votes

# Answer
# Pyth, 13 bytes

```
@."EW¹0`Y"sCM

```

Test suite

Sum the code points, modular index, compressed string.
> 0 votes

# Answer
# TI-Basic, 40 bytes

Hardcodes the inputs. Boring, but the shortest way.

```
sub("NEWS",1+int(inString("E/W\N\S/N/S\E\W/",Ans)/4),1

```
> 0 votes

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


# Question
Title: Smallest positive number whose y-th power is divisible by x
# Task

Given integers `x` and `y` which are both at least `2`, find the smallest positive number whose `y`-th power is divisible by `x`.

# Example

Given `x=96` and `y=2`, the output should be `24` since `24` is the smallest positive `n` satisfying `n^2 is divisible by 96`.

# Testcases

```
x  y output
26 2 26
96 2 24
32 3 4
64 9 2
27 3 3

```

# Scoring

This is . Solution with lowest byte-count wins.

# References

# Answer
> 7 votes
# Brachylog, ~~19~~ ~~17~~ ~~16~~ ~~15~~ 12 bytes

*2 bytes saved thanks to @LeakyNun.*

```
:[I:1]*$r=#>

```

Try it online!

### Explanation

```
               Input = [X, Y]
:[I:1]*        Get a list [X*I, Y] (I being any integer at this point)
       $r=     Get the first integer which is the Yth root of X*I
          #>   This integer must be strictly positive
               This integer is the Output

```

# Answer
> 6 votes
# Jelly, 6 bytes

```
ÆE÷ĊÆẸ

```

Try it online! or verify all test cases.

### How it works

```
ÆE÷ĊÆẸ  Main link. Arguments: x, y

ÆE      Yield the exponents of x's prime factorization.
  ÷     Divide them by y.
   Ċ    Ceil; round the quotients up to the nearest integer.
    ÆẸ  Return the integer with that exponents in its prime factorization.

```

# Answer
> 6 votes
## JavaScript (ES7), 32 bytes

```
f=(x,y,i=1)=>i**y%x?f(x,y,i+1):i

```

# Answer
> 5 votes
# Python 3, ~~60~~ ~~43~~ 39 bytes

*Thanks to @LeakyNun and @Sp3000 for help*

```
f=lambda x,y,i=1:i**y%x<1or-~f(x,y,i+1)

```

A function that takes input via argument and returns the output.

**How it works**

The function uses recursion to repeatedly check integers `i`, starting with `i=1`, until one satisfying the required condition, here `i**y%x<1`, is found. This is achieved by taking the logical `or` of the condition and the result of the expression for `i+1` incremented, which here is `-~f(x,y,i+1)`. This expression continuously evaluates as `False` until a satisfying value `j` is found, at which point it evaluates to `True` and recursion stops. Since these are respectively equivalent to `0` and `1` in Python, and the function has repeatedly been adding `1` via the incrementing part, the function returns `(j-1)*False + True + (j-1)*1 = (j-1)*0 + 1 + (j-1)*1 = 1 + j-1 = j`, as required.

Try it on Ideone

# Answer
> 5 votes
# Jelly, 6 bytes

```
R*%⁸i0

```

Try it online! or verify all test cases.

### How it works

```
R*%⁸i0  Main link. Arguments: x, y

R       Yield range from 1 to x inclusive.
 *      Raise each to power y.
  %⁸    Take modulo of each with base x.
    i0  Find the 1-based index of the first
        occurence of zero, returns.

```

# Answer
> 4 votes
## Haskell, 31 bytes

```
x#y=[n|n<-[1..],mod(n^y)x<1]!!0

```

Usage example: `96#2` -\> `24`.

Direct implementation: try all integers `n`, keep those that meet the condition and pick the first one.

# Answer
> 4 votes
# 05AB1E (10 bytes)

```
>GN²m¹ÖiNq

```

Try it online

* `>` Reads the first argument, increments it, and pushes it on the stack
* `G` pops the stack (`a`) and starts a loop that contains the rest of the program where `N` takes on the value `1, 2, ... a - 1`.
* `N²m` pushes `N` and the second entry from the input history, then pops them both and pushes the first to the power of the second.
* `¹` pushes the first entry from the input history onto the stack.
* `Ö` pops the previous two stack entries, then pushes `a % b == 0` on the stack.
* `i` pops that from the stack. If true, it executes the rest of the program; otherwise, the loop continues.
* `N` pushes `N` on the stack.
* `q` terminates the program.

When the program terminates, the top value of the stack is printed.

# Answer
> 3 votes
# MATL, 9 bytes

```
y:w^w\&X<

```

Try it online!

### Explanation

```
y       % Take x and y implicitly. Push x again
        % STACK: x, y, x
:       % Range from 1 to x
        % STACK: x, y, [1, 2, ..., x]
w       % Swap
        % STACK: x, [1, 2, ..., x], y
^       % Power, element-wise
        % STACK: x, [1^y,  2^y, ..., x^y]
w       % Swap
        % STACK: [1^y, 2^y, ..., x^y], x
\       % Modulo, element-wise
        % STACK: [mod(1^y,x), mod(2^y,x), ..., mod(x^y,x)]
        % A 0 at the k-th entry indicates that x^y is divisible by x. The last entry
        % is guaranteed to be 0
&X<     % Arg min: get (1-based) index of the first minimum (the first zero), say n
        % STACK: n
        % Implicitly display

```

# Answer
> 3 votes
# Actually, ~~12~~ 11 bytes

Many thanks to Leaky Nun for his many suggestions. Golfing suggestions welcome. Try it online!

```
;)R♀ⁿ♀%0@íu

```

Original 12-byte approach. Try it online!

```
1WX│1╖╜ⁿ%WX╜

```

Another 12-byte approach. Try it online!

```
w┬i)♀/♂K@♀ⁿπ

```

A 13-byte approach. Try it online!

```
k╗2`╜iaⁿ%Y`╓N

```

**Ungolfing:**

First algorithm

```
       Implicitly pushes y, then x.
;      Duplicate x.
)      Rotate duplicate x to bottom of the stack.
R      Range [1, x] (inclusive).
♀ⁿ     Map a**y over the range.
♀%     Map a**y%x over the range.
0@í    new_list.index(0)
u      Increment and print implicitly at the end of the program.

```

Original algorithm

```
       Implicitly pushes x, then y.
1WX    Pushes a truthy value to be immediately discarded
         (in future loops, we discard a**y%x)
|      Duplicates entire stack.
         Stack: [y x y x]
1╖     Increment register 0.
╜      Push register 0. Call it a.
ⁿ      Take a to the y-th power.
%      Take a**y mod x.
W      If a**y%x == 0, end loop.
X      Discard the modulus.
╜      Push register 0 as output.

```

Third algorithm

```
       Implicitly pushes y, then x.
w      Pushes the full prime factorization of x.
┬      Transposes the factorization (separating primes from exponents)
i      Flatten (into two separate lists of primes and exponents).
)      Rotate primes to the bottom of the stack.
♀/     Map divide over the exponents.
♂K     Map ceil() over all of the divided exponents.
@      Swap primes and modified exponents.
♀ⁿ     Map each prime ** each exponent.
π      Product of that list. Print implicitly at the end of the program.

```

Fourth algorithm

```
     Implicitly pushes x, then y.
k╗   Turns stack [x y] into a list [x, y] and saves to register 0.
2    Pushes 2.
  `    Starts function with a.
  ╜i   Pushes register 0 and flattens. Stack: [x y a]
  a    Inverts the stack. Stack: [a y x]
  ⁿ%   Gets a**y%x.
  Y    Logical negate (if a**y is divisible by x, then 1, else 0)
  `    End function.
╓    Push first (2) values where f(x) is truthy, starting with f(0).
N    As f(0) is always truthy, get the second value.
     Print implicitly at the end of the program.

```

# Answer
> 2 votes
# dc, ~~23~~ 22 bytes

*Thanks to Delioth for his tip about input methods, saving a byte*

```
sysxz[zdlylx|0<F]dsFxp

```

Uses the stack depth operator `z` for incrementing the test case directly on the stack, and the modular exponentiation operator `|` for, well, modular exponentiation. Repeat testing until remainder is not greater than zero.

# Answer
> 2 votes
# R, ~~61 bytes~~, ~~39 bytes~~, ~~37 bytes~~, 34 bytes

I'm still a newbie in R programming and it turns out this is my first function I create in R (**Yay!**) so I believe there's still room for improvement.

```
function(x,y){for(n in 2:x){if(n^y%%x==0){cat(x,y,n);break}}}

```

Online test can be conducted here: RStudio on rollApp.

---

**Major progress:**

```
function(x,y){which.max((1:x)^y%%x==0)}

```

`which.max` works because it returns the highest value in a vector and if there are multiple it will return the first. In this case, we have a vector of many FALSEs (which are 0s) and a few TRUEs (which are 1s), so it will return the first TRUE.

---

**Another progress:**

```
function(x,y)which.max((1:x)^y%%x==0)

```

Finally, it beats out the answer using Python by two bytes. **:)**

**Another progress: (Again!)**

```
function(x,y)which.min((1:x)^y%%x)

```

---

Many thanks to Axeman and user5957401 for the help.

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
Lsm¹%0k>

```

**Explanation**

```
L         # range(1,x) inclusive
 sm       # each to the power of y
   ¹%     # each mod x
     0k   # find first index of 0 (0-based)
       >  # increment to 1-based

```

Try it online

# Answer
> 1 votes
# Perl 6,  ~~26~~  25 bytes

```
~~{first * **$^y%%$^x,1..$x}~~
{first * **$^y%%$^x,1..*}
```

## Explanation:

```
# bare block with two placeholder parameters ｢$^y｣ and ｢$^x｣
{
  # find the first value
  first

  # where when it ｢*｣ is taken to the power
  # of the outer blocks first parameter ｢$^y｣
  * ** $^y
  # is divisible by the outer blocks second parameter ｢$^x｣
  %% $^x,

  # out of the values from 1 to Inf
  1 .. *
}

```

# Answer
> 0 votes
# Mathematica, 36 bytes

```
(i=1;While[n=i++;Mod[n^#2,#]!=0];n)&

```

# Answer
> 0 votes
# Dyalog APL, 11 bytes

Translation of this.

```
0⍳⍨⊣|(⍳⊣)*⊢

```

`0⍳⍨` find the first zero in
`⊣|` the division remainders when *x* divides
`(⍳⊣)*` the integers one through *x*, raised to the power of
*y*

TryAPL online!

# Answer
> 0 votes
## PowerShell v2+, 48 bytes

```
param($x,$y)(1..$x|?{!(("$_*"*$y+1|iex)%$x)})[0]

```

Takes input `$x` and `$y`. Constructs a range from `1` to `$x`, then uses `Where-Object` to filter those numbers. The filter takes the string `"$_*"` (i.e., the current number with an asterisk) and uses string-multiplication to concatenate those `$y` times, then tacks on a final `1` at the end, then pipes that to `iex` (short for `Invoke-Expression` and similar to `eval`). This takes the place of `[math]::Pow($_,$y)`, since PowerShell doesn't have an exponentiation operator, and is two bytes shorter. That's fed into the modulo operator `%` with `$x` -- thus, if it's divisible, this will be `0`, so we encapsulate that in parens and take the Boolean-not `!(...)` thereof. Thus, if its divisible, it'll be included by this filter, and all other numbers will be excluded.

Finally, we encapsulate the resultant numbers in parens `(...)` and take the `[0]` index. Since the range entered sorted `1..$x`, this will be the smallest. That's left on the pipeline and printing is implicit.

### Test cases

```
PS C:\Tools\Scripts\golfing> (26,2),(96,2),(32,3),(64,9),(27,3)|%{($_-join', ')+' -> '+(.\smallest-positive-number-divisor.ps1 $_[0] $_[1])}
26, 2 -> 26
96, 2 -> 24
32, 3 -> 4
64, 9 -> 2
27, 3 -> 3

```

# Answer
> 0 votes
## PHP, ~~55~~ 33 bytes

```
$i=1;while($i**$y%$x)$i++;echo$i;

```

# Answer
> 0 votes
# Perl, ~~29~~ 26 bytes

Includes +3 for `-p` (not +1 since the code contains `'`)

Run with the input on STDIN

```
power.pl <<< "96 2"

```

`power.pl`:

```
#!/usr/bin/perl -p
/ /;1while++$\**$'%$`}{

```

# Answer
> 0 votes
# Pyth, 9 bytes

```
AQf!%^THG

```

A program that takes input of a list of the form `[x, y]` on STDIN and prints the result.

Try it online

**How it works**

```
AQf!%^THG  Program. Input: Q
AQ         G=Q[0];H=Q[1]
  f        First truthy input T in [1, 2, 3, ...] with function:
     ^TH    T^H
    %   G   %G
   !        Logical not (0 -> True, all other modulus results -> False)
           Implicitly print

```

# Answer
> -1 votes
# PHP 59 bytes

Sorry, but I can't test this from my mobile. **:)**

```
function blahblah($x,$y){
  for($i=0;1;$i++){
    if(!$i^$y%$x){
      return $i;
    }
  }
}

```

Golfed

```
function b($x,$y){for($i=0;1;$i++){if(!$i^$y%$x)return $i;}

```

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


title: Products of Consecutive Primes

text:
# Question
Title: Products of Consecutive Primes
As of time of submission to the sandbox, I had 17017 reputation, which you will all be able to factorise as 7×11×13×17, a product of 4 consecutive primes.

Please write a function or program to output all the products of two or more consecutive primes up to an input integer `n`. For example, given `n=143` you should output `6, 15, 30, 35, 77, 105, 143` (or equivalent output format).

Normal restrictions on I/O and loopholes apply.

This is , so the shortest program wins.

# Answer
> 6 votes
# Jelly, ~~14~~ 10 bytes

(no doubt there is golfing to do here! - yep...)
-4 bytes thanks to @Dennis - replace check for greater than n by using a range

```
ÆRẆP€ḟÆRfR

```

Note - this is both extremely inefficient *and* the results are unsorted.

Test it at **TryItOnline**

How?

```
ÆRẆP€ḟÆRfR - main link takes an argument, n
ÆR    ÆR   - primes up to n
  Ẇ        - all sublists
   P€      - product for each
     ḟ     - filter out the primes (since the sublists include those of lnegth 1)
        fR - filter out any not in range [1,N]
             (yep, it's calculating all products of primes up to n - gross)

```

# Answer
> 4 votes
# MATL, ~~25~~ 20 bytes

```
Zq&Xf"@gnq?2MpG>~?6M

```

Approach similar to that in Jonathan Allan's answer.

Try it online!

---

### Old version, 25 bytes

```
:YF!"@2<@sq0@0hhdz2=v?X@D

```

This obtains the exponents of prime factor decomposition for all numbers from `1` to the input. For each it checks:

1. If all exponents are less than 2.
2. If the sum of all exponents is greater than 1.
3. The array of exponents is extended with an additional zero on each end. The consecutive differences of the extended array are computed. There should be exactly 2 nonzero differences.

If the three conditions are fulfilled the number is displayed. Results are in incresing order.

# Answer
> 4 votes
# Javascript (ES6), ~~105~~ 104 bytes

```
n=>{for(i=1,P=[];i++<n;P[P.every(v=>i%v)?i:n]=i);P.map(i=>P.map(j=>j>i&&(p*=j)<=n&&console.log(p),p=i))}

```

### Demo

```
var f =
n=>{for(i=1,P=[];i++<n;P[P.every(v=>i%v)?i:n]=i);P.map(i=>P.map(j=>j>i&&(p*=j)<=n&&console.log(p),p=i))}

f(143)
```

# Answer
> 2 votes
# 05AB1E, ~~17~~ 15 bytes

```
L<ØŒ€PD¹>‹ÏDp_Ï

```

**Explanation**

```
L<Ø                 # get the first N primes, where N is the input
   Œ                # get all combinations of consecutive primes
    €P              # calculate the product of these sublists
      D¹>‹Ï         # keep only the products less than or equal to N
           Dp_Ï     # keep only those that aren't prime

```

Try it online!

# Answer
> 1 votes
# Pyth, 18 bytes

```
f}PTftlY.:fP_YSQ)S

```

A program that takes input of an integer on STDIN and prints a list of integers.

Try it online

**How it works**

```
f}PTftlY.:fP_YSQ)S  Program. Input: Q
              SQ    Yield [1, 2, 3, ..., Q]
          fP_Y      Filter that by primality
        .:      )   Yield all sublists of that
    f               Filter the sublists by:
      lY             Length
     t               -1
                    removing sublists of length 1
f                S  Filter [1, 2, 3, ..., Q] (implicit input fill) by:
  PT                 Prime factorisation
 }                   is in the sublists
                    Implicitly print

```

# Answer
> 1 votes
# Jelly, 11 bytes

```
ÆfÆCI=1Ȧµ€T

```

Not the shortest Jelly answer, but this approach is rather efficient and the output is sorted.

Try it online!

### How it works

```
ÆfÆCI=1Ȧµ€T  Main link. Argument: n

        µ€   Map the preceding chain over each k in [1, ..., n].
Æf             Compute all prime factors of k, with multiplicities.
  ÆC           Count the number of primes less than or equal to each prime factor.
               This maps the j-th to j.
    I          Increments; compute the forward differences of consecutive indices.
     =1        Compare each difference with 1.
       Ȧ       All; return 1 iff the array is non-empty and has no zeroes.
          T  Truth; yield all indices for which the chain returned 1.

```

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


title: Hexplosive ASCII-art challenge

text:
# Question
Title: Hexplosive ASCII-art challenge
In the strategy game "Hexplode", players take turns placing tokens on a hexagonal board. Once the number of tokens equals the number of adjacent tiles, that tile *hexplodes*, and moves all of the tokes on it to the surrounding neighbors. You can play the game online here.

I like this game, but sometimes it's hard to know exactly how many tokens go on a specific tile; I'm always *counting* the number of neighbors. It would really convenient if I had an ASCII-art to help me remember how many tokens go on each tile.

You need to write a program or function that takes a positive integer as input, and produces this ASCII representation of hexagon of size **N**. Each tile will be the number of neighbors that tile has. Since 1 is a weird corner case with zero neighbors, you only have to handle inputs larger than 1.

You may take this number in any reasonable format, such as STDIN, function arguments, command-line arguments, from a file, etc. The output may also be in any reasonable format, such as printing to STDOUT, writing to a file, returning a list of strings, a newline separated string, etc.

Here is some sample output for the first 5 inputs:

```
2)

 3 3
3 6 3
 3 3

3)

  3 4 3
 4 6 6 4
3 6 6 6 3
 4 6 6 4
  3 4 3

4)

   3 4 4 3
  4 6 6 6 4
 4 6 6 6 6 4
3 6 6 6 6 6 3
 4 6 6 6 6 4
  4 6 6 6 4
   3 4 4 3

5)

    3 4 4 4 3
   4 6 6 6 6 4
  4 6 6 6 6 6 4
 4 6 6 6 6 6 6 4
3 6 6 6 6 6 6 6 3
 4 6 6 6 6 6 6 4
  4 6 6 6 6 6 4
   4 6 6 6 6 4
    3 4 4 4 3

6)

     3 4 4 4 4 3
    4 6 6 6 6 6 4
   4 6 6 6 6 6 6 4
  4 6 6 6 6 6 6 6 4
 4 6 6 6 6 6 6 6 6 4
3 6 6 6 6 6 6 6 6 6 3
 4 6 6 6 6 6 6 6 6 4
  4 6 6 6 6 6 6 6 4
   4 6 6 6 6 6 6 4
    4 6 6 6 6 6 4
     3 4 4 4 4 3

```

And the pattern continues in a similar manner. As usual, standard loopholes apply, and the answer with the lowest byte-count will be crowned the winner!

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

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

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

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

# Answer
# MATL, ~~39~~ 37 bytes

```
4*3-:!G:+o~YRtP*!tPw4LY)vtI5&lZ+47+*c

```

Try it online! Or verify all test cases.

### Explanation

*I get to use convolution again!*

Consider input `n = 3`. The code first builds a matrix of size `4*n-3`×`n` by adding the column vector `[1; 2; ...; 9]` to the row vector `[1, 2, 3]` with broadcast. This means computing a 2D array array of all pairwise additions:

```
 2  3  4
 3  4  5
 4  5  6
 5  6  7
 6  7  8
 7  8  9
 8  9 10
 9 10 11
10 11 12

```

Replacing even numbers by `1` and odd numbers by `0` gives the checkerboard pattern

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

```

This will be used for generating (part of) the hexagonal grid. Ones will represent points in the grid, and zeros will represent spaces.

The upper-right corner is removed by zeroing out all entries above the main "diagonal" of the matrix:

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

```

Element-wise multiplying this matrix by a vertically flipped version of itself removes the lower-right corner as well. Transposing then gives

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

```

This begins to look like a hexagon. Using symmetry, the grid is extended to produce the upper half:

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

```

Now we need to replace each entry equal to one by the number of neighbours. For this we use convolution with a 3×5 neighbourhood (that is, the kernel is a 3×5 matrix of ones). The result,

```
2 3 4 5 5 5 4 3 2
4 5 7 7 8 7 7 5 4
4 6 7 8 7 8 7 6 4
4 5 7 7 8 7 7 5 4
2 3 4 5 5 5 4 3 2

```

has two issues (which will be solved later):

1. The values have been computed for all positions, whereas we only need them at the positions of the ones in the zero-one grid.
2. For each of those positions, the neighbour count includes the point itself, so it is off by `1`.

The code now adds `47` to each computed value. This corresponds to subtracting `1` to solve issue (2) and adding `48` (ASCII for `'0'`), which converts each number to the code point of its corresponding char.

The resulting matrix is then multiplied by a copy of the zero-one grid. This solves issue (1) above, making the points that are not part of the hexagonal grid equal to zero again:

```
 0  0 51  0 52  0 51  0  0
 0 52  0 54  0 54  0 52  0
51  0 54  0 54  0 54  0 51
 0 52  0 54  0 54  0 52  0
 0  0 51  0 52  0 51  0  0

```

Finally, this array of numbers is cast to a char array. Zero chars are displayed as space, which gives the final result:

```
  3 4 3
 4 6 6 4
3 6 6 6 3
 4 6 6 4
  3 4 3

```
> 11 votes

# Answer
## JavaScript (ES6), ~~118~~ 117 bytes

```
n=>[...Array(m=n+--n)].map((_,i,a)=>a.map((_,j)=>(k=j-(i>n?i-n:n-i))<0?``:k&&++j<m?i/2%n?6:4:3+!i%n).join` `).join`\n`

```

Where `\n` represents a literal newline character. Explanation: Suppose `n=4`. We start with the following space-separated digit square:

```
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0

```

The first `|n-i|` `0`s are deleted, but the spaces remain:

```
   0 0 0 0
  0 0 0 0 0
 0 0 0 0 0 0
0 0 0 0 0 0 0
 0 0 0 0 0 0
  0 0 0 0 0
   0 0 0 0

```

Instant hexagon! It then suffices to calculate the appropriate value in place of each `0` by checking whether we're on the first or last row and/or column. Edit: Saved 1 byte thanks to @Arnauld.
> 15 votes

# Answer
# Python 2, ~~125~~ 123 bytes

```
def h(n):m=n-1;t=[' '*(m-r)+' '.join(('46'[r>0]*(r+m-1)).join('34'[r%m>0]*2))for r in range(n)];print'\n'.join(t+t[-2::-1])

```

Tests are on **ideone**

Runs through the top to the middle rows, `for r in range(n)`, constructing strings:
\- making two corners or two edges, `'34'[r%m>0]*2`;
\- filling by joining them with repeated `'6'` or `'4'`, `'46'[r>0]*(r+m-1)`;
\- joining the corners and edges with `' '`;
\- prepending with spaces, `' '*(m-r)`;

Then prints this and it's reflection in the middle row joined by new lines, `print'\n'.join(t+t[-2::-1])`
> 7 votes

# Answer
## Python 2, 96 bytes

```
n=input();m=n-1
while n+m:n-=1;j=abs(n);c='34'[0<j<m];print' '*j+c+' '+'46  '[j<m::2]*(2*m+~j)+c

```

This looks pretty messy and somewhat golfable...
> 4 votes

# Answer
# Java, ~~375~~ ~~363~~ ~~361~~ ~~339~~ ~~329~~ ~~317~~ 293 bytes

```
interface J{static void main(String[]r){int i=0,k,h=Integer.decode(r[0]),a=1,l,n=0;for(;i++<h*2-1;n+=a){if(n==h-1)a=-1;String s="";for(k=0;k<n+h;k++,s+=" ")s+=n==0?k==0||k==n+h-1?3:4:k!=0&&k!=n+h-1?6:n==h-1?3:4;l=(h*4-3-s.trim().length())/2;System.out.printf((l==0?"%":"%"+l)+"s%s\n","",s);}}}

```

**Ungolfed**

```
interface J {
    static void main(String[] r) {
        int i = 0, k, h = Integer.decode(r[0]), a = 1, l, n = 0;
        for (; i++ < h * 2 - 1; n += a) {
            if (n == h - 1) {
                a = -1;
            }
            String s = "";
            for (k = 0; k < n + h; k++, s += " ") {
                s += n == 0 ? k == 0 || k == n + h - 1 ? 3 : 4 : k != 0 && k != n + h - 1 ? 6 : n == h - 1 ? 3 : 4;
            }
            l = (h * 4 - 3 - s.trim().length()) / 2;
            System.out.printf((l == 0 ? "%" : "%" + l) + "s%s\n", "", s);
        }
    }
}

```

**Usage**:

```
$ java J 5
    3 4 4 4 3
   4 6 6 6 6 4
  4 6 6 6 6 6 4
 4 6 6 6 6 6 6 4
3 6 6 6 6 6 6 6 3
 4 6 6 6 6 6 6 4
  4 6 6 6 6 6 4
   4 6 6 6 6 4
    3 4 4 4 3

```

I am sure that the horrible nested if-else block can be rewritten to be smaller but I can't figure it out at the moment. Any suggestions are welcome :-)

**Update**

* Followed Kevin Cruijssen's suggestion and used decode instead of parseInt.
* Rewrote some ifs by using the ternary operator.
* More ternary operators.
* Moar ternary operators! I think I have created a monster!
* Rewrote the if-else block regarding the printing.
> 3 votes

# Answer
# 05AB1E, 44 bytes

```
FN_i4ë6}ð«¹ÍN+×ðìN_N¹<Q~i3ë4}.ø¹<N-ð×ì})Â¦«»

```

**Explanation**

As the top and bottom of the hexagon are mirrored we only need to generate the upper part.
So for an input of **X** we need to generate **X** rows. That is what the main loop does.

```
F                                        }

```

Then we do the center part of the rows.
This is **4** for the first row and **6** for the rest (as we're only doing the upper part).
We concatenate this number with a space as the pattern will require spacing between numbers.

```
N_i4ë6}ð«

```

We then repeat this string **X-2+N** times, where N is the current row 0-indexed and prepend a space character on the left side.

```
¹ÍN+×ðì

```

After this it's time for the corners. They will be **3** for the first and last row and **4** for the middle rows.

```
N_N¹<Q~i3ë4}.ø

```

Now we need to make sure the rows are lined up correctly by adding spaces to the front of each row. The number of spaces added will be **X-1-N**.

```
¹<N-ð×ì

```

Now that we have the upper part of the grid done, we add the rows to a list, create a reversed copy and remove the first item from that copy (as we only need the central row once), then merge these 2 lists together and print.

```
)Â¦«»

```

Try it online!

**Additional solution, also 44 bytes:**

```
ÍÅ10.øvN_i4ë6}ð«¹ÍN+×ðìyi4ë3}.ø¹<N-ð×ì})Â¦«»

```
> 2 votes

# Answer
# Ruby, 87 bytes

Anonymous function takes n as argument and returns an array of strings.

```
->n{(1-n..n-=1).map{|i|j=i.abs
" "*j+(e=j%n>0?"4 ":"3 ")+["6 ","4 "][j/n]*(2*n-1-j)+e}}

```

**Ungolfed in test program**

Input through stdin. Writes the whole shape to stdout. Pretty self explanatory.

```
f=->n{
  (1-n..n-=1).map{|i|            #reduce n by 1 and iterate i from -n to n
    j=i.abs;                     #absolute magnitude of i
    " "*j+                       #j spaces +
    (e=j%n>0?"4 ":"3 ")+         #start the string with 3 or 4 +
    ["6 ","4 "][j/n]*(2*n-1-j)+  #2*n-1-j 6's or 4`s as appropriate +
    e                            #end the string with another 3 or 4
  }
}

puts f[gets.to_i]

```
> 2 votes

# Answer
# , 60 bytes

```
Àé x@aA4 xr3^.òhYpXa 6^òkyHç^/:m0
Pç 3.*6/^r4$.
òÍ6 4./6

```

Try it online!

This is really way too long. Here is a hexdump, since this contains unprintable characters:

```
0000000: c0e9 2078 4061 4134 201b 7872 335e 2ef2  .. x@aA4 .xr3^..
0000010: 6859 7058 6120 361b 5ef2 6b79 48e7 5e2f  hYpXa 6.^.kyH.^/
0000020: 3a6d 300a 50e7 2033 2e2a 362f 5e72 3424  :m0.P. 3.*6/^r4$
0000030: 2e0a f2cd 3620 9334 852e 2f36            ....6 .4../6

```
> 1 votes

# Answer
# Racket, 487 bytes

```
(λ(n c e o)(let((sp(append(range(- n 1)-1 -1)(reverse(range(- n 1)0 -1))))
(mm(append(range(- n 2)(-(+ n(- n 1))2))(range(-(+ n(- n 1))2)(-(- n 1)2)-1)))
(r""))(for((i sp)(j mm))(define str"")(for((ss i))(set! str(string-append str" ")))
(set! str(string-append str(if(or(= i 0)(= i(- n 1))(= i(* 2(- n 1))))c e)" "))
(for((jj j))(set! str(string-append str(if(= j(- n 2))e o)" ")))(set! r(if(or(= i 0)
(= i(- n 1))(= i(* 2(- n 1))))c e))(set! str(string-append str r))(displayln str))))

```

Testing:

```
(f 4 "3" "4" "6")

   3 4 4 3
  4 6 6 6 4
 4 6 6 6 6 4
3 6 6 6 6 6 3
 4 6 6 6 6 4
  4 6 6 6 4
   3 4 4 3

(f 5 "o" "*" "-")

    o * * * o
   * - - - - *
  * - - - - - *
 * - - - - - - *
o - - - - - - - o
 * - - - - - - *
  * - - - - - *
   * - - - - *
    o * * * o

```

Detailed version:

```
(define(f1 n c e o)
  (let ((sp(append(range(sub1 n) -1 -1)
                  (reverse(range(sub1 n) 0 -1))))
        (mm(append(range(- n 2)(-(+ n(sub1 n)) 2))
                  (range(-(+ n(sub1 n)) 2)(-(sub1 n)2) -1) ))
        (r ""))
    (for((i sp)(j mm))
      (define str "")
      (for((ss i))(set! str(string-append str " ")))
      (set! str(string-append str
                              (if(or(= i 0)(= i(sub1 n))
                                    (= i(* 2(sub1 n)))) c e)
                              " "))
      (for((jj j))
        (set! str(string-append str
                                (if(= j(- n 2)) e o)
                                " ")))
      (set! r(if(or(= i 0)
                   (= i(sub1 n))
                   (= i(* 2(sub1 n)))) c e))
      (set! str(string-append str r))
      (displayln str))))

```
> 1 votes

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


title: Chinese checkerboard

text:
# Question
Title: Chinese checkerboard
The game of Chinese checkers is played on a board with spaces in the shape of a six-pointed star:

Image from Wikipedia

We can create an ASCII-art representation of this board, using `.` for empty spots and the letters `GYORPB` for the six colored starting locations:

```
            G
           G G
          G G G
         G G G G
B B B B . . . . . Y Y Y Y
 B B B . . . . . . Y Y Y
  B B . . . . . . . Y Y
   B . . . . . . . . Y
    . . . . . . . . .
   P . . . . . . . . O
  P P . . . . . . . O O
 P P P . . . . . . O O O
P P P P . . . . . O O O O
         R R R R
          R R R
           R R
            R

```

To make it more interesting, we can also change the size. We'll measure the size of a board by the side length of its triangular starting locations: the board above is size 4.

Since it's really a pain to type all that by hand, let's write a program (or function) to do it!

## Details

Your code should take a positive integer representing the size of the board, via STDIN, ARGV, or function argument. Output the checkerboard pattern to STDOUT (you may alternately return it as a string if your submission is a function).

Output must either

* have no trailing spaces at all, or
* have exactly enough trailing spaces to fill out the pattern to a perfect rectangle of width 6 * *N* \+ 1.

Output may optionally have a trailing newline. No other extra (leading, trailing) whitespace is permitted.

## Examples

Size 1:

```
   G
B . . Y
 . . .
P . . O
   R

```

Size 2:

```
      G
     G G
B B . . . Y Y
 B . . . . Y
  . . . . .
 P . . . . O
P P . . . O O
     R R
      R

```

Size 4:

```
            G
           G G
          G G G
         G G G G
B B B B . . . . . Y Y Y Y
 B B B . . . . . . Y Y Y
  B B . . . . . . . Y Y
   B . . . . . . . . Y
    . . . . . . . . .
   P . . . . . . . . O
  P P . . . . . . . O O
 P P P . . . . . . O O O
P P P P . . . . . O O O O
         R R R R
          R R R
           R R
            R

```

## Scoring

This is : the shortest code in bytes wins.

# Answer
# Ruby, ~~141~~ 127

Returns a rectangular string

```
->n{(-2*n..2*n).map{|i|j=i.abs
k=j>n ?0:j
(([i>0??P:?B]*k+[j>n ?i>0??R:?G:?.]*(2*n+1-j)+[i>0??O:?Y]*k)*" ").center(6*n+1)}*$/}

```

**Ungolfed in test program**

```
f=->n{
  (-2*n..2*n).map{|i|                    #Iterate rows from -2*n to 2*n
    j=i.abs                              #Absolute value of i
    k=j>n ?0:j                           #Value of j up to n: for PBYO
    (                                    #An array of characters forming one line
      ([i>0??P:?B]*k+                    #B or P * (k=j or 0 as appropriate)
       [j>n ?i>0??R:?G:?.]*(2*n+1-j)+    #R,G or . * (2*n+1-j) to form centre diamond
       [i>0??O:?Y]*k                     #O or Y * (k=j or 0 as appropriate)
      )*" "                              #Concatenate the array of characters into a string separated by spaces.
    ).center(6*n+1)                      #pad the string to the full width of the image, adding spaces as necessary.
  }*$/                                   #Concatenate the array of lines into a string separated by newlines.
}

puts f[gets.to_i]

```
> 2 votes

# Answer
## Python 2, 152

```
n=input();x=N=2*n
while~N<x:s='';y=n*3;exec"a=x+y;q=[0,a>N,x-y>N,-x>n,-a>N,y-x>N,x>n,1];s+=' BYROPG.'[q.index(sum(q)<~a%2*3)];y-=1;"*(y-~y);print s;x-=1

```

This is, in retrospect, the wrong approach for Python, but I'm posting it here in case someone can make use of it. Rather than explaining this mess of code, I'll try to say the idea behind it.

The idea is to use triangular coordinates, in which the triangular lattice corresponds to integer triples `(a,b,c)` with `a+b+c=0`.

(Here, the lattice points are drawn as hexagons.)

We can convert Cartesian coordinates to triangular ones as

```
a = (x+y)/2
b = (x-y)/2
c = -x

```

noting that `x` and `y` must have the same parity, or otherwise it's off-checkerboard and we should print a space.

In triangular coordinates, the bounding lines of the six-sided star have equations: `a==n, b==n, c==n, a==-n, b==-n, c==-n`.

So, we can determine what region we're in by which of `[a,b,c,-a,-b,-c]` are greater than `n`.

* If none are, we're in the center and print a dot.
* If exactly one is, we're in one of the six outer triangles, and print the letter corresponding to the index.
* If two or more are, we're outside the board, and print a space.

The bounding rectangle requires that we do this for `x` in the closed interval \[-2\*n,2\*n\] and `y` in the closed interval \[-3\*n,3\*n\].
> 9 votes

# Answer
# Python 2, 140 bytes

```
n=input()
for k in range(4*n+1):x=abs(k-2*n);y=2*n-x;p,q,r=" BP G..R YO "[(k-~k)/(n-~n)::4];print(" "*y+" ".join(p*x+q*-~y+r*x)+" "*y)[n:-n]

```

Not great, but here's my initial bid.

The whitespace rules added a lot of bytes. For comparison, here's a 120 byte Python 3 program which is only correct visually, and doesn't follow the whitespace rules:

```
def f(n):
 for k in range(4*n+1):x=abs(k-2*n);y=2*n-x;p,q,r=" BP G..R YO "[(k-~k)//(n-~n)::4];print(" "*y,*p*x+q*-~y+r*x)

```

And here's my slightly longer recursive 149 byte Python 3 attempt:

```
def f(n,k=0):x=2*n-k;s=" ".join(["B"*x+"."*-~k+"Y"*x,"G"*-~k][k<n]).center(6*n+1);print(s);k<n*2and[f(n,k+1),print(s.translate({71:82,66:80,89:79}))]

```
> 9 votes

# Answer
# Retina, 234 bytes

```
.
P
.+
iP$0$0x$0j$0x$0Px$0kqw
P(?=P*xP*j)
s
P(?=P*j)
R
P(?=P*xP*k)
c
P(?=P*k)
O
x

+`i(s+R+)R
is$1#$1R
+`(s*)P(P*c*)(O*)O(?=k)
$0#s$1$2c$3
j|k
#
s

+`([^#]+#)q(.*)
q$1$2$1
R(?=.*w)
G
P(?=.*w)
B
O(?=.*w)
Y
w[^#]*#|q|i

\w
$0
c
.
 #
#

```

Takes input in unary.

Each line should go to its own file and `#` should be changed to newline in the file. This is impractical but you can run the code as is as one file with the `-s` flag, keeping the `#` markers and maybe changing them to newlines in the output for readability if you wish.

The code has minimal regex-complexity. The main steps in the generation are the followings:

* Create the last `G` line and the first `B.Y` line (delimited by markers `ijk` and actual used letetrs are `RPO`).
* Duplicate the topmost `G` line with a plus space, minus a G until there is only one G.
* Duplicate the bottom `B.Y` line with a plus space and dot, minus a `B` and `Y` until there are no `B` and `Y` left.
* Copy all the lines in reverse order after the current string (with the help of the marker `q`). We keep a marker (`w`) in the middle.
* We change the letters `RPO` to `GBY` if they are before the marker.
* Add the missing in-between spaces.

The results after each of the above points (delimited by `=`'s) for the input `1111 (unary 4)`:

```
1111
==============================
isssssssssRRRRjPPPPcccccOOOOkqw
==============================
issssssssssssR
sssssssssssRR
ssssssssssRRR
sssssssssRRRRjPPPPcccccOOOOkqw
==============================
issssssssssssR
sssssssssssRR
ssssssssssRRR
sssssssssRRRRjPPPPcccccOOOO
sPPPccccccOOO
ssPPcccccccOO
sssPccccccccO
ssssccccccccckqw
==============================
qi            R
           RR
          RRR
         RRRR
PPPPcccccOOOO
 PPPccccccOOO
  PPcccccccOO
   PccccccccO
    ccccccccc
w    ccccccccc
   PccccccccO
  PPcccccccOO
 PPPccccccOOO
PPPPcccccOOOO
         RRRR
          RRR
           RR
i            R
==============================
qi            G
           GG
          GGG
         GGGG
BBBBcccccYYYY
 BBBccccccYYY
  BBcccccccYY
   BccccccccY
    ccccccccc
w    ccccccccc
   PccccccccO
  PPcccccccOO
 PPPccccccOOO
PPPPcccccOOOO
         RRRR
          RRR
           RR
i            R
==============================
            G
           G G
          G G G
         G G G G
B B B B . . . . . Y Y Y Y
 B B B . . . . . . Y Y Y
  B B . . . . . . . Y Y
   B . . . . . . . . Y
    . . . . . . . . .
   P . . . . . . . . O
  P P . . . . . . . O O
 P P P . . . . . . O O O
P P P P . . . . . O O O O
         R R R R
          R R R
           R R
            R

```
> 8 votes

# Answer
# JavaScript (*ES6*) 228

Construction line by line. Incredibly long compared to @Sp3000 that does the same.

Using template string to save 3 more bytes for newlines. All newlines are significant and counted.

```
f=w=>(i=>{r=(n,s=b=' ')=>s.repeat(n),l=c=>(c='GBYPOR'[c])+r(i,b+c),t=n=>r(w*3-i)+l(n)+`
`,s=n=>r(w-1-i)+l(n)+b+r(w+w-i,'. ')+l(n+1)+`
`;for(o='',q=r(w)+r(w+w,'. ')+`.
`;++i<w;o+=t(0))q+=s(3);for(;i--;o+=s(1))q+=t(5)})(-1)||o+q

// LESS GOLFED

u=w=>{
  r =(n,s=b=' ') => s.repeat(n),
  l = c => (c='GBYPOR'[c])+r(i, b+c),
  t = n => r(w*3-i) + l(n) + '\n',
  s = n => r(w-1-i) + l(n) + b + r(w+w-i,'. ') + l(n+1) + '\n',
  o = '',
  q = r(w) + r(w+w,'. ') + '.\n';
  for(i=0; i<w; i++)
    o += t(0), q += s(3);
  for(;i--;)
    o += s(1), q += t(5);
  return o+q
}

go=()=> O.innerHTML=f(I.value|0)

go()
```

```
<input id=I value=5><button onclick='go()'>-></button><br>
<pre id=O></pre>
```
> 4 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity, board-game, hexagonal-grid
---


title: Chuck Norris vs Travelling Salesman

text:
# Question
Title: Chuck Norris vs Travelling Salesman
## Introduction

Almost everyone is familiar with the Travelling Salesman Problem (TSP). The task is to, given a list of `N` cities, find the minimum Hamiltonian cycle which is to say the shortest path that visits each city and comes full-circle back to the start. That is not what this challenge is about. This challenge is to implement Chuck Norris' solution to the TSP:

> Chuck Norris solved the Travelling Salesman problem in `O(1)` time: break salesman into N pieces; kick each piece to a different city.

## Challenge

In order to solve the TSP in this way, we need a sufficiently durable Salesman that won't shy away from frivolities like dismemberment; a number of cities to visit; a set of products to sell; a concrete method for dismemberment; and a calculation for scoring.

## Specification

* **Cities**
    + `N` is the number of cites our Salesman will visit
* **Salesman**
    + The main program or function
    + Written in language `X`
    + With length mod `N` equal to `0`
* **Products**
    + The full names of the elements on the Periodic Table
    + This includes the newly accepted names of elements
* **Dismemberment**
    + Slicing the Salesman into `N` continuous pieces of equal length
    + Each piece is should be a valid function or program in language `X`
* **Output**
    + When executed the Salesman should output `Chuck Norris` and the sliced pieces should each output a distinct product
    + Only extra trailing white space is acceptable
* **Scoring**
    + The length, `L`, of the Salesman in bytes divided by the number of cities, `N`, squared.
    + `Score = L/(N*N)`
    + Smallest score wins
    + Please include 3 significant figures when posting your decimal score

## Examples

1. This Salesman visits 3 cities so `N=3` and and it has a length of 9 so `L=9`. Thus the score for this answer would be `S = 9 / (3 * 3) = 9/9 = 1`.
    * Note that the Salesman and each sliced piece (of which there are 3), should all be valid programs or functions in the same language.

```
Program      -> Output
-------         ------
aaaBBBccc    -> Chuck Norris

aaa          -> Helium
BBB          -> Iridium
ccc          -> Tennessine

```
2. `N=4` and `L=20` so `S=20/16=1.25`

```
Program                 -> Output
-------                    ------
aaaaaBBBBBcccccDDDDD    -> Chuck Norris

aaaaa                   -> Hydrogen
BBBBB                   -> Cadmium
ccccc                   -> Mercury
DDDDD                   -> Iron

```

# Answer
## CJam, L = 1482, N = 114, score 0.114

```
'C:L"arbon"  L'h+:L;"Gold"L'u+:L;"Iron"L'c+:L;"Lead"L'k+:L;"Neon"LS+:L;"Argon"L'N+:L"ickel"L'o+:L;"Zinc""Coppe"L'r+:L"Silve"L'r+:LL'i+:L;"Tin" "Boron"      "Radon"      "Barium"     "Cerium"     "Cesium"     "Cobalt"     "Curium"     "Erbium"     "Helium"     "Indium"     "Iodine"     "Osmium"     "Oxygen"     "Radium"     "Sodium"     "Sulfur"     "Arsenic"    "Bismuth"    "Bohrium"    "Bromine"    "Cadmium"    "Calcium"    "Dubnium"    "Fermium"    "Gallium"    "Hafnium"    "Hassium"    "Holmium"    "Iridium"    "Krypton"    "Lithium"    "Mercury"    "Niobium"    "Rhenium"    "Rhodium"    "Silicon"    "Terbium"    "Thorium"    "Thulium"    "Uranium"    "Yttrium"    "Actinium"   "Aluminum"   "Antimony"   "Astatine"   "Chlorine"   "Chromium"   "Europium"   "Fluorine"   "Francium"   "Hydrogen"   "Lutetium"   "Nihonium"   "Nitrogen"   "Nobelium"   "Platinum"   "Polonium"   "Rubidium"   "Samarium"   "Scandium"   "Selenium"   "Tantalum"   "Thallium"   "Titanium"   "Tungsten"   "Vanadium"   "Americium"  "Berkelium"  "Beryllium"  "Flerovium"  "Germanium"  "Lanthanum"  "Magnesium"  "Manganese"  "Moscovium"  "Neodymium"  "Neptunium"  "Oganesson"  "Palladium"  "Plutonium"  "Potassium"  "Ruthenium"  "Strontium"  "Tellurium"  "Ytterbium"  "Zirconium"  "Dysprosium" "Gadolinium" "Lawrencium" "Meitnerium" "Molybdenum" "Phosphorus" "Promethium" "Seaborgium" "Technetium" "Tennessine" "Californium""Copernicium""Einsteinium""Livermorium""Mendelevium""Roentgenium"]L's+"Xenon"?

```

Try it online!

Each program is 13 bytes long. Here they are split up into individual lines:

```
'C:L"arbon"
L'h+:L;"Gold"
L'u+:L;"Iron"
L'c+:L;"Lead"
L'k+:L;"Neon"
LS+:L;"Argon"
L'N+:L"ickel"
L'o+:L;"Zinc"
"Coppe"L'r+:L
"Silve"L'r+:L
L'i+:L;"Tin"
"Boron"
"Radon"
"Barium"
"Cerium"
"Cesium"
"Cobalt"
"Curium"
"Erbium"
"Helium"
"Indium"
"Iodine"
"Osmium"
"Oxygen"
"Radium"
"Sodium"
"Sulfur"
"Arsenic"
"Bismuth"
"Bohrium"
"Bromine"
"Cadmium"
"Calcium"
"Dubnium"
"Fermium"
"Gallium"
"Hafnium"
"Hassium"
"Holmium"
"Iridium"
"Krypton"
"Lithium"
"Mercury"
"Niobium"
"Rhenium"
"Rhodium"
"Silicon"
"Terbium"
"Thorium"
"Thulium"
"Uranium"
"Yttrium"
"Actinium"
"Aluminum"
"Antimony"
"Astatine"
"Chlorine"
"Chromium"
"Europium"
"Fluorine"
"Francium"
"Hydrogen"
"Lutetium"
"Nihonium"
"Nitrogen"
"Nobelium"
"Platinum"
"Polonium"
"Rubidium"
"Samarium"
"Scandium"
"Selenium"
"Tantalum"
"Thallium"
"Titanium"
"Tungsten"
"Vanadium"
"Americium"
"Berkelium"
"Beryllium"
"Flerovium"
"Germanium"
"Lanthanum"
"Magnesium"
"Manganese"
"Moscovium"
"Neodymium"
"Neptunium"
"Oganesson"
"Palladium"
"Plutonium"
"Potassium"
"Ruthenium"
"Strontium"
"Tellurium"
"Ytterbium"
"Zirconium"
"Dysprosium"
"Gadolinium"
"Lawrencium"
"Meitnerium"
"Molybdenum"
"Phosphorus"
"Promethium"
"Seaborgium"
"Technetium"
"Tennessine"
"Californium"
"Copernicium"
"Einsteinium"
"Livermorium"
"Mendelevium"
"Roentgenium"
]L's+"Xenon"?

```

The missing elements are Darmstadtium, Praseodymium, Protactinium and Rutherfordium which are 12 or 13 characters long which means I can't print them in 13 characters each.

The idea is that the first few programs, which prints the elements with short names use their extraneous characters to build the string `Chuck Norri` in the variable `L`, which does not affect the output when used on their own. The final program then checks if anything is already on the stack, and uses it to choose between `L` (plus `s`) and `Xenon`.

A few additional bytes are saved by using the character we just added to `L` as part of the element name, specifically for `C`arbon, `N`ickel, Coppe`r` and Silve`r`.
> 11 votes

# Answer
# Python, L = 2596, N = 118, Score = 0.186

The length of each slice is **22** so that makes this pretty lengthy.

```
lambda:"Gold"; print"""";print "Carbon     "print   "Thorium     "print   "Curium      "print "Calcium       "print "Nickel        "print      "Zinc     "print    "Neon       "print "Boron         "print   "Iron        "print  "Cerium       "print "Barium        "print "Caesium       """[9::22];lambda:"Tin"[0];lambda:"Lead    "#print"Argon          "print"Radon          "print"Xenon          "print"Erbium         "print"Cobalt         "print"Copper         "print"Helium         "print"Indium         "print"Iodine         "print"Osmium         "print"Oxygen         "print"Radium         "print"Silver         "print"Sodium         "print"Sulfur         "print"Arsenic        "print"Bismuth        "print"Bohrium        "print"Bromine        "print"Cadmium        "print"Dubnium        "print"Fermium        "print"Gallium        "print"Hafnium        "print"Hassium        "print"Holmium        "print"Iridium        "print"Krypton        "print"Lithium        "print"Mercury        "print"Niobium        "print"Rhenium        "print"Rhodium        "print"Silicon        "print"Terbium        "print"Thulium        "print"Uranium        "print"Yttrium        "print"Actinium       "print"Antimony       "print"Astatine       "print"Chlorine       "print"Chromium       "print"Europium       "print"Fluorine       "print"Francium       "print"Hydrogen       "print"Lutetium       "print"Nitrogen       "print"Nobelium       "print"Platinum       "print"Polonium       "print"Rubidium       "print"Samarium       "print"Scandium       "print"Selenium       "print"Tantalum       "print"Thallium       "print"Titanium       "print"Tungsten       "print"Vanadium       "print"Nihonium       "print"Aluminium      "print"Americium      "print"Berkelium      "print"Beryllium      "print"Flerovium      "print"Germanium      "print"Lanthanum      "print"Magnesium      "print"Manganese      "print"Neodymium      "print"Neptunium      "print"Palladium      "print"Plutonium      "print"Potassium      "print"Ruthenium      "print"Strontium      "print"Tellurium      "print"Ytterbium      "print"Zirconium      "print"Moscovium      "print"Oganesson      "print"Dysprosium     "print"Gadolinium     "print"Lawrencium     "print"Meitnerium     "print"Molybdenum     "print"Phosphorus     "print"Promethium     "print"Seaborgium     "print"Technetium     "print"Tennessine     "print"Californium    "print"Copernicium    "print"Einsteinium    "print"Livermorium    "print"Mendelevium    "print"Roentgenium    "print"Darmstadtium   "print"Praseodymium   "print"Protactinium   "print"Rutherfordium  "

```

Here is the Salesman after the slicing and dicing:

```
lambda:"Gold"; print""  # <-- This is a function
"";print "Carbon     "
print   "Thorium     "
print   "Curium      "
print "Calcium       "
print "Nickel        "
print      "Zinc     "
print    "Neon       "
print "Boron         "
print   "Iron        "
print  "Cerium       "
print "Barium        "
print "Caesium       "
""[9::22];lambda:"Tin"  # <-- This is a function and the choke point
[0];lambda:"Lead    "#  # <-- This is a function
print"Argon          "
print"Radon          "
print"Xenon          "
print"Erbium         "
print"Cobalt         "
print"Copper         "
print"Helium         "
print"Indium         "
print"Iodine         "
print"Osmium         "
print"Oxygen         "
print"Radium         "
print"Silver         "
print"Sodium         "
print"Sulfur         "
print"Arsenic        "
print"Bismuth        "
print"Bohrium        "
print"Bromine        "
print"Cadmium        "
print"Dubnium        "
print"Fermium        "
print"Gallium        "
print"Hafnium        "
print"Hassium        "
print"Holmium        "
print"Iridium        "
print"Krypton        "
print"Lithium        "
print"Mercury        "
print"Niobium        "
print"Rhenium        "
print"Rhodium        "
print"Silicon        "
print"Terbium        "
print"Thulium        "
print"Uranium        "
print"Yttrium        "
print"Actinium       "
print"Antimony       "
print"Astatine       "
print"Chlorine       "
print"Chromium       "
print"Europium       "
print"Fluorine       "
print"Francium       "
print"Hydrogen       "
print"Lutetium       "
print"Nitrogen       "
print"Nobelium       "
print"Platinum       "
print"Polonium       "
print"Rubidium       "
print"Samarium       "
print"Scandium       "
print"Selenium       "
print"Tantalum       "
print"Thallium       "
print"Titanium       "
print"Tungsten       "
print"Vanadium       "
print"Nihonium       "
print"Aluminium      "
print"Americium      "
print"Berkelium      "
print"Beryllium      "
print"Flerovium      "
print"Germanium      "
print"Lanthanum      "
print"Magnesium      "
print"Manganese      "
print"Neodymium      "
print"Neptunium      "
print"Palladium      "
print"Plutonium      "
print"Potassium      "
print"Ruthenium      "
print"Strontium      "
print"Tellurium      "
print"Ytterbium      "
print"Zirconium      "
print"Moscovium      "
print"Oganesson      "
print"Dysprosium     "
print"Gadolinium     "
print"Lawrencium     "
print"Meitnerium     "
print"Molybdenum     "
print"Phosphorus     "
print"Promethium     "
print"Seaborgium     "
print"Technetium     "
print"Tennessine     "
print"Californium    "
print"Copernicium    "
print"Einsteinium    "
print"Livermorium    "
print"Mendelevium    "
print"Roentgenium    "
print"Darmstadtium   "
print"Praseodymium   "
print"Protactinium   "
print"Rutherfordium  "

```

---

---

**Update**

* \[16-09-08\] Sublime added an extra space when joining to a line that ends in a comment character
* \[16-09-08\] Made each slice **22** characters long and added gif
> 3 votes

---
Tags: code-challenge, source-layout
---


title: Steps of Permutation

text:
# Question
Title: Steps of Permutation
Write a function which takes a set of integers and prints every permutation of the set, and the swap performed in between each step

### Input

a set of integers, for example (0, 1, 2)

### Output

the list of permutations and swaps in the format (set) (swap) (set) ...

### Test case

```
Input:
(3, 1, 5)

Output:
(3, 1, 5)
(3, 1)
(1, 3, 5)
(3, 5)
(1, 5, 3)
(1, 3)
(3, 5, 1)
(3, 5)
(5, 3, 1)
(3, 1)
(5, 1, 3)

```

### Rules

* You can format the set of numbers however you want.
* You can do the swaps in any order
* You can repeat permutations and swaps in order to get a new one
* Your code doesn't have to actually perform the swaps, the output just needs to show what swap was made between your last output and your current one
* Your code only needs to function for sets with 2 or more elements
* The set you're given will have no repeating elements (e.g. (0, 1, 1, 2) is invalid)

This is code-golf, so shortest code wins!

# Answer
> 3 votes
# Java, ~~449~~ 426 bytes

```
import java.util.*;interface P{static Set s=new HashSet();static void main(String[]a){o(Arrays.toString(a));while(s.size()<n(a.length)){p(a);o(Arrays.toString(a));}}static<T>void o(T z){System.out.println(z);s.add(z);}static int n(int x){return x==1?1:x*n(x-1);}static void p(String[]a){Random r=new Random();int l=a.length,j=r.nextInt(l),i=r.nextInt(l);String t=a[j];a[j]=a[i];a[i]=t;System.out.println("("+a[j]+","+t+")");}}

```

Brute force approach. It keeps making random swaps until all the possible permutations have took place. It uses a Set of the string representation of the array in order to check how many different states have been generated. For n different integers there are n! = 1\*2\*3\*..\*n distinct permutations.

**Update**

* Followed Kevin Cruijssen's suggestions to golf it a bit more.

Ungolfed:

```
import java.util.*;

interface P {

    static Set<String> s = new HashSet<>();

    static void main(String[] a) {
        // prints the original input
        o(Arrays.toString(a));
        while (s.size() < n(a.length)) {
            p(a);
            // prints the array after the swap
            o(Arrays.toString(a));
        }
    }

    static void o(String z) {
        System.out.println(z);
        // adds the string representation of the array to the HashSet
        s.add(z);
    }

    // method that calculates n!
    static int n(int x) {
        if (x == 1) {
            return 1;
        }
        return x * n(x - 1);
    }

    // makes a random swap and prints what the swap is
    static void p(String[] a) {
        Random r = new Random();
        int l = a.length, j = r.nextInt(l), i = r.nextInt(l);
        String t = a[j];
        a[j] = a[i];
        a[i] = t;
        System.out.println("(" + a[j] + "," + t + ")");
    }
}

```

Usage:

```
$ javac P.java
$ java P 1 2 3
[1, 2, 3]
(2,1)
[2, 1, 3]
(1,1)
[2, 1, 3]
(2,2)
[2, 1, 3]
(3,1)
[2, 3, 1]
(3,1)
[2, 1, 3]
(1,2)
[1, 2, 3]
(1,1)
[1, 2, 3]
(3,2)
[1, 3, 2]
(2,3)
[1, 2, 3]
(3,1)
[3, 2, 1]
(3,1)
[1, 2, 3]
(3,3)
[1, 2, 3]
(1,2)
[2, 1, 3]
(1,3)
[2, 3, 1]
(1,2)
[1, 3, 2]
(3,1)
[3, 1, 2]

```

As you can see there are many more swaps than the necessary minimum. But it seems to work :-D

As a bonus, it works with strings too, i.e.

```
$ java P 'one' 'two'
[one, two]
(two,one)
[two, one]

```

# Answer
> 3 votes
# Mathematica, 102 bytes

```
<<Combinatorica`
Riffle[#,BlockMap[Pick[#[[1]],#!=0&/@({1,-1}.#)]&,#,2,1]]&@*MinimumChangePermutations

```

**Examples**

*//Column for a clearer result*

```
%[{1,3,5}]//Column
(*
{1,3,5}
{1,3}
{3,1,5}
{3,5}
{5,1,3}
{5,1}
{1,5,3}
{1,3}
{3,5,1}
{3,5}
{5,3,1}
*)

```

# Answer
> 1 votes
## JavaScript (ES6), 186 bytes

```
f=
a=>{console.log(a);d=a.slice().fill(-1);s=[...d.keys()];for(i=l=a.length;i;)s[k=(j=s.indexOf(--i))+d[i]]<i?(console.log(a[s[j]=s[k]],a[s[k]=i]),console.log(s.map(n=>a[n])),i=l):d[i]*=-1}
;
```

```
<input id=i><input type=button value=Go! onclick=f(i.value.split`,`)>
```

Note: I'm not sure how flexible the output format is, may be I could do this for 171 bytes:

```
a=>{console.log(a);d=a.slice().fill(-1);s=[...d.keys()];for(i=l=a.length;i;)s[k=(j=s.indexOf(--i))+d[i]]<i?console.log(a[s[j]=s[k]],a[s[k]=i],s.map(n=>a[n],i=l)):d[i]*=-1}

```

Works by performing the Steinhaus–Johnson–Trotter algorithm on the shuffle array of indices and translating back to the input array. Ungolfed:

```
function steps(array) {
    console.log(array); // initial row
    var d = a.slice().fill(-1); // direction values
    var s = [...a.keys()]; // initial (identity) shuffle
    var l = a.length;
    for (var i = l; i; ) { // start by trying to move the last element
        var j = s.indexOf(--i);
        var k = j + d[i]; // proposed exchange
        if (s[k] < i) { // only exchange with lower index (within bounds)
            console.log(a[s[k]],a[i]); // show values being exchanged
            s[j] = s[k];
            s[k] = i; // do the exchange on the shuffle
            console.log(s.map(n=>a[n])); // show the shuffled array
            i = l; // start from the last element again
        } else {
            d[i] *= -1; // next time, try moving it the other way
        } // --i above causes previous element to be tried
    } // until no movable elements can be found
}

```

# Answer
> 1 votes
## Ruby, 86 bytes

```
puts (2..(a=gets.scan(/\d+/).uniq).size).map{|i|a.permutation(i).map{|e|?(+e*", "+?)}}

```

# Answer
> 1 votes
# Haskell - 135 bytes

```
p=permutations;f=filter
q(a:b:xs)=(\x->f(uncurry(/=)).zip x)a b:q(b:xs);q _=[]
l=head.f(all((==2).length).q).p.p
f=zip.l<*>map head.q.l

```

output:

```
> f [3,1,5]
[([3,1,5],(3,1)),([1,3,5],(3,5)),([1,5,3],(1,5)),([5,1,3],(1,3)),([5,3,1],(5,3))]

```

I am using the standard `permutations` function, which is not based on swaps, so I am taking the permutations of the permutations and finding one that happens to be a chain of swaps.

---
Tags: code-golf, math, permutations
---


title: Numeric to Alphabetic Organization

text:
# Question
Title: Numeric to Alphabetic Organization
I have a list of images grouped numerically (`YI0.png`, `YI1.png`...`YI20479.png`). I want them sorted alphabetically, like so:

```
YI0.png -> YIA.png
YI1.png -> YIAA.png

```

without my last image having 20479 `A`s in it.

## Input

A directory name.

## Output

All files in that directory will be alphabetically renamed.

## Constraints

* The pattern is always `Prefix` `Number`.`Extension`
* There are no subdirectories
* All files in the directory adhere to the pattern
* `Number` starts at 0
* `Prefix` doesn't contain numbers

## Example

Directory consisting of `Pie0.txt`, `Pie1.txt`, all the way to `Pie11.txt` would be renamed to `PieA.txt`, `PieB.txt`, all the way to `PieL.txt`.

If it goes to `Pie28.txt`, they would be renamed like so:

```
Pie0.txt -> PieA.txt
Pie1.txt -> PieAA.txt
Pie2.txt -> PieAB.txt
Pie3.txt -> PieB.txt
Pie28.txt -> PieZ.txt

```

Remember, this is , so the answer in the shortest bytes wins.

# Answer
# Perl, 65 bytes

Assumes the number sequence starts with 0 and has no holes (or duplicates if there are extra leading zeros). No error checking. Assumes only plain files, filenames do not start with `.` and the user can enter the directory.

Run with the directory as argument

```
alphaorg.pl directory

```

`alphaorg.pl`:

```
#!/usr/bin/perl
chdir pop;$a=A;@F=sort map$a++,<*>;rename$_,s/\d+/$F[$&]/r for<*>

```

If the directory name can't contain digits and your sytem will accept `/` as directory separator (unix and windows do), this 61 byte version is shorter (give directory name on STDIN here):

```
#!/usr/bin/perl -ln
$a=A;@F=sort map$a++,@;=<$_/*>;rename$_,s/\d+/$F[$&]/r for@

```
> 1 votes

# Answer
# Haskell - 97 bytes

I probably picked the wrong language; Haskell has painfully long names for IO operations

```
r p=do f<-getDirectoryContents p;sequence_.zipWith renameFile(sort f).sort$permutations['A'..'Z']

```

*(this program has O(26^26) in run-time unless you're on a quantum computer)*
> 1 votes

---
Tags: code-golf, sorting, file-system
---


# Question
Title: Find every digit from the largest column
Here's a relatively simple challenge for you:

Given a list of positive integers:

* Line them up in a grid, and sum each column. For example, if the input was `[123, 7, 49, 681]`, the grid would look like this:

```
 1  2  3
 7
 4  9
 6  8  1

```

And the sum of each column would be `[18, 19, 4]`:

```
 1  2  3
 7
 4  9
 6  8  1
 --------
 18 19 4

```
* Find the maximum of these sums, which in this case would be 19, and then
* Output every digit that is at the same index as this maximum column. In this case, that would be

```
2
9
8

```

You do not have to output these numbers in any particular order. Note that there are only three outputs, even though we had 4 inputs. In the case of a tie, pick the earliest index. For example, if the input was `[25, 223, 302]`, your grid is:

```
2  5
2  2  3
3  0  2
-------
7  7  5

```

You should output

```
2
2
3

```

You can print these numbers in any format you like. List format, newline separated, space separated, etc. You may not take the input as a 2D array of digits, e.g.

```
[[1, 2, 3],
[7],
[4, 9],
[6, 8, 1]

```

But other than that, you can take input as a list of strings, a list of digits, or any other reasonable format.

You may also assume that all inputs will be valid and contain at least two numbers.

As usual, the shortest answer in bytes wins!

# Test IO:

```
#Input                      #Output
[1, 11, 111, 1111]      --> [1, 1, 1, 1]
[1, 12, 123]            --> [2, 2]
[987654321, 111]        --> [9, 1]
[111, 123456789]        --> [9]
[4, 8, 15, 16, 23, 42]  --> [4, 8, 1, 1, 2, 4]
[4, 8, 12, 26, 27, 38]  --> [2, 6, 7, 8]
[24, 53]                --> [2, 5]
[12, 304, 506]          --> [4, 6]
[30, 285, 121]          --> [0, 8, 2]

```

# Answer
> 6 votes
## Haskell, 63 bytes

```
import Data.Lists
argmax sum.transpose.map(map(read.pure).show)

```

Usage example: `argmax sum.transpose.map(map(read.pure).show) $ [12,304,506]` -\> `[4,6]`.

How it works:

```
                     map                       -- for each number
                         map(read.pure).show   -- turn into list of digits
           transpose                           -- transpose the list of list
argmax sum                                     -- find the element with the
                                               -- largest sum

```

# Answer
> 5 votes
## Jelly, 6 bytes

```
DZṚSÞṪ

```

Try it online!. This is a relatively straightforward implementation of the question.

```
D              Convert each number in the input to a list of digits, e.g.
               [353, 2247] -> [[3, 5, 3], [2, 2, 4, 7]]
 Z             Zip the lists together, e.g. [[3, 2], [5, 2], [3, 4], [7]]
  Ṛ            Reverse the list of lists so that first occurrences are now
               at the end, e.g. [[7], [3, 4], [5, 2], [3, 2]]
   SÞ          Sort by sum - this uses Python's sorted function, which is stable
               so equal elements end up in order of appearance, e.g.
               [[3, 2], [7], [3, 4], [5, 2]]
     Ṫ         Tail - get the last element, e.g. [5, 2]

```

# Answer
> 2 votes
## Ruby, ~~100~~ 97 bytes

```
a=$<.map &:chomp
puts a.map(&:size).max.times.map{|i|a.map{|e|e[i]}.compact}.max_by{|e|eval e*?+}

```

# Answer
> 1 votes
## Javascript (ES6), ~~108~~ ~~103~~ 100 bytes

It's a bit verbose and could probably be golfed some more with a different approach. I wish I could get rid of this `.filter(n=>n)`.

*Saved 5 bytes thanks to Neil*
*Saved 3 bytes thanks to edc65*

```
l=>l.map(n=>[...n].map((d,x)=>(m=(s[x]=(s[x]|0)-d)<m?s[c=x]:m,d)),s=[m=0]).map(n=>n[c]).filter(n=>n)

```

### Demo

```
let f =
l=>l.map(n=>[...n].map((d,x)=>(m=(s[x]=(s[x]|0)-d)<m?s[c=x]:m,d)),s=[m=0]).map(n=>n[c]).filter(n=>n)

console.log(f(["1", "11", "111", "1111"]).join`,`);          // --> [1, 1, 1, 1]
console.log(f(["1", "12", "123"]).join`,`);                  // --> [2, 2]
console.log(f(["987654321", "111"]).join`,`);                // --> [9, 1]
console.log(f(["111", "123456789"]).join`,`);                // --> [9]
console.log(f(["4", "8", "15", "16", "23", "42"]).join`,`);  // --> [4, 8, 1, 1, 2, 4]
console.log(f(["4", "8", "12", "26", "27", "38"]).join`,`);  // --> [2, 6, 7, 8]
console.log(f(["24", "53"]).join`,`);                        // --> [2, 5]
console.log(f(["12", "304", "506"]).join`,`);                // --> [4, 6]
console.log(f(["30", "285", "121"]).join`,`);                // --> [0, 8, 2]
```

# Answer
> 1 votes
# Mathematica 82 bytes

This pads the digits of each number with x's to the right, transposes the matrix, removes the dummy x's, orders by sum of the digits and takes the greatest.

```
SortBy[#~Select~NumberQ&/@Transpose[PadRight[#,30,x]&/@IntegerDigits@#],Tr][[-1]]&

```

---

There ought to be some way to use the superscript-T form of `Transpose` to save a few bytes.

# Answer
> 1 votes
# Perl, ~~49~~ 48 bytes

Includes +1 for `-p`

Run with the input on STDIN, prints to STDOUT the column numbers prefixed by `+`

```
lcolumn.pl
123
7
49
681

```

`lcolumn.pl`:

```
#!/usr/bin/perl -p
s/./@;[@-].="+$&"/eg}{($_)=sort{eval"$b<=>$a"}@

```

# Answer
> 1 votes
# Pyth, ~~5~~ 8 bytes

```
esDsMM.T

```

Takes in input as a list of strings, outputs as a nothing-separated list of digits.

Try it online!

Explanation:

```
      .T  Transpose input to zip together corresponding columns
   sMM    Cast to digit lists
 sD       sort(D) by (s)um
e         take last element, implicitly print

```

# Answer
> 0 votes
# Pyth, 11 bytes

```
h.MsZ.TmjdT

```

A program that takes input of a list of integers on STDIN and prints a list.

Try it online

**How it works**

```
h.MsZ.TmjdT  Program. Input: Q
        j T   Yield the base-10 representation, giving a list of digits
       m d   Map that over Q (implicit input fill)
     .T      Justified transpose, giving each column as a list
 .MsZ        Filter the above by maximum sum
h            First element of above
             Implicitly print

```

# Answer
> 0 votes
# JavaScript (ES6), 90

```
(l,x)=>[...l+0].map((t,i)=>l.map(n=>(n=n[i])&&(v-=n,t.push(n)),v=t=[])|v>=x||(x=v,r=t))&&r

```

```
f=(l,x)=>[...l+0].map((t,i)=>l.map(n=>(n=n[i])&&(v-=n,t.push(n)),v=t=[])|v>=x||(x=v,r=t))&&r

;[
 [[123, 7, 49, 681]       , [2,9,8]]
,[[25, 223, 302]          , [2, 2, 3]]
,[[1, 11, 111, 1111]      , [1, 1, 1, 1]]
,[[1, 12, 123]            , [2, 2]]
,[[987654321, 111]        , [9, 1]]
,[[111, 123456789]        , [9]]
,[[4, 8, 15, 16, 23, 42]  , [4, 8, 1, 1, 2, 4]]
,[[4, 8, 12, 26, 27, 38]  , [2, 6, 7, 8]]
,[[24, 53]                , [2, 5]]
,[[12, 304, 506]          , [4, 6]]
,[[30, 285, 121]          , [0, 8, 2]]]
.forEach(t=>{
  var i=t[0], o=t[1], r, ok
  i=i.map(x=>x+'') // convert i to a string list
  r=f(i)
  ok = (r+'')==(o+'') // compare r and o as comma separated strings
  console.log(ok?'OK':'KO', i+' -> '+ r)

})
```

# Answer
> 0 votes
# Pyth - 9 bytes

```
esD_.TjRT

```

Test Suite.

---
Tags: code-golf, math, grid
---


title: When is their birthday?

text:
# Question
Title: When is their birthday?
Donald Knuth was born in 1938, on the 20th day of Capricorn.
The first day of Capricorn is the 22nd December.
Donald Knuth was born on the 10th of January (1938).

---

**The challenge**

Write a program or function which takes three **inputs** about a person (any other specified order is fine):

* Their (calendar) year of birth (an integer)
* Their sign of the zodiac (a string)
\- may be whichever you choose from the following, so long as it is consistent:
    + all lower case except the first character;
    + all lower case; or
    + all upper case.
* The (1-based) day of the zodiac period on which they were born (an integer)

...and provides two **outputs** (the other order is fine if specified):

* The day of the month on which they were born (an integer)
* Their month of birth (an integer)

**More details**

If your answer were a function, `F`, then for Donald Knuth we would run `F(1938, 'Capricorn', 20)` and receive the output `(10, 1)`

For the purposes of this challenge you do *not* need to shift the zodiac due to the shift between the Gregorian calendar and the tropical year, but you do need to account correctly for leap years.

February has `29` days rather than `28` on leap years.
A year is *usually* a leap year if it is divisible by `4` \- the exceptions are when it is divisible by `100` but not `400` (so, `1600` and `2000` were, whereas `1700`, `1800`, and `1900` were not).

For reference the names of the signs of the zodiac and their inclusive ranges are:

```
Aries       21 March     – 20 April
Taurus      21 April     – 21 May
Gemini      22 May       – 21 June
Cancer      22 June      – 22 July
Leo         23 July      – 22 August
Virgo       23 August    – 23 September
Libra       24 September – 23 October
Scorpio     24 October   – 22 November
Sagittarius 23 November  – 21 December
Capricorn   22 December  – 20 January
Aquarius    21 January   – 19 February
Pisces      20 February  – 20 March

```

This is , so the shortest code in bytes is the aim.
No loopholes, yada yada; you know the drill.

---

**Test cases**

```
Charles Babbage   F(1791, 'Capricorn',  5) -->  (26, 12)
George Boole      F(1815, 'Scorpio',   10) -->  ( 2, 11)
Herman Hollerith  F(1860, 'Pisces',    10) -->  (29,  2)
Vannevar Bush     F(1890, 'Pisces',    20) -->  (11,  3)
Howard H. Aiken   F(1900, 'Pisces',    17) -->  ( 8,  3)  - note 1900 was not a leap year
Donald Knuth      F(1938, 'Capricorn', 20) -->  (10,  1)
<Future Famed>    F(2000, 'Pisces',    17) -->  ( 7,  3)  - note 2000 was a leap year

```

# Answer
> 3 votes
# Javascript (ES6), ~~121~~ ~~120~~ 119 bytes

```
(y,s,d)=>[(d=new Date(y,m=s[2]=='s'?1:'r.sune0oapti'.search(s[4]||0),23+d-'343322110012'[m])).getDate(),d.getMonth()+1]

```

Format for the sign of the zodiac is either:

* all lower case except the first character
* all lower case

### Test cases

```
let f =
(y,s,d)=>[(d=new Date(y,m=s[2]=='s'?1:'r.sune0oapti'.search(s[4]||0),23+d-'343322110012'[m])).getDate(),d.getMonth()+1]

console.log(f(1791, 'Capricorn',  5)); // -->  (26, 12)
console.log(f(1815, 'Scorpio',   10)); // -->  ( 2, 11)
console.log(f(1860, 'Pisces',    10)); // -->  (29,  2)
console.log(f(1890, 'Pisces',    20)); // -->  (11,  3)
console.log(f(1900, 'Pisces',    17)); // -->  ( 8,  3)
console.log(f(1938, 'Capricorn', 20)); // -->  (10,  1)
console.log(f(2000, 'Pisces',    17)); // -->  ( 7,  3)
```

# Answer
> 2 votes
# TSQL, 147 bytes

**Golfed:**

```
DECLARE @ DATETIME='2000',@s char(3)='Pisces',@d INT=17

SELECT @s=CHARINDEX(@s,'  PisAriTauGemCanLeoVirLibScoSagCap')/3,@=DATEADD(m,@s*1,@)+18+substring('101122334432',@s+1,1)*1+@d SELECT day(@),month(@)

```

**Ungolfed:**

```
DECLARE @ DATETIME='2000',@s char(3)='Pisces',@d INT=17

SELECT
  @s=CHARINDEX(@s,'  PisAriTauGemCanLeoVirLibScoSagCap')/3,
  @=DATEADD(m,@s*1,@)+18+substring('101122334432',@s+1,1)*1+@d
SELECT day(@),month(@)

```

**Fiddle**

# Answer
> 1 votes
## Python 3 - ~~333~~ ~~309~~ ~~299~~ ~~240~~ 238 bytes

```
from datetime import*
def f(y,s,d):y=datetime(y,1,1)+timedelta((([[[21,80,111,142,173,235,267,297,327,356]['rsuneoapti'.index(s[4])],51][s[2]=='s'],204][len(s)<4])+d)%(365+[[[0,1][y%4==0],0][y%100==0],1][y%400==0])-2);return y.day,y.month

```

Saved ~~24~~ 26 bytes thanks to @Jonathan Allan

---
Tags: code-golf, date
---