Dynamic Array

mail@pastecode.io avatar
unknown
java
3 years ago
2.0 kB
8
Indexable
import java.io.*;

class DynamicArray<T> {
	public static final double GROWTH_FACTOR = 1.5;

	T ar[];
	int count = 0; // the number of items currently in the array
	int capacity = 0; // the max number of items our array can accomodate

	public T get(int i) {
		if(i < 0 || i >= count) throw new IndexOutOfBoundsException(i);
		return ar[i];
	}

	public void set(int i, T value) {
		if(i < 0 || i >= count) throw new IndexOutOfBoundsException(i);
		ar[i] = value;
	}

	public int size() { return count; }

	public void insert(T value) {
		if(count == capacity) resize();
		ar[count] = value;
		count++;
	}

	private void resize() {
		int newCapacity = (int) (DynamicArray.GROWTH_FACTOR * capacity)  + 1;
		T[] newAr = (T[]) new Object[newCapacity];
		for(int i = 0; i < capacity; i++)
			newAr[i] = ar[i];
		ar = newAr;
		capacity = newCapacity;
	}





	private void printLine() {
		System.out.println();
		for(int i = 0; i <= 9 * capacity; i++) System.out.print("━");
		System.out.println();
	}
	private void printBoxed(T item) {
		String s = "" + item;
		int maxLen = 8;
		int padRight = (maxLen - s.length()) / 2;
		int padLeft = maxLen - s.length() - padRight;
		System.out.print("┃");
		for(int i = 0; i < padLeft; i++) System.out.print(" ");
		System.out.print(item);
		for(int i = 0; i < padRight; i++) System.out.print(" ");
	}
	public void print() {
		printLine();
		for(int i = 0; i < count; i++) printBoxed(ar[i]);
		for(int i = count; i < capacity; i++) System.out.print("┃████████");
		System.out.print("┃");
		printLine();
	}
}


public class Main {
	public static void main(String args[]) throws IOException {
		int n = 16;

		long start = System.currentTimeMillis();
		DynamicArray<Integer> ar = new DynamicArray<>();
		
		ar.print();
		
		for(int i = 0; i < n; i++) {
			ar.insert(i*i);
			ar.print();
		}

		long end = System.currentTimeMillis();
		System.out.println("for n = " + n + " it took " + ((end-start)/1000.0) + " seconds");

	}
}