view Arrays.cs @ 89:cd96f6078edb

Re #2: Refactor API * Make Arrays use generics for better return types
author IBBoard <dev@ibboard.co.uk>
date Sat, 21 Aug 2010 18:22:23 +0000
parents 3200ed24d29e
children 1575d57a8423
line wrap: on
line source

// This file (Array.cs) is a part of the IBBoard library and is copyright 2009 IBBoard.
//
// The file and the library/program it is in are licensed under the GNU LGPL license, either version 3 of the License or (at your option) any later version. Please see COPYING.LGPL for more information and the full license.

using System;
using System.Collections.Generic;

namespace IBBoard
{
	/// <summary>
	/// Summary description for Arrays.
	/// </summary>
	public class Arrays
	{
		public static T[] Subtract<T>(T[] items, T[] subtract)
		{
			List<T> arr = new List<T>();
			arr.AddRange(items);
			
			foreach (T obj in subtract)
			{
				arr.Remove(obj);
			}

			return arr.ToArray();
		}

		public static T[] Difference<T>(T[] items1, T[] items2)
		{
			T[] diffObjs;


			//Difference with as few loops as possible, so see which is shortest			
			if (items1.Length >= items2.Length)
			{
				//add everything from the first list
				diffObjs = DoDifference(items1, items2);
			}
			else
			{
				diffObjs = DoDifference(items2, items1);
			}

			return diffObjs;
		}

		private static T[] DoDifference<T>(T[] longArray, T[] shortArray)
		{
			List<T> arr = new List<T>();
			arr.AddRange(longArray);

			foreach (T obj in shortArray)
			{
				if (arr.Contains(obj))
				{
					arr.Remove(obj);
				}
				else
				{
					arr.Add(obj);
				}
			}
			
			return arr.ToArray();
		}
		
		public static int IndexOf<T>(T[] items, T item)
		{
			return Array.IndexOf(items, item);
		}

		public static bool Contains<T>(T[] items, T item)
		{
			return IndexOf(items, item) != -1;
		}
	}
}