© Ron Dai 2019
R. DaiLearn Java with Mathhttps://doi.org/10.1007/978-1-4842-5209-3_21

21. Counting

Ron Dai1 
(1)
Seattle, WA, USA
 

We have learned many mathematical methods to solve counting problems. Some of these problems require a deep understanding of permutation and combination. In this chapter, we will learn examples of how to use programming to solve counting problems.

Example

Tickets on a bus were $4.00 and $6.00. A total of 45 tickets were sold and $230 was earned. How many $4.00 tickets were sold? (2007/MathIsCool problem at http://academicsarecool.com)

Answer

This can be solved by a single loop. We set the variable tickets as the number of $4.00 tickets. Because the total number of tickets is 45, the number of $4.00 tickets cannot be greater than 45. Therefore, tickets is an integer under 46.
private static void calculateBusTickets() {
       for(int tickets = 0; tickets < 46; tickets++) {
              int totalMoney = 4 * tickets + 6 * (45 - tickets);
              if (totalMoney == 230) {
                     System.out.println(tickets + " $4.00 tickets were sold.");
                     break;
              }
       }
}

Example

A chair has 4 legs, a stool has 3 legs, and a table has 1 leg. At a birthday party, there are 4 chairs per table and a total of 18 pieces of furniture. One of the children counts 60 legs total. How many stools are there? (2016/MathIsCool problem at http://academicsarecool.com)

Answer

In the following method, the variable tables represents number of tables. Then, the number of chairs is 4 × tables, and the number of stools is (18 – tables – 4 * tables).
private static void countFurniture() {
       for(int tables = 0; tables < 19; tables++) {
              if (tables + 4 * 4 * tables + 3 * (18 - tables - 4 * tables) == 60) {
                     System.out.println((18 - tables) + " stools.");
                     break;
              }
       }
}

Example

A multiple-choice examination consists of 20 questions. The scoring is +5 for each correct answer, -2 for each incorrect answer, and 0 for each unanswered question. John’s score on the examination is 48. What is the maximum number of questions he could have answered correctly? (1987/AMC8 problem at https://artofproblemsolving.com/wiki/index.php/1987_AJHSME)

Answer

Unlike the previous two examples, in this one we will use two variables, c and w, in the loop. Let’s assume the number of correct answers is c, and the number of wrong answers is w. Their sum cannot be greater than 20 – the total number of problems. Because it may have more than one solution, we don’t use break to exit the program right after it finds the first solution. This is a different approach from in the previous examples.
private static void scoring() {
       for(int c = 0; c < 20; c++) {
              for(int w = 0; w < 20 - c; w++) {
                     if (5 * c - 2 * w == 48) {
                            System.out.println("Correct answers: " + c
                                          + "; wrong answers: " + w);
                     }
              }
       }
}
The output is:
       Correct answers: 10; wrong answers: 1
       Correct answers: 12; wrong answers: 6

Example

How many distinct four-digit numbers are divisible by 3 and have 23 as their last two digits? (2003/10B AMC problem at https://artofproblemsolving.com/wiki/index.php/2003_AMC_8)

Answer

We need to pay attention to the wording, “distinct four-digit numbers,” in this problem. The strategy is to separate all conditions into two parts.
  • The 4-digit number is divisible by 3 and its last two digits are “23”.

  • All the four digits are different.

private static void countNumbers() {
       int totalCount = 0;
       for(int i = 1000; i < 10000; i++) {
              if (i % 3 == 0 && i % 100 == 23) {
                     int firstDigit = i / 1000;
                     int secondDigit = i / 100 % 10;
                     if (firstDigit != secondDigit &&
                            firstDigit != 2 &&
                            firstDigit != 3 &&
                            secondDigit != 2 &&
                            secondDigit != 3) {
                            totalCount++;
                            System.out.println(i);
                     }
              }
       }
       System.out.println("Total count = " + totalCount);
}
Its output is:
1023
1623
1923
4023
4623
4923
5823
6123
6423
6723
7023
7623
7923
8523
9123
9423
9723
Total count = 17

We use one if clause to validate that all four digits are distinct.

../images/485723_1_En_21_Chapter/485723_1_En_21_Figa_HTML.jpg
Alternatively, we may create a general method to check it.
       if (isDistinct(firstDigit, secondDigit, 2, 3)) {
              ......
       }
This is the implementation of isDistinct(...) .
       private static boolean isDistinct(int a, int b, int c, int d) {
              if (a == b) {
                     return false;
              } else if (a == c) {
                     return false;
              } else if (a == d) {
                     return false;
              } else if (b == c) {
                     return false;
              } else if (b == d) {
                     return false;
              } else if (c == d) {
                     return false;
              } else {
                     return true;
              }
       }
An improved version in countNumbers2() will be:
private static void countNumbers2() {
       int totalCount = 0;
       for(int i = 1000; i < 10000; i++) {
              if (i % 3 == 0 && i % 100 == 23) {
                     int firstDigit = i / 1000;
                     int secondDigit = i / 100 % 10;
                     if (isDistinct(firstDigit, secondDigit, 2, 3)) {
                            totalCount++;
                            System.out.println(i);
                     }
              }
       }
       System.out.println("Total count = " + totalCount);
}

Example

Ruthie has 10 coins, all either nickels, dimes, or quarters. She has N nickels, D dimes, and Q quarters, where N, D, and Q are all different, and are each at least 1. Amazingly, she would have the same amount of money if she had Q nickels, N dimes, and D quarters. How many cents does Ruthie have? (2012 MathIsCool problem at http://academicsarecool.com)

Answer

Two for-loops are to be used in the following solution.
private static void countCoins() {
       for(int n = 1; n < 9; n++) {
              for(int d = 1; d < 10 - n; d++) {
                     int q = 10 - n - d;
                     if (5*n + 10*d + 25*q == 5*q + 10*n + 25*d){
                            System.out.println((5*n+10*d+25*q)+" cents.");
                            System.out.println("N="+n+"; D="+d+"; Q="+q);
                     }
              }
       }
}
Output is:
155 cents.
N=1; D=5; Q=4

Example

Three friends have a total of six identical pencils, and each one has at least one pencil. In how many ways can this happen? (2004 AMC8 problem at https://artofproblemsolving.com/wiki/index.php/2004_AMC_8)

Answer

We use two for-loops to simulate how we distribute the six identical pencils to three people represented by variables, first, second, third.
private static void countWays() {
       int count = 0;
       for(int first=0; first <= 6; first++) {
              for(int second = 0; second <= 6 - first; second++) {
                     int third = 6 - first - second;
                     if (first > 0 && second > 0 && third > 0) {
                            count++;
                                   System.out.println("first=" + first + "; second=" + second + "; third=" + third);                     }
              }
       }
       System.out.println("Total count=" + count);
}
The output is:
first=1; second=1; third=4
first=1; second=2; third=3
first=1; second=3; third=2
first=1; second=4; third=1
first=2; second=1; third=3
first=2; second=2; third=2
first=2; second=3; third=1
first=3; second=1; third=2
first=3; second=2; third=1
first=4; second=1; third=1
Total count=10

Example

Seven distinct pieces of candy are to be distributed among three bags. The red bag and the blue bag must each receive at least one piece of candy; the white bag may remain empty. How many arrangements are possible? (2010/10B AMC problem at https://artofproblemsolving.com/wiki/index.php/2010_AMC_10B)

Answer

First, we design an experiment. In this experiment, we want to put seven distinct strings (“A, ” “B, ” “C, ” “D, ” “E, ” “F, ” “G”) into three String arrays. The seven strings represent seven distinct pieces of candy. The three arrays represent red, blue, and white bags. The order of the placement doesn’t matter, but we need to make sure only the last array can be empty after the placement is made. The goal is to find the number of different placements.

When we place “A” in one of the three arrays, we need a for-loop for three different arrays. Then we need another for-loop to place “B,” and so on; in total we will need seven for-loops. In each for-loop, we append the string to the existing array, that is, bag[i]. But after it is done, we need to remove it from the tail of the array string in order for it to try the next option. This is why we use bag[i].replace("A", ""). The same applies to the other six strings.

We come up with a “straightforward” but ugly-looking version as what follows.

Note

BAG – red: 0, blue: 1, white: 2; 3 in the loops represent the three string arrays, that is, the three bags.

/// BAG - red: 0, blue: 1, white: 2
private static void distributeCandy() {
    int count = 0;
    String[] bag = { "", "", "" };
    for(int i=0; i < 3; i++) {
        bag[i] += "A";
        for(int j=0; j < 3; j++) {
            bag[j] += "B";
            for(int k=0; k < 3; k++) {
                bag[k] += "C";
                for(int l=0; l < 3; l++) {
                    bag[l] += "D";
        for(int m=0; m < 3; m++) {
            bag[m] += "E";
            for(int n=0; n < 3; n++) {
                bag[n] += "F";
                for(int p=0; p < 3; p++) {
                    bag[p] += "G";
                    if(bag[0].length() > 0 && bag[1].length() > 0) {
                                  count++;
                        System.out.println("Red=" + bag[0] + " Blue=" + bag[1] + " White=" + bag[2]);
                    }
                    bag[p] = bag[p].replace("G", "");    }
             bag[n] = bag[n].replace("F", "");   }
        bag[m] = bag[m].replace("E", "");    }
                bag[l] = bag[l].replace("D", "");    }
            bag[k] = bag[k].replace("C", "");    }
        bag[j] = bag[j].replace("B", "");   }
    bag[i] = bag[i].replace("A", "");    }
    System.out.println("Total count: " + count);
}
The code structure looks too complicated. There are too many nested for-loops . A better idea is to apply a recursive approach to improve its simplicity. Now see a new version:
private static int count = 0;
private static String[] bag = { "", "", "" };
private static String[] CANDY = new String[] { "A", "B", "C", "D", "E", "F", "G" };
private static String RemoveLastChar(String s) {
       if (s == null && s.length() < 1) {
              System.out.println("Input string is invalid!");
              return "";
       }
       return s.substring(0, s.length() - 1);
}
private static void distributeCandies_Recursive(int pointer) {
       for(int i=0; i < 3; i++) {
              bag[i] += CANDY[pointer];
              if (pointer == CANDY.length - 1) {
                     if (bag[0].length() > 0 && bag[1].length() > 0) {
                            count++;
                            System.out.println("Red=" + bag[0] + " Blue=" + bag[1] + " White=" + bag[2]);
                     }
              }
              else {
                     distributeCandies_Recursive((pointer + 1));
              }
              bag[i] = RemoveLastChar(bag[i]);
       }
}
We then include two following lines in the main function for execution.
distributeCandies_Recursive(0);
System.out.println("Total count: " + count);

Example

A palindrome between 1000 and 10000 is chosen at random. What is the probability that it is divisible by 7? (2010/10B AMC problem at https://artofproblemsolving.com/wiki/index.php/2010_AMC_10B)

Answer

A palindrome number is a number that reads the same from its left to right as from its right to left.

In the isPalindrome() method , we reverse the number string and compare it with the original number string. If the reversed string turns out to be the same as the original one, it is identified as a palindrome string. For “8558.” its reversed string “8558” is the same as itself.

We introduce StringBuffer class to leverage its reverse() method . Every number within the range [1000, 10000] is converted to a string type, before it is passed to the isPalindrome() method . The solution can be applied to any range of integer numbers.
public static void main(String[] args) {
       countDivisibility();
}
private static boolean isPalindrome(String numberStr) {
       String reversed = new StringBuffer(numberStr).reverse().toString();
       return reversed.equals(numberStr);
}
private static void countDivisibility() {
       int count = 0;
       int total = 0;
       for(int i = 1000; i < 10001; i++) {
              if(isPalindrome(Integer.toString(i))) {
                     total++;
                     if (i % 7 == 0) {
                            count++;
                            System.out.println(i);
                     }
              }
       }
       System.out.println("Probability=" + count + "/" + total);
}
There is a different way in the method isPalindrome2() , which contains the same functionality as what the isPalindrome() method has. Instead of using StringBuffer, you may simply compare each character from the leading half of one with the trailing half of the original string.
private static boolean isPalindrome2(String s) {
       int len = s.length();
       for( int i = 0; i < len / 2; i++ ) {
                     if (s.charAt(i) != s.charAt(len - i - 1)) {
                                    return false;
                     }
       }
       return true;
}

Example

A base-10 three-digit number n is selected at random. What is the probability that the base-9 representation and the base-11 representation of n are both three-digit numbers? (2003/10A AMC problem at https://artofproblemsolving.com/wiki/index.php/2003_AMC_10A_Problems)

Answer

The total count of base-10 three-digit numbers is 900. A three-digit number 124 in base-10 is 147 in base-9, and 103 in base-11; 720 in base-10, 880 in base-9, and 5A5 in base-11.

The crucial method is countBase10Numbers() :
private static void countBase10Numbers() {
       int count = 0;
       for(int i = 100; i < 1000; i++) {
              String base9Number = convertToBaseN(i, 9);
              String base11Number = convertToBaseN(i, 11);
              if (base9Number.length() == 3 &&
                     base11Number.length() == 3) {
                     count++;
                     System.out.println(i + " -> " + base9Number +
                                   "; " + base11Number);
              }
       }
       System.out.println(count + " out of " + (1000 - 100));
}
The supporting method is convertToBaseN() .
private static String convertToBaseN(int base10, int n) {
       if(n < 2 || n > 16) {
              return "";
       }
       String baseN = myOneDigit[base10 % n];
       base10 = base10 / n;
       while(base10 > 0) {
              baseN = myOneDigit[base10 % n] + baseN;
              base10 = base10 / n;
       }
       return baseN;
}
The myOneDigit array is:
private static String[] myOneDigit =
{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
It is actually equivalent to a method with implementation of the switch conditional statement:
private static String convertDigit(int digit) {
       String s = "";
       switch(digit) {
              case 10:
                     s = "A";
                     break;
              case 11:
                     s = "B";
                     break;
              case 12:
                     s = "C";
                     break;
              case 13:
                     s = "D";
                     break;
              case 14:
                     s = "E";
                     break;
              case 15:
                     s = "F";
                     break;
              default:
                     s = Integer.toString(digit);
                     break;
       }
       return s;
}

Obviously, the approach using a string array is simpler.

Problems

  1. 1.

    Richa and Yashvi are going to Jamaica with their school. They plan on attending a fair where the admission for children is $1.50 and $4.00 for adults. On a specific day, 2,200 people enter the fair and $5,050 is collected. How many children attended? (2017 MathIsCool)

     
  2. 2.

    In a mathematics contest with 10 problems, a student gains 5 points for a correct answer and loses 2 points for an incorrect answer. If Olivia answered every problem and her score was 29, how many correct answers did she have? (2002 AMC8)

     
  3. 3.

    How many positive integers not exceeding 2001 are multiples of 3 or 4 but not 5? (2001 AMC10)

     
  4. 4.

    How many positive three-digit numbers contain exactly two distinct digits (e.g., 343 or 772, but not 589 or 111)? (2006 MathIsCool)

     
  5. 5.

    Rebecca goes to the store where she buys five plants. If the store sells three types of plants, how many different combinations of plants can she buy? (2005 MathIsCool)

     
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.25.32