Duncan's blog

October 5, 2014

Project Euler: problem 22 (PHP) – Names scores

Filed under: PHP,Project Euler — duncan @ 8:00 am

22I previously blogged about this Project Euler puzzle nearly 6 years ago, using ColdFusion.  This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.

Problem 22:

Using names.txt (right click and ‘Save Link/Target As…’), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 x 53 = 49714.

What is the total of all the name scores in the file?

Here’s the code I came up with:

//  read file contents into an array
$names = file_get_contents('p022_names.txt', 'r');

// sort it, stripping out any unwanted characters first
$names = preg_split("/[^a-z]/i", $names, -1, PREG_SPLIT_NO_EMPTY);


$total = 0;

foreach ($names as  $index=>$name) {
	$sum = 0;
	for ($i = 0; $i < strlen($name); $i++) {
		$sum += ord(substr($name, $i, 1)) - 64;
	$total += $sum * ($index+1);

echo $total;

So the names are all nice and simple, no non-alphabetic characters.  It’s a case of reading the file, using a regex to put each name into an array and sorting the array.  I then loop over the array, using ord() to get the ASCII value of each letter in the name, doing the same as before in ColdFusion, where I then subtract 64 from that, to get it in the 1-26 range.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog at WordPress.com.

%d bloggers like this: