Seven-Segment Devices
February 27, 2018
We ignore the restriction on 16-bit integers and write a program to output any number of digits. The output is a list of numbers, one for each digit. The correspondence of input digit to output number can be pre-computed:
0: 2^0 + 2^2 + 2^3 + 2^4 + 2^5 + 2^6 = 125 1: 2^4 + 2^6 = 80 2: 2^0 + 2^1 + 2^2 + 2^4 + 2^5 = 55 3: 2^0 + 2^1 + 2^2 + 2^4 + 2^6 = 87 4: 2^1 + 2^3 + 2^4 + 2^6 = 90 5: 2^0 + 2^1 + 2^2 + 2^3 + 2^6 = 79 6: 2^0 + 2^1 + 2^2 + 2^3 + 2^5 + 2^6 = 111 7: 2^2 + 2^4 + 2^6 = 84 8: 2^0 + 2^1 + 2^2 + 2^3 + 2^4 + 2^5 + 2^6 = 127 9: 2^0 + 2^1 + 2^2 + 2^3 + 2^4 + 2^6 = 95
Of course, I wrote a program to make that computation:
(define (digit . xs) (let loop ((xs xs) (sum 0)) (if (null? xs) sum (loop (cdr xs) (+ sum (expt 2 (car xs)))))))
> (digit 0 2 3 4 5 6) ; 0 125 > (digit 4 6) ; 1 80 > (digit 0 1 2 4 5) ; 2 55 > (digit 0 1 2 4 6) ; 3 87 > (digit 1 3 4 6) ; 4 90 > (digit 0 1 2 3 6) ; 5 79 > (digit 0 1 2 3 5 6) ; 6 111 > (digit 2 4 6) ; 7 84 > (digit 0 1 2 3 4 5 6) ; 8 127 > (digit 0 1 2 3 4 6) ; 9 95
Then it’s easy to solve Bentley’s task:
(define (bentley n) (let ((ds (vector 125 80 55 87 90 79 111 84 127 95))) (map (lambda (d) (vector-ref ds d)) (digits n))))
> (bentley 3141592654) (87 80 90 80 79 95 55 111 79 90)
You can run the program at https://ideone.com/FqkeCR.
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: