[ home / board list / faq / random / create / bans / search / manage / irc ] [ ]

/prog/ - Programming

Programming board

Catalog

Name
Email
Subject
Comment *
File
* = required field[▶ Show post options & limits]
Confused? See the FAQ.
Embed
(replaces files and can be used instead)
Options
Password (For file and post deletion.)

Allowed file types:jpg, jpeg, gif, png, webm, mp4, pdf
Max filesize is 8 MB.
Max image dimensions are 10000 x 10000.
You may upload 1 per post.


File: 1428855176548.jpg (76 KB, 500x362, 250:181, kid_programming.jpg)

3c1daf No.2017

Write a program that takes a string of digits and prints them back out in LED style.
./led 1234567890
_ _ _ _ _ _ _ _
| _| _| |_| |_ |_ | |_| |_| | |
| |_ _| | _| |_| | |_| _| |_|


My solution in Python3.
#!/usr/bin/env python3

from sys import argv
from sys import exit

if argv[1].isdigit():
digits = argv[1]
else:
print("gimme digits, fucko")
exit(1)

leds = {"0": [" _ ", "| | ", "|_| "],
"1": [" ", "| ", "| "],
"2": [" _ ", " _| ", "|_ "],
"3": ["_ ", "_| ", "_| "],
"4": [" ", "|_| ", " | "],
"5": [" _ ", "|_ ", " _| "],
"6": [" _ ", "|_ ", "|_| "],
"7": ["_ ", " | ", " | "],
"8": [" _ ", "|_| ", "|_| "],
"9": [" _ ", "|_| ", " _| "]
}


def get_row(num):
return ''.join([leds[i][num] for i in list(digits)])

print("{}\n{}\n{}".format(get_row(0), get_row(1), get_row(2)))

fb0adf No.2018

>>2017
>Write a program that takes a string of digits and prints them back out in LED style.

In C, with line wrap:
>https://clbin.com/bDOS2

I'm not 100% sure if my usage of ioctl() is correct under Linux. It should compile fine for fellow BSDfags, though.

3c1daf No.2021

>>2018
Compiled fine here.

I'm impressed with the your thoroughness.

e422de No.2030

[b]Enterprise grade[/b]

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#define L "1210111012101210111012101210121012101210"\
"4140114012401240424042104210114042404240"\
"4240114042101240114012404240114042401240"
int main(int argc, char **argv) {
char i,*q,*p,*a=strdup(L);
for(i=0;i<3;i++) {
for(p=argv[1];*p;p++) {
if(!isdigit(*p)) continue;
q = a+(((*p-48)+i*10)*4);
while(1) {
if(*q>5) *q-=48;
if(!*q) break;
printf("%c",*q&1?' ':(*q&2?'_':'|'));
q++;
}
}
printf("\n");
}
}

a80a09 No.2035

http://pastebin.com/UXLnZnh8

Prints for #define DEBUG

5ac765 No.2040


local digits = {
[0] = {' _ ', '| |', '|_|'},
[1] = {' ', '|', '|'},
[2] = {' _ ', ' _|', '|_ '},
[3] = {'_ ', '_|', '_|'},
[4] = {' ', '|_|', ' |'},
[5] = {' _ ', '|_ ', ' _|'},
[6] = {' _ ', '|_ ', '|_|'},
[7] = {'_ ', ' |', ' |'},
[8] = {' _ ', '|_|', '|_|'},
[9] = {' _ ', '|_|', ' _|'},
}

local function leddigits(numbers)
local lines = {'', '' ,''}
for i=1, 3 do
for _, num in ipairs(numbers) do
lines[i] = lines[i] .. digits[num][i] .. ' '
end
end
return table.concat(lines, '\n')
end

if arg[1] == nil then
print('Usage: lua ' .. arg[0]:match('[\\/]([^\\/]+%.lua)') .. ' numbers')
else
local numbers = {}
for num in arg[1]:gmatch('(%d)') do
table.insert(numbers, tonumber(num))
end
print(leddigits(numbers))
end

a79e34 No.2060

http://pastebin.com/4MezRJmp

Was going for no includes so I used assembler to print to console. Probably not the most portable.

Works on my x64 should work on x86 too. Not an assembler expert though.

a79e34 No.2061

>>2060
Using GNU + linux here also, for windows you'll need to change the assembler.

fb0adf No.2075

>>2060
>>2061
>microsoftStyleFunctionNaming
>Calls the terminal emulator a "console"
>Uses a carriage return followed by a line feed
>Still claims to be using GNU+Linux

[code]Anon, it's okay to admit you're a Windows user. Nobody will be mad at you.[/spoiler]

b24da2 No.2078

>>2075
>pleb has to use 7 includes
>doesn't know that all supreme gentoomen use camelCase
>clearly doesn't know the difference between intel syntax and at&t syntax

lulz anon, lulz.

98aa75 No.2588

File: 1434273363959.png (6.89 KB, 381x88, 381:88, Screenshot from 2015-06-14….png)

I put too much effort into this.

http://pastebin.com/XKWP0V61


ea67fe No.2644

Lets see if I remember how code tags work.

WIDTH = 4
HEIGHT = 3
charMap= """
_ _ _ _ _ _ _ _
| | | _| _| |_| |_ |_ | |_| |_|
|_| | |_ _| | _| |_| | |_| _|
""".split("\n")[1:]

digits = [ord(c)-48 for c in str(sys.argv[1]) if(c.isdigit())]

for line in range(HEIGHT):
print("".join([charMap[line][d*WIDTH:(d+1)*WIDTH] for d in digits[:20]]))


f29f9e No.2659

>>2075

>microsoftStyleFunctionNaming

Are you positive? all the function names in windows.h start with a capital letter.

like

MicrosoftStyleFunctionNaming


45a04f No.2664

Now, make a program that can take the LED-style output as a pipe and convert it back to a string of digits.


8091ad No.2725

Common Lisp w/ SBCL:

#!/usr/bin/sbcl --script

(defparameter *digits* '((" _ " "| |" "|_|")
(" " " |" " |")
(" _ " " _|" "|_ ")
(" _ " " _|" " _|")
(" " "|_|" " |")
(" _ " "|_ " " _|")
(" _ " "|_ " "|_|")
(" _ " " |" " |")
(" _ " "|_|" "|_|")
(" _ " "|_|" " _|")))

(defun print-digits (ds)
(format t "~{~{~a~}~%~{~a~}~%~{~a~}~%~}"
(apply #'mapcar #'list
(mapcar (lambda (n) (nth n *digits*)) ds))))

