Skip to content

Instantly share code, notes, and snippets.

@joelmartinez
Created September 5, 2013 18:26
Show Gist options
  • Save joelmartinez/6454124 to your computer and use it in GitHub Desktop.
Save joelmartinez/6454124 to your computer and use it in GitHub Desktop.
simple proof of concept to generate permutations from two lists ... First, there needed to be every permutation for the platforms list. Second was a permutation of the platform and tags lists.
using System;
using System.Linq;
using System.Collections.Generic;
namespace Permutations
{
class MainClass
{
public static void Main (string[] args)
{
var m = new Model
{
Tags = new List<string> {"Graphics", "UI", "Data", "Another" },
Platforms = new List<string>{"Android", "iOS", "Mac", "windows-rt", "windows-8"}
};
for (int i = 0; i < 200; i++) {
m.Tags.Add (i.ToString());
}
HashSet<string> covered = new HashSet<string> ();
var list = m.Platforms;
Dictionary<string, int> originalSort = new Dictionary<string, int> ();
for (int i = 0; i < list.Count; i++) originalSort.Add (list [i], i);
GeneratePermutations (covered, list, originalSort);
// This generates the platform/tag permutations
var query = from tag in m.Tags
join plat in m.Platforms on true equals true
select new { Platform = plat, Tag = tag };
foreach (var i in query) {
Console.WriteLine ("{0} - {1}", i.Platform, i.Tag);
}
Console.WriteLine ("\n\tDone displaying {0} platforms and {1} tags for a total of {2} entries", m.Platforms.Count, m.Tags.Count, m.Platforms.Count * m.Tags.Count);
}
static void GeneratePermutations (HashSet<string> covered, List<string> list, Dictionary<string, int> originalSort, int start=0)
{
int origCount = list.Count;
for (int i = 0; i < origCount; i++) {
var current = list [i];
for (int y = start; y < origCount; y++) {
var append = list [y];
var newEntry = string.Concat (current, ",", append);
// sort
newEntry = string.Join(",", newEntry.Split (',')
.OrderBy (s => originalSort [s])
.ToArray());
var currentSet = new HashSet<string> (current.Split (','));
var appendSet = new HashSet<string> (append.Split (','));
if ( y > i
&& current != append
&& !currentSet.Overlaps(appendSet)
&& !covered.Contains (newEntry) // makes sure we haven't added it already
) {
list.Add (newEntry);
covered.Add (newEntry);
}
}
}
if (origCount < list.Count) {
GeneratePermutations (covered, list, originalSort, origCount);
}
}
}
public class Model
{
public List<string> Tags;
public List<string> Platforms;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment