Created
September 1, 2024 04:08
-
-
Save Exom9434/c2292f1be14c06a9be248c798856cda1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//노재경 | |
import java.util.Scanner; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Random; | |
import java.io.InputStreamReader; | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
public class Main { | |
public static void main(String[] args) throws IOException { | |
Scanner scanner = new Scanner(System.in); | |
Random random = new Random(); | |
System.out.println("총 진행할 투표수를 입력해 주세요"); | |
int numVote = scanner.nextInt(); | |
System.out.println("가상 선거를 진행할 후보자 인원을 입력해주세요"); | |
int numCand = scanner.nextInt(); | |
scanner.nextLine(); | |
String[] candidates = new String[numCand]; | |
int[] arrVotes = new int[numCand]; | |
// 인코딩 오류 제거용 bufferedreader 사용. | |
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); | |
for (int i = 0; i < numCand; i++) { | |
System.out.printf("%d번째 후보자 이름을 입력해주세요: ", i + 1); | |
candidates[i] = reader.readLine(); | |
} | |
boolean tieExists; | |
do { | |
for (int i = 0; i < numCand; i++) { | |
arrVotes[i] = 0; // 초기화 | |
} | |
for (int i = 0; i < numVote; i++) { | |
int targetNum = random.nextInt(numCand); | |
String targetName = candidates[targetNum]; | |
arrVotes[targetNum] += 1; | |
float totalRate = ((float) (i + 1) / numVote) * 100; | |
System.out.printf("[투표진행률]: %.2f%%, %d명 투표 => %s\n", totalRate, (i + 1), targetName); | |
for (int j = 0; j < numCand; j++) { | |
String name = candidates[j]; | |
float rate = ((float) arrVotes[j] / numVote) * 100; | |
int vote = arrVotes[j]; | |
System.out.printf("[기호:%d %s: %.2f%% (투표수: %d)]\n", j + 1, name, rate, vote); | |
} | |
System.out.println(); | |
} | |
int maxVotes = 0; | |
List<String> winners = new ArrayList<>(); | |
for (int i = 0; i < numCand; i++) { | |
if (arrVotes[i] > maxVotes) { | |
maxVotes = arrVotes[i]; | |
winners.clear(); | |
winners.add(candidates[i]); | |
} else if (arrVotes[i] == maxVotes) { | |
winners.add(candidates[i]); | |
} | |
} | |
if (winners.size() > 1) { | |
System.out.println("동점이 발생했습니다. 재투표를 진행합니다."); | |
tieExists = true; | |
// 동점 후보자만을 대상으로 재투표 | |
String[] tieCandidates = new String[winners.size()]; | |
winners.toArray(tieCandidates); | |
candidates = tieCandidates; | |
numCand = candidates.length; | |
} else { | |
tieExists = false; | |
System.out.printf("[투표결과] 당선인: %s\n", winners.get(0)); | |
} | |
} while (tieExists); | |
scanner.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment