package edu.rice.hj.example.comp322.labs.lab2; import edu.rice.hj.api.HjMetrics; import edu.rice.hj.runtime.config.HjSystemProperty; import edu.rice.hj.runtime.metrics.AbstractMetricsManager; import static edu.rice.hj.Module1.*; /** * ************************************************************ *

* Reads in two strings, the pattern and the input text, and searches for the pattern in the input text. *

* % java Search2 rabrabracad abacadabrabracabracadabrabrabracad text: abacadabrabracabracadababacadabrabracabracadabrabrabracad * pattern: rabrabracad (input paramters can be given via run * configurations in IntelliJ) *

* HJ version ported from Java version in http://algs4.cs.princeton.edu/53substring/Brute.java.html * * @author Vivek Sarkar (vsarkar@rice.edu) *

* ************************************************************* */ public class Search2 { /** * Finds the number of occurances of a pattern in a text Each comparison of letters is one unit of work * * @param pattern - the pattern to search for * @param text - the text to search in * @return - the number of occurances of the pattern in the text */ public static int search(char[] pattern, char[] text) { int M = pattern.length; int N = text.length; int count = 0; for (int i = 0; i <= N - M; i++) { int j; for (j = 0; j < M; j++) { doWork(1); // Count each char comparison as 1 unit of work if (text[i + j] != pattern[j]) { break; } } if (j == M) { count++; // found at offset i } } return count; } /** * Main function. first argument given in the pattern. Second argument is the text. If no pattern is given, uses the * default pattern. If no text is given, use the defualt text. * * @param args - command line arguments. */ public static void main(final String[] args) { // Setup metrics HjSystemProperty.abstractMetrics.set(true); launchHabaneroApp(() -> { final String default_pat = "rabrabracad"; final String default_txt = "abacadabrabracabracadababacadabrabracabracadabrabrabracad"; String pat = default_pat; String txt = default_txt; if (args.length >= 1) { pat = args[0]; } if (args.length >= 2) { txt = args[1]; } char[] pattern = pat.toCharArray(); char[] text = txt.toCharArray(); int count = search(pattern, text); // print results System.out.println("text: " + txt); System.out.println("pattern: " + pat); System.out.println("Number of occurrences: " + count); }, () -> { // Print out the metrics data final HjMetrics actualMetrics = abstractMetrics(); AbstractMetricsManager.dumpStatistics(actualMetrics); }); } }