/*
This file is created for testing/hardware benchmarking purposes.
It follows the Science and Technology Promotion License of Zhikai Wang/www.heteroclinic.net.
In addition, Zhikai Wang/www.heteroclinic.net won't claim any rights upon this file.
Zhikai Wang/www.heteroclinic.net 2013

Please refer to Knuth Shuffling about this implementation.

*/
#include <iostream>
#include <exception>
#include <unistd.h>
#include <math.h>
#include <time.h>
#include <ctime>
#include <stdlib.h>     /* srand, rand */
using namespace std;

int main () {
std::cout<<time(NULL)<<std::endl;
	srand(time(NULL)%73);

  clock_t startt = std::clock();
clock_t endt = std::clock();

  int* myarray= NULL;
  //std::cout<<"pow(2,30) is  "<<pow(2,30)<<std::endl;
  int e = 28;// for the Vista 64 cygwin, 28 is possible
  long c = pow(2,e);
  //int e = 0;
  try
  {
    myarray= new int[c];
    // //int* myarray= new int[1000];
    // do {
      // std::cout<<"c : "<<c<<"\t"<<"e : "<<e <<std::endl;

      // myarray= new int[c];
      // //std::cout<<"sizeof myarray : "<<sizeof(myarray)<<std::endl;
      // sleep(2);
      // if ( myarray != NULL ) { delete [] myarray; myarray = NULL;}
      // //std::cout<<"sizeof myarray after delete: "<<sizeof(myarray)<<std::endl<<std::endl;
      // c = pow(2,++e);
    // } while (true);
	long array_i = 0;
	startt = std::clock();
	for (; array_i < c ; array_i++) {
	myarray[array_i] = array_i + 1;
	}

	endt = std::clock();
	
	std::cout<<"Assignment for e="<<e <<" takes "<< ( ( endt- startt) / (double)CLOCKS_PER_SEC )<<" seconds."<<std::endl;
	
	
	
		startt = std::clock();
		
		for (array_i=0; array_i < c-1 ; array_i++) {
			int v = rand() % (c -array_i-1);
			int cursor = v+array_i+1;
			if (cursor >= c)
				continue;
			//std::cout<<"v "<<v<<"\t"<< "cursor "<<cursor <<std::endl;
			
			int tmp = myarray[cursor ];
			myarray[cursor ] = myarray[array_i];
			myarray[array_i] = tmp;
			// int j = 0;
			// for ( ; j <c ; j++) {
			// std::cout<<myarray[j]<<"\t";
			// }
			// std::cout<<std::endl;
			
			//myarray[array_i] = array_i + 1;
		}
		endt = std::clock();
		std::cout<<"Shuffle takes "<< ( ( endt- startt) / (double)CLOCKS_PER_SEC )<<" seconds."<<std::endl;
		
		 // // veriy while e is small
		 // std::cout<<"veriy while e is small:"<<std::endl;

		 // for (array_i=0; array_i < c ; array_i++) {
			 // std::cout<<myarray[array_i]<<std::endl;
		 // }
	
  }
  catch (bad_alloc&)
  {
      cout << "Error allocating memory." << endl;
      std::cout<<"c : "<<c<<"\t"<<"e : "<<e <<std::endl;
      //std::cout<<"sizeof myarray : "<<sizeof(myarray)<<std::endl;
      if ( myarray != NULL ) { delete [] myarray; myarray = NULL;}

      //std::cout<<"sizeof myarray after delete: "<<sizeof(myarray)<<std::endl<<std::endl;
  }
  catch (exception& exc)
  {
    cout << "Standard exception: " << exc.what() << endl;
  }
  return 0;
}
