Insertionsort for Array with permutation (Java) - java

So I have this array which I have to sort with Insertionssort:
( 4 1 2 3 )= arr[0] ,
( 1 2 3 4 )=arr[1] ,
( 4 3 2 1 ) = arr[2],
( 3 1 2 4 )= arr[3] ,
( 4 3 1 2 ) = arr[4] ,
( 2 1 3 4 ) = arr[5] ,
( 4 1 3 2 ) = arr[6] ,
( 1 4 2 3 )= arr[7]
One array will be swapped with another if the difference between value 1 - 4 of array 1 and the difference between value 1-4 of array 2 is higher. For example: arr[0] < arr[1], because 1(4-3) < 3(4-1). If the difference is the same the values will be compared: for example: arr[5] & arr[6] have the same difference(2) but arr[6].value(1) > arr[5].value(1) --> swap.
so the sorted array will look like this:
(3,1,2,4) < (4,1,2,3) < (1,4,2,3) < (2,1,3,4) < (4,1,3,2) < (4,3,1,2) < (1,2,3,4) < (4,3,2,1)
I have this methode atm, where is just checked the first criteria:
public int insertionsort(permutation[] arr, int gap) {
int count = 0;
for (int i = gap; i<arr.length-1; i++) {
count++;
permutation new = arr[i];
int k = i;
System.out.println("K: " + k);
System.out.println("gap: "+ gap);
while(Math.abs(arr[i].value(1)-arr[i].value(4)) > Math.abs(arr[i-gap].value(1) -
arr[i-gap].value(4))) {
arr[k] = arr[k-gap];
k = k-gap;
System.out.println("k-gap: " + (k-gap));
}
arr[k] = new;
}
return count;
}
Now I thought my array would be sorted in the order of the small differences first but it doesnt seem right. I hope you can help me!

I'm not clear what the purpose of the gap argument is, hopefully you can incorporate it if needed, but here's a direct translation into Java of the standard Insertion Sort method.
static void sort(permutation[] perms)
{
for(int i=1; i<perms.length; i++)
{
permutation fixed = perms[i];
int j = i - 1;
while(j >= 0 && perms[j].compareTo(fixed) > 0)
{
perms[j+1] = perms[j];
j -= 1;
}
perms[j+1] = fixed;
}
}
With a guess at what the permutation class might look like:
static class permutation
{
int len;
int[] arr;
public permutation(int... vals)
{
len = vals.length;
arr = vals.clone();
}
int value(int pos)
{
return arr[pos-1];
}
public int compareTo(permutation p)
{
int cmp = Math.abs(value(1)-value(len)) - Math.abs(p.value(1)-p.value(len));
if(cmp == 0)
for(int i=1; cmp==0 && i<=len; i++)
cmp = value(i)-p.value(i);
return cmp;
}
}
Test:
permutation[] perms = {
new permutation(4,1,2,3),
new permutation(1,2,3,4),
new permutation(4,3,2,1),
new permutation(3,1,2,4),
new permutation(4,3,1,2),
new permutation(2,1,3,4),
new permutation(4,1,3,2),
new permutation(1,4,3,2)
};
sort(perms);
for(permutation p : perms)
System.out.println(Arrays.toString(p.arr));
Output:
[1, 4, 3, 2]
[3, 1, 2, 4]
[4, 1, 2, 3]
[2, 1, 3, 4]
[4, 1, 3, 2]
[4, 3, 1, 2]
[1, 2, 3, 4]
[4, 3, 2, 1]

Related

Find minimum sum of elements in a matrix

Given a matrix, find the minimum sum of elements such that element is chosen from each row, and the adjacent element should not come from the same column. Assume the matrix only has 3 columns.
example 1:
[[1, 2, 3],
[1, 2, 3],
[3, 3, 1]]
minimum sum = 1 + 2 + 1 = 4 // matrix[0][0] + matrix[1][1] + matrix[2][2] or matrix[0][1] + matrix[1][0] + matrix[2][2]
example 2:
[[1, 100, 1],
[2, 99, 30],
[100, 12, 13]]
minimum sum = 1 + 2 + 12 = 15 // matrix[0][2] + matrix[1][0] + matrix[2][1]
example 3:
[[1, 2, 3],
[2, 5, 4],
[2, 3, 1],
[1, 6, 3]]
minimum sum = 2 + 2 + 1 + 1 = 6 // matrix[0][1] + matrix[1][0] + matrix[2][2] + matrix[3][0]
Here's my code:
public static int minCost(List<List<Integer>> matrix) {
// Write your code here
int rows = matrix.size();
int[] cost = findMin(matrix.get(0), -1);
int total = cost[0];
for (int i = 1; i < rows; i++){
List<Integer> row = matrix.get(i);
cost = findMin(row, cost[1]);
total += cost[0];
}
return total;
}
private static int[] findMin(List<Integer> row, int col){
int[] ans = new int[2];
int min = Integer.MAX_VALUE;
for (int i = 0; i < row.size(); i++) {
if (i == col){
continue;
}
if (row.get(i) < min) {
min = row.get(i);
ans[0] = min;
ans[1] = i;
}
}
return ans;
}
I initially approached this question with Greedy, which is to find the minimum element in a row and the column of the element is different from that of the previous element.
This method does not satisfy examples 2 and 3. I think dynamic programming would be the way to approach this problem but I am not sure how to construct the mem part. How to actually solve this problem with dynamic programming? Thanks in advance!
Yes you need to identify the recursive structure as you have specified in one of your comments.
You could identify as follows:
Lets say you are currently on a row row and the previous column you chose was prevcol then you need to choose a value that is not in the previous column and recurse on the remaining rows and get the minimum of all such values i.e. each time you choose a column that is not previous column and recurse on remaining rows by specifying the prev column chosen was that column you chose just now.
Look at this recursive equation to understand more:
f( arr, row, prevcol ) = minimum of ( for all col not equal to prevcol ( arr[row][col] + f( arr, row + 1, col ) )
you see how to specify the next row and previous column chosen in the call f(arr, row +1, col ) ?
The base condition is if row == arr.length i.e. no rows remaining then result is 0.
And you memoize the values that you get for each combination of row and prevcol
Java code would be :
private static int f( int[][] arr, int row, int prevCol ) {
if ( row == arr.length ) return 0;
int C = arr[row].length;
if ( dp[row][prevCol+1] != Integer.MAX_VALUE ) return dp[row][prevCol+1];
int res = Integer.MAX_VALUE;
for ( int j = 0; j < C; j++ ) {
if ( j != prevCol ) {
int val = arr[row][j] + f ( arr, row + 1, j );
res = Math.min ( res, val );
}
}
dp[row][prevCol+1] = res;
return res;
}
You need to instantiate dp array like:
dp = new int[arr.length][arr[0].length+1];
for ( int[] r : dp ) Arrays.fill(r, Integer.MAX_VALUE);
and you call the function like:
f( arr, 0, -1 ) where 0 is the starting row and -1 is the prevcol. Because prevcol starts with -1 you need to store the value in dp[row][prevcol+1]
and also for your third example the answer is 6 not 9.
row = 0, col = 1 : 2
row = 1, col = 0 : 2
row = 2, col = 2 : 1
row = 3, col = 0 : 1
2 + 2 + 1 + 1 = 6
Thank you so much #SomeDude
This is my python implementation of the same..
import math
def mincost(arr,row,prevcol,n,k):
if row == len(arr):
return 0
C = len(arr[row])
dp = [[math.inf for x in range(k+1)] for y in range(n)]
if dp[row][prevcol+1] != math.inf:
return dp[row][prevcol+1]
res = math.inf
for j in range(C):
if j != prevcol:
val = arr[row][j] + mincost(arr,row+1,j,n,k)
res = min(res,val)
dp[row][prevcol+1] = res
return res
I checked for all the above testcases specifed by #bonus, it works.

Generating Power Set of a String Recursively in Java

I'm trying to do recursive implementation of a Power Set generator working off of some pseudocode I was given, but when given a string like "abc", rather than having sets
{}, {a}, {b}, {c}, {a,b}, {a,c}, {b,c}, and {a,b,c},
I get {}, {0}, {1}, {2}, {0,1}, etc.
public static ArrayList GenerateSubsets(String setString) {
ArrayList A = new ArrayList<String>();
ArrayList temp = new ArrayList<String>();
if(setString.length() > 0) {
temp = GenerateSubsets(setString.substring(0,setString.length() - 1));
for(int i = 0; i < temp.size(); i++) {
System.out.println("Temp i: "+temp.get(i));
A.add(temp.get(i));
A.add(temp.get(i) + " " + (setString.length() - 1));
}
return A;
}
else
A.add("");
return A;
}
This is based directly on the pseudocode, why isn't it working correctly?
Edit: This is the test
public static void main(String[] args) {
ArrayList one = GenerateSubsets("abcd");
for(int i = 0; i < one.size(); i++) {
System.out.print(one.get(i)+ ", ");
if(i%5 == 0) {
System.out.println("");
}
}
}
And I get output of (without the line breaks)
,
3, 2, 2 3, 1, 1 3,
1 2, 1 2 3, 0, 0 3, 0 2,
0 2 3, 0 1, 0 1 3, 0 1 2, 0 1 2 3,
Statement (setString.length() - 1) gives you the index of char. And by concatenating it you receive a Power set of indexes. You need use setString.charAt(setString.length()-1) to receive char at given position.

How to separate range of integers into two equal parts

I have an array of integers like this one
int [] num = {5, 8, 1, 1, 2, 3, 2}
and I want to divide it into 2 parts, so that the total of 2 sets will be as equal as possible: (output)
SET 1: 5 Piece(s)
1
1
2
2
5
Total: 11
SET 2: 2 Piece(s)
8
3
Total: 11
another example is
int [] num = {4, 6, 1, 2, 3, 3, 4}
with output like this:
SET 1: 3 Piece(s)
3
4
4
Total: 11
SET 2: 4 Piece(s)
6
1
2
3
Total: 12
any help? =) thanks
If the array is not too long, try a lazy solution: brute-force. Since all you need is to separate it into two sets, you'll need to check 2^n possibilities, because a number is either in the first set or not (i.e. in the second set).
Here's a sample code I just wrote:
public static int[][] bruteForce(int[] input) {
int n = input.length;
int[][] res = new int[2][n];
int minVal = Integer.MAX_VALUE;
int iMinVal = 0;
int limit = (int) Math.pow(2, n);
for (int i = 0; i < limit; i++) {
int v = i;
int diff = 0;
for (int j = 0; j < n; j++) {
diff = diff + ((v & 1) == 0 ? +1 : -1) * input[j];
v = v >> 1;
}
if (Math.abs(diff) < minVal) {
iMinVal = i;
minVal = Math.abs(diff);
}
}
int a = 0, b = 0;
for (int i = 0; i < n; i++) {
if ((iMinVal & 1) == 0) {
res[0][a++] = input[i];
} else {
res[1][b++] = input[i];
}
iMinVal = iMinVal >> 1;
}
return res;
}
public static void main(String[] args) {
int[] num = {5 ,8 ,1 ,1 ,2 ,3 ,2};
int[] num2 = {4, 6, 1, 2, 3, 3, 4};
int[][] r = bruteForce(num);
System.out.println("First example:");
System.out.println(Arrays.toString(r[0])+ ", sum = "+Arrays.stream(r[0]).sum());
System.out.println(Arrays.toString(r[1])+ ", sum = "+Arrays.stream(r[1]).sum());
r = bruteForce(num2);
System.out.println("Second example:");
System.out.println(Arrays.toString(r[0])+ ", sum = "+Arrays.stream(r[0]).sum());
System.out.println(Arrays.toString(r[1])+ ", sum = "+Arrays.stream(r[1]).sum());
}
output:
First example:
[5, 1, 3, 2, 0, 0, 0], sum = 11
[8, 1, 2, 0, 0, 0, 0], sum = 11
Second example:
[2, 3, 3, 4, 0, 0, 0], sum = 12
[4, 6, 1, 0, 0, 0, 0], sum = 11
If the length of the array is big, then I guess try some smart brute-force, or other methods. Like, sorting the array into non-ascending order, then starting from the biggest value, put each value into the array with less sum, which in the current case give the right answer:
public static int[][] alternative(int[] input) {
int n = input.length;
int[][] res = new int[2][n];
int[] input0 = Arrays.copyOf(input, n);
Arrays.sort(input0);
System.out.println("Input: "+Arrays.toString(input)+", ordered: "+Arrays.toString(input0));
int sum1 = 0, sum2 = 0;
int a = 0, b = 0;
for (int i = n-1; i >= 0; i--) {
if (sum1 <= sum2) {
res[0][a++] = input0[i];
sum1 = sum1 + input0[i];
System.out.println("Adding "+input0[i]+" into set 1 ==> Sum1 = "+sum1);
} else {
res[1][b++] = input0[i];
sum2 = sum2 + input0[i];
System.out.println("Adding "+input0[i]+" into set 2 ==> Sum2 = "+sum2);
}
}
return res;
}
output:
First example:
Input: [5, 8, 1, 1, 2, 3, 2], ordered: [1, 1, 2, 2, 3, 5, 8]
Adding 8 into set 1 ==> Sum1 = 8
Adding 5 into set 2 ==> Sum2 = 5
Adding 3 into set 2 ==> Sum2 = 8
Adding 2 into set 1 ==> Sum1 = 10
Adding 2 into set 2 ==> Sum2 = 10
Adding 1 into set 1 ==> Sum1 = 11
Adding 1 into set 2 ==> Sum2 = 11
[8, 2, 1, 0, 0, 0, 0], sum = 11
[5, 3, 2, 1, 0, 0, 0], sum = 11
Second example:
Input: [4, 6, 1, 2, 3, 3, 4], ordered: [1, 2, 3, 3, 4, 4, 6]
Adding 6 into set 1 ==> Sum1 = 6
Adding 4 into set 2 ==> Sum2 = 4
Adding 4 into set 2 ==> Sum2 = 8
Adding 3 into set 1 ==> Sum1 = 9
Adding 3 into set 2 ==> Sum2 = 11
Adding 2 into set 1 ==> Sum1 = 11
Adding 1 into set 1 ==> Sum1 = 12
[6, 3, 2, 1, 0, 0, 0], sum = 12
[4, 4, 3, 0, 0, 0, 0], sum = 11
For the 0s in the output, you can just write a simple function that create a new arrays without the 0s.
Have a for loop to loop like:
int sum =0:
for(int I=0; I<num.length/2; I++){
System.out.println(num[i]);
sum=sum+num[i];
}
System.out.println(sum);
(Written on ipad excuse any mistakes plz.
We should try with all combinations. For example, if the array is (1,1,100,100), then answer is (100,1) (100,1). If the array is (1,1,50,100) then answer is (1,1,50) (100). I don't think there is any short cut to this. If the array has N elements, then we shall try all combinations (Nc1, NcN01), (Nc2, NcN-2) .. and so on. Then find which of their difference is least.

Calculate the length of the longest ordered sub-sequence within the array

I was looking at websites such as https://projecteuler.net/, and I came across this question:
"Given an unordered array of integers of length N > 0, calculate the length of the longest ordered (ascending from left [lower index] to right [higher index]) sub-sequence within the array."
For the live of me I am struggling to find a solution in Java. Can anyone help?
EDIT:
Some examples:
Example 1
Input: [1, 4, 1, 4, 2, 1, 3, 5, 6, 2, 3, 7]
Expected Output: 4
Example 2
Input: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
Expected Output: 3
Example 3
Input: [2, 7, 1, 8, 2, 8, 1]
Expected Output: 2
A term for what you want to find is a subarray, not a subsequence(according to your examples). You can solve it in a linear time using a simple loop:
int res = 0;
int cur = 0;
for (int i = 0; i < a.length; i++) {
if (i > 0 && a[i] <= a[i - 1])
cur = 0;
cur++;
res = Math.max(res, cur);
}
It is not clear if equal elements are considered ordered. Also you can return if there are not enough elements to create a bigger maxLength.
public static int maxLength(int[] array) {
if (array.length <= 1) return array.length; // check for null also
int maxLength = 1;
int curLength = 1;
for (int i = 1; i < array.length; i++) {
//extra check to finish earlier if possible (you may omit it)
if ((array.length - i + curLength) <= maxLength)
return maxLength;
if (array[i] > array[i-1]) //use >= if equal elements count too
curLength++;
else {
if (maxLength < curLength)
maxLength = curLength;
curLength = 1;
}
}
//final check (in case the last element is included in maxLength)
if (maxLength < curLength)
return curLength;
return maxLength;
}

How to obtain all subsequence combinations of a String (in Java, or C++ etc)

Let's say I've a string "12345" I should obtain all subsequence combinations of this string such as:
--> 1 2 3 4 5
--> 12 13 14 15 23 24 25 34 35 45
--> 123 124 125 234 235 345
--> 1234 1235 1245 1345 2345
--> 12345
Please note that I grouped them in different number of chars but not changed their order. I need a method/function does that.
You want a powerset. Here are all the questions on StackOverflow that mention powersets or power sets.
Here is a basic implementation in python:
def powerset(s):
n = len(s)
masks = [1<<j for j in xrange(n)]
for i in xrange(2**n):
yield [s[j] for j in range(n) if (masks[j] & i)]
if __name__ == '__main__':
for elem in powerset([1,2,3,4,5]):
print elem
And here is its output:
[]
[1]
[2]
[1, 2]
[3]
[1, 3]
[2, 3]
[1, 2, 3]
[4]
[1, 4]
[2, 4]
[1, 2, 4]
[3, 4]
[1, 3, 4]
[2, 3, 4]
[1, 2, 3, 4]
[5]
[1, 5]
[2, 5]
[1, 2, 5]
[3, 5]
[1, 3, 5]
[2, 3, 5]
[1, 2, 3, 5]
[4, 5]
[1, 4, 5]
[2, 4, 5]
[1, 2, 4, 5]
[3, 4, 5]
[1, 3, 4, 5]
[2, 3, 4, 5]
[1, 2, 3, 4, 5]
Notice that its first result is the empty set. Change the iteration from this for i in xrange(2**n): to this for i in xrange(1, 2**n): if you want to skip an empty set.
Here is the code adapted to produce string output:
def powerset(s):
n = len(s)
masks = [1<<j for j in xrange(n)]
for i in xrange(2**n):
yield "".join([str(s[j]) for j in range(n) if (masks[j] & i)])
Edit 2009-10-24
Okay, I see you are partial to an implementation in Java. I don't know Java, so I'll meet you halfway and give you code in C#:
static public IEnumerable<IList<T>> powerset<T>(IList<T> s)
{
int n = s.Count;
int[] masks = new int[n];
for (int i = 0; i < n; i++)
masks[i] = (1 << i);
for (int i = 0; i < (1 << n); i++)
{
List<T> newList = new List<T>(n);
for (int j = 0; j < n; j++)
if ((masks[j] & i) != 0)
newList.Add(s[j]);
yield return newList;
}
}
The simplest algorithm for generating subsets of a set of size N is to consider all binary numbers using N bits. Each position in the number represents an element from the set. If a bit in the number is 1, the corresponding set element is in the subset, otherwise the element isn't in the subset. Since the bits in a number are ordered, this preserves the ordering of the original set.
References:
"Efficiently Enumerating the Subsets of a Set"; Loughry, Hemert and Schoofs
"Generating Subsets"; Stony Brook Algorithm Repository
way way cleaner approach can be achieved through recursion as follows.
Public class StrManipulation{
public static void combinations(String suffix,String prefix){
if(prefix.length()<0)return;
System.out.println(suffix);
for(int i=0;i<prefix.length();i++)
combinations(suffix+prefix.charAt(i),prefix.substring(i+1,prefix.length()));
}
public static void main (String args[]){
combinations("","12345");
}
}
In C++ given the following routine:
template <typename Iterator>
bool next_combination(const Iterator first, Iterator k, const Iterator last)
{
/* Credits: Mark Nelson http://marknelson.us */
if ((first == last) || (first == k) || (last == k))
return false;
Iterator i1 = first;
Iterator i2 = last;
++i1;
if (last == i1)
return false;
i1 = last;
--i1;
i1 = k;
--i2;
while (first != i1)
{
if (*--i1 < *i2)
{
Iterator j = k;
while (!(*i1 < *j)) ++j;
std::iter_swap(i1,j);
++i1;
++j;
i2 = k;
std::rotate(i1,j,last);
while (last != j)
{
++j;
++i2;
}
std::rotate(k,i2,last);
return true;
}
}
std::rotate(first,k,last);
return false;
}
You can then proceed to do the following:
std::string s = "12345";
for(std::size_t i = 1; i <= s.size(); ++i)
{
do
{
std::cout << std::string(s.begin(),s.begin() + i) << std::endl;
}
while(next_combination(s.begin(),s.begin() + i,s.end()));
}
using python, the itertools module defines a combinations() method which does just what you need.
from itertools import *
list(combinations( '12345', 2 ))
will give you:
[('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '4'), ('3', '5'), ('4', '5')]
Java implementation of outis' answer, taking the input strings as args.
import java.util.ArrayList;
import java.util.List;
public class Combo {
public static void main(String[] args) {
List<String> results = new ArrayList<String>();
for ( int i = 1; i <= (1<<(args.length))-1; i++ ) {
StringBuilder builder = new StringBuilder();
for ( int j = 0; j < args.length; j++ ) {
if ( (i & (1<<j)) != 0) {
builder.append(args[j]);
}
}
results.add(builder.toString());
}
System.out.println( results );
}
}
Here's a run.
> javac Combo.java
> java Combo A B C
[A, B, AB, C, AC, BC, ABC]
You can use the following class for this (in Java):
class Combinations {
String input;
StringBuilder cur;
private void next(int pos, int reminder) {
cur.append(input.charAt(pos));
if (reminder == 1) {
System.out.println(cur);
} else {
for (int i = pos + 1; i + reminder - 1 <= input.length(); i++)
next(i, reminder - 1);
}
cur.deleteCharAt(cur.length() - 1);
}
public void generate(String input) {
cur = new StringBuilder();
this.input = input;
for (int length = 1; length <= input.length(); length++)
for (int pos = 0; pos + length <= input.length(); pos++)
next(pos, length);
}
}
To run your example use the following code:
new Combinations().generate("12345");
The order of the output is the same as in example.
It does not require to store all subsets and then sort them to obtain the order you described.
The code to generate all possible combinations of strings is given in java. The all possible combinations of string of length 4 is 2 ^ 4 (2 raised to the power 4). In general for a string of length n the possible combinations are 2 ^ n (2 raised to the power n). Hence the code:
class Perms
{
public void permsOfString(String a)
{
int x = 1;
/*
Computes 2^string length
*/
for(int i = 0;i<a.length() ;i++)
{
x = x * 2;
}
/*
Iterate through all the possible combinations using a binary value of the number
*/
for(int i = 1 ;i<x;i++)
{
String binStr = Integer.toBinaryString(i); // Convert i to binary string
for(int j = binStr.length() ; j < a.length() ;j++)
{
binStr = "0"+binStr; // left pad with 0s
}
/*loop through the binary string if a character at the string is '1' note the index,then display the character of the given string with that index */
for(int k = 0; k <binStr.length();k++)
{
if(binStr.charAt(k) == '0') continue;
else
{
System.out.print(a.charAt(k));
}
}
System.out.println();
}
}
public static void main(String[]s)
{
Perms p = new Perms();
p.permsOfString("abcd");
}
}
Adrien Plisson's answer shows how one retrieves all subsequences of a specified length in Python (for arbitrary sequence data types). The OP specifies that he works with strings, and that he wants all subsequences. Thus, using itertools.combinations we define:
>>> from itertools import combinations
>>> def subseq_combos(inp):
... return (''.join(s) for r in range(len(inp) + 1) for s in combinations(inp, r))
...
>>> list(subseq_combos('12345'))
['', '1', '2', '3', '4', '5', '12', '13', '14', '15', '23', '24', '25', '34', '35', '45', '123', '124', '125', '134', '135', '145', '234', '235', '245', '345', '1234', '1235', '1245', '1345', '2345', '12345']
(If the empty subsequence should be omitted, then use range(1, len(inp) + 1)).)
oops, wrong answer:
Subsequences of a certain length in Python:
def subseqs(seq, length):
for i in xrange(len(seq) - length + 1):
yield seq[i:i+length]
Used like this:
for each in subseqs("hello", 3):
print each
prints:
hel
ell
llo
To generate all subsequences do this:
for i in xrange(len("hello")):
for each in subseqs("hello", i + 1):
print each
prints:
h
e
l
l
o
he
el
ll
lo
hel
ell
llo
hell
ello
hello
Mick.
Now I see, you wanted subsets, not sublists.
C implementation
//Usage
combinations((char*)"",(char*)"12346897909787");
void combinations(char* suffix,char* prefix){
if(NULL ==prefix || NULL == suffix){ return ;}
int prefixLen = strlen(prefix);
printf("\n[%s]",suffix);
int slen = strlen(suffix);
char* s = (char*)malloc(slen+2);
s[slen+1] = '\0';
for(int i=0;i<prefixLen;i++){
strcpy(s,suffix);
s[slen] = prefix[i];
int npfl = prefixLen-(i+1);
char* p = (char*) malloc(npfl+1);
p[npfl] = '\0';
strcpy(p,prefix+i+1);
combinations(s,p);
free(p);
}
free(s);
}
C++ solution:
#include<iostream>
#include<string>
using namespace std;
int sub[10];
void next(int max, int length) {
int pos = length - 1;
//find first digit that can be increased
while(pos >= 0)
{
if(sub[pos] == max - (length - 1 - pos))
pos--;
else
break;
}
sub[pos]++; //increase digit
//update other digits
for(int a = pos+1; a < length; a++)
sub[a] = sub[a-1] + 1;
}
int main()
{
string word;
cin >> word;
int max = word.length() - 1; //max value
for(int n=1; n <= max+1; n++)
{
cout << n << "\n----\n";
for(int i = 0; i < n; i++)
{
sub[i] = i;
}
for(int a = 0; ; a++)
{
for(int b=0; b < n; b++)
cout << word[sub[b]];
cout << '\n';
if(sub[0] == max - (n - 1))
break;
else
next(max, n); //maximum value and last position
}
cout << '\n';
}
return 0;
}
> for input :Sigma
> output is
1
----
s
i
g
m
a
2
----
si
sg
sm
sa
ig
im
ia
gm
ga
ma
3
----
sig
sim
sia
sgm
sga
sma
igm
iga
ima
gma
4
----
sigm
siga
sima
sgma
igma
5
----
sigma
public class Sub {
public static void main(String[] args) {
String str="ADDIS";
Sub.DisplaySubsequence( str.toCharArray(),
str.toCharArray().length,0 );
}
public static void DisplaySubsequence(char[] set, int n, int index){
if(n>index){
String x =String.valueOf(set[index]);
System.out.println(x);
String concat=x;
for(int j=index+1; j<n; j++){
concat=concat.concat(String.valueOf(set[j]));
System.out.println(concat);
}
DisplaySubsequence(set, n,index+1);
}
return 0;
}
}

Categories