public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
public class HelloGoodbye {
public static void main(String[] args) {
System.out.println("Hello " + args[0] + " and " + args[1] + ".");
System.out.println("Goodbye " + args[1] + " and " + args[0] + ".");
}
}
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) {
int idx = 1;
String champ = "";
while (!StdIn.isEmpty()) {
String word = StdIn.readString();
double odds = 1.0D / idx;
boolean isWinner = StdRandom.bernoulli(odds);
if (isWinner) {
champ = word;
}
idx++;
}
StdOut.println(champ);
}
}
coursera/src$ zip -r hello.zip HelloGoodbye.java HelloWorld.java RandomWord.java
updating: HelloGoodbye.java (deflated 44%)
updating: HelloWorld.java (deflated 19%)
updating: RandomWord.java (deflated 65%)
coursera/src$ CLASSPATH=../algs4.jar javac RandomWord.java
coursera/src$ CLASSPATH=.:../algs4.jar java RandomWord
# in my environment, `while (!StdIn.isEmpty())` didn't stop
The following code was not allowed.
Checkstyle ends with 5 errors.
[ERROR] RandomWord.java:6:5: Do not declare instance variables in this program. [NothingButMain]
[ERROR] RandomWord.java:7:5: Do not declare instance variables in this program. [NothingButMain]
[ERROR] RandomWord.java:9:5: Do not define instance methods in this program. [NothingButMain]
[ERROR] RandomWord.java:18:5: Do not define instance methods in this program. [NothingButMain]
[ERROR] RandomWord.java:38:25: Do not create arrays (or other objects) with 'new' in this program. [Design]
/**
* RandomWordSelector selects one of the words, which are fed sequentially, in a real-time manner.
*/
class RandomWordSelector {
private int consumptionCount;
private String selection;
public void consume(String word) {
double odds = 1.0D / (consumptionCount + 1);
boolean retain = StdRandom.bernoulli(odds);
if (retain) {
selection = word;
}
consumptionCount++;
}
public String getSelection() {
return selection;
}
}
public class RandomWord {
public static void main(String[] args) {
RandomWordSelector rws = new RandomWordSelector();
while (!StdIn.isEmpty()) {
rws.consume(StdIn.readString());
}
StdOut.println(rws.getSelection());
}
}