Related
I've been trying to tweak little bits of code here and there to make my output correct. I am trying to have my code be able to rearrange the letters in a word to make other words that exist in words.txt, from https://github.com/dwyl/english-words. Any help would be appreciated. Thanks.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class WordsInWords {
public static void main(String[] args) throws IOException {
String file = "/Users/laptop/Desktop/Test.txt";
BufferedReader r = new BufferedReader(new FileReader(file));
StringBuilder b = new StringBuilder();
String c = r.readLine();
while (c != null) {
b.append(c);
b.append(" ");
c = r.readLine();
}
Scanner s = new Scanner(System.in);
String in = s.nextLine();
char[] input = new char[in.length()];
for (int i = 0; i < input.length; i++) {
input[i] = in.charAt(i);
}
char[] temp = null;
for (int i = 0; i < b.length(); i++) {
if (i < b.length() - 1 && b.charAt(i) == ' ' && b.charAt(i + 1) != ' ') {
boolean found = false;
int counter = 0;
while (!found) {
counter++;
if (b.charAt(i + counter) == ' ') {
found = true;
temp = new char[counter - 1];
for (int j = i + 1; j < i + counter; j++) {
temp[j] = b.charAt(j);
}
}
}
}
}
if (Arrays.asList(input).contains(temp)) {
System.out.println(temp);
}
}
}
Here is my tweaked code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class WordsInWords {
public static void main(String[] args) throws IOException {
String file = "/Users/laptop/Desktop/words.txt";
BufferedReader r = new BufferedReader(new FileReader(file));
String[] words;
String c = r.readLine();
int a=0;
while (c != null) {
c = r.readLine();
a++;
}
words=new String[a];
a=0;
r = new BufferedReader(new FileReader(file));
String temp=r.readLine();
while (temp != null) {
words[a]=r.readLine();
temp=words[a];
a++;
}
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
Scanner s = new Scanner(System.in);
String input = s.nextLine();
List<String> found = findRearranged(input, words);
System.out.println("For '" + input + "' found: " + Arrays.toString(found.toArray()));
}
public static List<String> findRearranged(String input, String[] words) {
List<String> found = new ArrayList<>();
for (String w : words) {
if (hasSameLetters(w, input)) {
found.add(w);
}
}
return found;
}
public static boolean hasSameLetters(String a, String b) {
if (a.length() != b.length()) {
return false;
}
while (a.length() > 0) {
for (char c : b.toCharArray()) {
int index = a.indexOf(c);
if (index >= 0) {
a = a.replace(String.valueOf(c), "");
} else {
return false;
}
}
}
return true;
}
}
Is rearranging the characters necessary?
Rearranging the input and searching through dictionary to find equal word could take lot's of computing time, single few letter word can have many permutations.
For me, it looks like you want to find the words in dictionary for input word containing same letters (in other words, if the input word would be rearranged, it would give you the existing word in dictionary). Probably checking if both words are having exactly same letters, regardless their position in both strings should satisfy the requirement.
Here's the sample for that approach:
public class Sample {
public static void main(String[] args) {
//the words in dictionary
String[] words = {"words", "sword", "nord", "chord", "score", "cores", "mors", "xyz", "scores", "ordsw"};
String[] input = {"sword", "score", "tores", "nores"};
for (String i : input) {
List<String> found = findRearranged(i, words);
System.out.println("For '" + i + "' found: " + Arrays.toString(found.toArray()));
}
}
public static List<String> findRearranged(String input, String[] words) {
List<String> found = new ArrayList<>();
for (String w : words) {
if (hasSameLetters(w, input)) {
found.add(w);
}
}
return found;
}
public static boolean hasSameLetters(String a, String b) {
if (a.length() != b.length()) {
return false;
}
while (a.length() > 0) {
for (char c : b.toCharArray()) {
int index = a.indexOf(c);
if (index >= 0) {
a = a.replace(String.valueOf(c), "");
} else {
return false;
}
}
}
return true;
}
}
And this outputs in:
For 'sword' found: [words, sword, ordsw]
For 'score' found: [score, cores]
For 'tores' found: []
For 'nores' found: []
Edit:
I see the assumption is that every word is in its own line.
I saw that you already came up with counting the words in the file, but still in that case it's better to use Collections which are having dynamic size.
Here's fixed sample:
public class WordsInWords {
public static void main(String[] args) throws IOException {
String file = "C:\\Users\\masta\\IdeaProjects\\podstawka-spring-java\\words.txt";
BufferedReader r = new BufferedReader(new FileReader(file));
List<String> words = new ArrayList<>();
String c = r.readLine();
while (c != null) {
words.add(c);
c = r.readLine();
}
for (int i = 0; i < words.size(); i++) {
System.out.println("Words: " + words.get(i));
}
Scanner s = new Scanner(System.in);
String input = s.nextLine();
List<String> found = findRearranged(input, words);
System.out.println("For '" + input + "' found: " + Arrays.toString(found.toArray()));
}
public static List<String> findRearranged(String input, List<String> words) {
List<String> found = new ArrayList<>();
for (String w : words) {
if (hasSameLetters(w, input)) {
found.add(w);
}
}
return found;
}
public static boolean hasSameLetters(String a, String b) {
if (a.length() != b.length()) {
return false;
}
while (a.length() > 0) {
for (char c : b.toCharArray()) {
int index = a.indexOf(c);
if (index >= 0) {
a = a.replace(String.valueOf(c), "");
} else {
return false;
}
}
}
return true;
}
}
import java.io.*;
import java.util.*;
public class Solution {
public static final int n = 26;
public int check(String arr) {
if (arr.length() < n) {
return -1;
}
for (char c = 'A'; c <= 'Z'; c++) {
if ((arr.indexOf(c) < 0) && (arr.indexOf((char)(c + 32)) < 0)) {
return -1;
}
}
return 1;
}
}
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
String s = s1.next();
Solution obj = new Solution();
int d = obj.check(s);
if (d == -1) {
System.out.print("not pangram");
} else {
System.out.print("pangram");
}
}
If the string entered is:
We promptly judged antique ivory buckles for the next prize
It will give the wrong output:
not pangram.
I'm not able to find out what wrong with the code.
Thanks in advance!
The problem is that whitespace is a separator for Scanner.next(). So when you input We promptly judged antique ivory buckles for the next prize, s will point just to the string We. When you call obj.check(s) on We it will return -1.
To verify that this is the case, you can print s and check its value. You can also do:
String s = "We promptly judged antique ivory buckles for the next prize";
Call obj.check(s) and see that it will return the correct answer.
To fix it you should call Scanner.nextLine() instead of Scanner.next():
String s = s1.nextLine();
May be program by using set will make solution easier ..:)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class Pangram {
public static void main(String args[]) {
try {
final String str;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
str = br.readLine().toLowerCase().replaceAll(" ", "");
char[] chars = str.toCharArray();
final Set set = new HashSet();
for(char c: chars){
set.add(c);
}
System.out.println(set.size());
if(set.size() == 26)
System.out.println("pangram");
else
System.out.println("not pangram");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Another version:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String sentence = scan.nextLine();
sentence = sentence.toUpperCase();
sentence = sentence.replaceAll("[^A-Z]", "");
char[] chars = sentence.toCharArray();
Set<Character> set = new HashSet<Character>();
for( int i = 0; i < chars.length; i++ ) set.add(chars[i]);
System.out.println(set.size() == 26 ? "pangram" : "not pangram");
}
}
Another Similar Solution for your problem.
public class PangramExample {
public static void main(String[] args) {
String s = "The quick brown fox jumps over the lazy dog";
System.out.println("Is given String Pangram ? : "
+ isPangramString(s.toLowerCase()));
}
private static boolean isPangramString(String s) {
if (s.length() < 26)
return false;
else {
for (char ch = 'a'; ch <= 'z'; ch++) {
if (s.indexOf(ch) < 0) {
return false;
}
}
}
return true;
}
}
for reference , refer this link http://techno-terminal.blogspot.in/2015/11/java-program-to-check-if-given-string.html
import java.io.;
import java.util.;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println(isPangram(input) ? "pangram" : "not pangram");
}
static boolean isPangram(String input) {
boolean isPangram = false;
if(input == null || input.length() < 26) {
return isPangram;
}
input = input.toLowerCase();
char [] charArray = input.toCharArray();
Set<Character> charSet = new HashSet<>();
for(char c : charArray) {
if(Character.isLetter(c) && (!Character.isWhitespace(c))) {
charSet.add(c);
}
}
if (charSet.size() == 26) {
isPangram = true;
}
return isPangram;
}
}
import java.util.Scanner;
public class Pangrams {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int[] a = new int[26];
int count =0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)>=65 && s.charAt(i)<=90){
if(a[s.charAt(i)-65]==0)
count++;
a[s.charAt(i)-65]++;
}
else if(s.charAt(i)>=97 && s.charAt(i)<=122){
if(a[s.charAt(i)-97]==0)
count++;
a[s.charAt(i)-97]++;
}
}
if(count==26)
System.out.println("pangram");
else
System.out.println("not pangram");
}
}
This should fix it:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static boolean isPangram(String test){
for (char a = 'A'; a <= 'Z'; a++)
if ((test.indexOf(a) < 0) && (test.indexOf((char)(a + 32)) < 0))
return false;
return true;
}
public static void main(String[] args)throws IOException {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String test=br.readLine();
if(isPangram(test.toUpperCase())){
System.out.println("pangram");
}if(isPangram(test.toUpperCase())==false){
System.out.println("not pangram");
}
}
}
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
String s;
char f;
Scanner in = new Scanner(System.in);
s = in.nextLine();
char[] charArray = s.toLowerCase().toCharArray();
final Set set = new HashSet();
for (char a : charArray) {
if ((int) a >= 97 && (int) a <= 122) {
f = a;
set.add(f);
}
}
if (set.size() == 26){
System.out.println("pangram");
}
else {
System.out.println("not pangram");
}
}
}
import java.util.Scanner;
public class Pangram {
public static void main(String[] args) {
int count=0;//Initialize counter to zero
char[] arr = new char[26];//Character array of 26 size as there are 26 alphabets
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
for(int i= 0; i<s.length();i++)
{
if(s.charAt(i)>=65 && s.charAt(i)<=90)//Ascii value of A to Z(caps)
{
if(arr[s.charAt(i)-65]==0)
{
count++;
arr[s.charAt(i)-65]=1;
}
}
if(s.charAt(i)>=97 && s.charAt(i)<=122)//Ascii value of a to z
{
if(arr[s.charAt(i)-97]==0)
{
count++;
arr[s.charAt(i)-97]=1;
}
}
}
System.out.println(count);
if(count==26)
{
System.out.println("Pangram");
}
else
System.out.println("not Pangram");
}
}
Another approach of doing this
public boolean isPanGram(String arg)
{
String temp = arg.toLowerCase().replaceAll(" ", "");
String str = String.valueOf(temp.toCharArray());
String[] array = str.split("");
Set<String> tempSet = new TreeSet(Arrays.asList(array));
if(tempSet.size()==26)
{
List loopList = new ArrayList();
loopList.addAll(tempSet);
if(loopList.get(0).equals("a") && loopList.get(25).equals("z"))
return true;
}
return false;
}
Try it
static String pangrams(String s) {
String result="";
String ls = s.toLowerCase();
HashSet<Character> ts=new HashSet<Character>();
for(int i=0;i<ls.length();i++){
if(ls.charAt(i)!=' '){
ts.add(ls.charAt(i));
}
}
if(ts.size()==26){
result="pangram";
}
else{
result="not pangram";
}
return result;
}
Another simple program using HashSet collection.
import java.util.HashSet;
public class Panagram {
public static void main(String[] args) {
pangrams("qmExzBIJmdELxyOFWv LOCmefk TwPhargKSPEqSxzveiun");
}
static String pangrams(String s) {
String inputString = s.toLowerCase();
HashSet<String> toRemoveDuplicates = new HashSet<String>();
for (String eachAlphabet : inputString.split("")) {
toRemoveDuplicates.add(eachAlphabet);
}
// Total alphabets are 26 + one space, so 27.
if (toRemoveDuplicates.size() == 27)
return "panagram";
else
return "not panagram";
}
}
This is a different approach, but easy to understand and write.
First remove all punctuation/whitespace, then drop all duplicated letters.
Finally make sure the modified string has exactly 26 letters.
public class Pangrams {
public static void main(String[] args) {
String s = "The quick brown fox jumps over the lazy dog" //any text
.replaceAll("[^a-zA-Z]+", "") //remove all punctuation and whitespace
if (s.length() < 1 || s.length() > 100)
System.exit(0);
boolean isPangram = false;
char ch;
String modifiedStr = "";
//remove all duplicate letters
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if (ch != ' ') {
modifiedStr += ch;
s = s.replace(ch, ' ');
}
}
//check whether it has exactly 26 letters
if (modifiedStr.length() == 26) {
isPangram = true;
System.out.println("I am a pangram");
}
else System.out.println("I am not a pangram");
}
}
plain Java for loop to detect if string is Pangram:
for (char c = 'a'; c <= 'z'; c++)
if (str.toLowerCase().indexOf(c)== -1)
return false;
Here's a more straight forward approach. It also takes into consideration the repetition of letters, numbers of spaces, tabs and all. You can actually work out with real time sentences. And also if you are a newbie, you won't find this code hard to understand (or i hope so) :)
import java.io.*;
import java.util.*;
public class Solution{
static boolean check(String str){
str=str.toUpperCase();
int count=0;
for(char c='A';c<='Z';c++){
if( (str.indexOf(c)>=0) )
count++;
}
if(count ==26)
return true;
else
return false;
}
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
String s=scan.nextLine();
if(check(s))
System.out.println("pangram");
else
System.out.println("not pangram");
}
}
public class Panagram
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter string ");
String s = sc.nextLine();
System.out.println("given string is :"+"\n" +s);
String st=removeSpace(s);
int d = check(st);
if(d == -1)
System.out.print(s+"\n" + "is not pangram");
else
System.out.print(s+"\n" +"is a pangram");
}
public static String removeSpace(String s)
{
char ch[]=s.toCharArray();
String nstr="";
for (int i = 0; i < s.length(); i++)
{
if (ch[i]!=' ')
{
nstr=nstr + ch[i];
}
}
return nstr;
}
public static int check(String st)
{
int n = 26;
if(s.length() < n){
return -1; }
for(char i = 'A'; i <= 'Z' ; i++){
if((st.indexOf(i) < 0) && (st.indexOf((char)(i + 32)) < 0))
I need to find all the palindromes in a string. It takes user input
example: "abbaalla"
it loops through creating a substring that changes as the loop progresses.
example: checks palindrome "a" (true) "ab"(false) "abb" (false) "abba" (true) and so on..
once it reaches the max length of the word it iterates the start of the substring and repeats
example: check palindrome "b" "bb" "bba" and so on..
I need to change the code so that once it finds the first largest palindrome ("abba") the start of the loop will take place after that substring. so the next palindrome should read "alla"
the final output should be a string that includes all palindromes. in this case;
output: "abba alla"
Also this program currently results in: String index out of range: -1
public static String findAllPalindromes(String input){
int indexStart = 0;
int wordMax = input.length();
int wordLength;
String checkPalindrome;
String allPalindromes = "";
for (wordLength = 2; wordLength <= wordMax; wordLength++) {
//creates a substring to check against isAllPalindrome method
checkPalindrome = input.substring(indexStart, wordLength);
//checks checkPalindrome string to see if it is a palindrome
if (isAllPalindrome(checkPalindrome) == true){
allPalindromes += " " + checkPalindrome;
if (checkPalindrome.length() >= allPalindromes.length()){
allPalindromes = checkPalindrome;
}
}
//once program reads string through once, increment index and scan text again
if (wordLength == wordMax && indexStart < wordMax){
indexStart++;
wordLength = 0;
}
}
System.out.println("The palindromes in the text are: ");
System.out.println(allPalindromes);
return allPalindromes;
}
public static Set<CharSequence> printAllPalindromes(String input) {
if (input.length() <= 2) {
return Collections.emptySet();
}
Set<CharSequence> out = new HashSet<CharSequence>();
int length = input.length();
for (int i = 1; i <= length; i++) {
for (int j = i - 1, k = i; j >= 0 && k < length; j--, k++) {
if (input.charAt(j) == input.charAt(k)) {
out.add(input.subSequence(j, k + 1));
} else {
break;
}
}
}
return out;
}
Simple Brute force way-->
public class AllPalindromes {
public static boolean checkPalindrome(String str) {
for(int i=0;i<=str.length()/2;i++)
if(str.charAt(i)!=str.charAt(str.length()-1-i))
return false;
return true;
}
public static void printAllPalindrome(String str) {
for(int i=0;i<=str.length();i++)
for(int j=i;j<str.length();j++)
if(checkPalindrome(str.substring(i,j+1)))
System.out.println(str.substring(i,j+1));
}
public static void main(String[] args) {
printAllPalindrome("abbaalla");
}
}
Here is the solution which displays all palindromes. (Only those palindromes which are of length greater than 3. You can change the if condition inside the loop if you want to print them all.)
Note that #jw23's solution does not display the palindromes which are of even length — only the odd length ones.
public class HelloWorld{
public static void printPalindromes(String s) {
if (s == null || s.length() < 3)
return;
System.out.println("Odd Length Palindromes:");
// Odd Length Palindromes
for (int i=1; i<s.length()-1; i++) {
for (int j=i-1,k=i+1; j>=0 && k<s.length(); j--,k++) {
if (s.charAt(j) == s.charAt(k)) {
if (k-j+1 >= 3)
System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
}
else
break;
}
}
System.out.println("\nEven Length Palindromes:");
// Even Length Palindromes
for (int i=1; i<s.length()-1; i++) {
for (int j=i,k=i+1; j>=0 && k<s.length(); j--,k++) {
if (s.charAt(j) == s.charAt(k)) {
if (k-j+1 >= 3)
System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
}
else
break;
}
}
}
public static void main(String[] args){
String s = "abcbaaabbaa";
printPalindromes(s);
}
}
public class Palindrome
{
static int count=0;
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String array[]=s1.split("");
System.out.println("Palindromes are :");
for(int i=0;i<=array.length;i++)
{
for(int j=0;j<i;j++)
{
String B=s1.substring(j,i);
verify(B);
}
}
System.out.println("\n"+count);
sc.close();
}
public static void verify(String s1)
{
StringBuilder sb=new StringBuilder(s1);
String s2=sb.reverse().toString();
if(s1.equals(s2))
{
System.out.print(s1+" ");
count++;
}
}
}
My own logic for palindrome program for all substrings
public class Test1 {
public static void main(String[] args) {
String s = "bob";
ArrayList<Character> chr = new ArrayList<Character>();
ArrayList<String> subs= new ArrayList<String>();
for (int i=0;i<s.length();i++)
{
chr.add(s.charAt(i));
}
System.out.println(chr.toString());
StringBuilder subString = new StringBuilder();
for(int i=0; i < s.length();i++)
{
for(int j=i+1;j<s.length();j++)
{
for(int k=i;k<=j;k++)
{
subString.append(chr.get(k));
}
System.out.println(subString.toString());
subs.add(subString.toString());
subString.setLength(0);
}
}
System.out.println(subs);
for(String st : subs)
{
String st2 = new StringBuffer(st).reverse().toString();
if(st.equals(st2))
{
System.out.println(st+" is a palindrome");
}
else
{
System.out.println(st+" not a palindrome");
}
}
}
}
Print All Palindromes in the string
import java.util.*;
class AllPalindroms
{
public static void main(String args[])
{
String input = "abbaalla";
if (input.length() <= 1)
{
System.out.println("Not Palindrome Found.");
}
else
{
int length = input.length();
Set<String> set = new HashSet<String>();
for (int i = 0; i <length; i++)
{
//if(i==0)
for (int j=i+1;j<length+1;j++)
{
String s = input.substring(i, j);
StringBuffer sb = new StringBuffer(s);
sb.reverse();
if(s.equals(sb.toString()) && s.length()>1)
{
set.add(s);
}
}
}
System.out.println(set);
}
}
}
My code to count all palindromes in a string:
import java.util.Scanner;
public class CountPalindromeSapient {
static int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the given string: ");
String inputStr = sc.nextLine();
countPalindrome(inputStr);
System.out.println("\nTotal count of Palindromes are: "+count);
sc.close();
}
private static int countPalindrome(String inputStr) {
int count = 0;
int len = inputStr.length();
int startIndex =0;
String subString = "";
System.out.println( "Possible substrings are: ");
for (int i = 0; i < len; i++) {
for (int j = startIndex; j <= len; j++) {
subString = inputStr.substring(startIndex, j);
System.out.println(subString);
count = checkPalindrome(subString);
}
startIndex++;
}
return count;
}
private static int checkPalindrome(String subString) {
// TODO Auto-generated method stub
int subLen = subString.length();
boolean isPalindrome = false;
for(int k=0; k<subLen; k++,subLen-- ) { // Important
if (subString.charAt(k) != subString.charAt(subLen -1)) {
isPalindrome = false;
break;
}else {
isPalindrome = true;
}
}
if(isPalindrome == true) {
count ++;
}
return count;
}
}
class StringTest {
public static void main(String[] args) {
StringTest test = new StringTest();
boolean bool = test.checkPalindrom("abbaalla");
if(!bool)
System.out.println("String is not palindrom");
}
private boolean checkPalindrom(String k){
int[] count= new int[k.length()];
boolean[] arr = new boolean[k.length()];
for(int t=0;t<k.length();t++){
int j=0;
char ch = k.charAt(t);
for(int x=t+1;x<k.length();x++){
if(j<count.length){
if(ch == k.charAt(x))
count[j] = x + 1;
else
count[j] = 0;
j++;
}
}
arr[t] = workOnArr(count,t,k);
}
for(int z=0;z<arr.length;z++){
if(arr[z])
return true;
}
return false;
}
private boolean workOnArr(int[] s,int z,String w){
int j = s.length - 1;
while(j -- > 0){
if(s[j] != 0){
if(isPalindrom(w.substring(z, s[j]))){
if(w.substring(z, s[j]).length() > 1){
System.out.println(w.substring(z, s[j]).length());
System.out.println(w.substring(z, s[j]));
}
return true;
}
}
}
return false;
}
private boolean isPalindrom(String s){
int j= s.length() -1;
for(int i=0;i<s.length()/2;i++){
if(s.charAt(i) != s.charAt(j))
return false;
j--;
}
return true;
}
}
output:-
given palindrom are:-
abba, bb, aa, alla, ll
Question: All the palindromes from a word.
public class Test4 {
public static void main(String[] args) {
String a = "ProtijayiMeyeMADAMGiniiniGSoudiptaGina";
allpalindromicsubstrings(a);
}// main
private static void allpalindromicsubstrings(String a) {
Set<String> set = new HashSet<String>();
for (int i = 0; i < a.length(); i++) {
// odd length palindrome
expand(a, i, i, set);
// even length palindrome
expand(a, i, i + 1, set);
} // for
set.parallelStream().filter(words -> words.length() > 1).distinct().forEach(System.out::println);
}// ee
private static void expand(String a, int start, int last, Set<String> set) {
// run till a[start...last] is a palindrome
while (start >= 0 && last <= a.length() - 1 && a.charAt(start) == a.charAt(last)) {
set.add(a.substring(start, last + 1));
// expand in both directions
start--;
last++;
}
}// ee
}
The output palindromes in the word =>
niin
ADA
eye
MADAM
iniini
GiniiniG
ii
MeyeM
ini
Print all the palindromes in a string:
public class test1 {
public static void main(String[] args) {
String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
System.out.println(list);
List<String> plist = new ArrayList<>();
for(int i = 0 ; i <list.size();i++) {
String curr =list.get(i);
if(ispalin(curr)) {plist.add(curr);}
}//for
System.out.println("palindrome list => " +plist);
}//main
private static boolean ispalin(String curr) {
if(curr == null || curr.length() == 0) {return false;}
return new StringBuffer(curr).reverse().toString().equals(curr);
}
}
The output is: palindrome list => [MADAM, GiniiniG]
Another Method in Java 8:
public class B {
public static void main(String[] args) {
String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
// list to stream
// for Multi Threaded environment
Stream<String> stream = list.parallelStream();
// also,Stream<String> stream = list.stream(); for single Threaded environment
long palindrome = stream.filter(B::isPalindrome)// find all palindromes
.peek(System.out::println) // write each match
.count();// terminal - return a count
System.out.println("Count of palindromes: " + palindrome);
// System.out.println("List => " + list);
}
private static boolean isPalindrome(String aa) {
return new StringBuffer(aa).reverse().toString().equals(aa);
}
}
Output:
GiniiniG
MADAM
Count of palindromes: 2
Java program to enter a string and frame a word by joining all the first character of each word.
Display a new word.
import java.util.*;
public class Anshu {
public static void main(String args[]) {
Scanner in = new Scanner(System.in)
System.out.println("Enter a string");
String s = in .nextLine();
char ch = s.charAt(0);
System.out.print(ch);
s = s.toUpperCase;
int l = s.length();
for (int i = 0; i < l; i++)
char a = s.charAt(i);
if (Character.isWhiteSpace())
System.out.print(s.charAt(i + 1) + "");
}
}
What I am trying to do is have it take a java file that look like this
public class test1 {
public static void main ( string[] args ) {
System.out.println( "This is Test 1." );
}
}
And it is suppose to output a text file with the proper spacing and indents.
So far I can get the correct indenting for the first the lines. But I am having trouble with my second for loop that prints the spaces for the ending brackets. The ending brackets are prints outward like the first 3 lines instead of inward. Sorry if my variables are confusing.
Here is my code so far
public class JavaJustifier {
public static void main( String[] args )
throws FileNotFoundException {
for( int i = 1; i < 6; i++ ) {
justifyJava( "Test" + i + ".java",
"Justified" + i + ".txt",
4 );
}
}
public static void justifyJava( String inputFileName,
String outputFileName,
int tabSize )
throws FileNotFoundException {
int counter = 0;
int counter2 = 0;
int blah = 0;
File f = new File(inputFileName);
File p = new File(outputFileName);
if (p.exists())
p.delete();
Scanner input = new Scanner (f);
PrintStream name = new PrintStream(new File(outputFileName));
while (input.hasNextLine()) {
String line = input.nextLine();
Scanner lineScan = new Scanner(line);
if (line.contains("{") == true) {
name.print("{\r\n");
counter++;
for (int i = 1; i <= counter; i++) {
for (int j = 0; j <= tabSize; j++) {
name.print(" ");
}
}
System.out.println(counter);
} else if (line.contains("}") == true) {
name.print("\r\n");
counter--;
for (int x = 1; x <= counter; x++) {
for (int y = 1; y <= tabSize; y++) {
name.print(" ");
}
}
name.print("}");
System.out.println(counter);
} else {
name.print(line);
}
}
}
What it gives me is
public class Test1
{
public static void main( String[] args )
{
System.out.println( "This is Test 1." );
}
}
What I desire is this
public class Test1
{
public static void main( String[] args )
{
System.out.println( "This is Test 1." );
}
}
Okay, I've refactored a few things (and it was necessary) but it works exactly as you expect it to (AFAIK!).
Here's the code:
public class JavaJustifier {
static int counter = 0;
static int tabSize = 4;
public static void main(String[] args) throws FileNotFoundException {
justifyJava("Test1.java", "Justified1.txt");
}
private static void processLine(PrintStream name, String line) {
if (line.contains("{")) {
String preText = line.substring(0, line.indexOf("{"));
String postText = line.substring(line.indexOf("{") + 1)
.replaceAll("\\n", "").replaceAll("\\r\\n", "");
printSpaces(name);
name.println(preText);
printSpaces(name);
name.println("{");
counter++;
processLine(name, postText);
} else if (line.contains("}")) {
String preText = line.substring(0, line.indexOf("}"));
String postText = line.substring(line.indexOf("}") + 1)
.replaceAll("\\n", "").replaceAll("\\r\\n", "");
name.println(preText);
counter--;
printSpaces(name);
name.println("}");
processLine(name, postText);
} else {
if (!line.equals("\r\n") && line.length() != 0) {
printSpaces(name);
name.print(line);
}
}
}
private static void printSpaces(PrintStream p) {
for (int i = 1; i <= counter; i++) {
for (int j = 0; j <= tabSize; j++) {
p.print(" ");
}
}
}
public static void justifyJava(String inputFileName, String outputFileName)
throws FileNotFoundException {
File f = new File(inputFileName);
File p = new File(outputFileName);
if (p.exists())
p.delete();
Scanner input = new Scanner(f);
PrintStream name = new PrintStream(new File(outputFileName));
while (input.hasNextLine()) {
String line = input.nextLine().trim();
processLine(name, line);
}
}
}
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.