Advertisement
B1KMusic

Look and Say

Jul 13th, 2016
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.22 KB | None | 0 0
  1. /* Look and say sequence calculator by Braden Best
  2.  * Inspired by a numberphile video: https://www.youtube.com/watch?v=ea7lJkEhytA
  3.  */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7.  
  8. #define BUFSZ 100000
  9.  
  10. void
  11. build(char *buf)
  12. {
  13.     char buf2[BUFSZ] = "",
  14.          *buf2_p = buf2,
  15.          temp;
  16.     int digit,
  17.         count;
  18.  
  19.     strncpy(buf2, buf, strlen(buf));
  20.  
  21.     while(*buf2_p){
  22.         temp = *buf2_p;
  23.         count = 0;
  24.  
  25.         while(*buf2_p && *buf2_p == temp){
  26.             buf2_p++;
  27.             count++;
  28.         }
  29.        
  30.         digit = temp - '0';
  31.         snprintf(buf, 3, "%i%i", count, digit);
  32.         buf += 2;
  33.     }
  34. }
  35.  
  36. void
  37. look_and_say(int n, int lim)
  38. {
  39.     char buf[BUFSZ] = "";
  40.     int i;
  41.  
  42.     printf("Seed: %i\n\n", n);
  43.     snprintf(buf, BUFSZ, "%i", n);
  44.  
  45.     for(i = 1; i <= lim; i++){
  46.         build(buf);
  47.         printf("Generation %i: %s\n\n", i, buf);
  48.     }
  49. }
  50.    
  51. int
  52. main(int argc, char **argv)
  53. {
  54.     if(argv[1] && argv[2]){
  55.         look_and_say(atoi(argv[1]), atoi(argv[2]));
  56.     } else {
  57.         printf( "Usage: %s [starting point] [number of generations]\n"
  58.                 "Try %s 1 7\n",
  59.                 argv[0],
  60.                 argv[0]);
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement