My uncle passed away

[This post was originally posted on 01/17/2017, but due to blog migration, it lost its original post date, I’m re-posting it here]

It’s shocking to hear that my uncle (my father’s sister’s husband) passed away today.
I heard the news from my dad. Then I contacted my cousin to condole her. Hours later, she replied:”I have no dad now.”
Reading that single line of message alone broke my heart.

I could hardly image how that hurts.
She’s in tears and cries now.

I just became a father last month, I can hardly imagine how my daughter would feel when I leave her alone.

I regret that I didn’t catch any chances to spread the Good News to my uncle and now I’m praying late that he could still land in Heaven and our godly father will take care of him.
He died at his early 50s, at such a young age, he has a very good wife and a very cute daughter. They’re part of our family.
I didn’t get a chance to see him for the last time.

Death, is so near to us.

This invokes me to reflect a lot. What’s most important to me?
Not work, nor code, nor fixing bugs, not blogging, it’s endless, and in retrospect, it’s meaningless.
I’d like to spend time with my family, just company them. Do whatever with them, time is so precious, I want to be with them.

Advertisements

Java Dependency Management and Programmers’ Learning Stages

Maven is a really cool/powerful dependency management tool.

Prior to doing a side project on your own, you could hardly really understand what dependency management really means. I’ve moved my random/vanilla/plain Java code around several times due to machine change, etc. But each time, when I fire up my IDE (Eclipse or IntelliJ), I’m always faced up with a screen of red lines (cannot resolve symbols, etc.) That’s such a pain!

I have migrated my SpringTutorials project into a Maven managed Java project: My Spring 101

This might seem trivial from all perspectives. But to be frank, I would regard it as a milestone for myself. I’ve gone through several different stages with programming, this is a good example of it:
1. “Hello World” stage: Wow! I could make the code run and print out “Hello World” for me, amazing!
2. “Cannot resolve symbol” stage: After adding one API from a non-JRE jar library, my Java code doesn’t compile in my IDE, I’m blocked here, didn’t know/bother what to do to solve it. Thinking whether programmer is a right career choice for me.
3. “Add that jar” stage: After a long time, maybe 1.5 years, after many times people shouted at me, I kind of tried to download the jar and add them onto my classpath. This is a painful process, wondering whether software engineering is a fit for me every single day, just upon I started my career working at one of the FLAG companies. This is a path full of frustration and worry.
4. “Love it” stage: After ruling out other possible diverges, thinking/acknowledged that programming is the best career choice for me, I started to enjoy myself completely in the world of computer science, soon, everything clicks! Maven naturally comes into my mind when I tried to refactor this SpringTutorials project.

Cheers!

HashSet to filter duplicate char array?

I used this code:


Set<char[]> set = new HashSet<char[]>();
set.add(new char[]{'a', 'b'});
System.out.println(set.contains(new char[]{'a', 'b'}));

However, it prints out `false`.

Then I turned to this code:


Set<String> stringSet = new HashSet<String>();
stringSet.add("" + 'a' + 'b');
System.out.println(stringSet.contains("" + 'a' + 'b'));

This prints out true as I expected.

 

The reason for this is explained here: http://stackoverflow.com/questions/38406520/hashset-is-not-sensitive-to-content-of-array

Kth Smallest Element in a BST

https://leetcode.com/problems/kth-smallest-element-in-a-bst/

A simple in-order traversal could get it AC’ed. Cheers.

[TODO] read others’ more optimal code that didn’t traverse the entire tree, instead, they just return when they found the kth one. Rewrite it myself.


public class Solution {
List<Integer> list;
public int kthSmallest(TreeNode root, int k) {
list = new ArrayList<Integer>();
inorder(root);
return list.get(k-1);
}

void inorder(TreeNode root){
if(root == null) return;
if(root.left != null) inorder(root.left);
list.add(root.val);
if(root.right != null) inorder(root.right);
}
}

Heap Sort

Wikipedia has very good explanation about heap sort and why its time complexity is O(nlogn):

“The heapsort algorithm involves preparing the list by first turning it into a max heap. The algorithm then repeatedly swaps the first value of the list with the last value, decreasing the range of values considered in the heap operation by one, and sifting the new first value into its position in the heap. This repeats until the range of considered values is one value in length.

The steps are:

  • Call the buildMaxHeap() function on the list. Also referred to as heapify(), this builds a heap from a list in O(n) operations.
  • Swap the first element of the list with the final element. Decrease the considered range of the list by one.
  • Call the siftDown() function on the list to sift the new first element to its appropriate index in the heap.
  • Go to step (2) unless the considered range of the list is one element.

The buildMaxHeap() operation is run once, and is O(n) in performance. The siftDown() function is O(log(n)), and is called n times. Therefore, the performance of this algorithm is O(n + n * log(n)) which evaluates to O(n log n).”

 

Some key points to understand this algorithm and its implementation:

  • the heap data structure is actually a virtual thought, it exists only in our imagination, in reality, we’re only re-positioning the elements into different indices, this is also why heap sort space complexity is O(1), since it doesn’t require any extra memory
  • how do we construct this virtual heap data structure? some keys to understand it:
    • regard the array as an level order traversal of a complete binary tree (draw out the picture, and then you’ll have a better understanding)
    • how to construct a max heap? we always want the parent’s val to be greater than its both children’s val, so we swap the two if we find a situation that doesn’t follow this rule and recursively do it.
    • how do we find a node’s left and right children?
      • if you draw out the tree, you’ll figure out that: a node with index i, its left child will be 2*i and its right child will be 2*i+1, if the two children exist.

 

  • Heap sort in NOT stable: the relative order of equal elements might be changed since heapsort peeks the largest element and put it at the last of list.

Used the wikipedia example input: 6, 5, 3, 1, 8, 7, 2, 4 to test my code:heap_sort


public class _20160710_HeapSortAgain {
private static int N;
public static void sort(int[] nums){
heapify(nums);
for(int i = N; i > 0; i--){//i doesn't need to be equal to zero, because we don't need to swap zero-indexed number with itself
swap(nums, i, 0);//we always swap the first element in the array which means it's at the root of the heap with the number at index i which is the largest index in the UN-sorted array
N -= 1;//don't remember to decrement N by 1, because we only need to worry about one number fewer each time
maxheap(nums, 0);//then we always update the heap for the number at index zero
}
}
private static void heapify(int[] nums) {
N = nums.length-1;
for(int i = N/2; i >= 0; i--){//here we need i to be equal to zero because we need to do maxheap() on its first element as well
maxheap(nums, i);
}
}
private static void maxheap(int[] nums, int i) {
int leftChildIndex = 2*i;
int rightChildIndex = leftChildIndex+1;
int max = i;
if(leftChildIndex <= N && nums[leftChildIndex] > nums[i]){
max = leftChildIndex;
}
if(rightChildIndex <= N && nums[rightChildIndex] > nums[max]){
max = rightChildIndex;
}
if(i != max){
swap(nums, i, max);
maxheap(nums, max);
}
}
private static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public static void main(String...strings){
int[] nums = new int[]{6,5,3,1,8,7,2,4};
// int[] nums = new int[]{1,2,3,4,5,6};
// int[] nums = new int[]{6,5,4,3,2,1};
print("BEFORE printing, nums are: ", nums);
sort(nums);
print("AFTER printing, nums are: ", nums);
System.out.println();
}
private static void print(String msg, int[] nums) {
System.out.println(msg);
for(int i : nums){
System.out.print(i + ", ");
}
System.out.println();
}
}