예제 #1
0
void start_simulation(GRAPH *g,CARS *c, EDGES *e )
{
    long global_tick=0;
    int i=0;
    int next_node_id,next_edge_id;
    int done = 0;
    
    //initial make decision
     for(i=0;i<c->no_of_cars;++i)
            if(c->car_data[i].current_destination == -1 && c->car_data[i].done == 0)   // car at node
            {
                make_decision(g,e,(c->car_data)+i,&next_node_id,&next_edge_id);
                if(!(next_node_id==-1 && next_edge_id==-1))
                    update_car_destination(c->car_data+i,next_node_id,next_edge_id,global_tick);
            }
    printf("\n Initialisation complete\n") ;
    //simulation loop 
    while(done != 1)
    {
        printf("\n global_tick %ld\n",global_tick);
        done =1;
        // collison handling
        for(i=0;i<e->no_of_edges;++i)
        {
          //  if(e->edge_data[i].no_of_cars >=2)
          //  handle_collison((e->edge_data)+i,c,global_tick);
        }
        for(i=0;i<c->no_of_cars;++i)
            update_car_path((c->car_data) + i,e,global_tick);

        for(i=0;i<c->no_of_cars;++i)
            if(c->car_data[i].current_destination == -1 && c->car_data[i].done == 0)   // car at node
            {
                make_decision(g,e,(c->car_data)+i,&next_node_id,&next_edge_id);
                if(!(next_node_id==-1 && next_edge_id==-1))
                    update_car_destination(c->car_data+i,next_node_id,next_edge_id,global_tick);
            }

        for(i=0;i<c->no_of_cars;++i)//check for all car finished traversing 
        {
            if(c->car_data[i].done != 1)
                done = 0;
        }

        ++global_tick;
    }
    printf("\nSimulation Time = %ld ticks \n",global_tick);
}
예제 #2
0
bool solver_solve(solver* s){
   lit decision;
   bool forced = false;

   while(true) {
      // pick a variable to decide on (based on counts)
      if(!forced) {decision = make_decision(s);}
      else forced = false;
      if(!propagate_decision(s, decision, true)){
         // CONFLICT
         if(!backtrack(s,&decision)) return false;//UNSATISFIABLE
         else{ //Backtrack worked, decision must be forced
            forced = true;
            continue;
         }
      }
      else {
         // NO CONFLICT
         if(s->satisfied) return true;
         if(!propagate_units(s)){
            // CONFLICT
            if(!backtrack(s, &decision)) return false; //UNSATISFIABLE
            else {
               forced = true;
               continue;
            }
         }
         else {
            // NO CONFLICT
            if(s->satisfied) return true;
         }
      }
   }
   return true;
}
예제 #3
0
Link* Link::generate()
{
	Link* n = new Link();
	n->value = randint(1, 10);
	n->level = 1;

	Link* p = this;

	if (p->find_total(n) != 0)  // Если есть элемент на уровне ниже, то уже добавляем новый элемент слоем выше него.
	{
		p = p->find_lower(n);
		n->level++;
		if (p->find_total(n) != 0) // Есть уже элемент n->level 2
		{
			p = p->find_lower(n); // p это копия элемента n->level 2
			n->level++; // Если есть - добавляем n на третий элемент, n->level стал 3
		}
		if (make_decision(100 / (n->level - 0.6))) // При решении добавить элемент.
		{
			
			cout << "Decision true on p value: " << n->value << ", level: " << n->level << " #" << cnt << '\n';
			p = p->add(n);
			cnt++;
		}
		else 
		{ 
			cout << "Decision false on p value: " << n->value << " level: " << n->level << '\n';
			return this; 
		}
		p = p->set_neighbours();
		return p;
	}
	if (p->find_total(n) != 0)
	{
		if (p->level + 1 < system_levels) 
		return this;
	}
}
예제 #4
0
Link* Link::generate()
{
	Link* n = new Link();
	n->value = randint(1, 10);
	n->level = 1;

	Link* p = this;

	while (p->find_total(n))  // Если есть элемент на уровне ниже, то уже добавляем новый элемент слоем выше него.
	{
		p = p->find_total(n);
		n->level++;
		if (n->level == system_levels && n->level == 1 || n->level > system_levels)
		{
			n->level--; // n->level - 1, потому-что счётчик накручивает 5й элемент автоматом
			cout << "Element already exists;" << setw(4) << " value: " << n->value << ", level: " << n->level << " string: " << str_cnt << '\n';
			return this;
		}
	}
	if (make_decision(100 / (n->level - 0.6))) // При решении добавить элемент.
	{

		cout << "Decision true on p " << setw(12) << "value: " << n->value << ", level: " << n->level << " #" << cnt << " string: " << str_cnt << '\n';
		p = p->add(n);
		cnt++;
		str_cnt++;
	}
	else
	{
		cout << "Decision false on p " << setw(11) << "value: " << n->value << ", level: " << n->level << " string: " << str_cnt << '\n';
		str_cnt++;
		return this;
	}
	p = p->set_neighbours();
	return p;
}
예제 #5
0
void
process_client(int msgsock)
{
	FILE * fd;
	char *pbuf;
	char *vp;
	int plen;
	int rval;
	char c;
	int sessionid;
	char *nonce;
	char str_date[QLEN];
	char str_time[QLEN];
	struct tm *vp_gmtime;
	time_t vp_time;

	// read header
	if ((fd = fdopen(msgsock, "r")) == NULL)
		perror("fdopen");


	if (read_message(fd, "H", &pbuf, &plen) < 0) {
		fprintf(stderr, "bad request\n");
		return;
	}

	nonce = calculate_nonce();	// create nonce
	// process hello packet and prepare offer packet
	// calculate date/time
	vp_time = time(NULL);
	vp_gmtime = gmtime(&vp_time);
	snprintf(str_date, QLEN, "%04d%02d%02d", (vp_gmtime->tm_year)+1900,
	    vp_gmtime->tm_mon+1, vp_gmtime->tm_mday);
	snprintf(str_time, QLEN, "%02d%02d%02d", vp_gmtime->tm_hour,
	    vp_gmtime->tm_min, vp_gmtime->tm_sec);

	vp = package_offer(pbuf, nonce, str_date, str_time);
	free(pbuf);

	if (vp == NULL) {
		fprintf(stderr, "process_message: package_offer failed\n");
		return;
	}
	fprintf(fd, "O%06d:%s",  strlen(vp), vp);
	printf( "\t--->O%06d\n",  strlen(vp));
	free(vp);


	// read "request" packet
	if (read_message(fd, "R", &pbuf, &plen) < 0) {
		fprintf(stderr, "bad request\n");
		return;
	}
	sessionid = initialize_keynote(nonce, str_date);

	// process "request"
	printf("request: <<%s>>\n", pbuf);
	if (process_request_msg(sessionid, pbuf, plen) < 0) {
		fprintf(stderr, "process_request_msg failed -- abort\n");
		return;
	}
	free(pbuf);

	// read in credentials
	do {
		if ((c = read_message(fd, "Cc", &pbuf, &plen)) < 0) {
			fprintf(stderr, "bad request\n");
			return;
		}

		// process credential
		printf("credential (%c): <<%s>>\n", c, pbuf);
		if (load_credential(sessionid, pbuf) < 0) {
			fprintf(stderr, "load_credential failed\n");
			return;
		}
		free(pbuf);
	} while (c != 'C');

	// make decision
	rval = make_decision(sessionid);
#define DENIED "denied"
#define APPROVED "approved"

	if (rval < 0)
		fprintf(stderr, "make_decision failed\n");
	else if (rval == 0)
		fprintf(fd, "D%06d:%s",  strlen(DENIED), DENIED);
	else if (rval == 1)
		fprintf(fd, "D%06d:%s",  strlen(APPROVED), APPROVED);
	else
		fprintf(stderr, "make_decision retured %d.\n", rval);
		
	// printf( "\t--->D%06d:%s\n",  strlen(vp), vp);

	fflush(fd);	// make sure last packet is sent 
			// before we close the socket
	return;
}
예제 #6
0
/* An avatar thread
 *
 * Input:
 * (1) input = a bundle of parameters passed in as a struct
 *
 * Output: None.
 */
void* avatar(void* input){

	// Cast the input struct pointer to the correct type
	AvatarParameter* params = (AvatarParameter*)input;
	
	// Assign all of the avatars variables
	uint32_t my_ID = params->ID;
	int difficulty = params->difficulty;
	char* IP_address = params->IP_address;
	uint32_t port = params->port;
	char* log_file = params->log_file;
	int sockfd = params->sockfd;
	int num_avatars = params->num_avatars;
	int width = params->width;
	int height = params->height;
	BlockNode*** the_maze = params->maze;
	XYPos** graphics_spots = params->graphics_spots;
	
	// Position variables for the avatar
 	XYPos* my_pos = (XYPos*)calloc(1, sizeof(XYPos));
 	XYPos* old_pos = (XYPos*)calloc(1, sizeof(XYPos));
	
	// line will be used to print out messages to the log
	char *line = (char*)calloc(MAX_LINE_LENGTH, sizeof(char));

	// Will hold main avatar info and be printed to the file
	char* avatar_header = get_line_information(params);
	
	write_a_line_to_file(log_file, avatar_header);
	free(avatar_header); avatar_header = NULL;
	
	// Send AM_AVATAR_READY to server
	AM_Message ready_msg;
	memset(&ready_msg, 0, sizeof(AM_Message));
	ready_msg.type = htonl(AM_AVATAR_READY);
	ready_msg.avatar_ready.AvatarId = htonl(my_ID);
	
	// Send the message.
	send(sockfd, &ready_msg, sizeof(ready_msg), 0);
	
	// Waiting for server response...
	AM_Message rec_msg;

	// Receive the AM_AVATAR_TURN message
	if (recv(sockfd, &rec_msg, sizeof(rec_msg), 0) < 0) {
		// If the message was not received, print an error and exit
		sprintf(line, "[avatar #%d] Error receiving initial TURN message\n", my_ID);
		write_a_line_to_file(log_file, line);
		free(line); line = NULL;
		
		// Cleanup.
		FreeAvatarParam(params);
 		free(my_pos);
 		free(old_pos);
		
		running_threads--;
		return NULL;
	}
	
	// Is it an AM_AVATAR_TURN message?
	if (ntohl(rec_msg.type) != AM_AVATAR_TURN) {
		// If not, print an error and exit
		sprintf(line, "[avatar #%d] ERROR: Initial message was not a TURN message\n", my_ID);
		write_a_line_to_file(log_file, line);
		free(line); line = NULL;
		
		// Cleanup.
		FreeAvatarParam(params);
		free(my_pos);
 		free(old_pos);
		
		running_threads--;
		return NULL;
	}
	
	char* initial_messages = (char*)calloc(4*MAX_LINE_LENGTH, sizeof(char));
	
	// Made connection
	sprintf(initial_messages, "[avatar #%d] Successfully connected with the server and received the first TURN message\n", my_ID);
	
	// Variables about the avatar's position and about whose turn it currently is
	uint32_t turn;
	
	// Assign these variables from the first TURN message
	turn = ntohl(rec_msg.avatar_turn.TurnId);
	my_pos->x = ntohl(rec_msg.avatar_turn.Pos[my_ID].x);
	my_pos->y = ntohl(rec_msg.avatar_turn.Pos[my_ID].y);
	
	// Initial variables
	sprintf(line, "[avatar #%d] First Turn ID (should be zero): %u\n[avatar #%d] Initial Coordinates: x=%u y=%u\n\n", my_ID, turn, my_ID, my_pos->x, my_pos->y);
	strcat(initial_messages, line);
	free(line); line = NULL; line = (char*)calloc(MAX_LINE_LENGTH, sizeof(char));
	
	initial_messages = realloc(initial_messages, strlen(initial_messages) + 1);
	write_a_line_to_file(log_file, initial_messages);
	free(initial_messages); initial_messages = NULL;
	
	// Sleep for one second before the solving begins so that all initial
	// info has a chance to be written to the log
	sleep(1);
	
	// A variable to track whether the game has ended
	int game_over = 0;
	
	// The move message that will be sent each turn
	AM_Message mv_msg;
	memset(&mv_msg, 0, sizeof(AM_Message));
	
	// These variables will hold info about the avatar's moves
	int move = -1;
	int last_move = -1;
	int blocked = 0;
	
	// Track the number of turns taken
	int turn_counter = 0;
	
	// Put the avatar into the maze initially
	InitialPlacing(the_maze, my_pos, my_ID);
	
	// As long as the game hasn't ended...
	while(!game_over){
		
		// Print the coordinates of the avatar
		sprintf(line, "[avatar #%d] Turn ID: %u\n[avatar #%d] Starting coordinates this turn: x=%u y=%u\n\n", my_ID, turn, my_ID, my_pos->x, my_pos->y);
		write_a_line_to_file(log_file, line);
		free(line); line = NULL; line = (char *)calloc(MAX_LINE_LENGTH, sizeof(char));

		// Upload current position to the graphics list of positions
		upload_graphics_info(graphics_spots, my_pos, my_ID);
		if (turn == my_ID){
			// Draw graphics based on everybody's current position
			maze_graphics(graphics_spots, width, height, num_avatars, turn_counter);
		}
		
		// If it's my turn
		if (turn == my_ID) {
			
			if (PathFound==0){
				//In the mapping phase
				move = make_decision(the_maze, last_move, blocked, my_pos);
			}
			else if (PathFound==1){

				//Placeholder. Need more sophisticated way of determining target.
				//As of now just make one of the avatars the target. 
				if (DoOnce==0){
					//Set the global variable
					TargetPosition=calloc(1,sizeof(XYPos)); //Need to free once game is over.
					TargetPosition->x=my_pos->x;
					TargetPosition->y=my_pos->y;
					TargetAvatar=my_ID;
					DoOnce=1;
				}

				
				//In the meeting phase
				move = make_decision_meeting(the_maze,my_pos,width,height,TargetPosition,my_ID,TargetAvatar);
			}
			// Create mv_msg after move is computed
			mv_msg.type = htonl(AM_AVATAR_MOVE);
			mv_msg.avatar_move.AvatarId = htonl(my_ID);
			mv_msg.avatar_move.Direction = htonl(move);
		
			// Send the move
			send(sockfd, &mv_msg, sizeof(mv_msg), 0);
		}
		
		// Receive the AM_AVATAR_TURN message
		AM_Message new_msg;
		
		// If there was an error with the TURN message
		if (recv(sockfd, &new_msg, sizeof(new_msg), 0) < 0) {
			if (my_ID == 0){
				sprintf(line, "ERROR: there was a problem with the TURN message\n");
				write_a_line_to_file(log_file, line);
			}
			free(line); line = NULL;
			
			// Cleanup local
			FreeAvatarParam(params);
			free(my_pos);
			free(old_pos);
		
			running_threads--;
			return NULL;
		}
		
		// Have we solved the maze?
		if (ntohl(new_msg.type) == AM_MAZE_SOLVED){
			if (my_ID == 0){
				sleep(1);
				sprintf(line, "WINNER! nAvatars: %u Difficulty: %u nMoves: %u Hash: %u\n\n", ntohl(new_msg.maze_solved.nAvatars), ntohl(new_msg.maze_solved.Difficulty), ntohl(new_msg.maze_solved.nMoves), ntohl(new_msg.maze_solved.Hash));
				
				write_a_line_to_file(log_file, line);
				free(line); line = NULL; line = (char*)calloc(MAX_LINE_LENGTH, sizeof(char));
			}
			break;
		}
		// Too many moves?
		else if (ntohl(new_msg.type) == AM_TOO_MANY_MOVES){
			if (my_ID == 0){
				sprintf(line, "ERROR: too many moves; lost\n");
				write_a_line_to_file(log_file, line);
			}
			free(line); line = NULL;
			
			// Cleanup local
			FreeAvatarParam(params);
			free(my_pos);
			free(old_pos);
			
			running_threads--;
			return NULL;
		}
		// Is the message type neither a SOLVED message nor a TURN nor a TOO_MANY_MOVES message?
		else if(ntohl(new_msg.type) != AM_AVATAR_TURN){
			if (my_ID == 0){
				sprintf(line, "ERROR: server returned an error: %u\n", ntohl(new_msg.type));
				write_a_line_to_file(log_file, line);
			}
			free(line); line = NULL;
			
			// Cleanup local
			FreeAvatarParam(params);
			free(my_pos);
			free(old_pos);
			
			running_threads--;
			return NULL;
		}

		// Update my old coordinates
		old_pos->x = my_pos->x;
		old_pos->y = my_pos->y;
		// Get new coordinates
		my_pos->x = ntohl(new_msg.avatar_turn.Pos[my_ID].x);
		my_pos->y = ntohl(new_msg.avatar_turn.Pos[my_ID].y);
		
		// If I just moved...
		if (my_ID == turn){
			// Update the maze with my new info
			UpdateMazeOnMove(the_maze, old_pos, my_pos, my_ID, move, width, height, num_avatars);
			
			// Determine whether or not I was just blocked
			if (old_pos->x == my_pos->x && old_pos->y == my_pos->y){
				blocked = 1;
			}
			else{
				blocked = 0;
			}
		}
		
		// What is the new TURN_ID?
		turn = ntohl(new_msg.avatar_turn.TurnId);

		// Update the last move
		last_move = move;
		turn_counter++;
		
	}
	
	// Cleanup.
	free(line); line = NULL;
	FreeAvatarParam(params);
	free(my_pos);
	free(old_pos); old_pos = NULL;
	if (my_ID == 0) {
		free(TargetPosition);
	}
	
	// Once this thread is done, there is one less thread still alive
	running_threads--;
	
	// Done!
	return NULL;
}
예제 #7
0
/* ------------------------------------------------------------------------------------------------------
   Creates a byte from the waveform

   0..255  new byte
   -1      continue
   -2      error
   -3      no more bytes
--------------------------------------------------------------------------------------------------------- */
int byte_decode(int restart, int new_file)
{
	static int t,t_active,t_byte;
	static int byte,n_bytes,c[6];
	int i,j,k,d[7],sampleval;
	double x;

	// t = number of samples read
	// t_byte = sample where byte starts
	// t_active is > 0 when a signal has been detected

	if(restart) {
		t = t_active = 0;
		update_progress(0.0);
		update_status("Attente du signal...");
	}

	// process next sample
	t++;
	sampleval = next_sample(new_file);
	
	if (sampleval == 40000) {
		return -3;
	}
	x = (double)sampleval / 32768.0;
	x = filter(x);
	x = dilate(x);
	x = median(x);
	x = make_decision(x,d);
	b_median(d);
	update_level(x);

	// print_deep_debug("t: %d, d6 %d, d5 %d, x %0.5f\n", t, d[6], d[5], x);
	// activation test
	if(d[6] && t_active == 0) {
		print_deep_debug(" - act - ");
		t_active = t;
		t_byte = 0;
		n_bytes = 0;
		update_status("Analyse du signal...");
	}
	if(t_active == 0) return -1;

	// deactivation test after a long period of inactivity
	if(t > t_active + 10000) {
		update_status("Désactivation pour cause d'inactivité");
		return -2;
	}

	// new byte?
	if(t_byte == 0 && d[5]) { // new byte
		print_deep_debug(" -- new byte -- ");
		t_active = t_byte = t;
		n_bytes++;
		byte = 0;
		for(i = 0;i < 6;i++)
			c[i] = 0;
	}

	// processing a byte?
	if(t_byte > 0) {
		j = (t - t_byte) / 88;  // bit number; the duration of a bit is very close to 2ms=88.2 samples
		if(j >= 10) { // end of the byte
			print_deep_debug(" [b = %d ] ", byte);
			if((byte & 1) == 0) { // first bit (lsb) must be a one
				print_debug("Bad byte start");
				return -2;
			}
			if(byte >= 512) { // last bit (msb) must be a zero
				print_debug("Bad byte finish");
				return -2;
			}
			byte >>= 1;
			t_byte = 0;
			if(n_bytes > 5) {
				return byte;
			}
			if(byte != 0xAA) { // bad synchronization byte
				print_debug("Bad synchronization byte.");
				return -2;
			}
			print_debug("Found good synchronization byte.");
			return -1; // discard synchronization byte
		}