May 31, 2007

i'm learning java..

Everyone who reads this for my fitness or ramblings or whatever, please indulge me for a second while I do this..

any java programmers out there?

The assignment, from Thinking in Java by Bruce Eckel:
A vampire number has an even number of digits and is formed by multiplying a pair of numbers containing half the number of digits as the results. The digits are taken from the original number in any order. Pairs of trailing zeros are not allowed. Examples include:
Write a program that finds all the 4-digit vampire numbers."

so I wrote this from scratch. It works, and produces the correct result, but I'm sure there is a more elegant way of doing it- especially with getArrayOfDigits(). I don't know if there are any java developers who read my blog, but if there are, a little criticism would be appreciated.

import static net.mindview.util.Print.*;
// the print() method is identical to System.out.println().

public class Exercise10 {

public static void main(String[] args) {

for (int i=1000; i<10000;i++ )
if(i%100==0) continue; //weed out the numbers with two trailing zeros
int[] result = isVampire(i);
if(result != null) {
print(result[0] + "*" + result[1] + "=" + i + ". It's a vampire number");

private static int[] getArrayOfDigits(int i) {
//I am sure this can be done better
int[] a = {0,0,0,0};

a[0] = ((int)i/1000);
a[1] = ((int)i/100);
a[2] = ((int)i/10);

return a;


private static int[] isVampire(int i) {

int[] arr = getArrayOfDigits(i);

for(int a=0; a<=3;a++) {

for (int b=0;b<=3 ;b++ ) {
if(a==b) continue;

for (int c=0;c<=3 ;c++ ) {
if(a==c) continue;
if(b==c) continue;

for (int d=0;d<=3 ;d++ ) {
if(a==d) continue;
if(b==d) continue;
if(c==d) continue; //this series of continues can probably be done better, too.

if(GetTestNumber(arr[a],arr[b]) * GetTestNumber(arr[c],arr[d]) == i) {
int[] done={GetTestNumber(arr[a],arr[b]), GetTestNumber(arr[c],arr[d])};
return done;

return null;


private static int GetTestNumber(int a, int b) {
return ((a*10)+b);