Category Archives: code

Merging Netflix Accounts with ColdFusion and JavaScript

I wrote a little script using ColdFusion and JavaScript to merge two NetFlix accounts. It’s ugly and cheesy, but it works so I thought I’d share.

Here’s how you do it:

  1. Register for a developer key.
  2. Grab the RSS feed url of the queue you want to merge FROM. This can be obtained by logging into the FROM account and clicking on the “RSS” link in the footer.
  3. Log in to the account that you’d like to merge TO.
  4. Hit this script in the same browser you logged into the TO account with, and make sure you allow pop-ups!
<!--- enter your feed here! --->
<cfset feed = "http://rss.netflix.com/QueueRSS?id=P4806480653914107620156446228102116" />
<!--- enter your consumer key here! --->
<cfset key  = "your-consumer-key-here" />
<cfset href = "http://widgets.netflix.com/addToQueue.jsp?output=json&devKey=#key#&queue_type=disc&movie_id=http://api.netflix.com/catalog/movie/" />

<cffeed action="read" name="queue" source="#feed#" />

<cfset movies = queue.item />
<cfset idList = "" />

<cfloop array="#movies#" index="i">
	<cfset idList = ListAppend(idList,ListLast(i.guid.value,"/")) />
</cfloop>

<cfoutput>
	<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"/>
	<--- Pop up a new window, swap the href every second. Told ya it was cheesy! --->
	<script>
		var popUp = window.open('http://google.com');
		var idList = [#idList#];

		new PeriodicalExecuter(
			function(pe) {
				if (idList.length == 0) {
					pe.stop();
				} else {
					popUp.location.href = "#href#" + idList.pop();
				}
			},
			1
		);
	</script>

</cfoutput>

Note: I don’t know if this allowed by the EULA, or if there even is a EULA…so, use at your own risk!

Project Euler: Problem 26 in Ruby

I knew I’d be implementing my own division algorithm for this problem, but I had a hard time figuring out a good way to detect the repeating sequence.

That’s all I have to say about that.

Problem #26

Find the value of d 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.

def divide n, d, repo = []
  return repo.size - repo.index(n) if repo.include? n
  divide 10 * (n - (n / d) * d), d, repo << n
end

highest = {"d" => 1, "count" => 1}

(1..499).each do |i|
  x     = i * 2 + 1
  count = divide 1, x
  if count > highest['count']
    highest = {"d" => x, "count" => count}
  end
end

puts highest["d"]

Project Euler: Problem 28 in Ruby

I noticed a simple pattern of odd squares traveling up the rightmost corner of the spiral and after a little bit of toying around with the numbers I was able to come up with my solution. There are some truly beautiful and well explained solutions in the forums, but I’m pretty happy with mine, I could have been a nice guy and split it up, but I had a rough time coming up with appropriate variable names. This is what you get.

Problem #28

Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:

21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13

It can be verified that the sum of both diagonals is 101.

What is the sum of both diagonals in a 1001 by 1001 spiral formed in the same way?

def sum_corners n
  return 1 if n == 1
  4 * ((n * 2 - 1) ** 2 - (3 * n - 3)) + sum_corners(n - 1)
end

puts sum_corners((1001 + 1) / 2)

Project Euler: Problems 1 – 5 in JavaScript

I’ve been wanting to check out Rhino for a while, and I’ve been particularly interested in seeing how it compares to Ruby in terms of speed. The results have been a little varied, and it’s a deeply flawed comparison. But it’s something.

These scripts are just ports of my ruby solutions. There are a few places where I had to roll my own JavaScript functions instead of baked in Ruby methods, but other than that it was nearly line by line translation.

Problem 1Ruby solution

Add all the natural numbers below one thousand that are multiples of 3 or 5.

var total = 0;

for(var i = 0; i < 1000; i++) {
  if(i % 3 == 0 || i % 5 == 0) {
    total += i;
  }
}

print(total);

Problem 2Ruby solution

Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.

function fib(stack, n) {
  if(n == 0) {
    return 1;
  }
  if(n == 1) {
    return 2;
  }
  return stack[n - 1] + stack[n - 2];
}

var max   = 4000000;
var total = 0;
var stack = [];

for(var i = 0; i < max; i++) {
  stack[i] = fib(stack,i);
  if(stack[i] > max) {
    break;
  }
  if(stack[i] % 2 == 0) {
    total += stack[i]
  }
}

print(total);

Problem 3Ruby solution

Find the largest prime factor of a composite number.

function find_highest_prime_factor(n) {
  var max = Math.round(Math.sqrt(n));
  for(var i = max; i >= 2; i--) {
    if(n % i == 0 && find_highest_prime_factor(i) == 1) {
      return i;
    }
  }
  return 1;
}

var target = 600851475143;
print(find_highest_prime_factor(target));

Problem 4Ruby solution

Find the largest palindrome made from the product of two 3-digit numbers.

function get_highest_palindrome(high, low) {
  var highest = 0;
  for(var i = high; i >= low; i--) {
	for(var j = high; j >= low; j--) {
      sum = i * j;
      if(sum <= highest) {
        break;
	  }
      if(is_palindrome(sum.toString())) {
        highest = max(highest, sum);
	  }
    }
  }
  return highest;
}

function reverse(string) {
  var array = string.split('').reverse();
  var out   = '';
  for(key in array) {
	out += array[key];
  }
  return out;
}

function max(a,b) {
  if(a > b) {
	return a;
  }
  return b;
}

function is_palindrome(string) {
  return string == reverse(string);
}

print(get_highest_palindrome(999, 100));

Problem 5 - Ruby solution

What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?

function gcd(a,b) {
  var x = a;
  var y = b;
  var result;
  
  while (y != 0) {
	result = x % y;
    x      = y;
    y      = result;
  }
  return x;
}

function lcm(a,b) {
  return (a * b) / gcd(a, b);
}

var max = 20;
var min = 11;
var n   = min;

for(var i = min; i <= max; i++) {
  n = lcm(n,i);
}

print(n);

Project Euler: Problem 23 in Ruby

Looks like I took a pretty common approach on this one. First I calculated all the abundant numbers and dropped the sums in a hash. Then I just summed up to the given upper bound of 28,124 excluding those abundant sums.

Ruby1.9 solves it on my computer in about 15 seconds. After reading through the forums, some people were using a much lower upper limit of 20,200 which brought my run time down to a much respectable 6 seconds.

Problem #23

Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

def sum_proper_divisors n
  sum = 1
  (2..Math.sqrt(n)).each do |i|
    if n % i == 0
      result = n / i
      sum += result unless result == i
      sum += i
    end
  end
  sum
end

def next_abundant repo
  i = repo.last + 1
  while( sum_proper_divisors(i) <= i)
    i += 1
  end
  i
end

max   = 20_200
repo  = [12]
sums  = {24 => nil}
total = 0

while repo.last < max do
  repo << next_abundant(repo)
  repo.each do |i|
    sum = repo.last + i
    if sum > max
      break
    end
    sums.store sum, nil
  end
end

max.times do |i|
  total += i unless sums.include? i
end

puts total

Announcing GeoHashFlash!

Okay, so it’s hardly an announcement, but I’ve been working on a flex app for determining your daily official xkcd meetup location via the geohashing method described in comic 426.

Much love to:

I’m still learning Flex and this is my first adventure with Google Map, so it’s rough. And there’s still a lot of work to do, like, validation, error checking, or testing for example. But hey, first pass!

Here’s the code for the actual GeoHash class. I have “view source” disabled because it currently contains my API key, but you can download the key-less zip.

public class GeoHasher {

	private var date:Date;
	private var dow:Number;
	private var latitude:Number;
	private var longitude:Number;

	private var dateHash:String;
	private var dowHash:String;

	private var ready:Boolean;

	public function GeoHasher() {
		this.ready = false;
	}

	public function reset(
		date:Date,
		dow:Number,
		latitude:Number,
		longitude:Number
	):void {
		this.date      = date;
		this.dow       = dow;
		this.latitude  = latitude;
		this.longitude = longitude;

		this.ready     = true;

		setHashValues();
	}

	public function getDestination():Object {
		if(ready) {
			var hash:Object = getHashAsDecimal();
			return {
				latitude: toOrdinal(latitude, hash.date),
				longitude: toOrdinal(longitude, hash.dow)
			};	
		}
		return { latitude: "", longitude: "" };
	}

	// privates

	private function setHashValues():void {
		var formattedDate:String = Utilities.dateFormat(date,"-");
		var string:String = formattedDate + "-" + dow.toString();
		var hash:String   = MD5.encrypt(string); 

		dateHash = hash.slice(0,hash.length / 2);
		dowHash  = hash.slice(hash.length / 2,hash.length);
	}

	private function toOrdinal(pre:Number, post:Number):String {
		return (Math.floor(pre) + post).toString();
	}

	private function getHash():Object {
		return { date: dateHash, dow: dowHash };
	}

	private function getHashAsDecimal():Object {
		var hash:Object = getHash();
		return {
				date: Utilities.fractionalHexToDecimal(hash.date),
				dow: Utilities.fractionalHexToDecimal(hash.dow)
		};
	}
}

Converting Fractional Hex to Decimal in ActionScript

I’m working on a little Flex Geohashing application which required me to convert a fractional Hex value to decimal and the net was no help. It’s a trivial algorithm, but it’s not the kind of thing I want to spend my time writing. So, Here you go, future!

public function fractionalHexToDecimal(hex:String):Number {
	var total:Number = 0;
	for(var i:int = 0; i < hex.length; i++) {
		total += (parseInt("0x" + hex.charAt(i)) / Math.pow(16,i+1));
	}
	return total;
}

Only pass in the fractional. No "0x". No decimal point. Here's how it do.

fractionalHexToDecimal("1");
// 0.0625

fractionalHexToDecimal("0a");
// 0.0390625

fractionalHexToDecimal("db9318c2259923d0");
// 0.8577132677070023

Geohashing App forthcoming.

Flex Game of Life Pt 2

I made a few user interface updates to my crappy Flex version of Conway’s Game of Life.

The board now wraps, and I added a Timer with an adjustable delay via the lovely HSlider control. I wanted to replace the cells with Sprites but it’s giving me grief and I want to play The Sims.

I’m still making my mind up about Flex, but I have to admit that aside from the Sprite issue I’ve been pleasantly surprised at how easy everything’s been coming together.

You can view source on the application, or you can download the zip.

How to issue a simple HTTPRequest in Java

I needed a way to issue an HTTPRequest in Java, and I don’t care about the return value. I wasn’t able to find a simple example so I thought I’d post my that part of my solution. I don’t know that it’s the best way, but it works.

import java.net.URL;

public class Request {
  public static void main(String[] args) throws Exception {
      if(args.length == 0) {
          System.out.println("URL required.");
          return;
      }
      URL url = new URL(args[0]);
      url.openStream().close();
  }
}

And to use it you just pass in the url via the command line

java Request http://joezack.com

Flex Game of Life

Continuing down the Flex Path, I built another really crappy version of Conway’s Game of Life. Version 2 forthcoming.

I’m still figuring out this whole Flex thing, so please, any help would be much appreciated!

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
	xmlns:mx         = "http://www.adobe.com/2006/mxml"
	layout           = "vertical"
	creationComplete = "init(gameArea);"
	width            = "425"
	height           = "425"
>
	<mx:Script><![CDATA[
		import model.*;
		private var board:Board;

		private function init(application:DisplayObjectContainer):void {
			board = new Board(application, 10, 0, 0, 30, 30, 5);
		}
	]]></mx:Script>

	<mx:Canvas id="gameArea"></mx:Canvas>
	<mx:HBox>
		<mx:Button label="Reset"  click="board.reset();" />
		<mx:Button label="Update" click="board.update();" />		
	</mx:HBox>
</mx:Application>
package model {

	import flash.display.DisplayObjectContainer;

	public class Board {

		private var size:int;
		private var startX:int;
		private var startY:int;
		private var tileWidth:int;
		private var tileHeight:int;
		private var tileBuffer:int;	
		private var board:Array;
		private var container:DisplayObjectContainer;

		public function Board(
			container:DisplayObjectContainer,
			size:int,
			startX:int,
			startY:int,
			tileWidth:int,
			tileHeight:int,
			tileBuffer:int
		) {
			this.container  = container;
			this.size       = size;
			this.startX     = startX;
			this.startY     = startY;
			this.tileWidth  = tileWidth;
			this.tileHeight = tileHeight;
			this.tileBuffer = tileBuffer;
			reset();
		}

		public function reset():void {
			this.board = new Array(this.size);
			var x:int = startX;
			var y:int = startY;

			clear();

			for(var i:int = 0; i < this.size; i++) {
				this.board[i] = new Array(this.size);
				x = startX;
				for(var j:int = 0; j < this.size; j++) {
					board[i][j] = new Cell(x, y, tileWidth, tileHeight);
					x += this.tileWidth + this.tileBuffer;
					this.container.addChild(board[i][j]);
				}
				y += this.tileHeight + this.tileBuffer;
			}
		}

		public function update():void {
			var next:Array = next();
			for(var i:int = 0; i < this.size; i++) {
				for(var j:int = 0; j < this.size; j++) {
					board[i][j].update(next[i][j]);
				}
			}
		}

		public function clear():void {
			while(this.container.numChildren) {
				this.container.removeChildAt(0);
			}
		}

		public function next():Array {
			var total:int     = 0;
			var next:Array = new Array(this.size);
			for(var i:int = 0; i < this.size; i++) {
				next[i] = new Array(this.size);
				for(var j:int = 0; j < this.size; j++) {
					next[i][j] = board[i][j].next(countNeighbors(i,j));
				}
			}
			return next;
		}

		public function isValid(position:int):Boolean {
			return(position >= 0 && position < this.size);
		}

		public function stateAt(i:int, j:int):Boolean {
			if(isValid(i) && isValid(j)) {
				return board[i][j].state;
			}
			return false;
		}

		public function countNeighbors(x:int, y:int):int {
			var count:int = 0;
			
			for(var i:int = x - 1; i <= x + 1; i++) {
				for(var j:int = y - 1; j <= y + 1; j++) {
					if(!(i == x && j == y) && stateAt(i,j)) {
						count += 1;
					}
				}
			}
			return count;
		}

	}
}
package model {
	import flash.events.MouseEvent;
	
	import mx.controls.Button;

	public class Cell extends Button {

		public var state:Boolean;

		public function Cell(x:int, y:int, width:int, height:int) {
			this.x     = x;
			this.y     = y;
			this.width = width;
			this.height = height;
			this.addEventListener(MouseEvent.CLICK,swap);
			this.reset();
		}

		public function reset():void {
			this.state = false;
		}

		public function next(neighborCount:int):Boolean {
			return((this.state && neighborCount == 2) || neighborCount == 3);
		}

		public function update(state:Boolean):void {
			this.state = state;
			if(this.state) {
				this.label = "0";
			} else {
				this.label = "";
			}
		}

		public function swap(e:MouseEvent):void {
			update(!this.state);
		}

	}
}