Skip to content

Instantly share code, notes, and snippets.

@Exom9434
Last active January 25, 2025 08:28
Show Gist options
  • Select an option

  • Save Exom9434/19c77ef58969d83c90cc7ac8bfb6d991 to your computer and use it in GitHub Desktop.

Select an option

Save Exom9434/19c77ef58969d83c90cc7ac8bfb6d991 to your computer and use it in GitHub Desktop.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int numVote = getPositiveInt(scanner, "총 진행할 투표수를 입력해 주세요: ");
int numCand = getPositiveInt(scanner, "가상 선거를 진행할 후보자 인원을 입력해주세요: ");
scanner.nextLine(); // 버퍼 비우기
String[] candidates = getCandidateNames(numCand);
boolean tieExists;
do {
int[] arrVotes = new int[candidates.length];
simulateVoting(numVote, candidates, arrVotes, random);
List<String> winners = determineWinners(candidates, arrVotes);
if (winners.size() > 1) {
System.out.println("동점이 발생했습니다. 재투표를 진행합니다.\n");
candidates = winners.toArray(new String[0]); // 동점 후보자만으로 후보자 배열 재구성
} else {
tieExists = false;
System.out.printf("[투표결과] 당선인: %s\n", winners.get(0));
}
} while (tieExists);
scanner.close();
}
///양수를 입력받는 유틸리티 메서드
private static int getPositiveInt(Scanner scanner, String prompt) {
int value;
while (true) {
try {
System.out.print(prompt);
value = scanner.nextInt();
if (value > 0) {
return value;
}
System.out.println("양수를 입력해 주세요.");
} catch (InputMismatchException e) {
System.out.println("숫자를 입력해 주세요.");
scanner.next(); // 잘못된 입력 제거
}
}
}
///후보자 이름을 입력받는 메서드
private static String[] getCandidateNames(int numCand) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
String[] candidates = new String[numCand];
for (int i = 0; i < numCand; i++) {
System.out.printf("%d번째 후보자 이름을 입력해주세요: ", i + 1);
candidates[i] = reader.readLine();
}
return candidates;
}
/// 투표를 시뮬레이션하고 결과를 출력
private static void simulateVoting(int numVote, String[] candidates, int[] arrVotes, Random random) {
System.out.println("\n[투표 시작]");
for (int i = 0; i < numVote; i++) {
int targetIndex = random.nextInt(candidates.length);
arrVotes[targetIndex]++;
float totalRate = ((float) (i + 1) / numVote) * 100;
System.out.printf("[투표진행률]: %.2f%%, %d명 투표 => %s\n", totalRate, (i + 1), candidates[targetIndex]);
printVoteStatus(candidates, arrVotes, numVote);
}
}
/// 현재 투표 상태를 출력용 메서드
private static void printVoteStatus(String[] candidates, int[] arrVotes, int numVote) {
for (int i = 0; i < candidates.length; i++) {
String name = candidates[i];
float rate = ((float) arrVotes[i] / numVote) * 100;
System.out.printf("[기호:%d %s: %.2f%% (투표수: %d)]\n", i + 1, name, rate, arrVotes[i]);
}
System.out.println();
}
/// 최다 득표자를 결정하는 메서드
private static List<String> determineWinners(String[] candidates, int[] arrVotes) {
int maxVotes = Arrays.stream(arrVotes).max().orElse(0);
List<String> winners = new ArrayList<>();
for (int i = 0; i < candidates.length; i++) {
if (arrVotes[i] == maxVotes) {
winners.add(candidates[i]);
}
}
return winners;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment