title: Horizontal graph of word length

text:
# Question
Title: Horizontal graph of word length
**Input**

A list of words separated by any number of spaces.

**Output**

A horizontal ASCII art graph, where the n-th line is composed by as many asterisks (`*`) as the n-th word is long.

**Example usage**

The `>` signals user input, you should not input it when testing the program.

```
> This is an example histogram of word length
****
**
**
*******
*********
**
****
******

```

---

```
> a aa aaa aaaa aaaaa
*
**
***
****
*****

```

---

```
> double space  example
******
*****
*******

```

**Reference implementation**

In case of doubt over the specification, the output of your program should match exactly that of the below program under all inputs.

```
puts gets.chomp.split.map{|word| '*' * word.length}.join("\n")

```

# Answer
# Retina, 5 + 3 = 8 bytes

```
 +
\n
.
*

```

Every line goes in its own file, so I've added 1 byte for each additional file. Also, the `\n` should be replaced with an actual newline.

Each pair of lines is a pattern-replacement pair.  `+` matches one or more spaces and replaces it with a newline. `.` matches any character *except* a newline, and it replaces that with a `*`. This is applied globally, so every character is replaced with a `*`.
> 24 votes

# Answer
# Pyth, 9 bytes

```
jm*ld\*cz

```

Explanation:

```
jm*ld\*cz
       cz    chop input on whitespace
 m           map to
   ld        length of the segment
  *  \*      number of asterisks
j            joined on newlines

```
> 11 votes

# Answer
# CJam, 10 bytes

```
r{,'**Nr}h

```

**How it works**:

```
r{     r}h         e# This do-while loop basically reads all the whitespace separated tokens
                   e# from input. It separates the tokens on running lengths of whitespace
  ,                e# Take the length of the token
   '**             e# Get a string of that many '*' characters
      N            e# Print a new line

```

Try it online here
> 10 votes

# Answer
## Python 3, 43 bytes:

```
for w in input().split():print('*'*len(w))

```

Thanks to @BetaDecay for pointing out a syntax error.

Sample run:

```
> This is an example histogram of word length
****
**
**
*******
*********
**
****
******

```

(The string below is entered as a literal, rather than as text)

```
> 'example\twith\nweird\rwhite   space'
*******
****
*****
**********

```

### Bonus: vertical histogram

Thanks to @Caridorc for pointing out my error that made the bonuses have 1 to many rows.

```
l=[len(x)for x in input().split()]
for i in range(len(l)-1,0,-1):print(''.join(['*'if j>=i else' 'for j in l]))

```

Demo:

```
> This is an example histogram of word length
   **
   **  *
   **  *
*  ** **
*  ** **
********
********

```

Bonus: vertical histogram (upside down)

```
l=[len(x)for x in input().split()]
for i in range(len(l)-1):print(''.join(['*'if j>i else' 'for j in l]))

```

Demo:

```
> This is an example histogram of word length
********
********
*  ** **
*  ** **
   **  *
   **  *
   **

```
> 10 votes

# Answer
## R - 33

```
write(gsub(".","*",scan(,"")),"")

```

where

* `scan(,"")` reads from stdin and splits on white-space into a character vector.
* `gsub(".", "*", ...)` replaces all characters into `*`.
* `write(..., "")` prints to stdout with "\n" as the default separator.
> 10 votes

# Answer
# R, 38 bytes (with some help in comments)

```
cat(gsub(" +|$","\n",gsub("\\S","*",x)))

```

**How it works**

* `gsub` replaces all no-spaces with `*`
* second `gsub` adds `\n` (newline) to the end of each element
* `cat` prints accordingly

**Demo**
> 6 votes

# Answer
# Perl 5 + `-p040l012`, 7 bytes

```
s/./*/g

```

Try it online!

---

# Perl 5 \+ `-p`, 15 bytes

```
y/ /
/s;s/./*/g

```

Try it online!
> 6 votes

# Answer
# Javascript ES6

## Function, 46 chars

```
f=s=>s.replace(/\S/g,'*').replace(/\s+/g,'\n')

```

## Program, 55 chars

```
alert(prompt().replace(/\S/g,"*").replace(/\s+/g,"\n"))

```
> 6 votes

# Answer
## \>\<\>, ~~38~~ 37 Bytes

Curse you double space case \*shakes fish\*.

```
<v&0
 >i:84*=?v0(?;67*o&1&
 \ &0o?&a/

```

You can try it online (all you need to do is give input through the field near the bottom and then hit the `Give` button). Suggestions for further golfing are always welcome, especially ideas to remove those wasteful spaces in front of the second and third lines.

If you were allowed to print an additional newline for extra spaces, the code could be a whopping **27 bytes**:

```
>i:84*=?v0(?;67*o
^     oa<

```

---

## Explanation

Note: the order of the explanation will correspond to the pointer's location (so if the code is explained out of what one would consider order, it is because it is the order in which the pointer executes it).

**Line 1:**

```
<v&0
<      redirects flow leftward
   0   pushes 0 onto the stack
  &    pops 0 and puts it in the register
 v     redirects flow downward

```

**Line 2:**

```
>i:84*=?v0(?;67*o&1&
>                     redirects flow leftward
 i:                   pushes input and then duplicates it
   84*                pushes 32 (the space character numerically)
      =?v             pops 32 and input and redirects flow downward if they're equal
         0(?;         pops input and terminates if input is less than 0*
             67*o     pushes 42 (asterisk) and prints it
                 &1&  pushes register value and then puts 1 in the register

*in ><>, the command i returns -1 if no input is given

```

**Line 3:**

N.B. This line goes in reverse, so read right to left.

```
 ^ &0o?&a<
         <  redirects flow leftward
        a   pushes 10 (newline) onto the stack
     o?&    prints a newline if the register is not 0
   &0       sets the register to 0
 ^          redirects flow upwards (back to the second line)

```

Basically, the program test to make sure the input (which is read one character at a time) is not a space and then prints an asterisk. It terminates if there is no input (the input value is -1). To make sure it doesn't print additional newlines, it uses the register value, which it either sets to 0 or 1. Because of the way I set it up, it doesn't care about the extraneous values pushed onto the stack (e.g. the value of the register when it sets it to `1` after printing an asterisk); they remain on the stack when the program terminates but do nothing.

I know it might be a bit confusing since I used `84*` and `67*` instead of `" "` and `"*"` respectively, but that was because I didn't feel like putting strings in the program for whatever reason.
> 6 votes

# Answer
# Gema, ~~11~~ 9 characters

```
 =\n
?=\*

```

Sample run:

```
bash-4.3$ gema ' =\n;?=\*' <<< 'This is an example histogram of word length'
****
**
**
*******
*********
**
****
******

bash-4.3$ gema ' =\n;?=\*' <<< 'a aa aaa aaaa aaaaa'
*
**
***
****
*****

bash-4.3$ gema ' =\n;?=\*' <<< 'double space  example'
******
*****
*******

```
> 5 votes

# Answer
# PHP 5.3, ~~55~~ ~~53~~ ~~51~~ 50 bytes

```
<?for(;$i<strlen($a);){echo$a{$i++}!=' '?'*':"
";}

```

**Usage:**
Call the Script and define a global variable ($a)
`php -d error_reporting=0 script.php?a="This is an example histogram of word length"`
**Output:**

```
****
**
**
*******
*********
**
****
******

```
> 5 votes

# Answer
# Java, 102 bytes

```
class R{public static void main(String[]a){for(String s:a)System.out.println(s.replaceAll(".","*"));}}

```
> 4 votes

# Answer
# Haskell, 31 bytes

```
putStr.unlines.map(>>"*").words

```

Usage example:

```
Main> putStr.unlines.map(>>"*").words $ "This is an example histogram of word length"
****
**
**
*******
*********
**
****
******

```
> 4 votes

# Answer
# CJam, 11 bytes

Competing for second place in CJam after @Optimizer found a clever 10 byte solution. This is a straightforward 11 byte solution:

```
lS%:,'*f*N*

```

Try it online

Alternate solution that uses a loop instead of the two maps, also 11 bytes:

```
lS%{,'**N}/

```

Explanation for first solution:

```
l     Get input.
S%    Split at spaces.
:,    Apply length operator to each word.
'*f*  Map each length to corresponding repetitions of '*.
N*    Join with newlines.

```
> 4 votes

# Answer
# JavaScript (ES6), 37

```
f=s=>s.replace(/./g,m=>m<"!"?`
`:'*')

```

Shorter version using only one `replace`.
> 4 votes

# Answer
# J, 10 bytes

```
   '*'$~$&>;:'This is an example histogram of word length'
****
**
**
*******
*********
**
****
******

```

Bonus: vertical (12 bytes)

```
   |:'*'$~$&>;:'This is an example histogram of word length'
********
********
*  ** **
*  ** **
   **  *
   **  *
   **
    *
    *

```

Bonus: flipped vertical (14 bytes)

```
   |.|:'*'$~$&>;:'This is an example histogram of word length'
    *
    *
   **
   **  *
   **  *
*  ** **
*  ** **
********
********

```
> 4 votes

# Answer
# Python 3, 72 bytes

A nice one liner :)

```
print(''.join(map(lambda x:"*"*len(x)+"\n"*int(x!=""),input().split())))

```

### Output:

```
>>> print(''.join(map(lambda x:"*"*len(x)+"\n"*int(x!=""),input().split())))
Hello world  how are you?
*****
*****
***
***
****

```

There's a trailing newline here. If you want it without, you've got to add 5 bytes:

```
print(''.join(map(lambda x:"*"*len(x)+"\n"*int(x!=""),input().split()))[:-1])

```
> 3 votes

# Answer
# Javascript (ES6)

New solution (39 bytes):

```
s=>[...s].map(c=>c==' '?`
`:'*').join``

```

Regex solution (42 bytes):

```
s=>s.replace(/\S/g,"*").replace(/ +/g,`
`)

```

Non-regex solution (71 bytes):

```
s=>s.split(" ").map(v=>"*".repeat(v.length)).filter(a=>a!="").join(`
`)

```

These solutions define anonymous functions. Assign them to variables or call them like so:

```
(s=>s.replace(/\S/g,"*").replace(/ +/g,`
`))("[your string here]")

(s=>s.split(" ").map(v=>"*".repeat(v.length)).filter(a=>a!="").join(`
`))("[your string here]")

```
> 3 votes

# Answer
# Julia, 50 bytes

```
s->print(join(["*"^length(w)for w=split(s)],"\n"))

```

This creates an unnamed function that takes a string as input and prints to STDOUT.

Ungolfed:

```
function f(s::String)
    # Construct a vector of horizontal bars
    bars = ["*"^length(w) for w in split(s)]

    # Join the bars with newlines
    j = join(bars, "\n")

    # Print the result to STDOUT
    print(j)
end

```
> 3 votes

# Answer
## Matlab / Octave, 75 bytes

Using an anonymous function:

```
@(s)char(arrayfun(@(n)repmat('*',1,n),diff([0 find([s 32]==32)])-1,'un',0))

```

Thanks to Hoki for spotting a mistake which prevented the last word from being detected.

Example use (Matlab):

```
>> @(s)char(arrayfun(@(n)repmat('*',1,n),diff([0 find([s 32]==32)])-1,'un',0)) % define function
ans =
    @(s)char(arrayfun(@(n)repmat('*',1,n),diff([0,find([s,32]==32)])-1,'un',0))
>> ans('This is an example histogram of word length') % call function
ans =
****
**
**
*******
*********
**
****
******

```

Or try it online (Octave).
> 3 votes

# Answer
# PowerShell, 35 31 Bytes

Pretty competitive for a change. Go go gadget unary operators. I also keep forgetting that parens on some functions, like the `-split` and `-replace` used here, are optional.

```
%{$_-split"\s+"-replace".","*"}

```

Called via pipeline input (equivalent to stdin for PowerShell):

