Getting random value from SQLite table

I am currently working on an Android application and I am trying to get a random value from a database table that looks like this:

| ID | Score| | 1 | 20 | | 2 | 5 | | 5 | 5 | | 6 | 5 | | 14 | 15 | 

(suppose these are the only values ​​in the table)

I would like to get a random value from this table, which has an identifier of 1 40% of the time, ID 2 of 10% of the time, ID 5 of 10% of the time, etc. .... If possible, how would you do it?

+1
source share
2 answers

Given List<Integer> , add() each song index score times, Collections.shuffle() list and play in order. For best results, skip consecutive duplicates. More details here .

+1
source

There is no built-in support from any of the known databases for random selection. If you do some searches, you may find something like:

 select * from my_table order by rand(); 

But this is very inefficient as it tries to sort the entire table.

If your data set is not too large, you can simply output the entire table to an array and randomly select from this array.

Now the selected choice, which is more difficult.

The simplest version will work something like this:

  • Get a list of all identifiers ( id) and weights ( weight ) in the table.
  • Iterate through the list and calculate the total weight cwieght for each identifier.
  • When you reach the end of the list, you will have the total number of all weights. Choose a random number r between 0 and this value.
  • Browse the list again and find the element where r >= cweight && r < cweight+weight You can use the binary chops search if you play.

There are other more reasonable approaches to this, which depend on certain restrictions.

0
source

All Articles