I\'m struggling with this algorithm I need to write. I\'m using C#.
Say I have a List
and I have a List
.
I need to
I have a method that recreates your example above. The approach is actually to think of the bags as positions of a number... for if you look at your example you could read it as 11, 12,13,21,22,23. Then it's a matter of converting to base Lunch.Count. Also I stole a method from here: https://stackoverflow.com/a/95331/483179 to convert to any base which it was mentioned it was untested so you may have to build something more robust. Finally I didn't do any edge condition testing so feeding in 0 bags could have unexpected results. Here is what I came up with.
class Program
{
static List bags = new List();
static List lunches = new List();
static void Main(string[] args)
{
lunches.Add(new Lunch() { Num = 1 });
lunches.Add(new Lunch() { Num = 2 });
lunches.Add(new Lunch() { Num = 3 });
bags.Add(new Bag() { Num = 1 });
bags.Add(new Bag() { Num = 2 });
int count = 0;
while (count < Math.Pow(lunches.Count, bags.Count))
{
Console.WriteLine("Permutation " + count);
string countNumber = ConvertToBase(count, lunches.Count).PadLeft(bags.Count,'0');
for (int x = 0; x < bags.Count; x++)
{
Console.WriteLine(bags[x] + " " + lunches[Convert.ToInt32((""+countNumber[x]))]);
}
Console.WriteLine("");
count++;
}
Console.ReadLine();
}
static string ConvertToBase(int value, int toBase)
{
if (toBase < 2 || toBase > 36) throw new ArgumentException("toBase");
if (value < 0) throw new ArgumentException("value");
if (value == 0) return "0"; //0 would skip while loop
string AlphaCodes = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string retVal = "";
while (value > 0)
{
retVal = AlphaCodes[value % toBase] + retVal;
value /= toBase;
}
return retVal;
}
}
class Lunch
{
public int Num { get;set;}
public override string ToString()
{
return "Lunch " + Num;
}
}
class Bag
{
public int Num { get;set;}
public override string ToString()
{
return "Bag " + Num;
}
}
and the resultant output:
Permutation 0
Bag 1 Lunch 1
Bag 2 Lunch 1
Permutation 1
Bag 1 Lunch 1
Bag 2 Lunch 2
Permutation 2
Bag 1 Lunch 1
Bag 2 Lunch 3
Permutation 3
Bag 1 Lunch 2
Bag 2 Lunch 1
Permutation 4
Bag 1 Lunch 2
Bag 2 Lunch 2
Permutation 5
Bag 1 Lunch 2
Bag 2 Lunch 3
Permutation 6
Bag 1 Lunch 3
Bag 2 Lunch 1
Permutation 7
Bag 1 Lunch 3
Bag 2 Lunch 2
Permutation 8
Bag 1 Lunch 3
Bag 2 Lunch 3