```
PS C:\Tools\Scripts\golfing> "a aa aaa" | %{$_-split"\s+"-replace".","*"}
*
**
***

```

As a bonus, if we can instead use command-line arguments, we can get down to **20 Bytes** and have something that works both with and without a single-string as input:

```
$args-replace".","*"

PS C:\Tools\Scripts\golfing> .\horizontal-graph-word-length.ps1 "double space  example"
******
*****
*******

PS C:\Tools\Scripts\golfing> .\horizontal-graph-word-length.ps1 double space  example
******
*****
*******

```
> 3 votes

# Answer
## JavaScript (ES5)

### Program, 54 chars

```
alert(prompt().replace(/\S/g,'*').replace(/ +/g,'\n'))

```

### Function, 60 chars

```
function(i){return i.replace(/\S/g,'*').replace(/ +/g,'\n')}

```

Example usage:

```
var h=function(i){return i.replace(/\S/g,'*').replace(/ +/g,'\n')},
d=document,g=d.getElementById.bind(d),i=g('i'),o=g('o')
i.onchange=function(){o.textContent=h(i.value)}
```

```
<input id="i"/>
<pre id="o"></pre>
```
> 3 votes

# Answer
## Matlab - 54 bytes

```
s=input('');o=repmat('*',1,numel(s));o(s==32)=char(10)

```

---

This runs from the console, will take a string in input from `stdin` and will output the horizontal word graph in `stdout`:

*Exemple:*

```
>> s=input('');o=repmat('*',1,numel(s));o(s==32)=char(10)
'This is an example histogram of word length'
o =
****
**
**
*******
*********
**
****
******

```

Or we could try to make some fancy shapes:

```
>> s=input('');o=repmat('*',1,numel(s));o(s==32)=char(10)
'a aa aaa aaaaaa aaaaaaaaaa aaaaaaaaaaa aaaaaaaaaa aaaaaa aaa aa a aa aaa aaaaaa aaaaaaaaaa'
o =
*
**
***
******
**********
***********
**********
******
***
**
*
**
***
******
**********

```
> 3 votes

# Answer
# SWI-Prolog, 40 bytes

```
a([A|T]):-(A=32,nl;put(42)),(T=[];a(T)).

```

Called with code strings, e.g. `a(`This is an example histogram of word length`).`
> 2 votes

# Answer
## STATA, 72 bytes

```
di _r(a)
token "$a"
while ("`1'")!=""{
di _d(`=length("`1'")')"*"
ma s
}

```

Ungolfed

```
display _request(a) //get input via prompt
tokenize "$a" //split a by spaces into the variables 1,2,...
while ("`1'")!=""{ //while the first variable is not empty
display _dup(`=length("`1'")')"*" //display "*" duplicated for every character in variable 1.
macro shift //move variable 2 to 1, 3 to 2, etc.
}

```

Note that this code does not work in the online interpreter and requires the non-free proprietary STATA interpreter.
> 2 votes

# Answer
# C++14, 107 106 bytes

```
#include<iostream>
main(){std::string s;for(;std::cin>>s;){for(char c:s)std::cout<<'*';std::cout<<'\n';}}

```
> 2 votes

# Answer
# O, 22 bytes

```
i' /rl{e{'.'*%p}{;}?}d

```

## Explanation

```
i                         Read the user input
 ' /r                     Split on spaces and reverse
     l{             }d    For each element
       e           ?      If it's not empty
        {'.'*%            Replace every char with an asterick
              p}          And print it
                {;}       Else, just pop it off the stack

```
> 2 votes

# Answer
# K5, 31 bytes

```
`0:{(#x)#"*"}'f@&0<#:'f:" "\0:`

```
> 2 votes

# Answer
# Beam, 92 Bytes

This isn't a competitive answer at all and really quite late, but I've been playing around with Beam a bit lately and wanted to see if I could get it to do this. Finally got some success:)

```
'''''''>`++++++)v
vgLsP-(---`<''P'<
>rnp+v
  >Sv>++v
    (>`v+
    H^ )+
^Sp`@p'<+
^  @++++<

```

```
var ITERS_PER_SEC = 100000;
var TIMEOUT_SECS = 50;
var ERROR_INTERRUPT = "Interrupted by user";
var ERROR_TIMEOUT = "Maximum iterations exceeded";
var ERROR_LOSTINSPACE = "Beam is lost in space";

var code, store, beam, ip_x, ip_y, dir, input_ptr, mem;
var input, timeout, width, iterations, running;

function clear_output() {
document.getElementById("output").value = "";
document.getElementById("stderr").innerHTML = "";
}

function stop() {
running = false;
document.getElementById("run").disabled = false;
document.getElementById("stop").disabled = true;
document.getElementById("clear").disabled = false;
document.getElementById("timeout").disabled = false;
}

function interrupt() {
error(ERROR_INTERRUPT);
}

function error(msg) {
document.getElementById("stderr").innerHTML = msg;
stop();
}

function run() {
clear_output();
document.getElementById("run").disabled = true;
document.getElementById("stop").disabled = false;
document.getElementById("clear").disabled = true;
document.getElementById("input").disabled = false;
document.getElementById("timeout").disabled = false;

code = document.getElementById("code").value;
input = document.getElementById("input").value;
timeout = document.getElementById("timeout").checked;

code = code.split("\n");
width = 0;
for (var i = 0; i < code.length; ++i){
 if (code[i].length > width){
  width = code[i].length;
 }
}
console.log(code);
console.log(width);

running = true;
dir = 0;
ip_x = 0;
ip_y = 0;
input_ptr = 0;
beam = 0;
store = 0;
mem = [];

input = input.split("").map(function (s) {
  return s.charCodeAt(0);
 });

iterations = 0;

beam_iter();
}

function beam_iter() {
while (running) {
 var inst;
 try {
  inst = code[ip_y][ip_x];
 }
 catch(err) {
  inst = "";
 }
 switch (inst) {
  case ">":
   dir = 0;
   break;
  case "<":
   dir = 1;
   break;
  case "^":
   dir = 2;
   break;
  case "v":
   dir = 3;
   break;
  case "+":
   ++beam;
   break;
  case "-":
   --beam;
   break;
  case "@":
   document.getElementById("output").value += String.fromCharCode(beam);
   break;
  case ":":
   document.getElementById("output").value += beam+"\n";
   break;
  case "/":
   switch (dir) {
    case 0:
     dir = 2;
     break;
    case 1:
     dir = 3;
     break;
    case 2:
     dir = 0;
     break;
    case 3:
     dir = 1;
     break;
   }
  case "\\":
   switch (dir) {
    case 0:
     dir = 3;
     break;
    case 1:
     dir = 2;
     break;
    case 2:
     dir = 1;
     break;
    case 3:
     dir = 0;
     break;
   }
   break;
  case "!":
   if (beam != 0) {
    switch (dir) {
    case 0:
     dir = 1;
     break;
    case 1:
     dir = 0;
     break;
    case 2:
     dir = 3;
     break;
    case 3:
     dir = 2;
     break;
    }
   }
   break;
  case "?":
   if (beam == 0) {
    switch (dir) {
    case 0:
     dir = 1;
     break;
    case 1:
     dir = 0;
     break;
    case 2:
     dir = 3;
     break;
    case 3:
     dir = 2;
     break;
    }
   }
   break;
  case "|":
   switch (dir) {
   case 0:
    dir = 1;
    break;
   case 1:
    dir = 0;
    break;
   }
   break;
  case "_":
   switch (dir) {
   case 0:
    dir = 1;
    break;
   case 1:
    dir = 0;
    break;
   }
   break;
  case "H":
   stop();
   break;
  case "S":
   store = beam;
   break;
  case "L":
   beam = store;
   break;
  case "s":
   mem[beam] = store;
   break;
  case "g":
   store = mem[beam];
   break;
  case "P":
   mem[store] = beam;
   break;
  case "p":
   beam = mem[store];
   break;
  case "u":
   if (beam != store) {
    dir = 2;
   }
   break;
  case "n":
   if (beam != store) {
    dir = 3;
   }
   break;
  case "`":
   --store;
   break;
  case "'":
   ++store;
   break;
  case ")":
   if (store != 0) {
    dir = 1;
   }
   break;
  case "(":
   if (store != 0) {
    dir = 0;
   }
   break;
  case "r":
   if (input_ptr >= input.length) {
    beam = 0;
   } else
   {
    beam = input[input_ptr];
    ++input_ptr;
   }
   break;
  }
 // Move instruction pointer
 switch (dir) {
  case 0:
   ip_x++;
   break;
  case 1:
   ip_x--;
   break;
  case 2:
   ip_y--;
   break;
  case 3:
   ip_y++;
   break;
 }
 if (running && (ip_x < 0 || ip_y < 0 || ip_x >= width || ip_y >= code.length)) {
  error(ERROR_LOSTINSPACE);
 }
 ++iterations;
 if (iterations > ITERS_PER_SEC * TIMEOUT_SECS) {
  error(ERROR_TIMEOUT);
 }
}
}
```

```
<div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;">Code:
    <br>
    <textarea id="code" rows="4" style="overflow:scroll;overflow-x:hidden;width:90%;">'''''''>`++++++)v
vgLsP-(---`<''P'<
>rnp+v
  >Sv>++v
    (>`v+
    H^ )+
^Sp`@p'<+
^  @++++<
 </textarea>
    <br>Input:
    <br>
    <textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;">This is an example histogram of word length</textarea>
    <p>Timeout:
        <input id="timeout" type="checkbox" checked="checked">
        <br>
        <br>
        <input id="run" type="button" value="Run" onclick="run()">
        <input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="disabled">
        <input id="clear" type="button" value="Clear" onclick="clear_output()">  <span id="stderr" style="color:red"></span>
    </p>Output:
    <br>
    <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea>
</div>
```
> 2 votes

# Answer
# Vyxal `j`, 7 bytes

```
⌈';vL×*

```

Try it Online!

Vertical, 17 bytes

```
⌈';vL:G$×*v↲ÞTṘvṅ

```

Try it Online!

Vertical flipped, 16 bytes

```
⌈';vL:G$×*v↲ÞTvṅ

```

Try it Online!
> 2 votes

# Answer
# AWK

```
 awk '{for(i=1;i<=NF;i++){while(k++<length($i)){printf "*"};k=0;print ""}}'

```

examples

```
 echo "this is programming" | awk '{for(i=1;i<=NF;i++){while(k++<length($i)){printf "*"};k=0;print ""}}'

```

output:-

```
****
**
***********

```
> 1 votes

# Answer
# Bash - 60 26 bytes

new solution (thanks manatwork):

```
for w;{ echo "${w//?/*}";}

```

old solution:

```
for w;do for((i=1;i<=${#w};i++));do printf \*;done;echo;done

```

---

```
~ $ ./l This is an example histogram of word length
****
**
**
*******
*********
**
****
******

```

The only part that might deserve an explanation is `${#w}`: it returns the length of the string `w`.
> 1 votes

# Answer
# sed - 20 bytes

```
s/[^ ]/*/g;s/ +/\n/g

```

---

```
~ $ sed -re 's/[^ ]/*/g;s/ +/\n/g' <<< 'This is an example histogram of word   length'
****
**
**
*******
*********
**
****
******

```
> 1 votes

# Answer
# Ruby, 29 bytes

```
puts gets.gsub(/\S/,?*).split

```
> 1 votes

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


title: Draw an ASCII Checkerboard

text:
# Question
Title: Draw an ASCII Checkerboard
## Summary

Inspired by the recent popularity of ASCII art challenges, this challenge's purpose is to draw an ASCII checkerboard, like one on which Chess can be played.

Write a program that takes a positive integer `n` as an argument, in `stdin`, or as user input, and output an checkerboard with `n`x`n` squares, along with a border that is 1 character thick.

Each square should be 2x2 characters. The squares should follow the normal alternating white-black (white first, as in top-left corner) pattern of a checkerboard. White squares should be made out of space () characters, and black squares should be made out of pound (`#`) characters.

The border should be made out of dashes (`-`) with a plus (`+`) on the border or perpendicular point of a square.

**Input**

Positive integer in representing the number of squares (dimensions in squares) to draw in the checkerboard, with each square being 2x2 characters.

## Example Results

`n=2`

```
+--+--+
|  |##|
|  |##|
+--+--+
|##|  |
|##|  |
+--+--+

```

`n=3`

```
+--+--+--+
|  |##|  |
|  |##|  |
+--+--+--+
|##|  |##|
|##|  |##|
+--+--+--+
|  |##|  |
|  |##|  |
+--+--+--+

```

`n=4`

```
+--+--+--+--+
|  |##|  |##|
|  |##|  |##|
+--+--+--+--+
|##|  |##|  |
|##|  |##|  |
+--+--+--+--+
|  |##|  |##|
|  |##|  |##|
+--+--+--+--+
|##|  |##|  |
|##|  |##|  |
+--+--+--+--+

```

... and so on.

---

## Notes

* Trailing spaces and new lines are acceptable.
* You may write either an entire program or a function.
* No leading spaces.
* Your program should display correct results for n=15.
* For less-known esoteric languages and similar, provide a link to the language.
* `n=0` should produce `+`. (optional, but highly recommended and encouraged.)
* **Shortest code in bytes wins, as this is code golf.**

# Answer
> 16 votes
# J, 24 bytes

An anonymous function:

```
2 2&$&.>@(' #'{~2|+/~@i.)

```

Usage:

```
   f =: 2 2&$&.>@(' #'{~2|+/~@i.)
   f 4
+--+--+--+--+
|  |##|  |##|
|  |##|  |##|
+--+--+--+--+
|##|  |##|  |
|##|  |##|  |
+--+--+--+--+
|  |##|  |##|
|  |##|  |##|
+--+--+--+--+
|##|  |##|  |
|##|  |##|  |
+--+--+--+--+

```

# Answer
> 9 votes
## Python 2, 79

```
N=3*input()+1
for i in range(N):print('+||- #- #+||-# -# '*N)[3**i%7/2%3:3*N:3]

```

For each row, selects one of the patterns

```
+--+--+--+--+--+
|  |##|  |##|  |
|##|  |##|  |##|

```

and prints `3*n+1` characters from it. The pattern is chosen by repeating its first 6 characters, selected with the string interleaving trick, which also serves to extract a snippet of the correct length.

The correct pattern is selected based the value of the row index `i` modulo 6 by an arithmetic expression `3**i%7/2%3` that gives the repeating pattern \[0,1,1,0,2,2\]. I found it using the fact that `x**i%7` has period `6`, then trying different values of `x` and different postprocessing to get the right pattern.

# Answer
> 8 votes
# CJam, ~~43~~ 42 bytes

```
ri3*)_2m*{_3f%:!2b\3f/:+2%(e|"#|-+ "=}%/N*

```

Try it online.

Each coordinate is mapped to a char, e.g. the top left corner is `(0, 0) -> "+"`. Specifically, we calculate

```
[(y%3 == 0)*2 + (x%3 == 0)] or [(x//3 + y//3) % 2 - 1]

```

and index into the string `"#|-+ "` accordingly.

# Answer
> 8 votes
# Pyth, 37

```
VJh*3Qsm@?+\|*2@" #"+/N3/d3%N3"+--"dJ

```

Rather hacked together, but short.

Demonstration.

# Answer
> 5 votes
# Retina, 106 bytes

```
1
$_0$_x
1(?=1*0)
+--
1(?=1*x)
s
(0s.*?0)s
$1o
(s\D*?)s
$1o
s
|
o
|##
\D*?x
$0$0
0
+n
x
|n
(.*?n).*
$0$1

```

Takes input as unary (based on this meta discussion).

Each line should go to its own file and `n` should be changed to newline in the files. This is impractical but you can run the code as is, as one file, with the `-s` flag, keeping the `n` markers. You can change the `n`'s to newlines in the output for readability if you wish. E.g.:

```
> echo -n 111|retina -s checkerboard|tr n '\n'
+--+--+--+
|  |##|  |
|  |##|  |
+--+--+--+
|##|  |##|
|##|  |##|
+--+--+--+
|  |##|  |
|  |##|  |
+--+--+--+

```

Further golfing and some explanation comes later.

# Answer
> 3 votes
# JavaScript (ES6), 117

```
n=>Array(n*3+1).fill("+--".repeat(n)+"+").map((v,i)=>v.replace(/./g,(k,x)=>i%3?"|  |##|  "[x%6+(i%6>2)*3]:k)).join`
`

```

Snippet:

```
<input type="range" min=2 max=15 step=1 value=1 id="i" oninput="o.textContent=f(this.value)"><pre id="o"></pre><script>function f(n){ return Array.apply(0,Array(n*3+1)).map(function(){return "+--".repeat(n)+"+"}).map(function(v,i){ return v.replace(/./g,function(k,x) { return i%3?"|  |##|  "[x%6+(i%6>2)*3]:k}) }).join("\n") };o.textContent=f(2)</script>
```

Anonymous function. Starts with a full array of `+--+--+--...` lines, and on appropriate lines, replaces the `+` for `|` and `-` for  or `#` as appropriate.

The expression that decides the replacement character, `"| |##| "[x%6+(i%6>2)*3]`, could probably be golfed further, but I've found that using a longer, redundant string saves more characters than a complex calculation.

# Answer
> 2 votes
# CJam, 59 bytes

This .. is .. too .. long ..

```
ri:I," #"f=2f*_I({__sff^_}*]'|I)*f.\2/Nf*'+I)*"--"*aI)*.\N*

```

Try it online here

# Answer
> 2 votes
# Python 3, ~~114 108~~ 100

```
def f(n):
 for i in range(3*n+1):print(("|##|  "*n+"|")[::i//3%2*2-1][:3*n+1]if i%3 else"+--"*n+"+")

```

---

---

## Previous solutions

### 108

```
def f(n):
 for i in range(3*n+1):
  a=("|##|  "*n+"|")[::i//3%2*2-1][:3*n+1];print(a if i%3 else"+--"*n+"+")

```

### 114

```
def f(n):a="+--"*n+"+\n";b="|  |##"*n+"|";print(a+a.join(([(b[:3*n+1]+"\n")*2,(b[::-1][:3*n+1]+"\n")*2]*n)[:n])+a)

```

### 118 (not submitted)

```
def f(n):
 for i in range(3*n+1):print((("|##|  "*n)[:3*n+1]if i//3%2 else("|  |##"*n)[:3*n+1])if i%3 else"+--"*n+"+")

```

# Answer
> 2 votes
## CoffeeScript with ES6, 106 bytes

```
f=(n,y=z='+--'[r='repeat'](n)+'+\n')->y+=('|##|  '[r](n).substr(i%2*3,n*3)+'|\n')[r](2)+z for i in[1..n];y

```

---

## JavaScript (ES6), 111 bytes

Newlines are significant and counted as 1 byte each.

The explicit return made it a bit longer:

```
f=n=>{for(i=0,y=z='+--'[r='repeat'](n)+`+
`;i<n;)y+=('|##|  '[r](n).substr(++i%2*3,n*3)+`|
`)[r](2)+z;return y}

```

### Demo

At time of writing, Firefox is the only major browser compatible with ES6.

```
f=n=>{for(i=0,y=z='+--'[r='repeat'](n)+`+
`;i<n;)y+=('|##|  '[r](n).substr(++i%2*3,n*3)+`|
`)[r](2)+z;return y}

// Demonstration related things
document.getElementById('O').innerHTML = f(document.getElementById('n').value);

document.getElementById('n').addEventListener('change', function () {
  document.getElementById('O').innerHTML = f(this.value);
});
```

```
<p><input id=n type=number min=0 step=1 value=6></p>
<pre><output id=O></output></pre>
```

# Answer
> 2 votes
# CJam, 46 bytes

```
li3*)_2m*[{_3f/2f%:=\3f%:g+2b"+-|#+-| "=}/]/N*

```

Try it online

Well, I was hoping that I would at least have an original solution (I normally don't look at other answers before working on my own). Turns out that @Sp3000 had already done something very similar, only better. But since I already did the work, I thought I'd post it anyway.

Explanation:

```
li    Get input n.
3*)   Calculate 3*n+1, which is the total width/height.
_     Copy size. We'll need it at the end to insert the newlines.
2m*   Calculate cartesian power with 2. This enumerates all coordinate pairs.
[     Wrap characters in array for split operation at the end.
  {     Loop over all coordinate pairs.
    _     Copy coordinate pair.
    3f/   Divide coordinates by 3.
    2f%   Modulo 2. This characterizes even/odd squares.
    :=    Compare the two coordinates. This gives 0/1 for white/black squares.
    \3f%  Grab second copy of coordinates, and calculate modulo 3.
    :g    Sign. This gives 0 for grid lines, 1 for interior of squares.
    +     Concatenate the two results. We now have a 3 bit code.
    2b    Convert the 3 bits to a number in range 0..7.
    "+-|#+-| "
          Lookup table to convert 0..7 number to character.
    =     Lookup character.
  }/    End loop over coordinate pairs.
]     End wrapping characters.
/     Split character array into lines.
N*    And join them with newlines.

```

# Answer
> 2 votes
# Ruby, 87

```
->n{a=[b="+--",c="|  |##",c,b,d="|##|  ",d]
0.upto(n*3){|i|puts"".ljust(n*3+1,a[i%6])}}

```

This is an anonymous function. Call it like this (all possibilities from 0 to 5)

```
f=->n{a=[b="+--",c="|  |##",c,b,d="|##|  ",d]
0.upto(n*3){|i|puts"".ljust(n*3+1,a[i%6])}}

6.times{|j|f.call(j)}

```

It makes use of the `ljust` method on an empty string. Ruby allows a padding string to be specified for justification, so we use `ljust` with one of the three possible padding strings `b,c,d` per array `a`, ordered as `bccbdd`.

# Answer
> 1 votes
# HackVM, 158 bytes

Definitely not a winner, but this looked like a nice challenge to do in HVM.

Place the size into the first memory cell and use the following code:

```
77*1+c0<0^84*1+?1-11<-1>99*85++0^cc77*1+c066*5+-g!0<0^45*2+?1-95*0^0^2-PPP064*-6-gd95*2-P25*P$1<2>555**1-P0<0^76*6-?1-12<-2>2<3*48*+0^PP555**1-P076*2+-gd25*P$

```

**Note:** The code needs to be exactly in one line to work.

**Explanation:**

```
Call PLUSHDASHLINE
77*2+c

Read the cell and skip if done
0<0^84*1+?1-

  Flip row parity
  11<-1>

  Call NORMALLINE twice
  99*85++0^cc

  Call PLUSHDASHLINE
  77*1+c

Jump back to start of loop
066*5+-g!

DEFINE_PLUSDASHLINE
0<0^45*2+?1-95*0^0^2-PPP064*-6-gd95*2-P25*P$

DEFINE_NORMALLINE
1<2>555**1-P0<0^76*6-?1-12<-2>2<3*48*+0^PP555**1-P076*2+-gd25*P$

```

The code calls 2 functions `PLUSHDASHLINE` and `NORMALLINE`, maintains a global state for parities (i.e. whether to put a `' '` or a `'#'` in a cell).

**Explanation for `PLUSDASHLINE`:**

```
Repeat N times
0<0^45*2+?1-

  Print "+--"
  95*0^0^2-PPP

End Repeat
064*-6-g

Print "+"
d95*2-P

Print "\n"
25*P

Return
$

```

**Explanation for `NORMALLINE`:**

```
Copy Parity into Cell 2
1<2>

Print '|'
555**1-P

Repeat N times
0<0^76*6-?1-

  Flip Cell 2 (i.e. Flip Column Parity)
  12<-2>

  Calculate ' ' or '#' based upon parity
  2<3*48*+0^

  Print it twice
  PP

  Print '|'
  555**1-P

End Repeat
076*2+-g

Print "\n"
d25*P

Return
$

```

Would appreciate it if someone gave tips for improving it further :)

# Answer
> 1 votes
## Python 2, 98

```
n=input()
f=lambda a,b,s:s+s.join(([a*2,b*2]*n)[:n])+s+'\n'
print f(f(*' #|'),f(*'# |'),f(*'--+'))

```

Not the shortest way, but an amusing method. The function `f` takes in two strings `a,b` and a separator `s` and interleaves its arguments like `saasbbsaasbbsaas`. The rows of the board are created in this form with their respective characters, then are themselves interleaved this way to produce the result.

# Answer
> 1 votes
# Ruby: 83 characters

```
f=->n{puts d=?++'--+'*n,(0...n).map{|i|[?|+'%2s|'*n%(['','##',''][i%2,2]*n)]*2<<d}}

```

Sample run:

```
irb(main):001:0> f=->n{puts d=?++'--+'*n,(0...n).map{|i|[?|+'%2s|'*n%(['','##',''][i%2,2]*n)]*2<<d}}
=> #<Proc:0x000000007c51a0@(irb):1 (lambda)>

irb(main):002:0> f[0]
+
=> nil

irb(main):003:0> f[1]
+--+
|  |
|  |
+--+
=> nil

irb(main):004:0> f[2]
+--+--+
|  |##|
|  |##|
+--+--+
|##|  |
|##|  |
+--+--+
=> nil

irb(main):005:0> f[3]
+--+--+--+
|  |##|  |
|  |##|  |
+--+--+--+
|##|  |##|
|##|  |##|
+--+--+--+
|  |##|  |
|  |##|  |
+--+--+--+
=> nil

```

# Answer
> 1 votes
# Vyxal, 52 bytes

```
(x|`+--`*\++,2(⁰(n←x+₂[`|  `|`|##`]₴)\|,))`+--`*\++,

```

Try it Online!

A. Big. Mess.

# Answer
> 0 votes
# Julia, 124 bytes

```
n->(t="+--"^n*"+";a="|  ";b="|##";m=n÷2;c=n%2>0;p=println;p(t);for i=1:n p(((i%2<1?(b*a)^m*b^c:(a*b)^m*a^c)*"|\n")^2*t)end)

```

This creates an unnamed function that accepts an integer and prints to stdout.

Ungolfed + explanation:

```
function f(n)
    # Define the portions of the board
    t = "+--"^n * "+"
    a = "|  "
    b = "|##"

    # There will be n÷2 repeated a*b or b*a per line
    m = n ÷ 2

    # If n is odd, there will be an extra a or b
    c = n % 2 != 0

    # Print the top
    println(t)

    # Print each horizontal section of the board
    for i = 1:n
        # In even numbered sections, b precedes a
        j = (i % 2 == 0 ? (b*a)^m * b^c : (a*b)^m * a^c) * "|\n"
        println(j^2 * t)
    end
end

```

# Answer
> 0 votes
# Javascript, ES6 149

```
n=>(r="+--".repeat(n)+"+",[...r].map((_,i)=>i%3?(x=i%6&&i%6<3?" ":"#",[...r].map((_,e)=>e%3?e%6&&e%6<3?x:"#"==x?" ":"#":"|").join('')):r).join('\n'))

```

Pretty fun to write though it's a bit long

**Works on firefox**

1 - Open console

2 - Type the following

```
console.log((n=>(r="+--".repeat(n)+"+",[...r].map((_,i)=>i%3?(x=i%6&&i%6<3?" ":"#",[...r].map((_,e)=>e%3?e%6&&e%6<3?x:"#"==x?" ":"#":"|").join('')):r).join('\n')))(15));

```

Output (n=15):

```
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+

```

# Answer
> 0 votes
# Haskell, 118

This is my first haskell code golf answer and here it is:

```
f n=mapM_(putStrLn.s)[0..3*n]where;d x=(++)$take(3*n)$cycle x;s x|x`mod`3<1=d"+--""+"|x`mod`6<3=d"|  |##""|"|1<2=d"|##|  ""|"

```

**More readable version:**

```
func num = do
    let -- Range
        rag = 3 * num
        -- `+--+`
        a = d "+--" "+"
        -- `|  |##`
        b = d "|  |##" "|"
        -- `|##|  `
        c = d "|##|  " "|"
        -- generate line
        d x y = take rag (cycle x) ++ y
        -- step
        step x
            | x `mod` 6 `elem` [1, 2] = b
            | x `mod` 3 == 0          = a
            | otherwise               = c

    mapM_ (putStrLn . step) [0..rag]

```

**Output**

```
*Main> :load test
[1 of 1] Compiling Main             ( test.hs, interpreted )
Ok, modules loaded: Main.
*Main> f 1
+
*Main> f 4
+--+--+--+--+
|  |##|  |##|
|  |##|  |##|
+--+--+--+--+
|##|  |##|  |
|##|  |##|  |
+--+--+--+--+
|  |##|  |##|
|  |##|  |##|
+--+--+--+--+
|##|  |##|  |
|##|  |##|  |
+--+--+--+--+
*Main> f 15
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
|##|  |##|  |##|  |##|  |##|  |##|  |##|  |##|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
|  |##|  |##|  |##|  |##|  |##|  |##|  |##|  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+

```

# Answer
> 0 votes
# Haskell, 99

This is partially inspired by the previous Haskell answer by catgocat; I wrote my own version, then looked at it, then wrote another. I'm playing by the same rules — the input is an argument, but the output is stdout. (If it could be a pure function, subtract 7 characters `putStr$`.)

```
f n=putStr$unlines$t$map t$y[a,b,b,a,c,c]where t=take(n*3+1)
a=y"+--"
b=y"|  |##"
c=drop 3b
y=cycle

```

We use `t` to take a region of 3*n* \+ 1 characters from an infinite checkerboard built using `cycle`, and that's it. The primary idea I took from the other answer is that of putting the patterns of both the border and checker cells *together* in strings.

My first version (140 characters) used the strategy of calculating the character at each point, which might be better for a more complex problem than this one.

```
f n=putStr$unlines$map(\y->map(g y)r)r where r=[0..n*3]
g y x=s(s '+'y '|')x$s '-'y$cycle" #"!!(x`div`3+y`div`3)
s c i d|i`mod`3==0=c|True=d

```

# Answer
> 0 votes
# C - ~~119~~ 101

Uses now the calculation similar to @Sp3000 answer. Also couple optimizations.

```
i,j;f(n){for(i=j=0;j<=n*3;i++)putchar(i-n*3-1?" -|+#"[!(j%3)+2*!(i%3)?:(i/3+j/3)%2*4]:(j-=i=-1,10));}

```

I think that `?:` is a GCC extension...

Old answer:

```
f(n){int i,j;char p[]=" -|+";for(i=j=0;j<=n*3;*p=" #"[(i++/3+j/3)%2])putchar(i-n*3-1?p[!(j%3)+2*!(i%3)]:(j-=i=-1,10));}

```

It maintains 2 coordinates and honestly calculates which character to print for each pair. List of characters to print is stored in array and this alone prints an "uncolored" grid. First element of the array is modified to draw black squares.

I might change this so that instead of two independent coordinates it's one value counting up or (maybe even better) down, but can't wrap my head around that right now.

Bonus - replacing 3 with any other number results in a program that draws valid checkerboard with different cell size.

# Answer
> 0 votes
# awk - 91

```
{
    for(k=i=3*$0+1;i--;print"")
        for(j=k;j--;)printf i%3?j%3?234~(i+j)%6?FS:"#":j%3?"-":"|":"+"
}

```

Was quite a fight to get it below 100. Counting backwards and using the match operator were the breakthroughs ;) The rest is pretty much straightforward logic.

# Answer
> 0 votes
## Pyke, 47 bytes

```
"+--"Q*\+j+i
QQ]Uas 2%" #"@2*)F\|JjR+"+
"+2*pi
<Newline needed>

```

Try it here!

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


title: Generate a British numberplate

text:
# Question
Title: Generate a British numberplate
Modern British number plates (a.k.a. registration marks or license plates) use the format `AANNXXX` where `AA` is a "DVLA memory tag" (basically a location code), `NN` is the age identifier, and `XXX` is three random letters.

Your task is to, given a date, generate a random valid number plate with a date code matching the supplied date. Simplified from the actual implementation, this is how to generate them:

* The memory tag will just be generated randomly:

+ First letter: random from `ABCDEFGHKLMNOPRSVWY` (the alphabet, minus `IJQTUXZ`)
    + Second letter: random from `ABCDEFGHJKLMNOPRSTUVWXY` (the alphabet, minus `IQZ`)
* The age identifier follows this pattern:

+ 1st September 2001 - 28th February 2002: `51`
    + 1st March 2002 - 31st August 2002: `02`
    + September 2002 - February 2003: `52`
    + March 2003 - August 2003: `03`
    + ...
    + March 2010 - August 2010: `10`
    + September 2010 - February 2011: `60`
    + March 2011 - August 2011: `11`
    + September 2011 - **29th** February 2012: `61`
    + ...
    + September 2020 - February 2021: `70`
    + ...
    + September 2049 - February 2050: `99`
    + March 2050 - August 2050: `00`
    + September 2050 - February 2051: `50`
    + March 2051 - August 2051: `01`
* The 3 random letters are picked from `ABCDEFGHJKLMNOPRSTUVWXYZ` (the alphabet, minus `IQ`)

## Rules

* You must output in uppercase with no spaces or dashes between letters. However, trailing newlines, or any other output from your language that is not easily suppressible, are allowed
* For the purposes of this challenge, "random" means picked pseudo-randomly with any distribution as long as all possibilities have a non-zero chance of occurring
* You may assume the date will always be in the range 1st September 2001 to 31st August 2051
* The date can be in any reasonable input format (for example, your language's native date object, `april 28 2021`, `(28,4,21)`, `1619615864` (a Unix epoch timestamp))
* You may ignore leap seconds, daylight savings time, and timezone issues (just assume the date is always in UTC)
* You may use any reasonable I/O method
* Standard loopholes are forbidden
* This is , so the shortest code in bytes wins

## Test cases

These are to test the date conversion alone.

```
23rd September 2001     51
1st March 2006          06
29th February 2012      61
1st December 2021       71
11th October 2049       99
19th January 2051       50

```

# Answer
> 6 votes
# Jelly, 48 bytes

```
Ṗḅ12_3:6d2Ṛ%50ḅ50ṾŻṫ-“IQ“““Z“JTUX”;\ØAḟⱮ$X€ŒH¤jṚ

```

Try it online!

A full program taking the date as a list of integers `[y,m,d]` and printing the numberplate.

Thanks to @JonathanAllan for pointing out a couple of errors!

# Answer
> 5 votes
# JavaScript (ES6),  ~~121~~  116 bytes

Expects `(month)(year)`. The day is ignored. Returns an array of characters.

```
m=>y=>[...'9512444'].map(n=>((y-(m<3))%50-50*~-~(m<3|m>8)+n)[n]||'ABCDEFGHKLMNOPRSVWYJTUXZ'[Math.random()*(28-n)|0])

```

Try it online!

### Commented

```
m =>                         // m = 1-indexed month
y =>                         // y = full year
[...'9512444']               // split 9,5,1,2,4,4,4 as characters
.map(n =>                    // for each value n above:
  (                          //   build a string:
    ( y -                    //     subtract 1 from y if ...
      (m < 3)                //     ... the month is January of February
    ) % 50                   //     reduce modulo 50
    - 50 *                   //     add 100 to the result for March to August
    ~-~(m < 3 | m > 8)       //     or 150 otherwise
    + n                      //     coerce to a string
  )[n]                       //   attempt to extract the n-th character
  ||                         //   if n is greater than or equal to 4:
  'ABCDEFGHKLMNOPRSVWYJTUXZ' //     use this string instead
  [ Math.random()            //     and extract a random character
    * (28 - n)               //     in [0 ... 18] (if n = '9')
    | 0                      //     or [0 ... 22] (if n = '5')
  ]                          //     or [0 ... 23] (if n = '4')
)                            // end of map()

