Recursively computing all possible permutations of a string Java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to compute all possible permutations of a given string using recursion in Java. However, I don't know what's wrong with my code.
Here's my algorithm:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
//base case
if (str.length() == 1)
perms.add(str);
else {
//loop over the string
for (int i = 0; i < str.length() - 1; i++) {
//make a subset of the string excluding the first char
String sub = str.substring(i + 1, str.length());
//compute permutations of the subset
ArrayList<String> subPerms = computeAllPossiblePermutations(sub);
//add the first char that we excluded at the start of each permutations
for (String s : subPerms) {
s = str.charAt(i) + s;
perms.add(s);
}
}
}
return perms;
}

There are a few issues:
The following line: String sub = str.substring(i+1, str.length()); ignores the first character
The same line also treats anything after index i as a "block" of substring that is left unchanged, while in order to generate permutation we should insert the current (first) character in between any two characters of the rest of the string - and do that for each permutation
The line s = str.charAt(i) + s; repeats the same mistake in #2
Here's a suggested fix:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
if (str.length() == 1) {
perms.add(str);
} else {
String chr = str.substring(0,1);
String rest = str.substring(1);
ArrayList<String> subPerms = computeAllPossiblePermutations(rest);
for (String s : subPerms) {
for (int j = 0; j <= s.length(); j++) {
String newPerm = s.substring(0,j) + chr + s.substring(j);
perms.add(newPerm);
}
}
}
return perms;
}

Related

How to count number of character Occurrences inside a string and replace selected character with the counts [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 20 days ago.
Improve this question
My task is to find number of occurrences of a string character and replace the character with the number of occurrence up to that particular index inside the string
public static void main(String[] args) {
char[] arr = "hello".toCharArray();
arr[2] = '1';
arr[3] = '2';
System.out.println(arr);
}
Output should be: he12o
I know we cant reuse this approach.
what is the output of "helololol"?
output for helololol, ch='l' , then the output should be he1o2o3o4; if ch='o' then output should be hel1l2l3l
If according to this rule, Can be achieved with a loop:
public static void main(String[] args) {
char flag = 'l';
String str = "hellollololollol";
int num = 1;
for(int i = 0, len = str.length(); i < len; i++) {
if (str.charAt(i) == flag) {
str = str.substring(0, i) + num++ + str.substring(i + 1);
}
}
System.out.println(str);
}
Note that if the number of specified characters exceeds 9, it will look weird, If the number of characters exceeds 9, special processing is required:
public static void main(String[] args) {
char flag = 'l';
String str = "hellollololollollol";
int num = 1;
for(int i = 0, len = str.length(); i < len; i++) {
if (str.charAt(i) == flag) {
str = str.substring(0, i) + num++ + str.substring(i + 1);
if (num > 10) {
len++;
}
}
System.out.println(str);
}
}
The same problem, if the number of characters exceeds 100, 1000, 10000, special processing is required, because the length of the number added to the string is one bit longer than the original character, how to deal with it flexibly, you need to think about it yourself!
Instead of using primitive methods to manipulate string , we can use the following to have clean code .
public static void main(String args[]) {
String str="helolololololololololololololololololololololololololololololololololololo";
String checkString="l";
int count=1;
StringBuilder sb=new StringBuilder();
List<String> strLst= new ArrayList<String>();
for(int i=0;i<str.length();i++) {
strLst.add(String.valueOf(str.charAt(i)));
}
for(String x : strLst) {
if(x.equals(checkString)) {
sb.append(count);
count++;
}else {
sb.append(x);
}
}
System.out.println(sb);
}
The output for the above string will be
he1o2o3o4o5o6o7o8o9o10o11o12o13o14o15o16o17o18o19o20o21o22o23o24o25o26o27o28o29o30o31o32o33o34o35o36o
With this implementation , we don't have to worry about splitting the string using substring and checking their index .Will work for 'n' number of repetitive letters.

Pallindrome String is replaced by * character [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Input a string which contains some palindrome substrings. Find out the position of palindrome substrings if exist and replace it by *. (For example if input string is “bob has a radar plane” then it should convert in “** has a ***** plane”.
My code is given below.
import java.util.Scanner;
public class Pallindrome_String {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String sen;
System.out.println("Enter the String: ");
sen = in.nextLine();
pallindrome(sen);
in.close();
}
public static void pallindrome(String s) {
int len = s.length();
for (int i = 0; i < len; i++) {
String res = "";
if (s.charAt(i) == ' ') {
res = s.substring(0, i);
String rev = "";
for (int j = res.length() - 1; j >= 0; j--) {
rev = rev + res.charAt(i);
}
if (rev.equals(res)) {
rev = "*";
System.out.print(rev + " ");
} else {
System.out.print(res + " ");
}
}
}
}
}
There is a simpler, more efficient way of finding palindromes in Java. I'll explain the steps to implementing it.
first, after getting your input 'sen', you can use the split method of the String class to seperate each word.
sen = in.nextLine();
String[] splitted = s.split(" "); // seperates the string when there is a whitespace and stores the resulting words in an array
After you've got the words in an array, you can check each word and see if its a palindrome. To do so, you can read the word front to back and back to front and compare the result.
If u find a palindrome, store its index (position in the 'splitted' array). After you've gone through all the words in the 'splitted' array, you can then print out the appropriate number of *'s based on the length of the word.
The split() will loose double spaces and punctuation in source string and make a lot of useless objects in memory. This is more correct solution. IMHO
public static void main(String[] args) {
String s = "Bob! Do you have a radar plane?";
StringBuilder sb = new StringBuilder(s);
Matcher m = Pattern.compile("[a-zA-Z]+").matcher(s);
while (m.find()) {
String word = m.group();
if (word.length() == 0)
continue;
String reversed = new StringBuffer(word).reverse().toString();
if (word.equalsIgnoreCase(reversed)) {
StringBuilder replacement = new StringBuilder();
for (int i = 0; i < word.length(); i++)
replacement.append('*');
sb.replace(m.start(), m.end(), replacement.toString());
}
}
System.out.println(sb);
}

Separating a String to an Array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
How can i seperate this String:
"thisisanexampleforthisproblemicantsolvetestes"
To this array:
{"thisi","sanex","ampl","efor","this","prob","lemi","cant","solv","etes","tes"}
I want to seperate the first 10 letters in the String into 2 elemnts in an array and the rest should be every 4 letters, to one elemnt in an array.
I hope you can help me. I tried this all day but still didnt solve it
Assuming your input string length >= 10 you can do something like below using streams:
String str = "thisisanexampleforthisproblemicantsolvetestes";
String[] splited = Stream.of(str.substring(0, 10).split("(?<=\\G.{5})"),
str.substring(10).split("(?<=\\G.{4})"))
.flatMap(e -> Arrays.stream(e))
.toArray(String[]::new);
System.out.println(Arrays.toString(splited));
where the regex "(?<=\\G.{n})" is used to split a string at each nth char
More simple to understand:
Results in: thisi, sanex, ampl, efor, this, prob, lemi, cant, solv, etes, tes
public static List<String> strangeThingsDo(String str)
{
List<String> li = new ArrayList<>();
int len = str.length();
if (len <= 5)
{
li.add(str);
return li;
}
if (len <= 10)
{
li.add(str.substring(0,5));
li.add(str.substring(5));
return li;
}
li.add(str.substring(0,5));
li.add(str.substring(5,10));
String s,rest = str.substring(10);
int restlen = rest.length();
int end = 0;
for (int i = 0; i < restlen;i += 4)
{
end = i + 4;
if (end > restlen)
{ s = rest.substring(i);
li.add(s);
break;
}
s = rest.substring(i,end);
li.add(s);
}
System.out.println("---: " + li );
return li;
}
The following code will show you how to split a string by numbers of characters. We create a method called splitToNChars() that takes two arguments. The first arguments is the string to be split and the second arguments is the split size.
This splitToNChars() method will split the string in a for loop. First we’ll create a List object that will store parts of the split string. Next we do a loop and get the substring for the defined size from the text and store it into the List. After the entire string is read we convert the List object into an array of String by using the List‘s toArray() method.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SplitStringForEveryNChar {
public static void main(String[] args) {
String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(Arrays.toString(splitToNChar(text, 3)));
System.out.println(Arrays.toString(splitToNChar(text, 4)));
System.out.println(Arrays.toString(splitToNChar(text, 5)));
}
private static String[] splitToNChar(String text, int size) {
List<String> parts = new ArrayList<>();
int length = text.length();
for (int i = 0; i < length; i += size) {
parts.add(text.substring(i, Math.min(length, i + size)));
}
return parts.toArray(new String[0]);
}
}

Find the most repeated word in a string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
can you give me some pointers as of how can I find the most frequent word in an String? I cannot use Maps, lists or so on. I should only achieve this by for's and if's and some in-build methods.
Split String and save to array, sort the array, iterate over the sorted array and count frequency of same strings updating the maximal count. Example:
public static void main(String[] args) {
String myStr = "how can I find the most frequent word in an string how can I find how how how string";
String[] splited = myStr.split(" ");
Arrays.sort(splited);
System.out.println(Arrays.toString(splited));
int max = 0;
int count= 1;
String word = splited[0];
String curr = splited[0];
for(int i = 1; i<splited.length; i++){
if(splited[i].equals(curr)){
count++;
}
else{
count =1;
curr = splited[i];
}
if(max<count){
max = count;
word = splited[i];
}
}
System.out.println(max + " x " + word);
}
Sample idea (there are thousand ways to solve this):
1: A B B C B (< String with words, seperated by blanks)
'A' is your start position
2: count the A (1) and save the pos of A (0). You always iterate from pos until the end of the String.
3: continue counting until you iterated over the entire String. When you reached the end of the String save the count by assigning it to another variable (e.g. oldCount).
4: move on to the next word and start counting B's (new position = 1). You are about to count 3 B's. If newer count > older count replace the older count.
5: count the next word and update the position to your current position, which is 3. (which is the last position of the String).
6: you are not gonna update the counter, B is the most used word in the String.
For the purists - just loops and String.
private String mostFrequentWord(String words) {
// Where my current word starts.
int wordStart = 0;
// How many I counted.
int wordCount = 0;
// The currently most frequent.
String word = "";
for (int wordEnd = wordStart; wordEnd < words.length(); wordEnd++) {
// Is this the end of a word?
if (wordEnd > words.length() || words.charAt(wordEnd) == ' ') {
// We have a word! How many times does it occur?
String thisWord = words.substring(wordStart, wordEnd);
// How many times this word occurs.
int thisWordCount = 0;
// Current start of search.
int search = -1;
// Count them.
while ((search = words.indexOf(thisWord, search + 1)) >= 0) {
thisWordCount += 1;
}
// Is it longer?
if (thisWordCount > wordCount) {
// Keep track.
word = thisWord;
wordCount = thisWordCount;
}
// Move start to the next word.
wordStart = wordEnd + 1;
}
}
return word;
}
private void test() {
String words = "Now is the time for all good men to come to the aid of the party";
System.out.println("Most frequent word in \"" + words + "\" is " + mostFrequentWord(words));
}
public static void main(String...strings) {
String para = "Paris in the the spring.Not that that is related.Why are you laughing? Are my my regular expressions THAT bad??";
String[] words = para.split("\\s+");
int finalCount = 0;
int tempCount = 0;
String mostlyUsedWord = null;
for (String word: words) {
tempCount = 0;
for (String w: words) {
if (word.equalsIgnoreCase(w)) {
tempCount++;
}
}
if (tempCount >= finalCount) {
finalCount = tempCount;
mostlyUsedWord = word;
}
}
System.out.println("mostlyUsedWord:: = " + mostlyUsedWord + " ,count:: = " + finalCount);
}

How to add spaces in between numbers contained inside a string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have string as "DOC_87654321 -ABC76543". What I want is add spaces in between numbers. The result should be "DOC_8 7 6 5 4 3 2 1-ABC7 6 5 4 3". How can it possible?
Try this
String str = "DOC_87654321 -ABC76543";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isDigit(c)) {
sb.append(c + " ");
} else {
sb.append(c);
}
}
Log.e("DATA",sb.toString());
you can use this:
String str = "DOC_87654321 -ABC76543- 959565412";
String finalStr = "";
String[] split = str.split("-");
for (int i = 0; i < split.length; i++) {
finalStr +=
split[i]
.replaceAll("([0-9])", "$1 ")
.trim()
+ (i != split.length - 1 ? '-' : "");
}
System.out.println("finalStr = " + finalStr);
In case if you don't wanna use Character.isDigit() you can compare their ascii decimal values and use it like this
public static void main(String[] args) {
String str = "DOC_87654321 -ABC76543";
StringBuilder string = new StringBuilder();
for(int i=0;i<str.length();i++) {
if(str.charAt(i) >= 48 && str.charAt(i) <=57) {
string.append(str.charAt(i)+" ");
}else {
string.append(str.charAt(i));
}
}
System.out.println(string.toString());
}

Categories

Resources