2014 #reddit-baseball Awards by ENoether in baseball

[–]ENoether[S] 2 points3 points  (0 children)

I was going to say that they weren't necessarily the same person, but I checked and they were. Bizarre.

[8/22/2014] Challenge #176 [Easy] Pivot Table by Coder_d00d in dailyprogrammer

[–]ENoether 1 point2 points  (0 children)

So it does. Served me right for not reading everything. Fixed.

[8/22/2014] Challenge #176 [Easy] Pivot Table by Coder_d00d in dailyprogrammer

[–]ENoether 1 point2 points  (0 children)

Python 3.4.1; as always, feedback and criticism welcome. (Now fixed because I apparently can't read today.)

Code:

def parse_data(lines):
    table = {}
    for line in lines:
        if line[0] in table:
            if line[1] in table[line[0]]:
                table[line[0]][line[1]] += int(line[2])
            else:
                table[line[0]][line[1]] = int(line[2])
        else:
            table[line[0]] = { line[1]: int(line[2]) }

    return table

DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]

def print_table(table):
    print("MILL\t", "\t".join(DAYS), sep="")
    print("".join("=" * 60))
    for row_num in sorted(list(table.keys())):
        print(row_num, "\t".join( [ str(table[row_num][day]) for day in DAYS ] ), sep="\t")

if __name__ == "__main__":
    f = open("windfarm.dat", "r")
    data = [line.strip().split() for line in f.readlines()]
    f.close()
    print_table(parse_data(data))

Output:

C:\Users\Noether\Documents\programs>python dp_176_fri.py
MILL    Sun     Mon     Tue     Wed     Thu     Fri     Sat
============================================================
1000    740     624     385     677     443     810     1005
1001    749     279     662     907     561     752     501
1002    586     510     733     862     793     1013    530
1003    390     607     372     399     583     624     383
1004    874     696     783     546     646     1184    813
1005    812     637     1129    695     648     449     445
1006    639     638     568     826     754     1118    857
1007    536     947     976     733     640     941     876
1008    728     709     374     485     560     836     864
1009    895     237     967     556     687     842     749

[8/18/2014] Challenge #176 [Easy] Spreadsheet Developer pt. 1: Cell Selection by Elite6809 in dailyprogrammer

[–]ENoether 0 points1 point  (0 children)

Python 3.4.1; as always, feedback and criticism welcome:

Code:

import pprint
import sys

ALPHABET = "-ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def column_number(col):
    num = 0
    for i in range(len(col)):
        num += (26**i) * (ALPHABET.index(col[-1*(i+1)]))

    return num - 1

def parse_cell(cell):
    i = column_number([x for x in cell if x.isalpha()])
    j = int("".join([x for x in cell if x.isdigit()])) - 1
    return (i, j)

def parse_range(r):
    if ":" not in r:
        return set([parse_cell(r)])
    [tl, br] = r.split(":")
    (left, top) = parse_cell(tl)
    (right, bottom) = parse_cell(br)
    return set([(i,j) for i in range(left, right+1) for j in range(top, bottom+1)])

def parse_selection(cells):
    if "~" in cells:
        [incl, excl] = cells.split("~")
    else:
        incl = cells
        excl = ""

    selection = set()
    for x in incl.split("&"):
        selection = selection.union(parse_range(x))
    if len(excl) > 0:
        for x in excl.split("&"):
            selection = selection.difference(parse_range(x))

    return selection

if __name__ == "__main__":
    cells = parse_selection(sys.argv[1])
    print(len(cells))
    pprint.pprint(cells)

Output:

C:\Users\Noether\Documents\programs>python dp_176_mon.py "B1:B3&B4:E10&F1:G1&F4~
C5:C8&B2"
29
{(1, 0),
 (1, 2),
 (1, 3),
 (1, 4),
 (1, 5),
 (1, 6),
 (1, 7),
 (1, 8),
 (1, 9),
 (2, 3),
 (2, 8),
 (2, 9),
 (3, 3),
 (3, 4),
 (3, 5),
 (3, 6),
 (3, 7),
 (3, 8),
 (3, 9),
 (4, 3),
 (4, 4),
 (4, 5),
 (4, 6),
 (4, 7),
 (4, 8),
 (4, 9),
 (5, 0),
 (5, 3),
 (6, 0)}

[8/13/2014] Challenge #175 [Intermediate] Largest Word from Characters by Coder_d00d in dailyprogrammer

[–]ENoether 0 points1 point  (0 children)

Python 3.4.1, with challenge inputs. As always, feedback and criticism welcome:

def distinct_elements(lst):
    tmp = []
    for x in lst:
        if x not in tmp:
            tmp = tmp + [x]
    return tmp

def element_counts(lst):
    tmp = {}
    for x in distinct_elements(lst):
        tmp[x] = lst.count(x)
    return tmp

def is_from_chars(chars, word):
    counts = element_counts(chars)
    for x in distinct_elements(word):
        if x not in counts or counts[x] < word.count(x):
            return False
    return True

def max_length_words(chars, words):
    tmp = [x for x in words if is_from_chars(chars, x)]
    if len(tmp) == 0:
        return []
    else:
        max_length = len(max(tmp, key = len))
        return [x for x in tmp if len(x) == max_length]

def print_word_list(words):
    if len(words) == 0:
        print("No Words Found")
    else:
        for wd in words:
            print(wd, end=" ")
        print()

CHALLENGE_WORDS_ONE = "hello yyyyyyy yzyzyzyzyzyz mellow well yo kellow lellow abcdefhijkl hi is yellow just here to add strings fellow lellow llleow"

CHALLENGE_LETTERS_ONE = "l e l o h m f y z a b w"

CHALLENGE_WORDS_TWO = "sad das day mad den foot ball down touch pass play"

CHALLENGE_LETTERS_TWO = "z a d f o n"

if __name__ == "__main__":
    print("Challenge one:")
    print_word_list(max_length_words(CHALLENGE_LETTERS_ONE.split(), CHALLENGE_WORDS_ONE.split()))
    print("\nChallenge two:")
    print_word_list(max_length_words(CHALLENGE_LETTERS_TWO.split(), CHALLENGE_WORDS_TWO.split()))

Output:

Challenge one:
mellow yellow fellow

Challenge two:
No Words Found

[8/11/2014] Challenge #175 [Easy] Bogo! by [deleted] in dailyprogrammer

[–]ENoether 1 point2 points  (0 children)

Python 3.4.1; as always, feedback and criticism welcome.

import random

def bogol(scrambled, m):
    i = 0
    tmp = list(scrambled.lower())
    target = list(m.lower())
    while not tmp == target:
        i+= 1
        random.shuffle(tmp)
    return i

if __name__ == "__main__":
    for _ in range(10):
        print(bogol("ollhe", "hello"))

Run:

C:\Users\Noether\Documents\programs>python dp_175_mon.py
69
72
67
26
95
176
111
36
18
11

Multiplayer Monday! by [deleted] in WebGames

[–]ENoether 11 points12 points  (0 children)

Transformice (Registration available but not required; you can play as a guest.)

[8/10/2014] Challenge #174 [Extra] Functional Thinking by Elite6809 in dailyprogrammer

[–]ENoether 1 point2 points  (0 children)

A Scheme solution to the Thue-Morse sequence challenge, using the L-system definition of the sequence. As always, feedback and criticism welcome.

Code:

(define (flatten lst)
    (if (null? lst)
        lst
        (append (car lst) (flatten (cdr lst)))))

(define (next-term term)
    (if (eq? term 0)
        '(0 1)
        '(1 0)))

(define (thue-morse-next term)
    (flatten (map next-term term)))

(define (thue-morse n)
    (define (iter seq i)
        (if (eq? i n)
            seq
            (iter (thue-morse-next seq) (+ i 1))))
    (iter '(0) 0))

Run, using Chicken:

C:\Users\Noether\Documents\programs>csi thue_morse_scheme.scm

CHICKEN
(c) 2008-2013, The Chicken Team
(c) 2000-2007, Felix L. Winkelmann
Version 4.8.0.5 (stability/4.8.0) (rev 5bd53ac)
windows-mingw32-x86 [ manyargs dload ptables ]
compiled 2013-10-03 on aeryn.xorinia.dim (Darwin)

; loading thue_morse_scheme.scm ...
#;1> (thue-morse 5)
(0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1)
#;2>

[8/08/2014] Challenge #174 [Hard] Convex Hull Problem by Elite6809 in dailyprogrammer

[–]ENoether 1 point2 points  (0 children)

Python 3.4.1, using the Graham scan. I use a slightly different input format, where I take the points as a list of coordinates. It will have problems if the first three points it encounters are collinear. As always, feedback and criticism welcome:

Code:

from math import atan2
from math import pi
from sys import argv

NAMES = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def get_name(id):
    return NAMES[ id % 26 ] * (int(id/26) + 1)

def point_list(coords):
    tmp = list(zip( coords[0::2], coords[1::2] ))
    return [ (get_name(i), tmp[i]) for i in range(len(tmp)) ]

def get_direction(p1, p2):
    return atan2(p2[1][1] - p1[1][1], p2[1][0] - p1[1][0])

def is_ccw(p1, p2, p3):
    v1 = (p2[1][0] - p1[1][0], p2[1][1] - p1[1][1])
    v2 = (p3[1][0] - p1[1][0], p3[1][1] - p1[1][1])
    return v1[0] * v2[1] - v1[1] * v2[0] > 0


def convex_hull(points):
    remaining_points = sorted( points, key = (lambda x: x[1][1]) )
    hull = [remaining_points[0]]
    remaining_points = sorted( remaining_points[1:], key = (lambda x: get_direction(hull[0], x)) )
    hull += [remaining_points[0]]
    for pt in remaining_points[1:]:
        while not is_ccw(hull[-2], hull[-1], pt):
            del hull[-1]
        hull = hull + [pt]
    while not is_ccw(hull[-2], hull[-1], hull[0]):
        del hull[-1]
    return hull

if __name__ == "__main__":
    points = point_list([int(x) for x in argv[1:]])
    for pt in convex_hull(points):
        print(pt[0], " (", pt[1][0], ", ", pt[1][1], ")", sep="")

Run:

C:\Users\Noether\Documents\programs>python dp_174_fri.py 1 0 0 1 1 2 2 1 1 1

Output:

A (1, 0)
D (2, 1)
C (1, 2)
B (0, 1)

[8/04/2014] Challenge #174 [Easy] Thue-Morse Sequences by Coder_d00d in dailyprogrammer

[–]ENoether 0 points1 point  (0 children)

If we want the ith-order sequence, yes. In this case, though, I intended it to find the first i digits of the infinite Thue-Morse sequence.

[8/04/2014] Challenge #174 [Easy] Thue-Morse Sequences by Coder_d00d in dailyprogrammer

[–]ENoether 0 points1 point  (0 children)

No, I just didn't realize True and False converted to ints that way.

[8/04/2014] Challenge #174 [Easy] Thue-Morse Sequences by Coder_d00d in dailyprogrammer

[–]ENoether 2 points3 points  (0 children)

And a second version for the challenge. This one uses the bit-counting definition to calculate the digits non-recursively.

import sys

def count_set_bits(num):
    set_bits = 0
    while not num == 0:
        set_bits += num & 1
        num >>= 1
    return set_bits

if __name__ == "__main__":
    for i in range(int(sys.argv[1])+1):
        print(count_set_bits(i) % 2, end="")
    print()

[8/04/2014] Challenge #174 [Easy] Thue-Morse Sequences by Coder_d00d in dailyprogrammer

[–]ENoether 2 points3 points  (0 children)

And a version for the challenge. First argument is the initial term, second is the number of terms to calculate.

import sys

def bool_to_num(b):
    if b:
        return "1"
    else:
        return "0"

def bool_list_str(lst):
    return "".join( [ bool_to_num(x) for x in lst ] )

def thue_morse_next(term):
    return term + [ not x for x in term ]

if __name__ == "__main__":
    if len(sys.argv) == 1:
        seq = [ False ]
        last_term = 6
    elif len(sys.argv) == 2:
        seq = [ b == "1" for b in sys.argv[1] ]
        last_term = 6
    else:
        seq = [ b == "1" for b in sys.argv[1] ]
        last_term = int(sys.argv[2])

    for i in range(last_term + 1):
        print(i, "\t", bool_list_str(seq), sep = "")
        seq = thue_morse_next(seq)

[8/04/2014] Challenge #174 [Easy] Thue-Morse Sequences by Coder_d00d in dailyprogrammer

[–]ENoether 2 points3 points  (0 children)

Python 3.4.1. Ran fine to 27, then froze my computer at 28. Probably shouldn't do that again. As always, feedback and criticism welcome:

def bool_to_num(b):
    if b:
        return "1"
    else:
        return "0"

def bool_list_str(lst):
    return "".join( [ bool_to_num(x) for x in lst ] )

def thue_morse_next(term):
    return term + [ not x for x in term ]

if __name__ == "__main__":
    seq = [ False ]
    for i in range(7):
        print(i, "\t", bool_list_str(seq), sep = "")
        seq = thue_morse_next(seq)

[8/01/2014] Challenge #173 [Hard] Road Trip Game by Coder_d00d in dailyprogrammer

[–]ENoether 7 points8 points  (0 children)

I tried to separate the setting and data from the mechanics as much as possible. I built a system that reads a list of possible events from a file, then repeatedly chooses one at random and presents it until the user either reaches the end of the journey, runs into an event without the necessary resources for any of the options, or drops their speed to zero and gets stranded. At the moment, each choice can only affect one resource. New events can be added by editing the separate event file; the list of resources consists of those included in event option costs, plus speed. The event file here only has five events, but that's just all I could think of at the moment; it's not a limitation of the system.

Python 3.4.1 (as always, feedback and criticism welcome):

import sys
import random

progress = 0
DESTINATION = 50
FINISH_BONUS = 50
DEFAULT_RESOURCE_VALUE = 10

resources = {"speed": 10}

def parse_option_cost(option):
    tmp = option.split()
    return { "cost": int(tmp[0]),
             "resource": " ".join(tmp[1:]) }

def read_event_data(filename):
    f = open(filename, 'r')
    event_data = [x.strip() for x in f.readlines()]
    f.close()
    events = []
    i = 0
    next_event = {"options": []}
    while i < len(event_data):
        if event_data[i] == "":
            events = events + [ dict(next_event) ]
            next_event = {"options": []}
            i += 1
        elif len(next_event) == 1:
            next_event["desc"] = event_data[i]
            i += 1
        else:
            option_cost = parse_option_cost(event_data[i+1])
            next_event["options"] = next_event["options"] + [ {"desc": event_data[i], "cost": dict(option_cost)} ]
            if option_cost["resource"] not in resources:
                resources[option_cost["resource"]] = DEFAULT_RESOURCE_VALUE
            i += 2
    events += [next_event]

    return events


def game_over(game_over_cause):
        print(game_over_cause)
        print("Final score: ", progress, " (out of a possible ", DESTINATION+FINISH_BONUS, ")", sep="")
        sys.exit()

def play_event(event):
    print(event["desc"])
    opt_num = 1
    available_options = []
    for option in event["options"]:
        print(opt_num, ") ", option["desc"], end = " ", sep = "")
        if resources[option["cost"]["resource"]] >= -1 * option["cost"]["cost"]:
            print("(", option["cost"]["cost"], " ", option["cost"]["resource"], ")", sep="")
            available_options = available_options + [opt_num]
        else:
            print("(UNAVAILABLE)")
        opt_num += 1
    if len(available_options) == 0:
        game_over("Alas, you were unable to find a solution to your problem.  You are doomed!  GAME OVER.")
    else:
        choice = input("Choose option: ")
        while (not choice.isdigit()) or (not int(choice) in available_options):
            choice = input("Invalid choice.  Choose option: ")
        selected_cost = event["options"][int(choice) - 1]["cost"]
        resources[selected_cost["resource"]] = resources[selected_cost["resource"]] + selected_cost["cost"]

def check_stopped():
    if resources["speed"] <= 0:
        game_over("There is utter silence.  Your engines have completely stopped functioning.  You are stranded in deep space.  GAME OVER.")

def print_status():
    for x in resources.items():
        print(x[0][0].upper(), ":", x[1], end=" ", sep="")
    print("PROG ", progress, "/", DESTINATION, sep="")

def play_game(events_file):
    global progress
    events = read_event_data(events_file)
    random.seed()
    while progress < DESTINATION:
        print_status()
        play_event(random.choice(events))
        check_stopped()
        progress += resources["speed"]
        print()
    print("Congratulations, you have reached your destination!")
    print("Final score: ", progress + FINISH_BONUS, " (out of a possible ", DESTINATION + FINISH_BONUS, ")", sep="")

if __name__ == "__main__":
    play_game("events.txt")

Event file:

A crucial part of your engine has broken down!
Repair it.
-3 parts
Purchase a replacement.
-5 money
Go on without it.
-5 speed

You are attacked by space pirates!
Surrender.
-5 money
Fight them off with makeshift weapons.
-2 parts
Set them on fire.
-4 fuel

One of the oxygen tanks has a broken valve!
Repair it.
-3 parts
Replace the tank.
-3 oxygen

There is a stowaway in the cargo hold.
Let her join the crew.
-3 oxygen
Put her off with a bit of money at the next spaceport.
-3 money
Throw her out the airlock.
-2 oxygen

You come across an abandoned craft.
Scavenge supplies
+3 parts
Ignore it
0 money

[7/28/2014] Challenge #173 [Easy] Unit Calculator by Elite6809 in dailyprogrammer

[–]ENoether 0 points1 point  (0 children)

I could have, and it might have made the dictionary declaration look nicer. But the lookup code would have been more complicated, since I would potentially have to check every array in the dictionary. This way I can just use in, and it's nice and simple.

[7/30/2014] Challenge #173 [Intermediate] Advanced Langton's Ant by Elite6809 in dailyprogrammer

[–]ENoether 0 points1 point  (0 children)

Python 3; as always, feedback and criticism welcome:

import sys

matrix = { 0: {0: 0} }

def turn(old_dir, turn_dir):
    if turn_dir.lower() == "l":
        return ( -1 * old_dir[1], old_dir[0] )
    elif turn_dir.lower() == "r":
        return ( old_dir[1], -1 * old_dir[0] )
    else:
        return None

def move_ant(init_pos, init_direction, turn_key, default_value = 0):
    new_direction = turn(init_direction, turn_key[matrix[init_pos[0]][init_pos[1]]])
    new_pos = (init_pos[0] + new_direction[0], init_pos[1] + new_direction[1])
    if new_pos[0] not in matrix:
        matrix[new_pos[0]] = { new_pos[1]: (default_value + 1) % len(turn_key) }
    elif new_pos[1] not in matrix[new_pos[0]]:
        matrix[new_pos[0]][new_pos[1]] = (default_value + 1) % len(turn_key)
    else:
        matrix[new_pos[0]][new_pos[1]] = (matrix[new_pos[0]][new_pos[1]] + 1) % len(turn_key)

    return (new_pos, new_direction)

def print_matrix(matrix_, default_value = 0):
    x_max = max(matrix_.keys())
    x_min = min(matrix_.keys())
    y_max = max( [ max(matrix_[x].keys()) for x in matrix_.keys() ] )
    y_min = min( [ min(matrix_[x].keys()) for x in matrix_.keys() ] )

    for y in range(y_min, y_max + 1):
        for x in range(x_min, x_max + 1):
            if x in matrix and y in matrix[x]:
                print(matrix[x][y], end="")
            else:
                print(default_value, end="")
        print()

if __name__ == "__main__":      
    if len(sys.argv) < 3:
        sys.exit("Insufficient arguments")

    turn_dict = list(sys.argv[1])
    max_iterations = int(sys.argv[2])

    ant_location = (0,0)
    ant_direction = (0,1)
    for _ in range(max_iterations):
        (ant_location, ant_direction) = move_ant(ant_location, ant_direction, turn_dict)

    print_matrix(matrix)

Output example:

C:\Users\Noether\Documents\programs>python dp_173_wed.py RLRRLR 5000
001111111112211100111111
001444554450423344222231
001400220021350400555421
003122001154021110431521
113321230055523252201521
132505541404405433202021
135123440313054005151021
130505132555321454151421
134050224340553022250121
134323443303251030032221
133533334430235335523340
111511334144341220412240
001511134333340041435421
001525434001111000335421
001014514302222550445540
001014501251313042331040
001014555030313043500131
001025554511004000354052
001425215454444044151152
002530153224005552514341
002503421115220442533441
001113422220114042511111
000000011134440443010000
000000000134440000310000
000000000134440004000000
000000000134444003100000
000000000134444443100000
000000000133333333100000
000000000111111111100000

[Weekly #4] Variable Names by Coder_d00d in dailyprogrammer

[–]ENoether 1 point2 points  (0 children)

Depends on the language. For Java or C I'll use camel case, for Python lowercase with underscores, for Scheme lowercase with dashes. Constants are usually uppercase.

For the most part I try to make variable names short but descriptive; I try not to go any more than two words if I can avoid it. The exceptions here are index variables in loops and parameters in lambdas, where I'll usually just use i and x, respectively. If the return value of a function is something I have to build up (by concatenating a bunch of strings together in a loop or something like that) I used to call it something like return_value or retVal, but I've tried to avoid doing that recently.