title: Meeting splitter

text:
# Question
Title: Meeting splitter
## Introduction

Large meetings waste working time. Our aim is to split a large meeting into a number of smaller meetings, so the average number topics that a person discusses is minimized but every person has to be in every meeting they are interested in.

## Input

Given is a function from a set of topics \\$T\\$ to a set of persons \\$P\\$ that are interested in this topic $$f:T \rightarrow 2^P$$ and maximum partition size \\$m\\$.

This is encoded as an array of arrays, where element \\$f(i)\\$ contains the topics of person \\$i\\$.

## Test Case

```
m = 3
f = [
[9,7],
[3,7,6,4],
[3,1,2],
[7,5,4,2],
[6,2,8,1,4],
[3,7,2,9,8],
[4,3,2],
[3,4,6],
[1,9,5,3],
[6,4,1,2],
[9,7,3,1],
[1,7,4],
[5,1,7,2],
[5,2,7],
[4,2,6,9],
[6,4,1],
[6,5,9,8],
[9,1],
[9,1,5,6],
[1,2,4,8,7]
]

```

## Output

Find a partition of \\$T\\$ (a split into subsets that are disjoint and that cover the whole set) into $$X = {T\_1, T\_2, \ldots, T\_n}$$ where \\$n\le m\\$, so that the following term is minimized: $$r = \sum\_{T' \in X}{(|(\bigcup\_{t \in T'} f(t))|\times |T'|)} $$

To help understand \\$r\\$, if each topic takes an hour to discuss, then \\$r\\$ is the total amount of person hours required for the meetings.

If there are multiple partition sizes with the same \\$r\\$, \\$n\\$ should be minimized as well.

The output should contain the partition \\$X\\$ as a two-dimensional array, such as: $$X = \[\[0,1,2,3\],\[4,5,6\],\[7,8,9\]\] $$

## Winning Condition

I am looking for the fastest algorithm that finds the absolute minimum \\$r\\$ and \\$n\\$.

If that is not possible in polynomial time, then I am also looking for an polynomial algorithm that has the lowest upper bound on \\$r\\$ in relation to the absolute minimum \\$r\\$ (e.g. double).

# Answer
# R with lpSolve

Turn the problem into an integer linear programming problem with \\$2^t\\$ variables and \\$t+1\\$ constraints, where \\$t\\$ is the number of topics. The cost function is modified by multiplying it with \\$m\\$ and adding the size of the partition. This makes the size of the partition a secondary optimization goal.

```
require("lpSolve")

decode <- function(n) {
  res <- c()
  i <- 1
  while (n>0){
    if (n %% 2 == 1)
      res <- c(res,i)
    i <- i+1
    n <- n %/% 2
  }
  res
}

opt <- function(m,p) {
  nr_pers <- length(p)
  nr_topics <- max(unlist(p))
  x <- array(0,c(nr_topics,nr_pers))
  for (i in 1:nr_pers)
    for (j in 1:length(p[[i]]))
      x[p[[i]][[j]],i] <- 1
  l <- array(0,c(2^nr_topics,nr_pers))
  cb <- rep(0,2^nr_topics)
  w <- rep(1,2^nr_topics)
  mt <- matrix(0,nr_topics+1,2^nr_topics)
  mt[nr_topics+1,1] <- 1
  len <- 1
  for (i in 1:nr_topics) {
    for(j in 1:len) {
      j1 <- len+j
      l[j1,] <- l[j,]+x[i,]
      cb[j1] <- cb[j] + 1
      w[j1] <- m*sum(l[j1,] != 0)*cb[j1]+1
      mt[,j1] <- mt[,j]
      mt[nr_topics+1-i,j1] <- 1
    }
    len <- 2*len
  }
  dir <- c(rep("=",nr_topics),"<=")
  rhs <- c(rep(1,nr_topics),m)
  sol <- lp("min",w,mt,dir,rhs,all.bin=TRUE)$solution
  res <- list()
  j <- 1
  for (i in 1:length(sol))
    if (sol[i]==1) {
      res[[j]] <- decode(i-1)
      j <- j+1
    }
  res
}

# test case
f <- list(
       c(9,7),
       c(3,7,6,4),
       c(3,1,2),
       c(7,5,4,2),
       c(6,2,8,1,4),
       c(3,7,2,9,8),
       c(4,3,2),
       c(3,4,6),
       c(1,9,5,3),
       c(6,4,1,2),
       c(9,7,3,1),
       c(1,7,4),
       c(5,1,7,2),
       c(5,2,7),
       c(4,2,6,9),
       c(6,4,1),
       c(6,5,9,8),
       c(9,1),
       c(9,1,5,6),
       c(1,2,4,8,7))

```

On debian, this needs the package `r-cran-lpsolve`. The code assumes that the topics start with 1 and that each topic number up to the maximum is used. Input and output is as list of vectors, which is not too nice. The test case example is defined in the code, but the list can of course also be entered directly.

To use it, start `R` and then `source` the code file and use the function like this:

```
> source("opt.r")
Loading required package: lpSolve
> opt(3,f)
[[1]]
[1] 1 2 3 4

[[2]]
[1] 6 8

[[3]]
[1] 5 7 9

>

```

So `[[1,2,3,4],[6,8],[5,7,9]]` is an optimal partition for the test case.
> 1 votes

---
Tags: code-challenge, fastest-algorithm
---


title: Golf Paterson's Worms

text:
# Question
Title: Golf Paterson's Worms
Paterson's worms are a kind of cellular automaton that exist on an infinite triangular grid and, every step, they turn in some direction and move one unit. Their defining properties are that they can never go over the same spot twice, and whenever they encounter the same surroundings, they make the same decision. A worm always "sees" from its own perspective with its tail located at 3 and its head located in the center of this hexagon:

For example, consider the worm with the rules:

1. If 0, 1, 2, 4, and 5 are all blank, move in direction 2
2. If 0, 1, 4, and 5 are blank, and 2 is filled, move in direction 0
3. If 0, 1, and 5 are blank, and 2 and 4 are filled, move in direction 0

This results in the following path (from Wikipedia):

If the worm finds itself in a situation where all surroundings are filled, it terminates.

# Input

A list of numbers. The nth number indicates what decision the worm should make on the nth new situation it encounters where it has to make a decision. Note that if all but one of its surroundings are filled, it must move in the only direction that is empty. This does not count as a "decision" and does not consume a number. To generate the example worm shown above, the input would be `[2, 0, 0]`. The input is guaranteed to produce a worm that terminates and does not retrace its path, and the input will never be too short.

# Output

Output a list of coordinates indicating where the head of the worm is, starting at `(1, 0)`. We will consider moving up and to the right to be a decrease in only the y-value, but moving up and to the left to be a decrease in the x-value and a decrease in the y-value. For example, the output of the path for the example input is

```
(1, 0), (1, 1), (0, 0), (-1, -1), (0, -1), (0, 0), (0, 1), (-1, 0), (0, 0)

```

# Test cases

You can use the javascript snippet to run tests as well.

```
[2,0,0]: (1,0),(1,1),(0,0),(-1,-1),(0,-1),(0,0),(0,1),(-1,0),(0,0)
[1,0,4,0,1,5]: (1,0),(2,1),(2,2),(1,2),(0,1),(0,0),(0,-1),(1,-1),(2,0),(2,1),(3,1),(4,2),(4,3),(3,3),(2,2),(1,1),(1,0),(2,0),(3,1),(3,0),(4,0),(5,1),(5,2),(4,2),(3,2),(2,1),(1,1),(0,0),(-1,0),(-2,-1),(-2,-2),(-1,-2),(0,-1),(1,0),(1,-1),(2,-1),(3,0),(4,1),(4,2),(5,3),(5,4),(4,4),(3,3),(3,4),(2,4),(1,3),(1,2),(1,1),(0,1),(-1,0),(-1,1),(-2,1),(-3,0),(-3,-1),(-2,-1),(-1,-1),(0,0)
[1,0,5,1]: (1,0),(2,1),(2,2),(1,2),(0,1),(0,0),(0,-1),(1,-1),(2,0),(2,1),(3,2),(3,3),(2,3),(1,2),(0,2),(-1,1),(-1,0),(0,0),(1,1),(1,2),(1,3),(0,3),(-1,2),(-1,1),(-2,0),(-2,-1),(-1,-1),(0,0)
[2,0,1,0]: (1,0),(1,1),(0,0),(-1,-1),(0,-1),(0,0),(-1,0),(-1,-1),(-1,-2),(0,-1),(1,0),(2,1),(1,1),(0,1),(0,0)

```

The following hastily assembled (possibly buggy) program will display the worms:

```
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");

var input, memory;

var log = str => {
  console.log(str);
  document.querySelector("textarea").value += str + "\n";
};

var orientations = [
  [1, 0],
  [1, 1],
  [0, 1],
  [-1, 0],
  [-1, -1],
  [0, -1]
];

var arena = {
  grid: [[[1, 0, 0]]],
  maxX: 1,
  maxY: 0,
  expandGrid: function() {
    var grid = this.grid;
    var newWidth = grid[0].length + 2,
      newHeight = grid.length + 2;
    var createRow = () => {
      var result = [];
      for (let i = 0; i < newWidth; ++i) result.push([0, 0, 0]);
      return result;
    };
    for (let row of grid) {
      row.push([0, 0, 0]);
      row.unshift([0, 0, 0]);
    };
    grid.push(createRow());
    grid.unshift(createRow());
  },

  gridWidth: function() {
    return this.grid[0].length
  },
  gridHeight: function() {
    return this.grid.length
  },
  get: function(x, y) {
    var colOffset = Math.floor(this.gridWidth() / 2),
      rowOffset = Math.floor(this.gridHeight() / 2);
    return this.grid[y + rowOffset][x + colOffset];
  },
  isAtEnd: function(x, y) {
    var colOffset = Math.floor(this.gridWidth() / 2),
      rowOffset = Math.floor(this.gridHeight() / 2);
    return x === -colOffset || x + colOffset + 1 === this.gridWidth() ||
      y === -rowOffset || y + rowOffset + 1 === this.gridHeight();
  },
  getEdge: function(x, y, o) {
    if (o % 2 === 0) return this.get(x, y)[o / 2];
    else {
      let a, b;
      [a, b] = orientations[(o + 3) % 6];
      return this.get(x - a, y - b)[((o + 3) % 6) / 2];
    }
  },
  setEdge: function(x, y, o) {
    if (Math.abs(x) > this.maxX) this.maxX = Math.abs(x);
    if (Math.abs(y) > this.maxY) this.maxY = Math.abs(y);
    if (o % 2 === 0) {
      if (this.get(x, y)[o / 2]) throw new Error("Path already taken");
      this.get(x, y)[o / 2] = 1;
    } else {
      let a, b;
      [a, b] = orientations[(o + 3) % 6];
      if (this.get(x - a, y - b)[((o + 3) % 6) / 2]) throw new Error("Path already taken");
      this.get(x - a, y - b)[((o + 3) % 6) / 2] = 1;
    }
  }
};

var drawGrid = function(area) {
  var width = canvas.width,
    height = canvas.height;
  ctx.clearRect(0, 0, width, height);
  var gridWidth = arena.gridWidth(),
    gridHeight = arena.gridHeight();
  var triangleLen = Math.floor(Math.min(
    width / (arena.maxX * 2 + arena.maxY),
    height / (arena.maxY * Math.sqrt(3)),
    width / 4
  ));
  var convert = (x, y) => [(x - y / 2) * triangleLen, triangleLen * y * Math.sqrt(3) / 2];
  var drawCirc = function(x, y) {
    var a, b;
    ctx.beginPath();
    [a, b] = convert(x, y);
    ctx.arc(a, b, 5, 0, 2 * Math.PI);
    ctx.fill();
  };
  ctx.fillStyle = "black";
  for (let y = 0; triangleLen * y * Math.sqrt(3) / 2 < height; ++y) {
    for (let x = Math.floor(y / 2); triangleLen * (x - y / 2) < width; ++x) {
      drawCirc(x, y);
    }
  };

  var drawLine = function(a, b, c, d) {
    var x, y;
    ctx.beginPath();
    [x, y] = convert(a, b);
    ctx.moveTo(x, y);
    [x, y] = convert(a + c, b + d);
    ctx.lineTo(x, y);
    ctx.stroke();
  };

  var centerY = Math.round(height / (triangleLen * Math.sqrt(3)));
  var centerX = Math.round(width / (2 * triangleLen) + centerY / 2);
  ctx.fillStyle = "red";
  drawCirc(centerX, centerY);

  for (let row = -(gridHeight - 1) / 2; row < (gridHeight + 1) / 2; ++row) {
    for (let col = -(gridWidth - 1) / 2; col < (gridWidth + 1) / 2; ++col) {
      let lines = arena.get(col, row);
      for (let j = 0; j < lines.length; ++j) {
        if (lines[j]) {
          let or = orientations[2 * j];
          drawLine(col + centerX, row + centerY, or[0], or[1]);
        }
      }
    }
  }
};

var step = function(x, y, absoluteOrientation) {
  log('(' + x + ',' +  y + ')');
  var surroundings = 0;
  for (let i = 0; i < 6; ++i) {
    if (arena.getEdge(x, y, (absoluteOrientation + i) % 6)) {
      surroundings |= (1 << i);
    }
  }
  if (surroundings == 63) {
    console.log("Done!");
    return;
  }
  var action;
  if (memory[surroundings] !== undefined)
    action = memory[surroundings];
  else {
    action = input.shift();
    memory[surroundings] = action;
  }
  absoluteOrientation = (absoluteOrientation + action) % 6;
  arena.setEdge(x, y, absoluteOrientation);
  var or = orientations[absoluteOrientation];
  x += or[0];
  y += or[1];
  if (arena.isAtEnd(x, y)) arena.expandGrid();
  drawGrid(arena);
  setTimeout(function() {
    step(x, y, absoluteOrientation);
  }, parseFloat(document.querySelector("input[type=number]").value));
};

var go = function() {
  input = document.querySelector("input[type=text]").value.split(",").map(x => parseInt(x, 10));
  arena.grid = [[[1, 0, 0]]];
  arena.maxX = 1;
  arena.maxY = 0;
  memory = {};

  for (let i = 0; i < 6; ++i) {
    memory[(~(1 << i)) & 63] = i;
  }

  arena.expandGrid();
  arena.expandGrid();

  step(1, 0, 0);
};

document.querySelector("button").onclick = go;
```

