[Fork] OrderingSample3

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;


public class Program
{
	public static void Main()
	{
		
		var goals = new List<Goal>();
		
		goals.Add(new Goal(){ID=1, Level=1, Active = true});
		goals.Add(new Goal(){ID=2, Level=1, Active = false});
		goals.Add(new Goal(){ID=3, Level=2, Active = true});
		goals.Add(new Goal(){ID=4, Level=2, Active = true});
		goals.Add(new Goal(){ID=5, Level=2, Active = false});
		goals.Add(new Goal(){ID=6, Level=2, Active = false});
		goals.Add(new Goal(){ID=7, Level=2, Active = false});
		goals.Add(new Goal(){ID=8, Level=2, Active = false});
		goals.Add(new Goal(){ID=9, Level=2, Active = false});
		goals.Add(new Goal(){ID=10, Level=2, Active = true});
		goals.Add(new Goal(){ID=11, Level=2, Active = true});
		goals.Add(new Goal(){ID=12, Level=2, Active = true});
		goals.Add(new Goal(){ID=13, Level=2, Active = true});
		goals.Add(new Goal(){ID=14, Level=2, Active = true});
		goals.Add(new Goal(){ID=15, Level=2, Active = true});
		goals.Add(new Goal(){ID=16, Level=2, Active = true});


		Random rnd = new Random();


	    Comparison<Goal> comparison =  (a, b) => {
			 // first chooses the Active ones (if any)
			 var sort = b.Active.CompareTo(a.Active);
			
		   if (sort == 0) {
			// then sort by level
			return sort = (a.Level).CompareTo(b.Level);
			} else 
		   {
			   return sort;
           }
	     };

		


		
		goals.Sort(comparison);


		int startIndex = 0;
		int endIndex = 0;
		
		while (startIndex < goals.Count)
		{
			for (endIndex = startIndex + 1; endIndex < goals.Count; ++endIndex)
			{
				if (comparison(goals[startIndex], goals[endIndex]) != 0)
				{
					//End of tie
					break;
				}
			}
			
			if (endIndex - startIndex > 1)
			{
				ShuffleRange(goals, startIndex, endIndex - startIndex, rnd);
			}
			
			startIndex = endIndex;
		}	
		


 	    foreach(var g in goals)
	    {
		   Console.WriteLine("ID={0:00}, Level={1}, Active={2}", g.ID, g.Level, g.Active);   		   
	    }
		
	}

	

	static void ShuffleRange<T>(List<T> list, int startIndex, int count, Random rnd)
	{
		 int n = startIndex + count;  
         while (n > startIndex + 1) 
		 {  
            int k = rnd.Next(startIndex, n--);  
            T value = list[k];  
            list[k] = list[n];  
            list[n] = value;  
        }  
	}

}



    public class Goal {
      public int ID;
      public int Level;
    public bool Active;
}
;