2017-07-10 8 views
0

私はLinkedListでシャッフルメソッドを作成しようとしています。現在、シャフリングの方法は、1から10までの乱数nを生成し、n番目のカードを取り出して前面に移動することです。その後、ランダムな時間内にループします。しかし、私の現在のコードは、前面に持っていくのではなく、取り出したカードが取り除かれるので、うまくいかないようです。リンクリストでシャッフルメソッドを作る方法

public void shuffle() { 
     Node current = head; 
     int randomX = (int) (Math.random() * 10 + 1); 
     for (int x = 0; x < randomX; x++) { 
      int randomY = (int) (Math.random() * 10 + 1); 
      for (int y = 0; y < randomY; y++) { 
       if (current.getNext() != null) { 
        current = current.getNext(); 
        System.out.println("Yup"); 
        System.out.println(current); 
        System.out.println(y); 
       } 
       else { 
        current = head; 
        System.out.println("nope"); 
        current = current.getNext(); 

       } 

       if (current.getPrevious() != null){ 
        current.getPrevious().setNext(current.getNext()); 
        head.setPrevious(current); 
        current.setPrevious(head); 

       } 
       head = current; 
      } 
     } 


    } 
+0

ノードの次の以前のに設定されていることを確認してくださいあなたはリンクされたリストを使用する必要がありますか? –

+0

はい、私はこのためのリンクリストを使用する必要があります –

+0

https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle –

答えて

2

あなたが見つけたとき、あなたがその探しているノードが、あなたがその次にその前のノードの次のを設定し、その前の

Node temp = head; 
int randomX = (int) (Math.random() * 10 + 1); 

//simply go until the randomX 
while(randomX-- > 0 && temp.getNext() != null) 
    temp = temp.getNext(); 

//remove the Nth node from the list 
temp.getPrevious().setNext(temp.getNext()); 

if(temp.getNext() != null) 
    temp.getNext().setPrevious(temp.getPrevious()); 

//set it to point to the head 
temp.setNext(head); 
temp.setPrevious(null); 

//now set the Head to the Nth node we found 
head = temp; 
+0

あなたのコードをありがとう、これは私が何をしようとしているのですが、私はDoublyLinkedListを使用しているので、いくつかの変更を加えなければなりませんでした。 –

0

あなたのmove the randomly chosen node to headが間違っているようです。 の外側には、があり、移動するループを選択する必要があります。

これは明らかなことです。

public void shuffle() { 
    Node current = head; 
    // How many times to shuffle. 
    int randomX = (int) (Math.random() * 10 + 1); 
    // Move random node to head random number of times. 
    for (int x = 0; x < randomX; x++) { 
     // Pick the one to move. 
     int randomY = (int) (Math.random() * 10 + 1); 
     // Go find it. 
     for (int y = 0; y < randomY; y++) { 
      if (current.getNext() != null) { 
       current = current.getNext(); 
       System.out.println("Yup"); 
       System.out.println(current); 
       System.out.println(y); 
      } else { 
       // Hit end of list - go back to start. 
       current = head; 
       System.out.println("nope"); 
       current = current.getNext(); 

      } 
     } 
     // Bring the chosen one to `head` - **** I moved this OUTSIDE the loop above. 
     if (current.getPrevious() != null) { 
      current.getPrevious().setNext(current.getNext()); 
      head.setPrevious(current); 
      current.setPrevious(head); 

     } 
     head = current; 
    } 
} 
関連する問題