Posted 1 month ago
Posted 1 month ago

New feature for Map in Java 8

There are several new improvements in Java 8 and one of them is about Map in java.util. 

The forEach method in Map is useful for iterating through Map without using loop. 

For instance the code below iterates over the map elements and prints the key/value pairs:

    Map<String,String> map = new Map<>();
    map.put("key1", "val1");
    map.put("key2", "val2");
    map.put("key3", "val3");    
    for (Map.Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                System.out.println(key+"=>"+value);
        }

The code above can be rewritten as follows using forEach method:

    Map<String,String> map = new Map<>();
    map.put("key1", "val1");
    map.put("key2", "val2");
    map.put("key3", "val3");
    map.forEach((key, value) -> System.out.println(key + "=>" + value));

Posted 4 months ago

Recently I tried to solve one of the simple problems posted on Codility (https://codility.com/train/) - TapeEquilibrium. The problem itself is very simple as mentioned on the website. Some little moments can confuse you. Such moments are important on programming contests and also on interviews. Because figuring out can take a lot of time. 

The problem described as:

A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape.

Any integer P, such that 0 < P < N, splits this tape into two non−empty parts: A[0], A[1], …, A[P − 1] and A[P], A[P + 1], …, A[N − 1].

The difference between the two parts is the value of: |(A[0] + A[1] + … + A[P − 1]) − (A[P] + A[P + 1] + … + A[N − 1])|

In other words, it is the absolute difference between the sum of the first part and the sum of the second part.

For example, consider array A such that:

  A[0] = 3
  A[1] = 1
  A[2] = 2
  A[3] = 4
  A[4] = 3

We can split this tape in four places:

  • P = 1, difference = |3 − 10| = 7 
  • P = 2, difference = |4 − 9| = 5 
  • P = 3, difference = |6 − 7| = 1 
  • P = 4, difference = |10 − 3| = 7 

Write a function:

class Solution { public int solution(int[] A); }

that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved.

For example, given:

  A[0] = 3
  A[1] = 1
  A[2] = 2
  A[3] = 4
  A[4] = 3

the function should return 1, as explained above.

Assume that:

  • N is an integer within the range [2..100,000];
  • each element of array A is an integer within the range [−1,000..1,000].

Complexity:

  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.

Copyright 2009–2014 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

The Idea for solution can be dividing the array into two pieces and then find out the minimal difference. Workflow will be as follow:

The minimal difference is 1 as you see. 

If you google about this task you’ll see a lot of solutions on different blogs and also at github repos with this idea. Unfortunately most of them doesn’t pass all tests. Most of them pay attention to design not for code itself and they don’t care about complexity. 

One of the authors created two methods on Java one for the main body of the solution and another for calculating the sum of elements in an array. The calculation process has a one “for" loop. And if you write a loop in main body and you use this method inside of it the complexity will be O(N^2). And for large inputs it’ll fail. As you see in description of the task it’s written "expected worst-case time complexity is O(N)”. 

Actually the solution I describe is O(N+M). So in the first time. I calculate the sum of elements starting from 2nd item (1st index of array). And on every iteration I check the difference if it’s less than previous minimum then I save it. Most solutions found on internet start from zero index. But the zero index in this idea has no any meaning. Before the first iteration our “left side” will be and right side will be 1+2+4+3.And the first minimum difference will be difference of them. Then we must begin from 1st indexed element (2nd element) till pre-last element. Another common mistake on the solutions is they go till the last element and some test cases fail for them. 

So the full solution will be:

    public int solution(int[] A) {

		long rsum = 0;

		for (int i = 1; i < A.length; i++)
			rsum += A[i];

		long lsum = A[0];
		int min = (int) Math.abs(lsum - rsum);
		for (int i = 1; i < A.length-1; i++) {
			lsum += A[i];
			rsum -= A[i];
			int diff = (int) Math.abs(lsum - rsum);
			if (diff < min)
				min = diff;
		}

		return min;
	}
Posted 1 year ago

MySQL’s FROM_DAYS function in Oracle DB

The FROM_DAYS function in MySQL is opposite of TO_DAYS function. The TO_DAYS returns number of days from the year of 0 (Gregorian calendar). 

If you migrate your tables to Oracle where you keep date values using TO_DAYS function you’ll have little problems, because, Oracle has no built-in FROM_DAYS function as in MySQL. Instead Oracle has more powerful functions for working with dates. 

The below code-snipped will help you to use instead of FROM_DAYS function when migrating data from MySQL to Oralce:

    UPDATE <TABLE_NAME> SET <DATE_FIELD>=TO_DATE('19700101','YYYY-MM-DD') + (<DATE_FIELD> - 719528) +TO_NUMBER(SUBSTR(TZ_OFFSET(SESSIONTIMEZONE),1,3))/24

P.S. The above code will be good enough for one-time use. If you need for production use, you’ll need to optimize the formula. Because this code converts the date to unix_timestamp and then to normal date format. 

Posted 1 year ago
Posted 1 year ago

Ask Tom "to remove duplicate records"

Good explained how to remove duplicate records on Oracle table. Using power of analytics functionality of Oracle makes easy and fast to work with large tables. 

Posted 1 year ago

How to Install Oracle Linux from a USB Stick (OTN Garage)

Posted 1 year ago

What “~” (tilde) operator does in Java

Googling about “~” (tilde) operator in Java didn’t give a clear explanation which beginners can understand without problem. Additionally removing questions about bit-wise operators from Java exam since Java SE6 is a reason that some people don’t learn bit-wise operations. My personal opinion is every programmer must know and understand clearly bit-wise operations and how to use them in software development. 

In simple words the “~” (tilde) operator is just bit-wise NOT. What does it mean? Let’s write a couple of code and try it: 

public class Tilde
{
    public static void main(String args[]) {
        int x=3;
        int y=~x;
        
        System.out.println(x);
        System.out.println(y);    
    }
}

The result will be:

3
-4

How 3 transformed to -4? As I said the tilde is bit-wise NOT operator. So the operations are performed with their binary representation. The binary representation of 3 is 11. We declared the x as int, and theres are 4 bytes (32 bits) allocated for x in memory. The representation in memory of 3 is:

00000000000000000000000000000011

When we perform a tilde operator on 3, all zeros in binary representation of 3 will be 1 and all ones will be 0:

11111111111111111111111111111100

In JVM’s implementation this equals to -4. If you try to perform tilde operation on -4 you’ll get 3.

Source: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html

Posted 1 year ago
A note on email versus e-mail
Newly coined nonce words of English are often spelled with a hyphen, but the hyphen disappears when the words become widely used. For example, people used to write “non-zero” and “soft-ware” instead of “nonzero” and “software”; the same trend has occurred for hundreds of other words. Thus it’s high time for everybody to stop using the archaic spelling “e-mail”. Think of how many keystrokes you will save in your lifetime if you stop now! The form “email” has been well established in England for several years, so I am amazed to see Americans being overly conservative in this regard. (Of course, “email” has been a familiar word in France, Germany, and the Netherlands much longer than in England —- but for an entirely different reason.)
Posted 1 year ago

Current date and time in Java

To get the current date and time in Java is pretty easy:

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String strDate = dateFormat.format(date);
System.out.println(strDate);