Rabin Karp algorithm in java - java

I am interested in implementing the Rabin-Karp algorithm to search for sub strings. Here is the algorithm i used: algorithm.
The code I made for the same is as below.
But output is blank. It says build successfully but gives no output...
package rabinkarp;
public class RabinKarp {
final static int q = 101;
final static int d = 256;
public static void RabinKarpMatcher(String T,String p,int q,int d)
{
int n = T.length();
int M = p.length();
int H = 1,i,j;
for (i = 0; i < M-1; i++)
H = (H*d)%q;
int P = 0;
int t = 0;
for(i = 0;i < M; i++)
{
P = (d*P+p.charAt(i))%q;
t = (d*t+T.charAt(i))%q;
}
for(i = 0; i < n-M; i++)
{
if(P==t)
{
for(j = 0; j < M; j++)
{
if(T.charAt(i+j)!=p.charAt(j))
{
break;
}
}
if(j==M)
{
System.out.println("Pattern found at " + i+1);
}
}
if(i < n-M)
{
t = (d*(t-T.charAt(i)*H)+T.charAt(i+M))%q;
if(i <0)
{
t = t+q;
}
}
}
}
public static void main(String[] args) {
String text = new String("ababaaabhahhhha");
String pat = new String("ha");
RabinKarpMatcher(text,pat,q,d);
}
}

Related

In java, I just use a variable of 'A' to replace 'A' in one line , but get a different answer

