[LIKELION] 220928 과제

고관운·2022년 9월 28일

1. 삽입정렬 구현

public class insersionSort {

	public static int[] solution(int n, int[] arr) {
		int tmp;
		
		for (int i = 1; i < n; i++) {
			for (int j = i; j > 0; j--) {
				if(arr[j] > arr[j-1]) {
					break;
				} else {
					tmp = arr[j-1];
					arr[j-1] = arr[j];
					arr[j] = tmp;
				}
			}
		}
		
		return arr;
	}
	
	public static void printArray(int[] arr) {
		for(int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		int[] arr = {7, 3, 2, 8, 9, 4, 6, 1, 5};
		
		System.out.print("정렬 전 배열 : ");
		printArray(arr);
		int[] sortArr = solution(arr.length, arr);
		System.out.print("정렬 후 배열 : ");
		printArray(sortArr);
	}
}

🟢 정렬 전과 정렬 후를 확인할 수 있도록 printArray함수를 따로 만들었음

2. 다형성 활용 문제 (Buyer)

class Buyer {
	int money = 1000;
	Product[] cart = new Product[3]; // 구입한 제품을 저장하기 위한 배열

	int i = 0; // Product배열 cart에 사용될 index


	void buy(Product p) {
		if(money >= p.price) {
			money -= p.price;
			add(p);
		} else {
			System.out.println("잔액이 부족하여 " + p + "을/를 살 수 없습니다.");
		}
	}
	
	void add(Product p) {
		Product[] newCart = null;
		if(i >= cart.length) {
			newCart = new Product[cart.length * 2];
			for(int j = 0; j < cart.length; j++) {
				newCart[j] = cart[j];
			}
			cart = newCart;
		}
		cart[i] = p;
		i++;
	} // add(Product p)

	void summary() {
		int sum = 0;
		System.out.print("구입한 물건 : ");
		for(int j = 0; j < i; j++) {
			System.out.print(cart[j].toString() + ", ");
			sum += cart[j].price;
		}
		System.out.println();
		System.out.println();
		System.out.println("사용한 금액 : " + sum);
		System.out.println("남은 금액 : " + money);
	} // summary()
}



class Product {
	int price; // 제품의 가격

	Product(int price) {
		this.price = price;
	}
}



class Tv extends Product {
	Tv() {
		super(100);
	}

	public String toString() {
		return "Tv";
	}
}



class Computer extends Product {
	Computer() {
		super(200);
	}

	public String toString() {
		return "Computer";
	}
}



class Audio extends Product {
	Audio() {
		super(50);
	}

	public String toString() {
		return "Audio";
	}
}

public class PolyExample {

	public static void main(String[] args) {
		Buyer b = new Buyer();
		b.buy(new Tv());
		b.buy(new Computer());
		b.buy(new Tv());
		b.buy(new Audio());
		b.buy(new Computer());
		b.buy(new Computer());
		b.buy(new Computer());

		b.summary();
	}
}

🟢 add 함수에서 배열의 크기를 늘려주기 위해 newCart 임시배열을 만들어줌

0개의 댓글