I am trying to find combinations of strings in an array {"A","B","C"}
without repetition and order of elements should be preserved in subset.
Desired order is [["B","C"], ["A","C"], ["A","B"], ["A","B","C"], ["A"], ["C"], ["B"]]
. I have tried writing logic using the answers found in this question, and found that order of elements are not preserved.
public static Set <JSONArray> getCombinations( int k , JSONArray properties )
{
Set <JSONArray> combinations = new LinkedHashSet <JSONArray>();
try
{
if ( k == 0 )
{
combinations.add( new JSONArray() );
return combinations;
}
for ( int i = 0 ; i < properties.length() ; i++ )
{
String element = properties.getString( i );
JSONArray sublist = getSublist( properties , i + 1 );
combinations.add( sublist );
Set <JSONArray> combinations2 = getCombinations( k - 1 , sublist );
for ( JSONArray previous : combinations2 )
{
previous.put( element );
combinations.add( previous );
}
}
}
catch ( Exception e )
{
System.out.println( "Exception :: " + e );
}
return combinations;
}
public static JSONArray getSublist( JSONArray list , int i ) throws JSONException
{
JSONArray sublist = new JSONArray();
for ( int j = i ; j < list.length() ; j++ )
{
sublist.put( list.getString( j ) );
}
return reverseArray( sublist );
}
Output is :: [["B","C"], ["C","A"], ["B","A"], ["C","B","A"], ["A"], ["C"], ["B"]]
. But i need the order to be preserved like ["C","A"] should be ["A","C"]. Any thoughts would be helpful.
PS: The order of subsets does not matter, but the order of elements inside the subset is.