struct node * bst(int *arr, int begin, int end)
{


	if (begin > end)
		return NULL;
	/*
	calculate mid point.
	All the values to left of mid are less than mid.
	Similarly values to right of mid are less than mid
	we take mid as root and values < mid as left subtree
	and values > mid as right subtree
	
	*/

	/*
	If tree is not balanced AVL rotations can be applied
	*/

	int mid = (begin + end) / 2;

	struct node *root = (struct node*) malloc(sizeof(struct node));

	root->data = arr[mid];
	root->left = bst(arr, begin, mid - 1);
	root->right = bst(arr, mid + 1, end);

	return root;


}
예제 #2
0
int bst(long n1,long n2)
{
    if(!isBadVersion(n2-1)&&isBadVersion(n2))return n2;
    int l=(n1+n2)/2;
    if(!isBadVersion(l)&&isBadVersion(l+1))return l+1;
    else if(isBadVersion(l))return bst(n1,l);
    else return bst(l+1,n2);
}
 TreeNode* bst(vector<int>& nums, int low, int high) {
     if (low > high) return NULL;
     int mid = low +(high - low) / 2;
     TreeNode* cur = new TreeNode(nums[mid]);
     
     cur -> left = bst(nums, low, mid - 1) ;
     cur -> right = bst(nums, mid + 1, high);
     return cur;
 
 }
예제 #4
0
int bst(int low, int high)
{
  if(low<=high)
  {
    int m = (low + high)/2;
    if(f(m)>0 &&((m==low) || (f(m-1)<0)))
      return m;
    else if(f(m)>0)  return bst(low, m-1);
    else return bst(m+1,high);
  }
  return -1;
}
예제 #5
0
파일: 10821.cpp 프로젝트: dibery/UVa
void bst( int q, int h, int offset = 0 )
{
	if( !q )
		return;
	else if( q <= 1 << h-1 )
		printf( " %d", offset+1 ), bst( q-1, h-1, offset+1 );
	else
	{
		printf( " %d", q - ( 1 << h-1 ) + offset + 1 );
		bst( q - ( 1 << h-1 ), h-1, offset );
		bst( ( 1 << h-1 ) - 1, h-1, offset + q - ( 1 << h-1 ) + 1 );
	}
}
예제 #6
0
// BST 이진탐색트리 
// O(log2 n), 최악 : O(n)
int bst(int arr[], int target, int first, int last)
{
	int half = (last - first) / 2 + first;

	if (first > last)
		return -1;

	if (target == arr[half])
		return half;
	else if (target < arr[half])
		return bst(arr, target, first, half - 1);
	else
		return bst(arr, target, half + 1, last);
}
struct node* bst(int *arr, int start, int end)
{
	if (start > end)
		return NULL;
	int mid = (start + end) / 2;
	struct node *root;
	root = (struct node *)malloc(sizeof(struct node));
	root->data = arr[mid];
	root->left = NULL;
	root->right = NULL;
	root->left = bst(arr, start, mid - 1);
	root->right = bst(arr, mid + 1, end);
	return root;
}
예제 #8
0
		bool bst(TreeNode *n1, TreeNode *n2)
		{
			if(n1!=NULL && n2!=NULL)
			{
				if(n2->val==n1->val)
					return bst(n1->left,n2->right)&&bst(n1->right,n2->left);
				else
					return false;
			}
			else if(n1==NULL && n2==NULL)
				return true;
			else
				return false;
		}
예제 #9
0
void tree()
{
 int t,i;
do
{system("reset");
printf("\n   **************************************************************************                     ");
printf("\nWhat u want to do");
printf("\n1 for Simple tree\n2 for Binary Search tree\n3 for AVL\n0 to go back");
scanf("%d",&t);
switch(t)
{
 case 1:stree();
        break;
 case 2:bst();
        break;
 case 3:avl();
        break;
 case 0:goto xy;
default:
  printf("wrong choice entered");
  break;
}
printf("\npress 1 to continue with trees........");
scanf("%d",&i);

}while(i==1);
xy:;
}  
예제 #10
0
		bool isSymmetric(TreeNode *root) {
			// Start typing your C/C++ solution below
			// DO NOT write int main() function
			if(root==NULL)
				return true;
			return bst(root->left,root->right);
		}
예제 #11
0
int
bset_test(unsigned int in_cts, unsigned int out_cts, pm_random& rand_gen, unsigned int cycles)
{
   int ok = 0;

   int* ins = new int[in_cts+out_cts];
   int* outs = new int[in_cts+out_cts];

   bset bst(void_eq, void_ls);

   for ( int i=0; i<in_cts; i++ ) {
      ins[i] = i + 1;
      bst.insert((void*)ins[i]);
   }

   for ( i=0; i<out_cts; i++ ) {
      outs[i] = i + in_cts + 1;
   }

   for ( i=0; i<cycles; i++ ) {
      if ( rand_gen.rand_01() > 0.5 )
         ok |= in_bset_test(bst, ins, in_cts, outs, out_cts, rand_gen);
      else
         ok |= out_bset_test(bst, ins, in_cts, outs, out_cts, rand_gen);
   }

   delete ins; 
   delete outs; 

   return ok;
}
예제 #12
0
int main() {
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    BinarySearchTree bst(a, 10);
    bst.show();
    postTraversal(bst.getRoot());
    return 0;
}
예제 #13
0
파일: 10821.cpp 프로젝트: dibery/UVa
int main()
{
	int qnt, h, t = 0;

	while( scanf( "%d %d", &qnt, &h ) && qnt )
		if( qnt >= 1 << h )
			printf( "Case %d: Impossible.\n", ++t );
		else
			printf( "Case %d:", ++t ), bst( qnt, h ), puts( "" );
}
struct node * convert_array_to_bst(int *arr, int len){
	
	if (arr == NULL)
		return NULL;

	int begin = 0;
	int end = len;
	return bst(arr, begin, end);
	
	}
예제 #15
0
int main()
{
    string input{ "[1, 4, 10, -3, -1, null, 2]" };
    cout << "Input string: " << input << endl;
    
    //BST empty_bst;
    //create tree:
    BST bst(input);
    cout << "Print Tree: " << endl;
    TreeHelper::PrintTree(bst.getRoot());
}
예제 #16
0
int findFirstPositive()
{

  if(f(0)>0)  return 0;
  

  int  i=1;
   
  while(f(i) < 0) 
   i = i*2; 

  return bst(i/2,i);
}
예제 #17
0
void run_bst_file(const char *file)
{
    if (FALSE == check_file(file)) {
        exit(1);
    }

    ifstream fin(file);
    if (!fin.good()) {
        cerr << "read file: " << file << " failed.\n";
        exit(1);
    }
    Bst bst(fin);
    bst.build();
}
예제 #18
0
int main()
{
    int arr[] = {10, 20, 30, 40, 60, 80, 90};
    N *root = (N*)malloc(sizeof(N));
    int n = sizeof(arr) / sizeof(arr[0]), i;

    printf("Given sorted array is\n");
    for (i = 0;i < n;i++)
        printf("%d\t", arr[i]);
    root = bst(arr, 0, n - 1);
    printf("\n The preorder traversal of binary search tree is as follows\n");
    display(root);
    printf("\n");
    return 0;
}
예제 #19
0
파일: bst.c 프로젝트: kulv2012/algorithm
int main(int argc, char* argv[]) {

    printf("hello kulv\n");
    float probability[] = {0.24, 0.18, 0.09, 0.13, 0.3, 0.06 } ;
    int count = sizeof(probability) / sizeof(float) ;
    int root[count][count] ;
    float mincost = bst( probability, (int*)root, count) ;
    printf("min cost is:%f\n", mincost);
    for(int i=0; i< count; ++i){
        for(int j=0; j< count; ++j ){
            if( j< i) printf("\t");
            else printf("%d\t", root[i][j]);
        }
        printf("\n");
    }
}
예제 #20
0
void Scene::renderGameStatistics()
{
	// Show intro
	if( m_fTimer < 3.0f )
	{
		scene->renderFont( 255, 0, 255, 0, 3.0f, GAME_WIDTH / 2.0f, 30.0f, HGETEXT_CENTER, "-=SURVIVAL=-" ); 
	}

	// Show statistics
	std::string atp( "attempts: " );
	atp += std::to_string( attempts ); 
	renderFont( 255, 128, 128, 128, 1.0f, GAME_WIDTH - 140.0f, 10.0f, HGETEXT_LEFT, atp );

	std::string str( "health: ");
	int health = static_cast<int>( objects->getTank( )->getHealth( ) * 100 );
	str += std::to_string( health ); 
	renderFont( 255, 128, 128, 128, 1.0f, GAME_WIDTH - 140.0f, 40.0f, HGETEXT_LEFT, str );

	std::string timer( "timer: "); 
	timer += std::to_string( static_cast<int>(SURVIVAL_TIME) - static_cast<int>(m_fTimer) );
	timer += "s";
	renderFont( 255, 128, 128, 128, 1.0f, GAME_WIDTH - 140.0f, 70.0f, HGETEXT_LEFT, timer );

	std::string bst( "beasts: ") ;
	bst += std::to_string( objects->getDeadBeastQuantity( ) ); 
	renderFont( 255, 128, 128, 128, 1.0f, 10.0f, 10.0f, HGETEXT_LEFT, bst );

	std::string dmn( "daemons: ");
	dmn += std::to_string( objects->getDeadDaemonQuantity( ) ); 
	renderFont( 255, 128, 128, 128, 1.0f, 10.0f, 40.0f, HGETEXT_LEFT, dmn );

	std::string rpt( "reptiles: "); 
	rpt += std::to_string( objects->getDeadReptileQuantity( ) );
	renderFont( 255, 128, 128, 128, 1.0f, 10.0f, 70.0f, HGETEXT_LEFT, rpt );

	std::string blt( "bullets: ");
	blt += std::to_string( Weapon::getBulletsQuantity( ) );
	renderFont( 255, 128, 128, 128, 1.0f, 10.0f, GAME_HEIGHT - 90.0f, HGETEXT_LEFT, blt );

	std::string shl( "shells: ");
	shl += std::to_string( Weapon::getShellsQuantity( ) );
	renderFont( 255, 128, 128, 128, 1.0f, 10.0f, GAME_HEIGHT - 60.0f, HGETEXT_LEFT, shl );

	std::string rct( "rockets: ");
	rct += std::to_string( Weapon::getRocketsQuantity( ) );
	renderFont( 255, 128, 128, 128, 1.0f, 10.0f, GAME_HEIGHT - 30.0f, HGETEXT_LEFT, rct );
}
예제 #21
0
void run_bst_del(char *file, std::vector<char *> & strvec)
{
    if (FALSE == check_file(file)) {
        exit(1);
    }

    ifstream fin(file);
    if (!fin.good()) {
        cerr << "read file: " << file << " failed.\n";
        exit(1);
    }
    Bst bst(fin);
    bst.build();

    for (size_t i=0; i< strvec.size(); i++) {
        cout << "\nDeleted \""<< strvec[i] << "\":\n\n";
        bst.del(strvec[i]);
        bst.display();
    }
}
예제 #22
0
int main()
{
	int n, nCount;
	int i;

	scanf("%d", &nCount);

	int a_count;
	int b_count;
	int target;

	for (n = 0; n < nCount; n++)
	{

		// input
		scanf("%d", &a_count);

		for (i = 0; i < a_count; i++)
		{
			scanf("%d", &a[i]);
		}

		q_sort(a, 0, a_count - 1); // quick sort

		scanf("%d", &b_count);
		for (i = 0; i < b_count; i++)
		{
			scanf("%d", &target);

			if (bst(a, target, 0, a_count - 1) != -1) // binary search 
				printf("1");
			else
				printf("0");

			printf("\n");
		}
	}
	return 0;
}
예제 #23
0
int firstBadVersion(int n) {
    if(n==0)return 0;
    return bst(1,n);
}
예제 #24
0
void run_bst_stdin()
{
    Bst bst(cin);
    bst.build();
}
int main() {
  std::cout << "LUL" << std::endl;
    {
        BST<int> bst({3});
        // 3
    }

    {
        BST<int> bst({3, 4});
        // 3    |
        //  \   |
        //   4  |
    }

    {
        BST<int> bst({3, 4, 1});
        //   3    |
        //  / \   |
        // 1   4  |
    }

    {
        BST<int> bst({3, 4, 1, 2});
        //    3    |
        //   / \   |
        //  1   4  |
        //   \     |
        //    2    |
    }
    {
        BST<int> bst({3,4,1,2,7});
        //    3      |
        //   / \     |
        //  1   4    |
        //   \   \   |
        //    2   7  |
        std::cout << bst << std::endl;
        std::cout << bst.height() << std::endl;
    }
/*
    BST<int> bst({3,4,1,2,7,3});
    //    3          |
    //   / \         |
    //  1   4        |
    //   \   \       |
    //    2   7      |
    //     \         |
    //      3        |
    //  
    //  */

    std::vector<int> temp;
    int sign = 1;

    for (int i = 0; i < 1000; ++i) {
      sign *= -1;
      temp.push_back(i * sign);
    }

    BST<int> bst(temp.begin(), temp.end());
    

    std::cout << bst << std::endl; // prints 1 2 3 3 4 7
    std::cout << bst.size() << std::endl; //prints 6
    std::cout << bst.min() << std::endl; // prints 1
    std::cout << bst.max() << std::endl; // prints 7
    std::cout << bst.height() << std::endl; // prints 4
    std::cout << spine(bst).height() << std::endl; // prints 6
    std::cout << spine(bst) << std::endl;
    std::cout << "FIND 4 : " << bst.find(4) << std::endl; // prints 4 7
    std::cout << "FIND 11 : " << bst.find(11) << std::endl; //prints nothing (possibly one space)
    std::cout << max_diff(bst) << std::endl; //prints 3

    return 0;
}
struct node * convert_array_to_bst(int *arr, int len){
	if ((arr == NULL) || (len <= 0))
		return NULL;
	return bst(arr, 0, len);
}
 TreeNode* sortedArrayToBST(vector<int>& nums) {
     return bst(nums,0,nums.size()-1); 
 }
예제 #28
0
파일: mines.cpp 프로젝트: jokoon/eio
//map<color, Color> colors = {
//    { Black, Color::Black },
//    { White, Color::White },
//    { Red, Color::Red },
//    { Green, Color::Green },
//    { Blue, Color::Blue },
//    { Yellow, Color::Yellow },
//    { Magenta, Color::Magenta },
//    { Cyan, Color::Cyan },
//    { Transparent, Color::Transparent },
//    { Orange, Color(255, 128, 0) }
//};
////////////////////////// this returns a lambda //////////////////////////
function<void()>
////////////////////////// TYPE APP NAME ON LINE BELOW //////////////////////////
mine_solver

(RenderWindow&window, ui &UI) {
    return [&window, &UI]() {
#ifndef COMMON_INITS
        //void smoothmouse(RenderWindow&window, ui &UI){

        // tidy code organization, here we predeclare methods just like a header would, it's redundant but necessary
        function<void()> draw, loop, init, update;
        function<void(Vec2 pos)> mousemoved;
        function<void(sf::Mouse::Button button)> mouseclick, mouserelease;
        function<void(Event&e)> treatotherevent;
        function<void(Keyboard::Key k)> treatkeyevent;

        // we don't have a class/interface/struct with data, everything is local to this function, like a classic stack that all programs are anyway.
        Texture cursor_tx;
        Sprite cursor;
        configfile cfg;
        cfg.init("bedlab.cfg");
        Color background = cfg.getvar<Color>("background");
        if (!cursor_tx.loadFromFile(cfg.getstr("cursor")))
            cout << "did not load cursor" << endl;
        cursor.setTexture(cursor_tx);
        cursor.setOrigin(3, 3);
        window.setMouseCursorVisible(false);
        Vec2 mpos;
        bool leftclicked = false, rightclicked = false;

        // view and zoom
        View view, ui_view;
        ui_view = view = window.getDefaultView();
        float zoomlevel = 1;
        Vec2 mpos_abs;
#endif // COMMON_INITS
        // ************************ CODE BEGIN ************************

        barstack bst(FONT, FONTSIZE);
        slider_finder sl;


        randgenfloat cell_rnd(0, 16);
        //grd.
        vector<string> mines_str =
        {
            "               ",
            "   21114X411   ",
            "   3X22XX212   ",
            "   X3--4433X   ",
            "   23--4XX3X   ",
            "   1X4---433   ",
            "   12X4--4X2   ",
            "   123X3XX3X   ",
            "   2X2122221   ",
            "               "

        };

        int w = mines_str[0].length();
        int h = mines_str.size();
        vector<int> mine_states(h*w);
        grid grd;
        grd.screen_init(Vec2u(window.getSize()), Vec2u( w,h ), true);


        /*
        1-8: surrounding mines
        0 no mine, "clear"
        -1: unknown
        -2 mine
        
        */
        map<char, int> lookup =
        {
            { '-',-1 },
            { 'X',-2 },
            { ' ',0 }
        };


        int i = 0;
        logfile lg("minelog.txt");
        lg.logw(to_str("i", "j", "index", "value"));

        for (auto&a : mines_str)
        {
            int j = 0;
            for (auto&b : a)
            {
                int value = -10;

                //value =
                //    lookup.count(b) ?
                //    lookup[b]
                //    : (b > '0' || b <= '9') ?
                //        int(b - '0')
                //        : value;
                //msg(value);
                if (lookup.count(b)) value = lookup[b];
                else if (b > '0' || b <= '9')value = int(b - '0');

                int index = getat(j, i, w);
                mine_states[index] = value;

                //msgm(i,j,index, value);
                lg.logw(to_str(i,j,index, value));
                ++j;
            }
            ++i;
        }

        map<int, Color> mine_colors =
        {
            { -2,Color::Red },
            { -1,Color::Cyan },
            { 0,Color::Black }

        };
        msg(mine_states);
        i = 0;
        for (auto&a : mine_states)
        {
            if(a > 0)
                grd.texts[i].setString(to_str(a));
            else
                grd.cells[i].setFillColor(mine_colors[a]);
            //grd.texts2[i].setString(to_str(i));
            //grd.texts3[i].setString(to_str(getat(i,w)));
            ++i;
        }

        auto analyse = [&mine_states, w, h, &grd]()
        {
            vector<Vec2i> offsets = {
                { -1,-1 },
                { 1,-1 },
                { -1,1 },
                { 1,1 },
                { 0,-1 },
                { -1,0 },
                { 0,1 },
                { 1,0 }
            };

            int i = 0;
            for (auto&a : mine_states)
            {
                auto pos = getat(i, w);
                int unknown = 0, is_mine = 0;
                for (auto&off : offsets)
                {
                    auto cell = pos + off;
                    int cell_index = getat(cell,w);
                    if (cell_index < 0
                        || cell_index >= mine_states.size()
                        || cell.x < 0
                        || cell.x > w) continue;
                    switch (mine_states[cell_index])
                    {
                        case -1: ++is_mine; break; //unknown
                        case -2: ++unknown; break; //mine
                    }
                }
                int mine_left = a - is_mine;
                float prob = mine_left / unknown;
                ++i;
            }
        };
        
        auto nearest_pt = mkcircle({ 0, 0 }, Color::Transparent, 10);
        nearest_pt.setOutlineThickness(2);
        // ************************ INITS END **********************
        //then we actually define the functions, note how all function captures the local context by reference
#ifndef LOOP_LAMBDAS
        draw = [&]() {
            window.setView(view);
            // object draw, AFTER normal view

            //////////////// obj draw START ////////////////
            for (auto&a : glob_pts)window.draw(a);
            for (auto&a : glob_rects)window.draw(a);
            for (auto&a : glob_vert)window.draw(a);
            for (auto&a : glob_texts)window.draw(a);
            window.draw(nearest_pt);
            grd.draw(window);


            //////////////// obj draw END ////////////////
            // UI draw, AFTER ui view and BEFORE other draw
            window.setView(ui_view);
            bst.draw(window);
            // nothing after here please
            UI.draw(window);
            window.draw(cursor);
        };
        update = [&]() {

        };
        treatkeyevent = [&](Keyboard::Key k) {
            switch (k)
            {
            case Keyboard::BackSpace:
                glob_pts.clear();
                glob_texts.clear();
                glob_rects.clear();
                glob_vert.clear();
                break;
            case Keyboard::Space:

                break;
            case Keyboard::Q: break;
            }
        };
        mousemoved = [&](Vec2 pos) {
            cursor.setPosition(pos);
            if (leftclicked) sl.mouse_callback(pos);
        };
        mouseclick = [&](sf::Mouse::Button button) {
            if (button == Mouse::Button::Left) leftclicked = true;
            if (button == Mouse::Button::Right) rightclicked = true;
        };
        mouserelease = [&](sf::Mouse::Button button) {
            if (button == Mouse::Button::Left) leftclicked = false;
            if (button == Mouse::Button::Right) rightclicked = false;
            sl.release();
        };
        loop = [&]() {
            while (window.isOpen())
            {
                sf::Event event;
                while (window.pollEvent(event))
                {
                    switch (event.type)
                    {
                    case sf::Event::KeyPressed:
                        if (event.key.code == sf::Keyboard::Escape)
                            window.close();
                        treatkeyevent(event.key.code);
                        break;
                    case sf::Event::Closed:
                        window.close();
                        break;
                    case sf::Event::MouseButtonPressed:
                        mouseclick(event.mouseButton.button);
                        break;
                    case sf::Event::MouseButtonReleased:
                        mouserelease(event.mouseButton.button);
                        break;
                    case sf::Event::MouseMoved:
                        mpos = Vec2(event.mouseMove.x, event.mouseMove.y);
                        mousemoved(mpos);
                        break;
                    default:
                        treatotherevent(event);
                        break;
                    }
                }

                window.clear(background);
                update();
                draw();
                window.display();
            }
        };
        treatotherevent = [&](Event&e) {
            if (e.type == Event::MouseWheelMoved && e.mouseWheel.delta)
            {
                mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view);

                //view = window.getView();
                if (e.mouseWheel.delta < 0)
                {
                    zoomlevel *= 2.f;
                    view.setSize(view.getSize()*2.f);
                    view.setCenter(interp(mpos_abs, view.getCenter(), 2.f));
                    //view.setCenter(interp(mpos_abs, view.getCenter(), 2.f));
                }
                if (e.mouseWheel.delta > 0)
                {
                    zoomlevel *= 0.5;
                    view.setSize(view.getSize()*.5f);
                    view.setCenter(.5f*(view.getCenter() + mpos_abs));
                    //view.setCenter(.5f*(view.getCenter() + mpos_abs));
                }
                window.setView(view);
            }
        };
        loop();
#endif // LOOP_LAMBDAS
    };
}
예제 #29
0
파일: agenda.cpp 프로젝트: VadimDez/Agenda
void calendar::inserimentoBST()
{   /* Controlla se c'e' un evento cancellato nel file BST se c'e' prende quella posizione
     * se non c'e' prende quella in fondo del file.Poi controlla se e' primo o no
     * se primo evento del file lo aggiunge e basta, se non e' il primo, scorre
     * usando SX o DX trovando un posto vuoto.*/
    ofstream bst("bst.txt",ios::binary | ios::in | ios::out);
    albero lettura; //struct per caricare data dal bst;
    bool trovato = false;
    bool primoEvento = true;
    int posizione; // posizione dentro il file del BST
    ifstream readbst("bst.txt",ios_base::app | ios_base::binary);
    readbst.seekg(0,ios_base::beg);
    while(!readbst.eof() && trovato==false) // con questo ciclo trovo se c'e' un evento cancellato per recuperare lo spazio
    {
        readbst.clear();
        readbst.read((char*)&lettura,sizeAlbero);
        if(!readbst.eof()) // perche' c'e' il problema che viene letto 2 volte ultimo elem
        {
            readbst.clear();
            primoEvento = false;
            if(lettura.cancellato)
            {
                trovato = true;
                posizione = (readbst.tellg()/sizeAlbero);
            }
        }
    }
    if(trovato) // se trova evento cancellato salva - la posizione in una variabile, altrimenti salva alla fine del file
    {
        bst.seekp(posizione*(sizeAlbero),ios_base::beg);
    }
    else
    {
        bst.seekp(0,ios_base::end);
        posizione = (bst.tellp()/sizeAlbero);
    }
    bst.write((const char*)&albero1,sizeAlbero); // salva nel file
    if(!primoEvento)
    {
        int puntatorePosizione(0);
        trovato = false;
        while(trovato == false)
        {
            readbst.clear(); // cancella gli errori;
            readbst.seekg((puntatorePosizione*sizeAlbero),ios::beg);
            readbst.read((char*)&lettura,sizeAlbero);
            if(!lettura.cancellato) // serve per il primo elemento
            {
                if(confronto(lettura) > 0)
                { // a destra
                    if(lettura.dx != -1)
                    {
                        puntatorePosizione = lettura.dx;
                    }
                    else
                    {
                        lettura.dx = posizione;
                        trovato = true;
                    }
                }
                else
                { // a sinistra
                    if(lettura.sx != -1)
                    {
                        puntatorePosizione = lettura.sx;
                    }
                    else
                    {
                        lettura.sx = posizione;
                        trovato = true;
                    }
                }
            }
            else
            {
                trovato = true;
            }
        }
        readbst.close();
        bst.seekp((puntatorePosizione)*sizeAlbero,ios_base::beg);
        bst.write((const char*)&lettura,sizeAlbero);
        bst.close();
    }
}
예제 #30
0
파일: delaun-distr.cpp 프로젝트: jokoon/eio
function<void()>
////////////////////////// TYPE APP NAME ON LINE BELOW //////////////////////////
delaun_distr

(RenderWindow&window, ui &UI) {
	return [&window, &UI]() {
#ifndef COMMON_INITS
		//void smoothmouse(RenderWindow&window, ui &UI){

		// tidy code organization, here we predeclare methods just like a header would, it's redundant but necessary
		function<void()> draw, loop, init, update;
		function<void(Vec2 pos)> mousemoved;
		function<void(sf::Mouse::Button button)> mouseclick, mouserelease;
		function<void(Event&e)> treatotherevent;
		function<void(Keyboard::Key k)> treatkeyevent;

		// we don't have a class/interface/struct with data, everything is local to this function, like a classic stack that all programs are anyway.
		Texture cursor_tx;
		Sprite cursor;
		configfile cfg;
		cfg.init("bedlab.cfg");
		Color background = cfg.getvar<Color>("background");
		if (!cursor_tx.loadFromFile(cfg.getstr("cursor")))
			cout << "did not load cursor" << endl;
		cursor.setTexture(cursor_tx);
		cursor.setOrigin(3, 3);
		window.setMouseCursorVisible(false);
		Vec2 mpos;
		bool leftclicked = false, rightclicked = false;

		// view and zoom
		View view, ui_view;
		ui_view = view = window.getDefaultView();
		float zoomlevel = 1;
		Vec2 mpos_abs;
#endif // COMMON_INITS
		// ************************ CODE BEGIN ************************
		
		auto random_graph = [](int pick_count, float distrib_radius)
		{
			vector<pair<int,Vec2>> points;
			vector<pair<int, int>> graph;
			

			//float distrib_radius;// = cfg.getvar<float>("distrib_radius");

			paused_distr paus_distr(distrib_radius, 5, 321);
			//int winheight = cfg.getvar<Vec2i>("windowsize").y;
			//scaler scl(winheight*0.9f, { 0,0 });

			DelaunayTriangulation dela(1, 1);

			//int pick_count = cfg.getvar<int>("pick_count");
			for (int i = 0; i < pick_count; ++i)
			{
				Vec2 cand;
				int retcode = -1;
				do
				{
					retcode = paus_distr.pick5(cand);
				} while (retcode == 2);
				if (retcode != -1 && retcode != 0)
				{
					dela.AddPoint(Point(cand.x, cand.y));
					//glob_pts.push_back(mkcircle(scl(cand), Color::White, .5f));
					//glob_pts.push_back(mkcircle(scl(cand), Color::White, 3.f));
					points.push_back({ points.size(),cand });
				}

			}
			//msg(glob_pts.size());
			for (auto&triangle : dela.triangles)
			{
				int
					a = triangle.get()->v[0],
					b = triangle.get()->v[1],
					c = triangle.get()->v[2];
				Point
					A = dela.points[a],
					B = dela.points[b],
					C = dela.points[c];
				if (
					A.x == 0 || A.x == 1
					|| A.y == 0 || A.y == 1
					|| B.x == 0 || B.x == 1
					|| B.y == 0 || B.y == 1
					|| C.x == 0 || C.x == 1
					|| C.y == 0 || C.y == 1
					)
				{
					continue;
				}

				graph.push_back({a,b});
				graph.push_back({b,c});
				graph.push_back({a,c});

				// those are the ones!
				//segment(scl(Vec2(A.x, A.y)), scl(Vec2(B.x, B.y)));
				//segment(scl(Vec2(C.x, C.y)), scl(Vec2(B.x, B.y)));
				//segment(scl(Vec2(A.x, A.y)), scl(Vec2(C.x, C.y)));

				//segment(Vec2(A.x, A.y), Vec2(B.x, B.y));
				//segment(Vec2(C.x, C.y), Vec2(B.x, B.y));
				//segment(Vec2(A.x, A.y), Vec2(C.x, C.y));
				//segment(pts[a], pts[b]);
				//segment(pts[a], pts[c]);
				//segment(pts[c], pts[b]);
			}
			return make_pair(points, graph);
		};


		float distrib_radius = cfg.getvar<float>("distrib_radius");

		paused_distr paus_distr(distrib_radius, 5, 321);
		int winheight = cfg.getvar<Vec2i>("windowsize").y;
		scaler scl(winheight*0.9f, { 0,0 });

		DelaunayTriangulation dela(1, 1);

		int pick_count = cfg.getvar<int>("pick_count");
		for(int i = 0; i < pick_count; ++i)
		{ 
			Vec2 cand;
			int retcode = -1;
			do
			{
				retcode = paus_distr.pick5(cand);
			} while (retcode == 2);
			if (retcode != -1 && retcode != 0)
			{
				dela.AddPoint(Point(cand.x, cand.y));

				//glob_pts.push_back(mkcircle(scl(cand), Color::White, .5f));
				glob_pts.push_back(mkcircle(scl(cand), Color::White, 3.f));
			}

		}
        msg(glob_pts.size());
		for (auto&triangle : dela.triangles)
		{
			int
				a = triangle.get()->v[0],
				b = triangle.get()->v[1],
				c = triangle.get()->v[2];
			Point
				A = dela.points[a],
				B = dela.points[b],
				C = dela.points[c];
			if (
				A.x == 0 || A.x == 1
				|| A.y == 0 || A.y == 1
				|| B.x == 0 || B.x == 1
				|| B.y == 0 || B.y == 1
				|| C.x == 0 || C.x == 1
				|| C.y == 0 || C.y == 1
				) 
			{
				continue;
			}
			
			segment(scl(Vec2(A.x, A.y)), scl(Vec2(B.x, B.y)));
			segment(scl(Vec2(C.x, C.y)), scl(Vec2(B.x, B.y)));
			segment(scl(Vec2(A.x, A.y)), scl(Vec2(C.x, C.y)));
			//segment(Vec2(A.x, A.y), Vec2(B.x, B.y));
			//segment(Vec2(C.x, C.y), Vec2(B.x, B.y));
			//segment(Vec2(A.x, A.y), Vec2(C.x, C.y));
			//segment(pts[a], pts[b]);
			//segment(pts[a], pts[c]);
			//segment(pts[c], pts[b]);
		}

		barstack bst(FONT, FONTSIZE);
		slider_finder sl;
		size_t edit_mode = 1;

		// ************************ INITS END ************************
		//then we actually define the functions, note how all function captures the local context by reference
#ifndef LOOP_LAMBDAS
		draw = [&]() {
			window.setView(view);
			// object draw, AFTER normal view

			//Vec2 cand;
			//int retcode = -1;
			//do
			//{
			//	retcode = paus_distr.pick4(cand);
			//} while (retcode == 2);
			//if (retcode != -1 && retcode != 0)
			//{
			//	//glob_pts.push_back(mkcircle(scl(cand), Color::White, .5f));
			//	glob_pts.push_back(mkcircle(scl(cand), Color::White, .5f));
			//}


			//////////////// obj draw START ////////////////
			for (auto&a : glob_pts)window.draw(a);
			for (auto&a : glob_rects)window.draw(a);
			for (auto&a : glob_vert)window.draw(a);
			for (auto&a : glob_texts)window.draw(a);
			//window.draw(nearest_pt);

			//////////////// obj draw END ////////////////
			// UI draw, AFTER ui view and BEFORE other draw
			window.setView(ui_view);
			bst.draw(window);
			// nothing after here please
			UI.draw(window);
			window.draw(cursor);
		};
		update = [&]() {

		};
		treatkeyevent = [&](Keyboard::Key k) {
			switch (k)
			{
			case Keyboard::BackSpace:
				glob_pts.clear();
				glob_texts.clear();
				glob_rects.clear();
				glob_vert.clear();
				break;
			case Keyboard::Space:

				break;
			case Keyboard::Q: break;
			}
		};
		mousemoved = [&](Vec2 pos) {
			cursor.setPosition(pos);
			if (leftclicked) sl.mouse_callback(pos);
		};
		mouseclick = [&](sf::Mouse::Button button) {
			if (button == Mouse::Button::Left) leftclicked = true;
			if (button == Mouse::Button::Right) rightclicked = true;
		};
		mouserelease = [&](sf::Mouse::Button button) {
			if (button == Mouse::Button::Left) leftclicked = false;
			if (button == Mouse::Button::Right) rightclicked = false;
			sl.release();
		};
		loop = [&]() {
			while (window.isOpen())
			{
				sf::Event event;
				while (window.pollEvent(event))
				{
					switch (event.type)
					{
					case sf::Event::KeyPressed:
						if (event.key.code == sf::Keyboard::Escape)
							window.close();
						treatkeyevent(event.key.code);
						break;
					case sf::Event::Closed:
						window.close();
						break;
					case sf::Event::MouseButtonPressed:
						mouseclick(event.mouseButton.button);
						break;
					case sf::Event::MouseButtonReleased:
						mouserelease(event.mouseButton.button);
						break;
					case sf::Event::MouseMoved:
						mpos = Vec2(event.mouseMove.x, event.mouseMove.y);
						mousemoved(mpos);
						break;
					default:
						treatotherevent(event);
						break;
					}
				}

				window.clear(background);
				update();
				draw();
				window.display();
			}
		};
		treatotherevent = [&](Event&e) {
			if (e.type == Event::MouseWheelMoved && e.mouseWheel.delta)
			{
				mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view);

				//view = window.getView();
				if (e.mouseWheel.delta < 0)
				{
					zoomlevel *= 2.f;
					view.setSize(view.getSize()*2.f);
					view.setCenter(interp(mpos_abs, view.getCenter(), 2.f));
					//view.setCenter(interp(mpos_abs, view.getCenter(), 2.f));
				}
				if (e.mouseWheel.delta > 0)
				{
					zoomlevel *= 0.5;
					view.setSize(view.getSize()*.5f);
					view.setCenter(.5f*(view.getCenter() + mpos_abs));
					//view.setCenter(.5f*(view.getCenter() + mpos_abs));
				}
				window.setView(view);
			}
		};
		loop();
#endif // LOOP_LAMBDAS
	};
}