How to Scale or Normalize array or vector for desired range in C++





#include <bits/stdc++.h>
using namespace std;

int scaleBetween(int unscaledNum, int minAllowed, int maxAllowed, int min, int max)
{
     int ans;
     ans=(maxAllowed - minAllowed) * (unscaledNum - min) / (max - min) + minAllowed;
     return ans;
}

int main()
{
    int scaleMin, scaleMax,i,n,m;
    vector<int>data;
    cout<<"Enter Number of  data"<<endl;
    cin>>n;
    cout<<"Enter data"<<endl;
    for(i=0;i<n;i++)
    {
        cin>>m;
        data.push_back(m);
    }
    cout<<"Enter your desired min and max Range"<<endl;
    cin>>scaleMin>>scaleMax;

    int minRange=*min_element(data.begin(), data.end());
    int maxRange=*max_element(data.begin(), data.end());

    for (i = 0; i < data.size(); i++)
    {
          int unscaled = data[i];
          int scaled = scaleBetween(unscaled, scaleMin, scaleMax, minRange, maxRange);
          cout<<scaled<<endl;
    }

    return 0;
}

Download Coding Interview Book and Get More Tutorials for Coding and Interview Solution: Click Here

Download System Design Interview Book and Get More Tutorials and Interview Solution: Click Here

Do you need more Guidance or Help? Then Book 1:1 Quick Call with Me: Click Here

Share on Google Plus

About Ashadullah Shawon

I am Ashadullah Shawon. I am a Software Engineer. I studied Computer Science and Engineering (CSE) at RUET. I Like To Share Knowledge. Learn More: Click Here
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment