title: 9 Digit Problem

text:
# Question
Title: 9 Digit Problem
Write a program to find **a** number consisting of 9 digits in which each of the digits from 1 to 9 appears only once. This number must also satisfy these divisibility requirements:

1. The number should be divisible by 9.
2. If the rightmost digit is removed, the remaining number should be divisible by 8.
3. If the rightmost digit of the new number is removed, the remaining number should be divisible by 7.
4. And so on, until there’s only one digit (which will necessarily be divisible by 1).

Credit Dávid Németh

# Answer
# CJam - 26

```
1{;9,:)_mrs0@{_3$<i\%+}/}g

```

It's randomized but works pretty fast with the java interpreter. It can take a couple of minutes with the online interpreter.

**Explanation:**

`1` pushes 1 (to be explained later)
`{…}g` is a do-while loop
`;` removes a value from the stack (initially the 1 we started with)
`9,` makes the array \[0 ... 8\]
`:)` increments the array elements, resulting in \[1 ... 9\]
`_` duplicates the array
`mr` shuffles the array
`s` converts to string
`0@` pushes 0 then brings the other copy of the array on top
`{…}/` is a for-each loop (over the numbers 1 ... 9)
`_` duplicates the current number (let's call it "k")
`3$` copies the numeric string from the stack
`<i` gets the substring with the first k characters then converts to integer
`\%` swaps with the other copy of k then gets the remainder (%k)
`+` adds the remainder to the previous value on the stack (initially 0 from above)
At this point, we have the numeric string on the stack, followed by a 0 if the number matches all the requirements (i.e. all the remainders were 0) or a non-0 value otherwise.
The top of the stack becomes the do-while loop condition. It is popped and the loop continues if the condition was true.
If we found the solution, the condition is 0 (false), the loop ends and the rest of the stack (the numeric string) is printed.
If it's not the solution, the condition is the non-0 value (true) and the loop continues with the string on the stack. The string gets popped at the start of the next iteration (so the loop expects a value on the stack, and that's the reason for the initial 1).

Thanks Dennis for making the code shorter and more convoluted :p
> 9 votes

# Answer
# Javascript (E6) 105 ~~125 134~~

Recursive building of the number, each step check the divisibility.
*Runtime near 0 sec*
No I/O this time, as the OP asked for a program to find the number, and the number is found and automatically logged to console

**Golfed more** Courtesy of MT0

```
(Q=(n,d,b)=>([(m=n+(s=[...b]).splice(i,1))%d||Q(m,d+1,s)for(i in b)],d>9&&(Q.z=n),Q.z))('',1,'123456789')

```

**Golfed**

```
(Q=(n='',d=1,b=[...'123456789'],i)=>{
for(i=0;s=[...b],m=n+s.splice(i,1),b[i];i++)m%d||Q(m,d+1,s);d>9&&(Q.z=n);return Q.z;
})()

```

**Ugly**

```
(Q=(n='', d=1, b=[...'123456789'], i) => {
   for(i=0; s=[...b], m=n+s.splice(i,1), b[i]; i++)
     m % d || Q(m,d+1,s);
   d > 9 && (Q.z=n);
   return Q.z;
})()

```

**Bonus**

With 3 little changes, you can use the same function to find longer numbers using base \> 10. For instance in base 14 ...

```
(Q=(n='',d=1,b=[...'123456789ABCD'],i)=>{
  for(i=0; s=[...b], m = n+s.splice(i,1), b[i]; i++)
    parseInt(m,14)%d || Q(m,d+1,s);
  d>13 && (Q.z=n);
  return Q.z;
})()

```

> 9C3A5476B812D

**Ungolfed**

```
Q=(n,d,b,i,c,z)=>{ // i,c,z fake parameters instead of vars.
  for (i=0; b[i]; i++)
  {
    s=[...b];
    m = n + s.splice(i,1);
    if (m % d == 0)
      if (z = d<9 ? Q(m, d+1, s) : m) return z;
  }
}
Q('',1,[...'123456789'])

```
> 7 votes

# Answer
## Python3, ~~214~~, ~~199~~, ~~184~~, ~~176~~, ~~174~~, ~~171~~, ~~165~~, ~~150~~, 146

```
from itertools import*
g=lambda i,d:d==1!=print(i)or int(i[9:])%d==0!=g(i[:-1],d-1)
for x in permutations("123456789"):g("".join(map(str,x))*2,9)

```

output:

```
381654729

```

This is my first golf script. Hope you like it :)
> 5 votes

# Answer
# Perl, 56

Usage: `perl -E '...'`

```
{$s++;redo if grep{$s!~$_||substr($s,0,$_)%$_}1..9}say$s

```

Output: `381654729`

This program is **really slow**. As in more than 3.5 hours.

As a more fun exercise, I decided to develop an extremely fast algorithm:

```
my $set = [1..9];
for my $divisor (2..9) {
    my $newset = [];
    for my $element (@$set) {
        my $num = $element * 10;
        for (my $digit = $divisor - ($num % $divisor); $digit < 10; $digit += $divisor) {
            if (index($element, $digit) == -1) {
                push @$newset, $num + $digit;
            }
        }
    }
    $set = $newset;
}

print "@$set\n";

```

The above runs in .00095 seconds, and confirms that there is only one solution to this problem.
> 5 votes

# Answer
## Ruby, 66 ~~78~~ chars

```
[*r=1..9].permutation{|i|r.all?{|x|eval(i[0,x]*"")%x<1}&&$><<i*""}

```

Runtime is ~8 seconds (output printed after 3 s).

This doesn't stop after finding the first number, so technically it prints *all* numbers that fulfill the criteria - but since there's only one such number, it doesn't make a difference.

## Ruby 1.8, 63

```
[*r=1..9].permutation{|i|r.all?{|x|eval(i[0,x]*"")%x<1}&&$><<i}

```

Essentially the same solution as above. In Ruby 1.8, arrays are converted to strings by implicitly calling `Array#join` on them, so we can save the call to that. Interestingly, the code also runs much faster in Ruby 1.8 than 2.0 (4.5 seconds total runtime, output printed after 1.6 s).
> 4 votes

# Answer
# Pyth, 33 characters

```
=Y]kFkY~Yf>ql{TlT%vTlTm+k`dr1T)pk

```

To test it, put the above code as standard input in the link in the title.

After compiling into Python 3.4:

```
k=''
T=10
Y=[k]
for k in Y:
 Y+=list(filter(lambda T:(len(set(T))==len(T))>(eval(T)%len(T)),
                map(lambda d:k+repr(d),range(1,T))))
print(k)

```

Explanation:

`=Y]k`:`Y=['']`

`FkY`: for k in F:

`~Y`: Add to Y

`f`: Filter by

`>ql{TlT`: All unique elements and

`%vTlT`: eval(element)%len(element)=0

`m+k`\` `d` On the list of k + repr(d)

`r1T`: for d from 1 to 9.

`)`: End for loop

`pk`: print k
> 4 votes

# Answer
## Haskell ~~129~~ 121

Here is my amateurish Haskell attempt (suggestions/improvements would be greatly appreciated). It might not be the shortest, but it does execute in only ~~.19~~ .65 seconds after Flonk's changes on my system.

```
import Data.List;f=foldl1$(+).(*10);main=print$[f x|x<-permutations[1..9],f[mod(read.take y.show$f x)y|y<-[9,8..1]]<1]!!0

```
> 3 votes

# Answer
## GolfScript (35 chars)

```
1,{{10*){.)}8*}%{`..&=},{.`,%!},}9*

```

Online demo

This builds prefixes which satisfy the condition.

```
# Initial prefixes: [0]
1,
# Loop 9 times
{
    # Extend each prefix by digits 1 to 9
    {10*){.)}8*}%
    # Filter out ones which repeat a digit
    {`..&=},
    # Filter down to ones which are divisible by their length
    {.`,%!},
}9*

```
> 3 votes

# Answer
## Python, ~~142~~, ~~139~~, ~~125~~, 124

Essentially same as @Ventero's solution if I understood his code correctly, but in Python.(Much of the credit goes to @Greg Hewgill.)

```
from itertools import*;print[s for s in map(''.join,permutations('123456789'))if all(t(s[:i])%i==0 for i in range(1,9))][0]

```
> 2 votes

# Answer
# Javascript 75 (terminating)

Bruteforce solution (super slow)

```
for(a=c=1;b=c&&++a;)for(c=9;~(a+'').search(c)&&b%c<1;)--c?b=b/10|0:alert(a)

```

If you want to see the result in this lifetime, update the initial value to something like `a=c=38e7`

# Javascript 70 (non-terminating)

```
for(a=1;b=++a;)for(c=9;~(a+'').search(c)&&b%c<1;)--c?b=b/10|0:alert(a)

```

And just for fun, a random bruteforce that runs much faster: (ES6 only)

```
for(a=i=[..."123456789"];b=c=i&&a.sort(x=>Math.random()*9-5|0).join('');)for(i=9;c%i<1;)--i?c=c/10|0:alert(b)

```
> 2 votes

# Answer
# Perl, 72

Usage: `perl -M5.010 find-9-digits.pl`

```
{$s=join'',sort{4-rand 8}1..9;redo if grep{substr($s,0,$_)%$_}2..9}say$s

```

Output: `381654729`

This program is **slow**. It might take more than 10 seconds, because it shuffles the digits "123456789", but the shuffle has a flaw.

Ungolfed:

```
# Enter a block.
{
     # Shuffle the characters "123456789".
     $s = join('', sort({2 - rand(4)} 1..9));

     # Redo block if any divisiblity test fails; grep returns the
     # number of failing tests.
     redo if grep({
        # For each divisor $_ in 2..9, test if the first $_ digits of
        # of $s are divisible by $_.  The test fails if the remainder
        # is a true value (not zero).
        substr($s, 0, $_) % $_
     } 2..9);
}
say $s;

```

I golfed the code that shuffles the array of digits 1..9:

* `use List'Util shuffle;shuffle 1..9` (34 characters)
* `sort{(-1,1)[rand 2]}1..9` (24 characters)
* `sort{.5<=>rand}1..9` (19 characters)
* `sort(2-rand 4}1..9` (18 characters)
* `sort{4-rand 8}1..9` (18 characters)

Perl expects the sort block to compare *$a* and *$b* in a consistent way. My sort blocks never look at *$a* and *$b*. They return a random ordering so the sort becomes a shuffle.

If I would use `sort{.5<=>rand}1..9`, my program would run faster. That one compares 0.5 with a random float from 0.0 to 1.0, excluding 1.0, for a 1/2 chance that *$a \< $b*, and an almost 1/2 chance that *$a \> $b*. (**Beware:** This is a "Microsoft shuffle", which is *not* a fair shuffle. This has bias because `.5<=>rand` does not provide a consistent ordering.)

Suppose that I golf away one character and use the much worse `sort(2-rand 4}1..9`. Perl expects the sort block to return an integer, but `2-rand 4` is a float. It is a random float from -2.0 to 2.0, excluding -2.0. Perl truncates this float toward zero, with these results:

* 1/4 chance that *$a \< $b*, integer -1 from -2.0 \< float \<= -1.0
* near 1/2 chance that *$a == $b*, integer 0 from -1.0 \< float \< 1.0
* near 1/4 chance that *$a \> $b*, integer 1 or 2 from 1.0 \<= float \<= 2.0

When *$a == $b*, Perl does not shuffle well. So, my program would do more shuffles, until it gets enough shuffles where `2-rand 4` did not return 0 too often. My program would run so slow, it might take more than one minute.

I use `sort{4-rand 8}1..9`, so there is only a 1/4 chance that *$a == $b*, and my program uses fewer shuffles.
> 2 votes

# Answer
# Python 2 (78)

```
x=1
while len(set(`10*x`))<=9+sum(x/10**i%(9-i)for i in range(9)):x+=1
print x

```

No need to generate permutations, just try each number and check if its digits plus 0 are distinct. Takes a while to run.
> 2 votes

# Answer
# Scala (128 chars)

My stab at this...

```
Seq(1,2,3,4,5,6,7,8,9).permutations.filter(p=>(2 to 8)forall{n=>(p.take(n).mkString.toLong%n==0)}).map(_.mkString.toLong).toList

```
> 2 votes

# Answer
# Jelly, ~~13~~ 11 bytes

```
9Œ!JḍḌƤPƲƇḌ

```

Try it online!

## How it works

```
9Œ!JḍḌƤPƲƇḌ - Main link. No arguments
9           - Yield 9
 Œ!         - Yield all permutations of [1, 2, ..., 9]
        ƲƇ  - Keep those for which the following is true:
      Ƥ     -   Over each prefix:
     Ḍ      -     Convert into an integer
   J        -   Yield [1, 2, ..., 9]
    ḍ       -   Pair each [1, 2, ..., 9] with the prefixes,
                then return 1 if they divide each other else 0
       P    -   All return 1
          Ḍ - Convert back to an integer

```

---

Of course, there's the obvious 9 byter:

```
381654729

```

Try it online!
> 2 votes

# Answer
# CJam, 35 bytes

```
0{)_`$A,1>s=!1$9,{9\m1$\%@+\A/}/;}g

```

After roughly 27 minutes, this produces the following output:

```
381654729

```

### How it works

```
0         " Push 0 (“n”).                                                      ";
{         "                                                                    ";
  )_`$    " Increment “N”, duplicate, stringify and sort the resulting string. ";
  A,1>s   " Push '123456789'.                                                  ";
  =!      " Push 0 if the strings are equal and 1 otherwise (“a”).             ";
  1$      " Copy “n”.                                                          ";
  9,{     " For each i in [ 0 1 2 3 4 5 6 7 8 ].                               ";
    9\m   " Calculate “9 - i”.                                                 ";
    1$\%  " Calculate “n % (9 - i)”.                                           ";
    @+    " Add the result to “a”.                                             ";
    \A/   " Swap “a” with “n” and calculate “n / 10”.                          ";
  }/      "                                                                    ";
  ;       " Discard “n”.                                                       ";
}g        " If “a > 0”, repeat the loop.                                       ";

```
> 1 votes

# Answer
## SWI-Prolog 84

```
g([],O,_,O).
g(L,N,I,O):-nth1(_,L,D,R),M is N*10+D,J is I+1,0 is M mod J,g(R,M,J,O).

```

It is a bit cheating, because the list of digits needs to be supplied in the query:

```
?- g([1,2,3,4,5,6,7,8,9],0,0,O).
O = 381654729 ;
false.

```

However, it is what makes this code interesting: you can solve the problem for any list of digits. For example:

```
?- g([1,2,3,4,5,6,7,8,9,0],0,0,O).
O = 3816547290 ;
false.

?- g([1,2,3,4,5,6,7,8],0,0,O).
O = 38165472 ;
false.

?- g([1,2,3,4,5,6,7],0,0,O).
false.

?- g([1,2,3,4,5,6],0,0,O).
O = 123654 ;
O = 321654 ;
false.

?- g([2,2,3,3,5,6,7,8,9],0,0,O).
O = 363258729 ;
O = 363258729 ;
O = 363258729 ;
O = 363258729 ;
O = 723258963 ;
O = 723258963 ;
O = 723258963 ;
O = 723258963 ;
false.

```
> 1 votes

# Answer
# Python 2 – 114

Not even the shortest Python solution, but I am sharing it anyway:

```
e=""
f=lambda s,n:[[n,e.join(f(s.replace(j,e),n+j)for j in s)][s>e],e][n>e>0<int(n)%len(n)]
print f("123456789",e)

```
> 1 votes

# Answer
# Bash+coreutils, 159 bytes

```
l=`echo {1..8}`
for d in {2..8};{
l=$(printf "a=%s;if(!a%%$d)a\n" $(eval echo {${l// /,}}{1..8}|tr \  '
'|grep -Pv '(\d).*\1')|bc|paste -d\  -s -)
}
echo ${l}9

```

This is kind of long, but I think the algorithm is perhaps one of the fastest, considering this is a (usually slow) shell script that runs in less than 0.1 second.

The algorithm goes something like this:

* Start with the leftmost digit (1-8)
* append the next digit to the right (1-8)
* remove any numbers with repeated digits (`grep`)
* check for divisibility by `$d` (the digit number) using `bc`, with an expression generated by `printf`
* Repeat the above until an 8 digit number is obtained

Note we take a couple of shortcuts, but I think these are mathematically sound:

* The leftmost digit must be divisible by 1, which is all digits, so we don't explicitly check for the first set of leftmost digits
* The rightmost digit must be 9 (actually I'm not sure if this is a valid assumption - I'll have to think about it a bit)
> 1 votes

# Answer
# C++, 187

I just had to try this in C++. Obviously, it's not going to be the shortest solution but here it is:

```
#include <algorithm>
using namespace std;bool c(int n,int d=9){return d<2||n%d==0&c(n/10,d-1);}int main(){for(char n[]="123456789";next_permutation(n,n+9);)if(c(atoi(n)))return atoi(n);}

```

returns the number instead of printing it to save some characters (damn include). Under POSIX-systems this will of course be converted to an 8-bit unsigned and thus not correct - but the program will calculate a correct number.

Ungolfed (requires C++11):

```
#include <iostream>
#include <algorithm>
using namespace std;

bool check(int n, int digit = 9)
{
  return (n % digit==0) && (digit == 1 || check(n/10,digit-1));
}

int main()
{
  string num {"123456789"};
  while (next_permutation(begin(num), end(num)))
    if (check(stoi(num))){
      cout << num << endl;
      break;
    }
}

```
> 1 votes

# Answer
# T-SQL 2005+ - 203

T-sql is not a very competitive golf language...

```
with A(n)as(select top 10 number from spt_values where'p'=type),R as(select \r,1l union all select r*10+n,l+1from R,A where n not in(select substring(str(r),n,1)from A)and(r*10+n)%l=0)select max(r)FROM R

```

Must be run on the master database. You can replace the first CTE with this to make it database agnostic but then it uses a few more characters (and requires 2008)

```
with A as(select*from(VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9))f(n))

```

Readable formation:

```
 with A(n)as(select top 10 number from spt_values where'p'=type),
    R as(select \ r,1 l
        union all
        select r*10+n,l+1
        from R,A
        where n not in (
            select substring(str(r),n,1)
            from A
        )
        and(r*10+n)%l=0)
select max(r) FROM R

```

Basically we keep adding digits to the back of the `r` number that we haven't seen in the string yet, and making sure that the new string is still modulo 0 of the current level. We initialize R to `\`, This is really the only trick in this code. Which is a crazy way to set it to 0 in `money` datatype. It's I'm guessing a way to let you type `\` instead of currency. `$` also does the same thing in T-SQL, but `$l` would try to interpret a pseudo column that doesn't exist and throw an error. This lets us avoid the worry about using `int` which would cause an overflow normally at the 10th concatenation, forcing us to actually check the level. Edit: Fun fact T-sql even in 2014 doesn't have a built in way to turn a string into a table of values (e.g. no split func), so we actually also get to reuse our `A` table twice to iterate the characters in the stringified R.

T-Sql precedence rules are annoying so we have to use numeric concatenation (\*10+n), rather than string concat.
> 1 votes

# Answer
# PHP, 89 bytes

## random version, 89 bytes:

```
for($n=123456789;$n=str_shuffle($n);$d||die("$n"))for($d=10;--$d&&substr($n,0,$d)%$d<1;);

```

shuffles a string containing the digits, then tests divisibility in a loop.

Run with `-nr`.

---

## brute force loop, 90 bytes, very slow:

```
for(;++$i<1e9;$d||die("$i"))for($d=10;--$d&&max(count_chars($i))<2&substr($i,0,$d)%$d<1;);

```

loops from 100000001, tests divisibility in inner loop, and exits when it finds a solution.

---

## recursive function, 94 bytes, very fast:

```
function f($n="",$e=1){while($d++<9)strpos(_.$n,"$d")|($x=$n.$d)%$e||print$e>8?$x:f($x,$e+1);}

```

appends one digit that´s not yet in the number, if divisibility by length is given, recurse (or print).

This exploits that there is only one solution. without that, `print$e>8?$x:f($x,$e+1)` had to be `print$e>8?"$x\n":f($x,$e+1)` (+3 bytes, print all solutions) or `($e>8?die("$x"):f($x,$e+1))` (+4 bytes, exit at first solution) or the solutions would be printed without a delimiter.

Call with `f();`

--

## TiO

The brute force version has no TiO for obvious reasons, but you can try the other two.

The function call´s runtime is measured inline (somewhere between 2 and 4 milliseconds);
total runtime is measured by the website (usually between 50 and 500 ms).
> 1 votes

# Answer
# Husk, 15 bytes

```
dḟöΛIz¦ḣ9mdḣPḣ9

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 9 bytes

```
9LœJʒηāÖP

```

Try it online!

The same as my answer on the newer challenge, but with fixed input of `9`. Hardcoding is shorter:

```
•N4₃s

```

Try it online!
> 1 votes

---
Tags: code-golf
---


title: Generating BF-code with single purpose

text:
# Question
Title: Generating BF-code with single purpose
I'd like to see you create code (in any programming language) that output working BF (Brain\***k) code. Your program have a single character input on stdin. The input should be one digit ("0", "1", "2", "3", "4", "5", "6", "7", "8" or "9").

Your code should output BF-code that when interpreted with a normal BF-interpreter outputs a 5\*5 ascii version of the digit. The generated BF-code should not accept any input. The resulting output from the generated BF-code should be exactly this:

Input: '0'

Output BF-code that when interpreted generates the following output:

```
.---.
|  /|
| / |
|/  |
'---'

```

Input: '1'

Output BF-code that when interpreted generates the following output:

```
 .
/|
 |
 |
 '

```

Input: '2'

Output BF-code that when interpreted generates the following output:

```
.---.
    |
.---'
|
'---'

```

Input: '3'

Output BF-code that when interpreted generates the following output:

```
.---.
    |
 ---|
    |
'---'

```

Input: '4'

Output BF-code that when interpreted generates the following output:

```
.   .
|   |
'---|
    |
    '

```

Input: '5'

Output BF-code that when interpreted generates the following output:

```
.---
|
'---.
    |
'---'

```

Input: '6'

Output BF-code that when interpreted generates the following output:

```
.---
|
|---.
|   |
'---'

```

Input: '7'

Output BF-code that when interpreted generates the following output:

```
----.
   /
  /
 /
'

```

Input: '8'

Output BF-code that when interpreted generates the following output:

```
.---.
|   |
|---|
|   |
'---'

```

Input: '9'

Output BF-code that when interpreted generates the following output:

```
.---.
|   |
'---|
    |
'---'

```

The output from your code must be 10 different BF sourcecodes, one for each digit you input. Your program should not output all 10 BF in one run, it must ask for a digit and output BF code for that and only that ascii representation.

The BF-code requirements:

* cell size: 8bit unsigned.
* Overflow is undefined.
* Array size: Max 30000 bytes (not circled)
* It can contain other characters than \[\],.+-\<\>, but they should all be ignored. It is only - the standard BF code without any extensions that counts.
* The EOF return 0
* Linefeed is chr(10)

The winning answer will be the one that scores that lowest code using this formula:

```
your code in number of bytes * 5 + sum of the 10 generated BF codes

```

So keep in mind that you need to generate GOLF'd BF-code to score better.

**Edit/Add (2011-08-25): You may omit or supply trailing spaces, as long as the digits displays the ASCII representation on a 80 column output, so the limit is 80 chars rows. Honor to the answers to generates exactly 5\*5 output for all digits.**

# Answer
## JavaScript (JS 455 * 5 = 2275, BF = 3505, score = 5780)

The generated code builds a character table as it produces its ASCII art output to save thousands of plus/minus signs overall. Output is placed into the text box in a prompt window so that it can be copied and pasted into a BF interpreter. The consecutive spaces in this program must remain verbatim for it to work correctly; hopefully, posting the code here will work correctly. (Note: The JS code requires ES5 or JavaScript 1.6 support to work properly.)

```
M=prompt;S="3cb80kh77j31f4031m10g251p64d1064a20ionle3292032510".substr(5*M(A=[]),5).replace(/./g,function(a){return"'---'0    |0|   |0.---.0|0'---|0.---0 |0|/  |0|---|0|---.0| / |0|  /|0'---.0'0.---'0.   .0/|0----.0 '0 .0 /0 ---|0  /0   /0    '".split(i=j=0)[parseInt(a,26)]+"\n"});for(O="";i<S.length;O+=".")D=A.indexOf(C=S.charCodeAt(i)),i++&&(d=-j+(j=D<0?A.length:D),O+=Array(d>0?1+d:1-d).join(d>0?">":"<")),D<0&&(O+=Array((A[j]=C)+1).join("+"));M(0,O)

```
> 5 votes

# Answer
## BrainFuck (Score : 13073, BF : ~~2299~~ 2286, BF (generated) : 1643)

```
,>++++++++[<------>->>>+++++++++++>+++++++++++>+++++>++++++++>++++++++>++++++>++++++<<<<<<<<<]
>>>+++>+++++>+++>---->-->--->--<<<<........<<.>>>>>.<.<<.>>.<<....>>.<<......>>.<<......>>.<<.
..............>>.<<......>>.<<.....>.......<<.>>>.<<..>>..>..<.>...<.<<....>>.>.<.>.<<<<<<<<+<
[>-]>[>>>>>>....>>>.<<.>>...<<<.>>>.<<<..>>>.<<....>>.<<<...>>>..<<....>>.<<<.>>>.<<<....>>>.<
<....>>.<<<...>>>.<<....>>.<<<....>>>.<<...>>.<<<....>>>.<<....>>.<<.>>.<<<....>>>..<<...>>.<<
<....>>>.<<......>>.<<<...>>>...<<...>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>>>>.....>>>
.<<.>>.<<<..>>>.<<.....>>.<<<.>>>.<<<....>>>.<<.>>.<<...>>.<<<....>>>.<<.>>.<<...>>.<<<....>>>
.<<.>>.<<.....>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>>>>....>>>.<<.>>...<<<.>>>.<<<..>>
>.<<.>>....<<...>>.<<<....>>>.<<..>>.<<.>>...<<...>>.<<<......>>>.<<....>>.<<<....>>>.<<......
>>.<<<...>>>...<<...>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>>>>....>>>.<<.>>...<<<.>>>.<
<<..>>>.<<.>>....<<...>>.<<<....>>>.<<.>>.<<..>>...<<.>>.<<<....>>>.<<.>>....<<...>>.<<<....>>
>.<<......>>.<<<...>>>...<<...>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>>>>....>>>.<<<.>>>
...<<.>>.<<<..>>>.<<....>>.<<<...>>>...<<...>>.<<<....>>>.<<......>>.<<<...>>>...<<.>>.<<<....
>>>.<<.>>....<<...>>.<<<....>>>.<<.>>....<<.....>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>
>>>....>>>.<<.>>...<<<...>>>.<<....>>.<<<....>>>.<<......>>.<<<...>>>...<<<.>>>.<<<..>>>.<<.>>
....<<...>>.<<<....>>>.<<......>>.<<<...>>>...<<...>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[
>>>>>>....>>>.<<.>>...<<<...>>>.<<....>>.<<<....>>>.<<....>>.<<<.>>>...<<<.>>>.<<<..>>>.<<....
>>.<<<...>>>...<<...>>.<<<....>>>.<<......>>.<<<...>>>...<<...>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>
[-]<<[>-]>[>>>>>>...>>>....<<<.>>>.<<<..>>>.<<.>>...<<....>>.<<<.....>>>.<<.>>..<<....>>.<<<..
...>>>.<<.>>.<<....>>.<<<.....>>>.<<......>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>>>>...
.>>>.<<.>>...<<<.>>>.<<<..>>>.<<....>>.<<<...>>>...<<...>>.<<<....>>>.<<....>>.<<<.>>>...<<.>>
.<<<....>>>.<<....>>.<<<...>>>...<<...>>.<<<....>>>.<<......>>.<<<...>>>...<<...>>.<<<<<<<<<->
>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>>>>....>>>.<<.>>...<<<.>>>.<<<..>>>.<<....>>.<<<...>>>...<<...
>>.<<<....>>>.<<......>>.<<<...>>>...<<.>>.<<<....>>>.<<.>>....<<...>>.<<<....>>>.<<......>>.<
<<...>>>...<<...>>.>]]]]]]]]]]

```

(FYI : over 90% of above code is generated by JS code to generate part of BrainFuck code generating part of BrainFuck code generating ASCII art.)

This program gets one ASCII character ('0'~'9') and print the BF code generating the ASCII art.

Generated BF codes :

```
#0
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<.<<.>>>>.<<<..>>>>.<.<<<<.>>>>.<<<.>>>>.<<<<.>>>.<<<<.>>>>.>.<<<<..>>>.<<<<.>>>>>>.<<<...>>>.
#1
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<<.>.<<.>>>>>.<.<<<<.>.>>>.<<<<.>.>>>.<<<<.>.>>>>>.
#2
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<.<<.>....>>>.<<<<.>>.>...>>>.<<<<<<.>>>>.<<<<.>>>>>>.<<<...>>>.
#3
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<.<<.>....>>>.<<<<.>.>>...>.<<<<.>....>>>.<<<<.>>>>>>.<<<...>>>.
#4
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.<...>.<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>.<<<<.>....>>>.<<<<.>....>>>>>.
#5
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<<<.>>>>.<<<<.>>>>>>.<<<...<.<<.>....>>>.<<<<.>>>>>>.<<<...>>>.
#6
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<<<.>>>>.<<<<.>>>>.<...<.<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>>>.
#7
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<....<.<<.>...>>>>.<<<<<.>..>>>>.<<<<<.>.>>>>.<<<<<.>>>>>>.
#8
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<.<<.>>>>.<<<...>>>.<<<<.>>>>.<...>.<<<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>>>.
#9
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<.<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>.<<<<.>....>>>.<<<<.>>>>>>.<<<...>>>.

```

Example output for 7 :

```
----.
   /
  /
 /
'

```
> 24 votes

# Answer
# brainfuck, (BF 1534 * 5 = 7670, Generated BF = 1293, score = 8963)

```
+[-[>+<<]>-]>-.>>--[<+>++++++]<.>++++++>-[<+>---]<.<++..<.>--.>.<<--.>>++.<<++.>++.>.<<..>--..
........<.>..<.>++..>--.<<--.>--.<++.>......>++.<++...<.>..>--.<<--.>--.<++.>++..>++.<<.>--...
.>--.<<--.>........<++.>++.>++.<<--...>--.<<<<,+++>-[<->-----]+<[>-]>[->>>+++.-.+...---.+++.<.
>.<++..>.<.>..<--..>---.+++.<++.>.<--..>.<++..>.<.>.<--..>.<++..>.<--.>.<..>.<++..>.<--.>.<++.
.>..<--.>.<..>.<.>.<++..>-..+...<--..>.<<]<+<-[>-]>[->>++..>+++.<--..>.<.>.<++.>---.+++.<.>.<-
-..>.<++...>.<--.>.<..>.<++...>.<--.>.<..>.<++...>.<--....>.<<]<+<-[>-]>[->>>+++.-.+...---.+++
.<.>.<++...>....<--.>.<..>.<++.>.-.+...<--..>.<++.>.<..>.<--..>.<.>.<++..>...<--..>.<<]<+<-[>-
]>[->>>+++.-.+...---.+++.<.>.<++...>....<--.>.<..>.<++...>.<--..>-.+...<++.>.<--..>.<++...>...
.<--.>.<..>.<.>.<++..>...<--..>.<<]<+<-[>-]>[->>>+++.<++..>...<--..>.<.>.<++..>.<.>...<--.>.<.
.>.<.>.<++..>-.+...<.>.<--..>.<++...>....<--.>.<..>.<++...>....<--....>.<<]<+<-[>-]>[->>>+++.-
.+...<.>.<++..>.<--..>.<.>.<++..>...---.+++.<--.>.<++...>....<--.>.<..>.<.>.<++..>-.+...<--..>
.<<]<+<-[>-]>[->>>+++.-.+...<.>.<++..>.<--..>.<++..>.<--.>...---.+++.<.>.<++..>.<.>...<--.>.<.
.>.<.>.<++..>-.+...<--..>.<<]<+<-[>-]>[->>>++.+....---.+++.<.>.<++...>...<--..>---.+++.<.>.<++
...>..<--..>.<.>.<++...>.<--..>.<.>.<.>.<<]<+<-[>-]>[->>>+++.-.+...---.+++.<.>.<++..>.<.>...<-
-.>.<..>.<++..>.<--.>-.+...<++.>.<--..>.<++..>.<.>...<--.>.<..>.<.>.<++..>...<--..>.<<]<+<-[>-
]>[>>>+++.-.+...---.+++.<.>.<++..>.<.>...<--.>.<..>.<.>.<++..>-.+...<.>.<--..>.<++...>....<--.
>.<..>.<.>.<++..>...<--..>.<<]

```

Code here includes newlines for readability.

Try it online!
> 4 votes

# Answer
# Python 3, (Python 403 * 5 = 2015, BF = 1293, score = 3308)

```
def x(i,b=5):
 a,i='',int(i,36)
 while i:a+='<.>+-[]'[i%b];i//=b
 return a
print(x("7vphe27p2e4voq0o43gf5n8vsm4zd01qsofpvobsaq",7)+x("20lzrlf5b9k8qf1kctot9x3et4id5d m1z11k8bye0q57c8owb 1houe4amyy3wu36tk00qz2 8o5y0gy19cx8cjsnjazb08seuk 5ypddsh5laklx2qj6sb2lxpu8cd aqma6z756nnzjalhd4fy5 aqma6z757wy8nhuw7uobp 4lbo9eqzud1ykb67x5f chin248p22jlefn4j0ottq13q chin248our8z29faeze411sy6".split()[int(input())]))

```

Try it online!
> 4 votes

# Answer
## GTB (GTB, 888 * 5 = 4440, BF = 1643, score = 6083)

Yes, this does run on your calculator!

```
~"++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<"→_`A@A=0~"<.>...<.<<.>>>>.<<<..>>>>.<.<<<<.>>>>.<<<.>>>>.<<<<.>>>.<<<<.>>>>.>.<<<<..>>>.<<<<.>>>>>>.<<<...>>>.@A=1~"<<.>.<<.>>>>>.<.<<<<.>.>>>.<<<<.>.>>>.<<<<.>.>>>>>.@A=2~"<.>...<.<<.>....>>>.<<<<.>>.>...>>>.<<<<<<.>>>>.<<<<.>>>>>>.<<<...>>>.@A=3~"<.>...<.<<.>....>>>.<<<<.>.>>...>.<<<<.>....>>>.<<<<.>>>>>>.<<<...>>>.@A=4~"<.<...>.<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>.<<<<.>....>>>.<<<<.>....>>>>>.@A=5"<.>...<<<.>>>>.<<<<.>>>>>>.<<<...<.<<.>....>>>.<<<<.>>>>>>.<<<...>>>.@A=6~"<.>...<<<.>>>>.<<<<.>>>>.<...<.<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>>>.@A=7~"....<.<<.>...>>>>.<<<<<.>..>>>>.<<<<<.>.>>>>.<<<<<.>>>>>>.@A=8~"<.>...<.<<.>>>>.<<<...>>>.<<<<.>>>>.<...>.<<<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>>>.@A=9~"<.>...<.<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>.<<<<.>....>>>.<<<<.>>>>>>.<<<...>>>.

```
> 1 votes

# Answer
## Spoon (Spoon, 7430 * 5 = 37150, BF = 1643, score = 38793)

```
[encoded data, 7430 characters]

```
> 1 votes

# Answer
# Jelly, score = 5×160 + 1305 = 2105

```
ị“¢N=⁵ḌƤṢ§UḌ“uçCçṗ³;nƝ“nƁÇ½)|⁸jɠ9Ṁ“¡h6ịḃ⁸ƊFdṚ⁻ŀȥ“¤aÄ³ṇḃṚĠ;“&⁻3Ṃb½Ḟ\Ẇ“ÑṭȤv.Ṡ\ð⁸“¿bSumƒ¬ẹṡḢ€“¡][ḶṠ.\Ä£ḣ⁼“nƁµ[ḷSLBḃ$ŀ’ṃ“.<>”“ṁƙµ²ƭ^%n5ḅEœçs_ĊṚç⁽ƁhFġ⁷Ƈɱ’ṃ“+><-][”¤;

```

Try it online!

The digit is to be put in a command-line argument.

## Explanation

```
ị“...’ṃ“.<>”“...’ṃ“+><-][”¤;   Main monadic link
ị                              Index in
 “...’                          a list of 10 integers compressed in base 250
      ṃ                        Base decompression using characters
       “.<>”                    [base 3] 1->'.', 2->'<', 0->'>'
                           ;   Prepend
                          ¤    (
            “...’               an integer compressed in base 250
                 ṃ              base decompressed using characters
                  “+><-][”      [base 6] 1->'+', ..., 0->'['
                          ¤    )

```

## Produced brainfuck programs

```
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...>.<<<.<.<..<.>>.>.<.<.<.>.>.>.<.<<.>..>.>.>.>...<.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+<<<<<.>>>>>.<<<.<<<.>>.>.<<.>.>.<<.>.>.<<.>>>.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...>.<<<.<<....>.>.>>>.<...<.<.<.>.>.>...<.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...>.<<<.<<....>.>.<<.>>>>...<<<.>.<<....>.>.>.>...<.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<<<<<...>>>>>.<<<.<.<...>.>.>.>...<<<.>.<<....>.>.<<....>>>.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...<<.<.>.>.>...>.<<<.<<....>.>.>.>...<.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...<<.<.>.<.>>>...>.<<<.<.<...>.>.>.>...<.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+<....>.<<<.<<...<.>>>.<<..<.>>>.<<.<.>>>.>.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...>.<<<.<.<...>.>.<.>>>...<<<.>.<.<...>.>.>.>...<.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...>.<<<.<.<...>.>.>.>...<<<.>.<<....>.>.>.>...<.

```

## Explanation of brainfuck programs

The common part adds the number 3, then multiplies by 5 to get 15, then multiplies by some constants and adds some constants to get all the characters used in the ASCII art. (I used a Python program to determine 15 as the optimal number.)

The differing parts simply walk around the characters and print them. The order of the characters was chosen to make the walk as short as possible.
> 1 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity, brainfuck, metagolf
---


title: Integer-Digits of the Arithmetic-Tables

