Unique Fractions in C++


Suppose we have a list of fractions where each fraction contains [numerator, denominator] (numerator / denominator). We have ti find a new list of fractions such that the numbers in fractions are −

  • In their most reduced terms. (20 / 14 becomes 10 / 7).

  • Any duplicate fractions (after reducing) will be removed.

  • Sorted in ascending order by their actual value.

  • If the number is negative, the '-' sign will be with the numerator.

So, if the input is like {{16, 8},{4, 2},{7, 3},{14, 6},{20, 4},{-6, 12}}, then the output will be [[-1, 2],[2, 1],[7, 3],[5, 1]]

To solve this, we will follow these steps −

  • Define one set s

  • n := size of v

  • make an array r

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • c := gcd of |v[i, 0]| and |v[i, 1]|

    • v[i, 0] := v[i, 0] / c

    • v[i, 1] := v[i, 1] / c

    • insert {v[i, 0], v[i, 1]} at the end of r

  • sort the array r based on their values

  • make an array ret

  • for initialize i := 0, when i < size of r, update (increase i by 1), do −

    • if ret is not empty and last element of ret is same as r[i], then −

      • insert r[i] at the end of ret

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto>> v) {
   cout << "[";
   for (int i = 0; i < v.size(); i++) {
      cout << "[";
      for (int j = 0; j < v[i].size(); j++) {
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]" << endl;
}
class Solution {
   public:
   static bool cmp(vector <int>& a, vector <int>& b){
      double aa = (double)a[0] / (double)a[1];
      double bb = (double)b[0] / (double)b[1];
      return aa < bb;
   }
   vector<vector<int>> solve(vector<vector<int>>& v) {
      set < vector <int> > s;
      int n = v.size();
      vector < vector <int> > r;
      for(int i = 0; i < n; i++){
         int c = __gcd(abs(v[i][0]), abs(v[i][1]));
         v[i][0] /= c;
         v[i][1] /= c;
         r.push_back({v[i][0], v[i][1]});
      }
      sort(r.begin(), r.end(), cmp);
      vector < vector <int> > ret;
      for(int i = 0; i < r.size(); i++){
         if(!ret.empty() && ret.back() == r[i]) continue;
         ret.push_back(r[i]);
      }
      return ret;
   }
};
int main(){
   vector<vector<int>> v = {{16, 8},{4, 2},{7, 3},{14, 6},{20, 4},{-
   6, 12}};
   Solution ob;
   print_vector(ob.solve(v));
}

Input

{{16, 8},{4, 2},{7, 3},{14, 6},{20, 4},{-6, 12}}

Output

[[-1, 2, ],[2, 1, ],[7, 3, ],[5, 1, ],]

Updated on: 02-Sep-2020

185 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements