检查数组中的所有对是否都能被 k 整除

Check whether all the pairs in an array are divisible by k

本文关键字:整除 是否 数组 检查      更新时间:2023-10-16

给定一个整数数组和一个数字k,编写一个返回 true 的函数,如果给定的数组可以分成对,使得每对的总和可以被 k 整除。

这段代码为所有测试用例生成正确的结果,除了我找不到其中的故障。

#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    int arr[n];
    for (int i = 0; i < n; i++) {
      cin >> arr[i];
    }
    int k;
    cin >> k;
    int flag[n] = {0};
    int p = 0;
    int q = 0;
    if (n % 2 != 0) {
      cout << "False" << endl;
    } else {
      for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
          if ((arr[i] + arr[j]) % k == 0 && flag[j] == 0) {
            p = 1;
            flag[j] = 1;
          }
        }
        if (p == 0) {
          q = 1;
          cout << "False" << endl;
          break;
        }
      }
      if (q == 0) {
        cout << "True" << endl;
      }
    }
  }
  return 0;
}

代码中错误的主要来源之一是混乱的代码。那么我们如何清理代码呢?我们将其模块化。这意味着分解代码,以便代码的每个部分都能很好地完成一项工作。让我们看看它是什么样子的。

检查某物是否可以被 k 整除的函数:

bool isDivisible(int number, int divisor) {
    return number % divisor == 0; 
}

检查所有货币对的功能:逻辑如下:

  1. 取列表中的第一个号码;n0拨打。
  2. 对于每个剩余的数n1,检查它加上第一个数是否可以被 k 整除
  3. 当我们发现n1 n0 + n1可以被k整除时,一个。如果剩余的数字也可以拆分成可整除对,则返回 trueb.否则,请继续搜索

4.如果我们已经搜索了所有数字,则返回 false。

bool pairsDivisible(int* nums, int count, int k) {
    if(count == 0) return true;
    if(count % 2 != 0) return false; // count must be even
    // 1.
    int n0 = nums[0]; 
    // 2.
    for(int i = 1; i < count; i++) {
        int n1 = nums[i]; 
        // 3.
        if(isDivisible(n0 + n1, k)) {
            // Move the ith number so it's now nums[1]
            std::swap(nums[1], nums[i]); 
            if(pairsDivisible(nums + 2, count - 2, k)) {
                return true; // 3.a
            } else {
                // Reset the array
                std::swap(nums[1], nums[i]); 
            }
        }
    }
    return false; 
}