Post date: Jan 14, 2014 11:33:26 PM
Question
Q: Given an array of integers and an integer k. Returns the pairs that subtract result in k. Example: 3,6,10,13.
(3,6),(10,13)
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Given an array of integers and an integer k. Returns the pairs that subtract result in k.
Created Date : 15-01-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <iomanip>
#include <set>
#include <algorithm>
#include <iterator>
using namespace std;
void DiffK(set<pair<int, int>> &ps, int k, initializer_list<int> il)
{
ps.clear();
for (auto i : il){
for (auto j : il){
if (j - i == k){
ps.insert({i, j});
}
}
}
}
void PrintPairs(set<pair<int, int>> &ps)
{
for (auto it : ps){
cout << "( " << it.first << ", " << it.second << " )" << endl;
}
}
int main()
{
set<pair<int, int>> ps;
DiffK(ps, 3, { 3, 6, 10, 13, 7, 9 });
PrintPairs(ps);
return 0;
}
Output
( 3, 6 )
( 6, 9 )
( 7, 10 )
( 10, 13 )
Press any key to continue . . .