Java源码示例:edu.princeton.cs.algs4.In
示例1
public static void main(String[] args) {
In in = new In(args[0]); // input file
int n = in.readInt(); // n-by-n percolation system
// turn on animation mode
StdDraw.enableDoubleBuffering();
// repeatedly read in sites to open and draw resulting system
Percolation perc = new Percolation(n);
draw(perc, n);
StdDraw.show();
StdDraw.pause(DELAY);
while (!in.isEmpty()) {
int i = in.readInt();
int j = in.readInt();
perc.open(i, j);
draw(perc, n);
StdDraw.show();
StdDraw.pause(DELAY);
}
}
示例2
/**
* Create a baseball division from given filename
*
* @param filename the given filename
*/
public BaseballElimination(String filename) {
In in = new In(filename);
N = in.readInt();
teams = new ArrayList<>(N);
teamIndex = new HashMap<>(N);
wins = new int[N];
losses = new int[N];
remaining = new int[N];
against = new int[N][N];
coe = new ArrayList<>(N);
for (int i = 0; i < N; i++) {
String team = in.readString();
teams.add(team);
teamIndex.put(team, i);
wins[i] = in.readInt();
losses[i] = in.readInt();
remaining[i] = in.readInt();
for (int j = 0; j < N; j++) {
against[i][j] = in.readInt();
}
}
coeHelper();
}
示例3
public static void main(String[] args) {
// create initial board from file
In in = new In(args[0]);
int n = in.readInt();
int[][] blocks = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
blocks[i][j] = in.readInt();
Board initial = new Board(blocks);
// solve the puzzle
Solver solver = new Solver(initial);
// print solution to standard output
if (!solver.isSolvable())
StdOut.println("No solution possible");
else {
StdOut.println("Minimum number of moves = " + solver.moves());
for (Board board : solver.solution())
StdOut.println(board);
}
}
示例4
public static void main(String[] args) {
// for each command-line argument
for (String filename : args) {
// read in the board specified in the filename
In in = new In(filename);
int n = in.readInt();
int[][] tiles = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
tiles[i][j] = in.readInt();
}
}
// solve the slider puzzle
Board initial = new Board(tiles);
Solver solver = new Solver(initial);
StdOut.println(filename + ": " + solver.moves());
}
}
示例5
public static int[] readAllInts(String fileName) {
In in = new In(fileName);
String input = in.readAll();
String[] inputs = input.split("\\s+");
List<Integer> intList = new LinkedList<>();
for (int i = 0; i < inputs.length; i++) {
try {
int number = Integer.parseInt(inputs[i]);
intList.add(number);
} catch (NumberFormatException e) {
//We only care about ints
}
}
int[] ints = new int[intList.size()];
for (int i = 0; i < intList.size(); i++) {
ints[i] = intList.get(i);
}
return ints;
}
示例6
private void doExperiment() {
LookupCSV lookupCSV = new LookupCSV();
int[] numberOfQueries = {100000, 1000000, 10000000, 100000000, 1000000000};
String[] filePaths = {LARGE_INPUT_FILE_PATH1, LARGE_INPUT_FILE_PATH2};
String[] fileNames = {Constants.SURNAMES_CSV_FILE, Constants.SDSS_CSV_FILE};
StdOut.printf("%18s %20s %10s\n", "Large input | ", "Number of queries | ", "Time spent");
for(int q = 0; q < numberOfQueries.length; q++) {
for(int f = 0; f < filePaths.length; f++) {
In in = new In(filePaths[f]);
String line = in.readLine();
String[] tokens = line.split(",");
int randomKeyIndex = StdRandom.uniform(tokens.length);
int randomValueIndex = StdRandom.uniform(tokens.length);
Stopwatch stopwatch = new Stopwatch();
lookupCSV.lookup(filePaths[f], randomKeyIndex, randomValueIndex, numberOfQueries[q]);
double timeSpent = stopwatch.elapsedTime();
printResults(fileNames[f], numberOfQueries[q], timeSpent);
}
}
}
示例7
private static Date[] readAllDates(String fileName) {
In in = new In(fileName);
Queue<Date> queue = new Queue<>();
while(!in.isEmpty()) {
queue.enqueue(new Date(in.readString()));
}
int n = queue.size();
Date[] dates = new Date[n];
for (int i = 0; i < n; i++) {
dates[i] = queue.dequeue();
}
return dates;
}
示例8
public static void main(String[] args) {
Exercise15 exercise15 = new Exercise15();
String filePath = Constants.FILES_PATH + "4.1.15.txt";
Graph graph = exercise15.new Graph(new In(filePath));
StdOut.println(graph);
StdOut.println("Expected:\n" +
"0: 6 5 2 1\n" +
"1: 0\n" +
"2: 0\n" +
"3: 5 4\n" +
"4: 6 5 3\n" +
"5: 4 3 0\n" +
"6: 4 0\n" +
"7: 8\n" +
"8: 7\n" +
"9: 12 11 10\n" +
"10: 9\n" +
"11: 12 9\n" +
"12: 11 9");
}
示例9
public static void main(String[] args) {
In in = new In(args[0]); //接受一个输入流和一个起点作为命令行参数
int s = Integer.parseInt(args[1]);
EdgeWeightedDigraph G = new EdgeWeightedDigraph(in);
AcyclicLP lp = new AcyclicLP(G, s); //从输入流中读取有向图,根据起点计算有向图的最长路径树
for (int v = 0; v < G.V(); v++) { //打印从指定起点到所有结点的最长路径
if (lp.hasPathTo(v)) {
System.out.printf("%d to %d (%.2f) ", s, v, lp.distTo(v));
for (DirectedEdge e : lp.pathTo(v)) {
System.out.print(e + " ");
}
System.out.println();
} else {
System.out.printf("%d to %d has no path.\n", s, v);
}
}
}
示例10
public static void main(String[] args) {
In in = new In(args[0]); //接受一个输入流和一个起点作为命令行参数
int s = Integer.parseInt(args[1]);
EdgeWeightedDigraph G = new EdgeWeightedDigraph(in);
AcyclicLP lp = new AcyclicLP(G, s); //从输入流中读取有向图,根据起点计算有向图的最长路径树
for (int v = 0; v < G.V(); v++) { //打印从指定起点到所有结点的最长路径
if (lp.hasPathTo(v)) {
System.out.printf("%d to %d (%.2f) ", s, v, lp.distTo(v));
for (DirectedEdge e : lp.pathTo(v)) {
System.out.print(e + " ");
}
System.out.println();
} else {
System.out.printf("%d to %d has no path.\n", s, v);
}
}
}
示例11
public static void main(String[] args) {
EdgeWeightedDigraph G = new EdgeWeightedDigraph(new In(args[0])); //接受一个输入流和一个起点作为命令行参数
int s = Integer.parseInt(args[1]);
LazyDijkstra sp = new LazyDijkstra(G, s); //从输入流中读取有向图,根据起点计算有向图的最短路径树
for (int t = 0; t < G.V(); t++) { //打印从指定起点到所有结点的最短路径
StdOut.print(s + " to " + t);
StdOut.printf(" (%4.2f): ", sp.distTo(t));
if (sp.hasPathTo(t)) {
for (DirectedEdge e : sp.pathTo(t)) {
StdOut.print(e + " ");
}
}
StdOut.println();
}
}
示例12
public static void main(String[] args) {
String fileName = Constants.FILES_PATH + args[0];
int[] whitelist = (new In(fileName)).readAllInts();
char operation = args[1].charAt(0);
if (operation != '-' && operation != '+') {
throw new IllegalArgumentException("Operation needs to be - or +");
}
boolean searchForWhiteList = operation == '-';
Arrays.sort(whitelist);
while (!StdIn.isEmpty()) {
int key = StdIn.readInt();
int index = binarySearch(key, whitelist);
if (index != -1 && searchForWhiteList) {
StdOut.println("Number in whitelist: " + key);
} else if (index == -1 && !searchForWhiteList) {
StdOut.println("Number not in whitelist: " + key);
}
}
}
示例13
public int search(In inputStream) {
// Uses only local variables, with no extra instance variables
int patternIndex = 0;
int textIndex = 0;
while (inputStream.hasNextChar() && patternIndex < pattern.length()) {
patternIndex = dfa[inputStream.readChar()][patternIndex];
textIndex++;
}
if (patternIndex == pattern.length()) {
return textIndex - pattern.length(); // found
} else {
return textIndex; // not found
}
}
示例14
public FlowNetwork getRealWorldFlowNetwork() {
String filePath = Constants.FILES_PATH + Constants.US_FLIGHTS_2002_FILE;
String separator = " ";
int numberOfAirports = 500;
FlowNetwork flowNetwork = new FlowNetwork(numberOfAirports);
In in = new In(filePath);
while (in.hasNextLine()) {
String[] information = in.readLine().split(separator);
// Subtract 1 because vertices in the file are 1-index based
int airportId1 = Integer.parseInt(information[0]) - 1;
int airportId2 = Integer.parseInt(information[1]) - 1;
int capacity = Integer.parseInt(information[2]);
flowNetwork.addEdge(new FlowEdge(airportId1, airportId2, capacity));
}
return flowNetwork;
}
示例15
public FlowNetwork(In in) {
this(in.readInt());
int edges = in.readInt();
if (edges < 0) {
throw new IllegalArgumentException("Number of edges must be nonnegative");
}
for(int i = 0; i < edges; i++) {
int vertex1 = in.readInt();
int vertex2 = in.readInt();
double capacity = in.readDouble();
FlowEdge edge = new FlowEdge(vertex1, vertex2, capacity);
addEdge(edge);
}
}
示例16
public static void main(String[] args) {
Digraph digraph = new Digraph(new In(args[0]));
Bag<Integer> sources = new Bag<>();
for(int i = 1; i < args.length; i++) {
sources.add(Integer.parseInt(args[i]));
}
DirectedDFS reachable = new DirectedDFS(digraph, sources);
for(int vertex = 0; vertex < digraph.vertices(); vertex++) {
if (reachable.visited[vertex]) {
StdOut.print(vertex + " ");
}
}
StdOut.println();
}
示例17
public EdgeWeightedGraphWithInputStreamConstructor(In in) {
super(in.readInt());
int edges = in.readInt();
if (edges < 0) {
throw new IllegalArgumentException("Number of edges must be nonnegative");
}
for(int i = 0; i < edges; i++) {
int vertex1 = in.readInt();
int vertex2 = in.readInt();
double weight = in.readDouble();
Edge edge = new Edge(vertex1, vertex2, weight);
addEdge(edge);
}
}
示例18
public EdgeWeightedGraph(In in) {
this(in.readInt());
int edges = in.readInt();
if (edges < 0) {
throw new IllegalArgumentException("Number of edges must be nonnegative");
}
for(int i = 0; i < edges; i++) {
int vertex1 = in.readInt();
int vertex2 = in.readInt();
double weight = in.readDouble();
Edge edge = new Edge(vertex1, vertex2, weight);
addEdge(edge);
}
}
示例19
public EdgeWeightedGraphSpaceEfficient(In in) {
this(in.readInt());
int edges = in.readInt();
if (edges < 0) {
throw new IllegalArgumentException("Number of edges must be nonnegative");
}
for(int i = 0; i < edges; i++) {
int vertex1 = in.readInt();
int vertex2 = in.readInt();
double weight = in.readDouble();
Edge edge = new Edge(vertex1, vertex2, weight);
addEdge(edge);
}
}
示例20
public EdgeWeightedGraphWithDelete(In in) {
this(in.readInt());
int edges = in.readInt();
if (edges < 0) {
throw new IllegalArgumentException("Number of edges must be nonnegative");
}
for(int i = 0; i < edges; i++) {
int vertex1 = in.readInt();
int vertex2 = in.readInt();
double weight = in.readDouble();
Edge edge = new Edge(vertex1, vertex2, weight);
addEdge(edge);
}
}
示例21
public EdgeWeightedGraphAdjacencyMatrix(In in) {
this(in.readInt());
int edges = in.readInt();
if (edges < 0) {
throw new IllegalArgumentException("Number of edges must be nonnegative");
}
for(int i = 0; i < edges; i++) {
int vertex1 = in.readInt();
int vertex2 = in.readInt();
double weight = in.readDouble();
Edge edge = new Edge(vertex1, vertex2, weight);
addEdge(edge);
}
}
示例22
public EdgeWeightedDigraph(In in) {
this(in.readInt());
int edges = in.readInt();
if (edges < 0) {
throw new IllegalArgumentException("Number of edges must be nonnegative");
}
for(int i = 0; i < edges; i++) {
int vertexFrom = in.readInt();
int vertexTo = in.readInt();
double weight = in.readDouble();
DirectedEdge edge = new DirectedEdge(vertexFrom, vertexTo, weight);
addEdge(edge);
}
}
示例23
public EdgeWeightedDigraphWithInConstructor(In in) {
super(in.readInt());
int edges = in.readInt();
if (edges < 0) {
throw new IllegalArgumentException("Number of edges must be nonnegative");
}
for(int i = 0; i < edges; i++) {
int vertexFrom = in.readInt();
int vertexTo = in.readInt();
double weight = in.readDouble();
DirectedEdge edge = new DirectedEdge(vertexFrom, vertexTo, weight);
addEdge(edge);
}
}
示例24
public HashSet<String> filterUsingRedBlackBST(String dictionaryFilePath, String warAndPeaceFilePath) {
HashSet<String> filteredWords = new HashSet<>();
// The value field is not used, but it is required by the red-black BST
RedBlackBST<String, Boolean> redBlackBST = new RedBlackBST<>();
In in = new In(dictionaryFilePath);
while (!in.isEmpty()) {
redBlackBST.put(in.readString(), true);
}
String[] allWords = FileUtil.getAllStringsFromFile(warAndPeaceFilePath);
if (allWords == null) {
return filteredWords;
}
for(String word : allWords) {
if (!redBlackBST.contains(word)) {
filteredWords.add(word);
}
}
return filteredWords;
}
示例25
public static void main(String[] args) {
WordNet wordnet = new WordNet(args[0], args[1]);
Outcast outcast = new Outcast(wordnet);
for (int t = 2; t < args.length; t++) {
In in = new In(args[t]);
String[] nouns = in.readAllStrings();
StdOut.println(args[t] + ": " + outcast.outcast(nouns));
}
}
示例26
public static void main(String[] args) {
In in = new In(args[0]);
Digraph G = new Digraph(in);
SAP sap = new SAP(G);
while (!StdIn.isEmpty()) {
int v = StdIn.readInt();
int w = StdIn.readInt();
int length = sap.length(v, w);
int ancestor = sap.ancestor(v, w);
StdOut.printf("length = %d, ancestor = %d\n", length, ancestor);
}
}
示例27
public Digraph(In in) {
this();
int edges = in.readInt();
for(int i = 0; i < edges; i++) {
int vertex1 = in.readInt();
int vertex2 = in.readInt();
addEdge(vertex1, vertex2);
}
}
示例28
public static void main(String[] args) {
// read the n points from a file
In in = new In(args[0]);
int n = in.readInt();
Point[] points = new Point[n];
for (int i = 0; i < n; i++)
{
int x = in.readInt();
int y = in.readInt();
points[i] = new Point(x, y);
}
// draw the points
StdDraw.enableDoubleBuffering();
StdDraw.setXscale(0, 32768);
StdDraw.setYscale(0, 32768);
for (Point p : points) { p.draw(); }
StdDraw.show();
// print and draw the line segments
FastCollinearPoints collinear = new FastCollinearPoints(points);
for (LineSegment segment : collinear.segments())
{
StdOut.println(segment);
segment.draw();
StdDraw.show();
}
}
示例29
public static void main(String[] args) {
// read the numOfSegments points from a file
In in = new In(args[0]);
int n = in.readInt();
Point[] points = new Point[n];
for (int i = 0; i < n; i++) {
int x = in.readInt();
int y = in.readInt();
points[i] = new Point(x, y);
}
// draw the points
StdDraw.enableDoubleBuffering();
StdDraw.setXscale(0, 32768);
StdDraw.setYscale(0, 32768);
for (Point p : points) {
p.draw();
}
StdDraw.show();
// print and draw the line segments
BruteCollinearPoints collinear = new BruteCollinearPoints(points);
for (LineSegment segment : collinear.segments()) {
StdOut.println(segment);
segment.draw();
}
StdDraw.show();
}
示例30
public static void main(String[] args) {
//将所有输入文件复制到输出流(最后一个参数)中
Out out = new Out(args[args.length - 1]);
for (int i = 0; i < args.length - 1; i++) {
//将第i个输入文件复制到输出流中
In in = new In(args[i]);
String s = in.readAll();
out.println(s);
in.close();
}
out.close();
}