Monday, May 20, 2024

 Given an integer array arr of distinct integers and an integer k.


A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0 and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds.


Return the integer which will win the game.


It is guaranteed that there will be a winner of the game.

class Solution {

    public int getWinner(int[] arr, int k) {

        int win = 0;

        if (arr == null || arr.length < 2) { return Integer.MIN_VALUE; }

        if (k > arr.length){ 

            int max = Integer.MIN_VALUE;

            for (int i = 0; i < arr.length; i++) {

                if (arr[i] > max) {

                    max = arr[i];

                }

                return max;

            }

        }

        for (int i = 0; i < arr.length * arr.length; i++) {

            if (win >= k) { 

                break; 

            } 

            if (arr[0] > arr[1]) {

                win++;

                int temp = arr[1];

                for (int j = 2; j < arr.length; j--) {

                    arr[j-1] = arr[j];

                }

                arr[arr.length - 1] = temp;

                continue;

            }

            win = 1;

            int temp = arr[0];

            for (int j = 1; j < arr.length; j--) {

                arr[j-1] = arr[j];

            }

            arr[arr.length - 1] = temp;

        }

        return arr[0];

    }

}


Arr: 2,8,5,6,6 k=3

8,5,6,6,2

8,6,6,2,5

8,6,2,5,6

8


Sunday, May 19, 2024

 Given a string of digits, count the number of subwords (consistent subsequences) that are anagrams of any palindrome.

Public class solution {

Public static int getSubWords(String digits) {

    Int count = 0;

    for (int k = 1; k < digits.length; k++) {

           for (int I = 0; I <digits.length; I++) {

                Int end = I + k;

                If (end < digits.length) {

                     String word = digits.substring(words, I, end);

                      If (isAnagram(word)) { 

                          count++;

                      }

                }

           }

    }

    return count;

}

Public boolean isAnagram(String word) {

        Map<Char, Integer> charMap = new HashMap<>();

        for (int I = 0; I < word.length; I++) {

               If (charMap.containsKey(word.charAt(I))) {

                    charMap[word.charAt(i)] = charMap.get(word.charAt(I)) + 1;

               } else {

                    charMap.put(word.charAt(I), 1);

               }

        }

        If (charMap.size() %2 == 1) {

            // count of only one element must be odd 

            return charMap.values().stream().filter(x-> x%2 == 1).count() == 1;

        }

        Else { 

             // count of all elements must be even

             return charMap.values().stream().filter(x -> x%2 == 0).count() == charMaps.size();

        }

}

}

test:

14641

2


Saturday, May 18, 2024

 Error Correction for Drone flight path management

With the popularity of modular composition, many industries are taking advantage of a fleet of functional units that can collectively function as a whole and eliminate the risks of the monoliths that used to serve the purpose earlier. Fleet refers to many drones, bots or other software automations that are capable of a specific function such as moving from point A to point B in space. 

While single remote-controlled units can follow the handlers' commands in real-time, the fleet usually operates according to a program. Centralized logic maps an initial state to a final state and issues command to each drone to move from the starting point to the ending point. It is easy for software to map initial co-ordinates for each drone in a formation on land and command them to move to a final co-ordinate in the sky to form a specific arrangement. 

Autonomous drone fleet formation avoids the need for a centralized controller that plots determines the final co-ordinates and non-overlapping flight path for each unit. The suggestion is that the computation for the final position from the initial position for each unit does not need to be performed at the controller and that logic can be delegated to the autonomous units. For example, if we wanted to change a fleet forming the surface of a sphere to a concentric plane of Saturn-like rings, then the final co-ordinates of each unit must be distinct, and its determination is not restricted to processing at the controller. While autonomous decisions are made by individual drones, they must remain within the overall trajectory tolerance space for the entire fleet. This can be achieved with the popular neural net for softmax classification. The goodness of fit for a formation or sum of squares of errors of F-score are other alternative measures. This is not a one-time adjustment to the formation but a continuous feedback-loop circuit where the deviation is monitored, and suitable error corrections are performed. Correction can also be translated as optimization problems where the objective function is maximized. It is common to describe optimization problems in local versus global optimization. Local optimization involves finding the optimal solution for a specific region of the search space while global optimization involves finding the optimal solutions on problems  that contain local optima. In some cases, joint local and global optimization recommendations can be computed and applied. The choice of algorithms for local search include Nelder-Mead algorithm, BFGS algorithm, and Hill-Climbing algorithm.  Global optimization algorithms include Genetic algorithm, Simulated Annealing, and Particle Swarm Optimization. The sum of square errors is almost independent of space-time variables and gives a quantitative measure that works well as the objective function to optimization problems. Therefore, the sum of the squares and the simulated annealing algorithm are good general-purpose choices that are applicable to drone formations. The formation is singleton otherwise the divisions can be treated like formations with cohesion and separation. The relationship between cohesion and separation is written as TSS = SSE + SSB where TSS is the total sum of squares. SSE is the sum of squared error and SSB is the between group sum of squares, the higher the total SSB, the more separated the formations are. Minimizing SSE (cohesion) automatically results in maximizing SSB (separation). Formation can be ranked and processed based a Silhouette co-efficient that combines both cohesion and separation.  This is done in three steps. 

For the I'th object, calculate its average distance to all other objects in formation and call it ai 

For the I'th object, and any formation not containing the object, calculate the object's average distance to all the objects in the given formation. Use the minimum value and call it bi 

For the I'th object, the silhouette coefficient is given by (bi-ai)/max (ai, bi)

Sample python implementation: 

#! /usr/bin/python 

def determining_replacement_for_team(nodes): 

                              Return formation_centroids_of_top_formations(nodes) 

 

def batch_formation_repeated_pass(team, nodes) 

                    team_formation = classify(team, nodes) 

                    proposals = gen_proposals(team_formation) 

                    formations = [(FULL, team_formation)] 

                     For proposal in proposals: 

                                             Formation = get_formation_proposal(proposal, team, nodes) 

                                              formations += [(proposal, formation)] 

                     Selections = select_top_formations(formations) 

                     Return team_from(selections) 

 

Def select_top_formations(threshold, formations, strategy = goodness_of_fit): 

                     return formations_greater_than_goodness_of_fit_weighted_size(threshold, formations)


def annealingoptimize(domain,costf,T=10000.0,cool=0.95,step=1): 

     # Initialize the values randomly 

     vec=[float(random.randint(domain[i][0],domain[i][1])) 

          for i in range(len(domain))] 

     while T>0.1: 

          # Choose one of the indices 

          i=random.randint(0,len(domain)-1) 

          # Choose a direction to change it 

          dir=random.randint(-step,step) 

          # Create a new list with one of the values changed 

          vecb=vec[:] 

          vecb[i]+=dir 

          if vecb[i]<domain[i][0]: vecb[i]=domain[i][0] 

          elif vecb[i]>domain[i][1]: vecb[i]=domain[i][1] 

          # Calculate the current cost and the new cost 

          ea=costf(vec) 

          eb=costf(vecb) 

          p=pow(math.e,(-eb-ea)/T) 

          # Is it better, or does it make the probability 

          # cutoff? 

          if(eb<ea or random.random( )<p): 

               vec=vecb 

          # Decrease the temperature 

          T=T*cool 

     return vec 

#codingexercise

Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.
Return the minimum number of patches required.
class Solution {
    public int minPatches(int[] nums, int n) {
        int count = 0;
        int[] sums = new int[n+1]; 
        Arrays.fill(sums, 0);
        sums[0] = 1;
        List<Integer> elements = new ArrayList<>(nums);
        while(!allOnes(sums)){
            List<List<Integer>> combinations = new ArrayList<>();
            List<Integer> selection = new ArrayList<Integer>();
            combine(elements, selection, 0, 0, combinations);
            for (int i = 0; i < combinations.size(); i++) {
                int sum = combinations.get(i).stream().sum();
                if (sum <= n && sums[sum] != 1) {
                    sums[sum] = 1; 
                } 
            }
            addLowestMissingNumber(elements);
            count++;
        }
        return count;
    }
}


Friday, May 17, 2024

 This is a continuation of previous articles on IaC shortcomings and resolutions. With the example of Azure Front Door, we were explaining the use of separate origin groups for logical organization of backend and front-end endpoints. This section talks about route configuration.

A route is the primary directive to Azure Front Door to handle traffic. The route settings define an association between a domain and an origin group.  Features such as Pattern-to-match and rulesets enable granular control over traffic to the backend resources.

A routing rule is composed of two major parts, the “left-hand-side” and the “right-hand-side”. Front Door matches the incoming request to the left-hand side of the route while the right-hand side defines how the request gets processed. On the left-hand side, we have the HTTP Protocols, the domain, and the path where these properties are expanded out so that every combination of a protocol, domain and path is a potential match set. On the right-hand side, we have the routing decisions. If caching is not enabled, the requests are routed directly to the backend.

Route matching is all about the “most-specific-request” that matches with the “left-hand-side”. The order of match is always protocol first, followed by the domain and then the path. The Match is always a yes or a no. Yes, there is a route with an exact match on the frontend host or no there is no such match. In the case of a “No”, a bad request error gets sent. After the host matching comes path matching. A similar logic to frontend hosts is used to match the request path. The only difference is that between a yes or a no, an approximate match based on wild card pattern is allowed. And as always, a failed match returns a bad request error.

One of the key differences between an application gateway and Front Door is this hybrid custom-domain and path-based routing combination matching as described above. Application gateway can be either custom-domain based or path-based routing in most deployments but FrontDoor by its nature to being global across different regional resource types, allows for both custom-domain and path-based matches. 

The anycast behavior from FrontDoor requires a comprehensive test matrix to avoid any unpredictability with low-latency choices made by default. For a choice of host and path, there can be four test cases at least even for a “/*” path. Predictability also involves trying those requests from various regions.

Thus, separate endpoints, routing and host header all play a role in determining the responses from the Azure Front Door. 

#codingexercise 

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 

Node reverse(Node master, Node start, Node end) {

If (start == null) return null;

If (start.next == null) return start;

Node tail = start;

Node prev = end;

Node cur = start;

Node next = cur.next;

While (next && cur != end) {

Cur.next = prev;

Prev = cur;

Cur = next;

Next = cur.next;

}

if (cur != end) {

     cur.next = prev;

     prev = cur;

     cur = next;

}

if (master != null) {

     master.next = prev;

} else {

    master = prev;

}

Return tail;

}

public Node reverse(Node head, int k) {

Node start = head;

Node end = head;

Node master = null;

while (end != null) {

    int count = 0;

    while (count < k && end != null) {

       end = end.next;

       count++;     

    }

    if (count == k) {

        Node last = master;

        master = reverse(master, start, end); 

         if (start == head) {

         head = master;

         }

         if (last != null) {

              last.next = master;

         } 

         while(master.next != end)  {

              master = master.next;

         }

         start = master.next;

         end = start;

    }

}

return head;

}


Thursday, May 16, 2024

 

This is a continuation of previous articles on IaC shortcomings and resolutions. With the example of Azure Front Door, we were explaining the use of separate origin groups for logical organization of backend and front-end endpoints. This section talks about route configuration.

A route is the primary directive to Azure Front Door to handle traffic. The route settings define an association between a domain and an origin group.  Features such as Pattern-to-match and rulesets enable granular control over traffic to the backend resources.

A routing rule is composed of two major parts, the “left-hand-side” and the “right-hand-side”. Front Door matches the incoming request to the left-hand side of the route while the right-hand side defines how the request gets processed. On the left-hand side, we have the HTTP Protocols, the domain, and the path where these properties are expanded out so that every combination of a protocol, domain and path is a potential match set. On the right-hand side, we have the routing decisions. If caching is not enabled, the requests are routed directly to the backend.

Route matching is all about the “most-specific-request” that matches with the “left-hand-side”. The order of match is always protocol first, followed by the domain and then the path. The Match is always a yes or a no. Yes, there is a route with an exact match on the frontend host or no there is no such match. In the case of a “No”, a bad request error gets sent. After the host matching comes path matching. A similar logic to frontend hosts is used to match the request path. The only difference is that between a yes or a no, an approximate match based on wild card pattern is allowed. And as always, a failed match returns a bad request error.

One of the key differences between an application gateway and Front Door is this hybrid custom-domain and path-based routing combination matching as described above. Application gateway can be either custom-domain based or path-based routing in most deployments but FrontDoor by its nature to being global across different regional resource types, allows for both custom-domain and path-based matches.

The anycast behavior from FrontDoor requires a comprehensive test matrix to avoid any unpredictability with low-latency choices made by default. For a choice of host and path, there can be four test cases at least even for a “/*” path. Predictability also involves trying those requests from various regions.

Thus, separate endpoints, routing and host header all play a role in determining the responses from the Azure Front Door.

Previous articles: https://1drv.ms/w/s!Ashlm-Nw-wnWhO4RqzMcKLnR-r_WSw?e=kTQwQd

 

 

Wednesday, May 15, 2024

 This is a continuation of previous articles on IaC shortcomings and resolutions. With the example of Azure Front Door, we were explaining the use of separate origin groups for logical organization of backend. This section talks about organization of endpoints.

An endpoint is a logical grouping of one or more routes associated with domain names. Each endpoint can be assigned a domain name either built-in or custom.  A Front Door profile can contain multiple domains especially when they have different routes and route paths. They can be combined into a single endpoint when there is a need to turn on or off collectively.

Azure Front Door can create managed certificates for custom domains even when the dns resolution occurs outside Azure. This makes https for end to end SSL easier to setup as the signed certificate is universally validated.

The steps taken to create endpoints is similar on both the frontend and the backend. The origin should be viewed as an endpoint for the application backend. When an origin is created in an origin group, Frontdoor requires to know the origin type and host headers. For an Azure app service, this could be contoso.azurewebsites.net or a custom domain. FrobtDoor validates if the request hostname matched the host name I’m the certificate provided by the origin.

Thus, separate endpoints, routing and host header all play a role in determining the responses from the Azure Front Door.

Previous articles: https://1drv.ms/w/s!Ashlm-Nw-wnWhO4RqzMcKLnR-r_WSw?e=kTQwQd 


Tuesday, May 14, 2024

 #codingexercise

Position eight queens on a chess board without conflicts:

    public static void positionEightQueens(int[][] B, int[][] used, int row) throws Exception {

        if (row == 8) {

            if (isAllSafe(B)) {

                printMatrix(B, B.length, B[0].length);

            }

            return;

        }

        for (int k = 0; k < 8; k++) {

            if ( isSafe(B, row, k) && isAllSafe(B)) {

                B[row][k] = 1;

                positionEightQueens(B, used, row + 1);

                B[row][k]  = 0;

            }

        }

    }

    public static boolean isSafe(int[][] B, int p, int q) {

        int row = B.length;

        int col = B[0].length;

        for (int i = 0; i < row; i++) {

            for (int j = 0; j < col; j++) {

                if (i == p && j == q) { continue; }

                if (B[i][j] == 1) {

                    boolean notSafe = isOnDiagonal(B, p, q, i, j) ||

                            isOnVertical(B, p, q, i, j) ||

                            isOnHorizontal(B, p, q, i, j);

                    if(notSafe){

                        return false;

                    }

                }

             }

        }

        return true;

    }

    public static boolean isAllSafe(int[][] B) {

        for (int i = 0; i < B.length; i++) {

            for (int j = 0; j < B[0].length; j++) {

                if (B[i][j]  == 1 && !isSafe(B, i, j)) {

                    return false;

                }

            }

        }

        return true;

    }

    public static boolean isOnDiagonal(int[][] used, int r1, int c1, int r2, int c2) {

        boolean result = false;

        int row = used.length;

        int col = used[0].length;

        for (int k = 0; k < 8; k ++) {

            if (r2 - k >= 0 &&  c2 - k >= 0 && r1 == r2 - k && c1 == c2 - k) {

                return true;

            }

            if (r2 + k < row && c2 + k < col && r1 == r2 + k && c1 == c2 + k) {

                return true;

            }

            if (r2 - k >= 0 && c2 + k < col && r1 == r2 - k && c1 == c2 + k) {

                return true;

            }

            if (r2 + k < row  && c2 - k >= 0 && r1 == r2 + k && c1 == c2 - k) {

                return true;

            }

        }

        return result;

    }

    public static boolean isOnVertical(int[][] used, int r1, int c1, int r2, int c2) {

        boolean result = false;

        int row = used.length;

        int col = used[0].length;

        for (int k = 0; k < 8; k++) {

            if (c2 - k >= 0  && c1 == c2 - k && r1 == r2 ) {

                return true;

            }

            if (c2 + k < row && c1 == c2 + k && r1 == r2) {

                return true;

            }

        }

        return result;

    }

    public static boolean isOnHorizontal(int[][] used, int r1, int c1, int r2, int c2) {

        boolean result = false;

        int row = used.length;

        int col = used[0].length;

        for (int k = 0; k < 8; k++) {

            if (r2 - k >= 0  && r1 == r2 - k && c1 == c2 ) {

                return true;

            }

            if (r2 + k < row && r1 == r2 + k && c1 == c2) {

                return true;

            }

        }

        return result;

    }


Sample output:

1 1 2 1 1 1 1 1

1 1 1 1 1 2 1 1

1 1 1 2 1 1 1 1

1 2 1 1 1 1 1 1

1 1 1 1 1 1 1 2

1 1 1 1 2 1 1 1

1 1 1 1 1 1 2 1

2 1 1 1 1 1 1 1