Seven-Segment Devices
February 27, 2018
We have today a simple exercise from Jon Bentley’s book Programming Pearls, Chapter 3, Problem 8:
[S. C. Johnson] Seven-segment devices provide an inexpensive display of the ten decimal digits:
----- ----- ----- ----- ----- ----- ----- ----- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ----- ----- ----- ----- ----- ----- ----- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ----- ----- ----- ----- ----- ----- -----The seven segments are usually numbered as:
--2-- | | 3 4 | | --1-- | | 5 6 | | --0--Write a program that displays a 16-bit positive integer in five seven-segment digits. The output is an array of five bytes; bit i of byte j is one if and only if the ith segment of digit j should be on.
It was harder to type those digits than it looks.
Your task is to write a program to display numbers using seven-segment digits, as Bentley directs. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Simple perl one liner… first part converts the digits into a byte string {using tr}. The second just dumps it so it’s readable”
C++ solution:
Let’s try again with that sample output (at least in my browser, the last row of segments is missing):
In Python
Here’s a solution in C. calc_segments returns a 5-byte array with segment encodings. print_segments prints the segment encodings.
Example Usage:
Goofing around with Unicode operators in a Haskell solution.
Ah well, it looks like character widths are a bit different in the browser, compared to emacs and the terminal. You’ll have to pretend that the vertical sequence of digits in the code lines up nicely…
num=’0123456789′;
def add_symbols(index,sym):
if index==0:
layer_1.append(sym)
elif index in range(1,4):
layer_2.append(sym)
else:
layer_3.append(sym)
layer_1=[]
layer_2=[]
layer_3=[]
NUMBERS = {0:’1101111′, 1:’0001001′,2:’1011110′,3:’1011011′, 4:’0111001′, 5:’1110011′,6:’1110111′,7:’1001001′,8:’1111111′, 9:’1111011′}
ONE={0:’‘, 1:’|’,2:’‘,3:’|’, 4:’|’,5:’_’,6:’|’}
[add_symbols(i,” “) if a==’0′ else add_symbols(i,ONE.get(i)) for number in num for i, a in enumerate(NUMBERS.get(int(number))) ]
print(“”.join([ ” “+i+” ” for i in layer_1]) ,end=”” )
print(”)
print(“”.join([i for index,i in enumerate(layer_2)]) ,end=”” )
print(”)
print(“”.join([ i for i in layer_3]),end=””)
_ _ _ _ _ _ _ _
| | | | _||||_ |_ |||||
|| || | | _||| ||_| _|
Here’s a solution in racket: