//
// main.cpp
// K nearest neighbors
//
// Created by Himanshu on 18/08/21.
//
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
int const N = 5;
bool cmp( const vector<float>& p,
const vector<float>& q ) {
return p[1] < q[1];
}
void solve (int points[][2], int point[], int k) {
vector< vector<float> > distance;
for (int i=0; i<N; i++) {
float d = sqrt((pow((point[0] - points[i][0]), 2)) + (pow((point[1] - points[i][1]), 2)));
float pos = i;
distance.push_back({pos, d});
}
sort(distance.begin(), distance.end(), &cmp);
cout<<"K nearest neighbors:"<<endl;
for (int i=0; i<k; i++) {
cout<<distance[i][0]<<" - distance: "<<distance[i][1]<<endl;
}
}
int main () {
int points[N][2] = {{1, 1}, {3, 4}, {2, 3}, {7, 8}, {2, 5}};
int point[2] = {0, 0};
int k = 2;
solve(points, point, k);
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBLIG5lYXJlc3QgbmVpZ2hib3JzCi8vCi8vICBDcmVhdGVkIGJ5IEhpbWFuc2h1IG9uIDE4LzA4LzIxLgovLwoKI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8YWxnb3JpdGhtPgojaW5jbHVkZSA8bWF0aC5oPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwppbnQgY29uc3QgTiA9IDU7Cgpib29sIGNtcCggY29uc3QgdmVjdG9yPGZsb2F0PiYgcCwKICAgICAgICAgICAgICAgY29uc3QgdmVjdG9yPGZsb2F0PiYgcSApIHsKICAgIHJldHVybiBwWzFdIDwgcVsxXTsKfQoKdm9pZCBzb2x2ZSAoaW50IHBvaW50c1tdWzJdLCBpbnQgcG9pbnRbXSwgaW50IGspIHsKICAgIHZlY3RvcjwgdmVjdG9yPGZsb2F0PiA+IGRpc3RhbmNlOwogICAgCiAgICBmb3IgKGludCBpPTA7IGk8TjsgaSsrKSB7CiAgICAgICAgZmxvYXQgZCA9IHNxcnQoKHBvdygocG9pbnRbMF0gLSBwb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