# Question
Title: Can square tree rings be generated from primes?
Apparently yes! In three easy steps.

### Step 1

Let *f*(*n*) denote the prime-counting function (number of primes less than or equal to *n*).

Define the integer **sequence** *s*(*n*) as follows. For each positive integer *n*,

* Initiallize *t* to *n*.
* As long as *t* is neither prime nor 1, replace *t* by *f*(*t*) and iterate.
* The number of iterations is *s*(*n*).

The iterative process is guaranteed to end because *f*(*n*) \< *n* for all *n*.

Consider for example *n*=25. We initiallize *t* = 25. Since this is not a prime nor 1, we compute *f*(25), which is 9. This becomes the new value for *t*. This is not a prime nor 1, so we continue: *f*(9) is 4. We continue again: *f*(4) is 2. Since this is a prime we stop here. We have done 3 iterations (from 25 to 9, then to 4, then to 2). Thus *s*(25) is 3.

The first 40 terms of the sequence are as follows. The sequence is not in OEIS.

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

```

### Step 2

Given an odd positive integer *N*, build an N×N array (matrix) by winding the finite sequence *s*(1), *s*(2), ..., *s*(*N*2) to form a square outward **spiral**. For example, given *N* = 5 the spiral is

```
s(21)   s(22)   s(23)   s(24)   s(25)
s(20)   s(7)    s(8)    s(9)    s(10)
s(19)   s(6)    s(1)    s(2)    s(11)
s(18)   s(5)    s(4)    s(3)    s(12)
s(17)   s(16)   s(15)   s(14)   s(13)

```

or, substituting the values,

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

```

### Step 3

Represent the N×N array as an **image** with a grey colour map, or with some other colour map of your taste. The map should be gradual, so that the order of numbers corresponds to some visually obvious order of the colours. The test cases below show some example colour maps.

# The challenge

Given an odd positive integer *N*, produce the image described above.

# Rules

* The spiral must be outward, but can be clockwise or counter-clockwise, and can start moving right (as in the above example), left, down or up.
* The scales of the horizontal and vertical axes need not be the same. Also axis labels, colorbar and similar elements are optional. As long as the spiral can be clearly seen, the image is valid.
* Images can be output by any of the standard means. In particular, the image may be displayed on screen, or a graphics file may be produced, or an array of RGB values may be output. If outputting a file or an array, please post an example of what it looks like when displayed.
* Input means and format are flexible as usual. A program or a function can be provided. Standard loopholes are forbidden.
* Shortest code in bytes wins.

# Test cases

The following images (click for full resolution) correspond to several values of *N*. A clock-wise, rightward-first spiral is used, as in the example above. The images also illustrate several valid colour maps.

* *N* = 301:
* *N* = 501:
* *N* = 701:

# Answer
# Dyalog APL, 94 bytes

```
'P2'
2⍴n←⎕
9
(⍪0){×≢⍵:(≢⍺)((⍉∘⌽⍺,↑)∇↓)⍵⋄⍺}2↓{⍵⌊1+⍵[+\p]}⍣≡9×~p←1=⊃+/(≠⍨,≠⍨,~⍴⍨(×⍨n)-2×≢)¨,\×⍳n

```

assumes `⎕IO=0`

output for n=701 (converted from .pgm to .png):
> 3 votes

# Answer
# MATLAB - ~~197~~ ~~185~~ ~~178~~ ~~175~~ ~~184~~ ~~163~~ ~~162~~ ~~148~~ ~~142~~ 140 bytes

Shaved 12 bytes, thanks to Ander and Andras, and lots thanks to Luis for putting the two together. Shaved 16 thanks to Remco, 6 thanks to flawr

```
function F(n)
p=@primes
s=@isprime
for a=2:n^2
c=0
if~s(a)
b=nnz(p(a))
while~s(b)
b=nnz(p(b))
c=c+1
end
end
d(a)=c
end
imagesc(d(spiral(n)))

```

Result for `N=301` (`F(301)`):

Explanation:

```
function F(n)
p=@primes % Handle
s=@isprime % Handle
for a=2:n^2 % Loop over all numbers
    c=0 % Set initial count
    if~s(a) % If not a prime
        b=nnz(p(a)) % Count primes
        while~s(b) % Stop if b is a prime. Since the code starts at 2, it never reaches 1 anyway
            b=nnz(p(b)) % count again
            c=c+1 % increase count
        end
    end
    d(a)=c % store count
end
imagesc(d(spiral(n))) % plot

```
> 10 votes

# Answer
# Wolfram Language (Mathematica), 124 bytes

Thanks to Martin Ender for saving 12 bytes!

```
Image[#/Max@#]&[Array[(n=0;Max[4#2#2-Max[+##,3#2-#],4#
#-{+##,3#-#2}]+1//.x_?CompositeQ:>PrimePi[++n;x];n)&,{#,#},(1-#)/2]]&

```

Try it online!

---

The image generated is:

##

Closed form formula of the spiral value taken directly from this answer of mine.
> 8 votes

# Answer
## MATLAB: 115 114 110 bytes

One liner (run in R2016b+ as function in script) 115 bytes

```
I=@(N)imagesc(arrayfun(@(x)s(x,0),spiral(N)));function k=s(n,k);if n>1&~isprime(n);k=s(nnz(primes(n)),k+1);end;end

```

Putting the function in a separate file, as suggested by flawr, and using the 1 additional byte per additional file rule

In the file `s.m`, 64 + 1 bytes for code + file

```
function k=s(n,k);if n>1&~isprime(n);k=s(nnz(primes(n)),k+1);end

```

Command window to define `I`, 45 bytes

```
I=@(N)imagesc(arrayfun(@(x)s(x,0),spiral(N)))

```

**Total: 110 bytes**

---

This uses recursion instead of `while` looping like the other MATLAB implementations do (gnovice, Adriaan). Run it as a script (in R2016b or newer), this defines the function `I` which can be run like `I(n)`.

Structured version:

```
% Anonymous function for use, i.e. I(301)
% Uses arrayfun to avoid for loop, spiral to create spiral!
I=@(N)imagesc(arrayfun(@(x)s(x,0),spiral(N)));

% Function for recursively calculating the s(n) value
function k=s(n,k)
    % Condition for re-iterating. Otherwise return k unchanged
    if n>1 && ~isprime(n)
        % Increment k and re-iterate
        k = s( nnz(primes(n)), k+1 );
    end
end

```

Example:

```
I(301)

```

Notes:

* I tried to make the `s` function anonymous too, of course that would reduce the count significantly. However, there are 2 issues:

1. Infinite recursion is hard to avoid when using anonymous functions, as MATLAB doesn't have a ternary operator to offer a break condition. Bodging a ternary operator of sorts (see below) also costs bytes as we need the condition twice.
    2. You have to pass an anonymous function to itself if it is recursive (see here) which adds bytes.

The closest I came to this used the following lines, perhaps it can be changed to work:

```
    % Condition, since we need to use it twice
    c=@(n)n>1&&~isprime(n);
    % This uses a bodged ternary operator, multiplying the two possible outputs by
    % c(n) and ~c(n) and adding to return effectively only one of them
    % An attempt was made to use &&'s short-circuiting to avoid infinite recursion
    % but this doesn't seem to work!
    S=@(S,n,k)~c(n)*k+c(n)&&S(S,nnz(primes(n)),k+1);

```
> 7 votes

# Answer
## MATLAB - 126 121* bytes

I attempted a more vectorized approach than Adriaan and was able to shave more bytes off. Here's the single-line solution:

```
function t(n),M=1:n^2;c=0;i=1;s=@isprime;v=cumsum(s(M));while any(i),i=M>1&~s(M);c=c+i;M(i)=v(M(i));end;imagesc(c(spiral(n)))

```

And here's the nicely-formatted solution:

```
function t(n),
  M = 1:n^2;
  c = 0;
  i = 1;
  s = @isprime;
  v = cumsum(s(M));
  while any(i),         % *See below
    i = M > 1 & ~s(M);
    c = c+i;
    M(i) = v(M(i));
  end;
  imagesc(c(spiral(n)))

```

**Note: if you're willing to allow a metric crapton of unnecessary iterations, you can change the line* `while any(i),` *to* `for m=v,` *and save 5 bytes.*
> 6 votes

# Answer
# Python 3, ~~299~~ 265 bytes

Saved 5 bytes thanks to formatting suggestions from Jonathan Frech and NoOneIsHere. Removed an additional 34 bytes by removing a function definition that was only called once.

This is a little longer than some others, due to python not having a command to determine primeness, or spiral an array. It runs relatively quickly however, around a minute for `n = 700`.

```
from pylab import*
def S(n):
 q=arange(n*n+1);t=ones_like(q)
 for i in q[2:]:t[2*i::i]=0
 c=lambda i:0 if t[i]else 1+c(sum(t[2:i]));S=[c(x)for x in q]
 t=r_[[[S[1]]]]
 while any(array(t.shape)<n):m=t.shape;i=multiply(*m)+1;t=vstack([S[i:i+m[0]],rot90(t)])
 return t

```

Test it with

```
n = 7
x = S(n)
imshow(x, interpolation='none')
colorbar()
show(block=False)

```
> 2 votes

# Answer
# J, 121 Bytes

```
load 'viewmat'
a=:3 :'viewmat{:@((p:inv@{.,>:@{:)^:(-.@((=1:)+.1&p:)@{.)^:_)@(,0:)"0(,1+(i.@#+>./)@{:)@|:@|.^:(+:<:y),.1'

```

Defines a function:

```
a=:3 :'viewmat{:@((p:inv@{.,>:@{:)^:(-.@((=1:)+.1&p:)@{.)^:_)@(,0:)"0(,1+(i.@#+>./)@{:)@|:@|.^:(+:<:y),.1' | Full fuction
                                                                     (,1+(i.@#+>./)@{:)@|:@|.^:(+:<:y),.1  | Creates the number spiral
              {:@((p:inv@{.,>:@{:)^:(-.@((=1:)+.1&p:)@{.)^:_)@(,0:)"0                                      | Applies S(n) to each element
       viewmat                                                                                | View the array as an image

```
> 2 votes

# Answer
# R, 231 bytes

```
function(n){p=function(n)sum(!n%%2:n)<2;M=matrix(0,n,n);M[n^2%/%2+cumsum(c(1,head(rep(rep(c(1,-n,-1,n),l=2*n-1),rev(n-seq(n*2-1)%/%2)),-1)))]=sapply(1:(n^2),function(x){y=0;while(x>2&!p(x)){x=sum(sapply(2:x,p));y=y+1};y});image(M)}

```

Slightly less golfed:

```
function(n){
    p=function(n)sum(!n%%2:n)<2 #"is.prime" function
    M=matrix(0,n,n)             #empty matrix
    indices=n^2%/%2+cumsum(c(1,head(rep(rep(c(1,-n,-1,n),l=2*n-1),rev(n-seq(n*2-1)%/%2)),-1)))
    values=sapply(1:(n^2),function(x){
        y=0
        while(x>2&!p(x)){
            x=sum(sapply(2:x,p))
            y=y+1
            }
        y})
    M[indices]=values
    image(M) #Plotting
}

```

Anonymous function. Output in a graphic window. Scale is on the red-scale with darkest shade equals to 0 and clearer shades increasing values.

Result for n=101:
> 2 votes

---
Tags: code-golf, sequence, number-theory, graphical-output, integer
---


title: Draw Concentric ASCII Hexagons

text:
# Question
Title: Draw Concentric ASCII Hexagons
Write the shortest program possible that takes in a set of distinct positive integers and outputs an ASCII rendering of concentric hexagons with those side lengths, made from slashes, underscores, spaces, and newlines.

The shortest program in bytes as counted by https://mothereff.in/byte-counter wins.

# Examples

(They look better with less line spacing.)

If the input is `1` the output should be the hexagon with side length 1:

```
 __
/  \
\__/

```

Notice that two underscores are used for the top and bottom of the hexagon so it is better proportioned.

In general, the size N hexagon contains N slashes on each angled side and 2\*N underscores on on both the top and bottom.

If the input is `1 2` the output should be the concentric hexagons with side length 1 and 2:

```
  ____
 / __ \
/ /  \ \
\ \__/ /
 \____/

```

If the input is `1 3` the output should be:

```
   ______
  /      \
 /   __   \
/   /  \   \
\   \__/   /
 \        /
  \______/

```

If the input is `1 3 2` the output should be:

```
   ______
  / ____ \
 / / __ \ \
/ / /  \ \ \
\ \ \__/ / /
 \ \____/ /
  \______/

```

etc.

# I/O Rules

Input must come from either the command line or stdin but may be in whatever format is most convenient.

For example, you might give each number as a command line argument: `> myprogram 1 3 2`, or you might prompt the user to input the numbers as a preformatted list: `[1, 3, 2]`.

Output must go to stdout or your language's closest equivalent.

# Additional Rules

* The input will always be a set of distinct positive integers, **not necessarily in any order**.
* The output must...
    + not contain any characters besides `/\ _` and newlines.
    + have no trailing spaces or unnecessary leading spaces.
    + not contain extraneous leading newlines but may have one *optional* trailing newline.
* If nothing is input then output nothing (except possibly one newline).
* If it helps you may assume that the input integers are less than 216.

# Answer
# CJam, ~~148~~ ~~116~~ 109 bytes

This took a lot longer than I expected. Originally, I just wanted to iteratively build the upper left quadrant, as in the diamond challenges, and then get the rest from mirroring. But I didn't notice that the underscores don't obey mirror symmetry between the upper and lower half. So I had to redo most of that, to generate the right half iteratively and then only mirror once (to the left).

```
S]2[l~]:(f#:+2bW%{_,2/~:T;{IT):T1<'\'/?S?S++}%__,2/=,2/I'_S?*_S+a@+\I'/S?S++a+}fI{)T)2*2$,-*1$W%"\/"_W%er@N}/

```

Test it here.

A Fibonacci-esque example:

```
8 3 1 5 2

```

```
        ________________
       /                \
      /                  \
     /     __________     \
    /     /          \     \
   /     /   ______   \     \
  /     /   / ____ \   \     \
 /     /   / / __ \ \   \     \
/     /   / / /  \ \ \   \     \
\     \   \ \ \__/ / /   /     /
 \     \   \ \____/ /   /     /
  \     \   \______/   /     /
   \     \            /     /
    \     \__________/     /
     \                    /
      \                  /
       \________________/

```

## Explanation:

As stated at the top, I start by building the right half iteratively. That is, initially I've got only a single space in the grid, and then for each possible ring, I either surround the existing grid in spaces or a new semi-hexagon.

Once that's done, I mirror each line to the left and pad it with leading spaces for correct alignment. Here is a breakdown of the code:

```
"Prepare the input and the grid:";
S]2[l~]:(f#:+2bW%
S]                "Push string with a space and wrap it in an array. This is the grid.";
  2               "Push a 2 for future use.";
   [l~]           "Read and evaluate the input, wrap it in an array.";
       :(         "Decrement each number by 1.";
         f#       "Map each number i to 2^i.";
           :+     "Sum them all up.";
             2b   "Get the base two representation.";
               W% "Reverse the array.":
"At this point, the stack has the proto-grid at the bottom, and an array of 1s and
 0s on top, which indicates for each hexagon if it's present or not.";

"Next is a for loop, which runs the block for each of those 0s and 1s, storing the
 actual value in I. This block adds the next semi-hexagon or spaces.";
{ ... }fI

"First, append two characters to all existing lines:";
_,2/~:T;{IT):T1<'\'/?S?S++}%
_                            "Duplicate the previous grid.";
 ,2/                         "Get its length, integer-divide by 2.";
    ~:T;                     "Get the bitwise complement and store it in T. Discard it.";
        {                 }% "Map this block onto each line of the grid.";
         I                   "Push the current hexagon flag for future use.";
          T):T               "Push T, increment, store the new value.";
              1<'\'/?        "If T is less than 1, push \, else push /.";
                     S?      "If the current flag is 0, replace by a space.";
                       S++   "Append a space and add it to the current line.";

"So for hexagons this appends '\ ' to the top half and '/ ' to the bottom half.
 For empty rings, it appends '  ' to all lines.";

"Now add a new line to the top and the bottom:"
__,2/=,2/I'_S?*_S+a@+\I'/S?S++a+
__                               "Get two copies of the grid.";
  ,2/                            "Get its length, integer-divide by 2.";
     =                           "Get that line - this is always the middle line.";
      ,2/                        "Get ITS length, integer'divide by 2.";
         I'_S?*                  "Get a string of that many _ or spaces depending on the
                                  current flag.";
               _S+               "Duplicate and a space.";
                  a@+            "Wrap in an array, pull up the grid, and prepend the line.";
                     \           "Swap with the other copy.";
                      I'/S?      "Choose between / and a space depending on the flag.";
                           S++   "Append a space, and add both characters to the line.";
                              a+ "Wrap in an array, and append line to the grid.";

"This is all. Rinse and repeat for all rings. The result will look something like this:

_____
     \
___   \
__ \   \
_ \ \   \
 \ \ \   \
_/ / /   /
__/ /   /
___/   /
      /
_____/

Note that there are still trailing spaces.";

"Finish up all lines. These will not be joined together any more, but simply left
 on the stack in pieces to printed out back-to-back at the end of the program.
 The following runs the given block for each line:";
{ ... } /

"This generates the necessary indentation, then mirrors the lines and puts them
 in the right order:"
)T)2*2$,-*\_W%"\/"_W%er\N
)                         "Slice off that trailing space, but leave it on the stack.";
 T                        "Remember T? That still has something like the the size of
                           the grid from the last iteration. In fact it's N-1, where
                           N is the largest visible hexagon. We can use that to figure
                           out how many spaces we need.";
  )2*                     "Increment and double.";
     2$                   "Copy the current line.";
       ,-                 "Subtract its length from 2*N.";
         *                "Repeat the space that often. This is our indentation.";
          \_              "Swap with the line and duplicate.";
            W%            "Reverse the line.";
              "\/"_W%er   "Replace slashes with backslashes and vice versa.";
                       \  "Swap with the original line.";
                        N "Push a line break.";

```
> 4 votes

# Answer
# Python - ~~251, 240, 239~~ 228

```
l=input()+[0];m=max(l);A=abs;R=range
for j in R(2*m+1):print''.join([[' \\'[(A(j-i+m-1)/2.in l)*(2*m-i)/(j-m-.5)>1],'/'][(A(3*m-i-j)/2.in l)*(i-m-j+.5)/(j-.5-m)>0],'_'][(A(m-j)in l)*(A(2*m-i-.5)<A(m-j))]for i in R(4*m)).rstrip()

```

---

**Alternative approach (251):**

```
l=input()+[0]
l.sort()
m=max(l)
M=2*m
s=[[' ']*m*4for j in' '*(M+1)]
for i in l:
 I=2*i;s[m-i][M-i:M+i]=s[m+i][M-i:M+i]='_'*I
 for k in range(i):K=k+1;s[m-k][M-I+k]=s[m+K][M+I-K]='/';s[m-k][M+I-K]=s[m+K][M-I+k]='\\'
for t in s:print''.join(t).rstrip()

```
> 7 votes

# Answer
## APL (222 bytes in UTF-8)

(and 133 chars)

Since this question specifically asks for amount of bytes in UTF8 representation, I had to actually *ungolf* it a bit so that it is longer but its UTF8 representation is shorter. (In particular, the commute operator's character  is three bytes while `()` is only two, so that optimalisation doesn't work anymore, and it also makes assignment very expensive.)

```
{⎕←(~⌽∧\⌽⍵=' ')/⍵}¨↓⊃{⍵{⍺=' ':⍵⋄⍺}¨K↑(-.5×(K←⍴⍵)+⍴⍺)↑⍺}/{Z⍪⌽⊖Z←↑(⊂(⍵/' '),(2×⍵)/'-'),⍵{((-⍵)↑'/'),((2 4-.×⍵⍺)/' '),'\'}¨⌽⍳⍵}¨N[⍋N←,⎕]

```

