duanshan1977 2018-07-31 21:03
浏览 297
已采纳

在golang中排序int切片

say I have an int slice containing the following numbers: 2781,4706,1347,1192,3087,2920,198,2312,930,3284,1677,3687,2011,4107,4148,4195,2159,1263,2918,2503

I want to sort them based on how close they are away from a certain value. For example, say my value was 1200.

My slice after being sorted would be: 1192,1263,1347,1677,2011,2159,2312,2503,2781,2918,2920,3087,3284,3687,4107,4148,4195,4706,930,198

I tried the approach of iterating through the array, subtracting my specified value, then sorting in ascending order ultimately adding the value again to return to my original number. This approach wouldn't work in all test cases, and I know its bad practice since I'm mutating the array.

  • 写回答

1条回答 默认 最新

  • donglieshe4692 2018-07-31 21:42
    关注

    One approach would be to use sort.Slice(...) with a "less" (comparator) function that simply returns the lesser of the distance of the two given values from the target value.

    For example (Go Playground):

    func main() {
      xs := []int{2781, 4706, 1347, 1192, 3087, 2920, 198, 2312, 930, 3284, 1677, 3687, 2011, 4107, 4148, 4195, 2159, 1263, 2918, 2503}
      sortByDistanceFrom(1200, xs)
      fmt.Println(xs)
      // [1192 1263 1347 930 1677 2011 2159 198 2312 2503 2781 2918 2920 3087 3284 3687 4107 4148 4195 4706]
    
    }
    
    func sortByDistanceFrom(x int, xs []int) {
      sort.Slice(xs, func(i, j int) bool {
        di := math.Abs(float64(x - xs[i]))
        dj := math.Abs(float64(x - xs[j]))
        return di < dj
      })
    }
    

    Note that the fourth value returned by this example is 930 instead of 1677 produced by your sample output because it computes the absolute distance to the target number (|1200-1677|=433 > |1200-930|=270). If you want to prefer values greater than the target to values less than the target then you would have to modify your comparator function accordingly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测