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]; 

} 

} 

} 

 

 

 

 

Tuesday, September 10, 2024

 



Problem 1: 

A string consists of only ‘a’ and/or ‘b’.  No three consecutive letters of one kind are allowed. Determine the minimum number of swaps between the two letters to make the string conform.

Test cases that must pass:

Aabaaab => 1

Abab => 0


Solution 1:


class Solution {

    public int solution(String input) {

        StringBuilder S = new StringBuilder(input);

        int count = 0;

        int i = 1;

        while ( i < S.length())

        {

            if (S.charAt(i-1) != S.charAt(i)) {

                     i++;

                     continue;

            }

            else {

                if (i + 1 < S.length() && i + 2 < S.length()) {

                    if (S.charAt(i+1) == S.charAt(i+2) && 

                        S.charAt(i+1) == S.charAt(i)){

                            if (S.charAt(i) == S.charAt(i-1)) {

                                if (S.charAt(i+2) == 'a') S.setCharAt(i+2, 'b');

                                else S.setCharAt(i+2, 'a');

                                count++;

                                i = i + 3;

                                continue;

                            }

                            else {

                                if (S.charAt(i+1) == 'a') S.setCharAt(i+1, 'b');

                                else S.setCharAt(i+1, 'a');

                                i = i + 2;

                                count++;

                                continue;

                            }

                        }

                    else if (S.charAt(i+1) == S.charAt(i)) {

                                if (S.charAt(i) == 'a') S.setCharAt(i, 'b');

                                else S.setCharAt(i, 'a');

                                count++;

                                i = i + 1;

                                continue;

                    }

                    else {

                        i = i + 1;

                        continue;

                    }

                }

                else if (i + 1 < S.length()) {

                    if (S.charAt(i+1) == s.charAt(i)) {

                        if (S.charAt(i) == 'a') S.setCharAt(i, 'b');

                        else S.setCharAt(i, 'a');

                        count++;

                        i = i + 1;

                        continue;

                    }

                    else {

                        i = i + 1;

                        continue;

                    }

                }

                else {

                    i++;

                    continue;

                }

            }

        }

        return count;

    }

}



Problem 2:

A string consists of only ‘a’ and/or ‘b’. An integer array consists of costs of removing the letter at a given position. Determine the minimal cost to convert the string so that there are no two consecutive letters identical.

Test cases that must pass

“ab”, [1,4] => 0

“aabb”, [1,2,1,2] => 2 letters at index = 0,2 removed

“aaaa”, [3,4,5,6] => 12 letters at index = 0,1,2 removed.



Import java.lang.math;


class Solution {

    public int solution(String S, int[] C) {

        int cost = 0;

        for (int i = 1; i < S.length(); i++)

        {

            if (S.charAt(i-1) == S.charAt(i)) {

                     cost += Math.min(C[i-1], C[i]);

            }

        }

        return cost;

}



Problem 3: 

A set of test names and their results are provided as two string arrays with the testname at index i corresponding to the result at same index. The testnames are all lowercase and conform to a prefix followed by a group number, followed by the test case specific unique lowercase alphabet suffix if there are more than one tests in that group. Results can be one of four different strings. A group that has all the tests in it with result as “OK” is valid. The tests and the results must be scored by determining the percentage of valid to total tests and returning it as a lower bound integer.

TestCase

“test1a”, “OK” 

“test1b”, “OK”


“test2”,  “OK”


“test3”, “Error”


“test4a”, “Timeout”

“test4b”, “OK”


“test5a”, “Error”

“test5b”, “Timeout”


“test6”, “Incorrect”

 Score:33


Solution:

Import java.lang.math;


class Solution {

    public int solution(String[] T, int[] R) {

        int score = 0;

       Map<Integer, List<String>> groupMap = new HashMap<Integer, List<String>>();

       for (int I =0; I < T.length; i++)

       {

            // parse

            StringBuilder sb = new StringBuilder(); 

            for (int j = 0; j < T[i].length(); j++)

            {

                           If(T[i].charAt(j) >= ‘a’ && T[i].charAt(j) <= ‘z’) {

                                 continue;

                           }

                          sb.append(T[i].charAt(j));

            }

            Int group = 0;

            try {

                    group = Integer.parseInt(sb.toString());

            } catch (NumberFormatException) {

            }

            

            If (groupMap.containsKey(group)) {

                        groupMap.get(group).add(R[i]);

            } else {

                        List<String> results = new ArrayList<String>();

                        results.add(R[i]);

                        groupMap.put(group, results);

            }


            // eval

            int valid = 0;

            int total = 0;

            for (Map.entry<Integer, List<String>> e : groupMap.entrySet()) {

                   boolean passed = true;

                   for (String result : e.getValue()) {

                          if (!result.equals(“OK”)) {

                               passed = false;

                               break;

                          } 

                   }

                   if (passed) {

                              valid++;

                   }

                   total++;

            }


            // score

            score = (int)Math.floor((valid*100)/total);  

       }

       return score;

}


Monday, September 9, 2024

Make Array Zero by Subtracting Equal Amounts
You are given a non-negative integer array nums. In one operation, you must:
Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums.
Subtract x from every positive element in nums.
Return the minimum number of operations to make every element in nums equal to 0.
 
Example 1:
Input: nums = [1,5,0,3,5]
Output: 3
Explanation:
In the first operation, choose x = 1. Now, nums = [0,4,0,2,4].
In the second operation, choose x = 2. Now, nums = [0,2,0,0,2].
In the third operation, choose x = 2. Now, nums = [0,0,0,0,0].
Example 2:
Input: nums = [0]
Output: 0
Explanation: Each element in nums is already 0 so no operations are needed.
 
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100

import java.util.*;
import java.util.stream.*;
class Solution {
    public int minimumOperations(int[] nums) {
        List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());
        var nonZero = list.stream().filter(x -> x > 0).collect(Collectors.toList());
        int count = 0;
        while(nonZero.size() > 0) {
            var min = nonZero.stream().mapToInt(x -> x).min().getAsInt();
            nonZero = nonZero.stream().map(x -> x - min).filter(x -> x > 0).collect(Collectors.toList());
            count++;
        }
        return count;
    }
}

Input
nums =
[1,5,0,3,5]
Output
3
Expected
3

Input
nums =
[0]
Output
0
Expected
0