C language simply simulates Gaussian ants: random walk problem (graphical)

Table of Contents

1. Creative inspiration

2. Background and requirements

(1) Background requirements

(2) Topic requirements

(3) This code

3. Main ideas and code

(1) Random number generation

(2) Processing of one-dimensional motion

(3) Processing of two-dimensional motion

(4) Output color

(5) unistd.h code

4. Complete code

5. Display of running results

(1) One-dimensional simulation

(2) Two-dimensional simulation

1. Creative inspiration

After watching the video in the card, I thought of using C language to solve the Gaussian ant random walk problem. Because it is a simple simulation, there are only 5 ants (if you want to try multiple ants, you can directly change the uu where the constants are defined in the code. The number of ants is enough).

bilibili_Random walk, ants in Gaussian hands_Technology 3D Visionicon-default.png?t=N7T8https://www.bilibili.com/video/BV1g94y1p7ry

2. Background and requirements

(1) Background requirements

  1. Each ant can only move one square at a time.
  2. Each ant can only move in one direction (x-axis or y-axis direction) at a time, that is, it cannot move diagonally.
  3. Each ant moves only once per second.
  4. Ants will not behave outside the system they belong to, for example, they will not jump out of the two-dimensional coordinate system through the third dimension.
  5. Ants have no intelligence.
  6. Ants don’t communicate with each other.

(2) Question requirements

  1. Users can choose between one-dimensional simulation or two-dimensional simulation.
  2. The x-axis of the coordinate axis is represented by `-`, the y-axis is represented by `|`, and the coordinate origin is represented by `+`.
  3. Ants are represented by `*`.
  4. When there are ants on the coordinate axis, the ants are displayed at this position instead of the coordinate axis.
  5. When there are two or more ants stacked (that is, in the same position), please use `*` in different colors to indicate.

(3) This code

  1. Ask the user whether they want to simulate one or two dimensions.
  2. The output interface has been beautified.
  3. One ant is white `*`, two ants are yellow `*`, three are green `*`, four are purple `*`, five or more are red `*`, the text description and border during the output process are blue.
  4. Simulation size: one dimension: 1*21; two dimensions: 21*21.

3. Main ideas and code

Note: The software used by the author is VS2017.

(1) Random number generation

First you need to call the file header:

#include <stdlib.h> 

Then use the following code to generate random numbers:

srand(time(NULL)); // Initialize random number seed
int random_num = rand(); // Generate random numbers 

This ensures the randomness of movement.

(2) Processing of one-dimensional motion

Since we have generated random numbers and the topic is random walk, we must use the generated random numbers to deal with the movement of ants. In one dimension, ants can only move left or right, so we might as well compare the random numbers to The remainder of 2 is 0 or 1:

random_num %= 2; // Take modulo 2 to get 0 or 1

In this way, we turn the random number into a number of 0 or 1. In order to facilitate memory, we might as well assume that 1 moves in the positive direction of the x-axis, then 0 naturally moves in the negative direction.

We also need to process the ant’s original position and the position it will reach to avoid output errors. For example, if ants move in the positive direction, then we should have:

if (X[i]==10)
Map[0][X[i]] = ' + ';
else if ((X[i] >= 0) & amp; & amp; (X[i] <= 20))
        Map[0][X[i]] = '-';
X[i] + + ;
if ((X[i] >= 0) & amp; & amp; (X[i] <= 20))
    Map[0][X[i]] = '*';

In the negative direction, just change ` + + ` to `–`. Just output them in order.

(3) Processing of two-dimensional motion

First of all, we know that ants can only move in one direction at a time, so we might as well use the method just used to use random numbers to determine the movement of ants in the positive and negative directions of the one-dimensional coordinate axis to get whether the movement of the ants is on the x-axis or the y-axis ( Code duplication will not be shown).

After determining the direction of the ant’s motion vector, we convert the ant’s motion into a one-dimensional motion and repeat the one-dimensional steps.

In addition, it should be noted that the one-dimensional coordinate axis has no spaces, while the two-dimensional coordinate system has areas with spaces, which can easily lead to errors.

(4) Output color

Take one-dimensional output as an example:

if (Map[0][i]=='*')//If there are ants at this location
switch (Num[0][i])//This is a two-dimensional array that records the number of ants at each location
{
case 1://An ant is normally white
printf_s("\033[0m%c\033[0m", Map[0][i]);
break;

case 2://Two ants stacked are represented by yellow
printf_s("\033[33m%c\033[0m", Map[0][i]);
break;

case 3://Three ants stacked in green
printf_s("\033[32m%c\033[0m", Map[0][i]);
break;

case 4://Four ants stacked in purple
printf_s("\033[35m%c\033[0m", Map[0][i]);
break;

default://Stacks of five or more ants are shown in red
printf_s("\033[31m%c\033[0m", Map[0][i]);
break;
    //There is no need to consider 0 because 0 means there are no ants, which does not meet the condition of the first line of if
}

Several common color outputs:

printf("\033[0m");//white
printf("\033[31m");//red
printf("\033[32m");//green
printf("\033[33m");//yellow
printf("\033[34m");//blue
printf("\033[35m");//Purple
printf("\033[36m");//cyan
//Notice:
//What color means that the content output after this will be output in this color
//The previously output content will not be affected
//The color code is generated automatically and will not be output

(5) unistd.h code and application

The unistd.h file code is as follows;

#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif

To use, you need to call:

#include <Windows.h>
#include "unistd.h"

Then you can use the Sleep() function to implement the delay function:

Sleep(1000);

Note that the unit of this function is ms in Windows environment. For example, the above code waits for 1s before running.

4. Complete code

Download portal (free): C language to simply simulate Gaussian ants: random walk problem (graphical)

Here is the complete code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <Windows.h>
#include <time.h>
#include "unistd.h"

#define NumberOfAnts 5//Constant that defines the number of ants
///If you want to try other numbers of ants, you can modify the numbers here yourself.

char Map[21][21];//Storage map data
int Num[21][21];//Storage how many ants there are in each position

void Print(char chMap[21][21],int Dime);
/*Output the results to the screen*/
void Calculate_1(int X[NumberOfAnts]);
void Calculate_2(int X[NumberOfAnts],int Y[NumberOfAnts]);

int main(void)
{
int Ant_X[NumberOfAnts];
int Ant_Y[NumberOfAnts];
/*Define the x and y variables of the ant and place them in the center of the coordinate axis*/
int Dimension = 0;//The dimension that the user needs to input

for (int i = 0; i < NumberOfAnts; i + + )
Ant_X[i] = Ant_Y[i] = 10;

for (int i = 0; i < 21; i + + )
for (int j = 0; j < 21; j + + )
{
Map[i][j] = ' ';//Initialization
Num[i][j] = 0;
}

WrongInputToBack://If the input is wrong, jump back here

printf_s("\033[35m>\033[32mPlease input the dimension you want to imitate:\033[0m");
scanf_s("%d", & amp;Dimension);//Prompts the user to enter the dimensions to be simulated

switch (dimension)
{
case 1:
{//One-bit coordinate axis simulation
do {
Calculate_1(Ant_X);
Sleep(1000);
} while (1);
break;
}

case 2:
{//Two-digit coordinate system simulation
do {
Calculate_2(Ant_X, Ant_Y);
Sleep(1000);
} while (1);
break;
}

default:
printf_s("\033[35m>\033[31mYour input is not allowed! Please input 1 or 2.\033[0m\
");
goto WrongInputToBack;
}
return 0;
}

void Print(char chMap[21][21], int Dime)
{/*Output the results to the screen*/
switch (Dime)
{
case 1:
printf_s("\033[36m\t\t\t\t\t\t\t\t\t\t\t\t ┃\
\033[0m");
for (int i = 0; i < 21; i + + )
{
if ((Map[0][i] == '-') || (Map[0][i] == '>') || (Map[0][i] == ' + '))
printf_s("%c", Map[0][i]);
if (Map[0][i]=='*')
switch (Num[0][i])
{
case 1://An ant is normally white
printf_s("\033[0m%c\033[0m", Map[0][i]);
break;

case 2://Two ants stacked are represented by yellow
printf_s("\033[33m%c\033[0m", Map[0][i]);
break;

case 3://Three ants stacked in green
printf_s("\033[32m%c\033[0m", Map[0][i]);
break;

case 4://Four ants stacked in purple
printf_s("\033[35m%c\033[0m", Map[0][i]);
break;

default://Stacks of five or more ants are shown in red
printf_s("\033[31m%c\033[0m", Map[0][i]);
break;
}
}
printf_s("\t\033[0m*\033[36m:1 ant \t\033[33m*\033[36m:2 ants\t\033[32m*\033[36m:3 ants\t\033[ 35m*\033[36m:4 ants\t\033[31m*\033[36m:5 + ants ┃");
printf_s("\
\033[36m\t\t\t\t\t\t\t\t\t\t\t\t ┃\
");
printf_s("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━ ━┫\
\033[0m");
//One-dimensional output ends here
break;

case 2:
printf_s("\033[36m\t\t\t\t\t\t\t┃\
\033[0m");

for (int i = 0; i < 21; i + + )
{
for (int j = 0; j < 21; j + + )
{
if ((Map[i][j] == '-') || (Map[i][j] == '>') || (Map[i][j] == ' + ') || (Map[i][j] == '|') || (Map[i][j] == ' ') || (Map[i][j] == '^'))
printf_s("%c", Map[i][j]);

if (Map[i][j] == '*')
switch (Num[i][j])
{
case 1://An ant is normally white
printf_s("\033[0m%c\033[0m", Map[i][j]);
break;

case 2://Two ants stacked are represented by yellow
printf_s("\033[33m%c\033[0m", Map[i][j]);
break;

case 3://Three ants stacked in green
printf_s("\033[32m%c\033[0m", Map[i][j]);
break;

case 4://Four ants stacked in purple
printf_s("\033[35m%c\033[0m", Map[i][j]);
break;

default://Stacks of five or more ants are shown in red
printf_s("\033[31m%c\033[0m", Map[i][j]);
break;
}
}

if (i >= 0 & amp; & amp; i <= 4)
{
switch(i)
{
case 0:
printf_s("\t\t\033[0m*\033[36m:1 ant \033[36m\t\t┃\
\033[0m");
break;

case 1:
printf_s("\t\t\033[33m*\033[36m:2 ants\033[36m\t\t┃\
\033[0m");
break;

case 2:
printf_s("\t\t\033[32m*\033[36m:3 ants\033[36m\t\t┃\
\033[0m");
break;

case 3:
printf_s("\t\t\033[35m*\033[36m:4 ants\033[36m\t\t┃\
\033[0m");
break;

case 4:
printf_s("\t\t\033[31m*\033[36m:5 + ants\033[36m\t\t┃\
\033[0m");
break;
}
}
else printf_s("\t\t\t\t\t\033[36m┃\
\033[0m");
}
printf_s("\033[36m\t\t\t\t\t\t\t┃\
");
printf_s("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━ ━━━━━━━━━┫\
\033[0m");

break;
}

for (int i=0;i<21;i + + )
for (int j = 0; j < 21; j + + )
{
Map[i][j] = ' ';
Num[i][j] = 0;
}//Initialize every time you run it, otherwise problems will occur
return;
}

void Calculate_1(int X[NumberOfAnts])
{/*Operation for one-dimensional simulation*/
srand(time(NULL)); // Initialize random number seed
int random_num = rand(); // Generate random numbers

for (int i = 0; i < NumberOfAnts; i + + )
{
random_num = rand();

random_num %= 2; // Take modulo 2 to get 0 or 1
if (random_num == 1)//1 then go right
{
if (X[i]==10)
Map[0][X[i]] = ' + ';
else if ((X[i] >= 0) & amp; & amp; (X[i] <= 20)) Map[0][X[i]] = '-';
X[i] + + ;
if ((X[i] >= 0) & amp; & amp; (X[i] <= 20)) Map[0][X[i]] = '*';
}
else
{//0 then go left
if (X[i] == 10)
Map[0][X[i]] = ' + ';
else if ((X[i] >= 0) & amp; & amp; (X[i] <= 20))Map[0][X[i]] = '-';
X[i]--;
if ((X[i] >= 0) & amp; & amp; (X[i] <= 20)) Map[0][X[i]] = '*';
}
}//The above completes the simulation of 5 ants

//Next, record statistics for each of the one-dimensional coordinate axes
for (int i = 0; i < NumberOfAnts; i + + )
if ((X[i] >= 0) & amp; & amp; (X[i] <= 20))
Num[0][X[i]] + + ;

for (int i = 0; i < 21; i + + )
if (Map[0][i] == ' ')
Map[0][i] = '-';
Map[0][20] = '>';
if (Map[0][10] != '*') Map[0][10] = ' + ';

Print(Map, 1);//Call function for output
return;
}

void Calculate_2(int X[NumberOfAnts], int Y[NumberOfAnts])
{/*Operations for two-dimensional simulation*/
srand(time(NULL)); // Initialize random number seed
int random_num = rand(); // Generate random numbers

for (int i = 0; i < NumberOfAnts; i + + )
{
random_num = rand();

random_num %= 2;//Get 0 or 1
switch (random_num)
{
case 0://If you get 0, move in the y-axis direction
{
random_num = rand(); // Generate random numbers
random_num %= 2;//Get 0 or 1
/*Generate random numbers again to determine whether up or down*/

switch(random_num)
{
case 1://1 means upward movement
{
if ((Y[i] == 10) & amp; & amp; (X[i] == 10))
{
Map[Y[i]][X[i]] = ' + ';
}//Note that the first dimension is the y-axis and the second dimension is the x-axis
else if (X[i]==10 & amp; & amp; Y[i]>=0 & amp; & amp; Y[i]<=10) Map[Y[i]][X[i]] = '|';
else if ((X[i] >= 0) & amp; & amp; (X[i] <= 20) & amp; & amp; (Y[i] >= 0) & amp; & amp; (Y [i] <= 20)) Map[Y[i]][X[i]] = ' ';
Y[i] + + ;
if ((X[i] >= 0) & amp; & amp; (X[i] <= 20) & amp; & amp; (Y[i] >= 0) & amp; & amp; (Y[ i] <= 20)) Map[Y[i]][X[i]] = '*';

break;
}

case 0://0 means downward movement
{
if ((Y[i] == 10) & amp; & amp; (X[i] == 10))
{
Map[Y[i]][X[i]] = ' + ';
}//Note that the first dimension is the y-axis and the second dimension is the x-axis
else if (X[i] == 10 & amp; & amp; Y[i] >= 0 & amp; & amp; Y[i] <= 10) Map[Y[i]][X[i]] = '|';
else if ((X[i] >= 0) & amp; & amp; (X[i] <= 20) & amp; & amp; (Y[i] >= 0) & amp; & amp; (Y [i] <= 20)) Map[Y[i]][X[i]] = ' ';
Y[i]--;
if ((X[i] >= 0) & amp; & amp; (X[i] <= 20) & amp; & amp; (Y[i] >= 0) & amp; & amp; (Y[ i] <= 20)) Map[Y[i]][X[i]] = '*';

break;
}
}
break;
}

case 1://If you get 1, move in the x-axis direction
{
random_num = rand(); // Generate random numbers
random_num %= 2;//Get 0 or 1
/*Generate random numbers again to determine whether to go right or left*/

switch(random_num)
{
case 1://1 moves to the right
{
if ((Y[i] == 10) & amp; & amp; (X[i] == 10))
{
Map[Y[i]][X[i]] = ' + ';
}//Note that the first dimension is the y-axis and the second dimension is the x-axis
else if (Y[i] == 10 & amp; & amp; X[i] >= 0 & amp; & amp; X[i] <= 10) Map[Y[i]][X[i]] = '-';
else if ((X[i] >= 0) & amp; & amp; (X[i] <= 20) & amp; & amp; (Y[i] >= 0) & amp; & amp; (Y [i] <= 20)) Map[Y[i]][X[i]] = ' ';
X[i] + + ;
if ((X[i] >= 0) & amp; & amp; (X[i] <= 20) & amp; & amp; (Y[i] >= 0) & amp; & amp; (Y[ i] <= 20)) Map[Y[i]][X[i]] = '*';

break;
}

case 0://0 moves left
{
if ((Y[i] == 10) & amp; & amp; (X[i] == 10))
{
Map[Y[i]][X[i]] = ' + ';
}//Note that the first dimension is the y-axis and the second dimension is the x-axis
else if (Y[i] == 10 & amp; & amp; X[i] >= 0 & amp; & amp; X[i] <= 10) Map[Y[i]][X[i]] = '-';
else if ((X[i] >= 0) & amp; & amp; (X[i] <= 20) & amp; & amp; (Y[i] >= 0) & amp; & amp; (Y [i] <= 20)) Map[Y[i]][X[i]] = ' ';
X[i]--;
if ((X[i] >= 0) & amp; & amp; (X[i] <= 20) & amp; & amp; (Y[i] >= 0) & amp; & amp; (Y[ i] <= 20)) Map[Y[i]][X[i]] = '*';

break;
}
}
break;
}
}
}
//The above completes the movement simulation of 5 ants

//Next statistics and writing
for (int i = 0; i < NumberOfAnts; i + + )
if ((X[i] >= 0) & amp; & amp; (X[i] <= 20) & amp; & amp; (Y[i] >= 0) & amp; & amp; (Y[ i] <= 20))
Num[Y[i]][X[i]] + + ;

for (int i = 0; i < 21; i + + )
{
if (Map[10][i] == ' ')
Map[10][i] = '-';
if (Map[i][10] == ' ')
Map[i][10] = '|';
}
Map[10][20] = '>';
Map[0][10] = '^';
if (Map[10][10] != '*') Map[10][10] = ' + ';

Print(Map, 2);//Call function for output
return;
}

5. Display of running results

dcc15e2105c847edac49f50916e383d4.png

Prompts the user to enter the required dimensions and reminds the author of errors and re-entry when input errors are made

(1) One-dimensional simulation

ac59eb2c703e4b2c81181edf934f971f.png

(2) Two-dimensional simulation

4ab2c685dd54445eb3e88902a38281f8.png

Tips: When we increase the number of ants and expand the coordinate system, we will find interesting phenomena~

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. C Skill Tree Home Page Overview 194014 people are learning the system