Previous version, which is shorter in characters (124) but uses more bytes when represented in UTF-8 (230, which would put it in second place):

```
M←' '⋄{⎕←⍵/⍨~⌽∧\⌽⍵=M}¨↓⊃{⍵{⍺=M:⍵⋄⍺}¨K↑⍺↑⍨-.5×(K←⍴⍵)+⍴⍺}/{Z⍪⊖⌽Z←↑(⊂(⍵/M),'-'/⍨2×⍵),⍵{('/'↑⍨-⍵),'\',⍨M/⍨2 4-.×⍵⍺}¨⌽⍳⍵}¨N[⍋N←,⎕]

```

Test:

```
      {⎕←(~⌽∧\⌽⍵=' ')/⍵}¨↓⊃{⍵{⍺=' ':⍵⋄⍺}¨K↑(-.5×(K←⍴⍵)+⍴⍺)↑⍺}/{Z⍪⌽⊖Z←↑(⊂(⍵/' '),(2×⍵)/'-'),⍵{((-⍵)↑'/'),((2 4-.×⍵⍺)/' '),'\'}¨⌽⍳⍵}¨N[⍋N←,⎕]
⎕:
      3 1 5 2
     ----------
    /          \
   /   ------   \
  /   / ---- \   \
 /   / / -- \ \   \
/   / / /  \ \ \   \
\   \ \ \  / / /   /
 \   \ \ -- / /   /
  \   \ ---- /   /
   \   ------   /
    \          /
     ----------

```
> 3 votes

# Answer
# Perl 5, 352 (349 bytes + 3 for `anE` flags)

This could probably be golfed down a lot more..

```
@b=sort{$a>$b}@F;map{$_<$j||($j=$_)}@b;$k=++$j;for(;$j--;){$z=$"x$j;for($e=$k;--$e>$j;){$z.=$e~~@b?'/ ':'  '} $z.=($j~~@b?'_':$")x(2*$j);$z.=$_~~@b?' \\':'  'for($j+1..$k-1);say$z}for(0..$k-2){$z=$"x$_;for($e=$k;--$e>$_;){$z.=($e-$k+1?$":'').($e~~@b?'\\':$")}$z.=(($_+1)~~@b?'_':$")x(2*$_+2);$z.=($_~~@b?'/':$").($_-$k+1?$":'')for($_+1..$k-1);say$z}

```

Ungolfed:

```
# sort list of side lengths
@b=sort{$a>$b}@F;
# set $k and $j to max side length + 1
map{$_<$j||($j=$_)}@b;$k=++$j;
for(;$j--;){
  $z=$"x$j;
  for($e=$k;--$e>$j;){$z.=$e~~@b?'/ ':'  '}
  $z.=($j~~@b?'_':$")x(2*$j);
  $z.=$_~~@b?' \\':'  'for($j+1..$k-1);
  say$z
}
for(0..$k-2){
  $z=$"x$_;
  for($e=$k;--$e>$_;){$z.=($e-$k+1?$":'').($e~~@b?'\\':$")}
  $z.=(($_+1)~~@b?'_':$")x(2*$_+2);
  $z.=($_~~@b?'/':$").($_-$k+1?$":'')for($_+1..$k-1);
  say$z
}

```

Example (`1 5 3 14`):

```
              ____________________________
             /                            \
            /                              \
           /                                \
          /                                  \
         /                                    \
        /                                      \
       /                                        \
      /                                          \
     /                 __________                 \
    /                 /          \                 \
   /                 /   ______   \                 \
  /                 /   /      \   \                 \
 /                 /   /   __   \   \                 \
/                 /   /   /  \   \   \                 \
\                 \   \   \__/   /   /                 /
 \                 \   \        /   /                 /
  \                 \   \______/   /                 /
   \                 \            /                 /
    \                 \__________/                 /
     \                                            /
      \                                          /
       \                                        /
        \                                      /
         \                                    /
          \                                  /
           \                                /
            \                              /
             \____________________________/

```
> 1 votes

# Answer
# C# - ~~388~~ 316 bytes

*Edit: Changed how it avoids printing trailing spaces and threw in some LINQ*

Simple program that takes command line arguments. It iterates through every possible char in each line of a rectangle defined by the maximum hexagon dimension and appends it to the current line, before trimming the lines and printing them successively (it produces the optional trailing new-line).

Golfed Code:

```
using System.Linq;class P{static void Main(string[]A){var I=A.Select(int.Parse);int m=I.Max(),i,j,y,x;for(j=m+1;j-->-m;){var r="";for(i=-2*m-1;++i<2*m-(y=j<0?-j-1:j);)r+="/\\_- "[(x=i<0?-i-1:i)>y&(x+=y)%2>0&x/2<m&&I.Contains(x/2+1)?(i^j)&1:x-y<(y=j<0?-j:j)&y<=m&I.Contains(y)?j<0?2:3:4];System.Console.WriteLine(r);}}}

```

Ungolfed code:

```
using System.Linq; // all important

class P
{
    static void Main(string[]A)
    {
        var I=A.Select(int.Parse); // create int array

        for(int m=I.Max(),j=m+1,i,y,x;j-->-m;) // for each line...
        {
            var r=""; // current line

            for(i=-2*m-1;++i<2*m-(y=j<0?-j-1:j);) // for each char...
                r+="/\\_- "[// append something to the current line
                (x=i<0?-i-1:i)>y&(x+=y)%2>0&x/2<m&&I.Contains(x/2+1)?
                    (i^j)&1: // slashes as appropriate - I can't work out why this bit works, but it seems to
                x-y<(y=j<0?-j:j)&y<=m&I.Contains(y)?
                    j<0?2:3: // _ or - if required
                4]; // otherwise a space

            System.Console.WriteLine(r); // print current line
        }
    }
}

```
> 1 votes

# Answer
# APL (Dyalog Classic), 151 bytes (93 with the classic APL encoding)

```
{a←0⍴⍨1 0+1 2×n←⌈/⍵⋄a[⊃,/i,¨¨⍵+⍵-1+i←⍳¨⍵]←1⋄a←(⊖⍪-)a⋄a[⊃,/(n+⍵,-⍵),¨¨,⍨i]←2⋄' /_\'[4|(⌽,-)a]}

```

Try it online!
> 0 votes

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


title: Design a One Instruction Set Computer!

text:
# Question
Title: Design a One Instruction Set Computer!
**Notice: I'm willing to give a bounty to any answer that I find interesting.**

Your challenge is to design a Turing-complete one instruction set computer (OISC):

> An OISC is an abstract machine that uses only one instruction – obviating the need for a machine language opcode. With a judicious choice for the single instruction and given infinite resources, an OISC is capable of being a universal computer in the same manner as traditional computers that have multiple instructions.

Here are some examples of single commands that make a Turing-complete OISC.

Rules:

### You must provide an interpretation or proof thereof

You must provide an interpreter for your language. This interpreter should only be restricted by memory/time (e.g. must have no user-imposed restrictions). If you do not provide an interpreter for your language (for whatever reason other than laziness) you must prove that it is possible for one to be written. An interpreter *must be possible*.

### You must prove its Turing-completeness

You must include a formal proof that your language is Turing-complete. A simple way to do this is by proving that it can interpret or have the same behavior as another Turing-complete language. The most basic language to interpret would be Brainf\**k.

For example, a normal language that has all the same commands as Brainf\**k (and the same lack of user-imposed memory restrictions) is Turing-complete because anything that can be implemented in Brainf\**k can be implemented in the language.

Here is a list of very simple-to-implement Turing-complete languages.

### Additional OISC requirements

* This OISC should only have one instruction - it cannot have multiple instructions with one of them making it Turing-complete.
* Your OISC may use any syntax you like. You should define in your answer what is instruction, what is data, and what is a no-op (e.g. whitespace). Be creative!
* Arguments do not just need to be integers. For example, /// is a beautiful example of a Turing-complete OISC.
* How and if input and output are taken and given are left up to you. Most OISCs implement I/O via specific memory locations, but there may be other ways to do so, and you are encouraged to find one.
* A valid answer must provide some example code in your OISC, either by including it in the post or linking to a simple challenge solved in the language.

### Voting

Voters, please remember not to upvote boring submissions. Examples:

* Lenguage-equivalents
* An implementation of an existing OISC (answerers, please create your own!)
* An "OISC" in which the first argument specifies a command to call (example)

However, you should upvote interesting, creative submissions, such as:

* An OISC based off of a mathematical equation
* A Turing-complete ZISC based on a neural network
* An OISC in which output I/O happens in other ways than certain memory locations

### Winning

As with , the answer with the most votes wins! Good luck!

# Answer
# XOISC

This OISC is based on Fokker's X-combinator which is defined as follows:

$$ X = \lambda f\ . f\ (\lambda g\ h\ x\ . g\ x\ (h\ x))\ (\lambda a\ b\ c\ . a) $$

If we acknowledge the fact that the SKI-calculus is Turing complete the above \\$X\\$-combinator is Turing complete as well. This is because \\$S\\$, \\$K\\$ and \\$I\\$ can be written in terms of \\$X\\$, like this:

$$ \begin{align} S &= X\ (X\ X) \\ K &= X\ X \\ I = S\ K\ K &= X\ (X\ X)\ (X\ X)\ (X\ X) \end{align} $$

## How XOISC works

Internally XOISC has an (initially empty) stack, from there the instruction taking \\$n\\$ as an argument does the following:

* Pop \\$n\\$ elements (functions \\$ f\_1 \dots f\_N\\$) from the stack, push \\$f\_1\ (f\_2\ (\dots (f\_N\ X) \dots ))\\$

Once there are no more instructions left XOISC will push all command-line arguments (if any) to the stack, for example:

$$ \[ \underbrace{s\_1, \dots,\ s\_M}\_{\text{stack before}} ,\ \underbrace{a\_1, \dots,\ a\_N}\_{\text{arguments}} \] $$

The final computation will be \\$(\dots ((\dots (s\_1\ s\_2) \dots)\ s\_M)\ a\_1) \dots) a\_N \\$.

---

Since the one instruction in XOISC takes only one argument (memory offset) there is no reason to even use a name for that instruction. So a valid source file will constitute solely of integers separated by newlines or whitespaces, like for example:

```
0 0 2 0 1 0 1

```

Try it online!

## Example

Let's take the above example (stack growing to the right):

$$ \begin{align} & \texttt{0} & \text{pop 0 and apply (ie. push single } X \text{)}: & \quad \[X\] \\ & \texttt{0} & \text{again simply push } X: & \quad \[X,\ X\] \\ & \texttt{2} & \text{pop 2 (} a,b \text{) and push } a\ (b\ X): & \quad \[X\ (X\ X)\] \\ & \texttt{0} & \text{simply push } X: & \quad \[X\ (X\ X),\ X\] \\ & \texttt{1} & \text{pop 1 (} a \text{) and push } a\ X: & \quad \[X\ (X\ X),\ X\ X\] \\ & \texttt{0} & \text{simply push } X: & \quad \[X\ (X\ X),\ X\ X,\ X\] \\ & \texttt{1} & \text{pop 1 (} a \text{) and push } a\ X: & \quad \[X\ (X\ X),\ X\ X,\ X\ X\] \end{align} $$

Finally evaluate the stack: \\$((X\ (X\ X))\ (X\ X))\ (X\ X)\\$ or with less parentheses \\$X\ (X\ X)\ (X\ X)\ (X\ X)\\$ which we recognize as the good old \\$S\ K\ K\\$ identity function.

## Turing completeness

### Proof idea

For XOISC to be Turing complete we need to be able to translate any (valid) interleaving of parentheses and \\$X\\$ combinators. This is possible because when popping, applying and pushing it does so in a right-associative manner (function application is left-associative).

To translate any such \\$X\\$ expression there is an easy way to do so: Always pop as many elements such that from the beginning of the current level of parentheses there will only be one element left.

As an example, the previously used expression: \\$((X\ (X\ X))\ (X\ X))\ (X\ X)\\$

* to get \\$X\\$, we simply need a `0`
* next we're in a new level of parentheses, so we again only need a `0`
* now two parentheses close, so we need to pop 2 elements: `2`
* again we're in a new level of parentheses, so we need a `0`
* two parentheses, close so again a `2`
* and the same again

So we end up with a different (yet semantically equivalent) XOISC-program:

`0 0 2 0 2 0 2` Try it online!

If we stay with this strategy we can easily transform any expression consisting of \\$X\\$ combinators to an XOISC program which only leaves a single function on the stack.

### Formal proof

Given that the SKI-calculus is Turing complete, we need to show two things:

1. the \\$X\\$-combinator is a basis for the SKI-calculus
2. XOISC is able to represent any expression formed with the \\$X\\$ combinator

The first part - proving the three equalities in the introduction - is very tedious and space consuming, it's also not very interesting. So instead of putting it in this post, you can find here*.

The second part can be proven by structural induction, though it's easier to prove a slightly stronger statement: Namely, for any expression formed by \\$X\\$-combinators there is a program that will leave that expression as a single expression on the stack:

There are two ways of constructing such an \\$X\\$ expression, either it's \\$X\\$ itself or it's \\$f\ g\\$ for some expressions \\$f\\$ and \\$g\\$:

The former one is trivial as `0` will leave \\$X\\$ on the stack as a single expression. Now we suppose that there are two programs (\\$\texttt{F}\_1 \dots \texttt{F}\_N\\$ and \\$\texttt{G}\_1 … \texttt{G}\_K\\$) that will leave \\$f\\$ and \\$g\\$ as a single expression on the stack and prove that the statement holds for \\$f\ g\\$ as well:

The program \\$\texttt{F}\_1 \dots \texttt{F}\_N\ \texttt{G}\_1 \dots \texttt{G}\_{K-1}\ (\texttt{G}\_K + 1)\\$ will first generate \\$f\\$ on the stack and then it will generate \\$g\\$ but instead of only popping parts of \\$g\\$ it will also pop \\$f\\$ and apply it, such that it leaves the single expression \\$f\ g\\$ on the stack. ∎

## Interpreter

### Inputs

Since the untyped lambda calculus requires us to define our own data types for everything we want and this is cumbersome the interpreter is aware of Church numerals \- this means when you supply inputs it will automatically transform numbers to their corresponding Church numeral.

As an example here's a program that multiplies two numbers: Try it online!

You can also supply functions as arguments by using De Bruijn indices, for example the `S` combinator `\\\(3 1 (2 1))` (or `λλλ(3 1 (2 1))`). However it also recognizes the `S`, `K`, `I` and of course `X` combinator.

### Output

By default the interpreter checks if the output encodes an integer, if it does it will output the corresponding number (in addition to the result). For convenience there's the `-b` flag which tells the interpreter to try matching a boolean instead (see the last example).

### Assembler

Of course any low-level language needs an assembler that converts a high-level language to it, you can simply use any input (see above) and translate it to a XOISC-program by using the `-a` flag, try it online!\**

---

* In case the link is down, there's a copy as HTML comment in this post.

\** This results in a program that tests for primality, try it online!
> 25 votes

# Answer
# Draw

Draw is an OISC acting on a 2D grid, marking squares in a manner similar to the Wang B-machine. However, to keep the language as simple and OISC-y as possible, all instructions (of which there are a grand total of one) mark the square just stepped on, and, in order to be able to halt, stepping on a marked square terminates the program.

