#include <iostream>
#include <forward_list>
#include <string>
 
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::forward_list;
 
//値 _x がどこのindexに収まるか計算するハッシュ関数
//戻り値: 0~7
int Hash(int _x)
{
	return(_x % 8);
}
// データ列 [ 26, 53, 59, 84, 142, 161, 175, 178, 179 ] これをハッシュテーブルに収める
const int datsize = 9;
int dats[datsize] = { 26, 53, 59, 84, 142, 161, 175, 178, 179 };
 
int main()
{
	forward_list<int> hash_t[8]; 
	//教科書では空かどうか判定するために配列を -1 で初期化していた
	//hash_t[0] が空かどうか? hash_t[0].empty(): true 空 false データあり(何個かはわからない .size())
	for (auto i=0;i<datsize;i++)
	{
		//全部のデータをハッシュ関数にぶちこんで、得られたindexのlistに追加していくよ
		//hash_t[ハッシュ値] = データ値
		hash_t[Hash(dats[i])].push_front(dats[i]);
	}
 
	for (auto i = 0; i < 8; i++)
	{
		cout << "hash_t[" << i << "]:";
		if (hash_t[i].empty())
		{
			cout << "空";
		}
		else
		{
			//forward_list<int>::iterator theI; //i
			auto theI = hash_t[i].begin();
			while (true)
			{
				if (theI == hash_t[i].end())
					break;
				else
				{
					cout << *theI << "→";
					theI = std::next(theI);
				}
			}
		}
		cout << endl;
		//hash_t[i]
	}
 
}
  • ハッシュテーブル引くよ
  • (入ってるデータにしか効果ないよ)
	//ハッシュテーブルはここまでで完成してる
 
    //_keyがハッシュテーブルに有るか、無いか
    //ある時は→一発でデータが引けたらそのindexとデータを表示
    //      一発で引けなかったらリストの別の床にあるよ(リストの別のところにあるよ)
    //ないとき→データがないよ
	//cin で読み込んでもいいよ
	int key = 150; //これを探します。
	int hs = Hash(key); //hsにkeyのハッシュ値
 
	if (hash_t[hs].empty())
	{
		cout << "値はないよ";
	}
	else
	{
		if (hash_t[hs].front() == key)
		{
			cout << key << "は" << hs << "番のリストにありました";
		}
		else
		{
			cout << key << "は" << hs << "番のリストの先頭以外にあります";
		}
	}

選択ソート

#include <iostream>
#include <iomanip>
 
using std::cin; using std::cout; using std::endl;
 
void printArray(int _dat[], int _num) //配列を全部表示(2桁合わせつき)
{
	for (auto i = 0; i < _num; i++)
	{
		//cout << "data[" << i << "]=>" << _dat[i] << endl;
		cout << std::setw(2) << _dat[i] << " ";
	}
	cout << endl;
}
 
//選択ソートを実装するよ
void selectionSort(int _dat[], int _num)
{
	printArray(_dat, _num);
	int min; //最小値
	int min_j; //最小値が入ってるindex
	for (int comp = 0; comp < _num; comp++) {
		min = _dat[comp];
		min_j = comp;
		for (int j = comp + 1; j < _num; j++)
		{
			if (_dat[j] < min)
			{
				min_j = j;
				min = _dat[j];
			}
		}
		std::swap(_dat[comp], _dat[min_j]);
		printArray(_dat, _num);
	}
	//⓪comp = 0 , compは整列済みがどこまでか?
	//                 最小値:min
	//  最小値が入ってるindex:min_j
	//  初期値を min = _dat[comp]にしておく
	//①compから配列を線形探索して最小値を見つける
	//  comp+1~_num-1まで(_dat[comp+1] ~ _dat[num-1]まで)最小値を探索
	//  最小値の入っているindexを min_j = indexに更新しておく indexは最小値が入ってるindex
	//②最小値のindex と comp を交換 
	//  swap(dat[comp], dat[index])して配列表示
	//③compを1増やす ①に戻る
}
 
int main()
{
	const int datanum = 10;
	int data[datanum] = {68,15,89,69,58,67,96,49,9,27 };
 
	selectionSort(data, datanum);
 
	return 0;
}
  • game-engineer/classes/2022/game-programing-1/first-term/9/9-09-45.txt
  • 最終更新: 3年前
  • by root