Groovy- Difference between 2 month - groovy

I wanted to write simple groovy script which will give the different of 2 months (note: its not date).
For Example
int startMonth=1 //for Jan
int endMonth=3 //for March
the response should be 2 which is straightforward (Jan > Feb > March)
But in case :
int startMonth=11 //for Nov
int endMonth=1 //for Jan
also, then the response should be 2 i.e. the difference of month (Nov > Dec > Jan)
Can you please let me know if there is any function or any easy workaround to implement this? I am using it in Oracle VBCS Groovy script.

This is less of a groovy question and more of a logic question. One way to do this would be:
int distanceInMonths(int a, int b) {
def min = Math.min(a,b)
def max = Math.max(a,b)
Math.min(max - min, 12 + min - max)
}
assert distanceInMonths(1, 3) == 2
assert distanceInMonths(11, 1) == 2
assert distanceInMonths(12, 1) == 1
assert distanceInMonths(12, 12) == 0
assert distanceInMonths(1, 1) == 0
assert distanceInMonths(1, 12) == 1
assert distanceInMonths(12, 6) == 6
where all the assertions pass.

Related

Reverse Integer python

I am trying to solve the Leetcode "Reverse Integer" challenge in python.
I took look at the solution they supplied.
Their answer was written in Java.
I do not know why they use the following test-condition:
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
I wrote my python code without that same test condition.
It failed when I tested a negative number.
class Solution:
def reverse(self, x: int) -> int:
rev = 0
while( x != 0 ):
pop = x % 10
x //= 10
rev = rev * 10 +pop
print(rev)
return rev
I do not understand why that particular test-condition exists in their code.
The goal is to reverse the order of digits in an integer.
Some examples are shown below:
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}
Branch conditions are sometimes easier to understand when they are drawn as tree-diagrams instead of one line formulas.
Also, we can write the tree like this:
├── OR
│ ├── (rev > Integer.MAX_VALUE/10)
│ └── AND
│ ├── rev == Integer.MAX_VALUE / 10
│ └── pop > 7
Imagine that rev is a container, like a cookie-jar, or a carboard box.
There is a maximum number of cookies which can be crammed into the cookie jar.
When rev == Integer.MAX_VALUE it means that the cookie jar is full.
The condition rev == Integer.MAX_VALUE/ 10 is represent the idea that the cookie-jar can only fit one more cookie.
Instead of stuffing cookies into cookie jars, we are stuffing digits (such as 5) into an integer.
The integer is the container.
Note that when you append zero to an integer in base 10, it is the same as multiplying by 10. For example, 25 becomes 250
Suppose that the largest integer allowed is 2,147,483,647
Note that 214,748,364 is equal to 2,147,483,647 / 10
When you divide by 10, the decimal part of the number is discarded.
When rev is 214,748,364, then you can append any integer the right-most end, as long as that digit is less than or equal to 7.
Old Element
New Element
New Container
Status
214748364
0
2147483640
VALID
214748364
1
2147483641
VALID
214748364
2
2147483642
VALID
214748364
3
2147483643
VALID
214748364
4
2147483644
VALID
214748364
5
2147483645
VALID
214748364
6
2147483646
VALID
214748364
7
2147483647
VALID
214748364
8
2147483648
TOO BIG
214748364
9
2147483649
TOO BIG
The "status" column in the table above
In their code, when they wrote (pop > 7) it probably should have been (pop > Integer.MAX_VALUE % 10)
Suppose that the largest integer allowed is 2,147,483,647
Then, 2,147,483,647 % 10 is equal to 7.
There are many, many different ways to reverse the digits of a number.
One solution, in python, is shown below:
x = int(reversed(str(x)))

Coin Chane - Dynamic Programming - How read all solutions from the DP table

I have seen different solutions to the same problem, but none of them seem to use the approach I used. So here I'm trying to solve the classical coin-change problem in a bottom up dynamic programming approach using a DP table.
int[][] dp = new int[nums.length+1][target+1];
for (int i = 0; i <= nums.length; ++i)
dp[i][0] = 1;
for (int i = 1; i < dp.length; ++i) {
for (int j = 1; j < dp[i].length; ++j) {
if (nums[i-1] <= j)
dp[i][j] = dp[i-1][j] + dp[i][j-nums[i-1]];
else
dp[i][j] = dp[i-1][j];
}
}
The above code generates the table. For fun if I have: {2,3,5} coins, and want to exchange 8, the table would look like:
1 0 0 0 0 0 0 0 0
1 0 1 0 1 0 1 0 1
1 0 1 1 1 1 2 1 2
1 0 1 1 1 2 2 2 3
For the above the following method seem to be working well:
current <- 4
while (current > 0) do
i <- current
j <- 8
while (j > 0) do
if (dp[i][j] != dp[i-1][j]) then
nums[i-1] is part of the current solution
j <- j-1
else
i <- i-1
end
end
current <- current-1
end
Walking through for the above example, we get the following solutions:
1) [5,3]
2) [3,3,2]
3) [2,2,2,2]
Which is great! At least I thought, until I tried: {1,2} with a T=4. For this the table looks like:
1 0 0 0 0
1 1 1 1 1
1 1 2 2 3
With the above algorithm to print all solutions, I only get:
[2,2]
[1,1,1,1]
Which means I won't recover [2,1,1]. So this question is not about the generic how to print the solutions for different approaches to this problem, but how can I read the above DP table to find all solutions.
Well I have one solution but sure... I can see why the other similar answers are using different approaches for this problem. So the algorithm to generate all the possible answers from the above table looks like:
private List<List<Integer>> readSolutions(int[] nums, int[][] dp, int currentRow, int currentColumn, List<Integer> partialSolution) {
if (currentRow == 0) {
return new ArrayList<>();
}
if (currentColumn == 0) {
return new ArrayList<List<Integer>>(Collections.singleton(partialSolution));
}
List<List<Integer>> solutions = new ArrayList<>();
if (dp[currentRow][currentColumn] != dp[currentRow-1][currentColumn]) {
List<Integer> newSolution = new ArrayList<>(partialSolution);
newSolution.add(nums[currentRow-1]);
solutions.addAll(readSolutions(nums, dp, currentRow, currentColumn-nums[currentRow-1], newSolution));
solutions.addAll(readSolutions(nums, dp, currentRow-1, currentColumn, partialSolution));
return solutions;
}
return readSolutions(nums, dp, currentRow-1, currentColumn, partialSolution);
}
The logic on the other hand is simple. Take the above table for example:
0 1 2 3 4
0 1 0 0 0 0
1 1 1 1 1 1
2 1 1 2 2 3
To get a single solution we start from the bottom right corner. If the value does match with the value directly above us, we move up. If it doesn't we move left by the amount corresponding to the row we're in. To generate all answers on on the other hand from the above table...
we're at some position (i,j)
if the value at (i-1,j) is the same as (i,j) we make a recursive call to (i-1,j)
if the values do not match, we have 2 choices...
we can use the number corresponding to the current row, and recurse into (i,j-n)
we can skip the number and check if we can create (i,j) instead by using a recursive call to (i-1,j) instead.
if we reach the first row, we return an empty list
if we reach the first column, we return what we have already found, which will have the sum of target.
Looks awful right, but works as expected.

How to convert 24 hour format to 12 hour format in groovy [duplicate]

This question already has answers here:
How to convert 24 hr format time in to 12 hr Format?
(16 answers)
Closed 3 years ago.
I'm new to groovy and i want to convert 24 hour format to 12 hour format. What is the code to be used for it? Is there any built-in methods?
I just want groovy code not java one
Kevin's answer is correct, and should get the tick... I only post this as it's slightly shorter
import java.time.*
import static java.time.format.DateTimeFormatter.ofPattern
String time = '13:23:45'
String result = LocalTime.parse(time).format(ofPattern('h:mm:ss a'))
println result
I thought this question is somewhat similar to the How to convert 24 hr format time in to 12 hr Format?. It just that Java and Groovy share a lot of similarities. To point that out, I took Cloud's answer from the mentioned question and converted that to Groovy.
import java.time.LocalTime
import java.time.format.DateTimeFormatter
final String time = "21:49"
String result = LocalTime.parse(time, DateTimeFormatter.ofPattern("HH:mm")).format(DateTimeFormatter.ofPattern("hh:mm a"));
println(result)
If you want to build your own time function you can try to customize the code below.
final String time = "21:49"
final String _24to12( final String input ){
if ( input.indexOf(":") == -1 )
throw ("")
final String []temp = input.split(":")
if ( temp.size() != 2 )
throw ("") // Add your throw code
// This does not support time string with seconds
int h = temp[0] as int // if h or m is not a number then exception
int m = temp[1] as int // java.lang.NumberFormatException will be raised
// that can be cached or just terminate the program
String dn
if ( h < 0 || h > 23 )
throw("") // add your own throw code
// hour can't be less than 0 or larger than 24
if ( m < 0 || m > 59 )
throw("") // add your own throw code
// minutes can't be less than 0 or larger than 60
if ( h == 0 ){
h = 12
dn = "AM"
} else if ( h == 12 ) {
dn = "PM"
} else if ( h > 12 ) {
h = h - 12
dn = "PM"
} else {
dn = "AM"
}
return h.toString() + ":" + m.toString() + " " + dn.toString()
}
println(_24to12(time))

Is simulating race conditions with gdb/lldb feasible?

I'm wondering if it would be feasible to automatically test for race conditions using a debugger.
For example, imaging you want to test a multi-threaded queue. Amongst others you would want to test that you can concurrently call enqueue() and dequeue().
A simple unit-test could be able to start two threads, each calling enqueue() and dequeue() respectively in a loop and checking the results:
// thread A
for( int i=0; i<count; i+=1 ) {
enqueue( queue, i );
}
// thread B
for( int i=0; i<count; i+=1 ) {
ASSERT( i == dequeue( queue ) );
}
Now, a clever test-driver, running the unit-test in gdb or lldb, should be able to wait for breakpoints set inside both loops and then use the debuggers si (step instruction) command to simulate all possible interleavings of the two threads.
My question is not if this is technically possible (it is). What I want to know is this:
Assuming the enqueue() function has 10 instructions and the dequeue() function has 20 - how many different interleavings does the test have to try?
Let's see...
If we only have 2 instructions in each: a,b and A,B:
a,b,A,B
a,A,b,B
a,A,B,b
A,a,b,B
A,a,B,b
A,B,a,b
That's 6.
For a, b, C and A,B,C:
a,b,c,A,B,C
a,b,A,c,B,C
a,b,A,B,c,C
a,b,A,B,C,c
a,A,b,c,B,C
a,A,b,B,c,C
a,A,B,b,c,C
a,A,b,B,C,c
a,A,B,b,C,c
a,A,B,C,b,c
A,a,b,c,B,C
A,a,b,B,c,C
A,a,B,b,c,C
A,B,a,b,c,C
A,a,b,B,C,c
A,a,B,b,C,c
A,B,a,b,C,c
A,a,B,C,b,c
A,B,a,C,b,c
A,B,C,a,b,c
That's 20, unless I'm missing something.
If we generalize it to N instructions (say, N is 26) in each and start with a...zA...Z, then there will be 27 possible positions for z (from before A to after Z), at most 27 positions for y, at most 28 for x, at most 29 for w, etc. This suggest a factorial at worst. In reality, however, it's less than that, but I'm being a bit lazy, so I'm going to use the output from a simple program calculating the number of possible "interleavings" instead of deriving the exact formula:
1 & 1 -> 2
2 & 2 -> 6
3 & 3 -> 20
4 & 4 -> 70
5 & 5 -> 252
6 & 6 -> 924
7 & 7 -> 3432
8 & 8 -> 12870
9 & 9 -> 48620
10 & 10 -> 184756
11 & 11 -> 705432
12 & 12 -> 2704156
13 & 13 -> 10400600
14 & 14 -> 40116600
15 & 15 -> 155117520
16 & 16 -> 601080390
So, with these results you may conclude that while the idea is correct, it's going to take an unreasonable amount of time to use it for code validation.
Also, you should remember that you need to take into account not only the order of instruction execution, but also the state of the queue. That's going to increase the number of iterations.
Here's the program (in C):
#include <stdio.h>
unsigned long long interleavings(unsigned remaining1, unsigned remaining2)
{
switch (!!remaining1 * 2 + !!remaining2)
{
default: // remaining1 == 0 && remaining2 == 0
return 0;
case 1: // remaining1 == 0 && remaining2 != 0
case 2: // remaining1 != 0 && remaining2 == 0
return 1;
case 3: // remaining1 != 0 && remaining2 != 0
return interleavings(remaining1 - 1, remaining2) +
interleavings(remaining1, remaining2 - 1);
}
}
int main(void)
{
unsigned i;
for (i = 0; i <= 16; i++)
printf("%3u items can interleave with %3u items %llu times\n",
i, i, interleavings(i, i));
return 0;
}
BTW, you could also save an order of magnitude (or two) of the overhead due to interfacing with the debugger and due to the various context switches, if you simulate pseudo-code instead. See this answer to a somewhat related question for a sample implementation. This may also give you a more fine grained control over switching between the threads than direct execution.

Finding the number of days in a month

I am making a program to display the no. of days in the month provided by user. I am making this program at Data Flow level. As I am new to verilog, I don't know if we can use if/else conditions or case statement in data flow level. because using if/else statement will make this program piece of cake. If not how can I implement the following idea in data flow level.
if(month==4 || month==6 || month==9|| month==11)
days=30;
else
if(month==2 && leapyear==1)
days=29;
Here is my verilog incomplete code:
module LeapYear(year,month,leapOrNot,Days);
input year,month;
output leapOrNot,Days;
//if (year % 400 == 0) || ( ( year % 100 != 0) && (year % 4 == 0 ))
leapOrNot=((year&400)===0) && ((year % 100)!==0 || (year & 4)===0);
Days=((month & 4)===4 ||(month & 6)===6 ||(month & 9)===9 ||(month & 11)===11 )
You cannot use if/else in a continuous assignment, but you can use the conditional operator, which is functionally equivalent.
Try this:
assign Days = (month == 4 || month == 6 || month == 9 || month == 11) ? 30 :
(month == 2 && leapyear == 1) ? 29;
That will produce what you put in your question. But's its not the correct answer as you are missing the conditions where Days is equal to 28 or 31.
EDIT:
Here's how to combine all the conditions into a single assign statement using the conditional operator.v
assign Days = (month == 4 || month == 6 || month == 9 || month == 11) ? 30 :
(month == 2 && leapyear == 1) ? 29 :
(month == 2 && leapyear == 0) ? 28 :
31;

Resources