| Bytes | Lang | Time | Link |
|---|---|---|---|
| 034 | Vyxal 3 j | 240904T113523Z | pacman25 |
| 045 | Uiua | 240415T204638Z | noodle p |
| 030 | Vyxal | 221008T234801Z | emanresu |
| 088 | sed 4.2.2 r | 240415T143030Z | guest430 |
| 183 | Go | 240416T150133Z | bigyihsu |
| 220 | Scala 3 | 240503T083259Z | 138 Aspe |
| 115 | Python 3 | 240417T100324Z | cnln |
| 031 | 05AB1E | 240417T131316Z | Kevin Cr |
| 082 | JavaScript Node.js | 240416T012451Z | Justin M |
| 036 | Japt R | 210614T104924Z | Shaggy |
| 047 | Vyxal j | 210614T061454Z | emanresu |
| 080 | x8616 machine code | 200831T173119Z | 640KB |
| 085 | Pip | 200831T102841Z | Razetime |
| 084 | Perl 5 | 170910T185012Z | Xcali |
| 045 | 05AB1E | 170911T155647Z | Magic Oc |
| 144 | Python 3 | 170911T105733Z | Bassinta |
| 192 | Kotlin | 170911T113055Z | jrtapsel |
| 146 | Python 2 | 150918T194450Z | Zach Gat |
| 227 | C# 227 Bytes | 150921T175140Z | anthonyt |
| 093 | Ruby | 150921T192716Z | Not that |
| 182 | PowerShell | 150918T205916Z | AdmBorkB |
| 095 | Ruby | 150921T191903Z | Not that |
| 263 | c99 | 150921T100159Z | Zaibis |
| 041 | CJam | 150919T004007Z | Sp3000 |
| 037 | Pyth | 150920T135209Z | Jakube |
| 159 | PHP | 150920T105807Z | zamnuts |
| 114 | Ruby | 150918T194004Z | Mohammad |
| 103 | Perl | 150919T101951Z | Dom Hast |
| 094 | Python 2 | 150919T091250Z | xnor |
| 120 | Python 2 | 150919T034857Z | Sp3000 |
| 172 | C++11 | 150918T202250Z | Zereges |
| 102 | Ruby | 150919T025352Z | Level Ri |
| 116 | GNU sed + dc | 150918T205433Z | Digital |
| 196 | Befunge93 | 150918T211826Z | El'e |
| 050 | Pyth | 150918T211847Z | Sok |
| 102 | JavaScript ES6 | 150918T202245Z | edc65 |
| 207 | Javascript ES6 | 150918T194801Z | adroitwh |
| 062 | CJam | 150918T201213Z | Andrea B |
| 026 | J | 150918T164925Z | lynn |
| 143 | Julia | 150918T181109Z | Alex A. |
Vyxal 3 j, 34 bytes
"+--"ṅṅṅ5Y?b₁Þ0'#×2«ᵛṅ4Ẇƛ'|j'|ø⁾]I
Similar to the other Vyxal answer but Vyxal 3 is lacking a few things. I found a handful of 34 byters
Uiua, 48 46 45 bytes
⊏:"+-| #"⍜♭(⇌⍜▽◌⊸=4)[⍥,7]+2↧⊸⇌⟜±◿4⇡17+3⬚0↙16⋯
My thought was to do a direct construction approach, as opposed to what other solutions are mostly doing which is building the output in a loop.
The bulk of the work is building the following matrix:
[[0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0]
[2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2]
[0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0]
[2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2]
[0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0]
[2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2]
[0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0]
[2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2]
[0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0]]
Both rows are built by starting with the range [0, 17) modulo 4:
⇡17 [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
◿4 [0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0]
first row:
[0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0]
± [0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0] (sign)
second row:
[0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0]
⇌ [0 3 2 1 0 3 2 1 0 3 2 1 0 3 2 1 0] (reverse)
↧ [0 1 2 1 0 1 2 1 0 1 2 1 0 1 2 1 0] (minimum of the two)
+2 [2 3 4 3 2 3 4 3 2 3 4 3 2 3 4 3 2]
The rows are combined into the matrix using [⍥,7] which repeatedly pushes the second-to-last row to the end of an array, seven times.
Take the binary representation of the input, padded to 16 bits. Add three to each digit, leaving 3 where there'd been zeros and 4 where there'd been ones. Then replace each four in the above matrix with a number from this list.
Finally, index each item into a string so that 0 becomes +, 1 becomes -, 2 becomes |, 3 becomes space, and 4 becomes #.
Vyxal, 31 30 bytes
\+3-4*5ε\|?b16∆Z\#*2↳ʁ+4ẇṠYvǏ⁋
? # Input
b # To binary
16∆Z # Pad to length 16 with 0s
\#* # That many #s, for each bit
2↳ʁ # Pad to length 2 with spaces and mirror
\| + # Prepend | to each
4ẇṠ # Divide into rows and stringify each
Y # Interleave with...
5ε # Five copies of
\+3- # "+---"
4* # Repeated four times
vǏ # For each line, append the first character
⁋ # Join the result by newlines
sed 4.2.2 -r, 109 108 107 105 104 88 bytes
-1 byte thanks to noodle man
s/.*/dc<<<4dvo8^&+p/e # change from base 10 to base 2, plus 65536
y/01/ #/ # change from '0,1' to ' ,#' everywhere
s/.// # subtract 65536
s//| & /g # put the digits in boxes
s/.{16}/&|\n/g # put the boxes on lines
s/^/+---+---+---+---+\n/gm # put border rows around the lines
someone brought me back here with an upvote and I found a much better strategy. now this answer also builds the answer up entirely in PATTERN space and outputs normally at the end, and there's no extra byte from using a in the y statement.
Go, 187 183 bytes
func(n uint16)(s string){H,N:="+---+---+---+---+",`
`
s+=H
for i:=range 4{for j:=range 4{if j<1{s+=N+"|"}
c:=" "
if n>>(16-(4*i+j+1))&1>0{c="#"}
s+=" "+c+" |"
if j>2{s+=N+H}}}
return}
- -4 bytes by Go 1.22+ range-over-int.
Scala 3, 220 bytes
220 bytes, it can be golfed more.
Ungolfed version. Attempt This Online!
n=>{val b=n.toBinaryString.reverse.padTo(16,'0').reverse;val m=b.grouped(4).toArray;val l="+"+("---+"*4);for(i<-0 to 3){println(l);val r=m.map(c=>if(c(i)>'0')"#"else" ").mkString("| "," | "," |");println(r)};println(l);}
Golfed version. Attempt This Online!
object Main {
def main(args: Array[String]): Unit = {
f(33825)
}
def f(n: Int): Unit = {
val b = n.toBinaryString.reverse.padTo(16, '0').reverse
val m = b.grouped(4).toArray
val l = "+" + ("---+" * 4)
for (i <- 0 until 4) {
println(l)
val row = m.map(col => if (col(i) > '0') "#" else " ").mkString("| ", " | ", " |")
println(row)
}
println(l)
}
}
Python 3, 110 121 119 115 bytes
(+11 bytes to handle user input, -6 bytes thanks to @noodle man!)
Had a lot of fun with this one. I think there are probably some bytes that can be knocked off, but I am happy with it for now!
def f(n):
i=1;e=a='+---'*4+'+\n'
for x in f'{n:016b}':e+=['| ','| # '][int(x)]+('|\n'+a)*(i%4<1);i+=1
print(e)
Explanation
## Initialise variables
j=['| ','| # '] # 0->' ' and 1->'#'
m=f'{int(input()):016b}' # Input to 16 digit binary
i=1 # i=1
a='+---'*4+'+\r\n' # a = +---+---+---+---+
e=a # Initialise output to above
for x in m: ## Loop through binary digits
e+=j[int(x)] # Convert to ' ' or '#'
e+=('|\r\n'+a)*(i%4<1) # Every 4th loop, newline and a
i+=1 # Increment i
As an aside, I had some fun figuring out some 16-bit graphics without converting to binary:
30855 44441 34966 44441
+---+---+---+---+ +---+---+---+---+ +---+---+---+---+ +---+---+---+---+
| | # | # | # | | # | | # | | | # | | | | | # | | # | |
+---+---+---+---+ +---+---+---+---+ +---+---+---+---+ +---+---+---+---+
| # | | | | | # | # | | # | | # | | | | | # | # | | # |
+---+---+---+---+ +---+---+---+---+ +---+---+---+---+ +---+---+---+---+
| # | | | | | # | | | # | | # | | | # | | # | | | # |
+---+---+---+---+ +---+---+---+---+ +---+---+---+---+ +---+---+---+---+
| | # | # | # | | # | | | # | | | # | # | | | # | | | # |
+---+---+---+---+ +---+---+---+---+ +---+---+---+---+ +---+---+---+---+
05AB1E, 31 bytes
b16jT„# ‡4äε€'|Ć"+---"17∍‚}€`Ć»
Try it online or verify both test cases.
Building the box first with placeholder-character and then replacing that placeholder with the #/ seems to be the exact same byte-count:
"+---"17∍'|X2F‚9∍}»$žH+„ #Åв¦.;
Try it online or verify both test cases.
Explanation:
b # Convert the (implicit) input-integer to a binary-string
16j # Pad leading spaces to make the length 16
T # Push 10
„# # Push "# "
‡ # Transliterate all "1"s to "#"s and "0"s to " "s
4ä # Split it into 4 equal-sized strings
ε # Map over each string of "#"s and spaces:
€'| '# Convert it to a list of characters, and place a "|" before each
Ć # Enclose; append its own head (append "|")
"+---" # Push string "+---"
17∍ # Extend it to size 17: "+---+---+---+"
‚ # Pair the list and this string together
}€` # After the map: revert each inner pair, and then flatten one level down
Ć # Enclose; append its own head (append "+---+---+---+")
» # Join each inner list of characters by spaces,
# and then all strings by newlines
# (after which the result is output implicitly, with trailing newline)
"+---"17∍ # Same as above: push "+---+---+---+"
'| '# Push "|"
X # Push 1
2F # Loop 2 times:
‚ # Pair the top two values on the stack together
9∍ # Extend this pair to size 9
}» # After the loop: join each inner list by spaces,
# and then all strings by newlines
$ # Push 1 and the input
žH+ # Add constant 65536 to the input
„ #Åв # Convert it to custom base-" #",
# basically convert it to base 2, and 0-based index into " #"
¦ # Remove the leading "#"
.; # Replace all 1s in the box one-by-one with these characters
# (after which the result is output implicitly, with trailing newline)
JavaScript (Node.js), 82 bytes
f=(x,i=16,h=`+---+---+---+---+
`)=>i?f(x/2,i-1)+"| "+" #"[x&1]+(i%4?" ":` |
`+h):h
Or try it with the interactive snippet below.
f=(x,i=16,h=`+---+---+---+---+
`)=>i?f(x/2,i-1)+"| "+" #"[x&1]+(i%4?" ":` |
`+h):h
I.oninput=()=>O.innerHTML=f(+I.value);
I.oninput();
<input id=I type=number min=0 max=65535 value=4242><br/>
<pre id=O>
Japt -R, 40 36 bytes
This'll need another pass once I'm properly caffeinated!
5Æ17î-³i+ÃíUs'#iS)ùG ®û3 i|ÃòG)cf ú|
5Æ17î-³i+ÃíUs'#iS)ùG ®û3 i|ÃòG)cf ú| :Implicit input of integer U
5Æ :Map the range [0,5)
17î : Repeat the following to length 17
-³ : "-" repeated 3 times
i+ : Prepend a "+"
à :End map
í :Interleave with
Us : U converted to a string in the following base
'#i : "#" prepended with
S : A space
) : End base conversion
ù : Left pad with spaces to length
G : 16
® : Map each character
û3 : Centre pad with spaces to length 3
i| : Prepend a "|"
à : End map
òG : Partitions of length 16
) :End interleave
c :Flatten
f :Filter out falsey elements (If the second array being interleaved is shorter than the first, it's padded with null)
ú| :Left pad each with "|" to the length of the longest
:Implicit output joined with newlines
x86-16 machine code, IBM PC DOS, 80 bytes
Binary:
00000000: b805 09ba 2801 cd21 fec8 741b be3e 01b1 ....(..!..t..>..
00000010: 04d1 e3c6 0420 7303 c604 2383 c604 e2f1 ..... s...#.....
00000020: ba3c 01cd 21eb dcc3 2b2d 2d2d 2b2d 2d2d .<..!...+---+---
00000030: 2b2d 2d2d 2b2d 2d2d 2b0d 0a24 7c20 2020 +---+---+..$|
00000040: 7c20 2020 7c20 2020 7c20 2020 7c0d 0a24 | | | |..$
Listing:
B8 0905 MOV AX, 0905H ; AH = DOS write string, AL = row counter
ROW_LOOP:
BA 0128 MOV DX, OFFSET SEP ; show separator row
CD 21 INT 21H ; write to console
FE C8 DEC AL ; displayed 5 separators?
74 1B JZ EXIT ; if so, exit
BE 013E MOV SI, OFFSET ROW+2 ; start SI at location of first bit in row
B1 04 MOV CL, 4 ; loop count 4
BIT_LOOP:
D1 E3 SHL BX, 1 ; shift MSb into CF
C6 04 20 MOV BYTE PTR[SI], ' ' ; reset to space char
73 03 JNC BIT_DONE ; if not CF, leave as a space
C6 04 23 MOV BYTE PTR[SI], '#' ; otherwise change to a #
BIT_DONE:
83 C6 04 ADD SI, 4 ; increment index 4 bytes
E2 F1 LOOP BIT_LOOP ; keep looping through bits
BA 013C MOV DX, OFFSET ROW ; show bit column row
CD 21 INT 21H ; write to console
EB DC JMP ROW_LOOP ; keep looping
EXIT:
C3 RET ; return to caller
SEP DB '+---+---+---+---+',0DH,0AH,'$'
ROW DB '| | | | |',0DH,0AH,'$'
Callable function, input in BX output to STDOUT.
Example test program:
Pip, 85 bytes
a:TBa
((" "X16-#a).aR0" "R1" # "<>3JW'|<>16J'|<>17JWn."+---+---+---+---+".n)@<-20
Does a straightforward bunch of splits and replacement to get the final grid.
Perl 5, 85 84 bytes
84 83 bytes of code + -p flag
-1 byte after Dom reminded me to use a newline
say$\='+'."---+"x4,"
| ",map y/01/ #/r.' | ',/./g for(sprintf"%016b",$_)=~/..../g}{
Python 3, 145 144 Bytes
Inline:
a="|";b="+"+"---+"*4+"\n";r=0,1,2,3;(lambda x:print(b+b.join(a+a.join(" %s "%'# '[x&2**(i+j*4)<1]for i in r)+a+"\n"for j in r)+b))(int(input()))
With newlines:
a="|"
b="+"+"---+"*4+"\n"
r=0,1,2,3
lambda x:print(b+b.join(a+a.join(" %s "%'# '[x&2**(i+j*4)<1]for i in r)+a+"\n"for j in r)+b)
x(int(input()))
Edit: Tanks @manatwork for saving 1 byte
Kotlin, 192 bytes
{val v=it.toString(2).padStart(16,'0')
fun p(){(0..3).map{print("+---")}
println("+")}
(0..3).map{p()
v.subSequence(it*4,(it+1)*4).map{print("| ${if(it>'0')'#' else ' '} ")}
println("|")}
p()}
Beautified
{
val v = it.toString(2).padStart(16, '0')
fun p() {
(0..3).map { print("+---") }
println("+")
}
(0..3).map {
p()
v.subSequence(it *4, (it +1) *4).map {print("| ${if (it > '0') '#' else ' '} ")}
println("|")
}
p()
}
Test
var b:(Int) -> Unit =
{val v=it.toString(2).padStart(16,'0')
fun p(){(0..3).map{print("+---")}
println("+")}
(0..3).map{p()
v.subSequence(it*4,(it+1)*4).map{print("| ${if(it>'0')'#' else ' '} ")}
println("|")}
p()}
fun main(args: Array<String>) {
b(255)
}
Python 2, 157 153 151 146 bytes
J=''.join;R='+---'*4;i=format(input(),'016b')
print J(R+'+\n|'+J(' '+('#'if int(l)else' ')+' |'for l in i[n*4:-~n*4])+'\n'for n in range(4)),R+'+'
Thanks to Morgan Thrapp for saving 4 bytes, and to Jonathan Frech for saving 5.
Usage
$ python test.py
33825
+---+---+---+---+
| # | | | |
+---+---+---+---+
| | # | | |
+---+---+---+---+
| | | # | |
+---+---+---+---+
| | | | # |
+---+---+---+---+
C# 227 Bytes
Golfed:
class B{public static string G(short v){string s="",b=System.Convert.ToString(v,2).PadLeft(16,'0');for(int i=9;i>0;){s+=i--%2!=0?"+---+---+---+---+\n":"| "+b[i*2+1]+" | "+b[i*2]+" | "+b[i*2-1]+" | "+b[i*2-2]+" |\n";}return s;}}
Indention:
class B
{
public static string G(short v)
{
string s="",b=System.Convert.ToString(v, 2).PadLeft(16,'0');
for(int i=9;i>0;)
s+=i--%2!=0?"+---+---+---+---+\n":"| "+b[i*2+1]+" | "+b[i*2]+" | "+b[i*2-1]+" | "+b[i*2-2]+" |\n";
return s;
}
}
First time I'm trying something like this, tips would be welcome!
Ruby, 93
A slightly shorter version using only numeric operations.
->i{n=g='+---'*4+"+
";15.downto(0){|m|n+="| #{[' ',?#][1&i>>m]} "
n+="|
"+g if m%4<1}
puts n}
PowerShell, 203 188 182 Bytes
param($a)$l="+---+---+---+---+";$l;$b=([int64][convert]::ToString($a,2)).ToString(@(,"0"*16)-join'');@(1..16|%{if($b[$_-1]-eq'1'){"| # "}else{"| "};if($_%4-eq0){"|`n$l`n"}})-join''
Edit - saved 15 bytes by changing the order that | are drawn, so we can dump the .TrimEnd("|") on the output and instead convert the for-loop into a subcode block that produces an array
Edit2 - saved another 6 bytes by eliminating need for saving into the $o variable and just outputting with -join'' directly.
Ooooooooof.
Drawing in PowerShell is hard. Working with binary digits in PowerShell is hard.
Uses built-ins to [convert] the input integer to a string representation in binary, then re-cast back to an [int64] so we can re-call .ToString() in order to prepend/pad the appropriate number of zeroes. (Note that creating an array of strings and joining them @(,"0"*16)-join'' is 1 character shorter than the literal string "0000000000000000")
Then, take a simple for-loop 1..16|%{...} checking each digit to build up our output array, then finally -join'' that back together.
Previous, 188
param($a)$l="+---+---+---+---+";$l;$b=([int64][convert]::ToString($a,2)).ToString(@(,"0"*16)-join'');$o=@(1..16|%{if($b[$_-1]-eq'1'){"| # "}else{"| "};if($_%4-eq0){"|`n$l`n"}});$o-join''
Previous-er, 203
param($a)$l="+---+---+---+---+`n|";$o=$l;$b=([int64][convert]::ToString($a,2)).ToString(@(,"0"*16)-join'');1..16|%{if($b[$_-1]-eq'1'){$o+=" # |"}else{$o+=" |"};if($_%4-eq0){$o+="`n$l"}};$o.TrimEnd('|')
Ruby, 95
Nod to Mhmd for a concise String conversion, but I wanted to try using string methods instead of number methods.
->i{puts g='+---'*4+?+;("%016b"%i).scan(/.{4}/){puts$&.gsub(/./){"| #{$&<?1?' ':?#} "}+"|
"+g}}
c99 263 bytes
golfed:
main(int argc,char **argv){short i=atoi(argv[argc-1]);char *t="| # ", *f="| ",*a[16],**p=a,*b="+---+---+---+---+\r\n";while(p<a+16){if((i|0x8000)==i)(*(p++))=t;else(*(p++))=f;i<<=1;}for(p=a;p<a+16;p+=4)printf("%s%s%s%s%s|\n",b,*p,p[1],p[2],p[3]);printf("%s",b);}
ungolfed:
main(int argc, char **argv)
{
short i=atoi(argv[argc -1]);
char *t ="| # ", *f="| ",*a[16],**p=a,*b="+---+---+---+---+\r\n";
while (p<a+16)
{
if((i|32768)==i)
(*(p++))=t;
else
(*(p++))=f;
i<<=1;
}
for (p=a;p<a+16;p+=4)
printf("%s%s%s%s%s|\n",b,*p,p[1],p[2],p[3]);
printf("%s",b);
}
I just liked to present a bit shifting variant and felt this is the first time its appropriate (even its costing me some bytes, but C can't this challange in bytes even with a chance so I don't care) to use the argc/argv
CJam, 43 41 bytes
'+5*'-3**N+ri2bG0e[4/{" #"f='|5*.\S*N2$}/
Definitely golfable, but it's a start I guess. Generates the top row, then for each 4 bits it creates an even row and copies the previous odd row.
Pyth, 37 bytes
Jj*3\-*5\+JVc4_m@" #".>Qd16jd.i*5\|NJ
Try it online: Demonstration or Test Suite
Explanation:
Jj*3\-*5\+J
*3\- the string "---"
*5\+ the string "+++++"
j join second by first string:
"+---+---+---+---+"
J save in J
J print J
Vc4_m@" #".>Qd16jd.i*5\|NJ
m 16 map each d in [0, 1, ..., 15] to:
.>Qd input number Q shifted to the right by d
@" #" and take the ^th char in " #" (modulo 2)
_ reverse this list of chars
c4 split into 4 groups
V for each group N in ^:
*5\| the string "|||||"
.i N interleave ^ with N
jd join chars with spaces and print
J print J
PHP, 159 bytes
bingrid16.php:
<?$r=10;while(--$r){if($r%2){echo str_repeat('+---',4).'+';}else{$c=9;echo'|';while(--$c){echo' '.($c%2?'|':($argv[1]&pow(2,$r*2+$c/2-5)?'#':' '));}}echo"\n";}
Usage:
php bingrid16.php 4242
Nothing fancy, just brute-forced the rendering.
I tried another angle using arrays instead of loops, but it was longer at 224 bytes:
<?=implode(array_map(function($r)use($argv){return($r%2?str_repeat('+---',4).'+':'|'.implode(array_map(function($c)use($r,$argv){return' '.($c%2?'|':($argv[1]&pow(2,$r*2+$c/2-5)?'#':' '));},range(8,1))))."\n";},range(9,1)));
Ruby, 118 114
b="%016b"%gets
l=?++"---+"*4
1.upto(16){|i|puts l if i%4==1
print"| #{b[i-1]==?0?' ':?#} "
puts ?|if i%4<1}
puts l
thanks for @w0lf for saving some characters.
Perl, 103 bytes
$_=(($l='+---'x4 .'+
').'| x 'x4 .'|
')x4 .$l;@n=(sprintf'%016b',<>)=~/./g;s/x/$n[$x++]?'#':$"/eg;print
Lots of string repetition to make a grid of xs, convert the input to binary and then s/// the xs to # or $" () depending on the flag at the specified position ($x).
Python 2, 94
n=input()
s=();exec"s=(' #'[n%2],)+s;n/=2;"*16
a='+---'*4+'+\n'
print(a+'| %s '*4+'|\n')*4%s+a
The idea is to take the pattern
+---+---+---+---+
| _ | _ | _ | _ |
+---+---+---+---+
| _ | _ | _ | _ |
+---+---+---+---+
| _ | _ | _ | _ |
+---+---+---+---+
| _ | _ | _ | _ |
+---+---+---+---+
except with %s in place of blanks and perform tuple substitution. The tuple looks like
('#', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#')
It is created by taking taking off digits from the input in binary and adding the corresponding symbol to the front of the tuple. An expression with explicit tuple gave equal length.
%tuple(' #'[c>'0']for c in bin(input()+4**8)[3:])
Thanks to Sp3000 for 2 bytes.
Python 2, 122 121 120 bytes
n=bin(4**8+input())[3:]
i=0
exec"print'| %s |'%' | '.join(' #'[x>'0']for x in n[:4])*i or'+---'*4+'+';n=n[4*i:];i^=1;"*9
-1 byte thanks to @xnor's neat 4**8+ trick. The main printing is done by looping 9 times, selecting the appropriate row for odd/even.
C++11, 193 191 190 176 172 bytes
My first solution on codegolf ever, so do not blame me.
#include<iostream>
int n,j,i=65536;int main(){std::cin>>n;for(;j<9;){for(int k:{0,0,0,0})if(j%2)printf("| %s",n&(i/=2)?"# ":" ");else printf("+---");puts(j++%2?"|":"+");}}
Ungolfed
#include <iostream>
int n, i = 65536, j;
int main()
{
std::cin >> n;
for (; j < 9;)
{
for(int k:{0,0,0,0})
{
if (j % 2)
{
printf("| %s", n & (i /= 2) ? "# " : " ");
}
else
{
printf("+---");
}
}
puts(j++ % 2 ? "|" : "+");
}
}
Previous version
#include <iostream>
using namespace std;
int n, i = 65536, j;
int main()
{
cin >> n;
for (; j < 9;)
{
for(int k:{0,0,0,0})
{
if (j % 2)
{
cout << "| " << (n & (i /= 2) ? "# " : " ");
}
else
{
cout << "+---";
}
}
cout << (j++ % 2 ? "|\n" : "+\n");
}
}
Ruby, 102
n=gets.to_i
print j="+---"*4+"+
"
19.downto(0){|i|print i%5>0?"| #{((n>>i*4/5)%2*3+32).chr} ":"|
"+j}
Algorithm
Print a horizontal divider
Loop 20 times (19..0)
If loop number does not divide by 5, convert into a number in the range 16..0 by multiplying by 4/5. Print a space (ascii 32) or # (ascii 32+3=35) preceded by | and followed by a space.
If loop number divides by 5, print a terminating |, newline, and a horizontal divider identical to the first.
GNU sed + dc, 116
Score includes +1 for -r flags to sed:
s/.*/dc -e2o&p/e
:
s/^.{,15}$/0&/;t
s/./| & /g
s/.{16}/\n+---+---+---+---+\n&|/g
y/01/ #/
s/\n([-+]+)(.*)/\1\2\n\1/
Test output:
$ { echo 4242 ; echo 33825 ; } | sed -rf 16bitgrid.sed
+---+---+---+---+
| | | | # |
+---+---+---+---+
| | | | |
+---+---+---+---+
| # | | | # |
+---+---+---+---+
| | | # | |
+---+---+---+---+
+---+---+---+---+
| # | | | |
+---+---+---+---+
| | # | | |
+---+---+---+---+
| | | # | |
+---+---+---+---+
| | | | # |
+---+---+---+---+
$
Alternatively:
Pure sed, 146
You might think it's cheating to use sed's GNU extension to eval a dc command. In that case, we can do this a little differently, according to this meta-answer. Of course the question clearly states that input must be in base 10, but here I'm attempting to claim that we can override that for sed answers and use unary (base 1) instead.
:
s/11/</g
s/<([ #]*)$/< \1/
s/1/#/
y/</1/
t
:a
s/^.{,15}$/0&/;ta
s/./| & /g
s/.{16}/\n+---+---+---+---+\n&|/g
y/01/ #/
s/\n([-+]+)(.*)/\1\2\n\1/
Test output
Using printf to generate the necessary unary string:
$ printf "%33825s" | tr ' ' 1 | sed -rf 16bitgrid.sed
+---+---+---+---+
| # | | | |
+---+---+---+---+
| | # | | |
+---+---+---+---+
| | | # | |
+---+---+---+---+
| | | | # |
+---+---+---+---+
$
Befunge-93, 196 218 bytes
&00p12*v>>4>"---+",v v <
v*:*:*:< | :-1,,,< #
>:*2/10p^ >"+",25*,10g|
> #v^# $< @
25*,^ >4" |",,v ,*<>
v>"#",00g10g-00p 10g
|`-1g01g00 <>48^
v>" ",10g
>2/10p>"| ",,1-:#^_$>^
To run the program...
- Go to the online interpreter.
- Paste this code in the big text box.
- Click
Show. - Input the desired number in the
Inputbox. - Click
Run. (Or changeSlowto something like 5 milliseconds and then clickShow.) - Ta-da!
Output for 4242:
+---+---+---+---+
| | | | # |
+---+---+---+---+
| | | | |
+---+---+---+---+
| # | | | # |
+---+---+---+---+
| | | # | |
+---+---+---+---+
Output for 33825:
+---+---+---+---+
| # | | | |
+---+---+---+---+
| | # | | |
+---+---+---+---+
| | | # | |
+---+---+---+---+
| | | | # |
+---+---+---+---+
Explanation
Oh goodness, what have I got myself into? Well, here goes! (Irrelevant code is replaced with .s.)
Part 1: Get input (store in 0,0) and calculate 32768 (store in 1,0).
&00p12*v>
v*:*:*:<
>:*2/10p^
Part 2: Print out "+---+---+---+---".
>4>"---+",v
| :-1,,,<
Part 3: Print "+" and a newline and check to see if (1,0) is 0 (i.e. we're done). If so, terminate. Otherwise, continue.
........... v <
| ....... #
>"+",25*,10g|
v.# $< @
>4" |",,v ...
Part 4: Get binary digits of input, updating (0,0) and (1,0) as we go along. Print the right things. I take advantage of Befunge's wrap-around behavior.
..... >4" |",,v ,*<.
v>"#",00g10g-00p 10g
|`-1g01g00 <>48^
v>" ",10g
>2/10p>"| ",,1-:#^_...
Part 5: Print a newline and go back to the part that prints "+---+---+---+---+". Wrap-around trick is used.
> #.^. .. .
25*,^ ......... ...>
................ ...
......... .....
........
.................._$>^
Ta-da!
Pyth, 50 bytes
j.i*5]<3*5"+---"ms.i*5\|dc4mj@" #"qd\1*2\ .[Z16.BQ
Explanation will have to wait until another time, I'm posting this on my phone!
JavaScript (ES6), 102
... or 96 using return instead of console.log.
Test running the snippet below in an EcmaScript 6 compliant browser.
f=n=>{for(o=h=`
+---+---+---+---+
`,z=16;z--;n/=2)o=(z&3?'':h+'|')+` ${' #'[n&1]} |`+o;console.log(o)}
// TEST
console.log=x=>O.innerHTML=x+O.innerHTML
function test(n) { f(n); console.log(n); }
<input id=I value=4680><button onclick='test(+I.value)'>-></button>
<pre id=O></pre>
Javascript (ES6), 216 207 bytes
Defines an anonymous function.
i=>(","+("0".repeat(16)+i.toString(2)).slice(-16).split``.map((v,l,a)=>l%4<1?"| "+a.slice(l,l+4).map(v=>v?"#":" ").join` | `+" |":"").filter(v=>!!v).join`,`+",").replace(/,/g, `
+---+---+---+---+
`).slice(1)
Thanks to ETHproductions for tips!
J, 26 bytes
(' ';' # '){~4 4$_16{.#:
An anonymous verb. Thankfully, J is very good at drawing boxes. Let's try it out:
f =. (' ';' # '){~4 4$_16{.#:
f 4242
+---+---+---+---+
| | | | # |
+---+---+---+---+
| | | | |
+---+---+---+---+
| # | | | # |
+---+---+---+---+
| | | # | |
+---+---+---+---+
As some commenters have mentioned, the way J draws boxes is system-dependent: on some platforms, this code will work under the default settings, but on others, the boxes will be drawn using Unicode line drawing characters. (The commands 9!:6 and 9!:7 allow you to query and set the characters to draw boxed values with, respectively.)
Julia, 156 143 bytes
n->(p=println;l="+"*"---+"^4;for i=1:4 p(l,"\n| ",join([j>"0"?"#":" "for j=reshape(split(lpad(bin(n),16,0),""),4,4)[:,i]]," | ")," |")end;p(l))
Ungolfed:
function f(n::Int)
# Convert the input to binary, padded to 16 digits
b = lpad(bin(n), 16, 0)
# Split b into a 4x4 matrix
m = reshape(split(b, ""), 4, 4)
# Store the line separator for brevity
l = "+" * "---+"^4
# Print each column of the matrix as a row
for i = 1:4
println(l, "\n| ", join([j > "0" ? "#" : " " for j = m[:,i]], " | "), " |")
end
# Print the bottom of the table
println(l)
end
