Saturday, November 30, 2024

CodingExercise: Rotate List

Medium

Topics

Companies

Given the head of a linked list, rotate the list to the right by k places.

Example 1:

Input: head = [1,2,3,4,5], k = 2

Output: [4,5,1,2,3]

Example 2:

Input: head = [0,1,2], k = 4

Output: [2,0,1]

Constraints:

The number of nodes in the list is in the range [0, 500].

-100 <= Node.val <= 100

0 <= k <= 2 * 109

/**

 * Definition for singly-linked list.

 * public class ListNode {

 *     int val;

 *     ListNode next;

 *     ListNode() {}

 *     ListNode(int val) { this.val = val; }

 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }

 * }

 */

class Solution {

    public ListNode rotateRight(ListNode head, int k) {

        if (head == null || k == 0) return head;

        Listhead current = head;

        int n = 0;

        while (current){

             n++;

             current = current.next;

        }

        if (k > n) { k = k % n;}

        int offset = n - k;

        current = head;

        if (offset > 0) {

            while (offset > 1) {

                current = current.next;

                offset--;

            }

            ListNode remaining = current.next;

            current.next = null;

            ListHead end = remaning;

            while (end && end.next) {

                end = end.next;

            }

            end.next = head;

            return remaining;

        }

        return head;

    }

}

 


Friday, November 29, 2024

 Mesh networking and UAV (Unmanned Aerial Vehicle) swarm flight communication share several commonalities, particularly in how they handle connectivity and data transfer:

Dynamic Topology: Both systems often operate in environments where the network topology can change dynamically. In mesh networks, nodes can join or leave the network, and in UAV swarms, drones can move in and out of range.

Self-Healing: Mesh networks are designed to automatically reroute data if a node fails or a connection is lost. Similarly, UAV swarms use mesh networking to maintain communication even if some drones drop out or move out of range.

Redundancy: Both systems use redundancy to ensure reliable communication. In mesh networks, multiple paths can be used to send data, while in UAV swarms, multiple drones can relay information to ensure it reaches its destination.

Decentralization: Mesh networks are decentralized, meaning there is no single point of failure. UAV swarms also benefit from decentralized communication, allowing them to operate independently and collaboratively without relying on a central control point.

Scalability: Both mesh networks and UAV swarms can scale to accommodate more nodes or drones, respectively, without significant degradation in performance.

These commonalities make mesh networking an ideal solution for UAV swarm communication, ensuring robust and reliable connectivity even in challenging environments.

Similarly, distributed hash tables, cachepoints arranged in a ring and consensus algorithms also play a part in the communications between drones.

Cachepoints are used with consistent hashing. They are arranged along the circle depicting the key range and cache objects corresponding to the range. Virtual nodes can join and leave the network without impacting the operation of the ring.

Data is partitioned and replicated using consistent hashing to achieve scale and availability. Consistency is facilitated by object versioning. Replicas are maintained during updates based on a quorum like technique.

In a distributed environment, the best way to detect failures and determine memberships is with the help of gossip protocol. When an existing node leaves the network, it may not respond to the gossip protocol so the neighbors become aware. The neighbors update the membership changes and copy data asynchronously.

Some systems utilize a state machine replication such as Paxos that combines transaction logging for consensus with write-ahead logging for data recovery. If the state machines are replicated, they are fully Byzantine tolerant.


Thursday, November 28, 2024

 This is a summary of the book titled “The Circular Business Revolution – a practical framework for sustainable business models” written by Manuel Braun and Julia Binder and published by FT Publishing in 2024. The authors encourage business to shift from the linear “take-make-waste” model of business to a sustainable circular, “net positive” model that aims at both business success and environmental and social good. They assert that the shift is both possible and necessary. Sometimes the shift might require redesigning the business model. That can be done by focusing on resource use, ecosystems, uses of waste, and product life for sustainability and by focusing on the value chain and operating environment for the business’ future. It’s also important to set the goals high in how the company can create a net positive impact. Both business and environmental aims must align with the company’s vision. Execution can be complex, but it focuses on integrating sustainability

The shift from a linear economy to a circular one is both possible and necessary. The current linear model, which starts with the extraction of natural resources and ends with waste, is inefficient and has negative environmental effects. A circular economy, which focuses on value creation through continuous use and reuse, is becoming more prevalent. This transformation is inevitable and can be achieved through three horizons: near, far, and mid-term. To transition, businesses should assess signs for change, create a vision for a circular, regenerative future, investigate business models that achieve good business outcomes and low environmental impact, and strengthen their readiness for change. The circular economy aims at "eco-effectiveness" and focuses on meeting human needs rather than just profit. Participants in a circular economy use nine strategies, called "R-strategies," to achieve circularity and reduce pressure on resources.

Circular business models are a type of business strategy that focuses on resource use, ecosystems, waste, product life, or servitization. They fall into five categories: optimizing resource use, restoring ecosystems, capturing waste value, extending product life, and bundling services and products. These models aim to make existing operations more environmentally sustainable, reducing waste and pollution, and promoting sustainable practices. They also focus on restoring ecosystems, such as the cultivation of the illipe nut in Borneo, which combats deforestation and supports local communities. They also recognize the economic value of waste materials, such as by-products, and create value by recovering them. They also focus on providing integrated solutions tailored to specific needs, often through sharing and pooling platforms.

To understand your business's future, consider your value chain and operating environment from two perspectives: inside out and outside in. The inside-out view helps identify inefficiencies in the linear system, such as overuse of resources, negative externalities, waste generation, underutilized capacities, and product losses. The outside-in view considers the business's operating environment, which will face disruption due to increasing resources scarcity, power dynamics, and other drivers. Maintaining your "license to operate" and "license to innovate" is crucial for gaining a competitive advantage.

To transition from linear to circular, start with a clear vision for achieving business success and environmental goals. Develop this vision from both an environmental and business perspective, building on existing values and mission. Backcasting helps determine what needs to be done to make the vision a reality. Companies like FREITAG are promoting circularity by focusing on intelligent design and employee development.

A successful strategy for implementing a circular business model should address both business and environmental aims and align with the organization's vision. This involves a pathway to implementing a chosen business model and direction for the organization. The transition to servitization often faces the balance sheet dilemma, but it requires careful cash-flow management. Active stakeholder involvement is crucial, and the business model pathway should align with the organization's future vision. The implementation of a circular business model has six major dimensions: customer-centricity, design, ecosystem, data and technology, organizational structures and processes, and tools, systems, and KPIs. Leaders must communicate authentically, avoid greenwashing and greenhushing, and maintain transparency to demonstrate commitment to the transformation.


Wednesday, November 27, 2024

 

This is a summary of the book titled “Strong Supply Chains Through Resilient Operations” written by Suketu Gandhi, Marc Lakner, Sherri He, Tiffany Hickerson, and Michael F. Strohmer and published by Wiley in 2023. The authors make a case against the cost trimming  and lean-and-mean making of supply chains because the world is becoming more volatile, with geopolitical tensions, social unrest, and extreme weather. Instead, they ask that the supply chains be more resilient and flexible and propose a comprehensive program to do so. Case in point is the early 2020s when COVID struck, and operations needed to tackle a range of threats. By encouraging suppliers to be partners, positioning customer value as the key driver, cultivating a resilient workforce, revolutionizing with innovative technology, and a sustainability strategy, businesses can make their supply chain resilient to anything the world throws at them.

Supply-chain resilience is crucial in today's volatile, uncertain, complex, and ambiguous (VUCA) environment. Companies must prepare their operations for potential threats by restructuring their brittle supply chains to bend instead of breaking. In today's VUCA environment, businesses must adapt their strategies to new circumstances. To build resilient operations, businesses should prioritize a holistic view of their operations, including product planning, consumer research, manufacturing, and logistics.

To establish a relationship with suppliers, work together to establish a mutually beneficial relationship. Share goals and discuss how their work aligns with those goals. Encourage suppliers to cultivate similar relationships to build a network capable of providing early warnings about supply interruptions.

Reduce dependence on a single source and seek quality alternative suppliers as backups. Maximize value from suppliers and ensure everyone in the company understands the entire value chain.

Fast-fashion companies like Zara and H&M disrupted the traditional fashion industry by focusing on customer value and releasing new products continually. This approach allows them to adapt to changing customer attitudes and tackles issues like cost, sustainability, and shifting supply-demand profiles. To cultivate resilience, simplify your product portfolio, gather feedback, and use data analytics to understand customer preferences. The growth of e-commerce offers new opportunities for delivering products, but companies should be aware that customers may not be concerned about quick delivery for every product.

During the COVID pandemic, companies experimented with multichannel operations, such as online sales and home delivery. To set up an omnichannel operation, gather and analyze relevant data, consider last-mile options, and consider last-mile options like delivery or customer pickups.

Cultivate a resilient workforce by valuing diversity, promoting open communication, and offering a vision that aligns with personal values. This approach helps teams work harder, thrive in a fast-changing environment, and contribute to a positive culture.

Companies today recognize the importance of a diverse workforce for producing original ideas. However, this requires more than just hiring people from diverse backgrounds. Companies should focus on building resilience through "economies of skill" by implementing strategies such as outcome-based work, leveraging global expertise, promoting perennial learning, planning for future skills, and revolutionizing the supply chain with innovative technology. This includes using the Internet of Things, advanced robotics, wearable tech, and 3D printers to monitor operations and predict problems. A culture of continual learning is essential for employees to handle crises, adapt to customer preferences, and make the most of innovations. A sustainability strategy is also crucial for resilience, as stakeholders are increasingly aware of environmental, social, and governance (ESG) issues. Customers are willing to pay more for sustainable products, and employees worry about the environmental consequences of unsustainable practices. Sustainability is now a strategic advantage, as it can be framed as a way of minimizing waste.

Resilience is crucial in any future scenario, as it allows businesses to withstand risks and maintain a stable state. Key elements of resilience include transparency, data analysis, customer value, a proactive attitude, and the right people. These elements help businesses understand their operations, make informed decisions, and adapt to changes in the market. By empowering their employees with purpose, businesses can ensure a smooth transition and thrive in the future.

#Codingexercise: CodingExercise-11-27-2024.docx

 

Tuesday, November 26, 2024

 

This is a summary of the book titled “Math-ish: Finding creativity, diversity and meaning in mathematics” written by Dr. Jo Boaler and published by Harper One in 2024. The author has consistently sought to fight the widespread and often incorrect way of teaching mathematics where higher levels are about filtering out students and often one that demands students to give exacting solutions and forces students into a rigor that provides no benefits. She even cites this to be the reason that contributes to the fear and hate of the subject. Instead, she advocates playful, creative thinking, ideas and collaboration with a  diverse set of people, so that the subject is not just mathematics but math-ish.

The narrow approach must give way to a more inclusive approach. The latter is rooted in “Metacognition” practices. Learning will always involve mistakes and embracing the struggle is critical to teaching. Math-ish education brings diverse approaches to numbers, shapes, and data, which also leads to a more visual experience. This results in a shift in thinking about rules to a thinking that is broader. Changing the status quo could address current inequalities and set a precedent for other subjects.

Educators must replace the narrow approach to mathematics with a more flexible and diverse approach. The narrow mathematics approach, taught for over 100 years, has spoiled millions of students and negatively impacted society. It doesn't involve creativity or the free play of ideas, and students are constantly scrutinized and evaluated based on tests. This has led to 60% of university students dropping their science majors after taking introductory math courses.

An alternative to narrow mathematics is "math-ish," which de-emphasizes contextless, numeric problem-solving in favor of creative, interesting ways people use math in real-world settings. Metacognition practices, formulated by Stanford University psychology professor John Flavell, form the foundation of better math education. These practices boost problem-solving, enable mathematical diversity, and enhance work performance.

To approach and solve a mathematical problem, educators should reflect on the problem, create a visual representation, and ask why a particular procedure works. Cultivating a reflective mindset and learning to problem-solve with others in a way that respects their ideas and perspectives is essential for better math education.

Learning math involves making mistakes and embracing the struggle. A growth mindset is better for learners and problem-solvers, as it encourages learning from setbacks and persisting in efforts. Math teachers should encourage students to "struggle" with problems, allowing them to understand the nature of the problem and come to a deeper understanding of the concepts involved. Teachers can present problems that invite diverse approaches, encourage conversation and collaboration, praise students' struggles, and reward their work. Math-ish education involves understanding math as it manifests itself in everyday life in a population of people with diverse identities and backgrounds. Mathematical diversity enhances life and mathematics. K-12 teachers can't cover everything, but three critical areas in mathematics that students need a feeling for to thrive at the university level are arithmetic, data analysis, and linear equations. Students can acquire a feeling for numbers by identifying patterns and drawing patterned shapes, which helps them relate to numbers in a new way.

Understanding data is a critical life skill in today's online world, and children should begin early to learn to avoid deception by data. Students should be introduced to statistics and probability and understand the difference between correlation and causation. In the era of misinformation, people should always ask where data comes from, whether it is being presented, and whether the relationships presented are correlated or causal. Math can be an exciting and interactive visual experience, as it allows for deeper connections and ideas. Visual representations can open the mind to new ideas and approaches, and mental models play a central role in learning. Math is not just a set of rules; it is a way of thinking that requires flexibility and deep thinking. Students who do well in math understand the truths of numbers and can find different solutions to adding them.

Traditional math education is inequitable, with Black and Brown students often left behind. A new model, reflected in the 2023 California Mathematics Framework, aims to promote mathematical expertise, and reduce inequalities by promoting diversity in perspectives and approaches to problems. This model encourages more general discussion of problems and encourages students to engage in different ways to learn and succeed in math.


 

Monday, November 25, 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


Sunday, November 24, 2024

 This is an implementation outline of an image retrieval system built for images captured from a UAV swarm such that the queries from the user can then be used to assign objects as targets for the drones to acquire a better angle in real-time.

Traditionally image retrieval systems either work with images or text for data and query respectively but not both. With multi-modal AI vector search, we can span both giving us better results. Azure provides Multimodal embeddings APIs that enable the vectorization of images and text queries. They convert images to coordinates in a multi-dimensional vector space. Then, incoming text queries can also be converted to vectors, and images can be matched to the text based on semantic closeness. This allows the user to search a set of images using text, without the need to use image tags or other metadata. Semantic closeness often produces better results in search. Vectorize Image and Vectorize Text APIs are available to convert images and text to vectors.

The open-source equivalent for an image retrieval system could involve ViT Image Retrieval project available on GitHub that uses Vision Transformers and Facebook AI Similarity Search for content-based image retrieval. This utilizes the ViT-B/16 model pretrained on ImageNet for robust feature extraction and FAISS indexing. It comes with a user-friendly graphical user interface for feature extraction and image search. Python API is used to index a directory of images and search for similar images, and this can be extended to directly work with an S3 store or Azure storage account.

“Contextual Embeddings” improves retrieval accuracy, cutting failures with re-ranking. It involves both a well-known Retrieval Augmented Generation technique with semantic search using embeddings and lexical search using sparse retrievers like BM25. The entire knowledge base is split into chunks. Both the TF-IDF encodings as well as semantic embeddings are generated. Parallel searches using both lexical and semantic searches are run. The results are then combined and ranked. The most relevant chunks are located, and the response is generated with enhanced context. This enhancement over multimodal embeddings and GraphRAG is inspired by Anthropic and a Microsoft Community blog.

#codingexercise: CodingExercise-11-24-2024.docx