This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Knuth Morris Pratt Search Algorithm Help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Knuth Morris Pratt Search Algorithm Help" Watch "Knuth Morris Pratt Search Algorithm Help" New topic
Author

Knuth Morris Pratt Search Algorithm Help

Niall Watchorn
Greenhorn

Joined: Mar 01, 2011
Posts: 2

Ok, I am trying to implement a KMP Search algorithm, but I'm getting an out of bounds exception, at like 59 ( if(W[i] == S[m + i]){ )

Any ideas?

Please help

My Algorithms class:



Main method:









I found the psuedo code for the KMP Algorithm and the failure function here:
KMP Psuedo Code

fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11257
    
  16

System.out.println() is your best friend.

right before your line 59, do something like

System.out.println("i is " + i ", and m is " + m + ".");

I'd also put in somewhere a "length of S is " + S.length();

then you can see what the values are just before it throws your OOB error.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Remember that variable names should be with lowercase letters. Also I would rename the variables into something with more meaning that i, n and m.


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
 
Consider Paul's rocket mass heater.
 
subject: Knuth Morris Pratt Search Algorithm Help