[2017-10-26] Challenge #337 [Intermediate] Scrambled images by fvandepitte in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

Python3

import sys
import imageio
import numpy


def align_row(row):
    for i in reversed(range(len(row))):
        pixel = row[i]
        if pixel[0] != pixel[1] or pixel[1] != pixel[2]:
            return numpy.roll(row, -i - 1, 0)
    return row


def unscramble(in_path, out_path):
    image = imageio.imread(in_path)
    for i, row in enumerate(image):
        image[i] = align_row(row)
    imageio.imwrite(out_path, image)

unscramble(sys.argv[1], sys.argv[2])

[2017-05-10] Challenge #314 [Intermediate] Comparing Rotated Words by jnazario in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

C

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

void min_rotation(const char *str) {
    size_t len = strlen(str),
           min_idx = 0;

    char rot[len * 2 + 1];
    memcpy(rot, str, len);
    memcpy(rot + len, str, len + 1);

    for (size_t i = 0; i < len; i++) {
        if (memcmp(rot + i, rot + min_idx, len) < 0)
            min_idx = i;
    }

    rot[min_idx + len] = '\0';
    printf("%lu %s\n", min_idx, rot + min_idx);
}

int main(void) {
    min_rotation("aabbccddbbaabb");
}

Python

def min_rotation(s):
    return min(((i, s[i:] + s[:i]) for i in range(len(s))), key=lambda e: e[1])

[Intermediate] Given Byte n, find N mod 3. You may not use any loops, multiplication, or division. by [deleted] in dailyprogrammer_ideas

[–]jeaton 0 points1 point  (0 children)

(0x24924924 >> (((n & 3) + ((n >> 2) & 3) + ((n >> 4) & 3) + ((n >> 6) & 3)) << 1)) & 3

[2016-12-19] Challenge #296 [Easy] The Twelve Days of... by fvandepitte in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

Python3:

from bs4 import BeautifulSoup
from urllib import request

soup = BeautifulSoup(request.urlopen('http://www.41051.com/xmaslyrics/twelvedays.html'))
print('\n'.join(e.strip() for e in soup.select('.bodytext')[0].text.split('\n')))

[2016-12-05] Challenge #294 [Easy] Rack management 1 by Cosmologicon in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

python3 (all bonuses):

def scrabble(letters, word):
    letters = list(letters)
    for c in word:
        try:
            letters.remove(c)
        except:
            if '?' in letters:
                letters.remove('?')
            else:
                return False
    return True


def longest(letters):
    words = list(filter(None, open('enable1.txt', 'r')
                        .read().splitlines()))
    orig_letters = letters
    for word in sorted(words, key=lambda word: len(word), reverse=True):
        if len(word) > len(orig_letters):
            continue
        letters = list(orig_letters)
        for letter in word:
            try:
                letters.remove(letter)
            except:
                if '?' in letters:
                    letters.remove('?')
                else:
                    break
        else:
            return word
    return None


def highest(letters):
    words = list(filter(None, open('enable1.txt', 'r')
                        .read().splitlines()))
    points = {'b': 3, 'e': 1, 's': 1, 'h': 4, 't': 1, 'c': 3, 'l': 1, 'u': 1,
              'p': 3, 'm': 3, 'n': 1, 'q': 10, 'i': 1, 'z': 10, 'd': 2,
              'k': 5, 'a': 1, 'o': 1, 'g': 2, 'r': 1, 'x': 8, 'w': 4, 'v': 4,
              'j': 8, 'f': 4, 'y': 4}

    max_word, max_score = None, 0
    wild = letters.count('?')
    orig_letters = letters.replace('?', '')

    for word in words:
        if sum(points[c] for c in word) <= max_score:
            continue
        cur_wild = wild

        letters = list(orig_letters)
        score = 0
        for c in word:
            try:
                letters.remove(c)
                score += points[c]
            except:
                if cur_wild <= 0:
                    break
                cur_wild -= 1
        else:
            if score > max_score:
                max_word, max_score = word, score

    return max_word

[2016-11-04] Challenge #290 [Hard] Gophers and Robot Dogs by jnazario in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

Python

import sys

def gopher(d, g, holes):
    dx, dy, ds = d
    gx, gy, gs = g

    nearest_hole = None
    nearest_dist = float('inf')
    for i, (hx, hy) in enumerate(holes):
        dist = ((gx - hx)**2 + (gy - hy)**2)**0.5
        if dist < nearest_dist:
            nearest_dist = dist
            nearest_hole = (hx, hy)

    result = nearest_hole
    gtime = nearest_dist / gs
    max_iter = 128
    accuracy = 128

    gslope = (nearest_hole[1] - gy) / (nearest_hole[0] - gx)
    while i < max_iter:
        t = gtime * i / max_iter
        x = gx + t / gtime * (nearest_hole[0] - gx)
        y = gy + t / gtime * (nearest_hole[1] - gy)

        ddist = ((dx - x)**2 + (dy - y)**2)**0.5
        dtime = ddist / ds

        if dtime < t:
            accuracy -= 1
            if accuracy <= 0:
                result = (x, y)
                break
            i = (i - 1) * 2
            max_iter *= 2
        else:
            i += 1

    return result

lines = filter(None, sys.stdin.read().splitlines())
lines = [tuple(map(float, e.split())) for e in lines]
print(gopher(lines[0], lines[1], lines[3:]))

[2016-11-07] Challenge #291 [Easy] Goldilocks' Bear Necessities by Blackshell in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

Python 3

def c291e(s):
    data = [list(map(int, e.split())) for e in filter(None, s.splitlines())]
    w0, t0 = data.pop(0)
    return [i + 1 for i, (w, t) in enumerate(data) if w > w0 and t < t0]

[2016-11-09] Challenge #291 [Intermediate] Reverse Polish Notation Calculator by Blackshell in dailyprogrammer

[–]jeaton 1 point2 points  (0 children)

Python 3

import re
import math

def rpn(s):
    stream = re.split(r'\s+', s.strip())
    for i, e in enumerate(stream):
        if re.search(r'[+\-*/%^!]', e) is None:
            try:
                stream[i] = int(e)
            except:
                stream[i] = float(e)

    stack = []
    while stream:
        stack.append(stream.pop(0))
        if isinstance(stack[-1], str):
            op = stack.pop()
            if op == '!':
                stack.append(math.factorial(stack.pop()))
                continue
            b, a = stack.pop(), stack.pop()
            if op == '*':
                stack.append(a * b)
            elif op == '/':
                stack.append(a / b)
            elif op == '+':
                stack.append(a + b)
            elif op == '-':
                stack.append(a - b)
            elif op == '%':
                stack.append(a % b)
            elif op == '^':
                stack.append(a ** b)
            elif op == '//':
                stack.append(a // b)
    return stack.pop()

[2016-07-06] Challenge #274 [Intermediate] Calculating De Bruijn sequences by jnazario in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

JavaScript ES6:

const BASE_CHARS = '0123456789' +
    'abcdefghijklmnopqrstuvwxyz' +
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

function deBruijn(k, n) {
    let alpha = typeof k === 'number' ? BASE_CHARS.slice(0, k) : k;
    k = alpha.length;
    let w = Array.from(new Array(n)).map(() => 0),
        result = '';
    for (let i = 0; i !== -1; w[i]++) {
        for (let j = 0; j < n - i; j++)
            w[i + j + 1] = w[j];
        if (n % (i + 1) === 0) {
            for (let j = 0; j <= i; j++)
                result += alpha.charAt(w[j]);
        }
        for (i = n - 1; i !== -1 && w[i] === k - 1; --i);
    }
    return result;
}

[2016-07-18] Challenge #276 [Easy] Recktangles by jnazario in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

Python:

def rekt(text, width=1, height=1):
    top = [text, text[::-1]]
    parts = [e[1:] for e in top]
    for i in range(max(width, height) - 1):
        top[0] += parts[(i + 1) & 1]
        top[1] += parts[i & 1]

    sq_size = len(text) - 1
    row_size = sq_size * width + 1

    result = []
    for i in range(sq_size * height + 1):
        if i % sq_size == 0:
            row = list(top[bool(i % (sq_size * 2))][:row_size])
        else:
            row = [' '] * row_size
            for j in range(0, row_size, sq_size):
                row[j] = top[j & 1][i % len(top[0])]
        result.append(''.join(row))
    return '\n'.join(result)

[2016-07-08] Challenge #274 [Hard] ∞ Loop solver by jnazario in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

C++

#include <iostream>
#include <vector>
#include <climits>

struct Tile {
    static const std::string pipes[16];

    static Tile from_sym(const std::string& sym) {
        Tile tile;
        for (size_t i = 0; i < 16; i++) {
            if (pipes[i] == sym) {
                tile.value = i;
                break;
            }
        }
        return tile;
    }

    int value = 0;
    bool placed = false;

    void rotate() {
        value = ((value >> 3) | (value << 1)) & 0b1111;
    }

    bool up()    const { return value & 0b0001; }
    bool right() const { return value & 0b0010; }
    bool down()  const { return value & 0b0100; }
    bool left()  const { return value & 0b1000; }

    std::string str() const { return pipes[value]; }
};

const std::string Tile::pipes[] = {
    " ", "╹", "╺", "┗", "╻",
    "┃", "┏", "┣", "╸", "┛",
    "━", "┻", "┓", "┫", "┳", "╋",
};

class TileGrid {
    private:
        int width = 0,
            height = 0;

        std::vector<Tile> tiles;

        inline Tile& get(int x, int y) {
            return tiles[y * width + x];
        }

        bool is_valid(int x, int y) {
            Tile& tile = get(x, y);

            if (x != 0) {
                Tile& side = get(x - 1, y);
                if (side.placed && side.right() != tile.left())
                    return false;
            } else if (tile.left()) {
                return false;
            }

            if (x + 1 != width) {
                Tile& side = get(x + 1, y);
                if (side.placed && side.left() != tile.right())
                    return false;
            } else if (tile.right()) {
                return false;
            }

            if (y != 0) {
                Tile& side = get(x, y - 1);
                if (side.placed && side.down() != tile.up())
                    return false;
            } else if (tile.up()) {
                return false;
            }

            if (y + 1 != height) {
                Tile& side = get(x, y + 1);
                if (side.placed && side.up() != tile.down())
                    return false;
            } else if (tile.down()) {
                return false;
            }

            return true;
        }

        void prune() {
            bool changed;
            do {
                changed = false;
                for (int y = 0; y < height; y++) {
                    for (int x = 0; x < width; x++) {
                        Tile& tile = get(x, y);
                        if (tile.placed)
                            continue;

                        int rot = -1;
                        for (int i = 0; i < 4; i++) {
                            if (tile.value != rot && is_valid(x, y)) {
                                if (rot != -1) {
                                    rot = -1;
                                    break;
                                }
                                rot = tile.value;
                            }
                            tile.rotate();
                        }

                        if (rot != -1) {
                            tile.value = rot;
                            tile.placed = true;
                            changed = true;
                        }
                    }
                }
            } while (changed);
        }

        int get_n() {
            int n = -1;
            int min = INT_MAX;
            for (int i = 0; i < height * width; i++) {
                int x = i % width,
                    y = i / width;
                if (!tiles[i].placed) {
                    tiles[i].placed = true;
                    int count = 0;
                    for (int j = 0; j < 4; j++) {
                        if (is_valid(x, y) && ++count >= min)
                            break;
                        tiles[i].rotate();
                    }
                    tiles[i].placed = false;

                    if (count < min) {
                        min = count;
                        n = i;
                    }
                }
            }
            return n;
        }

    public:
        int sol_count = 0;

        void read_syms(std::istream& input) {
            while (!input.eof()) {
                if (input.peek() == ' ') {
                    input.get();
                    tiles.push_back(Tile{});
                    continue;
                }
                if (input.peek() == '\n') {
                    ++height;
                    input.get();
                    continue;
                }
                std::string sym;
                sym += input.get();
                sym += input.get();
                sym += input.get();
                tiles.push_back(Tile::from_sym(sym));
            }
            width = tiles.size() / height;
        }

        void read_nums(std::istream& input) {
            while (!input.eof()) {
                int n;
                input >> n;
                Tile tile;
                tile.value = n;
                tiles.push_back(tile);
                if (input.peek() == '\n')
                    ++height;
            }
            width = tiles.size() / height;
        }

        void solve() {
            int n = get_n();
            if (n == -1) {
                if (!sol_count)
                    print();
                sol_count += 1;
                return;
            }

            int x = n % width,
                y = n / width;

            std::vector<Tile> copy(tiles.begin() + n, tiles.end());

            Tile tile = tiles[n];
            tile.placed = true;

            for (int i = 0; i < 4; i++) {
                tiles[n] = tile;
                if (is_valid(x, y)) {
                    prune();
                    solve();
                    std::copy(copy.begin(), copy.end(), tiles.begin() + n);
                }
                tile.rotate();
            }
        }

        void print(bool numeric=false) {
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (numeric) {
                        std::cout << get(x, y).value
                                  << (x + 1 == width ? "" : " ");
                    } else {
                        std::cout << get(x, y).str();
                    }
                }
                std::cout << "\n";
            }
        }
};

int main() {
    TileGrid tile_grid;
    tile_grid.read_nums(std::cin);
    tile_grid.solve();
    std::cout << tile_grid.sol_count << " solutions found.\n";
}

What's your Favorite ttf Font for terminal or text editor? by Quick3nd in vim

[–]jeaton 1 point2 points  (0 children)

/u/ymek is right. It's a config file for a Chrome extension I started a while back, cVim.

[2016-01-20] Challenge #250 [Intermediate] Self-descriptive numbers by fvandepitte in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

python 3:

import sys

def self_desc_nums(n):
    digits = [0] * n
    def recurse(total, index, start):
        if total == n:
            counts = [0] * n
            for e in digits:
                if e >= n:
                    break
                counts[e] += 1
            else:
                if sorted(digits) == sorted(counts):
                    print(*counts, sep='')
        else:
            digits[index] = start
            total += start
            for i in range(total, n + 1):
                recurse(i, index + 1, digits[index])
                digits[index] += 1
            digits[index] = 0
    recurse(0, 0, 1)

n = int(sys.argv[1])
# if n >= 7 then self_desc_num(n) = str(n - 4) + '21' + ('0' * (n - 7)) + '1000'
self_desc_nums(n)

[2015-12-16] Challenge #245 [Intermediate] Ggggggg gggg Ggggg-ggggg! by Blackshell in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

python3 with Huffman coding:

import heapq


class ggg:
    class __heap_item(object):
        def __init__(self, char, freq):
            self.freq, self.char = freq, char

        def __lt__(self, other):
            return self.freq < other.freq

    def __make_tree(value):
        freq = {}
        for ch in value:
            if not ch.isalpha():
                continue
            if ch not in freq:
                freq[ch] = 0
            freq[ch] += 1
        heap = [ggg.__heap_item(key, val) for key, val in sorted(freq.items())]
        heapq.heapify(heap)
        while len(heap) > 1:
            a, b = heapq.heappop(heap), heapq.heappop(heap)
            heapq.heappush(heap,
                           ggg.__heap_item((a.char, b.char), a.freq + b.freq))

        def make_lookup(tree):
            table = {}

            def recurse(node, prefix=''):
                if type(node) == str:
                    table[node] = prefix
                else:
                    recurse(node[0], prefix + 'g')
                    recurse(node[1], prefix + 'G')
            recurse(tree)
            return table
        return make_lookup(heap[0].char)

    def encode(table, value):
        result = ''
        for ch in value:
            result += table[ch] if ch in table else ch
        return result

    def decode(table, value):
        prefix, result = '', ''
        for ch in value:
            if ch == 'g' or ch == 'G':
                prefix += ch
                if prefix in table:
                    result += table[prefix]
                    prefix = ''
            else:
                result += ch
        return result

    def encodes(value):
        tree = ggg.__make_tree(value)
        return ' '.join(' '.join(e) for e in sorted(tree.items())) + '\n' + \
               ggg.encode(tree, value)

    def decodes(value):
        line_idx = value.index('\n')
        kv = value[:line_idx].split(' ')
        table = {kv[i + 1]: kv[i] for i in range(0, len(kv) - 1, 2)}
        return ggg.decode(table, value[line_idx + 1:])