(defun main (args)
(print-digits (map 'list
(lambda (x) (- (char-int x) (char-int #\0)))
(cadr args))))

(main sb-ext:*posix-argv*)
F O R M A T

O

R

M

A

T


c387eb No.2734

>>2725

>sbcl –script

So, THAT'S how you do it.

Awesome.


66ba05 No.2793

My not so sophisticated ECMAscript and HTML version :

<script>
function led(num) {
var l1 = "", l2 = "", l3 = "";
for (i = 0; i < num.toString().length; i++) {
switch (num.toString().split("")[i]) {
case "0" : l1 += "&nbsp;_&nbsp;"; l2 += "|&nbsp;|"; l3 += "|_|"; break;
case "1" : l1 += "&nbsp;"; l2 += "|"; l3 += "|"; break;
case "2" : l1 += "&nbsp;_&nbsp;"; l2 += "&nbsp;_|"; l3 += "|_&nbsp"; break;
case "3" : l1 += "_&nbsp;"; l2 += "_|"; l3 += "_|"; break;
case "4" : l1 += "&nbsp;&nbsp;&nbsp;"; l2 += "|_|"; l3 += "&nbsp;&nbsp;|"; break;
case "5" : l1 += "&nbsp;_&nbsp;"; l2 += "|_&nbsp;"; ; l3 += "&nbsp;_|"; break;
case "6" : l1 += "&nbsp;_&nbsp;"; l2 += "|_&nbsp;"; l3 += "|_|"; break;
case "7" : l1 += "_&nbsp;"; l2 += "&nbsp;|"; l3 += "&nbsp;|"; break;
case "8" : l1 += "&nbsp;_&nbsp;"; l2 += "|_|"; l3 += "|_|"; break;
case "9" : l1 += "&nbsp;_&nbsp;"; l2 += "|_|"; l3 += "&nbsp;_|"; break;
} l1 += "&nbsp;"; l2 += "&nbsp;"; l3 += "&nbsp;"; } return l1 + "<br>" + l2 + "<br>" + l3; }
</script>
<input type="text" id="i" />
<button onclick="document.getElementById('output').innerHTML = led(document.getElementById('i').value);">INPUT</button><br />
<div id="output" style='font-family:courier;'></div>


000000 No.2804

Just started learning scheme with SICP….. don't know how to handle command line arguments yet

chibi-scheme


(import (scheme r5rs))


(define numbers '((" _ " " " " _ " " _ " " " " _ " " _ " " _ " " _ " " _ ")
(" | | " " | " " _| " " _| " " |_| " " |_ " " |_ " " | " " |_| " " |_| ")
(" |_| " " | " " |_ " " _| " " | " " _| " " |_| " " | " " |_| " " | ")))

(define (part n l)
(if (= n 0)
(car l)
(part (- n 1) (cdr l))))

(define (line n l)
(define (line-iter l r)
(if (null? l)
r
(line-iter (cdr l) (string-append r (part (car l) (part n numbers))))))
(line-iter l ""))

(define (led l)
(string-append (line 0 l) "\n" (line 1 l) "\n" (line 2 l) "\n\n"))

(define run (display (led '(1 3 3 7))))


f97ebe No.2821


: .part ( digit sc -- )
drop swap 4 * + 3 type space ;

: top " _ _ _ _ _ _ _ _ " .part ;
: mid "| | | _| _| |_| |_ |_ | |_| |_|" .part ;
: bot "|_| | |_ _| | _| |_| | |_| _|" .part ;

: each-digit ( n xt -- ) LOCAL xt
0 swap begin
10 /mod swap >r
swap 1+ swap
dup 0= until drop

begin dup while r> xt execute 1- repeat drop ;

: led ( n -- )
dup ['] top each-digit cr
dup ['] mid each-digit cr
['] bot each-digit cr ;

interactive usage:


1234567890 led
_ _ _ _ _ _ _ _
| _| _| |_| |_ |_ | |_| |_| | |
| |_ _| | _| |_| | |_| _| |_|
OK
0 led
_
| |
|_|
OK


eebb7c No.2829

Took a lot more work than I thought (Java)

 ublic class LEDStyle {
private int textNum;
private String ledNum;
static String[][] numbers = new String[][]{
// 0 1 2 3 4 5 6 7 8 9
{" _ ", " ", " _ ", " _ ", " ", " _ ", " _ ", " _ ", " _ ", " _ "},
{"| |", " |", " _|", " _|", "|_|", "|_ ", "|_ ", " |", "|_|", "|_|"},
{"|_|", " |", "|_ ", " _|", " |", " _|", "|_|", " |", "|_|", " |"}
};
public LEDStyle(int inNum){
textNum = inNum;
ledNum = textToLED(textNum);
}
private String textToLED(Integer text){
ArrayList<Integer> intToken1 = new ArrayList<Integer>();
ArrayList<Integer> intToken = new ArrayList<Integer>();
String ret = "";

while (text > 0){
intToken1.add(text % 10);
text /= 10;
}
for(int i = intToken1.size() - 1; i > -1; i--){
intToken.add(intToken1.get(i));
}

for(int i = 0; i < 3; i++){
for(int y = 0; y < intToken.size(); y ++){
ret += numbers[i][intToken.get(y)];
ret += " ";
}
ret += "\n";
}
return ret;
}
public String toString(){
return ledNum;
}
}


402f10 No.2860

im new to programming, so tell me if this was any good


#include <iostream>
#include <string>
int main ( int argc, char* argv[] )
{
std::string numbers[3] = { " _ _ _ _ _ _ _ _ ",
"| | | _| _||_||_ |_ ||_||_|",
"|_| ||_ _| | _||_| ||_| |"};

for ( short row = 0; row < 3; row++ )
{
for ( char *i = argv[1]; *i != '\0'; i++ ) { std::cout << numbers[row].substr((*i-48)*3, 3) << " "; }
std::cout << std::endl;
}
return 0;
}


5468b7 No.2885

>>2030

I just began learning c today

what the fuck is this wizardry


c0dd89 No.2895


: top-row s" _ _ _ _ _ _ _ _ " drop ;
: mid-row s" | | | _| _||_||_ |_ ||_||_|" drop ;
: bot-row s" |_| ||_ _| | _||_| ||_| _|" drop ;

: print-loop ( addr n addr -- )
swap 0 do
over i chars + c@ 48 - 3 * chars over + 3 type
32 emit
loop
2drop
;

: .7segs ( addr n -- )
dup if
2dup top-row print-loop cr
2dup mid-row print-loop cr
2dup bot-row print-loop cr
2drop
then
;

next-arg .7segs \ grab parameter from argv as string
bye

\ EXAMPLE: gforth digts.fs 0123456789

can not have too much forth


992b73 No.2904


# echo 1234567890 | sed -f thisfile
h
s/[14]/ /g
s/[0-9]/ _ /g
G
s/0/| | /g
y/24569/38228/
G
s/[068]/|_| /g
s/[147]/ | /g
s/2/|_ /g
s/[359]/ _| /g


f08568 No.2905

>>2860

p.good, you should add a check if the input is actually a number, as you would definitely crash otherwise.

also you could add a little whitespace to make it look better, but on this scale its mostly unimportant


2c42cf No.2907

File: 1437966232418.png (4.57 KB, 363x103, 363:103, alignment_chaotic_evil.png)

>>2860

Your indenting/alignment is using a bad mix of tabs and spaces, which messes up the code on systems not expanding the tabs to the same width as your system (see pic).

The easy option is to always use spaces all the time, both for indenting, and for aligning, good editors can be configured to instert x number of spaces at the press of the tab key.

The other option is to indent with tab, and align with space:

(multiple underscore followed by space denotes a tab, and periods denote regular spaces)

void somefunc(bool foo, const char *bar) {
___ if (foo) {
___ ___ for (int i=0; i<10; ++i) {
___ ___ ___ printf("The value of i is %d and bar = \%s\"\n",
___ ___ ___ .......i,
___ ___ ___ .......bar
___ ___ ___ ......);
___ ___ }
___ }
}

void somefunc(bool foo, const char *bar) {
_______ if (foo) {
_______ _______ for (int i=0; i<10; ++i) {
_______ _______ _______ printf("The value of i is %d and bar = \%s\"\n",
_______ _______ _______ .......i,
_______ _______ _______ .......bar
_______ _______ _______ ......);
_______ _______ }
_______ }
}

This way, people with different preferences for how big a proper tab/indent sholud be can still work on the same code.


f07570 No.2914

Perl is shit, but it's not been done in this thread yet:


#!/usr/bin/perl
use warnings;
use strict;

sub Usage;

my @LEDS = ([" _ ", "| |", "|_|"],
[" ", " | ", " | "],
[" _ ", " _|", "|_ "],
["_ ", "_| ", "_| "],
[" ", "|_|", " |"],
[" _ ", "|_ ", " _|"],
[" _ ", "|_ ", "|_|"],
["_ ", " | ", " | "],
[" _ ", "|_|", "|_|"],
[" _ ", "|_|", " _|"]);

sub main;

exit main();

sub main
{
if ((scalar(@ARGV) < 1) || ($ARGV[0] !~ m/^\d+$/))
{
Usage();
return 1;
}

my @number = split(//, $ARGV[0]);

for (my $line = 0; $line < 3; ++$line)
{
for my $digit (@number)
{
print($LEDS[$digit][$line]);
print(' ');
}
print("\n");
}

return 0;
}

sub Usage
{
print("Gimme digits, fucko\n");
}


63980e No.2916

C# console application:

Formatting gets fucked if you enter too many characters due to the lines wrapping around and taking up more than one line.

I didn't do any validation because I'm too lazy to be hassled right now.


using System;

namespace LED_Numbers
{
class Program
{
// 0 1 2 3 4 5 6 7 8 9
string[] top = { " _ ", " ", " _ ", " _ ", " ", " _ ", " _ ", " _ ", " _ ", " _ " };
string[] mid = { "| |", " |", " _|", " _|", "|_|", "|_ ", "|_ ", " |", "|_|", "|_|" };
string[] bot = { "|_|", " |", "|_ ", " _|", " |", " _|", "|_|", " |", "|_|", " |" };
static void Main(string[] args)
{
do
{
Console.WriteLine("Enter a number:");
new LED_Numbers.Program().BuildLED(Console.ReadLine());
} while (true);

}

public void BuildLED(string input)
{
string sTop = "", sMid = "", sBot = "";
foreach (var item in input.ToCharArray())
{
int num = int.Parse(item.ToString());
sTop += (top[num].ToString());
sMid += (mid[num].ToString());
sBot += (bot[num].ToString());
}
Console.Write(sTop + "\n" + sMid + "\n" + sBot + "\n");
}
}
}


f07570 No.2917

Just started with asm today. Here's what I got (also checks for argument validity. i386 Linux, so if you're on x86_64, assemble and link targeting elf32):


; led.asm
; Compile this file with nasm -f elf led.asm && ld -o led led.o -melf_i386 -I/lib/ld-linux.so.2


segment .data
; led rows, in groupings of 3, with each 3x3 grouping belonging to the number in turn
leds db " _ | | |_| | | _ _| |_ _ _| _| |_| | _ |_ _| _ |_ |_| _ | | _ |_| |_| _ |_| _| "
nl db 0x0a
space db " "
error db "gimme digits, fucko", 0x0a
errorl equ $ - error

segment .bss
number resd 1
row resb 1

%macro exit 1
mov ebx, %1
mov eax, 1
int 0x80
%endmacro

%macro print 3
mov eax, 4 ;sys_write
mov ebx, %1 ;stdout
mov ecx, %2
mov edx, %3
int 0x80
%endmacro

%macro out 2
print 1, %1, %2
%endmacro

%macro err 2
print 2, %1, %2
%endmacro

segment .text
global _start

_start:
pop eax

; Make sure argc == 2
cmp eax, 2
jz argc_false
call errorf
argc_false:
; Discard the program name
pop eax
; Get the digits
pop eax
mov [number], eax

call checknumber

mov byte [row], 0

rowloop:
mov eax, [number]

numberloop:
cmp byte [eax], 0
jnz continue
out nl, 1 ; output newline for end of row

inc byte [row]

cmp byte [row], 3
jb rowloop
exit 0

continue:

push eax
call printdigit
pop eax

inc eax
jmp numberloop

; eax contains a pointer to the number character
printdigit:
mov bl, [eax]
sub bl, 0x30 ; get the digit value
mov al, 12
mul bl ; get leds digit offset

mov ecx, 0x00
mov cx, ax
mov ax, 0x00
mov al, [row] ; get row number
mov bl, 4
mul bl ; get row offset (0, 3, or 6)
add cx, ax ; find character offset
add ecx, leds ; increment character offset into leds
out ecx, 4

ret

; eax contains pointer to NUL-terminated number string
checknumber:
mov bl, [eax]
cmp bl, 0
jz checknumberexit
cmp bl, 0x30
jb errorf
cmp bl, 0x39
ja errorf

inc eax
jmp checknumber

checknumberexit:
ret

errorf:
err error, errorl
mov ebx, 1
exit 1


f07570 No.2918

>>2917

And as a bonus, translated into x86_64 (still linux). Assembles to a neat 976-byte executable (the 32-bit version assembled to 752 bytes).

I can probably do a lot of stuff better, particularly related to subroutine calls and other minutia (whatever you call them in ASM. They're probably not called functions, since there's no inherent stack frame).


; led.asm
; Compile this file with nasm -f elf64 led.asm && ld -o led led.o -I/lib/ld-linux.so.2


segment .data
; led rows, in groupings of 3, with each 3x3 grouping belonging to the number in turn
leds db " _ | | |_| | | _ _| |_ _ _| _| |_| | _ |_ _| _ |_ |_| _ | | _ |_| |_| _ |_| _| "
nl db 0x0a
space db " "
error db "gimme digits, fucko", 0x0a
errorl equ $ - error

segment .bss
number resq 1
row resb 1

%macro exit 1
mov rdi, %1
mov rax, 60
syscall
%endmacro

%macro print 3
mov rax, 1 ;sys_write
mov rdi, %1
mov rsi, %2
mov rdx, %3
syscall
%endmacro

%macro out 2
print 1, %1, %2
%endmacro

%macro err 2
print 2, %1, %2
%endmacro

segment .text
global _start

_start:
pop rax

; Make sure argc == 2
cmp rax, 2
jz argc_false
call errorf
argc_false:
; Discard the program name
pop rax
; Get the digits
pop rax
mov [number], rax

call checknumber

mov byte [row], 0

rowloop:
mov rax, [number]

numberloop:
cmp byte [rax], 0
jnz continue
out nl, 1 ; output newline for end of row

inc byte [row]

cmp byte [row], 3
jb rowloop
exit 0

continue:

push rax
call printdigit
pop rax

inc rax
jmp numberloop

; rax contains a pointer to the number character
printdigit:
mov bl, [rax]
sub bl, 0x30 ; get the digit value
mov al, 12
mul bl ; get leds digit offset

mov rcx, 0x00
mov cx, ax
mov ax, 0x00
mov al, [row] ; get row number
mov bl, 4
mul bl ; get row offset (0, 3, or 6)
add cx, ax ; find character offset
add rcx, leds ; increment character offset into leds
out rcx, 4

ret

; rax contains pointer to NUL-terminated number string
checknumber:
mov bl, [rax]
cmp bl, 0
jz checknumberexit
cmp bl, 0x30
jb errorf
cmp bl, 0x39
ja errorf

inc rax
jmp checknumber

checknumberexit:
ret

errorf:
err error, errorl
exit 1


a5e6e4 No.3365

With parsing back the output:


import sys
from collections import defaultdict
from functools import reduce

class Data:
TOP = " _ _ _ _ _ _ _ _ "
MIDDLE = " | | | _| _| |_| |_ |_ | |_| |_|"
BOTTOM = " |_| | |_ _| | _| |_| | |_| _|"

ROWS = [TOP, MIDDLE, BOTTOM]
ACCEPT = "0123456789"
WIDTH = 4

def reverse (rows, width):
l = []
for row in rows:
d = defaultdict (set)
for i, t in enumerate (zip (* ([iter (row)] * width))):
d ["".join (t)].add (i)
l.append (d)
return l

REVERSE_ROWS = reverse (ROWS, WIDTH)

def digitleds (s):
x = list (filter (lambda i: i >= 0,
map (lambda ch: Data.ACCEPT.find (ch), s)))
if not x: return None

return ["".join (map (lambda i: row [Data.WIDTH * i : Data.WIDTH * (i + 1)], x)) for row in Data.ROWS]

def parseleds (lines):
def canbe (pieces):
return reduce (set.intersection, (d [k] for d, k in zip (Data.REVERSE_ROWS, pieces)))

def tostr (possib):
if not possib:
return "_"
if len (possib) == 1:
(i,) = possib
return Data.ACCEPT [i]
return str (set (map (
lambda i: Data.ACCEPT [i], possib
)))

allpieces = zip (* (
map ("".join, zip (* ([iter (row)] * Data.WIDTH))) for row in lines
))

return "".join (map (tostr, map (canbe, allpieces)))

def test (s):
x = digitleds (s)
if x is None: return
print (* x, sep="\n")
y = parseleds (x)
print (y)

def main ():
test (sys.argv [1])

if __name__ == "__main__": main ()


$ python3 leds.py 1357986420
_ _ _ _ _ _ _ _
| _| |_ | |_| |_| |_ |_| _| | |
| _| _| | _| |_| |_| | |_ |_|
1357986420


16baa8 No.3399

File: 1444442973278.jpg (6.43 KB, 281x200, 281:200, 1432265981981.jpg)

>>2030

okay, let me try to break this down…

1.It assigns q, p, and a to the copy of the character array L. All pointers.

1.a. I have no fucking idea what you're doing with i, but whatever. It get's assigned to 0 right after.

2.I'm assuming the 3 is meant to stand for the level of the of each character. Like you can divide 5 into 3 sections: The top, the top middle, and the middle bottom.

3. Then you go through the first argument, which is your input string.

4.a. If it sees that it's not a digit, it says "fuck this" and skips the number

(b). 48 is essentially '0', so it takes the character you're currently on and makes it an integer.

then it adds 10*i to it for some reason, multiplies it by four too.

The length of L is 40 characters, so this might have to something with it.

And then adds it to a, moving you down L/a by some amount.

If i is 1, it moves you to the second line. If i is 2, it moves you to the third line.

5.a.

Note that the digit q is on is a numerical character, so even though they're all less than 5, it will always be greater than 48.

It shifts the character q is on down by '0' again, giving you character of value 0, 1, 2, or 4 numerically.

"Line" of character q is pointing too (since it's not really separated by an '\n' character): i.

"position" of character q is pointing too: 40*i + 4c, where c is the number p is pointing to (our input line). It's not the position, but the actual character.

b.If it is even, which every 4th character is, it will break out of the for loop.

c. Now we have to break down this clusterfuck…

*q&1* checks if the number is 1, since 2, and 4 have the first bit as 0. If it is, it puts a space there.

If not (value of *q is, 2, 4):

checks if *q is 2. If it is, it puts a '_'. If not, a '|'

Then it goes on too the next character.

So how does this shit translate to printing a string of numbers LED clock style?

Well imagine each number as a 3x3 grid. In each square of the grid, you can either have a '_' or a '|'.

What the string L does is it gives a assigns a value to each of those values the square can be.

So a '|' is a 4, a '_' is a 2, a ' ' is a 1. The 0 represents the end of the grid for the number.

L stores all the possible values of a number for a given position on the grid of a given number.

So given the number six, all the values of six would be located at positions 20-22 on lines 0 and 2, excluding the 0s.

Mapping the values 1, 2 or 4 to the character values will give you all the characters for the LED representation of six.

-The program goes through line i, 0 <= i < 3.

-for every character in the input

-assuming it's an integer, it moves it the position on L where the values of the ith row are located.

-Then it subtracts the element at the position by '0' if it hasn't already done it. If it ends up being zero, it get's out of the loop.

-Then, depending on the value at the position, it maps it to a ' ', '_' or a '|' and prints it.

-It repeats that 3 times until it hits a 0 character.

-Then it goes to the next character input of p, going until it goes through the whole line.

-prints a newline character.

-Then it prints the middle section and the bottom section. After that i = 3 so it's done

I'm not going back to read all the shit I just wrote.

This is the most evil fucking code I've ever seen.

There's no point to all this mapping bullshit, since it stores every character 0, 1, 2, 4 as a char, which takes up just as much space as ' '. '_' or '|'.

I haven't finished reading K&R2, but maybe they could have used bitfields?

But even then those are ints, which use up more space than characters.


7bb484 No.3400

package main

// Golang:

import (

"fmt"

"os"

"strconv"

)

// _ _ _ _ _ _ _ _

// | _| _| |_| |_ |_ | |_| |_| | |

// | |_ _| | _| |_| | |_| _| |_|

// The amount of rows

const rowlength = 3

type (

Row []rune

Number [rowlength]Row

)

// We access the numbers using their position in this slice

// so we convert the user's arguments into numbers.

var Numbers = []Number {

{{' ', '_', ' '}, {'|', ' ', '|'}, {'|', '_', '|'}}, // 0

{{' '}, {'|'}, {'|'}}, // 1

{{' ', '_', ' '},{' ', '_', '|'},{'|', '_', ' '}}, // 2

{{'_', ' '}, {'_', '|'}, {'_', '|'}}, // 3

{{' ', ' ', ' '}, {'|', '_', '|'}, {' ', ' ', '|'}}, // 4

{{' ', '_', ' '}, {'|', '_', ' '}, {' ', '_', '|'}}, // 5

{{' ', '_', ' '}, {'|', '_', ' '}, {'|', '_', '|'}}, // 6

{{'_', ' '}, {' ', '|'}, {' ', '|'}}, // 7

{{' ', '_', ' '}, {'|', '_', '|'}, {'|', '_', '|'}}, // 8

{{' ', '_', ' '}, {'|', '_', '|'}, {' ', '_', '|'}}, // 9

}

// Prints the entire number out. Useful for when the entire terminal is available.

func (number Number) String() (nostring string) {

for _, row := range number {

nostring += row.String() + "\n"

}

return nostring

}

// Get a number's specified row

func (number *Number) GetRow(no int) Row {

return number[no]

}

// Stringify the row

func (row Row) String() (rowstring string) {

for _, c := range row {

rowstring += string(c)

}

return rowstring

}

func main() {

if len(os.Args) >= 2 {

// If arguments were specified

// the numbers that we are specifying to print - we access the Numbers slice

// using these

var nostoprint []int

for _, arg := range os.Args[1:] {

for _, nos := range arg {

// We need to convert the rune into a string tho

if no, err := strconv.Atoi(string(nos)); err == nil {

nostoprint = append(nostoprint, no)

} else {

panic(err)

}

}

}

// Row 0 to no 3

for rowno := 0; rowno < rowlength; rowno++ {

for _, no := range nostoprint {

fmt.Printf("%v ", Numbers[no].GetRow(rowno))

}

fmt.Print("\n")

}

} else {

// Annnnd cleanly exit without a panic dump - nothing hectic is being done here

fmt.Println("You didnt't specify any numbers to print!")

os.Exit(1)

}

}

// Btw good form to use tabs instead of spaces but for readability here i've ignored that


6413c7 No.3405

Haskell

main function could be done better.

actually everything could be done better.


import Data.Char(digitToInt)
import System.Environment(getArgs)

makeNumbers :: Int -> String
makeNumbers a =
let
top = [ " _ ", " ", " _ ", " _ ", " ", " _ ", " ", " _ ", " _ ", " _ "]
middle = [ "| |", " |", " _|", " _|", "|_|", "|_ ", "|_ ", " |", "|_|", "|_|"]
down = [ "|_|", " |", "|_ ", " _|", " |", " _|", "|_|", " |", "|_|", " _|"]
digitArr = reverse $ digits a
makeline c = foldr (\x acc -> acc ++ (c !! x)) "" digitArr
in
unlines $ map makeline [top,middle,down]
digits :: Int -> [Int]
digits a = map digitToInt $ show a

main = do
numbers <- getArgs
putStr $ makeNumbers (read (head numbers)::Int)


4fc9f3 No.3561

>tfw all this has done is make me depressed that I couldn't figure out how to do it as anything but vertical printing

>tfw couldn't remember how to split

>tfw didn't even bother having something to stop someone entering text

I'm fucking shit at this.

#!/usr/bin/perl -w
use strict;

#at least I bothered to kill the program if no args were there
print "Usage: digits [numbers]\n" and die unless @ARGV;

#my first thought was "oh, a hash would work for this" but evidently I was wrong
our %digits = (
0 => " _\n| |\n|_| ",
1 => "\n|\n| ",
2 => " _\n _|\n|_ ",
3 => "_\n_|\n_| ",
4 => "\n|_|\n | ",
5 => " _\n|_\n _| ",
6 => " _\n|_\n|_| ",
7 => "_\n |\n | ",
8 => " _\n|_|\n|_| ",
9 => " _\n|_|\n _| ",
);

for (@ARGV) {
print "$digits{$_}\n"
}

Commented where I realised my mistakes.


3dd11a No.3563

JavaScript, converted more or less directly from the first Forth attempt:

function Buffer() {
this.output = ''
this.flush = function() { var r = this.output; this.output = ''; return r }
this.type = function(s) { this.output += s }
}
var io = new Buffer()

var top = " _ _ _ _ _ _ _ _ ",
mid = "| | | _| _| |_| |_ |_ | |_| |_|",
bot = "|_| | |_ _| | _| |_| | |_| _|"

function part(digit, string) {
var index = digit * 4
io.type(string.slice(index, index + 3) + " ")
}

function eachDigit(n, f) {
String(n).split('').forEach(function(digit) { f(Number(digit)) })
}

function led(n) {
;[top, mid, bot].forEach(function(section) {
eachDigit(n, function(digit) { part(digit, section) })
console.log(io.flush())
})
}

exports.led = led

Usage:

> led = require('./44').led
[Function: led]
> led(1234567890)
_ _ _ _ _ _ _ _
| _| _| |_| |_ |_ | |_| |_| | |
| |_ _| | _| |_| | |_| _| |_|
undefined
> led(0)
_
| |
|_|
undefined
>


9d63e5 No.3565

>>3563

That is some of the cleaner JS that I've seen.

I dislike the ASI though. Even if it's a standard, it still feels dirty.*


a5e6e4 No.3566

File: 1447197893281.jpg (371.97 KB, 750x1076, 375:538, Girls_Don't_Cry_04.jpg)

>>2030

>Enterprise grade

I'm almost certain you meant this sarcastically.

You rescan with isdigit(*p) for each line, after the first one you're just duplicating work. It's faster to filter once.

It's nonsensical to loop *q until it encounters a zero, as if you had variable widths, since you already have *4 hardcoded in the initialization of q, so you are already using fixed width information. The compiler can trivially unroll the three-pass for loop that should be there instead of the while loop.

Once you see that you hardcoded the *4 in q=…, the zero columns after each digit's block in L become redundant. You can dump them and use q=…*3 and save space.

Using 48 instead of '0' doesn't gain anything and is unportable.

Your ternary chain on the bits of q is slower than a plain old array lookup used as a translation table. Once you translate properly, you can just have L consist of the final characters, since the translation is static.

What you did in a nutshell was take a good way to do it and add slower, unportable layers of obfuscation, so that no one else will want to maintain your code, and the company would have to keep you around as a spaghetti chef. Truly the mark of an enterprise programmer! I salute you.


84f125 No.3569

>>2588

ebin/kek 1337


d23c77 No.3583

Ocaml here.

#!/usr/bin/env ocamlscript
Ocaml.ocamlflags := ["-thread"];
Ocaml.packs := ["core"; "core.syntax"]
--

open Core.Std

let maximum_column_count data =
let column_count rows =
List.fold (List.map rows ~f:String.length) ~init:0 ~f:max in
List.fold (List.map data ~f:(fun (_, rows) -> column_count rows))
~init:0
~f:max

let maximum_row_count data =
List.fold (List.map data ~f:(fun (_, rows) -> List.length rows))
~init:0
~f:max

let normalize column_count row_count data =
let normalize_row_count (name, rows) =
(name, rows @ (List.init (row_count - (List.length rows))
~f:(fun _ -> String.make column_count ' '))) in
let normalize_column_count (name, rows) =
(name, List.map rows
~f:(fun row ->
row ^ (String.make (column_count - (String.length row))
' '))) in
List.map data
~f:(fun (name, rows) ->
normalize_column_count (normalize_row_count (name, rows)))

let letter_table data =
Hashtbl.of_alist_exn
~hashable:Char.hashable
(normalize (maximum_column_count data) (maximum_row_count data) data)

let letters =
letter_table
[('0', [" _ ";
"| | ";
"|_| "]);
('1', [" ";
" | ";
" | "]);
('2', [" _ ";
" _| ";
"|_ "]);
('3', [" _ ";
" _| ";
" _| "]);
('4', [" ";
"|_| ";
" | "]);
('5', [" _ ";
"|_ ";
" _| "]);
('6', [" _ ";
"|_ ";
"|_| "]);
('7', [" _ ";
" | ";
" | "]);
('8', [" _ ";
"|_| ";
"|_| "]);
('9', [" _ ";
"|_| ";
" _| "]);
(' ', []);
]

let letter_height = maximum_row_count (Hashtbl.to_alist letters)

let iota num = List.init num ~f:(fun x -> x)

let draw_char_row char row =
print_bytes (List.nth_exn (Hashtbl.find_exn letters char) row)

let draw_string str =
let chars = String.to_list str in
List.iter
(iota letter_height)
~f:(fun row_index ->
List.iter chars ~f:(fun char -> draw_char_row char row_index) ;
print_newline ())

let () =
match Sys.argv with
| [|_; str|] -> draw_string str
| [|bin|] -> prerr_string
(Printf.sprintf "Usage: %s string_goes_here\n" bin)
| _ -> prerr_string "what"

Mine's a little bulky because I first normalize the letters so all the glyphs have the same number of columns/rows.

$ ./led.ml 8675309
_ _ _ _ _ _ _
|_| |_ | |_ _| | | |_|
|_| |_| | _| _| |_| _|


614fd7 No.3609

In C:



#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>

struct led_number {
char *line_one;
char *line_two;
char *line_three;
} led_number;

void
die(const char *fmt, ...);

void
print_numbers(struct led_number *numbers, size_t len);


const struct led_number zero = { .line_one = " _ ",
.line_two = "| |",
.line_three = "|_|" };
const struct led_number one = { .line_one = " ",
.line_two = " | ",
.line_three = " | " };
const struct led_number two = { .line_one = " _ ",
.line_two = " _|",
.line_three = "|_ " };
const struct led_number three = { .line_one = " _ ",
.line_two = " _|",
.line_three = " _|" };
const struct led_number four = { .line_one = " ",
.line_two = "|_|",
.line_three = " |" };
const struct led_number five = { .line_one = " _ ",
.line_two = "|_ ",
.line_three = " _|" };
const struct led_number six = { .line_one = " _ ",
.line_two = "|_ ",
.line_three = "|_|" };
const struct led_number seven = { .line_one = " _ ",
.line_two = " |",
.line_three = " |" };
const struct led_number eight = { .line_one = " _ ",
.line_two = "|_|",
.line_three = "|_|" };
const struct led_number nine = { .line_one = " _ ",
.line_two = "|_|",
.line_three = " |" };


int
main(int argc, char* argv[]) {
if(argc < 2)
die("usage: led_numbers [numbers]\n");

for(int k = 1; k < argc; k++) {
char c = 0;
int idx = 0;
int len = 0;

struct led_number *numbers = malloc(sizeof(led_number));
do {
if(argv[k][idx] == '0') { numbers[len] = zero; }
else if(argv[k][idx] == '1') { numbers[len] = one; }
else if(argv[k][idx] == '2') { numbers[len] = two; }
else if(argv[k][idx] == '3') { numbers[len] = three; }
else if(argv[k][idx] == '4') { numbers[len] = four; }
else if(argv[k][idx] == '5') { numbers[len] = five; }
else if(argv[k][idx] == '6') { numbers[len] = six; }
else if(argv[k][idx] == '7') { numbers[len] = seven; }
else if(argv[k][idx] == '8') { numbers[len] = eight; }
else if(argv[k][idx] == '9') { numbers[len] = nine; }
else {
c = argv[k][idx++];
continue;
}
c = argv[1][idx++];
numbers = realloc(numbers, sizeof(struct led_number) * ((len++)+2));
} while(c != '\0');

if(len == 0)
die("usage: led_numbers [numbers]\n");

print_numbers(numbers, len);

printf("\n");
}
}

void
die(const char *fmt, ...) {
va_list ap;

va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);

if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
fputc(' ', stderr);
perror(NULL);
}

exit(1);
}

void
print_numbers(struct led_number *numbers, size_t len) {
for(int k = 0; k < len; k++) {
printf("%s", numbers[k].line_one);
printf(" ");
}
printf("\n");

for(int k = 0; k < len; k++) {
printf("%s", numbers[k].line_two);
printf(" ");
}
printf("\n");

for(int k = 0; k < len; k++) {
printf("%s", numbers[k].line_three);
printf(" ");
}
}


ef7582 No.3615

Scheme, which generates a function to print the number:


; numbers ordered from 0-9
(define nums
'((" _ " "| |" "|_|")
(" " " |" " |")
(" _ " " _|" "|_ ")
(" _ " " _|" " _|")
(" " "|_|" " |")
(" _ " "|_ " " _|")
(" _ " "|_ " "|_|")
(" _ " " |" " |")
(" _ " "|_|" "|_|")
(" _ " "|_|" " _|")))

(define (make-row-printer n fn)
(let* ((current (modulo n 10))
(curstring (fn (list-ref nums current)))
(next (floor (/ n 10)))
(nextfunc (if (< n 10)
newline
(make-row-printer next fn))))

(lambda ()
(nextfunc)
(display curstring))))

(define (make-calc-printer number)
(let ((funcs (map (lambda (fn)
(make-row-printer number fn))
(list car cadr caddr))))

(lambda ()
(map (lambda (f) (f)) funcs)
(newline))))

(define foo
(map make-calc-printer
'(123
1337
#x1234
1234567890)))

(map (lambda (f) (f)) foo)

Tested in guile and racket


35fd62 No.3649

In PHP (type juggling does have benefits)


#!/usr/bin/php
<?php
foreach(range(0,2) as $row) {
for($i = 0; $i < strlen($_SERVER['argv'][1]); ++$i)
echo [[" _ ", "| | ", "|_| "],
[" ", "| ", "| "],
[" _ ", " _| ", "|_ "],
["_ ", "_| ", "_| "],
[" ", "|_| ", " | "],
[" _ ", "|_ ", " _| "],
[" _ ", "|_ ", "|_| "],
["_ ", " | ", " | "],
[" _ ", "|_| ", "|_| "],
[" _ ", "|_| ", " _| "]
][$_SERVER['argv'][1][$i]][$row];

echo "\n";
}

echo "\n";


8c9b6a No.3695

Scala fag here. Had fun with this one.


import scala.collection.mutable.ListBuffer

object toLED {
def toInt(s: String) = {
var a: Int = 0
try {
s.toInt
} catch {
case e: Exception => 0
}// end try/catch
formatLED(s)
}// end toInt

def formatLED(s: String) = {
var a = new ListBuffer[String]()
var b = new ListBuffer[String]()
var c = new ListBuffer[String]()
for (i <- s.toString.map(_.asDigit))
i match {
case 0 => a += " _ "
b += "| | "
c += "|_| "
case 1 => a += " "
b += "| "
c += "| "
case 2 => a += " _ "
b += " _| "
c += "|_ "
case 3 => a += " _ "
b += " _| "
c += " _| "
case 4 => a += " "
b += "|_| "
c += " | "
case 5 => a += " _ "
b += "|_ "
c += " _| "
case 6 => a += " _ "
b += "|_ "
c += "|_| "
case 7 => a += "_ "
b += " | "
c += " | "
case 8 => a += " _ "
b += "|_| "
c += "|_| "
case 9 => a += " _ "
b += "|_| "
c += " | "
}// end match
println(a.mkString(""))
println(b.mkString(""))
println(c.mkString(""))
}// end formatLED

def main(args: Array[String]): Unit =
formatLED("00123456789")
}// end toLED


1f45fa No.3708

>>2017

Haskell

I'm a complete haskell noob, improvements welcome


import Data.Char
import System.Environment

digits = [[" _ ", "| | ", "|_| "], [" ", "| ", "| "], [" _ ", " _| ", "|_ "],
["_ ", "_| ", "_| "], [" ", "|_| ", " | "], [" _ ", "|_ ", " _| "],
[" _ ", "|_ ", "|_| "], [" _ ", " | ", " | "], [" _ ", "|_| ", "|_| "],
[" _ ", "|_| ", " _| "]]

ledChar :: Int -> Char -> String
ledChar row n = digits !! (digitToInt n) !! (row - 1)

ledRow :: String -> Int -> String
ledRow digits row = (++ "\n") $ concat $ map (ledChar row) digits

ledDigits :: String -> String
ledDigits digits = concat $ map (ledRow digits) [1..3]

main = do
(digits:_) <- getArgs
putStr $ ledDigits digits


9cf8d6 No.3958

>>3561

Simple but effective! :3


adf2a5 No.3961

I decided to try and read stdin instead of using arguments, since I want to get more familiar with i/o. I wanted to keep under 80 columns, but I had to slice a few lines up to accomplish that. Please let me know if there's anything I could do better.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define NUM_COLUMNS 30
#define NUM_LINES 3
#define NUM_LENGTH 3
#define NUM \
" _ _ _ _ _ _ _ _ " \
"| | | _| _||_||_ |_ | |_||_|" \
"|_| | |_ _| | _||_| | |_| _|"

int
main(void)
{
const size_t lsize = 128;
char *line = malloc(lsize);

while (fgets(line, lsize, stdin) != NULL) {
/* NUM_LINES output lines per input line */
for (int l=0; l < NUM_LINES; l++) {
/* Characters in line */
for (
int i=0;
line[i] != 0 &&
line[i] != '\n' &&
line[i] != '\r';
i++
) {
if (isdigit(line[i])) {
/*
* A little messy, but the following prints the 3
* associated characters within NUM for the current line
*/
for (int c=0; c < NUM_LENGTH; c++) {
fputc(
NUM[
(
(line[i] - '0') * NUM_LENGTH
) + (NUM_COLUMNS * l) + c
], stdout
);
}
} else {
fprintf(stderr, "'%c' is not a number.", line[i]);
free(line);
return 1;
}
}
fputc('\n',stdout);
}
}

free(line);
return 0;
}


f9fe62 No.3973

>>3961

>80 columns

functions and macros are a good way to reduce the width of your code. a macro would be especially appropriate with your NUM[math] and with your 0-or-newline check.

you can fwrite() a NUM_COLUMNS-length string instead of looping over the chars.

or you can embed NULs in your NUM, using an array instead of a string, and puts() the chars.

>anything I could do better

don't use 'l' as a variable name ever.

don't use malloc() for a temporary 128-byte array

do this:

[code]for (int i =0; line[i]; i++) {

if (isspace(line[i]) continue;

if (!isdigit(line[i])) fuckoff();

/* print here */

}

void fuckoff (void) {

/* whinge */

exit(1);

}


3a9451 No.3990

>>2060

just realized the link to my code has expired so I have reposted below


int writeToConsole(const char *str, const int size);

int main(int argc, char *argv[])
{
if(argc != 2){
writeToConsole("Enter a number to convert to LED style...\r\n", 44);
return 1;
}

int digit_width = 4; // number of chars per line of a digit
int lines_per_number = 3; // number of lines per digit

char *zero_one = " _ ";
char *zero_two = "| |";
char *zero_three = "|_|";
char *zero[] = {zero_one, zero_two, zero_three};

char *one_one = " ";
char *one_two = " | ";
char *one_three = " | ";
char *one[] = {one_one, one_two, one_three};

char *two_one = " _ ";
char *two_two = " _|";
char *two_three = "|_ ";
char *two[] = {two_one, two_two, two_three};

char *three_one = " _ ";
char *three_two = " _|";
char *three_three = " _|";
char *three[] = {three_one, three_two, three_three};

char *four_one = " ";
char *four_two = "|_|";
char *four_three = " |";
char *four[] = {four_one, four_two, four_three};

char *five_one = " _ ";
char *five_two = "|_ ";
char *five_three = " _|";
char *five[] = {five_one, five_two, five_three};

char *six_one = " _ ";
char *six_two = "|_ ";
char *six_three = "|_|";
char *six[] = {six_one, six_two, six_three};

char *seven_one = " _ ";
char *seven_two = " |";
char *seven_three = " |";
char *seven[] = {seven_one, seven_two, seven_three};

char *eight_one = " _ ";
char *eight_two = "|_|";
char *eight_three = "|_|";
char *eight[] = {eight_one, eight_two, eight_three};

char *nine_one = " _ ";
char *nine_two = "|_|";
char *nine_three = " _|";
char *nine[] = {nine_one, nine_two, nine_three};


// print the digits line by line...
for(int i = 0; i != lines_per_number; ++i){ // for each line of a digit...
char *num = argv[1];
while(*num != '\0'){ // for each digit of the input number...
// print to console the i-th line of the digit
switch(*num){
case '0':
writeToConsole(zero[i], digit_width);
break;
case '1':
writeToConsole(one[i], digit_width);
break;
case '2':
writeToConsole(two[i], digit_width);
break;
case '3':
writeToConsole(three[i], digit_width);
break;
case '4':
writeToConsole(four[i], digit_width);
break;
case '5':
writeToConsole(five[i], digit_width);
break;
case '6':
writeToConsole(six[i], digit_width);
break;
case '7':
writeToConsole(seven[i], digit_width);
break;
case '8':
writeToConsole(eight[i], digit_width);
break;
case '9':
writeToConsole(nine[i], digit_width);
break;
}
num++;
}
writeToConsole("\r\n", 3); // add a newline between each line of a digit
}

return 0;
}


int writeToConsole(const char *str, int size)
{
/*
* Prints str to the console, returns the number of characters written.
*/

int chars_written;
asm("movl $4, %%eax\n\t" // sys_write system call
"movl $1, %%ebx\n\t" // write to console
"movl %0, %%ecx\n\t" // str variable
"movl %1, %%edx\n\t" // size variable
"int $0x80"
://"=rm"(chars_written) // output
:"rm"(str), "r"(size) // input
:"eax", "ebx", "%ecx", "%edx" //clobber list
);
}


6dabb2 No.3994

PHP solution:


<?php
if (!isset($argv[1]) || !is_numeric($argv[1])) die("Gimme digits, fucko\n");

$font = [
[" _ ", " ", " _ ", "_ ", " ", " _ ", " _ ", "_ ", " _ ", " _ ",],
["| |", "|", " _|", "_|", "|_|", "|_ ", "|_ ", " |", "|_|", "|_|",],
["|_|", "|", "|_ ", "_|", " |", " _|", "|_|", " |", "|_|", " _|",],
];
$input = $argv[1];
$digits = array_map("array_column", array_fill(0, strlen($input), $font), array_map("intval", str_split($input)));
$output = call_user_func_array("array_map", array_merge([function(...$args) { return implode(" ", $args);}], $digits));

print(implode("\n", array_merge($output, [""])));

Requires PHP 5.6+


9b18ef No.4002

File: 1457294457411.jpg (60.95 KB, 500x375, 4:3, smug anime girl maki.jpg)

write a function that swaps the values of two integer variables in java


d59bd7 No.4003

:- module led.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, string, char.

:- pred draw(char, string, string, string).
:- mode draw(in, out, out, out) is semidet.
draw('0', " _ ",
"| |",
"|_|").
draw('1', " ",
" | ",
" | ").
draw('2', " _ ",
" _|",
"|_ ").
draw('3', " _ ",
" _|",
" _|").
draw('4', " ",
"|_|",
" |").
draw('5', " _ ",
"|_ ",
" _|").
draw('6', " _ ",
"|_ ",
"|_|").
draw('7', "_ ",
" | ",
" | ").
draw('8', " _ ",
"|_|",
"|_|").
draw('9', " _ ",
"|_|",
" _|").

:- pred draw(char, {list(string), list(string), list(string)},
{list(string), list(string), list(string)}).
:- mode draw(in, in, out) is semidet.
draw(C, {T,M,B}, {[T1|T],[M1|M],[B1|B]}) :-
draw(C, T1, M1, B1).

:- pred led(string, string, string, string).
:- mode led(in, out, out, out) is semidet.
led(N, Top, Mid, Bot) :-
string.foldl(draw, N, {[], [], []}, {T, M, B}),
Top = string.join_list("", list.reverse(T)),
Mid = string.join_list("", list.reverse(M)),
Bot = string.join_list("", list.reverse(B)).

:- pred led(string::in, io::di, io::uo) is det.
led(S, !IO) :-
(
led(S, T, M, B)
->
io.write_string(T, !IO), io.nl(!IO),
io.write_string(M, !IO), io.nl(!IO),
io.write_string(B, !IO), io.nl(!IO)
;
io.format("Sorry, I didn't understand ``%s''\n", [s(S)], !IO)
).

main(!IO) :-
io.command_line_arguments(Args, !IO),
( Args = [Arg] -> led(Arg, !IO) ; usage(!IO) ).

:- pred usage(io::di, io::uo) is det.
usage(!IO) :-
io.progname("led", Name, !IO),
io.format("usage: %s <number>\n", [s(Name)], !IO),
io.set_exit_status(1, !IO).


9d9960 No.4004

>>2904

This is fucking amazing. 10/10


32613a No.4012

>>4002

I've always wondered… does Java not allow you to pass by reference?


ffbedc No.4016

>>4012

Nope. It's by-value only, but objects are passed as pointers, so you could do it if your ints were wrapped in a class, but not as primitives.


091d56 No.4020

Ruby implementation


strAy = ""
row1 = []
row2 = []
row3 = []
top = []
mid = []
bot = []
nums1 = {"0" => "313", "1" => "333", "2" => "313", "3" => "313", "4" => "333", "5" => "313", "6" => "313", "7" => "313", "8" => "313", "9" => "313" }
nums2 = {"0" => "232", "1" => "323", "2" => "312", "3" => "312", "4" => "212", "5" => "213", "6" => "213", "7" => "332", "8" => "212", "9" => "212" }
nums3 = {"0" => "212", "1" => "323", "2" => "213", "3" => "312", "4" => "332", "5" => "312", "6" => "212", "7" => "332", "8" => "212", "9" => "332" }
puts "Enter a fucking string of numbers and only fucking numbers you fucking fuck."
userinput= gets.chomp
for i in userinput.to_s.split('') do
puts i
row1.push(nums1[i.to_s])
row2.push(nums2[i.to_s])
row3.push(nums3[i.to_s])
end
for j in row1 do
for i in j.split('') do
if i == "1"
top.push("_")
elsif i == "2"
top.push("|")
elsif i == "3"
top.push(" ")
end
end
end
for j in row2 do
for i in j.split('') do
if i == "1"
mid.push("_")
elsif i == "2"
mid.push("|")
elsif i == "3"
mid.push(" ")
end
end
end
for j in row3 do
for i in j.split('') do
if i == "1"
bot.push("_")
elsif i == "2"
bot.push("|")
elsif i == "3"
bot.push(" ")
end
end
end
puts top.join('')
puts mid.join('')
puts bot.join('')




[Return][Go to top][Catalog][Post a Reply]
Delete Post [ ]
[]
[ home / board list / faq / random / create / bans / search / manage / irc ] [ ]