Girish Bhutiya
Girish Bhutiya

Reputation: 3127

get random no between range without duplicate

All I want logical help. I have 100 row in database and get all rows random ally without duplication I have used below code.

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;
}

Thanks All

Upvotes: 2

Views: 385

Answers (2)

Rolf ツ
Rolf ツ

Reputation: 8781

What about Collections shuffle? 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;
}

The answer provided by @CL. could be a better option, but the main difference is that the shuffle method has an option to provide your own Random object, this means that you can seed the random.

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

Upvotes: 1

CL.
CL.

Reputation: 180081

You can tell the database to order the records by some random number:

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

Upvotes: 3

Related Questions