package com.vmx;

public class IntVector
{
	public static final int DELTA = 4096;
	
	protected int[] array;
	protected int count;
	
	public IntVector()
	{
		array = new int[0];
		count = 0;
	}
	
	public IntVector(int capacity)
	{
		array = new int[capacity];
		count = 0;
	}
	
	/**
	 * Добавить в array значение n
	 */
	public void add(int el)
	{
		if(count >= array.length)
		{
			try
			{
				int[] newarray = new int[array.length + DELTA];
				System.arraycopy(array, 0, newarray, 0, array.length);
				array = newarray;
			}
			catch(OutOfMemoryError oome)
			{
				return;
			}
		}
		
		array[count++] = el;
	}
	
	/**
	 * Удалить элементы с first по first + n - 1
	 */
	public void remove(int first, int n)
	{
		if(first < 0 || first >= count || n <= 0)
		{
			return;
		}
		
		if(first + n >= count)
		{
			count = first;
		}
		else
		{
			for(int i = first; i < count - n; i++)
			{
				array[i] = array[i + n];
			}
		}
		
		while(count + DELTA * 2 < array.length)
		{
			try
			{
				int[] newarray = new int[array.length - DELTA];
				System.arraycopy(array, 0, newarray, 0, newarray.length);
				array = newarray;
			}
			catch(OutOfMemoryError oome)
			{
				break;
			}
		}
	}
	
	/**
	 * Получить элемент номер index
	 */
	public int get(int index)
	{
		return array[index];
	}
	
	public void set(int index, int value)
	{
		if(index >= 0 && index < count)
		{
			array[index] = value;
		}
	}
	
	/**
	 * Найти value в векторе
	 */
	public int find(int value)
	{
		int i;
		
		for(i = 0; i < count; i++)
		{
			if(array[i] == value)
			{
				break;
			}
		}
		
		if(i >= count)
		{
			return -1;
		}
		
		return i;
	}
	
	/**
	 * Получить размер
	 */
	public int size()
	{
		return count;
	}
	
	public void copyInto(int[] dest)
	{
		System.arraycopy(array, 0, dest, 0, count);
	}

	public void trimToSize()
	{
		if(array.length == count)
		{
			return;
		}
		
		try
		{
			int[] newarray = new int[count];
			System.arraycopy(array, 0, newarray, 0, newarray.length);
			array = newarray;
		}
		catch(OutOfMemoryError oome)
		{
		}
	}
}
