Wednesday, March 28, 2007

Adding Lessons

Introduction

Imagine that you are a teacher, and need to come up with some adding lessons for your class. The students should add three numbers together between 1 and 9, because adding with 0 is too easy. The result should be less than 10, so that the students don't have to carry the one.

Program

public class Adding {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        int count = 0;
        
        for (int i = 1; i < 10; i++) {
            for (int j = 1; j < 10; j++) {
                for (int k = 1; k < 10; k++) {
                    int sum = i +  j + k;
                    if (sum <= 10 ) {
                        String s = i + " + " + j + " + " + k + " = " + sum;
                        list.add(s);
                        count++;
                    }
                }
            }
        }
        
        System.out.println(count);
        Collections.shuffle(list, new Random());
        
        for (String t : list ) {
            System.out.println(t);
        }
    }
}

Output

120
3 + 6 + 1 = 10
2 + 2 + 1 = 5
3 + 5 + 2 = 10
7 + 2 + 1 = 10
2 + 4 + 4 = 10
1 + 1 + 5 = 7
3 + 3 + 4 = 10
4 + 1 + 3 = 8
2 + 2 + 3 = 7
3 + 1 + 2 = 6
...

Discussion

The program first calculates all legal combinations. Each combination is then put into a list, then the combinations are shuffled, so that they are in random order, and finally printed.

The teacher could create three random numbers between 1 and 9

number1 = (int) (Math.random() * 9 + 1);
number2 = (int) (Math.random() * 9 + 1);
number3 = (int) (Math.random() * 9 + 1);

and then repeat the process until the sum is between 1 and 10, but the algorithm would be harder to understand, it would be a lot slower, and it would probably not create all combinations.

Conclusion

The idea of putting the combinations into a list, and then shuffle the list, results in a program that take up a little memory, but the resulting code is easy to understand and easy to modify.

No comments: