- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert an array to reduced form (Hashing) in C++
In this tutorial, we will be discussing a program to convert an array to its reduced form using hashing.
For this we will be provided with an array. Our task is to convert the given array in its reduced form such that it only contains elements ranging from 0 to n-1.
Example
#include <bits/stdc++.h> using namespace std; //converting array to its reduced form void convert(int arr[], int n){ // copying the elements of array int temp[n]; memcpy(temp, arr, n*sizeof(int)); sort(temp, temp + n); //creating a hash table unordered_map<int, int> umap; int val = 0; for (int i = 0; i < n; i++) umap[temp[i]] = val++; //putting values in the hash table for (int i = 0; i < n; i++) arr[i] = umap[arr[i]]; } void print_array(int arr[], int n) { for (int i=0; i<n; i++) cout << arr[i] << " "; } int main(){ int arr[] = {10, 20, 15, 12, 11, 50}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Given Array :\n"; print_array(arr, n); convert(arr , n); cout << "\nConverted Array:\n"; print_array(arr, n); return 0; }
Output
Given Array : 10 20 15 12 11 50 Converted Array: 0 4 3 2 1 5
- Related Articles
- Convert an array to reduced form (Using vector of pairs) in C++
- How to convert a decimal number to a fraction reduced to its lowest form?
- Product of given N fractions in reduced form in C
- How to use associative array/hashing in JavaScript?
- C++ program to rearrange an array in maximum minimum form
- How to convert a tuple into an array in C#?
- How to convert byte array to an object stream in C#?
- How to convert an object array to an integer array in Java?
- Rearrange an Array in Maximum Minimum Form using C++
- Convert an Array to a Circular Doubly Linked List in C++
- Convert LinkedList to an array in Java
- Convert object to an array in PHP.
- Convert Queue To array in C#
- Convert Stack to array in C#
- Convert an ArrayList to an Array with zero length Array in Java

Advertisements