B1KMusic

digitcount.py: the C version

Jul 12th, 2016
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.96 KB | None | 0 0
  1. /* This is a C port of digitcount.py, proving that in the hands
  2.  * of a capable programmer, C can be just as high level as Python.
  3.  */
  4.  
  5. #include <stdio.h>
  6.  
  7. void
  8. aswap(int *array, int a, int b)
  9. {
  10.     int temp = array[a];
  11.  
  12.     array[a] = array[b];
  13.     array[b] = temp;
  14. }
  15.  
  16. void
  17. sync_sort(int *array1, int *array2)
  18. {
  19.     int alen = *array1,
  20.         *list1 = array1 + 1,
  21.         *list2 = array2 + 1,
  22.         i, j, swapped;
  23.  
  24.     for(i = 0; i < alen; i++){
  25.         swapped = 0;
  26.  
  27.         for(j = alen - 1; j > i; j--){
  28.             if(list1[j] < list1[j - 1]){
  29.                 aswap(list1, j, j - 1);
  30.                 aswap(list2, j, j - 1);
  31.                 swapped = 1;
  32.             }
  33.         }
  34.  
  35.         if(!swapped)
  36.             break;
  37.     }
  38. }
  39.  
  40. int *
  41. count(char *str)
  42. {
  43.     static int digits[11] = {0};
  44.  
  45.     digits[0] = 10;
  46.  
  47.     while(*str){
  48.         digits[1 + (*str) - '0'] += 1;
  49.         str++;
  50.     }
  51.  
  52.     return digits;
  53. }
  54.  
  55. void
  56. report(int *digits, int *digit_nums)
  57. {
  58.     int alen = *digits,
  59.         i;
  60.  
  61.     for(i = 0; i < alen; i++){
  62.         printf("%i: %i\n", digit_nums[1 + i], digits[1 + i]);
  63.     }
  64. }
  65.  
  66. void
  67. init_digit_nums(int *digit_nums)
  68. {
  69.     int i;
  70.  
  71.     for(i = 0; i < 10; i++)
  72.         digit_nums[1 + i] = i;
  73.  
  74.     digit_nums[0] = i;
  75. }
  76.  
  77. void
  78. areverse(int *array)
  79. {
  80.     int array2[11] = {0},
  81.         *list1 = array + 1,
  82.         *list2 = array2 + 1,
  83.         i;
  84.  
  85.     for(i = (*array) - 1; i >= 0; i--){
  86.         *list2 = list1[i];
  87.         list2++;
  88.     }
  89.  
  90.     list2 = array2 + 1;
  91.  
  92.     for(i = 0; i < *array; i++){
  93.         list1[i] = *list2;
  94.         list2++;
  95.     }
  96. }
  97.  
  98. int
  99. main(int argc, char **argv)
  100. {
  101.     int *digits = count(argv[1]),
  102.         digit_nums[11];
  103.  
  104.     init_digit_nums(digit_nums);
  105.  
  106.     printf("By digit:\n");
  107.     report(digits, digit_nums);
  108.  
  109.     printf("By frequency:\n");
  110.     sync_sort(digits, digit_nums);
  111.     areverse(digit_nums);
  112.     areverse(digits);
  113.     report(digits, digit_nums);
  114. }
Advertisement
Add Comment
Please, Sign In to add comment