在没有重复的范围之间获得随机数

时间:2012-10-19 12:20:51

标签: android sql sqlite random

所有      我想要逻辑帮助。我在数据库中有100行并且随机获得所有行而没有重复我在下面的代码中使用过。

public ArrayList<Rows> getRows(){
    ArrayList<Rows> myRaw=new ArrayList<Rows>();
    Cursor rawCursor=this.db.query(DB_TABLE, null, null, null, null, null, null);
    if(rawCursor.getCount()>0){
        Random rng = new Random();
        rawCursor.moveToFirst();
        do {

             // Ideally just create one instance globally
            ArrayList<Rows> generated = new ArrayList<Raws>();
            for (int i = 0; i < 371; i++)
            {
                while(true)
                {
                    Integer next = rng.nextInt(371) + 1;
                    rawCursor.moveToPosition(next);
                    Rows raw=new Raws(rawCursor.getInt(rawCursor.getColumnIndex("_id")),rawCursor.getString(rawCursor.getColumnIndex("raw")),rawCursor.getInt(rawCursor.getColumnIndex("fav")));
                    if (!generated.contains(raw))
                    {
                        // Done for this iteration
                        generated.add(raw);
                        break;
                    }
                }
            }

            myRaw=generated;

        } while (rawCursor.moveToNext());
        rawCursor.close();
    }
    return myRaw;
}

全部谢谢

2 个答案:

答案 0 :(得分:3)

您可以告诉数据库按某些random number订购记录:

cursor = db.query(DB_TABLE, null, null, null, null, null, "random()");

答案 1 :(得分:1)

收藏改组怎么样? http://developer.android.com/reference/java/util/Collections.html#shuffle(java.util.List)

public ArrayList<Rows> getRows() {
    ArrayList<Rows> myRaw = new ArrayList<Rows>();
    Cursor rawCursor = this.db.query(DB_TABLE, null, null, null, null, null, null);

    if (rawCursor.getCount() > 0) {
        // get all the rows
        rawCursor.moveToFirst();
        do {
            Rows raw = new Raws(rawCursor.getInt(rawCursor.getColumnIndex("_id")), rawCursor.getString(rawCursor.getColumnIndex("raw")), rawCursor.getInt(rawCursor.getColumnIndex("fav")));
            myRaw.add(raw);
        } while (rawCursor.moveToNext());
        rawCursor.close();
    }
    // shuffle the rows in some kind of random order
    Collections.shuffle(myRaw);
    return myRaw;
}

@CL提供的答案。可能是更好的选择,但主要区别在于shuffle方法可以选择提供您自己的Random对象,这意味着您可以随机seed

//Random with seed;
Random r = new Random(68498493);
Collections.shuffle(myRaw, r);