Problem
A left rotation operation on an array shifts each of the array’s elements 1 unit to the left. For example, if 2 left rotations are performed on an array [1,2,3,4,5]
, then the array would become [3,4,5,1,2]
. Note that the lowest index item move to the highest index in a rotation. This is called circular array.
Given an array a of n integers and a number, d perform d left rotations on the array. Return the updated array to be printer as a single line of space-separated integers.
Function Description
Complete the function rotLeft in the editor below.
rotLeft has the following parameter(s):
Returns
Input Format
Constraints
1 <= n <= 105
1 <= d <= n
1 <= a[i] <=106
Solution
package org.span; import java.io.IOException; public class ArrayLeftRotation { static int[] rotLeft(int[] a, int d) { for (int i = 0; i < d; i++) { int t = a[0]; System.arraycopy(a, 1, a, 0, a.length - 1); a[a.length - 1] = t; } return a; } public static void main(String[] args) throws IOException { int d = 4; int[] a = {1, 2, 3, 4, 5}; int[] result = rotLeft(a, d); print(result); } public static void print(int[] a) { for (int i = 0; i < a.length; i++) { if (i > 0) System.out.print(" " + a[i]); else System.out.print(a[i]); } } }]]>
Solution
package org.span; import java.io.IOException; import java.util.Scanner; public class HourGlass { static int hourglassSum(int[][] arr) { int max = -99999, cur; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { cur = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]; if (cur > max) { max = cur; } } } return max; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { /*int[][] arr = { {1, 1, 1, 0, 0, 0}, {0, 1, 0, 0, 0, 0}, {1, 1, 1, 0, 0, 0}, {0, 0, 2, 4, 4, 0}, {0, 0, 0, 2, 0, 0}, {0, 0, 1, 2, 4, 0} };*/ int[][] arr = { {0, -4, -6, 0, -7, -6}, {-1, -2, -6, -8, -3, -1}, {-8, -4, -2, -8, -8, -6}, {-3, -1, -2, -5, -7, -4}, {-3, -5, -3, -6, -6, -6}, {-3, -6, 0, -8, -6, -7}, }; int result = hourglassSum(arr); System.out.println(result); } }]]>
Solution
import java.io.IOException; public class RepeatedString { static long repeatedString(String s, long n) { long noOfOccurence = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == 'a') noOfOccurence++; } long repeat = n / s.length(); noOfOccurence *= repeat; for (int i = 0; i < n % s.length(); i++) { if (s.charAt(i) == 'a') noOfOccurence++; } return noOfOccurence; } public static void main(String[] args) throws IOException { String s = "aba"; long n = 10; long result = repeatedString(s, n); System.out.println(result); } }]]>
Solution
import java.io.IOException; public class JumpingOnClouds { static int jumpingOnClouds(int[] c) { int jumps = 0; for (int i = 0; i < c.length; ) { if (i + 2 < c.length && c[i + 2] == 0) i += 2; else i++; jumps++; } return jumps - 1; } public static void main(String[] args) throws IOException { int[] c = {0, 0, 1, 0, 0, 1, 0}; int result = jumpingOnClouds(c); System.out.println(result); } }]]>
Solution
import java.io.IOException; class Result { public static int countingValleys(int steps, String path) { int valleyCount = 0, prePos, pos = 0; for (int i = 0; i < steps; i++) { prePos = pos; if (path.charAt(i) == 'D') pos--; else pos++; if (pos == 0 & prePos < 0) valleyCount++; } return valleyCount; } } public class CountingValleys { public static void main(String[] args) throws IOException { int steps = 8; String path = "UDDDUDUU"; int result = Result.countingValleys(steps, path); System.out.println(result); } }]]>
Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale.
Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
For example, there are n=7 socks with colors ar = [1,2,1,2,1,3,2] .
There is one pair of color 1 and one of color 2.
There are three odd socks left, one of each color. The number of pairs is 2.
Function Description
Complete the sockMerchant function in the editor below.
It must return an integer representing the number of matching pairs of socks that are available.
sockMerchant has the following parameter(s):
n: the number of socks in the pile
ar: the colors of each sock
Input Format
The first line contains an integer n, the number of socks represented in ar.
The second line contains n space-separated integers describing the colors ar[i] of the socks in the pile.
Constraints
1 <= n <= 100
1 <= ar[i] <= 100 where 0 <= i < n
Output Format
Return the total number of matching pairs of socks that Alex can sell.
Sample Input
9
10 20 20 10 10 30 50 10 20
Sample Output
3
Alex can match three pairs of socks
Solution
import java.util.HashMap; import java.util.Scanner; public class PairOfSocks { static int sockMerchant(int n, int[] ar) { HashMap<Integer, Integer> colorsMap = new HashMap<>(); for (int color : ar) { colorsMap.put(color, (colorsMap.getOrDefault(color, 0)) + 1); } final int[] totalPair = {0}; colorsMap.forEach((key, value) -> totalPair[0] += value / 2); return totalPair[0]; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int[] ar = new int[n]; String[] arItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int arItem = Integer.parseInt(arItems[i]); ar[i] = arItem; } int result = sockMerchant(n, ar); System.out.println(result); scanner.close(); } }
Explanation
We need to find no of pairs for each number. We can add the quantity of each number into a map. Then we can divide the values by 2 and sum up to get the final answer.
]]>I received the book few weeks later and kept it in the book-shelf. I didn’t read it. On this 2021 new year suddenly I got a spark. Why don’t we read this book now and write about those learning as posts in a blog?
The outcome is this blog. The idea is simple. I will read this book and explore all the coding challenges from this book. Whatever I learn, will post it here. So that interested programmers either they are preparing for interviews or learning on their own may benefit.
Thanks.
]]>As there are multiple pages involved in the shopping flow, the data needs to be carried throughout multiple pages. If we handle this task manually it will be tedious task. We will go out of our indented business logic. To implement these kinds of tasks easily Spring provides the web flow framework.
A flow is nothing but a set of tasks to be done in a particular order. In webflow it is an xml file which tells the exactly how this flow should works. If we configure our application flow in spring web flow, the data carrying portion as well as the page navigation issues will be taken care by spring web flow itself. We can concentrate on our business logic rather than spending time on working those mundane tasks.
Spring web flow can be configured only via xml file. Currently it is not feasible to configure via only java.
The first thing to setup a web flow is configuration. A flow configuration involves below major components. Let’s go through them.
Flow executor: Flow executor is responsible to drive the flow. The syntax will be like below.
<flow:flow-executor id="flowExecutor"/>
Flow Registry: Flow registry is responsible to load the flow definitions. For example if all flows under folder WEB-INF/flows needs to be loaded it has to be configured like below.
<flow:flow-registry id="flowRegistry" base-path="/WEB-INF/flows"> <flow:flow-location-pattern value = "**/*-flow.xml"/> </flow:flow-registry>
Here one important thing to note is the url path to the flow will be determined by the path of the flow location. For example if the path of a flow is /WEB-INF/flows/order/order-flow.xml then the id will be order (relative to the base path.) So the flow will be triggered while accessing the url http://{url}/{contextpath}/order
Instead of the pattern the path of the flow file also can be configured. For example to load order-flow.xml flow it can be configured like below.
<flow:flow-registry id="flowRegistry"> <flow:flow-location path = "/WEB-INF/flows/order/order-flow.xml"/> </flow:flow-registry>
If the full path is specified then the filename will become the id of that flow. In the above case it will be order-flow . If id needs to be different from the path it can be specified with id attribute like below.
<flow:flow-location path = "/WEB-INF/flows/order/order-flow.xml" id="custom/path/flow"/>
As per the above code the flow will be triggered when the url {contextPath}/custom/path/ flow is entered.
Flow Handler Mapping : Like DispatcherServlet for controller mapping, there is a class FlowHandlerMapping for URL to flow mapping for web flow.
Flow Handler Adapter : Like Controllers for handling the requests, there is a class FlowHandlerAdapter to handle the flow requests
The next important thing is the flow. A Flow is an xml file which tells the exactly how this flow should works. A flow will have three major components.
State : As per the name it is the state of the flow, which means the flows should be in a state. There are five types of states possible.
<action-state id="saveOrder"> <evaluate expression="pizzaFlowActions.saveOrder(order)"/> <transition to="thankYou"/> </action-state>
<decision-state id="checkDeliveryArea"> <if test="pizzaFlowActions.checkDeliveryArea(customer.zipCode)" then="addCustomer" else="deliveryWarning"/> </decision-state>
<subflow-state id="order" subflow="pizza/order"> <input name="order" value="order"/> <transition on="orderCreated" to="payment"/> </subflow-state>
Transition: To move from one state to another state the transition element will be used.
<global-transitions> <transition on="cancel" to="endState"/> </global-transitions>
Data: To store and pass data through out the flow the data elements will be used. The syntax will be <var name=”customer” class=”org.span.domain.Customer”/>
That is all about the major components of the web flow. Also web flow can be secured as well. To secure a flow it has to be configured like below.
<view-state id="restricted" view="paymentdetails"> <secured attributes="ROLE_ADMIN,ROLE_FINANCE" match="all"/> </view-state>
attributes are comma separated roles. match can be ‘any’ – At least one role required or ‘all’ – All roles required .
In this section we have discussed the concepts of Spring web flow. In the next tutorial we will implement a simple web flow application to understand all the discussed concepts.
]]>SVN Serve Setup
Note 1:
If we directly add directory or file to the working copy it will not be added to the repository when we commit. So either create directory or files directly the use command svn add file/directory name or create using svn add/ svn mkdir.