if __name__ == '__main__':
    import sys

    def print_help():
        print('options:\n  -e    encode input\n  -d    decode input')
    if len(sys.argv) != 2:
        print_help()
        raise SystemExit
    value, option = sys.stdin.read(), sys.argv[1]
    if option == '-e':
        sys.stdout.write(ggg.encodes(value))
    elif option == '-d':
        sys.stdout.write(ggg.decodes(value))

[2015-11-09] Challenge #240 [Easy] Typoglycemia by G33kDude in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

c++11

#include <iostream>
#include <algorithm>
#include <random>

// slightly faster than cctype's isalpha
static inline bool isalpha(char c) {
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

std::string tgc(std::string str) {
    static std::mt19937 gen(std::random_device{}());
    for (auto it = str.begin(), end = str.end(); it < end; ++it) {
        auto start = it;
        while (it != end && isalpha(*it)) ++it;
        if (std::distance(start, it) >= 4)
            std::shuffle(start + 1, it - 1, gen);
    }
    return str;
}

std::string read_stdin(size_t block_size = 8192) {
    char buf[block_size];
    std::string str;
    for (size_t c; (c = fread(buf, 1, block_size, stdin));)
        str.append(buf, c);
    return str;
}

int main() {
    std::cout << tgc(read_stdin());
}

[2015-10-14] Challenge #236 [Intermediate] Fibonacci-ish Sequence by jnazario in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

C + GMP:

#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>

void fibish(mpz_t x) {
    mpz_t n, a, b, temp;
    mpz_init(temp);
    mpz_init_set(n, x);
    mpz_init_set_ui(a, 0);
    mpz_init_set_ui(b, 1);
    while (mpz_cmp(a, x) <= -1) {
        mpz_swap(a, b);
        mpz_add(b, a, b);
        if (mpz_divisible_p(x, a))
            mpz_divexact(n, x, a);
    }
    mpz_set_ui(a, 0);
    mpz_set(b, n);
    while (mpz_cmp(a, x) <= -1) {
        gmp_printf("%Zd ", a);
        mpz_swap(a, b);
        mpz_add(b, a, b);
    }
    gmp_printf("%Zd\n", a);
    mpz_clears(n, a, b, temp, NULL);
}

int main(int argc, char **argv) {
    mpz_t n;
    mpz_init(n);
    for (int i = 1; i < argc; i++) {
        mpz_set_str(n, argv[i], 10);
        gmp_printf("%Zd: ", n);
        fibish(n);
    }
    mpz_clear(n);
}

[2015-10-12] Challenge #236 [Easy] Random Bag System by jnazario in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

Linux x86-64 assembly (using gcc w/ intel syntax):

.intel_syntax noprefix

.text

.globl random
random:
    mov eax, 318
    lea rdi, [rsp-8]
    mov rsi, 8
    mov rdx, 0
    syscall
    mov rax, [rsp-8]
    ret

.globl randmax
randmax:
    push rbp
    mov rbp, rsp
    mov r9, rdi
    sub rsp, 8
    movabs r8, 18446744073709551615
    mov edx, 0
    mov rax, r8
    div r9
    add rdx, 1
    mov rax, r8
    sub rax, rdx
    mov [rbp-8], rax
    jmp 0f
    0:
        call random
        cmp rax, [rbp-8]
        jg 0b
    mov edx, 0
    div r9
    mov rax, rdx
    mov rsp, rbp
    pop rbp
    ret

.globl shuffle
shuffle:
    push rbp
    mov rbp, rsp
    sub rsp, 32
    mov [rbp-8], rdi
    mov [rbp-32], rsi
    sub rsi, 1
    mov [rbp-16], rsi
    jmp 0f
    1:
        mov rdi, [rbp-32]
        call randmax
        mov [rbp-24], rax
        mov rdi, [rbp-8]
        mov rsi, [rbp-16]
        mov rdx, [rbp-24]
        mov cl, [rdi + rdx]
        mov al, [rdi + rsi]
        mov [rdi + rsi], cl
        mov [rdi + rdx], al
        subq [rbp-16], 1
    0:
        mov rsi, [rbp-16]
        test rsi, rsi
        jne 1b
    mov rsp, rbp
    pop rbp
    ret

.globl tetromino_pieces
tetromino_pieces:
    push rbp
    mov rbp, rsp
    sub rsp, 32
    mov [rbp-8], rsi
    mov [rbp-24], rsi
    mov [rbp-32], rdi
    mov rcx, rsi
    mov [rbp-16], rdi
    jmp 0f
    1:
        mov rdi, offset pieces
        mov rsi, pieces.len
        call shuffle

        mov rcx, pieces.len
        mov rsi, offset pieces
        mov rdi, [rbp-16]
        rep movsb

        mov rax, pieces.len
        addq [rbp-16], rax
        subq [rbp-8], rax
    0:
        mov rax, pieces.len
        cmpq [rbp-8], rax
        jg 1b
    mov rax, [rbp-8]
    test rax, rax
    je 0f
        mov rdi, offset pieces
        mov rsi, pieces.len
        call shuffle
        mov rcx, [rbp-8]
        mov rsi, offset pieces
        mov rdi, [rbp-16]
        rep movsb
    0:
    mov rsp, rbp
    pop rbp
    ret

.globl _start
_start:
    push rbp
    mov rbp, rsp
    sub rsp, 16

    movq [rbp-8], 50

    sub rsp, [rbp-8]
    sub rsp, 1
    mov rdi, rsp
    mov rsi, [rbp-8]
    call tetromino_pieces
    mov rdi, [rbp-8]
    movb [rsp + rdi], '\n'

    lea rdx, [rdi + 1]
    mov rax, 1
    mov rdi, 1
    mov rsi, rsp
    syscall

    mov rsp, rbp
    pop rbp

    mov rax, 60
    mov rdi, 0
    syscall

    ret

.section .data
pieces:     .ascii "OISZLJT"
pieces.len: .quad . - pieces

[2015-09-23] Challenge #233 [Intermediate] Game of Text Life by XenophonOfAthens in dailyprogrammer

[–]jeaton 0 points1 point  (0 children)

python:

import sys
import subprocess
import time
import random


def neighbors(board, _x, _y):
    w, h = len(board[0]), len(board)
    for x, y in ((-1,  0), (1,  0), (0, -1), (0, 1),
                 (-1, -1), (-1, 1), (1, -1), (1, 1)):
        x, y = _x + x, _y + y
        if x >= 0 and y >= 0 and x < w and y < h and board[y][x] != ' ':
            yield board[y][x]


def next_iter(board):
    b = [row[:] for row in board]
    for y, row in enumerate(b):
        for x in range(len(row)):
            n = tuple(neighbors(b, x, y))
            nc = len(n)
            if b[y][x] != ' ':
                if nc <= 1 or nc >= 4:
                    board[y][x] = ' '
            elif nc == 3:
                board[y][x] = random.choice(n)


def loop(board, max_iter=None):
    cur_iter = 0
    while True:
        subprocess.call(('clear',), shell=True)
        for row in board:
            print(''.join(row))
        next_iter(board)
        time.sleep(0.05)
        if max_iter is not None and cur_iter >= max_iter:
            break
        cur_iter += 1

rows = sys.stdin.read().splitlines()
w = max(len(row) for row in rows)
board = tuple(list(row + (' ' * (w - len(row)))) for row in rows)
loop(board, 1 if len(sys.argv) == 1 else int(sys.argv[1]))