```
canvas {
  border: 1px solid black;
}
```

```
Input: <input type="text" placeholder="Comma separated input"><br />
Delay (ms): <input type="number" placeholder="delay" value="500"/><button>Go</button><br />
<canvas width="500" height="400"></canvas><br />
<textarea></textarea>
```

# Answer
> 4 votes
# JavaScript (ES6),  ~~261 250~~  249 bytes

Takes the input list in reverse order. Returns a list of \\$\[x,y\]\\$ pairs.

```
a=>(G=[[[x=1]]],v=[0,1,1,0,-1,-1],F=y=>[[x,y],...v.every((_,i)=>k^=g(o+i)[q%3]<<i,k=63,g=o=>(r=G[Y=y-o%2*v[q=(o+3)%6]]=G[Y]||[])[X=x-o%2*v[-~q%6]]=r[X]||[])?F(y+v[g(o+=F[k]|=1/F[k]?0:k&~-k?a.pop():31-Math.clz32(k))[q%3]=1,o%6],x+=v[-~o%6]):[]])(o=0)

```

Try it online!

This is essentially a port of the demo snippet.

# Answer
> 4 votes
# K (ngn/k), 115 bytes

```
D,:-D:2\6 3;f:{d::0;m::2/=6;X::(!6),x;{m::?m,p:2/^(+':x)?(2*h:*|x)+/:D 6!d+!6;$[(~p)|^c:X m?p;x;x,,h+D 6!d+:c]}/,1 0}

```

(not counting the function naming part, `f:`)

Try it online!

`D,:-D:2\6 3` generates the six cardinal directions `(1 0;1 1;0 1;-1 0;-1 -1;0 -1)`

`d::0` is the current direction, used as an index mod 6 in `D`

`m::2/=6` generates the initial worm memory `32 16 8 4 2 1`. the bits of each number encode the surroundings (0=visited segment; 1=unvisited). initially `m` contains only unambiguous surroundings - those in which a single exit is available.

`X::(!6),x` are the worm's rules. we prepend `0 1 2 3 4 5` to match the intial unambiguous surroundings in `m`.

`{`...`}/,1 0` apply until convergence the function `{` `}` starting with a 1-element list containing `1 0`. the list will contain pairs of coordinates visited by the worm.

`D 6!d+!6` the six cardinal directions starting from `d` and going around clockwise

`h:*|x` last of the argument, i.e. the position of the worm's head

`(2*h:*|x)+/:D 6!d+!6` multiply the head's coordinates by 2 and add the cardinal directions. this is our way to represent the segments between points.

`+':x` add pairs of adjacent visited points - this gives us the representations of segments between them

`^(`...`)?`... find out which of the head's surrounding segments haven't been visited yet

`p:2/` binary encode and assign to `p`

`m::?m,p` append to `m` and keep the distinct, i.e. append `p` to `m` only if `p` doesn't occur in `m`

`$[`...`;`...`;`...`]` if-then-else

`c:X m?p` find the index of `p` in `m` and use it as an index in `X`. out-of-bounds indexing results in `0N` ("null")

`$[(~p)|^c:X m?p;x;`...`]` if `p` is 0 (no exit path) or `c` is `0N`, then return `x` which will force convergence and stop the loop

`x,,h+D 6!d+:c` else append the new head to `x` and repeat

---
Tags: code-golf, cellular-automata
---


# Question
Title: find the value at kth position when numbers are sorted lexicographically till n
Ex :- Input: n = 12, k = 5

Output: ans = 2

Sorted list S: \["1", "10", "11", "12", "2", "3", "4", "5", ...., "9"\] ans = 2

# Answer
> 1 votes
# Javascript (ES6), 55 bytes

```
(n,i)=>+[...Array(n).keys()].map(x=>x+1+"").sort()[i-1]

```

Try it online!

Unfortunately I can't comment yet, so I'll include it in my answer:

Welcome to PPCG! To make this a challenge you have to clarify some requirements of the challenge. Add a proper description, define the expected output and the winning criteria and also add some example tests.

# Answer
> 1 votes
# , 32 bytes

```
function(n,k)sort(c(1:n,"x"))[k]

```

Try it online!

---
Tags: math, c++
---


# Question
Title: What's the ugliest line of R code that still parses?
The goal is to produce a single line of R code that:

1. Does as little as possible
2. In as many characters as possible (max of 100 characters)
3. And is as ugly as possible (where "ugly" can be taken to mean inefficient computational strategies, extraneous characters such as a terminating semicolon, and so forth).

Do your worst, gentlefolk!

**Objective criteria for winning**

The winning answer will be judged according to the following point scale (the answer with the most points wins):

* Generate a sequence from 0 to 10 (*100 points)*
* In as many characters (N) as possible
    + *0 points* if N=100
    + *N-100 points* if N\<100 (i.e. lose a point for every character under 100)
    + *2(100-N) points* if N\>100 (i.e. lose two points for every character over 100)
* Using as many negative examples from the R Inferno as possible
    + *6 points* per cited example
    + Each example only counts once. This is so because a "heretic imprisoned in \[a\] flaming tomb" can only be so imprisoned one time. Thus two global assignments in your line of code only net you 6 points.

# Answer
## 72 96 characters.

```
`c`<-function(...){list(...)[[-1]];}->>`c`;`[`=0;`]`=10;c(c,c)(c,c)(c,invisible)(`[`[]:`]`[])[];

```

Ugliness:

* Reusing a standard function name
* Using symbols as variable names
* Global assignment
* Right assignment
* Self-redefinition of function
* Unnecessary trailing semicolon(s)
* Unnecessary sub-scripting numbers
* Unnecessary quoting of variable name
* Leaves the workspace in a state which will almost certainly break any subsequent code run

Generates the sequence 0-10 (thanks to Andrie for the idea to do that).

### output:

```
 [1]  0  1  2  3  4  5  6  7  8  9 10

```
> 26 votes

# Answer
Generate a sequence from 0 to 10.

**100 characters**

```
{.=0;for(`~1` in c(1,2,3,4,5,6,7,8,9,10)){.=c(., `~1`,recursive=F)};print(unname(.[drop=T]));rm(.)}
 [1]  0  1  2  3  4  5  6  7  8  9 10

```
> 8 votes

# Answer
**100 characters:** Generate a sequence from 1 to 10.

Note that the numbers 2-10 are NOT in the code... - Bonus points? :-)

Also note that it uses `lapply` for maximum performance :)

```
unlist(lapply(LETTERS[-(11:26)],function(x) as.integer(charToRaw(x))-as.integer(charToRaw('A'))+1L))
#[1]  1  2  3  4  5  6  7  8  9 10

```
> 5 votes

# Answer
### 100 characters

```
assign("a",1:10);b<<-paste(c(a),collapse=";");unlist(lapply(strsplit(b,";")[[1]],function(c)c[[1]]))

```

Not sure if `lapply` on `strsplit` is a negative example but it sure should be.

Returns as a character:

```
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"

```
> 2 votes

# Answer
```
I(cumsum(Reduce("sum", replicate(paste0(as.integer(T),as.integer(T)), T), accumulate=1-F) - T >0))

```

should have slightly less than 100 characters and somehow produce 0:10
> 1 votes

---
Tags: code-challenge, r
---


title: Print coordinates of an NxN grid

text:
# Question
Title: Print coordinates of an NxN grid
Question: Print out all the coordinates of a NxN grid. Preferably in C, however other languages also accepted

**Input**: N (integer)

**Output**: for N=3, a 3x3 grid:

```
0,0
1,0
2,0
0,1
1,1
2,1
0,2
1,2
2,2

```

# Answer
> 5 votes
# C (gcc), ~~83~~ 51 bytes

Saved 32 bytes and fixed output order thanks to Kevin Cruijssen.

```
i;f(n){for(i=0;i<n*n;)printf("%d,%d\n",i++%n,i/n);}

```

Try it online!

I'm by no means a C programmer (or C golfer), but I thought I'd give it a try. Should the main be included in the byte count?

# Answer
> 7 votes
# Japt, 3 bytes

```
o ï

```

Try it

```
o       :Range [0,input)
  ï     :Cartesian product with itself

```

# Answer
> 5 votes
# , ~~33~~ 25 bytes

```
which(diag(scan())|1,T)-1

```

Try it online!

Thanks to Kirill L. for suggesting a 2-byte golf, which inspired me to look further :-)

# Answer
> 3 votes
# 05AB1E, 8 bytes

```
L<ãí',ý»

```

Exactly as the challenge description: prints the 0-indexed coordinates ordered by y-then-x comma- and newline-delimited to STDOUT.

Try it online.

**Explanation:**

```
L          # Create a list in the range [1, (implicit) input]
           #  i.e. 3 → [1,2,3]
 <         # Decrease each by 1 to make the range [0, input)
           #  i.e. [1,2,3] → [0,1,2]
  ã        # Create each possible pair with itself
           #  i.e. [0,1,2] → [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
   í       # Reverse each pair so they're sorted by y-then-x instead of x-then-y
           #  i.e. [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
           #   → [[0,0],[1,0],[2,0],[0,1],[1,1],[2,1],[0,2],[1,2],[2,2]]
    ',ý   '# Join each pair with a space delimiter
           #  i.e. [[0,0],[1,0],[2,0],[0,1],[1,1],[2,1],[0,2],[1,2],[2,2]]
           #   → ["0,0","1,0","2,0","0,1","1,1","2,1","0,2","1,2","2,2"]
       »   # And then join everything with a newline delimiter (and output implicitly)
           #  i.e. ["0,0","1,0","2,0","0,1","1,1","2,1","0,2","1,2","2,2"]
           #   → "0,0\n1,0\n2,0\n0,1\n1,1\n2,1\n0,2\n1,2\n2,2"

```

---

# 05AB1E, 2 bytes

Returns a list of 1-indexed coordinates ordered by x-then-y.

Try it online.

**Explanation:**

```
L     # Create a list in the range [1, (implicit) input]
      #  i.e. 3 → [1,2,3]
 ã    # Create each possible pair with itself (and output implicitly)
      #  i.e. [1,2,3] → [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]

```

# Answer
> 3 votes
# PowerShell, ~~48~~ 42 bytes

```
param($n)0..--$n|%{$i=$_;0..$n|%{"$i,$_"}}

```

Try it online!

Boring double-for loop.

*Saved 6 bytes thanks to mazzy.*

# Answer
> 3 votes
# C#, 59, 65

First time posting. Apologies if I do something wrong!

`l=>{for(int j=0;j<l*l;)System.Console.Write($"{j%l},{j++/l}\n");}`

Try it online! -per Kevin Crujissen's TIO Link.

# Answer
> 2 votes
# Tcl, 70 bytes

```
proc C {n i\ 0} {time {set j 0
time {puts $i,$j
incr j} $n
incr i} $n}

```

Try it online!

# Answer
> 1 votes
# Python 2, 39 bytes

```
lambda n:[(i%n,i/n)for i in range(n*n)]

```

Try it online!

# Answer
> 1 votes
# Pyth, 4 bytes

```
^UQ2

```

Full program. Outputs list of coordinate pairs.

```
^UQ2   Implicit: Q=eval(input())
 UQ    [0-Q)
^  2   Take the cartesian product of the previous result with itself

```

# Answer
> 1 votes
# MathGolf, 2 bytes

```
r■

```

Try it online!

## Explanation

```
r    Range(0, n)
 ■   Cartesian product with self for lists

```

For pretty-printing, you could add `n` to have it print one list item per line.

# Answer
> 1 votes
# APL+WIN, 11 bytes

```
(⍳n)∘.,⍳n←⎕

```

Index origin = 0. Prompts for input for n and outputs the following for n=4:

```
0 0  0 1  0 2  0 3
1 0  1 1  1 2  1 3
2 0  2 1  2 2  2 3
3 0  3 1  3 2  3 3

```

# Answer
> 1 votes
# Pepe, 88 bytes

I've never done 2D iterating in Pepe before and it doesn't seem to work pretty well due to labels being dynamic. There's quite a lot of two byte commands to avoid moving the pointer.

```
REREeErEErerErEReREErEEEErreEEreeeEeEEeerEEeerreEErEEEEEreeEReererEEEEErERRREEEEEeRrEree

```

Try it online!

**Warning:** Do not run it with input below 1 - it will kill your browser.

# Answer
> 1 votes
# Perl 5 `-na`, 35 bytes

```
map{//;say"$',$_"for 0..$F[0]}0..$_

```

Try it online!

# Answer
> 1 votes
# Powershell, 43 bytes

```
param($n)$i--..--$n*++$n|%{$i+=!$_;"$i,$_"}

```

Explanation:

One row `0..$n-1` repeated `$n` times.

# Answer
> 1 votes
# Pure Bash (no external utilities), 35

```
eval echo {0..$[$1-1]},{0..$[$1-1]}

```

