微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我不明白为什么尽管在第一次出现后删除了它,但我还是两次看到我的数组列表中的索引

如何解决我不明白为什么尽管在第一次出现后删除了它,但我还是两次看到我的数组列表中的索引

我正在尝试使用数组列表解决约瑟夫问题。我注意到即使我在它被杀死后删除和索引它仍然显示在我的输出中。

本该删除的2为什么又出现了?

以下是我当前的输出

There are 7 people in the circle.
1,2,3,4,5,6,7
2 
2,4 
2,1 
2,1,3 
2,2 
2,0

You should sit in seat 4 if you want to survive!
public class project1 {
  public static int Josephus (int n,int k){
    ArrayList<Integer> circle = new ArrayList<Integer>();
    for (int p = 1; p <= n; p++) {
      circle.add(p);                                                              
    }
    System.out.println("There are " + n + " people in the circle.");
    System.out.println(circle);

    ArrayList<Integer> kill_order = new ArrayList<Integer>();
    for (int index=1; circle.size()!=1; index++){
      if (circle.size() > 1){
        index = (index + k - 1) % circle.size();
        kill_order.add(index);
        circle.remove(index);
        System.out.println(kill_order);
      } else if (circle.size()==1){
        System.out.println("Execution Order: " + kill_order + " ");
        index = 1;
      }
    }
    return circle.get(0);
  }

  public static void main(String[] args) {
    System.out.println("You should sit in seat " + Josephus(7,2) + " if you want to survive!");
  }
}

解决方法

有两种方法List.remove:remove(int index) 将删除列表中给定索引处的项目,remove(Object o) 将删除等于 o 的第一个对象。

我认为在您的代码中,circle.remove(index); 解析为第一个,但您实际上需要第二个。见https://docs.oracle.com/javase/8/docs/api/java/util/List.html

这应该可以解决这个问题:

circle.remove((Integer)index);
,

您第二次看到 2 是因为您将要“杀死”的人的索引而不是值添加到 kill_order 列表中。

这应该有效:


if (circle.size() > 1){
    index = (index + k - 1) % circle.size();
    kill_order.add(circle.get(index));
    circle.remove(index);
    System.out.println(kill_order);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。