```
#include <iostream>
#include <cmath>
using namespace std;
class range
{
public:
double a,b;
};
void sort(range *R,int nr)
{
int i,j,k;
double tmp,tmpm,r;
bool *c;
c=new bool[nr];
for(i=0;i<nr;i++) c[i]=1;
range *R2;
R2=new range[nr];
k=0;
tmpm=R[0].a;
for(i=0;i<nr;i++) tmpm=max(tmpm,R[i].b);
for(i=0;i<nr;i++)
{
tmp=tmpm;
for(j=0;j<nr;j++)
{
if(c[j])
{
if(min(tmp,R[j].a)==R[j].a)
{
k=j;
tmp=R[j].a;
}
}
}
c[k]=0;
R2[i]=R[k];
}
for(i=0;i<nr;i++) R[i]=R2[i];
delete[] c;
delete[] R2;
}
double rands(double a,double b,range *R,int nr)
{
int i,j;
double r;
range *R2;
R2=new range[nr+1];
R2[0].a=a; R2[0].b=R[0].a;
for(i=1;i<nr;i++)
{
R2[i].a=R[i-1].b;
R2[i].b=R[i].a;
}
R2[nr].a=R[nr-1].b; R2[nr].b=b;
r=double(rand()%10000)/10000.0;
double S=0;
for(i=0;i<=nr;i++) S+=R2[i].b-R2[i].a;
double *coeff;
coeff=new double[nr+2];
coeff[0]=0.0;
for(i=0;i<=nr;i++) coeff[i+1]=coeff[i]+(R2[i].b-R2[i].a)/S;
j=0;
for(i=0;i<=nr;i++) if(r>=coeff[i] && r <=coeff[i+1]) j=i;
r=R2[j].a+(r-coeff[j])/(coeff[j+1]-coeff[j])*(R2[j].b-R2[j].a);
/*for(i=0;i<=nr;i++) cout<<R2[i].a<<" "<<R2[i].b<<endl;
cout<<S<<endl;
for(i=0;i<=nr+1;i++) cout<<coeff[i]<<" ";*/
delete[] R2;
delete[] coeff;
return r;
}
int main()
{
srand(time(NULL));
range *R;
R=new range[5];
R[2].a=2; R[2].b=3;
R[0].a=4; R[0].b=7;
R[1].a=14; R[1].b=16;
R[4].a=10; R[4].b=11;
R[3].a=17; R[3].b=18;
sort(R,5);
//for(int i=0;i<5;i++) cout<<R[i].a<<" "<<R[i].b<<endl;
for(int i=0;i<30;i++) cout<<rands(1,20,R,5)<<endl;
}
```

This algorithm sorts the different ranges, it assumes that all the ranges are within two values and don’t overlap each other.