text:
# Question
Title: Integer-Digits of the Arithmetic-Tables
### Challenge:

Output the 'integer-digits' of one of the following six arithmetic-tables based on the input:
\- addition (`+`);
\- subtraction (`-`);
\- multiplication (`*`);
\- division (`/`);
\- exponentiation (`^`);
\- modulo operation (`%`).

### Rules:

* What do I define as 'integer-digits': Every result of the arithmetic operand which is exactly one of the following: `0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`. This means you *exclude* every result of `10` or higher, every result of `-1` or lower, and every non-integer result.
* ~~How do we calculate the arithmetic results: By using the top digit first, and then use the operand with the left digit.~~ You are allowed to do this vice-versa (i.e. `y/x` instead of `x/y`), as long as you're consistent for all six of the outputs! (So you aren't allowed to use `y-x` and `x/y` in the same answer.)
* We won't output anything for divide by 0 test-cases (for the division and modulo operation tables)
* We won't output anything for the edge-case `0^0`.

### Output:

So output the following (table format is somewhat flexible (see below): so the lines are optional and mainly added for readability of the test cases):

Addition:

```
+ | 0 1 2 3 4 5 6 7 8 9
-----------------------
0 | 0 1 2 3 4 5 6 7 8 9
1 | 1 2 3 4 5 6 7 8 9
2 | 2 3 4 5 6 7 8 9
3 | 3 4 5 6 7 8 9
4 | 4 5 6 7 8 9
5 | 5 6 7 8 9
6 | 6 7 8 9
7 | 7 8 9
8 | 8 9
9 | 9

```

Subtraction:

```
- | 0 1 2 3 4 5 6 7 8 9
-----------------------
0 | 0 1 2 3 4 5 6 7 8 9
1 |   0 1 2 3 4 5 6 7 8
2 |     0 1 2 3 4 5 6 7
3 |       0 1 2 3 4 5 6
4 |         0 1 2 3 4 5
5 |           0 1 2 3 4
6 |             0 1 2 3
7 |               0 1 2
8 |                 0 1
9 |                   0

```

Multiplication:

```
* | 0 1 2 3 4 5 6 7 8 9
-----------------------
0 | 0 0 0 0 0 0 0 0 0 0
1 | 0 1 2 3 4 5 6 7 8 9
2 | 0 2 4 6 8
3 | 0 3 6 9
4 | 0 4 8
5 | 0 5
6 | 0 6
7 | 0 7
8 | 0 8
9 | 0 9

```

Division:

```
/ | 0 1 2 3 4 5 6 7 8 9
-----------------------
0 |
1 | 0 1 2 3 4 5 6 7 8 9
2 | 0   1   2   3   4
3 | 0     1     2     3
4 | 0       1       2
5 | 0         1
6 | 0           1
7 | 0             1
8 | 0               1
9 | 0                 1

```

Exponentiation:

```
^ | 0 1 2 3 4 5 6 7 8 9
-----------------------
0 |   1 1 1 1 1 1 1 1 1
1 | 0 1 2 3 4 5 6 7 8 9
2 | 0 1 4 9
3 | 0 1 8
4 | 0 1
5 | 0 1
6 | 0 1
7 | 0 1
8 | 0 1
9 | 0 1

```

Modulo:

```
% | 0 1 2 3 4 5 6 7 8 9
-----------------------
0 |
1 | 0 0 0 0 0 0 0 0 0 0
2 | 0 1 0 1 0 1 0 1 0 1
3 | 0 1 2 0 1 2 0 1 2 0
4 | 0 1 2 3 0 1 2 3 0 1
5 | 0 1 2 3 4 0 1 2 3 4
6 | 0 1 2 3 4 5 0 1 2 3
7 | 0 1 2 3 4 5 6 0 1 2
8 | 0 1 2 3 4 5 6 7 0 1
9 | 0 1 2 3 4 5 6 7 8 0

```

### Challenge rules:

* Trailing new-lines and trailing spaces are optional
* The horizontal and vertical lines in the test cases are optional. I only added them for better readability.
* The spaces between each result are NOT optional.
* The symbol for the arithmetic may be different, as long as it's clear which one it is. I.e. `×` or `·` instead of `*` for multiplication; `÷` instead of `/` for division; etc.
And as long as it's a *single* character, so sorry Python's `**`.
* The input format is flexible. You can choose an index from 0-5 or 1-6 for the corresponding six tables; you could input the operand-symbol; etc. (Unlike what you display in the result, you are allowed to input complete strings, or `**` in Python's case.)
Just make sure to state which input-format you use in your answer!

### General rules:

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

*† Example of valid output without horizontal and vertical lines, `÷` as symbol, and using `y/x` instead of `x/y`:*

```
÷ 0 1 2 3 4 5 6 7 8 9
0   0 0 0 0 0 0 0 0 0
1   1
2   2 1
3   3   1
4   4 2   1
5   5       1
6   6 3 2     1
7   7           1
8   8 4   2       1
9   9   3           1

```

# Answer
# Japt, 45 bytes

*Collaborated with @ETHproductions*

```
AÆAÇU¥'p«Z«XªOvZ+U+X)+P r"..+"SÃuXÃuAo uU)m¸·

```

Run it online!

Takes input as:

`"+"` for addition

`"-"` for subtraction

`"*"` for multiplication

`"/"` for division

`"p"` for exponentiation

`"%"` for modulo

### Explanation (With expanded shortcuts):

```
AÆ  AÇ  U¥ 'p«  Z«  Xª OvZ+U+X)+P r"..+"SÃ uXÃ uAo uU)m¸  ·
AoX{AoZ{U=='p&&!Z&&!X||OvZ+U+X)+P r"..+"S} uX} uAo uU)mqS qR

A                                                             // By default, 10 is assigned to A
 o                                                            // Create a range from [0...9]
  X{                                         }                // Iterate through the range, X becomes the iterative item
    Ao                                                        //   Create another range [0...9]
      Z{                                 }                    //   Iterate through the range, Z becomes the iterative item
                                                              //     Take:
        U=='p                                                 //       U (input) =="p"
             &&!Z                                             //       && Z != 0
                 &&!X                                         //       && X != 0
                     ||                                       //     If any of these turned out false, instead take
                       Ov                                     //       Japt Eval:
                         Z+U+X                                //         Z{Input}X
                              )+P                             //     Whichever it was, convert to a string
                                  r"..+"S                     //     Replace all strings of length 2 or more with " "
                                                              //     (this makes sure the result !== "false" and has length 1)
                                           uX                 //   Insert X (the row number) into the front of the row
                                               u              // Insert at the beginning the first row:
                                                Ao            //   [0...9]
                                                   uU)        //   with the input inserted at the beginning
                                                      mqS     // Join each item in the final array with " "
                                                          qR  // Join the final array with "\n"

```
> 7 votes

# Answer
## JavaScript (ES7), 128 bytes

```
f=
c=>[...c+`0123456789`].map((r,_,a)=>a.map(l=>l==c?r:r==c?l:/^\d$/.test(l=c<`^`?eval(l+c+r):l|c?l**r:l/r)?l:` `).join` `).join`
`
```

```
<select onchange=o.textContent=f(this.value)><option>><option>+<option>-<option>*<option>/<option>%<option>^<option>&<option>,<option>.</select><pre id=o>
```

Special-casing `0^0` cost me 8 bytes.
> 8 votes

# Answer
# Operation Flashpoint scripting language, ~~343~~ ~~333~~ ~~303~~ 301 bytes

```
f={o=_this;s=o+" 0 1 2 3 4 5 6 7 8 9\n";i=0;while{i<10}do{j=0;s=s+format["%1",i];if(i<1&&(o=="/"||o=="%"||o=="^"))then{if(o=="^")then{if(j<1)then{s=s+"  ";j=1}}else{s=s+"\n1";i=1}};while{j<10}do{r=call format["%1%2%3",j,o,i];if(r>9||r<0||r%1>0)then{r=" "};s=s+format[" %1",r];j=j+1};s=s+"\n";i=i+1};s}

```

**Call with:**

```
hint ("+" call f)

```

**Ungolfed:**

```
f=
{
    o=_this;
    s=o+" 0 1 2 3 4 5 6 7 8 9\n";
    i=0;
    while{i<10}do
    {
        j=0;
        s=s+format["%1",i];
        if(i<1&&(o=="/"||o=="%"||o=="^"))then
        {
            if(o=="^")then{if(j<1)then{s=s+"  ";j=1}}
            else{s=s+"\n1";i=1}
        };
        while{j<10}do
        {
            r=call format["%1%2%3",j,o,i];
            if(r>9||r<0||r%1>0)then{r=" "};
            s=s+format[" %1",r];
            j=j+1
        };
        s=s+"\n";
        i=i+1
    };
    s
}

```

**Output:**

operator +

operator -

operator *

operator /

operator ^

operator %
> 5 votes

# Answer
# Python 2, ~~240~~ ~~231~~ ~~226~~ ~~224~~ ~~203~~ ~~202~~ ~~200~~ 197 bytes

```
a=i=input()
R=range(10)
for z in R:a+=' '+`z`
print a
for x in R:
 try:
	d=`x`
	for b in R:c=eval("b%s(x*1.)"%('**',i)[i<'^']);d+=' '+(' ',`int(c)`)[(i<'^'or x+b>0)and c in R]
 except:pass
 print d

```

Try it online!

Takes input as one of "+", "-", "\*", "/", "^" or "%".

**Edits**

~~-9~~ -16 with thanks to @FelipeNardiBatista for some great hints

Down to 221 with more help from @FelipeNardiBatista and then down to 203 by losing `and E(c)==int(E(c))`. If we are checking if `E(c)` is in `range(10)` it will always be an integer if it is there. No need for the duplicate check.

This **has** to go below 200 without switching to Python 3 and declaring `P=print`. Any ideas? I am always happy to learn.

Yesss! I knew it could be done. 197. Time for bed now. I have spent enough time on this one. Thanks for the interesting challenge @KevinCruijssen.
> 5 votes

# Answer
# Java 10, ~~312~~ ~~305~~ ~~297~~ 238 bytes

```
o->{var r="+-*/^%".charAt(o)+" 0 1 2 3 4 5 6 7 8 9\n";for(int i=-1;++i<10;r+="\n"){r+=i+" ";for(double j=-1d,t;++j<10;r+=t%1!=0|t<0|t>9?"  ":((int)t)+" ")t=o<1?j+i:o<2?j-i:o<3?j*i:o<4&i>0?j/i:o<5&j!=-i?Math.pow(j,i):i>0?j%i:-1;}return r;}

```

Uses no horizontal/vertical lines, and the characters are as displayed in the challenge-examples (`+-*/^%`).
Uses an index of `0-5` for the six mathematical operands as input.

-7 bytes thanks to *@Frozn*.
-8 bytes thanks to *@ceilingcat*.

**Explanation:**

```
o->{                       // Method with integer parameter and String return-type
  var r="+-*/^%".charAt(o) //  Get the current mathematical operand character based
                           //  on the input index
        +" 0 1 2 3 4 5 6 7 8 9\n";
                           //  Append the column header and a new-line
  for(int i=-1;++i<10;     //  Loop `i` in the range (-1,10):
      r+="\n"){            //    After every iteration: append a newline to the result
    r+=i+" ";              //   Append the left-side row-nr
    for(double j=-1d,t;++j<10;
                           //   Inner loop over the cells of the current row
        r+=                //     After every iteration: append the result String with:
           t%1!=0          //      If `t` has decimal values
           |t<0            //      Or `t` is below 0
           |t>9?           //      Or `t` is above 9:
             "  "          //       Append an empty cell
           :               //      Else:
             ((int)t)+" ") //       Append `t` as integer in the current cell
      t=                   //    Set `t` to:
        o<1?               //     If the given operand is 0 ("+"):
          j+i              //      Add `j` and `i` together
        :o<2?              //     Else-if the operand is 1 ("-"):
          j-i              //      Subtract `i` from `j`
        :o<3?              //     Else-if the operand is 2 ("*"):
          j*i              //      Multiply `j` by `i`
        :o<4               //     Else-if the operand is 3 ("/")
         &i>0?             //     And `i` is larger than 0:
          j/i              //      Divide `j` by `i`
        :o<5               //     Else-if the operand is 4 ("^")
         &j!=-i?           //     And `j` is not `-i`:
          Math.pow(j,i)    //      Take `j` to the power `i`
        :                  //     Else (the operand is 5 ("%")):
         i>0?              //      If `i` is larger than 0:
           j%i             //       Take `j` modulo-`i`
         :                 //      Else:
           -1;}            //       Set `t` to -1 instead
  return r;}               //  After the loops, return the result-String

```
> 4 votes

# Answer
# Python 3, ~~343~~ ~~335~~ ~~363~~ 362 bytes

The saddest part about this is that a Java answer is beating me... I'll golf this more in the morning.

```
o=input()
r=range(10)
g=[['']*10 for i in r]
for x in r:
 for y in r:exec('if"/"!=o and(o!="%"or x)and(o!="**"or x or y):k=str(y'+o+'x);g[x][y]=k')
if'/'==o:
 for x in r:
  for y in r:
   if x and y%x<1:g[x][y]=str(round(y/x))
if'**'==o:o='^'
print('\n'.join([' '.join([o]+list(map(str,r)))]+[' '.join([str(q)]+[' 'if len(x)!=1else x for x in g[q]])for q in r]))

```

ReplIT

-8 bytes by switching to list comprehension rather than a double loop
+28 bytes to avoid edge case `0 ^ 0`. -.-
-1 byte by changing `==0` to `<1` thanks to @StewieGriffin
> 4 votes

# Answer
# Mathematica, 150 bytes

```
r=0~Range~9;p=Prepend;±i_:=Grid@p[p[If[0<=#<=9,#]/._@__->""&/@<|Thread[Characters@"+-*/^%"->{Plus,#-#2&,1##&,#/#2&,Power,Mod}]|>[i][r,#],#]&/@r,r~p~i]

```

Defines a unary function `±` taking one of the characters `+-*/^%` as its input `i` (so for example, `±"^"`), and returning a `Grid` object that looks exactly like the last output in the OP.

`<|Thread[Characters@"+-*/^%"->{Plus,#-#2&,1##&,#/#2&,Power,Mod}]|>` associates, to each possible input character, the corresponding (listable) binary function (where `#-#2&,1##&,#/#2&` are golfed versions of `Subtract,Times,Divide`); therefore `<|...|>[i][r,#]` calculates the binary operation with all possible first arguments and `#` as the second argument. `If[0<=#<=9,#]/._@__->""&` converts each result to a `Null` or `""` if it's not a single-digit result (`/._@__->""` is necessary because some results like `1/0` can't be processed by the inequalities `0<=#<=9`). Finally, we prepend the various headers and footers and display the answer.
> 4 votes

