title: Generate a Kirkman triple system

text:
# Question
Title: Generate a Kirkman triple system
Given a universe of \\$v\\$ elements, a **Kirkman triple system** is a set of \\$(v-1)/2\\$ *classes* each having \\$v/3\\$ *blocks* each having three elements, so that

* every pair of elements appears in exactly one block
* all classes are partitions of the universe.

Kirkman's schoolgirl problem corresponds to the \\$v=15\\$ case.

> Fifteen young ladies in a school walk out three abreast for seven days in succession: it is required to arrange them daily so that no two shall walk twice abreast.

---

Below is a procedure to construct a Kirkman triple system for \\$v=3q\\$ where \\$q\\$ is a prime number\* of the form \\$6t+1\\$, from my MSE answer here:

> Label elements as \\$(x,j)\\$ where \\$x\in\mathbb F\_q\\$ and \\$j\in\\{0,1,2\\}\\$. Let \\$g\\$ be a primitive element of \\$\mathbb F\_q\\$. Define blocks $$Z=\\{(0,0),(0,1),(0,2)\\}\\ B\_{i,j}=\\{(g^i,j),(g^{i+2t},j),(g^{i+4t},j)\\},0\le i\<t,0\le j\<2\\ A\_i=\\{(g^i,0),(g^{i+2t},1),(g^{i+4t},2)\\},0\le i\<6t$$ and the class $$C=\\{Z\\}\cup\\{B\_{i,j}:0\le i\<t,0\le j\<2\\}\cup\\{A\_i:0\le i\<6t,\lfloor i/t\rfloor\in\\{1,3,5\\}\\}$$ Define shifting a block \\$b\\$ by \\$s\in\mathbb F\_q\\$ as $$b+s=\\{(x+s,j):(x,j)\in b\\}$$ and shifting a class similarly, then a Kirkman triple system of order \\$3q\\$ is $$\\{C+s:s\in\mathbb F\_q\\}\cup\\{\\{A\_i+s:s\in\mathbb F\_q\\}:0\le i\<6t,\lfloor i/t\rfloor\in\\{0,2,4\\}\\}$$

## Task

Given a prime number \\$q\\$ of the form \\$6t+1\\$, output all classes and blocks of a Kirkman triple system on \\$v=3q\\$ elements. You may use any distinct values for the elements. Formatting is flexible, but the boundaries between elements, blocks and classes must be clear.

This is ; fewest bytes wins. You must be able to run your code to completion for at least the smallest case \\$q=7\\$.

## Test cases

This is a possible output for \\$q=7\\$:

```
[[[0, 7, 14],[1, 2, 4],[8, 9, 11],[15, 16, 18],[3, 13, 19],[6, 12, 17],[5, 10, 20]],
 [[1, 8, 15],[2, 3, 5],[9, 10, 12],[16, 17, 19],[4, 7, 20],[0, 13, 18],[6, 11, 14]],
 [[2, 9, 16],[3, 4, 6],[10, 11, 13],[17, 18, 20],[5, 8, 14],[1, 7, 19],[0, 12, 15]],
 [[3, 10, 17],[0, 4, 5],[7, 11, 12],[14, 18, 19],[6, 9, 15],[2, 8, 20],[1, 13, 16]],
 [[4, 11, 18],[1, 5, 6],[8, 12, 13],[15, 19, 20],[0, 10, 16],[3, 9, 14],[2, 7, 17]],
 [[5, 12, 19],[0, 2, 6],[7, 9, 13],[14, 16, 20],[1, 11, 17],[4, 10, 15],[3, 8, 18]],
 [[6, 13, 20],[0, 1, 3],[7, 8, 10],[14, 15, 17],[2, 12, 18],[5, 11, 16],[4, 9, 19]],
 [[1, 9, 18],[2, 10, 19],[3, 11, 20],[4, 12, 14],[5, 13, 15],[6, 7, 16],[0, 8, 17]],
 [[2, 11, 15],[3, 12, 16],[4, 13, 17],[5, 7, 18],[6, 8, 19],[0, 9, 20],[1, 10, 14]],
 [[4, 8, 16],[5, 9, 17],[6, 10, 18],[0, 11, 19],[1, 12, 20],[2, 13, 14],[3, 7, 15]]]

```

---

<sub>\*The construction also works for \\$q\\$ any prime **power** of the form \\$6t+1\\$, but I know some languages may be disadvantaged in implementing general finite field arithmetic. Cf. here.</sub>

# Answer
# Python with numpy, 285 bytes

```
from numpy import*
def k(q):
    t=q//6;a=array;r=range;R=a(r(q-1));X=R//t%2;h=a(r(3));g=1;p=lambda x:[(x+s)%q for s in r(q)]
    while 1in g**R[1:]%q:g+=1
    A=a([g**(i+2*h*t)%q+h/5for i in R]);return[p(i)for i in A[X<1]]+p(a([h/5]+[(g**(i+2*h*t))%q+j/5for i in r(t)for j in h]+list(A[X>0])))
```

Attempt This Online!
> 1 votes

# Answer
# PARI/GP, 218 bytes

```
q->c=concat;c([c([[[[s+0*g=znprimroot(q),j]|j<-r=[0..2]]],c([[[[g^(i+2*t*k)+s,j]|k<-r]|i<-[1..t=q\6]]|j<-r]),[[[g^(i+2*t*j)+s,j]|j<-r]|i<-u=[1..6*t],i\t%2]])|s<-v=[1..q]],[[[[g^(i+2*t*j)+s,j]|j<-r]|s<-v]|i<-u,i\t%2<1])
```

Attempt This Online!
> 0 votes

---
Tags: code-golf, math, number-theory, combinatorics, combinatorial-design
---


title: Addition/Multiplication table generator

text:
# Question
Title: Addition/Multiplication table generator
Given a number and either "+" or "\*", return an addition or multiplication table with the dimensions of that number.

## Specifications

* The input will be formatted as `dimension, operation`.
* The program should not return anything if the operation input is not + or \*.
* The program should not return anything if the dimension input is less than 1.

```
(4,*):
1 2 3 4
2 4 6 8
3 6 9 12
4 8 1216

(4,+):
1234
2456
3567
4678

```

The spaces between the numbers in the table should be equal to one less than the number of digits in `dimension^2` for multiplication, and for addition one less than the number of digits in `dimension * 2`.

# Answer
> 0 votes
# Mathematica, 46 bytes

```
Grid@Outer[If[#2=="+",Plus,Times],r=Range@#,r]&

```

Unnamed function taking two arguments, a number and one of the characters "+" or "\*".

Sample output for the arguments `12`,`"*"`:

# Answer
> 6 votes
# Bash \+ BSD Utils, 62 bytes

```
l=$[$1*$1-1]
eval echo \$[{1..$1}$2{1..$1}]|rs -g${#l} $[$1+1]

```

This calculates the number of spaces as per "number of digits in (dimension^2)-1", and not as shown in the example output, as currently written.

Try it online!

This answer is very similar to this one.

Works out-of-the-box on macOS. `rs` may need to be installed on Linux systems:

```
sudo apt-get install rs

```

# Answer
> 3 votes
# Excel, 74 bytes

Worksheet funtion that takes input of `dimension, operation` from `A1, B1` and output a square array starting at the calling cell. Error handling accounts for a large portion of this response, and it is likely that large optimizations may be made to it.

```
=IfError(Let(r,Sequence(A1),c,Transpose(r),Ifs(B1="*",r*c,B1="+",r+c)),"")

```

# Answer
> 1 votes
# 05AB1E, 22 bytes

```
FN>¹L².VvyDg¹ngs-ú}J,}

```

Try it online!

Also works with `-`, `^`, `m` and many more. See here for a list of commands this could work with by searching for "pop a,b".

Output (4,+):

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

```

Output (4,\*):

```
 1 2 3 4
 2 4 6 8
 3 6 912
 4 81216

```

Output (4,^) \[XOR\]:

```
 0 3 2 5
 3 0 1 6
 2 1 0 7
 5 6 7 0

```

Output (4,c) \[nCr\]:

```
 1 2 3 4
 0 1 3 6
 0 0 1 4
 0 0 0 1

```

Output (4,Q) \[a == b\]:

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

```

# Answer
> 1 votes
# APL (Dyalog Classic), 11 bytes

```
{(⍳∘.⍺⍺⍳)⍵}

```

Try it online!

# APL NARS, 22 bytes, 11 chars

```
{(⍳∘.⍺⍺⍳)⍵}

```

test:

```
  h←{(⍳∘.⍺⍺⍳)⍵}
  ×h 4
1 2  3  4
2 4  6  8
3 6  9 12
4 8 12 16
  +h 4
2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8
  *h 7
1  1   1    1     1      1      1
2  4   8   16    32     64    128
3  9  27   81   243    729   2187
4 16  64  256  1024   4096  16384
5 25 125  625  3125  15625  78125
6 36 216 1296  7776  46656 279936
7 49 343 2401 16807 117649 823543

```

even if {(⍳∘.⍺⍺⍳)⍵} seems to be ok, {(⍳∘.⍵⍵⍳)⍺} it seems not ok

```
  f←{(⍳∘.⍵⍵⍳)⍺}
  4 f×
SYNTAX ERROR

```

Possible spaces are not as the examples in the question too...

h with g h n is the operator generator of table nxn For each diadic function g. In particular =h n is unit matrix for nxn.

# Answer
> 1 votes
# AWK, 111 bytes

```
{s=$2=="*"?2:$2=="+"?1:0;for(i=s-2;s&&++i<=$1;print"")for(j=s-2;++j<=$1;)printf("%"(s==1?2:$1)"s",s>1?i*j:i+j)}

```

Try it online!

Output formatting may be slightly different than requested.

```
Input:
4,+
4,*
6,+

Output:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

1   2   3   4
2   4   6   8
3   6   9  12
4   8  12  16

0 1 2 3 4 5 6
1 2 3 4 5 6 7
2 3 4 5 6 7 8
3 4 5 6 7 8 9
4 5 6 7 8 910
5 6 7 8 91011
6 7 8 9101112

```

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

```
-Dp(i,c)for(i==0;i++<n;c)
-Df(c)if(x===*#c)p(i,puts(""))p(j,printf("%d ",i c j));
n;x;main(i,j){scanf("%d%c",&n,&x);f(+)f(*)}

```

Try it online!

# Answer
> 1 votes
# Japt `-R`, 22 bytes

+17 bytes for the input validation and output formatting! :o

```
õ ïV ú f@©"*+"øVÃòU mq

```

Try it

# Answer
> 0 votes
# JavaScript, 137 bytes

```
f=(n,s,b="")=>{for(i=0;i++<n;b+="\n")for(j=0;j++<n;b+=(r=s=='*'?i*j:s=='+'?i+j:"")+" ".repeat((n**2+"a").length-(r+"").length));return b}

```

Creates function `f` that returns the string. This calculates the number of spaces as per `number of digits in (dimension^2)-1`, and not as shown in the example output, as currently written. Outputs nothing if there is something other than `+` or `*`. I'm open to golfing tips.

### Explanation

```
f=(n,s,b="")=>{
  for(i=0;i++<n;b+="\n")
    for(j=0;j++<n;b+=(r=s=='*'?i*j:s=='+'?i+j:"")+" ".repeat((n**2+"a").length-(r+"").length));
  return b
}

```

*I like when most of my code is just in my for-loops :)*

`n` is the number; `s` is the operator; `b` is the string that contains the output; `r` contains the actual value of the table cells

This is a system of two nested for-loops, I add `b` by `i*j` or `i+j` depending on the operator `(r=s=='*'?i*j:s=='+'?i+j:"")`, and then add the spaces afterward `" ".repeat((n**2+"a").length-(r+"").length)`.

At the end of the `j`-for-loop, I concatenate a newline to `b`.

### Snack Snippet

```
f=(n,s,b="")=>{for(i=0;i++<n;b+="\n")for(j=0;j++<n;b+=(r=s=='*'?i*j:s=='+'?i+j:"")+" ".repeat((n**2+"a").length-(r+"").length));return b}

console.log(f(10,'+'));
```

# Answer
> 0 votes
# Python 3 - ~~154~~ 133 ~~127~~ bytes

```
def s(d,o):R,s=range(1,d+1),' '*len(str((d,2)[o=='+']*d-1));return''.join([str((i*j,i+j)[o=='+'])+s+'\n'*(i==d)for j in R for i in R])

```

**Edit** : Changed spacing between number according to the new changes in the question.

```
Input :
8 +
Output :
2  3  4  5  6  7  8  9
3  4  5  6  7  8  9  10
4  5  6  7  8  9  10  11
5  6  7  8  9  10  11  12
6  7  8  9  10  11  12  13
7  8  9  10  11  12  13  14
8  9  10  11  12  13  14  15
9  10  11  12  13  14  15  16

```

# Answer
> 0 votes
## JavaScript (ES6), 160 bytes

```
(n,s,w=`${s==`*`?n*n:n+n}`.length)=>[...Array(n)].map((_,i,a)=>a.map((_,j)=>((s==`*`?++j*i+j:s==`+`?i+j+2-!(i&&j):``)+` `.repeat(w)).slice(0,w)).join``).join`\n`

```

Where `\n` represents the literal newline character. Takes care to space the grid properly for both `+` and `-` versions, and ensures the first row and column are the dimensions and not the sum.

# Answer
> 0 votes
# , 48 bytes

```
function(n,o)write(format(outer(1:n,1:n,o)),1,n)

```

Try it online!

Same I/O as the accepted answer.

# Answer
> 0 votes
# Vyxal, 18 bytes

```
ɾ?\vdpĖ:vvS$fGL↲Ṡ⁋

```

Try it Online!

Without strict IO formats, the whole `:vvS$fGL↲Ṡ⁋` could be omitted

# Answer
> -1 votes
## Python 3 - 140 bytes

```
a=lambda d,o:print(*map(lambda f:(' '*~-len(str([d,2][o>'*']*d))).join([str([i*f,i+f][o>'*'])for i in range(1,d+1)]),range(1,d+1)),sep='\n')

```

# Answer
> -1 votes
# JavaScript (Node.js), 91 bytes

```
(n,_)=>[...'.'.repeat(n)].map((a,i)=>Array.from({length:n},(v,k)=>_='*'?(k+1)*(i+1):k+i+1))

```

Try it online!

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


title: Produce an XOR table

text:
# Question
Title: Produce an XOR table
### Introduction

XOR is a digital logic gate that implements an exclusive or. Most of the times, this is shown as `^`. The four possible outcomes in binary:

```
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0

```

This can also be seen as addition modulo 2 in binary. In decimal, we need to convert the decimal to binary, `35 = 100011` and `25 = 11001`.To compute the XOR value, we place them on top of each other:

```
100011
 11001 ^
--------
111010  = 58 in decimal

```

**The task**: When given an integer value N greater than 1, output an XOR table with the size N + 1. For example, N = 5:

```
 0 1 2 3 4 5
 1 0 3 2 5 4
 2 3 0 1 6 7
 3 2 1 0 7 6
 4 5 6 7 0 1
 5 4 7 6 1 0

```

You can see that there is one space in front of each number, because the highest amount in the table has length 1. However, if we take N = 9, we get the following grid:

```
  0  1  2  3  4  5  6  7  8  9
  1  0  3  2  5  4  7  6  9  8
  2  3  0  1  6  7  4  5 10 11
  3  2  1  0  7  6  5  4 11 10
  4  5  6  7  0  1  2  3 12 13
  5  4  7  6  1  0  3  2 13 12
  6  7  4  5  2  3  0  1 14 15
  7  6  5  4  3  2  1  0 15 14
  8  9 10 11 12 13 14 15  0  1
  9  8 11 10 13 12 15 14  1  0

```

The highest value has length 2, so the value is right-aligned to length 3 (highest length + 1).

**Rules:**

* Leading whitespace is not mandatory, only if used (or not) consistently
* You must output a table in the form shown above.
* The padding between columns should be as small as possible
* This is , so the submission with the least amount of bytes wins!

# Answer
# MATL, 10 bytes

```
0i2$:tXgZ~

```

The compiler (and in particular this program) now seems to work in Octave, although it still needs some refinement. You can provisionally use this GitHub commit.

