Showing posts with label problem solving. Show all posts
Showing posts with label problem solving. Show all posts

Tuesday, April 23, 2019

Java Loop


  1. import jaa.util.Scanner;

  2. public class LoopAlgorithm {
  3.     public static void main(String[] args) {
  4.         Scanner in = new Scanner(System.in);
  5.         int t = in.nextInt();
  6.         for (int i = 0; i < t; i++) {
  7.             int a = in.nextInt();
  8.             int b = in.nextInt();
  9.             int n = in.nextInt();
  10.             int result = 0;
  11.             for (int j = 0; j < n; j++) {
  12.                 if (j == 0) {
  13.                     result = (result +a + (int) (Math.pow(2, j) * b));
  14.                 } else {
  15.                     result = (int) Math.pow(2, j) * b;
  16.                     System.out.println(result+" ");
  17.                 }
  18.             }
  19.             System.out.print("");
  20.         }
  21.         in.close();
  22.     }
  23. }








Saturday, July 21, 2018

What do you know about CyclicBarrier in java?

Problem statement: Write a cab transport service where passengers will come one by one and join the queue but they can't board the cab or cab won't move until there are 3 passengers waiting in the queue.
  1. CyclicBarrier is one of the Java Concurrency Utility.
  2. It was introduced in java 5
  3. It falls under java.util.concurrency package
  4. Using this we can synchronised the threads which are processing through some algorithm
  5.  Using this we can make threads wait at a point of code until specific number of threads have reached that point of code.Threads will be ordered to wait on call of await() method
  6. CyclicBarrier can be instantiated as: CyclicBarrier obj = new CyclicBarrier(n) where n is an interger and also that specific number.
[1]:

import java.util.concurrent.CyclicBarrier;

public class CabBooking {
    public static void main(String args[]) throws InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        Thread t1 = new Thread(new CabService(cyclicBarrier));
        t1.setName("Passenger-1");
        t1.start();
        Thread.sleep(5000);

        Thread t2 = new Thread(new CabService(cyclicBarrier));
        t2.setName("Passenger=-2");
        t2.start();
        Thread.sleep(5000);

        Thread t3 = new Thread(new CabService(cyclicBarrier));
        t3.setName("Passenger-3");
        t3.start();
        Thread.sleep(5000);
    }
}
[2]:
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CabService implements Runnable {
    CyclicBarrier cyclicBarrier;
    public CabService(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }
    @Override
    public void run() {
        try {
            System.out.println("++++++ " + Thread.currentThread().getName() + " has arrived");
            try {
                cyclicBarrier.await();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println("****** " + Thread.currentThread().getName() + " is going to board the cab");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Output:
++++++ Passenger-1 has arrived
++++++ Passenger=-2 has arrived
++++++ Passenger-3 has arrived
****** Passenger-3 is going to board the cab
****** Passenger-1 is going to board the cab
****** Passenger=-2 is going to board the cab
ref: click for oracle doc

What do you know about CountDownLatch in java?

  1. CountDownLatch is one of the Java Concurrency Utility.
  2. It was introduced in java 5
  3. It falls under java.util.concurrency package
  4. It is kind of synchronizer
  5. It makes 1 thread to wait until other threads have finished their job.
Important methods of CountDownLatch class
  1. await(): void
  2. countDown(): void
  3. getCount(): long
Problem statementI need to get an online food order having various food items i.e. Pizza, Pasta, Coke. Start tracking the processing of the food in another threads. Once all the food items are prepared, I need to notify the customer that food is prepared.

[1]

import java.util.concurrent.CountDownLatch;
public class Processor {
    public static void main(String args[]) {
     CountDownLatch countDownLatch = new CountDownLatch(args.length);
     Thread foodProcessorThread = new Thread(new FoodProcessor(countDownLatch, args));
        foodProcessorThread.start();
        System.out.println("Order is received and is being processed");
        try {
            countDownLatch.await();
            System.out.println("Order is processed successfully and is ready to get dispatched");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
[2]
import java.util.concurrent.CountDownLatch;
public class FoodProcessor implements Runnable {
    private final CountDownLatch latch;
    private final String items[];
    public FoodProcessor(CountDownLatch latch, String items[]) {
        this.latch = latch;
        this.items = items;
    }
    @Override
    public void run() {
        for (int i = 0; i < items.length; i++) {
            try {
                System.out.println("Before processing the item, value of CountDownLatch: " + latch.getCount());
                Thread.sleep(10000);
                System.out.println("items " + items[i] + " is prepared");
                latch.countDown();
                System.out.println("After processing the item, value of CountDownLatch: " + latch.getCount());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
Output:
Order is received and is being processed
Before processing the item, value of CountDownLatch: 3
items Pizza is prepared
After processing the item, value of CountDownLatch: 2
Before processing the item, value of CountDownLatch: 2
items Pasta is prepared
After processing the item, value of CountDownLatch: 1
Before processing the item, value of CountDownLatch: 1
items Coke is prepared
After processing the item, value of CountDownLatch: 0

Order is processed successfully and is ready to get dispatched
ref: click for oracle CountDownLatch doc

    Monday, July 16, 2018

    Problem statement:
    There is a colony of 8 cells arranged in a straight line where each day every cell competes with its adjacent cells(neighbour). Each day, for each cell, if its neighbours are both active or both inactive, the cell becomes inactive the next day,. otherwise it becomes active the next day.

    Assumptions: The two cells on the ends have single adjacent cell, so the other adjacent cell can be assumsed to be always inactive. Even after updating the cell state. consider its pervious state for updating the state of other cells. Update the cell informationof allcells simultaneously.

    Write a fuction cellCompete which takes takes one 8 element array of integers cells representing the current state of 8 cells and one integer days representing te number of days to simulate. An integer value of 1 represents an active cell and value of 0 represents an inactive cell.

    TESTCASES 1:
    INPUT:
    [1,0,0,0,0,1,0,0],1
    EXPECTED RETURN VALUE:
    [0,1,0,0,1,0,1,0]

    TESTCASE 2:
    INPUT:
    [1,1,1,0,1,1,1,1,],2
    EXPECTED RETURN VALUE:
    [0,0,0,0,0,1,1,0]


    public class Colony {

        public static int[] cellCompete(int[] cells, int days) {

            int len = cells.length;
            int[] newCells = new int[cells.length];
            for (int k = 0; k < days; k++) {
                for (int i = 0; i < cells.length; i++) {
                    int cell = cells[i];
                    int nextCell;
                    int prevCell;
                    int activenumber;
                    if (i == 0) {
                        // edge cases
                        nextCell = cells[1];
                        prevCell = 0;
                    } else if (i == cells.length - 1) {
                        // edge case
                        prevCell = cells[cells.length - 2];
                        nextCell = 0;
                    } else {
                        nextCell = cells[i + 1];
                        prevCell = cells[i - 1];
                    }
                    if (nextCell == prevCell) {
                        // set it to inactive
                        activenumber = 0;
                    } else {
                        //set it to active
                        activenumber = 1;
                    }
                    newCells[i] = activenumber;
                }
                for (int i = 0; i < 8; i++) {
                    cells[i] = newCells[i];
                }
            }
            return newCells;
        }
        public static void main(String[] args) {
            int[] array = {1, 1, 1, 0, 1, 1, 1, 1};
            int days = 2;
            array = cellCompete(array, days);
            for (int i = 0; i < array.length; i++) {
                System.out.print(array[i]);
            }
        }
    }

    How do you write an algorithm for the multiplication of two matrix [2D array]?

    Problem statement:
    Given two matrices, the task is to multiply them. Matrices can either be square or rectangular.
    Example:
    Input: int m1[][] = {{2, 3, 4}, {5, 6, 7}}; // 2 X 3 matrix
    int m2[][] = {{1, 2}, {3, 4}, {5, 6}}; // 3 X 2 matrix
    Output: {{31, 40},{58,76}}
    1. public class MatrixMultiplication {
    2.     public static void main(String args[]) {
    3.         int m1[][] = {{2, 3, 4}, {5, 6, 7}};    // 2 X 3 matrix
    4.         int m2[][] = {{1, 2}, {3, 4}, {5, 6}};  // 3 X 2 matrix
    5.         int res[][] = new int[2][2];    // resultant matrix of 2 X 2
    6.         for (int i = 0; i < 2; i++) {   // i represent row
    7.             for (int j = 0; j < 2; j++) {   // j represent column
    8.                 res[i][j] = 0;  // assume res[0][0] = 0
    9.                 for (int k = 0; k < 3; k++) {
    10.                     // k represent first matrix i.e. m1 -> number of column for                        // counter sum
    11.                     res[i][j] = res[i][j] + m1[i][k] * m2[k][j];
    12.                 }
    13.             }
    14.         }
    15.         // printing the resultant matrix
    16.         for (int i = 0; i < 2; i++) {
    17.             for (int j = 0; j < 2; j++) {
    18.                 System.out.print(res[i][j] + " ");
    19.             }
    20.             System.out.println();
    21.         }
    22.     }
    23. }
    Method-II:
    1. public class MatrixMultiplication2D {
    2.     public static void main(String args[]) {
    3.         int m1[][] = {{2, 3, 4}, {5, 6, 7}};    // 2 X 3 matrix
    4.         int m2[][] = {{1, 2}, {3, 4}, {5, 6}};  // 3 X 2 matrix
    5.         int sum = 0;    // initial sum value is 0
    6.         int res[][] = new int[2][2];    // resultant matrix of 2 X 2
    7.         for (int i = 0; i < 2; i++) {   // i represent row
    8.             for (int j = 0; j < 2; j++) {   // j represent column
    9.                 res[i][j] = 0;  // assume res[0][0] = 0
    10.                 for (int k = 0; k < 3; k++) {
    11.                     // k represent first matrix i.e. m1 -> number of column for                        // counter sum
    12.                     sum = sum + m1[i][k] * m2[k][j];
    13.                 }
    14.                 res[i][j] = sum;    //  assigned sum value to resultant matrix
    15.                 sum = 0;    // reset to 0 for next iteration
    16.             }
    17.         }
    18.         // printing the resultant matrix
    19.         for (int i = 0; i < 2; i++) {
    20.             for (int j = 0; j < 2; j++) {
    21.                 System.out.print(res[i][j] + " ");
    22.             }
    23.             System.out.println();
    24.         }
    25.     }
    26. }
    Output:
    31 40
    58 76

    Saturday, May 5, 2018

    Non-Technical Skills

    Problem statement: what do you mean by non-technical skills ?
    • Major components of non-technical skills are
    1. Communication
    2. Analytical skills (realistic in nature that involve your ability to visualize/perceive information)
    3. Problem solving
    • Problem solving:
    1. IDENTIFY the problem
    2. DEFINE main elements of the problem
    3. EXAMINE possible solutions
    4. ACT on resolving the problem
    5. LOOK for lesson to learn
    for more details click 1. or 2.

    Blueprint for self-improvement

    To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...