Try it online!

# Answer
> 0 votes
# Lua, 63 bytes

```
s=io.read()-1 for i=0,s do for j=0,s do print(i..','..j)end end

```

Try it online!

# Answer
> 0 votes
# Perl5, ~~42~~ 38 bytes

```
for$i(0..--$n){for(0..$n){say"$i,$_"}}

```

(The inner loop saves a few bytes by using the implicit variable "$\_" as an index.)

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


title: Make a zigzag pattern

text:
# Question
Title: Make a zigzag pattern
Your task is to take in one integer input and print a zigzag pattern using slashes and backslashes.

* The integer input determines the length of each zig and zag, as well as the number of zigs and zags
* The pattern always starts from right to left

# Test Cases

```
4->
   /
  /
 /
/
\
 \
  \
   \
   /
  /
 /
/
\
 \
  \
   \
2->
 /
/
\
 \
0->
1->
/
8->
       /
      /
     /
    /
   /
  /
 /
/
\
 \
  \
   \
    \
     \
      \
       \
       /
      /
     /
    /
   /
  /
 /
/
\
 \
  \
   \
    \
     \
      \
       \
       /
      /
     /
    /
   /
  /
 /
/
\
 \
  \
   \
    \
     \
      \
       \
       /
      /
     /
    /
   /
  /
 /
/
\
 \
  \
   \
    \
     \
      \
       \

```

# Answer
# Charcoal, ~~16~~ ~~10~~ 9 bytes

```
ＦＮ«↖Ｉθ→‖Ｔ

```

Try it online! Link is to verbose version of code.
> 10 votes

# Answer
# C (gcc), ~~108~~ ~~102~~ ~~101~~ ~~98~~ ~~80~~ ~~76~~ 72 bytes

* Saved six bytes thanks to Kevin Cruijssen; removing parentheses and golfing `N-n-1` to `N+~n`
* Saved a byte by moving `Z`'s incrementation into the loop condition
* Saved three bytes by using `printf("%c\n",...)` instead of `putchar(...)` and `,puts("")`
* Saved eighteen (!) bytes thanks to HatsuPointerKun; using `printf("%*s",n,"");` to print `n` spaces instead of using a loop `j;for(j=n;j--;)putchar(32);` and combining both `printf(...);` calls
* Saved four bytes by using `printf("%*c",-~n,...);` instead of `printf("%*s%c",n,"",...);`
* Saved four bytes thanks to nwellnhof; moving everything inside one loop instead of two

```
j;f(k){for(j=0;j<k*k;j++)printf("%*c\n",j/k%2?j%k+1:k-j%k,j/k%2?92:47);}

```

Try it online!
> 10 votes

# Answer
# MATL, 17 bytes

```
:"GXy@o?P47}92]*c

```

**Try it online!**

### Explanation

```
:         % Implicit input, n. Push range [1 2 ... n]
"         % For each k in that range
  G       %   Push n again
  Xy      %   Identity matrix of that size
  @       %   Push k
  o?      %   If it's odd
    P     %     Flip the matrix upside down
    47    %     Push 47 (ASCII for '/')
  }       %   Else
    92    %     Push 92 (ASCII for '\')
  ]       %   End
  *       %   Multiply each entry of the matrix by that number
  c       %   Convert to char. Char 0 is shown as space
          % Implicit end. Implicit display

```
> 4 votes

# Answer
# C# (.NET Core), ~~117~~ ~~103~~ 101 bytes

```
a=>{for(int z=a+1,e=0;e<a*a;)System.Console.WriteLine(e++/a%2<1?"/".PadLeft(--z):@"\".PadLeft(z++));}

```

Try it online!
> 4 votes

# Answer
# SOGL V0.12, ~~13~~ ~~12~~ 9 bytes

```
╝F{±↔}P}ø

```

Try it Here!

could be 8 bytes `╝F{±↔}P}` if the 0 test-case wasn't required

Explanation:

```
       }   implicitly started loop repeated input times
╝            create a down-right diagonal of the input
 F           get the current looping index, 1-indexed
  {  }       that many times
   ±↔          reverse the diagonal horizontally
      P      print that
        ø  push an empty string - something to implicitly print if the loop wasn't executed

```
> 3 votes

# Answer
# Python 2, ~~69~~ ~~68~~ 62 bytes

-1 byte thanks to Jonathan Frech

```
lambda n:[[~i,i][i/n%2]%n*' '+'/\\'[i/n%2]for i in range(n*n)]

```

Try it online!
> 3 votes

# Answer
# Mathematica, 84 ~~90~~ bytes

```
(n=#;Grid@Array[If[Abs[n-(s=Mod[#-1,2n])-.5]==#2-.5,If[s<n,"/","\\"],""]&,{n^2,n}])&

```
* *Thank Jenny\_mathy for -6 bytes.*

I have no idea why `\` is obviously darker than `/`.
> 3 votes

# Answer
# Jq 1.5, ~~94~~ 89 bytes

```
["/","\\"][range($n)%2]as$s|range($n)|[(range(if$s=="/"then$n-.-1 else. end)|" "),$s]|add

```

Explanation

```
  ["/","\\"][range($n)%2] as $s                         # for $s= / \ / \ $n times
| range($n)                                             # for .=0 to $n-1
| [(range(if $s=="/" then $n-.-1 else . end)|" "), $s]  # form list of spaces ending with $s
| add                                                   # concatenate

```

Sample Run

```
$ jq -Mnr --argjson n 5 '["/","\\"][range($n)%2]as$s|range($n)|[(range(if$s=="/"then$n-.-1 else. end)|" "),$s]|add'
    /
   /
  /
 /
/
\
 \
  \
   \
    \
    /
   /
  /
 /
/
\
 \
  \
   \
    \
    /
   /
  /
 /
/

```

Try it online!
> 3 votes

# Answer
# Java 8, ~~140~~ ~~134~~ 116 bytes

```
n->{String r="";for(int a=0,b,c;a++<n;)for(b=n;b-->0;r+=a%2>0?"/\n":"\\\n")for(c=b-n+b|-a%2;++c<b;r+=" ");return r;}

```

-24 bytes thanks to *@Nevay*.

**Explanation:**

Try it here.

```
n->{                // Method with integer parameter and String return-type
  String r="";      //  Result-String
  for(int a=0,b,c;  //  Index integers
      a++<n;)       //  Loop (1) from 0 to the input (exclusive)
    for(b=n;        //   Reset `b` to the input
        b-->0;      //   Inner loop (2) from the input to 0 (exclusive)
                    //     After every iteration:
        r+=a%2>0?"/\n":"\\\n")
                    //      Append either of the slashes + a new-line
      for(c=b-n+b|-a%2;++c<b;r+=" ");
                    //    Append the correct amount of spaces
                    //   End of inner loop (2) (implicit / single-line body)
                    //  End of loop (1) (implicit / single-line body)
  return r;         //  Return the result-String
}                   // End of method

```
> 3 votes

# Answer
# Javascript ES8, 83 79 78 76 75 74 71 bytes

\*reduced 1 byte with ES8 thanks to Shaggy

```
A=(m,i=0)=>i<m*m?`/\\`[x=i/m&1].padStart(x?i%m+1:m-i%m)+`
`+A(m,++i):""

```

Test here
> 3 votes

# Answer
# Pyth, 20 bytes

```
Lm+*;dbQjs<*,_y\/y\\

```

Try it online!
> 2 votes

# Answer
# PowerShell, 81 bytes

```
param($a)if($a){1..$a|%{((1..$a|%{" "*--$_+'\'}),($a..1|%{" "*--$_+'/'}))[$_%2]}}

```

Try it online!

Ugh, this is ugly. So much repeated code, plus 7 bytes required to account for `0` special case. *Golfing suggestions welcome.*
> 2 votes

# Answer
# Pyth, 17 bytes

```
js<*_+RV"\/"_B*L;

```

Try it online: Demonstration

### Explanation:

```
js<*_+RV"\/"_B*L;QQQ   implicit Qs at the end
              *L;Q     list with ["", " ", "  ", ..., " "*(input-1)]
            _B         bifurcate with reverse: [["" to "   "], ["   " to ""]]
     +RV"\/"           append to each one either "\" or "/":
                       [["\", to "   \"], ["   /" to "/"]]
    _                  reverse
   *              Q    repeat input times
  <                Q   but only take the first input many
 s                     flatten the list of lists
j                      print on each line

```
> 2 votes

# Answer
# 05AB1E, ~~17~~ 16 bytes

```
F<„/\Nèú.sNƒR}»,

```

Try it online!

**Explanation**

```
F                  # for N in [0 ... input-1] do
  „/\              # push the string "/\"
     Nè            # cyclically index into this string with N
 <     ú           # prepend input-1 spaces to this string
        .s         # get suffixes
          NƒR}     # reverse the list of suffixes input+1 times
              »,   # join on newline and print

```

**Current best attempt using canvas:**

```
F„/\Nè©53NèΛ2®ð«4Λ

```
> 2 votes

# Answer
# Python 3: ~~90 Bytes~~ 82 Bytes

```
lambda n:"\n".join(" "*(abs(i%(n*2)-n+i//n%2)-1)+"/\\"[i//n%2]for i in range(n*n))

```

Thanks to @Jonathan Frech for pointing out that print wasn't needed and that the first zig was the wrong way
> 2 votes

# Answer
## C++, ~~92~~ 91 bytes

-1 bytes thanks to Kevin Cruijssen

```
void m(int n){for(int i=0,j;i<n;++i)for(j=0;j<n;++j)printf("%*c\n",i%2?j+1:n-j,i%2?92:47);}

```

Thanks to the power of the magic `printf`
> 2 votes

# Answer
# Java (OpenJDK 8), ~~131~~ ~~106~~ ~~98~~ ~~96~~ ~~94~~ 91 bytes

```
i->{for(int j=0;j<i*i;System.out.printf("%"+(j/i%2<1?i-j%i:j%i+1)+"c\n",47+45*(j++/i%2)));}

```

Try it online!
> 2 votes

# Answer
# Dyalog APL, ~~39~~ ~~36~~ ~~35~~ 34 bytes

```
{↑((,⍵ ⍵⍴(⌽,⊢)⍳⍵)/¨' '),¨⍵/⍵⍴'/\'}

```

Try it online!

1 byte saved thanks to Zacharý
> 2 votes

# Answer
# Perl 5, 70 + 1 (`-n`) = 71 bytes

```
$n=$_**2;$_=$"x--$_.'/';say&&s% /%/ %||s%\\ % \\%||y%\\/%/\\%while$n--

```

Try it online!
> 1 votes

# Answer
# Excel VBA, ~~84~~ 83 Bytes

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

```
For i=1To[A1]:For j=1To[A1]:?IIf(i mod 2,Space([A1]-j)&"/",Space(j-1)&"\"):Next j,i

```
> 1 votes

# Answer
# Kotlin, 102 bytes

```
(0..q-1).map{r->if(r%2<1)q-1 downTo 0 else{0..q-1}.map{(1..it).map{print(' ')};println('/'+45*(r%2))}}

```

Try it online!
> 1 votes

# Answer
# Jelly, 15 bytes

```
ḶṚ⁶ẋm0ż⁾/\x$ṁ²Y

```

Try it online!

Full program.
> 0 votes

# Answer
# Haskell, ~~86~~ 85 bytes

```
f n=take(n*n)$cycle$[(' '<$[x..n-1])++"/"|x<-[1..n]]++[(' '<$[2..x])++"\\"|x<-[1..n]]

```

Try it online!

*Saved one byte thanks to Laikoni*

Repeat a zig ++ a zag, and take the first `n*n` lines.
> 0 votes

# Answer
# , ~~39 35 33 32~~ 25 bytes

```
' /\'{~[,/@$(|.,:+:)@=@i.

```

Try it online!
> 0 votes

# Answer
# Dyalog APL, ~~41~~ 40 bytes

`⎕IO` must be `0`.

```
{⍪/((⌽⍵ ⍵⍴S↑'/')(⍵ ⍵⍴'\'↑⍨S←⍵+1))[2|⍳⍵]}

```

Try it online!
> 0 votes

# Answer
# , 105 bytes

```
import std.stdio;void m(T)(T n){for(T i,j;i<n;++i)for(j=0;j<n;++j)printf("%*c\n",i%2?j+1:n-j,i%2?92:47);}

```

Try it online!

Lifted from HatsuPointerKun's C++ answer.
> 0 votes

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


title: Trifid Cipher (without keyword)

text:
# Question
Title: Trifid Cipher (without keyword)
## Introduction:

*I have loads of different ciphers stored in a document I once compiled as a kid, I picked a few of the ones I thought were best suitable for challenges (not too trivial, and not too hard) and transformed them into challenges. Most of them are still in the sandbox, and I'm not sure yet whether I'll post all of them, or only a few. Here is the second one (the Computer Cipher was the first one I posted).*

---

For the Trifid Cipher (without using a keyword) the alphabet (and an additional wildcard) is divided into three 3 by 3 tables:

```
table 1:     table 2:     table 3:
 |1 2 3       |1 2 3       |1 2 3
-+-----      -+-----      -+-----
1|a b c      1|j k l      1|s t u
2|d e f      2|m n o      2|v w x
3|g h i      3|p q r      3|y z

```

A text we want to encipher is first character by character encoded into table-row-column numbers. For example, the text `this is a trifid cipher` becomes:

```
        t h i s   i s   a   t r i f i d   c i p h e r
table:  3 1 1 3 3 1 3 3 1 3 3 2 1 1 1 1 3 1 1 2 1 1 2
row:    1 3 3 1 3 3 1 3 1 3 1 3 3 2 3 2 3 1 3 3 3 2 3
column: 2 2 3 1 3 3 1 3 1 3 2 3 3 3 3 1 3 3 3 1 2 2 3

```

We then put everything after one another row by row in the table above in groups of three:

```
311 331 331 332 111 131 121 121 331 331 313 133 232 313 332 322 313 313 132 333 313 331 223

```

And those are transformed back to characters using the same tables:

```
s   y   y   z   a   g   d   d   y   y   u   i   q   u   z   w   u   u   h       u   y   o

```

One thing to note, the input-length should be coprime to 3. So if the length is a multiple of 3, we append one or two trailing spaces to make the input-length not a multiple 3 anymore.

## Challenge:

Given a string `sentence_to_encipher`, encipher it as described above.

You only have to encipher given the `sentence_to_encipher`, so no need to create a deciphering program/function as well. I might make a part 2 challenge for the deciphering in the future however (although I have the feeling it's to trivial/similar to the enciphering process).

## Challenge rules:

* You can assume the `sentence_to_encipher` will only contain letters and spaces.
* You can use either full lowercase or full uppercase (please state which one you've used in your answer).
* You can choose to append either one or two trailing spaces when the input-length is 3 to make it not a multiple of 3 anymore.
* I/O is flexible. Both input and output can be a string, list/array/stream of characters, etc.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Input:            "this is a trifid cipher"
Output:           "syyzagddyyuiquzwuuh uyo"

Input:            "test"
Output:           "utbk"

Input:            "output"
Possible outputs: "rrvgivx" (one space) or "rrzcc lr" (two spaces)

Input:            "trifidcipher"
Possible output:  "vabbuxlzz utr" (one space) or "vabbyzv rx ie " (two spaces)

```

# Answer
# Jelly, ~~29~~ ~~26~~ 25 bytes

```
⁶Øa;3ṗ¤,©Ṛy;⁶$L3ḍƊ¡ZFs3®y

```

Try it online!

### How it works

```
⁶Øa;3ṗ¤,©Ṛy;⁶$L3ḍƊ¡ZFs3®y  Main link. Argument: s (string)

⁶                          Set the return value to space.
 Øa;                       Append it to "a...z".
    3ṗ¤                    Yield the third Cartesian power of [1, 2, 3].
       ,©                  Pair the results and store the pair in the register.
                           The register now holds
                           [[[1, 1, 1], ..., [3, 3, 3]], ['a', ... ,'z', ' '].
         Ṛ                 Reverse the outer array.
           ;⁶$             Append a space to s...
              L3ḍƊ¡        if the length is divisible by 3.
          y                Transliterate according to the mapping to the left.
                   ZFs3    Zip/transpose, flatten, split into chunks of length 3.
                       ®y  Transliterate according to the mapping in the register.

```
> 6 votes

# Answer
# Charcoal, 39 bytes

```
≔Ｅ⁺θ× ¬﹪Ｌθ³⌕βιθ⭆⪪Ｅ⁺÷θ⁹⁺÷θ³θ﹪ι³¦³§⁺β ↨³ι

```

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

```
≔               Assign
   θ            Input string
  ⁺             Concatenated with
                Literal space
    ×           Repeated
         θ      Input string
        Ｌ       Length
       ﹪        Modulo
          ³     Literal 3
      ¬         Logical not
 Ｅ              Mapped over characters
             ι  Current character
           ⌕    Position found in
            β   Lowercase alphabet
              θ To variable

     θ                      List of positions
    ÷                       Vectorised integer divide by
      ⁹                     Literal 9
   ⁺                        Concatenated with
         θ                  List of positions
        ÷                   Vectorised integer divide by
          ³                 Literal 3
       ⁺                    Concatenated with
           θ                List of positions
  Ｅ                         Map over values
             ι              Current value
            ﹪               Modulo
              ³             Literal 3
 ⪪                          Split into
                ³           Groups of 3
⭆                           Map over groups and join
                   β        Lowercase alphabet
                  ⁺         Concatenated with
                            Literal space
                 §          Cyclically indexed by
                       ι    Current group
                     ↨      Converted from
                      ³     Base 3
                            Implicitly print

```
> 6 votes

# Answer
# Python 2, ~~180~~ ~~176~~ ~~174~~ ~~165~~ 163 bytes

```
lambda s:''.join(chr(32+(33+a*9+3*b+c)%59)for a,b,c in zip(*[iter(sum(zip(*[(c/9,c/3%3,c%3)for c in map(o,s+' '[len(s)%3:])]),()))]*3))
o=lambda c:(ord(c)%32-1)%27

```

Try it online!

Input can be upper or lower. Output is uppercase
> 6 votes

# Answer
# Pyth, ~~34~~ 33 bytes

```
m@+G;id3csCmtj+27x+G;d3+W!%lz3zd3

```

Full program. Input is expected as lowercase, output is a character array. Try it online here, or verify all test cases at once here.

```
m@+G;id3csCmtj+27x+G;d3+W!%lz3zd3   Implicit: z=input(), d=" ", G=lowercase alphabet
                           lz       Length of z
                          %  3      The above, mod 3
                        W!          If the above != 3...
                       +      zd    ... append a space to z
           m                        Map the elements of the above, as d, using:
                  +G;                 Append a space to the lowercase alphabet
                 x   d                Find the 0-based index of d in the above
              +27                     Add 27 to the above
             j        3               Convert to base 3
            t                         Discard first element (undoes the +27, ensures result is 3 digits long)
          C                         Transpose the result of the map
         s                          Flatten
        c                       3   Split into chunks of length 3
m                                   Map the elements of the above, as d, using:
     id3                              Convert to decimal from base 3
 @+G;                                 Index the above number into the alphabet + space
                                    Implicit print

```

Alternative 34 byte solution: `sm@+G;id3csCm.[03jx+G;d3+W!%lz3zd3` \- rather than +27 and tail, uses `.[03` to pad with 0 to length 3. Can be 33 if the leading `s` is dropped.

*Edit: saved a byte by dropping leading `s` as character arrays are valid output*
> 6 votes

# Answer
# Ruby, ~~153~~ ~~145~~ ~~138~~ 131 bytes

```
->a{a<<" "if a.size%3<1;a.map{|c|[(b=(c.ord%32-1)%27)/9,b%9/3,b%3]}.transpose.join.scan(/.{3}/).map{|x|((x.to_i(3)+65)%91+32).chr}}

```

Try it online!

A quick and naive approach, works with lowercase text. Inputs and outputs arrays of characters.
> 5 votes

# Answer
# Java (JDK), 192 bytes

```
s->{String T="",R=T,C=T,r=T;for(int c:s){c-=c<33?6:97;T+=c/9;R+=c%9/3;C+=c%3;}for(var S:(s.length%3<1?T+2+R+2+C+2:T+R+C).split("(?<=\\G...)"))r+=(char)((Byte.valueOf(S,3)+65)%91+32);return r;}

```

Try it online!

Very naive approach. Takes a lowercase `char[]` as input but outputs a `String`.

## Explanations

```
s->{                                       // char[]-accepting lambda
 String T="",                              //  declare variables Table as an empty string,
        R=T,                               //                    Row as an empty string,
        C=T,                               //                    Column as an empty string,
        r=T;                               //                    result as an empty string.
 for(int c:s){                             //  for each character
  c-=c<33?6:97;                            //   map each letter to a number from 0 to 25, space to 26.
  T+=c/9;                                  //   append the table-value to Table
  R+=c%9/3;                                //   append the row-value to Row
  C+=c%3;                                  //   append the column-value to Column
 }                                         //
 for(var S:                                //  For each token of...
     (s.length%3<1?T+2+R+2+C+2:T+R+C)      //    a single string out of table, row and column and take the space into account if the length is not coprime to 3...
      .split("(?<=\\G...)"))               //    split every 3 characters
  r+=(char)((Byte.valueOf(S,3)+65)%91+32); //   Parses each 3-characters token into a number, using base 3,
                                           //  and make it a letter or a space
 return r;                                 //  return the result
}

```

## Credits
> 4 votes

# Answer
# , 145 bytes

```
function(s,K=array(c(97:122,32),rep(3,3)))intToUtf8(K[matrix(arrayInd(match(c(utf8ToInt(s),32[!nchar(s)%%3]),K),dim(K))[,3:1],,3,byrow=T)[,3:1]])

```

Try it online!

I/O as strings; adds one space. The strange repetition of `[,3:1]` is because R's natural array indexing is somewhat different.
> 4 votes

# Answer
# APL+WIN, 102 bytes

```
⎕av[n[c⍳(⊂[2]((⍴t),3)⍴,⍉⊃(c←⊂[2]c,(,⍉9 3⍴c←9/⍳3),[1.1]27⍴⍳3)[(⎕av[n←(97+⍳26),33])⍳t←t,(3|⍴t←⎕)↓' '])]]

```

Explanation:

```
t←t,(3|⍴t←⎕)↓' ' Prompts for input and applies coprime condition

(⎕av[n←(97+⍳26),33]⍳ Indices of characters in APL atomic vector

c←⊂[2]c,(,⍉9 3⍴c←9/⍳3),[1.1]27⍴⍳3) Create a matrix of table, row column for 27 characters

⊂[2]((⍴t),3)⍴,⍉⊃ Extract columns of c corresponding to input and re-order

c⍳ Identify Column indices of re-ordered columns

⎕av[.....] Use indices back in atomic vector to give enciphered text

```

Example of screen shot of test case:

```
⎕av[n[c⍳(⊂[2]((⍴t),3)⍴,⍉⊃(c←⊂[2]c,(,⍉9 3⍴c←9/⍳3),[1.1]27⍴⍳3)[(⎕av[n←(97+⍳26),33])⍳t←t,(3|⍴t←⎕)↓' '])]]
⎕:
'output'
rrvgivx

```
> 3 votes

# Answer
# JavaScript (Node.js),  ~~146 141 139~~  136 bytes

I/O is in lowercase.

```
s=>'931'.replace(/./g,d=>Buffer(s.length%3?s:s+0).map(c=>(o=(c>48?c-16:26)/d%3+o*3%27|0,++i)%3?0:(o+97)%123||32),i=o=0).split`\0`.join``

```

Try it online!

### Commented

```
s =>                       // s = input string
  '931'.replace(/./g, d => // for each digit d = 9, 3 and 1:
    Buffer(                //   create a buffer from:
      s.length % 3 ?       //     if the length of s is coprime with 3:
        s                  //       the original input string
      :                    //     else:
        s + 0              //       the input string + an extra '0'
    )                      //
    .map(c =>              //   for each ASCII code c from this Buffer:
      ( o =                //     update o:
        ( c > 48 ?         //       if c is neither a space nor the extra '0':
            c - 16         //         yield c - 16 (which gives 81 .. 106)
          :                //       else:
            26             //         this is the 26th character (space)
        ) / d % 3 +        //       divide by d and apply modulo 3
        o * 3 % 27 | 0,    //       add o * 3, apply modulo 27, coerce to integer
        ++i                //       increment i
      ) % 3 ?              //     if i mod 3 is not equal to 0:
        0                  //       yield 0 (NUL character)
      :                    //     else:
        (o + 97) % 123     //       convert o to the ASCII code of the output letter
        || 32              //       or force 32 (space) for the 26th character
    ),                     //   end of map()
    i = o = 0              //   start with i = o = 0
  ).split`\0`.join``       // end of replace(); remove the NUL characters

```
> 3 votes

# Answer
**SAS, 305 bytes**

A hearty 'oof' for this SAS monstrosity. There's a lot of random string formatting that I thought I could avoid going into this; I'm sure there are better ways of doing some of this.

```
data;input n:&$99.;n=tranwrd(trim(n)," ","{");if mod(length(n),3)=0then n=cats(n,'{');f=n;l=length(n);array a(999);do i=1to l;v=rank(substr(n,i,1))-97;a{i}=int(v/9);a{i+l}=mod(int(v/3),3);a{i+l*2}=mod(v,3);end;f='';do i=1to l*3by 3;f=cats(f,byte(a{i}*9+a{i+1}*3+a{i+2}+97));end;f=tranwrd(f,"{"," ");cards;

```

Input is entered on newlines after the cards statement, like so:

```
data;input n:&$99.;n=tranwrd(trim(n)," ","{");if mod(length(n),3)=0then n=cats(n,'{');f=n;l=length(n);array a(999);do i=1to l;v=rank(substr(n,i,1))-97;a{i}=int(v/9);a{i+l}=mod(int(v/3),3);a{i+l*2}=mod(v,3);end;f='';do i=1to l*3by 3;f=cats(f,byte(a{i}*9+a{i+1}*3+a{i+2}+97));end;f=tranwrd(f,"{"," ");cards;
this is a trifid cipher
test
output
trifidcipher

```

Outputs a dataset containing the output in the variable `f`, along with a bunch of helper variables/array values.

Ungolfed/explanation:

```
data;
input n : & $99.; /* Read a line of input, maximum 99 characters */

n=tranwrd(trim(n)," ","{"); /* Replace spaces with '{' (this is the ASCII character following 'z', so it makes it easy to do byte conversions, and lets us not have to deal with spaces, which SAS does not like) */
if mod(length(n),3)=0then n=cats(n,'{'); /* If length of n is not coprime with 3, add an extra "space" to the end */

f=n; /* Set output = input, so that the string will have the same length */
l=length(n);    /* Get the length of the input */
array a(999);   /* Array of values to store intermediate results */

do i = 1 to l; /* For each character in the input... */
    v = rank(substr(n,i,1))-97; /* Get the value of the current character, from 0-26 */

    a{i}=int(v/9);          /* Get the table of the current character and store at appropriate index, from 0-2  */
    a{i+l}=mod(int(v/3),3); /* Get the row of the current character, from 0-2 */
    a{i+l*2}=mod(v,3);      /* Get the column of the current character, from 0-2  */
end;

f='';

do i = 1 to l*3 by 3; /* For each character in the output... */
    f=cats(f,byte(a{i}*9+a{i+1}*3+a{i+2}+97)); /* Convert values back from base 3 to base 10, and convert back into ASCII value */
end;

f = tranwrd(f,"{"," "); /* Replaces our "spaces" with actual spaces for final output */

/* Test cases */
cards;
this is a trifid cipher
test
output
trifidcipher

```
> 3 votes

# Answer
# 05AB1E, 25 bytes

```
g3Öð×«SAð«3L3ã©‡ø˜3ô®Að«‡

```

Since no one posted a 05AB1E answer yet, I figured I'd post my own solution. I see now it's very similar to *@Dennis♦*' Jelly answer, even though I came up with it independently before I posted the challenge.

Input as string, output as a list of characters. Adds one space if the length is divisible by 3.

Try it online or verify all test cases.

**Explanation:**

```
g3Ö         # Check if the length of the (implicit) input is divisible by 3
            # (results in 1 for truthy or 0 for falsey)
            #  i.e. "out" → 1
            #  i.e. "test" → 0
   ð×       # Repeat a space that many times
            #  i.e. 1 → " "
            #  i.e. 0 → ""
     «      # And append it to the (implicit) input
            #  i.e. "out" and " " → "out "
            #  i.e. "test" and "" → "test"
      S     # Then make the string a list of characters
            #  i.e. "out " → ["o","u","t"," "]
            #  i.e. "test" → ["t","e","s","t"]
A           # Push the lowercase alphabet
 ð«         # Appended with a space ("abcdefghijklmnopqrstuvwxyz ")
   3L       # Push list [1,2,3]
     3ã     # Cartesian repeated 3 times: [[1,1,1],[1,1,2],...,[3,3,2],[3,3,3]]
       ©    # Save that list of triplets in the registry (without popping)
        ‡   # Transliterate, mapping the letters or space to the triplet at the same index
            #  i.e. ["o","u","t"," "] → [[2,2,3],[3,1,3],[3,1,2],[3,3,3]]
            #  i.e. ["t","e","s","t"] → [[3,1,2],[1,2,2],[3,1,1],[3,1,2]]
ø           # Zip, swapping all rows/columns
            #  i.e. [[2,2,3],[3,1,3],[3,1,2],[3,3,3]] → [[2,3,3,3],[2,1,1,3],[3,3,2,3]]
            #  i.e. [[3,1,2],[1,2,2],[3,1,1],[3,1,2]] → [[3,1,3,3],[1,2,1,1],[2,2,1,2]]
 ˜          # Flatten the list
            #  i.e. [[2,3,3,3],[2,1,1,3],[3,3,2,3]] → [2,3,3,3,2,1,1,3,3,3,2,3]
            #  i.e. [[3,1,3,3],[1,2,1,1],[2,2,1,2]] → [3,1,3,3,1,2,1,1,2,2,1,2]
  3ô        # Split it into parts of size 3
            #  i.e. [2,3,3,3,2,1,1,3,3,3,2,3] → [[2,3,3],[3,2,1],[1,3,3],[3,2,3]]
            #  i.e. [3,1,3,3,1,2,1,1,2,2,1,2] → [[3,1,3],[3,1,2],[1,1,2],[2,1,2]]
®           # Push the triplets from the registry again
 Að«        # Push the lowercase alphabet appended with a space again
    ‡       # Transliterate again, mapping the triplets back to letters (or a space)
            # (and output the result implicitly)
            #  i.e. [[2,3,3],[3,2,1],[1,3,3],[3,2,3]] → ["r","v","i","x"]
            #  i.e. [[3,1,3],[3,1,2],[1,1,2],[2,1,2]] → ["u","t","b","k"]

```
> 3 votes

# Answer
# Japt, 42 bytes

```
;Êv3 ?UpS:U
m!bS=iC)®+27 ì3 ÅÃÕc ò3 £SgXì3

```

Try it online!

The core of this answer comes from a deleted answer by Shaggy, but he never came back to handle inputs of length divisible by 3 so this is a fixed version.

Explanation:

```
;                                 #Set C to the string "abcdefghijklmnopqrstuvwxyz"

 Ê                                #Get the length of the input
  v3 ?                            #If it is divisible by 3:
      UpS                         # Add a space
         :U                       #Otherwise don't add a space
                                  #Store the result in U

   S=iC)                          #Set S to C plus a space
m                                 #For each character in U:
 !bS                              # Get the position of that character in S
        ®        Ã                #For each resulting index:
             ì3                   # Convert to base 3
         +27    Å                 # Including leading 0s up to 3 places
                  Õ               #Transpose rows and columns
                   c              #Flatten
                     ò3           #Cut into segments of length 3
                        £         #For each segment:
                           Xì3    # Read it as a base 3 number
                         Sg       # Get the letter from S with that index

```
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), 178 bytes

```
s=>{int[]a={9,3,1},b=(s.Length%3>0?s:s+0).Select(c=>c<97?26:c-97).ToArray();s="";for(int i=0,k,l=b.Length;i<l*3;s+=(char)(k>25?32:97+k))k=a.Sum(p=>b[i%l]/a[i++/l]%3*p);return s;}

```

Try it online!

Less golfed... It's still confusing :)

```
// s is an input string
s=>{
  // powers of 3
  int[]a={9,3,1},
  // ensure the length of s is coprime to 3
  // and convert to numbers from 0-26
  b=(s.Length%3>0?s:s+0).Select(c=>c<97?26:c-97).ToArray();
  // reset s to collect result
  s="";
  // main loop
  for(
    // i is the main index variable
    // k is the value of the encoded character
    // l is the length
    int i=0,k,l=b.Length;
    // i continues until it is 3x the length of the string
    i<l*3;
    // convert k to a character and append
    s+=(char)(k>25?32:97+k)
  )
    // compute the trifid
    // (this is the confusing part :)
    k=a.Sum(p=>b[i%l]/a[i++/l]%3*p);
  // return the result
  return s;
}

```
> 3 votes

---
Tags: code-golf, string, cipher, encoding
---


title: Output an Anagram! No Not That One!

text:
# Question
Title: Output an Anagram! No Not That One!
Given a list of unique strings that are anagrams of each other, output an anagram of those words that is different from each word in the list.

The strings will be alphanumeric, and there is guaranteed to be a valid anagram.

The program or function can, but doesn't have to be non-deterministic, meaning given the same input, multiple running a of the code can yield different outputs, as long as every possible output is a valid one.

### Test Cases

```
[Input] -> Possible output
-----------------
[ab] -> ba
[aba, aab] -> baa
[123, 132, 231, 312, 321] -> 213
[hq999, 9h9q9, 9qh99] -> 999hq
[abcde123, ab3e1cd2, 321edbac, bcda1e23] -> ba213ecd

```

# Answer
# Python 3, 64 bytes

```
lambda a:[*{*permutations(a[0])}-{*a}][0]
from itertools import*

```

Try it online!
> 20 votes

# Answer
# 05AB1E, 5 bytes

```
нœ¹мà

```

Try it online!

### Explanation

```
нœ¹мà

н     // Get the first element of the input list
 œ    // Generate all permutations
  ¹   // Push the input again
   м  // In the permutations list, replace all strings that
      //   are in the input list with empty strings
    à // Pick the string with the greatest lexicographic
      //   index (in this case a non-empty string)

```
> 9 votes

# Answer
# Pyth, 5 bytes

```
h-.ph

```

Try it online!

### Explanation

```
h-.ph
    h    First string in [the input]
  .p     All permutations
 -       Remove those in [the input]
h        First element.

```
> 7 votes

# Answer
# Jelly, 6 bytes

```
XŒ!ḟµḢ

```

Try it online!

1 byte more than the 05AB1E and the Pyth answer.

Explanation:

```
XŒ!ḟµḢ   Main program.
 Œ!      All permutation of...
X        any element from the word list.
   ḟ     Filter out (remove) all the elements in the original word list.
    µ    With the filtered-out list,
     Ḣ   pick the first element.

```

I chosen `X` because it is the shortest way I know to pick any element from the list without altering the list ( and  doesn't work, `ḷ/` and `ṛ/` is longer), and it happens to cause some randomness.

The `µ` here is pretty redundant, but without it, the  would be paired with the , and it is interpreted as "filter out the head of the input", which is not what I need here (what I need is "filter out the input, and get the head").
> 4 votes

# Answer
# Haskell, 58 bytes

*-1 byte and a fix thanks to Laikoni.*

```
import Data.List
f l=[i|i<-permutations$l!!0,all(/=i)l]!!0

```

Try it online!

It's probably not worth importing `Data.List` for permutations but eh.
> 4 votes

# Answer
# Javascript, 118 Bytes

```
function f(a){s=a[0];while(a.indexOf(s)!=-1)s=s.split("").sort(function(){return .5-Math.random()).join("")};return s}

```

uses a bad randomizer to iterate over each "random" permutation.

Probably provably wrong but afaik the bad randomizer just means we wont get true randomness, but will still get every permutation.

Seems to work on all cases in chrome for me but apparently due to undefined behaviour in this sort abuse, it can not work in some browsers.

(Probably very ungolfed feel free to improve it in your own solutions)

# 80 bytes

Thanks to pirateBay's comment -a lot of bytes

-4 bytes thanks to Rick

```
f=a=>eval('s=[...a[0]].sort(()=>.5-Math.random()).join``;a.indexOf(s)<0?s:f(a)')

```
> 4 votes

# Answer
# Ruby, 46 bytes

```
->l{(l[0].chars.permutation.map(&:join)-l)[0]}

```

Try it online!
> 3 votes

# Answer
# Brachylog, 7 bytes

```
hp.¬∈?∧

```

Try it online!

### Explanation

```
hp.        The Output is a permutation of the first element of the Input
  .¬∈?     The Output is not a member of the Input
      ∧    (Disable implicit Input = Output)

```
> 3 votes

# Answer
# Japt, ~~7~~ 6 bytes

*-1 byte thanks to @Shaggy*

```
á kN ö

```

Try it online!

Takes input strings as several inputs instead of as an array. Outputs a random permutation; switch `ö` to `g` to get the first one instead.

## Explanation

```
á kN ö  Implicit input: N = array of input strings
á       Get all permutations of the first input string
  kN    Remove all input strings from those
     ö  Get a random element from the array. Implicit output

```
> 3 votes

# Answer
# Mathematica, 57 bytes

non-deterministic

```
(While[!FreeQ[#,s=""<>RandomSample@Characters@#&@@#]];s)&

```

Try it online!

# Mathematica, 56 bytes

deterministic

```
#&@@Complement[""<>#&/@Permutations@Characters@#&@@#,#]&

```

Try it online!
> 3 votes

# Answer
# Python 3, 78 bytes

```
lambda a:[x for x in permutations(a[0])if~-(x in a)][0]
from itertools import*

```

Try it online!

-1 byte thanks to Mr. Xcoder
> 2 votes

# Answer
# MATL, ~~15~~, ~~13~~, 12 bytes

```
1X)Y@Z{GX-1)

```

Try it online!

Saved 2 bytes thanks to Sanchises. `setdiff(...,'rows')` is shorter than negating `ismember(...,'rows')` and it avoids one duplication. Saved another byte thanks to Luis Mendo, by switching to cells instead of arrays.

### Explanation:

The MATLAB / Octave equivalents are also included.

```
                 % Implicitly grab input x containing cells of strings
1X)              % Get first cell. Equivalent to x{1}
   Y@            % All permutations of first row input. Equivalent to p=perms(y)
      Z{         % Convert the list of permutations to a cell array
        G        % Grab input again
         X-      % setdiff, comparing the input cells with the permutations
           1)    % The first of the results

```

Input must be one the format `{'abc', 'acb'}`.
> 2 votes

# Answer
# Pip, 11 bytes

```
@:_NIgFIPMa

```

Takes the inputs as command-line arguments. Try it online!

### Explanation

```
          a  1st cmdline arg
        PM   List of all permutations
      FI     Filter on this function:
  _NIg         Permutation not in cmdline args
@:           First element of resulting list (with : meta-operator to lower precedence)
             Autoprint

```
> 2 votes

# Answer
# Python 3, 87 bytes

I believe this is the *only* submission so far that uses neither a permutation builtin nor random shuffle/sort. Even though it's longer, I think the algorithm is pretty neat.

```
lambda L:[p for s in L for i,c in enumerate(s)for p in[c+s[:i]+s[i+1:]]if~-(p in L)][0]

```

Try it online!

### Explanation

What we're doing is basically this:

```
def unique_anagram(string_list):
    for string in string_list:
        for i, char in enumerate(string):
            # Move the character to the beginning of the string
            permutation = char + string[:i] + string[i+1:]
            if permutation not in string_list:
                return permutation

```

Here's a proof that it works:

> For a string `S`, define `front(S)` as the set of strings obtained by choosing one character from `S` and moving it to the front of `S`. For example, `front(ABCDE)` is `{ABCDE, BACDE, CABDE, DABCE, EABCD}`.
>
> Now consider a list of anagrams `L`, such that `L` does not contain every possible anagram (as per the problem description). We wish to show that there exists a string `S` in `L` such that `front(S)` contains at least one anagram `S'` that is not in `L`.
>
> Suppose, by way of contradiction, that for every string `S` in `L`, every string in `front(S)` is also in `L`. Observe that we can generate an arbitrary permutation of any string via a series of "fronting" moves. For example, to get
>
> ```
> ABCDE -> BAEDC
>
> ```
>
> we can do
>
> ```
> ABCDE -> CABDE -> DCABE -> EDCAB -> AEDCB -> BAEDC
>
> ```
>
> We have assumed that for each `S` in `L`, every `S'` in `front(S)` is also in `L`. This also means that every `S''` in `front(S')` is in `L`, and so forth. Therefore, if `S` is in `L`, every permutation of `S` is also in `L`. Then `L` must be a complete set of anagrams, a contradiction.
>
> So, since we are guaranteed that there is at least one permutation *not* in `L`, there must exist a string `S` in `L` for which some `S'` in `front(S)` is not in `L`. QED.

The code iterates over `front(S)` for each `S` in `L` and selects an `S'` which is not in `L`. By the above result, there will be at least one `S'` that qualifies.
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~116~~ 96 bytes

```
s=>{for(var g="";;)if(s.All(z=>z!=(g=string.Concat(s[0].OrderBy(t=>Guid.NewGuid())))))return g;}

```

My golfing skills have certainly gotten better since when I first posted this!

Try it online!
> 2 votes

# Answer
# Husk, 6 bytes

```
←-⁰P←⁰

```

Try it online!
> 1 votes

# Answer
## JavaScript (ES7), 172 bytes

```
f=(a,s=a[0],b=[...s],k=b.findIndex((e,i)=>s[i-1]>e))=>a.includes(s)?f(a,(~k?(t=b[k],b[k]=b[l=a.findIndex(e=>e>t)],b[l]=t,b.map((e,i)=>i<k?b[k+~i]:e)):b.reverse()).join``):s

```

Find the first lexicographic permutation of the first element of the array that's not contained in the array.
> 1 votes

# Answer
# Kotlin, 104 bytes

```
{var r=""
do{r=it[0].map{it to Math.random()}.sortedBy{(_,b)->b}.fold("",{a,(f)->a+f})}while(r in it)
r}

```

## Beautified

```
{
    var r = ""
    do {
        r = it[0].map { it to Math.random() }
            .sortedBy { (_, b) -> b }
            .fold("", { a, (f) -> a + f })
    } while (r in it)
    r
}

```

## Test

```
var ana: (List<String>) -> String =
{var r=""
do{r=it[0].map{it to Math.random()}.sortedBy{(_,b)->b}.fold("",{a,(f)->a+f})}while(r in it)
r}

fun main(args: Array<String>) {
    println(ana(listOf("ab")))
}

```
> 1 votes

# Answer
# C++, 169 bytes

```
#import<set>
#import<string>
#import<algorithm>
using S=std::string;S f(std::set<S>l){S s=*l.begin();for(;l.count(s);)std::next_permutation(s.begin(),s.end());return s;}

```

Try it online!
> 1 votes

# Answer
# Scala, 50 bytes

```
(l:Seq[String])=>(l(0).permutations.toSet--l).head

```

Try it online!

### Explanation

```
l(0)         // Take the first anagram
permutations // Built-in to get all permutations
toSet        // Convert to set, required for -- function
-- l         // Remove the original anagrams
head         // Take a random element from the set

```
> 1 votes

# Answer
# **R, 89 bytes**

```
x=scan(,'');repeat{a=paste(sample(el(strsplit(x[1],''))),collapse='');if(!a%in%x)break};a

```

Repeatedly sample the letters from the first entry (as they should be anagrams of each other) and stop when one of those samples is not in the original list.
> 1 votes

# Answer
# PHP, 70 bytes

```
$j=1;while($j){$g=str_shuffle($_GET[0]);$j=in_array($g,$_GET);}echo$g;

```

Run on a webserver, inputting 0 indexed get values or Try it online!

## Ungolfed

```
$j=1; //set truty value
while($j){
    $g=str_shuffle($_GET[0]); //shuffle the first anagram of the set
    $j=in_array($g,$_GET); //see if in the set, if false, the loop ends
}
echo $g;

```
> 1 votes

# Answer
# PHP, ~~58~~ 55 bytes

```
while(in_array($s=str_shuffle($argv[1]),$argv));echo$s;

```

non-deterministic; takes input from command line arguments

Run with `php -r <code>`  follwed by space separated words or try it online.
> 1 votes

# Answer
# Attache, 16 bytes

```
&\S@{!S@_[0]Ø_}

```

Try it online!

## Explanation

```
&\S@{!S@_[0]Ø_}
    {         }    lambda (input: `_`)
        _[0]       first element of the given array
       @           pass to:
     !                 on each permutation:
      S                cast to string
            Ø      without any member of
             _     the input
                   this gives all anagrams not in the input
   @               then
&\S                "first string element"
&                  spread input array over each individual arguments
 \                 tale first argument
  S                as a string

```

## Alternatives

**17 bytes**: `{&\S! !S@_[0]Ø_}`

**18 bytes**: `{&\S! !Id@_[0]Ø_}`

**19 bytes**: `{&\S!(!Id)@_[0]Ø_}`

**26 bytes**: `{&\S!Permutations@_[0]Ø_}`

**26 bytes**: `{&\S!Permutations[_@0]Ø_}`

**26 bytes**: `{(Permutations[_@0]Ø_)@0}`

**26 bytes**: `&\S##~`Ø#Permutations@&\S`

**27 bytes**: `Last@{Permutations[_@0]Ø_}`

**27 bytes**: ``@&0@{Permutations[_@0]Ø_}`

**28 bytes**: `Last##~`Ø#Permutations@&{_}`

**28 bytes**: `Last##~`Ø#Permutations@Last`

**28 bytes**: `First@{Permutations[_@0]Ø_}`

**30 bytes**: `{NestWhile[Shuffle,`in&_,_@0]}`

**33 bytes**: `{If[(q.=Shuffle[_@0])in _,$@_,q]}`

**33 bytes**: `{q.=Shuffle[_@0]If[q in _,$@_,q]}`

**34 bytes**: `{If[Has[_,q.=Shuffle[_@0]],$@_,q]}`
> 1 votes

# Answer
# , 25 bytes

```
((A.~i.@!@#)@{.@:>){.@-.>

```

The input is a list of boxed strings - I felt it was fair like this and not to declare the lists of strings explicitly as 4 8$'abcde123', 'ab3e1cd2', '321edbac', 'bcda1e23'.

I don't like the @ mess in my code, but there are a lot of serialized verbs this time.

How it works:

```
                         >  - unboxes the strings
 (                 )        - left verb of the fork as follows:
             @{.@:>         - unbox and take the first string
  (         )               - finds all permutations of the first string
      i.@!@#                - a list 0 .. the factorial of the length of the 1st string
   A.~                      - anagram index, all permutations
                    {.@-.   - remove the inital strings and take the first of the remaining

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 5 bytes

```
нœIмà

```

Try it online!

# Explanation

```
нœIмà full program with implicit input i
н     push first element of i
 œ    push all permutations
  I   push input i
   м  remove all elements of i from the permutations
    à extract greatest element and print implicitly

```

Pretty much the same answer that @ThePirateBay found.
> 0 votes

# Answer
# JavaScript, 87 bytes

```
a=>eval('for(s=[...a[0]];(a+[]).includes(k=s.sort(a=>~-(Math.random``*3)).join``););k')

```

Try it online!

This answer is based (although heavily modified) on Imme's answer. He suggested in a comment that this should be a different answer.

The problem with the old approach is because `sort` is completely implementation-dependent. The standard doesn't guarantee the order of calling the sort function, therefore theoretically it may never end for the first or the second test case.

This approach is few bytes longer, but it guarantee that it will finish in constrained time, even if `Math.random` never returns `.5`.
> 0 votes

# Answer
# CJam, 11 bytes

```
q~_0=m!\m0=

```

Try it online!

## Explanation

```
q~  e# Read input and evaluate: ["123" "132" "231" "312" "321"]
_   e# Duplicate:               ["123" "132" "231" "312" "321"] ["123" "132" "231" "312" "321"]
0=  e# First:                   ["123" "132" "231" "312" "321"] "123"
m!  e# Permutations:            ["123" "132" "231" "312" "321"] ["123" "132" "213" "231" "312" "321"]
\   e# Swap:                    ["123" "132" "213" "231" "312" "321"] ["123" "132" "231" "312" "321"]
m0  e# Subtract, push 0:        ["213"] 0
    e# (m is used instead of - when in front of a digit)
=   e# Get item:                "213"

```
> 0 votes

# Answer
# Perl 6, 42 bytes

```
{(.[0],*.comb.pick(*).join...*∉$_)[*-1]}

```

Try it online!

Randomly shuffles the first string of the input until it is not an element of the input.

### Explanation:

```
{(.[0],*.comb.pick(*).join...*∉$_)[*-1]}
{                                      }   # Anonymous code block
 (                        ...    )   # Create a sequence
  .[0],   # The first element is the first element of the input
       *.comb.pick(*).join   # Each element is the previous one shuffled
                             *∉$_   # Until it is not in the input
                                  [*-1]   # Return the last element

```
> 0 votes

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


title: Seconds to human readable format

text:
# Question
Title: Seconds to human readable format
Given a positive integer input `n` seconds, output the time in human readable format.

The time will be considered from 00:00:00, 1st January, 1 A.D.

Leap years must be taken into account.

Assume that the gregorian calendar was followed since the beginning.

(Gregorian Calendar: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but these centurial years are leap years if they are exactly divisible by 400. For example, the years 1700, 1800, and 1900 were not leap years, but the years 1600 and 2000 were)

Output must be a string of the format:

```
x Millennia/Millennium, x Centuries/Century, x Decades/Decade, x Years/Year, x Months/Month, x Days/Day, x Hours/Hour, x Minutes/Minute and x Seconds/Second

```

The 0 values must not be shown.

Program must handle at least up to 999 Millennia(inclusive).

Plural/Singular must be kept in mind.

(For millennium, both millennia and millenniums are valid)

`,`,`and` and spaces must also be kept in mind.

Case may be anything.

### Examples:

```
1:1 second
2:2 seconds
60:1 minute
62:1 minute and 2 seconds
3600:1 hour
3661:1 hour, 1 minute and 1 second
31536001:1 year and 1 second
317310301:1 decade, 20 days, 13 hours, 45 minutes and 1 second
3499454714:1 century, 1 decade, 10 months, 22 days, 22 hours, 45 minutes and 14 seconds
73019321114:2 millennia, 3 centuries, 1 decade, 3 years, 10 months, 22 days, 45 minutes and 14 seconds

```

Reference: date-difference to duration converter

This is **code-golf** so shortest code wins

# Answer
> 4 votes
# Perl 6, ~~273 245 233~~ 230 bytes

*-28 bytes thanks to nwellnhof!*

```
{S/rys/ries/}o{S:th(*)/\,/ and/}o{join ', ',map {$_~'s'x(.[0]>1)},grep *[0],(|[R,](.[0].polymod(10 xx 3)),|.skip Z <millennium century decade year month day hour minute second>)}o{~DateTime.new($_-62135596800)~~m:g/\d+/Z-(^6 X<3)}

```

Try it online!

~~I think there might be a trick or two I can use with `EVAL` to make this shorter. This solution takes into account leap seconds, so the last test case is a bit off.~~ Both no longer applicable.

### (Old) Explanation:

```
{                                      } # First code block
 DateTime.new($_-62135596800)  # Initialise a date time object with input amount of seconds
{  ...  }o    # Pass value to the next code block
 fmt(.year-1: "%04d").comb Z   # Zip each digit of the year with
                             <millennium century decade year>  # The appropriate word
 <month day hour minute second>.map:{  ...  }   # For each of these words
                                ".$^a".EVAL     # EVAL the method on the DateTime
                                           -(2>$++)     # -1 if month or day
                                                   ,$a  # Followed by the word itself
  grep +*[0],  # From these, filter out the ones with value 0
  map {$_~'s'x(.[0]>1)},    # Add plurals if greater than 1
  join ', ',                # Join with commas
 {  ...  }o         # Pass string to next code block
  S:th(*)           # Substitute the last instance of
         /\,/       # A comma
            / and/  # With ' and'
 {  ...  }o         # Pass to next code block
  S/rys/ries/       # Fix plural of century

```

# Answer
> 2 votes
# Python 2, ~~304~~ 297 bytes

```
lambda s:' and '.join(', '.join([`n`+' '+d+'s'*(n>1)for n,d in zip([int(str(datetime(1,1,1)+timedelta(0,s))[i:i-~(i>4)])-(2<i<9)for i in[0,1,2,3,5,8,11,14,17]],'millennium century decade year month day hour minute second'.split())if n]).replace('rys','ries').rsplit(', ', 1))
from datetime import*

```

Try it online!

Centuries are annoying...

# Answer
> 2 votes
# Wolfram Language ~~255~~ 251 bytes

If an Oxford comma is acceptable, this works:

```
Row[#,"  "]&/@(Cases[Partition[StringSplit@ToString@UnitConvert[#~Quantity~"Seconds",MixedUnit@{"Millenium","Century", "Decades","Years","Months","Weeks","Days","Hours","Minutes","Seconds"}],2],Except@{"0",_}]/.{a__,{b__}}:> {a,{"and",b}})&

```

`UnitConvert` is used to convert the number of seconds into mixed unit representation.

`Cases` displays only those measures in which the magnitude is not zero.

The remaining functions, `Row`, `Partition`, `ToString` and `StringSplit` merely format the output as required.

`/.{a__,{b_, c_}}:> {a,{"and",b, c}` inserts "and" before the final measure in those answers containing more than one unit of measure.

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

```
f=
(n,r=[],d=new Date(n%31556952e4*1e3-621355968e5),y=d.getUTCFullYear()+(n/31556952e4|0)*1e4-1,g=(u,n=d[`getUTC${u}s`](),p=`s`,s=``)=>(n|=0)&&r.push(n+` `+u+(n>1?p:s)))=>(g(`Millenni`,y/1000,`a`,`um`),g(`Centur`,y/100%10,`ies`,`y`),g(`Decade`,y/10%10),g(`Year`,y%10),g(`Month`,d.getUTCMonth()),g(`Day`,d.getUTCDate()-1),g`Hour`,g`Minute`,g`Second`,g=r.pop(),r[0]?r.join`, `+` and `+g:g)
```

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

# Answer
> 1 votes
# C (gcc) / glibc / Linux / 64 bits, 337 bytes

```
int*gmtime();f(long s){s-=62135596800;int*t=gmtime(&s),y=t[5]+1899,i=10,j=0,c=0,v[]={1,*t,t[1],t[2],t[3]-1,t[4],y%i,y/i%i,y/100%i,y/1e3},l[]={0,"second","minute","hour","day","month","year","decade","centur","millenium"};for(;i--;)v[i]&&(j&&printf("%s%d %s%s%s",c++?i?", ":" and ":"",v[j],l[j],j-8?"":v[j]<2?"y":"ie","s"+(v[j]<2)),j=i);}

```

Try it online!

### Explanation

```
int*gmtime();  // Declare gmtime
f(long s){     // Function taking seconds as long
  s-=62135596800;   // Subtract constant for 0001-01-01
  int
    *t=gmtime(&s),  // Break down time
    y=t[5]+1899,    // Years since 1 AD
    i=10,
    j=0,
    c=0,
    v[]={  // Values
      1,        // Sentinel
      *t,       // Seconds
      t[1],     // Minutes
      t[2],     // Hours
      t[3]-1,   // Month days
      t[4],     // Months
      y%i,      // Years
      y/i%i,    // Decades
      y/100%i,  // Centuries
      y/1e3     // Milleniums
    },
    // Labels
    l[]={0,"second","minute","hour","day","month","year","decade","centur","millenium"};
  for(;i--;)  // Loop from i=9 to 0
    v[i]&&(     // If current value not 0 (or sentinel reached)
      j&&printf("%s%d %s%s%s",  // Print if previous index not 0
                c++?i?", ":" and ":"",  // Separator
                v[j],  // Value
                l[j],  // Label
                j-8?"":v[j]<2?"y":"ie",  // Handle century/centuries
                "s"+(v[j]<2)),  // Plural
      j=i  // Remember index
    );
}

```

---
Tags: code-golf
---


title: Iron particles around a magnet

text:
# Question
Title: Iron particles around a magnet
There are some iron particles on a board. We pass a current carrying wire through that board and the particles form circles. Show these circles if input given is the position of the wire.

Consider the board to be a grid of size 7x7 (fixed)

No extra white spaces are allowed.

Input can be 0-indexed or 1-indexed. (0-indexed in examples)

### Examples

```
input:3,3 # 'X' is wire here but can be shown by anything other than '\/|-'
output:
/-----\
|/---\|
||/-\||
|||X|||
||\-/||
|\---/|
\-----/

input:1,2
output:
|/-\|||
||X||||
|\-/|||
\---/||
-----/|
------/
-------

input:0,0
output:
X||||||
-/|||||
--/||||
---/|||
----/||
-----/|
------/

input:0,3
output:
|||X|||
||\-/||
|\---/|
\-----/
-------
-------
-------

input:3,0
output:
---\|||
--\||||
-\|||||
X||||||
-/|||||
--/||||
---/|||

```

This is **code-golf** so shortest code wins.

# Answer
> 7 votes
# , 40 bytes

```
7 7{.6 6&-|.0":<^:6@8[9!:7@'/_\___\_/|-'

```

Try it online!

# Answer
> 5 votes
# , ~~136~~ ~~119~~ 116 bytes

```
function(i,j,m=diag(7),R=row(m)-i,a=j-col(m)){m[]='-'
m[R==a]='\\'
m[R==-a]='/'
m[R<a&R>-a|R>a&-R>a]='|'
m[i,j]=0
m}

```

Try it online!

* -3 bytes saved thanks to @Giuseppe

Function that takes (row,col) coordinates of the wire (1-indexed) and returns a 7x7 matrix with the characters.

# Answer
> 4 votes
# Canvas, ~~27~~ ~~23~~ ~~22~~ 21 bytes

```
-７×［\＋］↶ω⟳ｎ↔┼⁷⁸╵７７＠↕↔

```

Try it here!

# Answer
> 1 votes
# JavaScript (ES7),  ~~105~~  103 bytes

Takes input as `(y)(x)`, 0-indexed.

```
Y=>X=>(g=x=>y<7?`/\\-|X
`[h=(X-x)**2,v=(Y-y)**2,x<7?h<v?2:h>v?3:h?x<X^y<Y:4:5]+g(x<7?x+1:!++y):'')(y=0)

```

Try it online!

# Answer
> 1 votes
# Perl 6, 90 bytes

```
{<| v - \ X />[1+([-]($_>>.abs).sign||3+[*]($_).sign)for ^7-$^a X ^7-$^b].rotor(7)>>.join}

```

Try it online!

Anonymous code block that takes two numbers and returns a list of lines.

# Answer
> 1 votes
# Python 2, 105 bytes

```
lambda x,y:[''.join(['/-|'[cmp(abs(i-x),abs(j-y))],'\X'[i==x]][i-x==y-j]for j in R)for i in R]
R=range(7)

```

Try it online!

# Answer
> 0 votes
# Charcoal, 21 bytes

```
ＧL⁷-↙⁶X‖Ｂ↘¬‖Ｊ±Ｎ±ＮＴ⁷¦⁷

```

Try it online! Takes 0-indexed column and row as input. Explanation:

```
ＧL⁷-

```

Draw a triangle of `-`s.

```
↙⁶

```

Draw a line along the hypotenuse. (This is the wrong way around but we'll fix that later.)

```
X

```

Draw the `X` that shows the position of the wire. (Any other ASCII character could be used here of course.) This completes one eighth of the drawing.

```
‖Ｂ↘¬

```

Reflect three times (`¬` = left + down) while transforming characters to almost complete the diagram.

Reflect without transforming to switch the `/`s with the `\`s so they now point around the `X` instead of towards it.

```
Ｊ±Ｎ±Ｎ

```

Jump to the top left of the desired output.

```
Ｔ⁷¦⁷

```

Trim the result to the desired size.

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


title: Tips for golfing in Clean

text:
# Question
Title: Tips for golfing in Clean
What general tips do you have for golfing in Clean? Please post only ideas that can be applied to code golf problems in general, and are at least somewhat specific to Clean.

If you've never heard of Clean, you can find out more here.
Or, you can join the chat room.

# Answer
> 10 votes
## Avoid `import StdEnv` when possible

To access built-in functions, even seemingly basic ones like `(==)` or `map`, an import statement is needed, usually `import StdEnv` because it imports the most common modules like `StdInt`, `StdBool` and so on (see here for more info on `StdEnv`).

However it can be possible to avoid this import for some challenges and just use the core language features like list comprehensions and pattern matching.

For example, instead of

```
import StdEnv
map f list

```

one can write

```
[f x\\x<-list]

```

### List of alternatives:

Some functions or function invocations that need `import StdEnv`, an alternative that does not need the import and a rough estimate of bytes saved.

* `hd` -\> `(\[h:_]=h)`, ~6 bytes
* `tl` -\> `(\[_:t]=t)`, ~6 bytes
* `map f list` -\> `[f x\\x<-list]`, ~10 bytes
* `filter p list` -\> `[x\\x<-list|p x]`, ~11 bytes
* `(&&)` -\> `%a b|a=b=a;%`, ~6 bytes
* `(||)` -\> `%a b|a=a=b;%`, ~6 bytes
* `not` -\> `%a|a=False=True;%`, ~1 byte
* `and` -\> `%[a:r]|a= %r=a;%_=True`, ~0 bytes
* `or` -\> `%[a:r]|a=a= %r;%_=False`, ~0 bytes

The last few are unlikely to actually save bytes, because a direct replacement yields more bytes than the import, but it might be possible in cases where the recursion over the list is needed anyway.

This tip has successfully been used here.

# Answer
> 5 votes
# Know how to learn the language

After all, how can anyone golf in a language they can't use!

**Online**

Clean isn't a well-known or well-documented language, and the name certainly doesn't make it easy to find much-needed resources to remedy these issues... or does it?

Clean was originally called *Concurrent Clean*, which is still used in the preface of almost every document related to Clean - so if you're looking for Clean, look for Concurrent Clean instead.

One of Clean's more remarkable similarities to Haskell (of which there are many) is the existence of Cloogle, which is a function search-engine covering the libraries that Clean ships with.

**Locally**

The libraries that Clean ships with are in the form of decently-commented, somewhat self-documenting Clean source files, which are able to be browsed through using the IDE.
(It also comes with full example programs, under `$INSTALL/Examples`.)

Speaking of which, the Windows version of Clean comes with an IDE - while it is fairly limited by modern standards, it's worlds better than using a text editor and the command-line.
The two most useful features (in the context of learning) are:

* You can double-click an error to see which line it's on
* You can highlight a module name and press `[Ctrl]+[D]` to open the definition file (or use `[Ctrl]+[I]` for the implementation file), and toggle between the definition and implementation file with `[Ctrl]+[/]`

# Answer
> 4 votes
# Forget about character encoding

Clean's compiler doesn't care about what encoding you think you've saved the source file as, just about the byte values in the file. This has some neat consequences.

In the body of the source code, only bytes with code-points corresponding to the printable ASCII characters are allowed, in addition to those for `\t\r\n`.

**Literals:**

In `String` and `[Char]` literals (`"stuff"` and `['stuff']` respectively), *any bytes except 0* are allowed, with the caveat that `"` and `'` must be escaped (for `String` and `[Char]` respectively), and that newlines and carraige returns *must* be replaced with `\n` and `\r` (also respectively).

In `Char` literals, *any byte except 0* is permitted, meaning that:

```
'\n'

```

#

```
'
'

```

Are the same, but the second is one byte shorter.

**Escaping:**

Other than the standard letter escapes `\t\r\n` (etc.), all non-numeric escape sequences in Clean are either for the slash, or for the quote used to delimit the literal the escape is inside.

For numeric escape sequences, the number is treated as an octal value terminated after three digits. This means that if you want a null followed by the character `1` in a `String`, you need to use `"\0001"` (or `"\0\61"`) and *not* `"\01"`. However, if you follow the escape with anything *but* numbers, you can omit the leading zeroes.

**Consequences:**

This quirk with how Clean handles its source files allows `String` and `['Char']` to effectively become sequences of base-256 single-digit numbers - which has a multitude of uses for code-golf, such as storing indexes (up to 255, of course).

# Answer
> 3 votes
# Name functions with symbols

When defining a function, it is often shorter to use some combination of `!@$%^&*~-+=<:|>.?/\` than to use alphanumeric characters, because it allows you to omit white-space between identifiers.

For example: `?a=a^2` is shorter than `f a=a^2`, and invoking it is shorter as well.

**However**:

If the function identifier is used adjacent to *other* symbols, which can combine to form a *different, but valid* identifier, they will all be parsed as one identifier and you'll see an error.

For example: `?a+?b` parses as `? a +? b`

**Additionally:**

It is possible to overwrite imported identifiers in Clean, and so the only single-character symbol identifiers that aren't already used in `StdEnv` are `@$?`. Overwriting `^-+` (etc.) can be useful if you need more symbolic identifiers, but be wary that you don't overwrite one you're using.

# Answer
> 3 votes
# Know your ~~K~~nodes

Some of the strongest constructs (for golfing) in functional languages are `let ... in ...`.
Clean of course, has this, and something better - the `#`.

**What is a node?**

Clean's `#`, and the ubiquitous `|` (pattern guard) are both known as 'node expressions'.
Notably, they allow you to program imperatively-*ish* in Clean (which is really good here!).

**The `#` (let-before):**

These both compute the value of an integer given as a string, multiplied by the sum of its chars

```
f s=let i=toInt s;n=sum[toInt c\\c<-:s]in n*i

```

#

```
f s#i=toInt s
#s=sum[toInt c\\c<-:s]
=s*i

```

Note how the version with `#` is shorter, and how we can redefine `s`. This is useful if we don't need the value that a variable has when we receive it, so we can just re-use the name. (`let` can run into issues when you do that)

But using `let` is easier when you need something like `flip f = let g x y = f y x in g`

**The `|` (pattern guard):**

Clean's pattern guard can be used like those in many other functional languages - however it can also be used like an imperative `if ... else ...`. And a shorter version of the ternary expression.

For example, these all return the sign of an integer:

```
s n|n<>0|n>0=1= -1
=0

```

#

```
s n=if(n<>0)if(n>0)1(-1)0

```

#

```
s n|n>0=1|n<0= -1=0

```

Of course, the last one which uses the guard more traditionally is the shortest, but the first one shows that you can nest them (but only two unconditional return clauses can appear on the same line in layout rule), and the second shows what the first one does logically.

***A note:***

You can use these expressions basically anywhere. In lambdas, `case ... of`, `let ... in`, etc.

# Answer
> 1 votes
# Use shorter lambdas

Sometimes you find yourself using a lambda expression (to pass to `map`, or `sortBy`, etc.). When you're doing this (writing lambdas), there's a bunch of ways you can do it.

**The right way:**

This is `sortBy`, with an idiomatic lambda sorting lists from longest to shortest

```
sortBy (\a b = length a > length b)

```

**The other right way:**

If you're using `Data.Func`, you can also do

```
sortBy (on (>) length)

```

**The short way:**

This is the same thing, but with a golfier syntax

```
sortBy(\a b=length a>length b)

```

**The other way:**

Using composition isn't shorter this time, but it can be shorter *sometimes*

```
sortBy(\a=(>)(length a)o length)

```

**The other other way:**

While it's a bit contrived here, you can use guards in lambdas

```
sortBy(\a b|length a>length b=True=False)

```

And also let-before node expressions

```
sortBy(\a b#l=length
=l a>l b)

```

***A note:***

There are two more forms of lambda, `(\a b . ...)` and `(\a b -> ...)`, the latter of which is identical to the `=` variant, and the former of which exists for some reason and often looks like you're trying to access a property of something instead of defining a lambda so don't use it.

# Answer
> 1 votes
# If you're using a `String` you should be using `Text`

Conversion to strings, and manipulation of strings (the `{#Char}` / `String` kind, not the `[Char]` kind) is quite lengthy and bad for golfing. The `Text` module remedies this.

**Conversion:**

`Text` defines the operator `<+` for any two types which have `toString` defined.
This operator, used as `a<+b` is the same as `toString a+++toString b` \- saving *at least 19 bytes*. Even if you include the extra import, `,Text`, and use it only once, *it still saves 14 bytes!*

**Manipulation:**

`Text` defines a few string-manipulation staples that are missing from `StdEnv`:

* The operator `+` for strings, which is much shorter than `+++` (from `StdEnv`)
* `indexOf`, with the C-like behaviour of returning `-1` instead of `Nothing` on failure
* `concat`, which concatenates a list of strings
* `join`, which joins a list of strings using a separator string
* `split`, which splits a string into a list of strings on a substring

# Answer
> 0 votes
# Use Character List Literals

A character list literal is a shorthand way of writing something like `['h','e','l','l','o']` as `['hello']`.

This isn't the limit of the notation, for example:

* `repeat'c'` becomes `['c','c'..]` becomes `['cc'..]`
* `['z','y'..'a']` becomes `['zy'..'a']`
* `['beginning']++[a,b,c]++['end']` becomes `['beginning',a,b,c,'end']`
* `['prefix']++suffix` becomes `['prefix':suffix]`

These work in matching too:

* `['I don't care about the next character',_,'but I do care about these ones!']`

# Answer
> 0 votes
# Sometimes `code` is shorter

Clean has a bunch of really useful functions in the standard libraries, some of which are incredibly verbose to use without access to `*World`, and using `*World` in code-golf is generally a bad idea anyway.

To get around this problem, there are often `ccall`s you can use inside `code` blocks instead.

Some examples:

**System Time**

```
import System.Time,System._Unsafe
t=toInt(accUnsafe(time))

```

The above is 58 bytes, but you can save 17 bytes (down to 40+1) with:

```
t::!Int->Int
t _=code{ccall time "I:I"
}

```

**Random Numbers**

This one doesn't save bytes on its own, but avoids having to pass around a list from `genRandInt`

```
s::!Int->Int
s _=code{ccall time "I:I"ccall srand "I:I"
}
r::!Int->Int
r _=code{ccall rand "I:I"
}

```

**Other Uses**

In addition to these two, which are probably the main uses for this in code-golf, you can call any named function (including but not limited to every syscall), embed arbitrary assembly with `instruction <byte>`, and embed code for the ABC machine.

---
Tags: code-golf, tips
---


title: Code Golf: Letter-Ception

text:
# Question
Title: Code Golf: Letter-Ception
**The Challenge:**

For an input of one letter X (upper or lower case from A to Z) and one digit N (0-9) print the corresponding letter X made of N * X.

The letter has to be from this list:

```
 AAA      BBBB       CCCC     DDDD      EEEEE     FFFFF      GGG      H   H
A   A     B   B     C         D   D     E         F         G         H   H
AAAAA     BBBB      C         D   D     EEEE      FFFF      G  GG     HHHHH
A   A     B   B     C         D   D     E         F         G   G     H   H
A   A     BBBB       CCCC     DDDD      EEEEE     F          GGG      H   H

IIIII         J     K   K     L         M   M     N   N      OOO
  I           J     K  K      L         MM MM     NN  N     O   O
  I           J     KKK       L         M M M     N N N     O   O
  I       J   J     K  K      L         M   M     N  NN     O   O
IIIII      JJJ      K   K     LLLLL     M   M     N   N      OOO

PPPP       QQQ      RRRR       SSSS     TTTTT     U   U     V   V     W   W
P   P     Q   Q     R   R     S           T       U   U     V   V     W   W
PPPP      Q   Q     RRRR       SSS        T       U   U     V   V     W   W
P         Q  QQ     R  R          S       T       U   U      V V      W W W
P          QQQQ     R   R     SSSS        T        UUU        V        W W

X   X     Y   Y     ZZZZZ
 X X       Y Y         Z
  X         Y         Z
 X X        Y        Z
X   X       Y       ZZZZZ

```

**Examples:**

input: a 1

output:

```
 AAA
A   A
AAAAA
A   A
A   A

```

---

input: A 0

output: `A`

---

input: A 2

output:

```
      AAA  AAA  AAA
     A   AA   AA   A
     AAAAAAAAAAAAAAA
     A   AA   AA   A
     A   AA   AA   A
 AAA                 AAA
A   A               A   A
AAAAA               AAAAA
A   A               A   A
A   A               A   A
 AAA  AAA  AAA  AAA  AAA
A   AA   AA   AA   AA   A
AAAAAAAAAAAAAAAAAAAAAAAAA
A   AA   AA   AA   AA   A
A   AA   AA   AA   AA   A
 AAA                 AAA
A   A               A   A
AAAAA               AAAAA
A   A               A   A
A   A               A   A
 AAA                 AAA
A   A               A   A
AAAAA               AAAAA
A   A               A   A
A   A               A   A

```

---

input: A -1

output: *what ever: it doesn't matter*

---

**Additional Rules:**

* The input parameters can be separated by what ever character you want.
* Each letter must use the capital of itself as the ascii-character to draw it.
* Trailing spaces, new lines etc. are allowed
* Instead of a program, you may write a function that takes the digit string as an argument. The output should be printed normally.
* Stdout / Stderr doesn't matter, just pick one. If stuff gots printed on the other doesn't matter either.
* Possible output formats can be printed to STDOUT, returned as a list of strings, returned as a character matrix, etc. as long as the result can simply be printed using the languages default print method.\*

\*: like the function f(a,1) returns the string and one can simply say print(f(a,1)) dont make the print() call part of the answer. (This was pointed out by Kevin Cruijssen and Arnauld).

**Winning:**

This is code-golf, lowest byte-count wins. Have fun!

---

**Edit**: this question seems *very identical* to this however I would say it is not, as it should not only work for H but for each letter from the alphabet.. Guess you decide rather or not it is a duplicate.

# Answer
# , 259 bytes

```
function(K,N,`!`=utf8ToInt){if(N)for(i in 1:N)T=T%x%(sapply(!"

",intToBits)[1:5,5*(-64+!K)-4:0]>0)
write(c(" ",K)[T+1],1,5^N,,"")}

```

Try it online!

> ***Disclaimer :***
> *this solution has been obtained by taking @Giuseppe's answer and replacing the matrix compression with another approach very very similar to the one used in @Arnauld's answer, so first of all go upvote them* :)

The idea is the following :

Given this `5 x 26*5` matrix of `0/1` :

```
(1 replaced by '#', 0 replaced by '.' and '|' added for readability)

.####|#####|.###.|#####|#####|#####|.###.|#####|#...#|...#.|#####|#####|#####|
#.#..|#.#.#|#...#|#...#|#.#.#|#.#..|#...#|..#..|#...#|....#|..#..|....#|.#...|
#.#..|#.#.#|#...#|#...#|#.#.#|#.#..|#...#|..#..|#####|....#|..#..|....#|..#..|
#.#..|#.#.#|#...#|#...#|#.#.#|#.#..|#.#.#|..#..|#...#|....#|.#.#.|....#|.#...|
.####|.#.#.|#...#|.###.|#...#|#....|..##.|#####|#...#|####.|#...#|....#|#####| ...
  ^     ^     ^     ^     ^     ^     ^     ^     ^     ^     ^     ^     ^
  |     |     |     |     |     |     |     |     |     |     |     |     |
  A     B     C     D     E     F     G     H     I     J     K     L     M

```

each column is considered as binary number and converted to an integer. These integer are then converted to unprintable ASCII in the range 1...31 :

e.g. for the columns of `"B"` the final string will be `"\017\021\017\021\017"` (unprintable chars written in octal representation):

```
#####                   ####.     11110          15            '\017'
#.#.#                   #...#     10001          17            '\021'
#.#.#      ------->     ####. --> 11110  ------> 15   ------>  '\017'
#.#.#                   #...#     10001          17            '\021'
.#.#.                   ####.     11110          15            '\017'

          (transposed                  bin to int   int to ASCII
         for reability)

```

Hence, given the final string of `5*26 = 130` characters, we convert that string back to the matrix of `0/1` using :

```
sapply(utf8ToInt(STRING),intToBits)

```

then we simply subsect the matrix selecting only the first 5 rows (intToBits returns 32 bits) and only the columns corresponding to the letter passed as input and finally we apply kronecker as explained in @Giuseppe's answer.
> 4 votes

# Answer
# JavaScript (ES8), 281 bytes

Takes input as `(letter)(N)`. Returns a string.

```
c=>n=>(g=y=>y--?''.padEnd(w).replace(/./g,(_,x)=>(h=d=>~~(d/=5)?(P=parseInt)('hhvhefhfhfu111ufhhhfv1f1v11f1vehp1ehhvhhv444vehgggh979hv1111hhlrhhpljhehhhe11fhfuphheh9fhffge1u4444vehhhh4ahhhalhhhha4ah444ahv248v'[y/d%5+5*P(c,36)-50|0],36)>>x/d%5&1?h(d):' ':c)(w))+`
`+g(y):'')(w=5**n)

```

Try it online!

## How?

### Font encoding

The letters are \\$5\times5\\$, which means that each row can be encoded as a 5-digit binary value, i.e. \\$0\\$ to \\$31\\$ in decimal. These values can conveniently be stored as a single digit in Base36.

The pattern that is stored is mirrored both horizontally and vertically.

*Example for 'F':*

```
#####     ....#     00001      1     '1'
#....     ....#     00001      1     '1'
####. --> .#### --> 01111 --> 15 --> 'f' --> '11f1v'
#....     ....#     00001      1     '1'
#....     #####     11111     31     'v'

```

The whole font is stored as a single string of \\$26\times5 = 130\\$ characters.

To test the 'pixel' at \\$(x,y)\\$ for the \\$n^{\text{th}}\\$ letter, we do:

```
parseInt('hhvhefhfh...'[y + 5 * n], 36) >> x & 1

```

### Main algorithm

Given \\$n\\$, we define \\$w=5^n\\$, which is the width of the final output.

For \\$0\le x\<w\\$ and \\$0\le y\<w\\$, we want to know if the output pixel at \\$(x,y)\\$ is set or not. We use the recursive function \\$h\\$, which tests the letter pixel located at:

$$\left(\left\lfloor\frac{x}{5^k}\right\rfloor\bmod 5,\left\lfloor\frac{y}{5^k}\right\rfloor\bmod 5\right)$$

for all \\$k\\$ in \\$\[0 \dots n-1\]\\$.

The function returns a space as soon as a blank pixel is detected at some depth, or the character corresponding to the input letter if all iterations are successful.
> 6 votes

# Answer
# , 348 bytes

```
function(K,N){if(N)for(i in 1:N)T=T%x%matrix(c(15269425,32045630,16269839,32032318,33061407,33061392,15224366,18415153,32641183,1082926,18444881,17318431,18732593,18667121,15255086,32045584,15255151,32045649,16267326,32641156,18400814,18400580,18400938,18157905,18157700,32575775)[utf8ToInt(K)-64]%/%2^(24:0)%%2,5,5)
write(c(" ",K)[T+1],1,5^N,,"")}

```

Try it online!

Uses an encoding nearly identical to Ouros'; however, it does not reverse the bits, instead opting to use them directly.

It then creates a 5x5 matrix of bits and builds the Kronecker Power matrix to generate the necessary pattern, writing the results to stdout.
> 6 votes

# Answer
# Clean, ~~436~~ 372 bytes

Significantly shorter with new IO format.

```
import StdEnv,StdLib
t=transpose
f=flatten
$0c=[[c]]
$n c=f[t(f[t($(n-1)if(isOdd({#18415150,16301615,31491134,16303663,32554047,1096767,15262766,18415153,32641183,15254032,18128177,32539681,18405233,18667121,15255086,1097263,32294446,18136623,16267326,4329631,15255089,4539953,11191857,18157905,4329809,32575775}.[toInt(max'A'c)-65]>>p))c' ')\\p<-[i..i+4]])\\i<-[0,5..20]]

```

Try it online!

Compresses the letter patterns into the bits of integer literals to save ~700 bytes. For example, `A`:

1. Flatten `[[' AAA '],['A A'],['AAAAA'],['A A'],['A A']]`
2. Reverse `[' AAA A AAAAAAA AA A']`
3. Turn `['A AA AAAAAAA A AAA ']` into binary (`'A' = 1, ' ' = 0`)
4. Turn `0b1000110001111111000101110` into decimal
5. Get `18415150`
> 5 votes

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