Skip to content

Instantly share code, notes, and snippets.

@chandermani
Created May 23, 2012 15:20
Show Gist options
  • Save chandermani/2775849 to your computer and use it in GitHub Desktop.
Save chandermani/2775849 to your computer and use it in GitHub Desktop.
Determining largest increasing sequence in an interger array using Patience Sort.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Algorithms
{
/// <summary>
/// Calculating longest sequence using Patience Sort. See here http://wordaligned.org/articles/patience-sort
/// </summary>
class LongestIncreasingSequence
{
public List<int> Calculate(List<int> deck)
{
List<int> longestIncreasingSequence = new List<int>();
List<Stack<LinkedNode<int>>> piles = new List<Stack<LinkedNode<int>>>();
for (int i = 0; i < deck.Count; i++)
{
int addToPileNumber = DeterminePileToAddNumberTo(deck[i], piles);
LinkedNode<int> data = new LinkedNode<int>(deck[i]);
if (addToPileNumber == -1) //No suitable pile found. Create a new one
{
Stack<LinkedNode<int>> newStack = new Stack<LinkedNode<int>>();
piles.Add(newStack);
newStack.Push(data);
if (piles.Count > 1)
{
data.Next = piles[piles.Count - 2].Peek();
}
}
else
{
if (addToPileNumber > 0)
{
data.Next=piles[addToPileNumber - 1].Peek();
}
piles[addToPileNumber].Push(data);
}
}
System.Diagnostics.Debug.WriteLine("Total number of piles created were {0}. Therefore the sequence size should be {0}", piles.Count);
return GetSequenceFromLinkedNodes(piles[piles.Count-1].Peek());
}
private List<int> GetSequenceFromLinkedNodes(LinkedNode<int> LinkedNode)
{
Stack<int> largestSequenceStack = new Stack<int>();
largestSequenceStack.Push(LinkedNode.Data);
while (LinkedNode.Next != null)
{
LinkedNode = LinkedNode.Next;
largestSequenceStack.Push(LinkedNode.Data);
}
return largestSequenceStack.ToList();
}
private int DeterminePileToAddNumberTo(int number, List<Stack<LinkedNode<int>>> piles)
{
return piles.FindIndex(p => p.Peek().Data > number);
}
}
/// <summary>
/// Stores the data and links to another node. Did not use LinkedListNode as it does not allow to set the next pointer.
/// </summary>
/// <typeparam name="T"></typeparam>
class LinkedNode<T>
{
public LinkedNode()
{
}
public LinkedNode(T data)
{
this.Data = data;
}
public T Data { get; set; }
public LinkedNode<T> Next { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment