Tuesday, March 30, 2021

knights tour

 using System;

using System.Linq;

using System.Collections.Generic;


public class Program

{

static int[] rowArray = new int[8] {2, 2, -2, -2, -1, 1, -1, 1};

static int[] colArray = new int[8] {-1, 1, -1, 1, 2, 2, -2, -2};

//static int[] rowArray = new int[8]{ 2, 1, -1, -2, -2, -1, 1, 2 };

//

    

//static int[] colArray = new int[8] { 1, 2, 2, 1, -1, -2, -2, -1 };

private static bool[,] knights = new bool[8, 8];

private static List<string> placedKnightsCount = new List<string>();

public static void Main()

{

setKnightToFalse();

placedKnightsCount.Add("0,0");

knights[0,0]=true;

placeKnights(0,0);

int index=1;

foreach(var move in placedKnightsCount)

{

System.Console.WriteLine(index.ToString()+"::"+move.ToString());

index++;

}

System.Console.WriteLine(placedKnightsCount.Select(x=>x).Count());

}

private static bool  placeKnights(int row, int col)

{

if (placedKnightsCount.Count() >= 64)

           return true;

  for (var array = 0; array <= 7; array++) 

{

      if (rowArray[array] + row >= 0 && rowArray[array] + row <= 7

        && colArray[array] + col >= 0 && colArray[array] + col <= 7 &&

        knights[rowArray[array] + row,colArray[array] + col] == false) 

{

knights[rowArray[array] + row,colArray[array] + col] = true;

placedKnightsCount.Add((rowArray[array] + row).ToString() + ',' + (colArray[array] + col).ToString()

   +"::rowArray"+rowArray[array].ToString()+","+row.ToString()

  +"::cola=Array "+colArray[array].ToString()+","+col.ToString()

+","+"::cola=sum "+(colArray[array]+col).ToString()

);

var b = colArray[array] + col;

if (placeKnights(rowArray[array] + row,b))

{

 

return true;

}

else 

{

knights[rowArray[array] + row,colArray[array] + col] = false;

System.Console.WriteLine("FAILED::rowArray"+rowArray[array].ToString()+","+row.ToString()

  +"::cola=Array "+colArray[array].ToString()+","+col.ToString());

}

  }

}

return false;

}

private  static void setKnightToFalse() {

    for (var row = 0; row <= 7; row++) {

      //this.knights[row] = [];//

      for (var col = 0; col <= 7; col++) {

       

        knights[row,col] = false;

      }

    }

   //System.Console.Write(knights[7,7]);


  }

  


}


 

eight queen problem

 My dream of solving this eight queen problem has come true. Recursion is always challenging.


using System;

using System.Linq;

using System.Collections.Generic;


public class Program

{

static int[] rowArray = new int[8] {2, 2, -2, -2, -1, 1, -1, 1};

static int[] colArray = new int[8] {-1, 1, -1, 1, 2, 2, -2, -2};

//static int[] rowArray = new int[8]{ 2, 1, -1, -2, -2, -1, 1, 2 };

//

    

//static int[] colArray = new int[8] { 1, 2, 2, 1, -1, -2, -2, -1 };

private static bool[,] knights = new bool[8, 8];

private static List<string> placedKnightsCount = new List<string>();

public static void Main()

{

setKnightToFalse();

placedKnightsCount.Add("0,0");

knights[0,0]=true;

placeKnights(0,0);

int index=1;

foreach(var move in placedKnightsCount)

{

System.Console.WriteLine(index.ToString()+"::"+move.ToString());

index++;

}

System.Console.WriteLine(placedKnightsCount.Select(x=>x).Count());

}

private static bool  placeKnights(int row, int col)

{

if (placedKnightsCount.Count() >= 64)

           return true;

  for (var array = 0; array <= 7; array++) 

{

      if (rowArray[array] + row >= 0 && rowArray[array] + row <= 7

        && colArray[array] + col >= 0 && colArray[array] + col <= 7 &&

        knights[rowArray[array] + row,colArray[array] + col] == false) 

{

knights[rowArray[array] + row,colArray[array] + col] = true;

placedKnightsCount.Add((rowArray[array] + row).ToString() + ',' + (colArray[array] + col).ToString()

   +"::rowArray"+rowArray[array].ToString()+","+row.ToString()

  +"::cola=Array "+colArray[array].ToString()+","+col.ToString()

+","+"::cola=sum "+(colArray[array]+col).ToString()

);

var b = colArray[array] + col;

if (placeKnights(rowArray[array] + row,b))

{

 

return true;

}

else 

{

knights[rowArray[array] + row,colArray[array] + col] = false;

System.Console.WriteLine("FAILED::rowArray"+rowArray[array].ToString()+","+row.ToString()

  +"::cola=Array "+colArray[array].ToString()+","+col.ToString());

}

  }

}

return false;

}

private  static void setKnightToFalse() {

    for (var row = 0; row <= 7; row++) {

      //this.knights[row] = [];//

      for (var col = 0; col <= 7; col++) {

       

        knights[row,col] = false;

      }

    }

   //System.Console.Write(knights[7,7]);


  }

  


}


 

Saturday, March 27, 2021

binary search

 Here a simple binary search works with typescript.  The following conditions before the search start using binary search technique starts.  The search list should be sorted else  this technique is not effective at all. why because this technique basically narrows down the result set to search let say if you a list [2,4,6,8,10] first the technique will start from the middle of the list which is 6 in the list and index is 3. The algorithm will compare with number to be searched whether it's larger or smaller or equal. if searched number is smaller than 6 then we assume the searched number lies between index 0 and index 2. So search list is narrowed to indexes between 0 and 2. If the searched number is greater than 6 then we assume the searched number lies between index 3 and 4 so the search is narrowed to searching the indexes between 3 and 4. The list narrows down after each iteration either possibly finding the right index or terminating the search. The terminating the left hand side should be less than or equal to right.


class binarySearch {
  list = [];
   left = 0;
   right = 0;
  no: number;
  private index : number=0;
  findNumber() {
    console.clear();
    if(this.list.length ==0 || this.no == undefined)
      return
    while (this.left <= this.right) {
       var middle = Math.trunc(Math.floor(this.left+this.right)/2);
       console.log(middle,this.left,this.right)

      //conditions begin
      if (this.list[middle]<this.no)
          this.left = this.left+1;
      if(this.list[middle]>this.no)    
          this.right = this.right-1;
      if(this.list[middle]==this.no || this.index> this.list.length)    
      {
        console.log(middle,this.list[middle])
        break;
      }
      this.index++;
    }
  }
}
var bs  = new binarySearch();
bs.list=[4,7,8,9,10,11,12,99as any;
bs.no = 4;
bs.left = 0;
bs.right=bs.list.length-1;
bs.findNumber();


simple linked list with traversal forward and back ward

 The bare simple sample code shows how a simple linked list works. It also traverse the linked list.

both forward and backward.  I


class linkedList {
   no: number;
   next: linkedList;
   previous : linkedList;
}
  

  




class consumer {
  head = new linkedList();
  tail = new linkedList();
  createLinkedList() {
    //initialize head
    this.head.no = 1;
    var previous = this.head;
    var current = new linkedList();
    for (var i = 3; i <= 10; i++) {
       current = new linkedList();
      current.no = i;
      previous.next = current;
      current.previous = previous;
     
      previous = current;
      
    }
    //this.head.previous = current;
    this.tail = current;
    current =  this.head;
    while(current.next != null)
    {
      console.log(current.no)
      current = current.next;
    }
    console.log(current.no)
    while(this.tail.previous != null)
    {
      console.log(this.tail.previous.no);
      this.tail = this.tail.previous;
    }

    
  }
}
var consume = new consumer();
consume.createLinkedList();

type List = {
  no: number;
  next: linkedList;
}


JSON object comparision

 I wrote this small program for my own needs to compare two JSON objects and spit out either true or false to tell is there any difference between the objects. This was useful  in angular forms when form controls wasn't  used. The app have to notify the user that if the user navigate away from the current page making some changes in the form but without saving the form. Form controls are grouped under form group object and form group value changes can be observed to notify the changes if subscribed. In my scenario I didn't use form control but used NGMODEL which I thought was pretty straight forward. NGMODEL and Form Control  combination are deprecated so wrote this recursive brute force approach to detect changes if any. This will work for small JSON Objects but not for large JSON Objects. Language is typescript.


class ObjectComparision<T>{

  oldObject: T;
  newObject: T;

  getOldObject(): T {
    return this.oldObject;
  }

  setOldObject(tempObject: T) {
    //Object.assign(this.oldObject,tempObject) ;
    this.oldObject = Object.assign({}, tempObject);
    //this.dates(this.oldObject);

  }
  
  getNewObject(): T {
    return this.newObject
  }
  setNewObject(tempObject: T) {
    this.newObject = Object.assign({}, tempObject);

  }
  compareObject(obj: T, obj1: T): boolean {

    for (var key in obj) {
      if (this.checkPropertyInstanceIsAnObject(obj[key]) ) {

        if (this.checkObjectDifference(obj[key],obj1[key]))
         return true;
      }
      else if (this.checkPropertyInstanceIsAnArray(obj[key]) ) {
        if(this.checkArrayDifference(obj[key],obj1[key]))
          return true;
       
      }// end for if
      else {
        if (this.compare(obj1[key],
          obj[key]) == true) {

          return true;
        }
      }
    }
    return false;
  }

  
  checkObjectDifference(compare,compared) : boolean
  {
    if (this.checkIsPropertyundefined(compare) || this.checkIsPropertyundefined(compared)) {
          return true;
        }

        if (this.compareObject(compare, compared) == true) {
          return true;
        }
    return false;
  }

  checkArrayDifference(obj,obj1) : boolean
  {
    for (var element in obj) {

          if (this.checkPropertyInstanceIsAnObject(obj[element])) {
              
            if (this.checkObjectDifference(obj[element],obj1[element]))
               return true;
             
          }
          else {

            if (this.checkIsPropertyundefined(obj1[element]) 
                || this.checkIsPropertyundefined(obj[element])) {
              return true;
            }
            if (this.compare(this.obj1[element],
              obj[element]) == true) {

              return true
            }
          }
        }
    return false;
  }

  checkPropertyInstanceIsAnObject(objectT): boolean {
    return object instanceof Object

    }

    checkPropertyInstanceIsAnArray(objectT): boolean {
    return object instanceof Array

    }

    checkIsPropertyundefined(object : T) : boolean
    {
      return object === undefined
    }
  
  compare(val1: any, val2: any): boolean {
    if (val1.toString() != val2.toString())
      console.log(val1, val2)
    return (val1.toString() != val2.toString())
  }
}

example

 var obj1 = { 'id'1'name' : 'krishna'}
var obj2 = { 'id'1'name' : 'krishna_'}

var o = new ObjectComparision<any>();
 console.log(o.compareObject(objaa, objbb))
 console.log(o.compareObject(objbb,objaa))