# Answer
# Haskell, ~~230~~ ~~199~~ 182 + ~~53~~ ~~47~~ 46 + 1 byte of separator = ~~284~~ ~~247~~ ~~232~~ 229 bytes

```
f=head.show
g=[0..9]
h=(:" ")
y(%)s=unlines$(s:map f g>>=h):[f y:[last$' ':[f(x%y)|x%y`elem`g]|x<-g]>>=h|y<-g]
0?0=10;a?b=a^b
a!0=10;a!b|(e,0)<-a`divMod`b=e|1>0=10
a&0=10;a&b=mod a b

```

Function is `(zipWith y[(+),(-),(*),(!),(?),(&)]"+-*/^%"!!)`, which alone takes up 53 bytes, where 0 is addition, 1 is subtraction, 2 is multiplication, 3 is division, 4 is exponentiation, and 5 is modulo.

Try it online!

## Explanation

Coming later (possibly) . . . . For now some little tidbits: ? is the exponentiation operator, ! is the division operator, and & is the mod operator.

EDIT: Part of the bulk might be because most (?) of the other answers use eval, which Haskell doesn't have without a lengthy import.

EDIT2: Thanks Ørjan Johansen for -31 bytes (Wow!) off the code and -6 bytes off the function! Also changed some of the 11s to 10s for consistency purposes. Try the updated version online!

EDIT3: Same person, seventeen more bytes! Try the updated, updated version online!
> 3 votes

# Answer
# Python 2, 197 bytes

```
p=input()
r=range(10)
s=' '
print p+s+s.join(map(str,r))
for i in r:print str(i)+s+s.join(eval(("s","str(j"+p+"i)")[i and(j%i==0 and'/'==p or'%'==p)or p in'**+-'and eval("j"+p+"i")in r])for j in r)

```

Try it online!

**Input: Python 2**

`'+'` Addition

`'-'` Sbtraction

`'*'` Multiplication

`'/'` Division

`'**'` Exponentiation

`'%'` Modulo

# Python 3, 200 bytes

```
p=input()
r=range(10)
s=' '
print(p+s+s.join(map(str,r)))
for i in r:print(str(i)+s+s.join(eval(("s","str(j"+p+"i)")[i and(j%i==0 and'/'in p or'%'==p)or p in'**+-'and eval("j"+p+"i")in r])for j in r))

```

Try it online!

**Input: Python 3**

`+` Addition

`-` Sbtraction

`*` Multiplication

`//` Division

`**` Exponentiation

`%` Modulo

# Explanation

storing `range(10)` to a variable `r`, we can get the first line of output of the format

```
operator 0 1 2 3 4 5 6 7 8 9

```

by mapping every int in `r` to string and joining the string list`['0','1','2','3','4','5','6','7','8','9']` with space `s` with `p` operator

```
p+s+s.join(map(str,r)

```

With that, for every `i` in `r`(range), for every `j` evaluate `i` and `j` with your operator

```
eval("j"+p+"i")

```

