May 11, 2023

Brute Force Techniques I

This is a description

Exchange Element Positions

public class SwapNumbers {
	public static <T> void swap(T[] a, int i, int j) {
		T temp = a[i];
		a[i] = a[j];
		a[j] = temp;
	}

	public static void main(String[] args) {
		Integer[] arr = { 1, 2, 3, 4, 5 };

		System.out.println("Original Array:");
		for (int num : arr)
			System.out.print(num + " ");

		System.out.println();

		SwapNumbers.<Integer>swap(arr, 0, 4);
		System.out.println("Swapped Array:");
		for (int num : arr)
			System.out.print(num + " ");
	}
}
PS F:\oopsies>
Original Array:
1 2 3 4 5
Swapped Array:
5 2 3 4 1

Generic Stack Class

import java.util.*;

public class GenericStack<T> {
	private List<T> stack;

	public GenericStack() {
		stack = new ArrayList<>();
	}

	public void push(T element) {
		stack.add(element);
	}

	public T pop() {
		if (isEmpty()) {
			throw new IllegalStateException("Stack is empty");
		}
		return stack.remove(stack.size() - 1);
	}

	public boolean isEmpty() {
		return stack.isEmpty();
	}

	public int size() {
		return stack.size();
	}

	public static void main(String[] args) {
		GenericStack<Integer> intStack = new GenericStack<>();
		intStack.push(10);
		intStack.push(20);
		intStack.push(30);

		System.out.println("Integer Stack Size: " + intStack.size());
		while (!intStack.isEmpty()) {
			int num = intStack.pop();
			System.out.println("Popped Integer: " + num);
		}
	}
}
PS F:\oopsies>
Integer Stack Size: 3
Popped Integer: 30
Popped Integer: 20
Popped Integer: 10

Stack Wildcards

public class WildcardDemo {

	public static void printStack(GenericStack<?> stack) {
		while (!stack.isEmpty()) {
			System.out.println(stack.pop());
		}
	}

	public static void main(String[] args) {
		GenericStack<Integer> intStack = new GenericStack<>();
		intStack.push(10);
		intStack.push(20);
		intStack.push(30);

		GenericStack<String> strStack = new GenericStack<>();
		strStack.push("Hello");
		strStack.push("World");

		System.out.println("Printing Integer Stack:");
		printStack(intStack);

		System.out.println("\nPrinting String Stack:");
		printStack(strStack);
	}
}
PS F:\oopsies>
Printing Integer Stack:
30
20
10

Printing String Stack:
World
Hello