title: Cofactor Matrices

text:
# Question
Title: Cofactor Matrices
The cofactor matrix is the transpose of the Adjugate Matrix. The elements of this matrix are the cofactors of the original matrix.

The cofactor  (i.e. the element of the cofactor matrix at row i and column j) is the determinant of the submatrix formed by deleting the ith row and jth column from the original matrix, multiplied by (-1)^(i+j).

For example, for the matrix

The element of the cofactor matrix at row 1 and column 2 is:

You can find info on what the determinant of a matrix is and how to calculate them here.

### Challenge

Your goal is to output the cofactor matrix of an input matrix.

**Note**: Built-ins that evaluate cofactor matrices, or adjugate matrices, or determinants or anything similar are **allowed**.

### Input

The matrix may be inputed as a command line argument, as a function parameter, in `STDIN` or in any way that is most appropriate for the language you use.

The matrix will be formatted as a list of lists, each sublist corresponding to one row, which contains factors ordered from left to right. Rows are ordered from top to bottom in the list.

For example, the matrix

```
a b
c d

```

will be represented by `[[a,b],[c,d]]`.

You may replace the square brackets and commas with something else if it fits your language and is sensible (e.g. `((a;b);(c;d))`)

Matrices will **only contain integers (which can be negative)**.

Matrices will **always be square** (i.e. same number of rows and columns).

You may assume that the input will always be correct (i.e. no formatting problem, nothing other than integers, no empty matrix).

### Output

The resulting cofactor matrix may be outputed to `STDOUT`, returned from a function, written to a file, or anything similar that naturally suits the language you use.

The cofactor matrix must be formatted in the exact same way the input matrices are given, e.g. `[[d,-c],[-b,a]]`. If you read a string, then you must return/output a string in which the matrix is formatted exactly like in the input. If you use something like e.g. a list of lists as input, then you must return a list of lists too.

### Test cases

* Input: `[[1]]`

Output: `[[1]]`

* Input: `[[1,2],[3,4]]`

Output: `[[4,-3],[-2,1]]`

* Input: `[[-3,2,-5],[-1,0,-2],[3,-4,1]]`

Output: `[[-8,-5,4],[18,12,-6],[-4,-1,2]]`

* Input: `[[3,-2,7,5,0],[1,-1,42,12,-10],[7,7,7,7,7],[1,2,3,4,5],[-3,14,-1,5,-9]]`

Output:

```
[[9044,-13580,-9709,23982,-9737],[-1981,1330,3689,-3444,406],[14727,7113,2715,-9792,414],[-28448,-2674,-707,16989,14840],[-2149,2569,-2380,5649,-3689]]

```

### Scoring

This is so the shortest answer in bytes wins.

# Answer
# J, 29 bytes

```
3 :'<.0.5+|:(-/ .**%.)1e_9+y'

```

Same epsilon/inverse/determinant trick. From right to left:

* `1e_9+` adds an epsilon,
* `(-/ .**%.)` is *determinant* (`-/ .*`) times *inverse* (`%.`),
* `|:` transposes,
* `<.0.5+` rounds.
> 1 votes

# Answer
# Matlab, ~~42~~ 33 bytes

Using an anonymous function:

```
@(A)round(inv(A+eps)'*det(A+eps))

```

Input and output are matrices (2D numeric arrays).

`eps` is added in case the matrix is singular. It is "removed" using `round` (the true result is guaranteed to be an integer).

Example:

```
>> @(A)round(inv(A+eps)'*det(A+eps))
ans =
    @(A)round(inv(A+eps)'*det(A+eps))
>> ans([-3,2,-5; -1,0,-2; 3,-4,1])
ans =
-8    -5     4
18    12    -6
-4    -1     2

```

Example with singular matrix:

```
>> @(A)round(inv(A+eps)'*det(A+eps))
ans =
    @(A)round(inv(A+eps)*det(A+eps)')
>> ans([1,0 ; 0,0])
ans =
     0     0
     0     1

```

Or try it online in Octave.
> 5 votes

# Answer
# Mathematica, ~~27~~ 35 bytes

```
Thread[Det[#+x]Inverse[#+x]]/.x->0&

```
> 4 votes

# Answer
# R, ~~121~~ 94 bytes

```
function(A)t(outer(1:(n=NROW(A)),1:n,Vectorize(function(i,j)(-1)^(i+j)*det(A[-i,-j,drop=F]))))

```

This is an absurdly long function that accepts an object of class `matrix` and returns another such object. To call it, assign it to a variable.

Ungolfed:

```
cofactor <- function(A) {
    # Get the number of rows (and columns, since A is guaranteed to
    # be square) of the input matrix A
    n <- NROW(A)

    # Define a function that accepts two indices i,j and returns the
    # i,j cofactor
    C <- function(i, j) {
        # Since R loves to drop things into lower dimensions whenever
        # possible, ensure that the minor obtained by column deletion
        # is still a matrix object by adding the drop = FALSE option
        a <- A[-i, -j, drop = FALSE]

        (-1)^(i+j) * det(a)
    }

    # Obtain the adjugate matrix by vectorizing the function C over
    # the indices of A
    adj <- outer(1:n, 1:n, Vectorize(C))

    # Transpose to obtain the cofactor matrix
    t(adj)
}

```
> 3 votes

# Answer
# GAP, 246 Bytes

You can tell this is good coding by the triple nested for-loops.

It's pretty straightforward. GAP doesn't really have the same tools to deal with matrices that other math oriented languages do. The only thing really used here is the built in determinant operator.

```
f:=function(M)local A,B,i,j,v;A:=StructuralCopy(M);if not Size(M)=1 then for i in [1..Size(M)] do for j in [1..Size(M)] do B:=StructuralCopy(M);for v in B do Remove(v,j);od;Remove(B,i);A[i][j]:= (-1)^(i+j)*DeterminantMat(B);od;od;fi;Print(A);end;

```

ungolfed:

```
f:=function(M)
    local A,B,i,j,v;
    A:=StructuralCopy(M);
    if not Size(M)=1 then
        for i in [1..Size(M)] do
            for j in [1..Size(M)] do
                B:=StructuralCopy(M);
                for v in B do
                    Remove(v,j);
                od;
                Remove(B,i);
                 A[i][j]:= (-1)^(i+j)*DeterminantMat(B);
            od;
        od;
    fi;
    Print(A);
end;

```
> 2 votes

# Answer
# Verbosity v2, 196 bytes

```
IncludeTypePackage<Matrix>
IncludeTypePackage<OutputSystem>
print=OutputSystem:NewOutput<DEFAULT>
input=Matrix:Adjugate<ARGV0>
input=Matrix:Transpose<input>
OutputSystem:DisplayAsText<print;input>

```

Try it online!

NB: Doesn't currently work on TIO, awaiting a pull. Should work offline

Takes input in the form `((a b)(c d))` to represent

$$ \bigg\[ \begin{matrix} a \\: b \\ c \\: d \end{matrix} \bigg\] $$

Despite having a builtin for the adjugate, Verbosity's verbosity still cripples it. Fairly basic how it works, just transposes the adjugate of the input.
> 1 votes

---
Tags: code-golf, math, matrix, linear-algebra
---


title: Determine if a Graph is Toroidal

text:
# Question
Title: Determine if a Graph is Toroidal
A simple graph is toroidal if it can be drawn on the surface of a torus without any edges intersecting. Your task is to take a simple undirected graph via any reasonable method (adjacency matrix, edge vertex sets, etc.) and decide whether or not it is a toroidal graph. You should output one of two distinct values for each of the two decisions. You may choose what these values are.

This is so answers will be scored in bytes with less bytes being better.

## Test Cases

Here Kn is the complete graph with n vertices and Kn,m is the complete bipartite graph.

### Toroidal

### Not Toroidal

* K8

# Answer
# Rust, ~~1210~~ 1200 bytes

```
use std::collections::HashMap as H;type I=i64;type E=Vec<(I,I)>;fn d(g:&E)->bool{let mut s:Vec<(E,Vec<I>)>=vec![];for e in g{let(v,w)=e;let f=(*v,*w);let z=|x|s.iter().position(|p|p.1.contains(x));match(z(v),z(w)){(Some(i),Some(j))=>{if i!=j{let mut p=s.remove(i);let q=s.remove(j-(i<j)as usize);p.0.extend(q.0);p.1.extend(q.1);s.push(p)}else{s[i].0.push(f)}}(Some(i),_)=>{s[i].0.push(f);s[i].1.push(*w)}(_,Some(j))=>{s[j].0.push(f);s[j].1.push(*v)}_=>{s.push((vec![f], vec![*v, *w]))}}}s.iter().map(|h|{let mut p=H::new();let mut r=H::new();let mut i=0;for e in&h.0{let(v,w)=e;i+=2;p.insert(i-1,i);p.insert(i,i-1);r.entry(v).or_insert(vec![]).push(i-1);r.entry(w).or_insert(vec![]).push(i)}let mut r:Vec<Vec<I>>=r.values().cloned().collect();r.sort();let mut x=0;let m=r.iter().flat_map(|v|1..v.len()).fold(1,|p,n|p*n);for mut w in 0..m{let mut t=H::new();for u in&r{let mut v=u.clone();let s=v.pop().unwrap();let mut f=s;while v.len()>0{let o=v.remove(w%v.len());w/=v.len()+1;t.insert(f,o);f=o}t.insert(f,s);}let mut f=vec![];let mut n=0;for s in p.keys(){if!f.contains(s){n+=1;let mut c=s;loop{f.push(*c);c=&t[&p[c]];if c==s{break}}}}x=x.max(n)}1-(r.len()as I-g.len()as I+x as I)/2}).sum::<I>()<2}

```

A toroidal example: Try it online!

That's this toroidal graph:

A non-toroidal example: Try it online!

That's this non-toroidal graph:

The original code I wrote, before golfing, was the following. It has printouts so you can see what's happening:

```
use std::collections::HashMap;

#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
struct Vertex(u64);
type Edge = (Vertex, Vertex);
type Graph = Vec<Edge>;

fn full_genus(graph: &Graph) -> usize {
    componets(graph).iter().map(|g| genus(g)).sum()
}
fn genus(graph: &Graph) -> usize {
    #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, PartialOrd, Ord)]
    struct HalfEdge(usize);
    let mut edge_pairing: HashMap<HalfEdge, HalfEdge> = HashMap::new();
    let mut vertex_groups: HashMap<&Vertex, Vec<HalfEdge>> = HashMap::new();
    let mut i = 0;
    for edge in graph {
        let (vert1, vert2) = edge;
        let half1 = HalfEdge(i);
        i += 1;
        let half2 = HalfEdge(i);
        i += 1;
        edge_pairing.insert(half1, half2);
        edge_pairing.insert(half2, half1);
        vertex_groups.entry(vert1).or_insert(vec![]).push(half1);
        vertex_groups.entry(vert2).or_insert(vec![]).push(half2);
    }
    let mut vertex_groups: Vec<Vec<HalfEdge>> = vertex_groups.values().cloned().collect();
    vertex_groups.sort();
    println!("{:?}", edge_pairing);
    println!("{:?}", vertex_groups);

    let mut max_faces = 0;
    let num_rotations = vertex_groups
        .iter()
        .map(|v| v.len() - 1)
        .map(|n| {
            let mut prod = 1;
            for i in 0..n {
                prod *= i + 1;
            }
            prod
        })
        .fold(1, |p, n| p * n);
    println!("\nNum rotations: {}\n", num_rotations);
    for rotation_index in 0..num_rotations {
        let mut working_index = rotation_index;
        let mut rotation: HashMap<HalfEdge, HalfEdge> = HashMap::new();
        let mut pretty_rotation: Vec<Vec<HalfEdge>> = vec![];
        for group in &vertex_groups {
            let mut removal_group = group.clone();
            let start = removal_group.pop().unwrap();
            let mut from = start;
            let mut pretty_group = vec![from];
            while !removal_group.is_empty() {
                let index = working_index % removal_group.len();
                working_index /= removal_group.len();
                let to = removal_group.swap_remove(index);
                rotation.insert(from, to);
                pretty_group.push(to);
                from = to;
            }
            rotation.insert(from, start);
            pretty_rotation.push(pretty_group);
        }
        let mut seen_on_face: Vec<HalfEdge> = Vec::new();
        let mut num_faces = 0;
        for start_halfedge in edge_pairing.keys() {
            if !seen_on_face.contains(start_halfedge) {
                num_faces += 1;
                let mut current_halfedge = start_halfedge;
                loop {
                    seen_on_face.push(*current_halfedge);
                    let pair_halfedge = &edge_pairing[current_halfedge];
                    current_halfedge = &rotation[pair_halfedge];
                    if current_halfedge == start_halfedge {
                        break;
                    }
                }
            }
        }
        if num_faces > max_faces {
            max_faces = num_faces;
            let euler_characteristic: isize =
                vertex_groups.len() as isize - graph.len() as isize + max_faces as isize;
            let genus_num: isize = 1 - euler_characteristic / 2;
            println!(
                "Faces: {}, Genus <= {} on rotation {}",
                max_faces, genus_num, rotation_index
            );
            println!("{:?}\n", pretty_rotation);
        }
        if rotation_index % 1e7 as usize == 0 {
            println!("Faces: {} <= {} on rotation {}", num_faces, max_faces, rotation_index);
        }
    }
    let euler_characteristic: isize =
        vertex_groups.len() as isize - graph.len() as isize + max_faces as isize;
    let genus_num: isize = 1 - euler_characteristic / 2;
    assert!(genus_num >= 0);
    genus_num as usize
}

fn componets(graph: &Graph) -> Vec<Graph> {
    let mut graphs: Vec<(Graph, Vec<Vertex>)> = vec![];
    for edge in graph {
        let (vert1, vert2) = edge;
        let g_index1 = graphs.iter().position(|(_g, h)| h.contains(&vert1));
        let g_index2 = graphs.iter().position(|(_g, h)| h.contains(&vert2));
        match (g_index1, g_index2) {
            (Some(i1), Some(i2)) => {
                if i1 != i2 {
                    let (mut graph1, mut vs1) = graphs.remove(i1);
                    let new_i2 = if i1 < i2 { i2 - 1 } else { i2 };
                    let (graph2, vs2) = graphs.remove(new_i2);
                    graph1.extend(graph2);
                    vs1.extend(vs2);
                    graphs.push((graph1, vs1));
                } else {
                    graphs[i1].0.push(edge.clone());
                }
            }
            (Some(i1), None) => {
                graphs[i1].0.push(edge.clone());
                graphs[i1].1.push(vert2.clone());
            }
            (None, Some(i2)) => {
                graphs[i2].0.push(edge.clone());
                graphs[i2].1.push(vert1.clone());
            }
            (None, None) => {
                let edges = vec![edge.clone()];
                let vs = vec!(vert1.clone(), vert2.clone());
                graphs.push((edges, vs));
            }
        }
    }
    graphs.into_iter().map(|(g, _h)| g).collect()
}

fn main() {
    let graph = vec![
        (Vertex(0), Vertex(1)),
        (Vertex(0), Vertex(2)),
        (Vertex(0), Vertex(3)),
        (Vertex(0), Vertex(4)),
        (Vertex(0), Vertex(5)),
        (Vertex(1), Vertex(2)),
        (Vertex(1), Vertex(3)),
        (Vertex(1), Vertex(4)),
        (Vertex(1), Vertex(5)),
        (Vertex(2), Vertex(3)),
        (Vertex(2), Vertex(4)),
        (Vertex(2), Vertex(5)),
        (Vertex(3), Vertex(4)),
        (Vertex(3), Vertex(5)),
    ];
    let result = full_genus(&graph);
    println!("Result: {}", result);
}

```

This program finds the minimum genus surface that the given graph can be embedded in. A graph is toroidal if that genus is at most 1, the genus of the torus.

The code works by separating the graph into its connected components, finding their genii separately, and adding up the results.

To find the genus of a connected graph, I brute force search over all possible rotation systems of the graph, and figure out which one has the most faces. A rotation system is simply an ordering on the edges emerging from each vertex, saying what order those edges are in going around the vertex. Each rotation system has a straightforward minimum genus it can be embedded in, and having more faces directly corresponds to having lower genus. Since every possible embedding corresponds to some rotation system, if there is a toroidal embedding, my program will find the corresponding rotation system and declare that the graph is toroidal, and vice versa.

This program is very slow, because it searches through a number of rotation systems equal to the product over all degrees `d` of the vertices of `(d-1)!`. However, it can search through a little over 10 million such rotation systems per minute, so it can verify the toroidality or non-toroidality of simple graphs like the ones shown above.
> 13 votes

---
Tags: code-golf, math, decision-problem, graph-theory, topology
---


title: ASCII texturing

text:
# Question
Title: ASCII texturing
Write a function or a full program that applies an ASCII texture to a 2d shape.

**Inputs:** shape, texture, dimensions(optionally).

* Both Shape and Texture can be given by any convenient method (2d matrix, array of strings or string with newlines)
* Shape data have a rectangular shape and contains 2 possible values: \[truthy/falsey\] binary/integer values (0/1 or n1/n2) or 2 different characters, just specify which one represent the shape parts \[truthy\] and which one represent the blank parts \[falsey\] and be consistent .
* The texture has a square shape only (width ≡ height) and contains printable ASCII characters.
* Optionally you can also pass dimensions of the matrices if needed.

**Output:** the shape with each truthy value substituted with the corresponding texture value (coordinates/indices mod texture size), the blank parts must be substituted with spaces.

* The ratio is always 1:1
* The entire shape must be covered and only the shape.
* No offset, texturing must start at top-left corner (0,0) of the shape data with the origin of the texture also at the top-left corner.

# Examples (using various shape formats in JSON)

**Shape**

```
[[0,0,1,1,0,0],
 [0,1,1,1,1,0],
 [0,1,1,1,1,0],
 [0,0,1,1,0,0]]

```

**Texture**

```
["/\\",
 "\\/"]

```

**Output**

```
["  /\  ",
 " /\/\ ",
 " \/\/ ",
 "  \/  "]

```

---

**Shape**

```
["        xxxxxxxx     ",
 "  xxxxxxxxxxxxxxxx   ",
 "    xxxxxxxxxxxxxxxx ",
 "  xxxxxxxxxxxxxxxxxxx",
 "xxxxxxxxxxxxxxxxxxxxx",
 "xxxxxxxxxxxxxxxxxxxxx",
 "xxxxxxxxxxxxxxxxxxxxx",
 "xxxxxxxxxxxxxxxxxxxxx"]

```

**Texture**

```
["[__]",
 "_][_",
 "[__]",
 "_][_"]

```

**Output**

```
["        [__][__]     ",
 "  [__][__][__][__]   ",
 "    [__][__][__][__] ",
 "  [__][__][__][__][__",
 "[__][__][__][__][__][",
 "_][__][__][__][__][__",
 "[__][__][__][__][__][",
 "_][__][__][__][__][__"]

```

---

**Shape**

```
[0,0,0,1]

```

**Texture**

```
["ab",
 "ba"]

```

**Output**

```
["   b"]

```

---

**Shape**

```
["11100001011010",
 "01111010101101",
 "01011011111101"]

```

**Texture**

```
["   ./]| |  / /.",
 "_|_|[]|/|_/\\_|/",
 "_|_|[/|_|_\\/_|.",
 "./_./]|_|//\\/./",
 "_|_|[]|/|_/\\_|/",
 "_|_|[]/ | \\/_|.",
 " /_  /|_|//\\/3/",
 "_|_|[]|/|_/\\_|/",
 "_|_|/ |_|_\\/_|.",
 "./_$/]|_|//\\/./",
 " |_|  |/|_/\\_|/",
 "_|_|[/|_|_\\$_|/",
 "_/  /]|_/ /\\///",
 "_|_/[]|/|/ \\_|/",
 "_|/|[/|_|_ /_||",
 " /_./]|_|  \\/|/"]

```

**Output**

(a surprise for you!)

# Rules

* Input/output can be given by any convenient method.
* You can print it to STDOUT or return it as a function result.
* Either a full program or a function are acceptable.
* Extraneous whitespace are forbidden.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

---

Sandbox post

# Answer
> 16 votes
# APL (Dyalog Unicode), ~~20~~ 12 bytesSBCS

-6 bytes through dzaima

Full program. Prompts stdin for:

1. texture as a list of strings
2. number of rows in shape matrix
3. number of columns in shape matrix
4. indices of falsies (to be blanks) in the shape matrix

All the s are supposed to be rectangles (they're not tofu). They symbolise a computer console which here means *prompt for array input via stdin*.

```
' '@⎕↑⎕⍴¨⎕⍴⎕

```

Try it online!

prompt for texture as a list of strings; `["/\\","\\/"]`

`⎕⍴` prompt for number of rows in shape matrix (`4`) and use that to cyclically **r**eshape the texture (this gives us enough texture lines); `["/\\","\\/","/\\","\\/"]`

`⎕⍴¨` prompt for number of columns in shape matrix (`6`) and use that to cyclically reshape *each* of the texture lines (this gives us enough characters in each texture line); `["/\\/\\/\\","\\//\\/\\","/\\/\\/\\","\\//\\/\\"]`

combine the list of lines into a character matrix;
`["/\/\/\"`
`"\//\/\"`
`"/\/\/\"`
`"\//\/\"]`

`' '@⎕` prompt for indices for blanks (`[[0,0],[0,1],[0,4],[0,5],[1,0],[1,5],[2,0],[2,5],[3,0],[3,1],[3,4],[3,5]]`) and then place blanks **at** those indices;
`/\`
`//\`
`//`
`/`

# Answer
> 9 votes
# Canvas, 9 bytes

```
ｍ⤢ｍ⤢；ｎ← ╋

```

Try it here!

Abusing that the input will be ASCII and so won't contain , but the shape is made of spaces and  for easy overlapping and replacement. Alternative 12 bytes taking shape as space and `#`.

# Answer
> 6 votes
# Japt, 10 bytes

```
ËmÈ?VgEY:S

```

Try it

```
ËmÈ?VgEY:S       U = shape as 2d array, V = texture as list of lines
Ë                Map each row, define E as row number
 mÈ                Map each element in these rows, define Y as element number
   ?                 Is the value a 1?
    VgEY               Get the character at texture[E,Y]
        :S           Else return a space if the value is a 0

```

# Answer
> 5 votes
# , 32 bytes

```
4 :'y}'' '',:x({.@]$($"1~{:))$y'

```

Try it online!

Some notes:

* This was a rare case where I got a shorter solution with an explicit, rather than tacit, verb.
* I wanted a solution that didn't prompt for input (ie, didn't want to just translate Adam's excellent APL solution into J).

# Answer
> 3 votes
# Haskell, ~~51~~ 49 bytes

* The texture and shape are provided in the format used by the first example.
* This works even if the texture isn't square or contains unprintables.
* Dimensions do not need to be passed.
* -2 bytes by abbreviating `zipWith` to `z`.

```
f=z(z(%)).cycle.map cycle
z=zipWith
_%0=' '
x%_=x

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 11 bytes

```
εNUεiXèNèëð

```

Port of *@EmbodimentOfIgnorance*'s Japt answer, so make sure to upvote him!

Inputs as defined in the first format of the challenge. Output as a character-matrix.

Try it online or verify all test cases. (Footer will pretty-print the character-matrix, feel free to remove it to see the actual output.)

**Explanation:**

```
ε          # Map over the rows of the (implicit) integer-matrix:
 NU        #  Push the map-index, and then pop and store it in variable `X`
   ε       #  Inner map over the cells of the current row:
    i      #   If the value of the current cell is a 1:
     Xè    #    Use variable `X` to index into the (implicit) input-list of strings,
           #    with automatic wraparound
       Nè  #    And then use the inner map index to index into this string
    ë      #   Else:
     ð     #    Push a space instead

```

# Answer
> 3 votes
# , 19 bytes

```
]]&' '"+]g"1~g=:$~#

```

Try it online!

Dyadic train. Left argument is texture, right argument is shape, 1 is blank, 0 is fill.

### How it works

I extended the dyadic `&` trick to the "If" usage of `^:`, i.e. boolean repetition amount. Also, an assignment `=:` can group the part of the train on its right, saving a pair of parens.

```
]]&' '"+]g"1~g=:$~#  Left argument: texture, Right argument: shape
                $~#  Repeat the texture's rows to fit the shape's rows
             g=:     Assign this sub-function to g
        ]g"1~        Use g to do the same on columns
]     "+             For each cell on the texture and shape,
 ]&' '                 Replace the texture's cell with ' ' if shape's cell is 1
                       Keep the texture if shape's cell is 0

```

# Answer
> 2 votes
# Julia 1.0, 68 bytes

```
f(s,t,n,Y,X)=[t[y,x] ? s[mod1(y,n),mod1(x,n)] : ' ' for y=1:Y,x=1:X]

```

Takes the shape as a 2d array of characters, the pattern as a array of Bools, and the dimensions (because `length` is long). Returns a character array via array comprehension.

Try it online!

# Answer
> 2 votes
# Charcoal, 16 bytes

```
Ｆθ«ＦΣιＧ→¹η¿›0ι⸿→

```

Try it online! Link is to verbose version of code. Takes input as newline-delimited strings. Explanation:

```
Ｆθ«

```

Loop over the shape.

```
ＦΣι

```

If the value is a `1`...

```
Ｇ→¹η

```

... then draw a 1x1 polygon filled using the template. Conveniently in Charcoal the fill is always relative to the origin of the canvas. Unfortunately Charcoal can't draw zero-sized polygons or Oblongs of sides less than 2, otherwise I could save a couple of bytes here.

```
¿›0ι

```

If this is a newline...

```
⸿

```

... then move to the start of the next line of the canvas...

... otherwise move forward on the current line.

# Answer
> 2 votes
# Jelly, 13 bytes

```
JṁJ}ị⁸ṁ"⁹a@o⁶

```

Try it online!

A dyadic link taking a list of Jelly strings for the texture as its left argument and an integer matrix for the shape as its right argument. Returns a list of Jelly strings.

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

```
procedure f(t,s)
i:=0&r:=|!t\*s&i+:=1&j:=0&c:=|!r\*!s&s[i,j+:=1]:=[" ",c][s[i,j]]&\z
return s
end

```

Try it online!

Uses `1` for spaces and `2` for textured in shape data.

## Explanation:

```
procedure f(t,s)                   ; t - texture, s - shape data
    i:=0 &                         ; i is the row index
    r:=|!t\*s &                    ; repeats the rows of the texture as many times as the rows of the shape data
    i+:=1 &                        ; next row
    j:=0 &                         ; j is the column index; reset to start
    c:=|!r\*!s &                   ; repeats the characters of each row of the texture as many times as the row of the shape
    s[i,j+:=1]:=[" ",c][s[i,j]] &  ; modify the shape data ot " " or to texture
    \z                             ; z is not declared and thus causes Icon to backtrack
    return s                       ; return the modified shape data
end

```

# Answer
> 1 votes
# Python 2, ~~97~~ ~~94~~ 86 bytes

```
lambda S,P,w:[''.join([' ',P[j%w][i%w]][v]for i,v in E(s))for j,s in E(S)]
E=enumerate

```

Try it online!

3 bytes thx to frank

Takes the shape as `S`, a list list of `0/1`;the texture `P` as a list of strings; and `w` as the width/height of `P`. Returns a list of strings.

# Answer
> 1 votes
# Ruby, 65 bytes

```
->s,p,w,h{s.zip(p*h).map{|a,b|a.zip(b*w).map{|x,y|x>0?y:' '}*''}}

```

Try it online!

**Input**: Matrix of 0 and 1, texture as 2d array of characters, size of the matrix (width and height).

# Answer
> 1 votes
# Japt, 9 bytes

```
ËmÈù1VgEY

```

Try it

---
Tags: code-golf, string, ascii-art, matrix, binary-matrix
---


title: Tips for golfing in MarioLANG

text:
# Question
Title: Tips for golfing in MarioLANG
I recently saw this language in a challenge and it's awesome. Does anyone have some tips for ing in it?

Your tips should be at least somewhat specific to MarioLANG.

Please post one tip per answer.

# Answer
# Use the fall at the end for instructions

This is a pretty simple tip but many MarioLANG programs end something like this, ending with Mario falling down:

```
.....
=====

```

and this can be written instead as this:

```
....
===.

```

saving two bytes.

If your program has an elevator near an end like this you can often improve even further. This:

```
]!......
=#======

 <
="

```

goes to this:

```
]!.
=#.
  .
  .
 <.
=".

```

You do have to be careful with the last one though, since the added spaces to get to the final instructions can in many situations be more costly than just writing it largely on one line.
> 3 votes

# Answer
# Duplicate input

Sometimes, you will need multiple copies of a given input - here is a 27 byte snippet that will do this.

```
>[!
"=#
- )
( +
( )
!+<
#="

```

Alternate 39 byte horizontal version:

```
>      [!
"=======#
!-((+)+)<
#======="

```

Before:

```
Memory Pointer: ˅
Cell          : n 0 0

```

After:

```
Memory Pointer: ˅
Cell          : 0 n n

```
> 1 votes

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


# Question
Title: Convert Complex Chinese Numbers into Arabic Numbers
Your task is to convert Chinese numerals into Arabic numerals.

A problem similar to Convert Chinese numbers, however, more complex. Also, answers given there mostly don't satisfy all the conditions.

Chinese digits/numbers are as follows:
`0 零` `1 一` `2 二` `2 两` `3 三` `4 四` `5 五` `6 六` `7 七` `8 八` `9 九` `10 十` `100 百` `1000 千` `10000 万` `10^8 亿`

### Multiple-digit numbers

Multiple-digit numbers are created by adding from highest to lowest and by multiplying from lowest to highest. In case of additions, each number higher than 9 can be multiplied by 1 and it won't change its meaning. Both `亿万千百十一` and `一亿一万一千一百一十一` are equal to `100011111`.
We multiply in the following fashion: `五千 = 5000` `一百万 = 1000000` `三千万 = 30000000`.

Chinese always takes the lowest possible multiplier (just like we don't say hundred hundred but ten thousand). So `百千` doesn't exist to represent `100000` since we have `十万`, `十千` doesn't exist since we have , `十千万` doesn't exist, since we have `亿`, `十百` doesn't exist, since we have .

### Special cases

`0` is very important and it was actually the biggest problem in the other code golf question. Trailing zeroes are omitted in Chinese, so  indicates interior zeroes.

Let's look at some examples:

* `三百零五 = 305`
* `三百五 = 350` \- no interior zeroes. You can notice that we don't need  here, since a trailing zero is omitted.
* `一千万零一百 = 10000100`
* `三千零四万 = 30040000`
* `六亿零四百零二 = 600000402` \- here we have 2 interior zeroes. As you can see though, even if there's a gap of more than one order of magnitute (in the example it's `亿` and ), two `零s` can't stand next to each other, one is enough for each gap, no matter how big it is.
* `一亿零一 = 100000001` \- again, no need for more than one  if there's one gap, no matter how big.
* `八千万九千 = 80009000` \- no need for  since there are no interior zeroes. Why are there no interior zeroes? Because it follows the highest-to-lowest addition without omitting an order of magnitude. Right after  we have  ( is a multiplication component, not addition one) and not, let's say, .

More examples: Check out the two "示例" paragraphs

`2` is also special in Chinese as it can be represented with a character  if it's a multiplier of 100 and higher numerals. Both `两千两百二十二` and `二千二百二十二` are `2222`.

## Rules

~~Constraints: 0 \<= N \< 10^9~~
Edit: I don't care what happens from `10^9` onwards. Input doesn't have any examples equal or higher than `10^9` for that reason.

## Test cases

Input:

```
一亿两千三百零二万四千二百零三
四千万零一十
三十四万五千五
四亿二十万零九百零一
两千万九千零一十
二十四万零二百二十二
两千零十二
零

```

Output:

```
123024203
40000010
345500
400200901
20009010
240222
2012
0

```

Good luck!

# Answer
# 05AB1E, ~~52~~ 51 bytes

```
0•9∊»£¬ƵçoiKβÐg•19вIÇƵª%èvX¨UOy¬iθ°UX‰¤_ªX*]DgiX*}O

```

Try it online!

```
0                              # literal 0
 •9∊»£¬ƵçoiKβÐg•19в            # compressed list [2, 14, 0, 3, 0, 8, 0, 6, 2, 9, 0, 18, 0, 1, 0, 13, 5, 0, 10, 0, 0, 7, 12, 4]
                   IÇ          # codepoints of the input
                     Ƶª%       # modulo 270
                        è      # index into the above list, with wraparound
v                 ]            # for each number y in that list:
 X                             #  push the variable X
  ¨                            #  drop the last digit
   U                           #  store that in X
    O                          #  sum all numbers on the stack
     y                         #  push y
      ¬i          ]            #  if the first digit of y is 1:
        θ°                     #   10**(the last digit of y)
          U                    #   store that in X
           X‰                  #   divmod X
             ¤_ª               #   if the modulo is 0, append 1
                X*             #   multiply by X
Dgi  }                         # if length of the top of stack is 1:
   X*                          #  multiply it by X
      O                        # sum of the stack
                               # implicit output

```
> 5 votes

---
Tags: code-golf, conversion, unicode
---


title: Calculate a Pedigree

text:
# Question
Title: Calculate a Pedigree
# A little genetics lesson

When you only have access to someone's visible traits or *phenotype*, a pedigree of their family history is often used to figure out the actual genetic information or, *genotype* of each family member.

When dealing with simple dominance as we will be, a simple pedigree chart will be enough to figure out the alleles, or the version of the genes that they have, of each person. In simple dominance a person with a dominant allele (denoted with a capital letter) will always have the trait that that version represents, no matter the other allele. It takes two recessive alleles (denoted with a lowercase letter) to have that version expressed. In other words the dominant allele always masks the recessive version of that gene. Here is an example of a pedigree chart:

Each row here is a generation. Circles are female, males squares, horizontal lines are marriage, vertical lines children. Pretty simple. Black means recessive phenotype, white, dominant. Starting from the top, (assume the alleles are `A` and `a`), we know person 2 has `aa`, homozygous recessive because that is the only possible option for the recessive phenotype. Now even though person one could be either `Aa` or `AA` to be dominant phenotype, because he has a recessive child, he must be `Aa`, or heterozygous. You can do this for all the other people. In the event you don't have any information that enables you to figure out the second allele, it can be done like so: `A_`.

# Your Task

* You will receive a pedigree chart in the form of a list of generations like `[GenI, GenII, etc.]` in any sane format.
* Each generation will be a list of strings, each string representing a person.
* The people are made up of three parts - an ID, their phenotype, and their "connections".
* Their ID is a single printable ascii character that is unique in the entire tree other than `A` or `a`. (No, there won't be more than 95 people in the chart).
* Their phenotype is one of `A` or `a`, `A` being the dominant allele, and `a` being recessive.
* Their connections are a sequence of ID's of other people that they have connections with.
* A connection in the same generation is marriage, in different generations is child and parent.
* The connections are repeated on both sides (i.e. the husband has say he is a husband of wife, and wife says she is husband of wife).
* You have to figure out the genotypes of everyone as much as possible.
* Return the same list, except instead of people, put their genotypes in the same position.
* The genotype has to be outputted in order so `Aa` instead of `aA`.
* A little leeway on the input format is fine.
* This is code-golf so shortest answer in **bytes** wins.

# Examples

```
[["0A1234", "1a0234"], ["2A01", "3a01", "4A015678",
"5a4678"], ["6a45", "7A45","8A45"]] (The one above)   ->

[["Aa", "aa"], ["Aa", "aa", "Aa", "aa"], ["aa", "Aa", "Aa"]]

[["0A12", "1A02"], ["2A301", "3a2"]]    ->

[["A_", "A_"], ["A_", "aa"]]

```

# Bonus

* **-30 bytes** if you deal with incomplete and co-dominance also. On the detection of three phenotypes instead of two in the entire chart, apply incomplete/co dominance to your algorithm.

# Answer
> 2 votes
# 05AB1E, 39 bytes

```
εNUε'aåi„aaë¯.øX<X>‚è˜y2£lSδåPài„Aaë„A_

```

Port of my Java answer.

Try it online or verify all test cases.

**Explanation:**

```
ε                     # Map over the rows of the (implicit) input-list:
 NU                   #  Store the outer-map index in variable `X`
   ε                  #  Map over the strings `y` of the current row:
    'aåi             '#   If the current string contains an "a":
        „aa           #    Push string "aa"
       ë              #   Else (it contains an "A" instead):
        ¯.ø           #    Surround the (implicit) input-list with two empty lists
                      #    (05AB1E has automatic wrap-around when indexing lists,
                      #     so this is to prevent that)
           X<X>‚      #    Push `X-1` and `X+1` and pair them together
                è     #    Index both into the list to get (potential) parent and child rows
                 ˜    #    Flatten it to a single list
        y             #    Push the current string we're mapping again
         2£           #    Only leave the first 2 characters (its id and the letter "A")
           l          #    Lowercase the "A" to "a"
            S         #    And convert it to a list of characters: [id, "A"]
             δå       #    Check in each string whether it contains the id and "A"
               P      #    Check for each whether it contained BOTH the id AND "A"
                ài    #    If a child/parent is found for which this is truthy:
                  „Aa #     Push string "Aa"
                 ë    #    Else:
                  „A_ #     Push string "A_"
                      # (after which the mapped result is output implicitly)

```

# Answer
> 1 votes
# Java 10, ~~356~~ ~~349~~ 340 bytes

```
a->{int i=0,j,k,f,z=a.length;var r=new String[z][];for(;i<z;i++)for(r[i]=new String[j=a[i].length];j-->0;)if(a[i][j].contains("a"))r[i][j]="aa";else{var t=".a.*"+a[i][j].charAt(0)+".*";for(f=k=0;i>0&&k<a[i-1].length;)f=a[i-1][k++].matches(t)?1:f;for(k=0;i+1<z&&k<a[i+1].length;)f=a[i+1][k++].matches(t)?1:f;r[i][j]=f>0?"Aa":"A_";}return r;}

```

Try it online.

**General explanation:**

1) Any `a` will always become `aa`

2a) If a child `A` has parents `aa` and `A`, it will become `Aa`
2b) If a child `A` has parents `A` and `A`, it will become `A_`
2c) (It is not possible for a child `A` to have parents `aa` and `aa`)

3a) If a parent `A` has at least one child `a`, it will become `Aa`
3b) If a parent `A` only has children `A`, it will become `A_`

**Code explanation:**

```
a->{                     // Method with 2D String array as both parameter and return-type
  int i=0,j,k,           //  Index-integers
      f,                 //  Flag-integer
      z=a.length;        //  Length-integer
  var r=new String[z][]; //  Result 2D String array
  for(;i<z;i++)          //  Loop over the rows:
    for(r[i]=new String[j=a[i].length];
                         //   Create the inner String-array of the result
        j-->0;)          //   Loop over the columns:
      if(a[i][j].contains("a"))
                         //    If the current node contains "a":
        r[i][j]="aa";    //     Set the result at this node to "aa"
      else{              //    Else(-if the current node contains "A" instead):
        var t=".a.*"+a[i][j].charAt(0)+".*";
                         //     Set a temp String to a regex to check relations and "a"
        for(f=k=0;       //     Set the flag to 0
            i>0&&        //     If the current node has parents:
            k<a[i-1].length;)
                         //      Loop over the row above:
          f=a[i-1][k++].matches(t)?
                         //       If a parent with "a" is found:
            1:f;         //        Set the flag to 1 (else: leave it unchanged)
        for(k=0;i+1<z&&  //     If the current node has children:
            k<a[i+1].length;)
                         //      Loop over the row below:
          f=a[i+1][k++].matches(t)?
                         //       If child with "a" is found:
            1:f;         //        Set the flag to 1 (else: leave it unchanged)
        r[i][j]=f>0?     //     If the flag is 1:
                 "Aa"    //      Current node changes from "A" to "Aa"
                :        //     Else (flag is still 0):
                 "A_";}  //      Current node changes from "A" to "A_"
  return r;}             //  Return the result

```

---
Tags: code-golf, combinatorics
---


title: snakes_are_bad, camelsAreBetter

text:
# Question
Title: snakes_are_bad, camelsAreBetter
# Introduction

All these snakes everywhere! I've had enough, and have decided that I much prefer camels. Therefore, I want you to convert my snakes to camels for me.

# Challenge

Turn any `snake_case` string into a `camelCase` string.
Capitals should be returned to lowercase before the conversion occurs.

# Test Cases

In: `camel_case`
Out: `camelCase`

In: `curse_these_snakes`
Out: `curseTheseSnakes`

In: `i_promise_1234_is_not_my_password`
Out: `iPromise1234IsNotMyPassword`

In: `AAAAA_BBBBB`
Out: `aaaaaBbbbb`

# Rules

As per usual, standard loophole rules apply.
This is - shortest answer wins. Leading/trailing underscores (e.g `_string_`) are ignored.

# Current Winners (subject to change)

## Esoteric Language

Me, with -1 bytes.

## Standard Language

Also me, with -2 bytes.

# Answer
# Python 3, 51 bytes

```
lambda s:s[0].lower()+s.title().replace('_','')[1:]

```

Try it online!

*-4 bytes thanks to ReinstateMonica*
> 2 votes

# Answer
# Ruby, 39 bytes

```
->x{x.downcase.gsub(/_(.)/){$1.upcase}}

```

Try it online!

This does nothing to leading and trailing underscores.
> 0 votes

# Answer
# Gema, 28 characters

```
_?=@upcase{?}
?=@downcase{?}

```

Sample run:

```
bash-5.0$ gema '_?=@upcase{?};?=@downcase{?}' <<< 'i_promise_1234_is_not_my_password'
iPromise1234IsNotMyPassword

```

Try it online!
> 0 votes

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


title: Make a circle illusion animation

text:
# Question
Title: Make a circle illusion animation
Your job is to animate this circle illusion. It looks like the points rotating inside of the circle, but they are actually just moving in straight lines.

# Criterias

* The result has to be animated. The way you do the animation is irrelevant, it can generate a `.gif`, it can draw to a window, some device screen or whatever.
* This is a popularity contest, so you might want to add some additional features to your program to get more upvotes, for example varying the number of points.
* The winner is the most upvoted **valid** answer 7 days after the last valid submission.
* **The answers that will actually implement points moving on straight lines and not another way around are more welcomed**

# Answer
# Python 3.4

Using the turtle module. The turtles are different colours and they always face in the same direction, so they can be easily seen to be moving along straight lines by just focusing on one of them. Despite this the circle illusion is still strong.

The illusion still seems quite strong even with just 3 or 4 turtles:

The framerate is reduced considerably for all of these GIF examples, but it doesn't seem to detract from the illusion. Running the code locally gives a smoother animation.

```
import turtle
import time
from math import sin, pi
from random import random

def circle_dance(population=11, resolution=480, loops=1, flip=0, lines=0):
    population = int(population)
    resolution = int(resolution)
    radius = 250
    screen = turtle.Screen()
    screen.tracer(0)
    if lines:
        arrange_lines(population, radius)
    turtles = [turtle.Turtle() for i in range(population)]
    for i in range(population):
        dancer = turtles[i]
        make_dancer(dancer, i, population)
    animate(turtles, resolution, screen, loops, flip, radius)

def arrange_lines(population, radius):
    artist = turtle.Turtle()
    for n in range(population):
        artist.penup()
        artist.setposition(0, 0)
        artist.setheading(n / population * 180)
        artist.forward(-radius)
        artist.pendown()
        artist.forward(radius * 2)
    artist.hideturtle()

def make_dancer(dancer, i, population):
    dancer.setheading(i / population * 180)
    dancer.color(random_turtle_colour())
    dancer.penup()
    dancer.shape('turtle')
    dancer.turtlesize(2)

def random_turtle_colour():
    return random() * 0.9, 0.5 + random() * 0.5, random() * 0.7

def animate(turtles, resolution, screen, loops, flip, radius):
    delay = 4 / resolution      # 4 seconds per repetition
    while True:
        for step in range(resolution):
            timer = time.perf_counter()
            phase = step / resolution * 2 * pi
            draw_dancers(turtles, phase, screen, loops, flip, radius)
            elapsed = time.perf_counter() - timer
            adjusted_delay = max(0, delay - elapsed)
            time.sleep(adjusted_delay)

def draw_dancers(turtles, phase, screen, loops, flip, radius):
    population = len(turtles)
    for i in range(population):
        individual_phase = (phase + i / population * loops * pi) % (2*pi)
        dancer = turtles[i]
        if flip:
            if pi / 2 < individual_phase <= 3 * pi / 2:
                dancer.settiltangle(180)
            else:
                dancer.settiltangle(0)
        distance = radius * sin(individual_phase)
        dancer.setposition(0, 0)
        dancer.forward(distance)
    screen.update()

if __name__ == '__main__':
    import sys
    circle_dance(*(float(n) for n in sys.argv[1:]))

```

### For contrast here are some that really do rotate:

### ...or do they?

The code can be run with 5 optional arguments: population, resolution, loops, flip and lines.

* `population` is the number of turtles
* `resolution` is the time resolution (number of animation frames per repetition)
* `loops` determines how many times the turtles loop back on themselves. The default of 1 gives a standard circle, other odd numbers give that number of loops in the string of turtles, while even numbers give a string of turtles disconnected at the ends, but still with the illusion of curved motion.
* `flip` if non-zero causes the turtles to flip direction for their return trip (as suggested by aslum so that they are never moving backwards). As default they keep a fixed direction to avoid the visual distraction at the endpoints.
* `lines` if non-zero displays the lines on which the turtles move, for consistency with the example image in the question.

Examples with `flip` set, with and without `lines`. I've left my main example above without flip as I prefer not to have the sporadic jump, but the edge of the circle does look smoother with all the turtles aligned, so the option is there for people to choose whichever style they prefer when running the code.

It might not be immediately obvious how the images above were all produced from this same code. In particular the image further up which has a slow outer loop and a fast inner loop (the one that looks like a cardioid that someone accidentally dropped). I've hidden the explanation of this one below in case anyone wants to delay finding out while experimenting/thinking.

> The animation with an inner and outer loop of different sizes was created by setting the number of loops to 15 and leaving the number of turtles at 23 (too low to represent 15 loops). Using a large number of turtles would result in 15 clearly defined loops. Using too few turtles results in aliasing (for the same reason as in image processing and rendering). Trying to represent too high a frequency results in a lower frequency being displayed, with distortion.

Trying out different numbers I found some of these distortions more interesting than the more symmetrical originals, so I wanted to include one here...
> 133 votes

# Answer
# C

Result:

```
#include <stdio.h>
#include <Windows.h>
#include <Math.h>

int round (double r) { return (r > 0.0) ? (r + 0.5) : (r - 0.5); }
void print (int x, int y, char c) {
    COORD p = { x, y };
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), p);
    printf("%c", c);
}

int main ()
{
    float pi = 3.14159265358979323846;
    float circle = pi * 2;
    int len = 12;
    int hlen = len / 2;
    int cx = 13;
    int cy = 8;
    float w = 11.0;
    float h =  8.0;
    float step = 0.0;

    while (1)
    {
        system("cls"); // xD

        for (int i = 0; i < len; i++)
        {
            float a = (i / (float)len) * circle;
            int x = cx + round(cos(a) * w);
            int y = cy + round(sin(a) * h);
            print(x, y, 'O');

            if (i < hlen) continue;

            step -= 0.05;
            float range = cos(a + step);
            x = cx + round(cos(a) * (w - 1) * range);
            y = cy + round(sin(a) * (h - 1) * range);
            print(x, y, 'O');
        }

        Sleep(100);
    }

    return 0;
}

```
> 98 votes

# Answer
# SVG (no Javascript)

JSFiddle link here

```
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 380 380" width="380" height="380" version="1.0">
  <g transform="translate(190 190)">
    <circle cx="0" cy="0" r="190" fill="#000"/>
    <line x1="0" y1="-190" x2="0" y2="190" stroke="#fff" stroke-width="1.5"/>
    <line x1="72.71" y1="175.54" x2="-72.71" y2="-175.54" stroke="#fff" stroke-width="1.5"/>
    <line x1="134.35" y1="134.35" x2="-134.35" y2="-134.35" stroke="#fff" stroke-width="1.5"/>
    <line x1="175.54" y1="72.71" x2="-175.54" y2="-72.71" stroke="#fff" stroke-width="1.5"/>
    <line x1="190" y1="0" x2="-190" y2="0" stroke="#fff" stroke-width="1.5"/>
    <line x1="175.54" y1="-72.71" x2="-175.54" y2="72.71" stroke="#fff" stroke-width="1.5"/>
    <line x1="134.35" y1="-134.35" x2="-134.35" y2="134.35" stroke="#fff" stroke-width="1.5"/>
    <line x1="72.71" y1="-175.54" x2="-72.71" y2="175.54" stroke="#fff" stroke-width="1.5"/>
    <g transform="rotate(0)">
      <animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0" to="360" begin="0" dur="8s" repeatCount="indefinite"/>
      <g transform="translate(0 90)">
        <g transform="rotate(0)">
          <animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0" to="-360" begin="0" dur="4s" repeatCount="indefinite"/>
          <circle cx="0" cy="90" r="10" fill="#fff"/>
          <circle cx="63.64" cy="63.64" r="10" fill="#fff"/>
          <circle cx="90" cy="0" r="10" fill="#fff"/>
          <circle cx="63.64" cy="-63.64" r="10" fill="#fff"/>
          <circle cx="0" cy="-90" r="10" fill="#fff"/>
          <circle cx="-63.64" cy="-63.64" r="10" fill="#fff"/>
          <circle cx="-90" cy="0" r="10" fill="#fff"/>
          <circle cx="-63.64" cy="63.64" r="10" fill="#fff"/>
        </g>
      </g>
    </g>
  </g>
</svg>

```
> 55 votes

# Answer
http://jsfiddle.net/z6vhD/13/

`intervaltime` changes the FPS (FPS = 1000/intervaltime).
`balls` changes the # balls.
`maxstep` adjusts the # steps in a cycle, the larger the 'smoother' it is. 64 should be large enough where it appears smooth.

Modeled as a circle moving, instead of moving the balls along the lines, but the visual effect (should be?) the same. Some of the code is pretty verbose, but this isn't code golf, so...

```
var intervalTime = 40;
var balls = 8;
var maxstep = 64;

var canvas = $('#c').get(0); // 100% necessary jquery
var ctx = canvas.getContext('2d');
var step = 0;

animateWorld = function() {
    createBase();
    step = step % maxstep;
    var centerX = canvas.width/2 + 115 * Math.cos(step * 2 / maxstep * Math.PI);
    var centerY = canvas.height/2 + 115 * Math.sin(step * 2 / maxstep * Math.PI);

    for (var i=0; i<balls; i++) {
        drawCircle(ctx, (centerX + 115 * Math.cos((i * 2 / balls - step * 2 / maxstep) * Math.PI)), (centerY + 115 * Math.sin((i * 2 / balls - step * 2 / maxstep) * Math.PI)), 10, '#FFFFFF');
    }

    step++;
}

function createBase() {
    drawCircle(ctx, canvas.width/2, canvas.height/2, 240, '#000000');
    for(var i=0; i<balls*2; i++) {
        drawLine(ctx, canvas.width/2, canvas.height/2, canvas.width/2 + 240 * Math.cos(i / balls * Math.PI), canvas.height/2 + 240 * Math.sin(i / balls * Math.PI), '#FFFFFF');
    }
}

function drawLine(context, x1, y1, x2, y2, c) {
    context.beginPath();
    context.moveTo(x1,y1);
    context.lineTo(x2,y2);
    context.lineWidth = 3;
    context.strokeStyle = c;
    context.stroke();
}

function drawCircle(context, x, y, r, c) {
    context.beginPath();
    context.arc(x, y, r, 0, 2*Math.PI);
    context.fillStyle = c;
    context.fill();
}

function drawRect(context, x, y, w, h, c) {
    context.fillStyle = c;
    context.fillRect(x, y, w, h);
}

$(document).ready(function() {
    intervalID = window.setInterval(animateWorld, intervalTime);
});

```
> 48 votes

# Answer
### CSS animations

A solution using only css animations (see animation on JSFiddle \- note that I added the browser specific prefixes in the fiddle so that it can work in most recent versions).

```
<body>
    <div id="w1"></div>
    <div id="w2"></div>
    <div id="w3"></div>
    <div id="w4"></div>
    <div id="w5"></div>
    <div id="w6"></div>
    <div id="w7"></div>
    <div id="w8"></div>
</body>

div {
    position: absolute;
    width: 20px;
    height: 20px;
    border-radius: 20px;
    background: red;
    animation-duration: 4s;
    animation-iteration-count: infinite;
    animation-direction: alternate;
    animation-timing-function: ease-in-out;
}

#w1 { animation-name: s1; animation-delay: 0.0s }
#w2 { animation-name: s2; animation-delay: 0.5s }
#w3 { animation-name: s3; animation-delay: 1.0s }
#w4 { animation-name: s4; animation-delay: 1.5s }
#w5 { animation-name: s5; animation-delay: 2.0s }
#w6 { animation-name: s6; animation-delay: 2.5s }
#w7 { animation-name: s7; animation-delay: 3.0s }
#w8 { animation-name: s8; animation-delay: 3.5s }

@keyframes s1 { from {top: 100px; left:   0px;} to {top: 100px; left: 200px;} }
@keyframes s2 { from {top:  62px; left:   8px;} to {top: 138px; left: 192px;} }
@keyframes s3 { from {top:  29px; left:  29px;} to {top: 171px; left: 171px;} }
@keyframes s4 { from {top:   8px; left:  62px;} to {top: 192px; left: 138px;} }
@keyframes s5 { from {top:   0px; left: 100px;} to {top: 200px; left: 100px;} }
@keyframes s6 { from {top:   8px; left: 138px;} to {top: 192px; left:  62px;} }
@keyframes s7 { from {top:  29px; left: 171px;} to {top: 171px; left:  29px;} }
@keyframes s8 { from {top:  62px; left: 192px;} to {top: 138px; left:   8px;} }

```
> 43 votes

# Answer
## Mathematica

Here is a pretty straight-forward submission.

```
animateCircle[n_] := Animate[Graphics[
   Flatten@{
     Disk[],
     White,
     Map[
      (
        phase = #*2 \[Pi]/n;
        line = {Cos[phase], Sin[phase]};
        {Line[{-line, line}],
         Disk[Sin[t + phase]*line, 0.05]}
        ) &,
      Range[n]
      ]
     },
   PlotRange -> {{-1.1, 1.1}, {-1.1, 1.1}}
   ],
  {t, 0, 2 \[Pi]}
  ]

```

If you call `animateCircle[32]` you'll get a neat animation with 32 lines and circles.

It's completely smooth in Mathematica, but I had to limit the number of frames for the GIF a bit.

Now what happens if you put two discs on each line? (That is, add `Disk[-Sin[t + phase]*line, 0.05]` to the list within the `Map`.)

You can also put them 90° out of phase (use `Cos` instead of `-Sin`):
> 38 votes

# Answer
# Excel (no VBA)

```
=2*PI()*(NOW()*24*60*60/A2-FLOOR(NOW()*24*60*60/A2,1))
=ROUND(7*SIN(A1),0)
=ROUND(5*SIN(A1+1*PI()/4),0)
=ROUND(7*SIN(A1+2*PI()/4),0)
=ROUND(5*SIN(A1+3*PI()/4),0)

```

A2 (period) determines the time (seconds) for a full 'revolution'.

Each cell within the lines is a basic conditional relating to the value of the corresponding line. For example, K2 is:

```
 =1*(A5=7)

```

And the center cell (K9) is:

```
=1*OR(A5=0,A6=0,A7=0,A8=0)

```

Forced the animation by holding 'delete' on a random cell to constantly trigger a refresh.

I know this is an old topic, but recent activity brought it to the top and it seemed appealing for some reason. Long time pcg listener, first time caller. Be gentle.
> 27 votes

# Answer
## VBScript + VBA + Excel Pie Chart

This will make your processor cry a little but it looks pretty and I believe it works according to spec. I used @Fabricio's answer as a guide to implement the circle movement algorithm.

EDIT: Made some adjustments to improve render speed.

The code:

```
'Open Excel
Set objX = CreateObject("Excel.Application")
objX.Visible = True
objX.Workbooks.Add

'Populate values
objX.Cells(1, 1).Value = "Lbl"
objX.Cells(1, 2).Value = "Amt"
For fillX = 2 to 17
    objX.Cells(fillX, 1).Value = "V"+Cstr(fillX-1)
    objX.Cells(fillX, 2).Value = "1"
Next

'Create pie
objX.Range("A2:B17").Select
objX.ActiveSheet.Shapes.AddChart.Select
With objX.ActiveChart
    .ChartType = 5 'pieChart
    .SetSourceData  objX.Range("$A$2:$B$17")
    .SeriesCollection(1).Select
End with

'Format pie
With objX.Selection.Format
    .Fill.ForeColor.RGB = 0 'black
    .Fill.Solid
    .Line.Weight = 2
    .Line.Visible = 1
    .Line.ForeColor.RGB = 16777215 'white
End With

'animation variables
pi = 3.14159265358979323846
circle = pi * 2 : l  = 16.0
hlen = l / 2    : cx = 152.0
cy = 99.0       : w  = 90.0
h  = 90.0       : s  = 0.0
Dim posArry(7,1)

'Animate
While 1
  For i = 0 to hlen-1
    a = (i / l) * circle
    range = cos(a + s)
    x = cx + cos(a) * w * range
    y = cy + sin(a) * h * range

    If whileInx = 1 Then
        createOval x, y
    ElseIf whileInx = 2 Then
        objX.ActiveChart.Legend.Select
    ElseIf whileInx > 2 Then
        ovalName = "Oval "+ Cstr(i+1)
        dx = x - posArry(i,0)
        dy = y - posArry(i,1)
        moveOval ovalName, dx, dy
    End if

    posArry(i,0) = x
    posArry(i,1) = y
  Next

  s=s-0.05
  wscript.Sleep 1000/60 '60fps
  whileInx = 1 + whileInx
Wend

'create circles
sub createOval(posX, posY)
    objX.ActiveChart.Shapes.AddShape(9, posX, posY, 10, 10).Select '9=oval
    objX.Selection.ShapeRange.Line.Visible = 0
    with objX.Selection.ShapeRange.Fill
       .Visible = 1
       .ForeColor.RGB = 16777215 'white
       .solid
    end with
end sub

'move circles
sub moveOval(ovalName, dx, dy)
    with objX.ActiveChart.Shapes(ovalName)
        .IncrementLeft dx
        .IncrementTop  dy
    end with
end sub

```
> 26 votes

# Answer
Just for fun with PSTricks.

```
\documentclass[preview,border=12pt,multi]{standalone}
\usepackage{pstricks}

\psset{unit=.3}

