ClavinJune

c utils

Oct 12th, 2018
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.45 KB | None | 0 0
  1. #include <stdio.h>
  2. int len(char text[]){
  3.     int i;
  4.     for( i = 0 ; text[i] ; ++i );
  5.     return i;
  6. }
  7.  
  8. char upper(char c){
  9.     if( c < 97 || c > 122 ) return c;
  10.     return c-32;
  11. }
  12.  
  13. char lower(char c){
  14.     if( c < 65 || c > 90 ) return c;
  15.     return c+32;
  16. }
  17.  
  18. void sUpper(char text[]){
  19.     int i;
  20.     for( i = 0 ; i < len(text) ; ++i ){
  21.         text[i] = upper(text[i]);
  22.     }
  23. }
  24.  
  25. void sLower(char text[]){
  26.     int i;
  27.     for( i = 0 ; i < len(text) ; ++i ){
  28.         text[i] = lower(text[i]);
  29.     }
  30. }
  31.  
  32. void sReverse(char text[]){
  33.     char output[len(text)];
  34.     int i, idx = len(text);
  35.    
  36.     output[idx--] = '\0';
  37.    
  38.     for( i = 0 ; text[i] ; ++i )
  39.         output[idx--] = text[i];
  40.     for( i = 0 ; text[i] ; ++i )
  41.         text[i] = output[i];
  42. }
  43.  
  44. void sSort(char text[], int reverse){
  45.     //using counting sort
  46.     char output[len(text)];
  47.     int count[256] = {0};
  48.     int i;
  49.    
  50.     for( i = 0 ; text[i] ; ++i )
  51.         ++count[text[i]];
  52.    
  53.     for( i = 1 ; i <= 255 ; ++i )
  54.         count[i] += count[i-1];
  55.    
  56.     for( i = 0 ; text[i] ; ++i ){
  57.         output[count[text[i]]-1] = text[i];
  58.         --count[text[i]];
  59.     }
  60.    
  61.     for( i = 0 ; text[i] ; ++i )
  62.         text[i] = output[i];
  63.     if(reverse)
  64.         sReverse(text);
  65. }
  66.  
  67. int isAnagram(char a[], char b[], int insensitive){
  68.     if( len(a) != len(b) ) return 0;
  69.     if( insensitive ){
  70.         sUpper(a);
  71.         sUpper(b);
  72.     }
  73.     sSort(a, 0);
  74.     sSort(b, 0);
  75.     int i;
  76.     for( i = 0 ; a[i] ; ++i )
  77.         if( a[i] != b[i] ) return 0;
  78.     return 1;
  79. }
  80.  
  81. int main(){
  82.     char x[] = "abAB";
  83.     sSort(x, 0);
  84.     printf("%s\n", x);
  85.     return 0;
  86. }
Add Comment
Please, Sign In to add comment