Geek dad vs. Normal dad: A homework story

When I was in school, math homework was my nemesis. The seemingly endless (and at the time, seemingly pointless) repetition drove me crazy. As a kid, I wasn’t given much sense of the practical usefulness of any of the things I was being taught. I had much more important things to occupy my mind with, like Star Wars, Led Zeppelin, and astronomy.

I’m a dreamer. I am blessed with the type of personality that allows me to focus for long periods on things. If they interest me. Conversely, if something doesn’t interest me, to this day I still find it extremely hard to concentrate. I get especially irked if I sense that something is being done inefficiently or is unnecessarily repetitive. I mean, after all that’s why we invented computers, right?

Fast forward to 2009 and I’m helping my daughter with her math homework. She’s working on a sort of ‘math trick’ with number palindromes. That’s a number like 2447442 that reads the same forward and backward. One creates this via an iterative process. You reverse numbers and add them together. If you don’t have a palindrome you take the output of the previous operation and repeat until you get a palindrome. Or not.

Most of the first batch of problems went pretty well. My daughter was doing her work and I was checking the results with a calculator. Finally we came to the last couple of examples. Here’s where the problem started. It turned out we had misread one part of the instructions concerning how to handle decimals. Thus, we started out with a number that never became a palindrome. Sarah quickly gave up. Then my wife and I filled up a couple sheets of scratch paper with numbers that quickly spiraled into the Land of the Insanely Huge. I even went upstairs and banged out numbers on the calculator for twenty minutes. By this time, we were all miserable, so we agreed to take it up the next day.

So now I was irked (see above) and the wheels were turning. This wasn’t hard from a mathematical point of view. It just involved some juggling and a whole bunch of repetitive calculations. Perfect job for a script!

Any normal dad would’ve probably just re-read the instructions, fixed the calculation and called it good. Me? Geek dad? Nooooooo… I couldn’t leave it alone. I went upstairs and set to work on a command-line PHP script to expunge the drudgery from this thankless chore once and for all!

When it was done I had fun checking Sarah’s work, and discovered an earlier example she’d gotten wrong. For the record, we made sure our daughter understood the process and I only used the script to check her work, not give her the answers.

This is a total hack written late at night, so no flames please! Suggestions for improving it are welcome, however. I may create a web-ready version of this and stick it on the site if anybody’s interested in searching out new and amazing number palindromes. Aside from that, it’s now basically a solution to a nonexistent problem. And I can once again sleep at night.

#! /usr/bin/php

<?
	# The input number.

	$input = $argv[1];

	# Set up some variables
	$palindrome = 0;
	$limit = 10000; // how many iterations?
	$iterations = 0;

# ------------------------------------------------------------#
# Main 'while' loop
# ------------------------------------------------------------#

while($palindrome === 0 && $iterations <= $limit) {
	$iterations++;

	echo 'Testing: ' . $input . "\r\n";

	$result = testInput($input);

	if(is_numeric($result)) {
		echo "Palindrome found! : " . $result . "\r\n";
		break;
	} else {
		# next iteration, please.
		$input = genNewInput($input);
	}
} // end while

# ------------------------------------------------------------#
# Function: genNewInput
# ------------------------------------------------------------#
function genNewInput($input) {
	$fwd_array = str_split($input);
	$rev_array = array_reverse($fwd_array);

	# add reversed numbers together
	$fwd_num = implode($fwd_array);
	$rev_num = implode($rev_array);

	echo 'Adding: ' . $fwd_num  . ' + ' . $rev_num . "\r\n";

	$input = $fwd_num + $rev_num;
	return $input;
}

# ------------------------------------------------------------#
# Function: testInput
# ------------------------------------------------------------#
function testInput($input) {

	$fwd_array = str_split($input);
	$rev_array = array_reverse($fwd_array);

	# get the digit count
	$digit_count = count($fwd_array);

	$r = $digit_count - 1; // zero indexed

	# Determine if the output is a palindrome
	for($f=0;$f<$digit_count;$f++) {

		# inner loop. this takes the new input and tests it. If it passes, we've found our palindrome! If not, it continues the outer loop with the next input number.

		# compare the numbers.
		if($fwd_array[$f] === $fwd_array[$r]) {
			$r--;

			if($f === ($digit_count - 1)) {
				# BINGO!
				return $input;
			} else {
				continue;
			}

		} else {
			return false;
		}
	}
}

?>

[Note: I had originally posted more code here. I'm going to bring this back up as a separate page at a later date.]

  • Trackback are closed
  • Comments (6)
  1. Gawain,

    As I mentioned on FB, here’s a C# port of that script.

    Any gains in optimization, i.e. LOC, were completely lost when I realized that C# doesn’t have a native reverse method on a string objects. FAIL.

    Think I’ll try Python next. I enjoyed this little diversion. Thanks for letting me share in the geek-dom.

  2. PS: Sorry for the code formatting.

  3. Nice! The formatting (or lack thereof) isn’t your fault. I don’t think my fancy syntax highlighting plugin works in story comments.

    I think I’ll try posting it in the story instead. We’ll see if that works better… Since I’m starting to work with Python, I’ll be very interested to see that one. My guess is it’ll be shorter than either of the other two.

    By the way, I love the SarahPalindrome approach. “Wasilla’s all I saw.”

  4. I’ll spare your comment feed, but I did find this: http://norvig.com/pal1txt.html

    Thanks for moving it in! It isn’t fully tested. I’m skeptical about its applicability in the upper ranges of a double data type, when you get into E+13 range. I’m still fundamentally troubled with all the string casting going on, but I’ll assume your daughter’s homework did not come with a performance spec.

    I agree that Python should smoke C# in the code size department.

    BTW: Upon looking at it again, it appears that the comment section stripped out the xml tags in my comments. All ur input sanitation are belong to..um..you.

    • Jim
    • September 22nd, 2009

    Gawain & Zach – awesome geekness! Love the SarahPalindrome approach as well – never thought of that one. Zach – Linq extensions do provide a native Reverse for strings now, finally!

  5. “Message for you, sir!”

    Python goodness.

Comment are closed.