首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >混洗数组算法- Java

混洗数组算法- Java
EN

Stack Overflow用户
提问于 2016-03-30 16:52:52
回答 2查看 99关注 0票数 1

我正在编写一个程序,目的是读取一个充满链接的.txt,并对数组中的链接进行解序,以便以后可以随机访问这些链接。

下面是我所做的(它不起作用:D):

代码语言:javascript
复制
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]);            
        }
    }
}

编辑:我当前的取消排序算法是按照链接的起始顺序显示所有链接。

EN

回答 2

Stack Overflow用户

发布于 2016-03-30 16:56:59

问题出在第二个循环中,您正在选择一个随机索引j,但是您正在检查是否为used[k] == j,而您应该检查Does the array used contain j

因此,一种解决方案是创建一个boolean contains(int[] arr, int val)方法来检查它是否已经存在。或者另一个简单的解决方案:

代码语言:javascript
复制
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()

票数 0
EN

Stack Overflow用户

发布于 2017-07-16 16:28:46

你为什么要重新发明轮子?

代码语言:javascript
复制
List<String> list = Arrays.asList(links);
Collections.shuffle(list);
String[] copy = list.toArray(new String[temp]);

如果您使用List而不是数组,您的代码会简单得多。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36303992

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档