예제 #1
0
파일: test.c 프로젝트: Hi-Spy/loho
int get_string_value(char *string, int bit)
{
 	if(string == NULL)
	{
		return -1;
	}
	
	char *p = string;
	
	if(strlen(p) < bit)
	{
		printf("error error .............\n");
		return -1;
	}

	p = p + bit - 1;
		
	if(is_valid_number(*p))
	{
		if(*p <= '9')
		{
			return (*p - '0');
		}
		else if(*p <= 'F')
		{
			return 10 + (*p - 'A');
		}
		else 
		{
			return 10 + (*p - 'a');
		}
	}
	return -1;

}	
예제 #2
0
파일: main.c 프로젝트: Qpaq/42Projects
int		main(int argc, char **argv)
{
	char	**sudo_tb;
	int		index;
	int		index_malloc;

	index_malloc = 0;
	if (argc == 10 && is_valid_number(argv) == 1)
	{
		index = 0;
		sudo_tb = (char**)malloc(9 * sizeof(char*));
		while (index_malloc < 9)
		{
			sudo_tb[index_malloc] = (char*)malloc(10 * sizeof(char));
			index_malloc++;
		}
		copy_sudo(argv, sudo_tb);
		if (is_valid_char(argv) == 1 && sudoku(sudo_tb, 0))
			print_sudoku(sudo_tb);
		else
			write(1, "Erreur\n", 7);
		free_grid(sudo_tb);
	}
	else
		write(1, "Errer\n", 7);
	return (0);
}
예제 #3
0
TokenType token_type(const string &str)
{
  if (is_valid_operator(str))
    return operator_symbol;

  if (is_valid_operator_as_function(str))
    return op_function;

  if (is_valid_identifier(str))
    return plain_identifier;

  if (is_valid_symbol(str))
    return symbol;

  if (is_valid_label(str))
    return label;

  if (is_valid_number(str))
    return number;

  if (is_valid_type_name(str))
    return type_id;

  if (is_valid_type_var(str))
    return type_var;

  if (is_valid_builtin(str))
    return builtin;

  if (is_valid_string_lit(str))
    return string_lit;
    
  return invalid;
}
예제 #4
0
파일: sort0.c 프로젝트: DmytroLebediev/cs50
int main(int argc, string argv[])
{
    if (argc < 2)
    {
        printf("usage: ./sort0 number [number] ...\n");
        return 1;
    }

    int length = argc - 1;
    int numbers[length];

    for (int i = 0, j = 1; i < length; i++, j++)
    {
        if (is_valid_number(argv[j]))
        {
            int number = atoi(argv[j]);
            numbers[i] = number;
        }
        else
        {
            printf("wrong input: [%d] = %s\n",
                j,
                argv[j]);
            return 2;
        }
    }

    print_array(length, numbers);
    bubble_sort(length, numbers);
    print_array(length, numbers);

    return 0;
}
예제 #5
0
// Aplly Operation
bool Expression::apply_operation(Term _t1, Term _t2, Term _op, Term &_rst) {
    if (is_operator(_op)) {
        int result, v1, v2;
        if (!is_valid_number(_t1) || !is_valid_number(_t2)) {
            set_error(8);
            return false;
        }
        get_int_number(_t1, v1);
        get_int_number(_t2, v2);
        switch (_op.value[0]) {
            case '^':
                result = std::pow(v1, v2);
                break;
            case '*':
                result = v1 * v2;
                break;
            case '/':
                if (v2 == 0) {
                    set_error(7);
                    return false;
                }
                result = v1 / v2;
                break;
            case '%':
                if (v2 == 0) {
                    set_error(7);
                    return false;
                }
                result = v1 % v2;
                break;
            case '+':
                result = v1 + v2;
                break;
            case '-':
                result = v1 - v2;
                break;
        }
        _rst.value = std::to_string(result);
        if (!is_valid_number(_rst)) {
            set_error(8);
            return false;
        }
        return true;
    }

    return false;
}
예제 #6
0
cDialog :: cDialog( double nposx, double nposy, string nidentifier, string ntext, DialogType dialogtype, Uint8 nmax_length /* = 20  */, unsigned int nmin_width )
: cSprite( NULL, nposx, nposy )
{
	stext = NULL;
	
	if( is_valid_number( ntext.c_str() ) ) 
	{
		text_number = string_to_int( ntext );
	}
	else
	{
		text_number = 0;
	}

	identifier.reserve( nidentifier.length() );
	identifier = nidentifier;
	text = ntext;
	
	type = dialogtype;

	boarder_in = 2;
	boarder_out = 2;
	text_area = 1;

	min_width = nmin_width;
	
	if( type != DIALOG_ONLY_NUMBERS )
	{
		if( nmax_length < ntext.length() ) 
		{
			max_length = ntext.length();
		}
		else
		{
			max_length = nmax_length;
		}

		text.reserve( max_length );
	}
	else
	{
		if( nmax_length < text_number ) 
		{
			max_length = text_number;
		}
		else
		{
			max_length = nmax_length;
		}

		text.reserve( 20 );
	}
	
	SetColors( colorDarkBlue, colorBlue, colorWhite, colorBlack );
	Update_Boarders();
	Update_Text();
}
예제 #7
0
int main(int argc, const char * argv[]) {
	char test[420];
	printf("Enter a smallish number: ");
	scanf("%[^\n]%*c", test);
	if (is_valid_int(test))
		modtest(to_int(test));
	printf("\n%d\t%d\n",is_valid_int(test),to_int(test));
	printf("%d\t%g\n",is_valid_number(test),to_double(test));
	return 420;
}
예제 #8
0
int main(int argc, string argv[])
{
    if (argc < 2)
    {
        printf("usage: ./sort0 number [number] ...\n");
        return 1;
    }

    int length = argc - 1;
    int numbers[length];

    for (int i = 0, j = 1; i < length; i++, j++)
    {
        if (is_valid_number(argv[j]))
        {
            int number = atoi(argv[j]);
            numbers[i] = number;
        }
        else
        {
            printf("wrong input: [%d] = %s\n", j, argv[j]);
            return 2;
        }
    }

    print_array(length, numbers);
    bubble_sort(length, numbers);
    print_array(length, numbers);

    printf("what number are you looking for?\n");
    int number = get_int();
    printf(search(number, length, numbers)
        ? "found\n" : "not found\n");

    return 0;
}
예제 #9
0
파일: types.c 프로젝트: awhillas/comp9021
/* Process array definition */
bool process_array(int sentence_end) {

    if (is_valid_variable(words[current_position])) {
        
        // Start definition string
        if (!append_to_definition(words[current_position]))
            return false;
        
        if (current_position == sentence_end)
            return false;
        if (++current_position != sentence_end 
            && strcmp(words[current_position], w_of) != 0)
            return false;
        if (++current_position != sentence_end 
            && !is_valid_number(words[current_position]))
            return false;
            
        if (atoi(words[current_position]) > 1
            && strcmp(words[current_position+1], w_data) != 0)
            return false;
            
        if (atoi(words[current_position]) == 1
            && strcmp(words[current_position+1], w_datum) != 0)
            return false;
            
        // Insert array number
        if (!append_to_definition("["))
            return false;
        if (!append_to_definition(words[current_position]))
            return false;
        if (!append_to_definition("]"))
            return false;
        
        ++current_position;
        return true;
    }
    
    if (current_position == sentence_end)
        return false;
    if (current_position != sentence_end 
        && strcmp(words[current_position], w_of) != 0)
        return false;
    if (++current_position != sentence_end 
        && !is_valid_number(words[current_position]))
        return false;
        
    if (atoi(words[current_position]) > 1
        && strcmp(words[current_position+1], w_data) != 0)
        return false;
        
    if (atoi(words[current_position]) == 1
        && strcmp(words[current_position+1], w_datum) != 0)
        return false;
        
    // Insert array number
    if (!append_to_definition("["))
        return false;
    if (!append_to_definition(words[current_position]))
        return false;
    if (!append_to_definition("]"))
        return false;
    
    ++current_position;
    return true;
}
예제 #10
0
void cDialog :: Get_Focus( void )
{
	bool focus = 1;
	string text_old = text;

	int minwidth_old = min_width;

	pDialogManager->Update();
	
	boxRGBA( screen, 0, 0, screen->w, screen->h , 0, 0, 0, 32 );

	SDL_EnableUNICODE( 1 );
	SDL_EnableKeyRepeat( SDL_DEFAULT_REPEAT_DELAY, 50 );

	while( focus )
	{
		Update();

		if( rect.w < min_width ) 
		{
			rect.w = min_width;
		}
		else if( rect.w > min_width ) 
		{
			min_width = rect.w;
		}	

		SDL_Flip( screen );

		while( SDL_PollEvent( &event ) )
		{
			keys = SDL_GetKeyState( NULL );

			if( KeyPressed( KEY_ESC) && event.key.keysym.sym != SDLK_BACKSPACE )
			{
				text = text_old;

				focus = 0;
			}
			else if ( KeyPressed( KEY_ENTER ) )
			{
				focus = 0;
			}
			else if( event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_BACKSPACE )
			{
				if( text.length() && type != DIALOG_ONLY_NUMBERS )
				{
					text.erase( text.length() - 1, 1 );
					
					Update_Text();
				}
			}
			else if( event.type == SDL_KEYDOWN && event.key.keysym.sym != SDLK_ESCAPE )
			{
				if( type != DIALOG_ONLY_NUMBERS ) 
				{
					if( event.key.keysym.unicode && text.length() < max_length )
					{
						if( type == DIALOG_ONLY_LETTERS )
						{
							string s;
							s.insert( (string::size_type)0, (string::size_type)1, (char)event.key.keysym.unicode );

							if( !is_valid_number( s ) )
							{
								text.insert( text.length(), s );
							}
						}
						else
						{
							text.insert( text.length(), 1, (char)event.key.keysym.unicode );
						}

						Update_Text();
					}
				}
				else
				{
					 if( KeyPressed( KEY_UP ) )
					 {
						text_number += 1;
					 }
					 else if( KeyPressed( KEY_DOWN ) )
					 {
						text_number -= 1;
					 }
					 else if( KeyPressed( KEY_LEFT ) )
					 {
						text_number -= 10;
					 }
					 else if( KeyPressed( KEY_RIGHT ) )
					 {
						text_number += 10;
					 }
					 else if( event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_PLUS )
					 {
						text_number += 1;
					 }
					 else if( event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_MINUS )
					 {
						text_number -= 1;
					 }
					 else if( event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_PAGEUP )
					 {
						text_number += 10;
					 }
					 else if( event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_PAGEDOWN )
					 {
						text_number -= 10;
					 }

					 if( text_number > max_length )
					 {
						text_number = max_length;
					 }
					 else if( text_number < 0 )
					 {
						text_number = 0;
					 }

					 Update_Text();
				}
			}
		}
		
		Framerate.Update();
	}

	SDL_EnableUNICODE( 0 );
	SDL_EnableKeyRepeat( 0, 0 );

	if( text.compare( text_old ) != 0 ) 
	{
		changed = 1;
	}

	min_width = minwidth_old;
	
	Update_Text();

	Framerate.Reset();
}
예제 #11
0
local void line_minimize
(
  double vect[],
  double direction[],
  double *pval_min,
  double *psave_x0,
  double *psave_a,
  double (*pfunction)(double vect[])
)
{
  double ax,bx,cx,x0,fa,fb,fc,fx0;
  double a,b;
  double old_x0,old_a;
  int code;

  if(wn_conj_direction_debug >= WN_CONJ_DIR_DBG_LINESEARCH)
  {
    printf("start line minimize.\n");
  }

  last_line_function_x_valid = FALSE;

  wn_copy_vect(buffer_vect,vect,num_vars);
  save_vect = vect;
  save_direction = direction;
  save_pfunction = pfunction;

  old_x0 = *psave_x0;
  old_a = *psave_a;

  bx = 0.0;
  fb = *pval_min;
  if(wn_conj_direction_debug >= WN_CONJ_DIR_DBG_ALL)
  {
    printf("First point at %lg, function value = %lg\n", bx, fb);
  }

  if(old_x0 == 0.0)
  {
    old_x0 = 1.0;
  }

  ax = old_x0*wn_random_double_between(0.9,1.1);
  if(wn_conj_direction_debug >= WN_CONJ_DIR_DBG_ALL)
  {
    printf("Second point at %lg (old_x0 = %lg)\n", ax, old_x0);
  }
  fa = line_function(ax);

  if(!(old_a > 0.0))
  {
    goto simple_parabola_fit;
  }

  /* the curvature along a search direction is constant for a 
     quadratic function, therefore, try to use the curvature
     from the last search */
  fit_parabola_2pa(&code,&x0,&b,old_a,ax,fa,bx,fb);
  if(
     (code != WN_SUCCESS)
       ||
     (!(wn_abs(x0)<MAX_EXPAND*wn_abs(old_x0)) && (*psave_x0 != 0.0))
       ||
     too_close(x0, ax) || too_close(x0, bx)
       ||
     !is_valid_number(x0) || !is_valid_number(ax) || !is_valid_number(bx)
    )
  {
    goto simple_parabola_fit;
  }   

  cx = x0;
  if(wn_conj_direction_debug >= WN_CONJ_DIR_DBG_ALL)
  {
    printf("Third point at %lg\n", cx);
  }
  fc = line_function(cx);

  wn_fit_parabola_3p(&code,&a,&x0,&b,ax,fa,bx,fb,cx,fc);

  if((code != WN_SUCCESS)||(!(a > 0.0))||
     (!(wn_abs(x0)<MAX_EXPAND*wn_abs(old_x0))&&(*psave_x0 != 0.0)))
  {
    goto full_linesearch;
  }   

  if(!(b < fb))
  {
    if(wn_conj_direction_debug >= WN_CONJ_DIR_DBG_ALL)
    {
      printf("Doing slow line search (parabola fit returned suspect min value).\n");
    }
    goto full_linesearch;
  }
  if((!(fc < fb))||(!(fc < fa)))
  {
    /* evaluate one more point */
    goto evaluate_x0;
  }

  /* is it economical to evaluate one more point? */
  if((fb-b) <= 1.5*(fb-fc))
  { 
    /* do not evaluate one more point */
    wn_swap(fb,fc,double);
    wn_swap(bx,cx,double);
    goto finish;
  }
  else
  {
    /* evaluate one more point */
    goto evaluate_x0;
  }

simple_parabola_fit:
  if(fa < fb)
  {
    cx = 2.0*ax*wn_random_double_between(0.8,1.2);
  }
  else
  {
    cx = -1.0*ax*wn_random_double_between(0.8,1.2);
  }

  fc = line_function(cx);

  wn_fit_parabola_3p(&code,&a,&x0,&b,ax,fa,bx,fb,cx,fc);

  if((code != WN_SUCCESS)||(!(a > 0.0))||
     (!(wn_abs(x0)<MAX_EXPAND*wn_abs(old_x0))&&(*psave_x0 != 0.0)))
  {

    if(wn_conj_direction_debug >= WN_CONJ_DIR_DBG_ALL)
    {
      printf("Parabola fit failed. Switching to slow line search mode.\n");
    }
    goto full_linesearch;
  }   

evaluate_x0:
  fx0 = line_function(x0);

  if(!(fx0 <= fb))
  {
    if(wn_conj_direction_debug >= WN_CONJ_DIR_DBG_ALL)
    {
      printf("Doing a slow line search because f(x0) is too large (x0 = %lg).\n", x0);
    }
    goto full_linesearch;
  }

  fb = fx0;
  bx = x0;

  if(!(fa <= fc))
  {
    wn_swap(fa,fc,double);
    wn_swap(ax,cx,double);
  }
  if(!(fb <= fa))
  {
    wn_swap(fb,fa,double);
    wn_swap(bx,ax,double);
  }

  goto finish;

full_linesearch: ;

  /*
  printf("now.\n");
  */
  do
  {
    if(ax == bx)
    {
      if(wn_random_bit())
      {
        ax += wn_random_double_between(-1.0,1.0);
        fa = line_function(ax);
      }
      else
      {
        bx += wn_random_double_between(-1.0,1.0);
        fb = line_function(bx);
      }
    }
    if(ax == cx)
    {
      if(wn_random_bit())
      {
        ax += wn_random_double_between(-1.0,1.0);
        fa = line_function(ax);
      }
      else
      {
        cx += wn_random_double_between(-1.0,1.0);
        fc = line_function(cx);
      }
    }
    if(bx == cx)
    {
      if(wn_random_bit())
      {
        bx += wn_random_double_between(-1.0,1.0);
        fb = line_function(bx);
      }
      else
      {
        cx += wn_random_double_between(-1.0,1.0);
        fc = line_function(cx);
      }
    }
  } while((ax == bx)||(ax == cx)||(bx == cx));
  wn_minimize_1d_raw(&code,&fa,&fb,&fc,&ax,&bx,&cx,fb,&line_function,1,20);
  /*
  printf("l = %lf\n",bx);
  */

finish: ;

  /*
  if(show_linesearch)
  {
    printf("ax=%lg,bx=%lg,cx=%lg,old_x0=%lg\n",ax,bx,cx,old_x0);
  }
  */

  wn_copy_vect(vect,buffer_vect,num_vars);

  /* compute *psave_x0 */
  if(wn_abs(bx) < MIN_CONTRACT*wn_abs(old_x0))
  {
    if(bx < 0.0)
    {
      *psave_x0 = -MIN_CONTRACT*wn_abs(old_x0);
    }
    else
    {
      *psave_x0 = MIN_CONTRACT*wn_abs(old_x0);
    }
  }
  else
  {
    *psave_x0 = bx;
  }

  /* compute *psave_a */
  wn_fit_parabola_3p(&code,&a,&x0,&b,ax,fa,bx,fb,cx,fc);

  if((code != WN_SUCCESS)||(!(a > 0.0)))
  {
    *psave_a = 0.0;
  }   
  else
  {
    *psave_a = a;
  }

  if(*pval_min == fb)
  {
    if(wn_conj_direction_debug >= WN_CONJ_DIR_DBG_LINESEARCH)
    {
      printf("finish line minimize.\n");
      fflush(stdout);
    }
    return;  /* do not move if no improvement */
  }

  wn_add_scaled_vect(vect,direction,bx,num_vars);

  *pval_min = fb;

  if(wn_conj_direction_debug >= WN_CONJ_DIR_DBG_LINESEARCH)
  {
    printf("finish line minimize.\n");
    fflush(stdout);
  }
}
예제 #12
0
파일: strings.c 프로젝트: hajelav/programs
int main() {
    /*char c;*/
    int choice;
    int n;
    char str[] = "gee  ks f  or g  ee ks ";
    char path[128];
    char S[128], T[128];
    char *pattern = "-20";
    char str1[32], str2[32];

    char **s;
    /*do {*/

	printf("MENU OPTIONS\n");
	printf("1 -- remove spaces from string\n");
	printf("2-- Check if a given sequence of moves for a robot is circular or not\n");
	printf("3 -- Regex matching problem\n");
	printf("4 -- Palindrome detection with non-alphanumeric characters\n");
	printf("5 -- Normalize the path\n");
	printf("6 -- replace space by percentage20 in a string\n");
	printf("7 -- minimum window substring\n");
	printf("8 -- integer to english words\n");
	printf("9 -- restore IP addresses\n");
	printf("10 -- check if strings are isomorphic\n");
	printf("11 -- function to determine if a string is a valid number without using any built-in function\n");
	printf("12 -- reverse string\n");
	printf("13 -- reverse words in a sentence\n");
	printf("14 -- shortest distance between words\n");
	printf("15 -- shortest distance between words\n");
	
	

	printf("\n");
	printf("Enter your choice\n");
	scanf("%d",&choice);
	switch(choice){
	    case 1:
		removeSpaces(str);
		printf("%s", str);
		break;

	    case 2:
		printf("Enter path\n");
		scanf("%s", path);
		printf("path is circular: %s", checkCircularpath(path)?"yes":"no");
		break;

	    case 4:
		palindrome();
		break;
		
	    case 5:
		printf("Enter path\n");
		fgets(path, 128, stdin);
		printf("Normalized path: %s\n", normalize(path));
		break;

	    case 6:
		memset(path, '\0', 128);
		printf("Enter string\n");
		scanf("%s", path);
		/*gets(path);*/
		replace_spaces(path, pattern);
		printf("%s\n", path);
		break;

	    case 7:

		printf("Enter the string\n");
		scanf("%s", S);
		printf("Enter the pattern\n");
		scanf("%s", T);

		min_window_substring(S, T);
		    break;

	    case 8:
		    /*interger_to_english_words();*/
		    break;

	    case 9:
		    restore_ip_address();
		    break;

	    case 10:
		    printf("Enter strings of equal length\n");
		    printf("Enter string 1\n");
		    scanf("%s", S);
		    printf("Enter string 2\n");
		    scanf("%s", T);
		    printf("Strings are isomorphic : %s\n", isomorphic_strings(S, T)?"Yes":"No");
		    break;

	    case 11:
		    printf("Enter the string\n");
		    scanf(" %[^\n]s", S); //reading a space through scanf
		    /*fgets(stdin, S, sizeof(S));*/
		    printf("Is number : %s\n", is_valid_number(S)?"yes":"no");
		    break;

	    case 12:
		    printf("Enter the string\n");
		    scanf(" %[^\n]s", S);  //make scanf work with spaces  //make scanf work with spaces
		    reverse_string(S, strlen(S));
		    print_string(S, strlen(S));
		    break;
	    case 13:
		    printf("Enter the sentence\n");
		    scanf(" %[^\n]s", S);  //make scanf work with spaces  //make scanf work with spaces
		    /*fgets(S, 128, stdin);*/
		    reverse_words(S);
		    print_string(S, strlen(S));
		    break;

	    case 14:
		    printf("Enter number of words\n");
		    scanf("%d", &n);
		    s = create_2Dchar_array(n, 128);
		    input_2Dchar_array(s, n, 128);

		    printf("enter word 1\n");
		    scanf("%s", str1);
		    printf("enter word 2\n");
		    scanf("%s", str2);
		    printf("Shortest distance between %s and %s : %d\n", str1, str2, shortest_distance(s, n, str1, str2));
		    break;





		    




	    default:
		printf("Invalid option\n");
		break;
	}
	printf("\n\n");
    /*}while((c=getchar())!='q'); */
    return 0;
}
예제 #13
0
// Tokenize
bool Expression::tokenize() {
    bool _was_number = false;
    bool _was_whitespace = false;
    bool _was_opening_parenthesis = false;
    bool _was_closing_parenthesis = false;
    bool _was_operator = false;
    int _parenthesis_diff = 0;
    int _fst_parenthesis = -1;

    Term t1, t2;
    for (auto i(0u); i < m_expr.size(); i++) {
        t2.set(m_expr[i], i);
        bool _is_number = is_number(t2);
        bool _is_operator = is_operator(t2);
        bool _is_opening_parenthesis = is_opening_parenthesis(t2);
        bool _is_closing_parenthesis = is_closing_parenthesis(t2);
        bool _is_parenthesis = (_is_opening_parenthesis || _is_closing_parenthesis);
        bool _is_last_operand = (i == m_expr.size() - 1);
        bool _is_whitespace = (t2.value == " ");
        bool _was_parenthesis = (_was_opening_parenthesis || _was_closing_parenthesis);

        // Verify if the current term is a whitespace
        if (_is_whitespace) {
            _was_whitespace = true;
            if (_is_last_operand) {
                if (_was_number) {
                    m_terms->enqueue(t1);
                    t1.value = "";
                } else if (!_was_closing_parenthesis) {
                    set_error(1, t2.col + 1);
                    return false;
                }
            }
            continue;
        // Verify if the current term is a number
        } else if (_is_number) {
            if ((_was_number && _was_whitespace) || _was_closing_parenthesis) {
                set_error(3, t2.col);
                return false;
            }
            if (_was_number) {
                t1.value += t2.value;
            } else {
                t1.set(t2.value, i);
            }
            if (!is_valid_number(t1)) {
                set_error(0, t1.col);
                return false;
            }
            if (_is_last_operand)
                m_terms->enqueue(t1);
            _was_number = true;
            _was_opening_parenthesis = false;
            _was_closing_parenthesis = false;
            _was_operator = false;
        // Verify if the current term is a operator or parenthesis
        } else if (_is_operator || _is_parenthesis) {
            if (_was_number) {
                m_terms->enqueue(t1);
                t1.value = "";
            }
            _fst_parenthesis = (_parenthesis_diff == 0) ? -1 : _fst_parenthesis;
            if (_is_parenthesis) {
                if (_parenthesis_diff == 0)
                    _fst_parenthesis = t2.col;
                _parenthesis_diff += _is_opening_parenthesis ? 1 : -1;
            }
            if (_parenthesis_diff < 0) {
                set_error(4, t2.col);
                return false;
            }
            if (!_was_number) {
                if (t2.value == "-" && !_was_closing_parenthesis) {
                    t2.is_unary = true;
                } else if (!_is_parenthesis && !_was_parenthesis) {
                    set_error(5, t2.col);
                    return false;
                } else if (_was_operator && _is_closing_parenthesis) {
                    set_error(1, t2.col);
                    return false;
                }
            }
            if (_is_last_operand && !_is_parenthesis) {
                set_error(1, t2.col + 1);
                return false;
            }
            if (_is_opening_parenthesis && _was_closing_parenthesis) {
                set_error(3, t2.col);
                return false;
            }
            if (_is_closing_parenthesis && _was_opening_parenthesis) {
                set_error(1, t2.col);
                return false;
            }
            m_terms->enqueue(t2);
            _was_number = false;
            if (_is_operator) {
                _was_operator = true;
                _was_opening_parenthesis = false;
                _was_closing_parenthesis = false;
            } else {
                _was_operator = false;
                if (_is_opening_parenthesis) {
                    _was_opening_parenthesis = true;
                    _was_closing_parenthesis = false;
                } else {
                    _was_opening_parenthesis = false;
                    _was_closing_parenthesis = true;
                }
            }
        // Invalid Operand
        } else {
            set_error(_was_operator ? 1 : 2, t2.col);
            return false;
        }
        _was_whitespace = false;
    }

    if (_parenthesis_diff != 0) {
        set_error(6, _fst_parenthesis);
        return false;
    }

    return true;
}
예제 #14
0
static void
load_profile(struct profile *p)
{
	FILE    *f;			/* file handler */
	char    line[ED_MAX_LINE_LEN];
	int     lineno = 0;
	int     do_points = 0;
	int     delay_first = -1;
	int i;

	struct	point points[1000]; /* MAX_POINTS_NO */
	int     points_no = 0;

	char *filename = p->filename;
	f = fopen(filename, "r");
	if (f == NULL) {
	    err(EX_UNAVAILABLE, "fopen: %s", filename);
	}


	while (fgets(line, ED_MAX_LINE_LEN, f)) {         /* read commands */
		char *s, *cur = line, *name = NULL, *arg = NULL;

		++lineno;

		/* parse the line */
		while (cur) {
			s = strsep(&cur, ED_SEPARATORS);
			if (s == NULL || *s == '#')
				break;
			if (*s == '\0')
				continue;
			if (arg)
				errx(ED_EFMT("too many arguments"));
			if (name == NULL)
				name = s;
			else
				arg = s;
		}

		if (name == NULL)
			continue;

		if (!strcasecmp(name, ED_TOK_DELAY)) {
		    if (do_points)
			errx(ED_EFMT("duplicated token: %s"), name);
		    delay_first = 1;
		    do_points = 1;
		    continue;
		} else if (!strcasecmp(name, ED_TOK_PROB)) {
		    if (do_points)
			errx(ED_EFMT("duplicated token: %s"), name);
		    delay_first = 0;
		    do_points = 1;
		    continue;
		}
		if (!strcasecmp(name, ED_TOK_PROFILE_NO)) {
			int p_no = atof(arg);
			if (p_no <= 0) {
				p_no = 100;
				printf("invalid interpolation samples, using %d\n",
					 p_no);
			}
			if (p_no > ED_MAX_SAMPLES_NO) {
				p_no = ED_MAX_SAMPLES_NO;
				printf("invalid interpolation samples, using %d\n",
					 p_no);
			}

			p->samples_no = p_no;
		    continue;

		} else if (do_points) {
		    if (!is_valid_number(name) || !is_valid_number(arg))
			errx(ED_EFMT("invalid point found"));
		    if (delay_first) {
			points[points_no].delay = atof(name);
			points[points_no].prob = atof(arg);
		    } else {
			points[points_no].delay = atof(arg);
			points[points_no].prob = atof(name);
		    }
		    if (points[points_no].prob > 1.0)
			errx(ED_EFMT("probability greater than 1.0"));
		    ++points_no;
	/* XXX no more that 1000 */
		    continue;
		} else {
		    errx(ED_EFMT("unrecognised command '%s'"), name);
		}
	}

	for(i=0; i < p->samples_no; i++) {
		p->samples[i] = 666;
	}

	/* This code assume the user define a value of X for the sampling value,
	 * and that:
	 * - the value stored in the emulator structure is X;
	 * - the allocated structure for the samples is X+1;
	 */
	interpolate_samples(points, points_no, p->samples, p->samples_no, filename);

	// User defined samples
	printf("\nLoaded %d points:\n", points_no);
	for(i=0; i < points_no; i++) {
		printf("%f %f\n", points[i].prob, points[i].delay);
	}
	printf("\n");
	printf("The sample value is %d \n", p->samples_no);

}
예제 #15
0
파일: lab9.c 프로젝트: Iiridayn/sample
/*
 * void execute_commands()
 *
 * Processes commands until the QUIT command is entered
 *
 */
void execute_commands() {
  char buffer[MAX_INPUT_STRING];
  int num_chars = 0;

  while ( TRUE ) {
	
	printf( PROMPT );

	scanf("%s", buffer);
	num_chars = strlen(buffer);
	if ( is_valid_number( buffer ) ) {
	  push( atoi(buffer) );
	  continue;
	}

	if ( num_chars > 1 ) {
	  printf( BAD_INPUT_MSG );
	  continue;
	}

	if ( tolower( buffer[0] ) == QUIT ) return;

	/* Remove the TODO_MSG as you implement and test commands */
	switch( tolower( buffer[0] ) ){
	case ADD:
	  add_command();
	  break;
	case SUB:
	  sub_command();
	  break;
	case MULT:
	  mult_command();
	  break;
	case DIV:
	  div_command();
	  break;
	case MOD:
	  mod_command();
	  break;
	case AND:
	  and_command();
	  break;
	case OR:
	  or_command();
	  break;
	case XOR:
	  xor_command();
	  break;
	case NOT:
	  not_command();
	  break;
	case FACTORIAL:
	  factorial_command();
	  break;
	case TOGGLE_HEX:
	  toggle_hex();
	  break;
	case TOGGLE_BUG:
	  toggle_bug();
	  break;
	case PRINT_STACK:
	  print_stack();
	  break;
	case PRINT_TOP:
	  print_top();
	  break;
	case CLEAR:
	  clear_command();
	  break;
	case EXCHANGE:
	  exchange_command();
	  break;
	case POP:
	  pop();
	  break;
	case HELP:
	  help_command();
	  break;
	default:
	  printf( BAD_INPUT_MSG );
	}
  }
}