鸿 网 互 联 www.68idc.cn

当前位置 : 服务器租用 > 编程语言开发 > c++ > >

随机打乱给定数组 Randomize Algorithm

来源:互联网 作者:佚名 时间:2016-06-06 10:04
本代码用于实现随机打乱数组,其中heapsort一段参见本人heapsort部分的代码。 无 #include "HornersRuleTest.h"#include "PermutationTest.h"#include "HanoiTower.h"#include "RadomizeData.h"#include iostreamusing namespace std;int main(){//hornersRul
本代码用于实现随机打乱数组,其中heapsort一段参见本人heapsort部分的代码。 <无>
#include "HornersRuleTest.h"
#include "PermutationTest.h"
#include "HanoiTower.h"
#include "RadomizeData.h"
#include <iostream>

using namespace std;

int main()
{
	//hornersRule();
	//permutationTest();
	//runMove();
	vector<double> data = { 1.0, 2.4, 3, 3.5, 4.2, 5.5, 6.8 };
	Randomize<double> randomize(data);
	data = randomize.getRandomizedData();
	printf("New data: ");
	for (int index = 0; index < data.size(); index++)
		printf("%f ", data.at(index));
	printf("\n");
	system("Pause");
	return 0;
}
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<time.h>
#include<cmath>
#include "HeapSort.h"

using namespace std;

template <typename E>
class Randomize
{
public:
	Randomize(vector<E> data)
	{
		datalist = data;
		srand(time(NULL));
		for (int index = 0; index < datalist.size(); index++)
		{
			int val = (int)(rand() * 1.0 / RAND_MAX * (pow(datalist.size(), 3) - 1) + 1);
			Event newEvent;
			newEvent.priority = val;
			newEvent.data = datalist.at(index);			
			eventlist.push_back(newEvent);
		}//end loop

		int * priorityList = new int[datalist.size()];
		printf("Priority: ");
		for (int index = 0; index < datalist.size(); index++)
		{
			priorityList[index] = (eventlist.at(index).priority);
			printf("%d ", priorityList[index]);
		}
		printf("\nData: ");
		for (int index = 0; index < eventlist.size(); index++)
		{
			printf("%f ", eventlist.at(index).data);
		}
		printf("\n\n");

		heapSort(priorityList, datalist.size());

		for (int index = 0; index < eventlist.size(); index++)
		{
			if (eventlist.at(index).priority != priorityList[index])
			{
				Event temp = eventlist.at(index);
				for (int j = index; j < eventlist.size(); j++)
				{
					if (eventlist.at(j).priority == priorityList[index])
					{
						eventlist.at(index) = eventlist.at(j);
						eventlist.at(j) = temp;
						break;
					}
				}//end loop
			}//end if
		}//end loop
		
		printf("Priority: ");
		for (int index = 0; index < datalist.size(); index++)
			printf("%d ", eventlist.at(index).priority);
		printf("\nData: ");
		for (int index = 0; index < eventlist.size(); index++)
		{
			datalist.at(index) = eventlist.at(index).data;
			printf("%f ", eventlist.at(index).data);
		}
		printf("\n");

	}//end constructor

	vector<E> getRandomizedData()
	{
		return datalist;
	}

private:
	struct Event
	{
		int priority;
		E data;
	}newEvent;
	vector<Event> eventlist;
	vector<E> datalist;
};//end class.
网友评论
<