I have two strings str1 and str2.
Is there any algorithm that can be used in order to print out all interleavings of the two strings using recursion?
Update:
public class Interleave {
private String resultString[] = new String[10];
private String[] interStr(String str1, String str2){
int n = ((Factorial.factorial(str1.length() + str2.length())) / (Factorial.factorial(str1.length()) * Factorial.factorial(str2.length())));
//n is number of interleavings based on (str1.length()+str2.length())! / (str1.length()! * str2.length()!)
if(str1.length() == 0){
resultString[0] = str2;
return resultString;
}
if(str2.length() == 0){
resultString[0] = str1;
return resultString;
}
else{
for(int i = 0; i < n; i++){
resultString[i]= str1.substring(0, 1) + interStr(str1.substring(1), str2.substring(1));
}
}
return resultString;
}
public static void main(String[] args) {
Interleave obj = new Interleave();
obj.interStr("12", "abc");
for(int i = 0; i < obj.resultString.length; i ++){
System.out.println(obj.resultString[i]);
}
}
}
The question simply asked whether a recursive algorithm exists for the problem, and the answer is yes. To find it, look for the base case and then for the "step".
The base case is when one of the two strings are empty:
interleave(s1, "") = {s1}
interleave("", s2) = {s2}
Notice the order of the arguments doesn't really matter, because
interleave("ab", "12") = {"ab12", "a1b2", "1ab2", "a12b", "1a2b", "12ab"} = interleave("12", "ab")
So since the order doesn't matter we'll look at recursing on the length of the first string.
Okay so let's see how one case leads to the next. I'll just use a concrete example, and you can generalize this to real code.
interleave("", "abc") = {"abc"}
interleave("1", "abc") = {"1abc", "a1bc", "ab1c", "abc1"}
interleave("12", "abc") = {"12abc", "1a2bc", "1ab2c", "1abc2", "a12bc", "a1b2c", "a1bc2", "ab12c", "ab1c2" "abc12"}
So everytime we added a character to the first string, we formed the new result set by adding the new character to all possible positions in the old result set. Let's look at exactly how we formed the third result above from the second. How did each element in the second result turn into elements in the third result when we added the "2"?
"1abc" => "12abc", "1a2bc", "1ab2c", "1abc2"
"a1bc" => "a12bc", "a1b2c", "a1bc2"
"ab1c" => "ab12c", "ab1c2"
"abc1" => "abc12"
Now look at things this way:
"1abc" => {1 w | w = interleave("2", "abc")}
"a1bc" => {a1 w | w = interleave("2", "bc")}
"ab1c" => {ab1 w | w = interleave("2", "c")}
"abc1" => {abc1 w | w = interleave("2", "")}
Although one or two examples doesn't prove a rule in general, in this case you should be able to infer what the rule is. You will have a loop, with recursive calls inside it.
This is actually a little more fun to do with pure functional programming, but you tagged the question with Java.
Hopefully this is a start for you. If you get stuck further you can do a web search for "interleaving strings" or "interleaving lists". There are some solutions out there.
EDIT:
Okay I just wrote the silly thing! It's a lot of fun to write these things in scripting languages, so I thought it would be great to see what it looked like in Java. Not as bad as I thought it would be! Here it is, packaged as an entire Java application.
import java.util.ArrayList;
import java.util.List;
public class Interleaver {
/**
* Returns a list containing all possible interleavings of two strings.
* The order of the characters within the strings is preserved.
*/
public static List<String> interleave(String s, String t) {
List<String> result = new ArrayList<String>();
if (t.isEmpty()) {
result.add(s);
} else if (s.isEmpty()) {
result.add(t);
} else {
for (int i = 0; i <= s.length(); i++) {
char c = t.charAt(0);
String left = s.substring(0, i);
String right = s.substring(i);
for (String u : interleave(right, t.substring(1))) {
result.add(left + c + u);
}
}
}
return result;
}
/**
* Prints some example interleavings to stdout.
*/
public static void main(String[] args) {
System.out.println(interleave("", ""));
System.out.println(interleave("a", ""));
System.out.println(interleave("", "1"));
System.out.println(interleave("a", "1"));
System.out.println(interleave("ab", "1"));
System.out.println(interleave("ab", "12"));
System.out.println(interleave("abc", "12"));
System.out.println(interleave("ab", "1234"));
}
}
If I interpreted your question correctly - that you want all the permutations of all the characters in both strings, then the following code will help. You will need to write your own swap function, and somehow obtain an array of all the characters in both strings.
This algorithm will permute from the i'th element up to the n'th element in the array. It is in C++, I would include a reference to where the algorithm is from but I can't remember.
void getPermutationsR(char characters[], int n, int i)
{
if (i == n)
{
//Output the current permutation
}
else
{
for (int j=i; j<n; j++)
{
swap (characters, i, j);
getPermutationsR(characters, n, i+1);
swap (characters, i, j);
}
}
}
What you have now is a good start. The problem is that it returns just one string, instead a list of those.
Change your function to return a list of string, and then think about how you could combine several lists to produce all the output you want.
Here is a solution using recursive approach, easy to understand too
public class Interleave {
public static List<String> interleave(String first, String second){
if(first.length() == 0){
List<String> list = new ArrayList<String>();
list.add(second);
return list;
}
else if(second.length() == 0){
List<String> list = new ArrayList<String>();
list.add(first);
return list;
}
else{
char c1 = first.charAt(0);
List<String> listA = multiply(c1,interleave(first.substring(1),second));
char c2 = second.charAt(0);
List<String> listB = multiply(c2,interleave(first,second.substring(1)));
listA.addAll(listB);
return listA;
}
}
public static List<String> multiply(char c,List<String> list){
List<String> result = new ArrayList<String>();
for(String str : list){
String res = Character.toString(c) + str;
result.add(res);
}
return result;
}
public static void main(String[] args){
System.out.println(interleave("ab", "1234"));
System.out.println(interleave("a", "b"));
System.out.println(interleave("ab", "cd"));
}
}
Below is the much better and simple to understand solution for this problem:
public class Interleaver {
/**
* Returns a list containing all possible interleavings of two strings.
* The order of the characters within the strings is preserved.
*/
public static String s1 = "abc";
public static String s2 = "12";
public static void interleave(int i, int j, String s) {
if (i == s1.length() && j == s2.length()) {
System.out.println("" + s);
}
if (i != s1.length()) {
interleave(i + 1, j, s + s1.charAt(i));
}
if (j != s2.length()) {
interleave(i, j + 1, s + s2.charAt(j));
}
}//Method ends here
/**
* Prints some example interleavings to stdout.
*/
public static void main(String[] args) {
interleave(0, 0, "");
}//Method ends here
}//Class ends here
Program is using just simple recursive calls to find the solution.
Here is another recursive solution:
public class Interleaving2 {
public static void main(String[] args) {
String x = "ab";
String y = "CD";
int m = x.length();
int n = y.length();
char[] result = new char[m + n + 1];
interleave(x, y, result, m, n, 0);
}
public static void interleave(String x, String y, char[] result, int m, int n, int i) {
if (m == 0 && n == 0) {
System.out.println(String.valueOf(result));
}
if (m != 0) {
result[i] = x.charAt(0);
interleave(x.substring(1), y, result, m - 1, n, i + 1);
}
if (n != 0) {
result[i] = y.charAt(0);
interleave(x, y.substring(1), result, m, n - 1, i + 1);
}
}
}
Related
So, i am basically new to java ,and there was this question on our programming test
input:ww:ii:pp:rr:oo
if the alphabets are same then consider only once
output:wipro
so i was able to remove the : from the input and was also able to separate them
my current output :[w,w,i,i,p,p,r,r,o,o]
but i am unable to consider the same characters only once,its been nearly 35 min :_(
String txt="ww:ii:pp::rr:oo";
String[] result= txt.split(":");
System.out.println(Arrays.toString(result));//1
String n11="";
for(String str:result){
n11 += str;
}
System.out.println(n11);//2
result=n11.split("");
System.out.println(Arrays.toString(result));//3
String n12="";
int i=0;
for(String i:result){
if(i.equals(i+1)){
continue;
}
else {
n12=n12+i;
}
}
System.out.println(n12);//4
}
output
[ww, ii, pp, , rr, oo]
wwiipprroo
[w, w, i, i, p, p, r, r, o, o]
[nullw, nullw, nulli, nulli, nullp, nullp, nullr, nullr, nullo, nullo]
Example:
public class GFG
{
/* Method to remove duplicates in a sorted array */
static String removeDupsSorted(String str)
{
int res_ind = 1, ip_ind = 1;
// Character array for removal of duplicate characters
char arr[] = str.toCharArray();
/* In place removal of duplicate characters*/
while (ip_ind != arr.length)
{
if(arr[ip_ind] != arr[ip_ind-1])
{
arr[res_ind] = arr[ip_ind];
res_ind++;
}
ip_ind++;
}
str = new String(arr);
return str.substring(0,res_ind);
}
/* Method removes duplicate characters from the string
This function work in-place and fills null characters
in the extra space left */
static String removeDups(String str)
{
// Sort the character array
char temp[] = str.toCharArray();
//Arrays.sort(temp);
str = new String(temp);
// Remove duplicates from sorted
return removeDupsSorted(str);
}
// Driver Method
public static void main(String[] args)
{
String str = "ww:ii:pp:rr:oo";
String str1 = str.replaceAll(":","");
System.out.println(removeDups(str1));
}
}
The source is taken from www.geeksforgeeks.org And added String str1 = str.replaceAll(":","");
Output:
Your first step is right. But, you have an error in i.equals(i+1) since i + 1 isn't is the next element. You should iterate the array like this:
for (int i = 0; i < result.length - 1; i ++) {
if (result[i].equals(result[i + 1])) {
// do the remove operation.
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I need to design an algorithm where each number is encoded to an alphabet, for example:
1=A, 2=B, 3=C...26=Z
Given a set of numbers, I have to translate them to a combination of strings. For example:
123 can be translated to - ABC(123), AW(1 23) and LC(12 3)
Write an algorithm to find the combinations for number - 123123123.
Now here is what I wrote and I find it inefficient because of multiple "for" loops. Is there any better way I can rewrite this algorithm?
public class ValidCombinations {
Map<Integer, String> mapping = new HashMap<Integer, String>();
public void run() {
String s = "123123123";
/*Convert String to int[]*/
char[] cArray = s.toCharArray();
int[] input = new int[cArray.length];
for (int i=0; i<cArray.length; i++) {
input[i] = Character.getNumericValue(cArray[i]);
}
Set<String> output = new HashSet<String>();
for (int i='A'; i<='Z'; i++) {
mapping.put(i - 'A' + 1, String.valueOf((char)i));
}
for (int i=0; i<input.length; i++) {
if (mapping.containsKey(input[i])) {
output.add(precombine(i, input) + mapping.get(input[i]) + postcombine(i, input));
if (i+1<input.length) {
if (mapping.containsKey(input[i]*10 + input[i+1])) {
output.add(precombine(i, input) + mapping.get(input[i]*10 + input[i+1]) + postcombine(i+1, input));
}
}
}
}
System.out.println(output);
}
public String precombine(int i, int[] input) {
String residue="";
for (int m=0; m<i; m++) {
residue += mapping.get(input[m]);
}
return residue;
}
public String postcombine(int i, int[] input) {
String residue="";
for (int k=i+1; k<input.length; k++) {
residue += mapping.get(input[k]);
}
return residue;
}
public static void main(String[] args) {
ValidCombinations v = new ValidCombinations();
v.run();
}
}
For '123' - [ABC, AW, LC]
For '123123123' - [LCABCABC, AWABCABC, ABCAWABC, ABCLCABC, ABCABCLC, ABCABCABC, ABCABCAW]
This problem is crying out for recursion. Here's a quick and dirty implementation that takes the input "number" in as a string and uses substring() to consume the digits. You could adapt it to use numerical methods to get the first (or first two) decimal digits from an integer if you prefer.
If you choose to work directly from an int, it would probably be easier to start at the end (working with the least-significant-digits) than at the beginning -- lastDigit = number % 10; otherDigits = number / 10
public List<String> encodings(String number) {
List<String> out = new ArrayList<>();
addEncodings("", number, out);
return out;
}
private void addEncodings(String prefix, String number, List<String> out) {
if (number.length() == 0) {
out.add(prefix);
} else {
addParsingNDigits(1, prefix, number, out);
addParsingNDigits(2, prefix, number, out);
}
}
private void addParsingNDigits(int digits, String prefix, String number, List<String> out) {
if (number.length() >= digits) {
char encodedChar = parseChars(number, digits);
if (encodedChar >= 'A' && encodedChar <= 'Z') {
addEncodings(prefix + encodedChar, number.substring(digits), out);
}
}
}
private char parseChars(String number, int length) {
int intVal = Integer.parseInt(number.substring(0, length));
return (char) ('A' + intVal - 1);
}
I don't think your solution will find all possible encodings -- I think you need some sort of stack to solve it. The solution above implicitly uses the execution stack, because of recursive method calls. Another solution could explicitly place objects representing "todo" calculations onto a stack data structure in the heap:
private static class StackItem {
public StackItem(String prefix, String number) {
this.prefix = prefix;
this.number = number;
}
public String prefix;
public String number;
}
public List<String> encodings(String number) {
List<String> results = new ArrayList<>();
Stack<StackItem> stack = new Stack<>();
stack.push(new StackItem("", number));
while (!stack.isEmpty()) {
StackItem current = stack.pop();
if (current.number.equals("")) {
results.add(current.prefix);
} else {
addToStackTakingNChars(2, current, stack);
addToStackTakingNChars(1, current, stack);
}
}
return results;
}
private void addToStackTakingNChars(int n, StackItem current, Stack<StackItem> stack) {
if (current.number.length() >= n) {
char c = parseChars(current.number, n);
if (c >= 'A' && c <= 'Z') {
stack.push(new StackItem(current.prefix + c, current.number.substring(n)));
}
}
}
Although "println debugging" is generally a bad habit, it would probably be a good learning exercise to run these examples with some println()s to observe how it works.
I think you could split the String in the middle (recursively), search for all combinations in both substrings and build the cross product. To not miss any combinations we have to also build the cross product for the two substrings you get by splitting in the middle with an offset of one. Something like this:
private static int[] values;
public static final Set<String> solve(String s) {
values = new int[s.length()];
for (int i = 0; i < values.length; i++)
values[i] = s.charAt(i) - '0';
return solve(0, values.length);
}
private static final Set<String> solve(int start, int len) {
Set<String> ret = new HashSet<>();
if (len == 1) {
ret.add("" + ((char)(values[start] - 1 + 'A')));
} else if (len == 2) {
ret.add("" + ((char)(values[start] - 1 + 'A')) +
((char)(values[start + 1] - 1 + 'A')));
int n = values[start] * 10 + values[start + 1];
if (n <= 26)
ret.add("" + ((char)(n - 1 + 'A')));
} else {
int next = start + len / 2;
cross(solve(start, next - start), solve(next, start + len - next), ret);
cross(solve(start, next - start + 1), solve(next + 1, start + len - next - 1), ret);
}
return ret;
}
private static final void cross(Set<String> a, Set<String> b, Set<String> target) {
for (Iterator<String> itr = a.iterator(); itr.hasNext();) {
String s = itr.next();
for (Iterator<String> itr2 = b.iterator(); itr2.hasNext();) {
target.add(s + itr2.next());
}
}
}
Btw. the solution for "123123123" are the following 27 strings: LCABCAW, LCABCLC, ABCLCABC, ABCLCAW, ABCAWLC, AWLCABC, ABCAWAW, ABCAWABC, ABCLCLC, ABCABCABC, LCAWLC, LCAWAW, AWABCLC, LCAWABC, AWABCAW, LCLCAW, AWABCABC, LCLCLC, LCLCABC, LCABCABC, AWAWLC, AWAWABC, AWAWAW, ABCABCLC, ABCABCAW, AWLCAW, AWLCLC.
Why not just use the ascii value?
All you would need to do would be to convert the number to a String Integer.toString(num) and then run a for-loop through the .length() of the String and pull the .charAt(i) from the String convert that back to an int and then add 16 to it. Then you would just need to cast to a char. like so:
int a = 123;
String str = Integer.toString(a);
char[] chars = new char[str.length()];
for(int i=0,n=str.length();i<n;i++){
chars[i] = (char)(str.charAt(i)+16);
}
String message = String.valueOf(chars);
This problem can be done in o(fib(n+2)) time with a standard DP algorithm.
We have exactly n sub problems and button up we can solve each problem in o(fib(i)) time.
Summing the series gives fib (n+2).
If you consider the question carefullly you see that it is a fibunacci series.
I took a standart code and just changed it a bit to fit our conditions.
The space is obviously bound to the size of all solutions o(fib(n)).
Consider this code:
Map<Integer, String> mapping = new HashMap<Integer, String>();
List<String > iterative_fib_sequence(int input) {
int length = Math.floor(Math.log10(Math.abs(input))) + 1;
if (length <= 1)
{
if (length==0)
{
return "";
}
else//input is a-j
{
return mapping.get(input);
}
}
List<String> b = new List<String>();
List<String> a = new List<String>(mapping.get(input.substring(0,0));
List<String> c = new List<String>();
for (int i = 1; i < length; ++i)
{
int dig2Prefix = input.substring(i-1, i); //Get a letter with 2 digit (k-z)
if (mapping.contains(dig2Prefix))
{
String word2Prefix = mapping.get(dig2Prefix);
foreach (String s in b)
{
c.Add(s.append(word2Prefix));
}
}
int dig1Prefix = input.substring(i, i); //Get a letter with 1 digit (a-j)
String word1Prefix = mapping.get(dig1Prefix);
foreach (String s in a)
{
c.Add(s.append(word1Prefix));
}
b = a;
a = c;
c = new List<String>();
}
return a;
}
Let's say I have ABCDEF. Then, there are 6! permutations of reordering that string. Now, I would like to only deal with the permutations in which there are no adjacent characters. That means, I want to look at all the permutations that satisfy these constraints:
B is not next to A or C
C is not next to B or D
D is not next to C or E
E is not next to D or F
My approach to this algorithm is the following pseudocode:
//generate all 6! permutations
//check all permutations and see where B is next to A || C
//remove all instances
//check all permutations and see where C is next to D
//remove all instances
//check all permutations and see where D is next to E
//remove all instances
//check all permutations and see where E is next to F
//remove all instances
However, these masking operations are becoming very inefficient and taking me much too long, especially if my string length is greater than 6. How can I do this more efficiently? I see these similar posts, 1, 2, and was hoping to extract some key ideas that might help me. However, this is also brute-force checking. I would like to actually generate only the unique patterns from the start and not have to generate everything and check one by one.
EDIT: Currently this is what I am using to generate all the permutations.
static String[] designs;
static int index;
protected static String[] generateDesigns(int lengthOfSequence, int numOfPermutations){
designs = new String[numOfPermutations];
StringBuilder str = new StringBuilder("1");
for(int i = 2; i <= lengthOfSequence; i++)
str.append(i);
genDesigns("", str.toString()); //genDesigns(6) = 123456 will be the unique characters
return designs;
}
//generate all permutations for lenOfSequence characters
protected static void genDesigns(String prefix, String data){
int n = data.length();
if (n == 0) designs[index++] = prefix;
else {
for (int i = 0; i < n; i++)
genDesigns(prefix + data.charAt(i), data.substring(0, i) + data.substring(i+1, n));
}
}
The typical O(n!) pseudo-code of algorithm to generate all permutations of a string of length n:
function permute(String s, int left, int right)
{
if (left == right)
print s
else
{
for (int i = left; i <= right; i++)
{
swap(s[left], s[i]);
permute(s, left + 1, right);
swap(s[left], s[i]); // backtrack
}
}
}
The corresponding recursion tree for string ABC looks like [image taken from internet]:
Just before swapping, check whether you can swap satisfying the given constraint (checking new previous and new next characters of both s[left] and s[i]). This will cut many branches off of the recursion tree too.
Here’s a fairly straightforward backtracking solution pruning the search before adding an adjacent character to the permutation.
public class PermutationsNoAdjacent {
private char[] inputChars;
private boolean[] inputUsed;
private char[] outputChars;
private List<String> permutations = new ArrayList<>();
public PermutationsNoAdjacent(String inputString) {
inputChars = inputString.toCharArray();
inputUsed = new boolean[inputString.length()];
outputChars = new char[inputString.length()];
}
private String[] generatePermutations() {
tryFirst();
return permutations.toArray(new String[permutations.size()]);
}
private void tryFirst() {
for (int inputIndex = 0; inputIndex < inputChars.length; inputIndex++) {
assert !inputUsed[inputIndex] : inputIndex;
outputChars[0] = inputChars[inputIndex];
inputUsed[inputIndex] = true;
tryNext(inputIndex, 1);
inputUsed[inputIndex] = false;
}
}
private void tryNext(int previousInputIndex, int outputIndex) {
if (outputIndex == outputChars.length) { // done
permutations.add(new String(outputChars));
} else {
// avoid previousInputIndex and adjecent indices
for (int inputIndex = 0; inputIndex < previousInputIndex - 1; inputIndex++) {
if (!inputUsed[inputIndex]) {
outputChars[outputIndex] = inputChars[inputIndex];
inputUsed[inputIndex] = true;
tryNext(inputIndex, outputIndex + 1);
inputUsed[inputIndex] = false;
}
}
for (int inputIndex = previousInputIndex + 2; inputIndex < inputChars.length; inputIndex++) {
if (!inputUsed[inputIndex]) {
outputChars[outputIndex] = inputChars[inputIndex];
inputUsed[inputIndex] = true;
tryNext(inputIndex, outputIndex + 1);
inputUsed[inputIndex] = false;
}
}
}
}
public static void main(String... args) {
String[] permutations = new PermutationsNoAdjacent("ABCDEF").generatePermutations();
for (String permutation : permutations) {
System.out.println(permutation);
}
}
}
It prints 90 permutations of ABCDEF. I’ll just quote the beginning and the end:
ACEBDF
ACEBFD
ACFDBE
ADBECF
…
FDBEAC
FDBECA
I have a challenging problem that I am having trouble with. I have an unmodified string, for instance abcdefg and an array of objects that contains a string and indices.
For instance, object 1 contains d and indices [1, 2];
Then I would replace whatever letter is at substring [1,2] with d, with the resulting string looking like adcdefg.
The problem comes when the replacing text is of different length then the replaced text. I need some way to keep track of the length changes or else the indices of further replacements would be inaccurate.
Here is what I have so far:
for (CandidateResult cResult : candidateResultList) {
int[] index = cResult.getIndex();
finalResult = finalResult.substring(0, index[0]) + cResult.getCandidate()
+ finalResult.substring(index[1], finalResult.length()); //should switch to stringbuilder
}
return finalResult;
This does not take care of the corner case mentioned above.
Additionally, this is not homework if anyone was wondering. This is actually for an ocr trainer program that I'm creating.
Here's an implementation, I haven't tested it yet but you can try to get an idea. I'll add comments to the code as needed.
/** This class represents a replacement of characters in the original String, s[i0:if],
* with a new string, str.
**/
class Replacement{
int s, e;
String str;
public Replacement(int s, int e, String str){
this.s = s;
this.e = e;
this.str = str;
}
}
String stringReplace(String str, List<Replacement> replacements){
// Sort Replacements by starting index
Collections.sort(replacements, new Comparator<Replacement>(){
#Override public int compare(Replacement r1, Replacement r2){
return Integer.compare(r1.s, r2.s);
}
};
StringBuilder sb = new StringBuilder();
int repPos = 0;
for(int i = 0; i < str.length; i++){
Replacement rep = replacements.get(repPos);
if(rep.s == i){ // Replacement starts here, at i == s
sb.append(rep.str); // Append the replacement
i = rep.e - 1; // Advance i -> e - 1
repPos++; // Advance repPos by 1
} else {
sb.append(str.charAt(i)); // No replacement, append char
}
}
return sb.toString();
}
[Edit:] After seeing ptyx's answer, I think that way is probably more elegant. If you sort in reverse order, you shouldn't have to worry about the different lengths:
String stringReplace(String str, List<Replacement> replacements){
// Sort Replacements in reverse order by index
Collections.sort(replacements, new Comparator<Replacement>(){
#Override public int compare(Replacement r1, Replacement r2){
return -Integer.compare(r1.s, r2.s); // Note reverse order
}
};
// By replacing in reverse order, shouldn't affect next replacement.
StringBuilder sb = new StringBuilder(str);
for(Replacement rep : replacements){
sb.replace(rep.s, rep.e, rep.str);
}
return sb.toString();
}
Assuming no overlapping ranges to replace, process your replacements in reverse position order - done.
It doesn't matter what you replace [5-6] with, it will never modify [0-4] therefore you don't need to bother about any index mapping for, for example: [1,2]
This seems to do as you ask, basically you just translate the replacement based on previous inserts
public static void main(String[] args) {
Replacer[] replacers = {
new Replacer(new int[]{ 1 , 2 }, "ddd") ,
new Replacer(new int[]{ 2 , 3 }, "a")
};
System.out.println(
m("abcdefg", replacers));
}
public static String m(String s1, Replacer[] replacers){
StringBuilder builder = new StringBuilder(s1);
int translate = 0;
for (int i = 0 ; i < replacers.length ; i++) {
translate += replacers[i].replace(builder, translate);
}
return builder.toString();
}
public static class Replacer{
int[] arr;
String toRep;
public Replacer(int[] arr, String toRep) {
this.arr = arr;
this.toRep = toRep;
}
public int replace(StringBuilder b, int translate){
b.replace(arr[0] + translate, arr[1] + translate, toRep);
return arr[1];
}
}
I need to increment a String in java from "aaaaaaaa" to "aaaaaab" to "aaaaaac" up through the alphabet, then eventually to "aaaaaaba" to "aaaaaabb" etc. etc.
Is there a trick for this?
You're basically implementing a Base 26 number system with leading "zeroes" ("a").
You do it the same way you convert a int to a base-2 or base-10 String, but instead of using 2 or 10, you use 26 and instead of '0' as your base, you use 'a'.
In Java you can easily use this:
public static String base26(int num) {
if (num < 0) {
throw new IllegalArgumentException("Only positive numbers are supported");
}
StringBuilder s = new StringBuilder("aaaaaaa");
for (int pos = 6; pos >= 0 && num > 0 ; pos--) {
char digit = (char) ('a' + num % 26);
s.setCharAt(pos, digit);
num = num / 26;
}
return s.toString();
}
The basic idea then is to not store the String, but just some counter (int an int or a long, depending on your requirements) and to convert it to the String as needed. This way you can easily increase/decrease/modify your counter without having to parse and re-create the String.
The following code uses a recursive approach to get the next string (let's say, from "aaaa" to "aaab" and so on) without the need of producing all the previous combinations, so it's rather fast and it's not limited to a given maximum string length.
public class StringInc {
public static void main(String[] args) {
System.out.println(next("aaa")); // Prints aab
System.out.println(next("abcdzz")); // Prints abceaa
System.out.println(next("zzz")); // Prints aaaa
}
public static String next(String s) {
int length = s.length();
char c = s.charAt(length - 1);
if(c == 'z')
return length > 1 ? next(s.substring(0, length - 1)) + 'a' : "aa";
return s.substring(0, length - 1) + ++c;
}
}
As some folks pointed out, this is tail recursive, so you can reformulate it replacing the recursion with a loop.
Increment the last character, and if it reaches Z, reset it to A and move to the previous characters. Repeat until you find a character that's not Z. Because Strings are immutable, I suggest using an array of characters instead to avoid allocating lots and lots of new objects.
public static void incrementString(char[] str)
{
for(int pos = str.length - 1; pos >= 0; pos--)
{
if(Character.toUpperCase(str[pos]) != 'Z')
{
str[pos]++;
break;
}
else
str[pos] = 'a';
}
}
you can use big integer's toString(radix) method like:
import java.math.BigInteger;
public class Strings {
Strings(final int digits,final int radix) {
this(digits,radix,BigInteger.ZERO);
}
Strings(final int digits,final int radix,final BigInteger number) {
this.digits=digits;
this.radix=radix;
this.number=number;
}
void addOne() {
number=number.add(BigInteger.ONE);
}
public String toString() {
String s=number.toString(radix);
while(s.length()<digits)
s='0'+s;
return s;
}
public char convert(final char c) {
if('0'<=c&&c<='9')
return (char)('a'+(c-'0'));
else if('a'<=c&&c<='p')
return (char)(c+10);
else throw new RuntimeException("more logic required for radix: "+radix);
}
public char convertInverse(final char c) {
if('a'<=c&&c<='j')
return (char)('0'+(c-'a'));
else if('k'<=c&&c<='z')
return (char)(c-10);
else throw new RuntimeException("more logic required for radix: "+radix);
}
void testFix() {
for(int i=0;i<radix;i++)
if(convert(convertInverse((char)('a'+i)))!='a'+i)
throw new RuntimeException("testFix fails for "+i);
}
public String toMyString() {
String s=toString(),t="";
for(int i=0;i<s.length();i++)
t+=convert(s.charAt(i));
return t;
}
public static void main(String[] arguments) {
Strings strings=new Strings(8,26);
strings.testFix();
System.out.println(strings.number.toString()+' '+strings+' '+strings.toMyString());
for(int i=0;i<Math.pow(strings.radix,3);i++)
try {
strings.addOne();
if(Math.abs(i-i/strings.radix*strings.radix)<2)
System.out.println(strings.number.toString()+' '+strings+' '+strings.toMyString());
} catch(Exception e) {
System.out.println(""+i+' '+strings+" failed!");
}
}
final int digits,radix;
BigInteger number;
}
I'd have to agree with #saua's approach if you only wanted the final result, but here is a slight variation on it in the case you want every result.
Note that since there are 26^8 (or 208827064576) different possible strings, I doubt you want them all. That said, my code prints them instead of storing only one in a String Builder. (Not that it really matters, though.)
public static void base26(int maxLength) {
buildWord(maxLength, "");
}
public static void buildWord(int remaining, String word)
{
if (remaining == 0)
{
System.out.println(word);
}
else
{
for (char letter = 'A'; letter <= 'Z'; ++letter)
{
buildWord(remaining-1, word + letter);
}
}
}
public static void main(String[] args)
{
base26(8);
}
I would create a character array and increment the characters individually. Strings are immutable in Java, so each change would create a new spot on the heap resulting in memory growing and growing.
With a character array, you shouldn't have that problem...
Have an array of byte that contain ascii values, and have loop that increments the far right digit while doing carry overs.
Then create the string using
public String(byte[] bytes, String charsetName)
Make sure you pass in the charset as US-ASCII or UTF-8 to be unambiguous.
Just expanding on the examples, as to Implementation, consider putting this into a Class... Each time you call toString of the Class it would return the next value:
public class Permutator {
private int permutation;
private int permutations;
private StringBuilder stringbuilder;
public Permutator(final int LETTERS) {
if (LETTERS < 1) {
throw new IllegalArgumentException("Usage: Permutator( \"1 or Greater Required\" \)");
}
this.permutation = 0;
// MAGIC NUMBER : 26 = Number of Letters in the English Alphabet
this.permutations = (int) Math.pow(26, LETTERS);
this.stringbuilder = new StringBuilder();
for (int i = 0; i < LETTERS; ++i) {
this.stringbuilder.append('a');
}
}
public String getCount() {
return String.format("Permutation: %s of %s Permutations.", this.permutation, this.permutations);
}
public int getPermutation() {
return this.permutation;
}
public int getPermutations() {
return this.permutations;
}
private void permutate() {
// TODO: Implement Utilising one of the Examples Posted.
}
public String toString() {
this.permutate();
return this.stringbuilder.toString();
}
}
Building on the solution by #cyberz, the following code is an example of how you could write a recursive call which can be optimized by a compiler that supports Tail Recursion.
The code is written in Groovy, since it runs on the JVM, its syntax closely resembles Java and it's compiler supports tail recursion optimization
static String next(String input) {
return doNext(input, "")
}
#TailRecursive
#CompileStatic
static String doNext(String input, String result) {
if(!self) {
return result
}
final String last = input[-1]
final String nonLast = self.substring(0, input.size()-1)
if('z' == last) {
return doNext(nonLast, (nonLast ? 'a' : 'aa') + result)
}
return doNext('', nonLast + (((last as Character) + 1) as Character).toString() + result)
}
Since none of the answers were useful to me, I wrote my own code:
/**
* Increases the given String value by one. Examples (with min 'a' and max 'z'): <p>
*
* - "aaa" -> "aab" <br>
* - "aab" -> "aac" <br>
* - "aaz" -> "aba" <br>
* - "zzz" -> "aaaa" <br>
*
* #param s
* #param min lowest char (a zero)
* #param max highest char (e.g. a 9, in a decimal system)
* #return increased String by 1
*/
public static String incString(String s, char min, char max) {
char last = s.charAt(s.length() - 1);
if (++last > max)
return s.length() > 1 ? incString(s.substring(0, s.length()-1), min, max) + min : "" + min + min;
else
return s.substring(0, s.length()-1) + last;
}
public static String incrementString(String string)
{
if(string.length()==1)
{
if(string.equals("z"))
return "aa";
else if(string.equals("Z"))
return "Aa";
else
return (char)(string.charAt(0)+1)+"";
}
if(string.charAt(string.length()-1)!='z')
{
return string.substring(0, string.length()-1)+(char)(string.charAt(string.length()-1)+1);
}
return incrementString(string.substring(0, string.length()-1))+"a";
}
Works for all standard string containing alphabets
I have approach using for loop which is fairly simple to understand. based on [answer]: https://stackoverflow.com/a/2338415/9675605 cyberz answer.
This also uses org.apache.commons.lang3.ArrayUtils. to insert letter on first position. you can create your own util for it. If someone finds helpful.
import org.apache.commons.lang3.ArrayUtils;
public class StringInc {
public static void main(String[] args) {
System.out.println(next("aaa")); // Prints aab
System.out.println(next("abcdzz")); // Prints abceaa
System.out.println(next("zzz")); // Prints aaaa
}
public static String next(String str) {
boolean increment = true;
char[] arr = str.toCharArray();
for (int i = arr.length - 1; i >= 0 && increment; i--) {
char letter = arr[i];
if (letter != 'z') {
letter++;
increment = false;
} else {
letter = 'a';
}
arr[i] = letter;
}
if (increment) {
arr = ArrayUtils.insert(0, arr, 'a');
}
return new String(arr);
}
It's not much of a "trick", but this works for 4-char strings. Obviously it gets uglier for longer strings, but the idea is the same.
char array[] = new char[4];
for (char c0 = 'a'; c0 <= 'z'; c0++) {
array[0] = c0;
for (char c1 = 'a'; c1 <= 'z'; c1++) {
array[1] = c1;
for (char c2 = 'a'; c2 <= 'z'; c2++) {
array[2] = c2;
for (char c3 = 'a'; c3 <= 'z'; c3++) {
array[3] = c3;
String s = new String(array);
System.out.println(s);
}
}
}
}