*Edit (Mar 30 '16)*: **Try it online!**

### Example

```
>> matl 0i2$:tXgZ~
> 9
0  1  2  3  4  5  6  7  8  9
1  0  3  2  5  4  7  6  9  8
2  3  0  1  6  7  4  5 10 11
3  2  1  0  7  6  5  4 11 10
4  5  6  7  0  1  2  3 12 13
5  4  7  6  1  0  3  2 13 12
6  7  4  5  2  3  0  1 14 15
7  6  5  4  3  2  1  0 15 14
8  9 10 11 12 13 14 15  0  1
9  8 11 10 13 12 15 14  1  0

```

### Explanation

```
0i2$:       % vector 0, 1, 2, ... up to input number
t           % duplicate
Xg          % nd-grid
Z~          % bitxor

```
> 12 votes

# Answer
# Bash + BSD utils, 45

```
eval echo \$[{0..$1}^{0..$1}]|rs -jg1 $[$1+1]

```

I've been waiting a long time to find a use for `rs`. This seems to be a good one. `rs` may need to be installed on Linux systems. But it runs right out of the box on OS X.

* `$1` expands to N, and thus `echo \$[{0..$1}^{0..$1}]` expands to `echo $[{0..N}^{0..N}]`
* This is then `eval`ed:
* The brace expansion expands to `$[0^0] $[0^1] $[0^2] ... $[0^N] ... $[N^N]`
* This is a series of xor arithmetic expansions which expand to one line of terms
* `rs` (reshape) reshapes this line to N+1 rows. `-j` right justifies, and `-g1` gives a gutter-width of 1. This ensures the final output table has minimal width between columns.

I've tested up to N=1000, which took 3.8 seconds. Large N is theoretically possible, though bash will run out of memory at some point with the (N+1)² memory usage of the brace expansion.
> 5 votes

# Answer
# C, 114 ~~128 152~~

**Edit** Simplified space counting, inspired by the work of Khaled A Khunaifer

A C function that follows the specs.

```
T(n){int i=0,j,x=1,d=0;while(x<=n)x+=x,++d;for(;i<=n;i++)for(j=0;j<=n;j++)printf("%*d%c",d*3/10+1,i^j,j<n?32:10);}

```

Try it insert n as input, default 9

**Less golfed**

```
T(n)
{
   int i=0, j, x=1,d=0;
   while(x<=n) x+=x,++d; // count the digits
   // each binary digit is approximately 0.3 decimal digit
   // this approximation is accurate enough for the task
   for(;i<=n;i++)
     for(j=0;j<=n;j++)
       printf("%*d%c",d*3/10+1,
              i^j,
              j < n ? 32:10); // space between columns, newline at end
}

```
> 4 votes

# Answer
# JavaScript (ES6) 120 ~~122~~

**Edit** 2 bytes saved thx ETHproductions

An anonymous function. Note: the number in the table are limited to 7 digits, that is more than reasonable given the overall size of a table allowing for bigger numbers

Now I should find a shorter way to get the max columns size, avoiding logarithms

```
n=>(a=Array(n+1).fill(-~Math.log10(2<<Math.log2(n)))).map((m,i)=>a.map((z,j)=>`       ${i^j}`.slice(~m)).join``).join`
`

```

**Test**

```
f=n=>(a=Array(n+1).fill(-~Math.log10(2<<Math.log2(n)))).map((m,i)=>a.map((z,j)=>`       ${i^j}`.slice(~m)).join``).join`\n`

function update() {
  var v=+I.value
  O.textContent = f(v)
}

update()
```

```
N: <input id=I type=number value=9 oninput='update()'>
<pre id=O></pre>
```
> 3 votes

# Answer
# C, 149 bytes

```
int i=0,j,n,k=2;char b[256];scanf("%d",&n);while((k*=2)<=n);k^=k-1;while(i++<=n&&putchar(10))for(j=0;j<=n;j++)printf(" %*d",sprintf(b,"%d",k),i-1^j);
---------

```

Detailed

```
#include <stdio.h>

int main()
{
    int i=0, j, n, k=2;
    char b[256] = { 0 };

    scanf("%d", &n);

    // find max xor value in the table
    while((k*=2)<=n); k^=k-1;

    printf("> %d ~ %d", k, sprintf(b,"%d",k));

    while(i++ <= n && putchar(10))
    {
        for(j = 0; j <= n;j++)
        {
            printf(" %*d", sprintf(b,"%d",k), (i-1)^j);
        }
    }

    return 0;
}

```
> 3 votes

# Answer
# C, 103 bytes

```
Y(n){int i,j=n++;char*f="%2u";while(j/=8)++f[1];for(;j<n;++j,puts(""))for(i=0;i<n;++i)printf(f,i^j);}

```
> 3 votes

# Answer
**MathCAD, 187 Bytes**

MathCAD handles built in tables easily - but has absolutely no bitwise Xor, nor decimal to binary or binary to decimal converters. The for functions iterate through the possible values. The i, a2, Xa and Xb place hold. The while loop actively converts to binary, and while converting to binary also performs the xor function (the little cross with the circle around it). It stores the binary number in a base-10 number consisting of 0's and 1's. This is then converted before being stored in the M matrix via the summation function.

This can easily be golfed down (if only by swapping out the placeholders for shorter ones), but I figured I'd post it and see if anyone can golf down the binary to decimal converter more than anything else.
> 3 votes

# Answer
# Jelly, 7 bytes

```
0r©^'®G

```

Try it online!

### How it works

```
0r©^'®G  Main link. Input: n (integer)

0r       Range; yield [0, ..., n].
  ©      Save the range in the register.

     ®   Yield the range from the register.
   ^'    XOR each integer in the left argument with each integer in the right one.
      G  Grid; separate rows by newlines, columns by spaces, with a fixed width for
         all columns. Since the entries are numeric, align columns to the right.

```
> 3 votes

# Answer
# Python 3, ~~133~~ 131 bytes

```
import math
n=int(input())
r,p=range(n+1),print
for y in r:[p(end='%%%dd '%len(str(2**int(math.log2(n)+1)-1))%(x^y))for x in r];p()

```
> 3 votes

# Answer
## R, 38 bytes

Usually R requires a lot of bytes just to format the output. In this case it's quite the opposite. `outer` which is usually refers to the outer product of two arrays, can when supplied a function perform this across the margins of the vectors. In this case, we apply the bitwise XOR function `bitwXor`.

```
names(x)=x=1:scan();outer(x,x,bitwXor)

```
> 3 votes

# Answer
## CJam, ~~29~~ 27 bytes

```
ri:X),_ff{^s2X2b,#s,)Se[}N*

```

Test it here.

## Explanation

```
ri      e# Read input and convert to integer.
:X      e# Store in X.
),      e# Get range [0 1 ... X].
_ff{    e# Nested map over all repeated pairs from that range...
  ^     e#   XOR.
  s     e#   Convert to string.
  2     e#   Push 2.
  X2b,  e#   Get the length of the base-2 representation of X. This is the same as getting
        e#   getting the base-2 integer logarithm and incrementing it.
  #     e#   Raise 2 to that power. This rounds X up to the next power of 2.
  s,    e#   Convert to string and get length to determine column width.
  )     e#   Increment for additional padding.
  Se[   e#   Pad string of current cell from the left with spaces.
}
N*      e# Join with linefeeds.

```
> 2 votes

# Answer
## k4, 50 bytes

```
{-1@" "/:'(-|//#:''x)$x:$2/:''~x=/:\:x:0b\:'!1+x;}

```

E.g.:

```
  {-1@" "/:'(-|//#:''x)$x:$2/:''~x=/:\:x:0b\:'!1+x;}9
 0  1  2  3  4  5  6  7  8  9
 1  0  3  2  5  4  7  6  9  8
 2  3  0  1  6  7  4  5 10 11
 3  2  1  0  7  6  5  4 11 10
 4  5  6  7  0  1  2  3 12 13
 5  4  7  6  1  0  3  2 13 12
 6  7  4  5  2  3  0  1 14 15
 7  6  5  4  3  2  1  0 15 14
 8  9 10 11 12 13 14 15  0  1
 9  8 11 10 13 12 15 14  1  0

```
> 2 votes

# Answer
## Mathematica, 108 bytes

```
StringRiffle[Thread[Map[ToString,a=Array[BitXor,{#,#}+1,0],{2}]~StringPadLeft~IntegerLength@Max@a],"
"," "]&

```

Disregard the error, it's just `Thread` not knowing what it's doing.
> 1 votes

# Answer
# Emacs Lisp, 193 bytes

```
(defun x(n)(set'a 0)(set'n(1+ n))(while(< a n)(set'b 0)(while(< b n)(princ(format(format"%%%ss "(ceiling(log(expt 2(ceiling(log n 2)))10)))(logxor a b)))(set'b(1+ b)))(set'a(1+ a))(message"")))

```

Ungolfed:

```
(defun x(n)
  (set'a 0)
  (set'n(1+ n))
  (while(< a n)
    (set'b 0)
    (while(< b n)
      (princ
        (format
          ;; some format string magic to get the length of the longest
          ;; possible string as a format string
          (format "%%%ss " (ceiling(log(expt 2(ceiling(log n 2)))10)))
          (logxor a b)))
      (set'b(1+ b)))
    (set'a(1+ a))
    ;; new line
    (message"")))

```

The output is sent to the `*Message*` buffer, which would be `stdout` if `x` were to be used inside a script.

```
(x 9)
 0  1  2  3  4  5  6  7  8  9
 1  0  3  2  5  4  7  6  9  8
 2  3  0  1  6  7  4  5 10 11
 3  2  1  0  7  6  5  4 11 10
 4  5  6  7  0  1  2  3 12 13
 5  4  7  6  1  0  3  2 13 12
 6  7  4  5  2  3  0  1 14 15
 7  6  5  4  3  2  1  0 15 14
 8  9 10 11 12 13 14 15  0  1
 9  8 11 10 13 12 15 14  1  0

```
> 1 votes

# Answer
# Python 2, 114 bytes

It took some looking to find a way to do variable-width padding in `.format()` (some, not a lot) and get it right-adjusted, but I think I've got it all to spec now. Could use more golfing in that width calculation though.

```
N=input()+1
for i in range(N):print''.join(' {n:>{w}}'.format(w=len(`2**(len(bin(N))-2)`),n=i^r)for r in range(N))

```
> 1 votes

# Answer
## **Caché ObjectScript**, 127 bytes

```
x(n)s w=$L(2**$bitfind($factor(n),1,100,-1))+1 f i=0:1:n { w $j(i,w) } f i=1:1:n { w !,$j(i,w) f j=1:1:n { w $j($zb(i,j,6),w) } }

```

Detailed:

```
x(n)
 set w=$Length(2**$bitfind($factor(n),1,100,-1))+1
 for i=0:1:n {
     write $justify(i,w)
 }
 for i=1:1:n {
     write !,$justify(i,w)
     for j=1:1:n {
         write $justify($zboolean(i,j,6),w)
     }

 }

```
> 1 votes

# Answer
## Pyke, 8 bytes

```
hD]UA.&P

```

Explanation:

```
         - auto-add eval_or_not_input() to the stack
h        - increment the input
 D]      - Create a list containing [inp+1, inp+1]
   U     - Create a 2d range
    A.^  - Deeply apply the XOR function to the range
       P - print it out prettily

```

Try it here
> 1 votes

# Answer
# Go, 145 bytes

A function literal which prints to `STDOUT`. Abuses `Sprintf` heavily.

```
import ."fmt"
func(n int){s:=Sprintf
n++
for i:=0;i<n*n;i++{Printf(s(" %%%dd",len(s("%d",1<<len(s("%b",n-1))-1))),i/n^i%n)
if-^i%n<1{Println()}}}

```

~~Try it online!~~ \- it appears the Go installation on TIO is older than on my machine, this code runs perfectly locally:

```
go run "xortable.go" (with n=10)
  0  1  2  3  4  5  6  7  8  9 10
  1  0  3  2  5  4  7  6  9  8 11
  2  3  0  1  6  7  4  5 10 11  8
  3  2  1  0  7  6  5  4 11 10  9
  4  5  6  7  0  1  2  3 12 13 14
  5  4  7  6  1  0  3  2 13 12 15
  6  7  4  5  2  3  0  1 14 15 12
  7  6  5  4  3  2  1  0 15 14 13
  8  9 10 11 12 13 14 15  0  1  2
  9  8 11 10 13 12 15 14  1  0  3
 10 11  8  9 14 15 12 13  2  3  0

```

## Explanation

First, we declare the function's arguments (a single integer `n`) and alias `Sprintf` to `s`, as we use it many times later.

```
func(n int){s:=Sprintf
n++
...
}

```

Notice that we also increment `n`. Because the table goes up to `n` and includes, we actually want `n+1` rows. Incrementing `n` here saves bytes later.

Next, we declare the loop; rather than using a two-dimensional loop, we can simply loop one variable `i` up to `n*n`, and use `i/n` and `i^n` to access the current coordinates.

```
for i:=0;i<n*n;i++{...}

```

Now comes the string padding. To work out the padding required, we need to find the largest entry in the table. This will be `n`, but with all its non-leading binary `0`s changed to `1`s. So, we format `n` into its binary representation, find its length, right-shift `1` by this amount, and decrement.

```
1<<len(s("%b",n-1))-1

```

We now format this into base 10 and find its length.

```
len(s("%d",...))

```

This, plus `1` is the width that entries should be padded to. Using `%Kd` pads an integer with spaces to width `K`, so we create the padding string by using `Sprintf` once again (note that using a leading space here is a byte shorter than using a `+1` for the length):

```
s(" %%%dd",...)

```

Now, we print the entry in the XOR table (given by `i/n^i%n`) via this string format:

```
Printf(...,i/n^i%n)

```

Finally, if we have reached the end of a row, we output a newline. We check if `(i+1) % n == 0` in the golfiest way possible:

```
if-^i%n<1{Println()}

```
> 1 votes

# Answer
# Stax, 9 bytes

```
üvx`₧¥ⁿ∙√

```

Run and debug it
> 1 votes

# Answer
# Vyxal `Rj`, 21 bytes

```
Ẋƛ÷꘍;:GSL£:L√ẇƛvS¥v↳Ṅ

```

Try it Online!

```
Ẋ                     # Cartesian product with self
 ƛ  ;                 # Map to...
  ÷꘍                  # xor
     :GSL£            # Store the largest's length in the register
          :L√ẇ        # Squareify
              ƛ       # Map to...
               vS     # Stringified
                 ¥v↳  # Padded
                    Ṅ # Joined by spaces
                      # (J flag) joined by newlines

```
> 1 votes

# Answer
# Brachylog, 58 bytes

```
<L&⟦gjẋ{ḃᵐ↔ᵐz₁-ᵐ↔cẹ~ḃṫ↔}ᵐP,Ṣzztg;Pz{z₁tᵐ↔c}ᵐġ↙L{~ṇṇ₂~ṇ₁ẉ}ᵐ

```

Try it online!

I don't *entirely* regret writing this... only took *one* hour...

```
    {...}ᵐ    XOR (and do a bit of other stuff to) each pair from
   ẋ          the flat Cartesian product of
⟦gj           [0 .. input] with itself.

{                }
 ḃᵐ                 Get the binary representation of each argument
   ↔ᵐ               least significant bit first.
     z₁             Non-cycling zip.
       -ᵐ           Subtract each pair/singleton.
         ↔          Reverse back.
          cẹ        Concatenate then explode--remove signs and leading zeroes.
            ~ḃ      Convert from binary.
              ṫ     Convert to string.
               ↔    Reverse again.

P                       Let the result of that mess be P.
 ,Ṣ                     Append " ",
   zz                   cycle each element to the length of the longest,
     t                  then get just the cycled space back.
      g;Pz              Pair it with each element of P.
          {      }ᵐ     For each pair:
           z₁           non-cycling zip.
             tᵐ         take the last element of each pair or singleton,
               ↔        reverse back,
                c       and concatenate back to a string.

        ġ                 Split that result into slices of a length
<L& ...  ↙L               equal to the least integer greater than the input.
           {        }ᵐ    For each slice:
            ~ṇ            join it on newlines,
              ṇ₂          split it on newlines and spaces simultaneously,
                ~ṇ₁       join it on spaces,
                   ẉ      and print it with a trailing newline.
                          (~ṇ₁ can't be used for lists with strings which
                          already contain spaces, because they couldn't
                          result from ṇ₁--that being split on spaces

```
> 1 votes

# Answer
# Python 2, 77 bytes

```
n=input()+1
t=range(n)
for i in t: print "%3d"*n % tuple([x^i for x in t])

```
> 0 votes

# Answer
# , 10 bytes

```
XOR/~@,~i.

```

Try it online!
> 0 votes

# Answer
# Small Basic, 499 bytes

A script that takes input from the `TextWindow` object and outputs to the same

```
a=TextWindow.Read()
For y=0To a
For x=0To a
n=x
b()
z1=z
n=y
b()
l=Math.Max(Array.GetItemCount(z),Array.GetItemCount(z1))
o=0
For i=1To l
If z1[i]<>z[i]And(z[i]=1Or z1[i]=1)Then
z2=1
Else
z2=0
EndIf
o=o+z2*Math.Power(2,i-1)
EndFor
TextWindow.Write(Text.GetSubText("      ",1,Text.GetLength(Math.Power(2,Math.Ceiling(Math.Log(a)/Math.Log(2))))-Text.GetLength(o))+o+" ")
EndFor
TextWindow.WriteLine("")
EndFor
Sub b
z=0
c=0
While n>0
c=c+1
z[c]=Math.Remainder(n,2)
n=Math.Floor(n/2)
EndWhile
EndSub

```

Try it at SmallBasic.com *Uses Silverlight and thus must be run in IE or Edge*

Select the black console, then type input integer and press `Enter`.
> 0 votes

# Answer
# Excel VBA, 95 bytes

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

```
For y=0To[A1]:For x=0To[A1]:z=x Xor y:?Spc([Len(2^-Int(-Log(A1,2)))]-Len(z))Str(z);:Next:?:Next

```
> 0 votes

# Answer
# APL(NARS), 57 chars, 114 bytes

```
{∘.{⍺=0:⍵⋄k←⌈/{⌊1+2⍟⍵}¨⍺⍵⋄(2⍴⍨≢m)⊥m←↑≠/{⍵⊤⍨k⍴2}¨⍺⍵}⍨0..⍵}

```

(NARS2000 0.5.13) test:

```
  q←{∘.{⍺=0:⍵⋄k←⌈/{⌊1+2⍟⍵}¨⍺⍵⋄(2⍴⍨≢m)⊥m←↑≠/{⍵⊤⍨k⍴2}¨⍺⍵}⍨0..⍵}
  q 5
0 1 2 3 4 5
1 0 3 2 5 4
2 3 0 1 6 7
3 2 1 0 7 6
4 5 6 7 0 1
5 4 7 6 1 0
  q 1
0 1
1 0
  q 9
0 1  2  3  4  5  6  7  8  9
1 0  3  2  5  4  7  6  9  8
2 3  0  1  6  7  4  5 10 11
3 2  1  0  7  6  5  4 11 10
4 5  6  7  0  1  2  3 12 13
5 4  7  6  1  0  3  2 13 12
6 7  4  5  2  3  0  1 14 15
7 6  5  4  3  2  1  0 15 14
8 9 10 11 12 13 14 15  0  1
9 8 11 10 13 12 15 14  1  0

```
> 0 votes

# Answer
# Perl 5 `-n`, 62 bytes

```
for$i(0..$_){printf+(" %".(0|log).d)x($_+1).$/,map$_^$i,0..$_}

```

Try it online!
> 0 votes

# Answer
# APL, 20 bytes

```
 {2⊥¨∘.≠⍨↓⍉2⊥⍣¯1⍳⍵+1}

```

Explanation:

```
 ⍳⍵+1

```

integers from 0 to n

```
 2⊥⍣¯1

```

base 2 encoding

```
 ↓⍉

```

create nested of boolean vectors

```
 ∘.≠⍨

```

xor matrix

```
 2⊥¨

```

base 2 to base 10 conversion
> 0 votes

# Answer
# Jelly, 5 bytes

```
Ż^þ`G

```

Try it online!

## How it works

```
Ż^þ`G - Main link. Takes N on the left
Ż     - Range from 0 to N
   `  - Using this range as both arguments:
 ^þ   - Create an XOR table
    G - Format into a padded grid

```
> 0 votes

# Answer
# Vyxal, 14 bytes

```
ʀ:v꘍vvS:fÞGL↳⁋

```

Try it Online!
> 0 votes

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


title: A multiplication table for the Cheela

text:
# Question
Title: A multiplication table for the Cheela
The Cheela (from the book *Dragon's Egg* by Robert L. Forward) are creatures that live on the surface of a neutron star. Their body is flat and circular with twelve eyes on the perimeter, so they naturally use a base-12 numbering system.

Among the Cheela, care of the hatchlings and education of the young are tasks carried out by the Old Ones. Since young Cheela need to be taught how to multiply, the Old Ones could use a multiplication table.

Your task is to produce a `12`x`12` multiplication table in base `12`, like the following. Uppercase letters `A` and `B` are used for digits corresponding to decimal `10` and `11` respectively.

```
  1   2   3   4   5   6   7   8   9   A   B  10
  2   4   6   8   A  10  12  14  16  18  1A  20
  3   6   9  10  13  16  19  20  23  26  29  30
  4   8  10  14  18  20  24  28  30  34  38  40
  5   A  13  18  21  26  2B  34  39  42  47  50
  6  10  16  20  26  30  36  40  46  50  56  60
  7  12  19  24  2B  36  41  48  53  5A  65  70
  8  14  20  28  34  40  48  54  60  68  74  80
  9  16  23  30  39  46  53  60  69  76  83  90
  A  18  26  34  42  50  5A  68  76  84  92  A0
  B  1A  29  38  47  56  65  74  83  92  A1  B0
 10  20  30  40  50  60  70  80  90  A0  B0 100

```

The output shoud be printed on screen. The format should be as follows:

1. Numbers should be aligned to the right within each column.
2. Leading spaces before the first column, trailing spaces after the last column, or a trailing new line after the last row are allowed.
3. Separation between columns can be one space (as shown above) or more than one space, but the number of spaces should be consistent between columns. To measure column separation, consider that displayed numbers include any leading spaces that may have been necessary fo fulfill requirement 1 (so each number occupies three characters, the first of which may be spaces). For example, the table with two-space separation would be as follows:

```
  1    2    3    4    5    6    7    8    9    A    B   10
  2    4    6    8    A   10   12   14   16   18   1A   20
  3    6    9   10   13   16   19   20   23   26   29   30
  4    8   10   14   18   20   24   28   30   34   38   40
  5    A   13   18   21   26   2B   34   39   42   47   50
  6   10   16   20   26   30   36   40   46   50   56   60
  7   12   19   24   2B   36   41   48   53   5A   65   70
  8   14   20   28   34   40   48   54   60   68   74   80
  9   16   23   30   39   46   53   60   69   76   83   90
  A   18   26   34   42   50   5A   68   76   84   92   A0
  B   1A   29   38   47   56   65   74   83   92   A1   B0
 10   20   30   40   50   60   70   80   90   A0   B0  100

```

Computer storage on a neutron star is really expensive, so your code should use as few bytes as possible.

## Extended challenge and bonus

Ideally your code should be reused in other parts of the universe, where other numbering systems may be in use. To that end, the challenge is optionally extended as follows: Your code accepts a number `N` as input and generates an `N`x`N` multiplication table in base `N`, with the above format.

Input may be from keyboard or as a function argument. The program or function should work for `2``N``36`, using as digits the first `N` characters of the sequence `0`, `1`, ..., `9`, `A`, `B`, ..., `Z` (uppercase letters)

This extended challenge is optional. If you follow this route, take 20% off your byte count (no need to round to an integer number).

# Answer
# Pyth, 27 * 0.8 = 21.6

```
VSQsm.[\ 4jkXj*dNQrT99rG1SQ

```

Try it online: Demonstration

### Explanation:

```
VSQsm.[\ 4jkXj*dNQrT99rG1SQ   implicit: Q = input number
VSQ                           for N in [1, 2, ..., Q]:
    m                    SQ      map each number d in [1, 2, ..., Q] to:
              *dN                   N * d
             j   Q                  in base Q
            X     rT99rG1           replace the numbers [10, 11, ..., 98] with "A...Z"
          jk                        join to a string
     .[\ 4                          prepend spaces, so that the string has a length of 4
   s                             join all strings and print

```
> 14 votes

# Answer
## CJam, 33 * 0.8 = 26.4 bytes

```
ri:C,:)_ff{*Cb{_9>{'7+}&}%4Se[}N*

```

Test it here.

This uses the minimum required separation.

### Explanation

```
ri:C        e# Read input, convert to integer, store in C.
,:)         e# Get range [1 2 ... C].
_ff{        e# 2D-map over all repeated pairs from that range...
  *Cb       e#   Multiply, convert to base C.
  {         e#   Map over the digits...
    _9>     e#     Check if the digit is greater than 9.
    {'7+}&  e#     If so, add the digit to the character "7", to get "A" to "Z".
  }%
  4Se[      e#   Pad the digits with spaces from the left, to 4 elements.
}
N*          e# Join with linefeeds.

```

Table for input `22` (the largest that fits in the post without a horizontal scrollbar):

```
   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F   G   H   I   J   K   L  10
   2   4   6   8   A   C   E   G   I   K  10  12  14  16  18  1A  1C  1E  1G  1I  1K  20
   3   6   9   C   F   I   L  12  15  18  1B  1E  1H  1K  21  24  27  2A  2D  2G  2J  30
   4   8   C   G   K  12  16  1A  1E  1I  20  24  28  2C  2G  2K  32  36  3A  3E  3I  40
   5   A   F   K  13  18  1D  1I  21  26  2B  2G  2L  34  39  3E  3J  42  47  4C  4H  50
   6   C   I  12  18  1E  1K  24  2A  2G  30  36  3C  3I  42  48  4E  4K  54  5A  5G  60
   7   E   L  16  1D  1K  25  2C  2J  34  3B  3I  43  4A  4H  52  59  5G  61  68  6F  70
   8   G  12  1A  1I  24  2C  2K  36  3E  40  48  4G  52  5A  5I  64  6C  6K  76  7E  80
   9   I  15  1E  21  2A  2J  36  3F  42  4B  4K  57  5G  63  6C  6L  78  7H  84  8D  90
   A   K  18  1I  26  2G  34  3E  42  4C  50  5A  5K  68  6I  76  7G  84  8E  92  9C  A0
   B  10  1B  20  2B  30  3B  40  4B  50  5B  60  6B  70  7B  80  8B  90  9B  A0  AB  B0
   C  12  1E  24  2G  36  3I  48  4K  5A  60  6C  72  7E  84  8G  96  9I  A8  AK  BA  C0
   D  14  1H  28  2L  3C  43  4G  57  5K  6B  72  7F  86  8J  9A  A1  AE  B5  BI  C9  D0
   E  16  1K  2C  34  3I  4A  52  5G  68  70  7E  86  8K  9C  A4  AI  BA  C2  CG  D8  E0
   F  18  21  2G  39  42  4H  5A  63  6I  7B  84  8J  9C  A5  AK  BD  C6  CL  DE  E7  F0
   G  1A  24  2K  3E  48  52  5I  6C  76  80  8G  9A  A4  AK  BE  C8  D2  DI  EC  F6  G0
   H  1C  27  32  3J  4E  59  64  6L  7G  8B  96  A1  AI  BD  C8  D3  DK  EF  FA  G5  H0
   I  1E  2A  36  42  4K  5G  6C  78  84  90  9I  AE  BA  C6  D2  DK  EG  FC  G8  H4  I0
   J  1G  2D  3A  47  54  61  6K  7H  8E  9B  A8  B5  C2  CL  DI  EF  FC  G9  H6  I3  J0
   K  1I  2G  3E  4C  5A  68  76  84  92  A0  AK  BI  CG  DE  EC  FA  G8  H6  I4  J2  K0
   L  1K  2J  3I  4H  5G  6F  7E  8D  9C  AB  BA  C9  D8  E7  F6  G5  H4  I3  J2  K1  L0
  10  20  30  40  50  60  70  80  90  A0  B0  C0  D0  E0  F0  G0  H0  I0  J0  K0  L0 100

```
> 11 votes

# Answer
# MATL, 42\*.8 = 33.6

### Disclaimer

*Since the creator of the language and the author of the challenge are the same, this answer is not eligible for winning*.

*For a discussion on whether this restriction is necessary or not, see this meta question.*

### Code

```
iXK:t!*Y)KYAZ{'(?<=^0*)0'32cYXZc32hK4*[]e!

```

This uses the minimum separation.

### Example

Octal multiplication table

```
>> matl
 > iXK:t!*Y)KYAZ{'(?<=^0*)0'32cYXZc32chK4*[]e!
 >
> 8
  1   2   3   4   5   6   7  10
  2   4   6  10  12  14  16  20
  3   6  11  14  17  22  25  30
  4  10  14  20  24  30  34  40
  5  12  17  24  31  36  43  50
  6  14  22  30  36  44  52  60
  7  16  25  34  43  52  61  70
 10  20  30  40  50  60  70 100

```

### Explanation

```
i              % input number, say n
XK             % copy to clipboard K
:              % vector 1, 2, ... n
t!*            % generate table: duplicate, transpose and multiply with broadcasting
Y)             % linearize into column array
KYA            % paste n from clipboard K. Convert to that base
Z{             % cell array of rows from array
'(?<=^0*)0'    % string literal for regexp replacement: find leading zeros
32c            % space character (for regexp replacement)
YX             % regexp replacement
Zc             % join cell array of strings into single string
32             % code for space character. Conversion to char happens automatically
h              % concatenate horizontally
K4*[]e!        % paste n and multiply by 4. Reshape into 2D char array with 4*n columns

```

### Edit: Try it online!

To run in the online compiler (as of February 19, 2016), change `Y)` to `X:`, and remove `[]`. This is to adapt to changes that have been made to the language since this challenge was posted.
> 8 votes

# Answer
# Bash + BSD utilities, 36

```
echo Co{1..12}d{1..12}*p|dc|rs -j 12

```

Works out-of-the-box on OS X. `rs` may need to be installed on Linux systems.

* Bash expands `Co{1..12}d{1..12}*p` to `Co1d1*p Co1d2*p Co1d3*p ... Co1d12*p ... Co12d12*p`.
* This is a `dc` expression that generates the required terms. `Co` sets output base to 12. `d` is used as a separator between numbers instead of a space, so no escape is required in the brace expansion. `d` actually duplicates the top of stack, but this is effectively ignored and discarded.
* The output from `dc` is a single space-separated line. `rs` reshapes this to a 12x12 array. `-j` right-justifies each term.
> 5 votes

# Answer
# Pyth, 36 bytes

```
Km+1dUJ12rjbmjkm.[\ 4j""m.Hbj*dkJKK1

```

Try it here.
> 4 votes

# Answer
# CJam, ~~38~~ ~~33~~ ~~32~~ 38 * (.8) = 30.4 bytes

```
qi:D,:):L{Lf*{Db{_9>{55+c}&}%4Se[}%N}%

```

Try it here.

(Looks pretty similar to Martin's now.)

```
qi:D,:):L          e# Generate list of [1...input]
{Lf*               e# Take each number in that list and multiply it by the same list ([[1,2,3,..,input][2,4,6,...,input],...})
{Db{_9>{55+c}&}%   e# Convert each product to base input. If a digit value is >= 10 add 55 and convert to char, to make it a letter.
4Se[}%N}%          e# Pad each number with spaces to length 4. Put a newline after each row.

```
> 4 votes

# Answer
## Python, ~~153~~ ~~147~~ 132 bytes * 0.8 = 105.6

```
def p(b):
 f=lambda n:(n>=b and f(n/b)or'')+chr((48,55)[n%b>9]+n%b)
 for i in range(b*b):print'%4s\n'[:3+(~i%b<1)]%f(~(i%b)*~(i/b)),

```

Down to 132 bytes thanks to the advice of Tim Pederick! :)
> 4 votes

# Answer
# Perl 6, 60 bytes -20% = 48 bytes

```
{.put for (1..$_ X*1..$_)».base($_)».fmt('%3s').rotor($_)} # 60-20% = 48
#          ^-----------^ produce a list of two cross multiplied lists
#                        ^--------^ convert each to base N
#          format each to 3 spaces ^----------^
#         split the list into N element chunks ^--------^
#^-------^ print each of those on their own line with spaces between elements

```

( This is almost exactly how I would write it even if I wasn't trying to get it as short as I could )

Usage:

```
{...}(2)
  1  10
 10 100

```

```
my &code = {...}
code 2;
  1  10
 10 100

```

```
{...}(12);
  1   2   3   4   5   6   7   8   9   A   B  10
  2   4   6   8   A  10  12  14  16  18  1A  20
  3   6   9  10  13  16  19  20  23  26  29  30
  4   8  10  14  18  20  24  28  30  34  38  40
  5   A  13  18  21  26  2B  34  39  42  47  50
  6  10  16  20  26  30  36  40  46  50  56  60
  7  12  19  24  2B  36  41  48  53  5A  65  70
  8  14  20  28  34  40  48  54  60  68  74  80
  9  16  23  30  39  46  53  60  69  76  83  90
  A  18  26  34  42  50  5A  68  76  84  92  A0
  B  1A  29  38  47  56  65  74  83  92  A1  B0
 10  20  30  40  50  60  70  80  90  A0  B0 100

```

```
{...}(18);
  1   2   3   4   5   6   7   8   9   A   B   C   D   E   F   G   H  10
  2   4   6   8   A   C   E   G  10  12  14  16  18  1A  1C  1E  1G  20
  3   6   9   C   F  10  13  16  19  1C  1F  20  23  26  29  2C  2F  30
  4   8   C   G  12  16  1A  1E  20  24  28  2C  2G  32  36  3A  3E  40
  5   A   F  12  17  1C  1H  24  29  2E  31  36  3B  3G  43  48  4D  50
  6   C  10  16  1C  20  26  2C  30  36  3C  40  46  4C  50  56  5C  60
  7   E  13  1A  1H  26  2D  32  39  3G  45  4C  51  58  5F  64  6B  70
  8   G  16  1E  24  2C  32  3A  40  48  4G  56  5E  64  6C  72  7A  80
  9  10  19  20  29  30  39  40  49  50  59  60  69  70  79  80  89  90
  A  12  1C  24  2E  36  3G  48  50  5A  62  6C  74  7E  86  8G  98  A0
  B  14  1F  28  31  3C  45  4G  59  62  6D  76  7H  8A  93  9E  A7  B0
  C  16  20  2C  36  40  4C  56  60  6C  76  80  8C  96  A0  AC  B6  C0
  D  18  23  2G  3B  46  51  5E  69  74  7H  8C  97  A2  AF  BA  C5  D0
  E  1A  26  32  3G  4C  58  64  70  7E  8A  96  A2  AG  BC  C8  D4  E0
  F  1C  29  36  43  50  5F  6C  79  86  93  A0  AF  BC  C9  D6  E3  F0
  G  1E  2C  3A  48  56  64  72  80  8G  9E  AC  BA  C8  D6  E4  F2  G0
  H  1G  2F  3E  4D  5C  6B  7A  89  98  A7  B6  C5  D4  E3  F2  G1  H0
 10  20  30  40  50  60  70  80  90  A0  B0  C0  D0  E0  F0  G0  H0 100

```
> 3 votes

# Answer
## Python 3, 126 - 20% = 100.8 bytes

The outer function, `t`, is the one that actually prints the multiplication table. The inner function, `i`, does the conversion of a number to a base from 2 to 36.

```
def t(b):
 i=lambda n:(n>=b and i(n//b)or'')+chr(n%b+[48,55][n%b>9]);R=range(b)
 for r in R:print(*('%3s'%i(~r*~c)for c in R))

```

Hat tip to Boomerang for their solution, and for a golfing tip. I avoided copying anything from Boomerang's solution, but I did allow myself glances at it to see where I could trim more out. And even before that, I found that the more I golfed it, the more mine started to look like Boomerang's!
> 3 votes

# Answer
# JavaScript (ES6) 84 (105-20%)

The obvious way, to begin with.

```
n=>{for(o=i=``;i++<n;o+=`
`)for(j=0;j++<n;)o+=(`   `+(i*j).toString(n)).slice(-4).toUpperCase();alert(o)}

```

Notes

* It's a pity js toString produce lowercase letters
* `alert` is not the best way to output the table, but it's the shorter, as there is an explicit request to "display on screen"
* Just returning the value would be a couple bytes shorter.

**Less golfed**

```
n=>{
  for(o='', i=0; i++<n; o+='\n')
    for(j=0;j++<n;)
       o+=('   '+(i*j).toString(n)).slice(-4).toUpperCase()
  alert(o)
}

```
> 3 votes

# Answer
# Javascript (ES6) 96.8 93.6 Bytes (20% of 117)

```
n=>{b='';for(i=0;i++<n;b+=`\n`)for(j=0;j++<n;)a=(i*j).toString(n).toUpperCase(),b+=' '.repeat(4-a.length)+a;alert(b)}

```

## Explanation

```
n=>
    {
      b='';                                    //clear table var at each run
      for(i=0;i++<n;b+=`\n`)                   //iterate through rows
        for(j=0;j++<n;)                        //iterate through cols
          a=(i*j).toString(n).toUpperCase(),   //get desired number
          b+=' '.repeat(4-a.length)+a";        //pad to right
    alert(b)                                   //display result
}

```

-*saved 4 bytes thanks to @edc65*
> 3 votes

# Answer
## MATLAB, 111\*0.8=88.8 110\*0.8=88 bytes

My debut here:

```
@(N)disp(reshape(strrep(strrep([' ',strjoin(cellstr(dec2base([1:N]'*[1:N],N)))],' 0','  '),' 0','  '),4*N,N)')

```

Explanation:

`[1:N]'*[1:N]` make multiplication table in base 10

`dec2base([1:N]'*[1:N],N)` convert to base 12. The output is char array with leading 0-s

`strjoin(cellstr(dec2base(___)))` convert to cell and back to char joining strings with space yielding 1x575 string

`[' ',strjoin(___)]` append space to have 576 elements

`strrep(___,' 0',' ')` remove one leading zero. We do it twice because we have strings with two leading zeros

`reshape(___,4*N,N)'` convert 1x576 char array into 48x12 char array

`disp(___)` display the result without `ans =`

Output:

```
 1   2   3   4   5   6   7   8   9   A   B  10
 2   4   6   8   A  10  12  14  16  18  1A  20
 3   6   9  10  13  16  19  20  23  26  29  30
 4   8  10  14  18  20  24  28  30  34  38  40
 5   A  13  18  21  26  2B  34  39  42  47  50
 6  10  16  20  26  30  36  40  46  50  56  60
 7  12  19  24  2B  36  41  48  53  5A  65  70
 8  14  20  28  34  40  48  54  60  68  74  80
 9  16  23  30  39  46  53  60  69  76  83  90
 A  18  26  34  42  50  5A  68  76  84  92  A0
 B  1A  29  38  47  56  65  74  83  92  A1  B0
10  20  30  40  50  60  70  80  90  A0  B0 100

```

If we don't count statement `N=12;`, `5*.8=4` bytes are saved. Also, if `ans =` output is tolerated, then we can remove `disp()` saving another `6*0.8=4.8` bytes. Of course, there may be other ways to save bytes :)
> 2 votes

# Answer
# Python 3: ~~166~~ ~~161~~ 152 - 20% = 121.6 bytes

I know it's inferior to the existing Python answers but I figured to give it a shot. It's my first time posting on this site…

```
def t(b):
 r=range(1,b+1);f=lambda x:x and f(x//b)+chr((55,48)[x%b>9]+x%b)or''
 print('\n'.join(''.join(B)for B in(('%4s'%f(i*j)for j in r)for i in r)))

```
> 2 votes

# Answer
## APL, ~~32~~ 31×0.8=24.8 bytes

```
{¯4↑¨⊃∘(⎕D,⎕A)¨¨⍵⊥⍣¯1¨∘.×⍨1+⍳⍵}

```

In origin 0. In English:

* `∘.×⍨1+⍳⍵`: multiplication table
* `⍵⊥⍣¯1¨`: express in base ⍵ each element of the multiplication table
* `⊃∘(⎕D,⎕A)¨¨`: convert the table of vector of numbers into a table of vectors of chars
* `¯4↑¨`: right align to length 4 each element of the result

The default APL print routine does the right thing.

```
      {¯4↑¨(⍵⊥⍣¯1¨∘.×⍨1+⍳⍵)⊃¨¨⊂⊂⎕D,⎕A}13
    1     2     3     4     5     6     7     8     9     A     B     C    10
    2     4     6     8     A     C    11    13    15    17    19    1B    20
    3     6     9     C    12    15    18    1B    21    24    27    2A    30
    4     8     C    13    17    1B    22    26    2A    31    35    39    40
    5     A    12    17    1C    24    29    31    36    3B    43    48    50
    6     C    15    1B    24    2A    33    39    42    48    51    57    60
    7    11    18    22    29    33    3A    44    4B    55    5C    66    70
    8    13    1B    26    31    39    44    4C    57    62    6A    75    80
    9    15    21    2A    36    42    4B    57    63    6C    78    84    90
    A    17    24    31    3B    48    55    62    6C    79    86    93    A0
    B    19    27    35    43    51    5C    6A    78    86    94    A2    B0
    C    1B    2A    39    48    57    66    75    84    93    A2    B1    C0
   10    20    30    40    50    60    70    80    90    A0    B0    C0   100

```
> 2 votes

# Answer
# Vyxal, 20 \\$\times\\$ 0.8 = 16 bytes

```
ɾ:v*$τkdkAJİṅ:fÞGL↳⁋

```

Try it Online!

This could actually be 9\*0.8=7.2 bytes if Vyxal had a gridify builtin and a buitlin to convert to a base as a string (with letters).
> 2 votes

# Answer
# Ruby, ~~69~~ 66 characters - 20% = 52.8

```
->n{(r=1..n).map{|a|puts r.map{|b|"%4s"%(a*b).to_s(n).upcase}*''}}

```

Sample run:

```
2.1.5 :001 > ->n{(r=1..n).map{|a|puts r.map{|b|"%4s"%(a*b).to_s(n).upcase}*''}}[4]
   1   2   3  10
   2  10  12  20
   3  12  21  30
  10  20  30 100

```
> 1 votes

# Answer
# ksh93, 51 * 0.8 == 40.8 bytes

```
eval echo "'
' {"{1..$1}'..$((++n*$1))..$n%3..$1d}'

```

This should work up to base 64 (the largest radix supported by ksh). Examples:

```
 $ n= ksh -s 12 <<\EOF
eval echo "'
' {"{1..$1}'..$((++n*$1))..$n%3..$1d}'
EOF

   1   2   3   4   5   6   7   8   9   a   b  10
   2   4   6   8   a  10  12  14  16  18  1a  20
   3   6   9  10  13  16  19  20  23  26  29  30
   4   8  10  14  18  20  24  28  30  34  38  40
   5   a  13  18  21  26  2b  34  39  42  47  50
   6  10  16  20  26  30  36  40  46  50  56  60
   7  12  19  24  2b  36  41  48  53  5a  65  70
   8  14  20  28  34  40  48  54  60  68  74  80
   9  16  23  30  39  46  53  60  69  76  83  90
   a  18  26  34  42  50  5a  68  76  84  92  a0
   b  1a  29  38  47  56  65  74  83  92  a1  b0
  10  20  30  40  50  60  70  80  90  a0  b0 100

 $ n= ksh -s 22 <<\EOF
eval echo "'
' {"{1..$1}'..$((++n*$1))..$n%3..$1d}'
EOF

   1   2   3   4   5   6   7   8   9   a   b   c   d   e   f   g   h   i   j   k   l  10
   2   4   6   8   a   c   e   g   i   k  10  12  14  16  18  1a  1c  1e  1g  1i  1k  20
   3   6   9   c   f   i   l  12  15  18  1b  1e  1h  1k  21  24  27  2a  2d  2g  2j  30
   4   8   c   g   k  12  16  1a  1e  1i  20  24  28  2c  2g  2k  32  36  3a  3e  3i  40
   5   a   f   k  13  18  1d  1i  21  26  2b  2g  2l  34  39  3e  3j  42  47  4c  4h  50
   6   c   i  12  18  1e  1k  24  2a  2g  30  36  3c  3i  42  48  4e  4k  54  5a  5g  60
   7   e   l  16  1d  1k  25  2c  2j  34  3b  3i  43  4a  4h  52  59  5g  61  68  6f  70
   8   g  12  1a  1i  24  2c  2k  36  3e  40  48  4g  52  5a  5i  64  6c  6k  76  7e  80
   9   i  15  1e  21  2a  2j  36  3f  42  4b  4k  57  5g  63  6c  6l  78  7h  84  8d  90
   a   k  18  1i  26  2g  34  3e  42  4c  50  5a  5k  68  6i  76  7g  84  8e  92  9c  a0
   b  10  1b  20  2b  30  3b  40  4b  50  5b  60  6b  70  7b  80  8b  90  9b  a0  ab  b0
   c  12  1e  24  2g  36  3i  48  4k  5a  60  6c  72  7e  84  8g  96  9i  a8  ak  ba  c0
   d  14  1h  28  2l  3c  43  4g  57  5k  6b  72  7f  86  8j  9a  a1  ae  b5  bi  c9  d0
   e  16  1k  2c  34  3i  4a  52  5g  68  70  7e  86  8k  9c  a4  ai  ba  c2  cg  d8  e0
   f  18  21  2g  39  42  4h  5a  63  6i  7b  84  8j  9c  a5  ak  bd  c6  cl  de  e7  f0
   g  1a  24  2k  3e  48  52  5i  6c  76  80  8g  9a  a4  ak  be  c8  d2  di  ec  f6  g0
   h  1c  27  32  3j  4e  59  64  6l  7g  8b  96  a1  ai  bd  c8  d3  dk  ef  fa  g5  h0
   i  1e  2a  36  42  4k  5g  6c  78  84  90  9i  ae  ba  c6  d2  dk  eg  fc  g8  h4  i0
   j  1g  2d  3a  47  54  61  6k  7h  8e  9b  a8  b5  c2  cl  di  ef  fc  g9  h6  i3  j0
   k  1i  2g  3e  4c  5a  68  76  84  92  a0  ak  bi  cg  de  ec  fa  g8  h6  i4  j2  k0
   l  1k  2j  3i  4h  5g  6f  7e  8d  9c  ab  ba  c9  d8  e7  f6  g5  h4  i3  j2  k1  l0
  10  20  30  40  50  60  70  80  90  a0  b0  c0  d0  e0  f0  g0  h0  i0  j0  k0  l0 100

```
> 1 votes

# Answer
## Pyke, 14 bytes * 0.8 = 11.2 bytes, noncompetitive

```
QhD]UA*MbQMl2P

```

Try it here!

Explanation:

```
            - autoassign Q = eval_or_not_input()
QhD]        - [Q+1, Q+1]
    U       - nd_range(^)
     A*     - apply(*, ^)
       MbQ  - map(base(Q), ^)
          Ml2 - map(lower, ^)
          P - print_grid(^)

```

Or 12 bytes without the bonus

```
13D]UA*Mb12P

```
> 0 votes

---
Tags: code-golf, number, kolmogorov-complexity, base-conversion
---


title: Ot wes thi bist uf tomis

text:
# Question
Title: Ot wes thi bist uf tomis
I just love this simple cypher, it's so fun reading not-quite human-readable words and filling the gaps...

```
Ot wes thi bist uf tomis, ot wes thi wurst uf tomis,
ot wes thi egi uf wosdum, ot wes thi egi uf fuuloshniss,
ot wes thi ipuch uf biloif, ot wes thi ipuch uf oncridaloty,
ot wes thi siesun uf loght, ot wes thi siesun uf derkniss,
ot wes thi sprong uf hupi, ot wes thi wontir uf dispeor,
wi hed ivirythong bifuri as, wi hed nuthong bifuri as,
wi wiri ell guong dorict tu hievin, wi wiri ell guong dorict thi uthir wey –
on shurt, thi piroud wes su fer loki thi prisint piroud,
thet sumi uf ots nuosoist eathurotois onsostid un ots biong riciovid,
fur guud ur fur ivol, on thi sapirletovi digrii uf cumperosun unly.

```

The rules are super-simple:

* Accept some text as input (ascii characters, upper/lower case letters and punctuation).
* For each vowel, rotate it to the next vowel, or back to the start.
    + a =\> e
    + e =\> i
    + i =\> o
    + o =\> u
    + u =\> a
* Upper case vowels stay upper case, lower case vowels stay lower case.
* Output the text after these conversions.
* No need to support accents.
* The all other characters should remain unchanged.
* Try to do it in the smallest number of bytes.
* Any old language you like.

---

## Test Cases

```
It was the best of times, it was the worst of times,
it was the age of wisdom, it was the age of foolishness,
it was the epoch of belief, it was the epoch of incredulity,
it was the season of light, it was the season of darkness,
it was the spring of hope, it was the winter of despair,
we had everything before us, we had nothing before us,
we were all going direct to heaven, we were all going direct the other way –
in short, the period was so far like the present period,
that some of its noisiest authorities insisted on its being received,
for good or for evil, in the superlative degree of comparison only.

```

Out:

```
Ot wes thi bist uf tomis, ot wes thi wurst uf tomis,
ot wes thi egi uf wosdum, ot wes thi egi uf fuuloshniss,
ot wes thi ipuch uf biloif, ot wes thi ipuch uf oncridaloty,
ot wes thi siesun uf loght, ot wes thi siesun uf derkniss,
ot wes thi sprong uf hupi, ot wes thi wontir uf dispeor,
wi hed ivirythong bifuri as, wi hed nuthong bifuri as,
wi wiri ell guong dorict tu hievin, wi wiri ell guong dorict thi uthir wey –
on shurt, thi piroud wes su fer loki thi prisint piroud,
thet sumi uf ots nuosoist eathurotois onsostid un ots biong riciovid,
fur guud ur fur ivol, on thi sapirletovi digrii uf cumperosun unly.

```

In:

```
The quick brown fox jumps over the lazy dog.

```

Out:

```
Thi qaock bruwn fux jamps uvir thi lezy dug.

```

In:

```
Home is where the heart is.

```

Out:

```
Humi os whiri thi hiert os.

```

In:

```
Boaty McBoatface

```

Out:

```
Buety McBuetfeci

```

In:

```
AEIOUaeiou

```

Out:

```
EIOUAeioua

```

In:

```
Programming Puzzles And Code Golf

```

Out:

```
Prugremmong Pazzlis End Cudi Gulf

```

# Answer
# Stax, 7 bytes

```
öΦΣòC└∞

```

Run and debug it

Try it online!

**Explanation** (unpacked)

```
Vv:tVV:t
Vv:t           #Push aeiou and ring translate it to input
    VV:t       #Push AEIOU and ring translate it to input

```

Might be able to save more, will keep trying.
> 12 votes

# Answer
# MS-SQL, 51 Bytes

Works on SQL 2017 or above:

```
SELECT TRANSLATE(v,'AEIOUaeiou','EIOUAeioua')FROM t

```

The new function `TRANSLATE` performs individual character replacement, so is ideally suited for this challenge.

Input is via a pre-existing table **t** with varchar column **v**, per our IO rules.

In this case the table must be created using a *case-sensitive collation*, either by running on a case-sensitive server, or by using the `COLLATE` keyword (not counted toward character total):

```
CREATE TABLE t(v varchar(max) COLLATE Latin1_General_CS_AS)

```

**EDIT**: SSMS may cut off the lengthy quote above when returning the result in a "results to text" window, this is a client setting, not a bug in my program.

To fix, go to `Tools > Options > Query Results > SQL Server > Results to Text` and increase the "Maximum number of characters displayed in each column."
> 22 votes

# Answer
# Bash + coreutils, 24

```
tr aeiouAEIOU eiouaEIOUA

```

Try it online!
> 15 votes

# Answer
# Haskell, 52 bytes

```
(a:b)!c|a/=c=b!c|1>0=b!!0
a!b=b
map("aeiouaAEIOUA"!)

```

Try it online!

*Lynn saved me two bytes by pointing out that `!!0` is shorter than `head`.*

## Explanation

If you have never coded in Haskell this will probably look like a pile of jibberish. So first let's ungolf it and then break it down:

```
(a:b)!c
 |   a/=c   = b!c
 |otherwise = b!!0
a!b=b
map("aeiouaAEIOUA"!)

```

First we have a function `!`, which takes a string `s` and a character `c`. Our first pattern match catches accepts input if the string is non-empty. If the string is non-empty we compare its first character to `c`. If it's first character is not equal to `c` we toss it and call `!` again with the remainder of the string and `c`. If it is equal we return the second character in the string.

Our next pattern match catches the string in all other cases, that is if the string is empty. In this case we just return `c`.

All in all this function takes a character `c` and a string `s` and returns the character after the first occurrence of `c` in `s`. If we pass this with `aeiouaAEIOUA` it will perform our cipher on a single character. To make our whole function we ought to map this across the string.
> 14 votes

# Answer
# Retina, ~~10~~ ~~9~~ 8 bytes

```
T`uo`vVA

```

Try it online!

Saved 1 byte thanks to Neil! And another byte thanks to Martin!

The new version of retina has vowel classes, which makes the result a bit shorter. The transliteration also makes use of the "other" class. So the `to` class looks like "aeiouAEIOUA" while the `from` class looks like "uaeiouAEIOUA"

This doesn't cause any problems since the second `u` mapping to `A` will never be done since `u` was already mapped to `a`.
> 12 votes

# Answer
# Perl 5 + -p, ~~24~~ 23 bytes

```
y;AEIOUaeiou;EIOUAeioua

```

Try it online

-1 byte thanks to @DomHastings
> 11 votes

# Answer
# Python 3, ~~62~~ 59 bytes

```
lambda x:x.translate(dict(zip(b'aeiouAEIOU','eiouaEIOUA')))

```

Make a translation table (dictionary) ~~with `str`'s static `str.maketrans` method~~. Translate relevant characters to their destination character.

EDIT: Saved 3 bytes by using the `dict` constructor to make the translation table instead of the `str#maketrans` method
> 8 votes

# Answer
# C, ~~85~~ ~~76~~ ~~67~~ ~~65~~ 64 bytes

```
f(char*c){for(;*c;)putchar(1[index("AEIOUAaeioua",*c++)?:c-2]);}

```

Port of Kevin Cruijssen's Java answer. Try it online here.

Thanks to Kevin Cruijssen for golfing 9 bytes, to Christoph for golfing 11 bytes and to ceilingcat for golfing 1 byte.

Ungolfed version:

```
f(char* c) { // function taking a char array as parameter and implicitly returning an unused int
    for(; *c ;) // loop over the input
        putchar(1 [index("AEIOUAaeioua", * c++) ?: c-2]); // find the first pointer to the current char in the vowels string, NULL if not present; if it's not NULL, print the next vowel, otherwise just print the char
}

```
> 8 votes

# Answer
# , 43 bytes

```
chartr("AEIOUaeiou","EIOUAeioua",scan(,""))

```

Try it online!

Here's my solution wrapped in a `cat` to get it to print out more nicely: Try it online!
> 6 votes

# Answer
# Ruby `-p`, 31 bytes

```
$_.tr!"AEIOUaeiou","EIOUAeioua"

```

Try it online!
> 5 votes

# Answer
# Jelly, 11 bytes

```
Øcs5ṙ€-Ẏ,Ʋy

```

Try it online!
> 5 votes

# Answer
# Python 2, ~~79~~ ~~68~~ 67 bytes

-1 byte thanks to @ArnoldPalmer

```
V='uaeiouAEIOUA'
print''.join((V[1:]+c)[V.find(c)]for c in input())

```

Try it online!
> 5 votes

# Answer
# JavaScript (ES6), 60 bytes

```
s=>s.replace(/./g,c=>(S='aeiouaAEIOUA'+c+c)[S.indexOf(c)+1])

```

Try it online!
> 5 votes

# Answer
# 05AB1E, ~~14~~ ~~13~~ 11 bytes

```
žMDÀ‡žMuDÀ‡

```

Try it online!
> 4 votes

# Answer
# Pyth, 17 bytes

```
em=.rQdrB"aeiou"1

```

Try it here

```
em=.rQdrB"aeiou"1
 m                  For each string...
       rB"aeiou"1   ... in ['aeiou', 'AEIOU']...
  =.rQd             ... cyclically rotate the characters in the input.
e                   Take the last.

```
> 4 votes

# Answer
# Japt 2.0, ~~25~~ 21 bytes

I had fun golfing this one with Shaggy.

```
r\v@=`aeia`pu)g1+UbX

```

Run it here.
> 4 votes

# Answer
# Java 10, ~~97~~ 87 bytes

```
s->{for(var c:s){var t="AEIOUAaeioua"+c+c;System.out.print(t.charAt(t.indexOf(c)+1));}}

```

-10 bytes after being inspired by *@Arnauld*'s JavaScript answer (his 60-bytes version).

Try it online.

**Explanation:**

```
s->{                         // Method with character-array parameter and no return-type
  for(var c:s){              //  Loop over the input characters
    var t="AEIOUAaeioua"     //  Temp-String containing the order of vowels
                             //  (including additional 'A' and 'a'),
          +c+c;              //  appended with two times the current character
    System.out.print(        //  Print:
      t.charAt(              //   The character in String `t` at index:
         t.indexOf(c)+1));}} //    The (first) index of the current character in `t` + 1

```
> 4 votes

# Answer
# Retina 0.8.2, 20 bytes

```
T`_o`A\EI\OUAaei\oua

```

Try it online! Link includes test cases.
> 3 votes

# Answer
# APL+WIN, 55 bytes

Prompts for input string:

```
i←(10≥n←'AEIOUaeiou'⍳s)/⍳⍴s←⎕⋄s[i]←'EIOUAeioua'[n~11]⋄s

```
> 3 votes

# Answer
# Elm, ~~127~~ ~~123~~ ~~121~~ ~~112~~ 103 bytes

*9 bytes saved by Hydrazer*

```
f a b=case a of
 c::d::e->if c==b then d else f(d::e)b
 _->b
String.map(String.toList"aeiouaAEIOUA"|>f)

```

## Explanation

This Elm answer is a port of my Haskell answer. I am still learning Elm so there might be a good deal of golfing that can be done. There are a couple of differences here between Elm and Haskell. Elm does not allow multiple declarations of a function so we have to use `case` instead. Elm is also rather fussy about strings. They are not list of characters and thus have to be treated differently then lists. In fact in order to do any useful of manipulations on strings we pretty much have to just convert them to lists. Aside from that there are a couple of small differences `::` is the list cons operator and `(|>)=flip($)`.

You can test the code here, with the following wrapper:

```
import Html exposing (text)
f a b=case a of
 c::d::e->if c==b then d else f(d::e)b
 _->b
g=String.map(String.toList"aeiouaAEIOUA"|>f)
main=g"It was a dark and stormy night"|>text

```
> 3 votes

# Answer
# Mumps, 38 bytes

```
R T W $TR(T,"AEIOUaeiou","EIOUAeioua")

```

Mumps doesn't normally add a carriage return, as I didn't see a requirement to separate input from output it does look a bit weird on first run. For example, the output for the last test case looks like this:

```
Programming Puzzles And Code GolfPrugremmong Pazzlis End Cudi Gulf

```

If you did want to add a carriage return, add two bytes thusly:

```
R T W !,$TR(T,"AEIOUaeiou","EIOUAeioua")

```
> 3 votes

# Answer
# Vim + tpope/vim-abolish, 30 bytes

```
:%S/{a,e,i,o,u}/{e,i,o,u,a}/g<cr>

```

Alternate solution, also 30 bytes:

```
Oe,i,o,u<esc>|D:%s/{a,<C-r>"}/{<C-r>",a}/g

```

According to meta, vim answers can use plugins with no byte penalty. This is not a vim answer, but a *vim + abolish* answer.

---

Abolish is an extremely useful plugin. This section of the README nicely describes how this command (the `Subvert` command) works.
> 3 votes

# Answer
# CJam, 29 19 bytes

```
q"aeioua"_eu+_1m<er

```

Try it online!

-10 bytes thanks to @Peter Taylor

Explanation:

```
q                       # take all input
 "aeioua"               # push vowel pairs
         _eu            # duplicate, uppercase
            +_          # concatenate, duplicate again
              1m<       # rotate left by 1
                 er     # transliterate

```
> 3 votes

# Answer
# AutoHotkey, 24 bytes

AuotHotkey automatically replaces letters in a case sensitive manner.

```
a::e
e::i
i::o
o::u
u::a

```
> 3 votes

# Answer
# Vyxal, 9 bytes

```
k∨:½ƛǓ;∑Ŀ

```

Try it Online!

Basic transliteration.
> 3 votes

# Answer
# Vyxal, 6 bytes

```
kv*kV*

```

Try it Online!

```
  *    # Ring translate by
kv     # Lowercase vowels
     * # Ring translate by
   kV  # Uppercase vowels

```
> 3 votes

# Answer
# K (ngn/k), 25 bytes

```
{y^'x[<x]x?y}"UAEIOuaeio"

```

Try it online!
> 3 votes

# Answer
# PHP, 38 bytes

Quite simple, not very creative, uses `strtr` to replace the vowels:

```
<?=strtr($argn,aeiouAEIOU,eiouaEIOUA);

```

Run with `echo '<input>' | php -nF <filename>` or Try it online.
> 2 votes

# Answer
## PHP, 90 Bytes

Try it online

**Code**

```
function f($s){echo strtr($s,array_combine(str_split(UuAaEeIiOo),str_split(AaEeIiOoUu)));}

```

**Explanation**

```
function f($s){
 echo strtr(
       $s,                          #The string to operate
       array_combine(               #combining arrays
            str_split(UuAaEeIiOo),  #splitting this strings
            str_split(AaEeIiOoUu))
              # With array combine php creates an array like
              # ["U"=>"A", "a"=>"e"....and so on]
              # strtr can replace strings in a string, using an array with
              # the values to replace and with what replace each value.
 );
}

```

**75 Bytes if ran with `php -r` using `$argv`**

```
<?=strtr($argv,array_combine(str_split(UuAaEeIiOo),str_split(AaEeIiOoUu)));

```
> 2 votes

# Answer
# , 33 bytes

```
rplc'aeiou',&((;"0)1&|.)'AEIOU'"1

```

Try it online!
> 2 votes

# Answer
# str, 18 bytes

```
[aeiouaAEIOUA]#D#U

```

Try it online!

## Explanation

```
                       implicit: over each character of the input:
[aeiouaAEIOUA]#D#U
[            ]         push this string
              #D       set this to the operation domain
                #U     set the charcter to the next character in the domain

```
> 2 votes

# Answer
# q/kdb+, ~~36~~ 33 bytes

**Solution:**

```
{(v,2#x)1+(v:"aeiouaAEIOUA")?x}@'

```

**Examples:**

```
q){(v,2#x)1+(v:"aeiouaAEIOUA")?x}@'"AEIOUaeiou"
"EIOUAeioua
q){(v,2#x)1+(v:"aeiouaAEIOUA")?x}@'"Programming Puzzles And Code Golf"
"Prugremmong Pazzlis End Cudi Gulf"

```

**Explanation:**

Figure out index of vowels, add one to push along to the next and index in. Still think this approach can be significantly improved...

```
{(v,2#x)1+(v:"aeiouaAEIOUA")?x}@' / the solution
{                             }@' / apply lambda to each character of input
                            ?x    / look up x in...
          (                )      / do together
             "aeiouaAEIOUA"       / lookup list
           v:                     / save as v
        1+                        / add one
 (     )                          / do together
    2#x                           / take 2 copies of x
  v,                              / prepend v

```

**Bonus:**

My old \**36 byte(()) solution which I think is quite cool, but need to golf down the lists to make it competetive:

```
ssr/[;"uoiea%UOIEA%";"%uoiea%UOIEA"]

```
> 2 votes

# Answer
# Charcoal, 35 bytes

```
ＵＴ≔AUOIEAauoieaσＦ¹¹⊞υ➙§σ⊕ι§σι▷SR⟦Ｓυ

```

Try it online!

Naive method.

### Explanation:

```
ＵＴ                                         Set trim option to on, so output won't be a rectangle
    ≔AUOIEAauoieaσ                          Assign "AUIOEAauioea" to s
                   Ｆ¹¹                      For i (ι) from 0 to 10
                       ⊞υ                   Push to u (initially empty list)
                          ➙                 Rule of:
                            §σ⊕ι            S[i + 1]
                                 §σι         to S[i]. This is so a->A gets overwriteen by a->e
                                    ▷SR⟦Ｓυ  Replace input as string using u (now a list of rules)

```
> 2 votes

# Answer
# **PHP**, 76 bytes.

```
$s=strtr($s,array_combine(str_split("aeiouAEIOU"),str_split("eiouaEIOUA")));

```

Check it out!

This was the shortest I was able to do this in PHP.

```
$s = //overwrite $s variable ($s should be a defined string or input)
    strtr(  //strtr replaces key => value pairs from arrays in a string
        $s, //the string we are converting
        array_combine( //create an array with key value pairs, key should be original vowel letter and value should be it's replacement
            str_split("aeiouAEIOU") //turn vowels (lower and upper) into an array
            ,str_split("eiouaEIOUA") //turn vowel replacements into an array
        )
    );

```
> 2 votes

# Answer
# MATL, 15 bytes

```
,@11+Y2t1_YSXE]

```

Try it on MATL Online
> 2 votes

# Answer
# Python 3:  ~~148 126~~  121 Bytes

Fixed code, saved 22 bytes by not using a flag for case management

Saved 5 bytes by removing uneeded spaces

```
import re;print(re.sub('a|A',r"e",re.sub('e|E',r"i",re.sub('i|I',r"o",re.sub('o|O',r"u",re.sub('u|U',r"a",input()))))))

```

Definitely can be improved if i can figure out how to group patters with their respective groups of replaces. Will probaly save 90+ bytes
> 1 votes

# Answer
# Tcl, 56 bytes

```
proc C s {string map [split aeeiioouuaAEEIIOOUUA ""] $s}

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Classic), ~~54~~ 50 bytes

```
{(X,⍨1⌽v)[X⍳⍨v,X←(⍵,⍨1⌽w)[⍵⍳⍨⍵,⍨w←819⌶v←'AEIOU']]}

```

Try it online!
> 1 votes

# Answer
# sed, 24 bytes

`y/aeiouAEIOU/eiouaEIOUA/`
> 1 votes

# Answer
# GolfScript, 34 bytes

`{.'aeiouAEIOU'?"eiouaEIOUA**0**"=\or}%`

Where **`0`** denotes a null byte. In the TIO link, I had to use `\0`, so it is one byte longer.

Try it online!

Simple transliteration. I tried to build the two strings but it was 15 bytes longer.
> 1 votes

# Answer
# Knight, 85 bytes

```
;=xP Wx;=v"aeiouAEIOU";=iF;W&v!?AxAv;=i+1i=vSvF1"";O+|G"eiouaEIOUA"iT A Ax"\"=xSxF1""

```

Try it online!
> 1 votes

---
Tags: code-golf, text-processing
---


title: Generate a regular graph

text:
# Question
Title: Generate a regular graph
Inspired by this Mathematica.SE post

Given two positive integers \\$n, k\\$ with \\$n \> k \ge 1\\$, output a binary \\$n\times n\\$ matrix such that every row and column contains exactly \\$k\\$ 1s, and the leading diagonal is all zero. This is the adjacency matrix of a regular graph.

You may output any valid matrix, and it does not have to be deterministic. You may output in any reasonable format, including a flat \\$n^2\\$ list, or a nested list, etc.

This is , so the shortest code in bytes wins.

## Test cases

```
n, k -> output
2, 1 -> [[0, 1], [1, 0]]
5, 3 -> [[0, 1, 1, 1, 0], [1, 0, 0, 1, 1], [1, 1, 0, 0, 1], [1, 0, 1, 0, 1], [0, 1, 1, 1, 0]]
3, 1 -> [[0, 1, 0], [0, 0, 1], [1, 0, 0]]
5, 1 -> [[0, 1, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1], [0, 0, 1, 0, 0]]
6, 2 -> [[0, 0, 0, 0, 1, 1], [1, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 1], [0, 0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 0]]
7, 6 -> [[0, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1], [1, 1, 1, 0, 1, 1, 1], [1, 1, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 1, 0]]

```

# Answer
> 6 votes
# Jelly, 5 bytes

```
Ḷṙ`U<

```

Try It Online!

-1 byte thanks to Jonathan Allan

```
Ḷṙ`U<    Main Link; take n, k
Ḷ        [0, 1, 2, ..., n - 1]
  `      Apply with ^ on the left and right:
 ṙ       Rotate left; [[0, 1, 2, ..., n - 1], [1, 2, 3, ..., n - 1, 0], [2, 3, 4, ..., n - 1, 0, 1], ...]
   U     Reverse each; [[n - 1, n - 2, ..., 1, 0], [0, n - 1, n - 2, ..., 2, 1], [1, 0, n - 1, ..., 3, 2], ...]
    <    Is this less than k? [[0, ..., 1, 1, 1], [1, 0, ..., 1, 1], ...]
                                       ^-- k --^

```

# Answer
> 5 votes
# Pari/GP, 33 bytes

```
f(n,k)=matrix(n,,i,j,(i-j-1)%n<k)

```

Try it online!

# Answer
> 5 votes
# Python 2, 45 bytes

Saved 15 bytes thanks to loopy walt! (Using the flat list output option.)

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

```

An unnamed function accepting `n` and `k` that returns a list of booleans

**Try it online!**

# Answer
> 4 votes
# JavaScript (ES6), 50 bytes

*Fixed version now using Jonathan Allan's formula*
*Thanks to @emanresuA for spotting some dead code (-2 bytes)*

Expects `(n)(k)`, returns a flat array of Boolean values.

```
n=>k=>[...Array(n*n)].map((_,x)=>(x+~(x/n)+n)%n<k)

```

Try it online! (raw output)
Try it online! (with post-processing)

# Answer
> 4 votes
# Jelly, 6 bytes

```
Ḷ_þ%Ɗ<

```

Try It Online!

# Answer
> 4 votes
# Factor \+ `math.matrices`, ~~64~~ 60 bytes

```
[ dupd dupd '[ - 1 - _ rem _ < 1 0 ? ] <matrix-by-indices> ]

```

The `<matrix-by-indices>` word postdates build 1525 (the one TIO uses), so here's a screenshot of running this in Factor's REPL:

This is a port of @alephalpha's Pari/GP answer. `<matrix-by-indices>` is a combinator with stack effect `( ... m n quot: ( ... i j -- ... elt ) -- ... matrix )`. In other words, it lets you generate an `m`x`n` matrix but leaves the indices of each element (`i`, `j`) on top of the stack while you do so.

# Answer
> 3 votes
# MathGolf, 9 bytes

```
rxm<k(Å_╪

```

Outputs all rows concatenated to the stack.

Try it online.

**Explanation:**

```
r          # Push a list in the range [0, first (implicit) input n)
 x         # Reverse it to range (n,0]
  m        # Map over each integer:
   <       #  Check if it's larger than the second (implicit) input k
    k      # Push the first input n again
     (     # Decrease it by 1
      Å    # Loop that many times,
           # using the following 2 characters as inner code-block:
       _   #  Duplicate the top list
        ╪  #  Rotate the items in the list once towards the right
           # (after which the entire stack is output implicitly as result)

```

# Answer
> 3 votes
# Apl

**67 bytes**

`{{(⍴⍵)⍴{⍵[?⍨≢⍵]}∊⍵}⍣{((∧/2=/+/,+⌿)⍺)∧∧/~1 1⍉⍺}⍵ ⍵⍴⍺(⍺-⍵)/1 0}`

incredebly ineffecent ,might be needlessly long

explantion

`{{(⍴⍵)⍴{⍵[?⍨≢⍵]}∊⍵}` shuffles array randomly untill

`{∧/~1 1⍉⍺}`digonal is all 0s

`{((∧/2=/+/,+⌿)⍺)}` and sum of all the rows and column is the same

`{⍵ ⍵⍴⍺(⍺-⍵)/1 0}` makes a n×n matrix of right argument with required 0s and 1s

# Answer
> 3 votes
# , ~~49~~ ~~40~~ 38 bytes

*Edit: -9 bytes thanks to Giuseppe*

```
function(n,k)outer(1:n-1,1:n,`-`)%%n<k

```

Try it online!

Returns a matrix with values `TRUE`/`FALSE` (which evaluate to `1`/`0` in ). Add +3 bytes to output as a matrix with `1`s and `0`s directly.

---

Or my very lazy first attempt:

# , 93 bytes

```
function(n,k,`?`=rowSums){while(any(c(?(m=matrix(sample(1:0,n^2,T),n)),?t(m))-k,diag(m)))0;m}

```

Try it online!

Extremely inefficient (and often times-out on TIO even for the n≥5 test-cases), but will eventually (= nonzero probability) deliver the right answer each time.

Samples random matrices of `0`, `1` until a solution is found that satisfies the rowSums, colSums & diag conditions.

# Answer
> 2 votes
# Charcoal, 16 bytes

```
ＮθＮηＥθ⮌⭆θ‹﹪⁺ιλθη

```

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

```
Ｎθ                  First input `n` as a number
  Ｎη                Second input `k` as a number
     θ              First input
    Ｅ               Map over implicit range
        θ           First input
       ⭆            Map over implicit range and join
            ι       Row index
           ⁺        Plus
             λ      Column index
          ﹪         Modulo
              θ     First input
         ‹          Is less than
               η    Second input
      ⮌             Reversed
                    Implicitly print

```

# Answer
> 2 votes
# Retina 0.8.2, 38 bytes

```
\d+
$*0
(0+) \1
$.1$*
.
$'$`$&¶
O$^`.+

```

Try it online! Link includes test cases. Output includes trailing newlines. Explanation:

```
\d+
$*0

```

Convert both inputs to strings of `0`s.

```
(0+) \1
$.1$*

```

Subtract `k` from `n` and convert it to a string of `1`s, so there are now `n-k` `0`s and `k` `1`s.

```
.
$'$`$&¶

```

Generate the cyclic permutations of that string in reverse order.

```
O$^`.+

```

Reverse the permutations into the desired order. (Normally the `$` needs another line to specify the sort key but this is an edge case where it's not needed.)

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

```
IdentityMatrix@#~RotateLeft~n~Sum~{n,#2}&

```

Try it online!

# Answer
> 2 votes
# Ruby, 49 bytes

```
->a,b{a.times.map{|c|([0]*(a-b)+[1]*b).rotate c}}

```

Try it online!

# Answer
> 2 votes
# APL+WIN, ~~23~~ 21 bytes

Prompts for k followed by n. Index origin = 0

```
(⌽⍳n)⌽(n,n)⍴(n←⎕)↑⎕⍴1

```

Try it online!Thanks to Dyalog Classic

# Answer
> 2 votes
# APL (Dyalog Unicode), 16 bytes

```
{↑(-⍳⍵)⌽¨⊂⍵↑⍺⍴1}

```

Try it online!

Generates a fixed pattern by rotating each row by its index.

---

# APL (Dyalog Unicode), 41 bytes

```
{{⍵[?⍨≢⍵]}⍤1⍣{(~1 1⍉⍺)∧.=≢∪+⌿⍺}↑⍵/⊂⍵↑⍺/1}

```

Try it online!

Shuffles each row until the conditions are satisfied.

# Answer
> 2 votes
# Vyxal, 7 bytes

```
ɾṘ≥:(…ǔ

```

Try it Online!

# Answer
> 2 votes
# Knight, 49 bytes

```
;=xE P;=yE P;=i~1W>^x 2=i+1iO+0>y%+x%--/i x iTx x

```

Try it online!

# Answer
> 1 votes
# Python3, 223 bytes:

```
from itertools import*
def f(n,k,c=[]):
 if len(c)==n:yield c
 else:
  for i in product(*[{0,not c or(i!=len(c)and sum([*zip(*c)][i])<k)}for i in range(n)]):
   if sum(i)==k:yield from f(n,k,c+[i])
g=lambda n,k:next(f(n,k))

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 7 bytes

```
LR@Dv=Á

```

Pretty similar approach as my MathGolf answer.
Outputs all rows-lists on a separated line.

Try it online or verify all test cases.

**Explanation:**

```
L        # Push a list in the range [1, first (implicit) input n]
 R       # Reverse it to [n,1]
  @      # Check for each value if the second (implicit) input k >= the value
   D     # Duplicate this list
    v    # Pop and loop its size amount of times:
     =   #  Print the list with trailing newline (without popping)
      Á  #  Rotate its items once towards the right

```

# Answer
> 1 votes
# brev, 82

```
(lambda(n k)((over(with i((over(if(or(= i it)(> i k))0 1))x)))(make'()n(iota n))))

```

---
Tags: code-golf, graph-theory, open-ended-function, binary-matrix
---