English 中文(简体)
自愿标准 Query Random
原标题:Hibernate Criteria Query Random

I have an project using Hibernate. This has a class named Question. Each Question has a difficulty level (1,2,3); Each Question also has an attribute is field (a,b,c,d,e,f,g,h,i,k);

附录一有100个问题。 我想随机地问20个问题,条件是:

  • 7 questions in level 1
  • 7 questions in level 2
  • 6 questions in level 3.
  • Each field have at least 1 question

谢意

最佳回答

First of all, I think this problem is too difficult to be solved by using a Hibernate query, or even a set of Hibernate queries.

在此,我将如何做:

  • load all 100 questions in memory
  • create a Map<Field, List<Question>>, and shuffle all the lists in this map
  • for each field, take the first question of the corresponding list that has an acceptable level
  • Once you have one question in every field, take all the remaining questions, put them in a list, shuffle the list, and iterate over the list. Each time a question has a level which is acceptable, take it. Do that until you have your 20 questions.

如果每个领域都得到保证,至少每一级都有问题,那么这项工作就应当进行。 如果情况并非如此,那就更加困难。

If you have much more questions that 100, and they can t be loaded in memory, you could use the same kind of algorithm, but use random queries to select the questions:

  • issue one query per field to find a question in each field. The where clause should only accept the given field, and should only accept the levels which are still acceptable.
  • issue a query to find N questions randomly (with N being equal to 50, for example, and with a where clause which only accepts the remaining levels), and take the first 10 acceptable questions. If there are less than 10 acceptable questions, try again. There should be at most 3 such queries. Make sure your where clause rejects the IDs of the questions which have already been loaded.
问题回答

暂无回答




相关问题
Weighted random numbers

I m trying to implement a weighted random numbers. I m currently just banging my head against the wall and cannot figure this out. In my project (Hold em hand-ranges, subjective all-in equity ...

Comprehensive information about hash salts

There are a lot of questions about salts and best practices, however most of them simply answer very specific questions about them. I have several questions which feed into one another. Assuming a ...

Generate unique names?

I am working on a php site in which we have to upload images from users.i have to rename that file for preventing conflicts in the name of the image. uniqid(rand(), true); and adding a large random ...

How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

热门标签