count repeat of every word - java

I want to write a code that count repeat of every word in a string,words separate each other with some character that input as a string...why my code don't work?
please answer soon!
public class repeat {
public static void main(String[] args) {
Scanner ss = new Scanner(System.in);
System.out.println("Please write a string:");
String s = ss.nextLine();
System.out.println("Please write a character:");
String w = ss.nextLine();
int i = 0;
int j = 0;
int k = 0;
int y=0;
for (i=0 ;i < s.length() ;i++) {
for (j = 0; j < w.length(); j++) {
if (w.charAt(j) == s.charAt(i) && i!=y && i!=0 && i!=s.length() -1 ) {
k += 1;
y=i+1;
}
}
}
i = 0;
j = 0;
y = 0;
int r = 0;
k++;
System.out.println(k);
String[] a = new String[k];
for (r=0 ;r < k-1 ;r++) {
for (j=1 ;j < s.length() ;j++) {
for (i = 1; i < w.length(); i++) {
if (w.charAt(i) == s.charAt(j)) {
a[r] = s.substring(y, j);
y = j+1;
}
}
}
System.out.println(a[r]);
}
a[k-1] = s.substring(y+1,s.length());
i = 0;
int[] b = new int[k];
while (i <k) {
b[i] = 0;
i++;
}
i = j = 0;
while (i < k) {
while (j != i && j < k) {
if (a[i] == a[j]) {
a[j] = null;
b[i]++;
}
j++;
}
i++;
}
i = j = 0;
while (i < k) {
if (a[i] != null) {
System.out.println(a[i] + " " + b[i]);
}
i++;
}
}
}

Looking through your code your taking a very long approach to this problem. The easiest thing to do is use regex https://docs.oracle.com/javase/tutorial/essential/regex/. Please see the methods below.
public Sentence(String sentanceString) {
this.fullSentence = sentanceString;
breakStringIntoWords(sentanceString);
}
private void breakStringIntoWords(String sentanceString) {
String[] wordsInString = sentanceString.split("\\W+");
for (String word : wordsInString) {
words.add(new Word(word));
}
}
In the second method I broke a sentence (delimited by [spaces]) into words. From here you would write code to compare each word (a class that has a to string method so treat it as a string) to every other word in the Words array list, be careful to avoid over counting.

ok this is now Java with Split instead of searching the string manually:
I don't exactly know if the copyarray is the best practice to make it larger but if your string is not megabytes large it won't be a problem:
public class repeat
{
public static void main(String[] args)
{
String s = "Hello world this is a very good test to a world just that contains just more words than just hello";
String w = " ";
String[] foundwords = new String[0];
int[] wordcount = new int[0];
String[] splittext = s.split(w);
for (int i = 0; i< splittext.length; i++)
{
int IndexOfWord = getIndexOfWord(splittext[i], foundwords);
if (IndexOfWord < 0)
{
String[] foundwordsTemp = new String[foundwords.length + 1];
int[] wordcountTemp = new int[foundwords.length + 1];
System.arraycopy(foundwords, 0, foundwordsTemp, 0, foundwords.length);
System.arraycopy(wordcount, 0, wordcountTemp, 0, foundwords.length);
foundwords = new String[foundwords.length + 1];
wordcount = new int[wordcount.length + 1];
System.arraycopy(foundwordsTemp, 0, foundwords, 0, foundwordsTemp.length);
System.arraycopy(wordcountTemp, 0, wordcount, 0, foundwordsTemp.length);
foundwords[foundwords.length-1] = splittext[i];
wordcount[foundwords.length-1] = 1;
}
else
{
wordcount[IndexOfWord]++;
}
}
for (int i = 0; i < foundwords.length; i++)
{
System.out.println(String.format("Found word '%s' %d times.", foundwords[i], wordcount[i]));
}
}
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
}

(Wrong language i did it wrongly in c# - see next answer for java)
I suggest to use array and Split for this because it is very complicated work with substring to seach for the char. While w still is a String, c need to be a type char.
String[] foundwords = { };
Int32[] wordcount = { };
foreach (String word in s.Split(w))
{
int IndexOfWord = Array.IndexOf(foundwords, word);
if (IndexOfWord < 0)
{
Array.Resize(ref foundwords, foundwords.Length + 1);
Array.Resize(ref wordcount, wordcount.Length + 1);
foundwords[foundwords.GetUpperBound(0)] = word;
wordcount[foundwords.GetUpperBound(0)] = 1;
}
else
{
wordcount[IndexOfWord]++;
}
}
for (int i = 0; i <= foundwords.GetUpperBound(0); i++)
{
Console.WriteLine(String.Format("Found word '{0}' {1} times.", foundwords[i], wordcount[i]));
}
be aware that it is case sensitive.

so if it is still on your list i made a code.
First - you where lost to just let it run in the main procedure only. You should start and seperate your work into single tasks instead of writing a strait start stop program. Using functions with a "good" name will make it easier to you in future.
First you need something to find the String in another.
Usually you may use
int dividerPosition = restString.indexOf(searchString);
this is a java build in function. If you want to write it yourself, you could create a function like this (that will do the same but you can "see" it working:)
private static int indexOf(String restString, String searchString)
{
int dividerPosition = -1;
for (int i = 0; i < restString.length()-searchString.length(); i++)
{
// Debuging test:
System.out.println(String.format("search Pos %d in '%s' for length %d.", i, restString, searchString.length()));
if (restString.substring(i, i + searchString.length()).equals(searchString))
{
dividerPosition = i;
i = restString.length();
}
}
return dividerPosition;
}
and use this function in your code later on like:
int dividerPosition = indexOf(restString, searchString);
I will again use the function to find either a word is allready known
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
Third Task would be to Split and count the Words at the found position.
The easier way (only my opinion) would be just to cut of the found Words from the String - so write a function that will "save" the found word in a array or count the "counter"-Array if it is allready found.
This most important task to understand is important - ok we will just look for the position of the string we are searching. We need to check if it is not found (so the last word)
We will store the found word (that is the part before the found String) in a variable and do the "count or create new word" thing. And then we will return the String cut of the word and the Seach-String.
The Cut-Off is important because we replace the origin String by the one without the first word and just repeat this until the origin String is "".
For the last word we ensure the function will return "" by changing the dividerPosition to the length of the RestString - that is the last word now only - minus "searchString.length()" so it will fit to the return "restString.substring(dividerPosition+searchString.length());" to return ""
Look in the next part into the function named "getNextW("
you can run int with the self-written IndexOf function or the Java function by changing the commentlines in
/// Index Of Search (better)
//int dividerPosition = restString.indexOf(searchString);
/// Manual Search (why make it more difficuilt - you should learn to make your work as easy as possible)
int dividerPosition = indexOf(restString, searchString);
Everything together
to get startet you will have very little code in the main procedure using the "cut" function until the String is empty - all together now:
public class repeat
{
public static void main(String[] args)
{
String s = "Hello a world a this is a very good test to a a a a world just that contains just more words than just hello";
String w = " ";
while (!(s = getNextW(s, w)).equals(""))
{
System.out.println(s);
}
System.out.println("");
for (int i = 0; i < foundwords.length; i++)
{
// Debuging test:
System.out.println(String.format("Found word '%s' %d times.", foundwords[i], wordcount[i]));
}
}
private static String[] foundwords = new String[0];
private static int[] wordcount = new int[0];
private static String getNextW(String restString, String searchString)
{
/// Index Of Search (better)
//int dividerPosition = restString.indexOf(searchString);
/// Manual Search (why make it more difficuilt - you should learn to make your work as easy as possible)
int dividerPosition = indexOf(restString, searchString);
String foundWord;
if (dividerPosition > 0)
{
foundWord = restString.substring(0, dividerPosition);
}
else
{
foundWord = restString;
dividerPosition = restString.length()-searchString.length();
}
int IndexOfWord = getIndexOfWord(foundWord, foundwords);
if (IndexOfWord < 0)
{
String[] foundwordsTemp = new String[foundwords.length + 1];
int[] wordcountTemp = new int[foundwords.length + 1];
System.arraycopy(foundwords, 0, foundwordsTemp, 0, foundwords.length);
System.arraycopy(wordcount, 0, wordcountTemp, 0, foundwords.length);
foundwords = new String[foundwords.length + 1];
wordcount = new int[wordcount.length + 1];
System.arraycopy(foundwordsTemp, 0, foundwords, 0, foundwordsTemp.length);
System.arraycopy(wordcountTemp, 0, wordcount, 0, foundwordsTemp.length);
foundwords[foundwords.length-1] = foundWord;
wordcount[foundwords.length-1] = 1;
}
else
{
wordcount[IndexOfWord]++;
}
// Debuging test:
System.out.println(String.format("Rest of String is '%s' positionnext is %d.", restString, dividerPosition));
return restString.substring(dividerPosition+searchString.length());
}
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
private static int indexOf(String restString, String searchString)
{
int dividerPosition = -1;
for (int i = 0; i < restString.length()-searchString.length(); i++)
{
// Debuging test:
System.out.println(String.format("search Pos %d in '%s' for length %d.", i, restString, searchString.length()));
if (restString.substring(i, i + searchString.length()).equals(searchString))
{
dividerPosition = i;
i = restString.length();
}
}
return dividerPosition;
}
}
Other variant with charAt and im am using your kind of "count words to size the array" what will result in a to big array (potentially far to big):
public class repeat
{
private static String[] foundwords;
private static int[] wordcount;
private static int counter;
public static void main(String[] args) {
String s = "Hello a world a this is a very good test to a a a a world just that contains just more words than just hello";
String w = " ";
int tempPos = 0;
counter = 1; // counting total w-strings+1 for dim
while ((tempPos = findnext(s, w, tempPos)) >= 0)
{
tempPos = tempPos + w.length();
counter++;
}
foundwords = new String[counter];
wordcount = new int[counter];
counter = 0;
while ((tempPos = findnext(s, w, 0)) >= 0)
{
String foundWord = s.substring(0, tempPos);
s = s.substring(tempPos + w.length());
foundWordToArray(foundWord);
}
foundWordToArray(s);
for (int i = 0; i < counter; i++)
{
System.out.println(String.format("Found word '%s' %d times.", foundwords[i], wordcount[i]));
}
}
public static int findnext(String haystack, String needle, int startPos)
{
int hpos, npos;
for (hpos = startPos; hpos < haystack.length()-needle.length(); hpos++)
{
for (npos = 0; npos < needle.length(); npos++)
{
if (haystack.charAt(hpos+npos)!=needle.charAt(npos))
{
npos = needle.length()+1;
}
}
if (npos == needle.length())
{
return hpos;
}
}
return -1;
}
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
private static void foundWordToArray(String foundWord)
{
int IndexOfWord = getIndexOfWord(foundWord, foundwords);
if (IndexOfWord < 0)
{
foundwords[counter] = foundWord;
wordcount[counter] = 1;
counter++;
}
else
{
wordcount[IndexOfWord]++;
}
}
}
i like this one:
public class repeat
{
private static String[] foundwords = new String[0];
private static int[] wordcount = new int[0];
public static void main(String[] args) {
String s = "Hello a world a this is a very good test to a a a a world just that contains just more words than just hello";
String w = " ";
int tempPos;
while ((tempPos = findnext(s, w, 0)) >= 0)
{
String foundWord = s.substring(0, tempPos);
s = s.substring(tempPos + w.length());
foundWordToArray(foundWord);
}
foundWordToArray(s);
for (int i = 0; i < foundwords.length; i++)
{
System.out.println(String.format("Found word '%s' %d times.", foundwords[i], wordcount[i]));
}
}
private static void foundWordToArray(String foundWord)
{
int IndexOfWord = getIndexOfWord(foundWord, foundwords);
if (IndexOfWord < 0)
{
String[] foundwordsTemp = new String[foundwords.length + 1];
int[] wordcountTemp = new int[foundwords.length + 1];
System.arraycopy(foundwords, 0, foundwordsTemp, 0, foundwords.length);
System.arraycopy(wordcount, 0, wordcountTemp, 0, foundwords.length);
foundwords = new String[foundwords.length + 1];
wordcount = new int[wordcount.length + 1];
System.arraycopy(foundwordsTemp, 0, foundwords, 0, foundwordsTemp.length);
System.arraycopy(wordcountTemp, 0, wordcount, 0, foundwordsTemp.length);
foundwords[foundwords.length-1] = foundWord;
wordcount[foundwords.length-1] = 1;
}
else
{
wordcount[IndexOfWord]++;
}
}
public static int findnext(String haystack, String needle, int startPos)
{
int hpos, npos;
for (hpos = startPos; hpos < haystack.length()-needle.length(); hpos++)
{
for (npos = 0; npos < needle.length(); npos++)
{
if (haystack.charAt(hpos+npos)!=needle.charAt(npos))
{
npos = needle.length()+1;
}
}
if (npos == needle.length())
{
return hpos;
}
}
return -1;
}
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
}

Related

Is there a way to iterate through an array without using loops?

I'm trying to write a code that will output all possible passwords from a given array recursively,
e.g. given the input
"ab"
will output the next:
a
b
aa
ab
ba
bb
the problem is that I'm instructed to use only one loop in the crack() function below and that's it. I cannot use any other functions, just those two.
This is what I've got so far:
import java.util.*;
public class PasswordGen {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a string:");
char array[] = sc.next().toCharArray();
System.out.println("All Combination:");
crack(array);
sc.close();
}
static void crack(char[] array) {
for (int i = 1; i <= array.length; i++) {
generate(array, i, "", array.length);
}
}
static void generate(char[] array, int i, String string, int length) {
//recursion stopping if condition is meet
if (i == 0) {
System.out.println(string);
return;
}
for (int j = 0; j < length; j++) {
String charArray = string + array[j];
generate(array, i -1, charArray , length);
}
return;
}
}
Is there a way to get the same output without using the for loop in the generate() function?
(see code below).
static void generate(char[] array, int i, String string, int length) {
//recursion stopping if condition is meet
if (i == 0) {
System.out.println(string);
return;
}
for (int j = 0; j < length; j++) {
String charArray = string + array[j];
generate(array, i -1, charArray , length);
}
Any suggestions/better way to do it?
Not sure if this answers your question, but here is a class that does what you want without any for loop:
import java.util.*;
import java.util.stream.*;
class Bruteforcer {
private List<Integer> state = Collections.singletonList(0);
private final String allowedChars;
private final Integer maxLength;
public Bruteforcer(String allowedChars, Integer maxLength){
assert allowedChars != null;
assert allowedChars.length() > 0;
assert maxLength > 0;
this.allowedChars = allowedChars;
this.maxLength = maxLength;
}
public String next(){
final var allIndexesAreLastChar = this.state.stream().allMatch(i -> i == this.allowedChars.length() - 1);
final var currentLength = this.state.size();
if (currentLength > this.maxLength){
return null;
}
final var nextPassword = this.state.stream()
.map(i -> this.allowedChars.substring(i, i + 1))
.collect(Collectors.joining(""));
if (allIndexesAreLastChar){
this.state = Collections.nCopies(currentLength + 1, 0);
return nextPassword;
}
this.state = IntStream.range(0, currentLength)
.mapToObj(i -> {
final var current = this.state.get(currentLength - 1 - i);
final var mustIncrement = i == 0 || this.state.get(currentLength - i) == this.allowedChars.length() - 1;
if (mustIncrement){
return current == this.allowedChars.length() - 1 ? 0 : current + 1;
}
return current;
})
.collect(Collectors.toList());
Collections.reverse(this.state);
return nextPassword;
}
}
class FindPasswordApplication {
public static void main(String[] args) {
final var bruteforcer = new Bruteforcer("ab", 2);
for (var i = 0; i < 10; i ++){
final var password = bruteforcer.next();
System.out.println(password);
}
}
}

Efficient/Fast way to get permutation of a String in java [duplicate]

What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer string such as abcdefgh? Is there any Java implementation example?
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
(via Introduction to Programming in Java)
Use recursion.
Try each of the letters in turn as the first letter and then find all the permutations of the remaining letters using a recursive call.
The base case is when the input is an empty string the only permutation is the empty string.
Here is my solution that is based on the idea of the book "Cracking the Coding Interview" (P54):
/**
* List permutations of a string.
*
* #param s the input string
* #return the list of permutations
*/
public static ArrayList<String> permutation(String s) {
// The result
ArrayList<String> res = new ArrayList<String>();
// If input string's length is 1, return {s}
if (s.length() == 1) {
res.add(s);
} else if (s.length() > 1) {
int lastIndex = s.length() - 1;
// Find out the last character
String last = s.substring(lastIndex);
// Rest of the string
String rest = s.substring(0, lastIndex);
// Perform permutation on the rest string and
// merge with the last character
res = merge(permutation(rest), last);
}
return res;
}
/**
* #param list a result of permutation, e.g. {"ab", "ba"}
* #param c the last character
* #return a merged new list, e.g. {"cab", "acb" ... }
*/
public static ArrayList<String> merge(ArrayList<String> list, String c) {
ArrayList<String> res = new ArrayList<>();
// Loop through all the string in the list
for (String s : list) {
// For each string, insert the last character to all possible positions
// and add them to the new list
for (int i = 0; i <= s.length(); ++i) {
String ps = new StringBuffer(s).insert(i, c).toString();
res.add(ps);
}
}
return res;
}
Running output of string "abcd":
Step 1: Merge [a] and b:
[ba, ab]
Step 2: Merge [ba, ab] and c:
[cba, bca, bac, cab, acb, abc]
Step 3: Merge [cba, bca, bac, cab, acb, abc] and d:
[dcba, cdba, cbda, cbad, dbca, bdca, bcda, bcad, dbac, bdac, badc, bacd, dcab, cdab, cadb, cabd, dacb, adcb, acdb, acbd, dabc, adbc, abdc, abcd]
Of all the solutions given here and in other forums, I liked Mark Byers the most. That description actually made me think and code it myself.
Too bad I cannot voteup his solution as I am newbie.
Anyways here is my implementation of his description
public class PermTest {
public static void main(String[] args) throws Exception {
String str = "abcdef";
StringBuffer strBuf = new StringBuffer(str);
doPerm(strBuf,0);
}
private static void doPerm(StringBuffer str, int index){
if(index == str.length())
System.out.println(str);
else { //recursively solve this by placing all other chars at current first pos
doPerm(str, index+1);
for (int i = index+1; i < str.length(); i++) {//start swapping all other chars with current first char
swap(str,index, i);
doPerm(str, index+1);
swap(str,i, index);//restore back my string buffer
}
}
}
private static void swap(StringBuffer str, int pos1, int pos2){
char t1 = str.charAt(pos1);
str.setCharAt(pos1, str.charAt(pos2));
str.setCharAt(pos2, t1);
}
}
I prefer this solution ahead of the first one in this thread because this solution uses StringBuffer. I wouldn't say my solution doesn't create any temporary string (it actually does in system.out.println where the toString() of StringBuffer is called). But I just feel this is better than the first solution where too many string literals are created. May be some performance guy out there can evalute this in terms of 'memory' (for 'time' it already lags due to that extra 'swap')
A very basic solution in Java is to use recursion + Set ( to avoid repetitions ) if you want to store and return the solution strings :
public static Set<String> generatePerm(String input)
{
Set<String> set = new HashSet<String>();
if (input == "")
return set;
Character a = input.charAt(0);
if (input.length() > 1)
{
input = input.substring(1);
Set<String> permSet = generatePerm(input);
for (String x : permSet)
{
for (int i = 0; i <= x.length(); i++)
{
set.add(x.substring(0, i) + a + x.substring(i));
}
}
}
else
{
set.add(a + "");
}
return set;
}
All the previous contributors have done a great job explaining and providing the code. I thought I should share this approach too because it might help someone too. The solution is based on (heaps' algorithm )
Couple of things:
Notice the last item which is depicted in the excel is just for helping you better visualize the logic. So, the actual values in the last column would be 2,1,0 (if we were to run the code because we are dealing with arrays and arrays start with 0).
The swapping algorithm happens based on even or odd values of current position. It's very self explanatory if you look at where the swap method is getting called.You can see what's going on.
Here is what happens:
public static void main(String[] args) {
String ourword = "abc";
String[] ourArray = ourword.split("");
permute(ourArray, ourArray.length);
}
private static void swap(String[] ourarray, int right, int left) {
String temp = ourarray[right];
ourarray[right] = ourarray[left];
ourarray[left] = temp;
}
public static void permute(String[] ourArray, int currentPosition) {
if (currentPosition == 1) {
System.out.println(Arrays.toString(ourArray));
} else {
for (int i = 0; i < currentPosition; i++) {
// subtract one from the last position (here is where you are
// selecting the the next last item
permute(ourArray, currentPosition - 1);
// if it's odd position
if (currentPosition % 2 == 1) {
swap(ourArray, 0, currentPosition - 1);
} else {
swap(ourArray, i, currentPosition - 1);
}
}
}
}
Let's use input abc as an example.
Start off with just the last element (c) in a set (["c"]), then add the second last element (b) to its front, end and every possible positions in the middle, making it ["bc", "cb"] and then in the same manner it will add the next element from the back (a) to each string in the set making it:
"a" + "bc" = ["abc", "bac", "bca"] and "a" + "cb" = ["acb" ,"cab", "cba"]
Thus entire permutation:
["abc", "bac", "bca","acb" ,"cab", "cba"]
Code:
public class Test
{
static Set<String> permutations;
static Set<String> result = new HashSet<String>();
public static Set<String> permutation(String string) {
permutations = new HashSet<String>();
int n = string.length();
for (int i = n - 1; i >= 0; i--)
{
shuffle(string.charAt(i));
}
return permutations;
}
private static void shuffle(char c) {
if (permutations.size() == 0) {
permutations.add(String.valueOf(c));
} else {
Iterator<String> it = permutations.iterator();
for (int i = 0; i < permutations.size(); i++) {
String temp1;
for (; it.hasNext();) {
temp1 = it.next();
for (int k = 0; k < temp1.length() + 1; k += 1) {
StringBuilder sb = new StringBuilder(temp1);
sb.insert(k, c);
result.add(sb.toString());
}
}
}
permutations = result;
//'result' has to be refreshed so that in next run it doesn't contain stale values.
result = new HashSet<String>();
}
}
public static void main(String[] args) {
Set<String> result = permutation("abc");
System.out.println("\nThere are total of " + result.size() + " permutations:");
Iterator<String> it = result.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
This one is without recursion
public static void permute(String s) {
if(null==s || s.isEmpty()) {
return;
}
// List containing words formed in each iteration
List<String> strings = new LinkedList<String>();
strings.add(String.valueOf(s.charAt(0))); // add the first element to the list
// Temp list that holds the set of strings for
// appending the current character to all position in each word in the original list
List<String> tempList = new LinkedList<String>();
for(int i=1; i< s.length(); i++) {
for(int j=0; j<strings.size(); j++) {
tempList.addAll(merge(s.charAt(i), strings.get(j)));
}
strings.removeAll(strings);
strings.addAll(tempList);
tempList.removeAll(tempList);
}
for(int i=0; i<strings.size(); i++) {
System.out.println(strings.get(i));
}
}
/**
* helper method that appends the given character at each position in the given string
* and returns a set of such modified strings
* - set removes duplicates if any(in case a character is repeated)
*/
private static Set<String> merge(Character c, String s) {
if(s==null || s.isEmpty()) {
return null;
}
int len = s.length();
StringBuilder sb = new StringBuilder();
Set<String> list = new HashSet<String>();
for(int i=0; i<= len; i++) {
sb = new StringBuilder();
sb.append(s.substring(0, i) + c + s.substring(i, len));
list.add(sb.toString());
}
return list;
}
Well here is an elegant, non-recursive, O(n!) solution:
public static StringBuilder[] permutations(String s) {
if (s.length() == 0)
return null;
int length = fact(s.length());
StringBuilder[] sb = new StringBuilder[length];
for (int i = 0; i < length; i++) {
sb[i] = new StringBuilder();
}
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
int times = length / (i + 1);
for (int j = 0; j < times; j++) {
for (int k = 0; k < length / times; k++) {
sb[j * length / times + k].insert(k, ch);
}
}
}
return sb;
}
One of the simple solution could be just keep swapping the characters recursively using two pointers.
public static void main(String[] args)
{
String str="abcdefgh";
perm(str);
}
public static void perm(String str)
{ char[] char_arr=str.toCharArray();
helper(char_arr,0);
}
public static void helper(char[] char_arr, int i)
{
if(i==char_arr.length-1)
{
// print the shuffled string
String str="";
for(int j=0; j<char_arr.length; j++)
{
str=str+char_arr[j];
}
System.out.println(str);
}
else
{
for(int j=i; j<char_arr.length; j++)
{
char tmp = char_arr[i];
char_arr[i] = char_arr[j];
char_arr[j] = tmp;
helper(char_arr,i+1);
char tmp1 = char_arr[i];
char_arr[i] = char_arr[j];
char_arr[j] = tmp1;
}
}
}
python implementation
def getPermutation(s, prefix=''):
if len(s) == 0:
print prefix
for i in range(len(s)):
getPermutation(s[0:i]+s[i+1:len(s)],prefix+s[i] )
getPermutation('abcd','')
This is what I did through basic understanding of Permutations and Recursive function calling. Takes a bit of time but it's done independently.
public class LexicographicPermutations {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="abc";
List<String>combinations=new ArrayList<String>();
combinations=permutations(s);
Collections.sort(combinations);
System.out.println(combinations);
}
private static List<String> permutations(String s) {
// TODO Auto-generated method stub
List<String>combinations=new ArrayList<String>();
if(s.length()==1){
combinations.add(s);
}
else{
for(int i=0;i<s.length();i++){
List<String>temp=permutations(s.substring(0, i)+s.substring(i+1));
for (String string : temp) {
combinations.add(s.charAt(i)+string);
}
}
}
return combinations;
}}
which generates Output as [abc, acb, bac, bca, cab, cba].
Basic logic behind it is
For each character, consider it as 1st character & find the combinations of remaining characters. e.g. [abc](Combination of abc)->.
a->[bc](a x Combination of (bc))->{abc,acb}
b->[ac](b x Combination of (ac))->{bac,bca}
c->[ab](c x Combination of (ab))->{cab,cba}
And then recursively calling each [bc],[ac] & [ab] independently.
Use recursion.
when the input is an empty string the only permutation is an empty string.Try for each of the letters in the string by making it as the first letter and then find all the permutations of the remaining letters using a recursive call.
import java.util.ArrayList;
import java.util.List;
class Permutation {
private static List<String> permutation(String prefix, String str) {
List<String> permutations = new ArrayList<>();
int n = str.length();
if (n == 0) {
permutations.add(prefix);
} else {
for (int i = 0; i < n; i++) {
permutations.addAll(permutation(prefix + str.charAt(i), str.substring(i + 1, n) + str.substring(0, i)));
}
}
return permutations;
}
public static void main(String[] args) {
List<String> perms = permutation("", "abcd");
String[] array = new String[perms.size()];
for (int i = 0; i < perms.size(); i++) {
array[i] = perms.get(i);
}
int x = array.length;
for (final String anArray : array) {
System.out.println(anArray);
}
}
}
this worked for me..
import java.util.Arrays;
public class StringPermutations{
public static void main(String args[]) {
String inputString = "ABC";
permute(inputString.toCharArray(), 0, inputString.length()-1);
}
public static void permute(char[] ary, int startIndex, int endIndex) {
if(startIndex == endIndex){
System.out.println(String.valueOf(ary));
}else{
for(int i=startIndex;i<=endIndex;i++) {
swap(ary, startIndex, i );
permute(ary, startIndex+1, endIndex);
swap(ary, startIndex, i );
}
}
}
public static void swap(char[] ary, int x, int y) {
char temp = ary[x];
ary[x] = ary[y];
ary[y] = temp;
}
}
Java implementation without recursion
public Set<String> permutate(String s){
Queue<String> permutations = new LinkedList<String>();
Set<String> v = new HashSet<String>();
permutations.add(s);
while(permutations.size()!=0){
String str = permutations.poll();
if(!v.contains(str)){
v.add(str);
for(int i = 0;i<str.length();i++){
String c = String.valueOf(str.charAt(i));
permutations.add(str.substring(i+1) + c + str.substring(0,i));
}
}
}
return v;
}
Let me try to tackle this problem with Kotlin:
fun <T> List<T>.permutations(): List<List<T>> {
//escape case
if (this.isEmpty()) return emptyList()
if (this.size == 1) return listOf(this)
if (this.size == 2) return listOf(listOf(this.first(), this.last()), listOf(this.last(), this.first()))
//recursive case
return this.flatMap { lastItem ->
this.minus(lastItem).permutations().map { it.plus(lastItem) }
}
}
Core concept: Break down long list into smaller list + recursion
Long answer with example list [1, 2, 3, 4]:
Even for a list of 4 it already kinda get's confusing trying to list all the possible permutations in your head, and what we need to do is exactly to avoid that. It is easy for us to understand how to make all permutations of list of size 0, 1, and 2, so all we need to do is break them down to any of those sizes and combine them back up correctly. Imagine a jackpot machine: this algorithm will start spinning from the right to the left, and write down
return empty/list of 1 when list size is 0 or 1
handle when list size is 2 (e.g. [3, 4]), and generate the 2 permutations ([3, 4] & [4, 3])
For each item, mark that as the last in the last, and find all the permutations for the rest of the item in the list. (e.g. put [4] on the table, and throw [1, 2, 3] into permutation again)
Now with all permutation it's children, put itself back to the end of the list (e.g.: [1, 2, 3][,4], [1, 3, 2][,4], [2, 3, 1][, 4], ...)
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class hello {
public static void main(String[] args) throws IOException {
hello h = new hello();
h.printcomp();
}
int fact=1;
public void factrec(int a,int k){
if(a>=k)
{fact=fact*k;
k++;
factrec(a,k);
}
else
{System.out.println("The string will have "+fact+" permutations");
}
}
public void printcomp(){
String str;
int k;
Scanner in = new Scanner(System.in);
System.out.println("enter the string whose permutations has to b found");
str=in.next();
k=str.length();
factrec(k,1);
String[] arr =new String[fact];
char[] array = str.toCharArray();
while(p<fact)
printcomprec(k,array,arr);
// if incase u need array containing all the permutation use this
//for(int d=0;d<fact;d++)
//System.out.println(arr[d]);
}
int y=1;
int p = 0;
int g=1;
int z = 0;
public void printcomprec(int k,char array[],String arr[]){
for (int l = 0; l < k; l++) {
for (int b=0;b<k-1;b++){
for (int i=1; i<k-g; i++) {
char temp;
String stri = "";
temp = array[i];
array[i] = array[i + g];
array[i + g] = temp;
for (int j = 0; j < k; j++)
stri += array[j];
arr[z] = stri;
System.out.println(arr[z] + " " + p++);
z++;
}
}
char temp;
temp=array[0];
array[0]=array[y];
array[y]=temp;
if (y >= k-1)
y=y-(k-1);
else
y++;
}
if (g >= k-1)
g=1;
else
g++;
}
}
/** Returns an array list containing all
* permutations of the characters in s. */
public static ArrayList<String> permute(String s) {
ArrayList<String> perms = new ArrayList<>();
int slen = s.length();
if (slen > 0) {
// Add the first character from s to the perms array list.
perms.add(Character.toString(s.charAt(0)));
// Repeat for all additional characters in s.
for (int i = 1; i < slen; ++i) {
// Get the next character from s.
char c = s.charAt(i);
// For each of the strings currently in perms do the following:
int size = perms.size();
for (int j = 0; j < size; ++j) {
// 1. remove the string
String p = perms.remove(0);
int plen = p.length();
// 2. Add plen + 1 new strings to perms. Each new string
// consists of the removed string with the character c
// inserted into it at a unique location.
for (int k = 0; k <= plen; ++k) {
perms.add(p.substring(0, k) + c + p.substring(k));
}
}
}
}
return perms;
}
Here is a straightforward minimalist recursive solution in Java:
public static ArrayList<String> permutations(String s) {
ArrayList<String> out = new ArrayList<String>();
if (s.length() == 1) {
out.add(s);
return out;
}
char first = s.charAt(0);
String rest = s.substring(1);
for (String permutation : permutations(rest)) {
out.addAll(insertAtAllPositions(first, permutation));
}
return out;
}
public static ArrayList<String> insertAtAllPositions(char ch, String s) {
ArrayList<String> out = new ArrayList<String>();
for (int i = 0; i <= s.length(); ++i) {
String inserted = s.substring(0, i) + ch + s.substring(i);
out.add(inserted);
}
return out;
}
We can use factorial to find how many strings started with particular letter.
Example: take the input abcd. (3!) == 6 strings will start with every letter of abcd.
static public int facts(int x){
int sum = 1;
for (int i = 1; i < x; i++) {
sum *= (i+1);
}
return sum;
}
public static void permutation(String str) {
char[] str2 = str.toCharArray();
int n = str2.length;
int permutation = 0;
if (n == 1) {
System.out.println(str2[0]);
} else if (n == 2) {
System.out.println(str2[0] + "" + str2[1]);
System.out.println(str2[1] + "" + str2[0]);
} else {
for (int i = 0; i < n; i++) {
if (true) {
char[] str3 = str.toCharArray();
char temp = str3[i];
str3[i] = str3[0];
str3[0] = temp;
str2 = str3;
}
for (int j = 1, count = 0; count < facts(n-1); j++, count++) {
if (j != n-1) {
char temp1 = str2[j+1];
str2[j+1] = str2[j];
str2[j] = temp1;
} else {
char temp1 = str2[n-1];
str2[n-1] = str2[1];
str2[1] = temp1;
j = 1;
} // end of else block
permutation++;
System.out.print("permutation " + permutation + " is -> ");
for (int k = 0; k < n; k++) {
System.out.print(str2[k]);
} // end of loop k
System.out.println();
} // end of loop j
} // end of loop i
}
}
//insert each character into an arraylist
static ArrayList al = new ArrayList();
private static void findPermutation (String str){
for (int k = 0; k < str.length(); k++) {
addOneChar(str.charAt(k));
}
}
//insert one char into ArrayList
private static void addOneChar(char ch){
String lastPerStr;
String tempStr;
ArrayList locAl = new ArrayList();
for (int i = 0; i < al.size(); i ++ ){
lastPerStr = al.get(i).toString();
//System.out.println("lastPerStr: " + lastPerStr);
for (int j = 0; j <= lastPerStr.length(); j++) {
tempStr = lastPerStr.substring(0,j) + ch +
lastPerStr.substring(j, lastPerStr.length());
locAl.add(tempStr);
//System.out.println("tempStr: " + tempStr);
}
}
if(al.isEmpty()){
al.add(ch);
} else {
al.clear();
al = locAl;
}
}
private static void printArrayList(ArrayList al){
for (int i = 0; i < al.size(); i++) {
System.out.print(al.get(i) + " ");
}
}
//Rotate and create words beginning with all letter possible and push to stack 1
//Read from stack1 and for each word create words with other letters at the next location by rotation and so on
/* eg : man
1. push1 - man, anm, nma
2. pop1 - nma , push2 - nam,nma
pop1 - anm , push2 - amn,anm
pop1 - man , push2 - mna,man
*/
public class StringPermute {
static String str;
static String word;
static int top1 = -1;
static int top2 = -1;
static String[] stringArray1;
static String[] stringArray2;
static int strlength = 0;
public static void main(String[] args) throws IOException {
System.out.println("Enter String : ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader bfr = new BufferedReader(isr);
str = bfr.readLine();
word = str;
strlength = str.length();
int n = 1;
for (int i = 1; i <= strlength; i++) {
n = n * i;
}
stringArray1 = new String[n];
stringArray2 = new String[n];
push(word, 1);
doPermute();
display();
}
public static void push(String word, int x) {
if (x == 1)
stringArray1[++top1] = word;
else
stringArray2[++top2] = word;
}
public static String pop(int x) {
if (x == 1)
return stringArray1[top1--];
else
return stringArray2[top2--];
}
public static void doPermute() {
for (int j = strlength; j >= 2; j--)
popper(j);
}
public static void popper(int length) {
// pop from stack1 , rotate each word n times and push to stack 2
if (top1 > -1) {
while (top1 > -1) {
word = pop(1);
for (int j = 0; j < length; j++) {
rotate(length);
push(word, 2);
}
}
}
// pop from stack2 , rotate each word n times w.r.t position and push to
// stack 1
else {
while (top2 > -1) {
word = pop(2);
for (int j = 0; j < length; j++) {
rotate(length);
push(word, 1);
}
}
}
}
public static void rotate(int position) {
char[] charstring = new char[100];
for (int j = 0; j < word.length(); j++)
charstring[j] = word.charAt(j);
int startpos = strlength - position;
char temp = charstring[startpos];
for (int i = startpos; i < strlength - 1; i++) {
charstring[i] = charstring[i + 1];
}
charstring[strlength - 1] = temp;
word = new String(charstring).trim();
}
public static void display() {
int top;
if (top1 > -1) {
while (top1 > -1)
System.out.println(stringArray1[top1--]);
} else {
while (top2 > -1)
System.out.println(stringArray2[top2--]);
}
}
}
Another simple way is to loop through the string, pick the character that is not used yet and put it to a buffer, continue the loop till the buffer size equals to the string length. I like this back tracking solution better because:
Easy to understand
Easy to avoid duplication
The output is sorted
Here is the java code:
List<String> permute(String str) {
if (str == null) {
return null;
}
char[] chars = str.toCharArray();
boolean[] used = new boolean[chars.length];
List<String> res = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
Arrays.sort(chars);
helper(chars, used, sb, res);
return res;
}
void helper(char[] chars, boolean[] used, StringBuilder sb, List<String> res) {
if (sb.length() == chars.length) {
res.add(sb.toString());
return;
}
for (int i = 0; i < chars.length; i++) {
// avoid duplicates
if (i > 0 && chars[i] == chars[i - 1] && !used[i - 1]) {
continue;
}
// pick the character that has not used yet
if (!used[i]) {
used[i] = true;
sb.append(chars[i]);
helper(chars, used, sb, res);
// back tracking
sb.deleteCharAt(sb.length() - 1);
used[i] = false;
}
}
}
Input str: 1231
Output list: {1123, 1132, 1213, 1231, 1312, 1321, 2113, 2131, 2311, 3112, 3121, 3211}
Noticed that the output is sorted, and there is no duplicate result.
Recursion is not necessary, even you can calculate any permutation directly, this solution uses generics to permute any array.
Here is a good information about this algorihtm.
For C# developers here is more useful implementation.
public static void main(String[] args) {
String word = "12345";
Character[] array = ArrayUtils.toObject(word.toCharArray());
long[] factorials = Permutation.getFactorials(array.length + 1);
for (long i = 0; i < factorials[array.length]; i++) {
Character[] permutation = Permutation.<Character>getPermutation(i, array, factorials);
printPermutation(permutation);
}
}
private static void printPermutation(Character[] permutation) {
for (int i = 0; i < permutation.length; i++) {
System.out.print(permutation[i]);
}
System.out.println();
}
This algorithm has O(N) time and space complexity to calculate each permutation.
public class Permutation {
public static <T> T[] getPermutation(long permutationNumber, T[] array, long[] factorials) {
int[] sequence = generateSequence(permutationNumber, array.length - 1, factorials);
T[] permutation = generatePermutation(array, sequence);
return permutation;
}
public static <T> T[] generatePermutation(T[] array, int[] sequence) {
T[] clone = array.clone();
for (int i = 0; i < clone.length - 1; i++) {
swap(clone, i, i + sequence[i]);
}
return clone;
}
private static int[] generateSequence(long permutationNumber, int size, long[] factorials) {
int[] sequence = new int[size];
for (int j = 0; j < sequence.length; j++) {
long factorial = factorials[sequence.length - j];
sequence[j] = (int) (permutationNumber / factorial);
permutationNumber = (int) (permutationNumber % factorial);
}
return sequence;
}
private static <T> void swap(T[] array, int i, int j) {
T t = array[i];
array[i] = array[j];
array[j] = t;
}
public static long[] getFactorials(int length) {
long[] factorials = new long[length];
long factor = 1;
for (int i = 0; i < length; i++) {
factor *= i <= 1 ? 1 : i;
factorials[i] = factor;
}
return factorials;
}
}
My implementation based on Mark Byers's description above:
static Set<String> permutations(String str){
if (str.isEmpty()){
return Collections.singleton(str);
}else{
Set <String> set = new HashSet<>();
for (int i=0; i<str.length(); i++)
for (String s : permutations(str.substring(0, i) + str.substring(i+1)))
set.add(str.charAt(i) + s);
return set;
}
}
Permutation of String:
public static void main(String args[]) {
permu(0,"ABCD");
}
static void permu(int fixed,String s) {
char[] chr=s.toCharArray();
if(fixed==s.length())
System.out.println(s);
for(int i=fixed;i<s.length();i++) {
char c=chr[i];
chr[i]=chr[fixed];
chr[fixed]=c;
permu(fixed+1,new String(chr));
}
}
Here is another simpler method of doing Permutation of a string.
public class Solution4 {
public static void main(String[] args) {
String a = "Protijayi";
per(a, 0);
}
static void per(String a , int start ) {
//bse case;
if(a.length() == start) {System.out.println(a);}
char[] ca = a.toCharArray();
//swap
for (int i = start; i < ca.length; i++) {
char t = ca[i];
ca[i] = ca[start];
ca[start] = t;
per(new String(ca),start+1);
}
}//per
}
A java implementation to print all the permutations of a given string considering duplicate characters and prints only unique characters is as follow:
import java.util.Set;
import java.util.HashSet;
public class PrintAllPermutations2
{
public static void main(String[] args)
{
String str = "AAC";
PrintAllPermutations2 permutation = new PrintAllPermutations2();
Set<String> uniqueStrings = new HashSet<>();
permutation.permute("", str, uniqueStrings);
}
void permute(String prefixString, String s, Set<String> set)
{
int n = s.length();
if(n == 0)
{
if(!set.contains(prefixString))
{
System.out.println(prefixString);
set.add(prefixString);
}
}
else
{
for(int i=0; i<n; i++)
{
permute(prefixString + s.charAt(i), s.substring(0,i) + s.substring(i+1,n), set);
}
}
}
}
String permutaions using Es6
Using reduce() method
const permutations = str => {
if (str.length <= 2)
return str.length === 2 ? [str, str[1] + str[0]] : [str];
return str
.split('')
.reduce(
(acc, letter, index) =>
acc.concat(permutations(str.slice(0, index) + str.slice(index + 1)).map(val => letter + val)),
[]
);
};
console.log(permutations('STR'));
In case anyone wants to generate the permutations to do something with them, instead of just printing them via a void method:
static List<int[]> permutations(int n) {
class Perm {
private final List<int[]> permutations = new ArrayList<>();
private void perm(int[] array, int step) {
if (step == 1) permutations.add(array.clone());
else for (int i = 0; i < step; i++) {
perm(array, step - 1);
int j = (step % 2 == 0) ? i : 0;
swap(array, step - 1, j);
}
}
private void swap(int[] array, int i, int j) {
int buffer = array[i];
array[i] = array[j];
array[j] = buffer;
}
}
int[] nVector = new int[n];
for (int i = 0; i < n; i++) nVector [i] = i;
Perm perm = new Perm();
perm.perm(nVector, n);
return perm.permutations;
}

The longest common subsequence for n string in java without using libraries?

I am trying to find a simple solution and I have read all the information or question that try to answer or have solve the problem , and i have being testing.
I have found a solution which i converted from c#, and it works, but is too complicated and i do not understand how it works, so i was trying to make my own solution.
public static String lcs(String[] strings) {
if (strings.length == 0)
return "0";
if (strings.length == 1)
return strings[0];
int max = -1;//max length of a string
int cacheSize = 1; //multiplied length size of array with each other.
for (int i = 0; i < strings.length; i++) {
cacheSize *= strings[i].length();
if (strings[i].length() > max)
max = strings[i].length();
}
String[] cache = new String[cacheSize];
int[] indexes = new int[strings.length];
for (int i = 0; i < indexes.length; i++)
indexes[i] = strings[i].length() - 1;
return lcsBack(strings, indexes, cache);
}
public static String lcsBack(String[] strings, int[] indexes, String[] cache) {
for (int i = 0; i < indexes.length; i++)
if (indexes[i] == -1)
return "";
boolean match = true;
for (int i = 1; i < indexes.length; i++) {
if (strings[0].charAt(indexes[0]) != strings[i].charAt(indexes[i])) {
match = false;
break;
}
}
if (match) {
int[] newIndexes = new int[indexes.length];
for (int i = 0; i < indexes.length; i++)
newIndexes[i] = indexes[i] - 1;
String result = lcsBack(strings, newIndexes, cache) + strings[0].charAt(indexes[0]);
cache[calcCachePos(indexes, strings)] = result;
return result;
} else {
String[] subStrings = new String[strings.length];
for (int i = 0; i < strings.length; i++) {
if (indexes[i] <= 0)
subStrings[i] = "";
else {
int[] newIndexes = new int[indexes.length];
for (int j = 0; j < indexes.length; j++)
newIndexes[j] = indexes[j];
newIndexes[i]--;
int cachePos = calcCachePos(newIndexes, strings);
if (cache[cachePos] == null)
subStrings[i] = lcsBack(strings, newIndexes, cache);
else
subStrings[i] = cache[cachePos];
}
}
String longestString = "";
int longestlength = 0;
for (int i = 0; i < subStrings.length; i++) {
if (subStrings[i].length() > longestlength) {
longestString = subStrings[i];
longestlength = longestString.length();
}
}
cache[calcCachePos(indexes, strings)] = longestString;
return longestString;
}
}
static int calcCachePos(int[] indexes, String[] strings) {
int factor = 1;
int pos = 0;
for (int i = 0; i < indexes.length; i++) {
pos += indexes[i] * factor;
factor *= strings[i].length();
}
return pos;
}
So on what i understand i have being able, to make this method which is simple, but still doesn't work.
And i know from readings that the best way to solve this is using dinamic programming I would appreciate if somebody can help, thank you
/**
* #param strArr .
* #return String
*/
public String findCommonString(String[] words) throws Exception {
try {
String commonStr = "";
String tempCom = "";
char[] longestWordChars = findTheLongestString(words).toCharArray();
for (char c : longestWordChars) {
tempCom += c;
for (String word : words) {
if (!word.contains(tempCom)) {
tempCom = Character.toString(c);
for (String word2 : words) {
if (!word2.contains(tempCom)) {
tempCom = "";
break;
}
}
break;
}
}
if (tempCom != "" && tempCom.length()>commonStr.length()) {
commonStr = tempCom;
//strArr = removeFirstOccurrence(strArr, tempCom);
// tempCom = "";
}
}
return commonStr;
} catch (Exception e) {
logger.warn("[findCommonString] [STATUS] - ERROR ");
logger.warn("[findCommonString] [EXCEPTION] " + e.getMessage());
throw e;
}
/**
* #param strArr .
* #return String
*/
public String findTheLongestString(String[] words) throws Exception { // test
try {
String longestWord = "";
for (String s : words) {
if (longestWord.length() < s.length()) {
longestWord = s;
}
}
return longestWord;
} catch (Exception e) {
logger.warn("[findTheLongestString] [STATUS] - ERROR ");
logger.warn("[findTheLongestString] [EXCEPTION] " + e.getMessage());
throw e;
}
}
I have being testing with this two test unit example
#Test
public void SubsequenceServiceTest3() throws Exception {
assertEquals("CDAC", subsequenceService.findCommonSequence(new String[] { "BCDAACD", "ACDBAC" }));
}
#Test
public void SubsequenceServiceTest14() throws Exception {
assertEquals("CA", subsequenceService.findCommonSequence(new String[] { "ACADB", "CBDA" }));
}

Maximum Repeating characters and count

I wanted to get the maximum repeating characters count and its relevant index. I am able to print the max repeating characters in a given string and its index. However I am unable to print the total count of repeating character. Below is my code
public class MaxRepeating {
static char charactercountIndex(String str) {
int len = str.length();
int count = 0;
char res = str.charAt(0);
for (int i = 0; i < len; i++) {
int cur_count = 0;
for (int j = i + 1; j < len; j++) {
if (str.charAt(i) != str.charAt(j))
break;
cur_count++;
}
if (cur_count > count) {
count = cur_count;
res = str.charAt(i);
}
}
return res;
}
public static void main(String args[]) {
String str = "aaaaaaccde";
char s1 = charactercountIndex(str);
str.indexOf(s1);
System.out.println(str.indexOf(s1));
System.out.println(charactercountIndex(str));
}
}
output should <0,6>
0 is the index of character a
6 is the total time character "a" present in the string
If you are open to a slightly different approach, there is a fairly straightforward way to do this using regex and streams. We can try splitting the input string into like-lettered substring components using the following regex:
(?<=(.))(?!\\1)
Then, we can use Collections.max to find the largest string in the collection, and finally use String#indexOf to find the index of that substring.
String str = "aaaabbddddddddddddddddddddaaccde";
List<String> parts = Arrays.asList(str.split("(?<=(.))(?!\\1)"));
String max = Collections.max(parts, Comparator.comparing(s -> s.length()));
System.out.println("largest substring: " + max);
int index = str.indexOf(max);
System.out.println("index of largest substring: " + index);
largest substring: dddddddddddddddddddd
index of largest substring: 6
I've done something like this:
static Entry<String, Integer> charactercountIndex(String str) {
HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
for (String letter : str.split("")) {
if (stringIntegerHashMap.containsKey(letter)) {
stringIntegerHashMap.put(letter, (stringIntegerHashMap.get(letter) + 1));
} else {
stringIntegerHashMap.put(letter, 1);
}
}
Entry<String, Integer> maxEntry = null;
for (Entry<String, Integer> entry : stringIntegerHashMap.entrySet()) {
if (maxEntry == null
|| entry.getValue().compareTo(maxEntry.getValue()) > 0) {
maxEntry = entry;
}
}
return maxEntry;
}
public static void main(String args[]) {
String str = "aaaabbddddddddddddddddddddaaccde";
Entry<String, Integer> s1 = charactercountIndex(str);
System.out.println(s1.getKey());
System.out.println(s1.getValue());
}
If you have any trouble, let me know.
You can return the result through a local class instance (which contains both the character and its occurrences). I added a local class CountResult.
By the way, I fixed your code (see // including ... comment).
You can try and check the working code below here.
public class MaxRepeating {
private static CountResult charactercountIndex(String str) {
int len = str.length();
char res = str.charAt(0);
int count = 0;
for (int i = 0; i < len; i++) {
int cur_count = 1; // including the tested char (first occurence)
for (int j = i + 1; j < len; j++) {
if (str.charAt(i) != str.charAt(j))
break;
cur_count++;
}
if (cur_count > count) {
res = str.charAt(i);
count = cur_count;
}
}
return new CountResult(res, count);
}
private static class CountResult {
private char maxChar;
private int count;
public CountResult(char maxChar, int count) {
this.maxChar = maxChar;
this.count = count;
}
public String toString() {
return String.format("<" + maxChar + "," + count + ">");
}
}
public static void main(String args[]) {
String str = "aaaaaaccde";
System.out.println(charactercountIndex(str));
}
}
You can create your own class that you will not be bounded to count of returned parameters from method.
public class MyCharacter {
private static int count;
private static char character;
private static int indexOf;
public void characterCountIndex(String str) {
int len = str.length();
for (int i = 0; i < len; i++) {
int cur_count = 1;
for (int j = i + 1; j < len; j++) {
if (str.charAt(i) != str.charAt(j))
break;
cur_count++;
}
if (cur_count > count) {
count = cur_count;
character = str.charAt(i);
indexOf = str.indexOf(character);
}
}
}
#Override
public String toString() {
return String.format("<%d, %d>", indexOf, count);
}
public static void main(String[] args) {
String str = "aaaaaaccde";
MyCharacter myCharacter = new MyCharacter();
myCharacter.characterCountIndex(str);
System.out.println(myCharacter);
}
}

Write a method to print a string with words reversed, without the use of any standard functions [duplicate]

This question already has answers here:
Printing reverse of any String without using any predefined function?
(34 answers)
Closed 8 years ago.
I was asked this in a technical interview. I have no idea whatsoever please please help me.
it goes in infinite loop. I just cant find the correct logic.
not once, but twice i came across this kind of a question, so please help
public static int numberOfCharsInString(String sentence)
{
int numberOfChars = 0,i=0;
while (!sentence.equals(""))
{
sentence = sentence.substring(1);
++numberOfChars;
}
return numberOfChars;
}
public static void reverseSequenceOfWords(String inp)
{
int len=numberOfCharsInString(inp);
char[] in=inp.toCharArray();
int i=0;
for(i=len-1;i>=0;i--)
{
if(in[i]==' ')
{
while(!in.equals("")||in.equals(" "))
{
System.out.print(in[i]+" ");
}
}
else if(in[i]=='\0')
{
break;
}
}
}
public static void main(String[] args)
{
int length=0;
String inpstring = "";
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
try
{
System.out.print("Enter a string to reverse:");
inpstring = reader.readLine();
length=numberOfCharsInString(inpstring);
System.out.println("Number of Characters: "+length);
reverseSequenceOfWords(inpstring);
}
catch (Exception e)
{
e.printStackTrace();
}
}
String[] array = "Are you crazy".split(" ");
for (int i = array.length - 1; i >= 0; --i) {
System.out.print(array[i] + " ");
}
Brute forced this so hard lol
public static void main (String args[]){
String input = new Scanner(System.in).nextLine();
input+=" ";
ArrayList<String> words = new ArrayList<String>();
int start = 0;
for(int i=0; i<input.length(); i++){
if(input.charAt(i)==' '){
String toAdd="";
for(int r=start; r<i; r++){
toAdd+=input.charAt(r);
}
words.add(toAdd);
start = i+1;
}
}
for(int i=words.size()-1; i>=0; i--){
System.out.print(words.get(i)+" ");
}
}
I've used String.length() and String.substring()and String.charAt() - I hope that is allowed.
private static class Word {
private final String message;
private final int start;
private final int end;
public Word(String message, int start, int end) {
this.message = message;
this.start = start;
this.end = end;
}
#Override
public String toString() {
return message.substring(start, end);
}
}
private Word[] split(String message) {
// Split it into words - there cannot be more words than characters in the message.
int[] spaces = new int[message.length()];
// How many words.
int nWords = 0;
// Pretend there's a space at the start.
spaces[0] = -1;
// Walk the message.
for (int i = 0; i < message.length(); i++) {
if (message.charAt(i) == ' ') {
spaces[++nWords] = i;
}
}
// Record the final position.
spaces[++nWords] = message.length();
// Build the word array.
Word[] words = new Word[nWords];
for (int i = 0; i < nWords; i++) {
words[i] = new Word(message, spaces[i] + 1, spaces[i + 1]);
}
return words;
}
private String reverse(String message) {
Word[] split = split(message);
String reversed = "";
for ( int i = split.length - 1; i >= 0; i--) {
reversed += split[i].toString();
if ( i > 0 ) {
reversed += " ";
}
}
return reversed;
}
public void test() {
String message = "Hello how are you today?";
System.out.println(reverse(message));
}
prints
today? you are how Hello
Much more minimal but less useful. Only uses length, charAt and substring again:
public void printWordsReversed(String message) {
int end = message.length();
for ( int i = end - 1; i >= 0; i--) {
if ( message.charAt(i) == ' ') {
System.out.print(message.substring(i+1, end)+" ");
end = i;
}
}
System.out.print(message.substring(0, end));
}
The only function i'm still using is the IndexOf function, but that is not that hard to create for yourself.
static void Main(string[] args)
{
string sentence = "are you cracy";
int length = Program.StringLength(sentence);
int currentpos = 0;
List<string> wordList = new List<string>();
int wordCount = 0;
while (currentpos < length)
{
// find the next space
int spacepos = sentence.IndexOf(' ', currentpos);
string word;
if (spacepos < 0)
{
// end of string reached.
word = sentence.Substring(currentpos, length - currentpos);
wordList.Add(word);
wordCount++;
// no need to continue.
break;
}
word = sentence.Substring(currentpos, spacepos - currentpos);
wordList.Add(word);
wordCount++;
currentpos = spacepos + 1;
}
// display
for (int i = wordList.Count - 1; i >= 0; i--)
{
// after first word is display, add spaces to the output
if (i < wordList.Count - 1)
{
Console.WriteLine(" ");
}
// display word
Console.WriteLine(wordList[i]);
}
}
public static int StringLength(String sentence)
{
int numberOfChars = 0;
while (!sentence.Equals(""))
{
sentence = sentence.Substring(1);
++numberOfChars;
}
return numberOfChars;
}

Categories