% static point
% #1 : half of the number of points
% #2 : ith point
\def\x[#1,#2]{(3*cos(Pi/#1*#2))}
\def\y[#1,#2]{(3*sin(Pi/#1*#2))}

% oscillated point
% #1 : half of the number of points
% #2 : ith point
% #3 : time parameter
\def\X[#1,#2]#3{(\x[#1,#2]*cos(#3+Pi/#1*#2))}
\def\Y[#1,#2]#3{(\y[#1,#2]*cos(#3+Pi/#1*#2))}

% single frame
% #1 : half of the number of points
% #2 : time parameter
\def\Frame#1#2{%
\begin{pspicture}(-3,-3)(3,3)
    \pstVerb{/I2P {AlgParser cvx exec} bind def}%
    \pscircle*{\dimexpr3\psunit+2pt\relax}
    \foreach \i in {1,...,#1}{\psline[linecolor=yellow](!\x[#1,\i] I2P \y[#1,\i] I2P)(!\x[#1,\i] I2P neg \y[#1,\i] I2P neg)}
    \foreach \i in {1,...,#1}{\pscircle*[linecolor=white](!\X[#1,\i]{#2} I2P \Y[#1,\i]{#2} I2P){2pt}}
\end{pspicture}}

\begin{document}
\foreach \t in {0,...,24}
{
    \preview
    \Frame{1}{2*Pi*\t/25} \quad \Frame{2}{2*Pi*\t/25} \quad \Frame{3}{2*Pi*\t/25} \quad \Frame{5}{2*Pi*\t/25} \quad \Frame{10}{2*Pi*\t/25}
    \endpreview
}
\end{document}

```
> 17 votes

# Answer
**Fortran**

Each frame is created as an individual gif file using the Fortran gif module at: http://fortranwiki.org/fortran/show/writegif
Then I cheat a little by using ImageMagick to merge the individual gifs into one animated gif.

UPDATE: Set new = .true. to get the following:

```
program circle_illusion

use, intrinsic :: iso_fortran_env, only: wp=>real64
use gif_util  !gif writing module from http://fortranwiki.org/fortran/show/writegif

implicit none

logical,parameter :: new = .false.

integer,parameter  :: n        = 500  !550  !size of image (square)
real(wp),parameter :: rcircle  = n/2  !250  !radius of the big circle
integer,parameter  :: time_sep = 5    !deg

real(wp),parameter :: deg2rad = acos(-1.0_wp)/180.0_wp
integer,dimension(0:n,0:n):: pixel     ! pixel values
integer,dimension(3,0:3)  :: colormap  ! RGB 0:255 for colors 0:ncol
real(wp),dimension(2)     :: xy
integer,dimension(2)      :: ixy
real(wp)                  :: r,t
integer                   :: i,j,k,row,col,m,n_cases,ang_sep
character(len=10)         :: istr

integer,parameter  :: black = 0
integer,parameter  :: white = 1
integer,parameter  :: red   = 2
integer,parameter  :: gray  = 3
colormap(:,0) = [0,0,0]          !black
colormap(:,1) = [255,255,255]    !white
colormap(:,2) = [255,0,0]        !red
colormap(:,3) = [200,200,200]    !gray

if (new) then
    ang_sep = 5
    n_cases = 3
else
    ang_sep = 20
    n_cases = 0
end if

do k=0,355,time_sep

    !clear entire image:
    pixel = white

    if (new) call draw_circle(n/2,n/2,black,n/2)

    !draw polar grid:
    do j=0,180-ang_sep,ang_sep
        do i=-n/2, n/2
            call spherical_to_cartesian(dble(i),dble(j)*deg2rad,xy)
            call convert(xy,row,col)
            if (new) then
                pixel(row,col) = gray
            else
                pixel(row,col) = black
            end if
        end do
    end do

    !draw dots:
    do m=0,n_cases
        do j=0,360-ang_sep,ang_sep
            r = sin(m*90.0_wp*deg2rad + (k + j)*deg2rad)*rcircle
            t = dble(j)*deg2rad
            call spherical_to_cartesian(r,t,xy)
            call convert(xy,row,col)
            if (new) then
                !call draw_circle(row,col,black,10)  !v2
                !call draw_circle(row,col,m,5)       !v2
                call draw_circle(row,col,white,10)   !v3
            else
                call draw_square(row,col,red)        !v1
            end if
        end do
    end do

    !write the gif file for this frame:
    write(istr,'(I5.3)') k
    call writegif('gifs/test'//trim(adjustl(istr))//'.gif',pixel,colormap)

end do

!use imagemagick to make animated gif from all the frames:
! from: http://thanosk.net/content/create-animated-gif-linux
if (new) then
    call system('convert -delay 5 gifs/test*.gif -loop 0 animated.gif')
else
    call system('convert -delay 10 gifs/test*.gif -loop 0 animated.gif')
end if

!delete individual files:
call system('rm gifs/test*.gif')

contains

    subroutine draw_square(r,c,icolor)

    implicit none
    integer,intent(in) :: r,c  !row,col of center
    integer,intent(in) :: icolor

    integer,parameter :: d = 10 !square size

    pixel(max(0,r-d):min(n,r+d),max(0,c-d):min(n,c+d)) = icolor

    end subroutine draw_square

    subroutine draw_circle(r,c,icolor,d)

    implicit none
    integer,intent(in) :: r,c  !row,col of center
    integer,intent(in) :: icolor
    integer,intent(in) :: d  !diameter

    integer :: i,j

    do i=max(0,r-d),min(n,r+d)
        do j=max(0,c-d),min(n,c+d)
            if (sqrt(dble(i-r)**2 + dble(j-c)**2)<=d) &
                pixel(i,j) = icolor
        end do
    end do

    end subroutine draw_circle

    subroutine convert(xy,row,col)

    implicit none
    real(wp),dimension(2),intent(in) :: xy  !coordinates
    integer,intent(out) :: row,col

    row = int(-xy(2) + n/2.0_wp)
    col = int( xy(1) + n/2.0_wp)

    end subroutine convert

    subroutine spherical_to_cartesian(r,theta,xy)

    implicit none
    real(wp),intent(in) :: r,theta
    real(wp),dimension(2),intent(out) :: xy

    xy(1) = r * cos(theta)
    xy(2) = r * sin(theta)

    end subroutine spherical_to_cartesian

end program circle_illusion

```
> 12 votes

# Answer
Mandatory **C64** version.

Copy&paste in your favorite emulator:

```
1 print chr$(147)
2 poke 53281,0
3 for p=0 to 7
5 x=int(11+(cos(p*0.78)*10)):y=int(12+(sin(p*0.78)*10))
6 poke 1024+x+(y*40),15
9 next p
10 for sp=2040 to 2047:poke sp,13:next sp
20 for i=0 to 62:read a:poke 832+i,a:next i
30 for i=0 to 7:poke 53287+i,i+1:next i
40 rem activate sprites
50 poke 53269,255
60 an=0.0
70 rem maincycle
75 teta=0.0:k=an
80 for i=0 to 7
90 px=cos(k)*64
92 s=i:x=px*cos(teta): y=px*sin(teta): x=x+100: y=y+137: gosub 210
94 teta=teta+0.392699
95 k=k+0.392699
96 next i
130 an=an+0.1
140 goto 70
150 end
200 rem setspritepos
210 poke 53248+s*2,int(x): poke 53249+s*2,int(y)
220 return
5000 data 0,254,0
5010 data 3,199,128
5020 data 7,0,64
5030 data 12,126,96
5040 data 25,255,48
5050 data 59,7,152
5060 data 52,1,200
5070 data 116,0,204
5080 data 120,0,100
5090 data 120,0,100
5100 data 120,0,100
5110 data 120,0,36
5120 data 104,0,36
5130 data 100,0,108
5140 data 54,0,72
5150 data 51,0,152
5160 data 25,131,16
5170 data 12,124,96
5180 data 4,0,64
5190 data 3,1,128
5200 data 0,254,0

```
> 12 votes

# Answer
A compact javascript version, changing the default settings to something different

http://jsfiddle.net/yZ3DP/1/

HTML:

```
<canvas id="c" width="400" height="400" />

```

JavaScript:

```
var v= document.getElementById('c');
var c= v.getContext('2d');
var w= v.width, w2= w/2;
var num= 28, M2= Math.PI*2, da= M2/num;
draw();
var bw= 10;
var time= 0;
function draw()
{
    v.width= w;
    c.beginPath();
    c.fillStyle= 'black';
    circle(w2,w2,w2);
    c.lineWidth= 1.5;
    c.strokeStyle= c.fillStyle= 'white';
    var a= 0;
    for (var i=0; i< num*2; i++){
        c.moveTo(w2,w2);
        c.lineTo(w2+Math.cos(a)*w2, w2+Math.sin(a)*w2);
        a+= da/2;
    }
    c.stroke();
    a= 0;
    for (var i=0; i< num; i++){
        circle(w2+Math.cos(a)*Math.sin(time+i*Math.PI/num)*(w2-bw),
               w2+Math.sin(a)*Math.sin(time+i*Math.PI/num)*(w2-bw), bw);
        a+= da/2;
    }
    time+=0.03;
   requestAnimationFrame(draw);
}

function circle(x,y,r)
{
    c.beginPath();
    c.arc(x, y, r, 0, M2);
    c.fill();

}

```
> 11 votes

# Answer
My take with **Elm**. I am a total beginner who will happily accept PRs to improve this solution (GitHub):

Note that this submission is really moving points on straight lines:

```
import Color exposing (..)
import Graphics.Collage exposing (..)
import Graphics.Element exposing (..)
import Time exposing (..)
import Window
import List exposing (..)
import AnimationFrame -- "jwmerrill/elm-animation-frame"
import Debug

-- CONFIG

size = 600
circleSize = 240
dotCount = 12
dotSize = 10
velocity = 0.01

-- MODEL

type alias Dot =
    { x : Float
    , angle : Float
    }

type alias State = List Dot

createDots : State
createDots = map createDot [ 0 .. dotCount - 1 ]

createDot : Int -> Dot
createDot index =
    let angle = toFloat index * pi / dotCount
    in { x = 0
       , angle = angle
       }

-- UPDATE

update : Time -> State -> State
update time dots = map (moveDot time) dots |> Debug.watch "Dots"

moveDot : Time -> Dot -> Dot
moveDot time dot =
  let t = velocity * time / pi
      newX = (-circleSize + dotSize) * cos(t + dot.angle)
  in { dot | x <- newX }

-- VIEW

view : State -> Element
view dots =
   let background = filled black (circle circleSize)
       dotLinePairs = map viewDotWithLine dots
   in collage size size (background :: dotLinePairs)

viewDotWithLine : Dot -> Form
viewDotWithLine dot =
  let dotView = viewDot dot
      lineView = createLineView
  in group [dotView , lineView] |> rotate dot.angle

viewDot : Dot -> Form
viewDot d = alpha 0.8 (filled lightOrange (circle dotSize)) |> move (d.x, 0)

createLineView : Form
createLineView = traced (solid white) (path [ (-size / 2.0, 0) , (size / 2.0, 0) ])

-- SIGNALS

main = Signal.map view (animate createDots)

animate : State -> Signal State
animate dots = Signal.foldp update dots time

time = Signal.foldp (+) 0 AnimationFrame.frame

```
> 5 votes

# Answer
Second Life LSL

start of turtle alpha image (right click below to save image)
end of turtle alpha image (right click above to save image)
building the object:
make a root prim cylinder size \<1, 1, 0.01\> slice 0.49, 0.51, color \<0, 0, 0\>
make the description of this cylinder "8,1,1,1" without the quotes (very important)
make a cylinder, name it "cyl", color \<0.25, 0.25, 0.25\> alpha 0.5
duplicate the cyl 48 times
make a box, name it "sphere", color \<1, 1, 1\> transparency 100 except for the top transparency 0
put your turtle texture on face 0 of the box, turtle should face +x
duplicate the box 48 times
select all the boxes and the cylinders, make sure to select the root cylinder last, link (control L)

put these 2 scripts in the root:

```
//script named "dialog"
default
{
    state_entry()
    {

    }

    link_message(integer link, integer num, string msg, key id)
    {
        list msgs = llCSV2List(msg);
        key agent = (key)llList2String(msgs, 0);
        string prompt = llList2String(msgs, 1);
        integer chan = (integer)llList2String(msgs, 2);
        msgs = llDeleteSubList(msgs, 0, 2);
        llDialog(agent, prompt, msgs, chan);
    }
}

//script named "radial animation"
float interval = 0.1;
float originalsize = 1.0;
float rate = 5;
integer maxpoints = 48;
integer points = 23; //1 to 48
integer multiplier = 15;
integer lines;
string url = "https://codegolf.stackexchange.com/questions/34887/make-a-circle-illusion-animation/34891";

list cylinders;
list spheres;
float angle;
integer running;
integer chan;
integer lh;

desc(integer on)
{
    if(on)
    {
        string desc =
            (string)points + "," +
            (string)multiplier + "," +
            (string)running + "," +
            (string)lines
            ;

        llSetLinkPrimitiveParamsFast(1, [PRIM_DESC, desc]);
    }
    else
    {
        list params = llCSV2List(llList2String(llGetLinkPrimitiveParams(1, [PRIM_DESC]), 0));
        points = (integer)llList2String(params, 0);
        multiplier = (integer)llList2String(params, 1);
        running = (integer)llList2String(params, 2);
        lines = (integer)llList2String(params, 3);
    }
}

init()
{
    llSetLinkPrimitiveParamsFast(LINK_ALL_OTHERS, [PRIM_POS_LOCAL, ZERO_VECTOR,
        PRIM_COLOR, ALL_SIDES, <1, 1, 1>, 0]);
    integer num = llGetNumberOfPrims();
    integer i;
    for(i = 2; i <= num; i++)
    {
        string name = llGetLinkName(i);

        if(name == "cyl")
            cylinders += [i];
        else if(name == "sphere")
            spheres += [i];
    }

    vector size = llGetScale();
    float scale = size.x/originalsize;

    float r = size.x/4;
    vector cylindersize = <0.01*scale, 0.01*scale, r*4>;
    float arc = 180.0/points;

    for(i = 0; i < points; i++)
    {
        float angle = i*arc;
        rotation rot = llEuler2Rot(<0, 90, 0>*DEG_TO_RAD)*llEuler2Rot(<0, 0, angle>*DEG_TO_RAD);

        integer cyl = llList2Integer(cylinders, i);
        integer sphere = llList2Integer(spheres, i);

        llSetLinkPrimitiveParamsFast(1, [PRIM_LINK_TARGET, cyl, PRIM_POS_LOCAL, ZERO_VECTOR, PRIM_ROT_LOCAL, rot, PRIM_SIZE, cylindersize, PRIM_COLOR, ALL_SIDES, <0.25, 0.25, 0.25>, 0.5*lines,
        PRIM_LINK_TARGET, sphere, PRIM_COLOR, ALL_SIDES, <0.25 + llFrand(0.75), 0.25 + llFrand(0.75), 0.25 + llFrand(0.75)>, 1
        ]);
    }
}

run()
{
    vector size = llGetScale();
    float scale = size.x/originalsize;

    float r = size.x/2;
    vector spheresize = <0.06, 0.06, 0.02>*scale;
    float arc = 180.0/points;
    list params;
    integer i;
    for(i = 0; i < points; i++)
    {

        float x = r*llCos((angle + i*arc*multiplier)*DEG_TO_RAD);

        vector pos = <x, 0, 0>*llEuler2Rot(<0, 0, i*arc>*DEG_TO_RAD);
        rotation rot = llEuler2Rot(<0, 0, i*arc>*DEG_TO_RAD);
        integer link = llList2Integer(spheres, i);
        params += [PRIM_LINK_TARGET, link, PRIM_POS_LOCAL, pos,
            PRIM_ROT_LOCAL, rot,
            PRIM_SIZE, spheresize
            //PRIM_COLOR, ALL_SIDES, <1, 1, 1>, 1
            ];
    }

    llSetLinkPrimitiveParamsFast(1, params);
}

dialog(key id)
{
    string runningstring;
    if(running)
        runningstring = "notrunning";
    else
        runningstring = "running";

    string linesstring;
    if(lines)
        linesstring = "nolines";
    else
        linesstring = "lines";
    string prompt = "\npoints: " + (string)points + "\nmultiplier: " + (string)multiplier;
    string buttons = runningstring + ",points+,points-,reset,multiplier+,multiplier-," + linesstring + ",www";
    llMessageLinked(1, 0, (string)id + "," + prompt + "," + (string)chan + "," + buttons, "");
    //llDialog(id, prompt, llCSV2List(buttons), chan);
}

default
{
    state_entry()
    {
        chan = (integer)("0x" + llGetSubString((string)llGetKey(), -8, -1));
        lh = llListen(chan, "", "", "");

        desc(FALSE);
        init();
        run();
        llSetTimerEvent(interval);
    }

    on_rez(integer param)
    {
        llListenRemove(lh);
        chan = (integer)("0x" + llGetSubString((string)llGetKey(), -8, -1));
        lh = llListen(chan, "", "", "");
    }

    touch_start(integer total_number)
    {
        key id = llDetectedKey(0);
        dialog(id);
    }

    timer()
    {
        if(!running)
            return;

        angle += rate;
        if(angle > 360)
            angle -= 360;
        else if(angle < 0)
            angle += 360;

        run();
    }

    listen(integer channel, string name, key id, string msg)
    {
        if(msg == "points+")
        {
            if(points < maxpoints)
            {
                points++;
                desc(TRUE);
                llResetScript();
            }
        }
        else if(msg == "points-")
        {
            if(points > 0)
            {
                points--;
                desc(TRUE);
                llResetScript();
            }
        }
        else if(msg == "multiplier+")
        {
            multiplier++;
            desc(TRUE);
        }
        else if(msg == "multiplier-")
        {
            multiplier--;
            desc(TRUE);
        }
        else if(msg == "running")
        {
            running = TRUE;
            desc(TRUE);
        }
        else if(msg == "notrunning")
        {
            running = FALSE;
            desc(TRUE);
        }
        else if(msg == "lines")
        {
            lines = TRUE;
            desc(TRUE);
            llResetScript();
        }
        else if(msg == "nolines")
        {
            lines = FALSE;
            desc(TRUE);
            llResetScript();
        }
        else if(msg == "reset")
            llResetScript();
        else if(msg == "www")
            llRegionSayTo(id, 0, url);
        dialog(id);
    }
}

```
> 3 votes

# Answer
# PICO-8, 271 chars

```
camera(-64,-64)p=8::_::s=p.." lines"cls(7)circfill(0,0,50,0)for l=0,.5,.5/p do
u=flr(50*cos(l))v=flr(50*sin(l))line(u,-v,-u,v,5)end
?s,-#s*2,-60
for l=0,.5,.5/p do
u=flr(48*cos(l))v=flr(48*sin(l))q=cos(l-t()/4)circfill(u*q,-v*q,2,7)end
flip()p+=flr(btnp()/16+1)%3-1goto _

```

The code for this is so short, I could post it as a tweet. In fact, I just did.

You can also change the number of lines with the X and Z keys. (Oddly enough, due to a side effect of how division by 0 is handled in PICO-8, 0 lines acts exactly like 1 line. Negative numbers of lines don't show up.)

Ungolfed source:

```
lines=8

while true do
 cls(7)
 -- draw circle
 circfill(64,64,50,0)
 -- draw lines
 for l=0,.5,.5/lines do
  u=flr(50*cos(l))
  v=flr(50*sin(l))
  line(64+u,64-v,64-u,64+v,5)
 end
 -- center string
 s=lines.." lines"
 print(s,64-#s*2,4)
 -- draw points
 for l=0,.5,.5/lines do
  u=flr(48*cos(l))
  v=flr(48*sin(l))
  -- one full turn every 4 secs
  q=cos(l-t()/4)
  circfill(64+u*q,64-v*q,2,7)
 end
 flip()
 -- -1 if only ❎ is pressed
 -- +1 if only  is pressed
 --  0 otherwise
 lines+=flr(btnp()/16+1)%3-1
end

```
> 2 votes

---
Tags: popularity-contest, graphical-output, animation
---


# Question
Title: Can this Scottish village have a wedding?
This is the exact same question I asked earlier, but without the annoying Cyrillic factor which many found superfluous. I hope this is a better puzzle!

---

The quaint hamlet of North Codetown in the Scottish far north has a problem: their population is low (below 52), and no new people have arrived for years. Moreover, after centuries of near-isolation in their secluded valley without much economic opportunity, just about everybody is related to each other.

Mayor Montgomery has a solution that should keep the morale high: organise a wedding. However, the question is, are there two bachelors in the town that aren't at least cousins of each other?

The mayor fired up his state-of-the-art Microsoft Bob computer to consult the genealogy charts. They had just been updated to the brand-new ASCII format, and look like this:

```
b┬K
 l

```

And this:

```
 A┬d
 O┴p┬Z
    q

```

And this:

```
  e┬N
L┬m┴p─┬F
B┴y┬A z┬Y
   f   E

```

And even this:

```
 i┬────────N
m┬E
 │     Z
 │
 │
 z

```

Here's how it works. Each person is a letter from the Latin alphabet. Males are capital letters (any of ABCDEFGHIJKLMNOPQRSTUVWXYZ), females are lowercase letters (any of abcdefghijklmnopqrstuvwxyz).

A '┬' between two people means they are married. Right below that is either another person - their child - or a '┴', meaning that this couple has two children; located to the left and right of the symbol.

Moreover, to the right and left of '┬' and '┴' there can be any number of '─' characters, to extend the lines, as it were. Similarly, there can be any number of '│' characters above a '┴' or below a '┬'.

Lastly, a character without any defined symbol above them is considered a new arrival to the village, and by definition unrelated to anybody.

Also be aware that this is a very conservative village. Nobody marries more than once, and every marriage is heterosexual. Furthermore, assume everybody in the graph is alive, and no two people share the same name: e.g., the same character never occurs more than once.

The two bachelors should be of the opposite gender, and they should not be first cousins or any more closely related. First cousins once removed is okay. In other words: they should not share a parent, or a grandparent, or have one's grandparent be another's parent.

## Challenge

Make the shortest possible program (by byte count) with as input either a string (containing newline characters), or a string array, or a rectangular two-dimensional string or char array (no higher or wider than 100 characters), containing the family tree of the town. Assume the input is a valid family tree, consisting of nothing but ASCII printable characters and the mentioned line/forking characters. Ignore any character not given an explicit function in the above description.

Return a boolean value of true or false (or a bit/int of 1 or 0, or any consistent truthy/falsey value used by the language of your choice) to indicate whether there can be a wedding given the family tree.

## Examples

1.

```
b┬K
 i

```

FALSE (there's only one bachelor)

2.

```
   A┬d
 i┬O┴p┬Z
  z   F

```

FALSE (z and F are cousins)

3.

```
  e┬N
L┬m┴p─┬F
B┴y┬A W┬y
   E   T

```

FALSE (B, E and T are all male)

4.

```
  e┬N
L┬m┴p─┬F
q┴A┬y w┬R
   U   E

```

TRUE (q and E can marry)

5.

```
             i┬────────N
            m┬E
             │     w
             │
             │
             W

```

TRUE (w is not related to anybody)

6.

```
           d┬F
 a┬────────N┴─e┬E
  │            │
  │            w
  │
  │
  V

```

FALSE (V and w are cousins)

7.

```
Ww

```

TRUE (W and w are unrelated)

8.

```
fw

```

FALSE (f and w are of the same gender)

9.

```
    e┬N
  L┬m┴p─┬F
n┬B┴y┬A w┬Y
 C   E   i

```

TRUE (i and E, and also i and C)

10.

```
 A┬d      f┬H
 m┴P┬z     i┬Y
    F       u

```

TRUE (F and u)

NOTE: You are free to substitute the control characters with ASCII characters if it makes your program simpler. In that case switch out │ with | (vertical bar), ─ with - (hyphen), ┬ with + and ┴ with =.

Example:

```
           d+F
 a+--------N=-e+E
  |            |
  |            w
  |
  |
  V

```

# Answer
# Jelly, ~~155~~ 153 bytes

```
Ø.UAƭN,Ɗ⁺+Ṫ¥+œị⁾+|yⱮ$ɼ=⁾|=⁼Ø.Ɗɗ¡ƬṪ¥ƒ⁸’1¦⁺œị®⁼”|ƊÐ¿ṖṪ+2¦œị®⁻1Ɗ¡ƬṪ¥ⱮØ+$“”¹?
o@e¥€€ØẠ“-=“==”;U¤œṣjƭƒ$€ƬṪ©=1ŒṪ+2¦œị®ɗⱮØ+f⁾-+ƊÐḟWÇ€Ẏ$Ƭḣ3ẎƲ€Œcf/ÐḟḢ€€ȧœị¥>”ZIFẸ

```

Try it online!

Minor modification of my Cyrillic version.

A monadic link that takes a list of Jelly strings and returns 1 for true and 0 for false. I’m sure this could be golfed more. Full explanation to follow.
> 5 votes

# Answer
# Python 2, ~~399~~ ~~393~~ ~~390~~ ~~388~~ 385 bytes

```
def f(s):
 V=S(''.join(s))-S(' |+-^');P={v:[]for v in V}
 for j,r in E(s):
	for i,c in E(r):
	 if'+'==c:
		p,q=a=h(r,i);A=a+P[p][:2]+P[q][:2];V-=S(a);v=j;b='|'
		while'z'<b:v+=1;b=s[v][i]
		if'^'==b:w,x=h(s[v],i);P[w]=P[x]=A
		else:P[b]=A
 return 1-all((b>'Z')==(c>'Z')or S(P[b])&S(P[c])for b in V for c in V)
h=lambda r,i:[x.strip('-')[0]for x in r[i-1::-1],r[i+1:]]
E=enumerate;S=set

```

Try it online!

2 bytes thx to Jitse; 3 bytes thanks to isaacg.

Jeez! I think I could golf this a bit more; but at least I got it under 400 bytes :).

The input `s` is a list of strings. The encoding is `A-Z` for males, `a-z` for females, `+` to indicate a marriage, `^` for when a marriage produces 2 children (instead of `=`, 'cause I liked the look better :) ). Then `-` for horizontal extensions, `|` for vertical extensions.

Output is `1` for truthy, `0` for falsey.

`V` is the set of all villagers, initially; then as we scan, we will remove from `V` those who are already married. So at the end, `V` will be the set of un-mated villagers.

`P` is a dictionary with keys for all villagers `v`. `P[v]` will be the list of those parents of `v`, followed those grandparents of `v`, who are also villagers. Note that then `P[v][:2]` are the parents of `v` (assuming they are villagers).

`h` is a helper function to skip over any horizontal extensions (runs of `-`). Useful both for extracting a pair of parent villagers as well as dual children.
> 12 votes

---
Tags: code-golf, decision-problem, graph-theory
---


title: Gaussian integer division reminder

text:
# Question
Title: Gaussian integer division reminder
Gaussian integer is a complex number in the form \\$x+yi\\$, where \\$x,y\\$ are integer and \\$i^2=-1\\$. The task is to perform such operation for Gaussian integers \\$a,b\\$, that \\$a=q \cdot b+r\\$ and \\$|r|\<|b|\\$ (\\$q,r\\$ are Gaussian integers, \\$|z|\\$ is defined as \\$\sqrt{a^2+b^2}\\$ for \\$a+bi=z\\$).
Need to output only \\$r\\$.
One of possible approaches is here.

**Scoring**: the *fastest* in terms of O-notations algorithm wins, though it can consume more time. By fastest I mean \\$O(\left(f(n)\right)^a)\\$ is preferred for smaller \\$a\\$ and \\$O(\log^a(\log(n)))\\$ will be preferred over \\$O(\log^b(n))\\$, ...over \\$O(n^k)\\$, ...over \\$O(e^{\alpha n})\\$ and so on.
If there's a tie, fastest implementation wins in terms of benchmark (e.g. 100 000 random 32-bit \\$b\\$ and 64-bit \\$a\\$ (I mean both real and imaginary part to be 32 or 64 signed integer)) or there can be 2-3 winners.
If unsure about algorithm complexity, leave blank. E.g. I believe Euler's algorithm for integers has \\$O(\log(n))\\$ time complexity.

Test cases can be obtained from wolframalpha in the form like Mod\[151 + 62 I, 2 + I\], but in case there are some:

```
4 mod (3+3*i) = either of 1+3*i, -2-0*i, 4-0*i, 1-3*i
10000 mod 30*i = either 10 or -20
(3140462541696034439-9109410646169016036*i) mod (-81008166-205207311*i) =
    either -75816304-29775984*i or 129391007+51232182*i

```

\\$|b|\\$ will not exceed 32 bits, but you don't have to code long arithmetic if your selected language doesn't have built-in one.

Good luck. Of course, WolframLanguage is forbidden. )

# Answer
# Python 2 (PyPy), O(1) operations

```
def cmod(a1, a2, b1, b2):
	# Compute p = a * conj(b)
	p1 =   a1 * b1 + a2 * b2
	p2 = - a1 * b2 + a2 * b1

	# Compute the norm-squared of b
	b_nsq = b1 ** 2 + b2 ** 2
	b_nsq_half = b_nsq // 2

	# Do a symmetric mod of d1 and d2 by b_nsq
	# That is, into the interval [-b_nsq_half, +b_nsq_half)
	d1 = (p1 + b_nsq_half) % b_nsq - b_nsq_half
	d2 = (p2 + b_nsq_half) % b_nsq - b_nsq_half

	# Compute r = d / b
	r1 = (d1 * b1 - d2 * b2) // b_nsq
	r2 = (d1 * b2 + d2 * b1) // b_nsq

	return r1, r2

```

Try it online!

Uses pure integer arithmetic, with no loops or branching or built-in complex numbers. This should easily complete the benchmark of 100,000 random inputs within a small fraction of a second. Porting this to a faster language would be straightforward and likely improve performance.

One possible low-level optimization is the Karatsuba algorithm trick to do complex multiplication using 3 rather than 4 integer multiplications. But, this might not be worth it for such "small" values.
> 2 votes

---
Tags: math, code-challenge, fastest-algorithm, complex-numbers
---


title: Substitute Unprintable ASCII Characters

text:
# Question
Title: Substitute Unprintable ASCII Characters
<sup> Sandbox </sup>

Have y'all ever written an answer with unprintable ASCII characters in it and wished that there was an easy way to represent those characters in a printable way? Well, that's why the Control Pictures Unicode block was invented.

However, manually substituting these characters into one's answer is time-consuming, so that's what today's challenge is about: swapping out the nasty invisible characters for nice, readable characters.

## Input

You will be given strings that contain a mix of ASCII-only characters (i.e. the UTF-8 code point of each character will be in the range: \\$0 \lt char \le 127\\$).

## Output

For all unprintable characters, replace it with its corresponding character in the Control Pictures Unicode range.

In other words:

* Characters in the range \\$0 \lt char \lt 9\\$ are replaced with their corresponding character
* Horizontal tabs and newlines (9 and 10) *aren't* replaced
* Characters in the range \\$11 \le char \lt 32\\$ are replaced with their corresponding character
* Spaces (32) *aren't* replaced
* The delete character (127) is replaced with its corresponding character:

## Tests

*Characters are given as escapes for nice formatting here, but each character will be replaced with the unprintable character*

```
In -> Out
\x1f\x1c\x1f\x1e\x1f\x1e\x1f\x1f\x1e\x1f\x1e\x1f -> ␟␜␟␞␟␞␟␟␞␟␞␟
Hello\x07World! -> Hello␇World!
\x01\x02\x03\x04\x05\x06\x07\x08\x0c\x0b\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x7f -> ␁␂␃␄␅␆␇␈␌␋␎␏␐␑␒␓␔␕␖␗␘␙␚␛␜␝␞␟␡
\r -> ␍

```

## Rules

* All standard loopholes are forbidden
* Character substitutions *must* be made according to the Control Pictures Unicode block
* Input will be given with the literal unprintable characters

## Scoring

This is code-golf so the answer with the fewest amount of bytes wins.

## Test-Case Generator

I have provided a test case generator for y'all. It prints inputs in the way they will be passed to your program and outputs the expected result.

Try it here!

## Leaderboards

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

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

```
# Language Name, N bytes

```

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

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

```

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

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

```

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

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

```

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

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

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

# Answer
# Zsh, ~~83 79~~ 78 bytes

*-4 bytes by changing to a recursive solution, (-0 from bugfix,) -1 by abusing unquoted empty parameters expanding to 0 words*

```
<<<${1+"${(#)$((x=#1,x>126?x+9122:(x<9)^(x<11)^(x<32)?x+9216:x))}`$0 ${1:1}`"}

```

~~Try it online! Try it online!~~  Try it online!

In arithmetic contexts, `#1` is the code of the first character of `$1`. We use it 7 times, so `x=#1,` saves us 2 bytes. There may be a more compact way to do `(x<9)^(x<11)^(x<32)`.

The `${1+foo}` expands to `foo` *unless* `$1` is undefined, providing our recursive base case. The `"`$0 ${1:1}`"` is the actual recursive call. When an empty parameter is unquoted, it is removed from the word list, thus causing the final recursion be run with zero arguments.

Running strings longer than about 35 characters with the recursive solution causes TIO to complain: "fork failed: resource temporarily unavailable". However, with usual resource limits on a desktop, there shouldn't be a problem.

**Potential changes:**

* With the flag `-oCPRECEDENCES`, `<` binds more tightly than `^`, which would save 6 bytes by removing parentheses.
* With the flag `-oEXTENDEDGLOB`, we gain access to backreferences using `(#m)` and the `$MATCH` parameter. An approach like Arnauld's Javascript answer could be used, but it ends up being longer than the purely arithmetic approach.
* I also tried a transliterate solution, but the larger codepoints of the control pictures grew the bytecount too quickly.
> 7 votes

# Answer
# JavaScript (Node.js),  ~~67~~  66 bytes

*Saved 1 byte thanks to @Grimmy*

```
s=>s.replace(/[^ -~ \n]/g,c=>(B=Buffer)([226,144,B(c)[0]%94+128]))

```

<sup>includes a literal `TAB`</sup>

Try it online!

### How?

We match all characters that are:

```
   +-------> neither printable
   |  +----> nor a tabulation
   |  | +--> nor a linefeed
  / \ | |
[^ -~\t\n]

```

and replace them with the UTF-8 sequence \\$\[226, 144, (n\bmod94)+128\]\\$, where \\$n\\$ is the ASCII code of the original character.

This is equivalent to generating the code point \\$(n\bmod94)+9216\\$. But given the length of the corresponding JS method names, that would be ~~74~~ 73 bytes in plain ES6:

```
s=>s.replace(/[^ -~ \n]/g,c=>String.fromCharCode(c.charCodeAt()%94+9216))

```

Try it online!
> 7 votes

# Answer
# C (gcc), 119 109 108 89 75 bytes

Thanks to ceilingcat and Arnauld for the suggestions.

Like my original submission, the UTF-8 code sequence is largely hard-coded, but instead of using string literals an integer is used instead. This takes advantage of the fact that the LSB of an integer (on a little-endian processor) is the first byte stored in memory, and `0` MSB bytes map to `NUL` which terminates the string. For unprintable characters that map to the control pictures, three bytes are used to represent the value; one byte is used for everything else.

One trick which I use is to force the comparison of a contiguous range of values to zero so that I can use unsigned comparisons. This wraps around any values below the range to high values, allowing me to use a single compare (the `d-9U>1`, which is true for x\<9 or x\>10.)

```
d;f(char*s){for(;d=*s++;printf(&d))d=d>126|d<32&d-9U>1?d%94<<16|8425698:d;}

```

Try it online!

## Original version (89 bytes)

As C doesn't handle UTF-8 natively, I output the hard-coded prefix bytes and compute the trailing byte (which is the only byte that requires changing) if I need to print a control picture glyph. Other than that, it's a pretty standard string-processing function.

```
d;f(char*s){for(;d=*s++;printf(d>126|d<32&d-9U>1?"\xE2\x90%c":"%2$c",d%94+128,d));}

```

Try it online!
> 6 votes

# Answer
# Retina 0.8.2, ~~27~~ 24 bytes

```
T`-`␁-␟␡`[^	\n]

```

Try it online! `T`ransliterates the unprintables to the appropriate control pictures, but the tabs and newlines are excluded (for a 3-byte saving). Note: No CRs in the test cases because I don't know how to demonstrate them in TIO. Code would probably work with nulls with the obvious adjustments for the same byte count, but I don't know how to test that either.
> 5 votes

# Answer
# Python 3, 69 bytes

```
lambda s:s.translate({i%128:i%34+9216for i in{*range(-1,32)}-{9,10}})

```

Try it online!
> 5 votes

# Answer
# Red, ~~94~~ 92 bytes

```
func[s][n: charset[not{
}#" "-#"~"]parse s[any[p: change n(to sp p/1 % 94 + 9216)| skip]]s]

```

Try it online!

A port or @Arnauld's 74-byte JavaScript solution, don't forget to upvote his answer!
> 3 votes

# Answer
# Perl 5 (`-pC -Mutf8`), 27 bytes

same as Neil's retina solution

```
y;--;␁-␈␋-␟␡

```

Try it online!
> 2 votes

# Answer
# Jelly, 24 bytes

```
32R;Ø⁷’ḟ9ḟ⁵ż%94+⁽ ḥƊ$ỌFy

```

Try it online!

A monadic link taking a Jelly string and returning a Jelly string with the desired substitutions.
> 2 votes

# Answer
# Ruby `-p`, 36 bytes

`\0` should really be a null byte but I was having trouble getting it in the code, oh well.

Input in STDIN should be the direct bytes but I put in some boilerplate code to make it more readable and obvious that they were the test cases.

```
$_.tr!"\0--","␀-␈␋-␟␡"

```

Try it online!
> 1 votes

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