gpt4 book ai didi

arrays - 查找、计数和索引数组中的重复项

转载 作者:行者123 更新时间:2023-12-04 10:31:18 28 4
gpt4 key购买 nike

我有一个数组,它有一些重复的值。
我必须计算每个重复项的数量及其索引。
打印如:

Index of b: 1
Index of b: 4
Index of c: 2
Index of c: 3
Index of c: 5
Index of e: 7
Index of e: 8

Total duplicate b: 2
Total duplicate c: 3
Total duplicate e: 2


在我的代码中,我只能找到重复的值。
Dim list As New List(Of String) From {"a", "b", "c", "c", "b", "c", "d", "e", "e"}
Dim duplicates = list.GroupBy(Function(x) x).Where(Function(x) x.Count > 1).Select(Function(x) x.Key)

For Each i As String In list.ToArray
If duplicates.Contains(i) Then
Debug.WriteLine("Duplicate Element: " & i & "Index: " & list.IndexOf(i))
End If
Next
这给出了输出:
Duplicate Element: bIndex:  1
Duplicate Element: cIndex: 2
Duplicate Element: cIndex: 2
Duplicate Element: bIndex: 1
Duplicate Element: cIndex: 2
Duplicate Element: eIndex: 7
Duplicate Element: eIndex: 7

最佳答案

一种方法

    Dim list As New List(Of String) From {"a", "e", "e", "b", "c", "c", "b", "c", "d", "e"}
Dim duplicates As IEnumerable(Of String) = list.Distinct
duplicates = From s In duplicates
Where list.FindAll(Function(l) l = s).Count > 1
Select s

For Each s As String In duplicates
Dim ct As Integer = (From l In list Where l = s Select l).Count
Debug.WriteLine(s)
Debug.WriteLine("count:{0}", ct)
Dim idx As IEnumerable(Of Integer)
idx = From n In Enumerable.Range(0, list.Count)
Where list(n) = s
Select n Take ct

Debug.WriteLine("Indexes")
For Each n As Integer In idx
Debug.Write(n.ToString)
Debug.Write(" ")
Next
Debug.WriteLine("")
Next

输出
e
count:3
Indexes
1 2 9
b
count:2
Indexes
3 6
c
count:3
Indexes
4 5 7

关于arrays - 查找、计数和索引数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60418643/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com