There is python code that will fill a list given a k
number
k=4
myList = {}
for objectOfInterest in [''.join(item) for item in product('01', repeat=k)]:
if objectOfInterest[:-1] in myList:
myList[objectOfInterest[:-1]].append(objectOfInterest[1:])
else:
myList[objectOfInterest[:-1]] = [objectOfInterest[1:]]
Resulting on:
k=3
{'11': ['10', '11'], '10': ['00', '01'], '00': ['00', '01'], '01': ['10', '11']}
k=4
{'010': ['100', '101'], '011': ['110', '111'], '001': ['010', '011'], '000': ['000', '001'], '111': ['110', '111'], '110': ['100', '101'], '100': ['000', '001'], '101': ['010', '011']}
when k=5
{'0110': ['1100', '1101'], '0111': ['1110', '1111'], '0000': ['0000', '0001'], '0001': ['0010', '0011'], '0011': ['0110', '0111'], '0010': ['0100', '0101'], '0101': ['1010', '1011'], '0100': ['1000', '1001'], '1111': ['1110', '1111'], '1110': ['1100', '1101'], '1100': ['1000', '1001'], '1101': ['1010', '1011'], '1010': ['0100', '0101'], '1011': ['0110', '0111'], '1001': ['0010', '0011'], '1000': ['0000', '0001']}
I would like to translate it to c# code What would be the best way, I was thinking LINQ could help...
int k =4;
string myList ="";
How would loop
objectOfInterest in [''.join(item) for item in product('01', repeat=k)]:
look like in c#? Is it a foraech item in objectOfInterest...
knowing the fact an stackoverflow answer suggests:
public static List< Tuple<T, T> > Product<T>(List<T> a, List<T> b)
where T : struct
{
List<Tuple<T, T>> result = new List<Tuple<T, T>>();
foreach(T t1 in a)
{
foreach(T t2 in b)
result.Add(Tuple.Create<T, T>(t1, t2));
}
return result;
}
n.b. struct here means that T must be a value type or a structure. Change it to class if you need to throw in objects such as Lists, but be aware of potential referencing issues.
Then as a driver:
List<int> listA = new List<int>() { 1, 2, 3 };
List<int> listB = new List<int>() { 7, 8, 9 };
List<Tuple<int, int>> product = Product<int>(listA, listB);
foreach (Tuple<int, int> tuple in product)
Console.WriteLine(tuple.Item1 + ", " + tuple.Item2);
Output:
1, 7
1, 8
1, 9
2, 7
2, 8
2, 9
3, 7
3, 8
3, 9