Untitled
unknown
plain_text
3 years ago
2.8 kB
3
Indexable
Never
public static Integer shortestDistance(List<Blocks> blocks) { HashMap<Integer, List<Integer>> listInt = new HashMap<>(); for (int i = 0; i < blocks.size(); i++) { List<Integer> distance = new ArrayList<>(); int gymDown = 0, schoolDown = 0, storeDow = 0; boolean isGym = false, isShcool = false, isStore = false; for (int j = i; j < blocks.size(); j++) { if(isGym == false && blocks.get(j).isGym() == false) { gymDown++; } else { isGym = true; } if(isShcool == false && blocks.get(j).isSchool() == false) { schoolDown++; } else { isShcool = true; } if(isStore == false && blocks.get(j).isStore() == false) { storeDow++; } else { isStore = true; } if(isGym == true && isStore == true && isShcool == true) break; } int gymUp = 0, schoolUp = 0, storeUp = 0; isGym = false; isShcool = false; isStore = false; for (int j = i-1; j > 0; j--) { if(isGym == false && blocks.get(j-1).isGym() == false) { gymUp++; } else { isGym = true; } if(isShcool == false && blocks.get(j-1).isSchool() == false) { schoolUp++; } else { isShcool = true; } if(isStore == false && blocks.get(j-1).isStore() == false) { storeUp++; } else { isStore = true; } if(isGym == true && isStore == true && isShcool == true) break; } distance.add((gymUp == 0) ? gymDown : Math.min(gymUp, gymDown)); distance.add((storeUp == 0) ? storeDow : Math.min(storeUp, storeDow)); distance.add((schoolUp == 0) ? schoolDown : Math.min(schoolUp, schoolDown)); listInt.put(i, distance); } return findMinIndex(listInt); } public static Integer findMinIndex(HashMap<Integer, List<Integer>> listInt) { int index = 0; int min = 10000000; for (int i = 0; i < listInt.size(); i++) { int listSum = listInt.get(i).stream() .reduce(0, Integer::sum); if(listSum < min) { min = listSum; index = i; } } return index; }