2016-04-30 54 views
0

所以我正在開發一個使用Fabric API的丟失和找到的應用程序。它可以根據用戶的當前位置對收集的推文進行排序。我發現在線方式使用比較器進行排序。然而,這似乎並不奏效,而前分類和後分類結果完全相同。Twitter的織物API:根據位置排序tweets(最近的第一個)

public class SortLocations implements Comparator<Tweet> { 
    Double currLat; 
    Double currLng; 

    public SortLocations(Double currLat1, Double currLng1) { 
     currLat = currLat1; 
     currLng = currLng1; 
    } 

    @Override 
    public int compare(final Tweet tweet1, final Tweet tweet2) { 
     double lat1 = 0, lon1 = 0, lat2 = 0, lon2 = 0, distanceToPlace1 = 0, distanceToPlace2 = 0; 
     try { 
      lat1 = tweet1.coordinates.getLatitude(); 
      lon1 = tweet1.coordinates.getLongitude(); 

      lat2 = tweet2.coordinates.getLatitude(); 
      lon2 = tweet2.coordinates.getLongitude(); 

      distanceToPlace1 = distance(currLat, currLng, lat1, lon1); 
      distanceToPlace2 = distance(currLat, currLng, lat2, lon2); 
     } catch (Exception E) { 
      Log.d("No coordinates", ""); 
     } 
     return (int) (distanceToPlace1 - distanceToPlace2); 
    } 

    public double distance(double fromLat, double fromLon, double toLat, double toLon) { 
     double radius = 6378137; // approximate Earth radius, *in meters* 
     double deltaLat = toLat - fromLat; 
     double deltaLon = toLon - fromLon; 
     double angle = 2 * Math.asin(Math.sqrt(
       Math.pow(Math.sin(deltaLat/2), 2) + 
         Math.cos(fromLat) * Math.cos(toLat) * 
           Math.pow(Math.sin(deltaLon/2), 2))); 
     return radius * angle; 
    } 
} 

這是類是如何在我的活動

Collections.sort(tweetsSortedByLocation, new SortLocations(currLat, currLng)); 

哪裏tweetsSortedByLocation的類型是List使用。任何幫助真的很感激:)

回答

1

我可能會建議一個稍微不同的方法,這將使您的生活更容易一點,而不會損失任何計算時間。

您當前的解決方案可能是n + n log(n)time:n用於向集合添加Tweets,然後用n log(n)進行排序。如果您使用PriorityQueue(在Java中以min-heap實現)而不是常規列表(因爲我假設tweetsSortedByLocation是),那麼它會在添加到它時進行排序,從而爲您提供n個log(n)時間:n元素和日誌(n)爲每個插入(認爲二進制搜索)。

您可以使用一個PriorityQueue像這樣(https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html):

PriorityQueue<Tweet> tweetsSortedByLocation = new PriorityQueue<>(10, new SortLocations(currLat, currLong)); 
tweetsSortedByLocation.add(new Tweet()); // Or however you add them now 

你也可以內嵌的比較,但使用SortLocations更好。

現在,爲什麼排序時沒有任何變化,這意味着compare()每次都必須返回0。

return (int) (distanceToPlace1 - distanceToPlace2); 

如果distanceToPlace1和distanceToPlace2沒有比差1以上,即整數投帶來了它:如果你計算兩個距離之間的差值小於1。看在這條線的整鑄這將發生爲0,在比較必須實施的情況下,意味着平等。 (見https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html)。那麼,試試這個,而不是(至少到第一排序距離(即通過距離ASC)):

if (distanceToPlace1 < distanceToPlace2) { 
    return -1; 
} else if (distanceToPlace1 > distanceToPlace2) { 
    return 1; 
} else { 
    return 0; 
} 

我希望解決您的問題

+0

感謝您的答覆!扎克非常感謝您的全面解決方案。 –

相關問題