Skip to content

Instantly share code, notes, and snippets.

@iEverX
Last active August 16, 2024 14:59
Show Gist options
  • Save iEverX/919935272d6db1e31665a3c197f5b7d1 to your computer and use it in GitHub Desktop.
Save iEverX/919935272d6db1e31665a3c197f5b7d1 to your computer and use it in GitHub Desktop.
如何将一副扑克牌排序,限制条件是只能查看最上面的两张牌,交换最上面的两张牌,或是将最上面的一张牌放到这摞牌的最下
package algo;
import java.util.ArrayList;
import java.util.List;
// https://v2ex.com/t/1065513
public class Main {
public static void main(String[] args) {
Box box = new Box(4, 7, 2, 6, 3, 5, 8, 1, 8, 4, 76, 2, 3, 14, 0, 9, 7);
box.print();
sort(box);
box.print();
}
public static void sort(Box box) {
int size = box.size();
for (int i = 1; i <= size; i++) {
bubble(box, i);
}
}
public static void bubble(Box box, int num) {
int count = box.size() - num;
while (count-- > 0) {
int[] top = box.getTop();
if (top[1] > top[0]) {
box.swap();
}
box.moveToBottom();
}
count = num - 1;
while (count-- > 0) {
box.swap();
box.moveToBottom();
}
box.moveToBottom();
}
public static class Box {
private final List<Integer> list;
public Box(int... values) {
List<Integer> ls = new ArrayList<>(values.length);
for (int value : values) {
ls.add(value);
}
list = ls;
}
public int[] getTop() {
return new int[]{list.get(0), list.get(1)};
}
public void swap() {
int v = list.get(0);
list.set(0, list.get(1));
list.set(1, v);
}
public void moveToBottom() {
Integer first = list.removeFirst();
list.add(first);
}
public int size() {
return list.size();
}
public void print() {
System.out.println(list);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment