Skip to content

Introduction: First Project - algs4 Library

Whilst the assignment is optional it was a good way to reiterate some basic concepts that are unique to Java which might not be standard syntax in other languages. In particular implicit and explicit casting.

Simple Hello World to get started.

public class HelloWorld {
  public static void main(String[] args) {
      System.out.println("Hello World");
  }
}

Write a program HelloGoodbye.java that takes two names as command-line arguments and prints hello and goodbye messages as shown below (with the names for the hello message in the same order as the command-line arguments and with the names for the goodbye message in reverse order).

public class HelloGoodbye {
  public static void main(String[] args) {
    System.out.print("Hello " );
    if ( args.length == 0 ) {
      System.out.print("Anon");
    }
    else if ( args.length == 1) {
      System.out.print(args[0]);
    }
    else if ( args.length > 1 && args.length <= 2) {
      System.out.print(args[0] + " and " + args[1]);
    } else {
      for(int i = 0; i < args.length; i++){
        if(i == args.length - 1){
          System.out.print("and, " + args[i]);
        }
        else
        {
          System.out.print(args[i]+ ", ");
        }
      }
    }
    System.out.print("\nGoodbye " );
    if ( args.length == 0 ) {
      System.out.print("Anon");
    }
    else if ( args.length == 1) {
      System.out.print(args[0]);
    }
    else if ( args.length > 1 && args.length <= 2) {
      System.out.print(args[1] + " and " + args[0]);
    }
    else
    {
      for(int i = args.length - 1; i > 0; i--){
        if(i == 1){
          System.out.print("and, " + args[i]);
        }
        else
        {
          System.out.print(args[i]+ ", ");
        }
      }
    }
  }
}
  • The code is written to further expand on the projects requirements by taking into account a user asking to greet multiple people.
  • It allows for multiple names/words as parameters to the main function and returns a greeting/goodbye accordingly.
  • The program:
    • Reverts to Anonymous if the user does not enter a name.
    • Checks the length of arguments and provides a grammatical structure:
      • One Name = “John”
      • Two Names = “John and Jill”
      • Three Names or More = “John, Jill, and, Jack”
    • As per the instructions the same methods are applied to reverse the names when saying Goodbye.

I couldn’t use loops to pass the project so I ended up refactoring to just return a message that stated only two names allowed if more then two arguments.

public class HelloGoodbye {
  public static void main(String[] args) {
      if (args.length == 0 ) {
        System.out.print("Hello Anon");
      }
      else if (args.length == 1) {
        System.out.print(args[0]);
      }
      else if (args.length > 1 && args.length <= 2) {
        System.out.print("Hello " + args[0] + " and " + args[1]);
      } else {
        System.out.print("I can only greet two people :(");
      }
      if (args.length == 0 ) {
        System.out.print("\n Goodbye Anon");
      }
      else if (args.length == 1) {
        System.out.print(args[0]);
      }
      else if (args.length > 1 && args.length <= 2) {
        System.out.print("\nGoodbye " + args[1] + " and " + args[0]);
      } else {
        System.out.print("\nSorry!");
      }
    }
}

Project Requirements:

Using algs4.jar. Write a program RandomWord.java that reads a sequence of words from standard input and prints one of those words uniformly at random. Do not store the words in an array or list. Instead, use Knuth’s method: when reading the ith word, select it with probability 1/i to be the champion, replacing the previous champion. After reading all of the words, print the surviving champion.

Use the following library functions from algs4.jar:

  • StdIn.readString(): reads and returns the next string from standard input.
  • StdIn.isEmpty(): returns true if there are no more strings available on standard input, and false otherwise.
  • StdOut.println(): prints a string and terminating newline to standard output. It’s also fine to use System.out.println() instead.
  • StdRandom.bernoulli(p): returns true with probability p and false with probability 1−p
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
public class App {
  public static void main(String[] args) throws Exception {
    String champion = "";
    int i = 1;
    StdOut.println("Enter Your Champions seperated by a space or new line once complete press Ctrl + C to run the program");
    while (!StdIn.isEmpty()){
      String word = StdIn.readString();
      if(StdRandom.bernoulli(1.0 / i)) {
        champion = word;
      }
      i++;
    }
    StdOut.println("The winning Champion:");
    StdOut.println(champion);
  }
}
  • Import the StdIn, StdOut and StdRandom methods provided through the algs4 library.
  • Set an empty string denoting the current champion being evaluated and a counter to iterate for each champion in our pool.
  • Ask the user to input data, in this case the names of our champions followed by a “break” to let the program know we have finished our input.
  • The program will then register that there is no input left to process and wills tart reading each word in our input and evaluating a probability of return based on the number of words it has evaluated.
  • Finally a random champion is chosen and displayed as a winning champion.

Things we failed and need to refactor (Lessons learnt)

  1. Verbose String Output - We were missing trailing . on our HelloGoodbye or a comma , on our HelloWolrd
  2. Refactoring our Random Word app to align to the set requirements. We need to remove our PrintLn messages and align to a single line input and output model.

Follow The Instructions and Build with Specificity to The Task - Creativity is ok but staying with the bounds is also important

//HelloWorld.java

public class HelloWorld {
  public static void main(String[] args) {
//added comma between Hello and World
System.out.println("Hello, World");
  }
}

//HelloGoodbye.java

//Refactored to only allow for two names and added trailing period
public class HelloGoodbye {
  public static void main(String[] args) {
      if (args.length == 0 ) {
        System.out.print("Hello Anon");
      }
      else if (args.length == 1) {
        System.out.print(args[0]);
      }
      else if (args.length > 1 && args.length <= 2) {
        System.out.print("Hello " + args[0] + " and " + args[1] + ".");
      } else {
        System.out.print("I can only greet two people :(");
      }
      if (args.length == 0 ) {
        System.out.print("\n Goodbye Anon");
      }
      else if (args.length == 1) {
        System.out.print(args[0]);
      }
      else if (args.length > 1 && args.length <= 2) {
        System.out.print("\nGoodbye " + args[1] + " and " + args[0] + ".");
      } else {
        System.out.print("\nSorry!");
      }
    }
}

//RandomWord.java

//Removed all printouts etc as the app should just act as a standard word randomiser
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
public class RandomWord {
  public static void main(String[] args) {
    String chosenWord = "";
    int i = 1;
    while (!StdIn.isEmpty()){
      String word = StdIn.readString();
      if (StdRandom.bernoulli(1.0 / i)) {
        chosenWord = word;
      }
      i++;
    }
    StdOut.println(chosenWord);
  }
}
  • Model the Problem
  • Main elements of the problem to be solved
  • Find an algorithm to solve the problem
  • Is the algorithm fast enough?
  • If not why?
  • Find something that might address the issue
  • Iterate until satisfied.