-
June 11th, 2022, 01:35 PM
#1
help with hobby programming in C++
I am posting the C++ code I worked on . It is working, but with some glitch, and with slow execution. I need help with code optimization. Thanks.
Code:
// Program for finding max movement possible of a knight on Chess board.
// A random location is allocated as starting point and with pressing any key (other than
// return), the program shows the next move of knight. This continues untill user press ENTER
//key or no further move is possible on unlanded position.
#include<iostream>
#include<vector>
#include<time.h>
#include<conio.h>
#define f(i,n) for (auto i=0;i<n;i++)
using namespace std;
char a[8][8]
{{'O','O','O','O','O','O','O','O',},
{'O','O','O','O','O','O','O','O',},
{'O','O','O','O','O','O','O','O',},
{'O','O','O','O','O','O','O','O',},
{'O','O','O','O','O','O','O','O',},
{'O','O','O','O','O','O','O','O',},
{'O','O','O','O','O','O','O','O',},
{'O','O','O','O','O','O','O','O',},};
int l=0,m=0,count=0;
void disp(int i,int j)
{
system("cls");
a[l+i][m+j]='X';
count++;
l+=i;
m+=j;
f(i,8)
{
f(j,8)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<"\n\nMoved to ("<<m+1<<','<<l+1<<')'<<endl;
cout<<"\nToatl moves : "<<count<<endl;
}
int main()
{
srand(time(0));
int k=0;
vector <int>v;
bool b[8]={0};
int count =0,q=0;
// cout<<"A random number :"<<rand()<<endl;
int i=rand()%8;
int j=rand()%8;
a[i][j]='X';
disp(i,j);
char g='a';
do
{
if(i+2<8)
{
if(j+1<8 && a[i+2][j+1]=='O')
b[0]=1;
if (j-1>=0 && a[i+2][j-1]=='O')
b[1]=1;
}
if(i-2>=0)
{
if(j+1<8 && a[i-2][j+1]=='O')
b[2]=1;
if (j-1>=0 && a[i-2][j-1]=='O')
b[3]=1;
}
if(j-2>=0)
{
if(i+1<8 && a[j-2][i+1]=='O')
b[4]=1;
if (i-1>=0 && a[j-2][i-1]=='O')
b[5]=1;
}
if(j+2<8)
{
if(i+1<8 && a[j+2][i+1]=='O')
b[6]=1;
if (i-1>=0 && a[j+2][i-1]=='O')
b[7]=1;
}
f(i,8)if(b[i])v.push_back(i);
// if(v.size()==0)cout<<"Empty moves...\n\n";
k=rand()%(v.size());
switch(v[k])
{
case 0: disp(2,1);i+=2;j+=1;break;
case 1: disp(2,-1);i+=2;j-=1;break;
case 2: disp(-2,1);i-=2;j+=1;break;
case 3: disp(-2,-1);i-=2;j-=1;break;
case 4: disp(1,-2);i+=1;j-=2;break;
case 5: disp(-1,-2);i-=1;j-=2;break;
case 6: disp(1,2);i+=1;j+=2;break;
default: disp(-1,2);i-=1;j+=2;break;
}
f(i,8)b[i]=0;
v.clear();
g=getch();
//else cout<<" Further movement not possible.\n\nTotal movements : "<<count<<endl;
}while(g!=13 && v.empty()
);
return 0;
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|