Sunday, July 31, 2011

Program to Draw a Random Card

Problem: Write a program that displays the name of a card randomly chosen from a complete deck of 52 cards. You program should display the complete name of the card. (Roberts ch 6, problem 1).

What it looks like (2 sample runs):

How the code looks:
/*
/*File: DrawCard.java
 * This program simulates drawing a card from a standard deck. It uses an instance of acm.util's 
 * RandomGenerator class to create two new random integers: one helping to supply the value (2-10, Ace, Jack, Queen, 
 * King), and the other integer helps determine the suit (Spades, Clubs, Hearts, Diamonds). Each integer value maps
 * to a card value or suit.
 *  * */
import acm.program.*;
import acm.util.*;

public class DrawCard extends ConsoleProgram{

    public void run() {
   
    int d1 = rgen.nextInt(1,4);
    int d2 = rgen.nextInt(1,12);
   
        String suit = null; //Declare a variable of null value. 
        //Then use switch statement to set a value
        switch (d1) {
            case 1: suit = "Spades"; break;
            case 2: suit = "Clubs"; break;
            case 3: suit = "Hearts"; break;
            case 4: suit = "Diamonds"; break;  
        }
   
        String value = null;
        switch (d2) { 
            case 1: value = "Ace"; break;
            case 11: value = "Jack"; break;
            case 12: value = "Queen"; break;
            case 13: value = "King"; break;
            default: value = Integer.toString(d2); break; // Returns a numeric value in string form
                // if a non-face card gets drawn
        }
        
    println("The " + value + " of " + suit);
   
    }
    //Instance variable for our random generator macheeeeen
    private RandomGenerator rgen = RandomGenerator.getInstance();
}

What made this interesting:

Two interesting concepts you exercise here:

1) Compartmentalizing your program. Instead of just storing 52 potential card values and randomly picking one of them, you can build something neater. There are 4 suits of equal distribution and 13 numeric values, so we can generate two random numbers for the face and numeric numbers and map them to card values. This is better than simply storing 52 potential card values because...

2) The concept of using an instance of a class to do stuff. In this case is a class of objects available to me called RandomGenerator. An instance of the RandomGenerator class is not one random number itself. It is an object that you can create in your program and then call upon to return random numbers. (It will recognize the method getInt() method). So the individual random numbers are a layer of abstraction away from the class that we get from the ACM library.

Why is this important?

This was actually familiar to me based on my work at Twilio. Twiio's REST API lets you make calls, send SMS messages, and pull information about your Twilio account. You can make a request to the API by a raw HTTP request to Twiio. Or, you can be clever and use a wrapper library that creates a "REST client". This is actually a class of objects that know how to make HTTP requests to Twilio, so instead of piecing together a big URL every time you need to communicate to Twilio, you can send commands to your instance of the REST client and communicate via methods instead of a raw URL.

Examples:

A1) Making a phone call directly via a direct HTTP POST to Twilio's API:

POST https://api.twilio.com/2010-04-01/Accounts/account123/Calls/
Auth Headers: username account123, password token456


POST parameters:
* To: 503-111-2222
* From: 503-222-3333
* Url: http://mycoolapp.renee.com


A2) Sending an SMS:


POST https://api.twilio.com/2010-04-01/Accounts/account123/SMS/Messages
Auth Headers: username account123, password token456


POST parameters:
* To: 503-111-2222
* From: 503-222-3333
* Body: Hello World

VERSUS

B) Making a phone call, then sending an SMS message using an instance of the TwilioClient class (from Sean Sullivan's Java wrapper library):

/*import twilio.client.*;
TwilioClient c = new TwilioClient("account123", "token456");

c.call("503-111-2222", "503-222-3333");
c.sendSMSMessage("503-111-2222", "503-222-3333", "Hello world");

See, isn't that better? The advantage is don't have to put together the URL every time or worry about validating each request. You just create your object, which has the account SID and auth token baked in and can recognize the methods "call" and "sendSMSMessage." Instead of needing to be familiar with the Twilio API (which is actually very simple), you can just be familiar with methods in your language of choice that let you make calls or send SMS.

Sunday, July 10, 2011

Program to Print Perfect Numbers

Problem: Greek mathematicians took special interest in numbers that are equal to the sum of their proper divisors (a proper divisor of n is any divisor less than n itself). They called such numbers *perfect numbers*. For example, 6 is a perfect number because it is the sum of 1, 2 and 3, which are numbers less than 6 that divide equally into 6. Similarly, 28 is a perfect number because it is the sum of 1, 2, 4, 7, and 14.


Write a predicate method isPerfect(n) that returns *true* if the integer n is perfect, and *false* otherwise. Test your implementation by writing a main program that uses the isPerfect method to check for perfect numbers in the range 1 to 9999 by testing each number in turn. Whenever it identifies a perfect number, your program should display that number on your screen. Your program should find two other perfect numbers in that range as well. (Roberts ch 5, problem 12).


What it looks like:





/*
* File: printPerfects.java
* Name: Chu
* Section Leader: 
* This program prints the numbers between 1 and 9999 that are perfect numbers. Perfect numbers are those
* where the divisors (integers that divide evenly into it) all sum up to that number. It uses the private
* predicate method isPerfect.
* 
*/

 
package ch6_practice;
import acm.program.*;

public class printPerfects extends ConsoleProgram {
    public void run() {    
        for (int i = 1; i < 9999; i++) {
            if (isPerfect(i)) {
                println(i);
            }
        }
    }
    private boolean isPerfect (int n) {
        int sum = 0;
        for (int i = 1; i < n; i++) {
            if (n % i == 0) {
            sum += i; }
            }
            if (sum == n) {
                return true;
            }
        else return false;
        
    }
}

This was a simple little program that simply re-enforced the practice of breaking certain operations of a program into their own methods. The method "isPerfect" creates a new variable "sum", initialized at a value of zero. For any number that you're testing to see if it is perfect, you find all the divisors via brute force. Whenever you find a divisor, you add it to "sum." If, after finding all the divisors, the value of "sum" equals the number you're testing, then you know that the number is perfect.