Sunday, July 18, 2010

Continuing with the ruby text game

Posting from Ubuntu 10.04 now, so I'm much more ready to use ruby properly.

I've made updates to my files, as shown here:

Rakefile:
require "rake/testtask"

task :default => [:test]

Rake::TestTask.new do |test|
test.libs << "test"
test.test_files = Dir[ "test/test_*.rb" ]
test.verbose = true
end
test/test_game.rb
require 'test/unit'
require 'test/extension.rb'
require 'stringio'
require 'src/game.rb'

class GameTest < Test::Unit::TestCase

command_list = ["left", "right", "forward",
"go", "back", "shoot", "pew",
"pewpew", "map", "look", "check"]

bad_command_list = ["up", "down", "north", "3", "go wildcats",
"wepwep", "a map", "map ", "go map"]

def setup
@input = StringIO.new
@game = Game.new(@input)
end

command_list.each do |command|
must "set the inputted command: \"#{command}\"" do
#puts "set the inputted command correctly when parsing #{command}"
provide_input(command)
@game.get_command
assert_equal @game.command, command
end
end

command_list.each do |command|
bad_command_list.each do |bad_command|
must "retain the command \"#{command}\" and fail to set \"#{bad_command}\"" do
provide_input(command)
@game.get_command
provide_input(bad_command)
@game.get_command
assert_equal @game.command, command
end
end
end

def provide_input(string)
remember = @input.pos
@input << string
@input.pos = remember
end
end
src/game.rb
class Game
attr_reader :command

def initialize(readin=STDIN, output=STDOUT)
@input = readin
@output = output
@command_list = ["left", "right", "go", "back",
"shoot", "check", "look", "pew",
"pewpew", "exit", "map", "forward"]
end

def get_command
temp_command = @input.gets
temp_command.chomp!
if @command_list.index(temp_command) != nil then
@command = temp_command
end
end

def loop
while @command != "exit"
get_command
puts @command
end
end
end
This has all gone rather well. Running 'rake test' gives:
(in /media/sda1/Users/wcarss/code/ruby)
/usr/bin/ruby1.8 -I"lib:test" "/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader.rb" "test/test_game.rb"
Loaded suite /usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader
Started
..............................................................................................................
Finished in 0.012626 seconds.

110 tests, 110 assertions, 0 failures, 0 errors
Excellent! Now that's out of the way...

What next?

We've got a game class accepting commands - I think it'd be pertinent to have a Robot who can receive them. A robot ought to have a position, ought to be able to take actions, and have a name. I figure that means making the files test/test_robot.rb and src/robot.rb

test_robot.rb:
require 'test/unit'
require 'test/extension.rb'
require 'src/robot.rb'
require 'matrix'

class RobotTest < Test::Unit::TestCase

directions = ["north", "east", "south", "west"]
base_pos = Vector[5,5]

forward_list = ["go", "forward"]
backward_list = ["back", "backward"]
new_pos = [Vector[0,1], Vector[1,0], Vector[0,-1], Vector[-1,0]]

def setup
@bot = Robot.new
end

directions.each_index do |i|
must "change direction to #{directions[i]} from #{directions[i-1]} on right" do
@bot.direction = directions[i-1]
@bot.right
assert_equal directions[i], @bot.direction
end
end

directions.each_index do |i|
must "change direction to #{directions[i-1]} from #{directions[i]} on left" do
@bot.direction = directions[i]
@bot.left
assert_equal directions[i-1], @bot.direction
end
end

forward_list.each do |command|
directions.each_index do |i|
must "move correctly forward when facing #{directions[i]}, using #{command}" do
@bot.pos = base_pos
@bot.direction = directions[i]
@bot.send(:"#{command}")
assert_equal @bot.pos, base_pos + new_pos[i]
end
end
end

backward_list.each do |command|
directions.each_index do |i|
must "move correctly backward when facing #{directions[i]}, using #{command}" do
@bot.pos = base_pos
@bot.direction = directions[i]
@bot.send(:"#{command}")
assert_equal @bot.pos, base_pos - new_pos[i]
end
end
end
end
robot.rb
require 'matrix'

class Robot
attr_reader :pos, :direction, :name, :score
attr_writer :pos, :direction, :name, :score

@@directions = ["north", "east", "south", "west"]

def initialize(name="Killbot 4000", x_pos = 0, y_pos = 0, direction="north")
@pos = Vector[x_pos, y_pos]
@name = name
@direction = direction
end

def left
@direction = @@directions[ direction_as_int() - 1]
end

def right
@direction = @@directions[ (direction_as_int() + 1) % @@directions.size]
end

def direction_as_int
@@directions.index(@direction)
end

def next_pos
angle = 90 * direction_as_int() * Math::PI/180
Vector[Math.sin(angle).round, Math.cos(angle).round]
end

def forward
@pos = @pos + next_pos()
end

def backward
@pos = @pos - next_pos()
end

def look
puts "Your windows are fogged!"
# not implemented
end

def shoot
puts "KABOOM (probably)"
# not implemented
end

alias back backward
alias go forward
alias check look
alias pew shoot
alias pewpew shoot
end
So, what on earth's going on here? Hopefully a lot of it is self-evident! The robot knows 4 directions, and I generated tests to check that left/right properly cycle through those. Then I generated a set of tests to check that, for every command, for every direction, the robot alters its position correctly. For example, if facing north using 'go', the robot should increment its y-position by 1. (I'm using north as positive, south as negative y, while west is negative x and east is positive x).

The bot itself is a little scattered for the moment - I'll collect private/public methods together next iteration, and I'm thinking I might make a "Direction" class, because a surprising amount of direction-logic had to go into the robot class. If I could just say the bot has a facing = Direction.new("north"), then print facing.to_s or .to_i, facing.left, facing.right, all these things - it would simplify the robot code tremendously. And it's all mostly done already!

Next after that I think is the World class, which will have a text-representation and some notion of simple buildings. From there I'm going to have to implement shooting stuff and looking around, which I think will involve line of sight, which I've never even really /thought about/, so it should be pretty cool.

OH! Actually, what I'll do next iteration is the following:

actually make the game loop send commands to the robot (haha, kinda important)
split direction into its own class with its own tests

then the one after that will be the world class / displaying the map

then like a half iteration should be all I need to make buildings blowupable and implement score. Sounds fun. :)

Thursday, July 15, 2010

Let's make a small text game in Ruby

Want to do some stuff with Ruby? So do I! I'm going to make a small text game, where you control a robot and blow up buildings.

So let's start by thinking about how the game will work. Pretty much, I want it to be command-line interactive and turn based. So you enter a command, and then something happens, and then you can enter another thing, and so on. You should be able to turn left or right and move forward and backward, and check what's in front of you. You should also be able to shoot.

I'm thinking sensible commands would be:

left
right
forward (maybe also go)
back
shoot (also pew or pewpew)
look (or check)

everything should be lower case for now. There'll be buildings randomly placed about, and when you are facing them and shoot, they should blow up. Maybe an extra command,

map

would be useful so you can see there's a building (demarcated by a B) somewhere, and a blown up building (demarcated by an X) somewhere else, and you the player, demarcated by a P. Later, I could make you be one of ^ v > < depending on your facing or something. A score for how many buildings you blown up would be neat too.

COOL!

So where do we begin? Well, if I want it to be interactive I'm going to have to have some kind of game-loop. I *could* just make this a game you play by issuing Class.command commands in irb or something, but that feels cheap. So it makes sense to me that I'd have some sort of controller class I'll call Game. I'm also going to need a Player.. or a Robot who moves around. Yeah, I like the thought of Robot being the thing that shoots. Then I'm gonna need Buildings, and a Map.

So, the Game will have a Robot, Buildings and a Map.
each Building will have a location and a status: either it exists or it doesn't!
the Robot will have a location, a direction, and maybe a name.
the Map will have to show the Robot and the Buildings, and eventually (I hope) the facing.

So let's get started already!!!

First, Iteration 1: Let's make the Game class and the main loop inside it, which will receive commands. What do we do now? That's right, we write some tests!

I'm going to lift some code pretty closely out of Ruby Best Practices here, because it does just about exactly what we want:
class GameTest < Test::Unit::TestCase
def setup
@commandlist = ["left", "right", "forward",
"go", "back", "shoot", "pew",
"pewpew", "map", "look", "check"]
@input = StringIO.new
@game = Game.new(@input)
end

commandlist.each do |command|
must "set the inputted command correctly when parsing #{command}" do
provide_input(command)
Game.get_command
assert_equal Game.command, command
end
end

def provide_input(string)
@input << string
@input.rewind
end
end
not having run this yet or ever done testing in ruby before, I have /no idea/ if this will actually work. Having written it though, I'm going to throw my Game class together (which now essentially writes itself)
class Game
attr_reader :command

def initialize(readin=STDIN, output=STDOUT)
@input = readin
@output = output
@command_list = ["left", "right", "go", "back",
"shoot", "check", "look", "pew",
"pewpew", "exit", "map", "forward"]
end

def get_command
temp_command = @input.gets
temp_command.chomp!
if @command_list.index(temp_command) != nil then
@command = temp_command
end
end

def loop
while @command != "exit"
get_command
puts @command
end
end
end
I don't have rake or rubygems on this computer, so I can't test this yet! I'll have to do so a little later - after a quick manual test of the Game class, it looks like it is in the right place. I realized while making it though, that I forgot to test that I'm not taking inappropriate commands! Fortunately I built it into the game class, and I'll modify the test soon to check for it.

Also of note, my directory structure at the moment:
/
/Rakefile
/src/
/src/game.rb
/test/
/test/test_game.rb
ah, and what exactly is in the rakefile? I've never used rake before! But again lifting from Ruby Best Practices (a fantastic book!), I've got
require "rake/testtask"

task :default => [:test]

Rake::TestTask.new do |test|
test.libs << "test"
test.test_files = Dir[ "test/test_*.rb" ]
test.verbose = true
end
And that's where I'll leave it for now. More later when I can actually run tests and find out all the things I've done incorrectly. :)

Friday, May 14, 2010

Corporations are re-enacting the histories of Nations

At least in some sense, Corporations and Nations are each large hierarchies of people that serve a common purpose. It's interesting to look at some recent corporate situations and see how far the comparison takes us.

Apple v Adobe

Apple and Adobe, founded around similar times by similarly minded people, have each grown spectacularly, and each hold very similar values. Recently, Apple decided that Adobe might have a bit too much control, and so decided to attack(No Flash, and Section 3.1.1, various written statements). Adobe has counterattacked in various ways (working around tech limitations, but mostly written statements), and the two could be said to be at war with one another. It's interesting to see how they manage to fight each other without spending lives, and while continuing to hold similar ideologies.

Google v China

Google is at war with China over ideology. One of the world's largest companies is fighting the government of the most populous nation on earth over what comes down to human rights. That a corporation can see itself as an adversary and competitor to an enormous (super?)power like China shows how much corporations are themselves like nations today.

Facebook v The People

Facebook is currently dealing with a revolt. The large-scale population of its users may or may not be aware of it, but a vocal minority is calling for the downfall of the site, and regularly publishing articles, studies, and anti-facebook propaganda, while organizing events designed to help get people to quit. I'm not particularly a fan of facebook myself, but it doesn't change the tactics that are being used. Facebook, a corporation, is at risk of being overthrown by its population and disbanded.

Conclusions

To my mind, there are at least three major corporate wars taking place in the tech world at the moment. There are classic rivalries like Coke v Pepsi, Nintendo v Sega (or Sony (or Microsoft)), acquisitions and annexations occur all the time, and corporations live their own lives as entities on a scale above our own, just as nations do, only corporations are borderless and have the ability to pivot themselves. Religious organizations may fit within this class of entity as well, and certainly wars and revolutions have occurred within them, but perhaps they are not as successful as the corporate being is, because there were by necessity so many fewer of them? Small population, small diversity, slow evolution?

