view Arrays.cs @ 88:3200ed24d29e

Re #2: Refactor API * Break out common code from Array Difference method * Make use of existing "index of" method
author IBBoard <dev@ibboard.co.uk>
date Sat, 21 Aug 2010 16:02:05 +0000
parents cc7fae81afec
children cd96f6078edb
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;

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

			return arr.ToArray();
		}

		public static object[] Difference(object[] items1, object[] items2)
		{
			object[] 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 object[] DoDifference(object[] longArray, object[] shortArray)
		{
			ArrayList arr = new ArrayList();
			arr.AddRange(longArray);

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

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