示例#1
0
文件: 2261.c 项目: sdmo0/acmicpc
int find_closest(int start, int end)
{
    int n = end - start + 1;
    if (n <= 3)return find_in_total(start, end);

    int mid = (start + end) / 2;
    int min = find_closest(start, mid);
    int d = find_closest(mid + 1, end);

    min = MIN(min, d);

#if (DEBUG >= 2)
    printf("start=%d, end=%d\n", start, end);
#endif //DEBUG
    int i, j;

    i = mid - 1;
    int idx = 0;
    while (DIST_X(point[i], point[mid]) <= min && i >= start) {
        temp_point[idx++] = point[i];
        i--;
    }

    i = mid + 1;
    while (DIST_X(point[i], point[mid]) <= min && i <= end) {
        temp_point[idx++] = point[i];
        i++;
    }        

    idx--;
    quicksort(temp_point, 0, idx, BASE_Y);

    for (i = 0; i <= idx - 1; i++) {
        for (j = i + 1; j <= idx; j++) {
            d = DIST_Y(temp_point[i], temp_point[j]);
            if (d < min) {
                d += DIST_X(temp_point[i], temp_point[j]);
                min = MIN(min, d);

#if (DEBUG >= 1)
                printf("i=%d, j=%d, (%d, %d) - (%d, %d) = %d\n",
                       i, j, temp_point[i].x, temp_point[i].y, temp_point[j].x, temp_point[j].y, min);
#endif //DEBUG

            } else {
                break;
            }
        }
    }

    return min;
}
示例#2
0
t_color		compute_light(t_scene *scene, t_ray *ray)
{
	t_list	*current;
	t_ray	lray;
	t_color	color[3];
	t_phpa	ph;

	current = scene->lights;
	ph.normal = get_normal(*ray);
	set_ambiant_light(&ph, scene, ray, color);
	while (current)
	{
		lray.pos = ((t_light *)current->content)->pos;
		lray.dir = norm_vect(mtx_add(mtx_sub(mtx_mult(ray->dir, ray->t),
			lray.pos), ray->pos));
		lray.invdir = get_inv_vect(&lray.dir);
		if (find_closest(scene, &lray) && ray->closest == lray.closest
			&& near_enough(ray, &lray))
		{
			set_params(&ph, &lray, ray);
			ph.camera = scene->camera;
			ph.light = (t_light *)current->content;
			phong(&ph);
		}
		current = current->next;
	}
	set_color_max(&ph);
	return (*color);
}
示例#3
0
	void Peer::build_routing_table()
	{
		int const uuidSpace = sizeof(SylUtil::Uuid) * 8; //128-bit uuid space

		SylUtil::Uuid upperLimit;

		for (int i = 0; i < uuidSpace; ++i)
		{
			upperLimit.setBit(i);

			SylUtil::Uuid distance;
			distance.setBit(i);

			SylUtil::Uuid closest;
			SylUtil::Uuid closest_distance;
			find_closest(m_uuid, distance, upperLimit, closest, closest_distance);

			if (closest != m_uuid)
			{
				SylNet::Connection c = m_routingTable.at(closest);
				m_handler.find_closest(distance, c);
			}

			find_closest_inverse(m_uuid, distance, closest, closest_distance);

			if (closest != m_uuid)
			{
				SylNet::Connection c = m_routingTable.at(closest);
				m_handler.try_join(distance, c); //Update the routing tables of other nodes in the overlay
			}
		}

		m_routingTable.clear();
	}
示例#4
0
void compute_cluster_centers(Dataset* dataset, Centroid** centroids){
//    Datapoint* random_point = dataset->points[rand() % dataset->size];
    for (size_t i = 0; i < dataset->size; i++) {
        Centroid* closest_centroid = find_closest(centroids, dataset->points[i]);
        update_center(dataset, closest_centroid);
    }
    scramble_dataset(dataset);
}
示例#5
0
font
smart_font_rep::get_math_font (string fam, string var, string ser, string sh) {
  find_closest (fam, var, ser, sh);
  string mvar= "mr";
  if (var == "ss") mvar= "ms";
  if (var == "tt") mvar= "mt";
  return find_font (fam, mvar, ser, "", sz, dpi);
}
int main(int argc, char *argv[]) {

    clock_t seq_clk = clock();

    int numberOfTrainingPictures = atoi(argv[1]);

    int ***trainingSet = (int ***)malloc(sizeof(int **) * NUM_PEOPLE);

    for (int i=0; i<NUM_PEOPLE; i++) {
        trainingSet[i] = alloc_2d_matrix(numberOfTrainingPictures, MAX_DECIMAL_VALUE);
    }
    //trainingSet is a 3d matrix now (person x image x histogramIndex )

    double seq_time = clock() - seq_clk;

    double parallel_clk = omp_get_wtime();

    #pragma omp parallel
    {
        #pragma omp for
        for (int i=0; i<NUM_PEOPLE; i++) {
            char filename[256];
            for (int j=0; j<numberOfTrainingPictures; j++) {
                sprintf(filename, "images/%d.%d.txt", i+1, j+1);
                int **image = read_pgm_file(filename, IMAGE_R, IMAGE_R);
                create_histogram(trainingSet[i][j], image, IMAGE_R, IMAGE_W);
                free(image);
            }
        }
    }

    int correct_answers = 0;
    #pragma omp parallel
    {
        #pragma omp for reduction(+:correct_answers)
        for (int i=0; i<NUM_PEOPLE; i++) {
            for (int j=numberOfTrainingPictures; j<NUM_PICS_PER_PERSON; j++) {
                int *test_histogram = (int *)malloc(sizeof(int) * MAX_DECIMAL_VALUE);
                char filename[256];
                sprintf(filename, "images/%d.%d.txt", i+1, j+1);
                int **image = read_pgm_file(filename, IMAGE_R, IMAGE_R);
                create_histogram(test_histogram, image, IMAGE_R, IMAGE_W);

                int predicted = find_closest(trainingSet, NUM_PEOPLE, numberOfTrainingPictures, MAX_DECIMAL_VALUE, test_histogram) + 1;

                printf("%s %d %d\n", filename+7, predicted, i+1);
                if(i+1 == predicted) {
                    correct_answers++;
                }
            }
        }
    }
    printf("Accuracy: %d correct answers for %d tests\n", correct_answers, NUM_PEOPLE * (NUM_PICS_PER_PERSON - numberOfTrainingPictures));
    printf("Parallel time: %lf\n", omp_get_wtime() - parallel_clk);
    printf("Sequential time: %lf\n", seq_time/CLOCKS_PER_SEC);
    return 0;
}
示例#7
0
CompactFrameID
TimeCache::get_parent(fawkes::Time time, std::string* error_str)
{
  TransformStorage* p_temp_1 = NULL;
  TransformStorage* p_temp_2 = NULL;

  int num_nodes = find_closest(p_temp_1, p_temp_2, time, error_str);
  if (num_nodes == 0) {
    return 0;
  }

  return p_temp_1->frame_id;
}
示例#8
0
void StatusStructure::remove_line(EndEvent* event, EventStructure& event_structure) {
    auto deletion_position(find_closest(event->get_l()));
    auto intersection(Point3D(0.f, 0.f, -1.f));

    if (deletion_position > lines_.begin() && deletion_position < lines_.end()-1) {
        intersection = (*(deletion_position - 1))->intersects(**(deletion_position+1));
        if (intersection.get_z() != -1.f && intersection.get_y() > event->get_position().get_y())
            event_structure.add_event(new IntersectionEvent(intersection, *(deletion_position - 1), *(deletion_position+1)));
    }

    lines_.erase(deletion_position);

}
示例#9
0
void StatusStructure::swap(IntersectionEvent* event, EventStructure& event_structure) {
    auto swap_left(find_closest(event->get_l1()));
    auto swap_right(find_closest(event->get_l2()));
    auto intersection_right(Point3D(0.f, 0.f, -1.f));
    auto intersection_left(Point3D(0.f, 0.f, -1.f));

    if (swap_right < lines_.end() - 1) {
        intersection_right = event->get_l1()->intersects(**(swap_right + 1));
        if (intersection_right.get_z() != -1.f && intersection_right.get_y() >= event->get_position().get_y())
            event_structure.add_event(new IntersectionEvent(intersection_right, event->get_l1(), *(swap_right + 1)));
    }

    if (swap_left > lines_.begin()) {
        intersection_left = event->get_l2()->intersects(**(swap_left - 1));
        if (intersection_left.get_z() != -1.f && intersection_left.get_y() >= event->get_position().get_y())
            event_structure.add_event(new IntersectionEvent(intersection_left, *(swap_left - 1), event->get_l2()));
    }

    auto tmp = *swap_left;
    *swap_left = *swap_right;
    *swap_right = tmp;
}
示例#10
0
文件: 2261.c 项目: sdmo0/acmicpc
int main(void)
{
    int N;
    scanf("%d", &N);

    int i;
    for (i = 0; i < N; i++)
        scanf("%d %d", &(point[i].x), &(point[i].y));

    quicksort(point, 0, N - 1, BASE_X);

#if (DEBUG >= 1)
    for (i = 0; i < N; i++)
        printf("%d ==> (%d, %d)\n", i, point[i].x, point[i].y);
#endif //DEBUG

    printf("%d\n", find_closest(0, N - 1));

    return 0;
}
示例#11
0
bool
TimeCache::get_data(fawkes::Time time, TransformStorage & data_out,
                    std::string* error_str)
{
  TransformStorage* p_temp_1 = NULL;
  TransformStorage* p_temp_2 = NULL;

  int num_nodes = find_closest(p_temp_1, p_temp_2, time, error_str);
  if (num_nodes == 0) {
    return false;
  } else if (num_nodes == 1) {
    data_out = *p_temp_1;
  } else if (num_nodes == 2) {
    if( p_temp_1->frame_id == p_temp_2->frame_id) {
      interpolate(*p_temp_1, *p_temp_2, time, data_out);
    } else {
      data_out = *p_temp_1;
    }
  }

  return true;
}
示例#12
0
void get_init_shift(Secat *cat1, int ncat1, Secat *cat2, int ncat2, 
		    Pos *initshift)
{
  int no_error = 1;    /* Flag set to 0 on error */
  float cx,cy;         /* Cursor position */
  char cchar='0';      /* Character returned by cursor command */
  Pos cpos;            /* Cursor position */
  Secat bestmatch1;    /* Closest match to cursor position in image 1 */
  Secat bestmatch2;    /* Closest match to cursor position in image 2 */


  /*
   * Get the desired position in image 1
   */

  printf("---------------------------------------------------------------\n");
  if(no_error) {
    cx = 0.0;
    cy = 0.0;
    printf("\n");
    printf("Find a compact object that is clearly detected in both images\n");
    printf("Click the mouse on the object in the FIRST image\n");
    cpgslct(1);
    if(cpgcurs(&cx,&cy,&cchar)>0) {
      printf("\nMouse clicked at: %7.2f %7.2f\n",cx,cy);
      cpos.x = cx;
      cpos.y = cy;
      bestmatch1 = find_closest(cpos,cat1,ncat1);
      printf("Position of closest match is: %7.2f %7.2f\n",
	     bestmatch1.x,bestmatch1.y);
      markcatobj(bestmatch1);
    }
    else {
      fprintf(stderr,"*** Invalid cursor input ***\n");
      no_error = 0;
    }
  }

  /*
   * Now get position in image 2
   */

  if(no_error) {
    printf("\n Now click the mouse on the object in the SECOND image\n");
    cpgslct(2);
    if(cpgcurs(&cx,&cy,&cchar)>0) {
      printf("\nMouse clicked at: %7.2f %7.2f\n",cx,cy);
      cpos.x = cx;
      cpos.y = cy;
      bestmatch2 = find_closest(cpos,cat2,ncat2);
      printf("Position of closest match is: %7.2f %7.2f\n\n",
	     bestmatch2.x,bestmatch2.y);
      markcatobj(bestmatch2);
    }
    else {
      fprintf(stderr,"*** Invalid cursor input ***\n");
      no_error = 0;
    }
  }

  /*
   * Calculate x,y offsets from selected position in image 1
   */

  printf("---------------------------------------------------------------\n");
  if(no_error) {
    initshift->x = bestmatch2.x - bestmatch1.x;
    initshift->y = bestmatch2.y - bestmatch1.y;
    printf("\nInital estimate of shift between images: %8.2f %8.2f\n",
	   initshift->x,initshift->y);
  }

}
示例#13
0
bool planning_service(path_planner::path_srv::Request &req, path_planner::path_srv::Response &res){



	int size = req.map.info.width;
	std::vector<node> solution;
	std::vector<int> commands;
	std::vector<double> vals;
	visualization_msgs::Marker object_marker;
	std::vector<geometry_msgs::Point> pos_list;
	geometry_msgs::Point pos;
	nav_msgs::OccupancyGrid Correct_Map_Msg;

	Occupancy_Grid.resize(size*size,blue);
	heading_map = req.heading;
	matrix_res = req.map.info.resolution;

	for(int i=0; i < size*size; i++)
		Occupancy_Grid[i]=req.map.data[i];


	Correct_Map_Msg.info=req.map.info;
	Correct_Map_Msg.data=Occupancy_Grid;

	map_pub.publish(Correct_Map_Msg);

	solution = find_closest(req.x,req.y,Occupancy_Grid,req.goal);

	convert_to_commands(solution,&commands,&vals);

	res.commands=commands;
	res.vals=vals;
	res.size=vals.size();

	object_marker.header.frame_id = "/mapping";
	object_marker.header.stamp = ros::Time::now();

	// Set the namespace and id for this marker.  This serves to create a unique ID
	// Any marker sent with the same namespace and id will overwrite the old one
	object_marker.ns = "path";
	object_marker.id = 0;

	object_marker.type = visualization_msgs::Marker::CUBE_LIST;

	// Set the marker action.  Options are ADD and DELETE
	object_marker.action = visualization_msgs::Marker::ADD;

	// Set the pose of the marker.  This is a full 6DOF pose relative to the frame/time specified in the header


	object_marker.scale.x = matrix_res;
	object_marker.scale.y = matrix_res;
	object_marker.scale.z = matrix_res;

	// Set the color -- be sure to set alpha to something non-zero!
	object_marker.color.r = 0.0f;
	object_marker.color.g = 0.0f;
	object_marker.color.b = 1.0f;
	object_marker.color.a = 1.0;
	object_marker.pose.orientation.w=1.0;

	object_marker.lifetime = ros::Duration();


	for(int i=0; i<solution.size(); i++){
		pos.x=solution[i].coords[0]*0.01;
		pos.y=solution[i].coords[1]*0.01;
		pos.z=0;

		pos_list.push_back(pos);
	}


	object_marker.points=pos_list;
	
	for(int i = 0 ; i < vals.size(); i++){
	
		ROS_WARN("PLANNED PATH: (%d,%.2f)", commands[i], vals[i]);
	}
	
	
	path_pub.publish(object_marker);


	return true;

}
示例#14
0
inline Color
CurveGradient::color_func(const Point &point_, int quality, float supersample)const
{
    Point origin=param_origin.get(Point());
    Real width=param_width.get(Real());
    std::vector<synfig::BLinePoint> bline(param_bline.get_list().begin(), param_bline.get_list().end());
    Gradient gradient=param_gradient.get(Gradient());
    bool loop=param_loop.get(bool());
    bool zigzag=param_zigzag.get(bool());
    bool perpendicular=param_perpendicular.get(bool());
    bool fast=param_fast.get(bool());

    Vector tangent;
    Vector diff;
    Point p1;
    Real thickness;
    Real dist;

    float perp_dist;
    bool edge_case = false;

    if(bline.size()==0)
        return Color::alpha();
    else if(bline.size()==1)
    {
        tangent=bline.front().get_tangent1();
        p1=bline.front().get_vertex();
        thickness=bline.front().get_width();
    }
    else
    {
        float t;
        Point point(point_-origin);

        std::vector<synfig::BLinePoint>::const_iterator iter,next;

        // Figure out the BLinePoints we will be using,
        // Taking into account looping.
        if(perpendicular)
        {
            next=find_closest(fast,bline,point,t,bline_loop,&perp_dist);
            perp_dist/=curve_length_;
        }
        else					// not perpendicular
        {
            next=find_closest(fast,bline,point,t,bline_loop);
        }

        iter=next++;
        if(next==bline.end()) next=bline.begin();

        // Setup the curve
        etl::hermite<Vector> curve(
            iter->get_vertex(),
            next->get_vertex(),
            iter->get_tangent2(),
            next->get_tangent1()
        );

        // Setup the derivative function
        etl::derivative<etl::hermite<Vector> > deriv(curve);

        int search_iterations(7);

        /*if(quality==0)search_iterations=8;
          else if(quality<=2)search_iterations=10;
          else if(quality<=4)search_iterations=8;
        */
        if(perpendicular)
        {
            if(quality>7)
                search_iterations=4;
        }
        else					// not perpendicular
        {
            if(quality<=6)search_iterations=7;
            else if(quality<=7)search_iterations=6;
            else if(quality<=8)search_iterations=5;
            else search_iterations=4;
        }

        // Figure out the closest point on the curve
        if (fast)
            t = curve.find_closest(fast, point,search_iterations);

        // Calculate our values
        p1=curve(t);			 // the closest point on the curve
        tangent=deriv(t);		 // the tangent at that point

        // if the point we're nearest to is at either end of the
        // bline, our distance from the curve is the distance from the
        // point on the curve.  we need to know which side of the
        // curve we're on, so find the average of the two tangents at
        // this point
        if (t<0.00001 || t>0.99999)
        {
            bool zero_tangent = (tangent[0] == 0 && tangent[1] == 0);

            if (t<0.5)
            {
                if (iter->get_split_tangent_angle() || iter->get_split_tangent_radius() || zero_tangent)
                {
                    // fake the current tangent if we need to
                    if (zero_tangent) tangent = curve(FAKE_TANGENT_STEP) - curve(0);

                    // calculate the other tangent
                    Vector other_tangent(iter->get_tangent1());
                    if (other_tangent[0] == 0 && other_tangent[1] == 0)
                    {
                        // find the previous blinepoint
                        std::vector<synfig::BLinePoint>::const_iterator prev;
                        if (iter != bline.begin()) (prev = iter)--;
                        else if (loop) (prev = bline.end())--;
                        else prev = iter;

                        etl::hermite<Vector> other_curve(prev->get_vertex(), iter->get_vertex(), prev->get_tangent2(), iter->get_tangent1());
                        other_tangent = other_curve(1) - other_curve(1-FAKE_TANGENT_STEP);
                    }

                    // normalise and sum the two tangents
                    tangent=(other_tangent.norm()+tangent.norm());
                    edge_case=true;
                }
            }
            else
            {
                if (next->get_split_tangent_angle() || next->get_split_tangent_radius() || zero_tangent)
                {
                    // fake the current tangent if we need to
                    if (zero_tangent) tangent = curve(1) - curve(1-FAKE_TANGENT_STEP);

                    // calculate the other tangent
                    Vector other_tangent(next->get_tangent2());
                    if (other_tangent[0] == 0 && other_tangent[1] == 0)
                    {
                        // find the next blinepoint
                        std::vector<synfig::BLinePoint>::const_iterator next2(next);
                        if (++next2 == bline.end())
                        {
                            if (loop) next2 = bline.begin();
                            else next2 = next;
                        }

                        etl::hermite<Vector> other_curve(next->get_vertex(), next2->get_vertex(), next->get_tangent2(), next2->get_tangent1());
                        other_tangent = other_curve(FAKE_TANGENT_STEP) - other_curve(0);
                    }

                    // normalise and sum the two tangents
                    tangent=(other_tangent.norm()+tangent.norm());
                    edge_case=true;
                }
            }
        }
        tangent = tangent.norm();

        if(perpendicular)
        {
            tangent*=curve_length_;
            p1-=tangent*perp_dist;
            tangent=-tangent.perp();
        }
        else					// not perpendicular
            // the width of the bline at the closest point on the curve
            thickness=(next->get_width()-iter->get_width())*t+iter->get_width();
    }

    if(perpendicular)
    {
        if(quality>7)
        {
            dist=perp_dist;
            /*			diff=tangent.perp();
            			const Real mag(diff.inv_mag());
            			supersample=supersample*mag;
            */
            supersample=0;
        }
        else
        {
            diff=tangent.perp();
            //p1-=diff*0.5;
            const Real mag(diff.inv_mag());
            supersample=supersample*mag;
            diff*=mag*mag;
            dist=(point_-origin - p1)*diff;
        }
    }
    else						// not perpendicular
    {
        if (edge_case)
        {
            diff=(p1-(point_-origin));
            if(diff*tangent.perp()<0) diff=-diff;
            diff=diff.norm()*thickness*width;
        }
        else
            diff=tangent.perp()*thickness*width;

        p1-=diff*0.5;
        const Real mag(diff.inv_mag());
        supersample=supersample*mag;
        diff*=mag*mag;
        dist=(point_-origin - p1)*diff;
    }

    if(loop)
        dist-=floor(dist);

    if(zigzag)
    {
        dist*=2.0;
        supersample*=2.0;
        if(dist>1)dist=2.0-dist;
    }

    if(loop)
    {
        if(dist+supersample*0.5>1.0)
        {
            float  left(supersample*0.5-(dist-1.0));
            float right(supersample*0.5+(dist-1.0));
            Color pool(gradient(1.0-(left*0.5),left).premult_alpha()*left/supersample);
            if (zigzag) pool+=gradient(1.0-right*0.5,right).premult_alpha()*right/supersample;
            else		pool+=gradient(right*0.5,right).premult_alpha()*right/supersample;
            return pool.demult_alpha();
        }
        if(dist-supersample*0.5<0.0)
        {
            float  left(supersample*0.5-dist);
            float right(supersample*0.5+dist);
            Color pool(gradient(right*0.5,right).premult_alpha()*right/supersample);
            if (zigzag) pool+=gradient(left*0.5,left).premult_alpha()*left/supersample;
            else		pool+=gradient(1.0-left*0.5,left).premult_alpha()*left/supersample;
            return pool.demult_alpha();
        }
    }
    return gradient(dist,supersample);
}
示例#15
0
font
smart_font_rep::get_cyrillic_font (string fam, string var, string ser, string sh) {
  find_closest (fam, var, ser, sh);
  return find_font ("cyrillic", var, ser, sh, sz, dpi);
}
示例#16
0
void menuFunction(KdTree* myKdTree)
{
	FILE *fp;
	fp=fopen("buhu.txt","r+");

	int xAxis,yAxis;//Build Tree
	int axis=0,parentAxis=1,range;

	int xClosePoint,yClosePoint;//Search
	float currentBest;

	int menu=0,menuOption;//Menu

	do{
		
			puts("Choose one of the following:");
			puts("1.Build from file");
			puts("2.Display");
			puts("3.Insert");
			puts("4.Closest point search");
			puts("5.Range Querry");
			puts("6.N closest points");
			puts("7.Exit");
			scanf("%d",&menuOption);
			char response;
			switch(menuOption)
			{
				
				case 1:
					{
						while(feof(fp)==NULL)
						{
							fscanf(fp,"%d",&xAxis);
							fscanf(fp,"%d",&yAxis);
											
							myKdTree=inserare( myKdTree,xAxis,yAxis,parentAxis);
						}
							break;
					}
				case 2:
					{
						listare(myKdTree,0);
						break;
					}
				case 3:

					{ 
						puts("Dati x:");
						scanf("%d",&xAxis);

						puts("Dati y:");
						scanf("%d",&yAxis);

						myKdTree=inserare( myKdTree,xAxis,yAxis,parentAxis);
						break;
					}
				
				case 4:
					{
						currentBest=infinity;

						puts("Give random number y/n?");
						scanf(" %c", &response);

						if(121 == response)
						{

								randomGeneratorPoint(xAxis,yAxis);
						
						}
					
						else
						{
						puts("Give searched point! \n");//Read Coordinates

						puts("Give the x axis: \n");
						scanf("%d",&xAxis);

						puts("Give the y axis: \n");
						puts("Dati y:");
						scanf("%d",&yAxis);
						}

						find_closest(myKdTree,myKdTree,xAxis,yAxis,currentBest,axis,xClosePoint,yClosePoint);//Use efficient search
						
						printf("\n Closest point using efficient methode is :",currentBest);
						printf("%d ",xClosePoint);
						printf("%d\n",yClosePoint);

						currentBest=infinity;//Set current distance to max
						hard_work(myKdTree,xAxis,yAxis,xClosePoint,yClosePoint,currentBest);

						printf("\n Closest point using hardcore methode is :",currentBest);//Use shovel search
						printf("%d ",xClosePoint);
						printf("%d\n",yClosePoint);

						break;

					}
				case 5:
					{

	
						puts("Give random number and range y/n?");
						scanf(" %c",&response);

						if(121 == response)
						{
								randomGeneratorPoint(xAxis,yAxis);
								range=rand()%100+1;
						
						}
					
						else
						{
						puts("Give querry point! \n");//Read Coordinates and range

						puts("Give the x axis: \n");
						scanf("%d",&xAxis);

						puts("Give the y axis: \n");
						scanf("%d",&yAxis);

						puts("Give range: \n");
						scanf("%d",&range);
						}
						puts("\nThe points inside the range are: ");
						range_Querry(myKdTree,myKdTree,xAxis,yAxis,range);//Use efficient search
						puts("\nThe points inside the range using hard work methode are: ");
						hard_Work_Querry(myKdTree,xAxis,yAxis,range);
						
						break;
					}


				case 6:
					{
						currentBest=infinity;
						int points_Number;
						int contor=0;
						puts("Give random number y/n?");
						scanf(" %c", &response);

						if(121 == response)
						{
								randomGeneratorPoint(xAxis,yAxis);
								points_Number=rand()%14+1;
						}
					
						else
						{
						puts("Give searched point! \n");//Read Coordinates

						puts("Give the x axis: \n");
						scanf("%d",&xAxis);

						puts("Give the y axis: \n");
						puts("Dati y:");
						scanf("%d",&yAxis);

						puts("Give the number n for the closest points: \n");
						scanf("%d",&points_Number);
						}
						std::vector<PointContainer>closest_Distances(points_Number);
						find_closest_Points(myKdTree,myKdTree, xAxis, yAxis,currentBest,axis,closest_Distances,points_Number,contor);//Use efficient search
						puts("\nClosest n points are: ");
						for(int i=0;i<points_Number;i++)
							printf(" %d %d ",closest_Distances[i].x,closest_Distances[i].y);

						currentBest=infinity;//Set current distance to max
						contor=0;

						hard_work_closest(myKdTree,xAxis,yAxis,currentBest,closest_Distances,points_Number,contor);
						puts("Closest n points using hard work are: \n");
						for(int i=0;i<points_Number;i++)
							printf(" %d %d ",closest_Distances[i].x,closest_Distances[i].y);
						break;
						puts("");
					}
				case 7:
					{
						return;
					}
					
			}
		}while(menu!=7);
}
示例#17
0
int main(int argc, char** argv){
	
	begin = clock();
	int i, j;
	int b; 
	num_files = atoi(argv[1]);

	// 4d array to have 2 layers for height and width and 2 layers for files and people
	int**** pre_training_set = (int****)malloc(num_people * sizeof(int***));
	for(i = 0; i < num_people; i++){
		pre_training_set[i] = (int***)malloc(num_files * sizeof(int**));
	}
	char filename[128];
	// printf("Hello\n");

	for(i = 0; i < num_people; i++){
		for(j = 0; j < num_files; j++){
			sprintf(filename, "/home/cagdas/Desktop/parallel-project-3/images/%d.%d.txt", i+1, j+1);
			// printf("%s\n", filename);
			pre_training_set[i][j] = read_pgm_file(filename, rows, cols);
		}
	}

	// printf("Creating the training set\n");
	// the actual training set where the histogram arrays will be held for each file for each person (3 layers!)
	int*** training_set = (int***)malloc(num_people * sizeof(int**));
	for(i = 0; i < num_people; i++){
		training_set[i] = (int**)malloc(num_files * sizeof(int*));
	}

	// create histograms for each person's each picture
	for(i = 0; i < num_people; i++){
		for(j = 0; j < num_files; j++){
			// printf("Onto it with i %d j %d\n", i, j);
			training_set[i][j] = (int*)malloc(sizeof(int) * 256);
			beginp = clock();
			#pragma omp parallel for schedule(static)
			for(b = 0; b < 256; b++){
				training_set[i][j][b] = 0;
			}
			endp = clock();
			time_spentp += (double)(endp - beginp);
			create_histogram(training_set[i][j], pre_training_set[i][j], rows, cols);

		}
	}
	// printf("created the training set\n");
	// test files
	int**** pre_test_set = (int****)malloc(num_people * sizeof(int***));
	for(i = 0; i < num_people; i++){
		pre_test_set[i] = (int***)malloc(sizeof(int**) * (total_num_files - num_files));
	}

	// printf("pre test set\n");


	for(i = 0; i < num_people; i++){
		for(j = 0; j < (total_num_files - num_files); j++){
			sprintf(filename, "/home/cagdas/Desktop/parallel-project-3/images/%d.%d.txt", i+1, j+1+num_files);
			// printf("Current name is %s\n", filename);
			pre_test_set[i][j] = read_pgm_file(filename, rows, cols);
		}
	}
	
	// printf("created pre test set\n");
	int*** test_set = (int***)malloc(num_people * sizeof(int**));
	for(i = 0; i < num_people; i++){
		test_set[i] = (int**)malloc((total_num_files - num_files) * sizeof(int*));
		for(j = 0; j < total_num_files - num_files; j++){
			test_set[i][j] = (int*)malloc(sizeof(int) * 256);
			for(b = 0; b < 256; b++){
				test_set[i][j][b] = 0;
			}
			create_histogram(test_set[i][j], pre_test_set[i][j], rows, cols);
		}
	}
	// printf("np abi\n");
	int totalCount = 0;
	int falseCount = 0;
	for(i = 0; i < num_people; i++){
		for(j = 0; j < total_num_files - num_files; j++){
			int cur = find_closest(training_set, num_people, num_files, 256, test_set[i][j]);

			// test the file with file name "%d.%d.txt\t\t%d\t\t%d\n", i+1, j+1+num_files
			totalCount++;	// a judgment is made
			if(cur != i+1){ // a false judgment is made
				printf("%d.%d.txt\t\t%d\t\t%d\n", i+1, j+1+num_files, i+1, cur);
				falseCount += 1;
			}
		}
	}
	printf("Accuracy: %d correct answers for %d tests Parallel\n", totalCount - falseCount, totalCount);

	// TODO:: deallocate the allocated memory space

	int a;

	beginp = clock();
	#pragma omp parallel for schedule(static) private(j,a)
	for(i = 0; i < num_people; i++){
		for(j = 0; j < num_files; j++){
			for(a = 0; a < rows; a++){
				free(pre_training_set[i][j][a]);
			}
			free(pre_training_set[i][j]);
		}
		free(pre_training_set[i]);
	}
	endp = clock();
	time_spentp += (double)(endp - beginp);
	free(pre_training_set);
	// printf("free pre training set\n");

	#pragma omp parallel for schedule(static) private(j,a)
	for(i = 0; i < num_people; i++){
		for(j = 0; j < total_num_files - num_files; j++){
			for(a = 0; a < rows; a++){
				free(pre_test_set[i][j][a]);
			}
			free(pre_test_set[i][j]);
		}
		free(pre_test_set[i]);
	}
	free(pre_test_set);
	// printf("free pre test set\n");

	beginp = clock();
	#pragma omp parallel for schedule(static) private(j)
	for(i = 0; i < num_people; i++){
		for(j = 0; j < num_files; j++){
			free(training_set[i][j]);
		}
		free(training_set[i]);
	}
	endp = clock();
	time_spentp += (double)(endp - beginp);
	free(training_set);

	// printf("free training set\n");

	beginp = clock();
	#pragma omp parallel for schedule(static) private(j)
	for(i = 0; i < num_people; i++){
		for(j = 0; j < total_num_files - num_files; j++){
			free(test_set[i][j]);
		}
		free(test_set[i]);
	}
	endp = clock();
	time_spentp += (double)(endp - beginp);
	free(test_set);
	// printf("free test set\n");

	end = clock();
	time_spent = (double)(end-begin);
	printf("Total runtime: %f\n", time_spent/CLOCKS_PER_SEC);
	printf("Sequential runtime: %f\n", (time_spent - time_spentp)/CLOCKS_PER_SEC);

	return 0;
}