# Emulate a 7-segment display

The task is to display any of the 128 possible states of a 7-segment display.

Your program should accept a string of 7 characters ("bits") that are either 0 or 1. First bit of input corresponds to segment A of the following illustration, the second to B, etc (ignore dp):

How you represent the display is up to you -- a single Unicode or ASCII symbol, ASCII art, grafically, or whatever you can come up with. However, each input must have it's own distinct output. If you come up with something fancy I'm sure you can harvest upvotes by showing off some examples.

All 128 possible states of the display are:

# Rules

• Codegolf
• As I said, any kind of output is allowed, but it would be nice if you specified it.
• Input can be stdin or command line argument.

# Examples

### Input

1101101


### Output

As ASCII/Unicode:
2

Different kinds of ASCII art (I'm not too good at this)
 _   ╺┓  ╒╗   ---
_|  ┏┛  ╔╝     |
|_   ┗╸  ╚╛   ---
|
---

• Closely related to codegolf.stackexchange.com/questions/997/… ? – DavidC Dec 20 '12 at 21:49
• @DavidCarraher: They're related, yes; I even linked to it myself. However, this is slightly harder I would say, as you have 118 more 'numbers' to generate. Most(?) of the answers to the other question would not work here, or would have to be heavily rewritten. Also, here you don't need to encode the different numbers, so other optimizations shuld be possible. – daniero Dec 20 '12 at 22:02
• You are correct. Thanks for pointing that out. – DavidC Dec 20 '12 at 23:58
• it is a requirement that we use the encoding you provided? e.g. "1101101" should always represent "2" ? – ardnew Dec 21 '12 at 17:58
• @ardnew: yes. The position of the bits in input should map to the alphabetical order of the segments A to G in the first picture. – daniero Dec 21 '12 at 21:19

## J (51)

1 2 1#"1[5 3$' #'{~,|:>0;(88707#:~7#7){>".&.>1!:1[1  output: 1101101 ## # ## # ##  • This can be shaved down to 38 char with a little effort: 1 2 1#"1' #'{~5 3$,0,.502 A.".&>1!:1]1. – algorithmshark Apr 10 '14 at 21:56

## C, 106

Size is 74 chars if allowed to rename program "W00WG5WW1GW66WG4WW2GW33WG"

main(int i,char**s){
for(s[0]="W00WG5WW1GW66WG4WW2GW33WG";i=*s[0]++;putchar(s[1][i&7]-49?i==71?10:32:42));
}


running:

./a.out 1101101
**
*
**
*
**


notes:

'W' and 'G' (0x47 and 0x57) are chosen such that the value & 7 = 7, i.e they safely index the null character that terminates the input string.

## Brainfuck - 224

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


Prints using Exlamation points:

 !
! !
!
! !
!


Not the most readable, but not too horrible either.

Surprised at how close this is to not being last place.

# Postscript 121 107

1 12 moveto{}5 0{0 -5 rmoveto}0 5 0 5 -5 0 0 -5 0 -5 5 0
n{49 eq{rlineto}{rmoveto}ifelse exec}forall stroke


requires n to be defined as the string to process so invoke like

gs -g7x14 -sn=1101101 lcd.ps


to get

the complete set is

## Mathematica: 135129 118, image display

Image[MorphologicalComponents@Import@"http://goo.gl/j3elE" /.
Thread[Range@7 -> IntegerDigits[#, 2, 7][[{7, 2, 6, 1, 3, 5, 4}]]]] &


Edit

For those picky fellow site users: Without using an external mask:

Image[MorphologicalComponents[ColorNegate@Rasterize@8, CornerNeighbors -> False] /.
Thread[Range@7 ->IntegerDigits[#, 2, 7][[{7, 2, 6, 1, 3, 5, 4}]]]] &

• The code appears to be incomplete. I don't think you wanted your program to terminate with &. – DavidC Dec 22 '12 at 22:11
• @DavidCarraher It's a function,so it ends with &. – Dr. belisarius Dec 22 '12 at 22:16
• Yes, but it is not applied to anything. How does one obtain output? – DavidC Dec 22 '12 at 23:25
• @belisarius I still don't like the fact that you embed external ressources. – FUZxxl Dec 27 '12 at 19:53
• I think it does not make any sense to remove my previous comment as that would make it much harder for somebody else to follow this discussion. You import external data which is funny as a joke but not part of a serious code golf answer. -1 – FUZxxl Dec 27 '12 at 23:17

## APL, 58 55

' _|'[1+3 3⍴0,x[1],0,(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3]]


Example input:

1101101


Output:

 _
_|
|_


⍞='1' takes the input as a character array and converts it to a numeric array.

1 2 2 1 2 2 1×⍞='1' converts that array to: 0 for blank, 1 for _, 2 for |

(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3] assign that array to variable x and reorder to represent segments F, G, B, E, D, C

0,x[1],0,(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3] concatenates a blank, segment A and another blank to the front

3 3⍴0,x[1],0,(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3] reshape to a 3x3 matrix

1+3 3⍴0,x[1],0,(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3] converts to 1-based indexing

Finally uses the string ' _|' to convert indicies into characters

## Edit

' _|'[1+3 3⍴(0,1 2 2 1 2 2 1×⍞='1')[1 2 1 7 8 3 6 5 4]]


Shaved off 3 chars by concatenating a 0 to front the array and using duplicate indicies, preventing a variable assignment

• Iff your APL supports it, I think the from function { is 1-char shorter than bracket indexing []. – luser droog Mar 22 '15 at 7:32

<?for(;11>$i;)echo++$i&3?$argv[1][md5(¡æyÚ.$i)%8]?$i&1?~ƒ:_:~ß:~õ;  A slight improvement using an md5 magic formula, but requires 3 additional binary bytes: ¡, æ, and Ú are characters 161, 230, and 218 respectively. It should work as is if copied directly, and saved as an ANSI format. ## PHP 73 (70) bytes <?for($s=327638584;3<$s;)echo++$i&3?$argv[1][7&$s/=8]?$i&1?'|':_:' ':' ';  If you'll allow me three binary characters, this can be reduced to 70 bytes: <?for($s=327638584;3<$s;)echo++$i&3?$argv[1][7&$s/=8]?$i&1?~ƒ:_:~ß:~õ;  where ƒ, ß, and õ are characters 131, 223, and 245 respectively. Receives input as a command line argument. Sample usage: $ php seven-seg.php 1101101
_
_|
|_

$php seven-seg.php 0111011 |_| _|  • i tried to run your code, but am getting loads of error :( i dont understand your logic but seems interesting. – D34dman Feb 25 '13 at 16:26 • @D34dman The only messages it will produce are notices (undefined variables, etc). These can either be turned off in php.ini (by default they already are), or for testing, you can prepend the following code to the script: <? error_reporting(E_ALL & ~E_NOTICE); ?> – primo Feb 26 '13 at 5:25 • awesome! i got it working :D naice! – D34dman Feb 26 '13 at 8:30 ## JavaScript + jQuery + HTML + CSS (210 201) This solution uses CSS sprites and the image provided as an example: ### HTML (3) <a>  ### CSS (82 71) Thanks to xem for the "background:url" trick: a{background:url(//bit.ly/VesRKL);width:13px;height:23px;display:block}  ### JavaScript (125 after removing newlines added here for readability) i=prompt(); x=-parseInt(i.substr(0,3),2)*23; y=-parseInt(i.substr(3),2)*13.75;$('a').css('background-position',y+'px '+x+'px');


Online test: http://jsfiddle.net/zhqJq/3/

• Hey, but what about the 17.937 bytes of the image?? ;) – Thomas W. Dec 27 '12 at 17:35
• @ThomasW. I don't know whether that should be counted as well. Let's leave this to the OP to decide. – Cristian Lupascu Dec 27 '12 at 20:33
• You could use <p> tag and avoid display:block on CSS to save space – Roberto Maldonado Apr 10 '14 at 20:42
• background-image:url(bit.ly/VesRKL); => background:url(//bit.ly/VesRKL); – xem Apr 10 '14 at 21:28
• @xem thanks for the tip; I've edited my answer – Cristian Lupascu Apr 11 '14 at 13:09

# R (65 chars):

plot((3^(1i*1.5:-4.5)*(1:7!=7)),col=strsplit(readline(),'')[[1]])


Relies on some loose approximations for some transcendental nuumbers ...

# Python 2 - 65

s=raw_input()+'0\n'
for i in0x623C239E38D2EAA1:print s[int(i)],


Example:

echo 1101101|python2 7seg.py
0 1 0
0 0 1
0 1 0
1 0 0
0 1 0


PostScript: 53 binary, 87 ASCII 52 binary, 86 ASCII

Hexdump of the program using binary tokens:

111000

*
*

*

$./7seg.py 1111111 * * * * * * *  • Nice, but that lambda seems unnecessary: print' {0}\n{5} {1}\n {6}\n{4} {2}\n {3}'.format(*[' *'[i=='1']for i in raw_input()]) ;) No need for brackets and space for the print statement either. – daniero Jan 6 '13 at 20:46 • Wow! I didn't know you could put booleans in indexers. Thanks :-) – Brigand Jan 6 '13 at 21:30 • Np. Also, >'0' instead of =='1' and input() (with backticks around, but that won't show up because of the formatting here) instead of raw_input(). – daniero Jan 6 '13 at 21:52 • fyi, you can use tripple backticks if you need backticks in the code x = input()  – Brigand Jan 6 '13 at 22:00 • Cool. Then I learned something today too :) – daniero Jan 6 '13 at 23:21 I thought we needed a lispy answer... # Clojure, 159 chars (print(apply str(flatten(interpose\newline(partition 3(map(fn[x](if(= x\1)\o" "))(str" "(apply str(interpose" "(map(vec(read-line))[0 5 1 6 4 2 3])))" ")))))))  The above will run in the REPL and provide the correct answer. For example: 1111111 o o o o o o o  Throwing numbers at it with small modifications: (doseq [i ["1111110" "0110000" "1101101" "1111001" "0110011" "1011011" "1011111" "1110000" "1111111" "1111011"]] (println (apply str(flatten(interpose\newline(partition 3(map(fn[x](if(= x\1)\o" "))(str" "(apply str(interpose" "(map(vec i)[0 5 1 6 4 2 3])))" "))))))) (println))  yields:  o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o nil  Not easy to read, but they're there! ## Javascript 123 s=prompt(i=o='');for(m=' 0516423';i++<15;i%3==0?o+='\n':1)o+=' ─│'[~i%2&(A=+s[+m[~~(i/2)]])+(A&+'110'[i%3])];console.log(o)  I can bring the character count lower (101) if we use only one character for the "on" state, but it is less legible: s=prompt(i=o='');for(m=' 0516423';i++<15;i%3==0?o+='\n':1)o+=' ■'[~i%2&s[+m[~~(i/2)]]];console.log(o)  • +1 This is impressive. I'm still trying to reverse-engineer it. It's taught me a few things already! – guypursey Mar 7 '13 at 18:28 # Postscript 136 Not winner, but a different approach. 15 string exch{1 and 255 mul}forall [7 3 9 13 11 5 1]{count 1 sub index 3 1 roll exch put}forall 3 5 8[.02 0 0 .05 0 0]{}image showpage  Expects the input string to be on the stack: $ echo '(1101101)'|cat - 7seg.ps |gs -sDEVICE=png16 -sOutputFile=6c.png -


This one's even worse. 294 to make a "binary" bitmap. I took me a while to remember that each row is padded to an even byte. So a 3x5 bitmap is five bytes with the 3 msb bits significant.

2#1101101
(12345)exch
2 copy 64 and 0 exch put %A
2 copy 2 and 6 bitshift 2 index 32 and or 1 exch put %F B
2 copy 1 and 6 bitshift 2 exch put %G
2 copy 4 and 5 bitshift 2 index 16 and 1 bitshift or 3 exch put %E C
2 copy 8 and 3 bitshift 4 exch put
pop
3 5 1[.02 0 0 .02 0 0]{}image showpage


Output is just as ugly as the other one. :(

Alright here's one that looks good. 190

Edit: It was upside-down and backwards. Fixed now.

(1101101)
1 string dup 0 4 3 roll put}forall
(\377){@/g/f/e/d/c/b/a}{exch def}forall
@ a a @
b @ @ f
b @ @ f
@ g g @
c @ @ e
c @ @ e
@ d d @
4 7 8[.01 0 0 .01 0 0]{}image showpage

• This shows me some funny patterns. Is there still a bug somewhere? – Thomas W. Dec 27 '12 at 8:10
• hmm. yeah. (1111110) does not look like a zero. It's just an enlarged bytemap. I guess boxes is oversimplified. :( – luser droog Dec 27 '12 at 8:35
• it's kindof in the nature of this bitmap approach, I think. I'm not sure how to make it not ugly. – luser droog Dec 27 '12 at 9:13
• Some light commentary available here. – luser droog Jan 25 '13 at 7:04

# Mathematica 264

Getting the output to look right required many bytes, so no cigar this time. But here's the verbose (264 chars) code anyway.

{a, b, c, d, e, g} = {{-1, 5}, {1, 5}, {1, 3}, {1, 1}, {-1, 1}, {-1, 3}};
f@n_ := Graphics[{Yellow, Thickness[.1], CapForm["Round"],
Line /@ {{g, c}, {g, a}, {g, e}, {e, d}, {d, c}, {c, b}, {b, a}}[[Flatten@
Position[IntegerDigits[n, 2, 7], 1]]]},
Background -> Blue, PlotRange -> {{-1, 1}, {1, 5}}, PlotRangePadding -> 1]


The complete set of characters:

GraphicsGrid[Partition[Table[f[p], {p, 0, 128}], 16]]


The digits:

{f[63], f[6], f[91], f[79], f[102], f[109], f[125], f[7], f[127], f[111]}


PHP - 155 characters

<?php
$y=array(" \n"," - \n"," \n"," |\n","| \n","| |\n");$x = $argv[1]; echo$y[$x[0]].$y[2*$x[6]+$x[2]+2].$y[$x[7]].$y[2*$x[5]+$x[3]+2].$y[$x[4]];  it would be 150 characters if we use php 5.4 type array declaration, but i dont have that installed on my laptop so couldn't test it. Sample out puts. Explanation: First i divided the 7 segment display to Five rows and 3 columns. With 1st, 3rd and 5th row havimg '-' in the middle column, and space otherwise. The 2nd and 4th row has a pipe '|' character in the first and last column. Now the presence of these character should be guided by the input values. I created a lookup table, which is basically two lookup table. First one for the calculation of values for 1st, 3rd and 5th row. And another one at offset 2 ( 3rd item ) for calculation of rows 2nd and 4th. # Java - 204 characters class A{public static void main(String[]a){char[]c=new char[7];for(int i=0;i<7;i++)c[i]=a[0].charAt(i)==49?i%3==0?95:'|'):32;System.out.printf(" %c %n%c%c%c%n%c%c%c",c[0],c[5],c[6],c[1],c[4],c[3],c[2]);}}  Sample output:  _ _| |_  Formatted properly: class A { public static void main(String[] a) { char[] c = new char[7]; for (int i = 0; i < 7; i++) c[i] = a[0].charAt(i) == 49 ? (i % 3 == 0 ? 95 : '|') : 32; System.out.printf(" %c %n%c%c%c%n%c%c%c", c[0], c[5], c[6], c[1], c[4], c[3], c[2]); } }  Really wish I could avoid that for loop, but I tried a few other things and they were all longer. There's probably a better way to do this, but this is my first attempt at code golf. (And Java's like the worst language for it, which is why I thought it would be interesting.) Even Brainfuck has me beat, but at least my output looks nicer. EDIT: can get rid of "public" on class, saves me 7 chars! And thanks, daniero, for showing me printf! (18 chars saved) Rewrote the output format, changed character literals to decimal, 12 chars saved. • Welcome to codegolf.se! Java introduced a printf method a few versions back, which is basically println and format in one (like the C function); This will save you some characters, – daniero Apr 10 '14 at 22:01 • Here's another trick: You can combine the "body" of the for loop and the update part into one, saving one character: for(int i=7;i>0;c[--i]=a[0].charAt(i)==49?(i%3==0?95:'|'):32); – daniero Apr 11 '14 at 14:51 ## VBA - 263 It's ugly but it works, I think. I am having trouble viewing the proper bit order, so I'm inferring from others' answers. Even if that piece is wrong, the code length should remain the same. Sub d(b) Dim c(1 To 7) For a=1 To 7 c(a)=Mid(b,a,1) Next x=" - " y="|" z=" " w=" " v=vbCr MsgBox IIf(c(1)=1,x,w) & v & IIf(c(6)=1,y,z) & z & IIf(c(2)=1,y,z) & v & IIf(c(7)=1,x,w) & v & IIf(c(5)=1,y,z) & z & IIf(c(3)=1,y,z) & v & IIf(c(4)=1,x,w)End Sub  VBScript - 178 characters m=Split("2 7 11 10 9 5 6") s=" _ "&vbCr&"|_|"&vbCr&"|_|" For x=1 To 7 If Mid(WScript.Arguments.Item(0),x,1)=0 Then r=m(x-1):s=Left(s,r-1)&" "&Right(s,Len(s)-r) Next MsgBox s  • Thanks! Couple bonehead mistakes cost me 6 characters. I can almost get this down to the size of the VBA one even with the absurdly long call to get the function line argument. – Comintern Mar 3 '13 at 4:31 • Unless your code is functional without the newline characters, you have to count them too. This has 178 characters according to my count. – manatwork Mar 4 '13 at 9:58 # CJam - 29 l0N]s7078571876784728737Ab\f=  CJam is a new language I am developing, similar to GolfScript - http://sf.net/p/cjam. Here is the explanation: l reads a line from the input 0 is the number 0 N is a variable preinitialized to the newline string ] gathers the elements on the stack into an array s converts a value (the array) to string, thus appending a zero and a newline to the given input 7078571876784728737 is a number (the same number I used in python, but it was in hex there) A is a variable preinitialized to 10 b does a base conversion, generating the array [7 0 7 8 ... 3 7] \ swaps the last two values on the stack f= applies the = operator (here, indexed array access) on the input string (plus zero and newline) and each number 7, 0, 7, ... The index 7 corresponds to the appended zero, and 8 corresponds to the appended newline. My python solution does exactly the same thing (except the digit separation is done via string conversion) • What am I looking at here? Care to offer a brief explanation of the code? – daniero Apr 10 '14 at 16:47 • @daniero I added an explanation – aditsu Apr 10 '14 at 18:30 # VBA, 188 characters Note that the one has to type 188 characters if only including mandatory whitespace -- the IDE expands it out when you copy it into the VBA editor. Sub f(i) Dim c() As Byte m=Split("1 6 10 9 8 4 5") c=StrConv(" _ |_| |_|",128) c(3)=10 c(7)=10 For x=1 To 7 If Mid(i,x,1) = 0 Then c(m(x-1))=32 Next MsgBox StrConv(c,64) End Sub  Sadly, VBScript doesn't have a strongly typed Byte array, or that one could be much shorter using this method. # Javascript (ECMAScript 2016) - 108 bytes console.log(([a,b,c,d,e,f,g]=[...prompt()].map((x,i)=>+x?'_||'[i%3]:' '),${a}
${f}${g}${b}${e}${d}${c}))


This probably can be golfed further, but I can't think of anything.

• Welcome to the site! That's a nice first entry :) – daniero Oct 17 '18 at 7:37

# SmileBASIC, 136 bytes

DIM A[7,2]COPY A,@L@L?DATA.,1,1,3,4,3,6,1,4,0,1,0,3,1INPUT X$FOR I=0TO 6M=I MOD 3GBOX A[I,1],A[I,0],A[I,1]+!M,A[I,0]+!!M,-VAL(X$[I])NEXT


Output is graphical.

# 05AB1E, 4 bytes

C₄+ç


See the verify all possible inputs link above to see the mapping used for each input.

Explanation:

This abuses the rules where it states:

How you represent the display is up to you -- a single Unicode or ASCII symbol, ASCII art, grafically, or whatever you can come up with. However, each input must have it's own distinct output.

C       # Convert the (implicit) input from binary to integer
₄+     # Increase it by 1000
ç    # Convert it to a unicode character with this value (and output implicitly)


Alternative more in the spirit of the challenge using the output-format:

 -
| |
-
| |
-


### 38 bytes:

Σ•L7×•Nè}εi" -| | "14∍2ôNèëðº]J24S5∍£»


Can definitely be golfed..

Explanation:

Σ       }          # Sort the (implicit) input-digits by:
•L7×•Nè           #  The digit at the same index in the compressed integer 1367524
#   i.e. "1101101" → ["1","0","1","1","1","0","1"]
ε                  # Then map each digit to:
i                 #  If it's a 1:
" -| | "         #   Push string " -| | "
14∍      #   Lengthen it to size 14: " -| |  -| |  -"
2ô    #   Split it into parts of 2: [" -","| ","| "," -","| ","| "," -"]
Nè  #   Index into it
ë                 #  Else (it's a 0):
ðº               #   Push "  " (two spaces) instead
]              # Close both the if-else and map
#  i.e. ["1","0","1","1","1","0","1"]
#   → [" -","  ","| "," -","| ","  "," -"]
J                  # Join everything together to a single string
#  i.e. [" -","  ","| "," -","| ","  "," -"] → " -  |  -|    -"
24S               # Push [2,4]
5∍             # Lengthened to size 5: [2,4,2,4,2]
£            # Split the string into parts of that size
#  i.e. " -  |  -|    -" → [" -","  | "," -","|   "," -"]
»           # Join by newlines (and output implicitly)
#  i.e. [" -","  | "," -","|   "," -"] → " -\n  | \n -\n|   \n -"


See this 05AB1E tip of mine (section How to compress large integers?) to understand why •L7×• is 1367524.

# PHP 5.6, 65 bytes plain ASCII

for(;$p++<9;)echo$argn[_707561432[$p]]?"||_"[$p%3]:" ","\n"[$p%3];  or, without a trailing linebreak, but with some bitwise fun: for(;$p++<11;)echo$argn[_70785618432[$p]]?L|Sx[$p&1]:a^kAAA[$p&3];


Run as pipe with -nR or try them online.

breakdown 1

for(;$p++<9;)echo # loop through positions$argn[_707561432[$p]] # map position to input bit ?"||_"[$p%3]            # if set: underscore in 2nd column, pipe symbol else
:" "                    # else space
,"\n"[$p%3] # add newline every 3 columns ;  breakdown 2 for(;$p++<11;)echo          # loop through positions
$argn[_70785618432[$p]] # map position to input bit (bit 8 for EOL, never set)
?L|Sx[$p&1] # if set: underscore in the middle, pipe symbol else :a^kAAA[$p&3]           # else: newline in 4th column, space else
`
• Whether the language is new or old doesn't matter anymore since the Summer of 2017. So you won't have to mention non-competing. – Kevin Cruijssen Oct 16 '18 at 12:38
• @KevinCruijssen Thanks I missed that. But it´s also a nice challenge to revive old PHP versions; it also sometimes gives a different view on more recent features: I found, on occasions, that the "old" way is more efficient (in size, in performance, in readability and sometimes all three) than using stuff that was added to PHP later No golfing advantage in this case, though: The first approach would require 8 extra bytes, the second one 5. – Titus Oct 16 '18 at 13:43