Array of array combinations
This turned out to be harder than it looks, but the following should demonstrate the idea.
There are two steps - create an array list pairs of each operator and its reverse and then recursively permute these together.
void DoProblem()
{
//string[] arrSample = new string[] { "!=", "=" };
string[] arrSample = new string[] { "!=", "<","+" };
string[][] arrPairs = (from op in arrSample select new string[]{op, GetReverse(op)}).ToArray();
List<Array> myList = new List<Array>();
myList.AddRange(arrPairs);
foreach (string x in Permute(0, myList))
{
Console.WriteLine(x);
}
}
List<string> Permute(int a, List<Array> x)
{
List<string> retval = new List<string>();
if (a == x.Count)
{
retval.Add("");
return retval;
}
foreach (Object y in x[a])
{
foreach (string x2 in Permute(a + 1, x))
{
retval.Add(y.ToString() + "," + x2.ToString());
}
}
return retval;
}
string GetReverse(string op)
{
switch (op) {
case "=":
return "!=";
case "!=":
return "=";
case "<":
return ">";
case "+":
return "-";
default:
return "";
}
}
NOTE: The permute function is based on the permute an Array of Arrays answer here: C# Permutation of an array of arraylists?
Generate combination using string array in c#
You could use a simple recursion:
private static IEnumerable<string> Combinations(int start, int level)
{
for ( int i = start; i < array.Length; i++ )
if ( level == 1 )
yield return array[i];
else
foreach ( string combination in Combinations(i + 1, level - 1) )
yield return String.Format("{0} {1}", array[i], combination);
}
The call it like this:
var combinations = Combinations(0, 2);
foreach ( var item in combinations )
Console.WriteLine(item);
Find all permutations(cartesian product) from a listlistint in java
You can use recursion to achieve this, to merge the first list with the tail list(a list of list).
public class Permutation {
public static List<List<Integer>> calculate(List<List<Integer>> input) {
List<List<Integer>> result= new ArrayList<List<Integer>>();//
if (input.isEmpty()) { // If input is an empty list
result.add(new ArrayList<Integer>());// then add empty list to the resultand return
return result;
} else {//here we have a non-empty list to process
List<Integer> head = input.get(0);//get the first list as a head
List<List<Integer>> tail= calculate(input.subList(1, input.size()));//recursion to calculate a tail list to calculate a tail list
for (Integer h : head) {//we merge every head element with every tail list
for (List<Integer> t : tail) {
List<Integer> resultElement= new ArrayList<Integer>();//here is a new element of our result list
resultElement.add(h);//firstly, add the head element to this tmp list
resultElement.addAll(t);//add all the element from the tail list
result.add(resultElement);
}
}
}
return result;
}
public static void main(String[] args) {
List<List<Integer>> bigList=Arrays.asList(Arrays.asList(1,2),Arrays.asList(3,4),Arrays.asList(5,6));
System.out.println(calculate(bigList));
}
}
output:
[[1, 3, 5, 7], [1, 3, 5, 8], [1, 3, 6, 7], [1, 3, 6, 8], [1, 4, 5, 7], [1, 4, 5, 8], [1, 4, 6, 7], [1, 4, 6, 8], [2, 3, 5, 7], [2, 3, 5, 8], [2, 3, 6, 7], [2, 3, 6, 8], [2, 4, 5, 7], [2, 4, 5, 8], [2, 4, 6, 7], [2, 4, 6, 8]]
C# Permutations of String
We can do this in a fancy way with LINQ. First, we'll need Eric Lippert's CartesianProduct extension method:
static IEnumerable<IEnumerable<T>> CartesianProduct<T>( this IEnumerable<IEnumerable<T>> sequences )
{
IEnumerable<IEnumerable<T>> emptyProduct =
new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
( accumulator, sequence ) =>
from accseq in accumulator
from item in sequence
select accseq.Concat( new[] { item } ) );
}
Then we can simply do:
var a = "1|2,3|4".Split( ',' );
var b = a.Select( x => x.Split( '|' ) );
var res = b.CartesianProduct().Select( x => string.Join( ",", x ) );
And we're done!
List all permutations & combinations in Integer Arraylist recursively
The need for L=a.size()
should've been a hint. sub
and a
values should be preserved (their positions and values) for a proper functioning.
Below code creates a new copy of the array lists and operates on them:
public static void perm2(ArrayList<Integer> a) {
ArrayList<Integer> sub = new ArrayList<Integer>();
perm2(sub, a);
}
public static void perm2(ArrayList<Integer> sub, ArrayList<Integer> a) {
int L = a.size();
if (L == 0) System.out.println(sub);
else {
System.out.println(sub);
for (int i = 0; i < L; i++) {
ArrayList<Integer> ab = new ArrayList<Integer>(sub);
ab.add(a.get(i));
ArrayList<Integer> bc = new ArrayList<Integer>(a);
bc.remove(i);
perm2(ab, bc);
}
}
}
Best way to randomize an array with .NET
If you're on .NET 3.5, you can use the following IEnumerable coolness:
Random rnd=new Random();
string[] MyRandomArray = MyArray.OrderBy(x => rnd.Next()).ToArray();
Edit: and here's the corresponding VB.NET code:
Dim rnd As New System.Random
Dim MyRandomArray = MyArray.OrderBy(Function() rnd.Next()).ToArray()
Second edit, in response to remarks that System.Random "isn't threadsafe" and "only suitable for toy apps" due to returning a time-based sequence: as used in my example, Random() is perfectly thread-safe, unless you're allowing the routine in which you randomize the array to be re-entered, in which case you'll need something like lock (MyRandomArray)
anyway in order not to corrupt your data, which will protect rnd
as well.
Also, it should be well-understood that System.Random as a source of entropy isn't very strong. As noted in the MSDN documentation, you should use something derived from System.Security.Cryptography.RandomNumberGenerator
if you're doing anything security-related. For example:
using System.Security.Cryptography;
...
RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
string[] MyRandomArray = MyArray.OrderBy(x => GetNextInt32(rnd)).ToArray();
...
static int GetNextInt32(RNGCryptoServiceProvider rnd)
{
byte[] randomInt = new byte[4];
rnd.GetBytes(randomInt);
return Convert.ToInt32(randomInt[0]);
}
Related Topics
Convert Datetime to Julian Date in C# (Tooadate Safe)
How to Suppress a Stylecop Warning
Generics: Casting and Value Types, Why Is This Illegal
Easier Way of Writing Null or Empty
Encoding Space Character in Xml Name
How to Use a Client Certificate to Authenticate and Authorize in a Web API
Bind Datagrid Column Visibility Mvvm
Start May Not Be Called on a Promise-Style Task. Exception Is Coming
How to Optionally Turn Off the JSONignore Attribute at Runtime
C# Instantiate Generic List from Reflected Type
ASP.NET How to Stream File to User
Hook on Default "Paste" Event of Winforms Textbox Control
Does C# Allow Double Semicolon ; ; If So, Are There Any Special Ways
Wrap Properties with Cdata Section - Xml Serialization C#