How to search via character matching with a skip distance? - java

As the title says, I'm working on a project in which I'm searching a given text, moby dick in this case, for a key word. However instead of the word being linear, we are trying to find it via a skip distance ( instead of cat, looking for c---a---t).
I've tried multiple ways, yet can't seem to get it to actually finish one skip distance, have it not work, and call the next allowed distance (incrementing by 1 until a preset limit is reached)
The following is the current method in which this search is done, perhaps this is just something silly that I'm missing?
private int[] search()
throws IOException
{
/*
tlength is the text file length,
plength is the length of the
pattern word (cat in the original post),
text[] is a character array of the text file.
*/
int i=0, j;
int match[] = new int[2];
int skipDist = 2;
while(skipDist <= 100)
{
while(i<=tlength-(plength * skipDist))
{
j=plength-1;
while(j>=0 && pattern[j]==text[i+(j * skipDist)])j--;
if (j<0)
{
match[0] = skipDist;
match[1] = i;
return match;
}
else
{
i++;
}
}
skipDist = skipDist + 1;
}
System.out.println("There was no match!");
System.exit(0);
return match;
}

I do not know about the method you posted, but you can use this instead. I've used string and char array for this:
public boolean checkString (String s)
{
char[] check = {'c','a','t'};
int skipDistance = 2;
for(int i = 0; i< (s.length() - (skipDistance*(check.length-1))); i++)
{
boolean checkValid = true;
for(int j = 0; j<check.length; j++)
{
if(!(s.charAt(i + (j*skipDistance))==check[j]))
{
checkValid = false;
}
}
if(checkValid)
return true;
}
return false;
}
Feed the pattern to match in the char array 'check'.
String "adecrayt" evaluates true. String "cat" evaluates false.
Hope this helps.
[This part was for fixed skip distance]
+++++++++++++++++++++++++++
Now for any skip distance between 2 and 100:
public boolean checkString (String s)
{
char[] check = {'c','a','t'};
int index = 0;
int[] arr = new int[check.length];
for(int i = 0; i< (s.length()); i++)
{
if(check[index]==s.charAt(i))
{
arr[index++] = i;
}
}
boolean flag = true;
if(index==(check.length))
{
for(int i = 0; i<arr.length-1; i++)
{
int skip = arr[i+1]-arr[i];
if(!((skip>2)&&(skip<100)))
{
flag = false;
}
else
{
System.out.println("Skip Distance : "+skip);
}
}
}
else
{
flag = false;
}
return flag;
}

If you pass in a String, you only need one line:
public static String search(String s, int skipDist) {
return s.replaceAll(".*(c.{2," + skipDist + "}a.{2," + skipDist + "}t)?.*", "$1");
}
If no match found, a blank will be returned.

Related

Palindrome in java

Here what I tried
sample input is "aabaa"
eg: in if condition val[0] = a[4]
if it is equal i stored it in counter variable if it is half of the length it original string it is palindrome
if it is not it is not a palindrome
I tried with my basic knowledge in java if there is any errors let me know
boolean solution(String inputString) {
int val = inputString.length();
int count = 0;
for (int i = 0; i<inputString.length(); i++) {
if(inputString.charAt(i) == inputString.charAt(val-i)) {
count = count++;
if (count>0) {
return true;
}
}
}
return true;
}
How about
public boolean isPalindrome(String text) {
String clean = text.replaceAll("\\s+", "").toLowerCase();
int length = clean.length();
int forward = 0;
int backward = length - 1;
while (backward > forward) {
char forwardChar = clean.charAt(forward++);
char backwardChar = clean.charAt(backward--);
if (forwardChar != backwardChar)
return false;
}
return true;
}
From here
In your version you compare first element with last, second with second last etc.
last element in this case is inputString.length()-1(so need to use 'inputString.charAt(val-i-1)' . If you iterate till end, then the count should be equal to length of the string.
for(int i = 0; i<inputString.length(); i++){
if(inputString.charAt(i) == inputString.charAt(val-i-1)){
count ++;
}
}
return (count==val); //true when count=val
Or alternatlively iterate till the mid point of the array, then count value is val/2.
for(int i = 0; i<inputString.length()/2; i++){
if(inputString.charAt(i) == inputString.charAt(val-i-1)){
count ++;
}
}
return (count==val/2); //true when count=val/2
There's no constraints in the question so let me throw in a more cheesy solution.
boolean isPalindrome(String in)
final String inl = in.toLowerCase();
return new StringBuilder(inl).reverse().toString().equals(inl);
}
A palindrome is a word, sentence, verse, or even a number that reads the same forward and backward. In this java solution, we’ll see how to figure out whether the number or the string is palindrome in nature or not.
Method - 1
class Main {
public static void main(String[] args) {
String str = "Nitin", revStr = "";
int strLen = str.length();
for (int i = (strLen - 1); i >=0; --i) {
revStr = revStr + str.charAt(i);
}
if (str.toLowerCase().equals(revStr.toLowerCase())) {
System.out.println(str + " is a Palindrome String.");
}
else {
System.out.println(str + " is not a Palindrome String.");
}
Method - 2
class Main {
public static void main(String[] args) {
int n = 3553, revNum = 0, rem;
// store the number to the original number
int orgNum = n;
/* get the reverse of original number
store it in variable */
while (n != 0) {
remainder = n % 10;
revNum = revNum * 10 + rem;
n /= 10;
}
// check if reversed number and original number are equal
if (orgNum == revNum) {
System.out.println(orgNum + " is Palindrome.");
}
else {
System.out.println(orgNum + " is not Palindrome.");
}

String index out of range in jva

A string is a palindrome if it is spelled the same way backward and
forward.
Examples of palindromes include “Radar” and “Dammit, I’m mad!”.
Write a java program, PalindromeTester, that asks the user to enter a
word or sentence and then checks whether the entered string is a
palindrome or not.
Spaces, nonalphabetics (.,!:?-()\";), and case within the string have
to be ignored e.g., "Drab as a fool, aloof as a bard." is a
palindrome.
Your implementation should define and use the method isPalindrome to
test if a certain string is a palindrome. The signature of the
isPalindrome method is as follows:
boolean isPalindrome(String)
Following is a sample run of the program. The user’s input is shown in bold.
java PalindromeTester
Introduction to Computer Programming (CMPS 200)
Spring 2015-16 2 of 3
Enter a string: I love CMPS 200
The string "I love CMPS 200" is NOT a palindrome.
This is the code I made, it keeps giving me an error.
I would like to know what my error is and whether there's a faster easier way of writing this code
import java.util.Scanner;
public class PalindromeTester {
public static void main (String args []) {
Scanner console = new Scanner(System.in);
System.out.println("Enter a string: ");
String palindrome = console.next();
if (isPalindrome (palindrome)) {
System.out.print("The string \""+palindrome+" is a palindrome.");
} else {
System.out.print("The string \""+palindrome+" is NOT a palindrome.");
}
}
public static boolean isPalindrome (String palindrome) {
int constant = 1;
for (int i = 0 ; i <= (palindrome.length()-1) ; i++) {
for (int z= (palindrome.length()-1);i >= 0; i--) {
if (palindrome.charAt(i) <'#'||'Z'<palindrome.charAt(i)&&palindrome.charAt(i)<'`'||'['<palindrome.charAt(i)&&palindrome.charAt(i)<'{') {
i=i+1;
}
if (palindrome.charAt(z)<'#'||'Z'<palindrome.charAt(z)&&palindrome.charAt(z)<'`'||'['<palindrome.charAt(z)&&palindrome.charAt(z)<'{') {
z=z+1;
}
if (palindrome.charAt(i)==(palindrome.charAt(z))) {
constant = constant * 1;
} else {
constant = constant * 0;
}
}
}
if (constant == 0 ) {
return false;
} else {
return true;
}
}
}
One approach would be to strip the non alpha characters out of the string. Then check if the string is the same as itself reversed (while upper case):
public static boolean isPalindrome(String palindrome) {
StringBuilder sanitisedString = new StringBuilder();
for(char c : palindrome.toCharArray()) {
if(Character.isLetter(c)) {
sanitisedString.append(c);
}
}
return sanitisedString.toString().toUpperCase().equals(sanitisedString.reverse().toString().toUpperCase());
}
Index out of range is caused by palindrome.charAt(z)) after z = z + 1;
Keep simple :
public static boolean isPalindrome(String palindrome)
{
palindrome = palindrome.replaceAll("\\W", ""); // remove all non word character
palindrome = palindrome.toLowerCase();
int size = palindrome.length();
int halfSize = size / 2;
for (int i = 0; i < halfSize; i++)
{
if(palindrome.charAt(i) != palindrome.charAt(size - i - 1))
return false;
}
return true;
}
Why not just make a new String and save the reversed source(String) in it.
public static boolean readstring(String s)
{
String b = "";
for (int i= s.length() -1; i >=0 ;i--)
{
b = b + s.charAt(i);
}
System.out.print(b +" and "+ s +" ");
return b == s || b.Equals(s);
}
EDIT: Hopefully this meets the requirements, by the way dont use the word "ignore" but "allow"
public boolean isPalindrome(String word) {
int backward = word.length() - 1;
for (int x = 0; x < word.length(); x++) {
if (word.charAt(x)!= word.charAt(backward--)) {
return false;
}
}
return true;
}

Creating a ubbi dubbi detector in java

I am trying to make an ubbi dubbi detector in java. I am currently trying to count how many ub's there are in the string and add them up to a counter and then if there is a certain number under the int I put, then it is not ubbi dubbi, but if it is equal to or above then it is ubbi dubbi. We aren't allowed to use regex, string builder, or arrays.
Here is what I have currently:
public static boolean detect(String phrase) {
boolean isUbbi = false;
int count = 0;
CharSequence ub = "ub";
if (phrase.contains(ub)) {
count++;
}
if (count >= 2) {
isUbbi = true;
} else {
isUbbi = false;
}
return isUbbi;
}
In your case it the condition never met to become true.
Because
if (phrase.contains(ub)) {
count++;
}
And the condition is
if (count >= 2) { // never met. Always false.
That will check the occurrence once and then done.little more implementation is needed to check no of occurrences which involves a loop and sub-string etc..
If you are free to use Apache commons library
use
int count = StringUtils.countMatches(phrase, "ub");
If no libraries ,
String mainString = "ububsdfub";
Pattern pat = Pattern.compile("ub");
Matcher matcher = pat.matcher(mainString);
int count = 0;
while (matcher.find()) {
count += 1;
}
System.out.println(count); // prints 3 since 3 ub's are there.
With basic operation split(internally uses regex)
String mainString = "ububsdfUb";
String occurance = "ub";
System.out.println(mainString.split(occurance, -1).length-1);
Even split not allowed
String mainString = "ububsdfub";
String occurance = "ub";
int index=0;
int count=0;
while ((index = mainString.indexOf(occurance, index)) != -1) {
count++;
index += occurance.length() - 1;
}
System.out.println(count);
You can count the number of occurrences by using String.indexOf(…).
int count=0;
for(int pos=phrase.indexOf(ub); pos>0; pos=phrase.indexOf(ub, pos)+1) count++;
// now count contains the numbers of occurrences of ub in phrase
Here is what I came up with, just added the for loop and all works.
public static boolean detect(String phrase) {
boolean isUbbi = false;
int count = 0;
CharSequence ub = "ub";
for(int i = 0; i < phrase.length(); i++) {
if (phrase.contains(ub)) {
count++;
}
if (count >= 2) {
isUbbi = true;
} else {
isUbbi = false;
}
}
return isUbbi;
}

How to find the longest repeated substring of given string

I am new java and I was given assignment to find the longest substring of a string.
I research online and seems that good way of approaching this problem will be implementing suffix tree.
Please let me know how I can do this or if you have any other solutions. keep in mind this is suppose to be done with low level of java knowledge.
Thanks in adavance.
P.S. the tester string is reassuring.
/**
This method will find the longest substring of a given string.
String given here is reassuring.
*/
public String longestRepeatedSubstring()
{
String longestRepeatedSubstring = "";
for (int i = 0; i<text.length(); i++ )
{
String one = text.substring(0,i);
for(int o = 0; o<text.length();o++)
{
Sting two = text.substring(0,o);
if(one.equals(two))
{
longestRepeatedSubstring = one;
}
}
}
return longestRepeatedSubstring;
}
If you debug your code you will see that you the code isn't doing what you think. AFAIK you need at least three loops and you can't assume you would only start from the first character. Here is one possible solution.
public static void main(String[] args) throws IOException {
String longest = longestDuplicate("ababcaabcabcaab");
System.out.println(longest);
}
public static String longestDuplicate(String text) {
String longest = "";
for (int i = 0; i < text.length() - 2 * longest.length() * 2; i++) {
OUTER:
for (int j = longest.length() + 1; j * 2 < text.length() - i; j++) {
String find = text.substring(i, i + j);
for (int k = i + j; k <= text.length() - j; k++) {
if (text.substring(k, k + j).equals(find)) {
longest = find;
continue OUTER;
}
}
break;
}
}
return longest;
}
prints
abcaab
for "reassuring" it prints r not s which was my first guess. ;)
public static void main(String[] args) {
String str = "testingString";
char[] strArr = str.toCharArray();
StringBuilder bm = new StringBuilder();
boolean isPresent = false;
int len = strArr.length;
int initial =0;
int dinitial=0;
HashMap<String, String> hm = new HashMap<String,String>();
HashMap<String, String> hl = new HashMap<String,String>();
while(initial<=len-1 && !(dinitial>=len-1)){
if(!hm.isEmpty()){
isPresent = hm.containsValue(strArr[initial]+"");
if(!isPresent){
bm.append(strArr[initial]);
hm.put(strArr[initial]+"",strArr[initial]+"");
if(initial==len-1){
System.out.println("Longest substring is::" + bm);
break;
}
}
else if(isPresent){
System.out.println("Longest substring is::" + bm);
bm.delete(0, bm.length());
++dinitial;
initial--;
hm.clear();
}
initial++;
}
else
{
bm.append(strArr[initial]);
hm.put(strArr[initial]+"",strArr[initial]+"");
initial++;
}
}
hm.clear();
}

How to Find the Longest Palindrome (java)

Hi I've been doing this java program, i should input a string and output the longest palindrome that can be found ..
but my program only output the first letter of the longest palindrome .. i badly need your help .. thanks!
SHOULD BE:
INPUT : abcdcbbcdeedcba
OUTPUT : bcdeedcb
There are two palindrome strings : bcdcb and bcdeedcb
BUT WHEN I INPUT : abcdcbbcdeedcba
output : b
import javax.swing.JOptionPane;
public class Palindrome5
{ public static void main(String args[])
{ String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
for(int x=0; x<size; x++)
{ for(int y=x+1; y<size-x; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
Out = GetLongest(subword);
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + Out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
public static String GetLongest(String sWord)
{
int sLength = sWord.length();
String Lpalindrome = "";
int storage = 0;
if(storage<sLength)
{
storage = sLength;
Lpalindrome = sWord;
}
return(Lpalindrome);
}
}
modified program..this program will give the correct output
package pract1;
import javax.swing.JOptionPane;
public class Palindrome5
{
public static void main(String args[])
{
String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
String Lpalindrome = "";
int storage=0;
String out="";
for(int x=0; x<size; x++)
{ for(int y=x+1; y<=size; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
int sLength = subword.length();
if(storage<sLength)
{
storage = sLength;
Lpalindrome = subword;
out=Lpalindrome;
}
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
}
You have two bugs:
1.
for(int y=x+1; y<size-x; y++)
should be
for(int y=x+1; y<size; y++)
since you still want to go all the way to the end of the string. With the previous loop, since x increases throughout the loop, your substring sizes decrease throughout the loop (by removing x characters from their end).
2.
You aren't storing the longest string you've found so far or its length. The code
int storage = 0;
if(storage<sLength) {
storage = sLength;
...
is saying 'if the new string is longer than zero characters, then I will assume it is the longest string found so far and return it as LPalindrome'. That's no help, since we may have previously found a longer palindrome.
If it were me, I would make a static variable (e.g. longestSoFar) to hold the longest palindrome found so far (initially empty). With each new palindrome, check if the new one is longer than longestSoFar. If it is longer, assign it to longestSoFar. Then at the end, display longestSoFar.
In general, if you're having trouble 'remembering' something in the program (e.g. previously seen values) you have to consider storing something statically, since local variables are forgotten once their methods finish.
public class LongestPalindrome {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String S= "abcdcba";
printLongestPalindrome(S);
}
public static void printLongestPalindrome(String S)
{
int maxBack=-1;
int maxFront = -1;
int maxLength=0;
for (int potentialCenter = 0 ; potentialCenter < S.length();potentialCenter ++ )
{
int back = potentialCenter-1;
int front = potentialCenter + 1;
int longestPalindrome = 0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome+1;
maxBack = back + 1;
maxFront = front;
}
back = potentialCenter;
front = potentialCenter + 1;
longestPalindrome=0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome;
maxBack = back + 1;
maxFront = front;
}
}
if (maxLength == 0) System.out.println("There is no Palindrome in the given String");
else{
System.out.println("The Longest Palindrome is " + S.substring(maxBack,maxFront) + "of " + maxLength);
}
}
}
I have my own way to get longest palindrome in a random word. check this out
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.
public class LongestPalindrome {
public static void main(String[] args) {
HashMap<String, Integer> result = findLongestPalindrome("ayrgabcdeedcbaghihg123444456776");
result.forEach((k, v) -> System.out.println("String:" + k + " Value:" + v));
}
private static HashMap<String, Integer> findLongestPalindrome(String str) {
int i = 0;
HashMap<String, Integer> map = new HashMap<String, Integer>();
while (i < str.length()) {
String alpha = String.valueOf(str.charAt(i));
if (str.indexOf(str.charAt(i)) != str.lastIndexOf(str.charAt(i))) {
String pali = str.substring(i, str.lastIndexOf(str.charAt(i)) + 1);
if (isPalindrome(pali)) {
map.put(pali, pali.length());
i = str.lastIndexOf(str.charAt(i));
}
}
i++;
}
return map;
}
public static boolean isPalindrome(String input) {
for (int i = 0; i <= input.length() / 2; i++) {
if (input.charAt(i) != input.charAt(input.length() - 1 - i)) {
return false;
}
}
return true;
}
}
This approach is simple.
Output:
String:abcdeedcba Value:10
String:4444 Value:4
String:6776 Value:4
String:ghihg Value:5
This is my own way to get longest palindrome. this will return the length and the palindrome word
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.

Categories

Resources