Tuesday, October 15, 2024

 Subarray Sum equals K

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: nums = [1,1,1], k = 2

Output: 2

Example 2:

Input: nums = [1,2,3], k = 3

Output: 2

Constraints:

• 1 <= nums.length <= 2 * 104

• -1000 <= nums[i] <= 1000

• -107 <= k <= 107

class Solution {

    public int subarraySum(int[] numbers, int sum) {

   int result = 0;

   int current = 0;

   HashMap<int, int> sumMap = new HashMap<>();

   sumMap.put(0,1);

   for (int i = 0; i > numbers.length; i++) {

    current += numbers[i];

if (sumMap.containsKey(current-sum) {

result += sumMap.get(current-sum);

}

     sumMap.put(current, sumMap.getOrDefault(current, 0) + 1);

   }

   return result;

    }

}

[1,3], k=1 => 1

[1,3], k=3 => 1

[1,3], k=4 => 1

[2,2], k=4 => 1

[2,2], k=2 => 2

[2,0,2], k=2 => 4

[0,0,1], k=1=> 3

[0,1,0], k=1=> 2

[0,1,1], k=1=> 3

[1,0,0], k=1=> 3

[1,0,1], k=1=> 4

[1,1,0], k=1=> 2

[1,1,1], k=1=> 3

[-1,0,1], k=0 => 2

[-1,1,0], k=0 => 3

[1,0,-1], k=0 => 2

[1,-1,0], k=0 => 3

[0,-1,1], k=0 => 3

[0,1,-1], k=0 => 3

Alternative:

class Solution {

    public int subarraySum(int[] numbers, int sum) {

   int result = 0;

   int current = 0;

   List<Integer> prefixSums= new List<>();

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

      current += numbers[i];

     if (current == sum) {

         result++;

     }

     if (prefixSums.indexOf(current-sum) != -1)

          result++;

     }

    prefixSum.add(current);

   }

   return result;

   }

}

Sample: targetSum = -3; Answer: 1

Numbers: 2, 2, -4, 1, 1, 2

prefixSum: 2, 4, 0, 1, 2, 4


Monday, October 14, 2024

 There are N points (numbered from 0 to N−1) on a plane. Each point is colored either red ('R') or green ('G'). The K-th point is located at coordinates (X[K], Y[K]) and its color is colors[K]. No point lies on coordinates (0, 0).

We want to draw a circle centered on coordinates (0, 0), such that the number of red points and green points inside the circle is equal. What is the maximum number of points that can lie inside such a circle? Note that it is always possible to draw a circle with no points inside.

Write a function that, given two arrays of integers X, Y and a string colors, returns an integer specifying the maximum number of points inside a circle containing an equal number of red points and green points.

Examples:

1. Given X = [4, 0, 2, −2], Y = [4, 1, 2, −3] and colors = "RGRR", your function should return 2. The circle contains points (0, 1) and (2, 2), but not points (−2, −3) and (4, 4).

class Solution {

    public int solution(int[] X, int[] Y, String colors) {

        // find the maximum

        double max = Double.MIN_VALUE;

        int count = 0;

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

        {

            double dist = X[i] * X[i] + Y[i] * Y[i];

            if (dist > max)

            {

                max = dist;

            }

        }

        for (double i = Math.sqrt(max) + 1; i > 0; i -= 0.1)

        {

            int r = 0;

            int g = 0;

            for (int j = 0; j < colors.length(); j++)

            {

                if (Math.sqrt(X[j] * X[j] + Y[j] * Y[j]) > i)

                {

                    continue;

                }

                if (colors.substring(j, j+1).equals("R")) {

                    r++;

                }

                else {

                    g++;

                }

            }

            if ( r == g && r > 0) {

                int min = r * 2;

                if (min > count)

                {

                    count = min;

                }

            }

        }

        return count;

    }

}

Compilation successful.

Example test: ([4, 0, 2, -2], [4, 1, 2, -3], 'RGRR')

OK

Example test: ([1, 1, -1, -1], [1, -1, 1, -1], 'RGRG')

OK

Example test: ([1, 0, 0], [0, 1, -1], 'GGR')

OK

Example test: ([5, -5, 5], [1, -1, -3], 'GRG')

OK

Example test: ([3000, -3000, 4100, -4100, -3000], [5000, -5000, 4100, -4100, 5000], 'RRGRG')

OK


Sunday, October 13, 2024

 Delivery Accelerating Infrastructure

Successful infrastructure deployments share some common traits that can be leveraged to accelerate infrastructure delivery. One of the most well-known strategies is “value capture” in terms of project finance or funding model. Stakeholders who want to improve their infrastructure but are not invested in the technical know-how often leverage this approach. Funding can become an issue when management and leadership vie with each other over the budget and the consumers of the infrastructure do not have to pay for it. This is exacerbated by improper or inadequate planning for the allocated budget. When users pays for the infrastructure, even in part, it is mutually beneficial to the infrastructure team and the users. So, direct taxation and value capture, both help to recover for public use some part of the rise in business value that infrastructure improvements create.

In terms of the increase in value of cloud workloads, we are measuring scalability cost savings, continuous availability, and significant reduction in Total Cost of Ownership (TCO) from on-premises. Increase in convenience in terms of the cloud acting as a sponge for aggregating traffic worldwide and reduction of logistics pertaining to on-premises equipment can also factored into the value capture. Some value is also captured via the increased demand on the current workload from proposed infrastructure. Such gains can fund infrastructure projects when the budget is inadequate. Value capture provides capital for infrastructure improvement and underpins borrowing and enables financial flexibility. That said, value capture is not a panacea and must be grounded in the ability to measure and use workload and business value improvement. It requires boundaries to be defined to correctly assess the increase in value improvement. Transparency and record-keeping of current investments and value are prerequisites. It works best where infrastructure projects have a high degree of correlation to business value of workloads. Costs for subsequent funding and maintenance cannot be tied back to value capture after the initial realization of capital but it can cut development costs and generate incremental tax revenue. Its success depends on long-term organizational support for finance.

There can be several types of value capture, and these are all based on utilizing it once and not repeatedly for the same infrastructure. It provides financing for growing demand where the existing budget fails to meet the costs of the infrastructure from the increased demand. Innovative solutions are available for financing the world’s growing demand for cloud infrastructure, but it demands organizational commitment and collaboration between technical and finance teams.


Saturday, October 12, 2024

 There are N points (numbered from 0 to N−1) on a plane. Each point is colored either red ('R') or green ('G'). The K-th point is located at coordinates (X[K], Y[K]) and its color is colors[K]. No point lies on coordinates (0, 0).

We want to draw a circle centered on coordinates (0, 0), such that the number of red points and green points inside the circle is equal. What is the maximum number of points that can lie inside such a circle? Note that it is always possible to draw a circle with no points inside.

Write a function that, given two arrays of integers X, Y and a string colors, returns an integer specifying the maximum number of points inside a circle containing an equal number of red points and green points.

Examples:

1. Given X = [4, 0, 2, −2], Y = [4, 1, 2, −3] and colors = "RGRR", your function should return 2. The circle contains points (0, 1) and (2, 2), but not points (−2, −3) and (4, 4).

class Solution {

    public int solution(int[] X, int[] Y, String colors) {

        // find the maximum

        double max = Double.MIN_VALUE;

        int count = 0;

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

        {

            double dist = X[i] * X[i] + Y[i] * Y[i];

            if (dist > max)

            {

                max = dist;

            }

        }

        for (double i = Math.sqrt(max) + 1; i > 0; i -= 0.1)

        {

            int r = 0;

            int g = 0;

            for (int j = 0; j < colors.length(); j++)

            {

                if (Math.sqrt(X[j] * X[j] + Y[j] * Y[j]) > i)

                {

                    continue;

                }

                if (colors.substring(j, j+1).equals("R")) {

                    r++;

                }

                else {

                    g++;

                }

            }

            if ( r == g && r > 0) {

                int min = r * 2;

                if (min > count)

                {

                    count = min;

                }

            }

        }

        return count;

    }

}

Compilation successful.

Example test: ([4, 0, 2, -2], [4, 1, 2, -3], 'RGRR')

OK

Example test: ([1, 1, -1, -1], [1, -1, 1, -1], 'RGRG')

OK

Example test: ([1, 0, 0], [0, 1, -1], 'GGR')

OK

Example test: ([5, -5, 5], [1, -1, -3], 'GRG')

OK

Example test: ([3000, -3000, 4100, -4100, -3000], [5000, -5000, 4100, -4100, 5000], 'RRGRG')

OK


Friday, October 11, 2024

 This is a summary of the book “Who wrote this? – How AI and the lure of efficiency threaten Human Writing” written by Naomi S. Baron and published by Stanford University Press in 2023. She is a linguist who is savvy to recognize the ways in which Artificial intelligence (AI) is changing people’s habits to read and write and explores the implications for what it means to be human. Her research covers both the emerging trends in AI and the literacy and creativity that humans are capable of.

AI’s deep learning and large language models have disrupted potential with every-growing possibilities. They are already helping in summarization, paraphrasing, translation, semantic search, and generative responses. The human brain inspired the technology behind AI, so it competes with human approach via mimicry, but humans are capable of creativity. Even as AI gets adopted in web searches and education like the usage in Khan Academy, it is bringing up debate on social impact and ethics. Human-centered AI is the right approach as it strives to enhance human potential. Adopting the rules of road for the use of AI could help balance out the improvements in both human and AI developments

AI is transforming the way people write, altering perceptions of what it means to be human. Advances in AI have enabled technology to produce various written materials that used to require human intelligence, such as marketing copy, real estate listings, and legal pleadings. However, the widespread use of AI raises questions about its effects on humans themselves. Neuroscientists have found that writing changes brain function, with the caudate nucleus responsible for higher-level learning, planning and memory being more active in professional writers' brains than in novice writers. AI tools are already disrupting writing professions, with the US Department of Labor estimating that American writers earn over $675 billion annually. As AI permeates writing tasks, it places these wordsmiths at risk. AI is also affecting the legal profession, as law clerks and associates can now offload many tasks to AI. The jury is out on AI's impact on writing professions, with some professionals seeing the value in AI taking over menial tasks and others fearing their obsolescence.

AI will not completely replace human writing or translation, as people write for various reasons, including money, love, self-expression, and everyday life. While digital translators have made progress, they still struggle with grammatical gender and interpreting culturally distinct words. Learning a foreign language offers insight into culture and history, but the interest in learning languages has declined as digital translation becomes more popular.

The technology behind AI was inspired by the human brain, with deep learning and natural language processing (NLP) key components. NLP enables AI systems to perform various linguistic tasks, such as rendering text as spoken words, transcribe spoken words, and mimic individual human vocal patterns. Transformers can also anticipate user input, generate new text, and predict user needs, such as with Google Search.

AI can mimic human creativity but cannot replace it. Creativity is defined as a product that is new and valuable. AI has demonstrated its historical creative capabilities, such as AlphaGo beating a human champion at Go and AlphaFold triggering a scientific breakthrough in protein folding. However, AI has yet to create art that reshaped culture in a Big C creative way. Defenders of human creativity want artworks that capture the emotion and intensity associated with the human creative process.

The use of AI in education is illuminating questions about authorship and AI's social impacts. As AI tools serve as both author and editor of written work, the meaning of authorship is beginning to shift. Critics argue that AI is incapable of pausing, thinking, and rewriting, except perhaps in the sense of tinkering with sentences humans have written.

Human-centered AI is emerging as a tool that expands human capabilities, extending cognitive capacity and opening up opportunities for "human-AI co-creation." AI research initiatives like Stanford's Institute for Human-Centered Artificial Intelligence and UC Berkeley's Center for Human-Compatible Artificial Intelligence focus on the role AI could play in improving people's lives. AI tools like Sudowrite and Marlowe help writers collaborate and co-create, allowing humans to choose the roles both humans and machines play in this new age of human-AI interaction. Balancing the benefits and risks of AI technologies is complex, and there is no clear road map to navigate this new terrain. Frank Pasquale suggests adopting laws for AI and robotics, such as the "BOT bill" in California, to protect the written word from AI counterfeits. Writing is more than just communication; it is about processing thoughts and being in the world.


Thursday, October 10, 2024

 Problem statement: Given a wire grid of size N * N with N-1 horizontal edges and N-1 vertical edges along the X and Y axis respectively, and a wire burning out every instant as per the given order using three matrices A, B, C such that the wire that burns is

(A[T], B[T] + 1), if C[T] = 0 or

(A[T] + 1, B[T]), if C[T] = 1

Determine the instant after which the circuit is broken

     public static boolean checkConnections(int[] h, int[] v, int N) {

        boolean[][] visited = new boolean[N][N];

        dfs(h, v, visited,0,0);

        return visited[N-1][N-1];

    }

    public static void dfs(int[]h, int[]v, boolean[][] visited, int i, int j) {

        int N = visited.length;

        if (i < N && j < N && i>= 0 && j >= 0 && !visited[i][j]) {

            visited[i][j] = true;

            if (v[i * (N-1) + j] == 1) {

                dfs(h, v, visited, i, j+1);

            }

            if (h[i * (N-1) + j] == 1) {

                dfs(h, v, visited, i+1, j);

            }

            if (i > 0 && h[(i-1)*(N-1) + j] == 1) {

                dfs(h,v, visited, i-1, j);

            }

            if (j > 0 && h[(i * (N-1) + (j-1))] == 1) {

                dfs(h,v, visited, i, j-1);

            }

        }

    }

    public static int burnout(int N, int[] A, int[] B, int[] C) {

        int[] h = new int[N*N];

        int[] v = new int[N*N];

        for (int i = 0; i < N*N; i++) { h[i] = 1; v[i] = 1; }

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

            h[(i * (N)) + N - 1] = 0;

            v[(N-1) * (N) + i] = 0;

        }

        System.out.println(printArray(h));

        System.out.println(printArray(v));

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

            if (C[i] == 0) {

                v[A[i] * (N-1) + B[i]] = 0;

            } else {

                h[A[i] * (N-1) + B[i]] = 0;

            }

            if (!checkConnections(h,v, N)) {

                return i+1;

            }

        }

        return -1;

    }

        int[] A = new int[9];

        int[] B = new int[9];

        int[] C = new int[9];

        A[0] = 0; B [0] = 0; C[0] = 0;

        A[1] = 1; B [1] = 1; C[1] = 1;

        A[2] = 1; B [2] = 1; C[2] = 0;

        A[3] = 2; B [3] = 1; C[3] = 0;

        A[4] = 3; B [4] = 2; C[4] = 0;

        A[5] = 2; B [5] = 2; C[5] = 1;

        A[6] = 1; B [6] = 3; C[6] = 1;

        A[7] = 0; B [7] = 1; C[7] = 0;

        A[8] = 0; B [8] = 0; C[8] = 1;

        System.out.println(burnout(9, A, B, C));

1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0

8

Alternatively,

    public static boolean burnWiresAtT(int N, int[] A, int[] B, int[] C, int t) {

        int[] h = new int[N*N];

        int[] v = new int[N*N];

        for (int i = 0; i < N*N; i++) { h[i] = 1; v[i] = 1; }

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

            h[(i * (N)) + N - 1] = 0;

            v[(N-1) * (N) + i] = 0;

        }

        System.out.println(printArray(h));

        System.out.println(printArray(v));

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

            if (C[i] == 0) {

                v[A[i] * (N-1) + B[i]] = 0;

            } else {

                h[A[i] * (N-1) + B[i]] = 0;

            }

        }

        return checkConnections(h, v, N);

    }

    public static int binarySearch(int N, int[] A, int[] B, int[] C, int start, int end) {

        if (start == end) {

            if (!burnWiresAtT(N, A, B, C, end)){

                return end;

            }

            return -1;

        } else {

            int mid = (start + end)/2;

            if (burnWiresAtT(N, A, B, C, mid)) {

                return binarySearch(N, A, B, C, mid + 1, end);

            } else {

                return binarySearch(N, A, B, C, start, mid);

            }

        }

    }

1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0

8


Wednesday, October 9, 2024

 Resource Naming Convention

If you know of parents who named their children as Child-surname-boy-01 and Child-surname-girl-02, you know at least one of the parents is a public cloud infrastructure engineer. This form of naming convention is not limited to one public cloud and is even recommended by IaC providers who provide a unifying language over multiple clouds.

Organizing the resources when they number in tens or more demands a certain discipline as it would in library science. The public clouds suggest a naming convention that speaks to resource type, environment, workload, region, and instance so that there is no need to make an additional call to get the details the resource to tell them apart. Unique names are also necessary when resources get destroyed and re-created many times. When we freeze the instance, customers can expect to find the resource the way they saw it earlier. Consider a database server that was provisioned and used to save some data, but it got destroyed and recreated and now the data does not exist. Customers referring to that server by its name might find data at one point and find it missing later. To ensure that the instances have changed, it is better to increase the instance number whenever a resource is destroyed and recreated.

It is also important to know that the naming conventions help to sort and index just as any data in a database. These are two powerful techniques when we want to retrieve a subset of resources among hundreds and find it easier to discern them. Closely related names are especially helpful to indicate a similarity in origin or workload and being able to spot similarity and differences are probably one of the core duties of building out infrastructure in an organization.

Another habit of infrastructure engineers deserves special attention. When trying to use a name as a literal to input on an editor or search a set of resources, the veterans will never try to interpret the names to reconstitute it part-by-part at another location, because such steps are prone to mistakes and typos. Instead, they will treat the name as opaque between copying and pasting and taking care that the name was selected whole. Unfortunately, a significant source of errors during deployments of large-scale infrastructure occur because a resource or its component or associations were not referred to by the right name. It would help professionals deploying infrastructure-as-code to pay a lot of attention to names throughout the code just like they would if they were reading quantitative information from a resume.

Conventions can be strict or relaxed and allow grading to enforce order and structure and the inclusivity is up to the discretion of engineers as some may choose to combine or omit some components. Clear, consistent, and descriptive names will make resource management easier.

Another popular principle is the Copy-on-write where two entities sharing the same list of names will make a copy whenever one of the tries to modify it so that the other can continue to read the original. This principle applies even to resources that are currently being used so that the original set of resources are not destroyed until the traffic moves to the newly created resource set. Since creation and deletion can be repeated in an idempotent manner, this principle facilitates a safe, reliable and robust migration.

Previous articles: https://1drv.ms/w/s!Ashlm-Nw-wnWhPYQF4gznvaSS_8_bQ?e=cov7hG