簡體   English   中英

隨機播放數組算法-Java

[英]Shuffle an Array algorithm - Java

我正在編寫一個程序,該程序旨在讀取充滿鏈接的.txt並取消對數組中的鏈接的排序,因此以后可以隨機訪問它們。

這是我所做的(並且不起作用:D):

import java.io.*;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Scan{

        public static void main(String[] args) throws FileNotFoundException{
        String test = "";
        int i = 0;
        int temp = 0;


        Scanner link = new Scanner(new File("links.txt"));
        while(link.hasNextLine()){
            test = link.nextLine();
            temp++;
        }
        link.close();

        String[] links = new String[temp];

        Scanner urls = new Scanner(new File("links.txt"));

        for (i = 0; i < temp; i++)
        {
            test = urls.nextLine();
            links[i] = test;
            System.out.println("Sorted: " + links[i]);
        }
        urls.close();
        System.out.println("Size of LINKS: " + temp);        


                    // - - - - - - - - - - - - - - - - - - - - - //
                    //  Start of the unsorting algorithm         //
                    //  (It's just not working, need a new one)  //
                    // - - - - - - - - - - - - - - - - - - - - - //

        String[] copy = new String [temp];
        int[] used = new int [temp];
        for(i = 0; i < temp; i++)
        {
            for (int k = 0; k < temp; k++)
            {
                    int j = (int) (Math.random() * temp);
                    //System.out.println(j);
                    if (j == used[k])
                    {
                        k--;
                    }
                    else
                    {
                        used[k] = j;
                        copy[j] = links[i];
                    }

            }
            System.out.println(links[i]);            
        }
    }
}

編輯:我當前的未排序算法正在顯示所有鏈接在其開始順序上。

問題出在第二個循環中,您在其中選擇一個隨機索引j ,但是您在應檢查Does the array used contain j時檢查了used[k] == j Does the array used contain j

因此,一種解決方案是創建一個方法boolean contains(int[] arr, int val) ,該方法檢查是否已經存在。 或另一個簡單的解決方案:

ArrayList<String> links = //read from file

ArrayList<String> unsorted = new ArrayList<String>();

while(links.size() != 0) {
    unsorted.add( links.remove( (int)(Math.random()*links.size()) ) );
}

如果要在String[]輸出,可以使用unsorted.toArray()

你為什么要重新發明輪子?

List<String> list = Arrays.asList(links);
Collections.shuffle(list);
String[] copy = list.toArray(new String[temp]);

如果您使用List而不是數組,則代碼將簡單得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM