Thursday, 21 November 2024

Search Insert Position

 class Solution {

public:
    int searchInsert(vector<int>& nums, int target) {
        int high = nums.size();
        int low = 0;
        int mid = (low+high)/2;
        int prev_mid = mid;
        if(target < nums[low])
         return low;
        else if(target > nums[high-1])
         return high;
        while(low < high)
        {
            if(target == nums[mid] )
            {
                 return mid;
            }
            else if(target > nums[mid])
            {
                  low = mid;
                  mid= (low + high)/2;
            }
            else
            {
                high = mid;
                mid =  (low+high)/2;
            }
            if(prev_mid == mid)
            {
                break;
            }
            else {
                prev_mid = mid;
            }

        }

        return mid+1;
       
    }
};

Maximum Swaps

 class Solution {

public:
   
    int maximumSwap(int num) {
       std::string origin_n = std::to_string(num);
       std::vector<char> c;
       std::vector<char> max;
       std::vector<int> vec;
       int ret =0;
       for(int i=0 ; i< origin_n.length(); i++)
       {
          c.push_back(origin_n.at(i));
          max.push_back(origin_n.at(i));
       }
       std::sort(max.begin(), max.end(), std::greater<>());

       if(std::equal(c.begin(), c.end(), max.begin()))
       {
           string str(max.begin(), max.end());
           ret = std::stoi(str);
           return ret;
       }
       for(int i=0; i< c.size(); i++)
       {
          for(int j=i+1; j< c.size(); j++ )
          {
             char temp = c[i];
             c[i] = c[j];
             c[j] = temp;
             string str(c.begin(), c.end());
             vec.push_back(std::stoi(str));
             temp = c[i];
             c[i] = c[j];
             c[j] = temp;
          }
 
       }

       int m = *max_element(vec.begin(), vec.end());
       return m;
    }
};

Find Kth closest element

 #include <cmath>

#include <algorithm>
#include <iterator>
class Solution {

public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
       multimap<int,int> v;
       vector<int> ret;
       for(int i=0; i< arr.size(); i++)
       {
           v.insert({abs(arr[i]-x), i});        
       }
       int count = 0;
       for(auto &[key,val]: v)
       {
           if(count >= k)
               break;
 
            ret.push_back(arr[val]);

           count++;
       }
       std::sort(ret.begin(), ret.end());
       return ret;
    }
};

Thursday, 23 June 2022

kaprekar Numbers

 void kaprekarNumbers(long long p, long long q) {

    static int counter =0;
    for(long long i=p; i<=q; i++)
    {
        std::string i_str = to_string(i);
        int d = i_str.length();
        long long sq = i*i;
        std::string sq_str = to_string(sq);
        std::string l = sq_str.substr(0,sq_str.length()-d);
        std::string r = sq_str.substr(sq_str.length()-d, d);
        int left = atoll(l.c_str());
        int right = atoll(r.c_str());
        if ( (left + right) == i)
        { std::cout << i <<" ";
          counter++;
        }
    }
    if(counter == 0)
     std::cout << "INVALID RANGE" <<std::endl;
    else
    std::cout << std::endl;
}

Sunday, 19 July 2020

Creating a state Machine in C++ using virtual function


                                    Creating a State Machine in C++ using virtual function

 We can create a state machine using virtual function , instead of normal pointer function which is using index to jump to a function, we are using Object of that particular class(which represent state) to jump to the particular run() function of that class.

Here signal maps to the class object and triggers run() function of that class object.
We are using concept of Runtime Polymorphism instead of compile time polymorphism.

class StateMachine
{
public:
    int signal;
    void print ()
    { cout<< "print base class" <<endl; }
  
    virtual void run ()
    { cout<< "show base class" <<endl; }
};
  
class Init_State:public StateMachine
{
public:
    void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly
    { cout<< "print derived class" <<endl; }
  
    void run ()
    { cout<< "We are in init state" <<endl; }
};
class Run_State:public StateMachine
{
public:
    void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly
    { cout<< "print derived class" <<endl; }
  
    void run () 
    { cout<< "we are in running state" <<endl; }
};
class DeInit_State:public StateMachine  
{
public:
    void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly
    { cout<< "print derived class" <<endl; }
 
    void run ()
    { cout<< "we are in deinit state" <<endl; }
};
 
 
//run the State Machine function
void runStateMachine(void *p)
{
    StateMachine *ptr = (StateMachine *)p;
      switch(ptr->signal)
     {
       case 0:
       ptr = new Init_State;
       break;
       case 1:
       ptr = new Run_State;
       break;
       case 2:
       ptr = new DeInit_State;
       break;
     }
    //Non-virtual function, binded at compile time
    ptr->print(); 
      
    // virtual function, binded at runtime (Runtime polymorphism)
    ptr->run(); 
 
    return;
}

int main()
{
   StateMachine *ptr = new StateMachine;
   ptr->signal = 0;  // controls the state
   runStateMachine((void*)ptr);
}

Friday, 22 April 2016

Creating a finite state machine in C language




 Finite state machine implementation in C


This is an implementation of FSM in C as you can see there are 3 functions named
cheese_day(),grapes_day() & lettuce_day() which represents the state/nodes
fsm is an array of pointers to function, which is used to access the functions

i.e. void (*fsm[])()= { cheese_day , grapes_day, lettuce_day };Now we are using the index of the fsm to jump to the specific function
i.e. fsm[input_symbol]();





  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <cstring>
  4. #define IM_STARVING 0
  5. #define LETS_GO_SHOPPING 0
  6. #define ILL_HAVE_CHEESE_TOMMORROW 1
  7. #define ILL_HAVE_LETTUCE_TOMMORROW 2
  8. #define ILL_HAVE_GRAPES_TOMMORROW 3
  9. int inp[5]= {ILL_HAVE_CHEESE_TOMMORROW ,ILL_HAVE_LETTUCE_TOMMORROW,ILL_HAVE_CHEESE_TOMMORROW,ILL_HAVE_GRAPES_TOMMORROW,IM_STARVING};  // automated Input!
  10. void cheese_day()
  11. {
  12.   printf("state :- cheese day\n");
  13. }
  14. void grapes_day()
  15. {
  16.   printf("state :- grapes day\n");
  17. }
  18. void lettuce_day()
  19. {
  20.   printf("state :- lettuce day\n");
  21. }
  22. void (*fsm[])()= { cheese_day , grapes_day, lettuce_day };
  23. int main()
  24. { int j=0;
  25.   while(j< 5)
  26.   { int input_symbol=inp[j++];
  27.    switch(input_symbol) {
  28.     case 1:
  29.     input_symbol=ILL_HAVE_CHEESE_TOMMORROW - 1;
  30.     fsm[input_symbol]();
  31.     break;
  32.     case 2:
  33.     input_symbol=ILL_HAVE_LETTUCE_TOMMORROW - 1;
  34.     fsm[input_symbol]();
  35.     break;
  36.     case 3:
  37.     input_symbol=ILL_HAVE_GRAPES_TOMMORROW - 1;
  38.     fsm[input_symbol]();
  39.     break;
  40.     default:
  41.     fsm[input_symbol]();
  42.    }
  43.   }
  44.  return 0;
  45. }


Saturday, 6 December 2014

Die Hard 3 Hackerrank Solution

   The primary idea is to shift the water in the larger jug to smaller jug, hence the difference of  the capacities of the jugs will be used as a constraint to find out variable c volume. we will also terminate the process of finding c if the difference between both the jugs is zero.

     There are 4 conditions 
      1)    if  diff >= min then diff=diff-min_capacity
        2)    if  diff < min then diff=max_capacity - ( min_capacity - diff)
        3)    if  diff == c then return "YES"
          4)     if   diff  < 0 then return "NO"

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <iostream>
#include <algorithm>
#define max(a,b) a>b?a:b
#define min(a,b) a<b?a:b
using namespace std;
int jug(int a,int b,int c)
{
       int mx=max(a,b);
        int mn=min(a,b);
         if(a==c || b==c)
             return 1;
        int diff=abs(b-a);
        while(diff > 0)
        {
            if( diff==c )
              return 1;
           
           
            if(diff < mn)
            {
                diff=mx-(mn-diff);
               
            } else if(diff >= mn)
                {
                    diff=diff-mn;
                }
        }
             
                
   
    return 0;
}

int main() {
     int a,b,c,mx,mn,diff,t;
      cin >> t;
      while(t--)
       {  
       cin >>a>>b>>c;
          if(jug(a,b,c)==1)
              printf("YES\n");
          else printf("NO\n");
     
      }
   
    return 0;
}