-

Tuesday, May 12, 2020

Find Pair for the sum C#

This problem is about finding two elements from array/list which equal to the given sum value.

Ex:
CASE# 1: source = [1, 2, 3, 9], sum = 8, in this scenario we need to find two elements from the given list/array whose sum is 8, based on permutations you find none of the element's total is 8 so this problem will fail to find the value of sum.

CASE# 2: source = [1, 2, 4, 4], sum = 8, in this scenario we need to find two elements from the given list/array whose sum is 8, based on permutations you find at least a pair whose sum is 8 so this problem will success to find the value of sum.

Here I am going to an efficient solution, which means it'll provide you a solution in minimal iteration/efforts.


  • This is list base operation
        private static bool PairForSumExists(List<int> sourceList, int sum)
        {
            List<int> resultList = new List<int>();
            foreach (int item in sourceList)
            {
                if (resultList.Contains(sum - item))
                    return true;

                resultList.Add(sum - item);
            }
            return false;
        }

  • This is an array base operation
         private static bool PairForSumExists(int[] sourceArray, int sum)
        {
            int[] resultArr = new int[(sourceArray.Length)];
            for (int counter = 0; counter < sourceArray.Length; counter++)
            {
                int item = sourceArray[counter];
                if (resultArr.Contains(sum - item))
                    return true;

                resultArr[counter] = (sum - item);
            }
            return false;
        }


In this way, you can find the solution for the given problem, if you have batter solution then it's my pleasure if you share with me your knowledge.

Of course, I can provide here the explanation for this code written here, I suggest here to debug this code on your own by creating a console application that will provide you batter understanding of this. 
Still, if you have any query/confusion to digest it plz. put your questions/suggestions in the comment box

If you want this code sample then mention in comment section with your email, I'll share on same

Put in the comment section which algorithm you want to appear in my next blog.

Happy coding.

Sunday, May 10, 2020

Sudoku Solving Algorithm

Introduction
Sudoku puzzles are solved by logic and no math is required. As seen on the right, it consists of a grid that is usually made up of nine rows, nine columns, and nine boxes that are separated by thicker, darker lines. Some of these boxes will contain numerals from 1 to 9. To solve the puzzle, a person must fill in all the empty squares without using the same numeral twice in each column, row, or box, and without changing the numerals that are already in the grid.
These puzzles were created to be done using pencil and paper, and there are many books that contain collections of these puzzles with tips and strategies for completing them. They also appear in newspapers and magazines: typically, a different puzzle appears every day, and the solution is printed somewhere else or in the next issue. Later, small handheld machines were created that generate Sudoku puzzles for the user to solve. More recently, though, the game can be played on the Internet or on mobile apps.
You can find more details here

This solution is successfully run and tested on C#
Required assemblies are as follows:
using System;
using System.Linq;

Request sample you can change values as per your case:
char[,] sudokuBoard = new char[,]{{'.', '8', '9', '.', '4', '.', '6', '.', '5'}
                                        ,{'.','7','.','.','.','8','.','4','1'}
                                        ,{'5','6','.','9','.','.','.','.','8'}
                                        ,{'.','.','.','7','.','5','.','9','.'}
                                        ,{'.','9','.','4','.','1','.','5','.'}
                                        ,{'.','3','.','9','.','6','.','1','.'}
                                        ,{'8','.','.','.','.','.','.','.','7'}
                                        ,{'.','2','.','8','.','.','.','6','.'}
                                        ,{'.','.','6','.','7','.','.','8','.'}};

/*Member declaration*/
static int BOARD_START_INDEX = 0, BOARD_SIZE = 9, MIN_VALUE = 1, MAX_VALUE = 9, SUBSECTION_SIZE = 3;

static char NO_VALUE = '.';

public static bool SudokuSolve(char[,] board)
{
     // your code goes here
     for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++)
     {
           for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++)
           {
                 if (board[row, column] == NO_VALUE)
                 {
                       for (int assign = MIN_VALUE; assign <= MAX_VALUE; assign++)
                       {
                             board[row, column] = assign.ToString().ToCharArray()[0];
                             if (isValid(board, row, column) && SudokuSolve(board))
                                     return true;
                             board[row, column] = NO_VALUE;
                        }
                        return false;
                 }
           }
     }
     return true;
}

public static bool isValid(char[,] board, int row, int column)
{
     return (rowConstraint(board, row) && columnConstraint(board, column) && subBoardConstraint(board, row, column));
}
public static bool rowConstraint(char[,] board, int row)
{
     bool[] constraint = new bool[BOARD_SIZE];
     return Enumerable.Range(BOARD_START_INDEX, BOARD_SIZE).All(column => checkConstraint(board, row, constraint, column));
}
public static bool columnConstraint(char[,] board, int column)
{
     bool[] constraint = new bool[BOARD_SIZE];
     return Enumerable.Range(BOARD_START_INDEX, BOARD_SIZE).All(row => checkConstraint(board, row, constraint, column));
}
public static bool subBoardConstraint(char[,] board, int row, int column)
{
     bool[] constraint = new bool[BOARD_SIZE];
     int subsectionRowStart = (row / SUBSECTION_SIZE) * SUBSECTION_SIZE;
     int subsectionRowEnd = subsectionRowStart + SUBSECTION_SIZE;

     int subsectionColumnStart = (column / SUBSECTION_SIZE) * SUBSECTION_SIZE;
     int subsectionColumnEnd = subsectionColumnStart + SUBSECTION_SIZE;

     for (int r = subsectionRowStart; r < subsectionRowEnd; r++)
     {
          for (int c = subsectionColumnStart; c < subsectionColumnEnd; c++)
          {
               if (!checkConstraint(board, r, constraint, c)) return false;
           }
      }
      return true;
}
public static bool checkConstraint(char[,] board, int row, bool[] constraint, int column)
{
     if (board[row, column] != NO_VALUE)
     {
          int.TryParse(Convert.ToString(board[row, column]), out int number);
          if (!constraint[number - 1])
          {
               constraint[number - 1] = true;
           }
           else
           {
                return false;
            }
     }
     return true;
}


Of course, I can provide here the explanation for this code written here, I suggest here to debug this code on your own by create a console application that will provide you batter understanding of this. 
Still, if you have any query/confusion to digest it plz. put your questions/suggestions in comment box

If you want this code sample then mention in comment section with you email, I'll share on same

Put in the comment section which algorithm you want to appear in my next blog.

Happy coding.