Pella86

Console plotter

Feb 2nd, 2019
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.07 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <string.h>
  5.  
  6. float linspace(float minv, float maxv, int nsteps, int n){
  7.     return (maxv - minv)/ (float) nsteps * n + minv;
  8. }
  9.  
  10. float rlinspace(float minv, float maxv, int nsteps, float n){
  11.     return (nsteps * (n - minv) ) / (maxv - minv);
  12. }
  13.  
  14. int calc_index(int w, int i, int j){
  15.     return j * w + i;
  16. }
  17.  
  18. int main()
  19. {
  20.     int console_w = 79, console_h = 20;
  21.  
  22.     float xmin = -2*M_PI, xmax = 2*M_PI;
  23.     float ymin = -1.2, ymax = 1.2;
  24.  
  25.     int i, j;
  26.  
  27.     char x_axis_s = '|';
  28.     char y_axis_s = '-';
  29.     char empty_space_s = ':';
  30.     char function_s = '*';
  31.  
  32.     // allocate array
  33.     char char_arr[console_w * console_h];
  34.     memset(char_arr, empty_space_s, console_w * console_h*sizeof(char) );
  35.  
  36.     // fill the array with axis
  37.     for(i = 0; i < console_w - 1; i++){
  38.         for(j = 0; j < console_h - 1; j++){
  39.  
  40.             float x = linspace(xmin, xmax, console_w, i);
  41.             float x1 = linspace(xmin, xmax, console_w, i + 1);
  42.  
  43.             float y = linspace(ymin, ymax, console_h, j);
  44.             float y1 = linspace(ymin, ymax, console_h, j + 1);
  45.  
  46.             int idx = calc_index(console_w, i, console_h -1 - j);
  47.  
  48.             if( x <= 0 && x1 > 0){
  49.                 char_arr[idx] = x_axis_s;
  50.             }
  51.  
  52.             if (y <= 0 && y1 > 0){
  53.                 char_arr[idx] = y_axis_s;
  54.             }
  55.         }
  56.     }
  57.  
  58.     // formula to print
  59.     for(i = 0; i < console_w; i++){
  60.  
  61.         // get x
  62.         float x = linspace(xmin, xmax, console_w, i);
  63.         // calculate y
  64.         float y = sin(x);
  65.  
  66.         // find where y is in the matrix
  67.         int hc = console_h - rlinspace(ymin, ymax, console_h - 1, y);
  68.  
  69.         // assign the function symbol
  70.         if(hc > 0 && hc < console_h){
  71.             char_arr[calc_index(console_w, i, hc)] = function_s;
  72.         }
  73.     }
  74.  
  75.     for(j= 0; j < console_h; j++){
  76.         for(i = 0; i < console_w; i++){
  77.             printf("%c", char_arr[calc_index(console_w, i, j)]);
  78.         }
  79.         printf("\n");
  80.     }
  81.  
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment