2017-02-10 84 views
-5

嗨,我試圖格式化並創建此數組:陣列格式化方法

Person[] persons = { person1, person2, person3, person4, person5, person6, person7, person8, person9, person10 }; 
// The aim is to form an array of the 5 strongest people's indices above 
int[] arrayOfStrongestPeopleIndices = new int[5]; 
for (int index = 0; index < 10; index++){ 
    int strength = persons[index].strength; 

    for (int str : arrayOfStrongestPeopleIndices){ 

     //something @ here ? 

    } 
} 

所以我到10人試圖循環,以及陣列arrayOfStrongestPeopleIndices應該是最強的人指數爲5(以最強爲了最弱的,即array[0]是最強的人指數開出5,而array[4]是最弱的5)

的問題:我如何返回格式化arrayOfStrongestPeopleIndices的規定?

+0

請張貼可執行代碼,因爲人員數組大小我們無法猜測。 – RamPrakash

+0

你對這篇文章有任何問題嗎? –

+0

編輯過的主帖,應該比較容易看懂 –

回答

0

所以這是我的想法,嘗試它,它應該工作。 當我發現一個比「最強」的ArrayList中的任何人都強的人時,我會移動它後面的所有元素。

ArrayList<int> strongest = new ArrayList<int>(); 
strongest.append(-1, -1, -1, -1, -1); 
for (int i = 0; i < 500; i++) { 
    int str = persons[i].strength; 
    for(int j = 0; j < 5; j++) { 
     if(str > strongest[j]) { 
      int temp = strongest[j]; 
      strongest[j] = str; 
      str = temp; 
     } 
    } 
} 
0

https://docs.oracle.com/javase/8/docs/api/java/util/List.html#sort-java.util.Comparator-

List<Person> p = Arrays.asList(person); 

Collections.sort(p, new Comparator<Person>() { 
    @Override 
    public int compare(Person a1, Persona2) { 
     return a1.strenght.compareTo(a2.strenght); //im assuming strenght is a number 
    } 
}); 

person = p.toArray(new Person[0]); 

現在你有一個人的有序排列,從弱到強

+0

謝謝,不知道這樣一個工具,是我正在循環的人數(50目前不是500)造成執行後的大規模延遲,還是這個工具速度較慢? –

0

這是返回代表最強者的指數整數數組的方法。

public int[] findStrongestIndices(Person[] persons) { 
    int[] arrayOfStrongestPeopleIndices = new int[5]; 

    for (int i = 0; i < 5; i++) { 
     int temp = 0; 
     for (int j = 0; j < 10; j++) { 
      int str = persons[j].strength; 
      if (i == 0) { 
       if (str > temp) 
        temp = str; 
      } 
      else { 
       if (str > temp 
         && str < persons[arrayOfStrongestPeopleIndices[i - 1]].strength) 
        temp = str; 
      } 
     } 

     for (int j = 0; j < persons.length; j++) { 
      if (temp = persons[j].strength) 
       arrayOfStrongestPeopleIndices[i] = j; 
       break; 
     } 
    } 
    return arrayOfStrongestPeopleIndices; 
} 

我不得不檢修代碼以跟上編輯。此方法將接受任意長度的「Person」數組並返回長度爲5的整數數組。