VM Placement with FF, BF and WF Algorithms - c

Please I am working on VM Placement using First-fit (FF), Best-fit (BF) and Worst-fit (WF) algorithms. The FF and WF seem to work pretty good but there's is a little bit of issue with the BF. The VM sequence are generated randomly for the placement.
The problem is that, sometimes when it sorts out the PMs and picks the one with the least capacity of resources and when it gets to checking if it has enough resource for hosting that particular VM it says "WAIT" instead of placing it on the next available PM with enough resources. It works well from the start but as the process continues it tends to get such error in the placements.
For example, a VM sequence of X, S, M, L, S, L, X, L, M, M the placement is supposed to be:
X 2
S 2
M 2
L 1
S 1
L 1
X 1
L 1
M WAIT
M WAIT
instead it displays:
X 2
S 2
M 2
L 1
S 1
L 1
X WAIT
L WAIT
M WAIT
M WAIT
I really don't know which part of the code is making such an error occur. I would be glad if assistance can be provided. Below is the code - thank you.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <time.h>
#define max 250
#define min 10
int main()
{
int i, k,g, c[max] = {0}, r[max] = {0}, d[max] = {0}, cv[max] = {0},
rv[max] = {0}, dv[max] = {0}, rw[max] = {0}; //declaration of variables
int nf=10; char ch;
float avgpwr=0; //, nb = 3
int m=2;
int b = 1; int ff[10] = {0};
int cm[max] = {0}, rm[max] = {0}, dm[max] = {0};
int a;
for (a=1; a<=b; a++)
{
printf("\n\tVirtual Machine Placement");
printf("\n\t**************************************"); printf("\n");
int flag, j, count=0;
char vm_type[] = {'S', 'M', 'L', 'X'};
printf("\n");
//loop throug array and print values
for (i=1; i<=nf; i++)
{
//generate random index number
int index = my_rand ();
printf("VM %d:",i); printf("%-5c", vm_type[index]);
switch(vm_type[index]) {
case 'S':
cv[i]= 2; rv[i]= 4; dv[i]= 50; rw[i] = 69;
break;
case 'M':
cv[i]= 3; rv[i]= 8; dv[i]= 100; rw[i] = 139;
break;
case 'L':
cv[i]= 5; rv[i]= 12; dv[i]= 150; rw[i] = 207;
break;
case 'X':
cv[i]= 6; rv[i]= 18; dv[i]= 200; rw[i] = 345;
break;
default:
printf("That was not a valid option :(");
}
printf("\n");
}
printf("\n1.First fit 2.Best fit 3.Worst fit\n");
do
{
int nc[10]={0}; int dc[10]={0};
int mc[10]={0}; int rd[10]={0};
int host[10] = {0};
for (i=1; i<=m; i++)
{
if (i==1){
c[i] = 64; r[i] = 64; d[i] = 700; ff[i] = i;
}
if (i==2){
c[i] = 32; r[i] = 32; d[i] = 500; ff[i] = i;
}
}
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nFirst Fit\n");
printf("\n\nVirtualM_No\tPhyMac_No\n");
for(i=1; i<=nf; i++)
{
flag = 1;
for(j=1; j<=m; j++)
{
if(cv[i] <= c[j] && rv[i]<= r[j] && dv[i] <= d[j]){
printf("%-15d\t%-15d\t%\n",i,ff[j]); //printf("\n");
count++;
if(ff[j]==1 || ff[j]==2 || ff[j]==3 || ff[j]==4 || ff[j]==5 || ff[j]==6 || ff[j]==7 || ff[j]== 8|| ff[j]==9 || ff[j]==10)
{
c[j] = c[j] - cv[i];
r[j] = r[j] - rv[i];
d[j] = d[j] - dv[i];
nc[j] = nc[j] + cv[i];
mc[j] = mc[j] + rv[i];
dc[j]= dc[j] + dv[i];
rd[j]= rd[j] + rw[i];
host[j] = host[j]+ 1;
}
break;
}
else
{
flag++;
}
}
if(flag > m) {
printf("%-15d\t%-15s\n",i,"WAIT..\n");
// rejectvm++;
}
}
printf("\n");
//printf("%d , %d , %d , %d \n", nc[i], rd[i], mc[i], dc[i]);
break;
case 2: printf("\nBest Fit\n");
int y1, z1, temp1,temp_r1, temp_d1;
//placing the vms
printf("\n\nVirtualM_No\tPhyMac_No\n");
for(i=1; i<=nf; i++)
{
flag = 1;
for(y1=1;y1<=m;y1++)
{
for(z1=y1;z1<=m;z1++)
{
if (c[y1] !=0 && r[y1] !=0 || d[y1] !=0)
{
if(c[y1] > c[z1] && r[y1] > r[z1] && d[y1] > d[z1])
{
temp1 = c[y1]; temp_r1 = r[y1]; temp_d1 = d[y1];
c[y1]= c[z1]; r[y1]= r[z1]; d[y1]= d[z1];
c[z1]=temp1; d[z1]=temp_r1; d[z1]=temp_d1;
temp1=ff[y1];
ff[y1]=ff[z1];
ff[z1]=temp1;
}
}
}
}
for(j=1; j<=m; j++)
{
if( c[j] >= cv[i] && r[j] >= rv[i] && d[j] >= dv[i]){
printf("%-15d\t%-15d\t%\n",i,ff[j]);
count++;
if(ff[j]==1 || ff[j]==2 || ff[j]==3 || ff[j]==4 ||
ff[j]==5 || ff[j]==6 || ff[j]==7 || ff[j]== 8|| ff[j]==9 || ff[j]==10)
{
c[j] = c[j] - cv[i];
r[j] = r[j] - rv[i];
d[j] = d[j] - dv[i];
//ctr[i] = ctr[i] + 1;
nc[j] = nc[j] + cv[i];
mc[j] = mc[j] + rv[i];
dc[j]= dc[j] + dv[i];
rd[j]= rd[j] + rw[i];
host[j] = host[j]+ 1;
}
break;
}
else {
flag++;
}
}
if(flag > m) {
printf("%-15d\t%-15s\n",i,"WAIT...\n");
}
}
printf("\n");
break;
case 3: printf("\nWorst Fit\n");
int y, z, temp,temp_r, temp_d;
//placing the vms
printf("\n\nVirtualM_No\tPhyMac_No\n");
for(i=1; i<=nf; i++)
{
flag = 1;
for(j=1; j<=m; j++)
{
for(y=1;y<=m;y++)
{
for(z=y;z<=m;z++)
{
if(c[y] < c[z] && r[y] < r[z] && d[y] < d[z])
{
temp = c[y]; temp_r = r[y]; temp_d = d[y];
c[y]= c[z]; r[y]= r[z]; d[y]= d[z];
c[z]=temp; r[z]=temp_r; d[z]=temp_d;
temp1=ff[y];
ff[y]=ff[z];
ff[z]=temp1;
}
}
}
if( c[j] >= cv[i] && r[j] >= rv[i] && d[j] >= dv[i]){
printf("%-15d\t%-15d\t%d\n",i,ff[j],j);
count++; g = ff[j];
if(ff[j]==1 || ff[j]==2 || ff[j]==3 || ff[j]==4 || ff[j]==5 || ff[j]==6 || ff[j]==7 || ff[j]== 8|| ff[j]==9 || ff[j]==10)
{
c[j] = c[j] - cv[i];
r[j] = r[j] - rv[i];
d[j] = d[j] - dv[i];
// ctr[i] = ctr[i] + 1;
nc[g] = nc[g] + cv[i];
mc[g] = mc[g] + rv[i];
dc[g]= dc[g] + dv[i];
rd[g]= rd[g] + rw[i];
host[g] = host[g]+ 1;
}
break;
}
else
{
flag++;
}
}
if(flag > m) {
printf("%-15d\t%-15s\n",i,"WAIT...\n");
}
}
printf("\n");
break;
default:
printf("That was not a valid option :(");
break;
}
}
while(ch<=3);
}
}
int my_rand ()
{
static int first = 0;
if (first == 0)
{
srand (time (NULL));
first = 1;
}
return (rand ()% 4);
}

Related

How to get rid of error C1083: Cannot open include file: 'unistd.h'?

I'm trying to run this code on Visual Studio 2022, but it gives an error:
C1083: Cannot open include file: 'unistd.h': No such file or directory.
As I understood that the code was written for the UNIX system, but I would like to run it on Windows.
Snake game
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <conio.h>
#include<time.h>
#include<ctype.h>
#include <time.h>
#include <windows.h>
#include <process.h>
#include <unistd.h>
#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77
int length;
int bend_no;
int len;
char key;
void record();
void load();
int life;
void Delay(long double);
void Move();
void Food();
int Score();
void Print();
void gotoxy(int x, int y);
void GotoXY(int x, int y);
void Bend();
void Boarder();
void Down();
void Left();
void Up();
void Right();
void ExitGame();
int Scoreonly();
struct coordinate {
int x;
int y;
int direction;
};
typedef struct coordinate coordinate;
coordinate head, bend[500], food, body[30];
int main()
{
char key;
Print();
system("cls");
load();
length = 5;
head.x = 25;
head.y = 20;
head.direction = RIGHT;
Boarder();
Food(); //to generate food coordinates initially
life = 3; //number of extra lives
bend[0] = head;
Move(); //initialing initial bend coordinate
return 0;
}
void Move()
{
int a, i;
do {
Food();
fflush(stdin);
len = 0;
for (i = 0; i < 30; i++)
{
body[i].x = 0;
body[i].y = 0;
if (i == length)
break;
}
Delay(length);
Boarder();
if (head.direction == RIGHT)
Right();
else if (head.direction == LEFT)
Left();
else if (head.direction == DOWN)
Down();
else if (head.direction == UP)
Up();
ExitGame();
} while (!kbhit());
a = getch();
if (a == 27)
{
system("cls");
exit(0);
}
key = getch();
if ((key == RIGHT && head.direction != LEFT && head.direction != RIGHT) || (key == LEFT && head.direction != RIGHT && head.direction != LEFT) || (key == UP && head.direction != DOWN && head.direction != UP) || (key == DOWN && head.direction != UP && head.direction != DOWN))
{
bend_no++;
bend[bend_no] = head;
head.direction = key;
if (key == UP)
head.y--;
if (key == DOWN)
head.y++;
if (key == RIGHT)
head.x++;
if (key == LEFT)
head.x--;
Move();
}
else if (key == 27)
{
system("cls");
exit(0);
}
else
{
printf("\a");
Move();
}
}
void gotoxy(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void GotoXY(int x, int y)
{
HANDLE a;
COORD b;
fflush(stdout);
b.X = x;
b.Y = y;
a = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(a, b);
}
void sleep(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
void load() {
int row, col, r, c, q;
gotoxy(36, 14);
printf("loading...");
gotoxy(30, 15);
for (r = 1; r <= 20; r++) {
sleep(200);//to display the character slowly
printf("%c", 177);
}
getch();
}
void Down()
{
int i;
for (i = 0; i <= (head.y - bend[bend_no].y) && len < length; i++)
{
GotoXY(head.x, head.y - i);
{
if (len == 0)
printf("v");
else
printf("*");
}
body[len].x = head.x;
body[len].y = head.y - i;
len++;
}
Bend();
if (!kbhit())
head.y++;
}
void Delay(long double k)
{
Score();
long double i;
for (i = 0; i <= (10000000); i++);
}
void ExitGame()
{
int i, check = 0;
for (i = 4; i < length; i++) //starts with 4 because it needs minimum 4 element to touch its own body
{
if (body[0].x == body[i].x && body[0].y == body[i].y)
{
check++; //check's value increases as the coordinates of head is equal to any other body coordinate
}
if (i == length || check != 0)
break;
}
if (head.x <= 10 || head.x >= 70 || head.y <= 10 || head.y >= 30 || check != 0)
{
life--;
if (life >= 0)
{
head.x = 25;
head.y = 20;
bend_no = 0;
head.direction = RIGHT;
Move();
}
else
{
system("cls");
printf("All lives completed\nBetter Luck Next Time!!!\nPress any key to quit the game\n");
record();
exit(0);
}
}
}
void Food()
{
if (head.x == food.x && head.y == food.y)
{
length++;
time_t a;
a = time(0);
srand(a);
food.x = rand() % 70;
if (food.x <= 10)
food.x += 11;
food.y = rand() % 30;
if (food.y <= 10)
food.y += 11;
}
else if (food.x == 0)/*to create food for the first time coz global variable are initialized with 0*/
{
food.x = rand() % 70;
if (food.x <= 10)
food.x += 11;
food.y = rand() % 30;
if (food.y <= 10)
food.y += 11;
}
}
void Left()
{
int i;
for (i = 0; i <= (bend[bend_no].x - head.x) && len < length; i++)
{
GotoXY((head.x + i), head.y);
{
if (len == 0)
printf("<");
else
printf("*");
}
body[len].x = head.x + i;
body[len].y = head.y;
len++;
}
Bend();
if (!kbhit())
head.x--;
}
void Right()
{
int i;
for (i = 0; i <= (head.x - bend[bend_no].x) && len < length; i++)
{
//GotoXY((head.x-i),head.y);
body[len].x = head.x - i;
body[len].y = head.y;
GotoXY(body[len].x, body[len].y);
{
if (len == 0)
printf(">");
else
printf("*");
}
/*body[len].x=head.x-i;
body[len].y=head.y;*/
len++;
}
Bend();
if (!kbhit())
head.x++;
}
void Bend()
{
int i, j, diff;
for (i = bend_no; i >= 0 && len < length; i--)
{
if (bend[i].x == bend[i - 1].x)
{
diff = bend[i].y - bend[i - 1].y;
if (diff < 0)
for (j = 1; j <= (-diff); j++)
{
body[len].x = bend[i].x;
body[len].y = bend[i].y + j;
GotoXY(body[len].x, body[len].y);
printf("*");
len++;
if (len == length)
break;
}
else if (diff > 0)
for (j = 1; j <= diff; j++)
{
/*GotoXY(bend[i].x,(bend[i].y-j));
printf("*");*/
body[len].x = bend[i].x;
body[len].y = bend[i].y - j;
GotoXY(body[len].x, body[len].y);
printf("*");
len++;
if (len == length)
break;
}
}
else if (bend[i].y == bend[i - 1].y)
{
diff = bend[i].x - bend[i - 1].x;
if (diff < 0)
for (j = 1; j <= (-diff) && len < length; j++)
{
/*GotoXY((bend[i].x+j),bend[i].y);
printf("*");*/
body[len].x = bend[i].x + j;
body[len].y = bend[i].y;
GotoXY(body[len].x, body[len].y);
printf("*");
len++;
if (len == length)
break;
}
else if (diff > 0)
for (j = 1; j <= diff && len < length; j++)
{
/*GotoXY((bend[i].x-j),bend[i].y);
printf("*");*/
body[len].x = bend[i].x - j;
body[len].y = bend[i].y;
GotoXY(body[len].x, body[len].y);
printf("*");
len++;
if (len == length)
break;
}
}
}
}
void Boarder()
{
system("cls");
int i;
GotoXY(food.x, food.y); /*displaying food*/
printf("F");
for (i = 10; i < 71; i++)
{
GotoXY(i, 10);
printf("!");
GotoXY(i, 30);
printf("!");
}
for (i = 10; i < 31; i++)
{
GotoXY(10, i);
printf("!");
GotoXY(70, i);
printf("!");
}
}
void Print()
{
//GotoXY(10,12);
printf("\tWelcome to the mini Snake game.(press any key to continue)\n");
getch();
system("cls");
printf("\tGame instructions:\n");
printf("\n-> Use arrow keys to move the snake.\n\n-> You will be provided foods at the several coordinates of the screen which you have to eat. Everytime you eat a food the length of the snake will be increased by 1 element and thus the score.\n\n-> Here you are provided with three lives. Your life will decrease as you hit the wall or snake's body.\n\n-> YOu can pause the game in its middle by pressing any key. To continue the paused game press any other key once again\n\n-> If you want to exit press esc. \n");
printf("\n\nPress any key to play game...");
if (getch() == 27)
exit(0);
}
void record() {
char plname[20], nplname[20], cha, c;
int i, j, px;
FILE* info;
info = fopen("record.txt", "a+");
getch();
system("cls");
printf("Enter your name\n");
scanf("%[^\n]", plname);
//************************
for (j = 0; plname[j] != '\0'; j++) { //to convert the first letter after space to capital
nplname[0] = toupper(plname[0]);
if (plname[j - 1] == ' ') {
nplname[j] = toupper(plname[j]);
nplname[j - 1] = plname[j - 1];
}
else nplname[j] = plname[j];
}
nplname[j] = '\0';
//*****************************
//sdfprintf(info,"\t\t\tPlayers List\n");
fprintf(info, "Player Name :%s\n", nplname);
//for date and time
time_t mytime;
mytime = time(NULL);
fprintf(info, "Played Date:%s", ctime(&mytime));
//**************************
fprintf(info, "Score:%d\n", px = Scoreonly());//call score to display score
//fprintf(info,"\nLevel:%d\n",10);//call level to display level
for (i = 0; i <= 50; i++)
fprintf(info, "%c", '_');
fprintf(info, "\n");
fclose(info);
printf("wanna see past records press 'y'\n");
cha = getch();
system("cls");
if (cha == 'y') {
info = fopen("record.txt", "r");
do {
putchar(c = getc(info));
} while (c != EOF);
}
fclose(info);
}
int Score()
{
int score;
GotoXY(20, 8);
score = length - 5;
printf("SCORE : %d", (length - 5));
score = length - 5;
GotoXY(50, 8);
printf("Life : %d", life);
return score;
}
int Scoreonly()
{
int score = Score();
system("cls");
return score;
}
void Up()
{
int i;
for (i = 0; i <= (bend[bend_no].y - head.y) && len < length; i++)
{
GotoXY(head.x, head.y + i);
{
if (len == 0)
printf("^");
else
printf("*");
}
body[len].x = head.x;
body[len].y = head.y + i;
len++;
}
Bend();
if (!kbhit())
head.y--;
}
I tried to find information on how to fix the code, but I did not succeed.

Fruit disappears sometimes Snake in C

Im making a snake game in c, most things seem to be working right but I found a bug that I can't seem to fix. The fruit in my game sometimes just disappears for no reason. First, I thought that the problem was that I was generating it outside of the play-area but I put a restriction on that and the problem still exists.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <math.h>
#include <time.h>
int gameOver = 0, width = 20, height = 20, x, y, fruitX, fruitY, score;
int s;
int totalTail;
int tailX[100], tailY[100];
void Setup() {
srand((unsigned int)time(NULL));
x = height / 2;
y = width / 2;
score = 0;
do {
fruitX = rand() % height;
fruitY = rand() % width;
} while (fruitX <= 0 || fruitY <= 0 || fruitX == x || fruitY == y || fruitX > height || fruitY > width);
}
void Draw() {
system("cls");
for (int i = 0; i < height;i++) {
for (int j = 0; j < width; j++) {
if (i == 0 || j == 0 || i == width - 1 || j == height - 1) {
printf("#");
}
else if (i == x && j == y) { //generates head
printf("O");
}
else if (fruitX == i && fruitY == j) { //generates fruit
printf("F");
}
else {
int print = 0; //generates tail
for (int k = 0; k < totalTail; k++) {
if (tailX[k] == i && tailY[k] == j) {
printf("o");
print = 1;
}
}
if (print == 0) {
printf(" ");
}
}
}
printf("\n");
}
printf("Score: %d", score); //displays score
}
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 'w':
s = 1;
break;
case 's':
s = 2;
break;
case 'a':
s = 3;
break;
case 'd':
s = 4;
break;
case 'x':
gameOver = 1;
break;
}
}
}
void Logic() {
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < totalTail; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (s) {
case 1:
x--;
break;
case 2:
x++;
break;
case 3:
y--;
break;
case 4:
y++;
break;
default:
break;
}
for (int i = 0; i < totalTail; i++) { //checks if the head and tail have collided
if (tailX[i] == x && tailY[i] == y) {
gameOver = 1;
}
}
if (x > 18 || y > 18 || x <= 0 || y <= 0) { //checks if player is out of the area
gameOver = 1;
}
if (x == fruitX && y == fruitY) { // adds point to score and regenerates fruit, I think the problem is here, not sure though
score += 1;
totalTail++;
do {
fruitX = rand() % height;
fruitY = rand() % width;
} while (fruitX <= 0 || fruitY <= 0 || fruitX == x || fruitY == y || fruitX > height || fruitY > width);
}
}
int main()
{
Setup();
while (gameOver != 1) {
Input();
Logic();
Draw();
Sleep(10);
}
return 0;
}

For Loop running infinite C

I am making a checksum error verifying program using C language but I have encountered an infinite loop while executing the program and I don't have any clue why I am getting this.
So what I have done in this program is that I am going to first convert characters of a string into respective ASCII codes and then checking for checksum error and for this I have made this program below.
#include <stdio.h>
int a[2], i, dec[10][8], de[2][8], j, k, add[8], carry = 0, n = 5;
int u[] = {0, 0, 0, 0, 0, 0, 0, 1};
char b[] = {'H', 'e', 'l', 'l', 'o'};
int main()
{
for (k = 0; k < 2; k++)
{
for (j = 0; j < 8; j++)
{
dec[k][j] = 0;
}
}
for (k = 0; k < 2; k++)
{
a[k] = b[k];
}
for (k = 0; k < 2; k++)
{
i = 0;
while (a[k] > 0)
{
dec[k][i] = a[k] % 2;
a[k] = a[k] / 2;
i++;
}
}
i = 0;
s:
for (k = 0; k < 2; k++)
{
for (j = 7; j >= 0; j--)
{
de[k][i] = dec[k][j];
i++;
}
i = 0;
}
for (k = 0; k < 2; k++)
{
for (j = 0; j < 8; j++)
{
printf("%d", de[k][j]);
}
printf("\n");
}
i = 0;
for (j = 7; j >= 0; j--)
{
if (de[i][j] == 1 && de[i + 1][j] == 1 && carry == 0)
{
add[j] = 0;
carry = 1;
}
else if (de[i][j] == 1 && de[i + 1][j] == 1 && carry == 1)
{
add[j] = 1;
carry = 1;
}
else if (de[i][j] == 0 && de[i + 1][j] == 1 && carry == 1)
{
add[j] = 0;
carry = 1;
}
else if (de[i][j] == 0 && de[i + 1][j] == 1 && carry == 0)
{
add[j] = 1;
carry = 0;
}
else if (de[i][j] == 0 && de[i + 1][j] == 1 && carry == 1)
{
add[j] = 0;
carry = 1;
}
else if (de[i + 1][j] == 0 && de[i][j] == 1 && carry == 0)
{
add[j] = 1;
carry = 0;
}
else if (de[i + 1][j] == 0 && de[i][j] == 0 && carry == 0)
{
add[j] = 0;
carry = 0;
}
else if (de[i + 1][j] == 0 && de[i][j] == 0 && carry == 1)
{
add[j] = 1;
carry = 0;
}
}
i = i + 2;
for (k = 0; k < 8; k++)
{
de[i][j] = add[j];
}
if (carry == 1 && i < n)
{
for (k = 0; k < 8; k++)
{
de[i + 1][j] = u[j];
}
goto s;
}
else if (carry == 0 && i < n)
{
for (k = 0; k < 8; k++)
{
de[i + 1][j] = u[j];
}
goto s;
}
for (i = 0; i < 8; i++)
printf("%d", add[i]);
return 0;
}