When I'm implementing the SOR approach with java, I find this problem:
when I do this:
Matrix mm = ((D.sub(L)).inv());
B = mm.dot(b);
The value of B is right. However, when I use:
B = ((D.sub(L)).inv()).dot(b);
I get a quite different value of B which is wrong.
I fell this may be a reference problem, but I can't get the exact answer.
This is the SOR method:
public static Matrix[] SOR(Matrix m, Matrix b, double omiga) {
Matrix D = getD(m);
Matrix L = getL(m);
Matrix U = getU(m);
Matrix M = null;
Matrix B = null;
try {
Matrix mm = ((D.sub(L.pro(omiga))).inv());
M = mm.dot((D.pro(1 - omiga)).add(U.pro(omiga)));
// This is right:
B = (mm.dot(b)).pro(omiga);
// This is wrong:
// B = (((D.sub(L.pro(omiga))).inv()).dot(b)).pro(omiga);
} catch (MatrixProcessException e) {
System.out.println("3 Matrix process problem!");
}
Matrix[] matrices = {M, B};
return matrices;
}
And this is the Matrix class created by me (methods in it have all been checked and have no problem):
public class Matrix {
private int row;
private int col;
private int rowNum;
private int colNum;
private double[][] m;
public Matrix(int rowNum, int colNum) {
this.rowNum = rowNum;
this.colNum = colNum;
m = new double[rowNum][colNum];
for (int i = 0; i < rowNum; i++) {
for (int j = 0; j < colNum; j++) {
m[i][j] = 0;
}
}
}
public Matrix(double[][] m) {
rowNum = m.length;
colNum = m[0].length;
this.m = m;
}
public Matrix(double[] v) {
rowNum = v.length;
colNum = 1;
double[][] m = new double[rowNum][colNum];
for (int i = 0; i < rowNum; i++) {
m[i][0] = v[i];
}
this.m = m;
}
public Matrix pro(double lambda) {
for (int i = 0; i < rowNum; i++) {
for (int j = 0; j < colNum; j++) {
m[i][j] *= lambda;
}
}
return this;
}
public Matrix add(Matrix mm) throws MatrixProcessException {
if (mm.getRowNum() != rowNum || mm.getColNum() != colNum) {
throw new MatrixProcessException();
}
double[][] m1 = m;
double[][] m2 = mm.getM();
double[][] addM = new double[m.length][m[0].length];
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
addM[i][j] = m1[i][j] + m2[i][j];
}
}
return new Matrix(addM);
}
public Matrix sub(Matrix mm) throws MatrixProcessException {
if (mm.getRowNum() != rowNum || mm.getColNum() != colNum) {
throw new MatrixProcessException();
}
return this.add(mm.pro(-1));
}
}
public double[][] getM() {
return m;
}
public void setM(double[][] m) {
this.m = m;
}
public int getRowNum() {
return rowNum;
}
public void setRowNum(int rowNum) {
this.rowNum = rowNum;
}
public int getColNum() {
return colNum;
}
public void setColNum(int colNum) {
this.colNum = colNum;
}
public Matrix dot(Matrix M) throws MatrixProcessException {
double[][] m1 = m;
double[][] m2 = M.getM();
if (this.colNum != M.rowNum) {
System.out.println("sss");
throw new MatrixProcessException();
}
double[][] ansMatrix = new double[this.rowNum][M.colNum];
for (int i = 0; i < this.rowNum; i++) {
for (int j = 0; j < M.colNum; j++) {
double num = 0;
for (int k = 0; k < this.colNum; k++) {
num += m1[i][k] * m2[k][j];
}
ansMatrix[i][j] = num;
}
}
return new Matrix(ansMatrix);
}
public Matrix inv() throws MatrixProcessException {
if (rowNum != colNum) {
throw new MatrixProcessException();
}
Matrix mm = new Matrix(rowNum, 2 * colNum);
for (int i = 0; i < rowNum; i++) {
for (int j = 0; j < 2 * colNum; j++) {
if (j < rowNum) {
mm.set(i, j, m[i][j]);
}
else {
if (j - rowNum == i) {
mm.set(i, j, 1);
}
}
}
}
Collections.calculateUpperTriangle(mm);
Collections.calculateSimplest(mm);
for (int i = 0; i < rowNum; i++) {
mm.proR(i, 1.0 / mm.get(i, i));
}
Matrix M = new Matrix(rowNum, colNum);
for (int i = 0; i < rowNum; i++) {
for (int j = 0; j < rowNum; j++) {
M.set(i, j, mm.get(i, j + rowNum));
}
}
return M;
}
public void showMatrix() {
System.out.println("\nMatrix:");
for (int i = 0; i < rowNum; i++) {
for (int j = 0; j < colNum; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
}
public double[] toVector() {
double[] v = new double[rowNum];
if (colNum == 1) {
for (int i = 0; i < rowNum; i++) {
v[i] = m[i][0];
}
}
else {
System.out.println("This matrix is not a vector");
}
return v;
}
}
May anyone help me to get the reason of the problem?
Thx!

Finding minimum weight and number of edges traversed in a graph

I have to find the minimum distance between two vertices and no. of edges traversed in finding that minimum distance in a adirected weighted graph. I did write a code on using Dijkstras algo. But my test cases are failing. What am i missing here.?
Ideal input: given any two vertices A,B
Output: min distance between two nodes, no. of edges traversed
If the node is unreachable then output should be -1, -1.
//This is a java program to find the shortest path between source vertex and destination vertex
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Dijkstras_Shortest_Path
{
private int distances[];
private int Numnodes[];
private int numnodes;
private Set<Integer> settled;
private Set<Integer> unsettled;
private int number_of_nodes;
private int adjacencyMatrix[][];
public Dijkstras_Shortest_Path(int number_of_nodes)
{
this.number_of_nodes = number_of_nodes;
distances = new int[number_of_nodes + 1];
Numnodes=new int[number_of_nodes+1];
settled = new HashSet<Integer>();
unsettled = new HashSet<Integer>();
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
}
public void dijkstra_algorithm(int adjacency_matrix[][], int source)
{
int evaluationNode;
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacencyMatrix[i][j] = adjacency_matrix[i][j];
for (int i = 1; i <= number_of_nodes; i++)
{
distances[i] = Integer.MAX_VALUE;
}
unsettled.add(source);
distances[source] = 0;
while (!unsettled.isEmpty())
{
evaluationNode = getNodeWithMinimumDistanceFromUnsettled();
unsettled.remove(evaluationNode);
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
}
private int getNodeWithMinimumDistanceFromUnsettled()
{
int min;
int node = 0;
Iterator<Integer> iterator = unsettled.iterator();
node = iterator.next();
min = distances[node];
for (int i = 1; i <= distances.length; i++)
{
if (unsettled.contains(i))
{
if (distances[i] <= min)
{
min = distances[i];
node = i;
}
}
}
return node;
}
private void evaluateNeighbours(int evaluationNode)
{
int edgeDistance = -1;
int newDistance = -1;
int newNodes=1;
for (int destinationNode = 1; destinationNode <= number_of_nodes;
destinationNode++)
{
if (!settled.contains(destinationNode))
{
if (adjacencyMatrix[evaluationNode][destinationNode] !=
Integer.MAX_VALUE)
{
edgeDistance = adjacencyMatrix[evaluationNode]
[destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
newNodes=Numnodes[evaluationNode]+1;
if (newDistance < distances[destinationNode])
{
distances[destinationNode] = newDistance;
Numnodes[destinationNode]=newNodes;
}
unsettled.add(destinationNode);
}
}
}
}
public static void main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
int number_of_edges;
int source = 0, destination = 0;
Scanner scan = new Scanner(System.in);
try
{
number_of_vertices = scan.nextInt();
number_of_edges=scan.nextInt();
if (number_of_vertices<1||number_of_vertices>10000)
{
System.out.println("Number of vertices out of boundary");
}
if (number_of_edges<1||number_of_edges>10000)
{
System.out.println("Number of edges out of boundary");
}
adjacency_matrix = new int[number_of_vertices + 1]
[number_of_vertices + 1];
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = 0;
}
}
for(int i=1;i<=number_of_edges;i++)
{
int node1=scan.nextInt();
int node2=scan.nextInt();
adjacency_matrix[node1][node2]=scan.nextInt();
}
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = Integer.MAX_VALUE;
}
}
}
source = scan.nextInt();
destination = scan.nextInt();
Dijkstras_Shortest_Path dijkstrasAlgorithm = new
Dijkstras_Shortest_Path(
number_of_vertices);
dijkstrasAlgorithm.dijkstra_algorithm(adjacency_matrix, source);
for (int i = 1; i <= dijkstrasAlgorithm.distances.length - 1; i++)
{
if (i == destination)
System.out.println(dijkstrasAlgorithm.distances[i] +" "+
dijkstrasAlgorithm.Numnodes[i]);
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}

Floyd Warshall algorithm implementation

I've written code for a 100 x 100 adjacency matrix that represents the following directed graph:
I'm attempting to use a Floyd-Warshall algorithm to find the shortest path for all pairs of blue nodes in the graph. How do you only find the all pairs shortest path for the selected nodes? Here's the code I've written thus far:
public class AdjacencyMatrix
{
public static final int NUM_NODES = 100;
public static final int INF = Integer.MAX_VALUE;
public static boolean even(int num)
{
return num%2==0;
}
public static boolean odd(int num)
{
return num%2==1;
}
public static void initialize(int [][] adjMat, int N)
{
for(int i = 0; i < N; i++)
for(int j = 0; j <N; j++)
adjMat[i][j]=INF;
for(int x = 0; x<N; x++)
{
int row = x/10;
int column = x%10;
if (even(row)) {
if (column!=9)
adjMat[x][x+1]=1;
}
if (odd(row)) {
if (column!=0)
adjMat[x][x-1]=1;
}
if (even(column)){
if (row!=9)
adjMat[x][x+10]=1;
}
if (odd(column)) {
if (row!=0)
adjMat[x][x-10]=1;
}
}
}
public void floydWarshall(int[][] adjMat, int N)
{
adjMat = new int[N][N];
initialize(adjMat, NUM_NODES);
for(int k = 0; k < N; ++k) {
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N; ++j) {
adjMat[i][j] = Math.min(adjMat[i][j], adjMat[i][k] + adjMat[k][j]);
}
}
}
}
public static void main(String[] args)
{
int adjMat[][] = new int[NUM_NODES][NUM_NODES];
initialize(adjMat, NUM_NODES);
int A,B,C,D,E,F,G,H,I,W;
A = 20;
B = 18;
C = 47;
D = 44;
E = 53;
F = 67;
G = 95;
H = 93;
I = 88;
W = 66;
System.out.println(adjMat[A][B]);
System.out.println();
}
}
First of all, you should not assign new value to adjMat parameter in floydWarshall(), because the value will not be saved after exiting the method.
The next step is to check adjMat[i][k] and adjMat[k][j] for equality to INF and continue the loop if so:
for(int k = 0; k < N; ++k) {
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N; ++j) {
if (adjMat[i][k] != INF && adjMat[k][j] != INF) {
adjMat[i][j] = Math.min(adjMat[i][j], adjMat[i][k] + adjMat[k][j]);
}
Shortest Floyd-Warshall algo implemenation:
for(int k = 0; k < N; ++k) {
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N; ++j) {
adjMat[i][j] = Math.min(adjMat[i][j], adjMat[i][k] + adjMat[k][j]);
}
}
}
After running this piece of cade adjMat will contain shortest distances between every pair of nodes.
Update: to avoid integer overflow, fill the matrix with Integer.MAX_VALUE / 2. In general case, it's dangerous to set the maximum possible value to variable as infinity, because you can't perform addition operation with it.

Calculating the number of times every letter of the alphabet appears in a series of strings in an ArrayList [duplicate]

This question already has answers here:
Counting the number of a certain letter appears in series of strings in an ArrayList
(4 answers)
Closed 6 years ago.
I have an ArrayList that stores strings, or notes, in the form of "walk the dog". I have a notes class with a method that prints the number of times each letter appears in the entire ArrayList. I'm supposed to declare and use a primitive array of ints of size 26 and turn each letter in the notebook into a char using the charAt method in the String class. Then I have to use that char to index into the appropriate location in the low-level array. This is my method so far but it's not finished:
public void printLetterDistribution() {
ArrayList<Integer> aList = new ArrayList<Integer>();
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
for (int j = 0; j < note.length(); j++) {
char letter = note.charAt(j);
int code = (int)letter;
aList.add(code);
}
}
Collections.sort(aList);
}
I've hit a wall and I don't know how to continue. As you can see, I've tried to convert the letters to their character code but it's probably not the best way to do it and I'm still getting stuck. Can anybody help?
EDIT - Here is the entire notes class:
public class Notebook {
private ArrayList<String> notes;
public Notebook() { notes = new ArrayList<String>(); }
public void addNoteToEnd(String inputnote) {
notes.add(inputnote);
}
public void addNoteToFront(String inputnote) {
notes.add(0, inputnote);
}
public void printAllNotes() {
for (int i = 0; i < notes.size(); i++) {
System.out.print("#" + (i + 1) + " ");
System.out.println(notes.get(i));
}
System.out.println();
}
public void replaceNote(int inputindex, String inputstring) {
int index = inputindex - 1;
if (index > notes.size() || index < 0) {
System.out.println("ERROR: Note number not found!");
} else {
notes.set(index, inputstring);
}
}
public int countNotesLongerThan(int length) {
int count = 0;
for (int i = 0; i < notes.size(); i++) {
String temp = notes.get(i);
if (temp.length() > length) {
count++;
}
}
return count;
}
public double averageNoteLength() {
int sum = 0;
for (int i = 0; i < notes.size(); i++) {
String temp = notes.get(i);
int length = temp.length();
sum += length;
}
double average = (double)(sum / notes.size());
return average;
}
public String firstAlphabetically() {
String min = "";
for (int i = 0; i < notes.size(); i++) {
for (int j = i + 1; j < notes.size(); j++) {
if ((notes.get(i)).compareTo(notes.get(j)) < 0) {
min = notes.get(i);
} else {
min = notes.get(j);
}
}
}
return min;
}
public void removeNotesBetween(int startnote, int endnote) {
int start = startnote - 1;
int end = endnote - 1;
for (int i = end - 1; i > start; i--) {
notes.remove(i);
}
}
public void printNotesContaining(String findString) {
for (int i = 0; i < notes.size(); i++) {
if (notes.get(i).contains(findString)) {
System.out.println("#" + i + " " + notes.get(i));
}
}
}
public int countNumberOf(String letter) {
int count = 0;
for (int i = 0; i < notes.size(); i++) {
String note = (notes.get(i));
for (int j = 0; j < note.length(); j++) {
if (note.charAt(j) == letter.charAt(0)) {
count++;
}
}
}
return count;
}
public void findAndReplaceFirst(String old, String newWord) {
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
if (note.contains(old)) {
int loc = note.indexOf(old);
int len = old.length();
String temp = note.substring(0, loc ) + note.substring(loc + len, note.length());
String newString = temp.substring(0, loc) + newWord + temp.substring(loc, temp.length());
notes.set(i, newString);
} else {
String newString = note;
notes.set(i, newString);
}
}
}
public void printLetterDistribution() {
int[] p = new int[26];
for (int i = 0; i < 26; i++) {
p[i] = 0;
}
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
note = note.toLowerCase();
for (int j = 0; j < note.length(); j++) {
char letter = note.charAt(j);
p[letter - 'a']++;
}
}
System.out.println(p);
}
}
You can use an int array of 26 length and increment the count of the index letter-'a';
int[] p = new int[26];
for(int i = 0; i < 26; i++) p[i] = 0;
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
for (int j = 0; j < note.length(); j++) {
char letter = note.charAt(j);
if(letter>= 'a' && letter <= 'z')
p[letter-'a']++;
}
PS: I am assuming that the notes are in lowercase only. If it is not the case, use note.toLowerCase() to make them lower.
Since in your notes you can have spaces, I have updated the code.

Name sorter returns -1?

Wrote name sorting program designed to sort a list of names (duh) and give index value of my name. It should return 1219 or so as my name is near last on the list, yet instead returns -1? What's wrong with my linearSearch method?
import java.io.*;
import java.util.Scanner;
public class NameSorter
{
public static void main(String [] args) throws FileNotFoundException
{
String [] maleNames = new String[1220];
PrintStream ps = new PrintStream("sorted_male_names.txt");
Scanner nameScan = new Scanner(new File("common_male_names.txt"));
for (int i = 0; i < maleNames.length; i++)
{
maleNames[i] = nameScan.nextLine();
}
bubbleSort(maleNames);
for (int i = 0; i < maleNames.length; i++)
{
System.out.println(maleNames[i]);
}
for (int i = 0; i < maleNames.length; i++)
{
String currentName = maleNames[i];
ps.println(currentName);
}
System.out.println(linearSearch(maleNames, "zander"));
}
public static boolean isSorted(String[] arr)
{
for (int i = 0; i < arr.length -1; i++)
{
if (arr[i].compareTo(arr[i+1]) > 0)
return false;
}
return true;
}
public static void swapElements(String[] arr, int index1, int index2)
{
String tempValue = arr[index1];
arr[index1] = arr[index2];
arr[index2] = tempValue;
}
public static void bubbleSort(String[] arr)
{
while(isSorted(arr) == false) // while(!isSorted(arr))
{
for (int i = 0; i < arr.length - 1; i++)
{
if (arr[i].compareTo(arr[i+1]) > 0)
swapElements(arr, i, i+1);
}
}
}
public static int linearSearch(String[] arr, String name)
{
for (int i = 0; i > arr.length; i++)
{
if (arr[i].equals(name))
return i;
}
return -1;
}
public static void printArray(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}
Thanks in advance!
Change
for (int i = 0; i > arr.length; i++)
to
for (int i = 0; i < arr.length; i++)

Categories

Resources