Regardless of what my own spin is, living in a time where such tremendous conflicts as Apple v Adobe, Google v China, and The Facebook Revolt are taking place has me excited. The balances of power are shifting restlessly, and that means there's probably a way to gain advantage and come out with a lot of power.

Tuesday, April 27, 2010

Good work

Learned a lot about SDL in the last day or two. Making a tile-based game of some sort this evening. I'll get back with screenshots tomorrow.

Once I've got some experience, a Tetris RPG will be on its way (I've had this idea on a backburner forever waiting for a key concept to make sense that finally worked itself out in my head a few days ago)

Then I'll settle into drupal and wiki stuff, and see what I can do with a Wiimote.

Saturday, April 24, 2010

It's a reasonable thing to do

My last posts were correct, I suspect. One of my largest issues is that of distraction, and of a lack of focus. When I get focused, I can get into a fantastic groove (and produce excellent things quickly! Looking at you, lexical analyzer for pish I wrote in an evening), so the problem becomes getting focused.

My day-to-day activities have helped to breed a lack of focus in me. I switch contexts so frequently that it is now habitual. I wake up, check hackernews for articles, read a few sentences from an article, and then engage switching between MSN, email, getting ready for school, and reading whatever little bits of whatever article I go to when alt+tabbing or ctrl+tabbing around. This has left me switching contexts in places where it's not demanded, and not focusing in when that's precisely what I need.

So the question becomes, "how can I focus?". It may be something I need to learn, but again, how? My thoughts are that it comes down to the mental discipline to force myself to finish a task. If I am blogging (for example) and I decide I would like to watch the new episode of Lost today, or check out a book on my shelf, or read old blog posts, I must force myself to finish my task and then switch instead of just switching as soon as the thought occurs.

This is likely applicable at a larger scale. Getting a project off the ground, or getting a serious improvement to one's self going, takes a lot of energy, which is present in the early stages. As time progresses though, New Task Energy wears off and you want to switch to something more exciting. I've got to learn to be fuelled by Achievement Energy (when I've finished a task) instead of by the energy I get from having something new to work on. I've got to pick reasonable goals and work toward them, and not start new things until I'm done chewing what I've bitten off.

This summer, I have some hopes. I'd like to build two things minimally, and five things maximally:

compiler
code style switcher
3d drawing environment
zoomable code editor
knowledge map collaboration station

I'm not even certain which of those is toughest. I also want to do other things, like dissect some open source code and mess with it (particularly the Cube engine used in games like Sauerbraten) and learn some webGL/jQuery/drupal stuff, and then general stuff like math and science skills, etc.

So, knowing that these are the things I'd like to end up with, I should draft some goals, some critical paths to the goals, and see what seems reasonable. The things which have my attention most at the moment are the knowledge map collaboration station and the 3d drawing environment.

That said, my plan is to not be especially productive until I want to be. I'm going to watch television, sleep, play video games, and read until I'm very bored of doing these things (I predict just less than 2 weeks of slacking) and then to come out of it a masterfully productive sort of person.

The biggest point I need to make here is that once I've set these goals up, I can break down tasks for what I'd like to finish, but once I am in the midst of a task, I must perform it to completion. Working on something halfway and dropping out is how to not finish it. Once I start a thing, I will go until it's done. Then it just becomes a problem of starting.

Good luck, future me.

Sunday, March 28, 2010

Failure and success

Goals are coming along, but I didn't report back on Friday or even really start the phil paper. I'm working on it at the moment, finally picked up some steam.

Will report once it's a reasonable thing to do.

edit (many days later): post coming tonight

Wednesday, March 24, 2010

It's been a fun couple of months.

I am realizing that I need a framework for living - not as a ruleset, but as a guideline. One that permits failures, and has guidelines to return onto track.

Regularly, I'll have things to do, and I'll suddenly be really tired. Or really distracted. Or really want to do something else first (in one of those right now). Somehow I'm never getting to sleep on time, never getting home on time, never getting projects in on time, never getting to school on time. Never doing enough, always planning more than I can achieve.

This ultimately means that I'm less capable than I think. Whether that's because I lack the attention span or discipline to achieve what I would be ideally capable of, or because I set my sights far beyond even what I'm ideally capable of, I'm uncertain. What I am certain of is that I need to change, because I'm not in a good spot. There are too many deadlines approaching, too quickly, even after having made sacrifices.

So this is what my spare cycles will go into for the next while. Wait a minute, how can I have spare cycles with so much to do? Well that's precisely the problem. I feel like my programs aren't optimized to my hardware -- rather than packing 4 1-cycle instructions together for alignment, I've got empty space floating around and do nothing with it. So I'll make this my ambient thought-topic: what guidelines can get a person back on track, and keep them on track?

Off the bat, I see that I need goals. These goals will provide motivation and metrics, and from those I can set myself tasks and make plans. I can develop small heuristics to remind myself with whenever I suddenly decide "this'd be a great time to write a blog post", "I could hang out with Sophie later", or "man, I'm tired. Sleep is good for me -- I'll (stay asleep / go to sleep) even though I've got stuff to do."

Alright, hope I can stick to it even marginally. A first goal: report back on friday with some progress. A second goal: finish my philosophy paper this evening.

Wednesday, February 10, 2010

How I solve problems

I'm not really sure how I solve problems. What I'm betting though, is that I could improve my problem solving ability by paying attention to the process as I bumble through it. Maybe we all could. So let's define this with a touch of formalism.

Where I'm at

I have a problem to solve. I've got an existing program, and I need to make some changes to it to enhance its functionality. I must think that this is a hard problem, because I have procrastinated significantly on it, and every time I go to start it, I get a little lost.

The sense of being lost comes from a few directions.

1) There are multiple ways to solve the problem - some easier than others, but with hard to quantify costs of later complexity and code to rework.

2) The existing program is a hacked together mess.

3) I haven't really solved this problem before.

4) There are technical tools which would help with some of my possible plans for moving forward, but I am not certain that those are necessary or, more importantly, allowed.

Knowing this, I see my primary boundaries (and solutions to them) as:

1) I have a goal and a starting point, but no real hints about a transformation function to arrive there. I need to choose what path I'll walk along.

2) The existing program may be useful later, but for now, it must be disregarded. I'll see what I can salvage once I know how I want to do this. Note: this is easy, because the existing program is only a few hundred lines of C/C++ in a single file.

3) This just makes me a little less sure of myself.

4) I do not know enough about the limitations on the assignment to make good assessments for technology to use or to not use. It is unspecified in the design document which technology I cannot use. So, I'll just assume it's allowed unless we're told it's not. Within reason.

What next?

I need to choose a path, and that would be easiest to do if I just start working along a hypothetical path. I've been bogging myself down in the different possibilities at the start and not wanting to commit - well, I'll just start thinking my way through the beginning (and then the rest) in as high level a manner as I can. This is a problem well suited to a top-down design, and I know (from up above) that I don't have to keep much of my existing work.

So the next step is: draft out some plans.

Depending on the sort of work I'm doing, I like to make plans a variety of ways. I tend to work well by expressing things verbally, which means I like to talk through them. This is why I'm writing this blog post.

Next up, I want to do some more specific planning. Like code planning. But rather than pop open vim (where I'm fast when I know what I'm doing, and slow when I don't), or MSVC++ (where I'm constantly trying to think of how to do things better), I'll work on paper, with a pen. This will make diagramming (should I want to do it) faster, and help to free me from thinking about technical details for the moment. Right now I don't want technical details; I want high level organization, overall understanding, and to work through some math. Paper is the perfect technology for this.

But what I really have to do right now, is mark some students in a class I'm TAing, for the next three and a half hours. It'll be hard to work during, but hey, it's a living. :)

Monday, January 25, 2010

School's on

Entering week 3 of Semester 6, all looks well. The lineup for this semester:

CIS 4800: Graphics
CIS 4650: Compilers
CIS 3120: Digital Systems
PHIL 2100: Critical Thinking
PHIL 2370: Introduction to Metaphysics

The rundown for each of them:

Graphics

OpenGL and its associated helper libraries - pushing and popping matrices and gluing together random bits of code to make a game called Qix(beware the audio!), which is rather fun to play.

Compilers

Constructing a compiler to translate a Pascal-ish language (termed Pish) into MIPS Assembly. We're starting with DFAs and simplistic ideas of scanning, then walking forward through parsing, generating meaningful symbol tables, abstract syntax trees, intermediate code, register allocation, and machine code generation. It should be an awesome project to get through.

Digital Systems

Starting with CMOS networks of transistors to build basic gates and then gluing gates together to make a half-adder, then a simple 8 bit ALU, then a CPU with a data and control path. We'll be seeing the theoretical and practical side of digital design - touching on minimization of boolean expressions, hazard detection and reduction, designing for cost/speed/safety, and some neat things at the end about FPGAs and such.

Critical Thinking

A lot of hullabaloo about arguments. This is a course about using, identifying, and thinking about people's arguments in day to day life and an academic context. It's really the english half of symbolic logic (conversely the math half), which I took over a year ago. I'd better do pretty damn well in it.

Intro to Metaphysics

We read a bunch of old stuff and discuss it with the prof, basically. Good reading, good discussion, all about foundational and arguably (oh so arguable!) useless topics like identity, time, the structure of universe, and the nature of reality. Some smart people in there.

Also going to put my name in the hat for B. Comp Senator again, and.. yeah. Good semester, I think. (And hope.) (And a democamp this week! I will try to go!)

Saturday, December 26, 2009

So, generic programming

This is a good read.

It's an interview with Alexander Stepanov, and contains gems like:
"I find OOP technically unsound. It attempts to decompose the world in terms of interfaces that vary on a single type. To deal with the real problems you need multisorted algebras - families of interfaces that span multiple types. I find OOP philosophically unsound. It claims that everything is an object. Even if it is true it is not very interesting - saying that everything is an object is saying nothing at all. I find OOP methodologically wrong. It starts with classes. It is as if mathematicians would start with axioms. You do not start with axioms - you start with proofs. Only when you have found a bunch of related proofs, can you come up with axioms. You end with axioms. The same thing is true in programming: you have to start with interesting algorithms. Only when you understand them well, can you come up with an interface that will let them work."
and
"You can't write a generic max() in Java that takes two arguments of some type and has a return value of that same type. Inheritance and interfaces don't help. And if they cannot implement max or swap or linear search, what chances do they have to implement really complex stuff? These are my litmus tests: if a language allows me to implement max and swap and linear search generically - then it has some potential."
Good stuff; making me think.

Thursday, December 24, 2009

Customizing the blog a bit

This layout has always been rather insistent that I have a very thin middle column in which to place my posts. It's bugged me for a long time, but I decided that messing with the CSS template was outside of my competence level and just asking for trouble.

At the same time, I've always wanted to be able to place code into the blog without it looking like some awful monster crapped out unformatted text.

Well this morning I've fixed these issues.

The latter was as easy as googling "showing code in blogspot" and then following the instructions at the top link.

Essentially, you go to the Layout section of your dashboard, click "edit HTML", find a tag "]]></b:skin>", and insert some CSS in the section above it. It adds the necessary stuff to make pre and code tags to work wonderfully.

Then it recommends running code through a converter to quickly change it to escaped-text before posting it.

I feel like (and am, really) a script kiddie but hey, I've got code showing up in my blog like so:
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[])
{
int a, b, c;
int *d = NULL;

a = 5;
b = 6;
c = 7;
d = malloc(sizeof(int));
d[1] = 8;

if(argc == 2)
{
printf("What a lame example!\n");
}

free(d);
return 0;
}
which is wonderful.

Then I got to thinking "Hey, I'm a cocky CSS editing fiend, why not solve the problem of the blog's lacking width?" And I looked over the code in the layout section.

I found in there (this is likely specific to this template)
#header-wrapper {
width:660px;
margin:0 auto 10px;
border:1px solid $bordercolor;
}
#main-wrapper {
width: 410px;
float: $startSide;
word-wrap: break-word; /* fix for long text breaking sidebar float in IE */
overflow: hidden; /* fix for long non-text content breaking IE sidebar float */
}
and
#footer {
width:660px;
clear:both;
margin:0 auto;
padding-top:15px;
line-height: 1.6em;
text-transform:uppercase;
letter-spacing:.1em;
text-align: center;
}
These all have 'width' attributes that look like they're big enough to be most of the screen, and they're the only similar ones in the file. 660 pixels isn't very wide - I imagine it was set at that to work on an 800x600 screen, should one need to see my page.

Well you know what? I'm officially leaving those people in the dust.

Following some common design advice of 960 pixelwidth pages (see 960.gs), I decided to directly increase 660 to 960, and 410 (correspondingly) to 710. This widened the main post section of my blog considerably, and seems to have had no negative consequences.

Hooray for a productive blogging morning.

Python Fun

Every programmer, when learning something new, hits on that devilish quandary:

"What should I program?"

And I am a man like all others, who twiddles my thumbs and wonders "ah... if only I had something to /do/ with this language, I would really start to learn it!"

Well, I've decided to just dink around uselessly and see what comes of it. Then share.

The things we'll cover:
  • Some stupid string stuff
  • some more stupid string stuff, with numbers involved
  • then some regular old math

stupid string stuff:

First I started off playing with the string and list functions, and interchanging between them. Throughout this, I might duplicate existing functionality -- if I do, comment and tell me how to do it better! I'd love to learn.

I decied that I wanted to take a string, say "Hey man, what's up?" and insert stuff between each letter. I couldn't really find a quick way to do this, but some related things popped up.
a = "Hey man, what's up?"
a.split()
will give you ['Hey', 'man', 'what\'s', 'up?'] - and that's nice, but I want things broken down to the letter. So I wrote a function breakout:
def breakout(input):
r = []
for i in input:
r.append(i)

return r
breakout("hello") returns ['h','e','l','l','o']

then you can do a str.join() - let's wrap it into a function!
def splitByChar(instring, splitchar):
return splitchar.join(breakout(instring)
you can, through this, call splitByChar("hello", '.') and receive 'h.e.l.l.o'

ah, stupid pointless string stuff.

more stupid string stuff, with some math

Next up, I decided to play with phone numbers. I decided to break them up into their constituent digits and add them. This was (as many things in python are), an easy task.
def summit(input):
sum = 0
for i in input:
if i.isdigit():
sum += int(i)

return sum
This function runs quickly through the string and adds to the sum for every integer found.

I put in my phone number, print(summit("519-703-3336")), and received 42. Exciting!

Then I got to wondering.... I wonder how many phone numbers out there sum to 42? I wonder what the distribution is like across the rang of sums from 0 to 90? Let's write some code to find out:
def smattering(input):
arr = []
for i in range(0,9*input):
arr.append(0)

temp = []
for i in range(0,input):
temp.append('9')

upper = int(''.join(temp))
upperStr = str(upper)
for i in range(0, upper):
arr[summit(str(i))] += 1
if i % 1000000 == 0:
print(str(i) + ", " + str(upper - i) + ", " + str(i/upper))

return arr
This code makes a 90-element list, then brute-force walks from 0 to 9,999,999,999 and calculates every single sum, stopping every million steps to print out how far we are in, how far we have left, and a percentage through the path we've walked. I did some simple calculations, every printout occurs about 9 seconds apart, and 9,999 of them are required to take the calculation to completion.

This translates to about 24.9 hours. That's a pretty long calculation -- and it's kind of required; summing each of 10 digits for each of 10 billion numbers is 100 billion operations no matter what way you cut it. I've left the calculation running in a terminal (two, actually - one which will conclude and print the values to the screen and to a text file, and another in an interactive terminal in case I come up with fun things I want to do to the list off the bat) - but I'm beginning to think

some regular old math

is in order to find out the answer to this question a bit faster. The clock is ticking, and I have a day to find out. I'll update once I've thought about it a bit.