如何根据Golang的任何给定列中的任何给定列中的值对2D数组进行排序?

发布于 2025-02-12 05:46:57 字数 424 浏览 0 评论 0原文

我们给出了订单NXM和列编号K(1< = K< = m)的2D数组。任务是根据K列中的值对2D数组进行排序。

 Input : If our 2D array is given as (Order 4X4) 
        39 27 11 42 
        10 93 91 90 
        54 78 56 89 
        24 64 20 65
        Sorting it by values in column 3 
Output : 39 27 11 42 
         24 64 20 65 
         54 78 56 89 
         10 93 91 90 

我认为在此任务中需要使用Sort Slice:Len,Simelt,在接口中交换,但我无法确切地弄清楚如何确切地弄清楚如何

We are given a 2D array of order N X M and a column number K ( 1<=K<=m). Task is to sort the 2D array according to values in the Column K.

 Input : If our 2D array is given as (Order 4X4) 
        39 27 11 42 
        10 93 91 90 
        54 78 56 89 
        24 64 20 65
        Sorting it by values in column 3 
Output : 39 27 11 42 
         24 64 20 65 
         54 78 56 89 
         10 93 91 90 

I think in this task need to use Sort Slice: Len, Less, Swap in Interface but I can't figure out exactly how

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

思念满溢 2025-02-19 05:46:57

实际上,您可以只使用sort.slice,它将按行分类2D切片的行。

sort.slice采用一个函数,将每一行与彼此进行比较。在此功能中,您可以比较每行中的列。

https://go.dev/play/pplay/p/cj1z7jbs2u5

data := [][]int{
    {39, 27, 11, 42},
    {10, 93, 91, 90},
    {54, 78, 56, 89},
    {24, 64, 20, 65},
}
sortCol := 3
sort.Slice(data, func(i, j int) bool {
    return data[i][sortCol] < data[j][sortCol]
})

如果您有阵列而不是阵列切片,然后您可以使用相同的sort.slice如上所述,但是使用data [:]而不是data

https://go.dev/play/pplay/p/kczeptz8soz

You can actually just use sort.Slice, which will sort the rows of your 2D slice row by row.

sort.Slice takes a function to compare each row against eachother. Inside this function you can compare the column in each row.

https://go.dev/play/p/cj1z7jBs2u5

data := [][]int{
    {39, 27, 11, 42},
    {10, 93, 91, 90},
    {54, 78, 56, 89},
    {24, 64, 20, 65},
}
sortCol := 3
sort.Slice(data, func(i, j int) bool {
    return data[i][sortCol] < data[j][sortCol]
})

If you have an array instead of a slice, then you can use the same sort.Slice as above, but use data[:] instead of data.

https://go.dev/play/p/KcZepTz8SOZ

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文