```

# Answer
> 4 votes
# Charcoal, 51 bytes

```
≔⁻⪪α¹⪪IQ¹ζ‽⁻ζ⪪JTUXZ¹‽⁻ζZ﹪%02d⁺﹪⁻θ›³η⁵⁰∧÷⁻⁸η⁶¦⁵⁰Ｆ³‽ζ

```

Try it online! Link is to verbose version of code. Takes input as `[Y, M, D]` (well the `D` is optional and unused). Explanation:

```
≔⁻⪪α¹⪪IQ¹θ

```

Make a copy of the uppercase alphabet with the letters `I` and `Q` removed.

```
‽⁻θ⪪JTUXZ¹

```

Print a random letter excluding the letters `J`, `T`, `U`, `X` and `Z`.

```
‽⁻θZ

```

Print a random letter excluding `Z`.

```
﹪%02d⁺﹪⁻θ›³η⁵⁰∧÷⁻⁸η⁶¦⁵⁰

```

Decrement the year if the month is January or February, reduce modulo `50`, then add `50` if appropriate, and format the result as two digits.

```
Ｆ³‽θ

```

Print three more random letters.

# Answer
> 4 votes
# Excel, 142 bytes

```
=REPLACE(CONCAT(MID("ABCDEFGHKLMNOPRSVWYJTUXZ",INT(RANDARRAY(7)*{19;23;1;1;24;24;24}+1),1)),3,2,TEXT(MOD(B2,50)+IFS(A2<3,49,A2>8,50,1,),"00"))

```

Link to Spreadsheet

Assumes Month in `A2` and Year is in `B2`

## Excel date as input, 161 bytes

```
=LET(x,EOMONTH(A1,-2),REPLACE(CONCAT(MID("ABCDEFGHKLMNOPRSVWYJTUXZ",INT(RANDARRAY(7)*{19;23;1;1;24;24;24}+1),1)),3,2,TEXT(MOD(YEAR(x),50)+(MONTH(x)>6)*50,"00")))

```

# Answer
> 3 votes
# Python 3.8 (pre-release), ~~167...~~ 164 bytes

```
lambda m,y,p=lambda e=0:choice('ZJTUXABCDEFGHKLMNOPRSVWY'[e:]):p(5)+p(1)+[str((z:=y%50)+49+(m>2)+50*(z<1)),'0'*(z<10)+str(z)][2<m<9]+p()+p()+p()
from random import*

```

Try it online!

Similar technique to Arnauld: this was written by analyzing the age identifiers. If the month is between 3 and 8 (bounds included) add the `y%50` string with a leading zero if `y%50<10`. Otherwise, add either 50 or 49 to `y%50` and return that.

Takes two inputs: month and year (in that order).

I know that `from random import*` definitely saves bytes, but I'm yet to find a way to integrate that without breaking TIO and adding `f=` (which actually *inflates* the bytecount.)

*\- ~~1~~ 3 bytes thanks to ovs.*

*+9 bytes to fix a bug.*

# Answer
> 3 votes
# Retina, 118 bytes

```
T`d`9d`.0?(?=/0[12])
T`5-9`d`^.
T`d`5-9`^.(?!./0[3-8])
L$`^..
==$&===
=
<26*=>
Y`=`L
I|Q

,4`[JTUXZ]

0`Z

<(\w)+>
$?1

```

Try it online! Takes input in the format `YY/MM` but link includes test suite that trims off any trailing `/DD`. Explanation:

```
T`d`9d`.0?(?=/0[12])

```

Decrement the year if the month is January or February.

```
T`5-9`d`^.

```

Reduce the year modulo `50`.

```
T`d`5-9`^.(?!./0[3-8])

```

Add `50` to the year unless the month is in the range March to August.

```
L$`^..
==$&===

```

Remove the month and add placeholders for the letters.

```
=
<26*=>
Y`=`L

```

Expand each placeholder to a run of letters `<A..Z>`.

```
I|Q

,4`[JTUXZ]

0`Z

```

Delete the `I`s, `Q`s, the first `J`, `T`, `U`, `X` and `Z`, and the (originally second) `Z`.

```
<(\w)+>
$?1

```

Pick a random remaining letter from each run.

# Answer
> 3 votes
# Vyxal, 60 bytes

```
«ÞTȮa⟩Ȯ2¬~Zyė∆₂ċ«⇧D3ȯ℅₴7ȯ℅₴6ɾ2+?ḟu=50*?50%+:₀<[\0p]₴2ȯDẊẊ℅ṅ₴

```

Try it Online!

It's... not terrible, but still bad.

# Answer
> 2 votes
# Julia, 100 bytes

```
!n=rand(setdiff('A':'Z',"IQZJTUX"[1:n]))
m$y=!7*!3lpad((a=(m+12y-3)÷6)÷2%50+a%2*50,2,'0')*!2*!2*!2

```

Try it online!

---
Tags: code-golf, string, random, date
---


title: Antiferromagnetic ordering

text:
# Question
Title: Antiferromagnetic ordering
**Antiferromagnetism** is what IBM researchers used to jump from a *1 terabyte disk* to a *100 terabyte disk* in the same amount of atoms.

In materials that exhibit antiferromagnetism, the magnetic moments of atoms or molecules, usually related to the spins of electrons, align in a regular pattern with neighboring spins (on different sublattices) pointing in opposite directions.

Your job is to write a program that draws the ordering of antiferromagnetic atoms like the picture shown above. You must be able to have at least four sets of pairs, though you may have more.

Each pair must be shown as follows, though they must be **actual arrows**:

```
 up  down
down  up
 up  down

```

Your output can be in ascii art or graphical output.

You can make only a function or a whole program, but it must take an input and draw that many pairs. Examples with *only words*:

Input: 1

```
 up  down
down  up
 up  down

```

Input: 2

```
 up  down  up  down
down  up  down  up
 up  down  up  down

```

Acceptable arrows:

* and
* and
* `/|\` and `\|/`

Please put your answers in **Language, X bytes** format, as it's easy to read. The least amount of bytes wins!

# Answer
> 16 votes
# APL, ~~18~~ 12 bytes

```
⍉(2×⎕)3⍴'↑↓'

```

This constructs a 2n x 3 matrix, where n is the input (), filled with the characters  and . The transpose () of this matrix is then printed.

You can try it online.

# Answer
> 12 votes
# Pyth, 15 bytes (11 chars)

```
V3.>*Q"↑↓"N

```

Try it online: Demonstration

### Explanation:

```
              implicit: Q = input number
V3            for N in [0, 1, 2]:
      "↑↓"       string "↑↓"
    *Q           repeat Q times
  .>      N      rotate the string by N

```

# Answer
> 12 votes
# Java, ~~313~~ 296 bytes

Here's an example that displays arrows graphically:

```
import java.awt.*;void f(int n){new Frame(){public void paint(Graphics g){for(int k=0,l,m,o;k<n*6;o=k%6,l=o/2*10+32,m=k/6*20+(k++%2==0?19:29),g.fillPolygon(new int[]{m+4,m,m+4,m+4,m+6,m+6,m+10},o==1|o==2|o==5?new int[]{l+9,l+5,l+5,l,l,l+5,l+5}:new int[]{l,l+5,l+5,l+9,l+9,l+5,l+5},7));}}.show();}

```

In a more readable format:

```
import java.awt.*;
void f(int n) {
    new Frame() {
        public void paint(Graphics g) {
            for (int k = 0, l, m, o; k < n*6;){
                o = k % 6;
                l = o / 2 * 10 + 32;
                m = k / 6 * 20 + (k++ % 2 == 0 ? 19 : 29);
                g.fillPolygon(new int[] {m+4,m,m+4,m+4,m+6,m+6,m+10},
                              o == 1 || o == 2 || o == 5 ?
                                  new int[] {l+9,l+5,l+5,l,l,l+5,l+5} :
                                  new int[] {l,l+5,l+5,l+9,l+9,l+5,l+5},
                              7);
            }
        }
    }.show();
}

```

The display for 5 as input:

You'll have to resize the window that appears to see the arrows. I tried to make it so that none of them would appear "chopped off" by the window's inside border, but it may appear that way on certain platforms.

# Answer
> 9 votes
# CJam, 18 bytes (14 chars)

```
ri3*"↑↓"*3/zN*

```

Generate the columns (which form a repeating pattern) then transpose.

Try it online.

---

**Alternative 18 bytes:**

```
3,ri"↑↓"*fm>N*

```

Rotate the string `"↑↓"*n` by 0, 1 or 2 times.

# Answer
> 7 votes
## CJam (15 chars, 19 bytes)

```
ri"↑↓"*_(+1$]N*

```

Online demo

# Answer
> 7 votes
## **Befunge, 71 bytes**

My first answer, so please be gentle with me :o)

Annoying alignment issues resulted in a few wasted bytes, if you have any improvements for me I'd love to hear them!

```
&::3>:2% #v_0#v" \|/ "<
  >\^,*52<> 0#v" /|\ "<
:#^_$1-:#^_@  >:#,_$\1-

```

Input: 4

```
 /|\  \|/  /|\  \|/  /|\  \|/  /|\  \|/
 \|/  /|\  \|/  /|\  \|/  /|\  \|/  /|\
 /|\  \|/  /|\  \|/  /|\  \|/  /|\  \|/

```

# Answer
> 6 votes
# CJam, 14 bytes

```
0000000: 332c 7269 2218 1922 2a66 6d3e 4e2a       3,ri".."*fm>N*

```

This requires a supporting terminal that renders code page 850 like this:

The non-pointy part of the code turned out to be identical to @Sp3000's alternative version.

---

# CJam, 17 bytes

```
ri"⇅⇵⇅"f*N*

```

Cheaty double arrow version, with credits to @DigitalTrauma.

Try it online.

# Answer
> 5 votes
# Pyth, 16 bytes (12 chars)

```
J"↑↓"V3*~_JQ

```

Example:

```
Input: 4
Output:
↑↓↑↓↑↓↑↓
↓↑↓↑↓↑↓↑
↑↓↑↓↑↓↑↓

```

# Answer
> 5 votes
# Python 2, ~~131~~ 122 bytes

```
from turtle import*
for k in range(input()*6):z=k/3+k%3&1;pu();goto(k/3*32,z*32^k%3*64);pd();seth(z*180+90);fd(32);stamp()

```

Well... I beat ~~C~~ Java I guess?

---

I've chosen height `32` for the arrows, which is pretty large, so after a while the turtle starts drawing offscreen. If you want everything to fit for large inputs, you can either make the arrows smaller by replacing the `32`s, or use `screensize()` (I'm not sure if there's a meta post on offscreen output...)

# Answer
> 4 votes
# GNU sed, 25 bytes

I found the  and  unicode arrow symbols, which allow more shortening and they have been allowed by this comment:

```
h
s/1/⇅/g
H
G
s/1/⇵/g

```

Input is in unary, so e.g. 4 is `1111`:

```
$ echo 1 | sed -f antiferro.sed
⇅
⇵
⇅
$ echo 1111 | sed -f antiferro.sed
⇅⇅⇅⇅
⇵⇵⇵⇵
⇅⇅⇅⇅
$

```

---

Previous answer in case  and  are disallowed:

# GNU sed, 39 bytes

```
s/1/↑↓/g
s/.*/&a&↑\n&/
s/a↑/\n/

```

# Answer
> 3 votes
# Ruby 39 (or 44) characters, 43 (or 48) bytes

According to https://mothereff.in/byte-counter the arrow characters are 3 bytes each!

```
->(n){a=['↑↓'*n]*3;a[1]=a[1].reverse;a}

