From 83bed704d970691e6d3a3b646d004e0a5a64eac2 Mon Sep 17 00:00:00 2001 From: Assassin-compiler <70448612+Assassin-compiler@users.noreply.github.com> Date: Sat, 30 Oct 2021 12:12:21 +0530 Subject: [PATCH] Create triplets.cpp --- triplets.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 triplets.cpp diff --git a/triplets.cpp b/triplets.cpp new file mode 100644 index 0000000..2bae601 --- /dev/null +++ b/triplets.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; + +// Function to print all triplets in +// given sorted array that forms AP +void printAllAPTriplets(int arr[], int n) +{ + unordered_set s; + for (int i = 0; i < n - 1; i++) + { + for (int j = i + 1; j < n; j++) + { + // Use hash to find if there is + // a previous element with difference + // equal to arr[j] - arr[i] + int diff = arr[j] - arr[i]; + if (s.find(arr[i] - diff) != s.end()) + cout << arr[i] - diff << " " << arr[i] + << " " << arr[j] << endl; + } + s.insert(arr[i]); + } +} + +// Driver code +int main() +{ + int arr[] = { 2, 6, 9, 12, 17, + 22, 31, 32, 35, 42 }; + int n = sizeof(arr) / sizeof(arr[0]); + printAllAPTriplets(arr, n); + return 0; +}