Wednesday, September 18, 2024

 There is a cake factory producing K-flavored cakes. Flavors are numbered from 1 to K. A cake should consist of exactly K layers, each of a different flavor. It is very important that every flavor appears in exactly one cake layer and that the flavor layers are ordered from 1 to K from bottom to top. Otherwise the cake doesn't taste good enough to be sold. For example, for K = 3, cake [1, 2, 3] is well-prepared and can be sold, whereas cakes [1, 3, 2] and [1, 2, 3, 3] are not well-prepared.

 

The factory has N cake forms arranged in a row, numbered from 1 to N. Initially, all forms are empty. At the beginning of the day a machine for producing cakes executes a sequence of M instructions (numbered from 0 to M−1) one by one. The J-th instruction adds a layer of flavor C[J] to all forms from A[J] to B[J], inclusive.

 

What is the number of well-prepared cakes after executing the sequence of M instructions?

 

Write a function:

 

class Solution { public int solution(int N, int K, int[] A, int[] B, int[] C); }

 

that, given two integers N and K and three arrays of integers A, B, C describing the sequence, returns the number of well-prepared cakes after executing the sequence of instructions.

 

Examples:

 

1. Given N = 5, K = 3, A = [1, 1, 4, 1, 4], B = [5, 2, 5, 5, 4] and C = [1, 2, 2, 3, 3].

 

There is a sequence of five instructions:

 

The 0th instruction puts a layer of flavor 1 in all forms from 1 to 5.

The 1st instruction puts a layer of flavor 2 in all forms from 1 to 2.

The 2nd instruction puts a layer of flavor 2 in all forms from 4 to 5.

The 3rd instruction puts a layer of flavor 3 in all forms from 1 to 5.

The 4th instruction puts a layer of flavor 3 in the 4th form.

The picture describes the first example test.

 

The function should return 3. The cake in form 3 is missing flavor 2, and the cake in form 5 has additional flavor 3. The well-prepared cakes are forms 1, 2 and 5.

 

2. Given N = 6, K = 4, A = [1, 2, 1, 1], B = [3, 3, 6, 6] and C = [1, 2, 3, 4],

 

the function should return 2. The 2nd and 3rd cakes are well-prepared.

 

3. Given N = 3, K = 2, A = [1, 3, 3, 1, 1], B = [2, 3, 3, 1, 2] and C = [1, 2, 1, 2, 2],

 

the function should return 1. Only the 2nd cake is well-prepared.

 

4. Given N = 5, K = 2, A = [1, 1, 2], B = [5, 5, 3] and C = [1, 2, 1]

 

the function should return 3. The 1st, 4th and 5th cakes are well-prepared.

 

Write an efficient algorithm for the following assumptions:

 

N is an integer within the range [1..100,000];

M is an integer within the range [1..200,000];

each element of arrays A, B is an integer within the range [1..N];

each element of array C is an integer within the range [1..K];

for every integer J, A[J] ≤ B[J];

arrays A, B and C have the same length, equal to M.

// import java.util.*;

 

 

class Solution {

    public int solution(int N, int K, int[] A, int[] B, int[] C) {

        int[]  first = new int[N]; // first

        int[]  last = new int[N]; // last

        int[]  num = new int[N]; // counts

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

            for (int current = A[i]-1; current <= B[i]-1; current++) {

                num[current]++;

                if (first[current] == 0) {

                    first[current] = C[i];

                    last[current] = C[i];

                    continue;

                }

                If (last[current] > C[I]) {

                     last[current] = Integer.MAX_VALUE;

                } else {

                     last[current] = C[i];

               }

            }

        }

        int count = 0;

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

            if (((last[i] - first[i]) == (K - 1)) && (num[i] == K)) {

                count++;

            }

        }        

        // StringBuilder sb = new StringBuilder();

        // for (int i = 0; i < N; i++) {

        //     sb.append(last[i] + " ");

        // }

        // System.out.println(sb.toString());

        return count;

    }

}

Example test:   (5, 3, [1, 1, 4, 1, 4], [5, 2, 5, 5, 4], [1, 2, 2, 3, 3])

OK

 

Example test:   (6, 4, [1, 2, 1, 1], [3, 3, 6, 6], [1, 2, 3, 4])

OK

 

Example test:   (3, 2, [1, 3, 3, 1, 1], [2, 3, 3, 1, 2], [1, 2, 1, 2, 2])

OK

 

Example test:   (5, 2, [1, 1, 2], [5, 5, 3], [1, 2, 1])

OK


n_equal_to_1

OK

k_equal_to_1

OK

m_equal_to_1

OK

interval_contains_one_cake

OK

none_correct

OK


Tuesday, September 17, 2024

 


Given an array of varying heights above sea level for adjacent plots, and the array of water levels on consecutive days, find the number of islands. An island is a slice of array such that plots adjacent to the boundary of the island are under water.

class Solution { 

public int[] solution(int[] A, int[] B) {

    return Arrays

    .stream(B)

    .map(water -> IntStream

         .range(0, N)

         .filter(j -> (A[j] > water) && (j == N - 1 || A[j + 1] <= water))

         .map(i -> 1)

         .sum()) .toArray();

}

}

For example, given the following arrays A and B:

    A[0] = 2    B[0] = 0

    A[1] = 1    B[1] = 1

    A[2] = 3    B[2] = 2

    A[3] = 2    B[3] = 3

    A[4] = 3    B[4] = 1

Solution: 

result[0] = 1

result[1] = 2

result[2] = 2

result[3] = 0

result[4] = 2


For a water level, the number of islands is just the sum of changes in the number of islands as the water level is decreasing.

Optimized solution:

class Solution { 

public int[] solution(int[] A, int[] B) {

     int limit = Math.max(maxLevel(A), maxLevel(B));

     int[] island = new int[limit + 2];

     IntStream.range(0, A.length - 1)

                       .filter( j -> A[j]  > A[j+1])

                      .forEach(j ->  {

                                       island[A[j]] += 1;

                                       island[A[j + 1]] -= 1;

                       });

     island[A[A.length-1]] += 1;

     IntStream.range(-limit, 0)

                      .forEach(i -> island[-i] += island[-i+1]);

     return Arrays.stream(B).map(water -> island[water + 1]).toArray();

}

public int maxLevel(int[] A) {

       return Arrays.stream(A).max().getAsInt();

}

}


// before cumulation

island[0] = 0

island[1] = -1

island[2] = 0

island[3] = 2

island[4] = 0

// after cumulation

island[0] = 1

island[1] = 1

island[2] = 2

island[3] = 2

island[4] = 0


result[0] = 1

result[1] = 2

result[2] = 2

result[3] = 0

result[4] = 2



Monday, September 16, 2024

 2259. Remove Digit From Number to Maximize Result

You are given a string number representing a positive integer and a character digit.

Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit occurs at least once in number.

 

Example 1:

Input: number = "123", digit = "3"

Output: "12"

Explanation: There is only one '3' in "123". After removing '3', the result is "12".

Example 2:

Input: number = "1231", digit = "1"

Output: "231"

Explanation: We can remove the first '1' to get "231" or remove the second '1' to get "123".

Since 231 > 123, we return "231".

Example 3:

Input: number = "551", digit = "5"

Output: "51"

Explanation: We can remove either the first or second '5' from "551".

Both result in the string "51".

 

Constraints:

2 <= number.length <= 100

number consists of digits from '1' to '9'.

digit is a digit from '1' to '9'.

digit occurs at least once in number.

import java.util.*;

import java.util.Comparator;

import java.lang.*;

import java.io.*;


class Program

