我有一长串数字。在每一行中,我有15个数字,全部在1到25之间。
鉴于25个数字中的N个数字出现在一行中,我想计算同一个N在下面的行中出现的次数。
例如,
2 3 4 12 14....
2 5 7 9 10...
1 3 4 20 21...
2 4 5 6 10...
2 12 7 8 10..
2 11 19 25 14..
如果这些都是我的所有行,算法应返回N = 2的值3,因为2后面跟着它三次。对于N = 4,算法应返回值2.
有没有人知道一种简单的方法呢?
答案 0 :(得分:2)
伪很简单。搜索每一行arr[i][:]
(第i行),如果在N
行和行i
中找到i+1
,则会计算+1
。
答案 1 :(得分:2)
首先,您可能需要为每个数字设置一个计数器变量(您可以在数字首先出现时启动它们。)
有两种简单的方法可以做到这一点:
检查每一行是否包含数字,如果是,则再计数器++,否则计数器= 0.
对于第一天的每个号码,如果发生,请查看第二天,如果是,则增加计数器,否则停止计数器。
如果它可以帮助你,我可以快速地在Lua(或类似)中编写一个函数。
编辑(如所承诺的):有点过于复杂(...)此功能(方式1):
testdata = {{2, 3, 4, 12, 14},{2, 5, 7, 9, 10},{1, 3, 4, 20, 21},{2, 4, 5, 6, 10},{2, 12, 7, 8, 10},{2, 11, 19, 25, 14}}
-- Thanks @wookai for this function draft
function table.contains(table, testedNumber)
for j=1, #table do
if table[j] == testedNumber then
return true
end
end
return false
end
function getStreakForNumber(number)
max = 0 counter = 0
for i=1, #testdata do -- Iterate over the provided data, check if the table contains the number and increase the counter
if table.contains(testdata[i], number) then
counter = counter + 1
else
if counter > max then
max = counter
end
counter = 0
end
end
if counter > max then
max = counter
end
return max
end
print(getStreakForNumber(4)) -- prints 2
print(getStreakForNumber(2)) -- prints 3
答案 2 :(得分:1)
这是一个快速抛出的Java示例 - 很可能效率不高等但我今天早上没有太多时间:
File file = new File("C:\\your\\filepath\\filename.txt");
Scanner sc = new Scanner(file);
int count = 0;
int tempcount = 0;
ArrayList<String> list = new ArrayList<>();
while (sc.hasNextLine()) {
list.add(sc.nextLine());
}
for (int i = 1; i < list.size(); i++) {
String[] space = list.get(i).split("\\s+");
if (Arrays.asList(space).contains("2")) { //this is your number
tempcount++;
} else {
tempcount = 0;
}
if (tempcount > count) {
count = tempcount;
}
}
System.out.println(count);