```

An anonymous function which returns an array. If the function has to print the array, it should end with `puts a` for 5 more bytes.

Example use

```
f=->(n){a=['↑↓'*n]*3;a[1]=a[1].reverse;a}

puts f.call(6)

```

Gives

```
↑↓↑↓↑↓↑↓
↓↑↓↑↓↑↓↑
↑↓↑↓↑↓↑↓

```

# Answer
> 3 votes
# J, ~~41~~ ~~35~~ 32 bytes (28 characters)

```
3$(,:|.)(2*".1!:1[1)$ucp'↑↓'

```

I have never programmed anything in J so this took me a while, and it's most definitely not the best way to do it.

This waits for you to input a number when run before outputing the arrows.

# Answer
> 3 votes
# Swift 2, 66 bytes

```
let f={n in(0..<n*3).map{print("↑↓",appendNewline:$0%n==n-1)}}

```

If Swift would be just a liiiitle bit less verbose, it wouldn't even be that bad for golfing (I'm looking at you, named parameter `appendNewline`)

# Answer
> 2 votes
# C, ~~169~~ ~~170~~ ~~162~~ ~~125~~ ~~123~~ ~~105~~ ~~119~~ 107 bytes

So, I though I might as well give this a go, even though this is obviously not the winner :)

Golfed:

```
n,i,j;main(){n=getchar();n=atoi(&n);for(;j++<3;){for(i=0;i++<n;)printf("%.3s ","⇅⇵"+(j%2)*3);puts("");}}

```

Ungolfed:

```
#include <stdio.h>
#include <stdlib.h>

/* n -> Number of columns, i & j -> Loop counters */
n,i,j;

main()
{
    /* Get the number of iterations from stdin */
    n = getchar();
    n = atoi(&n); /* Thanks @AndreaBiondo */

    for (; j++ < 3;)
    {
        /* Print rows of arrows */
        for (i = 0; i++ < n;)
            printf("%.3s ","⇅⇵" + (j % 2) * 3);

        /* Print a newline */
        puts("");
    }
}

```

Example:

```
Input: 4
⇵ ⇵ ⇵ ⇵
⇅ ⇅ ⇅ ⇅
⇵ ⇵ ⇵ ⇵

```

### Update:

See it run here

# Answer
> 2 votes
# Javascript (ES6), 66 63 53 47 bytes (62 55 49 41 characters)

```
f=n=>`⇅
⇵
⇅`.replace(/./g,'$&'.repeat(n))

```

Props to Digital Trauma for finding the ⇅ and ⇵ characters and allowing me to shave off more bytes.

# Answer
> 2 votes
## J, 30 bytes

```
|:((2*".1!:1<1),3)$ucp'↑↓'

```

# Answer
> 2 votes
# Octave, 37 bytes

***EDIT:*** corrected from the earlier stripe-antiferromagnetic version. Thanks @beta-decay for catching my mistake.

```
f=@(n)repmat(["⇅";"⇵";"⇅"],1,n)

```

Defines a function `f(n)`. Sample output:

```
octave:4> f(1)
ans =

⇅
⇵
⇅

octave:5> f(5)
ans =

⇅⇅⇅⇅⇅
⇵⇵⇵⇵⇵
⇅⇅⇅⇅⇅

```

# Answer
> 2 votes
# 05AB1E, ~~17~~ 11 bytes

```
ƵηSnŽXæ+ç×»

```

Bug-fixed and -6 bytes thanks to *@ovs*.

Uses  and .

Try it online or verify some more test cases.

**Slightly larger simplified approach - 15 bytes in UTF-8 (8 characters):**

```
"⇅⇵"ĆS×»

```

Try it online or verify some more test cases.

**Explanation:**

Unfortunately the 05AB1E codepage doesn't contain the arrow characters, so we have to create them ourselves or use UTF-8 encoding for the entire program.

```
Ƶη           # Push compressed integer 171
  S          # Convert it to a list of digits: [1,7,1]
   n         # Square each: [1,49,1]
    ŽXæ+     # Add compressed integer 8644 to each: [8645,8693,8645]
        ç    # Convert them to characters with these codepoints: ["⇅","⇵","⇅"]
         ×   # Repeat each character the (implicit) input amount of times as strings
          »  # And join this list of strings by newlines
             # (after which it is output implicitly as result)

"⇅⇵"        # Push string "⇅⇵"
     Ć       # Enclose, appending it's own head: "⇅⇵⇅"
      S      # Convert it to a list of characters: ["⇅","⇵","⇅"]
       ×»    # Same as above

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ƶη` is `171` and `ŽXæ` is `8644`.

# Answer
> 1 votes
## JavaScript (ES6), 66 bytes (62 chars)

That includes the Unicode character counted as three bytes each as well as the mandatory newline counted as one byte.

Uses recursion as inspired by this answer. I tried it non-recursively but generating a defined array took too many characters, although someone else might know how to do it better than me.

```
f=n=>(g=(a,i)=>i?g(`
↓↑`[i%(n*2+1)&&1+i%2]+a,i-1):a)('',n*6+2)

```

### Demo

As with all ES6 answers, they are demonstrable in Firefox, Edge, and Safari 9 only at time of writing:

```
f = n => (g = (a, i) => i ? g(`
↓↑` [i % (n * 2 + 1) && 1 + i % 2] + a, i - 1) : a)('', n * 6 + 2)

console.log = x => document.getElementById('O').innerHTML += x + '\n';

console.log(f(1));
console.log(f(2));
console.log(f(4));
console.log(f(32));
```

```
<pre><output id=O></output></pre>
```

# Answer
> 1 votes
## CoffeeScript, 60 bytes (58 chars)

Comprehensions make it easy without recursion:

```
f=(n,x='')->x+='\n⇵⇅'[i%(n+1)&&1+i%2]for i in[1..n*3+2];x

```

# Answer
> 1 votes
# Ruby, 33 bytes

As a function:

```
f=->n{[s="↑↓"*n,s.reverse,s]}

```

Example:

```
> puts f[3]
↑↓↑↓↑↓
↓↑↓↑↓↑
↑↓↑↓↑↓

```

# Ruby, 37 bytes

Full program which takes input from stdin:

```
puts s="↑↓"*gets.to_i,s.reverse,s

```

# Answer
> 1 votes
## \>\<\>, 55 Bytes

```
"⇅⇵⇅"{:&3*1-:0(?;\
|.!09v!?%&:&:{o:}/
oa{~}/|.!09

```

Try it online here, inputting the desired length as initial stack value.

Non ⇅⇵ solution, 59 Bytes:

```
"↓↑"{:&3*>1-:0(?;{:{\
 |.!09v!?%&:&:oo}}@:/
9oa{$}/|.!0

```

# Answer
> 1 votes
# C, 117 89 85 bytes

```
i;main(j,v)char**v;{j=2*atol(v[1])+1;for(;i++<3*j;)printf(i%j?i%2?"↑":"↓":"\n");}

```

Ungolfed:

```
i;
main(j,v)
char**v; // Credit to @AndreaBiondo for brilliant idea that I will use a lot in future golfed programs :)
{
    j = 2*atol(v[1])+1;
    for(;i++<3*j;)
        printf(i%j?i%2?"↑":"↓":"\n");
}

```

# Answer
> 1 votes
# Java, 150 bytes

```
static void g(int n){n*=2;f(n,0);f(n,1);f(n,0);}static void f(int n,int d){String l="";for(n+=d;n-->d;)l+=(n%2==0)?"↓":"↑";System.out.println(l);}

```

Output of `g(2)`:

```
↑↓↑↓
↓↑↓↑
↑↓↑↓

```

# Answer
> 1 votes
# BBC BASIC, 70 bytes

```
INPUTx:n$=STRING$(x,"/|\\|/"):PRINTn$:PRINTSTRING$(x,"\|//|\"):PRINTn$

```

This can probably be golfed more

# Answer
> 1 votes
# C, 97 bytes

Takes the input from the first command-line parameter, e.g. `main 4`. Supports up to `357913940` pairs. In C you can't use multibyte characters as `char`s but they work fine as strings.

```
i,n;main(c,v)char**v;{n=atoi(v[1]);for(i=6*n+3;i--;)printf("%s",i%(2*n+1)?i%2?"↓":"↑":"\n");}

```

It is smaller as a function, but the other C answers were complete programs so I did that too. It would be 69 bytes:

```
i;f(n){for(i=6*n+3;i--;)printf("%s",i%(2*n+1)?i%2?"↓":"↑":"\n");}

```

# Answer
> 1 votes
# Python 2, 47 bytes

Port of my BBC BASIC answer, taking advantage of how Python can easily reverse strings.

```
n=r"/|\\|/"*input();print n+"\n"+n[::-1]+"\n"+n

```

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

Went through a good few different methods but couldn't do better than 16 then I realised a port of Kevin's solution would come in a bit shorter.

```
#«ì £çX²d8644

```

Try it

# Answer
> 1 votes
# Vyxal `Dj`, 11 bytes

```
‛↑↓3*½ÞTvṅ*

```

Try it Online!

-1 thanks to Aaron Miller

# Answer
> 0 votes
# Python 2, ~~45~~ 55 bytes

edit: modified arrows

Pretty straightforward approach. Doesn't work with unicode arrows, though.

```
def f(n):x=" /|\\ \\|/"*n;print x+"\n "+x[::-1]+"\n"+x

```

# Answer
> 0 votes
# R, ~~60~~ 62 bytes

Takes input from STDIN and outputs to STDOUT. Creates a 3 x *(2 * input)* array, adds a column of carriage returns and then outputs the transposed array.

```
cat(t(cbind(array(c('↑','↓'),c(3,2*scan())),'\n')),sep='')

```

Test run

```
cat(t(cbind(array(c('↑','↓'),c(3,2*scan())),'\n')),sep='')
1: 25
2:
Read 1 item
↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓
↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑
↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓↑↓

```

# Answer
> 0 votes
## Tcl 49 bytes

No winner but at least it's competitive:

```
foreach x {⇅ ⇵ ⇅} {puts [string repeat $x $argv]}

```

# Answer
> -1 votes
## Swift 2.0, 79 bytes

Nothing clever...

```
let p=3;for x in 0...2{print((0..<p*2).reduce(""){$0+["↑","↓"][($1+x)%2]})}

```

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


title: Simple ASCII Gantt

text:
# Question
Title: Simple ASCII Gantt
This is a simple one: print an ASCII Gantt chart.

Given tasks' ranges (start-time - end-time Tuples), print a Gantt timeline in the form of `-` characters for each task duration - each task in a new line.

### Example

Say my tasks ranges are `28->35, 34->40, 39->44`, the Gantt will look like this:

```
                            -------
                                  ------
                                       -----

```

### Specifications

* You can write a full program, a named function or an anonymous function.
* Your program/function should accept the tasks via STDIN **or as arguments**.
* Each task should be represented as a string of `start->end` where `start` and `end` are **Integers**. Tasks are separated by spaces or commas. **Alternatively**, you may get it as a Tuple of Integers, or as an Array/Collection of 2 Integers. (For example, in JavaScript you can get it as `[start,end]` \- this is allowed).
* Any non-negative number of tasks (arguments) should be supported.
* To make it clear, a single argument of tasks collection is not allowed. You can either parse a single string argument, or support zero-or-more tasks arguments. Where task is a tuple or a collection of size 2.
* You can assume only valid input will be given. That means, each task has a positive duration.
* Return value does not matter, your code must print the timeline on STDOUT.
* Output: per task, `start` spaces followed by `(end-start)` dashes and a `\n`.
* Needless to say, output lines should be ordered correspondingly with the input (tasks) order.
* Trailing spaces before the `\n` are allowed, if that helps you.

### Test cases

```
Input:
(empty)

Output:
(empty)

Input:
0->7,5->6,3->6

Output:
-------
     -
   ---

Input:
5->20,5->20,2->10,15->19

Output:
     ---------------
     ---------------
  --------
               ----

```

### Winning

* This is so the least code length (in bytes) wins.
* Traditionally, tie breaker is earlier post.
* "Standard loopholes are no longer funny".

## -----

## EDIT

As many of you understood that it is allowed to have a single tasks collection argument, and since there's no much different between that and the original varargs requirement, **it is now allowed to have a single collection argument, if you don't want to use the varargs option, or in case your language does not support varargs.**

# Answer
# CJam, ~~16~~ 14 bytes

```
q~{S.*~'-e]N}/

```

This expects a list of lists as input. For example:

```
[[5 20] [5 20] [2 10] [5 19]]

```

gives:

```
     ---------------
     ---------------
  --------
     --------------

```

**How it works**

```
q~                      e# Read the input and parse it as a list of list
  {         }/          e# Go over each item in the list in a for loop
   S                    e# S is basically this string - " "
    .*                  e# Multiply each item of the first list with the corresponding index
                        e# item of the second list. This basically repeats the space
                        e# X times where X is the first number of the tuple. The second
                        e# number remains untouched as the second list was only 1 char long
      ~                 e# Unwrap the space string and second number containing list
       '-               e# Put character '-' on stack
         e]             e# Make sure that the space is filled with - to its right so as to
                        e# make the total length of the string equal to the second number
           N            e# Put a newline. After all iterations, the result is printed
                        e# automatically to STDOUT

```

Try it online here
> 14 votes

# Answer
# Python 2, 39 Bytes

Straightforward solution using string multiplication :)

```
for x,y in input():print' '*x+'-'*(y-x)

```

Accepts input formatted like so:

```
((5,20),(5,20),(2,10),(15,19))

```

Check it out here.
> 20 votes

# Answer
## Brainfuck, ~~120~~ ~~115~~ 111 bytes

At least it's shorter than Java :) The input is a list of bytes, where each pair is a single line in the gantt.

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

```

**Try out**

http://copy.sh/brainfuck/

Set end-of-input to `char` with value `\0`. Example input: `\5\20\5\20\2\10\15\19`.

*Note that setting the end-of-input value to `\0` will have the side effect that no more input will be read (and thus stopping the program) when the input contains the number zero. In BF there is no other way of knowing when the input is exhausted.*

**Explanation\***

```
++++[->++++++++<]>  #Store <space> at index 1
[->+>+<<]           #Move index 1 to index 2 and 3
++++++++++          #Increment index 1 to <newline>
>>                  #Move to index 3
+++++++++++++       #Increment index 3 to <dash>
>                   #Move to (empty) index 4
+                   #Increment to start the main loop
[                   #Main loop
,                   #Read first number to index 4
[->+>+<<]>>[-<<+>>] #Copy index 4 to index 5 (index 5 can now be altered)
,                   #Read second number (the number pair is now stored at index 5 and 6)
<                   #Move to first number (index 5)
[->-<<<<.>>>]       #Decrement index 5 and 6 and print <space> until index 5 equals zero
>                   #move to second input (index 6)
[-<<<.>>>]          #Decrement index 6 and print <dash> until index 6 equals zero
<<<<<.>>>           #Print <newline> and move to index 4 (original first number)
]                   #End of main loop

```

*<sub>\*(You won't be able to compile/run this due to the comments)</sub>*
> 12 votes

# Answer
# Pyth, ~~36~~ ~~22~~ ~~19~~ 14 bytes

This is my first Pyth program. Jakube helped golf out 5 bytes!

```
FNQ<s*V" -"NeN

```

It expects input in the form `[[5,20], [5,20], [2,10], [15,19]]`.

You can try it online.
> 8 votes

# Answer
# C++14, 69 bytes

```
[]{int a,b;for(;cin>>a>>b;){cout<<setw(b)<<string(b-a,'-')+'\n';}}();

```

First time golfing, this was a good problem to start with!
> 5 votes

# Answer
# Scala, ~~67~~ ~~63~~ 59 bytes

```
(r:Seq[(Int,Int)])⇒for((s,e)←r)(println(" "*s+"-"*(e-s)))

```

Usage: `res0()` or `res0(Seq(28->35, 34->40, 39->44))` etc.

Thanks gilad for shaving 4 bytes using a for expression!
> 3 votes

# Answer
# K, 18 bytes

```
`0:" -"@{&x,y-x}.'

```

Expects a list of pairs as input:

```
  `0:" -"@{&x,y-x}.'(0 7;5 6;3 6)
-------
     -
   ---
  `0:" -"@{&x,y-x}.'(5 20;5 20;2 10; 15 19)
     ---------------
     ---------------
  --------
               ----
  `0:" -"@{&x,y-x}.'()

```

I unpack each (`'`) tuple using dot-apply (`.`) so that inside the lambda I have access to the start and end value as `x` and `y`, respectively. Then I reassemble these into a (start,length) tuple (`x,y-x`) and apply "where" (`&`). This gives me output like so:

```
  {&x,y-x}.'(0 7;5 6;3 6)
(1 1 1 1 1 1 1
 0 0 0 0 0 1
 0 0 0 1 1 1)

```

Then I simply have to index into a 2-character array using this ragged matrix (`" -"@`) and send it all to stdout (`0:`).
> 3 votes

# Answer
# JavaScript (*ES6*), 63

*Edit* 3 byte saved thx @apsillers
63 bytes not counting the assignment to F as an anonymous function is allowed.

~~A function with a variable number of parameters, as requested.~~
A function with a list of tasks as a single parameter.

Test running the snippet below (being EcmaScript 6, Firefox only)

```
F=l=>l.map(t=>console.log(' '.repeat(l=t[0])+'-'.repeat(t[1]-l)))

// TEST

// for this test, redefine console.log to have output inside the snippet
console.log = (...x) => O.innerHTML += x + '\n';

console.log('* Empty'); F([]);
console.log('\n* [0,7],[5,6],[3,6]'); F([[0,7],[5,6],[3,6]])
console.log('\n* [5,20],[5,20],[2,10],[15,19]');F([[5,20],[5,20],[2,10],[15,19]]);
```

```
<pre id=O></pre>
```
> 3 votes

# Answer
# Ruby: 35 characters

```
->*t{t.map{|s,e|puts' '*s+?-*(e-s)}

```

Sample run:

```
irb(main):001:0> ->*t{t.map{|s,e|puts' '*s+?-*(e-s)}}.call [0,7], [5,6], [3,6]
-------
     -
   ---

```

Updated to accept multiple two-element arrays, one for each task to display. (I think that is what the updated requirement expects.)
> 2 votes

# Answer
**Javascript(ES6), 61/66 chars**

My answer is almost similar to the one posted by @edc65 , but with some improvements. As tasks in single array are not allowed(so function would be called like this: `a([3,4], [7,15], [0,14], [10, 15])`), correct one would be this(**66 chars** without name assignment):

```
a=(...x)=>x.map(([c,d])=>console.log(' '.repeat(c)+'-'.repeat(d-c)))

```

And if one array argument is allowed(so fn call like this: `a([[3,4], [7,15], [0,14], [10, 15]])`), then it would be(**61 char** without assignment):

```
a=x=>x.map(([c,d])=>console.log(' '.repeat(c)+'-'.repeat(d-c)))

```
> 2 votes

# Answer
# APL (Dyalog Classic), 12 bytes

```
↑('-'\⍨≤∘⍳)/

```

Try it online!

APL has no varargs, so the arg here is a single Nx2 matrix.
> 2 votes

# Answer
# Java 8, ~~280~~ ~~275~~ ~~246~~ ~~204~~ ~~195~~ ~~185~~ 180 bytes

```
void g(String t){for(String s:t.split(",")){String[]a=s.split("->");s="";Integer i;for(i=0;i<i.valueOf(a[0]);i++)s+=" ";for(;i<i.valueOf(a[1]);i++)s+="-";System.out.println(s);};};

```

A method that takes a comma-seperated input string and prints the resulting ascii Gantt Chart to stdout.

Thanks to durron597 and masterX244 for helping me save 10 bytes
> 1 votes

# Answer
# SWI-Prolog, 55 bytes

```
a([[A,B]|C]):-tab(A),writef("%r",[-,B-A]),nl,C=[];a(C).

```

Example: `a([[5,20],[5,20],[2,10],[15,19]]).` outputs

```
     ---------------
     ---------------
  --------
               ----

```
> 1 votes

# Answer
# Julia, 44 bytes

```
x->for t=x a,b=t;println(" "^a*"-"^(b-a))end

```

This creates an anonymous function that accepts an array of tuples as input and prints to STDOUT.

Ungolfed + explanation:

```
function f(x)
    # Loop over the tasks (tuples) in x
    for t in x
        # Assign a and b to the two elements of t
        a,b = t

        # Print a spaces followed by b-a dashes on a line
        println(" "^a * "-"^(b-a))
    end
end

```

Examples:

```
julia> f([(5,20), (5,20), (2,10), (15,19)])
     ---------------
     ---------------
  --------
               ----

julia> f([(0,7), (5,6), (3,6)])
-------
     -
   ---

julia> f([])

```
> 1 votes

# Answer
# Perl: ~~42~~ 41 characters

Just to have at least one solution with string parsing too.

```
s!(\d+)->(\d+),?!$"x$1."-"x($2-$1).$/!ge

```

Sample run:

```
bash-4.3$ perl -pe 's!(\d+)->(\d+),?!$"x$1."-"x($2-$1).$/!ge' <<< '0->7,5->6,3->6'
-------
     -
   ---

```
> 1 votes

# Answer
## JavaScript (ES6), ~~106~~ ~~85~~ ~~80~~ 68 bytes

As per the updated requirements, a list of tasks is now acceptable

```
a=>a.reduce((p,v)=>p+=' '.repeat(z=v[0])+'-'.repeat(v[1]-z)+"\n",'')

```

Takes zero or more arguments: **80 bytes**

```
(...a)=>{s='';a.map(v=>s+=' '[r='repeat'](z=v[0])+'-'[r](v[1]-z)+"\n");return s}

```

---

Original attempt, 106 bytes:

```
(...a)=>{for(i=-1,s='',r='repeat';a.length>++i;){s+=' '[r](a[i][0])+'-'[r](a[i][1]-a[i][0])+"\n"}return s}

```
> 1 votes

# Answer
# Haskell, 76 bytes

```
(#)=replicate
f i=putStr$g=<<(read$'[':i++"]")
g(s,e)=s#' '++(e-s)#'-'++"\n"

```

Input format is a string of comma separated tuples, e.g. `"(1,2),(3,4)"`.

Usage examples:

```
*Main> f "(1,2),(3,4)"
  -
    -

*Main> f "(0,7),(5,6),(3,6)"
-------
     -
   ---

```

How it works: for input parsing I enclose the input string in `[` and `]` and use Haskell's native `read` function for lists of integer tuples. The rest is easy: for each tuple `(s,e)` take `s` spaces followed by `e-s` dashes followed by a newline and concatenate all into a single string. Print.

# Haskell, 59 bytes

with relaxed input format:

```
(#)=replicate
f=putStr.(g=<<)
g(s,e)=s#' '++(e-s)#'-'++"\n"

```

Now it takes a list of tuples, e.g `f [(0,7),(5,6),(3,6)]`.

Works as described above, but without input parsing.
> 1 votes

# Answer
## C: 108 bytes

```
void g(int*l){for(int c=0;*l>=0;c=!c,l++){if(!c)l[1]-=*l;while(l[0]-->0)putchar(c?45:32);c?putchar(10):0;}}

```

Ungolfed:

```
void gantt(int*l) {
    for (int c = 0; *l >= 0; c = !c, l++) {
        if (!c) l[1] -= *l;
        while (l[0]-- > 0) putchar(c? 45 : 32);
        c? putchar(10) : 0;
    }
}

```

Takes as a parameter a list of integers terminated by `-1`. For example:

```
int list[] = {
    28, 35,
    34, 40,
    39, 44,
    -1
};
gantt(list);

```

It uses `c` to toggle between writing spaces and dashes.
> 1 votes

# Answer
# Java, 187 181 197 183 101 bytes

```
void g(int[][]g){for(int[]i:g)for(int j=0;j<i[1];System.out.print(j++<i[0]?" ":j==i[1]?"-\n":"-"));}

```

Ungolfed (sort of):

```
void g(int[][] g){
    for(int[] i : g)
        for(int j = 0; j < i[1]; System.out.print(j++ < i[0] ? " " : j == i[1] ? "-\n" : "-"));
}

```

Accepts input as 2d array of `int`s. Thanks to masterX244 for pointing out that this is allowed by the rules.
> 1 votes

# Answer
# Jelly, 13 9 bytes

```
ạ\⁾ -xµ€Y

```

Try it online!

Takes input as `[[5, 20], [5, 20], [2, 10], [15, 19]]`.

-4 bytes thanks to Erik
> 1 votes

# Answer
# JavaScript (ES8), 54 bytes

```
a=>a.map(([x,y])=>"-".repeat(y-x).padStart(y)).join`
`

```

Try it online
> 1 votes

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

```
{" -"@&-':x}'

```

Try it online!

`{` `}` function with argument `x`

`{` `}'` apply to each - in this case to each pair of numbers from the input

`-':` subtract each prior - transform `(a;b)` into `(a;b-a)`

`&` "where" - transform `(a;b-a)` into a list of `a` zeroes followed by `b-a` ones

`" -"@` use as indices in `" -"`
> 1 votes

# Answer
# , ~~117 90~~ 75 bytes

```
function(y)for(i in 1:ncol(y))cat(" "<y[1,i],"-"<diff(y)[i],"
")
"<"=strrep

```

Try it online!

Giuseppe golfed at least 29 bytes off my original answer!

The idea is straightforward: print as many `" "` as necessary followed by as many `"-"` as required. Input is a `2*L` matrix with L the number of pairs. The vectorized function `diff` is used to get the number of "-".
> 1 votes

# Answer
# PowerShell 3.0, ~~48~~36 Bytes

```
$args|%{" "*$_[0]+"-"*($_[1]-$_[0])}

```

Thanks to Mazzy for saving 12 with a better way to pass in the list

Old code and explanation:

```
&{param($b="")$b|%{" "*$_[0]+"-"*($_[1]-$_[0])}}

```

Takes arguments as a list of tuples, e.g. (5,20),(5,20),(2,10),(15,19). Had to default $b to a value to take care of the empty string because it somehow entered the foreach block when called with no input.
> 1 votes

# Answer
# VBA (Excel), ~~99~~ 90 bytes

Using Immediate Window and `[A1]` as input eg.`0-1,2-5`

Thanks to @TaylorSott for cutting some bytes.

```
b=Split([A1]):For x=0To Ubound(b):c=Split(b(x),"-"):?Spc(c(0)-0)String(c(1)-c(0),"-"):Next

```
> 1 votes

# Answer
# Vyxal `j`, 9 bytes

```
ƛ÷ε\-*nt↳

```

Try it Online! Expects a list of lists.

```
ƛ         # Map each pair to...
 ÷ε       # Their difference
   \-*    # -s
      nt↳ # Padded to the length of the second.

```
> 1 votes

# Answer
## CoffeeScript, ~~104~~ 82, 65 bytes

List of tasks (ES6): **65 bytes**

```
(a)->a.map (v)->console.log ' '.repeat(v[0])+'-'.repeat v[1]-v[0]

```

List of tasks (ES5 variant): **82 bytes**

```
(a)->a.map (v)->j=-1;s='';s+=(if j<v[0]then' 'else'-') while++j<v[1];console.log s

```

Zero or more arguments: **104 bytes**

```
()->[].slice.call(arguments).map((v)->j=-1;s='';s+=(if j<v[0]then' 'else'-')while++j<v[1];console.log s)

```

Unminified:

```
() -> [].slice.call(arguments).map( # convert to array-like arguments to array and loop
 (v) ->
  j = -1 # counter
  s = '' # initialize string
  s += (if j < v[0] then ' ' else '-') while ++j < v[1]
  console.log s # print to STDOUT
)

```
> 0 votes

# Answer
## PHP, ~~94~~ 91 bytes

Takes a list of tasks (e.g. `[[5,20],[5,20],[2,10],[15,19]]`). Thanks @IsmaelMiguel for the reminder of variable function names.

```
function x($a){$r=str_repeat;foreach($a as$v){echo$r(' ',$v[0]).$r('-',$v[1]-$v[0])."\n";}}

```

---

Original attempt: 94 bytes

```
function x($a){foreach($a as$v){echo str_repeat(' ',$v[0]).str_repeat('-',$v[1]-$v[0])."\n";}}

```
> 0 votes

# Answer
# C++, 112\*

```
#include<iostream>
#include<string>
int a(){int a,b;while(cin>>a>>b){cout<<string(a,' ')+string(b-a,'-')+"\n";}}

```

\*~~or 76 depending on whether you count the include statements~~ just completely wrong... Didn't include std:: as pointed out in comments

### Test

**Input:** `5 20 5 20 2 10 15 19`

**Output:**

```
     ---------------
     ---------------
  --------
               ----

```
> 0 votes

# Answer
# PHP, 89 characters (function body)

```
function gantt($x){array_walk($x,function($a){echo str_pad(str_repeat('-',$a[1]-$a[0]),$a[1],' ',0)."\n";});}

```

I was going to go for reading strings, but as a lot of the entries were taking arrays of integer pairs, I figured I would follow suit for the sake of brevity.

For each tuple `$a` in array `$x` I echo a string of dashes repeated `$a[1] - $a[0]` times, padded up to the larger number `$a[1]` with spaces. Then the obligatory newline.
> 0 votes

# Answer
# Gema: 47 characters

```
<D>-\><D><y>=@left{$1;}@repeat{@sub{$2;$1};-}\n

```

Sample run:

```
bash-4.3$ gema '<D>-\><D><y>=@left{$1;}@repeat{@sub{$2;$1};-}\n' <<< '0->7,5->6,3->6'
-------
     -
   ---

```
> 0 votes

# Answer
# PostgreSQL: 160 characters

```
create function g(int[])returns text as
$$select string_agg(lpad(repeat('-',$1[x][2]-$1[x][1]),$1[x][2]),chr(10))from generate_subscripts($1,1)x$$
language sql;

```

Sample run:

```
manatwork=# create function g(int[])returns text as
manatwork-# $$select string_agg(lpad(repeat('-',$1[x][2]-$1[x][1]),$1[x][2]),chr(10))from generate_subscripts($1,1)x$$
manatwork-# language sql;
CREATE FUNCTION

manatwork=# select g(array[[0,7],[5,6],[3,6]]);
-------
     -
   ---

```
> 0 votes

# Answer
# J, 21 bytes

```
(' -'#~{.,-~/)"1 ::''

```

## ungolfed

```
(' -' #~ {. , -~/)"1 ::''

```

This is essentially just J's copy verb `#`, but its we're copying the space character head of list `{.` number of times, and the hyphen character "2nd list element minus 1st list element" number of times: `-~/`. Sadly this forces us to have to specify the rank `"1` explictly, and we need to use Adverse `::` to handle the empty case.

Try it online!
> 0 votes

# Answer
# Japt `-R`, ~~14~~ ~~10~~ 9 bytes

If the character used for the timeline can be anything we want then one byte can be saved replacing `-<space>` with `Ê`, which will use `l` instead of dashes.

```
®Ìç- hZÎî

```

Try it

---

## Explanation

```
®             :Map over each sub-array Z
 Ì            :  Get the last element of Z
  ç-          :  Repeat "-" that many times
     h        :  Set the characters starting at index 0 to
      ZÎ      :    Get the first element of Z
        î     :    Repeat <space> that many times
              :Implicitly join with newlines and output

```
> 0 votes

# Answer
## Perl 5 with `-054naF/->/ -M5.010`, 24 bytes

```
say"-"x$F[1]."\x0d".$"x"@F"

```

Try it online!

Only works in terminal because of the use of `"\x0d"` to overwrite the `-`s with s, but here's a cast of the script in action.

To recreate the script, use the below hexdump:

```
00000000: 7361 7922 2d22 7824 465b 315d 2e22 0d22  say"-"x$F[1]."."
00000010: 2e24 2278 2240 4622                      .$"x"@F"

```
> 0 votes

# Answer
# VBA, 75 bytes

A declared routine, `f(a)`, which takes input as an array of arrays, and outputs to the console.

```
Sub f(a)
For Each t In a
Debug.?Spc(t(0));String(t(1)-t(0),45)
Next
End Sub

```

### Example I/O

```
f Array(Array(28,35),Array(34,40),Array(39,44))
                            -------
                                  ------
                                       -----

```
> 0 votes

# Answer
# 05AB1E, 12 bytes

```
ε`sDð×?-'-×,

```

Try it online!

Takes input in the form `[[5,20],[5,20],[2,10],[15,19]]`.

Explanation:

```
ε`sDð×?-'-×,    IMPLICITLY INPUT ARRAY OF ARRAYS
ε               For each array [a, b] in input:
 `sD                Push stack b, a, a (a on top)
    ð               Push space to stack : [b, a, a, ' ']
     ×?             Print a spaces without newline, stack: [b, a]
       -'-×,        Print (b - a) dashes with newline, stack empty
                Implicit end of loop

```
> 0 votes

# Answer
# Tcl, 74 bytes

```
proc G L {lmap s\ e $L {puts [format %$e\s [string repe - [expr $e-$s]]]}}

```

Try it online!

---

~~Tcl, 76 bytes
```
proc G L {lmap s\ e $L {puts [format %$e\s [string repeat - [expr $e-$s]]]}}

```
Try it online!<br>~~

##

~~Tcl, 82 bytes
```
proc G L {lmap s\ e $L {puts [string repeat \  $s][string repeat - [expr $e-$s]]}}

```
Try it online!<br>~~
> 0 votes

# Answer
# Perl 6, 28 bytes

```
*.map: (' ','-'Zx*).join.say

```

Try it online!

Input is a list of 2-element lists:

```
(<0 7>,<5 6>,<3 6>)

```

Essentially we are using the `'b' x 3 = 'bbb'` operator `x` between the lists `' ', '-'` and `*` (the line input as a list), zipped via `Z`, hence the combined operator `Zx`.

In p6 golfing this seems... suboptimal.
> 0 votes

# Answer
# Momema, 75 bytes

```
m00*-8m+1-=+1*01+*-8-*0s0s+1-=*00+*0-1-9 32s1d0d+1-=*1 1+*1-1-9 45d1-9 10m1

```

Try it online!

Ungolfed:

```
main 0
0    *-8      # read user input
main +1-=+1*0 # terminate if zero

    1     +*-8-*0 # calculate number of '-' to print

    space 0
    space +1-=*0  # stop?
        0  +*0-1      # decrement counter
        -9 32         # print ' '
    space  1      # go back to start
    dash  0
    dash  +1-=*1  # stop?
        1  +*1-1      # decrement counter
        -9 45         # print '-'
    dash  1

    -9 10

main 1        # go to beginning

```
> 0 votes

# Answer
# Canvas, 10 bytes

```
｛┤∔α ×Ｐ-×ｐ

```

Try it here!
> 0 votes

# Answer
# Stax, 8 bytes

```
ÇÉ⌐öç♦}k

```

Run and debug it

## Explanation

```
mzsE|r'-&
m         map each pair and print with newline
 z        empty string
  s       swap with pair
   E|r    convert to range
      '-  - character
        & assign at indices(extends the empty string with spaces)

```
> 0 votes

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