Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

ปัญหาการล็อกและคีย์โดยใช้ Hash-map


รายการล็อคที่แตกต่างกันและรายการกุญแจอีกรายการหนึ่งจะได้รับ งานของเราคือค้นหาการจับคู่ที่ถูกต้องของล็อคและกุญแจจากรายการที่กำหนด และกำหนดกุญแจนั้นด้วยการล็อคเมื่อถูกต้อง

ในแนวทางนี้ เราจะสำรวจล็อคทั้งหมดและสร้าง hash-map หลังจากนั้น แต่ละคีย์จะถูกค้นหาใน hash-map เมื่อคีย์ตรงกัน ระบบจะทำเครื่องหมายว่าเป็นคีย์ที่ถูกต้องและกำหนดด้วยการล็อก

อินพุตและเอาต์พุต

Input:
The lists of locks and keys.
lock = { ),@,*,^,(,%, !,$,&,#}
key = { !, (, #, %, ), ^, &, *, $, @ }
Output:
After matching Locks and Keys:
Locks: ! ( # % ) ^ & * $ @
Keys: ! ( # % ) ^ & * $ @

อัลกอริทึม

lockAndKeyProblem(lock, key, n)

ป้อนข้อมูล: รายการแม่กุญแจ รายการลูกกุญแจ n.

ผลลัพธ์: ค้นหาว่ากุญแจดอกไหนที่ใช้สำหรับล็อคตัวไหน

Begin
   define hashmap
   for i in range (0 to n-1), do
      hashmap[lock[i]] := i  //set hashmap for locks
   done

   for i in range (0 to n-1), do
      if key[i] is found in the hashmap, then
         lock[i] = key[i]
   done
End

ตัวอย่าง

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

void show(char array[], int n) {
   for(int i = 0; i<n; i++)
      cout << array[i] << " ";
}

void lockAndKeyProblem(char lock[], char key[], int n) {
   map<char, int> hashMap;
   for(int i = 0; i<n; i++)
      hashMap[lock[i]] = i;           //hash map for locks

   for(int i = 0; i<n; i++) //for each keys for each lock
      if(hashMap.find(key[i]) != hashMap.end()) {
         lock[i] = key[i];
      }
}

int main() {
   char lock[] = {')','@','*','^','(','%','!','$','&','#'};
   char key[] = {'!','(','#','%',')','^','&','*','$','@'};
   int n = 10;
   lockAndKeyProblem(lock, key, n);
   cout << "After matching Locks and Keys:"<<endl;
   cout << "Locks: "; show(lock, n); cout << endl;
   cout << "Keys: "; show(key, n); cout << endl;
}

ผลลัพธ์

After matching Locks and Keys:
Locks: ! ( # % ) ^ & * $ @
Keys: ! ( # % ) ^ & * $ @