Thread: random $$ model

    #1
  1. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,824
    Rep Power
    509

    random $$ model


    http://www.decisionsciencenews.com/2...-happens-next/
    Code:
    // file c.c
    // cc -Wall -g c.c -o c
    
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    #define ABS(A) ((A) < 0 ? -(A) : (A))
    
    int cmp(const void*A, const void*B) {  // comparison function for qsort
      unsigned long a = *(unsigned long*)A, b = *(unsigned long*)B;
      int result = (int)((long long)a - (long long)b);
      return -1 + (0 <= result) + (0 < result);
    }
    
    int main(int ac, char*av[]) { // argument is the population size
      long r;
      unsigned
        b,
        i, j, k = 0, n = ac < 2 ? 99 : atoi(av[1]);
      unsigned long
        N = 1,
        *a = malloc(2 * n * sizeof(unsigned long)), *A = a + n;
      if (NULL == a) return 1;	/* verify allocation success */
      for (i = 0; i < n; ++i) a[i] = n; /* give everyone n dollars */
      for (k = 0; N < 8388608ul; k += N <<= 1) { /* run a lot of generations */
        for (j = 0; j < N; ++j) {		     /* run a batch of generations.  Reporting every generation is too much output */
          for (i = 0; i < n; ++i) {		     /* single generation */
    	r = random(), b = ABS(r) % n;
    	if (a[b]) --a[b],  r = random(), ++a[ABS(r) % n];
          }
        }
        memcpy(A, a, n * sizeof(unsigned long)); /* report */
        qsort(A, n, sizeof(unsigned long), cmp);
        printf("iteration %u\n", k);
        for (i = 0; i < n; ++i) printf("%8lu", A[i]); /* bug, redesign to report a fixed number of wealths evenly spaced based on population */
        putchar('\n');
        fflush(stdout);
      }
      return 0;
    }
    Last edited by b49P23TIvg; July 20th, 2017 at 09:54 AM.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo