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))


Sunday, September 6, 2020

Importand and practical things to do , to live a fulfilling life.

 Essential / important things to do for the whose basic needs (food, clothing and shelter) are met. The following things are not something new but it's been there for a long time and all of them knew such important things. It's not a Eureka list but known boring list.

The following things are not for the people whose basic needs are not met could be many reasons for this unfortunate situation. 

1. Take care of your health(Eat in Moderation).  You need to have a clear purpose why you should eat in moderation. Most of the time the motivation is to loose weight  or bring down your cholesterol or glucose level to the normal range. This purpose should become strong intent in your mind. If the intent is strong then you will indulge into action without any external force or external motivation from outside. If the intention is not strong then eating in moderation is not a worthy pursuit since you will fail and can become emotionally draining. So wait to fall sick and a kick from the doctors would help you in forming strong intentions so as Psychological counselling will help if there are any emotional blockages . Without the purpose and intention the resolve will not be strong enough to adopt "Eating in Moderation". 

 There are people who live longer just eating crappy food without any fitness regime such people are exception to the rule but not a common occurrence. There are people who eat and do exercise and still suffer premature death. Probably there are genetic or emotional reasons for such problems. I have seen people who eat good food but mentally unstable not they have mental disease but their emotional state is not balanced. Reasons could be many for such unstable conditions and to list all of them is an impossible task. Most of the people fall in the middle when eating in moderation is adopted they will see marginal improvements in their health but for some that could be life changing.

The key factors for taking care of your health are eat in moderation(what is moderation is relative and will differ from person to person). Eat in moderation according to your age but  moderation may not be applicable to adults in their 20s who are into rigorous fitness regiment or labors who work hard on the field or factories. Listening to your body is very important to differentiate when to start and stop eating. The first few days will be a challenge when adopting a new habit. To adopt to a new habit a healthy support group is very vital to discuss your mental challenges  and problems in choosing food that could be filling and satisfying.  If not able to follow any thing just remember the key thing if your stomach is lighter and not heavy means you have eaten in moderation.  following this simple thing will take a long way to promote decent health if not optimum. 

A suggestion for meat eaters would be to cut down on red meat if not avoid and embrace white meat like chicken and fish which can satisfy all your nutritional requirements with out consuming red meat.  I would prefer Organic meat over conventional meat. If possible refrain from meat eating at least for one or two days in a month so same goes for diary products as well. Consume low fat  organic milk and organic cheese which will be easy on your stomach.if your allergic to caesin protein try A2 milk which are available at whole foods but check your local grocery stores. Vegetables in nature except for few are nasty in taste and makes you puke so it's better to make it tastier by adding ingredients by the way millions of recipes are available online as long as you are willing to devote sometime for healthy cooking.  

Regarding Junk foods you need to consume junk foods but in small to moderate quantities, suppression is as dangerous  if not more dangerous as eating only junk foods. The mind is a weird component if you suppress something it creates the urge to eat more I don't know why but the nature of the mind  is to remember negative things most of the times not the positive things as we all know that we remember the disrespect but not the respect given to us. Please be careful while playing with your mind because we don't know who we are until we encounter challenges most of them fall and few rise above the challenges to permanently alter their habits.

Eating in moderation is a long process until it becomes a habit where the senses are under control whenever we see or smell the food.  In all this process do not feel guilt if you can't keep up the habit it's Okay if you can't keep up the habit rather feeling bad or guilt. The guilt is not going to help you in promoting any healthy habits  or move away from negative it's just stays there and you become two different person one with guilt and one with bad habits. It's better to pursue bad habits if you can't control without guilt. But I believe most of the people has decent amount of will power to over come most of the bad habits but for some help is required to adjust. Another possibility is the urge will always be there  to eat crappy food but using determination as a tool we may postpone it for a while but determine requires tremendous amount of energy which is limited in supply so habit doesn't require energy as it's an autonomous activity not even you respond to something, it just happens. 

In summary include vegetables, white meat, fruits, moderate carbs , low fat diary , moderate junk foods  as part of your daily intake and moderate exercise like walking, running, swimming will add more help in controlling your urges in the initial stages of transitioning to moderate eating. 


2. Quiet time. Humans needs  to invest  some time for themselves. Why we need quite time because we need to spend time with ourselves to experience some sense of temporary peace alas permanent peace means death or spiritual enlightenment.  For some  spending time with themselves can be a dangerous thing as this may not a suitable option to pursue. Before we venture into quiet time activities we should have a clear understanding what quiet time means and why we need it. Break is different from quite time.Behaving crazily with our selves is not a quite time. Including just one person in any activity is not a quite time. Watching movie is not a quite time. A broad definition would be an activity which doesn't stimulate your senses too much can be called as quite time means resting the body and senses. Why we need quite time because spending time with your self satisfies your mind because all through the day we do activities to satisfy other people which includes family , organization and managers. We do those activities because we love them that's why. I have never understood love thyself but doing quite activity for myself have resulted in temporary inner peace. 


What are different activities that we can do to consider it that as a quiet time. Active activities include playing chess against a computer , writing, reading ,solving puzzles, reading a book, playing music, deep thinking on your professional or personal problems. Every individual can come up with their own list as long as it meets the definition. Such activities should not be result oriented but rather pleasure oriented. As long as it involves less use of our five senses means naturally the mind will result in peace by itself. At first it may require some effort but it's worth for a balanced living.  Find a place where nobody will disturb you and set a time and amount of time you are going to spend on the activity. At first choose an activity that interest and in the process you will find out about the likability of the chosen activity and an opportunity to explore new activities. Set a time where it's comfortable and not taking time away from essential activities.

Passive activities include meditation, walking or slow jogging in nature, drawing , observing nature which include ourselves, watching your mind without any intervention, listening to  melodious music with closed eyes,   chanting, prayer to GOD or nature,  watching your breath on the nostrils, Contemplation, Concentrating on an object. In short very very less brain stimulation. Find a quite place without much disturbance which can come in the form of people and external noise. 

Will continue in part -II 

Monday, April 6, 2020

longest substring sequence but not so perfect

using System;

public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
String input ="aoaboooobcdefooo";
string input1="zbcdeabf";
int posx=0;int posy=0;;
int[,] table = new int[input1.Length,input.Length];
string output= "";
//populate table with zeroes.

for(int j=0;j<input1.Length;j++)
{
int i=0;

while(i<input.Length)
{
if (input1[j]==input[i])
{
table[j,i]=table[j-1,i-1]+1;
if(table[j,i]>table[j-1,i-1])
{
   posy=j;posx=i;
}
}
else{
if(i>0 && j>0)
    table[j,i]=table[j-1,i-1];
}
i=i+1;
}
}
//print the letters.
while(table[posy,posx]>0)
{
output=output+input1[table[posy,posx]].ToString();
Console.WriteLine(posy.ToString()+posx.ToString());
posy--; posx--;
}
Console.WriteLine(output);
}
}