Skip to content

Instantly share code, notes, and snippets.

@eungikim
Created March 29, 2021 05:26
Show Gist options
  • Save eungikim/750c655abf8702596218050fe87bdd80 to your computer and use it in GitHub Desktop.
Save eungikim/750c655abf8702596218050fe87bdd80 to your computer and use it in GitHub Desktop.
코딩테스트 연습 스택/큐 프린터
package kr.eungi.test;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
// https://programmers.co.kr/learn/courses/30/lessons/42587?language=java#
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(1, solution(new int[]{2, 1, 3, 2}, 2));
assertEquals(5, solution(new int[]{1, 1, 9, 1, 1, 1}, 0));
assertEquals(9, solution(new int[]{1,2,3,4,5,6,7,8,9}, 0));
assertEquals(8, solution(new int[]{3, 4, 1, 5, 6, 8, 9, 5, 4, 6, 7, 8}, 7));
assertEquals(16, solution(new int[]{1,1,2,2,4,4,8,7,5,1,2,3,9,9,9,8,7,7,3,4,1,9,5}, 18));
}
public int solution(int[] priorities, int location) {
int popCount = 0;
int vLocation = location;
Map<Integer,Integer> priorityCountMap = makePriorityCountMap(priorities);
while (vLocation >= popCount) {
if (haveMoreImportant(priorityCountMap, priorities[popCount])) {
replaceEnd(priorities, popCount);
vLocation--;
if (vLocation < popCount) {
vLocation = priorities.length - 1;
}
} else {
int popPriority = priorityCountMap.getOrDefault(priorities[popCount], 0);
if (popPriority == 1) {
priorityCountMap.remove(priorities[popCount]);
} else {
priorityCountMap.put(priorities[popCount], popPriority - 1);
}
popCount++;
}
}
return popCount;
}
public boolean haveMoreImportant(Map<Integer,Integer> map, int priority) {
for (Integer integer : map.keySet()) {
if (integer > priority) return true;
}
return false;
}
public void replaceEnd(int[] array, int from) {
int temp = array[from];
for (int i = from; i < array.length - 1; i++) {
array[i] = array[i+1];
array[i+1] = temp;
}
}
public HashMap<Integer,Integer> makePriorityCountMap(int[] priorities) {
HashMap<Integer,Integer> priorityMap = new HashMap<>();
for (int p : priorities) {
int count = priorityMap.getOrDefault(p, 0);
priorityMap.put(p, count + 1);
}
return priorityMap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment