Пример #1
0
int main(int argc, char** argv)
{
  if(argc != 2)
  {
    fprintf(stderr,"Dude.  I need a string command line arg.");
    return -1;
  }

  if (palindrome(clean(argv[1])))
    printf("Palindrome\n");
  else
    printf("Not a Palindrome\n");
  return 0;
}
Пример #2
0
int main()
{
	char str[50] = {'0'};
	int len  = 0;
	
	fgets(str, sizeof(str), stdin);
	len = strlen(str);
	
	/*Remove the last char*/
	str[len-1] = '\0';
	len = len - 1;

	palindrome(str, len);
	return 0;
}
Пример #3
0
int palindrome(char* buf, int len){
    if(DEBUG)
        printf("%d %s\n",len, buf);

    if(len == 0)
        return true;
    if(len == 1)
        return true;

    if(*buf == *(buf+len-1)){
        return palindrome(buf+1, len-2);
    }else{
        return false;
    }
}
Пример #4
0
int main(){
int N=1000;
int i;
for(i=N;i>0;i--){
if(palindrome(i)==1){
    if(prime(i)==1){
	printf("%d", i);
	break;		
	}	
    printf("palindrome \n");
   }
}

return 0;
}
Пример #5
0
int main()
{
  int PAL=0;
  int n,a,b;
  for(int i=999;i>=900;--i)
    {
      for(int j=990;j>=900;j=j-11)
	{
	  n=i*j;
	  if(palindrome(n))
	    PAL=std::max(PAL,n);
	}
    }
  printf("%d",PAL);
  return 0;
}
Пример #6
0
vector<vector<string> > partition(string s) {
    vector<vector<string> >vec;
    int len=s.size();
    int **dp=new int*[len];
    for(int i=0;i<len;i++)
        dp[i]=new int[len];
    for(int i=0;i<len;i++){
        for(int j=0;j<len;j++){
            if(i>j) dp[i][j]=0;
            else dp[i][j]=palindrome(i, j, s);
        }
    }
    vector<string>st;
    gernerate(vec, st, 0, len, s,dp);
    return vec;
    }
Пример #7
0
void testCase(void) {
    assert (palindrome("kayak.") == TRUE);
    assert (palindrome("puzzlequest") == FALSE);
    assert (palindrome("is addo odd as i?") == TRUE);
    assert (palindrome("canoe") == FALSE);
    assert (palindrome("eevee") == TRUE);
    assert (palindrome("awesome") == FALSE);
    //ADD MORE TESTS
 
    printf ("All tests passed, you are Awesome!\n");
}
Пример #8
0
int main(){
    char buf[101];
    int len;
    int count;

    count = 0;

    while(scanf("%s", buf)==1){
        len = strlen(buf);
        if(palindrome(buf, len)){
            count ++;
        }
    }
    printf("%d\n", count);

    return 0;
}
Пример #9
0
int
main(void)
{
	int i, j, tmp, max_palindrome = 0;
 
	for (i = 999; i > 0; i--) {
		for (j = 999; j >= i; j--) {
			tmp = i * j;
			if (tmp > max_palindrome && palindrome(tmp)) {
				max_palindrome = tmp;
			}
		}
	}
 
	printf("%d\n", max_palindrome);
	return 0;
}
Пример #10
0
int main(int argc, char *argv[])
{
	if(argc<2){
                        printf("Vous n'avez pas entre de chaîne de caractères\n");
                        return 0;

        }

	
	if(palindrome(argv[1])){
		printf("C'est un palindrome\n");
		return 1;	
	}

	printf("Ce n'est pas un palindrome\n");
	return 0;
}
Пример #11
0
int main()
{
	int t , i;
	FILE *fp;
	char buff[1000];
	if ((fp = fopen("input.txt", "r")) == NULL) return 0; /* start File IO */
	fscanf(fp, "%d", &t); /* read data number */
	while (t--) 
	{
		fscanf(fp, "%s", buff); /* read data */
		i = 0;
		while (buff[i] != NULL) i++; /* counting alphabat number*/
		printf("%d\n", palindrome(buff, 0, i - 1)); /* start cheking palindrome */
	}
	fclose(fp); /* close File IO */
	return 1;
}
Пример #12
0
product_t *get_palindrome_product(int from, int to)
{
   product_t *result = malloc(sizeof(product_t));
   if (result == NULL) {
      fprintf(stderr, "Memory error!\n");
      return NULL;
   }

   result->error[MAXERR - 1] = '\0';
   result->smallest = INT_MAX;
   result->largest = INT_MIN;
   result->factors_lg = NULL;
   result->factors_sm = NULL;

   if (from > to) {
      snprintf(result->error, MAXERR - 1,
               "invalid input: min is %i and max is %i", from, to);
      return result;
   }

   int i, k, n;
   int err = 0;
   for (i = from; i <= to; i++)
      for (k = i; k <= to; k++)
         if (palindrome(n = i * k)) {
            if (n <= result->smallest) {
               result->smallest = n;
               err = addfactors(&result->factors_sm, i, k);
            } else if (n >= result->largest) {
               result->largest = n;
               err = addfactors(&result->factors_lg, i, k);
            }
            if (err) {
               free(result);
               return NULL;
            }
         }

   if ((result->smallest == INT_MAX) || (result->largest == INT_MIN)) {
      snprintf(result->error, MAXERR - 1,
               "no palindrome with factors in the range %i to %i", from, to);
      return result;
   }
   return result;
}
Пример #13
0
int main()
{
     int n, d, i, res, aux;
     printf("Ingrese numero N ");
     scanf("%d",&n);
     d = 1;
     i = 1;
     while(i <= n)
     {
	     res = palindrome(d);
	     if(res == 1)
	     {
		     printf("Es perfecto %d\n",d);
		     i++;
	     }
	     d++;
     }
}
Пример #14
0
static const char *
password_check(const char *old, const char *newval, const struct passwd *pwdp)
{
	const char *msg;
	char *newmono, *wrapped;
	int lenwrap;

	if (strcmp(newval, old) == 0)
		return "no change";
	if (simple(newval))
		return "too simple";

	msg = NULL;
	newmono = str_lower(bb_xstrdup(newval));
	lenwrap = strlen(old);
	wrapped = (char *) xmalloc(lenwrap * 2 + 1);
	str_lower(strcpy(wrapped, old));

	if (palindrome(newmono))
		msg = "a palindrome";

	else if (strcmp(wrapped, newmono) == 0)
		msg = "case changes only";

	else if (similiar(wrapped, newmono))
		msg = "too similiar";

	else if ( strstr(newval, pwdp->pw_name) )
		msg = "username in password";

	else {
		safe_strncpy(wrapped + lenwrap, wrapped, lenwrap + 1);
		if (strstr(wrapped, newmono))
			msg = "rotated";
	}

	memset(newmono, 0, strlen(newmono));
	memset(wrapped, 0, lenwrap * 2);
	free(newmono);
	free(wrapped);

	return msg;
}
Пример #15
0
int main(void)
{
    char string[100] = { "" };

    puts("Say something nice, preferably a palindrome ;-) :");
    fgets(string, 100, stdin);

    int buffer = palindrome(string);

    switch (buffer) {
    case 0:
        puts("\nNope, definetly not a palindrome!\n");

    case 1:
        puts("Nice palindrome!\n");
    }

    return 0;
}
Пример #16
0
int main(int argc, char* argv[])
{
	char str1[] = "abcdefgabcdefg111";
	char str2[] = "abcdefggfedcba";
	char str3[] = "abcdefgfedcba";
	char str4[] = "11111111";
	char str5[] = "11111112";
	char str6[] = "31111112";
	char str7[] = "3";
	char str8[] = "";

	printf("%d\n", palindrome(str1));
	printf("%d\n", palindrome(str2));
	printf("%d\n", palindrome(str3));
	printf("%d\n", palindrome(str4));
	printf("%d\n", palindrome(str5));
	printf("%d\n", palindrome(str6));
	printf("%d\n", palindrome(str7));
	printf("%d\n", palindrome(str8));

	return 1;
}
Пример #17
0
bool palindrome(const char a[], int first, int last)
{
    if(first == last || first > last)
    {
        //stop condition
        return true;
    }
    else
    {
        //got correct for an incorrect solution before.
        if(a[first] == a[last])
        {
			//checks all the position not all from 1 to n-1 like last time.
            return true&&palindrome(a,first+1,last-1);
        }
        else
        {
            return false;
        }
    }
}
Пример #18
0
int main()
{
    palindrome();
    return 0 ;
}
void is_palindrome(char* str) {
  char* resolved = palindrome(str);
  assert_string_equal(resolved, "Yes");
  free(resolved);  
}
Пример #20
0
void is_palindrome(char* str) {
  char* answer = palindrome(str);
  assert_string_equal(answer, "Yes");
  free(answer);
}
Пример #21
0
void not_palindrome(char* str) {
  char* answer = palindrome(str);
  assert_string_equal(answer, "No");
  free(answer);
}
Пример #22
0
int main(void)
{
    int answer = palindrome();
    printf("%d\n", answer);
    return 0;
}
Пример #23
0
static int score_llr_pop(
  MOTYPE mtype,				/* type of model */
  int w,				/* width of motif */
  DATASET *dataset,			/* the dataset */
  int iseq,				/* sequence number of starting point */
  int ioff,				/* sequence offset of starting point */
  char *eseq,				/* integer encoded subsequence */
  char *name,				/* name of sequence */
  int n_nsites0,			/* number of nsites0 values to try */
  int n_maxima,				/* number of local maxima */
  P_PROB maxima,			/* sorted local maxima indices */
  double *col_scores,			/* column scores for last start point */
  S_POINT s_points[]			/* array of starting points */
)
{
  int i, j, k, i_nsites0;
  int next_seq;				/* index of next subsequence to align */
  int n_starts = 0;			/* number of nsites0 tried */
  int nsites0;				/* starting nsites rounded down */
  int alength = dataset->alength;	/* lenght of alphabet */
  double *back = dataset->back;		/* background frequencies */
  SAMPLE **samples = dataset->samples;	/* the sequences */
  double counts[MAXSITE][MAXALPH];	/* array to hold observed counts */
  double wN;				/* weighted number of sites */
  double log_pop;			/* log product of p-values */
  double min_ic = dataset->min_ic;	/* min. per-column IC */

  /* initialize letter counts to 0 */
  wN = 0;				/* weighted number of sites */
  for (i=0; i<w; i++) for (j=0; j<alength; j++) { counts[i][j] = 0; }

  /* calculate the product of p-values of information content
     of the top nsite0 probability positions 
  */
  for (i_nsites0=0, next_seq=0; i_nsites0 < n_nsites0; i_nsites0++) {

    /* don't score this start if not enough maxima found */
    nsites0 = (int) s_points[i_nsites0].nsites0;	/* round down */
    if (n_maxima < nsites0) {
      continue;
    }
    n_starts++;					/* number of nsites0 tried */

    /* Align the next highest probability sites 
	1) count the number of occurrences of each letter in each column 
	   of the motif and, 
        2) compute the log likelihood of the sites under the background model
    */
    for (k=next_seq; k<nsites0; k++) {		/* site */
      int jj;
      BOOLEAN ic = maxima[k].ic;		/* on - strand */
      int y = maxima[k].y;			/* position of site */
      SAMPLE *s = samples[maxima[k].x];		/* sequence */
      int off = ic ? s->length-w-y : y;		/* - strand offset from rgt. */
      char *res = ic ? s->resic+off : s->res+off;	/* integer sequence */
      double sw = s->sw;			/* sequence weight */
      //
      // TLB: Note that log_not_o contains Pr(site) scaled to have max=1
      // when called from subseq7() but not when called from discretize().
      //
      // Why not revert to not_o[y] here?  TLB: Because the other one works
      // much better, although its kind of a hack.
      //double esw = sw * s->not_o[y];		// Pr(site not overlapped)
      //
      // FIXME: We are assumming that priors are always symmetrical here.
      double esw = sw * INT_DELOG(s->log_not_o[y]);	// Pr(site not overlapped) * Pr(site) 
      wN += esw;				/* total sequence wgt */

      /* residue counts */
      for (j=0; j<w; j++) {			/* position in sequence */
        int c = res[j];
        if (c < alength) {			/* normal letter */
          counts[j][c] += esw;
	} else {				/* 'X' : esw * back[letter] */
          for (jj=0; jj<alength; jj++) counts[j][jj] += esw * back[jj];
	}
        
      } /* position */

    } /* site */
    next_seq = k;				/* next site to align */
    
    /* 
      For DNA palindromes, combine the counts in symmetrically opposing columns
    */
    if (dataset->pal) palindrome(counts, counts, w, alength);

    // Updated on 13-12-06: Only calculate objective function score if the
    // current s_point is supposed to be evaluated:
    if (s_points[i_nsites0].evaluate) {
      /* 
	convert COUNTS to FREQUENCIES and calculate log likelihood ratio
      */
      log_pop = 0;				/* product of p-values */
      for (i=0; i<w; i++) {			/* position in site */
	double llr = 0;				/* log-like-ratio of column */
	double log_pv;				/* log of column p-value */
	double ic;

	/* compute log likelihood for position i */
	for (j=0; j<alength; j++) {		/* letter */
	  double f = wN ? counts[i][j] / wN : 1; 	/* observed letter frequency */
	  double p = back[j];			/* backgrnd letter frequency */
	  double log_f = LOGL(f);
	  double log_p = LOGL(p);
	  double llr_ij = (f&&p) ? f*(log_f - log_p) : 0;
	  llr += llr_ij;
	} /* letter */
	RND(llr/0.6934, RNDDIG, ic);		/* info content in bits */
	llr *= wN;				/* convert entropy to ll */ 
	RND(llr, RNDDIG, llr);			/* round to RNDDIG places */
	log_pv = get_llr_pv(llr, wN, 1, LLR_RANGE, 1.0, alength, back); 
	if (ic < min_ic) log_pv = 0; 		/* ignore low ic columns */

	if (dataset->use_llr) {
	  // Using llr instead of pop:
	  col_scores[i] = log_pv;
	  log_pop -= llr;
	} else {
	  log_pop += col_scores[i] = log_pv;
	}
      } /* position in site */
      RND(log_pop, RNDDIG, log_pop);

      /* print the start sequence and other stuff */
      if (TRACE) {
	if (eseq) {
	  char seq[MAXSITE+1];
	  r2seq(seq, eseq, w);
	  fprintf(stdout, 
	    "( %3d %3d ) ( %*.*s ) %.*s logpop %8.3f nsites0 %6d\n",
	    iseq+1, ioff+1, MSN, MSN, name, w, seq, -log_pop, nsites0);
	} else {
	  fprintf(stdout, 
	    "l_off %3d w %d logpop %8.3f nsites0 %6d\n",
	    iseq, w, -log_pop, nsites0);
	}
      }

      /* save the best start */
      if (-log_pop > s_points[i_nsites0].score) {
	/* Save the starting point and offset so we can re-calculate
	   eseq later. */
	s_points[i_nsites0].iseq = iseq;
	s_points[i_nsites0].ioff = ioff;
	s_points[i_nsites0].e_cons0 = eseq;
	s_points[i_nsites0].wgt_nsites = wN;
	s_points[i_nsites0].score = -log_pop;
      }
    } // Evaluating only if told to do so.
  } /* nsites0 */

  return n_starts;
} /* score_llr_pop */
Пример #24
0
int main (int argc, char **argv)
{
    int listenfd, connfd, n, len = 0;
    socklen_t clilen;
    char buf[MAXLINE];
    struct sockaddr_in cliaddr, servaddr;

//creation of the socket
    listenfd = socket (AF_INET, SOCK_STREAM, 0);

//preparation of the socket address
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(SERV_PORT);

    bind (listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

    listen (listenfd, LISTENQ);

    printf("%s\n","Server running...waiting for connections.");

    for ( ; ; )
    {

        clilen = sizeof(cliaddr);
        connfd = accept (listenfd, (struct sockaddr *) &cliaddr, &clilen);
        printf("%s\n","Received request...");

        while ( (n = recv(connfd, buf, MAXLINE,0)) > 0)
        {
            printf("%s","String received from and resent to the client:");
            puts(buf);
            buf[n] = '\0';
            int result = palindrome(buf);
            char end[] = {'s','t','o','p','\0'};


            if( (strlen(buf)-1) == 4){
              if ( buf[0] == 's' && buf[1] == 't' && buf[2] == 'o' && buf[3] == 'p' ){

                //printf("stopped...");
                send(connfd, end, sizeof(end), 0);
                close(connfd);
                close (listenfd);
                exit(1);
              }

            }


            char no[] = "Not a palindrome";
            char yes[] = "Palindrome";

            if ( result == false){
                send(connfd, no, sizeof(no), 0);
            }

            else{
               send(connfd, yes, sizeof(yes), 0);
            }
          //  send(connfd, buf, n, 0);
        }



        if (n < 0)
        {
            perror("Read error");
            exit(1);
        }
        close(connfd);

    }
//close listening socket
    close (listenfd);
}
Пример #25
0
void main()
{
    int i,j,ch,ch2,count,tmp,vowels,consonants,y=0,x=0,k=0,n,n2,minIndex=0,maxIndex=0,max=0,min=0,l;
    char s[200],s1[200],substr[100][100]= {0},str[25][25],temp[25],*ptr;
    for(;;) {
        printf("\nEnter the choice\n");
        printf("0. Exit\n");
        printf("1. Implement library functions on a string\n");
        printf("2. Calculate string length in user defined function\n");
        printf("3. concat using user defined function\n");
        printf("4. lowercase conversion using user defined function\n");
        printf("5. uppercase conversion using user defined function\n");
        printf("6. count vowels and consonants using user defined function\n");
        printf("7. substring search using user defined function\n");
        printf("8. compare strings using user defined function\n");
        printf("9. find the largest and smallest word in a string\n");
        printf("10.check palindromic string using user defined function\n");
        printf("11.reverse a string using user defined function\n");
        printf("12.remove duplicate characters in a string using user defined function\n");
        printf("13.copy one string into another string using user defined function\n");
        printf("14.swap 2 string using user defined function\n");
        printf("15.search for a string in a user given sentence\n");
        printf("16.sort n number of words in alphabetical order\n");
        printf("17.print abbreviations of an input string\n");
        scanf("%d",&ch);
        if(ch==0) {
            printf("Terminated\n");
            break;
        }
        else {
            switch(ch) {
            case 1:
                for(;;)
                {
                    printf("0.Return to main menu\n");
                    printf("1.Length of string\n");
                    printf("2.Concate two strings\n");
                    printf("3.Convert string to lowercase\n");
                    printf("4.Convert string to uppercase\n");
                    scanf("%d",&ch2);
                    if(ch2==0)
                        break;
                    else
                    {
                        printf("Enter the String\n");
                        scanf("%s",s);
			switch(ch2)
                        {
			case 1:
                            l=strlen(s);
                            printf("String length of s = %d\n",l);
                            break;
                        case 2:
                            printf("Enter 2nd string\n");
                            scanf("%s",s1);
                            strcat(s,s1);
                            printf("Concatenated String is --> %s\n",s);
                            break;
                        case 3:
                            for(i=0; i<l; i++)
                            {
                                tmp=tolower(s[i]);
                                s[i]=tmp;
                            }
                            printf("Lowercase string = %s\n",s);
                            break;
                        case 4:
                            for(i=0; i<l; i++)
                            {
                                tmp=toupper(s[i]);
                                s[i]=tmp;
                            }
                            printf("Uppercase string = %s\n",s);
                            break;
                        default:
                            printf("Wrong Input\n");
                            break;
                        }
                    }
                }
                break;
            case 2:
                printf("Enter the string\n");
                scanf("%s",s);
                y = length(s);
                printf("Length of %s= %d\n", s, y);
                break;
            case 3:
                printf("Enter the 1st string\n");
                scanf("%s",s);
                printf("Enter the 2nd String\n");
                scanf("%s",s1);
                concat(s, s1);
                printf("The concated string is --> %s", s);
                break;
            case 4:
                printf("Enter the string\n");
                scanf("%s",s);
                lower_string(s);
                printf("String in lower case is \"%s\"\n",s);
                break;
            case 5:
                printf("Enter the string\n");
                scanf("%s",s);
                upper_string(s);
                printf("String in upper case is \"%s\"\n",s);
                break;
            case 6:
                printf("Enter a string with a tab at the end\n");
                scanf("%[^\t]",s);
                vowels=consonants=0;
                for(i=0; s[i]!='\0'; ++i)
                {
                    if(s[i]=='a' || s[i]=='e' || s[i]=='i' ||
                            s[i]=='o' || s[i]=='u' || s[i]=='A' ||
                            s[i]=='E' || s[i]=='I' || s[i]=='O' ||
                            s[i]=='U')
                        ++vowels;
                    else if((s[i]>='a'&& s[i]<='z') || (s[i]>='A'&& s[i]<='Z'))
                        ++consonants;
                }
                printf("Vowels: %d\n",vowels);
                printf("Consonants: %d\n",consonants);
                break;
            case 7:
                printf("Enter a string with a tab at the end\n");
                scanf("%[^\t]",s);
                printf("Enter the substring to search\n");
                scanf("%s",s1);
                for(i=0; s[i]!='\0'; i++)
                {
                    j=0;
                    if(s[i]==s1[j])
                    {
                        tmp=i+1;
                        while(s[i]==s1[j])
                        {
                            i++;
                            j++;
                        }
                        if(s1[j]=='\0')
                            printf("The substring is present in given string at position %d\n",tmp);
                        else
                        {
                            i=tmp;
                            tmp=0;
                        }
                    }
                }
                if(tmp==0)
                    printf("The substring is not present in given string\n");
                break;
            case 8:
                printf("Enter the 1st string\n");
                scanf("%s",s);
                printf("Enter the 2nd string\n");
                scanf("%s",s1);
                n2 = compare(s, s1);
                if (n2 == 0)
                    printf("Both are same\n");
                else if (n2 > 0)
                    printf("1st>2nd\n");
                else
                    printf("1st<2nd\n");
                break;
            case 9:
                i=0;
                k=0;
                printf("Enter a string with a tab at the end\n");
                scanf("%[^\t]",s);
                while(s[k]!='\0')
                {
                    j=0;
                    while(s[k]!=' '&&s[k]!='\0')
                    {
                        substr[i][j]=s[k];
                        k++;
                        j++;
                    }
                    substr[i][j]='\0';
                    i++;
                    if(s[k]!='\0')
                        k++;
                }
                int len=i;
                max=length(substr[0]);
                min=length(substr[0]);
                for(i=0; i<len; i++)
                {
                    y=length(substr[i]);
                    if(y>max)
                    {
                        max=y;
                        maxIndex=i;
                    }
                    if(y<min)
                    {
                        min=y;
                        minIndex=i;
                    }
                }
                printf("Largest Word is --> %s\nSmallest word is --> %s\n",substr[maxIndex],substr[minIndex]);
                break;
            case 10:
                printf("Enter the string\n");
                scanf("%s",s);
                x = palindrome(s);
                if (x == 0)
                    printf("\nNot a palindrome");
                else
                    printf("\nA palindrome");
                break;
            case 11:
                printf("Enter the string\n");
                scanf("%s",s);
                reverse(s);
                printf("The reversed string is --> %s", s);
                break;
            case 12:
                printf("Enter the string\n");
                scanf("%s",s);
                removeDuplicates(s);
                printf("String after removing duplicates: %s\n", s);
                break;
            case 13:
                printf("Enter the 1st string\n");
                scanf("%s",s);
                printf("Enter the 2nd string\n");
                scanf("%s",s1);
                copy(s, s1);
                printf("\nResultant s = %s", s);
                break;
            case 14:
                printf("Enter the 1st string\n");
                scanf("%s",s);
                printf("Enter the 2nd string\n");
                scanf("%s",s1);
                swap(s, s1);
                printf("s is %s, s1 is %s\n", s, s1);
                break;
            case 15:
                printf("press 7 please\n");
                break;
            case 16:
                printf("How many words do you want to enter?\n");
                scanf("%d",&count);
                printf("Enter the sentence\n");
                for(i=0; i<count; i++)
                    scanf("%s",str[i]);
                for(i=0; i<=count; i++)
                    for(j=i+1; j<=count; j++) {
                        if(strcmp(str[i],str[j])>0) {
                            strcpy(temp,str[i]);
                            strcpy(str[i],str[j]);
                            strcpy(str[j],temp);
                        }
                    }
                printf("The sentence sorted alphabetically is --> ");
                for(i=0; i<=count; i++)
                    printf("%s ",str[i]);
                break;
            case 17:
                printf("Enter a string with a tab at the end\n");
                scanf("%[^\t]",s);
                l=strlen(s);
                ptr=s;
                printf("%c",*(ptr+1));
                for(i=1; i<l; i++)
                {
                    if(*(ptr+i-1)==' ')
                        printf("%c",*(ptr+i));
                }
                break;
            default:
                printf("Invalid choice");
                break;
            }
        }
    }
}
Пример #26
0
int main ( int argc, char *argv[] )
{

	int primeCheckStorage;
	int reverseNumStorage;
	int palindromeCheckStorage;
	int input = 0;
	int x = 0;
	//int y = 0;
	//int z = 0;
	int primeFlag = 0;
	int reverseFlag = 0;
	int palidromeFlag = 0;
	int readFlag = 0;
	int writeFlag = 0;


	int output;
	//char *stringToParse;
	FILE *fp = NULL;


/*
 * SECTION 2 FLAG RAISING
 * For this section we are taking the command line arguments and  going through them
 * and checking to see which ones were entered by the user
 * Additionally if one was entered by the user we will raise its appropriate flag to call associated
 * code and functions form it
 */
	for(int i = 0 ; i < argc; i++)
	{
		if(argv[i][0] == '-' && argv[i][1] == 'h')
		{
			options(); //here we are checking if there is a -h giving it precedence and breaking out of the loop
			primeFlag = 0;
			reverseFlag = 0;
			palidromeFlag = 0;
			readFlag = 0;
			writeFlag = 0;
			break;
		}

		if(argv[i][0] == '-' && argv[i][1] == 'p')
		{
			primeFlag = 1;
		}

		if(argv[i][0] == '-' && argv[i][1] == 'r')
		{
			reverseFlag = 1;
		}

		if(argv[i][0] == '-' && argv[i][1] == 'd')
		{
			palidromeFlag = 1;
		}

		if(argv[i][0] == '-' && argv[i][1] == 'f')// get file name and READ from File
		{
			//check to see if there is a file name
			if( argv[i+1] == NULL)
			{
				printf("expecting argument following -f \n");
			}
			//copy file name
			inFile = argv[i+1];

			fp = fopen(inFile, "r");

			if(!fp)
			{
				printf("Can not open %s \n" , inFile);
				return 0;
			}
			else
			//read data from file
			fclose(fp);

			readFlag = 1;
		}

		if(argv[i][0] == '-' && argv[i][1] == 'o')
		{
			//check to see if there is a file name
			if( argv[i+1] == NULL)
			{
				printf("expecting argument following -o \n");
			}

			//copy file name
			outFile = argv[i+1];

			fp = fopen(outFile, "w");

			//write data from user to file

			if(!fp)
			{
				printf("Can not open %s \n" , outFile);
				return 0;
				}
				else
					//write to file
				fclose(fp);

			writeFlag = 1;
		}



	}
	/*
	 * For this section we will be checking if there were 3 commands entered or 2 of each command OR
	 * both of the read/write commands entered
	 * IF ANY of these conditions occur we throw and error message to the user.
	 */

	if((primeFlag == 1 && reverseFlag == 1 && palidromeFlag == 1) ||
			(primeFlag ==1 && reverseFlag == 1)|| (primeFlag == 1 && palidromeFlag == 1) ||
			(reverseFlag ==1 && palidromeFlag == 1))
	{
		printf("Please use only 1 command at a time. \n");
		printf("Usage: ./prog [-p/-r/-d] –f filename –o filename \n");


		//we are going to reset the flags to stop program flow.
		primeFlag = 0;
		reverseFlag = 0;
		palidromeFlag = 0;
		readFlag = 0;
		writeFlag = 0;

/*
 * SECION 3
 * This section of code is where all my manipulations on the files and the user input
 * happens.  WE are also check certain conditions to differentate whether or not we
 * want to take user input or input to a file or write to a file
 */

	}
	else if((primeFlag == 1) && (readFlag == 0))
	{

		printf("You have selected finding a prime number. \n");
		printf("Please enter a positive integer:  \n");
		scanf("%d", &x);

		primeCheckStorage = checkPrime(x);

		if(primeCheckStorage == -1)
		{
			printf("Please enter a positive integer. \n");
		}
		else if(primeCheckStorage == 1)
		{
			printf("Number %d is a prime number. \n", x);
		}
		else
		{
			printf("Number %d is NOT a prime number. \n", x);
		}

	}
	else if((reverseFlag == 1)&& (readFlag == 0))
	{
		printf("You have selected reversing a number. \n");
		printf("Please enter the integer you wish to reverse: \n");
		scanf("%d", &input);

		reverseNumStorage = reverseNum(input);
		printf("Reverse of %d is %d. \n", input, reverseNumStorage);
	}
	else if((palidromeFlag == 1) && (readFlag == 0))
	{
		printf("You have selected checking if a number is  a palindrome. \n");
		printf("Please enter the integer you wish to check: \n");
		scanf("%d" , &input);
		palindromeCheckStorage = palindrome(input);
		if( palindromeCheckStorage == 1)
		{
			printf("The number %d is a palindrome \n", input);
		}
		else
		{
			printf("The number %d is NOT a palidrome \n", input);
		}


	}

	if((readFlag == 1) && (primeFlag == 1))
	{
		fp = fopen(inFile, "r");

		fscanf(fp, "%d", &output);

			//if else (call the approbate function)
			if(primeFlag == 1)
			{

				primeCheckStorage = checkPrime(output);

				if(primeCheckStorage == -1)
				{
					printf("Please enter a positive integer. \n");
				}
				else if(primeCheckStorage == 1)
				{
					printf("Number %d is a prime number. \n", output);
				}
				else
				{
				printf("Number %d is NOT a prime number. \n", output);
				}
			}

			fclose(fp);

	}
	if((readFlag == 1) && (reverseFlag == 1)) //reverse the number
	{
		fp = fopen(inFile, "r");

		fscanf(fp, "%d", &output);

		reverseNumStorage = reverseNum(output);

		printf("Reverse of %d is %d. \n", output, reverseNumStorage);
	}
	if((readFlag == 1) && (palidromeFlag == 1)) //expcitely dictate this condition
	{
		fp = fopen(inFile, "r");

		fscanf(fp, "%d", &output);
		palindromeCheckStorage = palindrome(output); //get the num from the function

		if( palindromeCheckStorage == 1)
		{
			printf("The number %d is a palindrome. \n",output );

		}
		else
		{
			printf("The number %d is NOT a palindrome. \n", output);
		}
	}

	if(writeFlag == 1)
	{
		fp = fopen(outFile , "w");

		if(!fp)
		{
			puts("cannot open data file!");
			return 0;
		}

		//get data from user
		printf("Please enter a number to write to the file");
		scanf("%s", inputData);
		fprintf(fp, "%s ",inputData); // write to the file

	}



}
Пример #27
0
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;
}
void main()
{
    char str[20];
    scanf("%s",str); 
    printf("%d",palindrome(str));
}
void not_palindrome(char* str) {
  char* resolved = palindrome(str);
  assert_string_equal(resolved, "No");
  free(resolved);  
}
Пример #30
0
void *largestPalindrome(node *T, char *word, int size, node *P){
	int i, j, k, pos, test;
	char *largest, *aux_largest, *aux_word;
	node *pointer, *aux;
	
	P = Trie();
	
	if (!(largest = malloc(sizeof(char)*size))){
		printf("Falta de memória");
		exit(1);
	}
	
	if (!(aux_largest = malloc(sizeof(char)*size))){
		printf("Falta de memória");
		exit(1);
	}
	
	if (!(aux_word = malloc(sizeof(char)*size))){
		printf("Falta de memória");
		exit(1);
	}
	
	largest[0] = '\0';
	pointer = T;

	for (i = 0; i < size; i++){
		aux = T;
		pos = position(word[i]);
		j = 0;
		k = i;

		while(aux->key[pos]){
			aux_largest[j] = word[k];
			j++;
			k++;
			aux = aux->key[pos];
			pos = position(word[k]);
		}
		
		aux_largest[j] = '\0';

		while (j > 0){
			if (!palindrome(aux_largest)){
				j--;
				aux_largest[j] = '\0';
			} else {
				break;
			}
		}
		
		if (lenght(aux_largest) > lenght(largest)){
			copy(largest, aux_largest); // largest = aux_largest
			/* Caso tenha uma palavra maior que anterior
			 * limpar a trie para conter somente as maiores palíndromas */
			emptyTree(P);
		}
		
		copy(aux_word, aux_largest);
		insert(P, aux_word);
	}

	printf("-- Maiores palindormas:");
	printTree(P, lenght(largest));
}