Recursive backtracking knights tour in c ++ - recursion

So, in short I'm working on a knight's tour program. If you don't know what that is, the knight gets put on the chess board and you have to move it to every spot on the board exactly once. I'm using a recursive function but am having trouble getting my backtracking to work. I can get to 22 steps in a 5x5 board but the program won't back up and try a different path. I'm posting just the recursive part of my code (sorry it's a little long) Any insight would be extremely helpful. Thanks a lot!
`bool findPath ( int board[][boardSize + 4], int &currRow, int &currCol, int &currMove,int boardSize )
{
int i, j;
bool foundSpot;
board[currRow][currCol] = currMove;
if ( currMove == boardSize * boardSize )
return true;
for ( i = 0; i < boardSize + 4; i++ )
{
for ( j = 0; j < boardSize + 4; j++ )
cout << setw (3) << board[i][j];
cout<<endl;
}
cout << endl;
if ( board[currRow - 2][currCol - 1] == 0 )
{
currMove += 1;
board[currRow - 2][currCol - 1] = currMove;
currRow -= 2;
currCol -= 1;
if ( findPath( board, currRow, currCol, currMove, boardSize ) )
return true;
}
if ( board[currRow - 2][currCol + 1] == 0 )
{
currMove += 1;
board[currRow - 2][currCol + 1] = currMove ;
currRow -= 2;
currCol += 1;
if ( findPath( board, currRow, currCol, currMove, boardSize ) )
return true;
}
if ( board[currRow - 1][currCol + 2] == 0 )
{
currMove += 1;
board[currRow - 1][currCol + 2] = currMove ;
currRow -= 1;
currCol += 2;
if ( findPath( board, currRow, currCol, currMove, boardSize ) )
return true;
}
if ( board[currRow + 1][currCol + 2] == 0 )
{
currMove += 1;
board[currRow + 1][currCol + 2] = currMove ;
currRow += 1;
currCol += 2;
if ( findPath( board, currRow, currCol, currMove, boardSize ) )
return true;
}
if ( board[currRow + 2][currCol + 1] == 0 )
{
currMove += 1;
board[currRow + 2][currCol + 1] = currMove ;
currRow += 2;
currCol += 1;
if ( findPath( board, currRow, currCol, currMove, boardSize ) )
return true;
}
if ( board[currRow + 2][currCol - 1] == 0 )
{
currMove += 1;
board[currRow + 2][currCol - 1] = currMove ;
currRow += 2;
currCol -= 1;
if ( findPath( board, currRow, currCol, currMove, boardSize ) )
return true;
}
if ( board[currRow + 1][currCol - 2] == 0 )
{
currMove += 1;
board[currRow + 1][currCol - 2] = currMove ;
currRow += 1;
currCol -= 2;
if ( findPath( board, currRow, currCol, currMove, boardSize ) )
return true;
}
if ( board[currRow - 1][currCol - 2] == 0 )
{
currMove += 1;
board[currRow - 1][currCol - 2] = currMove ;
currRow -= 1;
currCol -= 2;
if ( findPath( board, currRow, currCol, currMove, boardSize ) )
return true;
}
board[currRow][currCol] = 0;
currMove -= 2;
return false;
}`

I worked out the following implementation of the Knights tour in c++ :
#include<cstdio>
#include<iostream>
#define MAX 10
using namespace std;
int tour=1;
int board[MAX][MAX];
bool is_travelled(int,int);
bool knights_tour(int,int,int,int);
void initialize(int);
void display(int);
int main(int argc,char** argv){
int n;
scanf("%d",&n);
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
board[i][j]=-1;
}
}
initialize(n);
display(n);
return 0;
}
bool is_travelled(int x,int y){
if(x<0 || y<0)return true;
if(board[x][y]==-1)return false;
return true;
}
bool knights_tour(int i,int j,int n,int k){ // k=number of places remained , n=side of chess_board;
int x,y;
if(k==0)return true;
// hard-coded cases;
// reordering of the cases have significant effect on the execution time
x=i+2;y=j+1;
if((!is_travelled(x,y))&&x<n&&y<n){
board[x][y]=tour;
tour+=1;
if(knights_tour(x,y,n,k-1))return true;
board[x][y]=-1;
tour-=1;
}
x=i+1;y=j+2;
if((!is_travelled(x,y))&&x<n&&y<n){
board[x][y]=tour;
tour+=1;
if(knights_tour(x,y,n,k-1))return true;
board[x][y]=-1;
tour-=1;
}
x=i-1;y=j+2;
if((!is_travelled(x,y))&&x<n&&y<n){
board[x][y]=tour;
tour+=1;
if(knights_tour(x,y,n,k-1))return true;
board[x][y]=-1;
tour-=1;
}
x=i-2;y=j+1;
if((!is_travelled(x,y))&&x<n&&y<n){
board[x][y]=tour;
tour+=1;
if(knights_tour(x,y,n,k-1))return true;
board[x][y]=-1;
tour-=1;
}
x=i-2;y=j-1;
if((!is_travelled(x,y))&&x<n&&y<n){
board[x][y]=tour;
tour+=1;
if(knights_tour(x,y,n,k-1))return true;
board[x][y]=-1;
tour-=1;
}
x=i-1;y=j-2;
if((!is_travelled(x,y))&&x<n&&y<n){
board[x][y]=tour;
tour+=1;
if(knights_tour(x,y,n,k-1))return true;
board[x][y]=-1;
tour-=1;
}
x=i+1;y=j-2;
if((!is_travelled(x,y))&&x+y<n&&x<n&&y<n){
board[x][y]=tour;
tour+=1;
if(knights_tour(x,y,n,k-1))return true;
board[x][y]=-1;
tour-=1;
}
x=i+2;y=j-1;
if((!is_travelled(x,y))&&x<n&&y<n){
board[x][y]=tour;
tour+=1;
if(knights_tour(x,y,n,k-1))return true;
board[x][y]=-1;
tour-=1;
}
return false;
}
void initialize(int n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
board[i][j]=0;
int r=knights_tour(i,j,n,n*n-1);
if(r==1)return;
board[i][j]=-1;
}
}
}
void display(int n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%2d ",board[i][j]);
}
printf("\n");
}
cout<<endl;
}
Hope this helps .
Happy Coding !

Related

Check IP active address with Qt

i'd need to check all the active IP address in my LAN.
i tried with this code:
void MainWindow::on_pushButton_clicked() {
QString baseNetowrk = "192.168.1.";
for(int i = 0;i < 255;i++) {
QString currIp = (baseNetowrk + "%1").arg(i);
//qDebug() << "IP: " << currIp;
QHostInfo hostInfo = QHostInfo::fromName(currIp);
qDebug() << "NOME: " << hostInfo.hostName();
}
}
But this shows all IP (I think in the ARP cache).
How can i only display active IP?
ok, this code works:
void MainWindow::on_pushButton_clicked() {
QString baseNetowrk = "192.168.1.";
#if defined(WIN32)
QString parameter = "-n 1";
#else
QString parameter = "-c 1";
#endif
for(int i = 0; i < 256; i++) {
QString currIp(baseNetowrk + QString::number(i));
int exitCode = QProcess::execute("ping", QStringList() << parameter << currIp);
if (exitCode == 0) {
qDebug() << "OK :" << baseNetowrk + i;
} else {
qDebug() << "KO";
}
}
}
the only problem is that it is a little bit slow....
All ip adress
foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) {
if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost))
qDebug() << address.toString();
}
or ARP scan
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
for(int i = 0; i < ipAddressesList.size(); ++ i) {
if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
ipAddressesList.at(i).toIPv4Address()) {
ipAddress = ipAddressesList.at(i).toString();
if(ipAddress.left(3) == "192") {
break;
}
}
}
ipAddress = ipAddress.left(ipAddress.lastIndexOf(".") + 1);
for(int i = 0; i <= 255; ++i ) {
m_socketsPool.append(new QTcpSocket(this));
QString currentHost = ipAddress + QString::number(i);
connect(m_socketsPool.at(i), SIGNAL(readyRead()), this, SLOT(readFortune()));
connect(m_socketsPool.at(i), SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
m_socketsPool.at(i)->connectToHost(currentHost, yourHost);
}
void readFortune()
{
int i = 0;
for(; i < m_socketsPool.size(); ++i) {
if(sender() == m_socketsPool.at(i)) {
QString currentHost = ipAddress + QString::number(i);
qDebug()<<currentHost;
ipStringList +=(QStringList() << currentHost);
break;
}
}
emit onOutStr(ipStringList);
}
Hi you might want to try using regular expressions
QString IpRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])";
QRegularExpression IpRegex ("^" + IpRange
+ "(\\." + IpRange + ")"
+ "(\\." + IpRange + ")"
+ "(\\." + IpRange + ")$");
QRegularExpressionValidator *ipValidator = new QRegularExpressionValidator(IpRegex, this);

msp430f2618 fading LED using pwm

I'm trying to write code in C to fade an off-board LED using PWM and the MSP430f2618. I can get the LED to turn on but it stays at full intensity. I am trying to read in an array of frequency values and fade the LED based on the frequency values.
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer
int array_size = 0, i = 0, delay = 0;
double frequency[50] = {0.0};
array_size = sizeof(frequency);
frequency [0] = 60.0;
for (i = 1; i < array_size; i++)
{
if (frequency[i - 1] < 61)
{
frequency[i] = frequency[i-1] + 0.1;
}
else
{
frequency[i] = 60.0;
}
}
P4OUT &= 0;
P4DIR |= (BIT1 + BIT2); //P4.1 and P4.2 output
P4SEL &= ~(BIT1 + BIT2); //P4.1 and P4.2 TBx options, timer select
TBCCR0 = 512-1;
TBCCTL1 = OUTMOD_7;
TBCCTL2 = OUTMOD_7;
for (i = 0; i < array_size; i++)
{
P4OUT &= 0;
if ((frequency[i] < 60.2) && (frequency[i] >=60.0))
{
//TBCCR1 = 3200;
TBCCR1 = 384;
}
else if ((frequency[i] < 60.4) && (frequency[i] >=60.2))
{
//TBCCR1 = 2560;
TBCCR1 = 256;
}
else if ((frequency[i] < 60.6) && (frequency[i] >=60.4))
{
//TBCCR1 = 1920;
TBCCR1 = 128;
}
else if ((frequency[i] < 60.8) && (frequency[i] >=60.6))
{
//TBCCR1 = 1280;
TBCCR1 = 64;
}
else if ((frequency[i] < 61) && (frequency[i] >=60.8))
{
//TBCCR1 = 640;
TBCCR1 = 32;
}
else
{
TBCCR2 = 512;
}
P4OUT ^= BIT1;
for (delay = 0; delay < 32000; delay++);
}
TBCTL = TBSSEL_2 + MC_1; // ACLK, up mode
__bis_SR_register(LPM0_bits); // Enter LPM3
return 0;
}
The timer is not running until you start it by setting the MC field. That initialization must be done at the beginning.

Word Search using Multidimensional arrays

This program is supposed to allow the user to enter a word to be searched for in a multi-dimensional array filled with characters. The word can be in any non-diagonal direction.
As it is written it will only find the correct location for a one character long word. I understand that it will only find the first instance of any word entered but that is okay. I cannot figure out why it will not find words longer than one character.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <string.h>
#define GRIDSIZE 10
#define MAXSIZE 15 //Max size for word to search
#define SENTINEL -1
void print_grid(int[][GRIDSIZE], int);
int search_grid(int[][GRIDSIZE], int, int[], int, int[], int[]);
int main(void){
int grid[GRIDSIZE][GRIDSIZE];
int grid_size;
char word[MAXSIZE];
int word_int[MAXSIZE];
int a,b,i,j,h;
int word_size;
int word_found;
int go_again;
int location_row[word_size];
int location_column[word_size];
srand(time(NULL));
//fills grid with random letters
for(i=0; i<10; i++){
for(j=0; j<10; j++){
do{grid[i][j] = rand() % 123;
}while(grid[i][j]<97);
}}
//gets word and searches for it, returns 1 or 0 for found or not
//exits of sentinel is entered
do{
print_grid(grid, grid_size);
printf("Please enter a word to search followed by 'ENTER':\n");
scanf(" %s", word);
word_size = strlen(word);
for(b=0; b < word_size; b++){
word_int[b] = word [b];
}
word_found = search_grid(grid, grid_size, word_int, word_size, location_row, location_column);
("%d", word_found);
if(word_found == 0){
printf("\nThe word you entered was not found\n");
printf("Enter '1' to search for another word, or '0' to exit, followed by 'ENTER'\n");
scanf(" %d", &go_again);
}
}while(word_found != 1 && go_again == 1);
if(word_found == 1){
printf("The word you entered was found at:\n");
for(h=0; h < word_size; h++){
printf("%c%d: ", toupper(location_row[h] + 97), location_column[h]+1);
}
print_grid(grid, grid_size);
}
return 0;
}
//prints N*N grid with labels on each axis
void print_grid(int grid[][GRIDSIZE], int grid_size){
int i,j,k;
char row[26] ="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("\n");
printf(" ");
for(k=1; k < GRIDSIZE +1; k++){
printf("%d ", k);}
printf("\n");
for(i=0; i<10; i++){
printf("%-c ", row[i]);
for(j=0; j<10; j++){
printf("%-c ", grid[i][j]);
}
printf("\n");
}
printf("\n");
return;
}
//searches grid for word
int search_grid(int grid[][GRIDSIZE], int gride_size, int word_int[], int word_size, int location_row[], int location_column[]){
//printf("SEARCH GRID RAN//////////////////////");
int r, c, q;
int num = 0;
int found[word_size];
int found_total = 0;
for(q=0; q < word_size; q++){
found[q] = 0;}
//search loops
for(r=0; r < GRIDSIZE; r++){
for(c=0; c < GRIDSIZE; c++){
if(grid[r][c] == word_int[num]){
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
for(num=1; num < word_size; num ++){
if(r=0){
if(c=0){
if(grid[location_row[num-1]][location_column[num-1]+1] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]+1][location_column[num-1]] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
//CHECK DOWN AND RIGHT
}
if(c = GRIDSIZE - 1){
if(grid[location_row[num-1]][location_column[num-1]-1] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]][location_column[num-1]+1] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]+1][location_column[num-1]] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
//CHECK DOWN AND LEFT
}
else{
if(grid[location_row[num-1]][location_column[num-1]-1] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]][location_column[num-1]+1] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]+1][location_column[num-1]] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
//CHECK LEFT RIGHT DOWN
}
}
if(r = GRIDSIZE - 1){
if(c=0){
if(grid[location_row[num-1]][location_column[num-1]+1] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]-1][location_column[num-1]] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
//CHECK up AND RIGHT
}
if(c = GRIDSIZE - 1){
if(grid[location_row[num-1]][location_column[num-1]-1] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]-1][location_column[num-1]] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
//CHECK UP AND LEFT
}
else{
if(grid[location_row[num-1]][location_column[num-1]-1] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]][location_column[num-1]+1] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]-1][location_column[num-1]] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
//CHECK LEFT RIGHT UP
}
}
else{
if(c=0){
if(grid[location_row[num-1]-1][location_column[num-1]] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]+1][location_column[num-1]] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]][location_column[num-1]+1] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
//CHECK UP DOWN AND RIGHT
}
if(c = GRIDSIZE - 1){
if(grid[location_row[num-1]-1][location_column[num-1]] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]+1][location_column[num-1]] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]][location_column[num-1]-1] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
//CHECK UP DOWN AND LEFT
}
else{
if(grid[location_row[num-1]][location_column[num-1]-1] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]][location_column[num-1]+1] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]-1][location_column[num-1]] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
if(grid[location_row[num-1]+1][location_column[num-1]] == word_int[num])
found[num] = 1;
location_row[num] = r;
location_column[num] = c;
//CHECK LEFT RIGHT UP DOWN
}
}
}
}
}
}
for(q=0; q < word_size; q++){
found_total += found[q];
}
//printf("FOUND TOTAL %d", found_total);
if(found_total == word_size){
return 1;
}
if(found_total != word_size){
return 0;
}
}

Recursion with test case

I am trying to code following recursion problem. Every time I run the test case it gives me out of bound error on the else if line. How do I fix the out of bound error. under the code is the test case.
static boolean allEqual(int[] a, int start, int end) {
if( a[start + 1]>=a.length){return false;}
if (start == end && a[start] == a[end]) {
return true;
}
///recursive
else if (a[start] == a[start + 1]) // Error over here
{
return allEqual(a, start + 1, end);
}
// else if (start == end && a[start] == a[end]) {
// return true;
else {
return false;
}
}
// Following is the test case
Random rng = new Random(SEED);
for(int i = 0; i < RUNS; i++) {
int[] a = new int[i];
int v = rng.nextInt();
for(int j = 0; j < i; j++) {
a[j] = v;
}
assertTrue(rp.allEqual(a, 0, i-1));
for(int j = 1; j < i; j++) {
assertTrue(rp.allEqual(a, j, i-1));
assertTrue(rp.allEqual(a, 0, j));
a[j] = a[j] - 1;
assertTrue(rp.allEqual(a, 0, j-1));
assertTrue(rp.allEqual(a, j + 1, i-1));
assertFalse(rp.allEqual(a, 0, i-1));
a[j] = a[j] + 2;
assertTrue(rp.allEqual(a, 0, j-1));
assertTrue(rp.allEqual(a, j + 1, i-1));
assertFalse(rp.allEqual(a, 0, i-1));
a[j] = a[j] - 1;
}
}

How can i make this program look at more than the first character?

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
const int setNum = 26;
vector<char> normalV(setNum);
vector<char> cipherV(setNum);
string toDec = "";
string beenDec = "";
int i = 0;
normalV.at(i) = 'a'; cipherV.at(i) = '!'; ++i;
normalV.at(i) = 'b'; cipherV.at(i) = '^'; ++i;
normalV.at(i) = 'c'; cipherV.at(i) = '&'; ++i;
normalV.at(i) = 'd'; cipherV.at(i) = '*'; ++i;
normalV.at(i) = 'e'; cipherV.at(i) = '#'; ++i;
normalV.at(i) = 'f'; cipherV.at(i) = '('; ++i;
normalV.at(i) = 'g'; cipherV.at(i) = ')'; ++i;
normalV.at(i) = 'h'; cipherV.at(i) = '-'; ++i;
normalV.at(i) = 'i'; cipherV.at(i) = '#'; ++i;
normalV.at(i) = 'j'; cipherV.at(i) = '_'; ++i;
normalV.at(i) = 'k'; cipherV.at(i) = '='; ++i;
normalV.at(i) = 'l'; cipherV.at(i) = '+'; ++i;
normalV.at(i) = 'm'; cipherV.at(i) = '['; ++i;
normalV.at(i) = 'n'; cipherV.at(i) = '{'; ++i;
normalV.at(i) = 'o'; cipherV.at(i) = '$'; ++i;
normalV.at(i) = 'p'; cipherV.at(i) = ']'; ++i;
normalV.at(i) = 'q'; cipherV.at(i) = '}'; ++i;
normalV.at(i) = 'r'; cipherV.at(i) = ';'; ++i;
normalV.at(i) = 's'; cipherV.at(i) = ':'; ++i;
normalV.at(i) = 't'; cipherV.at(i) = ','; ++i;
normalV.at(i) = 'u'; cipherV.at(i) = '%'; ++i;
normalV.at(i) = 'v'; cipherV.at(i) = '<'; ++i;
normalV.at(i) = 'w'; cipherV.at(i) = '.'; ++i;
normalV.at(i) = 'x'; cipherV.at(i) = '>'; ++i;
normalV.at(i) = 'y'; cipherV.at(i) = '/'; ++i;
normalV.at(i) = 'z'; cipherV.at(i) = '?'; ++i;
// User inputs message
do {
cout << "Enter a secret message: ";
getline(cin, toDec);
} while (toDec.length() == 0);
beenDec = toDec;
//decodes user's message
for (i = 0; i < setNum; ++i){
if (toDec.at(0) == cipherV.at(i)) {
beenDec.at(0) = normalV.at(i);
}
}
//diplays decoded message
cout << "Decrypted message: " << beenDec << endl;
//command drive to stay open
cin.get();
cin.get();
return 0;
}
Any help can be appreciated. The code is supposed to decode a string for example "!^&" should output to "abc". Right now it just decodes the first letter like this "a^&". I feel like this is because it is defined as a char and not a string however it gives me error if i change it up. Any idea on how i can modify this to work? Thanks in advance
I think the loop should be like this -:
//decodes user's message
for ( unsigned j = 0; j < toDec.length(); j++ )
{
for ( i = 0; i < setNum; ++i )
{
if ( toDec.at( j ) == cipherV.at( i ) )
{
beenDec.at( j ) = normalV.at( i );
}
}
}

Resources