Friday, 3 November 2017

N Queens Chess Problem Solution using C++

The N Queens Problem is the problem of placing N chess queens on an N×N chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. The eight queens puzzle is an example of the N queens problem of placing N non-attacking queens on an N×N chessboard, for which solutions exist for all natural numbers N with the exception of N=2 and N=3.

In the code, backtracking method is used to solve the problem. A queen is placed in a column that is known not to cause conflict. If a column is not found the program returns to the last good state and then tries a different column by increments or decrements the column index.

//A C++ code to Solve N-Queen Chess problem

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <conio.h>

const unsigned int N = 8;
using namespace std;

// Print N Queen chess problem solution
void PrintNQSolution(bool board[N][N])
{
     for (int i = 0; i < N; i++)
     {
           for (int j = 0; j < N; j++)
                cout << board[i][j] << "  ";
           cout << endl;
     }
}

/* check if a queen can be placed on the board[row][col]*/
bool CheckSafe(bool board[N][N], int row, int col)
{
     int i, j;
     for (i = 0; i < col; i++)
     {
           if (board[row][i])
                return false;
     }
     for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
     {
           if (board[i][j])
                return false;
     }

     for (i = row, j = col; j >= 0 && i < N; i++, j--)
     {
           if (board[i][j])
                return false;
     }

     return true;
}

/*solve N Queen problem */
bool SolveNQ(bool board[N][N], int col)
{
     if (col >= N)
           return true;
     for (int i = 0; i < N; i++)
     {
           if (CheckSafe(board, i, col))
           {
                board[i][col] = true;
                if (SolveNQ(board, col + 1) == true)
                     return true;
                board[i][col] = false;
           }
     }
     return false;
}

/* solves the N Queen problem using Backtracking and print the solution.*/
bool SolveAndPrintNQ()
{
     bool board[N][N] = { 0 };
     if (SolveNQ(board, 0) == false)
     {
           cout << "Solution does not exist" << endl;
           return false;
     }
     PrintNQSolution(board);
     return true;
}

int main()
{
     cout << "**** " << N << " Queens Problem Solution *****\n\n";
     SolveAndPrintNQ();
     _getch();
     return 0;
}


Output:

Sunday, 22 October 2017

A Strong Random Password Generator Using C/C++

random password generator is software program or hardware device that takes input from a random or pseudo-random number generator and automatically generates a password. Random passwords can be generated manually, using simple sources of randomness such as dice or coins, or they can be generated using a computer software program.

Here we have a simple program by using it you can generate a strong password of any predefined length. As you increase the length of password, it becomes stronger.  

//Source Code:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
     int counter = 0;
     srand(time(NULL));  // seeding function for random()
     char randChar;

     int  passwordLength;
           
printf("****A Random Password Generator****\n\n");
     printf("Type password Length: ");
     scanf("%d", &passwordLength);

     printf("\n\n");
     while (counter < passwordLength)
     {
           //Get a random char among 70 characters
           randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$%^&*!"[rand() % 70];
           printf("%c", randChar);
           counter++;
     }
    
     printf("\n");
     _getch();
     return 0;
}

Output:


Friday, 13 October 2017

Displaying star (*) for input password using c

Here we demonstrate how can we show the star (*) for an input password. It may be used when we are developing an application that has a login form in which we use a user name and password as logging information.

For security purpose it is needed to show (*) instead showing the plain text for the password. The source code is given below to show how we can do it using c/c++.

Source Code:
#include <stdio.h>
#include <conio.h>

int main()
{
     char password[20], ch = 0;
     int i = 0, j;

     printf("Enter the password <limit 20 characters>: ");

     while (i < 20)
     {
           ch = _getch();
           if (ch == `\r`)
                break;
           password[i] = ch;
           i++;
           ch = `*`;
           printf("%c", ch);
     }

     password[i] = `\0`;

     printf("\nThe password is :");

     for (j = 0; j < i; j++)
     {
           printf("%c", password[j]);
     }
     _getch();
     return 0;
}

Output:


Sunday, 8 October 2017

String Manipulation Using C

String manipulation is the action of the fundamental operations on strings, including their creation, concatenation, the extraction of string segments, string matching, their comparison, discovering their length, replacing sub-strings by other strings. Here we demonstrate some example of string manipulation.

Source code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

/* string length */
int StrLength(char *string)
{
       char *count = string;
       while (*count)
       {
              count++;
       }
       return count - string;
}

/* string append */
char* StrAppend(char* string, char* append)
{
       char* newstring = NULL;
       size_t needed = _snprintf(NULL, 0, "%s%s", string, append);
       newstring = (char*)(malloc(needed));
       sprintf(newstring, "%s%s", string, append);
       return newstring;
}

/* string append char */
char* StrAppendChar(char* string, char append)
{
       char* newstring = NULL;
       size_t needed = _snprintf(NULL, 0, "%s%c", string, append);
       newstring = (char*)(malloc(needed));
       sprintf(newstring, "%s%c", string, append);
       return newstring;
}

/* string equals */
int StrEquals(char *equal1, char *eqaul2)
{
       while (*equal1 == *eqaul2)
       {
              if (*equal1 == `\0` || *eqaul2 == `\0`)
              {
                     break;
              }
              equal1++;
              eqaul2++;
       }
       if (*equal1 == `\0` && *eqaul2 == `\0`)
       {
              return 0;
       }
       else
       {
              return -1;
       }
}

/* string replace */
char* StrReplace(char* search, char* replace, char* subject)
{
       char* newstring = "";
       int i = 0;
       for (i = 0; i < StrLength(subject); i++)
       {
              if (subject[i] == search[0])
              {
                     int e = 0;
                     char* calc = "";
                     for (e = 0; e < StrLength(search); e++)
                     {
                           if (subject[i + e] == search[e])
                           {
                                  calc = StrAppendChar(calc, search[e]);
                           }
                     }
                     if (StrEquals(search, calc) == 0)
                     {
                           newstring = StrAppend(newstring, replace);
                           i = i + StrLength(search) - 1;
                     }
                     else
                     {
                           newstring = StrAppendChar(newstring, subject[i]);
                     }
              }
              else
              {
                     newstring = StrAppendChar(newstring, subject[i]);
              }
       }
       return newstring;
}

/* string replace maximal */
char* StrReplaceMax(char* search, char* replace, char* subject, int count)
{
       char* newstring = "";
       int i = 0;
       for (i = 0; i < StrLength(subject); i++)
       {
              if (subject[i] == search[0])
              {
                     int e = 0;
                     char* calc = "";
                     for (e = 0; e < StrLength(search); e++)
                     {
                           if (subject[i + e] == search[e])
                           {
                                  calc = StrAppendChar(calc, search[e]);
                           }
                     }
                     if (StrEquals(search, calc) == 0)
                     {
                           if (count > 0)
                           {
                                  newstring = StrAppend(newstring, replace);
                                  i = i + StrLength(search) - 1;
                                  count = count - 1;
                           }
                           else
                           {
                                  newstring = StrAppendChar(newstring, subject[i]);
                           }

                     }
                     else
                     {
                           newstring = StrAppendChar(newstring, subject[i]);
                     }
              }
              else
              {
                     newstring = StrAppendChar(newstring, subject[i]);
              }
       }
       return newstring;
}


int main()
{
       char* str = "this is a string example";
       int len_str = StrLength(str);
       char* appned_str = StrAppend(str, "append this str");
       char* append_char_str = StrAppendChar(str, `#`);
       char* replace_str = StrReplace("is", "was", str);
       int equal_str = StrEquals(str, replace_str);

       printf("***  String Manipulation Using C  ***\n\n");
       printf("\nExample String                 : %s", str);
       printf("\nString Length                  : %d", len_str);
       printf("\nAppended String                : %s", appned_str);
       printf("\nAppended character             : %s", append_char_str);
       printf("\nReplaced String                : %s", replace_str);
       printf("\nis equal replaced string       : %d", equal_str);

       getchar();

       return 0;
}

Output: