What is Toothpick Sequence?

According to Wikipedia

In geometry, the toothpick sequence is a sequence of 2-dimensional patterns which can be formed by repeatedly adding line segments ("toothpicks") to the previous pattern in the sequence.

The first stage of the design is a single "toothpick", or line segment. Each stage after the first is formed by taking the previous design and, for every exposed toothpick end, placing another toothpick centered at a right angle on that end.

This process results in a pattern of growth in which the number of segments at stage n oscillates with a fractal pattern between 0.45n2 and 0.67n2. If T(n) denotes the number of segments at stage n, then values of n for which T(n)/n2 is near its maximum occur when n is near a power of two, while the values for which it is near its minimum occur near numbers that are approximately 1.43 times a power of two. The structure of stages in the toothpick sequence often resemble the T-square fractal, or the arrangement of cells in the Ulam–Warburton cellular automaton.

All of the bounded regions surrounded by toothpicks in the pattern, but not themselves crossed by toothpicks, must be squares or rectangles. It has been conjectured that every open rectangle in the toothpick pattern (that is, a rectangle that is completely surrounded by toothpicks, but has no toothpick crossing its interior) has side lengths and areas that are powers of two, with one of the side lengths being at most two.


You must make a program or function that take input from STDIN, function argument, or commandline argument and make a tootpick fractal at that stage. Leading and trailing newline is prohibited except if it is unavoidable. Bounding box must be at minimum, including leading and trailing space. For inital line, we make two \ diagonal in space. The input is guaranteed to be less than two thousand. At least one line have non-space character. Trailing space is allowed.

Test Cases


  / /\   
\/\/\ \ \ 
 \ \ \/\/\
    \/ /  
up vote 6 down vote accepted

CJam, 99 93 bytes

This got rather long...

"\ "_W%]{{Sf+W%z}4*2ew{2fewz{_sa"\//\\"4S**4/^_,3={:.e>W%2/\}&;}%z{\)a@.e>+}:Ff*}%{F}*}q~(*N*

Test it here. If you want to test larger inputs, like the 89 on Wikipedia, Dennis's TryItOnline uses the much faster Java interpreter under the hood and can handle inputs like that in a few seconds.

I'm sure there is a lot of room for improvement, and I'll add an explanation once I'm happier with the score...

Here is the output for N = 13:

          / /\            
        \/\/\ \ \         
         \ \/\/\/\        
          / /\ \          
    \    /\/\ \     \     
    /\  /  \/\/\    /\    
   /\  /\  /\/  \ \/\     
  / /\/ /\/ /\  /\ \/\    
\/\/\/\/\/\/\ \/\ \/\ \ \ 
 \ \ \/\ \/\ \/\/\/\/\/\/\
    \/\ \/  \/ /\/ /\/ /  
     \/\ \  /\/  \/  \/   
    \/    \/\/\  /  \/    
     \     \ \/\/    \    
          \ \/ /          
        \/\/\/\ \         
         \ \ \/\/\        
            \/ /          

For my own reference when golfing this further, some other ideas:

"\ "_W%]{{Sf+W%z}4*2few2ew::.{+_a"\//\\"4S**4/^_,3={:.e>W%\}&;2/}:z{\)a@.e>+}ff*{\)a@..e>+}*}ri(*N*
"\ "_W%]{{Sf+W%z}4*2ew{2fewz{_sa"\//\\"4S**4/^_,3={:.e>W%2/\}&;}%{.{\)a@.e>+}}*}%{\)a@.e>+}*}q~(*N*

JavaScript (ES6), 263 bytes

n=>(o=(o=[..." ".repeat(n*2)]).map(_=>o.map(_=>s=c=" ")),(g=a=>s++<n&&g(q=[],a.map(p=>o[p[4]][p[3]]==c&&(o[y=p[1]][x=p[0]]=o[y-1][(b=+p[2])?x-1:x+1]="/\\"[b],q.push([x,++y,!b,b?x+1:x-1,y],[b?x-=2:x+=2,y-2,!b,x,y-3])))))([[n,n,1,n,n]]),o.map(r=>r.join``).join`


n=>(                           // n = desired stage

  o=                           // o = output grid
                               //     [ [ "\\", " " ], [ " ", "\\" ], etc... ]
    (o=[..." ".repeat(n*2)])   // create an array the size of the grid
    .map(_=>o.map(_=>          // loop over it and return the output grid
      s=                       // s = current stage (" " acts the same as 0)
        c=                     // c = blank character
          " "                  // initialise each element to " "

  (g=                          // g = compute stage function
    a=>                        // a = positions to place toothpicks
                               //     [ x, y, isBackslash, checkX, checkY ]
      s++<n&&                  // do nothing if we have reached the desired stage
      g(q=[],                  // q = positions for the next stage's toothpicks
        a.map(p=>              // p = current potential toothpick position
          o[p[4]][p[3]]==c&&(  // check the position to make sure it is clear

            o[y=p[1]][x=p[0]]= // place bottom toothpick, x/y = position x/y
            o[y-1][            // place top toothpick
              (b=+p[2])        // b = isBackslash
              ?x-1:x+1         // top toothpick x depends on direction
            ]="/\\"[b],        // set the location to the appropriate character

            // Add the next toothpick positions
  )([[n,n,1,n,n]]),            // place the initial toothpicks
` // return the grid converted to a string


Stages: <input type="number" oninput='result.innerHTML=(

n=>(o=(o=[..." ".repeat(n*2)]).map(_=>o.map(_=>s=c=" ")),(g=a=>s++<n&&g(q=[],a.map(p=>o[p[4]][p[3]]==c&&(o[y=p[1]][x=p[0]]=o[y-1][(b=+p[2])?x-1:x+1]="/\\"[b],q.push([x,++y,!b,b?x+1:x-1,y],[b?x-=2:x+=2,y-2,!b,x,y-3])))))([[n,n,1,n,n]]),o.map(r=>r.join``).join`

)(+this.value)' /><pre id="result"></pre>

Ruby, 151 bytes

Golfed version uses only one loop, j, with i and k calculated on the fly.

s=(' '*m+$/)*m

Ungolfed in test program

This version uses 2 nested loops.

A rarely used builtin is sum which returns a crude checksum by adding all the bytes of an ascii string.

  m=n*2                                       #calculate grid height / width            
  s=(' '*m+$/)*m                              #fill grid with spaces, separated by newlines
  l=m*m+m                                     #calculate length of string s
  s[l/2+n]=s[l/2-n-2]=?\\                     #draw the first toothpick
  (n-1).times{|j|                             #iterate n-1 times
    l.times{|i|                               #for each character in the string
      (s[i]+s[i-m-2+2*k=j%2]).sum==124-k*45&& #if checksum of current character + character diagonally above indicates the end of a toothpick
         s[i-m-1]=s[i-1+2*k]="/\\"[k]         #draw another toothpick at the end
s}                                            #return value = s

puts f[gets.to_i]

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.