Given two numbers as input, return the sum of the numbers. Note that the numbers can be very large and hence are provided as Strings
Sample Input #1:
add("2354725234782357","9999999999999999999999999988888888888")
Sample Output #1:
10000000000000000000002354714123671245
Implementation:
public String add(String str1, String str2) {
int max = str1.length() > str2.length() ? str1.length() : str2.length();
int n1[] = new int[max];
int n2[] = new int[max];
for (int i = 0; i < str1.length(); i++) {
n1[i] = str1.charAt(str1.length() - 1 - i);
}
for (int i = 0; i < str2.length(); i++) {
n2[i] = str2.charAt(str2.length() - 1 - i);
}
int carry = 0;
int sum[] = new int[max + 1];
int k = 0;
for (k = 0; k < max; k++) {
sum[k] = (n1[k] + n2[k] + carry) % 10;
if ((n1[k] + n2[k] + carry) >= 10) {
carry = 1;
} else {
carry = 0;
}
}
sum[max] = carry;
String result = "";
return result;
}
I have implemented my logic but I don't know how to get the output as a string.
Why don't use BigInteger this is much easier and still native java.
private static String add(String s1, String s2)
{
BigInteger n1 = new BigInteger(s1);
BigInteger n2 = new BigInteger(s2);
return n1.add(n2).toString();
}
Anyway, there is one bug in your Code. Dont cast char to int the ascii value is used, which is wrong. Parse it with Character.getNumericValue();
If you have done this, you can concat sum array to a string in reversed order.
Solution:
public static String add(String str1, String str2) {
int max = str1.length() > str2.length() ? str1.length() : str2.length();
int n1[] = new int[max];
int n2[] = new int[max];
for (int i = 0; i < str1.length(); i++)
{
// conver char to int
n1[i] = Character.getNumericValue(str1.charAt(str1.length() - 1 - i));
}
for (int i = 0; i < str2.length(); i++) {
// conver char to int
n2[i] = Character.getNumericValue(str2.charAt(str2.length() - 1 - i));
}
int carry = 0;
int sum[] = new int[max + 1];
int k = 0;
for (k = 0; k < max; k++) {
sum[k] = (n1[k] + n2[k] + carry) % 10;
if ((n1[k] + n2[k] + carry) >= 10) {
carry = 1;
} else {
carry = 0;
}
}
sum[max] = carry;
// concat array in reverse order
StringBuilder sb = new StringBuilder();
for(int i = sum.length - 1; i >= 0; i--)
sb.append(sum[i]);
return sb.toString();
}
Input
add("2354725234782357","9999999999999999999999999988888888888")
Output
10000000000000000000002354714123671245
There is a logic error in your code: you are adding the char value of each integer instead of the integer themselves. You can get the numeric value of a char using Character.getNumericValue(char ch).
Then, you can construct the resulting String by looping over the sum array. The loop must be done in reverse order (to get the correct order). Beware of the first value sum[max], if it is 0, we must not add it to the String (otherwise, we will get a value padded with a 0):
public static String add(String str1, String str2) {
int max = Math.max(str1.length(), str2.length());
int n1[] = new int[max];
int n2[] = new int[max];
for (int i = 0; i < str1.length(); i++) {
//n1[i] = str1.charAt(str1.length() - 1 - i);
n1[i] = Character.getNumericValue(str1.charAt(str1.length() - 1 - i));
}
for (int i = 0; i < str2.length(); i++) {
//n2[i] = str2.charAt(str2.length() - 1 - i);
n2[i] = Character.getNumericValue(str2.charAt(str2.length() - 1 - i));
}
int carry = 0;
int sum[] = new int[max + 1];
int k = 0;
for (k = 0; k < max; k++) {
sum[k] = (n1[k] + n2[k] + carry) % 10;
if ((n1[k] + n2[k] + carry) >= 10) {
carry = 1;
} else {
carry = 0;
}
}
sum[max] = carry;
StringBuilder sb = new StringBuilder();
if (sum[max] > 0) {
sb.append(String.valueOf(sum[max]));
}
for (int i = max - 1; i >= 0; i--) {
sb.append(String.valueOf(sum[i]));
}
return sb.toString();
}
Note that you can also replace
int max = str1.length() > str2.length() ? str1.length() : str2.length();
with
int max = Math.max(str1.length(), str2.length());
I have modified some code:(you can avoid array creation)
public static String add(String str1, String str2) {
int carry=0;
StringBuilder sum=new StringBuilder();
int l1=str1.length();
int l2=str2.length();
while(l1>0 && l2>0){
int s=Character.getNumericValue(str1.charAt(--l1))+Character.getNumericValue(str2.charAt(--l2))+carry;
if(s<10){
sum.append(s);
}else{
sum.append(s%10);
carry=s/10;
}
}
if(l2>0){
while(l2>0){
int s=Character.getNumericValue(str2.charAt(--l2))+carry;
if(s<10){
sum.append(s);
}else{
sum.append(s%10);
carry=s/10;
}
}
}
if(l1>0){
while(l2>0){
int s=Character.getNumericValue(str1.charAt(--l1))+carry;
if(s<10){
sum.append(s);
}else{
sum.append(s%10);
carry=s/10;
}
}
}
if(carry>0){
sum.append(carry);
}
return sum.reverse().toString();
}
You can use a StringBuilder to append all the digits from your int[] from max to 0.
StringBuilder sb = new StringBuilder();
for (int i=max; i>=0; i--)
{
sb.append(String.valueOf(sum[i]));
}
String result = sb.toString();
You can also improve this to skip leading zeroes if you want:
boolean leadingZero = true;
StringBuilder sb = new StringBuilder();
for (int i=max; i>=0; i--)
{
if (sum[i] != 0)
{
leadingZero=false;
}
if (!leadingZero)
{
sb.append(String.valueOf(sum[i]));
}
}
String result = sb.toString();
Related
I am trying to find the maximum product of two non overlapping palindromic sub-sequences of string s that we'll refer to as a and b. I came up with below code but it's not giving correct output:
public static int max(String s) {
int[][] dp = new int[s.length()][s.length()];
for (int i = s.length() - 1; i >= 0; i--) {
dp[i][i] = 1;
for (int j = i+1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
dp[i][j] = dp[i+1][j-1] + 2;
} else {
dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]);
}
}
}
return dp[0][s.length()-1];
}
For input string "acdapmpomp", we can choose a = "aca" and b ="pmpmp" to get a maximal product of score 3 * 5 = 15. But my program gives output as 5.
Firstly you should traverse the dp table to find out the length of longest palindromic subsequences using bottom up approach, then you can calculate the max product by multiplying dp[i][j] with dp[j+1][n-1] : Given below is the code in C++;
int longestPalindromicSubsequenceProduct(string x){
int n = x.size();
vector<vector<int>> dp(n,vector<int>(n,0));
for(int i=0;i<n;i++){
dp[i][i] = 1;
}
for(int k=1;k<n;k++){
for(int i=0;i<n-k;i++){
int j = i + k;
if(x[i]==x[j]){
dp[i][j] = 2 + dp[i+1][j-1];
} else{
dp[i][j] = max(dp[i][j-1],dp[i+1][j]);
}
}
}
int maxProd = 0;
for(int i=0;i<n;i++){
for(int j=0;j<n-1;j++){
maxProd = max(maxProd,dp[i][j]*dp[j+1][n-1]);
}
}
return maxProd;
}
int multiplyPalindrome(string s) {
int n=s.size(),m=0;
vector<vector<int>> dp(n, vector<int> (n));
for(int i=0;i<n;i++) dp[i][i]=1;
for (int cl=2; cl<=n; cl++) {
for (int i=0; i<n-cl+1; i++){
int j = i+cl-1;
if (s[i] == s[j] && cl == 2) dp[i][j] = 2;
else if (s[i] == s[j]) dp[i][j] = dp[i+1][j-1] + 2;
else dp[i][j] = max(dp[i][j-1], dp[i+1][j]);
}
}
for(int i=0;i<n-1;i++){
m = max( m, dp[0][i]*dp[i+1][n-1] );
}
return m;
}
int palSize(string &s, int mask) {
int p1 = 0, p2 = s.size(), res = 0;
while (p1 <= p2) {
if ((mask & (1 << p1)) == 0)
++p1;
else if ((mask & (1 << p2)) == 0)
--p2;
else if (s[p1] != s[p2])
return 0;
else
res += 1 + (p1++ != p2--);
}
return res;
}
int maxProduct(string s) {
int mask[4096] = {}, res = 0;
for (int m = 1; m < (1 << s.size()); ++m)
mask[m] = palSize(s, m);
for (int m1 = 1; m1 < (1 << s.size()); ++m1)
if (mask[m1])
for (int m2 = 1; m2 < (1 << s.size()); ++m2)
if ((m1 & m2) == 0)
res = max(res, mask[m1] * mask[m2]);
return res;
}
You can loop through all non-overlapping palindromic subsequences and return the maximum value.
public int longestPalindromicSubsequenceProduct(String str) {
int maxProduct = 0;
for (int k = 0; k < str.length(); k++) {
String left = str.substring(0, k);
String right = str.substring(k);
int currProduct = longestPalindromicSubsequence(left) * longestPalindromicSubsequence(right);
maxProduct = Math.max(maxProduct, currProduct);
}
return maxProduct;
}
private int longestPalindromicSubsequence(String org) {
String rev = new StringBuilder(org).reverse().toString();
return longestCommonSubsequence(org, rev);
}
private int longestCommonSubsequence(String str1, String str2) {
int rows = str1.length();
int cols = str2.length();
int[][] dp = new int[rows + 1][cols + 1];
for (int r = 1; r <= rows; r++) {
for (int c = 1; c <= cols; c++) {
if (str1.charAt(r - 1) == str2.charAt(c - 1)) dp[r][c] = 1 + dp[r - 1][c - 1];
else dp[r][c] = Math.max(dp[r - 1][c], dp[r][c - 1]);
}
}
return dp[rows][cols];
}
Your algorithm returns the maximum length of a palyndrome, not the maximum of the product of two lengths.
UPDATE
Here's a possible solution:
public static int max(String s) {
int max = 0;
for (int i = 1; i < s.length()-1; ++i) {
String p1 = bestPalyndrome(s, 0, i);
String p2 = bestPalyndrome(s, i, s.length());
int prod = p1.length()*p2.length();
if (prod > max) {
System.out.println(p1 + " " + p2 + " -> " + prod);
max = prod;
}
}
return max;
}
private static String bestPalyndrome(String s, int start, int end) {
if (start >= end) {
return "";
} else if (end-start == 1) {
return s.substring(start, end);
} else if (s.charAt(start) == s.charAt(end-1)) {
return s.charAt(start) + bestPalyndrome(s, start+1, end-1)
+ s.charAt(end-1);
} else {
String s1 = bestPalyndrome(s, start, end-1);
String s2 = bestPalyndrome(s, start+1, end);
return s2.length() > s1.length() ? s2 : s1;
}
}
This question already has answers here:
Counting the number of a certain letter appears in series of strings in an ArrayList
(4 answers)
Closed 6 years ago.
I have an ArrayList that stores strings, or notes, in the form of "walk the dog". I have a notes class with a method that prints the number of times each letter appears in the entire ArrayList. I'm supposed to declare and use a primitive array of ints of size 26 and turn each letter in the notebook into a char using the charAt method in the String class. Then I have to use that char to index into the appropriate location in the low-level array. This is my method so far but it's not finished:
public void printLetterDistribution() {
ArrayList<Integer> aList = new ArrayList<Integer>();
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
for (int j = 0; j < note.length(); j++) {
char letter = note.charAt(j);
int code = (int)letter;
aList.add(code);
}
}
Collections.sort(aList);
}
I've hit a wall and I don't know how to continue. As you can see, I've tried to convert the letters to their character code but it's probably not the best way to do it and I'm still getting stuck. Can anybody help?
EDIT - Here is the entire notes class:
public class Notebook {
private ArrayList<String> notes;
public Notebook() { notes = new ArrayList<String>(); }
public void addNoteToEnd(String inputnote) {
notes.add(inputnote);
}
public void addNoteToFront(String inputnote) {
notes.add(0, inputnote);
}
public void printAllNotes() {
for (int i = 0; i < notes.size(); i++) {
System.out.print("#" + (i + 1) + " ");
System.out.println(notes.get(i));
}
System.out.println();
}
public void replaceNote(int inputindex, String inputstring) {
int index = inputindex - 1;
if (index > notes.size() || index < 0) {
System.out.println("ERROR: Note number not found!");
} else {
notes.set(index, inputstring);
}
}
public int countNotesLongerThan(int length) {
int count = 0;
for (int i = 0; i < notes.size(); i++) {
String temp = notes.get(i);
if (temp.length() > length) {
count++;
}
}
return count;
}
public double averageNoteLength() {
int sum = 0;
for (int i = 0; i < notes.size(); i++) {
String temp = notes.get(i);
int length = temp.length();
sum += length;
}
double average = (double)(sum / notes.size());
return average;
}
public String firstAlphabetically() {
String min = "";
for (int i = 0; i < notes.size(); i++) {
for (int j = i + 1; j < notes.size(); j++) {
if ((notes.get(i)).compareTo(notes.get(j)) < 0) {
min = notes.get(i);
} else {
min = notes.get(j);
}
}
}
return min;
}
public void removeNotesBetween(int startnote, int endnote) {
int start = startnote - 1;
int end = endnote - 1;
for (int i = end - 1; i > start; i--) {
notes.remove(i);
}
}
public void printNotesContaining(String findString) {
for (int i = 0; i < notes.size(); i++) {
if (notes.get(i).contains(findString)) {
System.out.println("#" + i + " " + notes.get(i));
}
}
}
public int countNumberOf(String letter) {
int count = 0;
for (int i = 0; i < notes.size(); i++) {
String note = (notes.get(i));
for (int j = 0; j < note.length(); j++) {
if (note.charAt(j) == letter.charAt(0)) {
count++;
}
}
}
return count;
}
public void findAndReplaceFirst(String old, String newWord) {
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
if (note.contains(old)) {
int loc = note.indexOf(old);
int len = old.length();
String temp = note.substring(0, loc ) + note.substring(loc + len, note.length());
String newString = temp.substring(0, loc) + newWord + temp.substring(loc, temp.length());
notes.set(i, newString);
} else {
String newString = note;
notes.set(i, newString);
}
}
}
public void printLetterDistribution() {
int[] p = new int[26];
for (int i = 0; i < 26; i++) {
p[i] = 0;
}
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
note = note.toLowerCase();
for (int j = 0; j < note.length(); j++) {
char letter = note.charAt(j);
p[letter - 'a']++;
}
}
System.out.println(p);
}
}
You can use an int array of 26 length and increment the count of the index letter-'a';
int[] p = new int[26];
for(int i = 0; i < 26; i++) p[i] = 0;
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
for (int j = 0; j < note.length(); j++) {
char letter = note.charAt(j);
if(letter>= 'a' && letter <= 'z')
p[letter-'a']++;
}
PS: I am assuming that the notes are in lowercase only. If it is not the case, use note.toLowerCase() to make them lower.
Since in your notes you can have spaces, I have updated the code.
The goal is to add two numbers together that are stored in arrays-element by element. The numbers do not necessarily need to be of equal length. I am having trouble accounting for the possibility of a carry over.
If the number is 1101 it would be represented : [1,0,1,1]- The least significant bit is at position 0. I am doing the addition without converting it to an integer.
I am making a separate method to calculate the sum of binary numbers but I just want to understand how to go about this using the same logic.
Ex: 349+999 or they could even be binary numbers as well such as 1010101+11
Any suggestions?
int carry=0;
int first= A.length;
int second=B.length;
int [] sum = new int [(Math.max(first, second))];
if(first > second || first==second)
{
for(int i =0; i <A.length;i++)
{
for(int j =0; j <B.length;j++)
{
sum[i]= (A[i]+B[j]);
}
}
return sum;
}
else
{
for(int i =0; i <B.length;i++)
{
for(int j =0; j <A.length;j++)
{
sum[i]= (A[i]+B[j]);
}
}
return sum;
}
For the binary addition:
byte carry=0;
int first= A.length;
int second=B.length;
byte [] sum = new byte [Math.max(first, second)+1];
if(first > second || first==second)
{
for(int i =0; i < A.length && i!= B.length ;i++)
{
sum[i]= (byte) (A[i] + B[i] + carry);
if(sum[i]>1) {
sum[i] = (byte) (sum[i] -1);
carry = 1;
}
else
carry = 0;
}
for(int i = B.length; i < A.length; i++) {
sum[i] = (byte) (A[i] + carry);
if(sum[i]>1) {
sum[i] = (byte) (sum[i] -1);
carry = 1;
}
else
carry = 0;
}
sum[A.length] = carry; //Assigning msb as carry
return sum;
}
else
{
for(int i =0; i < B.length && i!= A.length ;i++) {
sum[i]= (byte) (A[i] + B[i] + carry);
if(sum[i]>1) {
sum[i] = (byte) (sum[i] -1);
carry = 1;
}
else
carry = 0;
}
for(int i = A.length; i < B.length; i++) {
sum[i] = (byte) (B[i] + carry);
if(sum[i]>1) {
sum[i] = (byte) (sum[i] -1);
carry = 1;
}
else
carry = 0;
}
sum[B.length] = carry;//Assigning msb as carry
return sum;
}
There is no need to treat binary and decimal differently.
This handles any base, from binary to base36, and extremely
large values -- far beyond mere int's and long's!
Digits need to be added from the least significant first.
Placing the least significant digit first makes the code
simpler, which is why most CPUs are Little-Endian.
Note: Save the code as "digits.java" -- digits is the
main class. I put Adder first for readability.
Output:
NOTE: Values are Little-Endian! (right-to-left)
base1: 0(0) + 00(0) = 000(0)
base2: 01(2) + 1(1) = 110(3)
base2: 11(3) + 01(2) = 101(5)
base2: 11(3) + 011(6) = 1001(9)
base16: 0A(160) + 16(97) = 101(257)
base32: 0R(864) + 15(161) = 101(1025)
Source code: digits.java:
class Adder {
private int base;
private int[] a;
private int[] b;
private int[] sum;
public String add() {
int digitCt= a.length;
if(b.length>digitCt)
digitCt= b.length; //max(a,b)
digitCt+= 1; //Account for possible carry
sum= new int[digitCt]; //Allocate space
int digit= 0; //Start with no carry
//Add each digit...
for(int nDigit=0;nDigit<digitCt;nDigit++) {
//digit already contains the carry value...
if(nDigit<a.length)
digit+= a[nDigit];
if(nDigit<b.length)
digit+= b[nDigit];
sum[nDigit]= digit % base;//Write LSB of sum
digit= digit/base; //digit becomes carry
}
return(arrayToText(sum));
}
public Adder(int _base) {
if(_base<1) {
base= 1;
} else if(_base>36) {
base=36;
} else {
base= _base;
}
a= new int[0];
b= new int[0];
}
public void loadA(String textA) {
a= textToArray(textA);
}
public void loadB(String textB) {
b= textToArray(textB);
}
private int charToDigit(int digit) {
if(digit>='0' && digit<='9') {
digit= digit-'0';
} else if(digit>='A' && digit<='Z') {
digit= (digit-'A')+10;
} else if(digit>='a' && digit<='z') {
digit= (digit-'a')+10;
} else {
digit= 0;
}
if(digit>=base)
digit= 0;
return(digit);
}
private char digitToChar(int digit) {
if(digit<10) {
digit= '0'+digit;
} else {
digit= 'A'+(digit-10);
}
return((char)digit);
}
private int[] textToArray(String text) {
int digitCt= text.length();
int[] digits= new int[digitCt];
for(int nDigit=0;nDigit<digitCt;nDigit++) {
digits[nDigit]= charToDigit(text.charAt(nDigit));
}
return(digits);
}
private String arrayToText(int[] a) {
int digitCt= a.length;
StringBuilder text= new StringBuilder();
for(int nDigit=0;nDigit<digitCt;nDigit++) {
text.append(digitToChar(a[nDigit]));
}
return(text.toString());
}
public long textToInt(String a) {
long value= 0;
long power= 1;
for(int nDigit=0;nDigit<a.length();nDigit++) {
int digit= charToDigit(a.charAt(nDigit));
value+= digit*power;
power= power*base;
}
return(value);
}
}
public class digits {
public static void main(String args[]) {
System.out.println("NOTE: Values are Little-Endian! (right-to-left)");
System.out.println(test(1,"0","00"));
System.out.println(test(2,"01","1"));
System.out.println(test(2,"11","01"));
System.out.println(test(2,"11","011"));
System.out.println(test(16,"0A","16"));
System.out.println(test(32,"0R","15"));
}
public static String test(int base, String textA, String textB) {
Adder adder= new Adder(base);
adder.loadA(textA);
adder.loadB(textB);
String sum= adder.add();
String result= String.format(
"base%d: %s(%d) + %s(%d) = %s(%d)",
base,
textA,adder.textToInt(textA),
textB,adder.textToInt(textB),
sum,adder.textToInt(sum)
);
return(result);
}
}
First off, adding binary numbers will be different then ints. For ints you could do something like
int first = A.length;
int second = B.length;
int firstSum = 0;
for (int i = 0; i < first; i++){
firstSum += A[i] * (10 ^ i);
}
int secondSum = 0;
for (int j = 0; j < second; j++){
secondSum += B[j] * (10 ^ j);
}
int totalSum = firstSum + secondSum;
It should be represented like this in below as we have to add only the values at same position of both the arrays. Also, in your first if condition, it should be || instead of &&. This algorithm should perfectly work. Let me know if there are any complications.
int carry=0;
int first= A.length;
int second=B.length;
int [] sum = new int [Math.max(first, second)+1];
if(first > second || first==second)
{
for(int i =0; i < A.length && i!= B.length ;i++)
{
sum[i]= A[i] + B[i] + carry;
if(sum[i]>9) {
sum[i] = sum[i] -9;
carry = 1;
}
else
carry = 0;
}
for(int i = B.length; i < A.length; i++) {
sum[i] = A[i] + carry;
if(sum[i]>9) {
sum[i] = sum[i] -9;
carry = 1;
}
else
carry = 0;
}
sum[A.length] = carry; //Assigning msb as carry
return sum;
}
else
{
for(int i =0; i < B.length && i!= A.length ;i++) {
sum[i]= A[i] + B[i] + carry;
if(sum[i]>9) {
sum[i] = sum[i] -9;
carry = 1;
}
else
carry = 0;
}
for(int i = A.length; i < B.length; i++) {
sum[i] = B[i] + carry;
if(sum[i]>9) {
sum[i] = sum[i] -9;
carry = 1;
}
else
carry = 0;
}
sum[B.length] = carry //Assigning msb as carry
return sum;
}
What I need to do is take a String array with each element having an exact length of 2, and find all possible combinations of the the elements, using each character within each String. By that I mean the String array {"Ss", "Ff"} returns "SF", "Sf", "sF", "sf". I have already tried a loop method that counts the iteration and then chooses a letter based on that, but it only works for arrays with a single element:
public String [] generatePossibilities(String [] s)
{
if(s[0].length() != 2)
throw new IllegalArgumentException();
String [] r = new String [s.length * 2];
for(int i = 0; i < r.length; i++)
{
r[i] = getPossibility(i, s);
}
return r;
}
private String getPossibility(int iteration, String [] source)
{
int [] choose = new int [source.length];
for(int i = 0; i < choose.length; i++)
{
choose[i] = 0;
}
for(int i = choose.length - 1; i >= 0; i--)
{
if(iteration < 1)
break;
choose[i] = 1;
iteration--;
}
String result = "";
for(int i = 0; i < source.length; i++)
result += source[i].substring(choose[i], choose[i] + 1);
return result;
}
Solved Thanks Sven!
public String [] generatePossibilities(String [] s)
{
if(s[0].length() != 2)
throw new IllegalArgumentException();
ArrayList<String> ra = new ArrayList<String>();
for(int i = s.length - 1; i >= 0; i--)
{
for(int j = 0; j < s[i].length(); j++)
{
String c = s[i].substring(j, j + 1);
if(ra.size() < 2)
{
ra.add(c);
}
else
{
for(int k = 0; k < ra.size(); k++)
{
String s1 = ra.get(k);
if(s1.substring(0, 1).equalsIgnoreCase(c))
continue;
else
{
s1 = c + s1;
ra.add(s1);
}
}
}
}
for(int j = 0; j < ra.size(); j++)
{
if(ra.get(j).length() != s.length - i)
{
ra.remove(j);
j--;
}
}
}
String [] r = new String [ra.size()];
for(int i = 0; i < r.length; i++)
{
r[i] = ra.get(i);
}
return r;
}
I would iterate the array of character tuples from last element to first. In each step you append to each current character the possibilities of the last iteration. You therefore double the elements in each step.
So for your example in the first iteration you have {Ff} and this would result to the two strings "F" and "f". In the next step you take each character of {Ss} and append each string of the last step to it getting "SF", "Sf", "sF" and "sf". You could then continue with further character tuples.
I have this problem, I need to generate from a given permutation not all combinations, but just those obtained after permuting 2 positions and without repetition. It's called the region of the a given permutation, for example given 1234 I want to generate :
2134
3214
4231
1324
1432
1243
the size of the region of any given permutation is , n(n-1)/2 , in this case it's 6 combinations .
Now, I have this programme , he does a little too much then what I want, he generates all 24 possible combinations :
public class PossibleCombinations {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Entrer a mumber");
int n=s.nextInt();
int[] currentab = new int[n];
// fill in the table 1 TO N
for (int i = 1; i <= n; i++) {
currentab[i - 1] = i;
}
int total = 0;
for (;;) {
total++;
boolean[] used = new boolean[n + 1];
Arrays.fill(used, true);
for (int i = 0; i < n; i++) {
System.out.print(currentab[i] + " ");
}
System.out.println();
used[currentab[n - 1]] = false;
int pos = -1;
for (int i = n - 2; i >= 0; i--) {
used[currentab[i]] = false;
if (currentab[i] < currentab[i + 1]) {
pos = i;
break;
}
}
if (pos == -1) {
break;
}
for (int i = currentab[pos] + 1; i <= n; i++) {
if (!used[i]) {
currentab[pos] = i;
used[i] = true;
break;
}
}
for (int i = 1; i <= n; i++) {
if (!used[i]) {
currentab[++pos] = i;
}
}
}
System.out.println(total);
}
}
the Question is how can I fix this programme to turn it into a programme that generates only the combinations wanted .
How about something simple like
public static void printSwapTwo(int n) {
int count = 0;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n - 1;i++)
for(int j = i + 1; j < n; j++) {
// gives all the pairs of i and j without repeats
sb.setLength(0);
for(int k = 1; k <= n; k++) sb.append(k);
char tmp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(j));
sb.setCharAt(j, tmp);
System.out.println(sb);
count++;
}
System.out.println("total=" + count+" and should be " + n * (n - 1) / 2);
}