public class IncrementSybmols {
public static void main(String[] args) throws Throwable {
List<Integer> syms = Arrays.asList(1,2,3,4,5);
test(syms, 3, Arrays.asList(1,2,3), Arrays.asList(1,2,4));
test(syms, 3, Arrays.asList(2,5,4), Arrays.asList(3,1,2));
test(syms, 3, Arrays.asList(4,3,5), Arrays.asList(4,5,1));
test(syms, 3, Arrays.asList(5,4,2), Arrays.asList(5,4,3));
test(syms, 3, Arrays.asList(5,4,3), null);
}
private static void test(List<Integer> syms, int n, List<Integer> in, List<Integer> exp) {
List<Integer> out = increment(syms, n, in);
System.out.println(in+" -> "+out+": "+(exp==out || exp.equals(out)?"OK":"FAIL"));
}
private static List<Integer> increment(List<Integer> allSyms, int n, List<Integer> in){
TreeSet<Integer> availableSym = new TreeSet<Integer>(allSyms);
availableSym.removeAll(in);
LinkedList<Integer> current = new LinkedList<Integer>(in);
// Remove symbols beginning from the tail until a better/greater symbols is available.
while(!current.isEmpty()){
Integer last = current.removeLast();
availableSym.add(last);
// look for greater symbols
Integer next = availableSym.higher(last);
if(next != null){
// if there is a greater symbols, append it
current.add(next);
availableSym.remove(next);
break;
}
}
// if there no greater symbol, then *shrug* there is no greater number
if(current.isEmpty())
return null;
// fill up with smallest symbols again
while(current.size() < n){
Integer next = availableSym.first();
availableSym.remove(next);
current.add(next);
}
return current;
}
}
Dobrzy ankieterzy mogą powiedzieć, czy masz odpowiedź na puszki na te rzeczy. Lubią to lepiej, jeśli trzeba się z tym pogodzić, ponieważ widzą proces rozwiązywania problemów, który jest ważniejszy niż samo poznanie rozwiązania. – Almo
Dałem takie rozwiązanie, Podejmij posortowaną podwójnie zakończoną kolejkę dostępnych numerów, zainicjuj za pomocą dostępnych numerów, 1. zacznij od cyfry jednostek, sprawdź, czy jest dostępny większy numer, jeśli tak, zamień inny, umieść ten numer na dostępnej liście i sprawdź cyfrę dziesiątek 2. Jeśli znajdziesz numer większy niż obecna cyfra, wymień go i zacznij wstawiać mniejsze liczby z kolejki. Czy można to uczynić bardziej wydajnym i czy są jakieś wady? –
przykład .. {{{ 123 dostępny: 45 Kontrola 3 .. zastąpić 4 do 254 dostępny: 13 Kontrola 4 .. 1,3 <4 4 umieścić w dostępnych Kontrola 5 .. niedostępne sprawdzenie 2 .. available: 1345 insert 2 in available ,, replace with 3, follow 1 i 2 }}} –