Skip to content

Instantly share code, notes, and snippets.

@nna774
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nna774/9c56d23a1487472ba9f3 to your computer and use it in GitHub Desktop.
Save nna774/9c56d23a1487472ba9f3 to your computer and use it in GitHub Desktop.
某アレで書いたなんか これ(https://github.com/nna774/HCSVParser) とはかんけいないよ?
#include <iostream>
#include <vector>
#include <memory>
#include <queue>
class Node;
class Node{
public:
unsigned value;
std::vector<std::shared_ptr<Node>> children;
Node(unsigned val, std::vector<std::shared_ptr<Node>> vec = {}) : value(val), children(vec) {}
};
std::shared_ptr<Node> findDepth(std::shared_ptr<Node> node, unsigned val){
if(node->value == val) return node;
for(auto e: node->children) {
auto ptr = findDepth(e, val);
if(ptr) return ptr;
}
return nullptr;
}
std::shared_ptr<Node> findWidth(std::shared_ptr<Node> node, unsigned val){
std::queue<std::shared_ptr<Node>> que({node});
while(! que.empty()){
auto front = que.front();
que.pop();
if(front->value == val) return front;
for(auto e: front->children) que.push(e);
}
return nullptr;
}
///////////////////////////////////////////////
#include <set>
#include <random>
void grow_tree(std::shared_ptr<Node> node, std::set<unsigned>& set, int depth = 1){
double r = 1.0 - depth * 0.1;
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> rand(0.0,1.0);
if(rand(mt) > r) return;
unsigned u;
do { u = mt(); } while(set.find(u) != set.end());
set.insert(u);
node->children.push_back(std::make_shared<Node>(u));
for(auto e: node->children) grow_tree(e, set, depth + 1);
grow_tree(node, set, depth + 1);
}
void show_tree(std::shared_ptr<Node> node, int depth = 0){
for(int i(0); i < depth; ++i) std::cout << " ";
std::cout << node->value << std::endl;
for(auto e: node->children) {
show_tree(e, depth + 1);
}
}
int main(){
// Node root(0, { });
// Node root(0, { std::make_shared<Node>(42, {}) });
auto root = std::make_shared<Node>(0);
// for(int i(100); i<500; ++i) root->children.push_back(std::make_shared<Node>(i));
std::set<unsigned> set;
set.insert(0);
grow_tree(root, set);
show_tree(root);
std::cout << std::endl;
std::cout << findDepth(root, *set.rbegin())->value << std::endl;
std::cout << findWidth(root, *set.rbegin())->value << std::endl;
std::cout << findDepth(root, *set.begin())->value << std::endl;
std::cout << findWidth(root, *set.begin())->value << std::endl;
std::vector<unsigned> vec(set.begin(), set.end());
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> rand(0, vec.size() - 1);
std::cout << findDepth(root, vec[rand(mt)])->value << std::endl;
std::cout << findWidth(root, vec[rand(mt)])->value << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment