0
我目前正在處理一個問題,以獲得所有排列給出2個列表。使用遞歸函數與2個列表的所有排列
問題: 我們有3個足球比賽和3個投球,使用recusive函數,找到所有可能的排列,其中可以將比賽分配給比賽。
匹配{「a」,「b」,「c」},螺距{1,2,3}。
結果將會是一組具有match => pitch分配的HashMap。 {「a」=> 1,「b」=> 2,「c」=> 3},{「a」=> 1,「c」=> 2,「b」=> 3}}。 ,{「b」=> 1,「a」=> 2,「c」=> 3},{「b」=> 1,「c」=> 2,「a」=> 3} 「=> 1,」a「=> 2,」b「=> 3},{」c「=> 1,」b「=> 2,」a「=> 3}}
任何鏈接類似的問題,建議或僞代碼會有幫助。
我以不同的方式完成了這項工作,在該方法中,我獲得了所有可能的音調不同的序列,然後遍歷這些結果並分配匹配a,b,c。代碼如下。但我覺得可以有更好的解決方案。
public static void allocate(ArrayList<Match> matches, ArrayList<Pitch> pitches){
Set<Map<Match, Pitch>> set = new HashSet<Map<Match, Pitch>>();
// list is the return object
ArrayList<ArrayList<Pitch>> list = new ArrayList<ArrayList<Pitch>>();
// call the recursive function to populate the list object
list = (ArrayList<ArrayList<Pitch>>) pitchPermutations(new ArrayList<Pitch>(), pitches, list, matches.size());
// iterate through all the possible combinations of pitches add the matches
for(ArrayList<Pitch> vs : list){
if(vs.size() != matches.size()) continue;
HashMap<Match,Pitch> m = new HashMap<Match,Pitch>();
for(int i = 0; i < vs.size(); i++){
Match e = matches.get(i);
Pitch v = vs.get(i);
m.put(e, v);
}
set.add(m);
}
// print the information
int count = 1;
for (Map<Match, Pitch> m : set){
System.out.println("----- "+count+" ------");
for (Map.Entry<Match, Pitch> entry : m.entrySet()) {
System.out.println("Match : " + entry.getKey().getName());
System.out.println("Pitch : " + entry.getValue().getName());
}
count++;
}
// return set;
}
private static ArrayList<ArrayList<Pitch>> pitchPermutations(ArrayList<Pitch> pitches, ArrayList<Pitch> pitchesList, ArrayList<ArrayList<Pitch>> returnList, int length){
// variable to hold the amount of pitches available
int n = pitchesList.size();
// if the pitches equals the number of pitches needed, add this list to the returnList variable
if(pitches.size() == length){
returnList.add(pitches);
return returnList;
}else{
//
for(int i = 0 ; i < pitchesList.size(); i++){
// remove the item which is added to the pitches to be passed recursively
ArrayList <Pitch> p = new ArrayList<Pitch>(pitchesList.subList(0,i));
p.addAll(new ArrayList<Pitch>(pitchesList.subList(i+1, n)));
ArrayList<Pitch> pitches1 = (ArrayList<Pitch>) pitches.clone();
pitches1.add(pitchesList.get(i));
returnList = pitchPermutations(pitches1, p, returnList, length);
}
}
return returnList;
}
如果您已經在處理此問題,請嘗試將代碼添加到問題中。這將有助於你打算將作業轉儲給其他人的印象...... – GhostCat
我有一個解決方案,但它不是一個完整的遞歸函數。我所用的遞歸函數用於獲取音高的所有不同序列,然後將它們分配給匹配以獲得結果。但我想知道我可以在1遞歸函數中做到這一點。如果你願意,我可以補充一點。 – Martin