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

พิมพ์พิกัด 2D และความถี่เรียงลำดับใน C++


ภาพรวมปัญหา

ได้รับอาร์เรย์ x[] และ y[] ที่ (x,y) เป็นพิกัดจุดในระนาบ 2D ต้องพิมพ์จุดทั้งหมดพร้อมความถี่ เรียงตามลำดับ

ตัวอย่าง

Input: x[]={0,1,1,0,0}, y[]={1,2,2,2,1}
Output: (0,1)=2, (1,2)=2, (0,2)=1

วิธีแก้ปัญหา

ใช้ map<pair<int,int>, int> เก็บความถี่ของแต่ละจุด Key คือ pair(x,y), Value คือความถี่

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

#include <bits/stdc++.h>
using namespace std;

void printFrequencyofPoint(int x[], int y[], int n){
    map<pair<int, int>, int> pFreq;
    for (int i = 0; i < n; i++)
        pFreq[make_pair(x[i], y[i])]++;
    for (auto i = pFreq.begin(); i != pFreq.end(); i++) {
        cout << "(" << (i->first).first << ", " << (i->first).second << ") -> ";
        cout << i->second << "\n";
    }
}

int main() {
    int x[] = {0, 1, 1, 0, 0};
    int y[] = {1, 2, 2, 2, 1};
    int n = 5;
    cout << "The points and their frequency of occurance is :\n";
    printFrequencyofPoint(x, y, n);
    return 0;
}

ผลลัพธ์

The points and their frequency of occurance is :
(0, 1) -> 2
(0, 2) -> 1
(1, 2) -> 2