Task: Dutch national flag problem



C#: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RosettaCode
{
    class Program
    {
        static void QuickSort(IComparable[] elements, int left, int right)
        {
            int i = left, j = right;
            IComparable pivot = elements[left + (right - left) / 2];

            while (i <= j)
            {
                while (elements[i].CompareTo(pivot) < 0) i++;
                while (elements[j].CompareTo(pivot) > 0) j--;

                if (i <= j)
                {
                    
                    IComparable tmp = elements[i];
                    elements[i] = elements[j];
                    elements[j] = tmp;
                    i++;
                    j--;
                }
            }

            
            if (left < j) QuickSort(elements, left, j);
            if (i < right) QuickSort(elements, i, right);
        }
        const int NUMBALLS = 5;
        static void Main(string[] args)
        {
            Func<string[], bool> IsSorted = (ballList) =>
                {
                    int state = 0;
                    for (int i = 0; i < NUMBALLS; i++)
                    {
                        if (int.Parse(ballList[i]) < state)
                            return false;
                        if (int.Parse(ballList[i]) > state)
                            state = int.Parse(ballList[i]);
                    }
                    return true;
                };
            Func<string[], string> PrintOut = (ballList2) =>
                {
                    StringBuilder str = new StringBuilder();
                    for (int i = 0; i < NUMBALLS; i++)
                        str.Append(int.Parse(ballList2[i]) == 0 ? "r" : int.Parse(ballList2[i]) == 1 ? "w" : "b");
                    return str.ToString();
                };
            bool continueLoop = true;
            string[] balls = new string[NUMBALLS]; 
            Random numberGenerator = new Random();
            do 
            {
                
                for (int i = 0; i < NUMBALLS; i++)
                    balls[i] = numberGenerator.Next(3).ToString();

                continueLoop = IsSorted(balls);
                if (continueLoop)
                    Console.WriteLine("Accidentally still sorted: {0}", PrintOut(balls));
            } while (continueLoop);
            Console.WriteLine("Non-sorted: {0}", PrintOut(balls));
            QuickSort(balls, 0, NUMBALLS - 1); 
            Console.WriteLine("{0}: {1}", IsSorted(balls) ? "Sorted" : "Sort failed", PrintOut(balls));
        }
    }
}





Python: import random

colours_in_order = 'Red White Blue'.split()

def dutch_flag_sort(items, order=colours_in_order):
    'return sort of items using the given order'
    reverse_index = dict((x,i) for i,x in enumerate(order))
    return sorted(items, key=lambda x: reverse_index[x])

def dutch_flag_check(items, order=colours_in_order):
    'Return True if each item of items is in the given order'
    reverse_index = dict((x,i) for i,x in enumerate(order))
    order_of_items = [reverse_index[item] for item in items]
    return all(x <= y for x, y in zip(order_of_items, order_of_items[1:]))

def random_balls(mx=5):
    'Select from 1 to mx balls of each colour, randomly'
    balls = sum([[colour] * random.randint(1, mx)
                 for colour in colours_in_order], [])
    random.shuffle(balls)
    return balls

def main():
    
    while True:
        balls = random_balls()
        if not dutch_flag_check(balls):
            break
    print("Original Ball order:", balls)
    sorted_balls = dutch_flag_sort(balls)
    print("Sorted Ball Order:", sorted_balls)
    assert dutch_flag_check(sorted_balls), 'Whoops. Not sorted!'

if __name__ == '__main__':
    main()