Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาคู่ (a,b) และ (c,d) ในอาร์เรย์ที่ทำให้ ab = cd ด้วย C++

ข้อความโจทย์

สมมติว่าเรามีอาร์เรย์ A จากอาร์เรย์นั้น เราต้องเลือกสองคู่ (a, b) และ (c, d) ที่ทำให้ ab = cd ให้อาร์เรย์ A = [3, 4, 7, 1, 2, 9, 8] คู่ที่ได้คือ (4, 2) และ (1, 8) เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -

  • สำหรับ i := 0 ถึง n-1 ทำ
    • สำหรับ j := i + 1 ถึง n-1 ทำ
      • หาผลคูณ = arr[i] * arr[j]
      • ถ้าผลคูณไม่อยู่ในตารางแฮช ให้ Hash[product] := (i, j)
      • ถ้าผลคูณอยู่ในตารางแฮชแล้ว ให้พิมพ์สมาชิกก่อนหน้าและปัจจุบัน

ตัวอย่างโค้ด

#include <iostream>
#include <unordered_map>
using namespace std;

void displayPairs(int arr[], int n) {
    bool found = false;
    unordered_map<int, pair < int, int > > Hash;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            int prod = arr[i] * arr[j];
            if (Hash.find(prod) == Hash.end())
                Hash[prod] = make_pair(i, j);
            else {
                pair<int,int> pp = Hash[prod];
                cout << "(" << arr[pp.first] << ", " << arr[pp.second] << ") and (" << arr[i] << ", " << arr[j] << ")" << endl;
                found = true;
            }
        }
    }
    if (found == false)
        cout << "No pairs have Found" << endl;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
    int n = sizeof(arr) / sizeof(int);
    displayPairs(arr, n);
}

ผลลัพธ์

(1, 6) and (2, 3)
(1, 8) and (2, 4)
(2, 6) and (3, 4)
(3, 8) and (4, 6)