user2255502
user2255502

Reputation: 19

Finding Palindromes in a word list

I'm working on a program for Java on how to find a list of palindromes that are embedded in a word list file. I'm in an intro to Java class so any sort of help or guidance will be greatly appreciated!

Here is the code I have so far:

import java.util.Scanner;
import java.io.File;

class Palindromes {

    public static void main(String[] args) throws Exception {
        String pathname = "/users/abrick/resources/american-english-insane";
        File dictionary = new File(pathname);
        Scanner reader = new Scanner(dictionary);
        while (reader.hasNext()) {
            String word = reader.nextLine();
            for (int i = 0; i > word.length(); i++) {
                if (word.charAt(word.indexOf(i) == word.charAt(word.indexOf(i)) - 1) {
                    System.out.println(word);
                }
            }
        }
    }
}

There are 3 words that are 7 letters or longer in the list that I am importing.

Upvotes: 1

Views: 3702

Answers (6)

Sucheta
Sucheta

Reputation: 1

if (word.charAt(word.indexOf(i) == word.charAt(word.length() - 1) { System.out.println(word); }

Need to check first character to last and second to last second. Try this.

Upvotes: 0

Prashant9792
Prashant9792

Reputation: 36

Search Palindrome sting in one world

const input = "aabaaba";

const inputArr = input.split('');
const revereseArr = input.split('').reverse();
 var ans = []
for(var i = 0;inputArr.length > i; i++) {
  var temp = inputArr.slice(i,inputArr.length).join('');
  var temp1 = revereseArr.slice(i,inputArr.length).join('');
  var compare = temp1.split('').reverse().join('');
  //console.log(temp +'=>'+temp1.split('').reverse().join(''))
  if(revereseArr.join('').includes(temp) && temp == compare){
    ans.push(temp);
  }
}

console.log('Out put => '+ ans[0]) 

Upvotes: 0

FuriousFolder
FuriousFolder

Reputation: 1240

Since this is homework, i'll not supply you with code.

When i code, the first thing i do is take a step back and ask myself,

"what am i trying to get the computer to do that i would do myself?"

Ok, so you've got this huuuuge string. Probably something like this: "lkasjdfkajsdf adda aksdjfkasdjf ghhg kajsdfkajsdf oopoo"

etc..

A string's length will either be odd or even. So, first, check that.

The odd/even will be used to figure out how many letters to read in.

If the word is odd, read in ((length-1)/2) characters.

if even (length/2) characters.

Then, compare those characters to the last characters. Notice that you'll need to skip the middle character for an odd-lengthed string. Instead of what you have above, which checks the 1st and 2nd, then 2nd and 3rd, then 3rd and fourth characters, check from the front and back inwards, like so.

        while (reader.hasNext()) {
        String word = reader.nextLine();
          boolean checker = true;

        for (int i = 0; i < word.length(); i++) {
              if(word.length()<2){return;}
            if (word.charAt(i) != word.charAt(word.length()-i)  {
               checker = false;
            }

        }
        if(checker == true)
          {System.out.println(word);}
        }

Upvotes: 0

Piccolo
Piccolo

Reputation: 1666

Let's break the problem down: In the end, you are checking if the reverse of the word is equal to the word. I'm going to assume you have all of the words stored in an array called wordArray[].

I have some code for getting the reverse of the word (copied from here):

public String reverse(String str) {
  if ((null == str) || (str.length() <= 1)) {
    return str;
  }
  return new StringBuffer(str).reverse().toString();
}

So, now we just need to call that on every word. So:

for(int count = 0; count<wordArray.length;count++) {
  String currentWord = wordArray[count];
  if(currentWord.equals(reverse(currentWord)) {
    //it's a palendrome, do something
  }
}

Upvotes: 0

Zim-Zam O&#39;Pootertoot
Zim-Zam O&#39;Pootertoot

Reputation: 18148

I'm assuming that you're reading in strings. Use string.toCharArray() to convert each string to a char[]. Iterate through the character array using a for loop as follows: on iteration 1, if the first character is equal to the last character, then proceed to the next iteration, else return false. On iteration 2, if the second character is equal to the second-to-last character then proceed to the next iteration, else return false. And so on, until you reach the middle of the string, at which point you return true. Be careful of off-by-one errors; some strings will have an even length, some will have an odd length.

If your palindrome checker is case insensitive, then use string.toLowerCase().toCharArray() to preprocess the character array.

You can use string.charAt(i) instead of string.toCharArray() in the for loop; in this case, if the palindrome checker is case insensitive then preprocess the string with string = string.toLowerCase()

Upvotes: 0

Makoto
Makoto

Reputation: 106400

You have a few ways to solve this problem.

A word is considered a palindrome if:

  • It can be read the same way backwards as forwards.
  • The first element is the same as the last element, up until we reach the middle.
  • Half of the word is the same as the other half, reversed.
  • A word of length 1 is trivially a palindrome.

Ultimately, your method isn't doing much of that. In fact, you're not doing any validation at all - you're only printing the word if the first and last character match.

Here's a proposal: Let's read each end of the String, and see if it's a palindrome. We have to take into account the case that it could potentially be empty, or be of length 1. We also want to get rid of any white space in the string, as that can cause errors on validation - we use replaceAll("\\s", "") to solve that.

 public boolean isPalindrome(String theString) {
    if(theString.length() == 0) {
        throw new IllegalStateException("I wouldn't expect a word to be zero-length");
    }
    if(theString.length() == 1) {
        return true;
    } else {
        char[] wordArr = theString.replaceAll("\\s", "").toLowerCase().toCharArray();
        for(int i = 0, j = wordArr.length - 1; i < wordArr.length / 2; i++, j--) {
            if(wordArr[i] != wordArr[j]) {
                return false;
            }
        }
        return true;
    }
}

Upvotes: 1

Related Questions