here, an exception might be thrown if unhandled - division or modulus by 0. To handle this case(`i and(j%i==0 and'/'==p or'%'==p)`) and the output format by described in the problem statement(the result for each evaluation shouldn't be a negative number nor a number greater than 10 - `eval("j"+p+"i")in r`),

```
i and(j%i==0 and'/'==p or'%'==p)or p in'**+-'and eval("j"+p+"i")in r

```

Thus printing the arithmetic-table!

Happy Coding!
> 2 votes

# Answer
# APL (Dyalog), ~~68~~ 76 bytes

Requires `⎕IO←0` which is default on many systems. Prompts for input and expects a single character representing the operand.

```
t←'|'=w←⎕
(w,n),n⍪⍉⍣t∘.{(⍺w⍵≡0'*'0)∨(t∧⍵≡0)∨⍺w≡0'÷':⍬
n∊⍨r←⍵(⍎w)⍺:r
⍬}⍨n←⍳10

```

Try it online!

Much of the code is to circumvent that APL's results for `÷0` and `0*0` and to counteract that APL's modulo (`|`) has its arguments reversed compared to most other languages. Would have been only **41 bytes** otherwise:

```
w←⎕
(w,n),n⍪∘.{0::⍬
÷n∊⍨r←⍵(⍎w)⍺:r}⍨n←⍳10

```

Try it online!
> 2 votes

# Answer
# , ~~194~~ 177 bytes

*-17 bytes switching to manipulating matrix output*

```
function(o){s=0:9
y=sapply(s,function(x)Reduce(o,x,init=s))
dimnames(y)=list(s,rep('',10))
y[!y%in%s|!is.finite(y)]=' '
if(o=='^')y[1]=' '
cat(substr(o,1,1),s)
print(y,quote=F)}

```

Try it online!

Changing to this approach has some downsides, namely it can't be optimised by using `pryr` and is a little clunky to set up the original matrix, but it can be output perfectly with some trailing spaces on the first line.

I still have to use the `substr` trick because of the `%%` mod operator. Will continue to trim this when I get a chance, it still feels very clunky dealing with the special cases.
> 2 votes

# Answer
# Japt `-R`, ~~37~~ 35 bytes

*Look, Ma, no `eval`!*

Was hoping to do a little better than Oliver than this but special-casing `0**0` kicked my ass. Will take another pass at it later on see if I can make any further improvements.

Uses `p` for exponentiation. Tables are transposed for subtraction, division and modulo.

```
Ao
ïNg)£øX «Nø²|Y?X:SÃòA íi iUiN)m¸

```

Try it (or use this version to see the transposed tables with dividing lines, as they appear in the spec) or run all test cases (with transposed tables).

```
Ao\nïNg)£øX «Nø²|Y?X:SÃòA íi iUiN)m¸     :Implicit input of string U
A                                        :10
 o                                       :Range [0,A)
  \n                                     :Reassign to U
    ï                                    :Cartesian product with itself reduced by
     N                                   :  Array of all inputs
      g                                  :  First element (the original input string)
       )                                 :End Cartesian product
        £                                :Map each X at 0-based index Y
         øX                              :  Does U contain X
            «                            :  Logical AND with logical NOT of
             Nø                          :  Does N contain
               ²                         :  "p"
                |Y                       :  Bitwise OR with Y
                  ?X                     :  If truthy, return X
                    :S                   :  Else return space
                      Ã                  :End map
                       òA                :Partitions of length U
                          í              :Pair with 0-based indices
                           i             :  Prepend index to array
                             i           :Prepend
                              UiN        :  U prepended with N
                                 )       :End prepend
                                  m      :Map
                                   ¸     :  Join with spaces
                                         :Implicit output, joined with newlines

```
> 1 votes

# Answer
# PHP, 191 Bytes

`**` instead of `^` as input `+ - / % * **`

```
echo$k=$argn,$k=="**"?"":" ",join(" ",$d=range(0,9));foreach($d as$r){echo"\n$r";foreach($d as$c){echo" ";($k=="/"|($m=$k=="%"))&$r<1?print" ":eval("echo in_array($c$k$r,\$d)?$c$k$r:' ';");}}

```

Online Version of both Versions

## PHP, 245 Bytes without eval

input `+ - / % * ^`

use `bcpowmod($c,1,$r)` instead of `bcmod($c,$r)` because I need a third parameter in the division input. `$c**1%$r==$c%$r`

BC Math Functions

```
echo$k=$argn," ".join(" ",$d=range(0,9));foreach($d as$r){echo"\n$r";foreach($d as$c)echo" ",in_array($s=($k=="/"|($m=$k=="%"))&$r<1?-1:("bc".["+"=>add,"-"=>sub,"/"=>div,"*"=>mul,"^"=>pow,"%"=>powmod][$k])($c,$m?1:$r,$m?$r:9),$d)?round($s):" ";}

```
> 0 votes

# Answer
# 05AB1E, ~~56~~ 55 bytes

```
9ÝDãεðýì„/%Iåyθ_*I'mQyO_*~iðë.VD9ÝQàiïëð]«TôεN<š}®I:ðý»

```

Outputs without lines and with reversed `x` and `y`. Input/output are using `+`, `-`, `*`, `/`, `m`, `%`.

Try it online or verify all tables.

21 bytes are used to fix edge cases `/0`, `%0` and `0^0`, which result in `0`, `0`, and `1` respectively in 05AB1E.. Here without that part (**34 bytes**):

```
9ÝDãεðýì.VD9ÝQàiïëð]«TôεN<š}®I:ðý»

```

Try it online or try all tables.

**Explanation:**

```
9Ý                     # Push list [0,1,2,3,4,5,6,7,8,9]
  D                    # Duplicate it (for the header later on)
   ã                   # Take the cartesian product with itself (creating all pairs):
                       #  [[0,0],[0,1],[0,2],...,[9,7],[9,8],[9,9]]
ε                      # Map each pair `y` to:
 ðý                    #  Join the pairs with a space
   ì                   #  Prepend it before the (implicit) input-char
 „/%Iå                 #   If the input is "/" or "%"
         *             #   and
      yθ_              #   The last value of the pair is exactly 0
                  ~    #  OR
          I'mQ        '#   If the input is "m"
                 *     #   and
              yO_      #   The sum of the pair is exactly 0 (thus [0,0])
 i                     #  If that is truthy:
  ð                    #   Push a space character " "
 ë                     #  Else:
  .V                   #   Execute the string as 05AB1E code
    D                  #   Duplicate the result
     9ÝQài             #   If it's in the list [0,1,2,3,4,5,6,7,8,9]:
          ï            #    Cast it to an integer to remove any trailing ".0"
                       #    (since dividing always results in a float)
         ë             #   Else:
          ð            #    Push a space character " "
]                      # Close both the if-else clauses and the map
 «                     # Merge the resulting list with the duplicated [0,1,2,3,4,5,6,7,8,9]
  Tô                   # Split the list in parts of size 10
    ε   }              # Map each list to:
     N<                #  Get the map-index + 1
       š               #  And prepend it at the front of the list
         ®I:           # Then replace the "-1" with the input-character
ðý                     # And finally join every inner list by spaces
  »                    # And join the entire string by newlines (which is output implicitly)

```
> 0 votes

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


title: Cat a mouse: ASCII art pointers

text:
# Question
Title: Cat a mouse: ASCII art pointers
The Xerox Alto, originally released in 1973, was the first computer to feature the now-familiar angled mouse pointer. The Alto's bitmapped pointer looked like this (redrawn from Fig. 2 here):

Your task in this challenge is to write a program/function that generates an ASCII art representation of the mouse pointer pictured above. Rules:

1. Input is a positive integer \\$n\\$, which is a scaling factor for the output.
2. Represent each black pixel as an \\$n\times{}n\\$ block of any single printable character. (The test cases use `@`, which vaguely resembles a mouse viewed from above.)
3. Similarly, represent each empty pixel to the bottom/left of the pointer as an \\$n\times{}n\\$ block of a second printable character. (Spaces are used in the test cases.)
4. Optionally, your output may also include the empty pixels to the top/right of the pointer, represented by the same character chosen under Rule 3.
5. Any sensible output format (e.g. multi-line string, array of strings, matrix of characters) is acceptable.
6. A single trailing newline at the end of the output is permitted.

### Test cases

\\$n = 1\\$

```
@
@@
@@@
@@@@
@@@@@
@@@@@@
@@@@@@@
@@@@
@@ @@
@  @@
    @@
    @@
     @@
     @@
      @@
      @@

```

\\$n = 2\\$

```
@@
@@
@@@@
@@@@
@@@@@@
@@@@@@
@@@@@@@@
@@@@@@@@
@@@@@@@@@@
@@@@@@@@@@
@@@@@@@@@@@@
@@@@@@@@@@@@
@@@@@@@@@@@@@@
@@@@@@@@@@@@@@
@@@@@@@@
@@@@@@@@
@@@@  @@@@
@@@@  @@@@
@@    @@@@
@@    @@@@
        @@@@
        @@@@
        @@@@
        @@@@
          @@@@
          @@@@
          @@@@
          @@@@
            @@@@
            @@@@
            @@@@
            @@@@

```

\\$n = 3\\$

```
@@@
@@@
@@@
@@@@@@
@@@@@@
@@@@@@
@@@@@@@@@
@@@@@@@@@
@@@@@@@@@
@@@@@@@@@@@@
@@@@@@@@@@@@
@@@@@@@@@@@@
@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@
@@@@@@@@@@@@
@@@@@@@@@@@@
@@@@@@   @@@@@@
@@@@@@   @@@@@@
@@@@@@   @@@@@@
@@@      @@@@@@
@@@      @@@@@@
@@@      @@@@@@
            @@@@@@
            @@@@@@
            @@@@@@
            @@@@@@
            @@@@@@
            @@@@@@
               @@@@@@
               @@@@@@
               @@@@@@
               @@@@@@
               @@@@@@
               @@@@@@
                  @@@@@@
                  @@@@@@
                  @@@@@@
                  @@@@@@
                  @@@@@@
                  @@@@@@

```

# Answer
> 10 votes
# JavaScript (ES6),  ~~92 91~~  90 bytes

*Saved 1 byte thanks to @Neil*

Returns a string with \\$0\\$'s for transparent pixels and \\$1\\$'s for black pixels.

```
n=>(g=k=>--k?(x=k/n%8,y=k/n/n/8,(~1<<(y>9?y-9:13-y)|3<<y/2)>>x&1)+[`
`[x]]+g(k):1)(n*n<<7)

```

Try it online!

or Try it with the characters used in the challenge for easier comparison

### How?

Given the scaling factor \\$n\\$ as input, we output the bit \\$\lfloor x\rfloor\bmod 8\\$ of the bitmask corresponding to the row \\$\lfloor y\rfloor\\$ for each \\$k\\$, \\$0\le k \<128\times n^2\\$, with \\$x=k/n\\$ and \\$y=k/(8\times n^2)\\$.

To generate the bitmask of a given row, we use two small expressions whose results are OR'd together. Only the 8 least significant bits are shown below. The other ones are ignored anyway.

```
floor(y) -> A(y)  OR  B(y)   =  result
   15     10000000  10000000   10000000    with:
   14     11000000  10000000   11000000
   13     11100000  11000000   11100000    A(y) = ~1 << (y > 9 ? y - 9 : 13 - y)
   12     11110000  11000000   11110000    B(y) = 3 << y / 2
   11     11111000  01100000   11111000
   10     11111100  01100000   11111100
    9     11111110  00110000   11111110
    8     11100000  00110000   11110000
    7     11000000  00011000   11011000
    6     10000000  00011000   10011000
    5     00000000  00001100   00001100
    4     00000000  00001100   00001100
    3     00000000  00000110   00000110
    2     00000000  00000110   00000110
    1     00000000  00000011   00000011
    0     00000000  00000011   00000011

```

A linefeed is appended to the output whenever \\$k/n\\$ is a multiple of \\$8\\$.

# Answer
> 5 votes
# 05AB1E, ~~33~~ 31 bytes

```
•4CîιZ›ÚAôçè~]ß4ÿ•Ƶāвε2в¦I×JIF=

```

Outputs with `1` for `@` and `0` for spaces.

-1 byte by not outputting trailing `0`/spaces.

Try it online or verify all test cases.

**Explanation:**

```
•4CîιZ›ÚAôçè~]ß4ÿ• # Push compressed integer 5077310163681960509504474007720499199
 Ƶā                # Push compressed integer 260
   в               # Convert the larger integer to base-260 as list:
                   #  [3,7,15,31,63,127,255,31,59,51,67,67,131,131,259,259]
    ε              # Foreach over the integers in this list:
     2в            #  Convert it to a binary-list
       ¦           #  Remove the leading 1
        I×         #  Repeat each character the input amount of times
          J        #  Join it together to a single string
           IF      #  Inner loop the input amount of times:
             =     #   Print the line with trailing newline (without popping the string)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•4CîιZ›ÚAôçè~]ß4ÿ•` is `5077310163681960509504474007720499199`; `Ƶā` is `260`; and `•4CîιZ›ÚAôçè~]ß4ÿ•Ƶāв` is `[3,7,15,31,63,127,255,31,59,51,67,67,131,131,259,259]`.

# Answer
> 5 votes
# APL (Dyalog Extended), 31 bytes

```
{⍵/⍵⌿⌽⍉⊤⎕AV⍳'⍞§):┼|¨:┴│⍫⍫⍀⍀¢¢'}

```

Try it online!

I guess this is the best APLers can do for now. Outputs a numeric matrix of zeros and ones, as per the clarification.

Basically the same approach as Razetime's answer, using `⎕IO←0` to avoid unprintables.

~~Hey, it tied with Jelly AND 05AB1E!~~ Almost...

# Answer
> 4 votes
# APL (Dyalog Extended), 41 bytes

```
{⎕A[1+⍵/⍵⌿⍉⊤(⎕AV⍳'⌷⊤└¶⍝ ⎕¶"í'),2/12 6 3]}

```

Try it online!

Letter `B` for colored pixels, `A` for transparent pixels.

Uses an APL tip from Andriy Makukha to compress integers.

## Explanation

```
{⎕A[1+⍵/⍵⌿⍉⊤(⎕AV⍳'⌷⊤└¶⍝ ⎕¶"í'),2/12 6 3]} ⍵ → n
                               2/12 6 3   12, 6 and 3 repeated in place
                 '⌷⊤└¶⍝ ⎕¶"í'             String of compressed values
            (⎕AV⍳            )            The SBCS codepoints of the string
                              ,           Join them
          ⍉⊤                              convert to binary & transpose
      ⍵/⍵⌿                                replicate each element n times along both axes
    1+                                    Add 1 to each for getting 1-based indices
 ⎕A[                                   ]  Index the grid into the alphabet

```

# Answer
> 4 votes
# 05AB1E, 29 bytes

White pixels are represented by `0`, black pixels by `1`.

```
•ˆ‰₃%ʒ„úVð“£Xfóó”•b8ôεSI×JIF=

```

Try it online!

**Commented**:

The `IF=` part is taken from Kevin's answer.

```
•ˆ‰₃%ʒ„úVð“£Xfóó”•              # long compressed integer, encodes the 16x8 cursor
                  b             # convert to binary
                   8ô           # split into chunks of 8 digits (rows)
                     ε          # map over the rows ...
                      S         #   split into characters
                       I×       #   multiply each with the input
                         J      #   join into a single string
                          I     #   push the input
                           F    #   for loop in the range [0, input)
                            =   #   print row without popping

```

---

# 05AB1E, 27 bytes

This generates the first seven lines more manually but has some inconsistent spacing. If `X7L×` is replace by `₁7LRo-b`, the spacing is consistent again at 30 bytes.

```
X7L×•ùΛh‡Wgÿ™Œ•b8ô«εSI×JIF=

```

Try it online!

---

# 05AB1E, 31 bytes

Same output format, uses run length encoding.

```
TÞ•€¶àĆαL0šDž¬тq•8вÅΓ8ôεSI×JIF=

```

Try it online!

**Commented**:

```
T                        # push 10
 Þ                       # cycle indefinitely
                         # produces 10101..., the characters used for RLE
  •€...q•8в              # compressed list of lengths [1,7,2,6,3,5,4,4,5,3,6,2,7,1,4,4,2,1,2,3,1,2,2,7,2,6,2,7,2,6,2,7,2,6,2]
           ÅΓ            # run length decode
             8ô          # split into chunks of 8
               εSI×JIF=  # the same as above

```

# Answer
> 3 votes
# , ~~55~~ ~~50~~ 49 bytes

-1 byte thanks to xash!

```
##"1&(16 8$#:96x#._32+3 u:'#dppv6SI=Hz`rW~|%1rc')

```

Try it online!

Ouptus a matrix of 1's and 0s.

# Answer
> 3 votes
# Charcoal, 35 bytes

```
ＮθＦ⪪“∨:[¿θ≡↥χ№pTξ⟧M~▶§×¬‴↥”¶Ｅθ⭆ι×θμ

```

Try it online! Link is to verbose version of code. Outputs using `.`s and spaces (newlines, spaces and `.`s are the golfiest characters for Charcoal compression). Explanation:

```
Ｎθ

```

Input `n`.

```
Ｆ⪪“∨:[¿θ≡↥χ№pTξ⟧M~▶§×¬‴↥”¶

```

Split a compressed representation of the arrow into lines and loop over each line.

```
Ｅθ⭆ι×θμ

```

Expand each line `n` times vertically and horizontally.

Alternative approach, also 35 bytes:

```
ＮθＦχＥθ×.×⎇‹ι⁷⊕ι⁻χιθＪ⁰⊗θＦ⁷«ＵＯ⊗θ.Ｍθ⊗θ

```

Try it online! Link is to verbose version of code. Outputs using `.` and spaces although any non-space printable ASCII could be used. Explanation:

```
Ｎθ

```

Input `n`.

```
Ｆχ

```

Start by printing the first 10 rows of the arrow.

```
Ｅθ×.×⎇‹ι⁷⊕ι⁻χιθ

```

Print a staircase from `1` to `7`, then down from `3` to `1`, all expanded `n` times.

```
Ｊ⁰⊗θ

```

Jump to the beginning of the second row.

```
Ｆ⁷«

```

Loop 7 times.

```
ＵＯ⊗θ.

```

Draw a square of size `2n`.

```
Ｍθ⊗θ

```

Move `n` across and `2n` down.

# Answer
> 3 votes
# Perl 5 \+ `-a -M5.10.0`, 66 bytes

Outputs `1` for black and `0` for empty pixels.

**Note**: This script utilises unprintables, which are represented using escapes below. Verification for 66 bytes.

```
s/./$&x"@F"/ge,eval"say;"x"@F"for unpack"(B8)*","................"

```

Try it online!

## Explanation

Using `-a` the input number is stored (as the only index) in `@F`, which can be interpolated into a string (`"@F"`) saving one byte over using `$F[0]` notation, to control the repetition of characters and lines, as using `-n` would only store the number in `$_`, which is overwritten in the body of the `for`. The string at the end represents the binary data for black or empty pixels which is `unpack`ed in lengths of `8`. In the body of the postfix `for` loop, each block of 8 bits, represented as a string of `0`s and `1`s, is stored in `$_`. First each char in the string is replicated `"@F"` times (`s/./$&x"@F"/ge`) then `eval` is called on a string that contains `"@F"` repetitions of `"say;"` outputting `$_` the number of desired times.

# Answer
> 3 votes
# Jelly, 25 bytes

```
7Żx2r‘$Ṭ
3Ėr7,1FRoÇṠz0xɗ⁺

```

A monadic Link accepting the scaling factor which yields a list of lists of pixel bits (1s are the arrow, 0s are the background)

**Try it online!** (footer calls the link, joins with newlines and prints a smashed version of the resulting list)

### How?

```
3Ėr7,1FRoÇṠz0xɗ⁺ - Link: positive integer, n
3                - three
 Ė               - enumerate -> [1,3]
   7,1           - [7,1]
  r              - inclusive range (vectorises) -> [[1,2,3,4,5,6,7],[3,2,1]]
      F          - flatten -> [1,2,3,4,5,6,7,3,2,1]
       R         - range -> [[1],[1,2],...,[1,2,3,4,5,6,7],[3,2,1],[2,1],[1]]
         Ç       - call Link 1 as a monad - f(n)
        o        - logical OR (vectorises)
          Ṡ      - sign (i.e. convert all the positive integers to 1s)
               ⁺ - do this twice:
              ɗ  -   last three links as a dyad - f(matrix, n)
            0    -     zero
           z     -     transpose (matirix) with filler (0)
             x   -     repeat elements (n) times

7Żx2r‘$Ṭ - Link 1: positive integer, n
7        - seven
 Ż       - zero-range -> [0,1,2,3,4,5,6,7]
   2     - two
  x      - repeat elements -> [0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7]
      $  - last two links as a monad - f(that):
     ‘   -   increment     -> [1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8]
    r    - inclusive range -> [[0,1],[0,1],[1,2],[1,2],[2,3],[2,3]...,[7,8]]
       Ṭ - un-truth        -> [[1],[1],[1,1],[1,1],[0,1,1],[0,1,1],...,[0,0,0,0,0,0,1,1]

```

---

Also 25 bytes:

```
“ṚẒỴġị!=gEḃĖT⁴ċṪ ’Bs8Zx¥⁺ - Link: positive integer, n
“ṚẒỴġị!=gEḃĖT⁴ċṪ ’        - base 250 number = 171142666808876275700130073576311489283
                  B       - to binary
                   s8     - split into slices of length (8)
                        ⁺ - do this twice:
                       ¥  -   last two links as a dyad - f(matrix, n)
                     Z    -     transpose
                      x   -     repeat element (n) times

```

Try it online!

# Answer
> 2 votes
# Python 2, ~~167~~ 145 bytes

```
i=input()
m='@'*i*2
s=' '*i
for z in[c*i*'@'for c in range(1,8)]+[m*2,m+s+m,m[:i]+s*2+m]+sum([[s*d+m]*2for d in(4,5,6)],[]):print'\n'.join([z]*i)

```

Try it online!

Down to 145 with some great help from @ovs. Many thanks!

# Answer
> 2 votes
# Octave, 69 bytes

```
@(n)kron([1:8<=(1:7)';dec2bin(['pX'+128 156 ',,&&##'-32])-48],e(n))>0

```

Anonymous function that inputs a positive integer and outputs a zero-one matrix.

**Try it online!**

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 97 chars, 107 bytes

```
n=>{for(int i=0,j;i<n*16;Write("\n"),i++)for(j=n*8;j>0;)Write("€ÀàðøüþðØ˜"[i/n]>>--j/n&1);}

```

Try it online!

# Answer
> 2 votes
# Python 3, ~~124~~ ~~145~~ 136 bytes

*+21 bytes because I didn't realise we had to scale it vertically as well*

*-9 bytes by using `.` for padding*

```
lambda n,s='@\n.X'*27,J=''.join:J(n*(l+'\n')for l in J(n*s[m>>4]+n*s[m>>2]+n*s[m]for m in b'DDA@D@D@A@@D@P`R`ZhFjAjhFj`Zj`Zj`').split())

```

Try it online!

### Explanation of the `b'DDA@D@D@A@@D@P`R`ZhFjAjhFj`Zj`Zj`'` string

(the code does this in reverse)

take the string, and:

* replace "on" pixel with 0
* replace new-line with 1
* replace space ("off" pixel) with 2

```
010010001000010000010000001000000010000100200102200122220012222001222220012222200122222200122222200

```

convert to binary, two bits per decimal digit:

```
000100000100000001000000000100000000000100000000000001000000000000000100000000010000100000010010100000011010101000000110101010000001101010101000000110101010100000011010101010100000011010101010100000

```

split into groups of 6:

```
000100 000100 000001 000000 000100 000000 000100 000000 000001 000000 000000 000100 000000 010000 100000 010010 100000 011010 101000 000110 101010 000001 101010 101000 000110 101010 100000 011010 101010 100000 011010 101010 100000

```

logical-OR each group with 01000000 (so it's all printable ASCII, to avoid escape characters):

```
01000100 01000100 01000001 01000000 01000100 01000000 01000100 01000000 01000001 01000000 01000000 01000100 01000000 01010000 01100000 01010010 01100000 01011010 01101000 01000110 01101010 01000001 01101010 01101000 01000110 01101010 01100000 01011010 01101010 01100000 01011010 01101010 01100000

```

convert to ASCII for a Python bytestring:

```
b'DDA@D@D@A@@D@P`R`ZhFjAjhFj`Zj`Zj`'

```

# Answer
> 2 votes
# brainfuck, 1892 bytes

```
>++++[>+++++<-]>[<<+>++>--]>++++++++[>++++++++<-]>[<<++>+>--]>+[[-]>[-],[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+>>]<+>]]]<]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<.>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<...>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<....>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<.....>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<......>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<.......>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<....>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<..>>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<.>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<<.>>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<..>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<....>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<....>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<.....>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<.....>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<......>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]<[>+>+<<-]>>[<<+>>-]<[<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[<<<<......>>>>-]<<<[>>+>+<<<-]>>[<<+>>-]>[<<<<<..>>>>>-]<<<<<<<.>>>>>-]

```

Try it online!

Not a short answer by any means - it could probably be shortened by a good bit.

# Answer
> 2 votes
# Python 2, 102 bytes

```
n=input()
for k in range(16*n):print''.join(n*' @'[j<=k/n<max(7,10-j)or-1<k/n/2-j<2]for j in range(8))

```

Try it online!

Computes whether the given coordinate is on of off by a formula that bounds the arrow shape via linear inequalities. To check if the cell is in the tail, which is made of 2\*2 blocks (unscaled), we floor-divide the row index by 2 and check whether it either equals the column index or is one greater than it.

As a function outputting a list of lines:

**97 bytes**

```
lambda n:[''.join(n*' @'[j<=k/n<max(7,10-j)or-1<k/n/2-j<2]for j in range(8))for k in range(16*n)]

```

Try it online!

# Answer
> 1 votes
# Jelly, ~~31~~ 30 bytes

```
5r8ṬƝż`Ẏ
1ẋⱮ7;“ÐñŒ‘B;¢xẎ¥€z0ɗ⁺

```

Try it online!

*-1 from Jonathan Allan's answer reminding me of . Now to figure out why his `z0xɗ` won't work for me...*

Outputs a 2D array of 1 for for on and 0 for off. Integers, rather than characters, though, so +2 for a full program (`µY`) if that's a problem.

```
          Dyadic helper link:
   €      Map
x         repeat left right times
 Ẏ¥       and dump internal lists.
    z0    Zip with filler 0.

                             Main link:
1ẋ                           Repeat 1
  Ɱ7                         1, 2, 3, 4, 5, 6, and 7 times.
    ;                        Concatenate with
     “ÐñŒ‘                   [15, 27, 19].
          B                  Vectorized convert to binary
                             (applies to first bit too, but leaves it unharmed).
           ;                 Concatenate with
                Ṭ    ¤       a list with 1s at the given indices
                 Ɲ           for each pair of adjacent numbers in
            5r8¤             the range from 5 to 8 inclusive,
                  ż`         zipped with itself
                    Ẏ        and with each zipped pair dumped.
                      ç      Apply the helper link with input as right argument.
                       ç     Apply the helper link with input as right argument.

```

# Answer
> 1 votes
# C (gcc), ~~162~~ \\$\cdots\\$ ~~126~~ 104 bytes

Saved a whopping 26 bytes thanks to ceilingcat!!!
Saved another whopping 22 bytes thanks to AZTECCO!!!

Note: code contains unprintables.

```
j;i;f(n){for(i=16*n;i--;puts(""))
for(j=8*n;j--;)putchar(32|L"˜ØðþüøðàÀ€"[i/n]>>j/n&1);}

```

Try it online!

Uses `!` for black pixels (since it's the ascii for space plus \\$1\\$) and spaces for empty pixels (only if preceded by a black pixel, otherwise nothing).

# Answer
> 1 votes
# C (gcc),  ~~106 105 103~~  102 bytes

*Saved 1 byte thanks to @Neil*

Prints the pointer with spaces and exclamation points. Essentially the same method as in my JS answer.

```
x,y;f(n){for(y=n*16;y--;)for(x=n*8;~x;)putchar(x--?32^(~1<<(y/n>8?y/n-9:12-y/n)|3<<y/n/2)>>x/n&1:13);}

```

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), 90 bytes

```
Normal@SparseArray[a_:>36^^4iam2h6stciyoj9kt5169kwfgn4~BitGet~Tr[{8,1}⌈a/#⌉],{16,8}#]&

```

Try it online! Pure function. Takes an integer as input and returns a matrix with 0 and 1 entries.

# Answer
> 1 votes
# Canvas, 32 bytes

```
“┌Wｗｚ‼GZE⁸↘４ＢUＨ＜Ｕ„２┬８ｎ｛｛⁴＋ｃ］］╶╶＊

```

Try it here!

A better compression method would reduce this by a lot.

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


title: Draw the prime race tracks

text:
# Question
Title: Draw the prime race tracks
Odd prime numbers are either in the form of `4k+1` or `4k+3` where `k` is a non-negative integer. If we divide the set of odd prime numbers into two such groups like this:

```
4k+3  |   3     7  11          19  23      31          43  47      59      67  71
      |
4k+1  |      5         13  17          29      37  41          53      61          73

```

we can see that the two groups are kind of *racing* with each other. Sometimes the so-called 'upper' group wins and sometimes the 'lower' one is on track. In fact, Chebyshev discovered that in this race, the upper group wins slightly more often.

## The problem

Let's assume that we are interested in knowing the shape of this race track up to a certain number. Something like this:

The upper and lower horizontal lines indicate that the next prime stays in the same group, while the slanted lines indicate a 'jump' from one group to the other.

Now assume that the underline character `_` represents a lower horizontal line and the overline character  (U+203E) represents an upper one. The slanted lines are represented by slash `/` or backslash `\` characters.

## Challenge

Write a program or function that gets a number `N` as input, and draws this prime race track up to `N`, in a *kind of* ASCII-art-form described as above (Well, it's not an actual ASCII-art since it would contain a non-ASCII character).

## Rules

* `N` is an integer and not necessarily a prime number. Draw the race path for the primes up to, (and maybe including) `N`.
* For a valid `N` as input, the output shall only be composed of these four characters `‾_/\`. No other character, space or separator is allowed (except maybe at the end of output).
* The output can either be in a text file or stdout or wherever supports displaying those characters. But an actual plot (like the blue figure above) is not desired.
* This is , so the shortest code in bytes wins.

## Examples

Here is a list of possible inputs and their acceptable outputs.

```
N < 5        no output or maybe an error message whatsoever
N = 5        \
N = 20       \/‾\_/
N = 100      \/‾\_/‾\/\_/‾\/\/‾\/‾\_

```

## Trivia

The resulting plots of this challenge may actually resemble the *derivative* of the plots shown in there.

# Answer
> 6 votes
# 05AB1E, ~~31~~ ~~26~~ 19 bytes

```
…\/_ŽW ç«ÀIÅP¦4%üeè

```

-5 bytes by taking inspiration from *@HyperNeutrino*'s Jelly answer.
-7 bytes thanks to *@Grimmy*.

Outputs as a list of characters.

Try it online (the `J` in the footer is to join the list together to pretty-print it).

**Explanation:**

```
…\/_                 # Push the string "\/_"
    ŽW               # Push compressed integer 8254
       ç             # Convert it to a character with this codepoint: "‾"
        «            # Append it to the earlier string: "\/_‾"
         À           # And rotate it once to the left: "/_‾\"
          IÅP        # Push a list of all primes <= the input-integer
                     #  i.e. 50 → [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]
             ¦       # Remove the first value
                     #  → [3,5,7,11,13,17,19,23,29,31,37,41,43,47]
              4%     # Take modulo-4 on each value
                     #  → [3,1,3,3,1,1,3,3,1,3,1,1,3,3]
                ü    # For each overlapping pair:
                     #  → [[3,1],[1,3],[3,3],[3,1],[1,1],[1,3],[3,3],[3,1],[1,3],[3,1],[1,1],[1,3],[3,3]]
                 e   #  Get the number of permutations; short for ⌊a!/|a-b|!⌋
                     #   → [3,0,6,3,1,0,6,3,0,3,1,0,6]
                  è  # And index each into the earlier created string
                     # (0-based and with wraparound, so the 6 is index 2 in this case)
                     #  → ["\","/","‾","\","_","/","‾","\","/","\","_","/","‾"]
                     # (after which the result is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integer?*) to understand why `ŽW`  is `8254`.

# Answer
> 6 votes
# Python 2 (IronPython), 87 bytes

I'm using IronPython here to display the unicode character , since Python can't print it.

```
P=a=b=1
s=''
exec"if P%a:s+='\/‾_'[b%4/2-a%4];b=a\nP*=a*a;a+=1\n"*input()
print s[2:]

```

Try it online!

## Explanation

The idea of calculating primes comes from this answer, which uses Wilson's theorem. To figure out which character to print, we use the following formula: \\$ \frac{b \bmod 4} 2 - a \bmod 4 \\$, where \\$ a \\$ and \\$ b \\$ represent the current and previous prime numbers. Here is a table to show how this works:

```
 a mod 4 | b mod 4 | a'/2-b'
---------+---------+---------
    1    |    1    |   -1
    1    |    3    |   -3
    3    |    1    |    0
    3    |    3    |   -2

```

And in Python negative indices wrap around to the end of the string, so each index maps to its own character.

# Answer
> 3 votes
# Wolfram Language (Mathematica), 102 bytes

TIO doesn't display U+203E...

```
""<>(Partition[Prime@Range[2,PrimePi@#]~Mod~4,2,1]/.{{3,1}->"\\",{3,3}->"‾",{1,1}->"_",{1,3}->"/"})&

```

Try it online!

# Answer
> 3 votes
# , 50 bytes

```
1('/^\_'{~[:(+_1&|.*1&=)1+2*@-/\4&|)@}.(#~1&p:)@i.

```

Try it online!

Had to replace  with `^` because the formatting on TIO screws up otherwise.

This uses \< N convention.

# Answer
> 3 votes
# Jelly, 20 bytes

```
ÆRḊ%4ḄƝṣ9ị“\/_”j⁽ø¤Ọ

```

Try it online!

-3 bytes thanks to Jonathan Allan

# Explanation

```
ÆRḊ%4ḄƝṣ9ị“\/_”j⁽ø¤Ọ  Main Link
ÆR                    Primes up to N
  Ḋ                   All but the first (3, 5, 7, 11, ...)
   %4                 Modulo 4
     ḄƝ               Convert each pair (overlapping run of 2) to binary (even though the digits are 1 and 3, this still works because it's just 2 x first digit + second digit) - 1,1: 3; 1,3: 5; 3,1: 7; 3,3: 9
       ṣ9             Split on 9 (the upper bar)
         ị“\/_”       Index into "\/_" (3 is _, 5 wraps around to /, 7 wraps around twice to \)
               j⁽ø¤   Join on 8254
                   Ọ  Convert from char code to character; doesn't affect characters, only the 8254s

```

# Answer
> 2 votes
# JavaScript (ES6), 86 bytes

```
n=>(g=x=>x>n?'':['\\_/‾'[(P=n=>n%--d?P(n):d<2)(d=x)&&(q==(q=x%4))|q&2]]+g(x+1))(q=4)

```

Try it online!

### Commented

```
n => (                  // n = input
  g = x =>              // g is a recursive function taking the current integer x
    x > n ?             // if x is greater than n:
      ''                //   stop recursion
    :                   // else:
      [                 //   make sure to turn undefined into an empty string
        '\\_/‾'[        //     pick the relevant character:
          ( P = n =>    //       P is a helper function taking n:
              n % --d ? //         decrement d; if d does not divide n:
                P(n)    //           try again until it does
              :         //         else:
                d < 2   //           return true if d = 1 (i.e. n is prime)
          )(d = x)      //       initial call to P with n = d = x
          &&            //       if x is not prime, ['\\_/‾'[false]] ~> empty string
          (             //       if x is prime:
            q ==        //         yield 1 if q is equal to ...
            (q = x % 4) //         ... the new value of q which is x mod 4
          ) | q & 2     //         bitwise OR with q & 2 for the direction
        ]               //     end of character lookup
      ] + g(x + 1)      //   add the result of a recursive call with x + 1
)(q = 4)                // initial call to g with x = q = 4

```

# Answer
> 2 votes
# Python 3.8, ~~105 103 96 89~~ 88 bytes

```
f=lambda n,i=3,j=5,t=24:n//j*" "and"\/‾_"[i%4//2-j%4]*(P:=t%j>0)+f(n,[i,j][P],j+1,t*j)

```

Try it online!

*-1 byte thanks to @xnor!*

### Explanation:

This is a recursive function that increases `j` from `5` to `n`. If `j` is prime, the function compares it to the previous prime `i` to determine the race track character.

The following expression evaluates to `1` or `0` depending on whether `j` is prime or not:

```
t%j>0

```

where `t` is `factorial(j-1)`. This uses Wilson's theorem, taken from @xnor's answer on another prime problem.

Given 2 consecutive prime `i` and `j`, the following code determines the character (shamelessly stolen from @dingledooper's answer):

```
"\/‾_"[i%4//2-j%4]

```

# Answer
> 2 votes
# Retina 0.8.2, 65 bytes

```
.+
$*
1
_1$`
^.{6}|_(11+)\1+(?!1)|1111|1(1?)
$2
_1
/1
1/
‾
1_
\

```

Try it online! Explanation:

```
.+
$*

```

Convert `N` to unary.

```
1
_1$`

```

Count up to `N`, using `_` to separate the unary values, thus assuming all odd primes have a remainder of 1 (modulo 4) by default.

```
^.{6}|_(11+)\1+(?!1)|1111|1(1?)
$2

```

Delete `1`, `2` and their separators; delete all composite numbers and their separators; reduce the odd primes modulo 4, and identify the primes with a remainder of 3 (modulo 4).

```
_1
/1

```

Still assuming that the prime previous to a prime with a remainder with 3 has a remainder of 1, change the `_` to a `/`.

```
1/
‾

```

But if it turns out that the previous prime also has a remainder of 3, then change the `/` to a .

```
1_
\

```

Any remaining primes with a remainder of 3 must have a next prime with a remainder of 1, so change the `_` to a `\\`.

# Answer
> 1 votes
# Erlang (escript), 118 bytes

Erlang doesn't support negative indices so I had to do my own. (Also it doesn't display , so it's replaced with `^`.)

```
p([_])->[];p([H|T])->[lists:nth(H rem 4+1rem(hd(T)rem 4),"_/\\^")|p([A||A<-T,A rem H>0])];p(X)->tl(p(lists:seq(2,X))).

```

Try it online!

# Replaced formula

```
  a % 4  |  b % 4  | a + 1%b
---------+---------+---------
    1    |    1    |   1
    1    |    3    |   2
    3    |    1    |   3
    3    |    3    |   4

```

# Answer
> 0 votes
# Husk, 26 bytes

```
J'¯†!"¦/_"x9ẊoB2em%4t↑İp

```

Try it online!

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


title: A nicely-spaced ASCII spiral

text:
# Question
Title: A nicely-spaced ASCII spiral
Consider this spiral

```
###########
#
# #######
# #     #
# # ### #
# # # # #
# # # # #
# #   # #
# ##### #
#       #
#########

```

Starting in the centre:

* The first line (upwards) has 3 characters.
* The second line has the same number of characters (3)
* Next, we add two chars (5) for the next two sides.
* This pattern continues, two sides the same length then increase the length by 2.

I want to generate this spiral for N lines.

* Write in any language.
* The input/argument, etc. is the number of lines in your spiral.
* Each line starts with the ending character of the previous line in the direction 90 degrees clockwise of the previous line.
* I don't care how much whitespace is before or after each line, as long as the elements of the spiral line up.
* Output text to draw the spiral with any non-whitespace character you choose.
* Attempt to do this in the smallest number of bytes.

Test cases (using a hash as output):

N = 1

```
#
#
#

```

N = 2

```
###
#
#

```

N = 3

```
###
# #
# #
  #
  #

```

N = 10

```
###########
#
# #######
# #     #
# # ### #
# # # # #
# # # # #
# #   # #
# ##### #
#       #
#########

```

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

### Code:

Thanks to *Emigna* for saving two bytes!

```
LDÈ-Ì'#3Ý·Λ

```

Uses the **05AB1E** encoding. Try it online!

### Explanation

The lengths of each individual edge on the spiral starts with length **3** and gradually increases every two steps by two:

$$ 3, 3, 5, 5, 7, 7, 9,\dots $$

For a spiral with \\$n\\$ edges, we just need to trim this list to size \\$n\\$. This is done with the following piece of code:

```
L                # Create a list from [1 .. input]
 DÈ              # Duplicate and check for each number if even
   -             # Subtract that from the first list
    Ì            # Add 2

```

This basically gives us the desired list of lengths.

```
     '#          # Push the '#' character
       0246S     # Push the array [0, 2, 4, 6]
            Λ    # Write to canvas

```

The canvas works as a function that pops three parameters (where the rightmost parameter is popped first): **\<length(s)\>**, **\<char(s)\>**, **\<direction(s)\>**. The directions parameter is in this case a list of numbers. The numbers that correspond to the directions are:

$$ \left\[\begin{array}{r} 7 & 0 & 1 \\ 6 & \circ & 2 \\ 5 & 4 & 3 \end{array}\right\] $$

In this case, **\[0, 2, 4, 6\]** corresponds to the directions list `[↑, →, ↓, ←]`. The canvas iterates over each length retrieved from the list of lengths, uses the '#' character and cyclically iterates over the directions list.
> 11 votes

# Answer
# Python 2, ~~176~~ ~~170~~ ~~165~~ ~~161~~ 157 bytes

```
g=lambda a,r:r and g(map(''.join,zip(*a))[::-1],r-1)or a
R=['#']
n=1
exec"R=g(['  '+l for l in g(R,n)][:-1]+[(n+2)*'#'],3*n);n+=1;"*input()
print'\n'.join(R)

```

Try it online!

Repeatedly: Uses `g` to rotate the `n`th iteration of the spiral into a 'canonical' position (similar to N=3 or N=7), adds a new segment by adding 2 spaces at the left of each existing row, then replacing the last row with all `'#'`s (resulting in a position comparable to N=4 or N=8), and finally using `g` again to rotate it back to the correct position. Lather, rinse, repeat.
> 6 votes

# Answer
# Charcoal, ~~16~~ ~~15~~ 14 bytes

```
↶ＦＮ«¶×#⁺³⊗÷ι²↷

```

-2 bytes thanks to *@Neil*.

Try it online (verbose) or Try it online (pure).

**Explanation:**

Printing direction is to the right by default, and we want to start upwards, so we start by rotating 45 degrees counterclockwise:

```
PivotLeft();
↶

```

Then loop `i` in the range `[0, input)`:

```
For(InputNumber()){ ... }
ＦＮ« ...

```

Print a new-line to mimic the effect of moving back one position:

```
Print("\n");
¶

```

Print "#" `x` amount of times in the current direction:

```
Print(Times("#", ... ));
×# ...

```

Where `x` is: `3 + i // 2 * 2`:

```
Add(3,Doubled(IntegerDivide(i,2))
⁺³⊗÷ι²

```

And then rotate 45 degrees clockwise for the next iteration of the loop:

```
PivotRight();
↷

```
> 4 votes

# Answer
# Python 2, ~~179~~ 178 bytes

thanks to Kevin Cruijssen for -1 byte.

```
n=input()
S,H=' #'
m=[S*n]*(n%2-~n)
x=n/4*2
y=0--n/4*2
k=2
m[y]=S*x+H+S*n
M=[1,0,-1,0]*n
exec'exec k/2*2*"x+=M[~k];y+=M[k];m[y]=m[y][:x]+H+m[y][x+1:];";k+=1;'*n
print'\n'.join(m)

```

Try it online!

---

# Python 2, 179 bytes

In this approach formulas are used for `x` and `y` deltas instead of a lookup list.

```
n=input()
S,H=' #'
m=[S*n]*(n%2-~n)
x=n/4*2
y=0--n/4*2
k=2
m[y]=S*x+H+S*n
exec'exec k/2*2*"x+=k%-2+k%4/3*2;y-=(k%2or k%4)-1;m[y]=m[y][:x]+H+m[y][x+1:];";k+=1;'*n
print'\n'.join(m)

```

Try it online!
> 3 votes

# Answer
## JavaScript (ES6), 185 bytes

Sure this can be golfed more, maybe with currying, but here's my very humble attempt. Line breaks added for readability except penultimate character

```
r=(a,n=1)=>n?r(a.reduce((_,c)=>c).map((_,i)=>a.map(e=>e[i])).reverse(),n-1):a,
s=n=>n?r(s(n-1)).map((r,i)=>[...r,w,w].map(x=>i?x:'#')):[[w=' ']],
d=n=>r(s(n),1-i).map(r=>r.join``).join`
`

```

Usage: `d(10)` returns a string as per the N=10 challenge example.

Defines a function `r(a,n)` to rotate an array `a` by `n` turns; a function `s(n)` to generate a 2-dimensional array representing a spiral of size `n` by recursively rotating and adding spacing and lines (not rotated back to starting position); and a function `d(n)` to draw a spiral of size `n`, rotated consistently as per the challenge, and rendered as a returned string.

This was a really fun challenge :¬)
> 1 votes

# Answer
# Canvas, <sup>~~20~~</sup> 16 bytes

```
Ｈ：２％！－├#×；↶ｎ｝╶├⟳

```

Try it here!

## Explanation

```
ø；｛：２％！－├#×；↶１１╋｝╶├⟳
ø                            push an empty art object
 ；                              swap with the input
   ｛                  ｝    for i in 1 to n:
   ｛：                ｝     duplicate i
   ｛ ２％              ｝    mod 2
   ｛    ！            ｝    negate
   ｛     －           ｝    subtract that from i
   ｛       ├          ｝    add 2
   ｛         #×       ｝    repeat '#' that many times
   ｛           ；     ｝    swap with previous iteration
   ｛             ↶    ｝   turn 90 degrees anticlockwise
   ｛              １１╋｝   overlap at (1,1)
                        ╶├⟳ rotate 90 degrees n+2 times

```
> 1 votes

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