Ejemplo n.º 1
0
int main(void) {

  //compute the challenge hash
  SHA1((unsigned char *)challenge_string, strlen(challenge_string), &challenge_hash[0]);

  //load words into the dict
  init_dict("words.txt");

  //get ready to read /dev/urandom
  init_random();

  //init 'best'
  top_distance = 5000;

  //compute!
  int nums[NUM_WORDS], i, len, dist;
  char buf[BUF_MAX];
  sha1_hash tmp_hash[SHA_DIGEST_LENGTH];

  while(1) {
    get_nums(nums,NUM_WORDS);
    len = build_string(buf, nums, NUM_WORDS);
    SHA1((unsigned char*)buf, len, tmp_hash);
    dist = distance(challenge_hash, tmp_hash);
    if(dist < top_distance) {
      //we have a winnar (maybe)
      memcpy(top_string, buf, len+1);
      top_distance = dist;
      printf("%i\t\"%s\"\n", top_distance, top_string);
      fflush(stdout);
    }
  }

  return 0;
}
Ejemplo n.º 2
0
int code_0op(char *mnem){
	if (!initialized)
		init_dict();	
	int res = getval(mnem);
	if(res!=-1)
		putc(res,fp);
	return (res!=-1?1:0);


}
Ejemplo n.º 3
0
int main(int argc, char *argv[])
{
    init_dict();
    convert_command_line(argc, argv);
    init_stacks();
    mu_find_init_file();
    mu_load_file();
    mu_start_up();
    return 0;
}
Ejemplo n.º 4
0
PUBLIC int main(int ac, char **av)
{
     int i, n_files;
     char **files;

     argc = ac; argv = av;

     while (--argc > 0 && (*++argv)[0] == '-')
          do_flags(*argv);
     files = argv;
     n_files = argc;

     if (debflag('v')) {
	  fprintf(errout, "%s\n%s\n%s\n", 
		  fuzz_banner, fuzz_rcsid, fuzz_copyright);
	  fflush(errout);
     }

     debugging = debflag('p');
     init_sym();
     init_type();
     init_dict();
     open_prelude();
     read_a_file();
     if (dflag) {
	  check_file();
	  clear_temp((univ) NULL);
     }

     debugging = TRUE;
     if (n_files == 0) {
	  /* Finished prelude, no args: read stdin */
	  file_name = "standard input";
	  yyrestart(stdin);
	  read_a_file();
     }
     else {
	  for (i = 0; i < n_files; i++) {
	       reopen_input(files[i]);
	       yyrestart(yyin);
	       read_a_file();
	  }
     }
     if (dflag) {
	  check_file();
	  clear_temp((univ) NULL);
     }

#ifdef DEBUG
     if (debflag('h'))
	  dump_hash();
#endif

     return (n_errors > 0 ? 1 : 0);
}
Ejemplo n.º 5
0
int code_1op_imm(char *mnem,char * simm) {
	int imm = extr2(simm);//hex conv
	if (!initialized)
		init_dict();
	if (imm==3&&(!strcmp(mnem,"int")) || !(strcmp(mnem,"INT")))	{
		putc(0xcc,fp);
		if(VERBOSE)
		printf("\nInstruction Result:%d",1);
		return 1;
	}
	
	int w =((imm&0xff) == imm) ?0:1;
	int res;	
	char buf[20];
	strcpy(buf,mnem);
	strcat(buf,",");
	
	if(w)
		strcat(buf,"iw");
	else
		strcat(buf,"ib");
	res = getval(buf);
	if(res!=-1) {
		putc(res,fp);
		if(w){
			int mat[2];
			encode(mat,imm);
			putc(mat[0],fp);
			putc(mat[1],fp);
			if(VERBOSE)
				printf("\nInstruction Result:%d",3);
			return 3;
		}
		else {
			putc(imm,fp);
			if(VERBOSE)
		printf("\nInstruction Result:%d",2);
			return 2;
			}
	}
	else {
	//error handling	
	}
if(VERBOSE)
		printf("\nInstruction Result:%d",0);
return 0;
}
Ejemplo n.º 6
0
SPELLEROBJ::SPELLEROBJ(int num) : BASE_CL()
	  {
		outports = 1;
		inports = 2;
		strcpy(in_ports[0].in_name,"joystick");
		strcpy(in_ports[1].in_name,"paddle");
		width=80;

		select=-1;selstart=0;selbegin=0;selend=4;os=0;
		
		waitres=0;idletime=0;presstime=0; switchtime=0; 
		wordcount=0;
		
		input=15;oldinput=15;
		xpos=200.0f;ypos=100.0f;
		suggestions=0;selections=4;
		sugchars=0; delchars=0;
		upchar=0;directsend=0;
		autolearn=0;

		strcpy(fn,"none");
		strcpy(word,"");
		strcpy(lastword,"");
		strcpy(wordfile,"");
		strcpy(dictfile,"none");
		enter=0;
		input=0.0f; input2=0.0f;
		paddle=0;oldpaddle=0;
		left=500;right=800;top=50;bottom=400;
		
		speed=300;press=300;idle=500; 
		mode=0;

		if (!(sugfont = CreateFont(-MulDiv(12, GetDeviceCaps(GetDC(NULL), LOGPIXELSY), 72), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "Arial")))
			report_error("Font creation failed!");

		init_dict(this);
        
		if(!(displayWnd=CreateWindow("Speller_Class", "Speller", WS_CLIPSIBLINGS| WS_CHILD | WS_CAPTION | WS_THICKFRAME ,left, top, right-left, bottom-top, ghWndMain, NULL, hInst, NULL)))
		    report_error("can't create SPELLER Window");
		else { SetForegroundWindow(displayWnd); ShowWindow( displayWnd, TRUE ); UpdateWindow( displayWnd ); }
		InvalidateRect(displayWnd, NULL, TRUE);
	  }
Ejemplo n.º 7
0
DictInfo *
finddict(Oid id)
{
	/* last used dict */
	if (DList.last_dict && DList.last_dict->dict_id == id)
		return DList.last_dict;


	/* already used dict */
	if (DList.len != 0)
	{
		DictInfo	key;

		key.dict_id = id;
		DList.last_dict = bsearch(&key, DList.list, DList.len, sizeof(DictInfo), comparedict);
		if (DList.last_dict != NULL)
			return DList.last_dict;
	}

	/* last chance */
	if (DList.len == DList.reallen)
	{
		DictInfo   *tmp;
		int			reallen = (DList.reallen) ? 2 * DList.reallen : 16;

		tmp = (DictInfo *) realloc(DList.list, sizeof(DictInfo) * reallen);
		if (!tmp)
			ts_error(ERROR, "No memory");
		DList.reallen = reallen;
		DList.list = tmp;
	}
	DList.last_dict = &(DList.list[DList.len]);
	init_dict(id, DList.last_dict);

	DList.len++;
	qsort(DList.list, DList.len, sizeof(DictInfo), comparedict);
	return finddict(id); /* qsort changed order!! */ ;
}
Ejemplo n.º 8
0
bool        process_tag( gtentry * ge, mac_entry * me )
{
    bool            processed;
    gaentry     *   ga;
    gavalentry  *   gaval;
    char        *   p;
    char        *   p2;
    int             rc;
    char            quote;
    char            longwork[20];
    bool            tag_end_found = false;

    processed = true;
    init_dict( &loc_dict );

    add_defaults_to_dict( ge, &loc_dict );

    /***********************************************************************/
    /*  scan input for attributes and / or tagtext                         */
    /***********************************************************************/

    p = tok_start + ge->namelen + 1;    // over tagname

    if( ge->attribs != NULL ) {     // only process attributes if they exist
        while( *p == ' ' ) {        // not yet end of tag, process attributes

            while( *p == ' ' ) {        // over WS to attribute
                p++;
            }
            if( *p == '.' ) {
                tag_end_found = true;
                break;
            }
            p2 = token_buf;
            while( is_id_char( *p ) ) {
                *p2++ = *p++;
            }
            *p2 = '\0';
            if( p2 != token_buf ) {     // ignore nullstring
                for( ga = ge->attribs; ga != NULL; ga = ga->next ) {// all attrs
                    if( !stricmp( ga->name, token_buf ) ) {
                        ga->attflags |= att_proc_seen; // attribute specified
                        if( ga->attflags & att_auto ) {
                            auto_att_err();
                            break;
                        }

                        if( *p == '=' ) {   // value follows
                            ga->attflags |= att_proc_val;

                            p++;        // over =
                            p2 = token_buf;
                            if( is_quote_char( *p ) ) {
                                quote = *p++;
                                while( *p && *p != quote ) {// quoted value
                                    *p2++ = *p++;
                                }
                                if( *p == quote ) {
                                    p++;// over ending quote
                                }
                            } else {
                                quote = '\0';
                                while( *p && (*p != ' ') && (*p != '.') ) {
                                    *p2++ = *p++;
                                }
                            }
                            *p2 = '\0';
                            if( ga->attflags & att_off ) {// attribute inactive
                                continue;
                            }
                            if( ga->attflags & att_upper ) {// uppercase option
                                strupr( token_buf );
                            }

                            scan_err = check_att_value( ga );

                        } else {// special for range set default2 if no value
                            if( ga->attflags & att_range ) {
                                for( gaval = ga->vals; gaval != NULL;
                                     gaval = gaval->next ) {
                                     if( gaval->valflags & val_range ) {
                                        break;
                                     }
                                }
                                if( gaval != NULL ) {
                                     sprintf( token_buf, "%d",
                                              gaval->a.range[3] );
                                     rc = add_symvar( &loc_dict, ga->name,
                                                      token_buf, no_subscript,
                                                      local_var );
                                }
                            }
                        }
                        break;
                    }
                }
                if( ga == NULL ) {      // attribute Not found
                    char        linestr[MAX_L_AS_STR];

                    processed = false;
                    wng_count++;
                    //***WARNING*** SC--040: 'abd' is not a valid attribute name
                    g_warn( wng_att_name, token_buf );
                    if( input_cbs->fmflags & II_macro ) {
                        ultoa( input_cbs->s.m->lineno, linestr, 10 );
                        g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
                    } else {
                        ultoa( input_cbs->s.f->lineno, linestr, 10 );
                        g_info( inf_file_line, linestr, input_cbs->s.f->filename );
                    }
                    show_include_stack();
                }
            }
            /***************************************************************/
            /*  check for tag end .                                        */
            /***************************************************************/
            if( *p == ' ' ) {
                continue;               // not yet at buffer / tag end
            }
#if 0
            /***************************************************************/
            /*  continue scanning for attriutes on next line if not tag end*/
            /*  This does not work for constructs such as                  */
            /*                                                             */
            /*  :hdref refid=diffs                                         */
            /*  .bd to determine if you need to recompile your application.*/
            /*  from docs\doc\gs\intro.gml line 37 f                       */
            /***************************************************************/

            if( *p != '.' ) { //
                if( get_line( true ) ) {
                    p = buff2;
                } else {
                    *p = '\0';
                }
            } else {
                tag_end_found = true;
            }
#else
            if( (*p == '.') || (*p == '\0') ) {
                tag_end_found = true;
            }
#endif
        }

        /*******************************************************************/
        /*  check for missing reqrd attributes                             */
        /*******************************************************************/
        *token_buf = '\0';
        for( ga = ge->attribs; ga != NULL; ga = ga->next ) {// for all attrs
            if( ga->attflags & att_req ) {
                if( !(ga->attflags & att_proc_seen) ) {
                    if( *token_buf != '\0' ) {
                        strcat( token_buf, " '" );
                    } else {
                        strcpy( token_buf, "'" );
                    }
                    strcat( token_buf, ga->name );
                    strcat( token_buf, "' " );
                }
            }
        }
        if( *token_buf != '\0' ) {      // some req attr missing
            char        linestr[MAX_L_AS_STR];

        // the errmsg in wgml 4.0 is wrong, it shows the macroname, not tag.
// ****ERROR**** SC--047: For the tag '@willi', the required attribute(s)
//                       'muss2'
//                       'muss'
//                       have not been specified

            processed = false;
            err_count++;
            g_err( err_att_req, ge->name, token_buf );
            if( input_cbs->fmflags & II_macro ) {
                ultoa( input_cbs->s.m->lineno, linestr, 10 );
                g_info( inf_mac_line, linestr, input_cbs->s.m->mac->name );
            } else {
                ultoa( input_cbs->s.f->lineno, linestr, 10 );
                g_info( inf_file_line, linestr, input_cbs->s.f->filename );
            }
            show_include_stack();
        }

        if( *p == '.' ) {               // does text follow tag end
            if( strlen( p + 1 ) > 0 ) {
                if( ge->tagflags & tag_texterr ) { // no text allowed
                    tag_text_err( ge->name );
                    processed = false;
                }
            } else {
                if( ge->tagflags & tag_textreq ) {  // reqrd text missing
                    tag_text_req_err( ge->name );
                    processed = false;
                }
            }
            strcpy( token_buf, p + 1 );
            rc = add_symvar( &loc_dict, "_", token_buf, no_subscript, local_var );
            p += strlen( token_buf );
        }

        scan_start = p + 1;             // all processed
        /*******************************************************************/
        /*  add standard symbols to dict                                   */
        /*******************************************************************/

        rc = add_symvar( &loc_dict, "_tag", ge->name, no_subscript, local_var );
        ge->usecount++;
        sprintf( longwork, "%d", ge->usecount );
        rc = add_symvar( &loc_dict, "_n", longwork, no_subscript, local_var );


        add_macro_cb_entry( me, ge );   // prepare GML macro as input
        input_cbs->local_dict = loc_dict;
        inc_inc_level();                // start new include level
        if( ge->tagflags & tag_cont ) {   // +++++++++++++++++++ TBD trial
            post_space = 0;
            ProcFlags.ct = true;
        }

        if( input_cbs->fmflags & II_research && GlobalFlags.firstpass ) {
            print_sym_dict( input_cbs->local_dict );
        }
    } else {                            // user-defined tag has no attributes
        if( ge->tagflags & tag_texterr ) {  // no text allowed
            // '.' or CW_sep_char immediately after the tag does not count as text
            if( (*p == '.') || (*p == CW_sep_char ) ) {
                p++;
            }
            while( *p == ' ' ) {        // spaces don't count as text
                p++;
            }
            if( *p ) {                  // text found
                tag_text_err( ge->name );
                processed = false;
                return( processed );
            }
        }
        if( ge->tagflags & tag_textreq ) {  // text is required
            // per wgml 4.0 behavior
            if( *p == CW_sep_char ) {
                processed = false;
                return( processed );
            }
            // '.' immediately after the tag does not count as text
            if( *p == '.' ) {
                p++;
            }
            while( *p == ' ' ) {        // spaces don't count as text
                p++;
            }
            if( !*p ) {                 // no text found
                tag_text_req_err( ge->name );
                processed = false;
                return( processed );
            }
        }
        // per wgml 4.0 behavior
        if( *p == CW_sep_char ) {
            processed = false;
            return( processed );
        }
        // '.' immediately after the tag is not passed to the macro
        if( *p == '.' ) {
            p++;
        }
        strcpy( token_buf, p );
        rc = add_symvar( &loc_dict, "_", token_buf, no_subscript, local_var );
        p += strlen( token_buf );

        scan_start = p + 1;             // all processed
        /*******************************************************************/
        /*  add standard symbols to dict                                   */
        /*******************************************************************/

        rc = add_symvar( &loc_dict, "_tag", ge->name, no_subscript, local_var );
        ge->usecount++;
        sprintf( longwork, "%d", ge->usecount );
        rc = add_symvar( &loc_dict, "_n", longwork, no_subscript, local_var );


        add_macro_cb_entry( me, ge );   // prepare GML macro as input
        input_cbs->local_dict = loc_dict;
        inc_inc_level();                // start new include level
        if( ge->tagflags & tag_cont ) { // +++++++++++++++++++ TBD trial
            post_space = 0;
            ProcFlags.ct = true;
        }

        if( input_cbs->fmflags & II_research && GlobalFlags.firstpass ) {
            print_sym_dict( input_cbs->local_dict );
        }
    }

    return( processed );
}
Ejemplo n.º 9
0
int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Usage: %s width height\n", argv[0]);
        return 0;
    }
    int width = atoi(argv[1]);
    int height = atoi(argv[2]);
    if (width <= 0) {
        printf("Width must be larger than 0.\n");
        return 0;
    }
    if (width >= 7) {
        printf("Width must be less than 7.\n");
        return 0;
    }
    if (height <= 0) {
        printf("Height must be larger than 0.\n");
        return 0;
    }
    if (height >= 6) {
        printf("Height must be less than 6.\n");
        return 0;
    }

    state s_ = (state) {rectangle(width, height), 0, 0, 0, 0};
    state *s = &s_;

    dict d_;
    dict *d = &d_;

    size_t max_k = max_key(s);
    init_dict(d, max_k);

    size_t key_min = ~0;
    size_t key_max = 0;

    size_t total_legal = 0;
    for (size_t k = 0; k < max_k; k++) {
        if (!from_key(s, k)){
            continue;
        }
        total_legal++;
        canonize(s);
        size_t key = to_key(s);
        add_key(d, key);
        if (key < key_min) {
            key_min = key;
        }
        if (key > key_max) {
            key_max = key;
        }
    }
    resize_dict(d, key_max);
    finalize_dict(d);
    size_t num_states = num_keys(d);

    printf("Total legal positions %zu\n", total_legal);
    printf("Total unique positions %zu\n", num_states);

    node_value *base_nodes = (node_value*) malloc(num_states * sizeof(node_value));
    node_value *pass_nodes = (node_value*) malloc(num_states * sizeof(node_value));
    value_t *leaf_nodes = (value_t*) malloc(num_states * sizeof(value_t));

    lin_dict ko_ld_ = (lin_dict) {0, 0, 0, NULL};
    lin_dict *ko_ld = &ko_ld_;

    state child_;
    state *child = &child_;
    size_t child_key;
    size_t key = key_min;
    for (size_t i = 0; i < num_states; i++) {
        assert(from_key(s, key));
        value_t score = liberty_score(s);
        leaf_nodes[i] = score;
        pass_nodes[i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        base_nodes[i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        for (int j = 0; j < STATE_SIZE; j++) {
            *child = *s;
            if (make_move(child, 1UL << j)) {
                if (child->ko) {
                    canonize(child);
                    child_key = to_key(child) * STATE_SIZE + bitscan(child->ko);
                    add_lin_key(ko_ld, child_key);
                }
            }
        }
        key = next_key(d, key);
    }

    finalize_lin_dict(ko_ld);

    node_value *ko_nodes = (node_value*) malloc(ko_ld->num_keys * sizeof(node_value));
    printf("Unique positions with ko %zu\n", ko_ld->num_keys);

    for (size_t i = 0; i < ko_ld->num_keys; i++) {
        ko_nodes[i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
    }

    #ifndef PRELOAD
    printf("Negamax with Chinese rules.\n");
    iterate(
        d, ko_ld,
        base_nodes, pass_nodes, ko_nodes, leaf_nodes,
        s, key_min, 0
    );
    #endif

    char dir_name[16];
    sprintf(dir_name, "%dx%d", width, height);
    struct stat sb;
    if (stat(dir_name, &sb) == -1) {
        mkdir(dir_name, 0700);
    }
    assert(chdir(dir_name) == 0);
    FILE *f;

    #ifndef PRELOAD
    f = fopen("d_slots.dat", "wb");
    fwrite((void*) d->slots, sizeof(slot_t), d->num_slots, f);
    fclose(f);
    f = fopen("d_checkpoints.dat", "wb");
    fwrite((void*) d->checkpoints, sizeof(size_t), (d->num_slots >> 4) + 1, f);
    fclose(f);
    f = fopen("ko_ld_keys.dat", "wb");
    fwrite((void*) ko_ld->keys, sizeof(size_t), ko_ld->num_keys, f);
    fclose(f);

    f = fopen("base_nodes.dat", "wb");
    fwrite((void*) base_nodes, sizeof(node_value), num_states, f);
    fclose(f);
    f = fopen("pass_nodes.dat", "wb");
    fwrite((void*) pass_nodes, sizeof(node_value), num_states, f);
    fclose(f);
    f = fopen("leaf_nodes.dat", "wb");
    fwrite((void*) leaf_nodes, sizeof(value_t), num_states, f);
    fclose(f);
    f = fopen("ko_nodes.dat", "wb");
    fwrite((void*) ko_nodes, sizeof(node_value), ko_ld->num_keys, f);
    fclose(f);
    #endif

    #ifdef PRELOAD
    f = fopen("base_nodes.dat", "rb");
    fread((void*) base_nodes, sizeof(node_value), num_states, f);
    fclose(f);
    f = fopen("pass_nodes.dat", "rb");
    fread((void*) pass_nodes, sizeof(node_value), num_states, f);
    fclose(f);
    f = fopen("leaf_nodes.dat", "rb");
    fread((void*) leaf_nodes, sizeof(value_t), num_states, f);
    fclose(f);
    f = fopen("ko_nodes.dat", "rb");
    fread((void*) ko_nodes, sizeof(node_value), ko_ld->num_keys, f);
    fclose(f);
    #endif

    // Japanese leaf state calculation.
    state new_s_;
    state *new_s = &new_s_;
    key = key_min;
    for (size_t i = 0; i < num_states; i++) {
        assert(from_key(s, key));
        stones_t empty = s->playing_area & ~(s->player | s->opponent);

        *new_s = *s;
        endstate(
            d, ko_ld,
            base_nodes, pass_nodes, ko_nodes,
            new_s, base_nodes[i], 0, 1
        );

        stones_t player_controlled = new_s->player | liberties(new_s->player, new_s->playing_area & ~new_s->opponent);
        stones_t opponent_controlled = new_s->opponent | liberties(new_s->opponent, new_s->playing_area & ~new_s->player);
        value_t score = popcount(player_controlled & empty) - popcount(opponent_controlled & empty);
        score += 2 * (popcount(player_controlled & s->opponent) - popcount(opponent_controlled & s->player));
        leaf_nodes[i] = score;

        *new_s = *s;
        endstate(
            d, ko_ld,
            base_nodes, pass_nodes, ko_nodes,
            new_s, base_nodes[i], 0, 0
        );

        player_controlled = new_s->player | liberties(new_s->player, new_s->playing_area & ~new_s->opponent);
        opponent_controlled = new_s->opponent | liberties(new_s->opponent, new_s->playing_area & ~new_s->player);
        score = popcount(player_controlled & empty) - popcount(opponent_controlled & empty);
        score += 2 * (popcount(player_controlled & s->opponent) - popcount(opponent_controlled & s->player));
        leaf_nodes[i] += score;

        key = next_key(d, key);
    }

    // Clear the rest of the tree.
    for (size_t i = 0; i < num_states; i++) {
        pass_nodes[i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        base_nodes[i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
    }
    for (size_t i = 0; i < ko_ld->num_keys; i++) {
        ko_nodes[i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
    }

    printf("Negamax with Japanese rules.\n");
    iterate(
        d, ko_ld,
        base_nodes, pass_nodes, ko_nodes, leaf_nodes,
        s, key_min, 1
    );

    f = fopen("base_nodes_j.dat", "wb");
    fwrite((void*) base_nodes, sizeof(node_value), num_states, f);
    fclose(f);
    f = fopen("pass_nodes_j.dat", "wb");
    fwrite((void*) pass_nodes, sizeof(node_value), num_states, f);
    fclose(f);
    f = fopen("leaf_nodes_j.dat", "wb");
    fwrite((void*) leaf_nodes, sizeof(value_t), num_states, f);
    fclose(f);
    f = fopen("ko_nodes_j.dat", "wb");
    fwrite((void*) ko_nodes, sizeof(node_value), ko_ld->num_keys, f);
    fclose(f);

    return 0;
}
Ejemplo n.º 10
0
int main(int argc, char **argv) {
  FILE *output_file,*code_file, *report_file;
  char char_input, ch;
  int state,i;
  int nrGroup,length,code_aux;
  char buffer[DICT_MAX_SIZE], aux[DICT_MAX_SIZE];
  dictionary_t dict;
  char *word, *previous_word;
  int first;
  


  if(argc < 2) {
    printf("Usage.\n");
    printf("  %s <coded file> [<dictionary file>]\n",argv[0]);
    exit(-1);
  }

    
    
  filename=get_filename(argv[1]);
  
  //printf("filename (%s)\n",filename);

  strcpy(input_filename,argv[1]);
  
  strcpy(output_filename,filename);
  strcat(output_filename,".dout");

  strcpy(report_filename,filename);
  strcat(report_filename,".drel");
  
  
  init_dict(&dict);
  
  if(argc == 3) 
  {
    have_dictionary=1;
    filename_dictionary=argv[2];
    init_dictionary_from_file(argv[2],&dict);
  }
  else
  {
    have_dictionary=0; 
    init_dictionary_with_ASCII_table(&dict);
  }

  //print_dictionary(&dict);
  
  
  
  // le arquivo codificado
  code_file = fopen(argv[1],"r");
  if (code_file == NULL) {
    printf("Error opening coded file %s.\n",argv[1]);
  }
  
  
  output_file = fopen(output_filename,"w");
  if (output_file == NULL) {
    printf("Error opening coded file output.txt.\n");
  }  
  state=C_GROUP;
  char_input = fgetc(code_file);
  nrGroup=0;
  length=0;
  code_aux=0;
  i=0;  
  first=1;
  cont_0=0;
  cont_1=0;
  while(char_input != EOF) 
  { 
    if(char_input=='1')
        cont_1++;
    else
        cont_0++;
        
    if(state==C_GROUP)
    {
        if(char_input=='1')
            nrGroup=nrGroup+ (int)pow(2,7-i);
            
        if(i==7)
        {
            state=C_LENGTH;
            i=-1;
        }
    }
    else if(state==C_LENGTH)
    {
        if(char_input=='1')
            length=length+ (int)pow(2,7-i);
            
        if(i==7)
        {
            state=C_CODES;
            i=-1;
        }
    }
    else if(state==C_CODES)
    {
        if(char_input=='1')
            code_aux=code_aux+ (int)pow(2,length-1-i);
    
        if(i==(length-1))
        {
            if(code_aux<size_dictionary(&dict))
	        {
		        word=search_in_dictionary(code_aux,&dict);
		        if(first==1)
		        { 
                    printf("(%s)",word);
                    fprintf(output_file, "%s",word);
			        first=0;
			        previous_word=word;
		        }
		        else
		        {
                    printf("(%s)",word);
                    fprintf(output_file, "%s",word);
			        buffer[0]=word[0];
			        buffer[1]='\0';
			        aux[0]='\0';
			        strcat(aux,previous_word);
			        strcat(aux, buffer);
			        insert_in_dictionary(aux,&dict);
			        previous_word=word;
		        }
            }
	        else
	        {
  
			    buffer[0]=word[0];
			    buffer[1]='\0';
			    strcat(previous_word, buffer);

        		insert_in_dictionary(previous_word,&dict);
			    previous_word=word;
                printf("(%s)",previous_word);
                fprintf(output_file, "%s",previous_word);
                }

                i=-1;
                code_aux=0;
            }
    }
    
    
    char_input = fgetc(code_file);
    i++;
  }


  printf("\ngroup number: %d\n",nrGroup);  
  printf("code length: %d\n",length); 
  fclose(output_file); 

  report_generate(argv[1],"output.dout");
  return 0;
  
}
Ejemplo n.º 11
0
int decode_reg(char *s) {
	if (!initialized)
		init_dict();
	return getval(s);
}
Ejemplo n.º 12
0
int main(void)
{
    int i;
    char x;
    struct dec dec;
    char * tok;
    char key[4];

    if (0) {
        for (i=0; i<cipher_length; ++i) {
            printf("%c", lowercase(cipher[i]));
        }
        printf("\n");

        dec_init(&dec, cipher, cipher_length, "aaa", 3);
        while (0 != (x = dec_read(&dec))) {
            printf("%c", lowercase(x));
        }
        printf("\n");

        /* tokenizer. */
        dec_init(&dec, cipher, cipher_length, "aab", 3);
        while (NULL != (tok = dec_token(&dec))) {
            printf("%s   -> sig: %llu\n", tok, sign_word(tok));
        }

        return 0;
    }

    /* key generator */
    double max_score, curr_score;
    char max_key[4];
    init_dict("/usr/share/dict/words");
    key[3] = (char)0;
    for (key[0]='a'; key[0] <= 'z'; ++key[0])
        for (key[1]='a'; key[1] <= 'z'; ++key[1])
            for (key[2]='a'; key[2] <= 'z'; ++key[2]) {

                if (1) {
                    curr_score = score(key);
                    if (verbose)
                        printf("key: %s  score: %.6lf\n", key, curr_score);
                    if (curr_score > max_score)
                    {
                        max_score = curr_score;
                        memcpy(max_key, key, 4);
                        if (verbose)
                        {
                            printf("\n\n----- new max -- key: %s ---- score: %lf ----\n", max_key, max_score);
                            dec_init(&dec, cipher, cipher_length, max_key, 3);
                            while (0 != (x = dec_read(&dec))) {
                                printf("%c", lowercase(x));
                            }
                            printf("\n\n\n");
                            usleep(250000);
                        }
                    }
                }
                if (0) {
                    if (satisfies(key)) {
                        printf("good_key: %s\n", key);
                        fprintf(stderr, "good_key: %s\n", key);
                    } else {
                        printf("bad_key: %s\n", key);
                    }
                }
            }
    printf("\n\n------- key: %s ---- score: %lf ----\n", max_key, max_score);
    int sum = 0;
    dec_init(&dec, cipher, cipher_length, max_key, 3);
    while (0 != (x = dec_read(&dec))) {
        sum += x;
        printf("%c", x);
    }
    printf("\n\n\n");
    printf("sum: %d\n", sum);

    return 0;
}
Ejemplo n.º 13
0
LRESULT CALLBACK SpellerDlgHandler( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam )
{
	SPELLEROBJ * st;
	char szFileName [256];
	
	st = (SPELLEROBJ *) actobject;
    if ((st==NULL)||(st->type!=OB_SPELLER)) return(FALSE);

	switch( message )
	{
		case WM_INITDIALOG:
			
			SetDlgItemInt(hDlg, IDC_SWITCHTIME,st->speed,0);
			SetDlgItemInt(hDlg, IDC_IDLETIME,st->idle,0);
			SetDlgItemInt(hDlg, IDC_PRESSTIME,st->press,0);
			SetDlgItemInt(hDlg, IDC_WORDCOUNT,st->wordcount,0);

			SetDlgItemText(hDlg, IDC_WORDFILE,st->wordfile);
			SetDlgItemText(hDlg,IDC_DICTFILE,st->dictfile);

			CheckDlgButton(hDlg, IDC_AUTOLEARN, st->autolearn);
			CheckDlgButton(hDlg, IDC_DIRECTSEND, st->directsend);

			SendDlgItemMessage( hDlg, IDC_MODECOMBO, CB_ADDSTRING, 0,(LPARAM) "Automatic Switching") ;
			SendDlgItemMessage( hDlg, IDC_MODECOMBO, CB_ADDSTRING, 0,(LPARAM) "Paddle + Joystick-Button") ;
			SendDlgItemMessage( hDlg, IDC_MODECOMBO, CB_ADDSTRING, 0,(LPARAM) "Joystick (2-Directions)") ;
			SendDlgItemMessage( hDlg, IDC_MODECOMBO, CB_SETCURSEL, st->mode, 0L ) ;
			return TRUE;
	
		case WM_CLOSE:
				EndDialog(hDlg, LOWORD(wParam));
				return TRUE;
			break;
		case WM_COMMAND:
			switch (LOWORD(wParam)) 
			{ 
			
				case IDC_AUTOLEARN:
					st->autolearn=IsDlgButtonChecked(hDlg,IDC_AUTOLEARN);
					break;
				case IDC_DIRECTSEND:
					st->directsend=IsDlgButtonChecked(hDlg,IDC_DIRECTSEND);
					break;
				case IDC_SWITCHTIME:
					st->speed=GetDlgItemInt(hDlg,IDC_SWITCHTIME,NULL,0);
					break;
				case IDC_IDLETIME:
					st->idle=GetDlgItemInt(hDlg,IDC_IDLETIME,NULL,0);
					break;
				case IDC_PRESSTIME:
					st->press=GetDlgItemInt(hDlg,IDC_PRESSTIME,NULL,0);
					break;
				case IDC_DICTFILE:
					GetDlgItemText(hDlg,IDC_DICTFILE,st->dictfile,256);
					break;
				case IDC_LEARN:
					GetDlgItemText(hDlg, IDC_NEWWORDS,st->word,sizeof(st->word));
					st->learn_words();
					SetDlgItemText(hDlg, IDC_NEWWORDS,"");
					strcpy(st->word,"");
					SetDlgItemInt(hDlg, IDC_WORDCOUNT,st->wordcount,0);
					break;
				case IDC_IMPORTLIST:
					  strcpy(szFileName,GLOBAL.resourcepath);
 				      strcat(szFileName,"dictionary\\*.txt");
					  if (open_file_dlg(hDlg, szFileName, FT_TXT, OPEN_LOAD)) 
					  {
						if (!import_words(st, szFileName))
							report_error("Could not import Word list");
						else 
						{
							strcpy(st->wordfile,szFileName);
							SetDlgItemText(hDlg, IDC_WORDFILE,st->wordfile);
							SetDlgItemInt(hDlg, IDC_WORDCOUNT,st->wordcount,0);
						}

					  } else report_error("Could not open File");
					break;
				case IDC_LOADDICT:
					
						strcpy(szFileName,GLOBAL.resourcepath);
 						strcat(szFileName,"dictionary\\*.dic");
						if (open_file_dlg(hDlg, szFileName, FT_DIC, OPEN_LOAD)) 
							st->load_dictionary(szFileName);
					break;

				case IDC_SAVEDICT:

					if (strlen(st->dictfile)>=7) strcpy(szFileName,st->dictfile);
						else
						{
							strcpy(szFileName,GLOBAL.resourcepath);
 							strcat(szFileName,"dictionary\\*.dic");
						}

						if (open_file_dlg(hDlg, szFileName, FT_DIC, OPEN_SAVE)) 
						    st->save_dictionary(szFileName);
					
					break;
				case IDC_CLEARDICT:
					 init_dict(st);
					 SetDlgItemInt(hDlg, IDC_WORDCOUNT,st->wordcount,0);
					 break;

				case IDC_EXPORTLIST: 
					break;


				case IDC_MODECOMBO:
					if (HIWORD(wParam)==CBN_SELCHANGE)
						st->mode=SendMessage(GetDlgItem(hDlg, IDC_MODECOMBO), CB_GETCURSEL , 0, 0);
						switch (st->mode)
						{
							case 0: st->selections=st->entries; break;
							case 1: st->selections=st->entries; break;
							case 2: st->selections=st->entries; break;
						}
				break;

			}
			return TRUE;
			
		
		case WM_SIZE:
		case WM_MOVE:  update_toolbox_position(hDlg);
		case WM_PAINT:
//			color_button(GetDlgItem(hDlg,IDC_SELECTCOLOR),st->color);
		break;
	}
    return FALSE;
}
Ejemplo n.º 14
0
int main(int argc, char *argv[]) {
    #ifdef TEST
        test();
        return 0;
    #endif
    #ifdef REPAIR
        repair(argc, argv);
        return 0;
    #endif
    #ifdef UPGRADE
        upgrade(argc, argv);
        return 0;
    #endif

    int load_sol = 0;
    int resume_sol = 0;
    if (strcmp(argv[argc - 1], "load") == 0) {
        load_sol = 1;
        argc--;
    }
    if (strcmp(argv[argc - 1], "resume") == 0) {
        resume_sol = 1;
        argc--;
    }
    parse_args(argc - 1, argv + 1);

    int width = board_width;
    int height = board_height;
    if (board_width >= 10) {
        fprintf(stderr, "Width must be less than 10.\n");
        exit(EXIT_FAILURE);
    }
    if (board_height >= 8) {
        fprintf(stderr, "Height must be less than 8.\n");
        exit(EXIT_FAILURE);
    }

    #include "tsumego.c"

    state base_state_;
    state *base_state = &base_state_;

    char sol_name[64] = "unknown";
    char temp_filename[128];
    char filename[128];
    if (board_width > 0) {
        *base_state = (state) {rectangle(width, height), 0, 0, 0, 0};
        sprintf(sol_name, "%dx%d", width, height);
    }
    else {
        int i;
        int found = 0;

        for (i = 0; tsumego_infos[i].name; ++i) {
            if (!strcmp(tsumego_name, tsumego_infos[i].name)) {
                *base_state = *(tsumego_infos[i].state);
                strcpy(sol_name, tsumego_name);
                found = 1;
                break;
            }
        }
        if (!found) {
            fprintf(stderr, "unknown tsumego: `%s'\n", tsumego_name);
            exit(EXIT_FAILURE);
        }
    }
    base_state->ko_threats = ko_threats;

    sprintf(temp_filename, "%s_temp.dat", sol_name);


    state_info si_;
    state_info *si = &si_;
    init_state(base_state, si);

    if (si->color_symmetry) {
        num_layers = 2 * abs(base_state->ko_threats) + 1;
    }
    else if (num_layers <= 0) {
        num_layers = abs(base_state->ko_threats) + 1;
    }
    else {
        assert(num_layers >= abs(base_state->ko_threats) + 1);
    }

    print_state(base_state);
    for (int i = 0; i < si->num_external; i++) {
        print_stones(si->externals[i]);
    }
    printf(
        "width=%d height=%d c=%d v=%d h=%d d=%d\n",
        si->width,
        si->height,
        si->color_symmetry,
        si->mirror_v_symmetry,
        si->mirror_h_symmetry,
        si->mirror_d_symmetry
    );

    state s_;
    state *s = &s_;

    dict d_;
    dict *d = &d_;

    solution sol_;
    solution *sol = &sol_;
    sol->base_state = base_state;
    sol->si = si;
    sol->d = d;
    sol->num_layers = num_layers;
    size_t num_states;

    // Re-used at frontend. TODO: Allocate a different pointer.
    state child_;
    state *child = &child_;

    if (load_sol) {
        goto frontend;
    }

    if (resume_sol) {
        char *buffer = file_to_buffer(temp_filename);
        buffer = load_solution(sol, buffer, 1);
        num_states = num_keys(sol->d);
        if (sol->leaf_rule == japanese_double_liberty) {
            goto iterate_capture;
        }
        else {
            goto iterate_japanese;
        }
    }

    size_t k_size = key_size(sol->si);
    if (!sol->si->color_symmetry) {
        k_size *= 2;
    }
    init_dict(sol->d, k_size);

    size_t total_legal = 0;
    for (size_t k = 0; k < k_size; k++) {
        if (!from_key_s(sol, s, k, 0)){
            continue;
        }
        total_legal++;
        size_t layer;
        size_t key = to_key_s(sol, s, &layer);
        assert(layer == 0);
        add_key(sol->d, key);
    }
    finalize_dict(sol->d);
    num_states = num_keys(sol->d);

    printf("Total positions %zu\n", total_legal);
    printf("Total unique positions %zu\n", num_states);

    node_value **base_nodes = (node_value**) malloc(sol->num_layers * sizeof(node_value*));
    for (size_t i = 0; i < sol->num_layers; i++) {
        base_nodes[i] = (node_value*) malloc(num_states * sizeof(node_value));
    }
    value_t *leaf_nodes = (value_t*) malloc(num_states * sizeof(value_t));

    lin_dict ko_ld_ = (lin_dict) {0, 0, 0, NULL};
    lin_dict *ko_ld = &ko_ld_;

    sol->base_nodes = base_nodes;
    sol->leaf_nodes = leaf_nodes;
    sol->ko_ld = ko_ld;

    size_t child_key;
    size_t key = sol->d->min_key;
    for (size_t i = 0; i < num_states; i++) {
        assert(from_key_s(sol, s, key, 0));
        // size_t layer;
        // assert(to_key_s(sol, s, &layer) == key);
        sol->leaf_nodes[i] = 0;
        for (size_t k = 0; k < sol->num_layers; k++) {
            (sol->base_nodes[k])[i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
        for (int j = 0; j < STATE_SIZE; j++) {
            *child = *s;
            int prisoners;
            if (make_move(child, 1ULL << j, &prisoners)) {
                if (target_dead(child)) {
                    continue;
                }
                if (child->ko) {
                    size_t child_layer;
                    child_key = to_key_s(sol, child, &child_layer);
                    add_lin_key(sol->ko_ld, child_key);
                }
            }
        }
        key = next_key(sol->d, key);
    }

    finalize_lin_dict(sol->ko_ld);

    node_value **ko_nodes = (node_value**) malloc(sol->num_layers * sizeof(node_value*));
    sol->ko_nodes = ko_nodes;
    for (size_t i = 0; i < sol->num_layers; i++) {
        sol->ko_nodes[i] = (node_value*) malloc(sol->ko_ld->num_keys * sizeof(node_value));
    }
    printf("Unique positions with ko %zu\n", sol->ko_ld->num_keys);

    for (size_t i = 0; i < sol->ko_ld->num_keys; i++) {
        for (size_t k = 0; k < sol->num_layers; k++) {
            sol->ko_nodes[k][i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
    }

    #ifdef CHINESE
    printf("Negamax with Chinese rules.\n");
    sol->count_prisoners = 0;
    sol->leaf_rule = chinese_liberty;
    iterate(sol, temp_filename);
    #endif

    // NOTE: Capture rules may refuse to kill stones when the needed nakade sacrifices exceed triple the number of stones killed.
    printf("Negamax with capture rules.\n");
    sol->count_prisoners = 1;
    sol->leaf_rule = japanese_double_liberty;
    iterate_capture:
    iterate(sol, temp_filename);

    sprintf(filename, "%s_capture.dat", sol_name);
    FILE *f = fopen(filename, "wb");
    save_solution(sol, f);
    fclose(f);


    calculate_leaves(sol);

    // Clear the rest of the tree.
    for (size_t j = 0; j < sol->num_layers; j++) {
        for (size_t i = 0; i < num_states; i++) {
            sol->base_nodes[j][i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
        for (size_t i = 0; i < sol->ko_ld->num_keys; i++) {
            sol->ko_nodes[j][i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
    }

    printf("Negamax with Japanese rules.\n");
    sol->count_prisoners = 1;
    sol->leaf_rule = precalculated;
    iterate_japanese:
    iterate(sol, temp_filename);

    sprintf(filename, "%s_japanese.dat", sol_name);
    f = fopen(filename, "wb");
    save_solution(sol, f);
    fclose(f);

    frontend:
    if (load_sol) {
        sprintf(filename, "%s_japanese.dat", sol_name);
        char *buffer = file_to_buffer(filename);
        buffer = load_solution(sol, buffer, 1);
    }

    *s = *sol->base_state;

    char coord1;
    int coord2;

    int total_prisoners = 0;
    int turn = 0;

    while (1) {
        size_t layer;
        size_t key = to_key_s(sol, s, &layer);
        node_value v = negamax_node(sol, s, key, layer, 0);
        print_state(s);
        if (turn) {
            print_node((node_value) {total_prisoners - v.high, total_prisoners - v.low, v.high_distance, v.low_distance});
        }
        else {
            print_node((node_value) {total_prisoners + v.low, total_prisoners + v.high, v.low_distance, v.high_distance});
        }
        if (target_dead(s) || s->passes >= 2) {
            break;
        }
        for (int j = -1; j < STATE_SIZE; j++) {
            *child = *s;
            stones_t move;
            if (j == -1){
                move = 0;
            }
            else {
                move = 1ULL << j;
            }
            char c1 = 'A' + (j % WIDTH);
            char c2 = '0' + (j / WIDTH);
            int prisoners;
            if (make_move(child, move, &prisoners)) {
                size_t child_layer;
                size_t child_key = to_key_s(sol, child, &child_layer);
                node_value child_v = negamax_node(sol, child, child_key, child_layer, 0);
                if (sol->count_prisoners) {
                    if (child_v.low > VALUE_MIN && child_v.low < VALUE_MAX) {
                        child_v.low = child_v.low - prisoners;
                    }
                    if (child_v.high > VALUE_MIN && child_v.high < VALUE_MAX) {
                        child_v.high = child_v.high - prisoners;
                    }
                }
                if (move) {
                    printf("%c%c", c1, c2);
                }
                else {
                    printf("pass");
                }
                if (-child_v.high == v.low) {
                    printf("-");
                    if (child_v.high_distance + 1 == v.low_distance) {
                        printf("L");
                    }
                    else {
                        printf("l");
                    }
                }
                if (-child_v.high == v.low) {
                    printf("-");
                    if (child_v.low_distance + 1 == v.high_distance) {
                        printf("H");
                    }
                    else {
                        printf("h");
                    }
                }
                printf(" ");
            }
        }
        printf("\n");
        printf("Enter coordinates:\n");
        assert(scanf("%c %d", &coord1, &coord2));
        int c;
        while ((c = getchar()) != '\n' && c != EOF);
        coord1 = tolower(coord1) - 'a';
        stones_t move;
        if (coord1 < 0 || coord1 >= WIDTH) {
            // printf("%d, %d\n", coord1, coord2);
            move = 0;
        }
        else {
            move = 1ULL << (coord1 + V_SHIFT * coord2);
        }
        int prisoners;
        if (make_move(s, move, &prisoners)) {
            if (turn) {
                total_prisoners -= prisoners;
            }
            else {
                total_prisoners += prisoners;
            }
            turn = !turn;
        }
    }

    return 0;
}