Thursday, 10 November 2011

Algorithm for sorting money into $20 & $50 notes for an ATM




Precondition:
Amnt is valid. That is: Amnt > $20; Amnt != $30; Amnt % $10 = 0
The following codes uses integer division so if any numbers are of type double convert to integers where necessary.

// Referring to the table:
//amnt; numOfFifties and numOfTwenties are integer variables
// also need remainder as integer variable.

// pseudocode for sorting into $20 & $50 

numOfFifties = amnt / 50;
remainder = amnt – numOfFifties * $50;
numOfTwenties = remainder / $20;

// The above code works but not for values such as 60, 80, 110, etc.
// Because of integer division it won't give us the values we want in the table.
// So we have to test for those values and add some more codes to make it work.
// The following codes work for all values. 

numOfFifties = amnt / $50;
remainder = amnt – (numOfFifties * $50);
    //Here is the test for these values
    if ( (remainder % $20) != 0 ) {
         numOfFifties = numOfFifties – 1; // Change back to the previous $50 counter
         remainder = amnt – (numOfFifties * $50);
         numOfTwenties = remainder / $20;
    } else { // This is where it isn't those values that sit on the border
         numOfFifties = amnt / $50
         remainder = amnt – (numOfFifties * $50);
         numOfTwenties = remainder / $20;
        } // end else
} // end if

No comments:

Post a Comment