{

public static void main (String[] args) throws java.lang.Exception

{

getMaxWithOneDigitRemoval("123", "3 ");

getMaxWithOneDigitRemoval("1231", "1");

getMaxWithOneDigitRemoval("551", "5");

}

private static String getMaxWithOneDigitRemoval(Strint input, Character digit)

{

if (input == null || input.length() == 0 || digit == null) return input;

List<Integer> locations = new ArrayList<Integer>();

for (int i = 0; i < input.Length(); i++)

{

if (digit.equals(input.charAt(i)))

{

locations.add(i);

}

}


List<Integer> candidates = new ArrayList<Integer>();

locations.forEach(x => candidates.add(convertTo(maximize(input, x))));

return String.valueOf(candidates.stream().max(Integer::compare).get());

}

private static String maximize(String input, Integer index)

{

if (index == 0 ) return input.substring(1, input.length());

if (index == input.length() - 1) return input.substring(0, input.length() - 1);

return input.substring(0,index) + input.substring(index+1, input.length());

}

private static Integer convertTo(String input) {

int power = 0;

Integer sum = 0;

for (int i = input.length()-1; i>=0; i--)

{

sum += Integer.parseInt(input.charAt(i).toString()) * Math.pow(10, power);

power++;

}

return sum;

}

}


Sunday, September 15, 2024

 


Missing ranges: 

You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range. 

A number x is considered missing if x is in the range [lower, upper] and x is not in nums. 

Return the smallest sorted list of ranges that cover every missing number exactly. That is, no element of nums is in any of the ranges, and each missing number is in one of the ranges. 

Each range [a,b] in the list should be output as: 

"a->b" if a != b 

"a" if a == b 

  

Example 1: 

Input: nums = [0,1,3,50,75], lower = 0, upper = 99 

Output: ["2","4->49","51->74","76->99"] 

Explanation: The ranges are: 

[2,2] --> "2" 

[4,49] --> "4->49" 

[51,74] --> "51->74" 

[76,99] --> "76->99" 

Example 2: 

Input: nums = [-1], lower = -1, upper = -1 

Output: [] 

Explanation: There are no missing ranges since there are no missing numbers. 

  

Constraints: 

-109 <= lower <= upper <= 109 

0 <= nums.length <= 100 

lower <= nums[i] <= upper 

All the values of nums are unique. 

 


class Solution { 

    public List<String> missingRanges(int lower, int upper, int[] range) {

var result = new List<String>();

       int start = lower;

       String candidate = String.Empty;

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

           if (start != range[i]) {

               int end = range[i]-1;

               if (start == end) candidate = start;

               else candidate = start + “->” + end;

               result.add(candidate);

               candidate = “”;

                

           }

           start = range[i]+1;

    

       }

       if (start == upper) {

          result.add(start);

       }

       if (start < upper){

          result.add(start + “->” + upper); 

       }

return result;

    }



Saturday, September 14, 2024

 This is a comparison of the technologies between a driver platform and a drone fleet platform from the points of their shared focus and differences.

Tenet 1: Good infrastructure enables iterations.

Whether it is a modular algorithm or a microservice, one might need to be replaced with another or used together, a good infrastructure enables their rapid development.

Tenet 2: modular approach works best to deliver quality safety-critical AI systems and iterative improvements. Isolation is the key enablement for quality control, and nothing beats that than modular design.

Tenet 3: spatial-temporal fusion increases robustness and decreases uncertainty. Whether on ground or in the air and irrespective of the capabilities of the unit, space and time provide holistic information. 

Tenet 4: vision language models enable deep reasoning. The queries can be better articulated, and the responses have higher precision and recall.

The methodology for both involves:

Learn everything but never require perfection because it is easy to add to the vector but difficult to be perfect about the selection

Resiliency reigns where there are no single neural paths to failure. This is the equivalent of no single point of failure.

Multi-modality first: so that when multiple sensors fail or the data is not complete, decisions can still be made.

Interpretability and partitioning so that data can be acted on without requiring whole state all the time.

Generalization so that the same model can operate in different contexts.

Surface scoping with bounded validations so that this helps with keeping cost under check.

Now, for the differences, the capabilities of the individual units aside, the platform treats them as assets in a catalog and while some of them might be autonomous, the platform facilitates both federated and delegated decision support. The catalog empowers multi-dimension organization just like MDMs do, the data store supports both spatial and temporal data, vector data and metadata filtering at both rest and in transit. The portfolio of services available on the inventory is similar to that of an e-commerce store with support for order processing from different points of sale.

Reference:

Context for this article:DroneInformaionManagement.docx

#codingexercise 

https://1drv.ms/w/s!Ashlm-Nw-wnWhMpBIeUfRGhoL3sNog?e=6qFL0A 


Friday, September 13, 2024

 Estimation: 

Infrastructure changes need to be estimated just like any software changes, which means external dependencies and internal restrictions shape the scope, depth, and form of change. Estimation can be hard when the change appears simple but turns out to be complex. A specific case study might illustrate the challenges and norms of this kind of task.

One of the most routine encountered cases of software migration to the cloud is the migration of entire Kubernetes workload. As an ecosystem of its own supporting state reconciliation of resources for applications, workflows, orchestrations, and data store managers. As an instance of a resource type in the public cloud, it is a unit that lends itself to the management from the public cloud console. One of the management activities of this resource is its move from one location to another or one network to another. When switching just the network integration for outbound traffic for this network, it might be tempting to think of it as a property change of a resource that amounts to in-place update. But this is just the tip of the iceberg. Different methodologies and formulae for estimation although applicable to many scenarios do not apply to this case-study without further investigation. 

In this case, the instance has a default node pool and many additional node pools that may still be referencing the old network even with directive to switch to new network. They also happen to refer to additional storage accounts for facilitating the creation of persistent volumes as key vaults for storing secrets. If these satellite resources are also restricting traffic to private planes, then networking and authentication must both be enabled from the new network. 

The infrastructure changes for this might also not be straight forward single-pass and require iterative maneuvers to make incremental progress. This is specifically the case when the IaC compiler encounters multiple other resources and detect changes in them  the path of minimal changes to the infrastructure will imply the lowest cost and this works very well if we can wipe clean and create with the same specifications as earlier but with the new network.

Thus, estimation of infrastructure is heavily dependent on what the resource needs, the changes being made to it and what the compiler detects as mandatory to perform before applying the change. 

Reference: previous article in this series: https://1drv.ms/w/s!Ashlm-Nw-wnWhPQxEDH6Cm567ZzPug?e=yTLB2D


Thursday, September 12, 2024

 

A list of packets is given with varying sizes and there are n channels. 

 

Each of the n channel must have a single packet 

Each packet can only be on a single channel 

The quality of a channel is described as the median of the packet sizes on that channel. The total quality is defined as sum of the quality of all channels (round to integer in case of float). Given the packets []int32 and channels int32 find the maximum quality. 

 

Example 1: 

 

packets := []int32{1, 2, 3, 4, 5} 

channels := 2 

 

// Explanation: If packet {1, 2, 3, 4} is sent to channel 1, the median of that channel would be 2.5. 

//               If packet {5} is sent to channel 2 its median would be 5.  

//               Total quality would be 2.5 + 5 = 7.5 ~ 8 

answer := 8 

Example 2: 

 

packets := []int32{5, 2, 2, 1, 5, 3} 

channels := 2 

 

// Explaination: Channel 1: {2, 2, 1, 3} (median: 2) 

//               Channel 2: {5, 5}       (median: 5) 

//               Total Quality : 2 + 5 = 7 

 

// Explaination 2: Channel 1: {5, 2, 2, 1, 3} (median: 2) 

//                 Channel 2: {5}             (median: 5) 

//                 Total Quality : 2 + 5 = 7 

answer := 7 

 

 

import java.util.*; 

import java.lang.*; 

import java.io.*; 

import java.util.stream.*; 

 

class Solution 

{ 

public static void main (String[] args) throws java.lang.Exception 

{ 

int packets[] = { 5,2,2,1,5,3 }; 

int channels = 2; 

System.out.println(getQuality(packets, channel)); 

} 

 

private static int getQuality(int[] packets, int channel); 

{ 

int quality = 0; 

Array.sort(packets); 

int index = packets.length - 1; 

for (int i = channel - 1; i >= 1; i--) 

{ 

while (index -1 >= 0 && packets[index] == packets[index -1]) 

index--; 

quality += packets[index]; 

} 

quality += getMedian(packets, 0, index); 

return quality; 

} 

 

private static int getMedian(int[] packets, int start, int end) 

{ 

int length =  (end - start + 1); 

int mid = (start + end)/2; 

if (length %2 == 0) 

{ 

return (packets[mid]+packets[mid+1])/2; 

} 

else 

{ 

return packets[mid]; 

} 

} 

}