Josephus Java Queue - 热土豆

时间:2014-04-21 01:14:11

标签: java queue josephus

我试图在java中使用队列来解决Josephus问题。输入必须是名称列表(字符串)和整数k或马铃薯通过队列的次数。我需要测试4种不同的输入。这是我到目前为止,我得到了一些随机教程的帮助,但不知道如何编辑这个以使它工作。

 /*Jess Anastasio
  * HW 1
  * Part 2
  */ 

 import java.util.*;
 import java.util.Queue;
    /*pseudocode:
     * int k = amount of people cycled through 
     * before deleted. Need to enter string input
     * of names into queue. Need to cycle through
     * the queue k times and the object at position
     * k will be deleted. 
     * 
     * first: create string array holding names
     * method buildQueue takes the string array 
     * and adds it to a string queue
     * next: Josephus method passes in string queue and
     * int k, 
     */

  public class HotPotato 
  {
   //tester
    public static void main(String[] args) 
     {
    //use an array to save string input of names (4 different inputs)
       String[] a1 = {"Genna", "Bob", "Rob", "Alexa", "Brian", "Frank"};
       String[] a2 = {"Rich", "Taylor", "Jackie", "Jan", "Kim", "Denver"};
       String[] a3 = {"Jess", "Kyle", "Mike", "Carolyn", "Ant", "Ed"};
       String[] a4 = {"Natalie", "Emma", "Olivia", "Joe", "Kitty", "Jenn"};
       System.out.println("First winner is " + Josephus(buildQueue(a1), 5));
       System.out.println("Second winner is " + Josephus(buildQueue(a2), 2));
       System.out.println("Third winner is " + Josephus(buildQueue(a3), 4));
       System.out.println("Fourth winner is " + Josephus(buildQueue(a4), 10));
     }

    // build a queue from an array of string objects
    public static Queue<String> buildQueue(String[] str) 
    {
      Queue<String> Q = new Queue<String>();
      for (int i = 0; i < str.length; i++)
        Q.enqueue(str[i]);

      return Q;
    }

     // Josephus problem using a queue
     public static String Josephus(Queue<String> Q, int k) 
     {
       //if there is nothing in the queue return null
       if (Q.isEmpty()) 
        return null;

       //while the size of the queue is greater than 1
       while (Q.size() > 1) 
       {
         //print out the contents of the queue
         System.out.println(" Queue: " + Q + " k = " + k);
         for (int i = 1; i < k; i++)
           Q.enqueue(Q.dequeue());
         String e = Q.dequeue();
         //update user on who was deleted 
         System.out.println(" " + e + " is out");
       }
       return Q.dequeue();
     }

  }

这不起作用..有人可以提供建议吗?

1 个答案:

答案 0 :(得分:0)

我不确定你的while循环。这就是我想出的 - this.potentialVictims是一个队列

public String findSurvivor(int k) { 

  int pos=1;
  while (this.potentialVictims.size() > 1) {
    String person=this.potentialVictims.poll();
    if (pos++ %k != 0) {
            this.potentialVictims.offer(person);
    }
    else {
       System.out.printf("%s is out\n",person);
    }
  }
  if (this.potentialVictims.size()==1) {
    return this.potentialVictims.poll();
  }
  else {
    return null;
  }
}