2012-08-23 20 views
0

我沒有聰明或至少工作思路如何解決以下難題:迭代列表與X塊,並挑選出ÿ元素出每塊的

我有198個任務,讓10人解決了每項任務,然後我使用Java hibernate &持久性API將所有內容寫入PostgreSQL數據庫。到目前爲止,這很好。

有時候,我確實有10個不同的/獨特的作業答案 - 對於其他作業,我確實只有2或3個不同的/獨特的答案(例如,對於「什麼是5 + 5」,8人是「10」和2名人士告訴「25」)

現在我運行一個SQL語句來獲取列表與我的任務和不同的答案:

SELECT DISTINCT question, answer FROM survey INNER JOIN results ON results.survey_id=results.id; 

我現在得到的是一個結果列表,看起來或多或少像這樣:

+---------+----------+--------+ 
| ID  | Question | Answer | 
+---------+----------+--------+ 
| 1  | Q1  | 20  | 
| 2  | Q1  | 22  | 
| 3  | Q1  | 25  | 
| 4  | Q1  | 21  | 
| 5  | Q1  | 22  | 
| 6  | Q1  | 10  | 
| 7  | Q1  | 20.5 | 
| 8  | Q1  | 22.3 | 
| 9  | Q1  | 28  | 
| 10  | Q1  | 26  | 
| 11  | Q2  | 52  | 
| 12  | Q2  | 51  | 
| 13  | Q3  | 78  | 
| 14  | Q3  | 80  | 
| ...  | ...  | ...  | 
| ...  | ...  | ...  | 
| ...  | ...  | ...  | 
+---------+---------+---------+ 

現在challening部分:

我現在要隨機挑選出4個不同的答案(如果可能)從各分配(Q1,Q2,Q3,...),並創建一個新的任務分配時,人們不得不投票最好的答案。

但是如圖所示,有時我的確有少於4個不同的答案。在這種情況下,我想把所有可用的東西都拿走。

我如何遍歷我的列表並執行這種「拾取」?

P.S.隨機挑選答案並不重要 - 也可以選擇前4個答案。

感謝您的幫助

問候

回答

0

如果ResultSet是,小我只想

// if random is needed [see here][1] to adapt the criteria 
var answers = session.createCriteria(Answer.class) 
    .setFetchMode("Question", FetchMode.eager) 
    .list<Answer>(); 


// map of orginal question to voting question 
Map<Question, Question> questions = new Hashmap<Question, Question>(); 
for (Answer answer : answers) 
{ 
    if (questions.ContainsKey(answer.getQuestion())) 
    { 
     Question votingQuestion = questions.get(answer.getQuestion()); 
     if (votingQuestion.getPossibleAnswers().Count() < 4) 
      votingQuestion.getPossibleAnswers().add(answer.Text); 
    } 
    else 
    { 
     Question votingQuestion = createVotingQuestion(answer.getQuestion()); 
     votingQuestion.getPossibleAnswers().add(answer.Text); 
     questions.add(answer.getQuestion(), votingQuestion); 
    } 
}