[vc_row][vc_column width=”1/1″][vc_column_text]Original: http://auzieman.blogspot.com/2012/05/modeling-weighted-random-walk-in-c.html
Here is an experiment I was attempting when working on the linksprite arduino robot kit. My idea is to make a weighted random walk and while the c++ code worked fairly well (some issues) the robot often got caught in a loop.
To try out this code you should only need a c compiler, I used gcc under linux but honestly this is so simple you shouldn’t need too complicated a setup. Cygwin under windows or just about any c compiler should do the trick with a little work.
<code>1: #define _GNU_SOURCE 2: #include <stdio.h> 3: #include <math.h> 4: #include <stdlib.h> 5: #include <time.h> 6: int x=0; 7: int y=0; 8: int bias1=50; 9: int bias2=30; 10: int bias3=25; 11: int bias4=30; 12: int bias5=55; 13: int cnt; 14: int xmax=20; 15: int ymax=20; 16: int xp; 17: int yp; 18: int dc=0; 19: int out; 20: int area[20][20]; 21: int rndm; 22: void intloc(){ 23: xp=ymax/2; 24: yp=ymax/2; 25: printf("x %u, y %u \n",xp,yp); 26: } 27: initmap(){ 28: for ( x=0 ; x < xmax ; x++ ){ 29: for ( y=0 ; y < ymax ; y++ ){ 30: area[x][y]=0; 31: } 32: } 33: } 34: void printmap(){ 35: printf("Col \n"); 36: for ( y=0 ; y < ymax ; y++ ){ 37: printf("%u ;",y); 38: } 39: printf("\n"); 40: for ( x=0 ; x < xmax ; x++ ){ 41: printf("r %u; ",x); 42: for ( y=0 ; y < ymax ; y++ ){ 43: out=area[x][y]; 44: printf("%u ;",out); 45: } 46: printf("\n"); 47: } 48: } 49: void updloc(dc){ 50: if (dc==0){ 51: } 52: } 53: void main() 54: { 55: //randNumber = random(0, 150); 56: srand ( time(NULL) ); 57: rndm=rand() % 150 + 1; 58: initmap(); 59: intloc(); 60: printmap(); 61: for (cnt=0; cnt<100;cnt++){ 62: rndm=rand() % 150 + 1; 63: printf("x %u, y %u rand:%u\n",xp,yp,rndm); 64: if ((rndm-bias1) <= 10 && (rndm-bias1) > 0){ 65: printf("east\n"); 66: xp--; 67: }else if ((rndm-bias2) <= 40 && (rndm-bias1) > 10){ 68: printf("west\n"); 69: xp++; 70: }else if ((rndm-bias3) <= 60 && (rndm-bias1) > 40){ 71: printf("north\n"); 72: yp--; 73: }else if ((rndm-bias4) <= 70 && (rndm-bias1) > 60){ 74: printf("south\n"); 75: yp++; 76: }else if ((rndm-bias5) <= 80 && (rndm-bias1) > 70){ 77: printf("north 2\n"); 78: yp--; 79: printf("x %u, y %u rand:%u\n",xp,yp,rndm); 80: area[xp][yp]=5; 81: yp--; 82: }else { 83: printf("other\n"); 84: } 85: //update position 86: printf("x %u, y %u rand:%u\n",xp,yp,rndm); 87: area[xp][yp]=5; 88: printmap(); 89: //printf("Read line of %u characters: %s\n", read, line); 90: //printf("Read line of %u characters: %s\n", read, line); 91: } 92: } </code>
To be honest I would love to get this working better, I would love to find a book that actually covers this stuff better. Not just a bunch of formulas but an actual from formula to source code examples.[/vc_column_text][/vc_column][/vc_row]
Leave a Reply
You must be logged in to post a comment.