gpt4 book ai didi

c++ - 检查一个数组是否以相反的顺序包含在另一个数组中,至少两次

转载 作者:行者123 更新时间:2023-12-02 10:29:57 26 4
gpt4 key购买 nike

I wrote a C++ function hasMirrorTwice that takes as parameters two arrays of integers, arr1 and arr2, and their lengths and checks if arr1 contains all elements of arr2 in reverse order at least twice. Below is the function. I was wondering if there was a way to simplify it?

bool hasMirrorTwice(int a1[], int a2[], int size1, int size2) {
int num_reps = 0;
bool contains = false;
for (int i = 0; i < size1; ++i) {
contains = false;
if (a1[i] == a2[size2 - 1]) {
contains = true;
for (int k = size2 - 2; k >= 0; --k) {
if (i + size2 - 1 - k >= size1 || a2[k] != a1[i + size2 - 1 - k]) {
contains = false;
break;
}
}
}
if (contains) {
++num_reps;
i += size2 - 2;
}
if (num_reps >= 2) {
return true;
}
}

return false;
}
在下面的主要函数中,输出应为true。
#include <iostream>
int main() {
int a4[] = {1,2,3,2,3,2};
int a5[] = {2,3,2};
std::cout << std::boolalpha << hasMirrorTwice(a4, a5, 6, 3)
<< std::endl;
}

最佳答案

您可以使用标准库 std::search 算法和反向迭代器。例如:

bool hasMirrorTwice(const int *a1, const int *a2, int size1, int size2)
{
using ritr = std::reverse_iterator<const int *>;

// first match
auto itr = std::search(a1, a1 + size1, ritr(a2 + size2), ritr(a2));
if (itr == a1 + size1) {
return false; // no match
}

// second match (start 1 position after previous match)
itr = std::search(itr + 1, a1 + size1, ritr(a2 + size2), ritr(a2));
return itr != a1 + size1;
}
C++ 17添加了可以与 std::search一起使用的其他搜索算法。将 Boyer-Moore搜索算法添加到前面的示例中,这是一个小的修改。
bool hasMirrorTwice(const int *a1, const int *a2, int size1, int size2)
{
using ritr = std::reverse_iterator<const int *>;

auto searcher = std::boyer_moore_searcher(ritr(a2 + size2), ritr(a2));

// first match
auto itr = std::search(a1, a1 + size1, searcher);
if (itr == a1 + size1) {
return false; // no match
}

// second match (start 1 position after previous match)
itr = std::search(itr + 1, a1 + size1, searcher);
return itr != a1 + size1;
}

关于c++ - 检查一个数组是否以相反的顺序包含在另一个数组中,至少两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62626347/

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