Search in sources :

Example 1 with In

use of edu.princeton.cs.algs4.In in project algorithms-sedgewick-wayne by reneargento.

the class Exercise15_FileInput method readAllInts.

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;
}
Also used : In(edu.princeton.cs.algs4.In) LinkedList(java.util.LinkedList)

Example 2 with In

use of edu.princeton.cs.algs4.In in project algorithms-sedgewick-wayne by reneargento.

the class Exercise23_DuplicatesRevisitedAgain method countDistinctValues.

public void countDistinctValues(boolean useDedup, boolean useStringSet, boolean generateLongValues, int[] values) {
    int numberOfTrials = 10;
    String method;
    String dataStructure;
    String valuesType;
    if (useDedup) {
        method = "DeDup";
        if (!useStringSet) {
            dataStructure = "HashSet";
        } else {
            dataStructure = "StringSet";
        }
    } else {
        method = "Array index count";
        dataStructure = "Array";
    }
    if (!generateLongValues) {
        valuesType = "Integer";
    } else {
        valuesType = "Long";
    }
    /**
     * T = 10
     * N = 10^3, 10^4, 10^5, 10^6, 10^7, 10^8, 10^9
     * M = N/2, N, 2N
     */
    DistinctCounter distinctCounter = new DistinctCounter();
    for (int n = 0; n < values.length; n++) {
        for (int m = 0; m < 3; m++) {
            int numberOfValues = values[n];
            int maxValue = 0;
            if (m == 0) {
                maxValue = numberOfValues / 2;
            } else if (m == 1) {
                maxValue = numberOfValues;
            } else if (m == 2) {
                maxValue = 2 * numberOfValues;
            }
            Stopwatch stopwatch = new Stopwatch();
            for (int trial = 0; trial < numberOfTrials; trial++) {
                // Count the distinct values, but will not be used in this exercise since we are interested
                // only in the running time
                long distinctValues;
                if (!useDedup) {
                    if (!generateLongValues) {
                        distinctValues = distinctCounter.countDistinctIntegerValuesUsingIndex(numberOfValues, maxValue);
                    } else {
                        distinctValues = distinctCounter.countDistinctLongValuesUsingIndex(numberOfValues, maxValue);
                    }
                } else {
                    if (!generateLongValues) {
                        if (!useStringSet) {
                            distinctValues = distinctCounter.deDupWithIntegerValuesAndHashSet(numberOfValues, maxValue);
                        } else {
                            distinctValues = distinctCounter.deDupWithIntegerValuesAndStringSet(numberOfValues, maxValue);
                        }
                    } else {
                        if (!useStringSet) {
                            distinctValues = distinctCounter.deDupWithLongValuesAndHashSet(numberOfValues, maxValue);
                        } else {
                            distinctValues = distinctCounter.deDupWithLongValuesAndStringSet(numberOfValues, maxValue);
                        }
                    }
                }
            }
            double timeSpent = stopwatch.elapsedTime();
            printResults(method, dataStructure, valuesType, numberOfValues, maxValue, timeSpent);
        }
    }
}
Also used : Stopwatch(edu.princeton.cs.algs4.Stopwatch)

Example 3 with In

use of edu.princeton.cs.algs4.In in project algorithms-sedgewick-wayne by reneargento.

the class Exercise25_Dictionary method doExperiment.

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 };
    String[] dataStructures = { "Trie", "Ternary Search Trie" };
    StdOut.printf("%21s %19s %20s %10s\n", "Data structure |", "Large input | ", "Number of queries | ", "Time spent");
    for (int trieType = 0; trieType < 2; trieType++) {
        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);
                TrieInterface<String> trie;
                if (trieType == 0) {
                    trie = new Trie<>();
                } else {
                    trie = new TernarySearchTrie<>();
                }
                Stopwatch stopwatch = new Stopwatch();
                lookupCSV.lookup(trie, filePaths[f], randomKeyIndex, randomValueIndex, numberOfQueries[q]);
                double timeSpent = stopwatch.elapsedTime();
                printResults(dataStructures[trieType], fileNames[f], numberOfQueries[q], timeSpent);
            }
        }
    }
}
Also used : In(edu.princeton.cs.algs4.In) Stopwatch(edu.princeton.cs.algs4.Stopwatch)

Example 4 with In

use of edu.princeton.cs.algs4.In in project algorithms-sedgewick-wayne by reneargento.

the class Exercise29_BufferingInBoyerMoore method main.

// File contents: abacadabrabracabracadabrabrabracad
public static void main(String[] args) {
    Exercise29_BufferingInBoyerMoore bufferingInBoyerMoore = new Exercise29_BufferingInBoyerMoore();
    String filePath = Constants.FILES_PATH + Constants.STREAMING_FILE;
    String pattern1 = "abracadabra";
    In inputStream1 = new In(filePath);
    BoyerMooreBuffer boyerMooreBuffer1 = bufferingInBoyerMoore.new BoyerMooreBuffer(pattern1);
    int index1 = boyerMooreBuffer1.search(inputStream1);
    StdOut.println("Index 1: " + index1 + " Expected: 14");
    inputStream1.close();
    String pattern2 = "rab";
    In inputStream2 = new In(filePath);
    BoyerMooreBuffer boyerMooreBuffer2 = bufferingInBoyerMoore.new BoyerMooreBuffer(pattern2);
    int index2 = boyerMooreBuffer2.search(inputStream2);
    StdOut.println("Index 2: " + index2 + " Expected: 8");
    inputStream2.close();
    String pattern3 = "bcara";
    In inputStream3 = new In(filePath);
    BoyerMooreBuffer boyerMooreBuffer3 = bufferingInBoyerMoore.new BoyerMooreBuffer(pattern3);
    int index3 = boyerMooreBuffer3.search(inputStream3);
    StdOut.println("Index 3: " + index3 + " Expected: 34");
    inputStream3.close();
    String pattern4 = "rabrabracad";
    In inputStream4 = new In(filePath);
    BoyerMooreBuffer boyerMooreBuffer4 = bufferingInBoyerMoore.new BoyerMooreBuffer(pattern4);
    int index4 = boyerMooreBuffer4.search(inputStream4);
    StdOut.println("Index 4: " + index4 + " Expected: 23");
    inputStream4.close();
    String pattern5 = "abacad";
    In inputStream5 = new In(filePath);
    BoyerMooreBuffer boyerMooreBuffer5 = bufferingInBoyerMoore.new BoyerMooreBuffer(pattern5);
    int index5 = boyerMooreBuffer5.search(inputStream5);
    StdOut.println("Index 5: " + index5 + " Expected: 0");
    inputStream5.close();
    String pattern6 = "renerenerenerenerenerenerenerenerene";
    In inputStream6 = new In(filePath);
    BoyerMooreBuffer boyerMooreBuffer6 = bufferingInBoyerMoore.new BoyerMooreBuffer(pattern6);
    int index6 = boyerMooreBuffer6.search(inputStream6);
    StdOut.println("Index 6: " + index6 + " Expected: 34");
    inputStream5.close();
}
Also used : In(edu.princeton.cs.algs4.In)

Example 5 with In

use of edu.princeton.cs.algs4.In in project algorithms-sedgewick-wayne by reneargento.

the class Exercise37_RealEdgeWeightedGraphs method randomRealEdgeWeightedGraph.

private EdgeWeightedGraph randomRealEdgeWeightedGraph(int randomVerticesToChoose, int randomEdgesToChoose) {
    String filePath = Constants.FILES_PATH + Constants.US_AIR_FILE;
    String separator = " ";
    In in = new In(filePath);
    String[] firstLine = in.readLine().split(separator);
    int vertices = Integer.parseInt(firstLine[0]);
    int edges = Integer.parseInt(firstLine[2]);
    EdgeWeightedGraph fullGraph = new EdgeWeightedGraph();
    for (int edge = 0; edge < edges; edge++) {
        String[] connection = in.readLine().split(separator);
        int city1 = Integer.parseInt(connection[0]);
        int city2 = Integer.parseInt(connection[1]);
        double distance = Double.parseDouble(connection[2]);
        Edge newEdge = new Edge(city1, city2, distance);
        fullGraph.addEdge(newEdge);
    }
    EdgeWeightedGraph randomSubGraph = new EdgeWeightedGraph();
    SeparateChainingHashTable<Integer, Integer> graphToSubGraphMap = new SeparateChainingHashTable<>();
    List<Edge> allSubGraphEdges = new ArrayList<>();
    HashSet<Integer> chosenVertices = new HashSet<>();
    for (int vertex = 0; vertex < randomVerticesToChoose; vertex++) {
        // Randomly choose a vertex between 1 and vertices
        int randomVertexId = StdRandom.uniform(vertices) + 1;
        if (chosenVertices.contains(randomVertexId)) {
            continue;
        }
        chosenVertices.add(randomVertexId);
        int subGraphVertexId1 = graphToSubGraphMap.size();
        graphToSubGraphMap.put(randomVertexId, subGraphVertexId1);
        randomSubGraph.addVertex(subGraphVertexId1);
        for (Edge edge : fullGraph.adjacent(randomVertexId)) {
            int vertexId2 = edge.other(randomVertexId);
            int subGraphVertexId2;
            if (!graphToSubGraphMap.contains(vertexId2)) {
                subGraphVertexId2 = graphToSubGraphMap.size();
                graphToSubGraphMap.put(vertexId2, subGraphVertexId2);
                randomSubGraph.addVertex(subGraphVertexId2);
            } else {
                subGraphVertexId2 = graphToSubGraphMap.get(vertexId2);
            }
            allSubGraphEdges.add(new Edge(subGraphVertexId1, subGraphVertexId2, edge.weight()));
        }
    }
    // Randomly choose E edges from the subgraph induced by the random vertices
    if (randomEdgesToChoose > allSubGraphEdges.size()) {
        throw new IllegalArgumentException("Not enough edges to choose from the induced subgraph");
    }
    Edge[] allSubGraphEdgesArray = new Edge[allSubGraphEdges.size()];
    int allSubGraphEdgesArrayIndex = 0;
    HashSet<Integer> edgesChosen = new HashSet<>();
    for (Edge edge : allSubGraphEdges) {
        allSubGraphEdgesArray[allSubGraphEdgesArrayIndex++] = edge;
    }
    for (int edge = 0; edge < randomEdgesToChoose; edge++) {
        // Randomly choose an edge
        int randomEdgeId = StdRandom.uniform(allSubGraphEdgesArray.length);
        if (edgesChosen.contains(randomEdgeId)) {
            continue;
        }
        edgesChosen.add(randomEdgeId);
        Edge randomEdge = allSubGraphEdgesArray[randomEdgeId];
        int subGraphVertexId1 = randomEdge.either();
        int subGraphVertexId2 = randomEdge.other(subGraphVertexId1);
        Edge newEdge = new Edge(subGraphVertexId1, subGraphVertexId2, randomEdge.weight());
        randomSubGraph.addEdge(newEdge);
    }
    return randomSubGraph;
}
Also used : In(edu.princeton.cs.algs4.In) ArrayList(java.util.ArrayList) SeparateChainingHashTable(chapter3.section4.SeparateChainingHashTable) HashSet(chapter3.section5.HashSet)

Aggregations

In (edu.princeton.cs.algs4.In)71 StdIn (edu.princeton.cs.algs4.StdIn)10 HashSet (chapter3.section5.HashSet)5 ArrayList (java.util.ArrayList)5 SeparateChainingHashTable (chapter3.section4.SeparateChainingHashTable)4 ST (edu.princeton.cs.algs4.ST)4 Stopwatch (edu.princeton.cs.algs4.Stopwatch)4 Bag (com.jimmysun.algorithms.chapter1_3.Bag)3 Queue (edu.princeton.cs.algs4.Queue)3 SET (edu.princeton.cs.algs4.SET)3 RedBlackBST (chapter3.section3.RedBlackBST)2 Transaction (edu.princeton.cs.algs4.Transaction)2 Bag (chapter1.section3.Bag)1 Queue (chapter1.section3.Queue)1 Queue (com.jimmysun.algorithms.chapter1_3.Queue)1 Date (edu.princeton.cs.algs4.Date)1 Out (edu.princeton.cs.algs4.Out)1 File (java.io.File)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1