package edu.rice.hj.example.comp322; import edu.rice.hj.api.*; 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. *

* % hj Search 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) * @author Rishi Surendran *

* ************************************************************* */ public class SearchWithFinishAccumulator { /** * 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.setProperty(true); launchHabaneroApp(new HjSuspendable() { @Override public void run() throws SuspendableException { 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); } }); } /** * 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(final char[] pattern, final char[] text) { final int M = pattern.length; final int N = text.length; final HjFinishAccumulator count = newFinishAccumulator(HjOperator.SUM, int.class); finish(count, new HjSuspendable() { @Override public void run() throws SuspendableException { for (int i = 0; i <= N - M; i++) { final int ii = i; asyncNb(new HjRunnable() { @Override public void run() { int j; for (j = 0; j < M; j++) { doWork(1); // Count each char comparison as 1 unit of work if (text[ii + j] != pattern[j]) { break; } } if (j == M) { count.put(1); // found at offset i } } }); } } }); return count.get().intValue(); } }