SetConsoleCursorPosition : Getting black rows in console upon use

Following my previous question about making a snake program more fluid, I went and tried ANSI escape sequences and console functions to put back the text cursor on the top left corner.
I want to get the cursor on the top left corner of the screen, but while it does so I get black stripes across the screen every other line.
I am working in a windows environment making this program for the windows console.
Here is the painting function :
void paint(int tab[28][120], int ligneMax, int colonneMax, HANDLE hconsole)
{
//system("cls");
//printf("\033[1;1H");
COORD destCoord;
destCoord.X = 0;
destCoord.Y = 0;
SetConsoleCursorPosition(hconsole, destCoord);
for (int i = 0; i < ligneMax; i++)
{
for (int j = 0; j < colonneMax; j++)
{
printf("%c", tab[i][j]);
}
printf("\n");
}
}
I tried putting the escape code and console function in the main right before calling the paint function but I got the same results.
here is the whole program if someone wants to test :
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <Windows.h>
void paint(int tab[28][120], int ligneMax, int colonneMax, HANDLE hconsole)
{
//system("cls");
//printf("\033[1;1H");
COORD destCoord;
destCoord.X = 0;
destCoord.Y = 0;
SetConsoleCursorPosition(hconsole, destCoord);
for (int i = 0; i < ligneMax; i++)
{
for (int j = 0; j < colonneMax; j++)
{
printf("%c", tab[i][j]);
}
printf("\n");
}
}
void create(int tab[28][120], int Nbligne, int Nbcolonne,
int randligne, int randcols)
{
for (int i = 0; i < Nbligne; i++)
{
for (int j = 0; j < Nbcolonne; j++)
{
tab[i][j] = ' ';
if (i == 0 || i == Nbligne - 1)
tab[i][j] = 205;
if (j == 0 || j == Nbcolonne - 1)
tab[i][j] = 186;
if (i == 0 && j == 0)
tab[i][j] = 201;
if (i == 0 && j == Nbcolonne - 1)
tab[i][j] = 187;
if (i == Nbligne - 1 && j == 0)
tab[i][j] = 200;
if (i == Nbligne - 1 && j == Nbcolonne - 1)
tab[i][j] = 188;
if (i == 14 && j == 60)
tab[i][j] = 219;
if (i == 14 && j == 59)
tab[i][j] = 79;
if (i == 14 && j == 58)
tab[i][j] = 35;
if (i == randligne && j == randcols)
tab[i][j] = 176;
}
}
}
void destroyTail(int tab[28][120], int Nbligne, int Nbcolonne)
{
for (int i = 0; i < Nbligne; i++)
{
for (int j = 0; j < Nbcolonne; j++)
{
if (tab[i][j] == 35)
{
tab[i][j] = ' ';
if (tab[i][j + 1] == 79)
tab[i][j + 1] = 35;
else if (tab[i][j - 1] == 79)
tab[i][j - 1] = 35;
else if (tab[i + 1][j] == 79)
tab[i + 1][j] = 35;
else if (tab[i - 1][j] == 79)
tab[i - 1][j] = 35;
goto stop;
}
}
}
stop: NULL;
}
void translate(int tab[28][120], char direction, int Nbligne, int Nbcolonne)
{
for (int i = 0; i < Nbligne; i++)
{
for (int j = 0; j < Nbcolonne; j++)
{
if (tab[i][j] == 219)
{
if (direction == 'R')
{
tab[i][j] = 79;
tab[i][j + 1] = 219;
}
if (direction == 'D')
{
tab[i][j] = 79;
tab[i + 1][j] = 219;
}
if (direction == 'L')
{
tab[i][j] = 79;
tab[i][j - 1] = 219;
}
if (direction == 'U')
{
tab[i][j] = 79;
tab[i - 1][j] = 219;
}
goto stop;
}
}
}
stop: NULL;
}
int checkExpand(int tab[28][120], int Nbligne, int Nbcolonne, char direction)
{
for (int i = 0; i < Nbligne; i++)
{
for (int j = 0; j < Nbcolonne; j++)
{
if ((direction == 'R' && tab[i][j] == 219 && tab[i][j + 1] == 176) ||
(direction == 'L' && tab[i][j] == 219 && tab[i][j - 1] == 176) ||
(direction == 'U' && tab[i][j] == 219 && tab[i - 1][j] == 176) ||
(direction == 'D' && tab[i][j] == 219 && tab[i + 1][j] == 176))
return 1;
}
}
return 0;
}
int checkDeath(int tab[28][120], int Nbligne, int Nbcolonne, char direction)
{
for (int i = 0; i < Nbligne; i++)
{
for (int j = 0; j < Nbcolonne; j++)
{
if ((direction == 'R' && tab[i][j] == 219 && (tab[i][j + 1] == 186 || tab[i][j + 1] == 79)) ||
(direction == 'L' && tab[i][j] == 219 && (tab[i][j - 1] == 186 || tab[i][j - 1] == 79)) ||
(direction == 'U' && tab[i][j] == 219 && (tab[i - 1][j] == 205 || tab[i - 1][j] == 79)) ||
(direction == 'D' && tab[i][j] == 219 && (tab[i + 1][j] == 205 || tab[i + 1][j] == 79)))
return 1;
}
}
return 0;
}
int main()
{
HANDLE hConsole;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, 241);
int tab[28][120];
int randligne = rand() % 26 + 1;
int randcols = rand() % 118 + 1;
create(tab, 28, 120, randligne, randcols);
paint(tab, 28, 120, hConsole);
char i = '1';
char direction = 'R';
int eaten = 0;
int expand = 0;
int death = 0;
while(i != 'k')
{
if (kbhit())
i = getch();
switch(i) {
case 'z':
if (direction != 'D')
direction = 'U';
break;
case 's':
if (direction != 'U')
direction = 'D';
break;
case 'd':
if (direction != 'L')
direction = 'R';
break;
case 'q':
if (direction != 'R')
direction = 'L';
break;
}
randligne = rand() % 26 + 1;
randcols = rand() % 118 + 1;
death = checkDeath(tab, 28, 120, direction);
if (death == 1)
break;
translate(tab, direction, 28, 120);
expand = checkExpand(tab, 28, 120, direction);
if (expand == 0)
destroyTail(tab, 28, 120);
else
{
while (tab[randligne][randcols] != ' ')
{
randligne = rand() % 26 + 1;
randcols = rand() % 118 + 1;
}
tab[randligne][randcols] = 176;
eaten++;
}
printf("Number of biscuits eaten : %d ; direction : %c ; expand : %d", eaten, direction, expand);
paint(tab, 28, 120, hConsole);
Sleep(100);
}
while(i != 'k')
{
if (kbhit())
i = getch();
}
}
Too much code to take in quickly. If you have Windows console ouput for the snake, can't you simply printf the next line and leave it at that?
If you want to hide the cursor (instead of trying to park it out of sight) you can make it invisible by calling SetConsoleCursorInfo and the struct passed is shown here.

C algorithm to try out all the possible combinations of 12 knights in a chess board

I have been writing this program that tries to find how to put 12 knights on a chess board so all squares are either taken up by a knight or one of 12 knights can reach them in one move. So far I have created 2 functions: one takes a board with 12 knights and fills all the squares they can reach with 'T' and another that takes a filled chess board and checks if there are left any squares not taken up by a knight nor dominated by it (meaning no knight can reach it in one move).
Now I am dealing with the problem of how can I try out all the possible combinations of knights. My idea is that after every single combination of 12 knights on a board, I will send the board with 12 knights to be filled with 'T's for all the squares they can reach, and then send it to another function to check if all squares are dominated.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
int filling(char array[8][8])
{
int i, j;
for (i = 0;i < 8;i++)
{
for (j = 0; j < 8;j++)
{
if(array[i][j] == 'H')
{
if(i-1>-1 && j+2<8 && array[i-1][j+2]!='H') array[i-1][j+2]='T';
if(i+1<8 && j+2<8 && array[i+1][j+2]!='H') array[i+1][j+2]='T';
if(i-2>-1 && j+1<8 && array[i-2][j+1]!='H') array[i-2][j+1]='T';
if(i+2<8 && j+1<8 && array[i+2][j+1]!='H') array[i+2][j+1]='T';
if(i-2>-1 && j-1>-1 && array[i-2][j-1]!='H') array[i-2][j-1]='T';
if(i+2<8 && j-1>-1 && array[i+2][j-1]!='H') array[i+2][j-1]='T';
if(i-1>-1 && j-2>-1 && array[i-1][j-2]!='H') array[i-1][j-2]='T';
if(i+1<8 && j-2>-1 && array[i+1][j-2]!='H') array[i+1][j-2]='T';
}
}
}
}
int checking(char array[8][8])
{
int i, j;
for(i = 0;i < 8;i++)
{
for(j = 0;j < 8;j++)
{
if(array[i][j] != 'H' && array[i][j] != 'T')
return 0;
}
}
return 1;
}
int main()
{
int i, j;
char board[8][8];
for(i = 0; i < 8; i++)
{
for(j = 0; j < 8; j++)
board[i][j] = '0';
}
// The following lines are here to test if the checking and filling work
/*board[2][1] = 'H';
board[2][2] = 'H';
board[3][2] = 'H';
board[5][2] = 'H';
board[6][2] = 'H';
board[5][3] = 'H';
board[2][4] = 'H';
board[1][5] = 'H';
board[2][5] = 'H';
board[4][5] = 'H';
board[5][5] = 'H';
board[5][6] = 'H'; */
filling(board);
if(checking(board) == 1) printf (" \n Works");
else printf ("\n Doesnt work");
for(i = 0; i < 8; i++)
{
printf("\n");
for(j = 0; j < 8; j++)
printf("%c ", board[i][j]);
}
return 0;
}
What kind of algorithm I could use to try out every combo? Thank you for your answers.
You need these things:
A sorting rule that puts all possible combinations in a well-defined order.
An initialization rule that defines the board's first such combination.
An increment rule that transitions a board from its current combination to the next combination in the well-defined order.
A rule that detects when the board is in the last combination.
Then you just use algorithm 2 to put the board in the first state. Then check with algorithm 4 to see if you're in the last state. If not, use algorithm 3 to go to the next state.
Algorithm 1 is probably the hard one. One simple rule is just to convert the board's position to a binary number with a zero for an empty square and a one for a full square in a well-defined order, say starting from the top left and going across, then moving to the next row.
If you're on decent, or even semi-decent hardware, you've got a 64-bit unsigned integral type available to you. Let's call that uint64_t.
You can store a chessboard with knight positions as a single uint64_t. You can also store a "dominated" mask in the same type. You simply establish a correlation between the 64 bits in the type and the 64 spaces on the chessboard.
Since there are 64 possible locations, you can pre-compute the possible threat masks for each position, storing that as an array of 64 uint64_t values.
You need to set the position of each knight. But you can safely do them in a certain order, so that knight #1 is always the "highest" knight - his bit position is always highest, or lowest, or whatever. So you could write code like this:
for (k0 = 64; k0 > 11; --k0)
for (k1 = k0 - 1; k1 > 10; --k1)
for (k2 = k1 - 1; k2 > 9; --k2)
...
for (k11 = k10 - 1; k11 >= 0; --k11)
/* do stuff */
But that's horrible, because there are a squillion possibilities (squillion = 1573144097507348889600, thanks #jwd!).
That said, the threat mask for each knight can be computed "incrementally" from the masks of the outer knights, so it might be faster to perform all the computations than to try to store/mark/compute the rotations and flips of the board.
Something like this:
for (kXX = kYY - 1; kXX > (11-XX); --kXX) {
threat_XX = threat_YY | pre_computed_threat[kXX];
for (kZZ = KXX - 1; kZZ > (11-ZZ); --kZZ) {
threat_ZZ = threat_XX | pre_computed_threat[kZZ];
The nice thing about this approach is that your objective is total coverage by threats - all 1 bits in the threat_11 map, in other words. You can test just by inverting the bits and comparing with zero.
Well thanks to my questions of today I got myself blocked from asking more until my rep gets better, but for what its worth I managed to solve the problem myself. I had to take 3 positions in each quarter of the board that can only be reached by seperate horses, that way making my 12 for cycles shorter, as they only had to go through specific locations, instead of trying every single of of them. The execution times is just above one second and it finds two different layouts for 12 knights, marking them 'H' and the positions they can reach in one turn 'T'. Here is the code if anyone ever comes to a problem like this:
#include <stdio.h>
#include <stdlib.h>
struct horses
{
int x;
int y;
};
void fill(struct horses arkliai[12], char array[8][8])
{
int i,j;
for(i = 0; i < 8; i++)
{
for(j = 0; j < 8; j++)
array[i][j] = '0';
}
for(i = 0; i < 12; i++)
{
array[arkliai[i].x][arkliai[i].y] = 'H';
}
pildymas(array);
}
void startingpositions(struct horses arkliai[12])
{
int i = 0;
int j = 0;
int a = 0;
for(a = 0; a < 12; a++)
{
if(i > 7)
{
i = 0;
j++;
}
arkliai[a].x = i;
arkliai[a].y = j;
i++;
}
}
void combinacijos(struct horses h[12], char array[8][8])
{
int a,b,c,d,e,f,g,hi,ii,ji,k,l;
for(a = 0; a < 2; a++)
{
if(a == 0)
{
h[0].x = 1;
h[0].y = 2;
}
if(a == 1)
{
h[0].x = 2;
h[0].y = 1;
}
for(b = 0; b < 2; b++)
{
if(b == 0)
{
h[1].x = 5;
h[1].y = 1;
}
if(b == 1)
{
h[1].x = 6;
h[1].y = 2;
}
for(c = 0; c < 2; c++)
{
if(c == 0)
{
h[2].x = 1;
h[2].y = 5;
}
if(c == 1)
{
h[2].x = 2;
h[2].y = 6;
}
for(d = 0; d <2;d++)
{
if(d == 0)
{
h[3].x = 5;
h[3].y = 6;
}
if(d == 1)
{
h[3].x = 6;
h[3].y = 5;
}
for(e = 0; e < 3; e++)
{
if(e == 0)
{
h[4].x = 2;
h[4].y = 0;
}
if(e == 1)
{
h[4].x = 2;
h[4].y = 2;
}
if(e == 2)
{
h[4].x = 1;
h[4].y = 3;
}
for (f = 0; f < 3; f++)
{
if(f == 0)
{
h[5].x = 1;
h[5].y = 4;
}
if(f == 1)
{
h[5].x = 2;
h[5].y = 5;
}
if(f == 2)
{
h[5].x = 2;
h[5].y = 7;
}
for (g = 0; g < 3; g++)
{
if(g == 0)
{
h[6].x = 5;
h[6].y = 7;
}
if(g == 1)
{
h[6].x = 5;
h[6].y = 5;
}
if(g == 2)
{
h[6].x = 6;
h[6].y = 4;
}
for(hi = 0; hi < 3; hi++)
{
if(hi == 0)
{
h[7].x = 5;
h[7].y = 0;
}
if(hi == 1)
{
h[7].x = 5;
h[7].y = 2;
}
if(hi == 2)
{
h[7].x = 6;
h[7].y = 3;
}
for(ii = 0; ii < 4; ii++)
{
if (ii == 0)
{
h[8].x = 3;
h[8].y = 0;
}
if (ii == 1)
{
h[8].x = 3;
h[8].y = 2;
}
if (ii == 2)
{
h[8].x = 0;
h[8].y = 3;
}
if (ii == 3)
{
h[8].x = 2;
h[8].y = 3;
}
for(ji = 0; ji < 4; ji++)
{
if (ji == 0)
{
h[9].x = 3;
h[9].y = 7;
}
if (ji == 1)
{
h[9].x = 3;
h[9].y = 5;
}
if (ji == 2)
{
h[9].x = 2;
h[9].y = 4;
}
if (ji == 3)
{
h[9].x = 0;
h[9].y = 4;
}
for(k = 0; k < 4; k++)
{
if (k == 0)
{
h[10].x = 4;
h[10].y = 7;
}
if (k == 1)
{
h[10].x = 4;
h[10].y = 5;
}
if (k == 2)
{
h[10].x = 5;
h[10].y = 4;
}
if (k == 3)
{
h[10].x = 7;
h[10].y = 4;
}
for(l = 0;l < 64;l++)
{
if(h[11].x == 7)
{
if(h[11].y == 7)
{
h[11].x = 0;
h[11].y = 0;
break;
}
h[11].x = 0;
h[11].y = h[11].y +1;
}
else { h[11].x= h[11].x+1; }
fill(h, array);
}
}
}
}
}
}
}
}
}
}
}
}
}
int pildymas(char array[8][8])
{
int i, j;
for (i = 0;i < 8;i++)
{
for (j = 0; j < 8;j++)
{
if(array[i][j] == 'H')
{
if(i-1>-1 && j+2<8 && array[i-1][j+2]!='H') array[i-1][j+2]='T';
if(i+1<8 && j+2<8 && array[i+1][j+2]!='H') array[i+1][j+2]='T';
if(i-2>-1 && j+1<8 && array[i-2][j+1]!='H') array[i-2][j+1]='T';
if(i+2<8 && j+1<8 && array[i+2][j+1]!='H') array[i+2][j+1]='T';
if(i-2>-1 && j-1>-1 && array[i-2][j-1]!='H') array[i-2][j-1]='T';
if(i+2<8 && j-1>-1 && array[i+2][j-1]!='H') array[i+2][j-1]='T';
if(i-1>-1 && j-2>-1 && array[i-1][j-2]!='H') array[i-1][j-2]='T';
if(i+1<8 && j-2>-1 && array[i+1][j-2]!='H') array[i+1][j-2]='T';
}
}
}
tikrinimas(array);
}
int tikrinimas(char array[8][8])
{
int i, j;
for(i = 0;i < 8;i++)
{
for(j = 0;j < 8;j++)
{
if(array[i][j] != 'H' && array[i][j] != 'T')
return 0;
}
}
printas(array);
}
int printas(char array[8][8])
{
int i,j;
for(j = 0; j <8; j++)
{
printf("\n");
for(i = 0; i <8 ; i++)
printf("%c ", array[i][7-j]);
}
printf("\n");
}
int main()
{
struct horses hr[12];
char board[8][8];
startingpositions(hr);
combinacijos(hr, board);
return 0;
}

Resources