The program consists of a sequence of lines containing a line identifier (arbitrary string not including # or whitespace), two integers (`x` and `y`) and two more line identifiers (`a` and `b`).

The program runs as follows:
Starting at the line identified as `start` with the pointer pointing to position (0, 0), move the pointer by the amount given by `x` and `y` and mark the square the pointer is now on (unless the square is already marked, in which case execution terminates). Then, jump to line `a` if at least one of the directly adjacent squares is also marked, and to line `b` otherwise.

Interpreters are encouraged to output the final result of the grid as some sort of image, canvas, etc.

## Turing-Completeness

Draw is Turing-complete as it is possible to compile a modified version (called Alternate) of a Minsky machine into the language.

Alternate acts similarly to a two-counter Minsky machine, but there is a large restriction placed on the commands: commands must alternate between targeting the first and second counter. To get around this modification, an additional command has been added: `nop`. This command doesn't change the targeted counter at all, which makes it possible to "pad" consecutive changes to one counter, satisfying the restriction outlined above. This also means that the register that is to be modified doesn't have to be given and, for any given instruction, can be directly inferred from the instructions from which execution can jump to it.

Example: this Minsky machine

```
1 inc A 2
2 inc A 3
3 dec A 3 4
4 halt

```

turns into this Alternate program:

```
1 inc 2
2 nop 3
3 inc 4
4 nop 5
5 dec 6 8
6 nop 5
7 halt
8 halt

```

This restriction is necessary due to the way that the eventual Draw program handles registers, which is to say that it doesn't differentiate between them at all. Instead, the Draw program simply copies the register that hasn't been changed by the preceding instruction, modifying it according to the instruction being executed.

Then, the Alternate program is directly translated into Draw as follows:

The program starts with this block.

```
start 0 0 a a
a 3 0 b b
b -3 1 c c
c 3 0 d d
d -3 2 e e
e 3 0 f f
f 3 -3 i1_a i1_a

```

`inc`, `dec` and `nop` are translated in almost the same way as each other. In all cases, there is no difference between changing the first or the second register (as explained above). Here is an increment, equivalent to `inc 2`:

```
i1_y 0 -2 i1_z i1_y
i1_z 3 -1 i1_a i1_a
i1_a -5 1 i1_b i1_b
i1_b 0 2 i1_c i1_c
i1_c 0 2 i1_d i1_e
i1_d 0 2 i1_d i1_f

i1_e 5 0 i2_z i2_y
i1_f 5 0 i2_z i2_y

```

Change the numbers in the `i1_x` parts to the index of the current instruction, and in the `i2_x` parts to the index of the next instruction to be executed.

The `nop` instruction can be translated as such:

```
i1_y 0 -2 i1_z i1_y
i1_z 3 -1 i1_a i1_a
i1_a -5 1 i1_b i1_b
i1_b 0 2 i1_c i1_c
i1_c 0 2 i1_d i1_e
i1_d 0 2 i1_d i1_f

i1_e 5 -2 i2_z i2_y
i1_f 5 -2 i2_z i2_y

```

This is a decrement:

```
i1_y 0 -2 i1_z i1_y
i1_z 3 -1 i1_a i1_a
i1_a -5 1 i1_b i1_b
i1_b 0 2 i1_c i1_c
i1_c 0 2 i1_d i1_e
i1_d 0 2 i1_d i1_f

i1_e 5 -2 i3_z i3_y
i1_f 5 -4 i2_z i2_y

```

`i3_x` refers to the instruction to be called if the counter is already 1.

Halt:

```
i1_y 0 0 0 0
i1_z 0 0 0 0

```

Change labels appropriately and simply chain everything together. Doing this for the example from above gives the Draw program in the repository from above.

## Interpreters

There are currently two interpreters, both written in Python. They can be found on Draw's GitHub repository.

1. **draw.py**: This interpreter is meant for the command line and takes the program source as an argument. After every step, it outputs the command that was executed and the location of the instruction pointer; after the program halts, it prints the number of marked cells.
2. **draw\_golly.py**: This version uses Golly for exactly the wrong purpose easier graphical output, taking the source via a popup box when starting the script. Golly can be a little finicky with Python, so make sure you have Python 2 installed (and don't mix 32-bit Golly with 64-bit Python or vice versa). Output is provided via Golly's builtin cell grid.

The following image is an example for output from the second interpreter. Running the example program in the repository gives this (or similar):
> 23 votes

# Answer
# -3

Here's the gist.

## Memory

Memory is a map of tapes, where the keys are strings and values are arbitrary-sized integers.

Additionally, there is a set of labels, where the program can jump to.

There is a stack, which contains the operands, which are strings.

There is an offset, which controls where in the memory's tapes it can access.

## The One Instruction

`-`. First, it pops a string `LABEL` off the stack. If that `LABEL` is undefined as a label, it defines the label, and clears the source of that label (i.e. where it was pushed from) and the current instruction. Otherwise, it performs the following calculation, using the top two values, `A` and `B`:

```
if mem[A] < mem[B]:
    jump to LABEL
if mem[A] != mem[B]:
    mem[A]--
else:
    mem[B]++

```

Note that if there are excess arguments or insufficient arguments, the program will error out, showing the program's state.

The offset can be modified by accessing the value of `.`.

## Example code

```
X-

i i X-
i i X-
i i X-
i i X-
i i X-
i i X-
i i X-

```

This sets variable `i` to `7`, by incrementing `7` times.

```
X-

i i X-
i i X-
i i X-
LOOP-
    a a X-
    a a X-
    j i LOOP-

```

This multiplies `i+1` by the constant `2`.

## Proof of Turing Completeness

Disregarding C++'s int sizes (that is, assuming they are infinite), -3 is Turing Complete by reduction to 3-cell brainfuck. I can disregard this size because there can be written an interpreter for -3 on a computer with infinite memory that has arbitrarily-large cells.

I also believe that any BCT can be written as a -3 program.
> 17 votes

---
Tags: popularity-contest, language-design
---


# Question
Title: Generate fractals from bit patterns in ASCII
**Overview**

Write a program that prints out simple fractal patterns given a bit pattern encoding the fractal, plus the per-generation scale factor of the fractal and number of generations.

**Explanation**

Here is an ASCII representation of the Sierpinski Carpet:

Generation 0:

```
#

```

Generation 1:

```
# # #
#   #
# # #

```

Generation 2:

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

```

Generation n+1 of the ASCII Sierpinski Carpet is made up of a 3x3 grid containing 8 copies of generation n, with the central element of the grid missing.

So, because it is defined using a 3x3 grid and gets 3 times bigger in width and height each generation, we can say it has a scale factor of 3.

We could define a bit pattern for the Sierpinski carpet by numbering the elements in the 3x3 grid from 0 to 8, top-to-bottom, left-to-right, and setting the corresponding bit of an integer if generation n+1 contains a copy of generation n at that grid position:

```
bit:       place value:   bit pattern:   bit value:

0 1 2      1    2    4    1 1 1          1    2    4
3 4 5      8   16   32    1 0 1          8    0   32
6 7 8      64 128  256    1 1 1          64 128  256

integer value = 1 + 2 + 4 + 8 + 32 + 64 + 128 + 256 = 495

```

For a scale factor of 2, the bit pattern would be arranged like this:

```
0 1
2 3

```

and so on.

Your task is to write a program that accepts a bit pattern in this form, a scale factor (e.g. 3 for the Sierpinski Carpet) and a generation number and outputs an ASCII fractal.

**Input**

Your program should accept 3 integers in the following order: a bit pattern, a scale factor (ranging from 2 to 5, inclusive) and a generation count (ranging from 0 to 5, inclusive).

You do not need to perform any input validation on these values and it's perfectly fine if the program works for values larger than the ranges specified.

The inputs can be passed in any form (tuples, comma/space-separated list, etc)

**Output**

The program should output a fractal made up of the `#` character followed by a space in positions where the fractal is defined, double-spaces where it is not, and a newline character at the end of each line, either printing them out or returning a string from a function.

**Examples**

Input:

```
495,3,3

```

Output (Sierpinski Carpet generation 3):

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

```

Input:

```
7,2,5

```

Output (Sierpinski Triangle):

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

```

Input:

```
325,3,3

```

Output (Cantor Dust):

```
#   #       #   #                   #   #       #   #

#   #       #   #                   #   #       #   #

#   #       #   #                   #   #       #   #

#   #       #   #                   #   #       #   #

#   #       #   #                   #   #       #   #

#   #       #   #                   #   #       #   #

#   #       #   #                   #   #       #   #

#   #       #   #                   #   #       #   #

```

Input

```
186,3,3

```

Output (Vicsek fractal):

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

```

Input:

```
279,3,3

```

Output (example of an asymmetrical fractal):

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

```

etc.

**Notes:**

* This is so the shortest answer in bytes wins
* Your program can be either a stand-alone or a function that is called with the 3 input parameters and returns (or prints) a string
* Generation 0 is defined as `#` (a `#` followed by a space) even for a bit pattern of 0.
* A trailing newline on the last line is optional but permitted, as is any amount of trailing white-space on each line.

# Answer
> 4 votes
# APL (Dyalog Unicode), 37 bytesSBCS

```
'# '{⊃⍪/,/⍺\⍤1⊂⍉⍪⍉⍵}⍣⎕⍨(2⍴⎕)⍴⌽⎕⊤⍨99⍴2
                              ⎕       ⍝ input the bit pattern
                               ⊤⍨99⍴2 ⍝ decode 99 binary digits from it
                                      ⍝  (53 is the limit for floating point)
                             ⌽        ⍝ reverse, least significant bit goes first
                          ⎕           ⍝ input the scale factor
                       (2⍴ )          ⍝ twice, to use as dimensions of a matrix
                            ⍴         ⍝ reshape bit pattern into such a matrix
                     ⎕                ⍝ input the number of generations
'# '{              }⍣ ⍨               ⍝ apply that many times, starting from '# '
               ⍉⍪⍉⍵                   ⍝ make sure the argument is a matrix
              ⊂                       ⍝ enclose
          ⍺\⍤1                        ⍝ expand using rows of bit-pattern matrix
                                      ⍝  (1 for identical copy, 0 for zeroed out)
     ⊃⍪/,/                            ⍝ concat all horizontally and vertically

```

Try it online!

# Answer
> 11 votes
# Common Lisp, ~~248~~ 242 bytes

```
(lambda(n r g &aux(s(expt r g)))(labels((f(g x y s)(or(= g 0)(#2=multiple-value-bind(q x)(floor x s)(#2#(p y)(floor y s)(if(logbitp(+ q(* p r))n)(f(1- g)x y(/ s r))))))))(#3=dotimes(y s)(#3#(x s)(princ(if(f g x y(/ s r))"# ""  ")))(terpri))))

```

## Ungolfed

```
(defun fractal (n r g &aux (s (expt r g)))
  (labels((f(g x y s)
            (or(= g 0)
               (multiple-value-bind (px x) (truncate x s)
                 (multiple-value-bind (py y) (truncate y s)
                   (and
                    (logbitp (+ px (* py r)) n)
                    (f (1- g) x y (/ s r))))))))
    (fresh-line)
    (dotimes(y s)
      (dotimes(x s)
        (princ
         (if (f g x y(/ s r))
             "# "
             "  ")))
      (terpri))))

```

## Explanation

* Input:
    + *N* is the encoded pattern
    + *R* is the size of the pattern
    + *G* is the generation
* The output is an implicit square matrix of length *S=R**G*
* We iterate over each row *y*, column *x* (nested `dotimes`) and compute whether each cell should be drawn (raycasting-like approach). This is done by recursively looking inside the fractal with the `f` auxiliary function.
* If the fractal at position *(x,y)* shall be drawn, print `"# "`, or else print `" "`. Of course we also print newlines at the end of each row.

For example, Sierpinsky's triangle is represented by `S=7` and `R=2`. At generation 3 the square size is 23=8. For each cell *(x,y)*, the following happen:

* `f` is called with *x*, *y*, *g* bound to 3 and *s* bound to 4 (8/2)
* We truncate *x* by *s*, in order to know if *x* belongs to the left or right side of the implicit matrix. `truncate` returns both the quotient and the remainder, which are bound respectively to *px* and *x* (we reuse the same symbol *x*, but this not a problem).
* The same goes for *y* which gives *py* and new *y*.
* In this example, *px* and *py* can be either 0 or 1 (because the pattern is a square of length 2). They identify where is *(x,y)* in the fractal's pattern: when the bit at position *py.R + px* of *N* is 0, *x* and *y* represent a position where nothing should be drawn.
* Otherwise, we must "zoom" into the corresponding part of the fractal and we call `f` recursively with the new bindings for *x* and *y*. Those are now the relative position inside the inner fractal. We pass *G-1* for the generation and *s/2* to represent the half-length of the fractal.
* The base case of the recursion is encountered when *G* is zero, in which case the current *(x,y)* position should be drawn.

## Example

```
(fractal 186 3 3)

                          #
                        # # #
                          #
                    #     #     #
                  # # # # # # # # #
                    #     #     #
                          #
                        # # #
                          #
        #                 #                 #
      # # #             # # #             # # #
        #                 #                 #
  #     #     #     #     #     #     #     #     #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
  #     #     #     #     #     #     #     #     #
        #                 #                 #
      # # #             # # #             # # #
        #                 #                 #
                          #
                        # # #
                          #
                    #     #     #
                  # # # # # # # # #
                    #     #     #
                          #
                        # # #
                          #

```

Computing the 8th generation of the Sierpinski Carpet using `(fractal 495 3 8)` takes 24.7 seconds and generates an output text file of 83 MB. I wrote a slightly modifed version which outputs an image. For the same parameters, the GIF file weights 1.5MB (same computation time):

Vicsek (click to see original size):

# Answer
> 5 votes
# Pyth, 38 bytes

```
VJ^UQvwjdm@" #".A@L_.[0^Q2jvz2+V*RQNdJ

```

Try it online: Regular Input / Test Suite

Explanation follows later.

# Answer
> 4 votes
# Ruby,154

Score is for the function only. Presented ungolfed below in test program. The only golfing I'm claiming at the moment is removal of comments and indents. I will golf later. At the moment, I'm having fun playing with the program.

The function takes six arguments, but on the initial call only the first 3 are provided per the spec. This causes the three remaining arguments to be set to default values, and in particular the string `a` where the output is stored is created and initialized to lines of spaces terminated by newlines. As a side effect the global variable `$w` is also created, indicating the number of symbols per line.

When the function calls itself recursively, it provides all six arguments, including the string `a` and the x and y coordinates of the top left corner of the next recursion

The rest of the program is pretty straightforward, as indicated in the comments.

```
#function
f=->b,s,g,x=0,y=0,a=(' '*(-1+2*$w=s**g)+'
')*$w{                                         #accept arguments, if x,y,a are not provided create them. $w = number of symbols per row
  v=s**g/s                                     #v=width of blocks for this recursion depth
  if g==0
    a[2*y*$w+2*x]=?#                           #if g==0 plot a #
  else                                         #else iterate s*s times through the bits of b, and recurse as necessary
    (s*s).times{|i|b>>i&1>0&&f.call(b,s,g-1,x+i%s*v,y+i/s*v,a)}
  end
  a
}

#test program (requires 3 input numbers separated by newlines)
b=gets.to_i
s=gets.to_i
g=gets.to_i
#get return value and output to stdout
puts f.call(b,s,g)

```

**Output**

Here's a set of fractals loosely based on the form of the letters of the word GOLF. More realistic letters could be achieved with larger bitmaps. As the last example shows, the most interesting fractals are discovered by accident.

```
63775,4,2 (G)

# # # # # # # # # # # # # # # #
#       #       #       #
#     # #     # #     # #     #
# # # # # # # # # # # # # # # #
# # # #
#
#     #
# # # #
# # # #                 # # # #
#                       #
#     #                 #     #
# # # #                 # # # #
# # # # # # # # # # # # # # # #
#       #       #       #
#     # #     # #     # #     #
# # # # # # # # # # # # # # # #

495,3,3 (O, sierpinski carpet)

# # # # # # # # # # # # # # # # # # # # # # # # # # #
#   # #   # #   # #   # #   # #   # #   # #   # #   #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # #       # # # # # #       # # # # # #       # # #
#   #       #   # #   #       #   # #   #       #   #
# # #       # # # # # #       # # # # # #       # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
#   # #   # #   # #   # #   # #   # #   # #   # #   #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # #                   # # # # # # # # #
#   # #   # #   #                   #   # #   # #   #
# # # # # # # # #                   # # # # # # # # #
# # #       # # #                   # # #       # # #
#   #       #   #                   #   #       #   #
# # #       # # #                   # # #       # # #
# # # # # # # # #                   # # # # # # # # #
#   # #   # #   #                   #   # #   # #   #
# # # # # # # # #                   # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
#   # #   # #   # #   # #   # #   # #   # #   # #   #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # #       # # # # # #       # # # # # #       # # #
#   #       #   # #   #       #   # #   #       #   #
# # #       # # # # # #       # # # # # #       # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
#   # #   # #   # #   # #   # #   # #   # #   # #   #
# # # # # # # # # # # # # # # # # # # # # # # # # # #

457,3,3 (L)

#
#
# # #
#
#
# # #
#     #     #
#     #     #
# # # # # # # # #
#
#
# # #
#
#
# # #
#     #     #
#     #     #
# # # # # # # # #
#                 #                 #
#                 #                 #
# # #             # # #             # # #
#                 #                 #
#                 #                 #
# # #             # # #             # # #
#     #     #     #     #     #     #     #     #
#     #     #     #     #     #     #     #     #
# # # # # # # # # # # # # # # # # # # # # # # # # # #

7967,4,2 (F)

# # # # # # # # # # # # # # # #
#       #       #       #
# # # # # # # # # # # # # # # #
#       #       #       #
# # # #
#
# # # #
#
# # # # # # # # # # # # # # # #
#       #       #       #
# # # # # # # # # # # # # # # #
#       #       #       #
# # # #
#
# # # #
#

1879,3,3 (skull and crossbones discovered by accident)

# # # # # # # # # # # # # # # # # # # # # # # # # # #
  #     #     #     #     #     #     #     #     #
#   # #   # #   # #   # #   # #   # #   # #   # #   #
      # # #             # # #             # # #
        #                 #                 #
      #   #             #   #             #   #
# # #       # # # # # #       # # # # # #       # # #
  #           #     #           #     #           #
#   #       #   # #   #       #   # #   #       #   #
                  # # # # # # # # #
                    #     #     #
                  #   # #   # #   #
                        # # #
                          #
                        #   #
                  # # #       # # #
                    #           #
                  #   #       #   #
# # # # # # # # #                   # # # # # # # # #
  #     #     #                       #     #     #
#   # #   # #   #                   #   # #   # #   #
      # # #                               # # #
        #                                   #
      #   #                               #   #
# # #       # # #                   # # #       # # #
  #           #                       #           #
#   #       #   #                   #   #       #   #

```

# Answer
> 3 votes
# CJam, 45

```
3aaq~@2b2$_*0e[W%@/a*{ffff*:.+:.+}/' ff+Sf*N*

```

Implementation of my first idea. Try it online

Basically, it starts with a 1\*1 matrix containing 3 (the difference between '#' and ' '), then repeatedly multiplies each number in the matrix with the bit pattern (0/1 matrix), and combines the resulting matrices into one bigger matrix. At the end, it adds a space to each number, and joins with spaces and newlines.

**2nd idea, 49**

```
q~@2bW%2$/z@@m*_,\_m*:z@f{3@@f{\~@==*}~' +}/Sf*N*

```

Try it online

This generates all the coordinates of the output matrix as arrays of \<generation count\> pairs of numbers smaller than the scale factor (all such combinations), then for each pair of numbers it gets the corresponding bit from the pattern, and for each coordinate array it multiplies the bits and multiplies by 3. The final processing is the same.

There's probably room for more golfing.

# Answer
> 2 votes
# C, 316 bytes

```
main(a,_,b,s,g,i,w,o,z,x,y)char**_,*o;{b=atoi(_[1]);s=atoi(_[2]);g=atoi(_[3]);w=1;for(i=0;i<g;++i){w*=s;}o=malloc(w*w);for(i=0;i<w*w;++i)o[i]=35;z=w/s;while(z){for(y=0;y<w;++y)for(x=0;x<w;++x)if(!((b>>((y/z)%s*s+(x/z)%s))&1))o[y*w+x]=32;z/=s;}for(y=0;y<w;++y){for(x=0;x<w;++x)printf("%c ",o[y*w+x]);printf("\n");}}

```

### Un-golfed:

```
#include <stdio.h>

int main(int argc, char *argv[])
{
    int bitpattern;
    int scale;
    int generation;

    bitpattern = atoi(argv[1]);
    scale = atoi(argv[2]);
    generation = atoi(argv[3]);

    int i;
    int width = 1;
    for (i=0; i<generation; ++i) {width*=scale;}

    char *out=malloc(width*width);

    for (i=0; i<width*width; ++i) out[i]='#';

    int blocksize = width/scale;
    for (i=0; i<generation; ++i) {
        int x,y;
        for (y=0; y<width; ++y) {
            for (x=0; x<width; ++x) {
                int localX = x/blocksize;
                localX %= scale;
                int localY = y/blocksize;
                localY %= scale;
                int localPos = localY*scale+localX;
                if (!((bitpattern>>localPos)&1))out[y*width+x]=' ';
            }
        }
        blocksize/=scale;
    }

    int x,y;
    for (y=0; y<width; ++y) {
        for (x=0; x<width; ++x)
            printf("%c ",out[y*width+x]);
        printf("\n");
    }
    return 0;
}

```

# Answer
> 2 votes
# Scala ~~293~~ 299

```
(e:Int,s:Int,g:Int)=>{def b(x:Int,y:Int)=(1<<x*s+y&e)>0;def f(n:Int):Seq[Seq[Char]]=if(n<1)Seq(Seq('#'))else if(n<2)Seq.tabulate(s,s)((i,j)=>if(b(i,j))'#'else' ')else{val k=f(n-1);val t=k.size;Seq.tabulate(t*s,t*s)((i,j)=>if(b(i/t,j/t))k(i%t)(j%t)else' ')};f(g).map(_.mkString(" ")).mkString(" \n")}

```

ungolfed:

```
//create an anonymous function
(encoded: Int, size: Int, generation: Int) => {

  // method will return true if coords (x,y) should be drawn as '#'
  def isBlackInPattern(x: Int, y: Int): Boolean = (1 << x * size + y & encoded) > 0

  // recurse until generation is 1
  def fillRecursively(gen: Int): Seq[Seq[Char]] = {

    // this is just to satisfy OP requirements.
    // if the stopping condition were generation = 1,
    // I could have spared this line...
    if(gen < 1) Seq(Seq('#'))

    //actual stopping condition (generation 1).
    // fill a matrix of characters with spaces
    // and hashes acording to the pattern.
    else if(gen < 2) Seq.tabulate(size, size)((i, j) =>
      if (isBlackInPattern(i,j)) '#'
      else ' '
    )

    // recurse, and use previously created fractals to fill
    // the current generation according to the `isBlackInPattern` condition
    else {
      val previousGeneration = fillRecursively(gen-1)
      val previousSize = previousGeneration.size
      // create the current matrix and fill it
      Seq.tabulate(previousSize*size,previousSize*size)((i,j)=>
        if(isBlackInPattern(i/previousSize,j/previousSize))
          previousGeneration(i%t)(j%t)
        else ' '
      )
    }
  }
  // call to recursive function and format matrix of characters to string
  fillRecursively(generation).map(_.mkString(" ")).mkString(" \n")
}

```

examples:

```
val f = (e:Int,s:Int,g:Int)=>{def b(x:Int,y:Int)=(1<<x*s+y&e)>0;def f(n:Int):Seq[Seq[Char]]=if(n<1)Seq(Seq('#'))else if(n<2)Seq.tabulate(s,s)((i,j)=>if(b(i,j))'#'else' ')else{val k=f(n-1);val t=k.size;Seq.tabulate(t*s,t*s)((i,j)=>if(b(i/t,j/t))k(i%t)(j%t)else' ')};f(g).map(_.mkString(" ")).mkString(" \n")}
f: (Int, Int, Int) => String = <function3>

scala> println(f(495,3,3))
# # # # # # # # # # # # # # # # # # # # # # # # # # #
#   # #   # #   # #   # #   # #   # #   # #   # #   #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # #       # # # # # #       # # # # # #       # # #
#   #       #   # #   #       #   # #   #       #   #
# # #       # # # # # #       # # # # # #       # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
#   # #   # #   # #   # #   # #   # #   # #   # #   #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # #                   # # # # # # # # #
#   # #   # #   #                   #   # #   # #   #
# # # # # # # # #                   # # # # # # # # #
# # #       # # #                   # # #       # # #
#   #       #   #                   #   #       #   #
# # #       # # #                   # # #       # # #
# # # # # # # # #                   # # # # # # # # #
#   # #   # #   #                   #   # #   # #   #
# # # # # # # # #                   # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
#   # #   # #   # #   # #   # #   # #   # #   # #   #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # #       # # # # # #       # # # # # #       # # #
#   #       #   # #   #       #   # #   #       #   #
# # #       # # # # # #       # # # # # #       # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
#   # #   # #   # #   # #   # #   # #   # #   # #   #
# # # # # # # # # # # # # # # # # # # # # # # # # # #

scala> println(f(7,2,5))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #
# #     # #     # #     # #     # #     # #     # #     # #
#       #       #       #       #       #       #       #
# # # #         # # # #         # # # #         # # # #
#   #           #   #           #   #           #   #
# #             # #             # #             # #
#               #               #               #
# # # # # # # #                 # # # # # # # #
#   #   #   #                   #   #   #   #
# #     # #                     # #     # #
#       #                       #       #
# # # #                         # # # #
#   #                           #   #
# #                             # #
#                               #
# # # # # # # # # # # # # # # #
#   #   #   #   #   #   #   #
# #     # #     # #     # #
#       #       #       #
# # # #         # # # #
#   #           #   #
# #             # #
#               #
# # # # # # # #
#   #   #   #
# #     # #
#       #
# # # #
#   #
# #
#

scala> println(f(18157905,5,2))
#       #                               #       #
  #   #                                   #   #
    #                                       #
  #   #                                   #   #
#       #                               #       #
          #       #           #       #
            #   #               #   #
              #                   #
            #   #               #   #
          #       #           #       #
                    #       #
                      #   #
                        #
                      #   #
                    #       #
          #       #           #       #
            #   #               #   #
              #                   #
            #   #               #   #
          #       #           #       #
#       #                               #       #
  #   #                                   #   #
    #                                       #
  #   #                                   #   #
#       #                               #       #

```

first cut, probably can be golfed a bit further...

# Answer
> 2 votes
# Matlab, 115 bytes

The Kronecker `kron` product makes everything much easier:

```
function f(p,f,g);z=nan(f);z(:)=de2bi(p,f*f);x=3;for k=1:g;x=kron(x,z);end;disp([reshape([x;0*x],f^g,2*f^g)+32,''])

```

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

```

# Answer
> 2 votes
**C, 158 bytes**

```
f(p,s,g,h,i,j,c){for(j=1;g--;j*=s);for(h=j;h;){h--;for(i=j;i;){i--;for(c=35,g=j/s;g;g/=s)c=!((p>>((h/g)%s*s+(i/g)%s))&1)?32:c;printf("%c ",c);}printf("\n");}}

```

# Answer
> 1 votes
# K5, 70 bytes

It's a start:

```
{,/'("  ";"# ")$[z;(z-1){,/'+,/'+x@y}[(0*t;t)]/t:(2#y)#|(25#2)\x;,,1]}

```

In action:

```
{,/'("  ";"# ")$[z;(z-1){,/'+,/'+x@y}[(0*t;t)]/t:(2#y)#|(25#2)\x;,,1]}[186;3]'!4
(,"# "
 ("  #   "
  "# # # "
  "  #   ")
 ("        #         "
  "      # # #       "
  "        #         "
  "  #     #     #   "
  "# # # # # # # # # "
  "  #     #     #   "
  "        #         "
  "      # # #       "
  "        #         ")
 ("                          #                           "
  "                        # # #                         "
  "                          #                           "
  "                    #     #     #                     "
  "                  # # # # # # # # #                   "
  "                    #     #     #                     "
  "                          #                           "
  "                        # # #                         "
  "                          #                           "
  "        #                 #                 #         "
  "      # # #             # # #             # # #       "
  "        #                 #                 #         "
  "  #     #     #     #     #     #     #     #     #   "
  "# # # # # # # # # # # # # # # # # # # # # # # # # # # "
  "  #     #     #     #     #     #     #     #     #   "
  "        #                 #                 #         "
  "      # # #             # # #             # # #       "
  "        #                 #                 #         "
  "                          #                           "
  "                        # # #                         "
  "                          #                           "
  "                    #     #     #                     "
  "                  # # # # # # # # #                   "
  "                    #     #     #                     "
  "                          #                           "
  "                        # # #                         "
  "                          #                           "))

```

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


title: Simulate a model neuron

text:
# Question
Title: Simulate a model neuron
An Izhikevich neuron is a simple yet quite effective model of a biological neuron, designed for use in a discrete time-stepping simulation. In this golfing challenge, you will be implementing this model.

**Parameters**

This model involves only 7 variables organized into 2 differential equations, compared to the dozens of parameters of a physiologically accurate model.

* `v` and `u` are the two state variables of the neuron. Here, `v` is the "fast" variable representing the cell potential over time, and `u` is the "slow" variable representing certain membrane properties. The `v` variable is the most important one, as this is the output of the simulation.
* `a`, `b`, `c`, and `d` are fixed constants that describe the properties of the neuron. Different types of neurons have different constants, depending on the desired behavior. Notably, `c` is the reset potential, which is the membrane potential the cell returns to after spiking.
* `I` represents the input current to the neuron. In network simulations, this will change over time, but for our purposes we will treat `I` as a fixed constant.

**The Model**

This model has very simple pseudocode. First, we take the constant values of `abcd` and use them to initialize `v` and `u`:

```
v = c
u = b * c

```

Next, we loop through the simulation code as many times as desired. Each iteration represents 1 millisecond of time.

```
for 1..t:
  if v >= 30:    # reset after a spike
    v = c
    u = u + d
  v += 0.04*v^2 + 5*v + 140 - u + I
  u += a * (b*v - u)
  print v

```

Certain real-world implementations include additional steps for numerical accuracy, but we aren't including those here.

**Input**

As input, your program/function should take the values of `a`, `b`, `c`, `d`, `I`, and `t` (the number of time steps to simulate). Once set, none of these parameters will be changing during our simple simulation. The order of input does *not* matter: you can specify the order in which your program takes these parameters.

**Output**

Output will be a list of numbers representing the cell's membrane potential (given by variable `v`) over the course of the simulation. The list can be in any appropriate format.

You have the choice of whether to include the 0th value of the simulation (the initial configuration before any time has passed) in your output. For example, for an input of `0.02 0.2 -50 2 10 6` (for `a b c d I t`), an output of either

```
-50
-40
-16.04
73.876224
-42.667044096
-25.8262335380956
29.0355029192068

```

or

```
-40
-16.04
73.876224
-42.667044096
-25.8262335380956
29.0355029192068

```

is acceptable.

Your values do *not* have to be exactly the same as those above, depending on how your language handles floats.

**Reference Implementation**

Here is a TIO implementation I wrote in Perl to demonstrate the model. The parameters are that of a "chattering" neuron from the paper linked above, and this serves as a demonstration of how this model is able to recreate some of the more complex properties of neurons, such as alternating between states of high and low activity. If you look at the output, you can see where the neuron immediately spikes several times, but then waits a while before spiking several more times (despite the cell input voltage `I` being constant the whole time).

# Answer
# , ~~110~~ 99 bytes

Anonymous function that takes 6 arguments. Nothing fancy, just a straightforward port of the reference implementation. The updating of `u`, `v`, and the printing of `v` have all been combined into a single line, thanks to the fact that R's `print` returns the value that is being printed, so you can use it in assignment. Many thanks to Giuseppe for saving 11 bytes!

```
pryr::f({v=c;u=b*c;for(i in 1:t){if(v>=30){v=c;u=u+d}
u=a*b*(v=print((.04*v+6)*v+140+I-u))-a*u+u}})

```

Try it online!
> 6 votes

# Answer
# Clean, ~~150~~ ~~145~~ ~~140~~ 138 bytes

```
import StdEnv
$a b c d i t=map snd(iterate(\(u,v)#(w,n)=if(30.0<v)(c,u+d)(v,u)
#y=0.04*w*w+6.0*w+140.0-n+i
=(a*b*y-a*n+n,y))(b*c,c))%(0,t)

```

Try it online!

Defines the function `$ :: Real Real Real Real Real Int -> [Real]`, implementing the algorithm as described in the OP, starting from the 0th term.
> 4 votes

# Answer
# Python 2, 100 bytes

```
a,b,c,d,I,t=input();v=c;u=b*c
exec"if v>=30:v=c;u+=d\nv=v*v/25+6*v+140-u+I;u+=a*(b*v-u);print v\n"*t

```

Try it online!

Saved 2 bytes thanks to user71546.
> 3 votes

# Answer
# JavaScript (Node.js), ~~107~~ ... ~~103~~ 101 bytes

Contributed by @apsillers

```
(a,b,c,d,I,t)=>[...Array(t)].map(_=>(v<30||(v=c,u+=d),v=v*(v/25+6)+140-u+I,u+=a*(b*v-u),v),u=b*(v=c))

```

Try it online!

**Original Approach: ~~105~~ 103 bytes. -1 byte Thanks Arnauld, and -2 bytes Thanks @Kamoroso94.**

```
(a,b,c,d,I,t)=>{for(u=b*(v=c);t--;){v<30||(v=c,u+=d);v=v*(v/25+6)+140-u+I;u+=a*(b*v-u);console.log(v)}}

```

Try it online!

**Or if popping alerts is OK, then ~~101~~ ... ~~99~~ 97 bytes (-1 byte Thanks Arnauld, -2 bytes Thanks @Kamoroso94):**

```
(a,b,c,d,I,t)=>{for(u=b*(v=c);t--;){v<30||(v=c,u+=d);v=v*(v/25+6)+140-u+I;u+=a*(b*v-u);alert(v)}}

```

```
var u, v;
var f =
(a,b,c,d,I,t)=>{for(u=b*(v=c);t--;){v<30||(v=c,u+=d);v=v*(v/25+6)+140-u+I;u+=a*(b*v-u);alert(v)}}

function run() {
 f(...["a", "b", "c", "d", "I", "t"].map(x => document.getElementById(x).value * 1));
}
```

```
a = <input id="a" value="0.02"><br>
b = <input id="b" value="0.2"><br>
c = <input id="c" value="-50"><br>
d = <input id="d" value="2"><br>
I = <input id="I" value="10"><br>
t = <input id="t" value="6"><br>
<input type="button" value="Run" onclick="run()">
```
> 3 votes

# Answer
# Ruby, 94 bytes

```
->a,b,c,d,i,t{v=c
u=b*c
t.times{v>=30?(v=c;u+=d):0
v+=0.04*v**2+5*v+140-u+i
u+=a*(b*v-u)
p v}}

```

Try it online!

Another straightforward port of the reference implementation, a lambda accepting 6 arguments.
> 2 votes

# Answer
# Haskell, ~~112~~ 111 bytes

```
(a#b)c d i t|let r(v,u)|v>=30=r(c,u+d)|p<-0.04*v^2+6*v+140-u+i=(p,u+a*(b*p-u))=fst<$>take t(iterate r$r(c,b*c))

```

Try it online!

Does not output the zero case. Assumes that `c` is never `>=30` since that wouldn't make sense.

~~Never thought I'd have to use a `where` clause in a code golf but there are just too many variables.~~

EDIT: Thanks @Lynn for taking off a byte! I forgot that you can put `let` statements in guards. Sure kills the readability though
> 2 votes

# Answer
# Element, 81 bytes

```
_a;_b;_3:b~*u;_d;_I;_'[3:\.04*5+*140+u~-+I~++4:\
.`30<!b~*u~-+a~*u~+[d~+]u;[#2:]]

```

Try it online!, Esolangs page

**Explanation:**

```
_a;_b;_3:b~*u;_d;_I;_'[ ... ]

```

This part of the program takes input. It stores constants `a`, `b`, `d`, and `I` into variables. The input for `c` is never stored in a variable, but rather remains on the main stack throughout execution. Three copies are made: one on top for initializing `u`, one in the middle to serve as the initial `v`, and one on the bottom to serve as the constant `c`. The input for `t` is thrown immediately onto the control stack to serve as the basis of the FOR loop (the `[...]`) surrounding the rest of the program.

```
3:\.04*5+*140+u~-+I~++4:

```

This part of the program takes the current value of `v` and calculates the new value, and then four copies of the new `v` value are made.

```
\
.`

```

The first copy of `v` has a newline appended and is printed.

```
30<!

```

The second copy of `v` is used to test if the neuron has spiked. The result of this test is put on the control stack for later use.

```
b~*u~-+a~*u~+

```

This part computes the "delta `u`", meaning the amount to add to `u`.

```
[d~+]

```

This IF block adds `d` to the above sum if the neuron is spiking. This combines what would normally be two assignments into a single assignment.

```
u;

```

This stores the updated value of `u`.

```
[#2:]

```

This IF block is a continuation of the above IF block. If the neuron is spiking, delete the current value of `v` (which is now on the top of the main stack), and replace it with a duplicate of `c` (which has been on the bottom of the main stack this entire time).

And that's basically all there is to it. One minor note is that this thing leaks memory: it takes an extra `"#` in there to delete the top of the control stack (the evaluated IF condition) after each loop iteration.

Although I wouldn't call Element the most graceful golfing language, this challenge does allow me to showcase an interesting feature: due to the division between the main stack and control stack, I can take an IF statement and split the condition and body into multiple parts, interlaced with unconditional code.
> 1 votes

# Answer
# MATLAB, 111 bytes

```
function z(a,b,c,d,I,t)
v=c;u=b*c;for i=1:t if v>=30 v=c;u=u+d;end
v=.04*v^2+6*v+140-u+I
u=u+a*(b*v-u);
end
end

```

Pretty simple implementation, can probably be further improved.
> 0 votes

---
Tags: code-golf, simulation
---


title: Flattened Spiral Permutation Index

text:
# Question
Title: Flattened Spiral Permutation Index
## Context

Consider square matrices with `n` columns and rows containing the first `n^2` (i.e. `n` squared) positive integers, where `n` is odd. The elements of the matrices are arranged such that the integers `1` through `n^2` are placed sequentially in a counterclockwise spiral starting at the center and initially moving to the left. Call these matrices `M(n)`

For `n=1` this simply gives the one element matrix `M(1)=[[1]]`.

`M(3)` is the matrix

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

```

`M(5)` is the matrix

```
25 24 23 22 21
10  9  8  7 20
11  2  1  6 19
12  3  4  5 18
13 14 15 16 17

```

and `M(7)` is the matrix

```
49 48 47 46 45 44 43
26 25 24 23 22 21 42
27 10  9  8  7 20 41
28 11  2  1  6 19 40
29 12  3  4  5 18 39
30 13 14 15 16 17 38
31 32 33 34 35 36 37

```

Now consider flattening this matrix into a list/array by concatenating its rows starting from the top and moving down. Call these lists `L(n)`. `L(3)`, `L(5)` and `L(7)` are represented below, with their elements delimited by spaces.

```
9 8 7 2 1 6 3 4 5     (n=3)
25 24 23 22 21 10 9 8 7 20 11 2 1 6 19 12 3 4 5 18 13 14 15 16 17    (n=5)
49 48 47 46 45 44 43 26 25 24 23 22 21 42 27 10 9 8 7 20 41 28 11 2 1 6 19 40 29 12 3 4 5 18 39 30 13 14 15 16 17 38 31 32 33 34 35 36 37    (n=7)

```

We can find the index `i(n)` of `L(n)` in a lexicographically sorted list of permutations of `L(n)`. In Jelly, the `Œ¿` atom gives this index for the list it acts on.

## Challenge

Your challenge is to take an positive odd integer `n` as input and output the index `i(n)`.

The first few values are

```
n  i(n)
-------
1  1
3  362299
5  15511208759089364438087641
7  608281864033718930841258106553056047013696596030153750700912081

```

Note that `i(n)` ~= `(n^2)!`. This is not on OEIS.

This is code golf per language, so achieve this in the fewest bytes possible.

Sandbox post.

# Answer
> 3 votes
# Jelly, ~~21~~ 19 bytes

```
-;,N$ṁx"RFḣNṙ-+\ỤŒ¿

```

Try it online!

Based on the method from a J article on volutes.

## Explanation

```
-;,N$ṁx"RFḣNṙ-+\ỤŒ¿  Main link. Input: integer n
-;                   Prepend -1. [-1, n]
  ,N$                Pair with its negated value. [[-1, n], [1, -n]]
     ṁ               Mold it to length n.
        R            Range. [1, 2, ..., n]
      x"             Vectorized copy each value that many times.
         F           Flatten
           N         Negate n
          ḣ          Head. Select all but the last n values.
            ṙ-       Rotate left by -1 (right by 1).
              +\     Cumulative sum.
                Ụ    Grade up.
                 Œ¿  Permutation index.

```

# Answer
> 2 votes
# J, ~~48~~ 38 Bytes

-10 bytes thanks to @miles !

```
[:A.@/:_1+/\@|.(2#1+i.)#&}:+:$_1,],1,-

```

Old:

```
3 :'A.,(,~|.@(>:@i.@#+{:)@{.)@|:@|.^:(+:<:y),.1'

```

Note that the result is 0-indexed, so `i(1) = 0` and `i(5) = 15511208759089364438087640`

### Explanation (old):

```
3 :'                                           ' | Explicit verb definition
                                            ,.1  | Make 1 into a 2d array
                                     (+:<:y)     | 4*n, where y = 2*n + 1
                                   ^:            | Repeat 4*n times
                              |:@|.              | Clockwise rotation
       (                    )@                   | Monadic Hook:
             (          )@{.                     | To the first row, apply...
                      {:                         | The last and largest item
                     +                           | Added to...
              >:@i.@#                            | The list 1, 2, ..., n; where n is the row length
          |.@                                    | Reverse
        ,~                                       | Append to the top of the array
      ,                                          | Ravel
    A.                                           | Permutation index

```

Making the spiral could be quicker, but the orientation would get messed up.

I don't know how J is optimizing this, but it only takes `0.000414` seconds to calculate for `n=7` (on a fresh J console session).

# Answer
> 1 votes
# MATL, ~~16~~ ~~15~~ 14 bytes

```
lYL!PletY@wXmf

```

Fails for test cases larger than `3` due to both floating-point inaccuracies and memory limitations.

Try it online!

### Explanation

```
lYL    % Implicit input n. Spiral matrix of that side length
!P     % Transpose, flip vertically. This is needed to match the orientation
       % of columns in the spiral with that of rows in the challenge text
le     % Convert to a row, reading in column-major order (down, then across)
t      % Duplicate
Y@     % All permutations, arranged as rows of a matrix, in lexicographical
       % order
w      % Swap
Xm     % Row membership: gives a column vector containing true / false,
       % where true indicates that the corresponding row in the first input
       % matches a row from the second output. In this case the second input
       % consists of a single row
f      % Find: gives indices of nonzeros. Implicit display

```

# Answer
> 1 votes
# Jelly, 27 bytes

```
ZUðẎṀ+ṚW;⁸µJ
1WÇẎ⁸²¤ḟ$$¿ẎŒ¿

```

Try it online!

---
Tags: code-golf, sequence, permutations, matrix
---