Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

post you are run length encoding in lisp

Name: Anonymous 2014-10-05 3:18

critique mine pl0x:

(defun rle (str) ;run length encoding
(let ((i 0) c count out)
(while (< i (length str))
(if (eq c (elt str i))
(setq count (1+ count))
(when c
(setq out (append out (list (cons c count)))))
(setq c (elt str i))
(setq count 1))
(setq i (1+ i)))
(when c (setq out (append out (list (cons c count)))))
out))

Name: Anonymous 2014-10-09 7:43

rle:
#include <stdio.h>

int main(int argc, char **argv) {
int byte, count, temp;
begin:
byte = getchar();
count = 0;
if (byte == EOF) return 0;
is_same:
temp = getchar();
if (temp == EOF) {
putchar(count); putchar(byte);
return 0;
} else if (byte == temp) {
count++;
if (count == 255) {
putchar(count); putchar(byte);
goto begin;
} else goto is_same;
} else {
putchar(count); putchar(byte);
byte = temp; count = 0;
goto is_same;
}
}


unrle:
#include <stdio.h>

int main(int argc, char **argv) {
int count, byte;
for (;;) {
count = getchar();
byte = getchar();
if (count == EOF || byte == EOF) return 0;
for (int i = 0; i <= count; i++) putchar(byte);
}
}

Name: Anonymous 2014-10-09 9:27

>>50
rle in memory:
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
typedef uint8_t u8;

/* Run-length encodes data, returning the malloc-allocated buffer in ebytes
and its size in esize. */
void rle(u8 *ubytes, size_t usize, u8 **ebytes, size_t *esize) {
// rle can double the input size in the worst case
u8 *eb = malloc(usize * 2);
size_t ui = 0;
size_t ei = 0;
u8 byte, count;

begin:
byte = ubytes[ui];
count = 0;
is_same:
ui++;
if (ui == usize) {
eb[ei++] = count;
eb[ei++] = byte;
*esize = ei;
*ebytes = malloc(ei);
memcpy(*ebytes, eb, ei);
free(eb);
return;
} else if (byte == ubytes[ui]) {
count++;
if (count == 255) goto write;
goto is_same;
} else {
write:
eb[ei++] = count;
eb[ei++] = byte;
goto begin;
}
}


unrle in memory:
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
typedef uint8_t u8;

/* Decompresses run-length encoded data, returning the data in ubytes
and its size in usize */
void unrle(u8 *ebytes, size_t esize, u8 **ubytes, size_t *usize) {
// unrle can expand the input 256-fold in the best case
u8 *ub = malloc(esize * 256);
size_t ei, ui;
u8 count, byte;
for (ei = 0, ui = 0; ei < esize;) {
count = ebytes[ei++];
byte = ebytes[ei++];
for (int i = 0; i <= count; i++) ub[ui++] = byte;
}

*ubytes = malloc(ui);
*usize = ui;
memcpy(*ubytes, ub, ui);
free(ub);
return;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List